Compare commits

...

44 Commits

Author SHA1 Message Date
lilleman bad76b07c8 Answer overrides round 2: 0 🔴, 0 🟡 (0 misread); both overrides of the rank check are accepted
CI / tests (pull_request) Successful in 1m57s
2026-11-16 01:33:15 +01:00
lilleman 9dd8441f3b Finish item 359
CI / tests (pull_request) Successful in 1m57s
2026-11-16 01:32:41 +01:00
lilleman 1210f8cd68 Answer prose round 1: 0 🔴, 5 🟡 (0 misread); name no cut release in the move line
CI / tests (pull_request) Successful in 1m56s
2026-11-16 01:26:49 +01:00
lilleman 0f0ba7fa43 Answer product-owner round 1: 0 🔴, 2 🟡 (0 misread); say what to do in a Jira plan 2026-11-16 01:26:49 +01:00
lilleman 37078cffa9 Answer stability round 1: 0 🔴, 4 🟡 (0 misread); carry into a release named since the cut 2026-11-16 01:26:49 +01:00
lilleman 30129051ad Answer security round 1: 0 🔴, 0 🟡 (0 misread); no findings 2026-11-16 01:15:54 +01:00
lilleman 58055f0fac Answer overrides round 1: 0 🔴, 0 🟡 (0 misread); the override of the rank check is accepted 2026-11-16 01:15:23 +01:00
lilleman 55ad029df2 Test the singular and plural move lines
CI / tests (pull_request) Successful in 2m2s
2026-11-16 01:14:47 +01:00
lilleman b89ac805d3 Route on a cut release's carried item
CI / tests (pull_request) Successful in 1m58s
2026-11-16 01:08:13 +01:00
lilleman 8b649682dc Count a cut release's open items as the next release's 2026-11-16 01:05:47 +01:00
lilleman 4447e89e48 Reword item 359: releases stay semver, and the loop keeps working when someone else cuts one 2026-11-16 00:59:20 +01:00
lilleman 3c522160c9 Re-score item 359 at L 4, S 7 2026-11-15 23:44:52 +01:00
lilleman 39bf6e6d94 Answer overrides round 1: 0 🔴, 0 🟡 (0 misread); the override of the rank check is accepted
CI / tests (pull_request) Successful in 2m22s
2026-11-15 23:38:03 +01:00
lilleman 0339a515fc Finish item 386 2026-11-15 23:37:09 +01:00
lilleman 75c3c581ef Answer stability round 2: 0 🔴, 0 🟡 (0 misread); approved
CI / tests (pull_request) Successful in 2m8s
2026-11-15 23:36:33 +01:00
lilleman cca16e702a Make the open test tell the injected git from the real one 2026-11-15 23:26:27 +01:00
lilleman 36d9ddb6f5 Test the pruning on open and kill its surviving mutants 2026-11-15 23:17:22 +01:00
lilleman dbc8cfe854 Answer prose round 1: 0 🔴, 2 🟡 (0 misread); the help, the docstrings and the test name reworded in the previous commit 2026-11-15 23:06:50 +01:00
lilleman fffba3d454 Answer stability round 1: 0 🔴, 1 🟡 (0 misread); prune the copies of removed worktrees 2026-11-15 23:06:50 +01:00
lilleman 2695e9b530 Pin the worktree folder's name in a test 2026-11-15 22:54:09 +01:00
lilleman 4873ee9e74 Key project-record's copies per worktree
CI / tests (pull_request) Successful in 2m8s
2026-11-15 22:45:04 +01:00
lilleman 70e3c0b9de Answer overrides round 1: 0 🔴, 0 🟡 (0 misread); the override of the rank check is accepted
CI / tests (pull_request) Successful in 2m24s
2026-11-15 22:28:08 +01:00
lilleman 93a4da0728 Record the comprehension check: a scoring run at bcb04e3, overall 6.00; refresh floor item 300
CI / tests (pull_request) Successful in 2m23s
2026-11-15 22:27:10 +01:00
lilleman bcb04e32d4 Finish item 374 in the plan, and record lilleman's answer on the paired ruling's base
CI / tests (pull_request) Successful in 2m35s
2026-11-15 22:19:02 +01:00
lilleman 37fcedc5bf Merge remote-tracking branch 'origin/main' into item-374
CI / tests (pull_request) Successful in 2m44s
2026-11-15 22:11:23 +01:00
lilleman e18555be3e Answer product-owner round 2: 0 🔴, 1 🟡 (0 misread); the base of a rerun paired ruling is asked of lilleman
CI / tests (pull_request) Successful in 2m25s
2026-11-15 22:11:22 +01:00
lilleman 2136413dd6 Answer stability round 2: 0 🔴, 4 🟡 (0 misread); each survivor it named has a test that kills it 2026-11-15 22:11:22 +01:00
lilleman e37518db29 Answer prose round 1: 0 🔴, 11 🟡 (0 misread); the help lists merge's steps and stops, and the decision says where it differs from the call
CI / tests (pull_request) Successful in 2m45s
2026-11-15 21:56:11 +01:00
lilleman 9e0a6d4d7b Answer product-owner round 1: 1 🔴, 5 🟡 (1 misread); an absent item is named, an approved pull request answers its comments first, and todo-item keeps its own checks 2026-11-15 21:56:11 +01:00
lilleman aff46cd64e Answer stability round 1: 2 🔴, 8 🟡 (1 misread); the scoring-run gate follows the finish, a rerun commits what a finish left, and the queue wait ends after 30 minutes 2026-11-15 21:56:11 +01:00
lilleman 0109f97cd7 Answer security round 1: 0 🔴, 0 🟡 (0 misread); nothing reported
CI / tests (pull_request) Successful in 2m8s
2026-11-15 21:34:51 +01:00
lilleman 85f3b74d4f Merge a project's chunks one at a time, finishing each one's plan items in its turn
CI / tests (pull_request) Successful in 2m9s
2026-11-15 21:33:36 +01:00
lilleman bf1897b1a0 Answer overrides round 1: 0 🔴, 0 🟡 (0 misread); both overrides of the rank check are accepted
CI / tests (pull_request) Successful in 2m27s
2026-11-15 19:57:21 +01:00
lilleman 34468c20d7 File items 387 and 388: bind a project's rung to its ladder, and refuse an agent's write to a ladder file
CI / tests (pull_request) Successful in 2m26s
2026-11-15 19:55:34 +01:00
lilleman bedd304479 Merge remote-tracking branch 'origin/main' into patch-0.10.1
# Conflicts:
#	CHANGELOG.md
#	README.md
#	bin/loop_claude/loop/chunk_start.py
#	bin/loop_claude/loop/close.py
#	bin/loop_claude/loop/main.py
#	bin/loop_claude/routing.py
#	bin/loop_claude/test_loop_claude.py
#	bin/project_config/main.py
#	bin/project_config/test_project_config.py
#	docs/decisions.md
2026-11-15 19:54:42 +01:00
lilleman daaa61b607 Cut release 0.10.1
CI / tests (pull_request) Successful in 2m38s
2026-11-15 19:48:17 +01:00
lilleman 3422a39b6f Answer product-owner round 2: 0 🔴, 0 🟡 (0 misread); the answers stand, and a project's own ladder keeps goal 1.3's workflow 2026-11-15 19:45:31 +01:00
lilleman d2133c410f Answer prose round 1: 0 🔴, 9 🟡 (0 misread); say what each docstring's code does, give the outage step in plain words and keep each choice in one place
CI / tests (pull_request) Successful in 2m31s
2026-11-15 19:42:51 +01:00
lilleman a62992d877 Answer product-owner round 1: 0 🔴, 2 🟡 (0 misread); each cycle on a project's own ladder says so and says where the worker's model is off it, and the errors name a model's full name and the ladder's file 2026-11-15 19:42:49 +01:00
lilleman 2ecec90ec5 Answer stability round 1: 0 🔴, 4 🟡 (0 misread); refuse a ladder that names two models of one family, test the one finding a rung needs, and settle the two places in the PR summary 2026-11-15 19:42:47 +01:00
lilleman 46135acab6 Test the rungs rule-hook leaves unchecked, the home it reads the ladder under and the prompts' rungs at the ladder's ends
CI / tests (pull_request) Successful in 2m59s
2026-11-15 19:07:22 +01:00
lilleman 8d58dec886 Answer security round 1: 0 🔴, 0 🟡 (0 misread); no finding reached the bar 2026-11-15 18:59:31 +01:00
lilleman c5acadf8d3 Keep the shipped routing ladder beside the module that reads it, so a copy of bin/ carries it 2026-11-15 18:59:23 +01:00
lilleman 0a20b6d4f6 Read the routing ladder from routing-ladder.json, which a project replaces with a file of its own in its config's folder
CI / tests (pull_request) Successful in 2m37s
2026-11-15 18:51:59 +01:00
61 changed files with 1944 additions and 633 deletions
+1
View File
@@ -74,6 +74,7 @@
!bin/metric_bench/*.py
!bin/model_routing/
!bin/model_routing/*.py
!bin/model_routing/routing-ladder.json
!bin/mutate-changes
!bin/mutate_changes/
!bin/mutate_changes/*.py
+7
View File
@@ -2,6 +2,9 @@
## Unreleased
- 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.
- Two loop-claude runs in one project now work side by side, each on its own chunk. Each loop holds a slot of the project, a locked file under `~/.local/state/loop-claude/<key>/`, and names its session after it: the first loop's session keeps its name, `A <key> loop-claude`, and the second's is `A <key> loop-claude 2`. A rerun resumes a chunk left open first. A commit in the config's folder now takes only the file it changed, as `git commit -m <title> -- <file>`.
- `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.
@@ -28,6 +31,10 @@
- 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.
+3 -2
View File
@@ -9,6 +9,7 @@ How work proceeds in any repo, unless the repo's `AGENTS.md` says otherwise. The
- **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, and there it files and finishes an item but doesn't edit or move one yet. 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 this plan's items, as in a Jira plan, ask the human in the chunk's summary to move them. 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.
@@ -17,7 +18,7 @@ How work proceeds in any repo, unless the repo's `AGENTS.md` says otherwise. The
- **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.
- **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.
- **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 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.
@@ -138,7 +139,7 @@ Claude Code reads this section by its heading when it compacts a conversation. K
- **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.
- **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".
+7 -5
View File
@@ -1,6 +1,6 @@
# Claude Code configuration
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/`; `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.
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
@@ -107,7 +107,7 @@ A project's config may set four more things, each optional, as `project-config -
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.
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. 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 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.
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.
@@ -136,6 +136,8 @@ cd ~/code/acme-billing && ~/.claude/bin/project-config
The last line prints each setting's path once the config is complete.
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:
@@ -162,7 +164,7 @@ It renames `## Unreleased` in `CHANGELOG.md` to the version and merges that thro
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`.
- `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; once it is merged, `clean` removes the chunk's worktree and branch and fast-forwards the main checkout. `chunk-pr --help` states the steps.
- `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; 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.
- `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.
@@ -183,7 +185,7 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a
- `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, and with `--plan` never below the project's rung; `subagent-rung --help` states the rule.
- `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`. 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.
@@ -201,7 +203,7 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a
- `loop_effects/` holds `Effects`: the processes, terminal, clock and git a tool reaches, injected so its tests can script them. loop-claude, both replay tools and `reviewer-merge-trials`' driver use it.
- `loop_state/` holds where loop-claude keeps its 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 routing ladder, which loop-claude, `rule_hook`, both replay tools and `subagent-rung` read, and the list prices, which `routing_figures` and `transcript_archive` read.
- `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`, 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`; `mattermost_dm/` and `slack_dm/` are its two backends.
- `plan_store/` reads and writes a project's plan through the store the project's config names (`stores.py`), with the markdown file's edits in `markdown_edits.py`. `contract.py` holds the tests every backend that writes must pass, which `jira_epic.py` doesn't yet, and `fakes.py` a plan in memory.
- `rank_todo.py`, `settings_filter.py` and `statusline.py` are tools of one file each, tested beside them.
+49 -17
View File
@@ -9,7 +9,7 @@ from chunk_preflight.gathered import Forge
from deploy_release.forge import Run
BIN = pathlib.Path(__file__).resolve().parents[1]
# A human answers in hours, so merge polls once a minute and gives up after 90 minutes, which leaves room for the checks wait inside the 2 hours a background command may run, so that the give-up message prints.
# 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
@@ -26,24 +26,56 @@ def awaited(forge: Forge, run: Run) -> bool | Failure:
return answer.strip() == "true"
# Each review thread, with whether it is resolved and who wrote its last comment, beside who opened the pull request. gh fills {owner} and {repo} from the checkout.
THREADS = """query($owner: String!, $repo: String!, $number: Int!) { repository(owner: $owner, name: $repo) { pullRequest(number: $number) {
author { login }
reviewThreads(first: 100) { nodes { isResolved path comments(last: 1) { nodes { author { login } } } } }
} } }"""
def approval(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."""
viewed = run(["gh", "pr", "view", number, "--json", "reviewDecision"])
try:
decision = viewed if isinstance(viewed, Failure) else json.loads(viewed)["reviewDecision"]
except (ValueError, KeyError, TypeError):
return Failure(f"gh pr view printed no review decision: {str(viewed).strip()[:200]}")
if isinstance(decision, Failure):
return decision
if decision == "CHANGES_REQUESTED":
return Failure(f"a reviewer requested changes on pull request {number}")
if not decision:
return Failure("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")
if decision not in ("APPROVED", "REVIEW_REQUIRED"):
return Failure(f"GitHub reports the review decision {decision!r} on pull request {number}, and chunk-pr doesn't know that decision")
return decision == "APPROVED"
def approved(number: str, run: Run, sleep: typing.Callable[[float], None] = time.sleep) -> Failure | None:
"""None once GitHub reports pull request number approved, as its branch protection asks; a Failure where a reviewer requested changes, where the protection asks for no review, or where no approval came within WAIT_SECONDS."""
"""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."""
for waited in range(0, WAIT_SECONDS + 1, POLL_SECONDS):
viewed = run(["gh", "pr", "view", number, "--json", "reviewDecision"])
try:
decision = viewed if isinstance(viewed, Failure) else json.loads(viewed)["reviewDecision"]
except (ValueError, KeyError, TypeError):
return Failure(f"gh pr view printed no review decision: {str(viewed).strip()[:200]}")
if isinstance(decision, Failure):
return decision
if decision == "APPROVED":
return None
if decision == "CHANGES_REQUESTED":
return Failure(f"a reviewer requested changes on pull request {number}")
if not decision:
return Failure("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")
if decision != "REVIEW_REQUIRED":
return Failure(f"GitHub reports the review decision {decision!r} on pull request {number}, and chunk-pr doesn't know that decision")
read = approval(number, run)
if read is True or isinstance(read, Failure):
return None if read is True else read
asked = unanswered(number, run)
if asked is not None:
return asked
if waited < WAIT_SECONDS:
sleep(POLL_SECONDS)
return Failure(f"pull request {number} wasn't approved within {WAIT_SECONDS // 60} minutes; run chunk-pr merge again once it is")
def unanswered(number: str, run: Run) -> Failure | None:
"""A Failure naming the files where a reviewer's comment waits for an answer on pull request number: a review thread nobody resolved, whose last comment someone other than the pull request's author wrote. So a thread the worker answered, as that author, waits for the reviewer again. None where no thread waits."""
read = run(["gh", "api", "graphql", "-f", f"query={THREADS}", "-F", "owner={owner}", "-F", "repo={repo}", "-F", f"number={number}"])
try:
pull = read if isinstance(read, Failure) else json.loads(read)["data"]["repository"]["pullRequest"]
if isinstance(pull, Failure):
return pull
author = pull["author"]["login"]
waiting = sorted({thread["path"] for thread in pull["reviewThreads"]["nodes"] if not thread["isResolved"] and any(comment["author"]["login"] != author for comment in thread["comments"]["nodes"])})
except (ValueError, KeyError, TypeError):
return Failure(f"gh api graphql printed no review threads: {str(read).strip()[:200]}")
if not waiting:
return None
return Failure(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")
+235 -53
View File
@@ -3,7 +3,7 @@
usage: chunk-pr open <title> [<body>]
chunk-pr sync
chunk-pr ready [<title>]
chunk-pr merge
chunk-pr merge [--finish <ID> [--changelog <bullet> | --no-changelog]]...
chunk-pr clean
Run it in the chunk's worktree, on the chunk's branch. ready and merge act on the branch's open
@@ -25,22 +25,44 @@ ready marks the pull request ready for review. On Gitea a draft is a pull req
starts with `WIP: `, so there it drops that prefix. Given <title>, one line, which it holds
to the template as open does, it sets that
as the pull request's title first; where that fails, the pull request stays a draft.
merge waits for the pull request's checks, and those origin's default branch requires, to pass
on the head, then merges the pull request, and only while its head is still the commit
checked out, so a push after the gate is never merged. Where no check reports within a
minute, it takes the pull request as having none. It refuses where a check fails, or, on
Gitea, where the checks have not all passed within 30 minutes; on GitHub, gh watches them
until they end. Run it in the background.
It takes the first merge method the repository allows of: a merge commit, fast-forward
only, a rebase followed by a merge commit, a rebase, a squash. GitHub offers only the
merge commit, the rebase and the squash. It also refuses where `larv-review
scoring-run-owed` exits 1, because the chunk owes a scoring run it has not recorded.
merge merges the pull request in its turn: the chunks of one project on this machine take
turns, one at a time. Run it in the background. In its turn it:
1. fetches origin and merges its default branch into the branch, as sync does;
2. finishes each plan item a --finish names with `todo-item finish`, passing on
--changelog or --no-changelog, and commits what that changed in the plan and the
changelog, so both change only at merge time, on top of every chunk merged before;
3. pushes, also where step 2 failed after step 1 brought changes in;
4. waits for the pull request's checks, and those origin's default branch requires, to
pass on the head; where no check reports within a minute, it takes the pull request
as having none;
5. merges the pull request, only while its head is still the commit checked out, so a
push after the gate is never merged. It takes the first merge method the repository
allows of: a merge commit, fast-forward only, a rebase followed by a merge commit, a
rebase, a squash. GitHub offers only the merge commit, the rebase and the squash.
Its last line names each --finish item the plan did not hold when it began: an earlier
run finished that item, or its ID is mistyped.
Where the project's config sets `wait-for-approval = true` (`project-config --help`), it
also waits, once the checks have passed, until GitHub reports the pull request approved
as its branch protection requires. It refuses at once where a reviewer requested changes,
where the protection requires no review, on Gitea, and where it cannot read the config.
After 90 minutes without an approval it refuses too; run it again once the pull request
is approved.
merges only once GitHub reports the pull request approved as its branch protection
requires. It waits for that outside its turn, so other chunks merge meanwhile, and takes
a new turn once approved.
It stops, without merging, and says what to do before running it again:
- on a merge conflict in step 1, naming the conflicted files, with the merge in progress;
- where `larv-review scoring-run-owed` exits 1 after step 3, because the chunk owes a
scoring run it has not recorded;
- where origin's default branch has moved since the branch last recorded a paired
ruling, since that ruling read a head that no longer merges;
- where a check fails, or, on Gitea, where the checks have not all passed within 30
minutes; on GitHub, gh watches them until they end;
- where other pull requests still hold the turn after 30 minutes, naming the last;
- with `wait-for-approval`: where a reviewer requested changes, where the protection
requires no review, on Gitea, where it cannot read the config, and after 90 minutes
without an approval;
- with `wait-for-approval`, approved or not: where a reviewer's comment waits for an
answer, which is a review thread nobody resolved whose last comment is not the pull
request author's. Answer it in its thread and push any fix.
A run that waits for an approval takes two turns, so it can last the 90 minutes and,
twice, the 30 minutes in the queue and the checks. One killed before that left the
branch pushed, so run it again.
clean acts once the forge reports the branch's pull request merged at the commit checked out,
by any merge method. It fetches origin, fast-forwards the main checkout to origin's
default branch, removes the chunk's worktree, then deletes the local branch; origin's
@@ -51,7 +73,9 @@ clean acts once the forge reports the branch's pull request merged at the com
It prints what it did, exit 0, or why it failed, exit 1.
"""
import contextlib
import dataclasses
import fcntl
import json
import os
import pathlib
@@ -59,7 +83,7 @@ import sys
import time
import typing
from chunk_pr.approval import approved, awaited
from chunk_pr.approval import approval, approved, awaited, unanswered
from deploy_release.forge import checks_passed, gitea, merged_pull, open_pull, required_checks, Run, runner
from failure import Failure
from chunk_preflight.gathered import Forge
@@ -69,7 +93,14 @@ from project_config import templates
BIN = pathlib.Path(__file__).resolve().parents[1]
# 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
USAGE = "usage: chunk-pr open <title> [<body>] | chunk-pr sync | chunk-pr ready [<title>] | chunk-pr merge | chunk-pr clean"
# 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: "
USAGE = "usage: chunk-pr open <title> [<body>] | chunk-pr sync | chunk-pr ready [<title>] | chunk-pr merge [--finish <ID> [--changelog <bullet> | --no-changelog]]... | chunk-pr clean"
# 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.
METHODS: dict[Forge, tuple[tuple[str, str], ...]] = {
@@ -99,8 +130,9 @@ def step(argv: list[str], run: Run) -> str | Failure:
return synced(run)
case ["ready", *title] if len(title) <= 1 and not any(given.startswith("-") for given in title):
return Failure("give a title of one line") if title and not one_line(title[0]) else (misfit(title[0], run) if title else None) or marked_ready(run, title[0] if title else None)
case ["merge"]:
return merged(run)
case ["merge", *given]:
finishes = finishes_of(given)
return Failure(USAGE) if finishes is None else merged(run, finishes=finishes)
case ["clean"]:
return cleaned(run)
return Failure(USAGE)
@@ -195,23 +227,10 @@ def synced(run: Run) -> str | Failure:
return base
if branch == base:
return Failure(f"{branch} is origin's default branch; sync the chunk's branch")
fetched = run(["git", "fetch", "--quiet", "origin"])
if isinstance(fetched, Failure):
return fetched
behind = answers(run, ["rev-list", "--count", f"HEAD..origin/{base}"], ["rev-parse", "--show-toplevel"])
if isinstance(behind, Failure):
return behind
count, root = behind
if count == "0":
done = f"{branch} already holds origin/{base}."
else:
merged = run(["git", "merge", "--quiet", "--no-edit", f"origin/{base}"])
if isinstance(merged, Failure):
conflicted = answers(run, ["diff", "--name-only", "--diff-filter=U"])
if isinstance(conflicted, Failure) or not conflicted[0]:
return merged
return Failure(f"merging origin/{base} into {branch} conflicts in {', '.join(conflicted[0].splitlines())}; the merge stays in progress: resolve them and commit")
done = f"Merged origin/{base} into {branch}."
level = levelled(run, branch, base)
if isinstance(level, Failure):
return level
done = f"Merged origin/{base} into {branch}." if level else f"{branch} already holds origin/{base}."
plan = run([str(BIN / "project-config"), "plan"])
if isinstance(plan, Failure):
return Failure(f"{done.removesuffix('.')}, but the plan to check cannot be found: {plan.reason}")
@@ -224,6 +243,25 @@ def synced(run: Run) -> str | Failure:
return f"{done}\nrank_todo.py --check todo.md passed."
def levelled(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."""
fetched = run(["git", "fetch", "--quiet", "origin"])
if isinstance(fetched, Failure):
return fetched
behind = answers(run, ["rev-list", "--count", f"HEAD..origin/{base}"])
if isinstance(behind, Failure):
return behind
if behind[0] == "0":
return False
merged = run(["git", "merge", "--quiet", "--no-edit", f"origin/{base}"])
if isinstance(merged, Failure):
conflicted = answers(run, ["diff", "--name-only", "--diff-filter=U"])
if isinstance(conflicted, Failure) or not conflicted[0]:
return merged
return Failure(f"merging origin/{base} into {branch} conflicts in {', '.join(conflicted[0].splitlines())}; the merge stays in progress: {resolve}")
return True
def marked_ready(run: Run, title: str | None) -> str | Failure:
found = pull(run)
if isinstance(found, Failure):
@@ -241,33 +279,177 @@ def marked_ready(run: Run, title: str | None) -> str | Failure:
return f"Marked pull request #{number} ready, titled “{title}”." if title is not None else f"Marked pull request #{number} ready."
def merged(run: Run, sleep: typing.Callable[[float], None] = time.sleep) -> str | Failure:
def finishes_of(given: list[str]) -> list[list[str]] | None:
"""`todo-item finish`'s arguments for each item that merge's flags name, in their order; None where the flags are malformed."""
finishes, rest = [], given
while rest:
match rest:
case ["--finish", item, "--changelog", bullet, *rest] if item.isdigit():
finishes.append([item, "--changelog", bullet])
case ["--finish", item, "--no-changelog", *rest] if item.isdigit():
finishes.append([item, "--no-changelog"])
case ["--finish", item, *rest] if item.isdigit():
finishes.append([item])
case _:
return None
return finishes
def merged(run: Run, sleep: typing.Callable[[float], None] = time.sleep, finishes: typing.Sequence[list[str]] = ()) -> str | Failure:
"""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."""
found = pull(run)
if isinstance(found, Failure):
return found
forge, number, head = found
forge, number, _ = found
waits = awaited(forge, run)
if isinstance(waits, Failure):
return waits
owed = run([str(BIN / "larv-review"), "scoring-run-owed"])
if isinstance(owed, Failure):
return owed
method = merge_method(forge, run)
if isinstance(method, Failure):
return method
base = default_branch(run)
required = base if isinstance(base, Failure) else required_checks(forge, base, run)
checked = required if isinstance(required, Failure) else checks_passed(forge, number, head, required, run, sleep, NO_CHECKS_SECONDS)
if isinstance(checked, Failure):
return checked
approval = approved(number, run, sleep) if waits else None
if isinstance(approval, Failure):
return approval
if forge == "gh":
done = run(["gh", "pr", "merge", number, method, "--match-head-commit", head])
else:
done = gitea(run, f"repos/{{owner}}/{{repo}}/pulls/{number}/merge", f"Do={method}", f"head_commit_id={head}")
return done if isinstance(done, Failure) else f"Merged pull request #{number} ({method.removeprefix('--')})."
if isinstance(required, Failure):
return required
queue = answers(run, ["rev-parse", "--path-format=absolute", "--git-common-dir"])
if isinstance(queue, Failure):
return queue
absent = unplanned(run, finishes)
if isinstance(absent, Failure):
return absent
file = pathlib.Path(queue[0]) / QUEUE
while True:
try:
with turn(file, number, sleep):
head = levelled_and_finished(run, str(base), finishes)
checked = head if isinstance(head, Failure) else checks_passed(forge, number, head, required, run, sleep, NO_CHECKS_SECONDS)
if isinstance(checked, Failure):
return checked
ready = approval(number, run) if waits else True
asked = unanswered(number, run) if waits and ready is True else None
if isinstance(ready, Failure):
return ready
if asked is not None:
return asked
if ready and forge == "gh":
done = run(["gh", "pr", "merge", number, method, "--match-head-commit", str(head)])
elif ready:
done = gitea(run, f"repos/{{owner}}/{{repo}}/pulls/{number}/merge", f"Do={method}", f"head_commit_id={head}")
if ready:
return done if isinstance(done, Failure) else f"Merged pull request #{number} ({method.removeprefix('--')}).{absent}"
except Held as held:
return Failure(f"the merge queue stayed held for {QUEUE_SECONDS // 60} minutes, last by pull request #{held.args[0] or '?'}, so this one took no turn; run chunk-pr merge again")
except OSError as failure:
return Failure(f"cannot take a turn in the merge queue, {file}: {failure.strerror}")
waited = approved(number, run, sleep)
if isinstance(waited, Failure):
return waited
def unplanned(run: Run, finishes: typing.Sequence[list[str]]) -> str | Failure:
"""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."""
absent = []
for finish in finishes:
shown = run([str(BIN / "todo-item"), "show", finish[0]])
if isinstance(shown, Failure) and f"holds no item {finish[0]}" not in shown.reason:
return shown
absent += [finish[0]] if isinstance(shown, Failure) else []
return f" The plan held no item {', '.join(absent)} when merge began, so merge left the plan as it was there." if absent else ""
class Held(Exception):
"""Other merges kept the queue for QUEUE_SECONDS; the argument is the number of the pull request that held it last."""
@contextlib.contextmanager
def turn(queue: pathlib.Path, number: str, sleep: typing.Callable[[float], None]) -> typing.Iterator[None]:
"""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. Raises Held where another one still holds it after QUEUE_SECONDS, and OSError where the file cannot be opened or locked."""
fd = os.open(queue, os.O_RDWR | os.O_CREAT, 0o644)
try:
for waited in range(0, QUEUE_SECONDS + 1, QUEUE_POLL_SECONDS):
try:
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
break
except BlockingIOError:
if waited == QUEUE_SECONDS:
raise Held(os.pread(fd, 20, 0).decode(errors="replace").strip()) from None
sleep(QUEUE_POLL_SECONDS)
os.ftruncate(fd, 0)
os.pwrite(fd, number.encode(), 0)
yield
finally:
os.close(fd)
def levelled_and_finished(run: Run, base: str, finishes: typing.Sequence[list[str]]) -> str | Failure:
"""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)
if isinstance(found, Failure):
return found
_, branch, before = found
moved = levelled(run, branch, base, "resolve them, commit, push, and run chunk-pr merge again")
if isinstance(moved, Failure):
return moved
failed = next((failure for finish in finishes if (failure := finished(run, branch, finish))), None)
head = answers(run, ["rev-parse", "HEAD"])
if isinstance(head, Failure):
return head
pushed = run(["git", "push", "--quiet", "origin", branch]) if head[0] != before else ""
if isinstance(pushed, Failure):
return pushed
# The scoring run is asked for only now: scoring-run-owed counts as shipped the items the committed plan no longer holds.
owed = failed or run([str(BIN / "larv-review"), "scoring-run-owed"])
if isinstance(owed, Failure):
return owed
return remeasure(run, base) or head[0]
def finished(run: Run, branch: str, finish: list[str]) -> Failure | None:
"""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."""
shown = run([str(BIN / "todo-item"), "show", finish[0]])
if isinstance(shown, Failure) and f"holds no item {finish[0]}" not in shown.reason:
return shown
read = ["" if isinstance(shown, Failure) else run([str(BIN / "todo-item"), "finish", *finish]), run([str(BIN / "project-config"), "commit-title"]), run([str(BIN / "project-config"), "branch"]), run([str(BIN / "project-config"), "plan"]), run([str(BIN / "project-config"), "changelog"])]
if failed := next((answer for answer in read if isinstance(answer, Failure)), None):
return failed
_, template, branch_template, *records = (str(answer).strip() for answer in read)
summary = f"Finish item {finish[0]} in the plan"
# A branch that doesn't fit the config's `branch` template has no ID for {id}, so its titles are the summary alone, as CLAUDE.md → "Git, commits, and PRs" says.
title = template.replace(templates.ID, finish[0]).replace(templates.SUMMARY, summary) if templates.branch_fits(branch_template, branch) else summary
return committed(run, title, [pathlib.Path(record) for record in records if pathlib.Path(record).is_file()])
def committed(run: Run, title: str, files: list[pathlib.Path]) -> Failure | None:
"""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."""
held: dict[str, list[str]] = {}
for file in files:
top = run(["git", "-C", str(file.parent), "rev-parse", "--show-toplevel"])
if isinstance(top, Failure):
return top
held.setdefault(top.strip(), []).append(str(file))
for top, paths in held.items():
changed = run(["git", "-C", top, "status", "--porcelain", "--", *paths])
steps = [changed] if isinstance(changed, Failure) or not changed.strip() else [run(["git", "-C", top, "add", "--", *paths]), run(["git", "-C", top, "commit", "--quiet", "-m", title, "--", *paths])]
if failed := next((step for step in steps if isinstance(step, Failure)), None):
return failed
return None
def remeasure(run: Run, base: str) -> Failure | None:
"""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 = run([str(BIN / "project-config"), "comprehension-history"])
if isinstance(history, Failure):
return history
top = answers(run, ["rev-parse", "--show-toplevel"])
if isinstance(top, Failure) or not pathlib.Path(history.strip()).resolve().is_relative_to(top[0]):
return top if isinstance(top, Failure) else None
ruled = answers(run, ["log", "-1", "--format=%H", "-G", RULING, f"origin/{base}..HEAD", "--", history.strip()])
if isinstance(ruled, Failure) or not ruled[0].strip():
return ruled if isinstance(ruled, Failure) else None
since = answers(run, ["rev-list", "--count", f"{ruled[0].strip()}..origin/{base}"])
if isinstance(since, Failure) or since[0].strip() == "0":
return since if isinstance(since, Failure) else None
return Failure(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")
def merge_method(forge: Forge, run: Run) -> str | Failure:
+319 -22
View File
@@ -1,5 +1,9 @@
import contextlib
import fcntl
import json
import os
import pathlib
import shutil
import subprocess
import sys
import tempfile
@@ -7,10 +11,11 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from chunk_pr.main import cleaned, merged, step, USAGE
from chunk_pr.main import cleaned, merged, QUEUE, step, turn, USAGE
from failure import Failure
from test_env import isolated_env
from deploy_release.forge import Run
from chunk_pr.approval import THREADS
TOOL = pathlib.Path(__file__).resolve().parents[1] / "chunk-pr"
GITHUB = "git@github.com:me/project.git"
@@ -29,6 +34,11 @@ TITLE = [str(pathlib.Path(__file__).resolve().parents[1] / "project-config"), "p
BRANCH = [str(pathlib.Path(__file__).resolve().parents[1] / "project-config"), "branch"]
WAITS = [str(pathlib.Path(__file__).resolve().parents[1] / "project-config"), "wait-for-approval"]
GH_DECISION = ["gh", "pr", "view", "12", "--json", "reviewDecision"]
GH_THREADS = ["gh", "api", "graphql", "-f", f"query={THREADS}", "-F", "owner={owner}", "-F", "repo={repo}", "-F", "number=12"]
BEHIND = ["git", "rev-list", "--count", "HEAD..origin/main"]
COMMON = ["git", "rev-parse", "--path-format=absolute", "--git-common-dir"]
# The folder the fake checkouts name as their shared git folder, where merge keeps its queue's file.
GIT_FOLDER = tempfile.TemporaryDirectory()
class Checkout:
@@ -45,6 +55,8 @@ class Checkout:
self.decisions = ["APPROVED"]
# Set, what GitHub prints instead of a decision's JSON.
self.unreadable: str | Failure | None = None
# The pull request's review threads, as GitHub's GraphQL API prints them; its author is `worker`.
self.threads: list[dict[str, object]] = []
self.ran: list[list[str]] = []
self.answers: dict[tuple[str, ...], str | Failure] = {
("git", "remote", "get-url", "origin"): f"{origin}\n",
@@ -54,6 +66,9 @@ class Checkout:
tuple(WAITS): "false\n",
tuple(TITLE): "{summary}\n",
tuple(BRANCH): "item-{id}\n",
tuple(BEHIND): "0\n",
tuple(COMMON): f"{GIT_FOLDER.name}\n",
("git", "rev-parse", "--show-toplevel"): "/checkout\n",
}
def __call__(self, command: list[str]) -> str | Failure:
@@ -74,6 +89,8 @@ class Checkout:
return self.unreadable
if command == GH_DECISION:
return json.dumps({"reviewDecision": self.decisions.pop(0) if len(self.decisions) > 1 else self.decisions[0]})
if command == GH_THREADS:
return json.dumps({"data": {"repository": {"pullRequest": {"author": {"login": "worker"}, "reviewThreads": {"nodes": self.threads}}}}})
if command == TEA_BRANCH:
return json.dumps({"enable_status_check": False})
if command in (GH_SETTINGS, TEA_SETTINGS):
@@ -82,7 +99,7 @@ class Checkout:
def acted(self) -> list[list[str]]:
"""What it ran beyond reading the checkout, the pull requests and the repository's settings."""
reads = [GH_LIST, GH_DECISION, TEA_LIST, GH_SETTINGS, TEA_SETTINGS, OWED, GH_CHECKS, TEA_BRANCH, TEA_STATUS]
reads = [GH_LIST, GH_DECISION, TEA_LIST, GH_SETTINGS, TEA_SETTINGS, OWED, GH_CHECKS, TEA_BRANCH, TEA_STATUS, GH_THREADS]
return [command for command in self.ran if tuple(command) not in self.answers and command not in reads]
@@ -281,6 +298,11 @@ class Sync(unittest.TestCase):
self.assertEqual(step(["sync"], checkout), Failure("git fetch --quiet: could not read from remote"))
def changes(checkout: Checkout) -> list[list[str]]:
"""What a merge ran, leaving out what it read, the project's config included, and the fetch each turn opens with."""
return [command for command in checkout.acted() if command != FETCH and not command[0].endswith("/project-config")]
class Merge(unittest.TestCase):
def test_the_gate_passed_flag_it_no_longer_takes_is_refused_before_anything_runs(self):
checkout = Checkout(GITHUB, open=True)
@@ -302,7 +324,7 @@ class Merge(unittest.TestCase):
checkout = Checkout(GITHUB, open=True)
checkout.answers[tuple(GH_CHECKS)] = Failure("gh pr checks 12: CI / tests\tfail")
self.assertEqual(step(["merge"], checkout), Failure("gh pr checks 12: CI / tests\tfail"))
self.assertEqual(checkout.acted(), [])
self.assertEqual(changes(checkout), [])
def test_github_waits_a_minute_for_checks_to_report_before_taking_none_as_passed(self):
checkout = Checkout(GITHUB, open=True)
@@ -335,13 +357,13 @@ class Merge(unittest.TestCase):
def test_an_approved_pull_request_merges_after_the_checks_and_the_approval(self):
checkout = self.requiring_approval()
self.assertEqual(step(["merge"], checkout), "Merged pull request #12 (merge).")
self.assertEqual(checkout.ran[-3:], [GH_CHECKS, GH_DECISION, ["gh", "pr", "merge", "12", "--merge", "--match-head-commit", HEAD]])
self.assertEqual(checkout.ran[-4:], [GH_CHECKS, GH_DECISION, GH_THREADS, ["gh", "pr", "merge", "12", "--merge", "--match-head-commit", HEAD]])
def test_it_waits_a_minute_at_a_time_while_the_branch_protection_still_wants_a_review(self):
checkout = self.requiring_approval(GITHUB, "REVIEW_REQUIRED", "REVIEW_REQUIRED", "APPROVED")
slept: list[float] = []
self.assertEqual(merged(checkout, slept.append), "Merged pull request #12 (merge).")
self.assertEqual(slept, [60, 60])
self.assertEqual(slept, [60])
def test_an_approval_that_never_comes_leaves_it_unmerged_after_90_minutes(self):
checkout = self.requiring_approval(GITHUB, "REVIEW_REQUIRED")
@@ -350,10 +372,10 @@ class Merge(unittest.TestCase):
self.assertIsInstance(failed, Failure)
self.assertIn("90 minutes", failed.reason)
self.assertEqual(sum(slept), 90 * 60)
self.assertEqual(checkout.acted(), [])
self.assertEqual(changes(checkout), [])
def test_an_approval_that_comes_in_the_last_minute_still_merges(self):
checkout = self.requiring_approval(GITHUB, *["REVIEW_REQUIRED"] * 90, "APPROVED")
checkout = self.requiring_approval(GITHUB, *["REVIEW_REQUIRED"] * 91, "APPROVED")
slept: list[float] = []
self.assertEqual(merged(checkout, slept.append), "Merged pull request #12 (merge).")
self.assertEqual(sum(slept), 90 * 60)
@@ -364,7 +386,7 @@ class Merge(unittest.TestCase):
checkout = self.requiring_approval()
checkout.unreadable = answer
self.assertIsInstance(step(["merge"], checkout), Failure)
self.assertEqual(checkout.acted(), [])
self.assertEqual(changes(checkout), [])
def test_requested_changes_leave_it_unmerged_without_waiting(self):
checkout = self.requiring_approval(GITHUB, "CHANGES_REQUESTED")
@@ -372,7 +394,7 @@ class Merge(unittest.TestCase):
failed = merged(checkout, slept.append)
self.assertIsInstance(failed, Failure)
self.assertIn("requested changes", failed.reason)
self.assertEqual((slept, checkout.acted()), ([], []))
self.assertEqual((slept, changes(checkout)), ([], []))
def test_a_branch_protection_that_asks_for_no_review_leaves_it_unmerged_naming_the_setting(self):
for decision in ("", None):
@@ -381,14 +403,14 @@ class Merge(unittest.TestCase):
failed = step(["merge"], checkout)
self.assertIsInstance(failed, Failure)
self.assertIn("requires no review", failed.reason)
self.assertEqual(checkout.acted(), [])
self.assertEqual(changes(checkout), [])
def test_gitea_with_wait_for_approval_leaves_it_unmerged_since_chunk_pr_reads_approvals_on_github_only(self):
checkout = self.requiring_approval(GITEA)
failed = step(["merge"], checkout)
self.assertIsInstance(failed, Failure)
self.assertIn("GitHub", failed.reason)
self.assertEqual(checkout.acted(), [])
self.assertEqual(changes(checkout), [])
def test_a_config_it_cannot_read_or_that_prints_neither_true_nor_false_leaves_it_unmerged(self):
for answer in (Failure("no config names the checkout"), "maybe\n", ""):
@@ -396,7 +418,7 @@ class Merge(unittest.TestCase):
checkout = Checkout(GITHUB, open=True)
checkout.answers[tuple(WAITS)] = answer
self.assertIsInstance(step(["merge"], checkout), Failure)
self.assertEqual(checkout.acted(), [])
self.assertEqual(changes(checkout), [])
def protected(self, *reads: list[tuple[str, str]]) -> Checkout:
"""A Gitea Checkout whose main requires a check matching CI / tests*, its status at HEAD holding each of reads in turn."""
@@ -419,28 +441,28 @@ class Merge(unittest.TestCase):
def test_a_failed_check_on_gitea_leaves_it_unmerged(self):
checkout = self.protected([("CI / tests (pull_request)", "pending")], [("CI / tests (pull_request)", "failure")])
self.assertIsInstance(merged(checkout, lambda _: None), Failure)
self.assertEqual(checkout.acted(), [])
self.assertEqual(changes(checkout), [])
def test_a_branch_protection_it_cannot_read_leaves_it_unmerged(self):
checkout = Checkout(GITEA, open=True)
checkout.answers[tuple(TEA_BRANCH)] = Failure("tea api: 500")
self.assertEqual(merged(checkout, self.fail), Failure("tea api: 500"))
self.assertNotIn(TEA_STATUS, checkout.ran)
self.assertEqual(checkout.acted(), [])
self.assertEqual(changes(checkout), [])
def test_an_unknown_default_branch_leaves_it_unmerged_reading_no_checks(self):
checkout = Checkout(GITEA, open=True)
checkout.answers[("git", "symbolic-ref", "--short", "refs/remotes/origin/HEAD")] = Failure("no such ref")
self.assertEqual(merged(checkout, self.fail), Failure("origin records no default branch; set it with `git remote set-head origin --auto`: no such ref"))
self.assertNotIn(TEA_STATUS, checkout.ran)
self.assertEqual(checkout.acted(), [])
self.assertEqual(changes(checkout), [])
def test_gitea_checks_that_never_pass_leave_it_unmerged(self):
checkout = self.protected(*[[("CI / tests (pull_request)", "pending")]] * 1000)
failed = merged(checkout, lambda _: None)
self.assertIsInstance(failed, Failure)
self.assertIn("gave up on pull request 12", failed.reason)
self.assertEqual(checkout.acted(), [])
self.assertEqual(changes(checkout), [])
def test_a_scoring_run_the_chunk_owes_and_has_not_recorded_refuses_the_merge(self):
for origin in (GITHUB, GITEA):
@@ -448,27 +470,27 @@ class Merge(unittest.TestCase):
checkout = Checkout(origin, open=True)
checkout.answers[tuple(OWED)] = Failure("larv-review scoring-run-owed: the chunk owes 2 scoring runs")
self.assertEqual(step(["merge"], checkout), Failure("larv-review scoring-run-owed: the chunk owes 2 scoring runs"))
self.assertEqual(checkout.acted(), [])
self.assertEqual(changes(checkout), [])
def test_github_merges_with_a_merge_commit_pinned_to_the_head(self):
checkout = Checkout(GITHUB, open=True, allowed=("squashMergeAllowed", "mergeCommitAllowed"))
self.assertEqual(step(["merge"], checkout), "Merged pull request #12 (merge).")
self.assertEqual(checkout.acted(), [["gh", "pr", "merge", "12", "--merge", "--match-head-commit", HEAD]])
self.assertEqual(changes(checkout), [["gh", "pr", "merge", "12", "--merge", "--match-head-commit", HEAD]])
def test_github_without_merge_commits_rebases(self):
checkout = Checkout(GITHUB, open=True, allowed=("squashMergeAllowed", "rebaseMergeAllowed"))
step(["merge"], checkout)
self.assertEqual(checkout.acted(), [["gh", "pr", "merge", "12", "--rebase", "--match-head-commit", HEAD]])
self.assertEqual(changes(checkout), [["gh", "pr", "merge", "12", "--rebase", "--match-head-commit", HEAD]])
def test_gitea_merges_fast_forward_only_where_only_that_and_squash_are_allowed(self):
checkout = Checkout(GITEA, open=True, allowed=("allow_squash_merge", "allow_fast_forward_only_merge"))
self.assertEqual(step(["merge"], checkout), "Merged pull request #12 (fast-forward-only).")
self.assertEqual(checkout.acted(), [["tea", "api", "--method", "POST", "--field", "Do=fast-forward-only", "--field", f"head_commit_id={HEAD}", "repos/{owner}/{repo}/pulls/12/merge"]])
self.assertEqual(changes(checkout), [["tea", "api", "--method", "POST", "--field", "Do=fast-forward-only", "--field", f"head_commit_id={HEAD}", "repos/{owner}/{repo}/pulls/12/merge"]])
def test_a_repository_allowing_no_known_method_is_refused_unmerged(self):
checkout = Checkout(GITEA, open=True, allowed=("allow_manual_merge",))
self.assertIsInstance(step(["merge"], checkout), Failure)
self.assertEqual(checkout.acted(), [])
self.assertEqual(changes(checkout), [])
def test_a_forge_failure_is_returned(self):
checkout = Checkout(GITHUB, open=True)
@@ -484,7 +506,282 @@ class Merge(unittest.TestCase):
checkout = Checkout(origin, open=True)
checkout.answers[tuple(settings)] = Failure("settings: denied")
self.assertEqual(step(["merge"], checkout), Failure("settings: denied"))
self.assertEqual(checkout.acted(), [])
self.assertEqual(changes(checkout), [])
def queue_is_free() -> bool:
"""Whether another merge could take its turn now."""
fd = os.open(pathlib.Path(GIT_FOLDER.name) / QUEUE, os.O_RDWR | os.O_CREAT)
try:
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
return False
finally:
os.close(fd)
return True
class MergeQueue(unittest.TestCase):
PUSHED = ["git", "push", "--quiet", "origin", "item-7"]
TODO_ITEM = str(pathlib.Path(__file__).resolve().parents[1] / "todo-item")
CONFIG = str(pathlib.Path(__file__).resolve().parents[1] / "project-config")
def moved(self, checkout: Checkout) -> Checkout:
"""checkout with origin's main two commits ahead of the branch, whose head is `decaf` once main is merged in."""
checkout.answers[tuple(BEHIND)] = "2\n"
run = checkout.__call__
def merging(command: list[str]) -> str | Failure:
answer = run(command)
if command == MERGE and not isinstance(answer, Failure):
checkout.answers[("git", "rev-parse", "HEAD")] = "decaf\n"
return answer
checkout.__call__ = merging # type: ignore[method-assign]
return checkout
def with_plan(self, checkout: Checkout, held: bool = True) -> tuple[Checkout, str]:
"""checkout in a project whose config names a todo.md and a CHANGELOG.md in one folder, which is returned, and titles commits `[{id}] {summary}`. The plan holds item 7 where held. A commit moves the head to `f00d`."""
folder = tempfile.mkdtemp()
self.addCleanup(shutil.rmtree, folder)
for name in ("todo.md", "CHANGELOG.md"):
(pathlib.Path(folder) / name).write_text("")
checkout.answers.update({
(self.TODO_ITEM, "show", "7"): "From todo.md:\n" if held else Failure("todo-item show 7: todo.md holds no item 7"),
(self.CONFIG, "plan"): f"{folder}/todo.md\n",
(self.CONFIG, "changelog"): f"{folder}/CHANGELOG.md\n",
(self.CONFIG, "commit-title"): "[{id}] {summary}\n",
("git", "-C", folder, "rev-parse", "--show-toplevel"): f"{folder}\n",
("git", "-C", folder, "status", "--porcelain", "--", f"{folder}/todo.md", f"{folder}/CHANGELOG.md"): " M todo.md\n",
})
run = checkout.__call__
def committing(command: list[str]) -> str | Failure:
if command[3:4] == ["commit"]:
checkout.answers[("git", "rev-parse", "HEAD")] = "f00d\n"
return run(command)
checkout.__call__ = committing # type: ignore[method-assign]
return checkout, folder
@staticmethod
def thread(path: str, last: str, resolved: bool = False) -> dict[str, object]:
return {"isResolved": resolved, "path": path, "comments": {"nodes": [{"author": {"login": last}}]}}
def test_malformed_finish_flags_dont_run_anything(self):
for flags in (["--finish"], ["--finish", "abc"], ["--changelog", "Bullet."], ["12"], ["--finish", "--no-changelog"], ["--finish", "7", "--changelog"], ["--finish", "7", "--no-changelog", "--changelog", "Bullet."]):
with self.subTest(flags):
checkout = Checkout(GITHUB, open=True)
self.assertEqual(step(["merge", *flags], checkout), Failure(USAGE))
self.assertEqual(checkout.ran, [])
def test_a_branch_behind_the_default_branch_merges_it_in_and_pushes_before_the_checks(self):
checkout = self.moved(Checkout(GITHUB, open=True))
self.assertEqual(merged(checkout.__call__), "Merged pull request #12 (merge).")
self.assertEqual(changes(checkout), [MERGE, self.PUSHED, ["gh", "pr", "merge", "12", "--merge", "--match-head-commit", "decaf"]])
self.assertLess(checkout.ran.index(self.PUSHED), checkout.ran.index(GH_CHECKS))
def test_a_conflict_with_the_default_branch_leaves_it_unmerged_naming_the_files_and_frees_the_queue(self):
checkout = self.moved(Checkout(GITHUB, open=True))
checkout.answers[tuple(MERGE)] = Failure("git merge --quiet: CONFLICT")
checkout.answers[("git", "diff", "--name-only", "--diff-filter=U")] = "bin/tool.py\n"
failed = merged(checkout.__call__)
self.assertIsInstance(failed, Failure)
self.assertIn("conflicts in bin/tool.py; the merge stays in progress: resolve them, commit, push, and run chunk-pr merge again", failed.reason)
self.assertEqual((changes(checkout), MERGE in checkout.ran), ([], True))
self.assertTrue(queue_is_free())
def test_a_finished_item_is_committed_under_the_configs_title_and_pushed_before_the_merge(self):
checkout, folder = self.with_plan(Checkout(GITHUB, open=True))
files = [f"{folder}/todo.md", f"{folder}/CHANGELOG.md"]
self.assertEqual(merged(checkout.__call__, finishes=[["7", "--changelog", "Exports keep their order."]]), "Merged pull request #12 (merge).")
self.assertEqual(changes(checkout)[:1], [[self.TODO_ITEM, "finish", "7", "--changelog", "Exports keep their order."]])
self.assertEqual(changes(checkout)[-4:], [
["git", "-C", folder, "add", "--", *files],
["git", "-C", folder, "commit", "--quiet", "-m", "[7] Finish item 7 in the plan", "--", *files],
self.PUSHED,
["gh", "pr", "merge", "12", "--merge", "--match-head-commit", "f00d"],
])
def test_the_flags_reach_todo_item_as_given(self):
checkout, _ = self.with_plan(Checkout(GITHUB, open=True))
checkout.answers.update({(self.TODO_ITEM, "show", "8"): "From todo.md:\n", (self.TODO_ITEM, "show", "9"): "From todo.md:\n"})
self.assertEqual(step(["merge", "--finish", "7", "--no-changelog", "--finish", "8", "--finish", "9", "--changelog", "Exports keep their order."], checkout.__call__), "Merged pull request #12 (merge).")
self.assertEqual([command[1:] for command in checkout.ran if command[:2] == [self.TODO_ITEM, "finish"]], [["finish", "7", "--no-changelog"], ["finish", "8"], ["finish", "9", "--changelog", "Exports keep their order."]])
def test_an_item_the_plan_no_longer_holds_is_named_on_the_last_line_and_what_an_earlier_run_left_uncommitted_is_committed(self):
checkout, folder = self.with_plan(Checkout(GITHUB, open=True), held=False)
self.assertEqual(merged(checkout.__call__, finishes=[["7"]]), "Merged pull request #12 (merge). The plan held no item 7 when merge began, so merge left the plan as it was there.")
self.assertNotIn([self.TODO_ITEM, "finish", "7"], checkout.ran)
self.assertEqual([command[3] for command in changes(checkout)[:-1]], ["add", "commit", "origin"])
self.assertEqual(changes(checkout)[-1], ["gh", "pr", "merge", "12", "--merge", "--match-head-commit", "f00d"])
def test_each_item_the_plan_no_longer_holds_is_named(self):
checkout, _ = self.with_plan(Checkout(GITHUB, open=True), held=False)
checkout.answers[(self.TODO_ITEM, "show", "8")] = Failure("todo-item show 8: todo.md holds no item 8")
self.assertIn("The plan held no item 7, 8 when merge began", str(merged(checkout.__call__, finishes=[["7"], ["8"]])))
def test_a_plan_that_turns_unreadable_inside_the_turn_leaves_it_unmerged(self):
checkout, _ = self.with_plan(Checkout(GITHUB, open=True))
run, shows = checkout.__call__, []
def run_whose_second_show_fails(command: list[str]) -> str | Failure:
shows.extend([command] if command[1:2] == ["show"] else [])
return Failure("todo-item show 7: unreadable") if command[1:2] == ["show"] and len(shows) == 2 else run(command)
self.assertEqual(merged(run_whose_second_show_fails, finishes=[["7"]]), Failure("todo-item show 7: unreadable"))
self.assertNotIn([self.TODO_ITEM, "finish", "7"], checkout.ran)
def test_a_finish_that_changes_no_file_commits_and_pushes_nothing(self):
for clean in ("status", "records"):
with self.subTest(clean):
checkout, folder = self.with_plan(Checkout(GITHUB, open=True))
if clean == "status":
checkout.answers[("git", "-C", folder, "status", "--porcelain", "--", f"{folder}/todo.md", f"{folder}/CHANGELOG.md")] = "\n"
else:
checkout.answers.update({(self.CONFIG, "plan"): "PAY-1\n", (self.CONFIG, "changelog"): f"{folder}/none.md\n"})
self.assertEqual(merged(checkout.__call__, finishes=[["7", "--no-changelog"]]), "Merged pull request #12 (merge).")
self.assertEqual(changes(checkout), [[self.TODO_ITEM, "finish", "7", "--no-changelog"], ["gh", "pr", "merge", "12", "--merge", "--match-head-commit", HEAD]])
def test_a_branch_outside_the_branch_template_titles_the_finish_with_the_summary_alone(self):
checkout, folder = self.with_plan(Checkout(GITHUB, open=True))
checkout.answers[tuple(BRANCH)] = "feature/PAY-{id}\n"
merged(checkout.__call__, finishes=[["7"]])
self.assertIn("Finish item 7 in the plan", [command[6] for command in checkout.ran if command[3:4] == ["commit"]])
def test_a_plan_it_cannot_read_or_an_item_it_cannot_finish_leaves_it_unmerged(self):
for failing in ("show", "finish"):
with self.subTest(failing):
checkout, _ = self.with_plan(Checkout(GITHUB, open=True))
checkout.answers[(self.TODO_ITEM, failing, "7")] = Failure(f"todo-item {failing} 7: no config names the checkout")
self.assertEqual(merged(checkout.__call__, finishes=[["7"]]), Failure(f"todo-item {failing} 7: no config names the checkout"))
self.assertNotIn(self.PUSHED, checkout.ran)
def test_a_step_of_the_turn_that_fails_leaves_it_unmerged_with_that_failure(self):
_, folder = self.with_plan(Checkout(GITHUB, open=True))
for failing in (FETCH, BEHIND, COMMON, self.PUSHED, ["git", "-C", "<plan>", "rev-parse", "--show-toplevel"], ["git", "-C", "<plan>", "add"], ["git", "-C", "<plan>", "commit"], [self.CONFIG, "comprehension-history"]):
with self.subTest(failing):
checkout, folder = self.with_plan(Checkout(GITHUB, open=True))
run = checkout.__call__
def failing_run(command: list[str]) -> str | Failure:
asked = ["<plan>" if part == folder else part for part in command]
return Failure("that step failed") if tuple(asked[:len(failing)]) == tuple(failing) else run(command)
self.assertEqual(merged(failing_run, finishes=[["7"]]), Failure("that step failed"))
self.assertNotIn("merge", [command[2] for command in checkout.ran if command[0] == "gh"])
def test_a_finish_that_fails_after_the_default_branch_was_merged_in_still_pushes_the_branch(self):
checkout, _ = self.with_plan(self.moved(Checkout(GITHUB, open=True)))
checkout.answers[(self.TODO_ITEM, "finish", "7")] = Failure("todo-item finish 7: a decision cites item 7")
self.assertEqual(merged(checkout.__call__, finishes=[["7"]]), Failure("todo-item finish 7: a decision cites item 7"))
self.assertEqual(changes(checkout), [MERGE, self.PUSHED])
def test_the_scoring_run_is_asked_for_once_the_finish_is_committed_and_one_owed_leaves_it_unmerged(self):
checkout, _ = self.with_plan(Checkout(GITHUB, open=True))
commit = lambda: next(index for index, command in enumerate(checkout.ran) if command[3:4] == ["commit"])
self.assertEqual(merged(checkout.__call__, finishes=[["7"]]), "Merged pull request #12 (merge).")
self.assertLess(commit(), checkout.ran.index(OWED))
checkout, _ = self.with_plan(Checkout(GITHUB, open=True))
checkout.answers[tuple(OWED)] = Failure("the chunk owes 1 scoring run")
self.assertEqual(merged(checkout.__call__, finishes=[["7"]]), Failure("the chunk owes 1 scoring run"))
self.assertEqual(changes(checkout)[-1], self.PUSHED)
def test_a_merge_holds_the_queue_through_the_checks_and_frees_it_while_it_waits_for_an_approval(self):
checkout = Checkout(GITHUB, open=True)
checkout.answers[tuple(WAITS)] = "true\n"
checkout.decisions = ["REVIEW_REQUIRED", "REVIEW_REQUIRED", "APPROVED"]
free: dict[str, bool] = {}
def run(command: list[str]) -> str | Failure:
if command == GH_CHECKS:
free.setdefault("during the checks", queue_is_free())
return checkout(command)
self.assertEqual(merged(run, lambda seconds: free.setdefault("waiting for the approval", queue_is_free())), "Merged pull request #12 (merge).")
self.assertEqual(free, {"during the checks": False, "waiting for the approval": True})
self.assertEqual(checkout.ran.count(FETCH), 2)
def test_a_reviewers_comment_ends_the_wait_naming_its_file_until_the_author_answers_or_it_is_resolved(self):
checkout = Checkout(GITHUB, open=True)
checkout.answers[tuple(WAITS)] = "true\n"
checkout.decisions = ["REVIEW_REQUIRED"]
checkout.threads = [self.thread("bin/asked.py", "reviewer"), self.thread("bin/answered.py", "worker"), self.thread("bin/resolved.py", "reviewer", resolved=True)]
slept: list[float] = []
failed = merged(checkout, slept.append)
self.assertIsInstance(failed, Failure)
self.assertIn("waits for an answer, in bin/asked.py;", failed.reason)
self.assertEqual((slept, changes(checkout)), ([], []))
checkout.threads = checkout.threads[1:]
checkout.decisions = ["REVIEW_REQUIRED", "REVIEW_REQUIRED", "APPROVED"]
self.assertEqual(merged(checkout, slept.append), "Merged pull request #12 (merge).")
def test_an_approved_pull_request_with_a_comment_that_waits_for_an_answer_stays_unmerged(self):
checkout = Checkout(GITHUB, open=True)
checkout.answers[tuple(WAITS)] = "true\n"
checkout.threads = [self.thread("bin/asked.py", "reviewer")]
failed = merged(checkout)
self.assertIsInstance(failed, Failure)
self.assertIn("waits for an answer, in bin/asked.py;", failed.reason)
self.assertEqual(changes(checkout), [])
def test_review_threads_it_cannot_read_leave_it_unmerged(self):
for answer, reason in ((Failure("gh api graphql failed"), "gh api graphql failed"), ("not json", "gh api graphql printed no review threads: not json"), ("{}", "gh api graphql printed no review threads: {}")):
with self.subTest(answer):
checkout = Checkout(GITHUB, open=True)
checkout.answers.update({tuple(WAITS): "true\n", tuple(GH_THREADS): answer})
checkout.decisions = ["REVIEW_REQUIRED"]
self.assertEqual(merged(checkout, lambda seconds: None), Failure(reason))
self.assertEqual(changes(checkout), [])
def test_a_default_branch_that_moved_after_the_branchs_last_paired_ruling_stops_for_a_new_one(self):
history = "/checkout/docs/comprehension-history.md"
ruled = ["git", "log", "-1", "--format=%H", "-G", "^Ruling: ", "origin/main..HEAD", "--", history]
since = ["git", "rev-list", "--count", "bead..origin/main"]
for name, answers, stops in (
("moved since the ruling", {tuple(ruled): "bead\n", tuple(since): "2\n"}, True),
("ruled at this head", {tuple(ruled): "bead\n", tuple(since): "0\n"}, False),
("no ruling", {tuple(ruled): "\n"}, False),
):
with self.subTest(name):
checkout = Checkout(GITHUB, open=True)
checkout.answers.update({(self.CONFIG, "comprehension-history"): f"{history}\n", **answers})
done = merged(checkout.__call__)
self.assertEqual(isinstance(done, Failure) and "run the paired ruling again" in done.reason, stops, done)
self.assertEqual(changes(checkout), [] if stops else [["gh", "pr", "merge", "12", "--merge", "--match-head-commit", HEAD]])
def test_a_history_outside_the_checkout_or_one_git_cannot_read_never_stops_or_fails_the_merge_wrongly(self):
ruled = ("git", "log", "-1", "--format=%H", "-G", "^Ruling: ", "origin/main..HEAD", "--", "/checkout/history.md")
checkout = Checkout(GITHUB, open=True)
checkout.answers[(self.CONFIG, "comprehension-history")] = "/elsewhere/history.md\n"
self.assertEqual(merged(checkout.__call__), "Merged pull request #12 (merge).")
self.assertNotIn("log", [command[1] for command in checkout.ran])
for failing in (ruled, ("git", "rev-list", "--count", "bead..origin/main"), ("git", "rev-parse", "--show-toplevel")):
with self.subTest(failing):
checkout = Checkout(GITHUB, open=True)
checkout.answers.update({(self.CONFIG, "comprehension-history"): "/checkout/history.md\n", ruled: "bead\n"})
checkout.answers[failing] = Failure("git failed")
self.assertEqual(merged(checkout.__call__), Failure("git failed"))
def test_a_turn_keeps_every_other_merge_out_until_it_ends_even_by_an_error(self):
with self.assertRaises(ValueError):
with turn(pathlib.Path(GIT_FOLDER.name) / QUEUE, "12", lambda seconds: None):
self.assertFalse(queue_is_free())
raise ValueError
self.assertTrue(queue_is_free())
def test_a_queue_another_pull_request_holds_for_half_an_hour_leaves_it_unmerged_naming_the_holder(self):
checkout = Checkout(GITHUB, open=True)
slept: list[float] = []
with turn(pathlib.Path(GIT_FOLDER.name) / QUEUE, "1234", lambda seconds: None):
pass
with turn(pathlib.Path(GIT_FOLDER.name) / QUEUE, "31", lambda seconds: None):
failed = merged(checkout, slept.append)
self.assertEqual(failed, Failure("the merge queue stayed held for 30 minutes, last by pull request #31, so this one took no turn; run chunk-pr merge again"))
self.assertEqual((sum(slept), set(slept), changes(checkout)), (30 * 60, {10}, []))
def test_a_queue_freed_while_it_waits_gives_it_the_turn(self):
checkout = Checkout(GITHUB, open=True)
holder = contextlib.ExitStack()
holder.enter_context(turn(pathlib.Path(GIT_FOLDER.name) / QUEUE, "31", lambda seconds: None))
self.assertEqual(merged(checkout, lambda seconds: holder.close()), "Merged pull request #12 (merge).")
def test_a_queue_it_cannot_open_leaves_it_unmerged(self):
checkout = Checkout(GITHUB, open=True)
checkout.answers[tuple(COMMON)] = "/nonexistent/folder\n"
self.assertEqual(merged(checkout), Failure("cannot take a turn in the merge queue, /nonexistent/folder/chunk-pr-merge-queue: No such file or directory"))
self.assertEqual(checkout.acted(), [])
class Clean(unittest.TestCase):
+7 -3
View File
@@ -1,9 +1,9 @@
"""The pure choices the preflight's steps act on."""
import pathlib
from release_plan.release_standing import chunk_item, Cut, dated_cut, LastCut, ReadyToCut, ReviewDue, Unknown, Unplanned
from release_plan.release_standing import carried, chunk_item, Cut, dated_cut, LastCut, ReadyToCut, ReviewDue, Unknown, Unplanned
from chunk_preflight.gathered import CarriedOver, Forge, NoItem, Plan
from failure import Failure
from chunk_preflight.gathered import Forge, NoItem, Plan
from release_plan.todo_table import NoItemsTable
from plan_store import stores as plan_stores
from release_plan.release import version
@@ -52,7 +52,11 @@ def planned(todo: plan_stores.Plan | Failure, cut: LastCut, default: str, branch
first = pick.item
if first is None:
return NoItem(f"every item of release {version(pick.release)} in {where} waits." if pick.release is not None else f"{where}'s items table holds no item.")
return Plan(found, first, f"{first.tagline}\n\n{first.detail}".strip(), branch)
held = carried(found, cut)
moved = [(was, now) for was, now in zip(found, held) if was.release != now.release]
# Every carried item takes one release, the next.
over = CarriedOver(moved[0][1].release, tuple(was.id for was, _ in moved)) if moved else None
return Plan(held, first, f"{first.tagline}\n\n{first.detail}".strip(), branch, over)
def worktree_on(porcelain: str, branch: str) -> pathlib.Path | None:
+11 -1
View File
@@ -45,7 +45,8 @@ def item_lines(plan: str, item: ItemFacts) -> list[str]:
first = item.plan.first
worktree = item.worktree.reason if isinstance(item.worktree, Failure) else f"{item.worktree.path}, {item.worktree.how}"
return [
f"- The earliest release in {plan}: {version(first.release)}. Its first item that does not wait: item {first.id}, {levels(first)}.",
f"- The {'next release, after the last cut, that ' + plan + ' names' if item.plan.carried else 'earliest release in ' + plan}: {version(first.release)}. 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),
@@ -57,6 +58,15 @@ def item_lines(plan: str, item: ItemFacts) -> list[str]:
]
def carried_lines(plan: Plan) -> list[str]:
"""What the worker does about the items of a release someone cut while it held them."""
over = plan.carried
if over is None:
return []
items, count, them = (f"Items {listed([str(id_) for id_ in over.ids], 'and')} are", "they count", "them") if len(over.ids) > 1 else (f"Item {over.ids[0]} is", "it counts", "it")
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}."]
def joining_details(plan: Plan) -> 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."""
joining = bundle_candidates(plan.items, plan.first)
+10
View File
@@ -6,6 +6,7 @@ import typing
from failure import Failure
from release_plan.todo_table import Item
from release_plan.release_standing import LastCut
from release_plan.release import Release
from project_config import templates
# The CLI that lists a forge's pull requests: gh for a github.com origin, tea for any other.
@@ -20,6 +21,13 @@ class Ran:
stderr: str
@dataclasses.dataclass(frozen=True)
class CarriedOver:
"""The items, by ID in the plan's order, that the plan files under a release already cut, and that count as `into`'s, the next release: release_standing.carried."""
into: Release
ids: tuple[int, ...]
@dataclasses.dataclass(frozen=True)
class Plan:
"""The default branch's plan items, each with its detail, and `first`: the item the next chunk takes first."""
@@ -28,6 +36,8 @@ class Plan:
# first's tagline and detail.
text: str
branch_template: str
# The items of a release already cut, which `items` and `first` hold as the next release's. None where every item's release is after the last cut.
carried: CarriedOver | None = None
@property
def branch(self) -> str:
+3 -1
View File
@@ -27,7 +27,9 @@ and prints that the release reviews and the cuts are the human's to call. It pri
commits since the cut) and no commit titled `Release review of <release>` followed the tag,
finished and ready to cut once one did, and else to be planned first. On a branch with no tag,
such a commit counts only where its <release> is after the version under the dated heading.
Where todo.md's earliest release is x.y.z or earlier, it says todo.md files items under a release
Where todo.md files items under x.y.z or earlier, someone cut a release that still held them:
they count as the next release, the earliest after x.y.z that todo.md names or has named
since the cut, and a line says to move them there. Where there is no such release, it says todo.md files items under a release
already cut;
- with --worktree, the item's worktree: a sibling of the checkout named <checkout>-<branch>,
each / of the branch a dash, on the branch the config's `branch` template names, which is
+25 -2
View File
@@ -10,10 +10,10 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from project_config.templates import BRANCH
from chunk_preflight.gathered import CarriedOver, Gathered, ItemFacts, NamedPath, NoItem, Ran, Worktree
from chunk_preflight import choices
from failure import Failure
from chunk_preflight.choices import forge_of, worktree_add
from chunk_preflight.gathered import Gathered, ItemFacts, NamedPath, NoItem, Ran, Worktree
from test_env import isolated_env
from release_plan.release_standing import LastCut, UNSEEN_RELEASES
from chunk_preflight.main import line_count, ran, seconds, TIMEOUT
@@ -54,6 +54,10 @@ Change `src/app.py`'s `run` and the files under `src`, not `gone.py`.
SHIPPED = TODO.replace("| 3 | 0.2.0 | | | **Do the next thing.** | 2 | 2 | 3 | 5 | 3 | 1 by 9 | 56.2 |\n", "").replace("| 7 | 0.2.0 | 3 |", "| 7 | 0.2.0 | |").replace("### 3. Do the next thing.", "### 7. Do the thing after.")
# The plan once release 0.2.0 has shipped all its items: only release 0.3.0's item 9 is left.
LATER = TODO[:TODO.index("| 5 |")] + "| 9 | 0.3.0 | | | **Do a later thing.** | 1 | 1 | 1 | 1 | 1 | 1 by 9 | 90.0 |\n"
# Item 9's row, the only one under release 0.3.0.
NINTH = "| 9 | 0.3.0 | | | **Do a later thing.** | 1 | 1 | 1 | 1 | 1 | 1 by 9 | 90.0 |\n"
# A plan whose release 0.2.0 holds item 3 alone, before release 0.3.0's item 9.
SHIPPED_BUT_3 = TODO[:TODO.index("| 5 |")] + "| 3 | 0.2.0 | | | **Do the next thing.** | 2 | 2 | 3 | 5 | 3 | 1 by 9 | 56.2 |\n" + NINTH
# An items table that holds no row.
EMPTY = TODO[:TODO.index("| 5 |")]
CHANGELOG = "# Changelog\n\n## Unreleased\n\n- One.\n - A nested line.\n- Two.\n\n## 0.1.0\n\n- Old.\n"
@@ -576,8 +580,27 @@ class Plans(unittest.TestCase):
def test_takes_the_earliest_release_where_no_earlier_one_was_named_since_the_last_cut(self):
self.assertEqual(planned(LATER, LastCut("v0.1.0", "", 4, [LATER]), "origin/main", BRANCH).first.id, 9)
def test_counts_the_items_of_a_release_already_cut_as_the_next_releases_and_says_to_move_them(self):
plan = planned(TODO, LastCut("v0.2.0", "", 4, []), "origin/main", BRANCH)
self.assertEqual((plan.first.id, plan.first.release), (3, (0, 3, 0)))
self.assertEqual({item.release for item in plan.items}, {(0, 3, 0)})
self.assertEqual(plan.carried, CarriedOver((0, 3, 0), (5, 3, 7, 8)))
said = rendered(dataclasses.replace(item_facts(), plan=plan), LastCut("v0.2.0", "", 4, []))
self.assertIn("- Items 5, 3, 7 and 8 are filed under a release already cut, so they count as release 0.3.0's, the next.", said)
self.assertIn("`~/.claude/bin/todo-item move`", said)
self.assertIn("- The next release, after the last cut, that origin/main's todo.md names: 0.3.0. Its first item that does not wait: item 3,", said)
self.assertNotIn("already cut", rendered(item_facts()))
def test_says_to_move_one_or_two_items_of_a_release_already_cut_in_the_singular_or_the_plural(self):
cut = LastCut("v0.2.0", "", 4, [])
for todo, ids, said in ((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")):
with self.subTest(ids=ids):
plan = planned(todo, cut, "origin/main", BRANCH)
self.assertEqual(plan.carried, CarriedOver((0, 3, 0), ids))
self.assertIn(said, rendered(dataclasses.replace(item_facts(), plan=plan), cut))
def test_says_the_plan_files_items_under_a_release_already_cut(self):
why = planned(TODO, LastCut("v0.2.0", "", 4, []), "origin/main", BRANCH).why
why = planned(TODO.replace(NINTH, ""), LastCut("v0.2.0", "", 4, []), "origin/main", BRANCH).why
self.assertIn("release 0.2.0", why)
self.assertIn("v0.2.0", why)
self.assertIn("not after", why)
+14 -9
View File
@@ -2,7 +2,7 @@
usage: judge-replay <model>
<model> is a project model on the routing ladder, such as claude-opus-5-5. The tool replays the
<model> is a project model on the routing ladder this setup ships, such as claude-opus-5-5. The tool replays the
verdicts archived for the projects that ~/.claude/loop-claude-models.json runs on it: the latest
15 of each kind, finished, unfinished, interrupt and quoted answer. Each transcript copy in the
archive is what the judge read for the verdict beside it, so the replay hands the judge that copy,
@@ -41,8 +41,9 @@ from transcript_archive.project_key import checkout_of
from loop_effects.effects import Effects
from failure import Failure
from rung_replay.search import first_reply, replayed
from model_routing.ladder import Ladder, REVIEW_STEPS, Rung
from claude_code.reply import Limited
from model_routing.ladder import lowest_worker_rung, position, project_rung, review_floor, REVIEW_STEPS, Rung
from model_routing.ladder_file import read_ladder, SHIPPED
from loop_claude.project.premises import read_premises
from loop_claude.project.records import read_records
from claude_code.transcript import read_transcript
@@ -56,7 +57,11 @@ REFERENCE_EFFORT = "xhigh"
def main(argv: list[str], env: typing.Mapping[str, str], home: pathlib.Path, effects: Effects) -> int:
project = arguments_or_exit(TOOL, argv, __doc__, USAGE, model_argument)
# The shipped ladder, not a project's: the replay spans every project on the model.
ladder = read_ladder(SHIPPED)
if isinstance(ladder, Failure):
return failed(TOOL, ladder.reason)
project = arguments_or_exit(TOOL, argv, __doc__, USAGE, lambda argv: model_argument(ladder, argv))
if isinstance(project, int):
return project
cases = archived_cases(project.model, archive_root(home, env), home)
@@ -67,21 +72,21 @@ def main(argv: list[str], env: typing.Mapping[str, str], home: pathlib.Path, eff
cases = sample(cases, PER_KIND)
reference = Rung(project.model, REFERENCE_EFFORT)
# The candidates stop at the lowest rung a worker routes to: no route uses a rung below it for the judge.
replay = replayed(cases, reference, down_from(project, lowest_worker_rung(project)), lambda found, rung: rule(found, rung, home, effects), reproduced, "verdicts", climbs(project, reference))
replay = replayed(cases, reference, down_from(ladder, project, ladder.lowest_worker_rung(project)), lambda found, rung: rule(found, rung, home, effects), reproduced, "verdicts", climbs(ladder, project, reference))
if isinstance(replay, Limited):
return limited_exit(TOOL, replay)
print(report(project.model, reference, cases, replay))
return 0
def model_argument(argv: list[str]) -> Rung | None:
"""The project's rung of the one model argv names; None for any other argv."""
return project_rung(argv[0]) if len(argv) == 1 else None
def model_argument(ladder: Ladder, argv: list[str]) -> Rung | None:
"""The project's rung on ladder of the one model argv names; None for any other argv."""
return ladder.project_rung(argv[0]) if len(argv) == 1 else None
def climbs(project: Rung, reference: Rung) -> list[Rung]:
def climbs(ladder: Ladder, project: Rung, reference: Rung) -> list[Rung]:
"""The rungs above the project's rung that an E + I raises a review to, except the reference's, lowest first."""
return sorted({review_floor(project, score) for score in REVIEW_STEPS} - {project, reference}, key=position)
return sorted({ladder.review_floor(project, score) for score in REVIEW_STEPS} - {project, reference}, key=ladder.position)
def archived_cases(model: str, root: pathlib.Path, home: pathlib.Path) -> list[Case] | Failure:
+30 -30
View File
@@ -1,11 +1,11 @@
"""What loop-claude says to the worker each cycle. model_routing.review_choice chooses where the reviews run. review_launches and reruns put that choice into sentences, and escalation says where escalated subagents run; rung_sentences returns the sentences of all three. In a chunk's first prompt, routed_by places them after its routing sentences where an item routed the chunk, and fresh places them alone otherwise. rungs_held repeats them at the end of a prompt after a step-up or an unfinished verdict."""
from model_routing.review_choice import chosen, ReviewChoice
from loop_claude.cycle.chunk_items import CHUNK_ITEMS
from model_routing.ladder import climbed, LADDER, position, Rung
from model_routing.route import ESCALATION_MARKER, Route
from loop_claude.routing import escalation_rungs
from loop_claude.project.records import HUMAN_RULE_NAMES, RECORD_FILES
from review_rules.review_passes import INSTRUCTION_FILES, INSTRUCTION_FOLDERS
from model_routing.ladder import Ladder, Rung
from text_files.markdown_text import listed, quoted
from claude_code.transcript import Typed
@@ -29,17 +29,17 @@ NAME_THE_ITEMS = f"Name every todo.md item this chunk takes on one line, as in `
AFTER_CODE_HEALTH = 'which rank after code health (~/.claude/CLAUDE.md → "Shared goal") unless the goals file voids it'
def fresh(task: str, premises: str, route: Route, project: Rung | None, facts: str) -> str:
def fresh(task: str, premises: str, route: Route, ladder: Ladder, project: Rung | None, facts: str) -> str:
"""A chunk's first prompt; facts is preflight_facts' or preflight_failed's text."""
routed = f"{routed_by(route, project)} {recount(route)}" if route.item else " ".join(rung_sentences(route, project))
routed = f"{routed_by(route, ladder, project)} {recount(route)}" if route.item else " ".join(rung_sentences(route, ladder, project))
opening = f"{routed}\n\n" if routed else ""
return f"{task}\n\nContinue any open draft PR or worktree for the chunk before creating a new one. {READING_RULE} {NAME_THE_ITEMS}\n\n{opening}{facts}\n\nThe chunk's todo.md items, or else the task above, set its scope. The goals below, {AFTER_CODE_HEALTH}, choose between ways to deliver that scope, and never widen it.\n\nFrom the goals file, {premises}"
def routed_by(route: Route, project: Rung | None) -> str:
def routed_by(route: Route, ladder: Ladder, project: Rung | None) -> str:
return " ".join((
f"loop-claude runs you on {route.rung}, routed by item {route.item}'s L of {route.likelihood}.",
*rung_sentences(route, project),
*rung_sentences(route, ladder, project),
))
@@ -58,12 +58,12 @@ def preflight_failed(reason: str) -> str:
return f"loop-claude could not run `~/.claude/bin/chunk-preflight`, so find the chunk's facts yourself. Why it could not run: {reason}"
def review_launches(route: Route, project: Rung | None) -> list[str]:
def review_launches(route: Route, ladder: Ladder, project: Rung | None) -> list[str]:
"""The sentences naming where to launch reviews, in this order, each from the function that says when it applies; none off the ladder."""
if project is None:
return []
choice = chosen(project, route)
return [*shared_launches(choice, route, project), *scan_launch(choice, route), *planning_launch(route, project), *taken_in_launches(choice), *markdown_launch(choice)]
choice = chosen(ladder, project, route)
return [*shared_launches(choice, route, project), *scan_launch(choice, route), *planning_launch(route, ladder, project), *taken_in_launches(choice), *markdown_launch(choice)]
def scan_launch(choice: ReviewChoice, route: Route) -> list[str]:
@@ -71,9 +71,9 @@ def scan_launch(choice: ReviewChoice, route: Route) -> list[str]:
return ["Run a full scan only from such a subagent, since the scan's agents run on the model that starts them."] if choice.security != route.rung else []
def planning_launch(route: Route, project: Rung) -> list[str]:
def planning_launch(route: Route, ladder: Ladder, project: Rung) -> list[str]:
"""Where the worker runs below the project's rung, the sentence naming where to launch a subagent that files or scores todo.md items. On an Opus 5.5 project: `Your rung is below the project's: launch each subagent that files or scores todo.md items on the rung `~/.claude/bin/subagent-rung --plan claude-opus-5-5 <L>` prints.`"""
return [f"Your rung is below the project's: launch each subagent that files or scores todo.md items on the rung `~/.claude/bin/subagent-rung --plan {project.model} <L>` prints."] if position(route.rung) < position(project) else []
return [f"Your rung is below the project's: launch each subagent that files or scores todo.md items on the rung `~/.claude/bin/subagent-rung --plan {project.model} <L>` prints."] if ladder.position(route.rung) < ladder.position(project) else []
def markdown_launch(choice: ReviewChoice) -> list[str]:
@@ -118,19 +118,19 @@ def rung_named(rung: Rung, route: Route, project: Rung) -> str:
return f"the rung item {route.item}'s E + I of {route.escape_and_impact} picks"
def escalation(route: Route, project: Rung | None) -> list[str]:
def escalation(route: Route, ladder: Ladder, project: Rung | None) -> list[str]:
"""The prompt's escalation sentences, the marker's among them. None off the ladder or on its top rung. Where escalation_rungs opens none, the worker escalates only with the human's yes.
Else they name the rungs escalation_rungs opens to a subagent, and offer to resume the worker one rung up for the rest of the chunk, up to the highest of those rungs.
For a worker one rung above the project's, routed by item 3 of L 4, they read: `When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `<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's prompt with `Escalation trigger <n>:`, n the trigger's number.` and `Where the hard part is the rest of the chunk, end your run instead, asking loop-claude for a higher rung and naming a trigger that fired since your last step-up, if any: once the judge finds it in your transcript, the next cycle resumes you one rung up, up to `<rung>`.`
"""
if project is None or route.rung not in LADDER[:-1]:
if project is None or route.rung not in ladder.rungs[:-1]:
return []
marked = f"Open the subagent's prompt with `{ESCALATION_MARKER} <n>:`, n the trigger's number."
rungs = [f"`{rung.agent_args()}`" for rung in escalation_rungs(project, route)]
rungs = [f"`{rung.agent_args()}`" for rung in escalation_rungs(ladder, project, route)]
if not rungs:
return [
f"An escalation trigger in `~/.claude/CLAUDE.md` lets you hand the hard part of a task to a subagent with the Agent tool set to `{climbed(route.rung, 1).agent_args()}`, one rung above yours, only once the human agrees; loop-claude will not resume you higher for a trigger either, so ask the human for that yes.",
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 `{ladder.climbed(route.rung, 1).agent_args()}`, one rung above yours, only once the human agrees; loop-claude will not resume you higher for a trigger either, so ask the human for that yes.",
marked,
]
further = f", and on each further trigger one rung higher, up to {rungs[-1]}" if len(rungs) > 1 else ""
@@ -141,16 +141,16 @@ def escalation(route: Route, project: Rung | None) -> list[str]:
]
def reruns(route: Route, project: Rung | None) -> list[str]:
def reruns(route: Route, ladder: Ladder, project: Rung | None) -> list[str]:
"""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.
For a worker one rung below the project'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>`.`
"""
if project is None or route.rung not in LADDER:
if project is None or route.rung not in ladder.rungs:
return []
choice = chosen(project, route)
choice = chosen(ladder, project, route)
launched = (("reviewer", choice.reviewers), ("comprehension seat", choice.seat))
rerun = {name: climbed(rung, 1) for name, rung in launched if rung != LADDER[-1]}
rerun = {name: ladder.climbed(rung, 1) for name, rung in launched if rung != ladder.rungs[-1]}
if not rerun:
return []
if len(set(rerun.values())) == 1:
@@ -158,31 +158,31 @@ def reruns(route: Route, project: Rung | None) -> list[str]:
return [f"A reviewer that asks for a rerun one rung up reruns with the Agent tool set to `{rerun['reviewer'].agent_args()}`, and a comprehension seat with `{rerun['comprehension seat'].agent_args()}`."]
def resumed(unfinished_evidence: str, route: Route, project: Rung | None) -> str:
def resumed(unfinished_evidence: str, route: Route, ladder: Ladder, project: Rung | None) -> str:
"""Names the worker's rung, so it learns whether its request for a higher rung went through, and the project's again, since a step-up between cycles may have taken the worker above it."""
on = f" loop-claude runs you on {route.rung}." if project else ""
ruled = f" A judge ruled the chunk unfinished, quoting this passage of your transcript as the work remaining:\n\n{quoted(unfinished_evidence)}\n\n" if unfinished_evidence else " "
return f"Continue the task; the previous run ended before the chunk was finished.{ruled}The chunk is finished once it is merged, or nothing remains that you could do on your own. Even then, it is finished only once {ANSWERS_RECORDED}. {NAME_THE_ITEMS}{on}{rungs_held(route, project)}"
return f"Continue the task; the previous run ended before the chunk was finished.{ruled}The chunk is finished once it is merged, or nothing remains that you could do on your own. Even then, it is finished only once {ANSWERS_RECORDED}. {NAME_THE_ITEMS}{on}{rungs_held(route, ladder, project)}"
def rung_sentences(route: Route, project: Rung | None) -> list[str]:
def rung_sentences(route: Route, ladder: Ladder, project: Rung | None) -> list[str]:
"""The sentences that depend on the worker's rung: where its reviews run and rerun, and where its escalated subagents run."""
return [*review_launches(route, project), *escalation(route, project), *reruns(route, project)]
return [*review_launches(route, ladder, project), *escalation(route, ladder, project), *reruns(route, ladder, project)]
def rungs_held(route: Route, project: Rung | None) -> str:
def rungs_held(route: Route, ladder: Ladder, project: Rung | None) -> str:
"""rung_sentences, each after a space, to follow the sentence a prompt ends on."""
return "".join(f" {sentence}" for sentence in rung_sentences(route, project))
return "".join(f" {sentence}" for sentence in rung_sentences(route, ladder, project))
def answered(question: str, answer: str, route: Route, project: Rung | None, stepped: bool) -> str:
def answered(question: str, answer: str, route: Route, ladder: Ladder, project: Rung | None, stepped: bool) -> str:
"""stepped is whether the answer's ruling stepped the worker up."""
return f"Your question: {question}\n\n{QUOTE_SOURCES} answers it:\n\n{answer}\n\nContinue the task.{stepped_to(route, project, stepped)}"
return f"Your question: {question}\n\n{QUOTE_SOURCES} answers it:\n\n{answer}\n\nContinue the task.{stepped_to(route, ladder, project, stepped)}"
def typed(question: str, answer: str, route: Route, project: Rung | None, stepped: bool) -> str:
def typed(question: str, answer: str, route: Route, ladder: Ladder, project: Rung | None, stepped: bool) -> str:
"""The prompt that resumes the worker with the human's answer to an interrupt. answer is one line, as the terminal reads it."""
return f"{TYPED_HERE}\n{answer}\n\nYour question was: {question}\n\nContinue the task. The chunk is finished only once {ANSWERS_RECORDED}.{stepped_to(route, project, stepped)}"
return f"{TYPED_HERE}\n{answer}\n\nYour question was: {question}\n\nContinue the task. The chunk is finished only once {ANSWERS_RECORDED}.{stepped_to(route, ladder, project, stepped)}"
# Opens typed's prompt, with the answer on the line after it, so typed_answer finds the answer at the prompt's start, whatever the question holds.
@@ -198,9 +198,9 @@ def typed_answer(prompt: str) -> Typed | None:
return Typed(rest, answer)
def stepped_to(route: Route, project: Rung | None, stepped: bool) -> str:
def stepped_to(route: Route, ladder: Ladder, project: Rung | None, stepped: bool) -> str:
"""The sentences naming the worker's new rung, as resumed has them, where the ruling that brought the answer stepped the worker up; empty otherwise."""
return f" Your request for a higher rung went through: loop-claude runs you on {route.rung}. The escalation triggers that fired before this step are spent.{rungs_held(route, project)}" if stepped else ""
return f" Your request for a higher rung went through: loop-claude runs you on {route.rung}. The escalation triggers that fired before this step are spent.{rungs_held(route, ladder, project)}" if stepped else ""
def past_the_cap(question: str, answer: str, cap: int) -> str:
+9 -7
View File
@@ -14,6 +14,7 @@ from failure import Failure
from loop_claude.verdicts import Finished, Interrupt, Judged, QuotedAnswer, Unfinished, Verdict
from loop_claude.cycle.interrupt import interrupt, Talked, WorkerSession
from loop_claude.routing import judge_rung, next_route, step_up, StepUp
from model_routing.ladder import Ladder, Rung
from transcript_archive.read import last_spent
from transcript_archive import outcomes
from plan_store.stores import Plan
@@ -21,7 +22,6 @@ from loop_claude.cycle import prompts
from claude_code.transcript import read_transcript
from loop_claude.cycle.retry import retried
from model_routing.route import Route
from model_routing.ladder import Rung
from loop_claude.cycle import spend
from loop_claude.stop import Stop
from model_routing import worker_rungs
@@ -39,6 +39,8 @@ class Cycle:
# 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
judge_model: str
# The project's routing ladder, as model_routing/ladder_file.py read it when the cycle started.
ladder: Ladder
premises: str
# The project's rung; None for a model off the ladder.
project: Rung | None
@@ -79,7 +81,7 @@ def run_cycle(cycle: Cycle) -> Stop | Concluded:
def ruling_step_up(cycle: Cycle, verdict: Verdict) -> StepUp | None:
"""The step-up an interrupt's or a quoted answer's escalation makes, so the work after the answer runs on the stepped route; None where the route holds. A finished or unfinished verdict steps the route only as the loop starts the next cycle."""
return step_up(cycle.route, next_route(cycle.project, cycle.route, verdict)) if isinstance(verdict, Interrupt | QuotedAnswer) else None
return step_up(cycle.route, next_route(cycle.ladder, cycle.project, cycle.route, verdict)) if isinstance(verdict, Interrupt | QuotedAnswer) else None
def stopped(cycle: Cycle, stop: Stop, why: str) -> Stop:
@@ -100,7 +102,7 @@ def archived(project_archive: pathlib.Path, transcript_path: str, task: str, out
def judge_of(cycle: Cycle) -> Rung:
"""The judge's rung, which the archive names beside each verdict."""
return judge_rung(cycle.judge_model)
return judge_rung(cycle.ladder, cycle.judge_model)
def step(cycle: Cycle, state: Active) -> Event | Stop:
@@ -138,12 +140,12 @@ def worker_session(cycle: Cycle, transcript_path: str) -> WorkerSession:
def worker_start(cycle: Cycle, answered: QuotedAnswer | TypedAnswer | None, stepped: bool) -> list[str]:
if isinstance(answered, QuotedAnswer):
return worker_args(cycle.session, cycle.route.rung, prompts.answered(answered.question, answered.answer, cycle.route, cycle.project, stepped), resume=True)
return worker_args(cycle.session, cycle.route.rung, prompts.answered(answered.question, answered.answer, cycle.route, cycle.ladder, cycle.project, stepped), resume=True)
if isinstance(answered, TypedAnswer):
return worker_args(cycle.session, cycle.route.rung, prompts.typed(answered.question, answered.answer, cycle.route, cycle.project, stepped), resume=True)
return worker_args(cycle.session, cycle.route.rung, prompts.typed(answered.question, answered.answer, cycle.route, cycle.ladder, cycle.project, stepped), resume=True)
if session_open(cycle.session):
return worker_args(cycle.session, cycle.route.rung, prompts.resumed(cycle.unfinished_evidence, cycle.route, cycle.project), resume=True)
return worker_args(cycle.session, cycle.route.rung, prompts.fresh(cycle.task, cycle.premises, cycle.route, cycle.project, cycle.facts), resume=False)
return worker_args(cycle.session, cycle.route.rung, prompts.resumed(cycle.unfinished_evidence, cycle.route, cycle.ladder, cycle.project), resume=True)
return worker_args(cycle.session, cycle.route.rung, prompts.fresh(cycle.task, cycle.premises, cycle.route, cycle.ladder, cycle.project, cycle.facts), resume=False)
def rule(cycle: Cycle, transcript_path: str, quoted_answers: int) -> Ruled | Stop:
+4 -4
View File
@@ -9,12 +9,12 @@ from failure import Failure
from loop_claude.routing import first_route, kept, routed_item
from plan_store.stores import held_at, Plan, store as plan_store
from release_plan.todo_table import Item
from model_routing.ladder import Ladder, Rung
from transcript_archive.read import latest_worker
from project_config.main import located
from loop_claude.loop.this_loop import Loop
from loop_claude.cycle import prompts
from model_routing.route import Route, route_from
from model_routing.ladder import Rung
from claude_code.session import session_open, transcript_file
# Seconds routing waits for origin to name its default branch, asked only where the checkout records none; past them, the chunk runs on the project's rung.
@@ -34,15 +34,15 @@ def fetched_todo(loop: Loop) -> Plan | Failure:
return todo
def routed(route: Route | None, project: Rung | None, model: str, archived: typing.Callable[[], Route | None], item: typing.Callable[[], Item | None]) -> Route:
"""The route the cycle runs on. project is the project's rung, and model the project's model.
def routed(route: Route | None, ladder: Ladder, project: Rung | None, model: str, archived: typing.Callable[[], Route | None], item: typing.Callable[[], Item | None]) -> Route:
"""The route the cycle runs on. project is the project's rung on ladder, and model the project's model.
Where project is None, the model is off the ladder, and the worker runs on it. Otherwise the chunk keeps route, or on a rerun the route its archive last names, as routing.kept allows. Else the plan item routes the chunk afresh.
"""
if project is None:
return Route(Rung(model))
route = route or archived()
return route if route and kept(route, project) else first_route(project, item())
return route if route and kept(route, ladder, project) else first_route(ladder, project, item())
def archived_route(archive_folder: pathlib.Path, loop: Loop) -> Route | None:
+5 -5
View File
@@ -4,20 +4,20 @@ import pathlib
from loop_claude.cycle.run import archived_step, archived_stop, Concluded
from loop_claude.verdicts import Finished
from model_routing.ladder import Ladder, Rung
from loop_claude.loop.this_loop import Loop
from loop_claude.loop.reload import LoopRun
from loop_claude.stop import needs_human, Stop
from loop_claude.routing import next_route, step_up
from model_routing.ladder import Rung
from claude_code.session import transcript_file
# How many unfinished verdicts running end the loop, so a worker and a judge that disagree about a chunk cannot cycle unattended without end. A policy number, not derived from the routing steps: well above the two unfinished verdicts running that archived chunks have reached at most, and low enough that a stuck pair is stopped after six cycles. It counts every unfinished verdict, including those of cycles where the human answered an interrupt: a rerun is cheap, and a chunk that needs that many answers is worth a look. The human confirmed both the number and what it counts.
UNFINISHED_LIMIT = 6
def closed_cycle(loop_run: LoopRun, project: Rung | None, concluded: Concluded, archive_folder: pathlib.Path, loop: Loop) -> LoopRun | Stop:
def closed_cycle(loop_run: LoopRun, ladder: Ladder, project: Rung | None, concluded: Concluded, archive_folder: pathlib.Path, loop: Loop) -> LoopRun | Stop:
"""The loop run after a cycle concluded, with the step-up archived; the stop that needs the human, archived, once the chunk has had UNFINISHED_LIMIT unfinished verdicts running."""
after = after_verdict(loop_run, project, concluded)
after = after_verdict(loop_run, ladder, project, concluded)
# A finished chunk drops its route, so it has no step-up, and its run of unfinished verdicts restarts.
if after.route is None:
return after
@@ -38,10 +38,10 @@ def reached_limit(loop_run: LoopRun) -> Stop | None:
return needs_human("go on with the chunk", f"the judge ruled it unfinished {loop_run.unfinished_run} cycles running; finish the chunk yourself, or rerun loop-claude to give it {UNFINISHED_LIMIT} more cycles")
def after_verdict(loop_run: LoopRun, project: Rung | None, concluded: Concluded) -> LoopRun:
def after_verdict(loop_run: LoopRun, ladder: Ladder, project: Rung | None, concluded: Concluded) -> LoopRun:
"""The loop run the next cycle starts from. A finished chunk drops its route and its run of unfinished verdicts. An unfinished one takes the route 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."""
verdict = concluded.verdict
if isinstance(verdict, Finished):
return dataclasses.replace(loop_run, route=None, unfinished_evidence="", unfinished_run=0)
route = next_route(project, concluded.route, verdict)
route = next_route(ladder, project, concluded.route, verdict)
return dataclasses.replace(loop_run, route=route, unfinished_evidence=verdict.evidence, unfinished_run=loop_run.unfinished_run + 1)
+20 -6
View File
@@ -17,7 +17,7 @@ from loop_claude.loop.usage import HELP
from loop_claude.loop.this_loop import Loop
from loop_state.paths import Paths
from transcript_archive.project_key import project_key
from model_routing.ladder import project_rung
from model_routing.ladder_file import project_ladder_file, read_ladder, SHIPPED
from loop_claude.project.premises import read_premises
from loop_claude.project.records import read_records
from loop_claude.loop.chunk_slot import slotted
@@ -61,7 +61,7 @@ def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launc
concluded = run_cycle(cycle)
if isinstance(concluded, Stop):
return concluded
closed = closed_cycle(loop_run, cycle.project, concluded, cycle.project_archive, loop)
closed = closed_cycle(loop_run, cycle.ladder, cycle.project, concluded, cycle.project_archive, loop)
if isinstance(closed, Stop):
return closed
loop_run = closed
@@ -71,7 +71,7 @@ def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launc
def next_cycle(loop_run: LoopRun, loop: Loop) -> Cycle | Stop:
"""The cycle loop_run runs next, from the premises, the records and the project's models read afresh, and the route the chunk runs on; the stop where one of them cannot be read."""
"""The cycle loop_run runs next, from the premises, the records, the project's models and its routing ladder read afresh, and the route the chunk runs on; the stop where one of them cannot be read."""
premises = read_premises(loop.root, loop.paths.home)
if isinstance(premises, Failure):
return Stop(1, premises.reason)
@@ -81,14 +81,28 @@ def next_cycle(loop_run: LoopRun, loop: Loop) -> Cycle | Stop:
models = get_or_ask_models(project_key(loop.root, loop.paths.home), loop.paths, loop.env, loop.effects)
if isinstance(models, Stop):
return models
ladder_file = project_ladder_file(loop.root, loop.paths.home)
if isinstance(ladder_file, Failure):
return Stop(1, ladder_file.reason)
ladder = read_ladder(ladder_file)
if isinstance(ladder, Failure):
return Stop(1, ladder.reason)
archive_folder = project_archive(loop.root, loop.paths.home, loop.env)
# After the reads above, so a loop that stops on one makes no worktree.
facts, item = chunk_start(loop)
project = project_rung(models.worker)
route = routed(loop_run.route, project, models.worker, lambda: archived_route(archive_folder, loop), item)
project = ladder.project_rung(models.worker)
route = routed(loop_run.route, ladder, project, models.worker, lambda: archived_route(archive_folder, loop), item)
say(f"\n=== cycle {loop_run.cycle_number}, worker on {route.rung} ===", loop.effects, stdout=True)
if ladder_file != SHIPPED:
say(own_ladder(ladder_file, models.worker, project is None), loop.effects)
todo = fetched_todo(loop)
return Cycle(config=setup_version(loop.paths.claude_dir, loop.effects.git), effects=loop.effects, facts=facts, judge_model=models.judge, premises=premises, project=project, project_archive=archive_folder, records=records, root=loop.root, route=route, session=loop.session, task=loop_run.task, todo=todo, unfinished_evidence=loop_run.unfinished_evidence)
return Cycle(config=setup_version(loop.paths.claude_dir, loop.effects.git), effects=loop.effects, facts=facts, judge_model=models.judge, ladder=ladder, premises=premises, project=project, project_archive=archive_folder, records=records, root=loop.root, route=route, session=loop.session, task=loop_run.task, todo=todo, unfinished_evidence=loop_run.unfinished_evidence)
def own_ladder(file: pathlib.Path, model: str, unrouted: bool) -> str:
"""What a cycle says of a project that runs on a ladder of its own, so that a file left in place after its reason passed doesn't go unseen, nor one that leaves out the project's model, whose work the ladder then doesn't route."""
routes = f" {model} is not on it, so the worker runs on {model} unrouted; LOOP_CLAUDE_WORKER_MODEL and LOOP_CLAUDE_JUDGE_MODEL name other models for a run." if unrouted else ""
return f"routing on the project's own ladder, {file}.{routes}"
def loop_run_from(argv: list[str], cwd: pathlib.Path, effects: Effects) -> LoopRun | Stop:
+7 -2
View File
@@ -8,6 +8,7 @@ from loop_effects.effects import Effects, say
from failure import Failure
from loop_claude.loop.this_loop import Loop
from loop_state.paths import Paths
from model_routing.ladder_file import read_ladder, SHIPPED
from routing_figures.render import render
from model_routing.ladder import Rung
from routing_figures import state
@@ -41,9 +42,13 @@ def new_calls(root: pathlib.Path, paths: Paths, effects: Effects) -> list[Call]
measured = archive.measure_archive(root, str(paths.home), raised.since, effects.git)
if isinstance(measured, Failure):
return measured
# The shipped ladder, not the project's: the figures span every project.
ladder = read_ladder(SHIPPED)
if isinstance(ladder, Failure):
return ladder
figures = totals(measured.chunks, measured.skipped, measured.unread)
found = calls(figures)
if unwritten := archive.write_figures(root, render(figures, found, utc(effects.now()), cycle, raised.since)) or state.mark_measured(root, cycle):
found = calls(ladder, figures)
if unwritten := archive.write_figures(root, render(ladder, figures, found, utc(effects.now()), cycle, raised.since)) or state.mark_measured(root, cycle):
return unwritten
return [call for call in found if call not in raised.calls]
+20 -2
View File
@@ -69,8 +69,9 @@ entry, as on its first run, is asked for one on the terminal. LOOP_CLAUDE_JUDGE_
the model for the judge, LOOP_CLAUDE_WORKER_MODEL for the worker and the session /talk opens; with
both set, nothing is asked.
Where the project's model is on the routing ladder (bin/model_routing/ladder.py), the worker and the
session /talk opens run on the rung that the chunk's todo.md item picks, and the judge of some
The routing ladder is a list of rungs, least competent first, each a model at an effort. Where the
project's model is on it, the worker and the session /talk opens run on
the rung that the chunk's todo.md item picks, and the judge of some
models on another; a chunk no item routes runs on the project's model. The worker's prompts name the
rungs it launches its reviews on. The worker's rung steps up as a chunk stays unfinished, when the
worker names on its `Chunk items:` line an item that picks a higher rung, or when the judge finds
@@ -83,6 +84,22 @@ bin/model_routing/route.py); a rerun resumes an open chunk on the latest route n
todo.md or an archive that cannot be read or parsed is said on stderr, and the chunk is routed
without it.
The ladder is a JSON file, each rung a model's full name and an effort of low, medium, high, xhigh
or max:
[
{"model": "claude-opus-5-5", "effort": "medium"},
{"model": "claude-fable-5-2", "effort": "low"}
]
It holds one model of each family, such as opus, since the Agent tool launches a subagent or a
review by its family's name. This setup ships one, bin/model_routing/routing-ladder.json. A project
that keeps a routing-ladder.json in its config's folder, ~/.claude-projects/<key>/, runs on that
ladder instead, whole: write there every rung the project may run on. loop-claude reads the
project's ladder as each cycle starts, says on stderr where the project runs on its own, and never
commits the file. subagent-rung and rule-hook read the same ladder; the routing figures,
judge-replay and review-replay, which span every project, read the shipped one.
Once 20 cycles have closed across all projects in the archive since the last measurement, the next
loop to close one measures every finished chunk there, with no model run, and writes
routing-figures.md at the archive's root (bin/routing_figures/). Each call the figures make for a
@@ -104,6 +121,7 @@ Exit 1, saying why, when:
the project's review standards where they exist, cannot be read or is not UTF-8
- no config names the checkout, its config cannot be read, or the goals file holds no premises
- the models file cannot be read or written
- the project's routing ladder cannot be read or holds a fault
- claude leaves no transcript
- a transcript cannot be read or archived
- a finished chunk's session cannot be deleted
+34 -34
View File
@@ -30,11 +30,11 @@ Each verdict then moves the rung by one rule, and the rung never falls. The rung
import dataclasses
from release_plan.release_standing import chunk_item, LastCut, Next
from model_routing.ladder import climbed, highest, LADDER, position, project_rung, Rung, stepped_up, worker_rung
from loop_claude import escalation_mark
from failure import Failure
from loop_claude.verdicts import Interrupt, QuotedAnswer, Unfinished
from release_plan.todo_table import Item, NoItemsTable
from model_routing.ladder import Ladder, Rung
from plan_store.stores import Plan
from model_routing.route import Route
@@ -56,42 +56,42 @@ def routed_item(plan: Plan | Failure, cut: LastCut) -> Item | Failure | None:
return takes if takes and takes.likelihood and takes.escape_and_impact else None
def first_route(project: Rung, item: Item | None) -> Route:
"""The route a chunk starts on: the rung its item's L picks from the project's rung, or the project's rung without an item."""
def first_route(ladder: Ladder, project: Rung, item: Item | None) -> Route:
"""The route a chunk starts on: the rung its item's L picks on ladder from the project's rung, or the project's rung without an item."""
if item is None:
return Route(project)
return Route(worker_rung(project, item.likelihood), item.id, item.likelihood, item.escape_and_impact)
return Route(ladder.worker_rung(project, item.likelihood), item.id, item.likelihood, item.escape_and_impact)
def kept(route: Route, project: Rung) -> bool:
def kept(route: Route, ladder: Ladder, project: Rung) -> bool:
"""Whether a chunk keeps route: its rung is on the ladder and at or above item_rung."""
return floor_rung(project, route) == route.rung
return floor_rung(ladder, project, route) == route.rung
def item_rung(project: Rung, route: Route) -> Rung:
def item_rung(ladder: Ladder, project: Rung, route: Route) -> Rung:
"""The rung the route's item's L picks from the project's rung, or the project's rung itself when no item routed it. The worker may run on a rung below the project's."""
return worker_rung(project, route.likelihood) if route.item else project
return ladder.worker_rung(project, route.likelihood) if route.item else project
def floor_rung(project: Rung, route: Route, likelihood_taken_in: int = 0) -> Rung:
def floor_rung(ladder: Ladder, project: Rung, route: Route, likelihood_taken_in: int = 0) -> Rung:
"""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."""
floor = highest(route.rung, item_rung(project, route))
return highest(floor, worker_rung(project, likelihood_taken_in)) if likelihood_taken_in else floor
floor = ladder.highest(route.rung, item_rung(ladder, project, route))
return ladder.highest(floor, ladder.worker_rung(project, likelihood_taken_in)) if likelihood_taken_in else floor
def escalation_rungs(project: Rung, route: Route) -> tuple[Rung, ...]:
def escalation_rungs(ladder: Ladder, project: Rung, route: Route) -> tuple[Rung, ...]:
"""The rungs an escalation trigger opens to the worker, least competent first: from one above its own up to escalation_cap; none off the ladder."""
if route.rung not in LADDER:
if route.rung not in ladder.rungs:
return ()
return LADDER[position(route.rung) + 1:position(escalation_cap(project, route)) + 1]
return ladder.rungs[ladder.position(route.rung) + 1:ladder.position(escalation_cap(ladder, project, route)) + 1]
def escalation_cap(project: Rung, route: Route) -> Rung:
def escalation_cap(ladder: Ladder, project: Rung, route: Route) -> Rung:
"""The highest rung an escalation trigger takes the worker or a task to without the human's yes: docs/decisions.md → `routing: a worker hands a task one rung up`.
It counts from item_rung, the rung the chunk started on, so a step-up between cycles narrows what the worker may climb without a yes, and never widens it.
"""
return climbed(item_rung(project, route), ESCALATION_CAP)
return ladder.climbed(item_rung(ladder, project, route), ESCALATION_CAP)
@dataclasses.dataclass(frozen=True)
@@ -101,31 +101,31 @@ class StepUp:
after: Route
def next_route(project: Rung | None, route: Route, verdict: Unfinished | Interrupt | QuotedAnswer) -> Route:
def next_route(ladder: Ladder, project: Rung | None, route: Route, verdict: Unfinished | Interrupt | QuotedAnswer) -> Route:
"""The route the worker runs on after the judge's verdict. Off the ladder, project is None, and the route holds. The rung never falls."""
if project is None:
return route
if isinstance(verdict, Unfinished):
return unfinished_route(project, route, verdict)
return escalated_route(project, route, verdict)
return unfinished_route(ladder, project, route, verdict)
return escalated_route(ladder, project, route, verdict)
def unfinished_route(project: Rung, route: Route, verdict: Unfinished) -> Route:
def unfinished_route(ladder: Ladder, project: Rung, route: Route, verdict: Unfinished) -> Route:
"""The route after an unfinished verdict. The rung rises to floor_rung, which the verdict'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, and the mark moves only where the verdict escalates. Last, the route takes in the verdict's highest E + I, as Route.taking_in does.
"""
mark = escalation_mark.moved_to(verdict)
floor = floor_rung(project, route, verdict.taken_in.highest_likelihood)
floor = floor_rung(ladder, project, route, verdict.taken_in.highest_likelihood)
counted = route.unfinished + 1
if steps(counted, mark is not None and below_cap(project, route, floor)):
after = one_rung_up(route, floor, route.escalated_at if mark is None else mark)
if steps(counted, mark is not None and below_cap(ladder, project, route, floor)):
after = one_rung_up(ladder, route, floor, route.escalated_at if mark is None else mark)
else:
after = dataclasses.replace(route, rung=floor, unfinished=counted)
return after.taking_in(verdict.taken_in.highest_escape_and_impact)
def escalated_route(project: Rung, route: Route, verdict: Interrupt | QuotedAnswer) -> Route:
def escalated_route(ladder: Ladder, project: Rung, route: Route, verdict: Interrupt | QuotedAnswer) -> Route:
"""The route after an interrupt or a quoted answer. Without an escalation it holds, since neither is an unfinished verdict.
With one, the rung rises to floor_rung, which the verdict'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 loop_claude/escalation_mark.py says; at the cap the rung stays on floor_rung and the mark holds.
@@ -133,8 +133,8 @@ def escalated_route(project: Rung, route: Route, verdict: Interrupt | QuotedAnsw
mark = escalation_mark.moved_to(verdict)
if mark is None:
return route
floor = floor_rung(project, route, verdict.taken_in.highest_likelihood)
return one_rung_up(route, floor, mark) if below_cap(project, route, floor) else dataclasses.replace(route, rung=floor)
floor = floor_rung(ladder, project, route, verdict.taken_in.highest_likelihood)
return one_rung_up(ladder, route, floor, mark) if below_cap(ladder, project, route, floor) else dataclasses.replace(route, rung=floor)
def steps(counted: int, escalates: bool) -> bool:
@@ -142,9 +142,9 @@ def steps(counted: int, escalates: bool) -> bool:
return counted >= UNFINISHED_PER_STEP or escalates
def below_cap(project: Rung, route: Route, floor: Rung) -> bool:
def below_cap(ladder: Ladder, project: Rung, route: Route, floor: Rung) -> bool:
"""Whether an escalation from floor may step the rung: floor lies below escalation_cap."""
return position(floor) < position(escalation_cap(project, route))
return ladder.position(floor) < ladder.position(escalation_cap(ladder, project, route))
def step_up(before: Route, after: Route) -> StepUp | None:
@@ -152,13 +152,13 @@ def step_up(before: Route, after: Route) -> StepUp | None:
return StepUp(before, after) if after.worker_line() != before.worker_line() else None
def one_rung_up(route: Route, rung: Rung, escalated_at: int) -> Route:
def one_rung_up(ladder: Ladder, route: Route, rung: Rung, escalated_at: int) -> Route:
"""The route one rung above rung, with the count of unfinished verdicts restarted and the mark at escalated_at."""
return dataclasses.replace(route, rung=stepped_up(rung), unfinished=0, escalated_at=escalated_at)
return dataclasses.replace(route, rung=ladder.stepped_up(rung), unfinished=0, escalated_at=escalated_at)
def judge_rung(judge_model: str) -> Rung:
"""The highest of the judge model's own rungs: 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."""
if project_rung(judge_model) is None or judge_model not in JUDGE_REPLAYED:
def judge_rung(ladder: Ladder, judge_model: str) -> Rung:
"""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."""
if ladder.project_rung(judge_model) is None or judge_model not in JUDGE_REPLAYED:
return Rung(judge_model)
return highest(*(rung for rung in LADDER if rung.model == judge_model))
return ladder.highest(*(rung for rung in ladder.rungs if rung.model == judge_model))
+32
View File
@@ -468,6 +468,38 @@ class Cycles(unittest.TestCase):
self.assertIn('<UTC> Verdict: unfinished\n\nEvidence:\n> three\n\nConfig: <config>\nJudge: judge-model\nWorker: {"model": "claude-opus-5-5", "effort": "medium", "item": 4, "likelihood": 2, "escape_and_impact": 3}\n\n<UTC> Stepped up\n\nWorker: {"model": "claude-fable-5-2", "effort": "low", "item": 4, "likelihood": 2, "escape_and_impact": 3}\n', outcomes)
self.assertIn('<UTC> Verdict: finished\n\nEvidence:\n> four\n\nConfig: <config>\nJudge: judge-model\nWorker: {"model": "claude-fable-5-2", "effort": "low", "item": 4, "likelihood": 2, "escape_and_impact": 3}\n', outcomes)
def test_routes_on_the_ladder_the_projects_config_folder_holds_in_place_of_the_shipped_one(self):
checkout = Checkout(self)
checkout.env["LOOP_CLAUDE_WORKER_MODEL"] = "claude-fable-5-2"
ladder = checkout.home / ".claude-projects" / "proj" / "routing-ladder.json"
ladder.write_text('[{"model": "claude-fable-5-2", "effort": "low"}, {"model": "claude-fable-5-2", "effort": "max"}]')
checkout.commit_plan(CHEAP)
run = checkout.run([worker(), judge(), worker(), judge(), worker()])
self.assertEqual(run.code, 130)
# Item 4's L of 2 steps one rung down, to Opus 5.5 on the shipped ladder; the project's ladder holds no rung below the project's rung, and one above it, which the second unfinished verdict steps to.
self.assertEqual([(argument(call, "--model"), argument(call, "--effort")) for call in run.calls if call["role"] == "worker"], [("claude-fable-5-2", "low"), ("claude-fable-5-2", "low"), ("claude-fable-5-2", "max")])
self.assertEqual(run.stderr.count(f"routing on the project's own ladder, {ladder}.\n"), 3, "each cycle says so")
def test_says_where_the_projects_own_ladder_leaves_out_the_workers_model_and_says_nothing_on_the_shipped_one(self):
checkout = Checkout(self)
self.assertNotIn("own ladder", checkout.run([worker()]).stderr)
ladder = checkout.home / ".claude-projects" / "proj" / "routing-ladder.json"
ladder.write_text('[{"model": "claude-fable-5-2", "effort": "low"}]')
run = checkout.run([worker()])
self.assertIn(f"routing on the project's own ladder, {ladder}. worker-model is not on it, so the worker runs on worker-model unrouted; LOOP_CLAUDE_WORKER_MODEL and LOOP_CLAUDE_JUDGE_MODEL name other models for a run.\n", run.stderr)
self.assertEqual((argument(run.calls[0], "--model"), argument(run.calls[0], "--effort")), ("worker-model", None))
def test_reads_the_projects_ladder_afresh_each_cycle_and_exits_1_once_it_holds_a_fault(self):
checkout = Checkout(self)
checkout.env["LOOP_CLAUDE_WORKER_MODEL"] = "claude-fable-5-2"
ladder = checkout.home / ".claude-projects" / "proj" / "routing-ladder.json"
ladder.write_text('[{"model": "claude-fable-5-2", "effort": "high"}]')
checkout.env["FAKE_CLAUDE_EDIT"] = str(ladder.parent)
run = checkout.run([worker(replace=["routing-ladder.json", '"high"}', '"high"},']), judge()])
self.assertEqual((run.code, run.roles()), (1, ["worker", "judge"]))
self.assertEqual((argument(run.calls[0], "--model"), argument(run.calls[0], "--effort")), ("claude-fable-5-2", "high"))
self.assertIn(f"cannot read the routing ladder {ladder}: ", run.stderr)
def test_routes_on_and_states_the_same_item_from_the_fetched_default_branch_whatever_the_checkout_holds(self):
checkout = Checkout(self)
checkout.env["LOOP_CLAUDE_WORKER_MODEL"] = "claude-opus-5-5"
+127 -112
View File
@@ -30,7 +30,6 @@ from failure import Failure
from loop_claude.verdicts import Finished, Interrupt, Judged, QuotedAnswer, TakenIn, Unfinished
from git_cli.git_repo import git
from loop_claude.cycle import interrupt, judge, prompts, retry, run, spend, states, worker
from model_routing.ladder import LADDER, Rung
from claude_code.reply import Limited
from loop_claude.loop import main, reload, routing_check, this_loop, usage
from machine_load import memory
@@ -38,14 +37,17 @@ from transcript_archive import outcomes, write
from loop_state import paths
from plan_store.stores import plan_of
from transcript_archive.location import project_archive
from model_routing.ladder_file import read_ladder, SHIPPED
from model_routing.route import Route, route_from, WorkerLine
from loop_claude import routing
from model_routing.ladder import Rung
from loop_claude.stop import Stop
from claude_code.tokens import Tokens, tokens_of
from text_files.utc_stamp import utc
from loop_claude.cycle.judge import verdict_from
# How the archive records a worker that runs off the ladder.
LADDER = read_ladder(SHIPPED)
OFF_LADDER = '{"model": "worker-model"}'
# The claude-config release and commit each cycle the tests run is under.
CONFIG = "v0.8.0 (abc123)"
@@ -263,7 +265,7 @@ class Cycles(unittest.TestCase):
self.archive = project_archive(str(self.home / "code" / "proj"), self.home, {})
def cycle(self, fake, records="", unfinished_evidence="", facts="- A preflight fact."):
return run.Cycle(config=CONFIG, effects=fake.effects(), facts=facts, judge_model="judge-model", premises="## Goals", project=None, project_archive=self.archive, records=records, root=str(self.home), route=Route(Rung("worker-model")), session=self.session, task="Do it.", todo=plan_of(""), unfinished_evidence=unfinished_evidence)
return run.Cycle(config=CONFIG, effects=fake.effects(), facts=facts, judge_model="judge-model", ladder=LADDER, premises="## Goals", project=None, project_archive=self.archive, records=records, root=str(self.home), route=Route(Rung("worker-model")), session=self.session, task="Do it.", todo=plan_of(""), unfinished_evidence=unfinished_evidence)
def archived_outcomes(self):
return sorted(path.read_text() for path in self.archive.glob("*/*.outcomes.md"))
@@ -506,7 +508,7 @@ Spent since 2026-09-21T14:13:20Z, in tokens of input, cache write 5m, cache writ
self.assertEqual(concluded.route, Route(Routing.OPUS, 179, 2, 5, escalated_at=3))
first, resumed = fake.made("stream_claude")
self.assertEqual([args[args.index("--effort") + 1] for args in (first, resumed)], ["high", "medium"])
self.assertTrue(resumed[resumed.index("-p") + 1].endswith(f"Continue the task. Your request for a higher rung went through: loop-claude runs you on {Routing.OPUS}. The escalation triggers that fired before this step are spent.{prompts.rungs_held(concluded.route, Routing.OPUS)}"))
self.assertTrue(resumed[resumed.index("-p") + 1].endswith(f"Continue the task. Your request for a higher rung went through: loop-claude runs you on {Routing.OPUS}. The escalation triggers that fired before this step are spent.{prompts.rungs_held(concluded.route, LADDER, Routing.OPUS)}"))
self.assertNotIn("went through", first[first.index("-p") + 1])
answered = f"Verdict: quoted answer\n\nWhich one?\n\n{prompts.QUOTE_SOURCES} says:\n> Use A.\n\nEvidence:\n> working\n\nEscalation:\n> working\n\nConfig: {CONFIG}\nJudge: judge-model\nWorker: {SONNET_179}\n"
stepped = f"Stepped up\n\nWorker: {OPUS_179_AT_3}\n"
@@ -982,7 +984,9 @@ class Routing(unittest.TestCase):
def test_routes_on_no_item_where_the_release_after_the_last_cut_has_none(self):
self.assertEqual(routed_item(TODO, LastCut("v0.1.0", "", 3, [TODO])).id, 3)
self.assertIsNone(routed_item(TODO, LastCut("v0.2.0", "", 3, [TODO])))
# Someone cut 0.2.0 while it held items: they count as 0.3.0's, the next release, and where no later release is known, no item routes.
self.assertEqual(routed_item(TODO, LastCut("v0.2.0", "", 3, [TODO])).id, 3)
self.assertIsNone(routed_item(re.sub(r"(?m)^\| \d+ \| 0\.3\.0 \|.*\n", "", TODO), LastCut("v0.2.0", "", 3, [])))
later_only = TODO[:TODO.index("| 7 |")] + TODO[TODO.index("| 1 | 0.3.0 |"):]
self.assertIsNone(routed_item(later_only, LastCut("v0.1.0", "", 3, [TODO])))
self.assertIsNone(routed_item(later_only, LastCut("v0.1.0", "", 0, [TODO])))
@@ -996,53 +1000,53 @@ class Routing(unittest.TestCase):
self.assertEqual(routed_item(todo.replace(first, "") + first, NO_CUT).id, 3)
def test_starts_a_chunk_on_the_rung_its_items_l_picks_below_the_projects_too(self):
self.assertEqual(routing.first_route(self.OPUS, routed_item(TODO, NO_CUT)), Route(self.ONE_UP, 3, 4, 5))
self.assertEqual(routing.first_route(LADDER, self.OPUS, routed_item(TODO, NO_CUT)), Route(self.ONE_UP, 3, 4, 5))
cheap = routed_item(TODO.replace("| 4 | 2 | 3 |", "| 1 | 2 | 3 |"), NO_CUT)
self.assertEqual(routing.first_route(self.OPUS, cheap), Route(Rung("claude-sonnet-5-5", "high"), 3, 1, 5))
self.assertEqual(routing.first_route(self.OPUS, None), Route(self.OPUS))
self.assertEqual(routing.first_route(LADDER, self.OPUS, cheap), Route(Rung("claude-sonnet-5-5", "high"), 3, 1, 5))
self.assertEqual(routing.first_route(LADDER, self.OPUS, None), Route(self.OPUS))
def test_steps_up_a_rung_after_every_second_unfinished_verdict(self):
once = routing.next_route(self.OPUS, Route(self.OPUS, 3, 3, 4), unfinished())
once = routing.next_route(LADDER, self.OPUS, Route(self.OPUS, 3, 3, 4), unfinished())
self.assertEqual(once, Route(self.OPUS, 3, 3, 4, unfinished=1))
self.assertEqual(routing.next_route(self.OPUS, once, unfinished()), Route(self.ONE_UP, 3, 3, 4))
self.assertEqual(routing.next_route(self.OPUS, Route(LADDER[-1], unfinished=1), unfinished()).rung, LADDER[-1])
self.assertEqual(routing.next_route(LADDER, self.OPUS, once, unfinished()), Route(self.ONE_UP, 3, 3, 4))
self.assertEqual(routing.next_route(LADDER, self.OPUS, Route(LADDER.rungs[-1], unfinished=1), unfinished()).rung, LADDER.rungs[-1])
def test_steps_up_to_the_rung_a_taken_in_items_l_picks_and_never_down(self):
self.assertEqual(routing.next_route(self.OPUS, Route(self.OPUS), unfinished(4)).rung, self.ONE_UP)
self.assertEqual(routing.next_route(self.OPUS, Route(self.TWO_UP), unfinished(4)).rung, self.TWO_UP)
self.assertEqual(routing.next_route(self.OPUS, Route(self.OPUS, unfinished=1), unfinished(4)).rung, self.TWO_UP)
self.assertEqual(routing.next_route(LADDER, self.OPUS, Route(self.OPUS), unfinished(4)).rung, self.ONE_UP)
self.assertEqual(routing.next_route(LADDER, self.OPUS, Route(self.TWO_UP), unfinished(4)).rung, self.TWO_UP)
self.assertEqual(routing.next_route(LADDER, self.OPUS, Route(self.OPUS, unfinished=1), unfinished(4)).rung, self.TWO_UP)
def test_steps_up_from_a_rung_below_the_projects_one_rung_at_a_time(self):
low = Route(self.SONNET, 3, 1, 3, unfinished=1)
self.assertEqual(routing.next_route(self.OPUS, low, unfinished()).rung, self.OPUS)
self.assertEqual(routing.next_route(self.OPUS, Route(low.rung, 3, 1, 3), unfinished()).rung, low.rung)
self.assertEqual(routing.next_route(self.OPUS, Route(low.rung, 3, 1, 3), unfinished(3)).rung, self.OPUS)
self.assertEqual(routing.next_route(LADDER, self.OPUS, low, unfinished()).rung, self.OPUS)
self.assertEqual(routing.next_route(LADDER, self.OPUS, Route(low.rung, 3, 1, 3), unfinished()).rung, low.rung)
self.assertEqual(routing.next_route(LADDER, self.OPUS, Route(low.rung, 3, 1, 3), unfinished(3)).rung, self.OPUS)
def test_steps_up_a_rung_on_an_escalation_the_judge_found_up_to_two_above_the_items_rung_marking_the_transcript_entries_it_read(self):
self.assertEqual(routing.next_route(self.OPUS, Route(self.ONE_UP, 3, 4, 5), unfinished(escalated_at=7)), Route(self.TWO_UP, 3, 4, 5, escalated_at=7))
self.assertEqual(routing.next_route(self.OPUS, Route(self.TWO_UP, 3, 4, 5, escalated_at=7), unfinished(escalated_at=9)), Route(self.THREE_UP, 3, 4, 5, escalated_at=9))
self.assertEqual(routing.next_route(self.OPUS, Route(self.THREE_UP, 3, 4, 5, escalated_at=9), unfinished(escalated_at=12)), Route(self.THREE_UP, 3, 4, 5, unfinished=1, escalated_at=9))
self.assertEqual(routing.next_route(self.OPUS, Route(self.ONE_UP, 3, 4, 5, unfinished=1), unfinished(escalated_at=7)), Route(self.TWO_UP, 3, 4, 5, escalated_at=7))
self.assertEqual(routing.next_route(self.OPUS, Route(self.TWO_UP), unfinished(escalated_at=7)), Route(self.TWO_UP, unfinished=1))
self.assertEqual(routing.next_route(self.OPUS, Route(self.SONNET, 3, 2, 4), unfinished(4, escalated_at=7)), Route(self.ONE_UP, 3, 2, 4, unfinished=1))
self.assertEqual(routing.next_route(LADDER, self.OPUS, Route(self.ONE_UP, 3, 4, 5), unfinished(escalated_at=7)), Route(self.TWO_UP, 3, 4, 5, escalated_at=7))
self.assertEqual(routing.next_route(LADDER, self.OPUS, Route(self.TWO_UP, 3, 4, 5, escalated_at=7), unfinished(escalated_at=9)), Route(self.THREE_UP, 3, 4, 5, escalated_at=9))
self.assertEqual(routing.next_route(LADDER, self.OPUS, Route(self.THREE_UP, 3, 4, 5, escalated_at=9), unfinished(escalated_at=12)), Route(self.THREE_UP, 3, 4, 5, unfinished=1, escalated_at=9))
self.assertEqual(routing.next_route(LADDER, self.OPUS, Route(self.ONE_UP, 3, 4, 5, unfinished=1), unfinished(escalated_at=7)), Route(self.TWO_UP, 3, 4, 5, escalated_at=7))
self.assertEqual(routing.next_route(LADDER, self.OPUS, Route(self.TWO_UP), unfinished(escalated_at=7)), Route(self.TWO_UP, unfinished=1))
self.assertEqual(routing.next_route(LADDER, self.OPUS, Route(self.SONNET, 3, 2, 4), unfinished(4, escalated_at=7)), Route(self.ONE_UP, 3, 2, 4, unfinished=1))
def test_keeps_the_mark_through_a_step_no_escalation_took(self):
self.assertEqual(routing.next_route(self.OPUS, Route(self.OPUS, 3, 3, 4, unfinished=1, escalated_at=5), unfinished()), Route(self.ONE_UP, 3, 3, 4, escalated_at=5))
self.assertEqual(routing.next_route(LADDER, self.OPUS, Route(self.OPUS, 3, 3, 4, unfinished=1, escalated_at=5), unfinished()), Route(self.ONE_UP, 3, 3, 4, escalated_at=5))
def test_steps_up_a_rung_as_the_judge_interrupts_up_to_two_above_the_items_rung_without_counting_an_unfinished_verdict(self):
self.assertEqual(routing.next_route(self.OPUS, Route(self.ONE_UP, 3, 4, 5, unfinished=1), interrupted(escalated_at=7)), Route(self.TWO_UP, 3, 4, 5, escalated_at=7))
self.assertEqual(routing.next_route(self.OPUS, Route(self.TWO_UP, 3, 4, 5, escalated_at=7), interrupted(escalated_at=9)), Route(self.THREE_UP, 3, 4, 5, escalated_at=9))
self.assertEqual(routing.next_route(self.OPUS, Route(self.THREE_UP, 3, 4, 5, unfinished=1, escalated_at=9), interrupted(escalated_at=12)), Route(self.THREE_UP, 3, 4, 5, unfinished=1, escalated_at=9))
self.assertEqual(routing.next_route(self.OPUS, Route(self.SONNET, 3, 2, 4), interrupted(escalated_at=7)), Route(self.OPUS, 3, 2, 4, escalated_at=7))
self.assertEqual(routing.next_route(self.OPUS, Route(self.ONE_UP, 3, 4, 5, unfinished=1, escalated_at=2), interrupted(4)), Route(self.ONE_UP, 3, 4, 5, unfinished=1, escalated_at=2))
self.assertEqual(routing.next_route(LADDER, self.OPUS, Route(self.ONE_UP, 3, 4, 5, unfinished=1), interrupted(escalated_at=7)), Route(self.TWO_UP, 3, 4, 5, escalated_at=7))
self.assertEqual(routing.next_route(LADDER, self.OPUS, Route(self.TWO_UP, 3, 4, 5, escalated_at=7), interrupted(escalated_at=9)), Route(self.THREE_UP, 3, 4, 5, escalated_at=9))
self.assertEqual(routing.next_route(LADDER, self.OPUS, Route(self.THREE_UP, 3, 4, 5, unfinished=1, escalated_at=9), interrupted(escalated_at=12)), Route(self.THREE_UP, 3, 4, 5, unfinished=1, escalated_at=9))
self.assertEqual(routing.next_route(LADDER, self.OPUS, Route(self.SONNET, 3, 2, 4), interrupted(escalated_at=7)), Route(self.OPUS, 3, 2, 4, escalated_at=7))
self.assertEqual(routing.next_route(LADDER, self.OPUS, Route(self.ONE_UP, 3, 4, 5, unfinished=1, escalated_at=2), interrupted(4)), Route(self.ONE_UP, 3, 4, 5, unfinished=1, escalated_at=2))
def test_raises_the_worker_to_a_taken_in_items_rung_above_the_escalation_cap_without_a_step_as_the_judge_interrupts(self):
self.assertEqual(routing.next_route(self.OPUS, Route(self.OPUS, 3, 1, 3, escalated_at=2), interrupted(4, escalated_at=7)), Route(self.ONE_UP, 3, 1, 3, escalated_at=2))
self.assertEqual(routing.next_route(LADDER, self.OPUS, Route(self.OPUS, 3, 1, 3, escalated_at=2), interrupted(4, escalated_at=7)), Route(self.ONE_UP, 3, 1, 3, escalated_at=2))
def test_steps_up_from_the_rung_a_taken_in_item_picks_as_the_judge_interrupts(self):
self.assertEqual(routing.next_route(self.OPUS, Route(self.OPUS, 3, 3, 4), interrupted(4, escalated_at=7)), Route(self.TWO_UP, 3, 3, 4, escalated_at=7))
self.assertEqual(routing.next_route(self.OPUS, Route(self.TWO_UP, 3, 4, 5), interrupted(4, escalated_at=7)), Route(self.THREE_UP, 3, 4, 5, escalated_at=7))
self.assertEqual(routing.next_route(self.OPUS, Route(self.THREE_UP, 3, 4, 5, unfinished=1), interrupted(4, escalated_at=7)), Route(self.THREE_UP, 3, 4, 5, unfinished=1))
self.assertEqual(routing.next_route(LADDER, self.OPUS, Route(self.OPUS, 3, 3, 4), interrupted(4, escalated_at=7)), Route(self.TWO_UP, 3, 3, 4, escalated_at=7))
self.assertEqual(routing.next_route(LADDER, self.OPUS, Route(self.TWO_UP, 3, 4, 5), interrupted(4, escalated_at=7)), Route(self.THREE_UP, 3, 4, 5, escalated_at=7))
self.assertEqual(routing.next_route(LADDER, self.OPUS, Route(self.THREE_UP, 3, 4, 5, unfinished=1), interrupted(4, escalated_at=7)), Route(self.THREE_UP, 3, 4, 5, unfinished=1))
def test_keeps_an_e_plus_i_taken_in_only_where_it_picks_a_higher_review_rung(self):
taken = Route(self.OPUS, 3, 3, 4).taking_in(6)
@@ -1057,14 +1061,14 @@ class Routing(unittest.TestCase):
self.assertEqual(Route(self.OPUS).taking_in(0), Route(self.OPUS))
def test_a_rung_an_edit_took_off_the_ladder_counts_as_the_projects(self):
self.assertEqual(routing.next_route(self.OPUS, Route(Rung("claude-opus-5-5", "low")), unfinished()).rung, self.OPUS)
self.assertEqual(routing.next_route(self.OPUS, Route(Rung("claude-opus-5-5", "low")), unfinished(2)).rung, self.OPUS)
self.assertEqual(routing.next_route(LADDER, self.OPUS, Route(Rung("claude-opus-5-5", "low")), unfinished()).rung, self.OPUS)
self.assertEqual(routing.next_route(LADDER, self.OPUS, Route(Rung("claude-opus-5-5", "low")), unfinished(2)).rung, self.OPUS)
def test_runs_the_judge_of_a_replayed_model_on_its_models_highest_rung(self):
self.assertEqual(routing.judge_rung("claude-opus-5-5"), self.THREE_UP)
self.assertEqual(routing.judge_rung(LADDER, "claude-opus-5-5"), self.THREE_UP)
# A model off the ladder, or not replayed, gets no effort flag.
self.assertEqual(routing.judge_rung("judge-model"), Rung("judge-model"))
self.assertEqual(routing.judge_rung("claude-sonnet-5-5"), Rung("claude-sonnet-5-5"))
self.assertEqual(routing.judge_rung(LADDER, "judge-model"), Rung("judge-model"))
self.assertEqual(routing.judge_rung(LADDER, "claude-sonnet-5-5"), Rung("claude-sonnet-5-5"))
def test_refuses_a_route_whose_item_has_levels_off_their_scales_or_levels_without_an_item(self):
for item, likelihood, escape_and_impact in ((3, 0, 5), (3, 5, 5), (3, 4, 1), (3, 4, 9), (0, 4, 5), (0, 4, 0), (0, 0, 5)):
@@ -1109,21 +1113,21 @@ class Routing(unittest.TestCase):
archived = Route(self.TWO_UP, 3, 4, 5)
def never():
raise AssertionError("not asked")
self.assertEqual(chunk_start.routed(archived, None, "worker-model", never, never), Route(Rung("worker-model")))
self.assertEqual(chunk_start.routed(archived, self.OPUS, "claude-opus-5-5", never, never), archived)
self.assertEqual(chunk_start.routed(None, self.OPUS, "claude-opus-5-5", lambda: archived, never), archived)
self.assertEqual(chunk_start.routed(None, self.OPUS, "claude-opus-5-5", lambda: None, lambda: item), Route(self.ONE_UP, 3, 4, 5))
self.assertEqual(chunk_start.routed(Route(self.SONNET), self.OPUS, "claude-opus-5-5", never, lambda: None), Route(self.OPUS))
self.assertEqual(chunk_start.routed(archived, LADDER, None, "worker-model", never, never), Route(Rung("worker-model")))
self.assertEqual(chunk_start.routed(archived, LADDER, self.OPUS, "claude-opus-5-5", never, never), archived)
self.assertEqual(chunk_start.routed(None, LADDER, self.OPUS, "claude-opus-5-5", lambda: archived, never), archived)
self.assertEqual(chunk_start.routed(None, LADDER, self.OPUS, "claude-opus-5-5", lambda: None, lambda: item), Route(self.ONE_UP, 3, 4, 5))
self.assertEqual(chunk_start.routed(Route(self.SONNET), LADDER, self.OPUS, "claude-opus-5-5", never, lambda: None), Route(self.OPUS))
cheap = Route(self.SONNET, 4, 2, 3)
self.assertEqual(chunk_start.routed(cheap, self.OPUS, "claude-opus-5-5", never, never), cheap)
self.assertEqual(chunk_start.routed(Route(Rung("claude-haiku-5-5", "max"), 4, 2, 3), self.OPUS, "claude-opus-5-5", never, lambda: None), Route(self.OPUS))
self.assertEqual(chunk_start.routed(cheap, LADDER, self.OPUS, "claude-opus-5-5", never, never), cheap)
self.assertEqual(chunk_start.routed(Route(Rung("claude-haiku-5-5", "max"), 4, 2, 3), LADDER, self.OPUS, "claude-opus-5-5", never, lambda: None), Route(self.OPUS))
class RouteSources(unittest.TestCase):
def test_routes_on_the_plan_item_and_says_why_it_routes_on_the_projects_rung(self):
self.assertIsNone(chunk_start.plan_item(DefaultPlan(plan_of(""), NO_CUT), FakeEffects().effects()))
self.assertEqual(chunk_start.plan_item(DefaultPlan(plan_of(TODO), LastCut("v0.1.0", "", 3, [TODO])), FakeEffects().effects()).id, 3)
self.assertIsNone(chunk_start.plan_item(DefaultPlan(plan_of(TODO), LastCut("v0.2.0", "", 3, [TODO])), FakeEffects().effects()))
self.assertIsNone(chunk_start.plan_item(DefaultPlan(plan_of(TODO), LastCut("v0.3.0", "", 3, [TODO])), FakeEffects().effects()))
unreadable = Failure("git show origin/main:todo.md printed text that is not UTF-8")
for plan, said in ((DefaultPlan(plan_of(TODO.replace("| 4 | 2 | 3 |", "| x | 2 | 3 |")), NO_CUT), "routing on the project's rung: item 3's L 'x' is not a whole number from 1 to 4\n"), (DefaultPlan(unreadable, NO_CUT), f"routing on the project's rung: {unreadable.reason}\n"), (Failure("no origin remote"), "routing on the project's rung: no origin remote\n")):
with self.subTest(said=said):
@@ -1268,24 +1272,24 @@ class Steps(unittest.TestCase):
def test_a_finished_verdict_clears_the_route_and_the_evidence(self):
run_with = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="old", route=Route(self.OPUS))
self.assertEqual(close.after_verdict(run_with, self.OPUS, run.Concluded(Finished("x"), run_with.route)), dataclasses.replace(run_with, route=None, unfinished_evidence=""))
self.assertEqual(close.after_verdict(dataclasses.replace(run_with, unfinished_run=3), self.OPUS, run.Concluded(Finished("x"), run_with.route)).unfinished_run, 0)
self.assertEqual(close.after_verdict(run_with, self.OPUS, run.Concluded(Unfinished("new", taken_in=TakenIn(highest_likelihood=4)), run_with.route)), dataclasses.replace(run_with, route=Route(Rung("claude-fable-5-2", "low"), unfinished=1), unfinished_evidence="new", unfinished_run=1))
self.assertEqual(close.after_verdict(run_with, LADDER, self.OPUS, run.Concluded(Finished("x"), run_with.route)), dataclasses.replace(run_with, route=None, unfinished_evidence=""))
self.assertEqual(close.after_verdict(dataclasses.replace(run_with, unfinished_run=3), LADDER, self.OPUS, run.Concluded(Finished("x"), run_with.route)).unfinished_run, 0)
self.assertEqual(close.after_verdict(run_with, LADDER, self.OPUS, run.Concluded(Unfinished("new", taken_in=TakenIn(highest_likelihood=4)), run_with.route)), dataclasses.replace(run_with, route=Route(Rung("claude-fable-5-2", "low"), unfinished=1), unfinished_evidence="new", unfinished_run=1))
def test_steps_from_the_route_its_cycle_ended_on_which_a_ruling_may_have_raised(self):
run_with = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="", route=Route(self.OPUS, 3, 3, 4))
raised = Route(Rung("claude-fable-5-2", "low"), 3, 3, 4, escalated_at=5)
self.assertEqual(close.after_verdict(run_with, self.OPUS, run.Concluded(Unfinished("new"), raised)).route, dataclasses.replace(raised, unfinished=1))
self.assertEqual(close.after_verdict(run_with, LADDER, self.OPUS, run.Concluded(Unfinished("new"), raised)).route, dataclasses.replace(raised, unfinished=1))
def test_keeps_the_route_its_cycle_ended_on_off_the_ladder(self):
off_ladder = Route(Rung("worker-model"))
run_with = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="")
self.assertEqual(close.after_verdict(run_with, None, run.Concluded(Unfinished("new", "round 2: 🔴", TakenIn(highest_likelihood=4), entries_read=9), off_ladder)).route, off_ladder)
self.assertEqual(close.after_verdict(run_with, LADDER, None, run.Concluded(Unfinished("new", "round 2: 🔴", TakenIn(highest_likelihood=4), entries_read=9), off_ladder)).route, off_ladder)
def test_an_unfinished_verdicts_escalation_marks_the_transcript_entries_the_judge_read(self):
run_with = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="", route=Route(self.OPUS, 3, 3, 4, escalated_at=2))
self.assertEqual(close.after_verdict(run_with, self.OPUS, run.Concluded(Unfinished("new", "round 2: 🔴", entries_read=9), run_with.route)).route, Route(Rung("claude-fable-5-2", "low"), 3, 3, 4, escalated_at=9))
self.assertEqual(close.after_verdict(run_with, self.OPUS, run.Concluded(Unfinished("new", entries_read=9), run_with.route)).route, Route(self.OPUS, 3, 3, 4, unfinished=1, escalated_at=2))
self.assertEqual(close.after_verdict(run_with, LADDER, self.OPUS, run.Concluded(Unfinished("new", "round 2: 🔴", entries_read=9), run_with.route)).route, Route(Rung("claude-fable-5-2", "low"), 3, 3, 4, escalated_at=9))
self.assertEqual(close.after_verdict(run_with, LADDER, self.OPUS, run.Concluded(Unfinished("new", entries_read=9), run_with.route)).route, Route(self.OPUS, 3, 3, 4, unfinished=1, escalated_at=2))
def test_archives_a_step_up_as_it_happens_so_a_rerun_resumes_on_it(self):
with tempfile.TemporaryDirectory() as home:
@@ -1297,14 +1301,14 @@ class Steps(unittest.TestCase):
before = Route(self.OPUS, 3, 3, 4)
with contextlib.redirect_stderr(io.StringIO()):
self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.unfinished(before.worker_line(), "working", "j", ""), NOW))
after = close.closed_cycle(main.LoopRun(cycle_number=1, root="/r", task="Do it.", unfinished_evidence=""), self.OPUS, run.Concluded(Unfinished("working", taken_in=TakenIn(highest_likelihood=4)), before), archive, a_loop(FakeEffects().effects(), session=opened))
after = close.closed_cycle(main.LoopRun(cycle_number=1, root="/r", task="Do it.", unfinished_evidence=""), LADDER, self.OPUS, run.Concluded(Unfinished("working", taken_in=TakenIn(highest_likelihood=4)), before), archive, a_loop(FakeEffects().effects(), session=opened))
self.assertEqual(chunk_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened)), Route(Rung("claude-fable-5-2", "low"), 3, 3, 4))
with contextlib.redirect_stderr(io.StringIO()):
close.closed_cycle(after, self.OPUS, run.Concluded(Finished("done"), after.route), archive, a_loop(FakeEffects().effects(), session=opened))
close.closed_cycle(after, LADDER, self.OPUS, run.Concluded(Finished("done"), after.route), archive, a_loop(FakeEffects().effects(), session=opened))
self.assertEqual(chunk_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened)), Route(Rung("claude-fable-5-2", "low"), 3, 3, 4))
blocked = pathlib.Path(home, "blocked")
blocked.write_text("")
stop = close.closed_cycle(main.LoopRun(cycle_number=1, root="/r", task="Do it.", unfinished_evidence=""), self.OPUS, run.Concluded(Unfinished("working", taken_in=TakenIn(highest_likelihood=4)), before), blocked, a_loop(FakeEffects().effects(), session=opened))
stop = close.closed_cycle(main.LoopRun(cycle_number=1, root="/r", task="Do it.", unfinished_evidence=""), LADDER, self.OPUS, run.Concluded(Unfinished("working", taken_in=TakenIn(highest_likelihood=4)), before), blocked, a_loop(FakeEffects().effects(), session=opened))
self.assertEqual((stop.code, stop.reason.split(":")[0]), (1, "could not archive the transcript"))
def test_names_no_step_up_where_only_the_count_of_unfinished_verdicts_changed(self):
@@ -1322,7 +1326,7 @@ class Steps(unittest.TestCase):
before = Route(self.OPUS, 3, 3, 4)
with contextlib.redirect_stderr(io.StringIO()):
self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.unfinished(before.worker_line(), "working", "j", ""), NOW))
close.closed_cycle(main.LoopRun(cycle_number=1, root="/r", task="Do it.", unfinished_evidence=""), self.OPUS, run.Concluded(Unfinished("working", taken_in=TakenIn(highest_escape_and_impact=6)), before), archive, a_loop(FakeEffects().effects(), session=opened))
close.closed_cycle(main.LoopRun(cycle_number=1, root="/r", task="Do it.", unfinished_evidence=""), LADDER, self.OPUS, run.Concluded(Unfinished("working", taken_in=TakenIn(highest_escape_and_impact=6)), before), archive, a_loop(FakeEffects().effects(), session=opened))
self.assertEqual(chunk_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened)), Route(self.OPUS, 3, 3, 4, escape_and_impact_taken_in=6))
@@ -1362,13 +1366,13 @@ class TypedAnswers(unittest.TestCase):
def test_splits_the_prompt_handing_over_the_answer_into_the_answer_on_the_line_after_its_marker_and_the_rest_and_no_other_prompt(self):
route = Route(Rung("worker-model"))
marked = "The human answered your question at loop-claude's terminal:\nB"
typed = prompts.typed_answer(prompts.typed("Which one?", "Use B.", route, None, False))
typed = prompts.typed_answer(prompts.typed("Which one?", "Use B.", route, LADDER, None, False))
self.assertEqual(typed.answer, "Use B.")
self.assertTrue(typed.loop_words.startswith("Your question was: Which one?\n\nContinue the task."))
self.assertEqual(prompts.typed_answer(prompts.typed(f"Which one?\n{marked}", "Use B.", route, None, False)).answer, "Use B.")
self.assertEqual(prompts.typed_answer(prompts.typed("Which one?", "Use B.", Route(Routing.SONNET, 179, 2, 5), Routing.OPUS, True)).answer, "Use B.")
self.assertIsNone(prompts.typed_answer(prompts.answered("Which one?", marked, route, None, False)))
self.assertIsNone(prompts.typed_answer(prompts.resumed(marked, route, None)))
self.assertEqual(prompts.typed_answer(prompts.typed(f"Which one?\n{marked}", "Use B.", route, LADDER, None, False)).answer, "Use B.")
self.assertEqual(prompts.typed_answer(prompts.typed("Which one?", "Use B.", Route(Routing.SONNET, 179, 2, 5), LADDER, Routing.OPUS, True)).answer, "Use B.")
self.assertIsNone(prompts.typed_answer(prompts.answered("Which one?", marked, route, LADDER, None, False)))
self.assertIsNone(prompts.typed_answer(prompts.resumed(marked, route, LADDER, None)))
class WorkerArgs(unittest.TestCase):
@@ -1379,24 +1383,24 @@ class WorkerArgs(unittest.TestCase):
FACTS = "- A preflight fact."
def test_names_the_route_in_a_fresh_prompt_only_where_an_item_routed_it(self):
routed = prompts.fresh("Do it.", "## Goals", Route(Rung("m", "high"), 3, 4, 5), None, self.FACTS)
routed = prompts.fresh("Do it.", "## Goals", Route(Rung("m", "high"), 3, 4, 5), LADDER, None, self.FACTS)
self.assertIn(f"Continue any open draft PR or worktree for the chunk before creating a new one. {prompts.READING_RULE} {prompts.NAME_THE_ITEMS}\n\nloop-claude runs you on m at high effort, routed by item 3's L of 4.", routed)
unrouted = prompts.fresh("Do it.", "## Goals", Route(Rung("m")), None, self.FACTS)
unrouted = prompts.fresh("Do it.", "## Goals", Route(Rung("m")), LADDER, None, self.FACTS)
self.assertIn(f"before creating a new one. {prompts.READING_RULE} {prompts.NAME_THE_ITEMS}\n\n{self.FACTS}\n\nThe chunk's", unrouted)
self.assertNotIn("loop-claude runs you on", unrouted)
def test_has_the_routed_worker_count_its_items_size_again_and_puts_the_facts_before_the_scope(self):
routed = prompts.fresh("Do it.", "## Goals", Route(Rung("m", "high"), 3, 4, 5), None, self.FACTS)
routed = prompts.fresh("Do it.", "## Goals", Route(Rung("m", "high"), 3, 4, 5), LADDER, None, self.FACTS)
self.assertIn("item 3's size again", routed)
self.assertIn("escalation trigger 1", routed)
self.assertIn(f"\n\n{self.FACTS}\n\nThe chunk's", routed)
self.assertNotIn("size again", prompts.fresh("Do it.", "## Goals", Route(Rung("m")), None, self.FACTS))
self.assertNotIn("size again", prompts.fresh("Do it.", "## Goals", Route(Rung("m")), LADDER, None, self.FACTS))
def test_gives_each_fresh_worker_the_reading_rule_once(self):
rule = "never read more than 80 lines of a file at once, nor take a tool output over 3,000 characters into your context"
for route in (Route(Rung("m", "high"), 3, 4, 5), Route(Rung("m"))):
with self.subTest(route=route):
self.assertEqual(prompts.fresh("Do it.", "## Goals", route, None, self.FACTS).count(rule), 1)
self.assertEqual(prompts.fresh("Do it.", "## Goals", route, LADDER, None, self.FACTS).count(rule), 1)
def test_quotes_what_the_preflight_printed_or_has_the_worker_find_the_facts_itself(self):
self.assertIn("\n\n- A fact.", prompts.preflight_facts("- A fact."))
@@ -1407,93 +1411,95 @@ class WorkerArgs(unittest.TestCase):
def test_has_each_fresh_worker_continue_an_open_draft_pr_or_worktree_once_whatever_the_preflight_found(self):
for facts in (prompts.preflight_facts("- A fact."), prompts.preflight_failed("git could not start")):
with self.subTest(facts=facts):
self.assertEqual(prompts.fresh("Do it.", "## Goals", Route(Rung("m")), None, facts).count("Continue any open draft PR or worktree"), 1)
self.assertEqual(prompts.fresh("Do it.", "## Goals", Route(Rung("m")), LADDER, None, facts).count("Continue any open draft PR or worktree"), 1)
def test_keeps_every_review_on_the_projects_rung_while_the_worker_runs_below_it(self):
opus = Rung("claude-opus-5-5", "medium")
below = prompts.fresh("Do it.", "## Goals", Route(Rung("claude-sonnet-5-5", "high"), 3, 2, 4), opus, self.FACTS)
below = prompts.fresh("Do it.", "## Goals", Route(Rung("claude-sonnet-5-5", "high"), 3, 2, 4), LADDER, opus, self.FACTS)
self.assertIn(f"item 3's L of 2. 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.{self.SCAN} Your rung is below the project's: launch each subagent that files or scores todo.md items on the rung `~/.claude/bin/subagent-rung --plan 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.assertNotIn("Launch each", prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 4), opus, self.FACTS))
self.assertNotIn("Launch each", prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 4), LADDER, opus, self.FACTS))
def test_launches_reviewers_on_the_rung_the_items_e_plus_i_picks_above_the_workers(self):
opus = Rung("claude-opus-5-5", "medium")
level = prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 6), opus, self.FACTS)
level = prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 6), LADDER, opus, self.FACTS)
self.assertIn(f"item 3's L of 3. 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.{self.MARKDOWN} When an escalation trigger", level)
below = prompts.fresh("Do it.", "## Goals", Route(Rung("claude-sonnet-5-5", "high"), 3, 2, 5), opus, self.FACTS)
below = prompts.fresh("Do it.", "## Goals", Route(Rung("claude-sonnet-5-5", "high"), 3, 2, 5), LADDER, opus, self.FACTS)
self.assertIn(f"item 3's L of 2. Launch each reviewer with the Agent tool set to model fable, effort low, the rung item 3's E + I of 5 picks.{self.SEATS}{self.SCAN} Your rung is below the project's:", below)
self.assertNotIn("Launch each reviewer", prompts.resumed("", Route(Rung("claude-fable-5-2", "medium"), 3, 4, 6), opus))
self.assertNotIn("Launch each reviewer", prompts.resumed("", Route(Rung("claude-fable-5-2", "medium"), 3, 4, 6), LADDER, opus))
def test_names_the_reviewers_rung_each_higher_e_plus_i_an_item_taken_in_picks(self):
opus = Rung("claude-opus-5-5", "medium")
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.assertIn(f"item 3's L of 3.{taking_in} When an escalation trigger", prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 4), opus, self.FACTS))
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.", prompts.resumed("", Route(opus, 3, 3, 6), opus))
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.", prompts.resumed("", Route(Rung("claude-fable-5-2", "medium"), 3, 4, 4), opus))
self.assertNotIn("Where an item you take into", prompts.resumed("", Route(opus, 3, 3, 8), opus))
self.assertNotIn("Where an item you take into", prompts.resumed("", Route(Rung("m")), None))
self.assertIn(f"item 3's L of 3.{taking_in} When an escalation trigger", prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 4), LADDER, opus, self.FACTS))
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.", prompts.resumed("", Route(opus, 3, 3, 6), LADDER, opus))
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.", prompts.resumed("", Route(Rung("claude-fable-5-2", "medium"), 3, 4, 4), LADDER, opus))
self.assertNotIn("Where an item you take into", prompts.resumed("", Route(opus, 3, 3, 8), LADDER, opus))
self.assertNotIn("Where an item you take into", prompts.resumed("", Route(Rung("m")), LADDER, None))
def test_launches_reviewers_on_the_rung_the_highest_e_plus_i_taken_in_picks(self):
opus = Rung("claude-opus-5-5", "medium")
self.assertIn(f"loop-claude 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.{self.MARKDOWN} When an escalation trigger", prompts.resumed("", Route(opus, 3, 3, 5, escape_and_impact_taken_in=7), opus))
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.", prompts.resumed("", Route(opus, escape_and_impact_taken_in=5), opus))
self.assertIn(f"loop-claude 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.{self.MARKDOWN} When an escalation trigger", prompts.resumed("", Route(opus, 3, 3, 5, escape_and_impact_taken_in=7), LADDER, opus))
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.", prompts.resumed("", Route(opus, escape_and_impact_taken_in=5), LADDER, opus))
def test_keeps_seats_and_the_security_pass_on_the_projects_rung_while_the_worker_runs_above_it(self):
opus = Rung("claude-opus-5-5", "medium")
above = prompts.fresh("Do it.", "## Goals", Route(Rung("claude-fable-5-2", "low"), 3, 4, 4), opus, self.FACTS)
stepped_up = prompts.resumed("", Route(Rung("claude-fable-5-2", "low"), 3, 3, 4), opus)
above = prompts.fresh("Do it.", "## Goals", Route(Rung("claude-fable-5-2", "low"), 3, 4, 4), LADDER, opus, self.FACTS)
stepped_up = prompts.resumed("", Route(Rung("claude-fable-5-2", "low"), 3, 3, 4), LADDER, opus)
self.assertIn(f"{prompts.ANSWERS_RECORDED}. {prompts.NAME_THE_ITEMS} loop-claude runs you on claude-fable-5-2 at low effort.{self.SEATS}{self.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.{self.MARKDOWN} When an escalation trigger", stepped_up)
self.assertNotIn("the project's", prompts.resumed("", Route(opus, 3, 3, 4), opus))
self.assertNotIn("runs you on", prompts.resumed("", Route(Rung("m")), None))
self.assertNotIn("the project's", prompts.resumed("", Route(opus, 3, 3, 4), LADDER, opus))
self.assertNotIn("runs you on", prompts.resumed("", Route(Rung("m")), LADDER, None))
self.assertIn(f"item 3's L of 4.{self.SEATS}{self.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.{self.MARKDOWN} When an escalation trigger", above)
def test_names_the_rungs_an_escalation_trigger_lets_the_worker_hand_a_task_to_at_most_two_above_its_items(self):
opus = Rung("claude-opus-5-5", "medium")
fresh = prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 4), opus, self.FACTS)
fresh = prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 4), LADDER, opus, self.FACTS)
self.assertIn("item 3's L of 3. 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.", fresh)
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; above that, ask the human first. Open the subagent's prompt with `Escalation trigger <n>:`, n the trigger's number.", prompts.resumed("", Route(Rung("claude-fable-5-2", "low"), 3, 3, 4), opus))
self.assertIn(" An escalation trigger in `~/.claude/CLAUDE.md` lets you hand the hard part of a task to a subagent with the Agent tool set to `model opus, effort xhigh`, one rung above yours, only once the human agrees; loop-claude will not resume you higher for a trigger either, so ask the human for that yes. Open the subagent's prompt with `Escalation trigger <n>:`, n the trigger's number.", prompts.resumed("", Route(Rung("claude-fable-5-2", "medium"), 3, 3, 4), opus))
self.assertNotIn("escalation", prompts.resumed("", Route(Rung("claude-fable-5-2", "max"), 3, 4, 8), opus))
self.assertIn("only once the human agrees", prompts.resumed("", Route(Rung("claude-opus-5-5", "xhigh"), 3, 4, 5), opus))
self.assertIn("hand the hard part of the task to a subagent with the Agent tool set to `model opus, effort xhigh`, one rung above yours;", prompts.resumed("", Route(Rung("claude-fable-5-2", "medium"), 3, 4, 5), opus))
self.assertNotIn("escalation", prompts.resumed("", Route(Rung("m")), None))
self.assertNotIn("escalation", prompts.resumed("", Route(Rung("claude-opus-5-5", "low"), 3, 3, 4), opus))
self.assertIn(f"{prompts.READING_RULE} {prompts.NAME_THE_ITEMS}\n\nWhere an item you take into the chunk has an E + I of 5 or more, launch each reviewer with the Agent tool set to `model 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 loop-claude for a higher rung and naming a trigger that fired since your last step-up, if any: once the judge finds it in your transcript, the next cycle resumes you one rung up, up to `model fable, effort medium`. A reviewer", prompts.fresh("Do it.", "## Goals", Route(opus), opus, self.FACTS))
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; above that, ask the human first. Open the subagent's prompt with `Escalation trigger <n>:`, n the trigger's number.", prompts.resumed("", Route(Rung("claude-fable-5-2", "low"), 3, 3, 4), LADDER, opus))
self.assertIn(" An escalation trigger in `~/.claude/CLAUDE.md` lets you hand the hard part of a task to a subagent with the Agent tool set to `model opus, effort xhigh`, one rung above yours, only once the human agrees; loop-claude will not resume you higher for a trigger either, so ask the human for that yes. Open the subagent's prompt with `Escalation trigger <n>:`, n the trigger's number.", prompts.resumed("", Route(Rung("claude-fable-5-2", "medium"), 3, 3, 4), LADDER, opus))
self.assertNotIn("escalation", prompts.resumed("", Route(Rung("claude-fable-5-2", "max"), 3, 4, 8), LADDER, opus))
self.assertIn("only once the human agrees", prompts.resumed("", Route(Rung("claude-opus-5-5", "xhigh"), 3, 4, 5), LADDER, opus))
self.assertIn("only once the human agrees", prompts.resumed("", Route(Rung("claude-fable-5-2", "high"), 3, 4, 5), LADDER, opus), "one rung below the top still names the rung above")
self.assertNotIn("rerun", prompts.resumed("", Route(Rung("claude-opus-5-5", "low"), 3, 3, 4), LADDER, opus), "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 opus, effort xhigh`, one rung above yours;", prompts.resumed("", Route(Rung("claude-fable-5-2", "medium"), 3, 4, 5), LADDER, opus))
self.assertNotIn("escalation", prompts.resumed("", Route(Rung("m")), LADDER, None))
self.assertNotIn("escalation", prompts.resumed("", Route(Rung("claude-opus-5-5", "low"), 3, 3, 4), LADDER, opus))
self.assertIn(f"{prompts.READING_RULE} {prompts.NAME_THE_ITEMS}\n\nWhere an item you take into the chunk has an E + I of 5 or more, launch each reviewer with the Agent tool set to `model 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 loop-claude for a higher rung and naming a trigger that fired since your last step-up, if any: once the judge finds it in your transcript, the next cycle resumes you one rung up, up to `model fable, effort medium`. A reviewer", prompts.fresh("Do it.", "## Goals", Route(opus), LADDER, opus, self.FACTS))
def test_offers_the_worker_a_higher_rung_for_the_rest_of_the_chunk_up_to_the_escalation_cap(self):
opus = Rung("claude-opus-5-5", "medium")
offer = " Where the hard part is the rest of the chunk, end your run instead, asking loop-claude for a higher rung and naming a trigger that fired since your last step-up, if any: once the judge finds it in your transcript, the next cycle resumes you one rung up, up to `model fable, effort medium`."
self.assertIn(f"`Escalation trigger <n>:`, n the trigger's number.{offer}", prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 4), opus, self.FACTS))
self.assertIn(f"`Escalation trigger <n>:`, n the trigger's number.{offer}", prompts.resumed("", Route(Rung("claude-fable-5-2", "low"), 3, 3, 4), opus))
self.assertNotIn("Where the hard part", prompts.resumed("", Route(Rung("claude-fable-5-2", "medium"), 3, 3, 4), opus))
self.assertIn(f"`Escalation trigger <n>:`, n the trigger's number.{offer}", prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 4), LADDER, opus, self.FACTS))
self.assertIn(f"`Escalation trigger <n>:`, n the trigger's number.{offer}", prompts.resumed("", Route(Rung("claude-fable-5-2", "low"), 3, 3, 4), LADDER, opus))
self.assertNotIn("Where the hard part", prompts.resumed("", Route(Rung("claude-fable-5-2", "medium"), 3, 3, 4), LADDER, opus))
def test_lets_a_markdown_only_branch_review_on_the_projects_rung_where_the_reviewers_run_above_it(self):
opus = Rung("claude-opus-5-5", "medium")
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."
self.assertIn(markdown, prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 7), opus, self.FACTS))
self.assertIn(markdown, prompts.resumed("", Route(Rung("claude-fable-5-2", "low"), 3, 4, 4), opus))
self.assertNotIn("only Markdown", prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 4), opus, self.FACTS))
self.assertIn(markdown, prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 7), LADDER, opus, self.FACTS))
self.assertIn(markdown, prompts.resumed("", Route(Rung("claude-fable-5-2", "low"), 3, 4, 4), LADDER, opus))
self.assertNotIn("only Markdown", prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 4), LADDER, opus, self.FACTS))
def test_names_the_rung_a_reviewer_or_seat_reruns_on_one_above_its_own(self):
opus = Rung("claude-opus-5-5", "medium")
both = " A reviewer or comprehension seat that asks for a rerun one rung up reruns with the Agent tool set to `model fable, effort low`."
self.assertTrue(prompts.resumed("", Route(opus, 3, 3, 4), opus).endswith(both))
self.assertTrue(prompts.resumed("", Route(Rung("claude-sonnet-5-5", "high"), 3, 2, 4), opus).endswith(both))
self.assertTrue(prompts.fresh("Do it.", "## Goals", Route(opus), opus, self.FACTS).split(f"\n\n{self.FACTS}")[0].endswith(both))
self.assertTrue(prompts.resumed("", Route(Rung("claude-fable-5-2", "low"), 3, 4, 4), opus).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(prompts.resumed("", Route(opus, 3, 3, 7), opus).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(prompts.resumed("", Route(Rung("claude-fable-5-2", "max"), 3, 4, 8), opus).endswith(" A comprehension seat that asks for a rerun one rung up reruns with the Agent tool set to `model fable, effort low`."))
self.assertNotIn("rerun", prompts.resumed("", Route(Rung("m")), None))
self.assertNotIn("rerun", prompts.fresh("Do it.", "## Goals", Route(Rung("m", "high"), 3, 4, 5), None, self.FACTS))
self.assertIn(f"{both} After your first read", prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 4), opus, self.FACTS))
self.assertTrue(prompts.resumed("", Route(opus, 3, 3, 4), LADDER, opus).endswith(both))
self.assertTrue(prompts.resumed("", Route(Rung("claude-sonnet-5-5", "high"), 3, 2, 4), LADDER, opus).endswith(both))
self.assertTrue(prompts.fresh("Do it.", "## Goals", Route(opus), LADDER, opus, self.FACTS).split(f"\n\n{self.FACTS}")[0].endswith(both))
self.assertTrue(prompts.resumed("", Route(Rung("claude-fable-5-2", "low"), 3, 4, 4), LADDER, opus).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(prompts.resumed("", Route(opus, 3, 3, 7), LADDER, opus).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(prompts.resumed("", Route(Rung("claude-fable-5-2", "max"), 3, 4, 8), LADDER, opus).endswith(" A comprehension seat that asks for a rerun one rung up reruns with the Agent tool set to `model fable, effort low`."))
self.assertNotIn("rerun", prompts.resumed("", Route(Rung("m")), LADDER, None))
self.assertNotIn("rerun", prompts.fresh("Do it.", "## Goals", Route(Rung("m", "high"), 3, 4, 5), LADDER, None, self.FACTS))
self.assertIn(f"{both} After your first read", prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 4), LADDER, opus, self.FACTS))
fable = Rung("claude-fable-5-2", "max")
self.assertNotIn("rerun", prompts.resumed("", Route(fable), fable))
self.assertNotIn("rerun", prompts.resumed("", Route(fable), LADDER, fable))
def test_opens_a_fresh_session_by_name_and_resumes_an_open_one(self):
opened = session.session_named("A proj loop-claude", pathlib.Path("/h/.claude/projects"))
fresh = worker.worker_args(opened, Rung("m"), prompts.fresh("Do it.", "## Goals\n1. g\n\n## Audience\nme", Route(Rung("m")), None, self.FACTS), resume=False)
fresh = worker.worker_args(opened, Rung("m"), prompts.fresh("Do it.", "## Goals\n1. g\n\n## Audience\nme", Route(Rung("m")), LADDER, None, self.FACTS), resume=False)
self.assertEqual(fresh[fresh.index("--session-id") + 1], str(opened.id))
self.assertEqual(fresh[fresh.index("--name") + 1], "A proj loop-claude")
resumed = worker.worker_args(opened, Rung("m"), prompts.resumed("", Route(Rung("m")), None), resume=True)
resumed = worker.worker_args(opened, Rung("m"), prompts.resumed("", Route(Rung("m")), LADDER, None), resume=True)
self.assertEqual(resumed[resumed.index("--resume") + 1], str(opened.id))
self.assertNotIn("--session-id", resumed)
self.assertTrue(resumed[resumed.index("-p") + 1].startswith("Continue the task; the previous run ended before the chunk was finished. The chunk is finished once"))
@@ -1600,7 +1606,7 @@ class JudgePrompt(unittest.TestCase):
self.assertEqual(judge.quotes_checked(Unfinished("e", "new", entries_read=3), grounds), Unfinished("e", "new", entries_read=3))
def test_shows_a_typed_answer_before_the_step_up_as_the_humans(self):
typed = prompts.typed("Which one?", "Use B.", Route(Rung("worker-model")), None, False)
typed = prompts.typed("Which one?", "Use B.", Route(Rung("worker-model")), LADDER, None, False)
entries = [{**human(typed), "promptSource": "sdk"}, assistant({"type": "text", "text": "round 3: 🔴"})]
_, grounds = judge.judge_prompt(judge.Brief("Do it.", "## Goals", "", kinds(*entries), 1))
self.assertIn("\n\n[human] Use B.\n\n[step] ", grounds.shown)
@@ -1740,7 +1746,7 @@ class ChunkItems(unittest.TestCase):
self.assertEqual(chunk_items.named([said(example)]), (297, 298))
def test_every_prompt_that_starts_or_resumes_a_chunk_asks_for_the_line(self):
self.assertIn("on one line, as in `Chunk items: ", prompts.resumed("", Route(Rung("m")), None))
self.assertIn("on one line, as in `Chunk items: ", prompts.resumed("", Route(Rung("m")), LADDER, None))
def test_reads_only_a_line_the_worker_opens_with_the_label_in_its_own_text(self):
prompt = entries.LoopPrompt(text="Chunk items: 297 (L 3, E + I 5)")
@@ -1986,6 +1992,13 @@ class HelpLimits(unittest.TestCase):
self.assertIn(f"rerun to give it {close.UNFINISHED_LIMIT} more", said)
class OwnLadder(unittest.TestCase):
def test_a_cycle_on_a_projects_own_ladder_names_its_file_and_says_where_the_workers_model_is_off_it(self):
file = pathlib.Path("/h/.claude-projects/acme/routing-ladder.json")
self.assertEqual(main.own_ladder(file, "claude-fable-5-2", False), f"routing on the project's own ladder, {file}.")
self.assertEqual(main.own_ladder(file, "claude-opus-5-5", True), f"routing on the project's own ladder, {file}. claude-opus-5-5 is not on it, so the worker runs on claude-opus-5-5 unrouted; LOOP_CLAUDE_WORKER_MODEL and LOOP_CLAUDE_JUDGE_MODEL name other models for a run.")
class ExitContract(unittest.TestCase):
def test_every_exit_1_stop_has_its_clause_in_help(self):
read, git, premises_ = "a transcript cannot be read or archived", "git cannot start or finds no checkout", "no config names the checkout, its config cannot be read, or the goals file holds no premises"
@@ -2011,6 +2024,8 @@ class ExitContract(unittest.TestCase):
("loop/main.py", "run_loop", "1", "held.reason", "its slot in the project cannot be taken"),
("loop/main.py", "next_cycle", "1", "premises.reason", premises_),
("loop/main.py", "next_cycle", "1", "records.reason", unreadable),
("loop/main.py", "next_cycle", "1", "ladder_file.reason", premises_),
("loop/main.py", "next_cycle", "1", "ladder.reason", "the project's routing ladder cannot be read or holds a fault"),
("loop/main.py", "loop_run_from", "0 if task else 1", "HELP", "no task is given"),
("loop/main.py", "loop_run_from", "1", 'f"the edited loop-claude cannot read the state', "a reload cannot read the state the running script handed it"),
("loop/reload.py", "exec_if_edited", "1", "f'could not reload loop-claude:", "python cannot start for a reload"),
+48 -62
View File
@@ -1,4 +1,4 @@
"""The routing ladder, and the rungs a task's L and E + I pick from the project's rung: docs/decisions.md → `routing:`."""
"""A routing ladder, and the rungs a task's L and E + I pick on it from the project's rung: docs/decisions.md → `routing:`."""
import dataclasses
import re
import typing
@@ -7,6 +7,8 @@ from review_rules.review_passes import ReviewedPass
# How Rung.__str__ spells a rung that names an effort, and Rung.parse reads it back.
WORDING = re.compile(r"(?P<model>\S+) at (?P<effort>\S+) effort")
# Lowest first, as Claude Code's --effort takes them.
EFFORTS = ("low", "medium", "high", "xhigh", "max")
# What a review launch reviews: such a pass, a comprehension seat or the security pass.
ReviewKind = ReviewedPass | typing.Literal["seat", "security"]
@@ -28,14 +30,6 @@ class Rung:
"""The rung in the Agent tool's words. The tool takes a family name, such as opus, and runs that family's latest model, which is the model each rung names."""
return f"model {self.family()}, effort {self.effort}"
@staticmethod
def from_agent(model: str, effort: str) -> "Rung":
"""The rung the Agent tool's model and effort name: a family such as opus is its ladder model, at the effort given or else its cheapest. A family off the ladder, or an effort off it, gives a rung that is not on LADDER."""
family = next((rung for rung in LADDER if rung.family() == model), None)
if family is None:
return Rung(model, effort)
return Rung(family.model, effort) if effort else family
# loop-claude hands a rung to rule-hook in environment variables in this spelling, so parse must keep reading it.
def __str__(self) -> str:
return f"{self.model} at {self.effort} effort" if self.effort else self.model
@@ -47,76 +41,68 @@ class Rung:
return Rung(found["model"], found["effort"]) if found else None
# Least competent first.
LADDER = (
Rung("claude-sonnet-5-5", "high"),
Rung("claude-opus-5-5", "medium"),
Rung("claude-fable-5-2", "low"),
Rung("claude-fable-5-2", "medium"),
Rung("claude-opus-5-5", "xhigh"),
Rung("claude-fable-5-2", "high"),
Rung("claude-fable-5-2", "max"),
)
# The rungs a task's L steps its worker from the project's rung.
WORKER_STEPS = {1: -1, 2: -1, 3: 0, 4: 1}
# The rungs a task's E + I steps a review up from the project's rung; an E + I under 5 steps none.
REVIEW_STEPS = {5: 1, 6: 2, 7: 3, 8: 4}
def project_rung(model: str) -> Rung | None:
"""The model's cheapest rung, which for Opus 5.5 is its default effort; None for a model off the ladder."""
return next((rung for rung in LADDER if rung.model == model), None)
@dataclasses.dataclass(frozen=True)
class Ladder:
"""A project's rungs, least competent first. model_routing/ladder_file.py reads one, and refuses a file that holds no rung, one rung twice, since a rung's position sets every step, or two models of one family, since from_agent reads a family as one model."""
rungs: tuple[Rung, ...]
def from_agent(self, model: str, effort: str) -> Rung:
"""The rung the Agent tool's model and effort name: a family such as opus is its ladder model, at the effort given or else its cheapest. A family off the ladder, or an effort off it, gives a rung that is not on the ladder."""
family = next((rung for rung in self.rungs if rung.family() == model), None)
if family is None:
return Rung(model, effort)
return Rung(family.model, effort) if effort else family
def worker_rung(project: Rung, likelihood: int) -> Rung:
"""The rung a task's L picks for its worker, counted from the project's rung, stopping at either end of the ladder."""
return climbed(project, WORKER_STEPS[likelihood])
def project_rung(self, model: str) -> Rung | None:
"""The model's cheapest rung, which for Opus 5.5 is its default effort; None for a model off the ladder."""
return next((rung for rung in self.rungs if rung.model == model), None)
def worker_rung(self, project: Rung, likelihood: int) -> Rung:
"""The rung a task's L picks for its worker, counted from the project's rung, stopping at either end of the ladder."""
return self.climbed(project, WORKER_STEPS[likelihood])
def lowest_worker_rung(project: Rung) -> Rung:
"""The lowest rung any L routes a worker to, counted from the project's rung."""
return climbed(project, min(WORKER_STEPS.values()))
def lowest_worker_rung(self, project: Rung) -> Rung:
"""The lowest rung any L routes a worker to, counted from the project's rung."""
return self.climbed(project, min(WORKER_STEPS.values()))
def planning_rung(self, project: Rung, likelihood: int) -> Rung:
"""The rung of a task that files or scores todo.md items: the one its L picks, never below the project's rung."""
return self.highest(project, self.worker_rung(project, likelihood))
def planning_rung(project: Rung, likelihood: int) -> Rung:
"""The rung of a task that files or scores todo.md items: the one its L picks, never below the project's rung."""
return highest(project, worker_rung(project, likelihood))
def review_floor(self, project: Rung, escape_and_impact: int) -> Rung:
"""The rung a task's E + I picks for a review, counted up from the project's rung. An E + I of 0, for no task, picks the project's rung."""
return self.climbed(project, REVIEW_STEPS.get(escape_and_impact, 0))
def stepped_up(self, rung: Rung) -> Rung:
"""The rung above, or the top one; a rung off the ladder steps to the bottom one."""
return self.climbed(rung, 1)
def review_floor(project: Rung, escape_and_impact: int) -> Rung:
"""The rung a task's E + I picks for a review, counted up from the project's rung. An E + I of 0, for no task, picks the project's rung."""
return climbed(project, REVIEW_STEPS.get(escape_and_impact, 0))
def review_rung(self, project: Rung, worker: Rung, escape_and_impact: int, kind: ReviewKind, markdown_only: bool = False) -> Rung:
"""The rung a review of this kind runs on in a chunk whose worker runs on worker and whose item has that E + I; markdown_only where the branch changes only Markdown no agent follows.
A pass's reviewer runs on reviewers_rung; no replay has qualified a lower rung for any pass, docs/decisions.md → `routing: a review pass runs below the project's rung only on a rung whose replay of its rounds finds a share of their 🔴 and 🟡 findings no more than a margin below the project's rung's own replay`. A seat and the security pass run on the project's rung, so the seats score every chunk on one rung, and the security pass spends no more than the project chose.
"""
return project if kind in ("seat", "security") else self.reviewers_rung(project, worker, escape_and_impact, markdown_only)
def stepped_up(rung: Rung) -> Rung:
"""The rung above, or the top one; a rung off the ladder steps to the bottom one."""
return climbed(rung, 1)
def reviewers_rung(self, project: Rung, worker: Rung, escape_and_impact: int, markdown_only: bool = False) -> Rung:
"""The rung of each pass's reviewer: the higher of the worker's rung and review_floor's, which is never below the project's.
markdown_only means the branch changes only Markdown no agent follows. Such a branch holds no code or config for a higher rung to catch a defect in, so its reviewer runs on the project's rung: skills/larv-review/SKILL.md → "Markdown only".
"""
return project if markdown_only else self.highest(worker, self.review_floor(project, escape_and_impact))
def review_rung(project: Rung, worker: Rung, escape_and_impact: int, kind: ReviewKind, markdown_only: bool = False) -> Rung:
"""The rung a review of this kind runs on in a chunk whose worker runs on worker and whose item has that E + I; markdown_only where the branch changes only Markdown no agent follows.
def highest(self, *rungs: Rung) -> Rung:
"""The most competent of the rungs; one off the ladder ranks below every rung on it."""
return max(rungs, key=self.position)
A pass's reviewer runs on reviewers_rung; no replay has qualified a lower rung for any pass, docs/decisions.md → `routing: a review pass runs below the project's rung only on a rung whose replay of its rounds finds a share of their 🔴 and 🟡 findings no more than a margin below the project's rung's own replay`. A seat and the security pass run on the project's rung, so the seats score every chunk on one rung, and the security pass spends no more than the project chose.
"""
return project if kind in ("seat", "security") else reviewers_rung(project, worker, escape_and_impact, markdown_only)
def climbed(self, rung: Rung, by: int) -> Rung:
return self.rungs[max(0, min(len(self.rungs) - 1, self.position(rung) + by))]
def reviewers_rung(project: Rung, worker: Rung, escape_and_impact: int, markdown_only: bool = False) -> Rung:
"""The rung of each pass's reviewer: the higher of the worker's rung and review_floor's, which is never below the project's.
markdown_only means the branch changes only Markdown no agent follows. Such a branch holds no code or config for a higher rung to catch a defect in, so its reviewer runs on the project's rung: skills/larv-review/SKILL.md → "Markdown only".
"""
return project if markdown_only else highest(worker, review_floor(project, escape_and_impact))
def highest(*rungs: Rung) -> Rung:
"""The most competent of the rungs; one off the ladder ranks below every rung on it."""
return max(rungs, key=position)
def climbed(rung: Rung, by: int) -> Rung:
return LADDER[max(0, min(len(LADDER) - 1, position(rung) + by))]
def position(rung: Rung) -> int:
return LADDER.index(rung) if rung in LADDER else -1
def position(self, rung: Rung) -> int:
return self.rungs.index(rung) if rung in self.rungs else -1
+71
View File
@@ -0,0 +1,71 @@
"""Read a routing ladder from its JSON file: the one this setup ships, or a project's own, kept in its config's folder. docs/decisions.md → `routing: one ladder of (model, effort) rungs`."""
import json
import pathlib
import re
from model_routing.ladder import EFFORTS, Ladder, Rung
from failure import Failure
from project_config.main import located
from project_config.settings import Unnamed
# The file's name in both places. Three readers, seated as the human who writes an override in a hurry, picked a bare list of objects over a list of strings, a list of pairs and a list under a key. Two of them picked one name for both files: an override is then a copy of the shipped file with rungs cut.
NAME = "routing-ladder.json"
# The ladder this setup ships, beside this module, so a copy of bin/ carries it: mutate-changes and the tests of a reload each run the tools from such a copy.
SHIPPED = pathlib.Path(__file__).resolve().with_name(NAME)
# A model as Rung.family reads it: the Agent tool's family name follows the first hyphen.
MODEL = re.compile(r"[^\s-]+(-[^\s-]+)+")
SHAPE = f'a JSON list of rungs, least competent first, each as {{"model": "claude-opus-5-5", "effort": "medium"}}: a model\'s full name, one model for each family such as opus, and an effort of {", ".join(EFFORTS[:-1])} or {EFFORTS[-1]}'
def project_ladder_file(directory: str | None, home: pathlib.Path, shipped: pathlib.Path = SHIPPED) -> pathlib.Path | Failure:
"""The file that holds the ladder of the project whose checkout holds directory, else the current directory: the file NAME in its config's folder under home, or shipped where that folder holds none. Also shipped where no config names a checkout there, or git fails there. A Failure where the project's config is faulty or cannot be read, since its folder may hold the ladder."""
config = located(directory, home)
if isinstance(config, Unnamed):
return shipped
if isinstance(config, Failure):
return config
own = config.folder / NAME
return own if own.exists() else shipped
def project_ladder(directory: str | None, home: pathlib.Path, shipped: pathlib.Path = SHIPPED) -> Ladder | Failure:
"""The ladder project_ladder_file's file holds. A Failure where that file holds a fault too: the shipped ladder never stands in for a project's own, since work routed on it could run on a model the project cannot reach."""
file = project_ladder_file(directory, home, shipped)
return file if isinstance(file, Failure) else read_ladder(file)
def read_ladder(file: pathlib.Path) -> Ladder | Failure:
"""The ladder a file holds; a Failure naming the file and its fault where it holds none."""
try:
held = json.loads(file.read_text(encoding="utf-8"))
except (OSError, UnicodeDecodeError, ValueError) as failure:
# An OSError's own text names the file again.
return Failure(f"cannot read the routing ladder {file}: {failure.strerror if isinstance(failure, OSError) else failure}. The routing ladder is {SHAPE}")
faults = faults_of(held)
if faults:
return Failure(f"{file}: {'; '.join(faults)}. The routing ladder is {SHAPE}")
return Ladder(tuple(Rung(rung["model"], rung["effort"]) for rung in held))
def faults_of(held: object) -> list[str]:
"""What keeps held from being a ladder: it is no list or an empty one, or else each rung, by its number from 1, that is misspelt, repeats one above it, or names a second model of a family."""
if not isinstance(held, list) or not held:
return ["it holds no list of rungs"]
faults = []
# The first rung of each family, by number: the Agent tool launches by family name, which Ladder.from_agent reads back as that family's one model.
families: dict[str, tuple[int, str]] = {}
for number, rung in enumerate(held, 1):
if not well_formed(rung):
faults.append(f"rung {number} is {json.dumps(rung)}")
continue
family = Rung(rung["model"]).family()
first, model = families.setdefault(family, (number, rung["model"]))
if rung in held[:number - 1]:
faults.append(f"rung {number} repeats rung {held.index(rung) + 1}")
elif model != rung["model"]:
faults.append(f"rung {number} names a second model of the family {family}, after rung {first}")
return faults
def well_formed(rung: object) -> bool:
return isinstance(rung, dict) and rung.keys() == {"model", "effort"} and isinstance(rung["model"], str) and bool(MODEL.fullmatch(rung["model"])) and rung["effort"] in EFFORTS
+7 -7
View File
@@ -2,7 +2,7 @@
import dataclasses
from model_routing.route import HIGHEST_ESCAPE_AND_IMPACT, Route
from model_routing.ladder import review_rung, reviewers_rung, Rung
from model_routing.ladder import Ladder, Rung
@dataclasses.dataclass(frozen=True)
@@ -17,12 +17,12 @@ class ReviewChoice:
higher: dict[Rung, int]
def chosen(project: Rung, route: Route) -> ReviewChoice:
"""The rung each kind of review runs on for a chunk whose route is route, on a project whose rung is project."""
reviewers = reviewers_rung(project, route.rung, route.reviewed_on())
def chosen(ladder: Ladder, project: Rung, route: Route) -> ReviewChoice:
"""The rung each kind of review runs on for a chunk whose route is route, on a project whose rung on ladder is project."""
reviewers = ladder.reviewers_rung(project, route.rung, route.reviewed_on())
higher: dict[Rung, int] = {}
for escape_and_impact in range(route.reviewed_on() + 1, HIGHEST_ESCAPE_AND_IMPACT + 1):
if (rung := reviewers_rung(project, route.rung, escape_and_impact)) != reviewers:
if (rung := ladder.reviewers_rung(project, route.rung, escape_and_impact)) != reviewers:
higher.setdefault(rung, escape_and_impact)
markdown_only = reviewers_rung(project, route.rung, route.reviewed_on(), markdown_only=True)
return ReviewChoice(reviewers, markdown_only, review_rung(project, route.rung, route.reviewed_on(), "seat"), review_rung(project, route.rung, route.reviewed_on(), "security"), higher)
markdown_only = ladder.reviewers_rung(project, route.rung, route.reviewed_on(), markdown_only=True)
return ReviewChoice(reviewers, markdown_only, ladder.review_rung(project, route.rung, route.reviewed_on(), "seat"), ladder.review_rung(project, route.rung, route.reviewed_on(), "security"), higher)
+9
View File
@@ -0,0 +1,9 @@
[
{"model": "claude-sonnet-5-5", "effort": "high"},
{"model": "claude-opus-5-5", "effort": "medium"},
{"model": "claude-fable-5-2", "effort": "low"},
{"model": "claude-fable-5-2", "effort": "medium"},
{"model": "claude-opus-5-5", "effort": "xhigh"},
{"model": "claude-fable-5-2", "effort": "high"},
{"model": "claude-fable-5-2", "effort": "max"}
]
+42 -41
View File
@@ -4,58 +4,58 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from model_routing.ladder import highest, LADDER, lowest_worker_rung, planning_rung, project_rung, review_floor, review_rung, Rung, stepped_up, worker_rung, WORKER_STEPS
from release_plan.todo_table import LEVELS
from model_routing.ladder_file import read_ladder, SHIPPED
from review_rules.review_passes import REVIEWERS
from model_routing.ladder import Rung, WORKER_STEPS
# The ladder this setup ships, whose rungs the tests below name.
LADDER = read_ladder(SHIPPED)
OPUS = Rung("claude-opus-5-5", "medium")
FABLE_LOW = Rung("claude-fable-5-2", "low")
class Ladder(unittest.TestCase):
def test_holds_each_rung_once_since_a_rung_s_position_sets_every_step(self):
self.assertEqual(len(set(LADDER)), len(LADDER))
def test_puts_a_project_on_its_models_cheapest_rung_and_none_off_the_ladder(self):
self.assertEqual(project_rung("claude-opus-5-5"), OPUS)
self.assertEqual(project_rung("claude-sonnet-5-5"), Rung("claude-sonnet-5-5", "high"))
self.assertEqual(project_rung("claude-fable-5-2"), FABLE_LOW)
self.assertIsNone(project_rung("claude-opus-5"))
self.assertIsNone(project_rung("opus"))
self.assertEqual(LADDER.project_rung("claude-opus-5-5"), OPUS)
self.assertEqual(LADDER.project_rung("claude-sonnet-5-5"), Rung("claude-sonnet-5-5", "high"))
self.assertEqual(LADDER.project_rung("claude-fable-5-2"), FABLE_LOW)
self.assertIsNone(LADDER.project_rung("claude-opus-5"))
self.assertIsNone(LADDER.project_rung("opus"))
def test_steps_a_workers_rung_by_its_l_from_the_projects_rung(self):
position = LADDER.index(OPUS)
self.assertEqual([LADDER.index(worker_rung(OPUS, likelihood)) - position for likelihood in range(1, 5)], [-1, -1, 0, 1])
position = LADDER.rungs.index(OPUS)
self.assertEqual([LADDER.rungs.index(LADDER.worker_rung(OPUS, likelihood)) - position for likelihood in range(1, 5)], [-1, -1, 0, 1])
def test_steps_a_review_up_by_its_e_plus_i_from_the_projects_rung_and_never_down(self):
position = LADDER.index(OPUS)
self.assertEqual([LADDER.index(review_floor(OPUS, total)) - position for total in range(2, 9)], [0, 0, 0, 1, 2, 3, 4])
self.assertEqual(review_floor(OPUS, 0), OPUS)
position = LADDER.rungs.index(OPUS)
self.assertEqual([LADDER.rungs.index(LADDER.review_floor(OPUS, total)) - position for total in range(2, 9)], [0, 0, 0, 1, 2, 3, 4])
self.assertEqual(LADDER.review_floor(OPUS, 0), OPUS)
def test_a_step_past_either_end_stops_there(self):
self.assertEqual(worker_rung(OPUS, 1), Rung("claude-sonnet-5-5", "high"))
self.assertEqual(worker_rung(LADDER[0], 1), LADDER[0])
self.assertEqual(review_floor(Rung("claude-opus-5-5", "xhigh"), 8), LADDER[-1])
self.assertEqual(stepped_up(LADDER[-1]), LADDER[-1])
self.assertEqual(stepped_up(OPUS), FABLE_LOW)
self.assertEqual(LADDER.worker_rung(OPUS, 1), Rung("claude-sonnet-5-5", "high"))
self.assertEqual(LADDER.worker_rung(LADDER.rungs[0], 1), LADDER.rungs[0])
self.assertEqual(LADDER.review_floor(Rung("claude-opus-5-5", "xhigh"), 8), LADDER.rungs[-1])
self.assertEqual(LADDER.stepped_up(LADDER.rungs[-1]), LADDER.rungs[-1])
self.assertEqual(LADDER.stepped_up(OPUS), FABLE_LOW)
def test_steps_a_worker_for_every_level_on_ls_scale(self):
self.assertEqual(set(WORKER_STEPS), set(range(1, LEVELS["L"] + 1)))
def test_names_the_lowest_rung_any_l_routes_a_worker_to(self):
self.assertEqual(lowest_worker_rung(OPUS), Rung("claude-sonnet-5-5", "high"))
self.assertEqual(LADDER.lowest_worker_rung(OPUS), Rung("claude-sonnet-5-5", "high"))
def test_plans_on_the_rung_l_picks_but_never_below_the_projects(self):
self.assertEqual(planning_rung(OPUS, 1), OPUS)
self.assertEqual(planning_rung(OPUS, 4), FABLE_LOW)
self.assertEqual(LADDER.planning_rung(OPUS, 1), OPUS)
self.assertEqual(LADDER.planning_rung(OPUS, 4), FABLE_LOW)
def test_names_each_rung_by_a_family_the_agent_tool_takes(self):
self.assertEqual({rung.agent_args().split(",")[0] for rung in LADDER}, {"model sonnet", "model opus", "model fable"})
self.assertEqual({rung.agent_args().split(",")[0] for rung in LADDER.rungs}, {"model sonnet", "model opus", "model fable"})
def test_ranks_a_rung_off_the_ladder_below_every_rung_on_it(self):
self.assertEqual(highest(OPUS, LADDER[-1], LADDER[0]), LADDER[-1])
self.assertEqual(highest(Rung("claude-opus-5-5", "low"), LADDER[0]), LADDER[0])
self.assertEqual(stepped_up(Rung("claude-opus-5-5", "low")), LADDER[0])
self.assertEqual(LADDER.highest(OPUS, LADDER.rungs[-1], LADDER.rungs[0]), LADDER.rungs[-1])
self.assertEqual(LADDER.highest(Rung("claude-opus-5-5", "low"), LADDER.rungs[0]), LADDER.rungs[0])
self.assertEqual(LADDER.stepped_up(Rung("claude-opus-5-5", "low")), LADDER.rungs[0])
def test_passes_the_effort_only_where_the_rung_names_one(self):
self.assertEqual(Rung("claude-opus-5-5", "high").flags(), ["--model", "claude-opus-5-5", "--effort", "high"])
@@ -64,7 +64,7 @@ class Ladder(unittest.TestCase):
self.assertEqual(str(Rung("worker-model")), "worker-model")
def test_parses_what_str_wrote_for_each_rung_on_the_ladder(self):
for rung in LADDER:
for rung in LADDER.rungs:
with self.subTest(rung=rung):
self.assertEqual(Rung.parse(str(rung)), rung)
@@ -77,31 +77,32 @@ class Ladder(unittest.TestCase):
self.assertIsNone(Rung.parse(text))
def test_reads_the_agent_tools_words_back_as_a_rung(self):
for rung in LADDER:
for rung in LADDER.rungs:
with self.subTest(rung=rung):
model, effort = (part.split(" ")[1] for part in rung.agent_args().split(", "))
self.assertEqual(Rung.from_agent(model, effort), rung)
self.assertEqual(LADDER.from_agent(model, effort), rung)
def test_reads_a_family_named_without_an_effort_as_its_cheapest_rung(self):
self.assertEqual(Rung.from_agent("opus", ""), OPUS)
self.assertEqual(Rung.from_agent("sonnet", ""), Rung("claude-sonnet-5-5", "high"))
self.assertEqual(LADDER.from_agent("opus", ""), OPUS)
self.assertEqual(LADDER.from_agent("sonnet", ""), Rung("claude-sonnet-5-5", "high"))
def test_reads_an_unknown_family_or_an_effort_off_the_ladder_as_a_rung_off_it(self):
for model, effort in (("gpt", "high"), ("gpt", ""), ("opus", "low"), ("opus", "high"), ("haiku", "bogus")):
with self.subTest(model=model, effort=effort):
self.assertNotIn(Rung.from_agent(model, effort), LADDER)
self.assertEqual(Rung.from_agent("opus", "low"), Rung("claude-opus-5-5", "low"))
self.assertNotIn(LADDER.from_agent(model, effort), LADDER.rungs)
self.assertEqual(LADDER.from_agent("opus", "low"), Rung("claude-opus-5-5", "low"))
self.assertEqual(LADDER.from_agent("gpt", "high"), Rung("gpt", "high"))
def test_puts_reviewers_on_the_highest_of_the_projects_rung_the_workers_and_the_one_e_plus_i_picks(self):
sonnet, fable = LADDER[0], LADDER[-1]
self.assertEqual(review_rung(OPUS, sonnet, 4, "stability"), OPUS)
self.assertEqual(review_rung(OPUS, sonnet, 5, "stability"), FABLE_LOW)
self.assertEqual(review_rung(OPUS, fable, 5, "stability"), fable)
self.assertEqual(review_rung(OPUS, FABLE_LOW, 7, "stability"), Rung("claude-opus-5-5", "xhigh"))
sonnet, fable = LADDER.rungs[0], LADDER.rungs[-1]
self.assertEqual(LADDER.review_rung(OPUS, sonnet, 4, "stability"), OPUS)
self.assertEqual(LADDER.review_rung(OPUS, sonnet, 5, "stability"), FABLE_LOW)
self.assertEqual(LADDER.review_rung(OPUS, fable, 5, "stability"), fable)
self.assertEqual(LADDER.review_rung(OPUS, FABLE_LOW, 7, "stability"), Rung("claude-opus-5-5", "xhigh"))
def test_keeps_the_seats_and_the_security_pass_on_the_projects_rung_whatever_the_worker_or_e_plus_i(self):
self.assertEqual([review_rung(OPUS, LADDER[-1], 8, kind) for kind in (*REVIEWERS, "seat", "security")], [LADDER[-1]] * len(REVIEWERS) + [OPUS, OPUS])
self.assertEqual([LADDER.review_rung(OPUS, LADDER.rungs[-1], 8, kind) for kind in (*REVIEWERS, "seat", "security")], [LADDER.rungs[-1]] * len(REVIEWERS) + [OPUS, OPUS])
def test_puts_every_review_of_a_branch_changing_only_markdown_no_agent_follows_on_the_projects_rung(self):
self.assertEqual([review_rung(OPUS, LADDER[-1], 8, kind, markdown_only=True) for kind in (*REVIEWERS, "seat", "security")], [OPUS] * (len(REVIEWERS) + 2))
self.assertEqual(review_rung(OPUS, LADDER[0], 4, "stability", markdown_only=True), OPUS)
self.assertEqual([LADDER.review_rung(OPUS, LADDER.rungs[-1], 8, kind, markdown_only=True) for kind in (*REVIEWERS, "seat", "security")], [OPUS] * (len(REVIEWERS) + 2))
self.assertEqual(LADDER.review_rung(OPUS, LADDER.rungs[0], 4, "stability", markdown_only=True), OPUS)
+147
View File
@@ -0,0 +1,147 @@
import pathlib
import subprocess
import sys
import tempfile
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from failure import Failure
from test_env import isolated_env
from model_routing.ladder import Ladder, Rung
from model_routing.ladder_file import NAME, project_ladder, project_ladder_file, read_ladder, SHIPPED
from project_config.test_project_config import write_config
FABLE_ONLY = '[\n\t{"model": "claude-fable-5-2", "effort": "low"},\n\t{"model": "claude-fable-5-2", "effort": "max"}\n]\n'
FABLE_LADDER = Ladder((Rung("claude-fable-5-2", "low"), Rung("claude-fable-5-2", "max")))
OPUS = '{"model": "claude-opus-5-5", "effort": "medium"}'
class LadderCase(unittest.TestCase):
def setUp(self) -> None:
made = tempfile.TemporaryDirectory()
self.addCleanup(made.cleanup)
self.home = pathlib.Path(made.name).resolve()
self.shipped = self.home / "shipped.json"
self.shipped.write_text(f"[{OPUS}]", encoding="utf-8")
def checkout(self, name: str = "acme") -> pathlib.Path:
"""A git checkout under the home, holding one commit, that no config names yet."""
checkout = self.home / "code" / name
checkout.mkdir(parents=True)
self.git(checkout, "init", "--quiet", "-b", "main")
self.git(checkout, "commit", "--quiet", "--allow-empty", "-m", "base")
return checkout
def git(self, cwd: pathlib.Path, *args: str) -> None:
subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@example.com", *args], capture_output=True, check=True, cwd=cwd, env=isolated_env())
class ReadLadder(LadderCase):
def reason(self, text: str) -> str:
file = self.home / NAME
file.write_text(text, encoding="utf-8")
read = read_ladder(file)
assert isinstance(read, Failure), read
return read.reason
def test_the_ladder_this_setup_ships_reads_as_a_ladder(self):
self.assertIsInstance(read_ladder(SHIPPED), Ladder)
def test_reads_the_rungs_in_the_files_order(self):
file = self.home / NAME
file.write_text(FABLE_ONLY, encoding="utf-8")
self.assertEqual(read_ladder(file), FABLE_LADDER)
def test_a_file_that_is_missing_or_no_json_fails_naming_the_file_and_the_shape(self):
file = self.home / NAME
missing = read_ladder(file)
self.assertIsInstance(missing, Failure)
self.assertTrue(missing.reason.startswith(f"cannot read the routing ladder {file}: No such file or directory. The routing ladder is a JSON list of rungs"), missing.reason)
# The comma a reader leaves after the last rung when dropping one.
trailing = self.reason(f"[\n\t{OPUS},\n]\n")
self.assertIn(f"cannot read the routing ladder {file}: ", trailing)
self.assertIn("line 2", trailing)
self.assertTrue(trailing.endswith('. The routing ladder is a JSON list of rungs, least competent first, each as {"model": "claude-opus-5-5", "effort": "medium"}: a model\'s full name, one model for each family such as opus, and an effort of low, medium, high, xhigh or max'), trailing)
file.write_bytes(b"\xff")
self.assertIn(f"cannot read the routing ladder {file}: ", read_ladder(file).reason)
def test_a_file_holding_anything_but_a_list_of_rungs_fails(self):
for text in (OPUS, "[]", '"claude-opus-5-5 at medium effort"', "null"):
with self.subTest(text=text):
self.assertEqual(self.reason(text).split(". ")[0], f"{self.home / NAME}: it holds no list of rungs")
def test_names_each_misspelt_rung_by_its_number(self):
misspelt = {
"an effort off the scale": '{"model": "claude-opus-5-5", "effort": "ultra"}',
"no effort": '{"model": "claude-opus-5-5"}',
"an empty effort": '{"model": "claude-opus-5-5", "effort": ""}',
"a key too many": '{"model": "claude-opus-5-5", "effort": "low", "note": "x"}',
"a model that names no family": '{"model": "opus", "effort": "low"}',
"a model with a space": '{"model": "claude-opus 5-5", "effort": "low"}',
"a model that is no text": '{"model": 5, "effort": "low"}',
"a pair": '["claude-opus-5-5", "low"]',
"the rung as a tool prints it": '"claude-opus-5-5 at low effort"',
}
for what, rung in misspelt.items():
with self.subTest(what):
self.assertEqual(self.reason(f"[{OPUS}, {rung}]").split(". ")[0], f"{self.home / NAME}: rung 2 is {rung}")
self.assertIn("rung 1 is 1; rung 3 is 3. The routing ladder is a JSON list of rungs, least competent first", self.reason(f"[1, {OPUS}, 3]"))
def test_a_rung_held_twice_fails_naming_both_since_a_rungs_position_sets_every_step(self):
low = '{"model": "claude-opus-5-5", "effort": "low"}'
self.assertEqual(self.reason(f"[{low}, {OPUS}, {low}]").split(". ")[0], f"{self.home / NAME}: rung 3 repeats rung 1")
def test_a_second_model_of_one_family_fails_naming_the_familys_first_rung_since_a_subagent_launches_by_family(self):
older, newer = '{"model": "claude-fable-5-1", "effort": "max"}', '{"model": "claude-fable-5-2", "effort": "low"}'
self.assertEqual(self.reason(f"[{OPUS}, {older}, {newer}]").split(". ")[0], f"{self.home / NAME}: rung 3 names a second model of the family fable, after rung 2")
both = self.reason(f'[{older}, {newer}, {{"model": "claude-fable-5-2", "effort": "high"}}]').split(". ")[0]
self.assertEqual(both, f"{self.home / NAME}: rung 2 names a second model of the family fable, after rung 1; rung 3 names a second model of the family fable, after rung 1")
file = self.home / NAME
file.write_text(f'[{OPUS}, {newer}, {{"model": "claude-opus-5-5", "effort": "xhigh"}}, {{"model": "claude-fable-5-2", "effort": "max"}}]', encoding="utf-8")
self.assertIsInstance(read_ladder(file), Ladder, "one model at several efforts, between another family's rungs, is no fault")
class ProjectLadder(LadderCase):
def test_a_project_runs_on_the_ladder_its_configs_folder_holds_from_a_worktree_too(self):
checkout = self.checkout()
(write_config(self.home, checkout) / NAME).write_text(FABLE_ONLY, encoding="utf-8")
self.assertEqual(project_ladder(str(checkout), self.home, self.shipped), FABLE_LADDER)
worktree = self.home / "code" / "acme-item-7"
self.git(checkout, "worktree", "add", "--quiet", str(worktree), "-b", "item-7")
self.assertEqual(project_ladder(str(worktree), self.home, self.shipped), FABLE_LADDER)
def test_names_the_file_it_reads_the_projects_own_or_else_the_shipped_one(self):
checkout = self.checkout()
folder = write_config(self.home, checkout)
self.assertEqual(project_ladder_file(str(checkout), self.home, self.shipped), self.shipped)
(folder / NAME).write_text(FABLE_ONLY, encoding="utf-8")
self.assertEqual(project_ladder_file(str(checkout), self.home, self.shipped), folder / NAME)
self.assertEqual(project_ladder_file(str(self.home), self.home), SHIPPED, "outside a checkout, the ladder this setup ships")
def test_another_projects_ladder_is_not_read(self):
checkout, other = self.checkout(), self.checkout("other")
write_config(self.home, checkout)
(write_config(self.home, other) / NAME).write_text(FABLE_ONLY, encoding="utf-8")
self.assertEqual(project_ladder(str(checkout), self.home, self.shipped), Ladder((Rung("claude-opus-5-5", "medium"),)))
def test_a_checkout_no_config_names_and_a_folder_outside_any_checkout_run_on_the_shipped_ladder(self):
shipped = Ladder((Rung("claude-opus-5-5", "medium"),))
self.assertEqual(project_ladder(str(self.checkout()), self.home, self.shipped), shipped)
self.assertEqual(project_ladder(str(self.home), self.home, self.shipped), shipped)
def test_a_faulty_ladder_of_the_projects_own_fails_and_the_shipped_one_does_not_stand_in(self):
checkout = self.checkout()
own = write_config(self.home, checkout) / NAME
own.write_text("[]", encoding="utf-8")
self.assertEqual(project_ladder(str(checkout), self.home, self.shipped).reason.split(". ")[0], f"{own}: it holds no list of rungs")
def test_a_faulty_config_fails_since_its_folder_may_hold_the_ladder(self):
checkout = self.checkout()
config = write_config(self.home, checkout) / "config.toml"
config.write_text(config.read_text(encoding="utf-8") + 'readme = "checkout:README.md"\n', encoding="utf-8")
self.assertIn("`readme` is not a setting", project_ladder(str(checkout), self.home, self.shipped).reason)
if __name__ == "__main__":
unittest.main()
+2 -2
View File
@@ -4,13 +4,13 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from model_routing.ladder import LADDER
from model_routing.prices import PRICES
from model_routing.ladder_file import read_ladder, SHIPPED
class Prices(unittest.TestCase):
def test_every_model_on_the_ladder_has_a_price_since_a_model_without_one_is_left_out_of_every_figure(self):
self.assertEqual(sorted({rung.model for rung in LADDER} - set(PRICES)), [])
self.assertEqual(sorted({rung.model for rung in read_ladder(SHIPPED).rungs} - set(PRICES)), [])
if __name__ == "__main__":
+4 -2
View File
@@ -1,17 +1,19 @@
import unittest
from model_routing.review_choice import chosen
from model_routing.ladder_file import read_ladder, SHIPPED
from model_routing.route import Route
from model_routing.ladder import Rung
LADDER = read_ladder(SHIPPED)
OPUS = Rung("claude-opus-5-5", "medium")
FABLE = Rung("claude-fable-5-2", "max")
class Chosen(unittest.TestCase):
def test_names_no_higher_rung_on_the_top_one(self):
self.assertEqual(chosen(OPUS, Route(FABLE, 3, 4, 5)).higher, {})
self.assertEqual(chosen(LADDER, OPUS, Route(FABLE, 3, 4, 5)).higher, {})
def test_reviews_a_branch_changing_only_markdown_on_the_projects_rung_and_the_seats_and_security_pass_there_always(self):
choice = chosen(OPUS, Route(FABLE, 3, 4, 5))
choice = chosen(LADDER, OPUS, Route(FABLE, 3, 4, 5))
self.assertEqual((choice.reviewers, choice.markdown_only, choice.seat, choice.security), (FABLE, OPUS, OPUS, OPUS))
+22 -8
View File
@@ -1,8 +1,12 @@
import unittest
from model_routing.worker_rungs import environment, handed
from model_routing.worker_rungs import environment, handed, hands_rungs
from model_routing.ladder import Ladder, Rung
from model_routing.ladder_file import read_ladder, SHIPPED
from model_routing.route import Route
from model_routing.ladder import Rung
LADDER = read_ladder(SHIPPED)
class Environment(unittest.TestCase):
@@ -18,13 +22,23 @@ class Environment(unittest.TestCase):
self.assertEqual(environment(None, Route(self.WORKER)), {"LOOP_CLAUDE_PROJECT_RUNG": "", "LOOP_CLAUDE_WORKER_RUNG": "claude-sonnet-5-5 at high effort", "LOOP_CLAUDE_ESCAPE_AND_IMPACT": "0"})
def test_handed_reads_back_what_environment_named(self):
self.assertEqual(handed(environment(self.PROJECT, Route(self.WORKER, 3, 1, 5))), (self.PROJECT, self.WORKER, 5))
self.assertEqual(handed(environment(None, Route(self.WORKER))), (None, self.WORKER, 0))
self.assertEqual(handed(environment(self.PROJECT, Route(self.WORKER, 3, 1, 5)), LADDER), (self.PROJECT, self.WORKER, 5))
self.assertEqual(handed(environment(None, Route(self.WORKER)), LADDER), (None, self.WORKER, 0))
def test_a_rung_off_the_ladder_given_reads_as_none(self):
fable_only = Ladder((Rung("claude-fable-5-2", "low"),))
self.assertEqual(handed(environment(self.PROJECT, Route(Rung("claude-fable-5-2", "low"))), fable_only), (None, Rung("claude-fable-5-2", "low"), 0))
def test_tells_whether_both_rungs_are_named_before_any_ladder_is_read(self):
self.assertTrue(hands_rungs(environment(self.PROJECT, Route(self.WORKER))))
self.assertFalse(hands_rungs(environment(None, Route(self.WORKER))))
self.assertFalse(hands_rungs({"LOOP_CLAUDE_PROJECT_RUNG": "claude-opus-5-5 at medium effort"}))
self.assertFalse(hands_rungs({}))
def test_a_missing_or_unknown_rung_reads_as_none_and_a_missing_or_unknown_e_plus_i_as_0(self):
self.assertEqual(handed({}), (None, None, 0))
self.assertEqual(handed({"LOOP_CLAUDE_WORKER_RUNG": "claude-haiku-5-5 bogus"}), (None, None, 0))
self.assertEqual(handed({"LOOP_CLAUDE_WORKER_RUNG": "claude-haiku-5-5 at bogus effort"}), (None, None, 0))
self.assertEqual(handed({}, LADDER), (None, None, 0))
self.assertEqual(handed({"LOOP_CLAUDE_WORKER_RUNG": "claude-haiku-5-5 bogus"}, LADDER), (None, None, 0))
self.assertEqual(handed({"LOOP_CLAUDE_WORKER_RUNG": "claude-haiku-5-5 at bogus effort"}, LADDER), (None, None, 0))
for bogus in ("", "five", "-1", "5.0", "²"):
with self.subTest(bogus=bogus):
self.assertEqual(handed({"LOOP_CLAUDE_ESCAPE_AND_IMPACT": bogus})[2], 0)
self.assertEqual(handed({"LOOP_CLAUDE_ESCAPE_AND_IMPACT": bogus}, LADDER)[2], 0)
+11 -6
View File
@@ -3,7 +3,7 @@
loop-claude sets these variables for its worker and for the claude an interrupt resumes; a human's shell does not, and rule-hook then checks no review launch."""
import typing
from model_routing.ladder import LADDER, Rung
from model_routing.ladder import Ladder, Rung
from model_routing.route import Route
PROJECT_RUNG = "LOOP_CLAUDE_PROJECT_RUNG"
@@ -17,12 +17,17 @@ def environment(project: Rung | None, route: Route) -> dict[str, str]:
return {PROJECT_RUNG: str(project) if project else "", WORKER_RUNG: str(route.rung), ESCAPE_AND_IMPACT: str(route.reviewed_on())}
def handed(environ: typing.Mapping[str, str]) -> tuple[Rung | None, Rung | None, int]:
"""The project's and the worker's rungs, each None when unset or not on the ladder, and the reviews' E + I, 0 when unset or not a whole number. An older loop-claude hands no E + I, and 0 steps no review up."""
def hands_rungs(environ: typing.Mapping[str, str]) -> bool:
"""Whether the environment names a project's and a worker's rung, as loop-claude sets them for a project on its ladder. Where it names neither, no review launch is checked, so the caller skips reading the project's ladder."""
return bool(environ.get(PROJECT_RUNG) and environ.get(WORKER_RUNG))
def handed(environ: typing.Mapping[str, str], ladder: Ladder) -> tuple[Rung | None, Rung | None, int]:
"""The project's and the worker's rungs, each None when unset or not on ladder, and the reviews' E + I, 0 when unset or not a whole number. ladder is the project's. An older loop-claude hands no E + I, and 0 steps no review up."""
escape_and_impact = environ.get(ESCAPE_AND_IMPACT, "")
return on_the_ladder(environ.get(PROJECT_RUNG)), on_the_ladder(environ.get(WORKER_RUNG)), int(escape_and_impact) if escape_and_impact.isdecimal() else 0
return on_the_ladder(environ.get(PROJECT_RUNG), ladder), on_the_ladder(environ.get(WORKER_RUNG), ladder), int(escape_and_impact) if escape_and_impact.isdecimal() else 0
def on_the_ladder(value: str | None) -> Rung | None:
def on_the_ladder(value: str | None, ladder: Ladder) -> Rung | None:
rung = Rung.parse(value or "")
return rung if rung in LADDER else None
return rung if rung in ladder.rungs else None
-1
View File
@@ -350,7 +350,6 @@ def item(issue: Issue, project: str, ids: set[int]) -> Item | Failure:
"""The item an issue holds, without its detail. It is blocked by each of its blockers among ids, the plan's items: a blocker that is done or lies outside the epic doesn't make the item wait."""
release = earliest_release(issue.fix_versions)
if release is None:
# Until a project can tie its releases to something other than semver versions, an item with no release cannot be placed in the plan.
return Failure(f"{issue.key} names no Fix Version that is a semver version, such as 1.2.0; set one in Jira")
scored = scores(issue.key, issue.scores)
if isinstance(scored, Failure):
+5 -5
View File
@@ -59,11 +59,6 @@ PAGE_SPELLING = '"confluence:https://<site>/wiki/spaces/<space>/pages/<page ID>"
OUTSIDE = "a path that starts with / or ~/ and lies outside the checkout and the config's folder, so that no git remote receives the credentials"
@dataclasses.dataclass(frozen=True)
class Unnamed(Failure):
"""No config names a checkout here: none names the one asked for, or git finds no checkout. A reader of titles takes them bare there, as in a third party's clone; a config that is faulty or cannot be read is a plain Failure."""
@dataclasses.dataclass(frozen=True)
class Epic:
"""A Jira Cloud epic: site is its site's address, such as https://acme.atlassian.net, and key its issue key, such as ABC-12."""
@@ -91,6 +86,11 @@ class Page:
spelling: str
@dataclasses.dataclass(frozen=True)
class Unnamed(Failure):
"""No config names a checkout here: none names the one asked for, or git fails there, as outside a checkout. A config that is faulty or cannot be read is a plain Failure."""
@dataclasses.dataclass(frozen=True)
class ProjectConfig:
"""folder is `~/.claude-projects/<key>`, top is the worktree that asked, and paths holds each of SETTINGS as an absolute path, except three kinds that pages or epics hold instead: `plan` and `goals-and-audience` where they are kept in Jira, and a record kept on a Confluence page."""
+6 -1
View File
@@ -12,7 +12,7 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from project_config.settings import env_files, Epic, Finish, held, load, NOTIFIERS, OUTSIDE, Page, ProjectConfig, SETTINGS, Unnamed
from failure import Failure
from test_env import isolated_env
from project_config.main import title_templates
from project_config.main import located, title_templates
from project_config.templates import Titles
TOOL = pathlib.Path(__file__).resolve().parents[1] / "project-config"
@@ -241,6 +241,11 @@ class LoadTest(ConfigCase):
self.assertIn(str(self.checkout), reason)
self.assertIn("~/.claude-projects/<key>/config.toml", reason)
def test_a_folder_that_is_no_checkout_fails_as_unnamed_with_gits_reason(self) -> None:
outside = located(str(self.checkout), self.home)
self.assertIsInstance(outside, Unnamed)
self.assertIn("not a git repository", outside.reason)
def test_every_missing_setting_is_named(self) -> None:
kept = "".join(line + "\n" for line in CLIENT.splitlines() if not line.startswith(("plan", "changelog", "principles", "standards")))
self.write("acme", kept)
+34 -5
View File
@@ -10,8 +10,10 @@ save refuses them: edit the epic in Jira.
open prints the path of a file holding the record's text, and nothing else. Read and edit that
file. Where the record is kept as a file, the path is that file. Where it is kept elsewhere, the
path is a copy under ~/.local/state/project-record/<key>/, written afresh with the record as it
stands, so open it again before each edit. A record that doesn't exist yet has no file at the path:
path is a copy under ~/.local/state/project-record/<key>/<worktree>/, a folder named for the
worktree that ran open, so two worktrees of one project don't share a copy. The copy is written
afresh with the record as it stands, so open it again before each edit. open also removes the
folders of worktrees git no longer lists. A record that doesn't exist yet has no file at the path:
create it there.
save stores the file's text in the record, and prints one line saying so. Where the record is kept
@@ -24,17 +26,20 @@ writes the copy afresh.
Exit 2 on bad arguments, and 1, saying why, on any other failure.
"""
import hashlib
import pathlib
import shutil
import sys
from failure import Failure
from record_store.stores import FileStore, goals_store, local_file, RECORDS, RecordStore, store, stored
from git_cli.git_repo import git, Git
from project_config.main import located
from project_config.settings import ProjectConfig
# Not git's verbs, such as checkout and commit: those read as acting on the repo.
COMMANDS = ("open", "save")
# Where the copy of a record kept outside files goes, under the user's home, in a folder per project.
# Where the copy of a record kept outside files goes, under the user's home, in a folder per project and worktree.
COPIES = ".local/state/project-record"
# The goals file opens like a record, though it is a setting of its own.
GOALS = "goals-and-audience"
@@ -49,7 +54,7 @@ def main(argv: list[str]) -> int:
return 2
home = pathlib.Path.home()
config = located(None, home)
done = config if isinstance(config, Failure) else act(argv[0], *opened(config, argv[1], home))
done = config if isinstance(config, Failure) else performed(config, argv[0], argv[1], home)
if isinstance(done, Failure):
print(f"project-record: {done.reason}", file=sys.stderr)
return 1
@@ -57,12 +62,36 @@ def main(argv: list[str]) -> int:
return 0
def performed(config: ProjectConfig, command: str, name: str, home: pathlib.Path, run: Git = git) -> str | Failure:
"""What command, one of COMMANDS, prints for the record called name. An open also prunes the copies of removed worktrees."""
if command == "open":
pruned(config, home, run)
return act(command, *opened(config, name, home))
def opened(config: ProjectConfig, name: str, home: pathlib.Path) -> tuple[RecordStore, pathlib.Path]:
"""The store of the record called name, and the copy it gets where it isn't kept as a file. A store that keeps the version it read, for a later save, keeps it beside the copy."""
copy = home / COPIES / config.key / f"{name}.md"
copy = home / COPIES / config.key / worktree_folder(config.top) / f"{name}.md"
return (goals_store(config) if name == GOALS else store(config, name, copy.with_suffix(".version"))), copy
def worktree_folder(top: pathlib.Path) -> str:
"""The name of the folder that holds the copies of the worktree at top: the worktree's own name, for a reader, and a hash of its path, since two worktrees in different folders may share a name."""
return f"{top.name}-{hashlib.sha256(str(top).encode()).hexdigest()[:8]}"
def pruned(config: ProjectConfig, home: pathlib.Path, run: Git = git) -> None:
"""Remove the copies of the worktrees git no longer lists, so the folders don't pile up one per chunk. Best effort: a folder that stays only takes disk, and where git can't list the worktrees nothing is removed."""
listed = run("worktree", "list", "--porcelain")
folders = home / COPIES / config.key
if isinstance(listed, Failure) or not folders.is_dir():
return
worktrees = [config.top, *(pathlib.Path(line.removeprefix("worktree ")) for line in listed.splitlines() if line.startswith("worktree "))]
kept = {worktree_folder(worktree) for worktree in worktrees}
for stale in (folder for folder in folders.iterdir() if folder.is_dir() and folder.name not in kept):
shutil.rmtree(stale, ignore_errors=True)
def act(command: str, record: RecordStore, copy: pathlib.Path) -> str | Failure:
"""What command, one of COMMANDS, prints for record. copy is where a record kept outside files gets its file."""
if command == "open":
+80 -7
View File
@@ -17,19 +17,92 @@ from project_config.settings import Page, ProjectConfig
TOOL = pathlib.Path(__file__).resolve().parents[1] / "project-record"
COPIES = pathlib.Path("/home/me/.local/state/project-record/acme")
def worktree_config(top: str, **kept: Page) -> ProjectConfig:
return ProjectConfig("acme", pathlib.Path("/home/me/.claude-projects/acme"), pathlib.Path(top), {"goals-and-audience": pathlib.Path(top, "README.md")}, pathlib.Path("/home/me/acme.env"), pages=kept)
class Opened(unittest.TestCase):
def test_a_record_on_a_confluence_page_keeps_the_version_it_read_beside_its_copy(self):
page = Page("https://acme.atlassian.net", "2293761", "confluence:https://acme.atlassian.net/wiki/spaces/ENG/pages/2293761")
config = ProjectConfig("acme", pathlib.Path("/home/me/.claude-projects/acme"), pathlib.Path("/code/acme"), {}, pathlib.Path("/home/me/acme.env"), pages={"decisions": page})
record, copy = main.opened(config, "decisions", pathlib.Path("/home/me"))
self.assertEqual(copy, pathlib.Path("/home/me/.local/state/project-record/acme/decisions.md"))
record, copy = main.opened(worktree_config("/code/acme", decisions=page), "decisions", pathlib.Path("/home/me"))
self.assertEqual((copy.parent.parent, copy.name), (COPIES, "decisions.md"))
self.assertRegex(copy.parent.name, r"^acme-[0-9a-f]{8}$")
assert isinstance(record, ConfluencePage), record
self.assertEqual(record.kept, pathlib.Path("/home/me/.local/state/project-record/acme/decisions.version"))
self.assertEqual(record.kept, copy.with_suffix(".version"))
def test_the_goals_file_opens_through_the_goals_store(self):
config = ProjectConfig("acme", pathlib.Path("/home/me/.claude-projects/acme"), pathlib.Path("/code/acme"), {"goals-and-audience": pathlib.Path("/code/acme/README.md")})
record, copy = main.opened(config, "goals-and-audience", pathlib.Path("/home/me"))
self.assertEqual((record.label, copy), ("/code/acme/README.md", pathlib.Path("/home/me/.local/state/project-record/acme/goals-and-audience.md")))
record, copy = main.opened(worktree_config("/code/acme"), "goals-and-audience", pathlib.Path("/home/me"))
self.assertEqual((record.label, copy.parent.parent, copy.name), ("/code/acme/README.md", COPIES, "goals-and-audience.md"))
def test_two_worktrees_of_one_project_get_copies_that_differ(self):
home = pathlib.Path("/home/me")
main_checkout = main.opened(worktree_config("/code/acme"), "goals-and-audience", home)[1]
other = main.opened(worktree_config("/code/acme-item-5"), "goals-and-audience", home)[1]
self.assertNotEqual(main_checkout, other)
def test_one_worktree_always_gets_the_same_copy(self):
home = pathlib.Path("/home/me")
first = main.opened(worktree_config("/code/acme"), "goals-and-audience", home)[1]
self.assertEqual(first, main.opened(worktree_config("/code/acme"), "goals-and-audience", home)[1])
def test_two_worktrees_named_alike_in_different_folders_get_copies_that_differ(self):
home = pathlib.Path("/home/me")
first = main.opened(worktree_config("/code/acme-item-5"), "goals-and-audience", home)[1]
second = main.opened(worktree_config("/other/acme-item-5"), "goals-and-audience", home)[1]
self.assertNotEqual(first, second)
class Pruned(unittest.TestCase):
def setUp(self) -> None:
self.home = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory()))
self.config = worktree_config("/code/acme-item-5")
self.folders = self.home / ".local/state/project-record/acme"
for top in ("/code/acme", "/code/acme-item-5", "/code/acme-item-6"):
copy = main.opened(worktree_config(top), "goals-and-audience", self.home)[1]
copy.parent.mkdir(parents=True)
copy.write_text("edit")
def kept(self) -> set[str]:
return {folder.name for folder in self.folders.iterdir()}
def listed(self, *tops: str):
return lambda *args, **kwargs: "" if args != ("worktree", "list", "--porcelain") else "".join(f"worktree {top}\nHEAD abc\nbranch refs/heads/x\n\n" for top in tops)
def test_removes_the_copies_of_worktrees_git_no_longer_lists_and_keeps_the_others(self):
main.pruned(self.config, self.home, self.listed("/code/acme", "/code/acme-item-5"))
self.assertEqual(self.kept(), {main.worktree_folder(pathlib.Path(top)) for top in ("/code/acme", "/code/acme-item-5")})
def test_always_keeps_the_copy_of_the_worktree_that_asked(self):
main.pruned(self.config, self.home, self.listed("/code/acme"))
self.assertIn(main.worktree_folder(pathlib.Path("/code/acme-item-5")), self.kept())
def test_removes_nothing_where_git_cannot_list_the_worktrees(self):
main.pruned(self.config, self.home, lambda *args, **kwargs: Failure("not a repository"))
self.assertEqual(len(self.kept()), 3)
def test_leaves_files_beside_the_folders_alone(self):
(self.folders / "decisions.md").write_text("from before the folders")
main.pruned(self.config, self.home, self.listed("/code/acme"))
self.assertTrue((self.folders / "decisions.md").exists())
def test_a_copy_that_cannot_be_removed_does_not_fail_the_open(self):
self.folders.chmod(0o500)
self.addCleanup(self.folders.chmod, 0o700)
main.pruned(self.config, self.home, self.listed("/code/acme"))
self.assertEqual(len(self.kept()), 3)
def test_an_open_prunes_and_a_save_does_not(self):
run = self.listed("/code/acme", "/code/acme-item-5")
self.assertEqual(main.performed(self.config, "save", "goals-and-audience", self.home, run), "/code/acme-item-5/README.md is the record itself, so nothing is left to store.")
self.assertEqual(len(self.kept()), 3)
self.assertEqual(main.performed(self.config, "open", "goals-and-audience", self.home, run), "/code/acme-item-5/README.md")
self.assertEqual(self.kept(), {main.worktree_folder(pathlib.Path(top)) for top in ("/code/acme", "/code/acme-item-5")})
def test_does_nothing_where_the_project_has_no_copies(self):
main.pruned(worktree_config("/code/acme"), self.home / "elsewhere", self.listed("/code/acme"))
class Act(unittest.TestCase):
+17 -3
View File
@@ -156,18 +156,32 @@ def todos_since(tag: str | None | Failure, ref: str, plan: str | None, cwd: str,
def chunk_item(found: list[Item], cut: LastCut) -> Pick:
"""The pick from todo.md's items, weighed against the last cut. Routing and chunk-preflight both pick with it, so they name one item."""
upcoming = next_release(found, cut)
return standing(upcoming, next_item(found), cut.reviewed) if isinstance(upcoming, Upcoming) else upcoming
return standing(upcoming, next_item(carried(found, cut)), cut.reviewed) if isinstance(upcoming, Upcoming) else upcoming
def carried(found: list[Item], cut: LastCut) -> list[Item]:
"""found, with the release of each item that the plan files under the last cut's version, or an earlier one, replaced by the next release: the earliest after the cut that the plan holds or todo.md has named since it.
Someone cut a release while it held those items, and the loop works on: lilleman's call, 2026-11-16. found itself where nothing is cut, and where no release after the cut is known, since naming one is the human's.
"""
version = cut_version(cut)
named = named_releases(cut.todos_since)
known = {item.release for item in found} | (set() if isinstance(named, Failure) else named)
after = set() if version is None else {release for release in known if release > version}
if not after or all(item.release >= min(after) for item in found):
return found
return [dataclasses.replace(item, release=max(item.release, min(after))) for item in found]
def next_release(found: list[Item], cut: LastCut) -> Upcoming | Cut | Unknown:
"""The next release after cut, and whether work has landed towards it. found holds the plan's items.
Cut where the plan files items under the last cut's version or earlier, and Unknown where the tags, or todo.md's texts since the cut, cannot be read.
Cut where the plan files items under the last cut's version or earlier and no later release is known for carried to file them under, and Unknown where the tags, or todo.md's texts since the cut, cannot be read.
Where the branch has no tag, todos_since holds every version of todo.md, so a release todo.md named whose items are all done still reads as the next release.
"""
if isinstance(cut.tag, Failure):
return Unknown()
earliest = min((item.release for item in found), default=None)
earliest = min((item.release for item in carried(found, cut)), default=None)
version = cut_version(cut)
if version is None:
return Upcoming(earliest, True, has_unreleased(cut))
+31 -2
View File
@@ -77,6 +77,33 @@ class NextRelease(unittest.TestCase):
self.assertEqual(release_standing.next_release([one((1, 3, 0))], cut(Failure("count unreadable"))), release_standing.Upcoming((1, 3, 0), True, Failure("count unreadable")))
class Carried(unittest.TestCase):
def test_files_each_item_of_a_release_already_cut_under_the_earliest_release_the_plan_names_after_the_cut(self):
held = [dataclasses.replace(one((1, 2, 3)), id=1), dataclasses.replace(one((1, 2, 0)), id=2), dataclasses.replace(one((1, 4, 0)), id=3), dataclasses.replace(one((1, 3, 0)), id=4)]
carried = release_standing.carried(held, release_standing.LastCut("v1.2.3", "", 4, []))
self.assertEqual([(item.id, item.release) for item in carried], [(1, (1, 3, 0)), (2, (1, 3, 0)), (3, (1, 4, 0)), (4, (1, 3, 0))])
def test_leaves_the_plan_as_it_is_where_nothing_is_cut_or_it_names_no_release_after_the_cut(self):
held = [one((1, 2, 3))]
for tag in ("v1.2.3", "v1.2.2", None, Failure("tags unreadable")):
with self.subTest(tag=tag):
self.assertIs(release_standing.carried(held, release_standing.LastCut(tag, "", 4, [])), held)
def test_files_them_under_a_release_todo_md_named_since_the_cut_though_the_plan_holds_no_item_of_it(self):
held = [one((1, 2, 3)), dataclasses.replace(one((1, 4, 0)), id=2)]
cut = release_standing.LastCut("v1.2.3", "", 4, naming({(1, 2, 3), (1, 3, 0)}))
self.assertEqual([item.release for item in release_standing.carried(held, cut)], [(1, 3, 0), (1, 4, 0)])
self.assertEqual(release_standing.chunk_item(held, cut), release_standing.Next((1, 3, 0), dataclasses.replace(held[0], release=(1, 3, 0))))
self.assertEqual(release_standing.carried(held[:1], dataclasses.replace(cut, todos_since=Failure("log unreadable"))), held[:1])
def test_takes_the_cut_releases_item_first_as_the_next_releases(self):
held = [dataclasses.replace(one((1, 2, 3)), id=1), dataclasses.replace(one((1, 3, 0)), id=2)]
cut = release_standing.LastCut("v1.2.3", "", 4, [])
self.assertEqual(release_standing.chunk_item(held, cut), release_standing.Next((1, 3, 0), dataclasses.replace(held[0], release=(1, 3, 0))))
self.assertEqual(release_standing.next_release(held, cut), release_standing.Upcoming((1, 3, 0), True, True))
self.assertEqual(release_standing.next_release(held[:1], cut), release_standing.Cut((1, 2, 3)))
class ChunkItem(unittest.TestCase):
def test_takes_the_earliest_release_where_it_is_the_next_and_else_says_whether_the_next_is_ready_to_cut_or_to_plan(self):
cases = (
@@ -91,7 +118,8 @@ class ChunkItem(unittest.TestCase):
(Failure("tags unreadable"), 4, (0, 2, 0), set(), release_standing.Unknown()),
(Failure("tags unreadable"), 4, None, set(), release_standing.Unknown()),
("v1.2.3", 4, (1, 2, 3), set(), release_standing.Cut((1, 2, 3))),
("v1.2.3", 4, (1, 2, 2), {(1, 2, 4)}, release_standing.Cut((1, 2, 2))),
("v1.2.3", 4, (1, 2, 2), set(), release_standing.Cut((1, 2, 2))),
("v1.2.3", 4, (1, 2, 2), {(1, 2, 4)}, release_standing.Next((1, 2, 4), one((1, 2, 4)))),
("v1.2.3", 4, (1, 3, 0), {(1, 2, 4), (1, 3, 0)}, release_standing.ReadyToCut((1, 2, 4))),
("v0.9.2", 4, (1, 0, 0), {(0, 9, 3)}, release_standing.ReadyToCut((0, 9, 3))),
("v1.2.3", 4, (1, 4, 0), {(1, 2, 2), (1, 3, 0)}, release_standing.ReadyToCut((1, 3, 0))),
@@ -140,7 +168,8 @@ class ChunkItem(unittest.TestCase):
self.assertNotEqual(release_standing.chunk_item([], without_unreleased), release_standing.ReviewDue((0, 0, 1)), "0.0.1 is cut under its dated heading")
later = [HEADER + ROW.format(id=1, release="0.0.1") + ROW.format(id=2, release="0.1.0"), HEADER + ROW.format(id=2, release="0.1.0")]
self.assertEqual(release_standing.chunk_item(plan_under((0, 1, 0)), release_standing.LastCut(None, changelog, 4, later)), release_standing.Next((0, 1, 0), one((0, 1, 0))))
self.assertEqual(release_standing.chunk_item(plan_under((0, 0, 1)), release_standing.LastCut(None, changelog, 4, later)), release_standing.Cut((0, 0, 1)))
self.assertEqual(release_standing.chunk_item(plan_under((0, 0, 1)), release_standing.LastCut(None, changelog, 4, later)), release_standing.Next((0, 1, 0), one((0, 1, 0))))
self.assertEqual(release_standing.chunk_item(plan_under((0, 0, 1)), release_standing.LastCut(None, changelog, 4, history)), release_standing.Cut((0, 0, 1)))
def test_counts_neither_an_undated_heading_nor_a_heading_behind_a_tag_as_cut(self):
history = [HEADER + ROW.format(id=1, release="0.0.1"), HEADER]
+12 -7
View File
@@ -3,7 +3,7 @@
usage: review-replay <pass> <model> [--omit-claude-md]
<pass> is one of architecture, principles, overrides, stability, product-owner or prose.
<model> is a project model on the routing ladder, such as claude-opus-5-5. The tool replays the
<model> is a project model on the routing ladder this setup ships, such as claude-opus-5-5. The tool replays the
latest 10 archived rounds of the pass whose report holds a 🔴 or 🟡 finding, from the projects
that ~/.claude/loop-claude-models.json runs on the model. It replays each round on the code it
reviewed: in a throwaway clone of the project's checkout, at the newest commit of origin/HEAD
@@ -61,8 +61,9 @@ from review_replay.replay import codes_found, findings_replayed
from review_replay.omit_comparison import compared
from loop_effects.effects import Effects
from failure import Failure
from model_routing.ladder import Ladder, Rung
from claude_code.reply import Limited
from model_routing.ladder import project_rung, Rung
from model_routing.ladder_file import read_ladder, SHIPPED
from review_replay.recall import recall_report, recalled
from review_rules.review_passes import ReviewedPass, REVIEWERS
@@ -73,7 +74,11 @@ LATEST = 10
def main(argv: list[str], env: typing.Mapping[str, str], home: pathlib.Path, effects: Effects) -> int:
read = arguments_or_exit(TOOL, argv, __doc__, USAGE, pass_and_model)
# The shipped ladder, not a project's: the replay spans every project on the model.
ladder = read_ladder(SHIPPED)
if isinstance(ladder, Failure):
return failed(TOOL, ladder.reason)
read = arguments_or_exit(TOOL, argv, __doc__, USAGE, lambda argv: pass_and_model(ladder, argv))
if isinstance(read, int):
return read
reviewed, project, without = read
@@ -97,17 +102,17 @@ def main(argv: list[str], env: typing.Mapping[str, str], home: pathlib.Path, eff
print(f" {found.root} {found.at} on {rung} failed: {matched.reason}", file=sys.stderr, flush=True)
return matched
recall = recalled(chosen, project, replay_one, f"{reviewed} rounds")
recall = recalled(chosen, ladder, project, replay_one, f"{reviewed} rounds")
if isinstance(recall, Limited):
return limited_exit(TOOL, recall)
print(recall_report(reviewed, project, recall))
return 0
def pass_and_model(argv: list[str]) -> tuple[ReviewedPass, Rung, bool] | None:
"""The pass, the project's rung of the model, and whether OMIT follows, as argv names them in `<pass> <model> [--omit-claude-md]`; None for any other argv."""
def pass_and_model(ladder: Ladder, argv: list[str]) -> tuple[ReviewedPass, Rung, bool] | None:
"""The pass, the project's rung on ladder of the model, and whether OMIT follows, as argv names them in `<pass> <model> [--omit-claude-md]`; None for any other argv."""
if argv[2:] not in ([], [OMIT]) or len(argv) < 2:
return None
reviewed = next((kind for kind in REVIEWERS if kind == argv[0]), None)
project = project_rung(argv[1])
project = ladder.project_rung(argv[1])
return (reviewed, project, argv[2:] == [OMIT]) if reviewed and project else None
+5 -7
View File
@@ -1,10 +1,10 @@
"""The bar review-replay holds a rung to, and its report: docs/decisions.md → `routing: a review pass runs below the project's rung only on a rung whose replay of its rounds finds a share of their 🔴 and 🟡 findings no more than a margin below the project's rung's own replay`."""
import dataclasses
from rung_replay.command import down_from
from model_routing.ladder import EFFORTS, Ladder, Rung
from failure import Failure
from fractions import Fraction
from review_replay.rounds import is_red, Round
from model_routing.ladder import LADDER, Rung
from claude_code.reply import Limited
import math
from rung_replay.search import replayed_on
@@ -14,8 +14,6 @@ import typing
MARGIN = Fraction(1, 10)
# The fewest rounds a rung is tried on: 8 of the 10 the tool samples, so up to two may fail on the project's rung.
ENOUGH_ROUNDS = 8
# Lowest first, as Claude Code's --effort takes them.
EFFORTS = ("low", "medium", "high", "xhigh", "max")
# The two replays on the project's rung. Each lists, round by round, the indexes of the findings it found.
Reference = tuple[list[set[int]], list[set[int]]]
@@ -39,10 +37,10 @@ class Recall:
lowest: Rung | None
def candidates(project: Rung) -> list[Rung]:
def candidates(ladder: Ladder, project: Rung) -> list[Rung]:
"""The rungs tried below the project's, highest first: its model at each lower effort, which the ladder leaves out, then each ladder rung below it, down to the ladder's lowest. That reaches below the lowest a worker routes to, since a pass may run below the worker's rung."""
lower_efforts = [Rung(project.model, effort) for effort in reversed(EFFORTS[:EFFORTS.index(project.effort)])]
return lower_efforts + down_from(project, LADDER[0])[1:]
return lower_efforts + down_from(ladder, project, ladder.rungs[0])[1:]
def enough(rounds: list[Round]) -> bool:
@@ -97,7 +95,7 @@ def percent(fraction: Fraction) -> str:
return f"{float(fraction):.0%}"
def recalled(chosen: list[Round], project: Rung, replay_one: typing.Callable[[Round, Rung], set[int] | Failure | Limited], what: str) -> Recall | Limited:
def recalled(chosen: list[Round], ladder: Ladder, project: Rung, replay_one: typing.Callable[[Round, Rung], set[int] | Failure | Limited], what: str) -> Recall | Limited:
"""Replays chosen twice on the project's rung, then each candidate, highest first, on the rounds neither of those failed on, until one doesn't qualify."""
runs: list[list[set[int] | Failure]] = []
for _ in range(2):
@@ -114,7 +112,7 @@ def recalled(chosen: list[Round], project: Rung, replay_one: typing.Callable[[Ro
reference[1].append(second)
recalls: list[RungRecall] = []
lowest = None
for rung in candidates(project) if enough(rounds) and needed(rounds, reference) > 0 else []:
for rung in candidates(ladder, project) if enough(rounds) and needed(rounds, reference) > 0 else []:
on_rung: list[set[int] | Failure] | Limited = replayed_on(rounds, rung, replay_one, what)
if isinstance(on_rung, Limited):
return on_rung
+17 -4
View File
@@ -1,13 +1,17 @@
import contextlib
import io
import pathlib
import sys
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from review_replay.recall import candidates, needed, Recall, recall_report, tried
from review_replay.recall import candidates, needed, Recall, recall_report, recalled, tried
from review_replay.rounds import is_red, Round
from model_routing.ladder_file import read_ladder, SHIPPED
from model_routing.ladder import Rung
LADDER = read_ladder(SHIPPED)
REFERENCE = Rung("claude-opus-5-5", "medium")
LOW = Rung("claude-opus-5-5", "low")
SONNET = Rung("claude-sonnet-5-5", "high")
@@ -27,13 +31,22 @@ TENTH = ([{0}, set()], [{0}, set()])
class Candidates(unittest.TestCase):
def test_tries_the_project_models_lower_efforts_first_then_the_ladder_below_it(self):
self.assertEqual(candidates(REFERENCE), [LOW, SONNET])
self.assertEqual(candidates(LADDER, REFERENCE), [LOW, SONNET])
def test_tries_each_ladder_rung_below_highest_first(self):
self.assertEqual(candidates(Rung("claude-fable-5-2", "low")), [REFERENCE, SONNET])
self.assertEqual(candidates(LADDER, Rung("claude-fable-5-2", "low")), [REFERENCE, SONNET])
def test_tries_each_lower_effort_of_the_ladders_lowest_rung(self):
self.assertEqual(candidates(SONNET), [Rung("claude-sonnet-5-5", "medium"), Rung("claude-sonnet-5-5", "low")])
self.assertEqual(candidates(LADDER, SONNET), [Rung("claude-sonnet-5-5", "medium"), Rung("claude-sonnet-5-5", "low")])
class Recalled(unittest.TestCase):
def test_tries_the_rungs_below_where_the_project_rung_needs_one_finding(self):
# Eight findings, of which both replays on the project's rung find one: a share of an eighth, a tenth under which leaves one finding needed.
rounds = [a_round(at, ("🟡 a",)) for at in range(8)]
with contextlib.redirect_stderr(io.StringIO()):
recall = recalled(rounds, LADDER, REFERENCE, lambda one, rung: {0} if one == rounds[0] else set(), "prose rounds")
self.assertEqual(([one.rung for one in recall.tried], recall.lowest), ([LOW, SONNET], SONNET))
class Tried(unittest.TestCase):
+4 -4
View File
@@ -6,7 +6,7 @@ import typing
from routing_figures.chunk import ChunkFigures, Reports
from routing_figures.dollars import DIMENSIONS, Dollars
from model_routing.ladder import position, Rung
from model_routing.ladder import Ladder, Rung
# A rung or a subagent type is compared only once this many of its chunks or subagents are measured, so a single odd chunk calls for no change.
MEASURED_AT_LEAST = 5
@@ -73,9 +73,9 @@ class Call:
return SENTENCES[self.kind].format(*self.subjects)
def calls(figures: Figures) -> list[Call]:
"""Each routing change the figures call for."""
compared = sorted((rung for rung, chunks in figures.routed.items() if len(chunks) >= MEASURED_AT_LEAST and position(rung) >= 0), key=position)
def calls(ladder: Ladder, figures: Figures) -> list[Call]:
"""Each routing change the figures call for, comparing the rungs on ladder."""
compared = sorted((rung for rung, chunks in figures.routed.items() if len(chunks) >= MEASURED_AT_LEAST and ladder.position(rung) >= 0), key=ladder.position)
found = []
for lower, upper in zip(compared, compared[1:]):
measures: tuple[tuple[Kind, typing.Callable[[ChunkFigures], int]], ...] = (("rounds", lambda chunk: chunk.rounds_past_first), ("unfinished", lambda chunk: chunk.unfinished))
+7 -7
View File
@@ -6,11 +6,11 @@ import typing
from routing_figures.calls import Call, Figures, mean, summed
from routing_figures.chunk import ChunkFigures
from routing_figures.dollars import DIMENSIONS
from model_routing.ladder import position
from model_routing.ladder import Ladder
def render(figures: Figures, found: list[Call], at: str, cycle: int, since: str) -> str:
"""The figures as markdown, for the human to read. since is the latest reset's stamp, empty for none."""
def render(ladder: Ladder, figures: Figures, found: list[Call], at: str, cycle: int, since: str) -> str:
"""The figures as markdown, for the human to read. ladder orders the rungs, and since is the latest reset's stamp, empty for none."""
sections = [
"# Routing figures",
f"Measured {at}, at cycle {cycle} across loop-claude's archive, from {figures.chunks} finished chunk{'' if figures.chunks == 1 else 's'}{f' that finished after the reset of {since}' if since else ''}. {basis(figures)}",
@@ -19,7 +19,7 @@ def render(figures: Figures, found: list[Call], at: str, cycle: int, since: str)
*[part for dimension in DIMENSIONS for part in (f"## Dollars by {dimension}", dollars_table(figures, dimension))],
"## Routed chunks by the rung they started on",
fixes_basis(figures),
routed_table(figures),
routed_table(ladder, figures),
"## Escalations by trigger across every chunk, routed or not",
f"{triggers(figures.escalated) or 'None'}.",
"## Subagent reports against the tool results they read, in characters",
@@ -35,8 +35,8 @@ def dollars_table(figures: Figures, dimension: str) -> str:
return table((dimension.capitalize(), "Dollars"), [(label, money(dollars)) for label, dollars in sorted(figures.dollars[dimension].items(), key=lambda spent: -spent[1])])
def routed_table(figures: Figures) -> str:
"""One row per rung the routed chunks started on, from the bottom of the ladder up."""
def routed_table(ladder: Ladder, figures: Figures) -> str:
"""One row per rung the routed chunks started on, from the bottom of the ladder up, after the rungs off it."""
return table(("Rung", "Chunks", "Review rounds past each pass's first, mean", "Unfinished verdicts, mean", "Later fixes, mean", "Subagent rungs", "Escalations by trigger"), [
(
str(rung),
@@ -47,7 +47,7 @@ def routed_table(figures: Figures) -> str:
subagent_rungs(chunks),
triggers(summed(chunks, lambda chunk: chunk.escalated)),
)
for rung, chunks in sorted(figures.routed.items(), key=lambda routed: position(routed[0]))
for rung, chunks in sorted(figures.routed.items(), key=lambda routed: ladder.position(routed[0]))
])
+26 -24
View File
@@ -26,11 +26,13 @@ from failure import Failure
from git_cli import git_repo
from test_env import isolated_env
from release_plan.todo_table import Item
from model_routing.ladder import LADDER, Rung
from transcript_archive import outcomes, write
from model_routing.ladder_file import read_ladder, SHIPPED
from routing_figures.render import render
from model_routing.route import Route
from model_routing.ladder import Rung
LADDER = read_ladder(SHIPPED)
LOW = Rung("claude-opus-5-5", "medium")
HIGH = Rung("claude-fable-5-2", "low")
LOW_ROUTE = Route(LOW, 7, 3, 4).worker_line()
@@ -246,30 +248,30 @@ class Measured(unittest.TestCase):
class Calls(unittest.TestCase):
def test_calls_when_chunks_on_a_rung_took_more_rounds_or_unfinished_verdicts_than_the_rung_above(self):
chunks = [figures(LOW, rounds=2)] * 5 + [figures(HIGH, unfinished=1)] * 5
self.assertEqual(calls(totals(chunks)), [Call("rounds", (str(LOW), str(HIGH)))])
self.assertEqual(calls(totals(chunks))[0].sentence(), f"Chunks routed onto {LOW} took more review rounds past each pass's first than chunks routed onto {HIGH}.")
[unfinished] = calls(totals([figures(LOW, unfinished=1)] * 5 + [figures(HIGH)] * 5))
self.assertEqual(calls(LADDER, totals(chunks)), [Call("rounds", (str(LOW), str(HIGH)))])
self.assertEqual(calls(LADDER, totals(chunks))[0].sentence(), f"Chunks routed onto {LOW} took more review rounds past each pass's first than chunks routed onto {HIGH}.")
[unfinished] = calls(LADDER, totals([figures(LOW, unfinished=1)] * 5 + [figures(HIGH)] * 5))
self.assertEqual(unfinished, Call("unfinished", (str(LOW), str(HIGH))))
self.assertEqual(unfinished.sentence(), f"Chunks routed onto {LOW} took more unfinished verdicts than chunks routed onto {HIGH}.")
def test_compares_the_bottom_rungs_and_calls_nothing_on_a_tie(self):
self.assertEqual(calls(totals([figures(LADDER[0], rounds=1)] * 5 + [figures(LADDER[1])] * 5)), [Call("rounds", (str(LADDER[0]), str(LADDER[1])))])
self.assertEqual(calls(totals([figures(LOW, rounds=1)] * 5 + [figures(HIGH, rounds=1)] * 5)), [])
self.assertEqual(calls(totals([figures(reports={"Explore": Reports(1, 20, 20)})] * 5)), [])
self.assertEqual(calls(LADDER, totals([figures(LADDER.rungs[0], rounds=1)] * 5 + [figures(LADDER.rungs[1])] * 5)), [Call("rounds", (str(LADDER.rungs[0]), str(LADDER.rungs[1])))])
self.assertEqual(calls(LADDER, totals([figures(LOW, rounds=1)] * 5 + [figures(HIGH, rounds=1)] * 5)), [])
self.assertEqual(calls(LADDER, totals([figures(reports={"Explore": Reports(1, 20, 20)})] * 5)), [])
def test_compares_only_rungs_with_five_chunks_each(self):
self.assertEqual(calls(totals([figures(LOW, rounds=2)] * 5 + [figures(HIGH)] * 4)), [])
self.assertEqual(calls(LADDER, totals([figures(LOW, rounds=2)] * 5 + [figures(HIGH)] * 4)), [])
def test_calls_when_a_subagent_types_reports_outgrow_the_searches_they_ran(self):
[call] = calls(totals([figures(reports={"Explore": Reports(1, 30, 20)})] * 5))
[call] = calls(LADDER, totals([figures(reports={"Explore": Reports(1, 30, 20)})] * 5))
self.assertEqual(call, Call("reports", ("Explore",)))
self.assertEqual(call.sentence(), "Explore subagents' reports took more of the worker's context than their searches would have.")
self.assertEqual(calls(totals([figures(reports={"Explore": Reports(1, 30, 20)})] * 4)), [])
self.assertEqual(calls(totals([figures(reports={"Explore": Reports(1, 20, 30)})] * 5)), [])
self.assertEqual(calls(LADDER, totals([figures(reports={"Explore": Reports(1, 30, 20)})] * 4)), [])
self.assertEqual(calls(LADDER, totals([figures(reports={"Explore": Reports(1, 20, 30)})] * 5)), [])
def test_renders_each_dimension_largest_first_and_the_calls(self):
chunk = ChunkFigures({"project": collections.Counter({"a": 2.5, "b": 1234.5})}, LOW, 1, 0, collections.Counter({str(HIGH): 2}), {"Explore": Reports(2, 3, 4)}, collections.Counter(), 0.0)
text = render(totals([chunk]), [Call("reports", ("Explore",))], "2026-10-15T00:00:00Z", 40, "")
text = render(LADDER, totals([chunk]), [Call("reports", ("Explore",))], "2026-10-15T00:00:00Z", 40, "")
self.assertIn("Measured 2026-10-15T00:00:00Z, at cycle 40 across loop-claude's archive, from 1 finished chunk.", text)
self.assertIn("## Calls for a routing change\n\n- Explore subagents' reports took more of the worker's context than their searches would have.\n", text)
self.assertIn("## Dollars by project", text)
@@ -278,32 +280,32 @@ class Calls(unittest.TestCase):
self.assertIn("The judge's cost counts from the verdicts and rejections that record it, so a chunk archived before they did, and a judge run that failed, add none.", text)
self.assertNotIn("left out", text)
self.assertNotIn("no transcript", text)
self.assertIn("The archive holds no subagent transcript for 2 of the chunks' Agent calls.", render(totals([dataclasses.replace(chunk, lacking=1)] * 2), [], "2026-10-15T00:00:00Z", 40, ""))
self.assertIn("$0.50 of the recorded cost is left out", render(totals([ChunkFigures({}, LOW, 0, 0, collections.Counter(), {}, collections.Counter(), 0.5), chunk]), [], "2026-10-15T00:00:00Z", 40, ""))
self.assertIn("The archive holds no subagent transcript for 2 of the chunks' Agent calls.", render(LADDER, totals([dataclasses.replace(chunk, lacking=1)] * 2), [], "2026-10-15T00:00:00Z", 40, ""))
self.assertIn("$0.50 of the recorded cost is left out", render(LADDER, totals([ChunkFigures({}, LOW, 0, 0, collections.Counter(), {}, collections.Counter(), 0.5), chunk]), [], "2026-10-15T00:00:00Z", 40, ""))
self.assertIn(f"| {LOW} | 1 | 1.0 | 0.0 | unknown | {HIGH} 2 | |", text)
two = ChunkFigures({}, HIGH, 0, 1, collections.Counter({str(HIGH): 2, str(LOW): 1}), {}, collections.Counter(), 0.0)
self.assertIn(f"| {LOW} | 1 | 1.0 | 0.0 | unknown | {HIGH} 2 | |\n| {HIGH} | 1 | 0.0 | 1.0 | unknown | {HIGH} 2, {LOW} 1 | |", render(totals([two, chunk]), [], "2026-10-15T00:00:00Z", 40, ""))
self.assertIn(f"| {LOW} | 1 | 1.0 | 0.0 | unknown | {HIGH} 2 | |\n| {HIGH} | 1 | 0.0 | 1.0 | unknown | {HIGH} 2, {LOW} 1 | |", render(LADDER, totals([two, chunk]), [], "2026-10-15T00:00:00Z", 40, ""))
self.assertIn("| Explore | 2 | 3 | 4 |", text)
escalated = render(totals([figures(escalated={2: 2}), figures(escalated={2: 1, 10: 1}), figures(start=None, escalated={3: 1})]), [], "2026-10-15T00:00:00Z", 40, "")
escalated = render(LADDER, totals([figures(escalated={2: 2}), figures(escalated={2: 1, 10: 1}), figures(start=None, escalated={3: 1})]), [], "2026-10-15T00:00:00Z", 40, "")
self.assertIn(f"| {LOW} | 2 | 0.0 | 0.0 | unknown | | trigger 2: 3, trigger 10: 1 |", escalated)
self.assertIn("## Escalations by trigger across every chunk, routed or not\n\ntrigger 2: 3, trigger 3: 1, trigger 10: 1.\n", escalated)
self.assertIn("## Escalations by trigger across every chunk, routed or not\n\nNone.\n", text)
self.assertIn("## Calls for a routing change\n\nNone.\n", render(totals([]), [], "2026-10-15T00:00:00Z", 20, ""))
self.assertIn("from 0 finished chunks that finished after the reset of 2026-10-14T00:00:00Z.", render(totals([]), [], "2026-10-15T00:00:00Z", 20, "2026-10-14T00:00:00Z"))
self.assertIn("## Calls for a routing change\n\nNone.\n", render(LADDER, totals([]), [], "2026-10-15T00:00:00Z", 20, ""))
self.assertIn("from 0 finished chunks that finished after the reset of 2026-10-14T00:00:00Z.", render(LADDER, totals([]), [], "2026-10-15T00:00:00Z", 20, "2026-10-14T00:00:00Z"))
def test_renders_the_mean_later_fixes_of_the_matched_chunks_and_how_many_they_are(self):
text = render(totals([*MATCHED, figures()]), [], "2026-10-15T00:00:00Z", 40, "")
text = render(LADDER, totals([*MATCHED, figures()]), [], "2026-10-15T00:00:00Z", 40, "")
self.assertIn(f"| {LOW} | 4 | 0.0 | 0.0 | 1.0 (3 known) | | |", text)
self.assertIn("## Routed chunks by the rung they started on\n\nA routed chunk's later fixes are", text)
self.assertNotIn("later fixes", text.split("## Calls for a routing change")[0])
def test_counts_the_routed_chunks_whose_later_fixes_are_unknown(self):
self.assertIn("The later fixes of 2 of the routed chunks are unknown", render(totals([*MATCHED, figures(), figures(), figures(start=None)]), [], "2026-10-15T00:00:00Z", 40, ""))
self.assertNotIn("are unknown", render(totals(MATCHED), [], "2026-10-15T00:00:00Z", 40, ""))
self.assertIn("The later fixes of 2 of the routed chunks are unknown", render(LADDER, totals([*MATCHED, figures(), figures(), figures(start=None)]), [], "2026-10-15T00:00:00Z", 40, ""))
self.assertNotIn("are unknown", render(LADDER, totals(MATCHED), [], "2026-10-15T00:00:00Z", 40, ""))
def test_names_each_default_branch_unread(self):
self.assertIn("## Default branches unread\n\n- log: no main branch\n", render(totals(MATCHED, unread=("log: no main branch",)), [], "2026-10-15T00:00:00Z", 40, ""))
self.assertNotIn("branches unread", render(totals(MATCHED), [], "2026-10-15T00:00:00Z", 40, ""))
self.assertIn("## Default branches unread\n\n- log: no main branch\n", render(LADDER, totals(MATCHED, unread=("log: no main branch",)), [], "2026-10-15T00:00:00Z", 40, ""))
self.assertNotIn("branches unread", render(LADDER, totals(MATCHED), [], "2026-10-15T00:00:00Z", 40, ""))
def test_measures_once_the_count_runs_20_past_the_last_measurement(self):
self.assertEqual([due(cycle, 20) for cycle in (39, 40, 41)], [False, True, True])
@@ -463,7 +465,7 @@ class Archive(unittest.TestCase):
(self.root / "broken" / "c3" / "copy.outcomes.md").write_bytes(b"\xff")
found = archive.measure_archive(self.root, "/h", "", no_checkout)
self.assertEqual((len(found.chunks), found.skipped), (1, ("broken", "log/c1")))
self.assertIn("## Chunks skipped, unreadable\n\n- log/c1\n", render(totals([], ("log/c1",)), [], "2026-10-15T00:00:00Z", 20, ""))
self.assertIn("## Chunks skipped, unreadable\n\n- log/c1\n", render(LADDER, totals([], ("log/c1",)), [], "2026-10-15T00:00:00Z", 20, ""))
def test_keeps_the_cycle_it_measured_at_and_reads_it_back(self):
self.assertEqual(state.read_state(self.root), state.State(0, ()))
+2 -2
View File
@@ -88,9 +88,9 @@ def main(argv: list[str], stdin: str) -> int:
def breaches_of(call: Call, home: str, environ: typing.Mapping[str, str]) -> tuple[str, str, list[Breach]] | None:
"""The text that may carry an override, what the log names the call by, and its breaches; None for a call no rule checks."""
if call.tool == "Agent":
return text(call.given, "prompt"), text(call.given, "subagent_type"), reviewer_breaches(call, environ)
return text(call.given, "prompt"), text(call.given, "subagent_type"), reviewer_breaches(call, environ, home)
if call.tool == "Skill":
return text(call.given, "args"), text(call.given, "skill"), skill_breaches(call, environ)
return text(call.given, "args"), text(call.given, "skill"), skill_breaches(call, environ, home)
if call.tool == "Bash":
command = text(call.given, "command")
return command, command.split("\n", 1)[0], bash_breaches(command, call.cwd, home) + read_breaches(call, home) + env_file_breaches(call, home)
+33 -16
View File
@@ -1,4 +1,5 @@
"""Refuse an Agent or Skill call that launches a review below the rung it needs, worked out from the rungs and the E + I loop-claude hands its worker: docs/decisions.md → `routing:`."""
"""Refuse an Agent or Skill call that launches a review below the rung it needs, worked out on the project's ladder from the rungs and the E + I loop-claude hands its worker: docs/decisions.md → `routing:`."""
import pathlib
import typing
from rule_hook.rules import Breach
@@ -6,8 +7,9 @@ from rule_hook.call import Call, text
from failure import Failure
from git_cli import git_repo
from rule_hook.git import guarded_git
from model_routing.worker_rungs import handed
from model_routing.ladder import position, review_rung, ReviewKind, Rung
from model_routing.worker_rungs import handed, hands_rungs
from model_routing.ladder import Ladder, ReviewKind, Rung
from model_routing.ladder_file import project_ladder
from review_rules.review_passes import prose, REVIEWERS
from claude_code.transcript import read_transcript
from claude_code.entries import UserText
@@ -23,29 +25,44 @@ SUBJECTS: dict[ReviewKind, str] = {"seat": "a comprehension seat", "security": "
SECURITY_SKILLS = {"claude-security", "security-review"}
def reviewer_breaches(call: Call, environ: typing.Mapping[str, str]) -> list[Breach]:
def reviewer_breaches(call: Call, environ: typing.Mapping[str, str], home: str) -> list[Breach]:
"""The breach of an Agent call that launches a review below its rung; none where loop-claude handed no rungs."""
project, worker, escape_and_impact = handed(environ)
kind = review_kind(call.given)
if kind is None or project is None or worker is None:
if kind is None or not hands_rungs(environ):
return []
required = review_rung(project, worker, escape_and_impact, kind, markdown_only(call.cwd))
named = named_rung(call.given, worker)
if position(named) >= position(required):
ladder = project_ladder(call.cwd, pathlib.Path(home))
if isinstance(ladder, Failure):
return [unread(ladder, call.cwd)]
project, worker, escape_and_impact = handed(environ, ladder)
if project is None or worker is None:
return []
required = ladder.review_rung(project, worker, escape_and_impact, kind, markdown_only(call.cwd))
named = named_rung(call.given, worker, ladder)
if ladder.position(named) >= ladder.position(required):
return []
subject = SUBJECTS.get(kind) or text(call.given, "subagent_type")
return [Breach("reviewer-rung", f"{subject} would run on {named}, below {required}: launch it with {required.agent_args()}", call.cwd)]
def skill_breaches(call: Call, environ: typing.Mapping[str, str]) -> list[Breach]:
def unread(ladder: Failure, cwd: str) -> Breach:
"""The breach of a review launched where loop-claude handed rungs and the project's ladder cannot be read, so nothing tells which rung the review needs."""
return Breach("reviewer-rung", f"the rung this review needs cannot be worked out: {ladder.reason}", cwd)
def skill_breaches(call: Call, environ: typing.Mapping[str, str], home: str) -> list[Breach]:
"""The breach of a Skill call that runs the security pass below the project's rung; none where loop-claude handed no rungs.
The skill runs on its caller's rung. A subagent launched as the security pass was held to the project's rung by reviewer_breaches. The worker's own rung is known, so its call is refused only below the project's rung. Any other subagent's rung is unknown, so its call is refused."""
project, worker, _ = handed(environ)
skill = text(call.given, "skill").lstrip("/").rsplit(":", 1)[-1]
if skill not in SECURITY_SKILLS or project is None or worker is None or opening_prompt(call.transcript).startswith(SECURITY_OPENER):
if skill not in SECURITY_SKILLS or not hands_rungs(environ) or opening_prompt(call.transcript).startswith(SECURITY_OPENER):
return []
if not call.subagent and position(worker) >= position(project):
ladder = project_ladder(call.cwd, pathlib.Path(home))
if isinstance(ladder, Failure):
return [unread(ladder, call.cwd)]
project, worker, _ = handed(environ, ladder)
if project is None or worker is None:
return []
if not call.subagent and ladder.position(worker) >= ladder.position(project):
return []
runs_on = "on a rung rule-hook cannot see" if call.subagent else f"in this context on {worker}, below {project}"
return [Breach("reviewer-rung", f"{skill} would run {runs_on}: invoke it from a subagent launched with {project.agent_args()}, its prompt opening with `{SECURITY_OPENER}`", call.cwd)]
@@ -70,12 +87,12 @@ def review_kind(given: dict[str, typing.Any]) -> ReviewKind | None:
return None
def named_rung(given: dict[str, typing.Any], worker: Rung) -> Rung:
"""The rung an Agent call's model and effort name. A call naming no model runs on the worker's model, at the effort it names or else the worker's; one naming a model but no effort runs on that model's cheapest rung."""
def named_rung(given: dict[str, typing.Any], worker: Rung, ladder: Ladder) -> Rung:
"""The rung an Agent call's model and effort name. A call naming no model runs on the worker's model, at the effort it names or else the worker's; one naming a model but no effort runs on that model's cheapest rung on ladder."""
model, effort = text(given, "model"), text(given, "effort")
if not model:
return Rung(worker.model, effort or worker.effort)
return Rung.from_agent(model, effort)
return ladder.from_agent(model, effort)
def markdown_only(directory: str) -> bool:
+1 -1
View File
@@ -72,7 +72,7 @@ RULES: dict[RuleName, Rule] = {
),
# A rung is not a judgment call, and the refusal names the arguments to pass, so no marker waives it.
"reviewer-rung": Rule(
"a reviewer, a comprehension seat or the security pass runs on the rung loop-claude names for it: for a seat or the security pass the project's rung, and for a reviewer the highest of the project's rung, the worker's and the one the chunk's item's E + I picks, or the project's rung where the branch changes only Markdown no agent follows, so a worker below the project's rung cannot hand a review to its own cheaper model",
"a reviewer, a comprehension seat or the security pass runs on the rung loop-claude names for it: for a seat or the security pass the project's rung, and for a reviewer the highest of the project's rung, the worker's and the one the chunk's item's E + I picks, or the project's rung where the branch changes only Markdown no agent follows, so a worker below the project's rung cannot hand a review to its own cheaper model. The rungs rank as on the project's routing ladder, and the review is refused while that ladder cannot be read",
"an Agent call, in a claude loop-claude started, whose subagent type is an agent under agents/, or whose prompt opens with seat-prompts.md's opening sentence or the one larv-review's Security section sets; and a `security-review` or `claude-security` Skill call in such a claude, which runs on its caller's rung, unless the caller is a subagent whose prompt opens with that sentence",
overridable=False,
),
+70 -10
View File
@@ -236,6 +236,10 @@ class OverrideLog(unittest.TestCase):
self.assertEqual(this_chunks(LogLine("t", branch, commit, "image-pin", "r", "w"), {"base", "c1"}, "chunk", on_default), expected)
# A home that holds no project config, so a review launched there is checked on the ladder this setup ships.
HOME = "/h"
class ReviewerRung(unittest.TestCase):
# A worker routed to Sonnet 5.5 at high, on a project whose rung is Opus 5.5 at medium, with its reviewers on the project's rung.
ENVIRON = {"LOOP_CLAUDE_PROJECT_RUNG": "claude-opus-5-5 at medium effort", "LOOP_CLAUDE_WORKER_RUNG": "claude-sonnet-5-5 at high effort", "LOOP_CLAUDE_ESCAPE_AND_IMPACT": "4"}
@@ -243,7 +247,7 @@ class ReviewerRung(unittest.TestCase):
ABOVE = {"LOOP_CLAUDE_PROJECT_RUNG": "claude-opus-5-5 at medium effort", "LOOP_CLAUDE_WORKER_RUNG": "claude-fable-5-2 at max effort", "LOOP_CLAUDE_ESCAPE_AND_IMPACT": "4"}
def refused(self, given: dict, environ: dict[str, str] = ENVIRON) -> list[str]:
return rules(reviewer_breaches(Call("Agent", given, "/r"), environ))
return rules(reviewer_breaches(Call("Agent", given, "/r"), environ, HOME))
def test_a_branch_changing_only_markdown_reviews_on_the_projects_rung_whatever_the_e_plus_i(self):
repo = tempfile.mkdtemp()
@@ -258,24 +262,24 @@ class ReviewerRung(unittest.TestCase):
git(repo, "commit", "-q", "-m", "prose")
high = self.ENVIRON | {"LOOP_CLAUDE_ESCAPE_AND_IMPACT": "7"}
on_project = {"subagent_type": "stability-reviewer", "model": "opus", "effort": "medium"}
self.assertEqual(rules(reviewer_breaches(Call("Agent", on_project, repo), high)), [])
self.assertEqual(rules(reviewer_breaches(Call("Agent", {**on_project, "model": "sonnet", "effort": "high"}, repo), high)), ["reviewer-rung"])
self.assertEqual(rules(reviewer_breaches(Call("Agent", on_project, repo), self.ABOVE)), [], "a worker that climbed doesn't lift a Markdown-only review either")
self.assertEqual(rules(reviewer_breaches(Call("Agent", on_project, repo), high, HOME)), [])
self.assertEqual(rules(reviewer_breaches(Call("Agent", {**on_project, "model": "sonnet", "effort": "high"}, repo), high, HOME)), ["reviewer-rung"])
self.assertEqual(rules(reviewer_breaches(Call("Agent", on_project, repo), self.ABOVE, HOME)), [], "a worker that climbed doesn't lift a Markdown-only review either")
for instructions in ("CLAUDE.md", "AGENTS.md", "skills/review/SKILL.md", "agents/reviewer.md", "rules/todo.md", "principles/tests.md", "workflow-bench/run-prompt.md"):
with self.subTest(instructions=instructions):
path = pathlib.Path(repo, instructions)
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text("Do this.\n")
self.assertEqual(rules(reviewer_breaches(Call("Agent", on_project, repo), high)), ["reviewer-rung"], "Markdown an agent follows is config")
self.assertEqual(rules(reviewer_breaches(Call("Agent", on_project, repo), high, HOME)), ["reviewer-rung"], "Markdown an agent follows is config")
path.unlink()
pathlib.Path(repo, "gate.yml").write_text("on: push\n")
self.assertEqual(rules(reviewer_breaches(Call("Agent", on_project, repo), high)), ["reviewer-rung"], "an uncommitted change to another file counts")
self.assertEqual(rules(reviewer_breaches(Call("Agent", on_project, repo), high, HOME)), ["reviewer-rung"], "an uncommitted change to another file counts")
git(repo, "add", ".")
git(repo, "commit", "-q", "-m", "config")
self.assertEqual(rules(reviewer_breaches(Call("Agent", on_project, repo), high)), ["reviewer-rung"])
self.assertEqual(rules(reviewer_breaches(Call("Agent", on_project, repo), high, HOME)), ["reviewer-rung"])
def test_a_reviewer_below_the_project_rung_is_refused_naming_the_arguments_to_pass(self):
breaches = reviewer_breaches(Call("Agent", {"subagent_type": "stability-reviewer", "model": "sonnet", "effort": "high", "prompt": "Review."}, "/r"), self.ENVIRON)
breaches = reviewer_breaches(Call("Agent", {"subagent_type": "stability-reviewer", "model": "sonnet", "effort": "high", "prompt": "Review."}, "/r"), self.ENVIRON, HOME)
self.assertEqual(rules(breaches), ["reviewer-rung"])
self.assertIn("stability-reviewer", breaches[0].detail)
self.assertIn("claude-sonnet-5-5 at high effort", breaches[0].detail)
@@ -332,13 +336,69 @@ class ReviewerRung(unittest.TestCase):
def test_a_claude_loop_claude_did_not_start_is_not_checked(self):
self.assertEqual(self.refused({"subagent_type": "stability-reviewer", "model": "haiku", "effort": "low"}, {}), [])
def project(self, ladder: str) -> tuple[str, str]:
"""A checkout whose config's folder holds ladder as its routing ladder, and its home."""
home = pathlib.Path(tempfile.mkdtemp()).resolve()
self.addCleanup(subprocess.run, ["rm", "-rf", str(home)])
checkout = home / "code" / "acme"
checkout.mkdir(parents=True)
(configured(self, checkout, home=home) / "routing-ladder.json").write_text(ladder)
return str(checkout), str(home)
# A project that runs on Fable 5.2 at low and at high alone, with a worker on its rung and an E + I of 5, which picks the rung one up.
TWO_RUNGS = '[{"model": "claude-fable-5-2", "effort": "low"}, {"model": "claude-fable-5-2", "effort": "high"}]'
ON_TWO_RUNGS = {"LOOP_CLAUDE_PROJECT_RUNG": "claude-fable-5-2 at low effort", "LOOP_CLAUDE_WORKER_RUNG": "claude-fable-5-2 at low effort", "LOOP_CLAUDE_ESCAPE_AND_IMPACT": "5"}
def test_a_review_is_held_to_the_rung_picked_on_the_projects_own_ladder(self):
checkout, home = self.project(self.TWO_RUNGS)
reviewer = {"subagent_type": "stability-reviewer", "model": "fable"}
self.assertEqual(rules(reviewer_breaches(Call("Agent", {**reviewer, "effort": "high"}, checkout), self.ON_TWO_RUNGS, home)), [])
# One up from Fable 5.2 at low is its medium effort on the shipped ladder, and its high effort on the project's, which holds no medium.
breaches = reviewer_breaches(Call("Agent", {**reviewer, "effort": "medium"}, checkout), self.ON_TWO_RUNGS, home)
self.assertEqual([breach.detail for breach in breaches], ["stability-reviewer would run on claude-fable-5-2 at medium effort, below claude-fable-5-2 at high effort: launch it with model fable, effort high"])
self.assertEqual(rules(reviewer_breaches(Call("Agent", {**reviewer, "effort": "medium"}, "/r"), self.ON_TWO_RUNGS, HOME)), [])
self.assertEqual(rules(breaches_of(Call("Agent", {**reviewer, "effort": "medium"}, checkout), home, self.ON_TWO_RUNGS)[2]), ["reviewer-rung"], "the hook reads the ladder under the home it is given")
def test_a_rung_loop_claude_handed_that_the_projects_ladder_does_not_hold_is_not_checked(self):
# As when the ladder's file changed after loop-claude started the worker: the next cycle routes on the new ladder.
checkout, home = self.project(self.TWO_RUNGS)
reviewer = Call("Agent", {"subagent_type": "stability-reviewer", "model": "haiku", "effort": "low"}, checkout)
for name in ("LOOP_CLAUDE_PROJECT_RUNG", "LOOP_CLAUDE_WORKER_RUNG"):
with self.subTest(name=name):
environ = self.ON_TWO_RUNGS | {name: "claude-opus-5-5 at medium effort"}
self.assertEqual(reviewer_breaches(reviewer, environ, home), [])
self.assertEqual(skill_breaches(Call("Skill", {"skill": "security-review"}, checkout), environ, home), [])
def test_a_security_skill_is_held_to_the_projects_rung_on_the_projects_own_ladder(self):
checkout, home = self.project('[{"model": "claude-fable-5-2", "effort": "high"}, {"model": "claude-fable-5-2", "effort": "low"}]')
# On this ladder the worker's low effort ranks above the project's high one; on the shipped ladder it ranks below.
environ = {"LOOP_CLAUDE_PROJECT_RUNG": "claude-fable-5-2 at high effort", "LOOP_CLAUDE_WORKER_RUNG": "claude-fable-5-2 at low effort"}
self.assertEqual(skill_breaches(Call("Skill", {"skill": "security-review"}, checkout), environ, home), [])
self.assertEqual(rules(skill_breaches(Call("Skill", {"skill": "security-review"}, "/r"), environ, HOME)), ["reviewer-rung"])
self.assertEqual(rules(breaches_of(Call("Skill", {"skill": "security-review"}, "/r"), home, environ)[2]), ["reviewer-rung"])
self.assertEqual(breaches_of(Call("Skill", {"skill": "security-review"}, checkout), home, environ)[2], [])
on_the_projects = environ | {"LOOP_CLAUDE_WORKER_RUNG": "claude-fable-5-2 at high effort"}
self.assertEqual(skill_breaches(Call("Skill", {"skill": "security-review"}, checkout), on_the_projects, home), [], "a worker on the project's rung runs the skill itself")
def test_a_review_is_refused_where_the_projects_ladder_cannot_be_read_and_loop_claude_handed_rungs(self):
checkout, home = self.project("[]")
own = pathlib.Path(home, ".claude-projects", "acme", "routing-ladder.json")
reviewer = Call("Agent", {"subagent_type": "stability-reviewer", "model": "fable", "effort": "max"}, checkout)
for breaches in (reviewer_breaches(reviewer, self.ON_TWO_RUNGS, home), skill_breaches(Call("Skill", {"skill": "security-review"}, checkout), self.ON_TWO_RUNGS, home)):
self.assertEqual(rules(breaches), ["reviewer-rung"])
self.assertTrue(breaches[0].detail.startswith(f"the rung this review needs cannot be worked out: {own}: it holds no list of rungs. "), breaches[0].detail)
self.assertEqual(breaches[0].directory, checkout)
self.assertEqual(reviewer_breaches(reviewer, {}, home), [], "a claude loop-claude did not start is not checked")
self.assertEqual(reviewer_breaches(Call("Agent", {"subagent_type": "Explore"}, checkout), self.ON_TWO_RUNGS, home), [], "nor is a subagent that reviews nothing")
self.assertEqual(skill_breaches(Call("Skill", {"skill": "simplify"}, checkout), self.ON_TWO_RUNGS, home), [])
def skill_refused(self, given: dict, environ: dict[str, str] = ENVIRON, subagent_prompt: str | list | None = None) -> list[Breach]:
transcript = ""
if subagent_prompt is not None:
transcript = os.path.join(tempfile.mkdtemp(), "agent-a1.jsonl")
self.addCleanup(subprocess.run, ["rm", "-rf", os.path.dirname(transcript)])
pathlib.Path(transcript).write_text(json.dumps({"type": "user", "message": {"role": "user", "content": subagent_prompt}}) + "\n")
return skill_breaches(Call("Skill", given, "/r", "general-purpose" if subagent_prompt is not None else "", transcript, subagent_prompt is not None), environ)
return skill_breaches(Call("Skill", given, "/r", "general-purpose" if subagent_prompt is not None else "", transcript, subagent_prompt is not None), environ, HOME)
def test_a_security_skill_from_the_sessions_own_agent_is_refused_below_the_projects_rung(self):
for skill in ("/security-review", "claude-security", "claude-security:claude-security", "security-review"):
@@ -358,7 +418,7 @@ class ReviewerRung(unittest.TestCase):
with self.subTest(prompt=prompt):
self.assertEqual(rules(self.skill_refused({"skill": "security-review"}, self.ENVIRON, prompt)), [])
self.assertEqual(rules(self.skill_refused({"skill": "security-review"}, self.ABOVE, "Invoke /security-review.")), ["reviewer-rung"], "a subagent's rung is unknown, whatever the worker's")
unreadable = skill_breaches(Call("Skill", {"skill": "security-review"}, "/r", "general-purpose", "/nonexistent/agent-a1.jsonl", True), self.ENVIRON)
unreadable = skill_breaches(Call("Skill", {"skill": "security-review"}, "/r", "general-purpose", "/nonexistent/agent-a1.jsonl", True), self.ENVIRON, HOME)
self.assertEqual(rules(unreadable), ["reviewer-rung"])
def test_any_other_skill_or_a_claude_loop_claude_did_not_start_is_not_checked(self):
+4 -4
View File
@@ -4,7 +4,7 @@ import sys
import typing
from failure import Failure
from model_routing.ladder import LADDER, position, Rung
from model_routing.ladder import Ladder, Rung
from claude_code.reply import Limited
from loop_state.paths import paths_from
from loop_claude.project.model_choice import read_models_file
@@ -32,9 +32,9 @@ def projects_on(model: str, home: pathlib.Path) -> list[str] | Failure:
return sorted(key for key, on in models.items() if on == model)
def down_from(top: Rung, floor: Rung) -> list[Rung]:
"""top, the project's rung, and each rung below it, highest first, down to floor."""
return list(LADDER[position(floor):position(top) + 1])[::-1]
def down_from(ladder: Ladder, top: Rung, floor: Rung) -> list[Rung]:
"""top, the project's rung, and each rung below it on ladder, highest first, down to floor."""
return list(ladder.rungs[ladder.position(floor):ladder.position(top) + 1])[::-1]
def limited_exit(tool: str, limited: Limited) -> int:
+4 -2
View File
@@ -10,8 +10,10 @@ from rung_replay.command import down_from
from failure import Failure
from rung_replay.search import first_reply, Miss, Replay, replayed, Tried
from claude_code.reply import Limited
from model_routing.ladder_file import read_ladder, SHIPPED
from model_routing.ladder import Rung
LADDER = read_ladder(SHIPPED)
REFERENCE = Rung("claude-opus-5-5", "medium")
MIDDLE = Rung("claude-sonnet-5-5", "high")
CHEAP = Rung("claude-haiku-5-5", "max")
@@ -73,8 +75,8 @@ class FirstReply(unittest.TestCase):
class DownFrom(unittest.TestCase):
def test_runs_from_the_projects_rung_down_to_the_floor_highest_first(self):
self.assertEqual(down_from(Rung("claude-fable-5-2", "low"), MIDDLE), [Rung("claude-fable-5-2", "low"), REFERENCE, MIDDLE])
self.assertEqual(down_from(REFERENCE, MIDDLE), [REFERENCE, MIDDLE])
self.assertEqual(down_from(LADDER, Rung("claude-fable-5-2", "low"), MIDDLE), [Rung("claude-fable-5-2", "low"), REFERENCE, MIDDLE])
self.assertEqual(down_from(LADDER, REFERENCE, MIDDLE), [REFERENCE, MIDDLE])
if __name__ == "__main__":
+1 -1
View File
@@ -6,4 +6,4 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from subagent_rung import main
sys.exit(main.main(sys.argv[1:]))
sys.exit(main.main(sys.argv[1:], pathlib.Path.home()))
+24 -11
View File
@@ -7,29 +7,37 @@ a defect, a level from 1 to 4 scored as for a todo.md item. It prints the rung t
the model's cheapest rung, the project's rung, in the Agent tool's words, such as `model sonnet,
effort high`. --plan, for a task that files or scores todo.md items, prints the project's rung where
that L picks a lower one, as ~/.claude/rules/todo-items.md lets only the project's rung or above
plan. For a model off the routing ladder, the tool doesn't print anything on stdout, says so on stderr and
exits 0; launch the subagent with no model or effort.
plan. For a model off the routing ladder, the tool doesn't print anything on stdout, says so on stderr,
naming the ladder's file, and exits 0; launch the subagent with no model or effort.
Exit 1, saying why, on bad arguments.
It reads the routing ladder of the project whose checkout it runs in: routing-ladder.json in the
folder of the project's config, ~/.claude-projects/<key>/, or else the one this setup ships, as in
a checkout no config names. loop-claude --help shows the file's shape.
Exit 1, saying why, on bad arguments, or where the project's config or its routing ladder is faulty
or cannot be read.
"""
import pathlib
import re
import sys
from failure import Failure
from model_routing.ladder import Ladder
from release_plan.todo_table import LEVELS
from model_routing.ladder import planning_rung, project_rung, worker_rung
from model_routing.ladder_file import project_ladder_file, read_ladder
USAGE = f"usage: subagent-rung [--plan] <model> <L>, L a level from 1 to {LEVELS['L']}"
def agent_args(model: str, likelihood: int, planning: bool = False) -> str | None:
"""The Agent tool's model and effort for the rung likelihood picks from model's cheapest rung, never below it when planning; None for a model off the ladder."""
project = project_rung(model)
def agent_args(ladder: Ladder, model: str, likelihood: int, planning: bool = False) -> str | None:
"""The Agent tool's model and effort for the rung likelihood picks on ladder from model's cheapest rung, never below it when planning; None for a model off the ladder."""
project = ladder.project_rung(model)
if project is None:
return None
return (planning_rung if planning else worker_rung)(project, likelihood).agent_args()
return (ladder.planning_rung if planning else ladder.worker_rung)(project, likelihood).agent_args()
def main(argv: list[str]) -> int:
def main(argv: list[str], home: pathlib.Path) -> int:
if argv[:1] in (["-h"], ["--help"]):
print(__doc__.strip())
return 0
@@ -39,9 +47,14 @@ def main(argv: list[str]) -> int:
print(f"subagent-rung: cannot read the arguments{' ' + ' '.join(argv) if argv else ''}; {USAGE}", file=sys.stderr)
return 1
model, likelihood = operands
args = agent_args(model, int(likelihood), planning)
file = project_ladder_file(None, home)
ladder = file if isinstance(file, Failure) else read_ladder(file)
if isinstance(ladder, Failure):
print(f"subagent-rung: {ladder.reason}", file=sys.stderr)
return 1
args = agent_args(ladder, model, int(likelihood), planning)
if args is None:
print(f"subagent-rung: {model} is not on the routing ladder; pass the Agent tool no model or effort", file=sys.stderr)
print(f"subagent-rung: {model} is not on the routing ladder {file}; pass the Agent tool no model or effort", file=sys.stderr)
else:
print(args)
return 0
+45 -11
View File
@@ -1,33 +1,67 @@
import pathlib
import subprocess
import sys
import tempfile
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from test_env import isolated_env
from subagent_rung import main
from model_routing.ladder_file import read_ladder, SHIPPED
from project_config.test_project_config import write_config
LADDER = read_ladder(SHIPPED)
TOOL = pathlib.Path(__file__).resolve().parents[1] / "subagent-rung"
class SubagentRung(unittest.TestCase):
def run_tool(self, *args: str) -> subprocess.CompletedProcess[str]:
return subprocess.run([sys.executable, str(TOOL), *args], capture_output=True, text=True)
def setUp(self) -> None:
made = tempfile.TemporaryDirectory()
self.addCleanup(made.cleanup)
# A home with no project config, so the tool reads the ladder this setup ships, whatever the host's own projects hold.
self.home = pathlib.Path(made.name).resolve()
def run_tool(self, *args: str, cwd: pathlib.Path | None = None) -> subprocess.CompletedProcess[str]:
return subprocess.run([sys.executable, str(TOOL), *args], capture_output=True, cwd=cwd or self.home, env={**isolated_env(), "HOME": str(self.home)}, text=True)
def project(self, ladder: str) -> pathlib.Path:
"""A checkout under the home whose config's folder holds ladder as its routing ladder."""
checkout = self.home / "code" / "acme"
checkout.mkdir(parents=True)
subprocess.run(["git", "init", "--quiet", str(checkout)], check=True, env=isolated_env())
(write_config(self.home, checkout) / "routing-ladder.json").write_text(ladder)
return checkout
def test_picks_the_rung_on_the_ladder_of_the_project_it_runs_in(self):
checkout = self.project('[{"model": "claude-fable-5-2", "effort": "low"}, {"model": "claude-fable-5-2", "effort": "max"}]')
(checkout / "nested").mkdir()
# On the shipped ladder an L of 1 steps Fable 5.2 down to Opus 5.5, and an L of 4 up to its medium effort.
self.assertEqual([self.run_tool("claude-fable-5-2", level, cwd=checkout / "nested").stdout for level in ("1", "4")], ["model fable, effort low\n", "model fable, effort max\n"])
off = self.run_tool("claude-opus-5-5", "3", cwd=checkout)
own = self.home / ".claude-projects" / "acme" / "routing-ladder.json"
self.assertEqual((off.returncode, off.stdout, off.stderr), (0, "", f"subagent-rung: claude-opus-5-5 is not on the routing ladder {own}; pass the Agent tool no model or effort\n"))
def test_exits_1_naming_the_file_where_the_projects_ladder_holds_a_fault(self):
checkout = self.project('[{"model": "claude-fable-5-2", "effort": "low"},]')
refused = self.run_tool("claude-fable-5-2", "3", cwd=checkout)
self.assertEqual((refused.returncode, refused.stdout), (1, ""))
self.assertTrue(refused.stderr.startswith(f"subagent-rung: cannot read the routing ladder {self.home / '.claude-projects' / 'acme' / 'routing-ladder.json'}: "), refused.stderr)
def test_prints_the_agent_tools_model_and_effort_for_the_rung_an_l_picks(self):
self.assertEqual(main.agent_args("claude-opus-5-5", 3), "model opus, effort medium")
self.assertEqual(main.agent_args("claude-opus-5-5", 2), "model sonnet, effort high")
self.assertEqual(main.agent_args("claude-opus-5-5", 4), "model fable, effort low")
self.assertEqual(main.agent_args("claude-sonnet-5-5", 1), "model sonnet, effort high")
self.assertIsNone(main.agent_args("claude-haiku-5-5", 1))
self.assertEqual(main.agent_args(LADDER, "claude-opus-5-5", 3), "model opus, effort medium")
self.assertEqual(main.agent_args(LADDER, "claude-opus-5-5", 2), "model sonnet, effort high")
self.assertEqual(main.agent_args(LADDER, "claude-opus-5-5", 4), "model fable, effort low")
self.assertEqual(main.agent_args(LADDER, "claude-sonnet-5-5", 1), "model sonnet, effort high")
self.assertIsNone(main.agent_args(LADDER, "claude-haiku-5-5", 1))
def test_a_planning_task_never_runs_below_the_projects_rung(self):
self.assertEqual(main.agent_args("claude-opus-5-5", 1, planning=True), "model opus, effort medium")
self.assertEqual(main.agent_args("claude-opus-5-5", 4, planning=True), "model fable, effort low")
self.assertEqual(main.agent_args(LADDER, "claude-opus-5-5", 1, planning=True), "model opus, effort medium")
self.assertEqual(main.agent_args(LADDER, "claude-opus-5-5", 4, planning=True), "model fable, effort low")
self.assertEqual(self.run_tool("--plan", "claude-opus-5-5", "2").stdout, "model opus, effort medium\n")
def test_picks_nothing_for_a_model_off_the_ladder(self):
self.assertIsNone(main.agent_args("claude-opus-5", 3))
self.assertIsNone(main.agent_args(LADDER, "claude-opus-5", 3))
def test_refuses_an_l_outside_1_to_4_or_a_wrong_count_of_arguments(self):
for argv in (["claude-opus-5-5", "0"], ["claude-opus-5-5", "01"], ["claude-opus-5-5", "5"], ["claude-opus-5-5", "x"], ["claude-opus-5-5"], ["3", "claude-opus-5-5"], ["claude-opus-5-5", "3", "--plan"], ["--planning", "claude-opus-5-5", "3"]):
@@ -43,7 +77,7 @@ class SubagentRung(unittest.TestCase):
def test_the_launcher_prints_nothing_and_says_why_and_exits_0_off_the_ladder(self):
off = self.run_tool("claude-opus-5", "4")
self.assertEqual((off.returncode, off.stdout), (0, ""))
self.assertEqual(off.stderr, "subagent-rung: claude-opus-5 is not on the routing ladder; pass the Agent tool no model or effort\n")
self.assertEqual(off.stderr, f"subagent-rung: claude-opus-5 is not on the routing ladder {SHIPPED}; pass the Agent tool no model or effort\n")
def test_the_launcher_accepts_an_l_of_1(self):
self.assertEqual(self.run_tool("claude-opus-5-5", "1").stdout, "model sonnet, effort high\n")
+54
View File
@@ -3819,3 +3819,57 @@ Inherited architect, decided by:
- Locality: `bin/review_rules/review_folder.py:17` `made_review_folder`: `home` is passed in from the command table, so each unit's inputs show in its signature; at the base `Path.home()` was read deep inside
- Shape: `bin/larv_review/scoring_setup.py:169` `prepare_scoring`: counts against the change: about 75 lines with a dozen early returns, and `prompt_parts` builds one path twice
- Shape: `bin/review_rules/round_titles.py:13` `OPENING`: the round-title spelling is written once next to the regexes that parse it
## 2026-11-15T21:26:29Z, PR #554 at bcb04e3
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|---|---|---|---|---|---|
| Junior A | 6.5 | 5 | 5.5 | 5 | 5.5 |
| Mid A | 7 | 6 | 6.5 | 6 | 6.5 |
| Maintainability senior | 7 | 5.5 | 6 | 6 | 6 |
| Inherited architect | 6.5 | 6 | 5.5 | 5.5 | 6 |
| Mean | 6.75 | 5.63 | 5.88 | 5.63 | 6.00 |
Junior A, hardest first:
- Locality, Self-sufficiency: `bin/loop_claude/routing.py:113` `unfinished_route`: five rung notions, two step-up counters and a seven-row verdict table at once, and the reasons in the decision log
- Shape: `bin/release_plan/release_standing.py:162` `next_release`: many edge-case branches and `str | None | Failure` threaded through every field of `LastCut`
- Locality, Shape: `bin/loop_claude/cycle/run.py:151` `rule`: judges, stamps, annotates, steps the rung up and archives, and no single unit owns the archive's order
- Self-sufficiency: `bin/loop_claude/cycle/judge.py:22` `INTERRUPT_RULES`: policy partly in prompt text and partly in Python checks, with nothing saying which the code enforces
- Locality: `bin/loop_claude/loop/reload.py:95` `exec_if_edited`: an edit to any `.py` under `bin/` makes a running loop re-exec, and a renamed `LoopRun` field breaks the reload
- Shape: `bin/model_routing/ladder.py:86` `review_rung`: a three-way rule whose docstring quotes a whole decision title
- Self-sufficiency: `bin/larv_review/main.py:1` module docstring: twelve subcommands' rules in about 155 lines of prose that cross-reference SKILL.md
- Shape: `bin/loop_claude/loop/chunk_start.py:24` `fetched_todo`: nearly the same plan read as `fetched_plan`, told apart only by a docstring
Mid A, hardest first:
- Shape: `bin/release_plan/release_standing.py:162` `next_release`: a three-state tag, `BEFORE_FIRST_RELEASE`, `nothing_cut` and `is_earliest` held at once, and comments that explain each branch alone
- Locality: `bin/loop_claude/routing.py:113` `unfinished_route`: five rungs, the escalation mark and the unfinished count feed one answer across three files
- Locality, Shape: `bin/chunk_pr/main.py:298` `merged`: a while loop around the queue turn, variables bound only on some paths, and no comment stating the loop's invariant
- Shape: `bin/chunk_preflight/main.py:128` `preflight`: lines 142-143 pack a conditional re-`located` and an eight-argument `Gathered` into two lines
- Shape: `bin/release_plan/ranking.py:48` `rank`: two table shapes branch through the whole module, and the defect rule sits far from where scores are read
- Self-sufficiency: `bin/larv_review/plan.py:77` `plan_reasons`: six inputs joined into one answer, and why each matters is in SKILL.md §3
- Shape: `bin/rule_hook/env_file.py:34` `reaching`: `and` and `or` mixed without parentheses, and four path spellings in a lookaround regex
- Self-sufficiency: `bin/loop_claude/cycle/judge.py:197` `quotes_checked`: long prompt text inside the `Reply` field metadata mixes the prompt with the schema
Maintainability senior, hardest first:
- Locality, Shape: `bin/chunk_pr/main.py:298` `merged`: a while loop holding a queue turn, approval waits and a `done` set only on some paths, with no loop invariant stated
- Locality, Self-sufficiency: `bin/loop_claude/routing.py:113` `unfinished_route`: five rungs, the escalation count and the mark from another file, and each step's reason in the decision log
- Locality, Self-sufficiency: `skills/larv-review/SKILL.md:146` "Comprehension check": paragraphs of four or five conditions, each pointing to a hook, a CLI's help or another rule file
- Shape: `bin/release_plan/release_standing.py:162` `next_release`: three sources of a cut, the `is_earliest` expression and `LastCut` fields typed `str | None | Failure`
- Shape: `bin/release_plan/ranking.py:136` `weigh`: two live table shapes double every path, and `Shape` is built from positional tuples of callables
- Locality, Shape: `bin/loop_claude/cycle/run.py:151` `rule`: judges, stamps, archives and steps up, beside a 17-field `Cycle` passed around whole
- Shape: `bin/chunk_pr/main.py:438` `remeasure`: control flow inside chained `isinstance(x, Failure) or …` expressions, and `finished` unpacks five runs by position
- Shape: `bin/chunk_preflight/main.py:128` `preflight`: the whole fallback logic packed into lines 142-143
Inherited architect, would restructure first:
- Navigation, Shape: `README.md:193` the `bin/` roles: about 70 flat entries under `bin/`, where only this list tells a tool from a library
- Navigation, Shape: `bin/larv_review/main.py:222` `COMMANDS`: the package named for the review mostly holds the comprehension check, and the review loop is prose in SKILL.md
- Locality, Shape: `bin/chunk_pr/main.py:384` `levelled_and_finished`: merges, finishes items, pushes, asks whether a scoring run is owed and remeasures under a name that gives two of the five
- Locality: `bin/chunk_pr/main.py:349` `unplanned`: matches the error text of `todo-item show`, as `finished` does, where `plan_store` reads the plan
- Navigation: `bin/rule_hook/round_cap.py:10` `round_cap_breaches`: the round cap is enforced in the hook, not in `larv_review`, where a reader looks first
- Shape: `bin/deploy_release/forge.py:1` module: the forge lives in `deploy_release` and in `chunk_preflight.choices.forge_of`, neither a home its name gives
- Shape: `bin/rule_hook/rules.py:26` `RULES`: the file is the registry and also four rules' checkers, so where a new rule goes is undecided
- Self-sufficiency: `bin/plan_store/stores.py:5` module docstring: cites plan items 365, 366 and 368 as part of the contract, as routing and ladder code cite decisions
+24 -5
View File
@@ -15,6 +15,7 @@ Each project principle states one rule that the decisions below apply; their ent
- bin/: a test parametrizes its cases with `subTest`, since pytest's `parametrize` doesn't reach a unittest `TestCase`
- bin/: the tools run on the host's Python, with no container, and so do their tests outside CI
- bin/: the tools support only the latest stable Python, and the tests, written in plain unittest, run on it in four pytest-xdist workers
- chunk-pr: the chunks of a project merge one at a time on a machine, each finishing its plan items in its turn, and a pull request that waits for an approval leaves the queue while it waits
- deploy: this repo keeps no `AGENTS.md`, since `~/.claude` is its checkout; its principles and decision titles head `docs/decisions.md`, its working rules follow them there, and its `.claude/settings.json` excludes every `.claude/CLAUDE.md`, so a session in the clone loads only the clone's `CLAUDE.md`
- loop-claude: each verdict records the claude-config release and commit that ran it, the raw tokens each thread spent by model and kind since the previous outcome that recorded a spend, and the human's typed answer the judge quotes as reversing a choice the worker took on its own recommendation
- loop-claude: one session per running loop of a project, named after the slot the loop holds, its id derived from that name; a chunk's commit in the config's folder takes only the file it changed
@@ -78,6 +79,20 @@ Valid while the archive's file names, the Vocabulary and the panel keep these wo
2026-10-28, lilleman, through todo item 245. Serves goal 1.5: the suite gates every chunk. The suite took 198 s, 102 s of which went to rerunning it on the oldest Python README Install named, 3.11. README Install now asks for the latest stable Python as `python3`, and mypy checks every tool under `bin/` for the version Install names. README's Test line runs the tests in four pytest-xdist workers through `uvx`: 29 s on a 16-CPU machine. Four is one heavy slot's CPUs, `CPUS_PER_SLOT` in `bin/machine_load/slots.py`, so a gate under `run-heavy` loads only the slot it waits for. The line pins pytest and pytest-xdist, as `test_types.py` pins mypy, so every machine runs the gate the same way. It passes the path of `python3`, since `uvx --python python3` picks a Python uv installed itself, which may be older. The tests use stdlib `unittest` alone, and pytest only runs them, so plain `python3 -m unittest` runs the same tests one at a time and another runner can replace pytest. Valid while every machine taking the checkout gets the latest stable Python soon after its release.
## chunk-pr: the chunks of a project merge one at a time on a machine, each finishing its plan items in its turn, and a pull request that waits for an approval leaves the queue while it waits
2026-11-15, lilleman's call of 2026-11-13 in item 374, which split item 361. Serves goals 1.5 and 1.4: with several chunks open, every chunk removed its item from `todo.md` and added a bullet to `CHANGELOG.md` in its branch, so each merge left the others a conflict, a gate rerun and often a review round. `chunk-pr merge --finish <ID>` now makes those edits in the chunk's turn, on top of every chunk merged before. The worker's choices follow. The first differs from the call, and the rest settle what it left open:
- **A merge of the default branch, where the call said rebase.** A rebase rewrites commits the pull request already shows. The forge then drops the approval and the review threads' places. rule-hook counts a pass's rounds by the branch's commit titles, and a rebase gives each of those commits a new hash. `chunk-pr sync` already merges, and the turn reuses it.
- **The queue is a file in the git folder the checkout's worktrees share**, held with flock for the turn (`bin/chunk_pr/main.py` → `QUEUE`). Every chunk of the project on the machine finds it without a config or a key. Two machines don't share it: there the second chunk merges without the first one's changes in its head, unless the branch protection requires an up-to-date branch. A turn lasts as long as its checks, which chunk-pr waits 30 minutes for on Gitea. So a merge waits 30 minutes for its turn, then fails naming the pull request that held the queue last, whose number the holder writes into the file.
- **The turn holds the queue through the checks**, so what merges is what the checks ran on. A project without forge checks waits the minute `chunk-pr --help` names.
- **The wait for an approval is outside the turn.** The first turn pushes the finished branch, so the approver reads what merges. Once approved, the pull request takes a new turn. Where the default branch moved meanwhile, that turn merges it in, and a branch protection that dismisses approvals on a push asks the approver again. A finish that fails is pushed with whatever the turn merged in, so the pull request's head stays the commit checked out. `larv-review scoring-run-owed` runs after the finish is committed, since it counts as shipped the items the committed plan no longer holds.
- **A reviewer's comment ends the wait, in place of the loop watching for one.** `chunk-pr merge` runs in the worker's own session, so its failure is what resumes the worker, which answers and runs it again. A comment that waits is a review thread nobody resolved whose last comment someone other than the pull request's author wrote: the worker answers as that author, so an answered thread waits for the reviewer again. A comment outside a thread doesn't end the wait, since bots write those too. An approved pull request with such a thread stays unmerged too: a client's reviewer who approves and asks for one more thing gets an answer first.
- **A paired ruling runs again once the default branch has moved past it**, on the last measured commit as before: `review: the comprehension check records …` says why the base stays. `chunk-pr merge` stops while the default branch holds commits the branch's last commit of a ruling doesn't, whoever merged them in: the turn, `chunk-pr sync` or the worker after a conflict. What the ruling says never stops the merge (project principle 2). A scoring run reads no base, so it stays.
- **An item the plan doesn't hold is named on merge's last line, not refused.** chunk-pr cannot tell an item an earlier run finished from a mistyped ID, so the reader does. Such a run still commits the plan and the changelog, since the earlier run may have stopped between `todo-item finish` and its commit. chunk-pr checks that an ID is a number before its turn, and leaves every other rule of `todo-item finish` to that tool.
Valid while a chunk's worker runs `chunk-pr merge` itself, and one machine runs a project's loops.
## chunks: a chunk takes every unblocked item of its release that fires the same review passes, whatever its purpose, and an item above R 5 ships alone
2026-10-22, lilleman, through todo item 217. Serves goal 1.4: each review has a fixed cost, so more items per chunk cost less per item. Across the 165 finished chunks loop-claude archived up to that day, a chunk took a median of 1.30M tokens with one item and 1.33M with two, and three in four chunks shipped one item. The old rule also asked one PR title to state what the items achieve together; lilleman dropped it, since unrelated items that fire the same passes cost one review.
@@ -284,7 +299,7 @@ Valid while the later fixes per finished chunk, which `score-outcomes` and the r
- **A bench of readers picked the spelling.** Three fresh readers, seated as the person who writes a client's `config.toml`, each picked `decisions = "confluence:https://<site>/wiki/spaces/<space>/pages/<page ID>"`, pasted from the browser with or without the title at its end, over the bare address, a page ID beside a `confluence-site` key, and a table. Each named the match with `jira:`. Any of the five records may name a page; the goals file, the plan, the working rules and the principles may not.
- **`decisions` and `comprehension-history` may name a page only where `plan` names a Jira epic.** rule-hook ranks a plan kept as a file before tool calls, inside its 30-second limit, and ranking reads those two records. A Confluence read and two adf-codec container runs would hold up every guarded tool call, and fail it while Confluence is down. `load` refuses goals in Jira beside a plan in a file for the same reason.
- **A write sends the version number the store read, plus one, and Confluence refuses it with 409 where someone saved the page since.** The store then fails, saying to ask the human, and doesn't write the page; the loop never overwrites a teammate's edit on its own (lilleman, 2026-11-12). A write with no read before it replaces the page as it stands, as the record contract asks.
- **`project-record` keeps the version `open` read in a file beside its copy**, `~/.local/state/project-record/<key>/<record>.version`, since `save` runs in a later process. The store keeps the version itself, so `write` still takes only the text. Every other tool reads and writes a record in one process, and its store keeps the version in memory, so a read by another tool, such as larv-review's, never moves the version an edit in `project-record` rests on.
- **`project-record` keeps the version `open` read in a file beside its copy**, `~/.local/state/project-record/<key>/<worktree>/<record>.version`, since `save` runs in a later process. The store keeps the version itself, so `write` still takes only the text. Every other tool reads and writes a record in one process, and its store keeps the version in memory, so a read by another tool, such as larv-review's, never moves the version an edit in `project-record` rests on. The folder `<worktree>` is named for the worktree that ran `open`, and `open` removes the folders of worktrees git no longer lists, so a chunk's copy doesn't outlive its worktree.
- **The page holds ADF, which adf-codec converts both ways**, so a teammate reads the record as Confluence renders it. Where adf-codec cannot convert the markdown, the write fails with adf-codec's error. A node markdown cannot hold reads as text: a mention as its name, a macro as `_(<macro> not included)_`. So the next write replaces it with that text, and a record page should hold only what markdown can.
## project config: a tool that reads a file's commits says where it does not support that file, and the work goes on
@@ -320,7 +335,7 @@ Messages keep each file's usual name, such as `todo.md`, as its label, since the
- **A bench of readers picked the spelling.** Three fresh readers, seated as the person who writes a client's `config.toml`, each picked `plan = "jira:https://<site>/browse/<key>"` over the bare address, a `jira:<key>` beside a `jira-site` key, and a `[plan]` table. Each also picked one pair of env-file keys, `ATLASSIAN_EMAIL` and `ATLASSIAN_API_TOKEN`, for Jira and Confluence over a pair for each, since one account's token opens both.
- **An item's ID stays a whole number: the issue's number in the epic's Jira project.** About 30 modules read an ID as an int, and the `branch` and title templates already spell a ticket's name, as `ABC-{id}`. So the store refuses a child issue from another Jira project, and counts a blocker only among the plan's own items (`bin/plan_store/jira_epic.py`).
- **The scores sit in one issue property, `plan-item`**, which needs no Jira admin (lilleman, 2026-11-12). An issue without it reads as an item nobody scored.
- **The release is the earliest Fix Version named as a semver version**, and an issue with none fails the read, naming it, until todo.md's item 359 ties releases to something else.
- **The release is the earliest Fix Version named as a semver version**, and an issue with none fails the read, naming it.
- **The loop files an item as a Task under the epic, and marks it as its own** (lilleman's calls of 2026-11-12). `"Filed by": "loop"` in the `plan-item` property tells such an issue from one a person filed, whose summary and description the loop never edits. Task is an issue type every Jira Software project template has; a project without it refuses the issue, saying so. The issue takes the project's Fix Version named as the release, with a leading v or without, and the store refuses an item whose release the project has no Fix Version for, before it files anything. A security finding also gets the label `security`, and its text never holds a secret's value. Jira ranks the new issue last, and no bar or goals check applies, until todo.md's item 384 says where a plan in Jira states its formula. Jira takes a blocker's link only after the issue exists, so the store first checks that each blocker is an open child. A link Jira still refuses leaves the issue filed: the write counts as landed, with a note naming the link to make by hand. A failed create says the issue may exist all the same, since a lost answer doesn't tell.
- **The store reads, files and finishes, and doesn't edit an issue** until todo.md's item 382. It finishes an item with the transition that the config's `jira-finish-transition` names, which must lead to the status `jira-finish-status` names, since each Jira workflow differs (lilleman's call, 2026-11-12); any open child of the epic may move. It refuses a status outside Jira's done status category: the read counts an issue as finished only in that category, so the item would stay in the plan. Where the issue's present status has no direct transition to the status `jira-finish-status` names, `todo-item finish` fails and a person moves the issue in Jira: the store never walks an issue through other statuses to reach it. lilleman answered on 2026-11-15: "If it is possible to move it to done without a transisiont, that should happen. If not, fail." The implementer read "without a transition" as "without a transition in between". `rank_todo.py` refuses to rank a plan in Jira, and its `--check` passes, since Jira's backlog ranks it; rule-hook's rank check skips it. Each read first asks Jira for the epic itself, since a search under an epic the account cannot see answers no issues, as a finished plan does.
@@ -388,6 +403,8 @@ The base is the last measured commit: the default branch's newest merged change
2026-11-11, lilleman. Serves goal 1.1. Item 296 made `chunk-pr merge` refuse while a scoring run the plan calls is unrecorded on the branch, so a missing run can block a merge. No score or ruling does, and the titles say so: "no score blocks a merge".
2026-11-15, lilleman, on the worker's proposal in item 374, replacing the call of 2026-11-13. The call asked that a ruling never charge one chunk with another's change, by reading against the new base after a rebase. Only the release review runs a paired ruling, and it measures the whole release, so its base stays the last measured commit. What another chunk's merge changes is the head: a ruling recorded before the merge came in read a head that never merges. So `chunk-pr merge` stops where the default branch has moved since the branch last recorded a paired ruling, and the worker runs the ruling again at the new head.
## review: the premises chunk's whole review is the human's approval
2026-09-20, lilleman. Serves goal 1.1. A reviewer's finding on that chunk could only be declined by citing the goals the chunk exists to write. Valid while every decline must name a goal or a technical principle.
@@ -551,9 +568,9 @@ On 2026-11-12, `bin/judge-replay claude-opus-5-5` replayed 60 verdicts, 15 of ea
Valid while the archived verdicts show what a judge should return, and until a new model joins the ladder: replay then.
## routing: one ladder of (model, effort) rungs, ordered by the Artificial Analysis Intelligence Index; a task's L picks its worker's rung and its E + I its reviewers', by fixed steps counted from the cheapest rung of the project's model
## routing: one ladder of (model, effort) rungs, ordered by the Artificial Analysis Intelligence Index, shipped as `bin/model_routing/routing-ladder.json`, which a project may replace with a file of that name in its config's folder; a task's L picks its worker's rung and its E + I its reviewers', by fixed steps counted from the cheapest rung of the project's model
2026-10-14, lilleman. Serves goal 1.4, and goal 1.3: one ladder, the same in every project, read by loop-claude and by the worker through `bin/subagent-rung`. The judge's rung is set by `routing: on a model judge-replay covered`. `bin/model_routing/ladder.py` holds the rungs and the steps.
2026-10-14, lilleman. Serves goal 1.4, and goal 1.3: one shipped ladder and one set of steps for every project, read by loop-claude and by the worker through `bin/subagent-rung`; a project runs on other rungs only through a ladder file of its own (2026-11-15 note). The judge's rung is set by `routing: on a model judge-replay covered`. `bin/model_routing/routing-ladder.json` holds the rungs and `ladder.py` beside it the steps.
The rungs, least competent first: 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. The 2026-11-11 note below put them so. Before it they were Sonnet 5.5 at high; Opus 5.5 at medium, high, xhigh and max; Fable 5.1 at max, after the 2026-10-29 note took Haiku 5.5 off. They first were: Haiku 5.5 at low, medium, high, xhigh and max; Sonnet 5.5 at high; Opus 5.5 at medium, high, xhigh and max; Fable 5.1 at max. The order and the cut come from the Artificial Analysis Intelligence Index (https://artificialanalysis.ai/leaderboards/models), which scores each model at each effort and gives a cost per task. A rung stays only where no cheaper rung scores as high, so a step up always buys more score (goal 1.4). The first cut, from the index read 2026-10-14, dropped Sonnet 5.5 at low, medium, xhigh and max, Opus 5.5 at low, and every Fable 5.1 rung, and every tie in the index fell among the dropped rungs. lilleman put Fable 5.1 at max back on top: the index scored it under Opus 5.5 at high, but Anthropic's model catalog names Fable the most capable model, and for the hardest tasks lilleman wants the highest quality at any price. Fable 5.2 at max tops the index outright, so that exception has ended.
@@ -573,6 +590,8 @@ A project's rung is its model's cheapest rung, which for Opus 5.5 is its default
2026-11-14, lilleman ruled that L 3 is to step one rung up and L 4 two up, in every project and for delegated subagents. The steps stated above, L 3 none and L 4 one up, hold until `bin/model_routing/ladder.py` changes. Then, on an Opus 5.5 project, an L 3 worker or subagent runs on Fable 5.2 at low, and an escalation stops without lilleman's yes at Opus 5.5 at xhigh. An L 4 one runs on Fable 5.2 at medium, and stops at Fable 5.2 at high. The ruling settles the two calls of the routing figures measured at 2026-11-14T00:59:50Z, which were not yet in `routing-calls-raised.md`; the chunk that settles them cites their stamp there. The figures came from 276 chunks finished since the 2026-10-29 reset. Chunks started on Opus 5.5 at medium, 79 of them, took a mean 0.8 review rounds past each pass's first, 0.3 unfinished verdicts and 0.2 later fixes. Chunks started on Fable 5.2 at low, 5 of them, took 0.4, 0.0 and 0.0. On an Opus 5.5 project only L 4 items start on Fable 5.2 at low, so it did better on harder items. Two things weaken the evidence: 5 chunks is the fewest a call allows, and the Opus 5.5 figures include chunks from before Fable 5.2 joined the ladder. On the 2026-11-11 index, an L 3 task's cost rises about 1.3 times, from $2.45 to $3.10, for fewer rounds and fewer unfinished verdicts (goal 1.4). The chunks started on Sonnet 5.5 at high, 164 of the 276, don't move.
2026-11-15, lilleman asked for the ladder as a file that a project can replace, on a day when an outage left only Fable 5.2 answering: the rungs were a constant in `bin/model_routing/ladder.py`, so no project could leave Sonnet 5.5 and Opus 5.5 without a release. The shipped ladder is `bin/model_routing/routing-ladder.json`, a JSON list of rungs, least competent first. A project that keeps a `routing-ladder.json` in its config's folder, `~/.claude-projects/<key>/`, runs on that ladder whole, and the steps count on it as on the shipped one. Every project still runs the same routing rules and steps, so the workflow of goal 1.3 holds; the ladder joins what a project's config folder may supply, which that goal's list does not name yet. lilleman chose a file per project over one per machine, so a single project can differ. A ladder holds one model of each family, since the Agent tool launches a subagent or a review by its family's name. The project's file is lilleman's to write, as any change to the ladder is, and the loop never commits it. loop-claude reads the project's ladder as each cycle starts; `subagent-rung` and rule-hook's `reviewer-rung` read it each time they run, from the checkout they run in. A ladder file that holds a fault stops each of them, since work routed on the shipped ladder in its place could run on a model the project cannot reach. The routing figures, `judge-replay` and `review-replay` span every project, so they read the shipped ladder: a rung only a project's own ladder holds is left out of the figures' calls, and no replay qualifies it. lilleman shipped the change as 0.10.1, a patch cut from the tag v0.10.0, on the day of the outage: it adds a file format and an exit 1 to `subagent-rung`, which the technical principles' semantic versioning gives a minor, and lilleman asked for the patch "even if that breaks semver", so that the release in use could run again without taking the unreleased work on `main`.
Valid while the index ranks these models, and while no newer model joins the catalog.
## routing: the worker changes rung only as a chunk starts, after every second unfinished verdict, when it names a chunk item that picks a higher rung, or when it cites an escalation trigger the judge finds
@@ -679,7 +698,7 @@ Valid while the worker writes the tests that larv-review's reviewers hold to the
- **The spelling.** A `Touches:` line, then one bullet per file: the path in backticks, then its parts, each a name in backticks or `lines <first>-<last>`, with `(small)` after a part the item changes only a little; a path or a name that holds a backtick takes a longer run of backticks with a space inside each end, as a Markdown code span does. A path alone is the whole file. Three readers seated as the README's audience picked the bulleted list over one line and over a table, since backticks hold a heading's commas, colons and parentheses. Two of the three put `(small)` after the part and outside the backticks, and two left line ranges unquoted. Each picked a different config key: `touch-predictions` was one reader's first choice and the second choice of the other two.
- **A part's boundaries.** Python's `ast` module names the innermost function or class, a top-level assignment by the name it sets, and `(module)` for the rest. A Markdown file's parts are its headings outside fenced code. Any other file, and Python that doesn't parse, falls back to line ranges. A table row is no part of its own: the item named one, but the tables chunks collide on are the plan's and the changelog's, which don't count.
- **What doesn't count.** The plan and every record the config names, the changelog among them, since every chunk writes them: `todo.md` item 374 writes the plan and the changelog at merge time, and the other records are appended to. `touch-predictions record` leaves them out of what a chunk touched, and the rule keeps them out of predictions.
- **What doesn't count.** The plan and every record the config names, the changelog among them, since every chunk writes them: `chunk-pr merge --finish` writes the plan and the changelog at merge time, and the other records are appended to. `touch-predictions record` leaves them out of what a chunk touched, and the rule keeps them out of predictions.
- **The pick.** `chunk-preflight` takes the items of the next release that don't wait, in the plan's order, each where it overlaps neither the next item nor an item taken before it. The call asked for the set that keeps the most chunks running. The plan's order comes first all the same: the largest set could start a low-ranked item in place of one ranked above it, and with more ready items than the parallel limit, either set fills the limit. `todo.md` item 375 takes as many of the picked items as its limit allows.
- **An overlap that is taken.** Two items may share a part where either marks it `(small)`. The call takes an overlap only for a small change to the same part, and a few lines re-apply onto whatever the other chunk did to it.
- **Which items share a chunk** stays the worker's choice, by the review passes they fire, so the pick names items, and an item the next chunk takes starts no chunk of its own.
+49
View File
@@ -2249,3 +2249,52 @@ Read most (opens and searches):
- `bin/plan_store/stores.py` 2
- `docs/decisions.md` 2
- `CHANGELOG.md` 1
## Reading cost, chunk ba82c458ad98, finished 2026-11-15T13:51:17Z
120652 new input tokens before the first commit.
Read most (opens and searches):
- `docs/decisions.md` 10
- `bin/loop_claude/test_black_box.py` 8
- `bin/loop_claude/loop/usage.py` 5
- `CHANGELOG.md` 3
- `CLAUDE.md` 3
- `bin/claude_code/session.py` 2
- `bin/command_lines/shell_command.py` 2
- `bin/loop_claude/loop/main.py` 2
- `rules/todo-items.md` 2
- `README.md` 1
## Reading cost, chunk 8026e60ea27c, finished 2026-11-15T21:44:03Z
199967 new input tokens before the first commit.
Read most (opens and searches):
- `docs/decisions.md` 11
- `bin/chunk_pr/test_chunk_pr.py` 8
- `skills/larv-review/SKILL.md` 8
- `CLAUDE.md` 5
- `README.md` 5
- `bin/chunk_pr/main.py` 5
- `bin/project_config/templates.py` 4
- `rules/todo-items.md` 4
- `bin/project_config/main.py` 3
- `bin/chunk_pr/approval.py` 2
## Reading cost, chunk 0851f830bb67, finished 2026-11-15T22:41:58Z
50560 new input tokens before the first commit.
Read most (opens and searches):
- `README.md` 1
- `bin/project_config/main.py` 1
- `bin/project_config/settings.py` 1
- `bin/project_record/main.py` 1
- `bin/project_record/test_project_record.py` 1
- `docs/decisions.md` 1
- `rules/decisions.md` 1
- `settings.json` 1
+1 -1
View File
@@ -2,7 +2,7 @@
paths:
- "**/AGENTS.md"
- "**/docs/decisions.md"
- "**/project-record/*/decisions.md"
- "**/project-record/*/*/decisions.md"
---
# Decisions: one home, each linked to a goal or a technical principle
+11 -5
View File
@@ -145,7 +145,7 @@ Launch one principles-auditor on the trigger in §3, so the project is read once
### Comprehension check
The comprehension check records how hard the project is for its contributor to read (`~/.claude/rules/goals-and-audience.md`), and no score blocks a merge; only a run the plan calls and the branch lacks does, per "Scoring run". Simulated readers, the seats, launched per `~/.claude/skills/comprehension-panel/SKILL.md`, each read the whole project, not the diff. It reports no findings and is no pass: it runs once, in §5, after every pass is done, the auto-reviewer included, so it reads the branch as review left it. It runs a paired ruling in the release review, even where an opt-out skips its architect, and a scoring run where one is due. It skips only as "Opt-out" or "Suspended" below says.
The comprehension check records how hard the project is for its contributor to read (`~/.claude/rules/goals-and-audience.md`), and no score blocks a merge; only a run the plan calls and the branch lacks does, per "Scoring run". Simulated readers, the seats, launched per `~/.claude/skills/comprehension-panel/SKILL.md`, each read the whole project, not the diff. It reports no findings and is no pass: it runs in §5, after every pass is done, the auto-reviewer included, so it reads the branch as review left it. It runs a paired ruling in the release review, even where an opt-out skips its architect, and a scoring run where one is due. It skips only as "Opt-out" or "Suspended" below says.
**Paired ruling.** Each seat votes whether the project reads better, the same or worse at this branch's head than at the base.
@@ -153,7 +153,7 @@ The comprehension check records how hard the project is for its contributor to r
- **Head.** The head holds `origin/<default branch>`, merged in at §4 step 1, so it differs from the default branch only by this branch's change.
- **Seats.** Mid A and the inherited architect. Write what they read and their replies into a votes file in the chunk's review folder, in the shape `~/.claude/bin/larv-review --help` shows, and run `~/.claude/bin/larv-review record-ruling <votes file>`. On `Split:`, launch the maintainability senior and Junior A together, add their lines, and run it again.
**Scoring run**, when `~/.claude/bin/larv-review needs-scoring-run <the IDs of the items the chunk ships, if any>` prints `Scoring run due:`. Run `needs-scoring-run` before removing the chunk's items from `todo.md`. `chunk-pr merge` refuses until the branch's committed history records every run the plan calls, which `larv-review scoring-run-owed` counts at merge time from the merge base; an earlier due line is only a snapshot.
**Scoring run**, when `~/.claude/bin/larv-review needs-scoring-run <the IDs of the items the chunk ships, if any>` prints `Scoring run due:`. `chunk-pr merge` refuses until the branch's committed history records every run the plan calls, which `larv-review scoring-run-owed` counts at merge time from the merge base; an earlier due line is only a snapshot.
- **Seats.** Junior A, Mid A, the maintainability senior and the inherited architect each score the project at the head from 1 to 10 overall and on four dimensions: Navigation, Locality, Shape and Self-sufficiency. Run `~/.claude/bin/larv-review prepare-scoring`, adding `--preloaded <text>` only where its default list of pre-loaded files is wrong. It makes the worktree the seats read and prints each seat's prompt file; launch each seat with its file's text as its prompt. Write their lines into a scores file and run `~/.claude/bin/larv-review record-scoring <scores file> <the same item IDs>`, which appends the run to the history and prints the four seats' means.
- **Floor item.** Where `record-scoring` prints `Floor:`, a `Next:` line follows: file one floor item, or refresh the open one. A floor item is a plan item meant to bring every mean to the project's readability floor, which `record-scoring`'s `Floor:` line names. File it as one ambitious refactor, not touch-ups. It restructures the area behind the places `larv-review places` prints for this run, chosen where they bear on the lowest dimension, sized to bring every mean to that floor, and quotes those places. Its tagline opens with `Reach the comprehension floor:`, so its own chunk runs a scoring run; while a mean stays under the floor, that run's `Next:` line asks for the next floor item. Mark it `owner`, since the human asked that such a project always hold one, so no score deletes it. Put it in the earliest release the plan names after the one the chunk ships into, or else in the next version after that one that `~/.claude/rules/todo-items.md` allows, so the floor doesn't hold up any release. While one is open, refresh its places and aim from the newest run instead of filing another; the item the chunk ships doesn't count as open. Commit it with the run, as "Record" says.
@@ -200,9 +200,15 @@ Launch prose-reviewer with what the diff touched and every section this review c
## 5. Goal alignment, then merge
1. Read the finished PR against the goals file's goals and code health, unless that file voids it: does anything in it work against one? It breaks a maintain goal → do not merge; redesign the change or drop its item. It works against an achieve goal → do not merge; ask the human, stating the conflict.
2. Run the comprehension check (§3) where it runs; it runs once. When `origin/<default branch>` moves after that, return to §4, and keep the ruling and scoring run already recorded.
3. Run `~/.claude/bin/touch-predictions record <ID>...` in the worktree, naming the chunk's items: it records what they were predicted to touch beside what the branch touched, where the project's config names that record. A later pass through this step, after a return to §4, skips it, since the items have left the plan. Then remove the chunk's items from `todo.md` per `~/.claude/CLAUDE.md` → "Working loop" in the branch. Commit and push both; the commit re-enters no pass.
4. Aligned and every pass done → **merge** with `~/.claude/bin/chunk-pr merge`, run in the background with its `timeout` set to 7200000 ms, since its wait can outlast the Bash tool's default. It waits for the pull request's checks to pass, and for a human's approval where the project's config sets `wait-for-approval` (`chunk-pr --help`), then takes the first merge method the repository allows on its forge. A repo whose `AGENTS.md` names another method merges that way with the forge's CLI instead, once the pull request's checks pass, `~/.claude/bin/larv-review scoring-run-owed` exits 0 and, where `~/.claude/bin/project-config wait-for-approval` prints `true`, GitHub reports the pull request approved. A repo withholds this in its `AGENTS.md` → leave the PR ready and unmerged, and say which line withheld it.
2. Run the comprehension check (§3) where it runs. When `origin/<default branch>` moves after that, return to §4, and keep the scoring run already recorded. Where the chunk recorded a paired ruling, run it again at the new head and record it: it read the head before the other chunk's merge came in.
3. Run `~/.claude/bin/touch-predictions record <ID>...` in the worktree, naming the chunk's items: it records what they were predicted to touch beside what the branch touched, where the project's config names that record. A later pass through this step, after a return to §4, skips it. Commit and push it; the commit re-enters no pass. Leave the chunk's items in the plan, and write no changelog bullet in the branch: step 4 does both, so that `todo.md` and `CHANGELOG.md` never conflict between chunks. Revise any decision that cites an item now, since `todo-item finish` refuses while one does.
4. Aligned and every pass done → **merge** with `~/.claude/bin/chunk-pr merge`, run in the background with its `timeout` set to 7200000 ms, since its wait can outlast the Bash tool's default. Give it one `--finish <ID>` per item the chunk ships, each with the arguments `todo-item finish` takes (`todo-item --help`), as in `chunk-pr merge --finish 12 --changelog '<bullet>' --finish 13 --no-changelog`. The project's chunks merge one at a time. In its turn, `chunk-pr merge` merges `origin/<default branch>` into the branch, finishes those items, pushes, and waits for the pull request's checks to pass; then it takes the first merge method the repository allows on its forge. Where it stops, do what it asks and run it again with the same arguments:
- **A merge conflict.** Resolve it, commit and push. Rerun only the passes whose triggers the resolution's own lines meet (§3), each in a round of its own.
- **A paired ruling to run again.** `chunk-pr merge` has merged the default branch in and pushed. Run the ruling at that head, record it, commit and push. Don't return to §4 for it: the next turn waits for the checks at the new head.
- **An owed scoring run, or a queue another pull request holds.** Record the run, or wait, as the message says.
- **A reviewer's comment**, where the project's config sets `wait-for-approval` (`chunk-pr --help`) and the pull request waits for a human's approval. Answer it in its thread on the forge, and fix what it asks as a finding of the chunk. The wait doesn't hold the queue, so other chunks merge meanwhile.
A repo whose `AGENTS.md` names another method merges that way with the forge's CLI instead, after it finishes the chunk's items with `todo-item finish` in the branch, and once the pull request's checks pass, `~/.claude/bin/larv-review scoring-run-owed` exits 0 and, where `~/.claude/bin/project-config wait-for-approval` prints `true`, GitHub reports the pull request approved. A repo withholds this in its `AGENTS.md` → leave the PR ready and unmerged, and say which line withheld it.
5. Merged → run `~/.claude/bin/chunk-pr clean` in the chunk's worktree, and put a failure it prints in the summary.
6. Stop. The next chunk gets a fresh session.
+35 -42
View File
@@ -6,18 +6,15 @@
`Bar = 0.1`
`Next ID = 387`
`Next ID = 389`
## Items
| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 374 | 0.11.0 | | decision | **Merge open chunks one at a time: rebase, finish the item in todo.md and CHANGELOG.md, rerun the gate and the paired ruling, and keep a chunk waiting for approval in the queue without blocking the next.** | 4 | 2 | 3 | 7 | 6 | 1.5 by 4, 1.6 by 3 | 1.0 |
| 386 | 0.11.0 | | | **Key project-record's copies per worktree, so two chunks of one project editing the same record kept outside a file don't overwrite each other's unsaved edit.** | 2 | 2 | 2 | 4 | 2 | 1.1 by 2 | 0.8 |
| 359 | 0.11.0 | | | **Tie a project's releases to what its config names: semver tags, Jira Fix Versions, sprints, or none.** | 3 | 2 | 3 | 6 | 4 | 1.6 by 3 | 0.8 |
| 382 | 0.11.0 | | | **Edit a Jira issue the loop filed, and score an unscored issue a teammate filed with a comment saying why.** | 4 | 2 | 3 | 7 | 4 | 1.6 by 3 | 0.8 |
| 384 | 0.11.0 | | | **Rank an issue the loop files in Jira by its score among the issues the loop filed, a security finding first.** | 3 | 2 | 2 | 5 | 3 | 1.6 by 2 | 0.7 |
| 375 | 0.11.0 | 374 | decision | **Run up to the project's configured number of chunks at once, each in its own window of one tmux session named for the project, mark a window whose chunk waits for the human, and refuse to start without tmux at the needed version.** | 4 | 2 | 3 | 7 | 7 | 1.5 by 7 | 0.6 |
| 375 | 0.11.0 | | decision | **Run up to the project's configured number of chunks at once, each in its own window of one tmux session named for the project, mark a window whose chunk waits for the human, and refuse to start without tmux at the needed version.** | 4 | 2 | 3 | 7 | 7 | 1.5 by 7 | 0.6 |
| 319 | 0.12.0 | | | **Start a fresh session with a brief of the chunk when a rung step changes the worker's model, in place of resuming the old session.** | 3 | 2 | 3 | 6 | 4 | 1.1 by 2, 1.4 by 2 | 1.2 |
| 309 | 0.12.0 | | | **Run a scoring run's second pass on one head with two seats in place of four, once `larv-review agreement` shows the seats agree with each other more than a run agrees with its rerun.** | 2 | 2 | 2 | 4 | 2 | 1.4 by 3 | 1.2 |
| 299 | 0.12.0 | | | **Replay the archived judge verdicts through code rules and a classifier trained locally on the archive, and file an item for each verdict kind one of them decides with no missed interrupt.** | 2 | 2 | 2 | 4 | 3 | 1.4 by 3 | 1.0 |
@@ -38,6 +35,7 @@
| 306 | 0.14.0 | | | **Set a strategy that keeps loop-claude's archive and larv-review's review folders backed up and small over the years, compressing older entries without losing any.** | 3 | 2 | 4 | 7 | 5 | 3 by 5 | 3.9 |
| 304 | 0.14.0 | 303 | defect | **Archive each review-replay and judge-replay run's transcript beside its result, so a replay that decided a rung can be checked and re-priced later.** | 2 | 2 | 2 | 4 | 3 | 1.4 by 2, 3 by 2 | 3.8 |
| 287 | 0.14.0 | | | **Move the forge helpers `Forge`, `forge_of`, `runner`, `open_pull`, `merged_pull`, `pull_at`, `gitea`, `checks_passed` and `required_checks` into one module that `chunk_preflight`, `chunk_pr`, `deploy_release` and `larv_review` all import from, so no tool imports another tool's internals for them.** | 3 | 1 | 3 | 5 | 5 | code health by 3 | 2.9 |
| 387 | 0.14.0 | | | **Bind a project's rung to its ladder in one value, so the routing functions and `Cycle` take one argument for both.** | 3 | 1 | 3 | 5 | 5 | code health by 3 | 2.9 |
| 338 | 0.14.0 | | owner | **Script each step that 0.9.0's chunks repeated by hand and a program can compute, filing one item per step, and file this audit again for the next release.** | 1 | 2 | 1 | 2 | 2 | 1.4 by 3, 1.5 by 3 | 2.3 |
| 288 | 0.14.0 | | | **Point the two reading-cost decisions at code health and goal 1.4's counter-signal, in place of the goal 1.1 they cite.** | 1 | 2 | 1 | 2 | 1 | code health by 1, 1.4 by 1 | 2.2 |
| 77 | 0.14.0 | | | **Teach `bin/metric-bench` Go and TypeScript, rerun it once two projects' comprehension histories name places, and bring into review only a metric that tracks the panel.** | 4 | 2 | 1 | 5 | 6 | 1.1 by 7, 1.4 by 7 | 2.1 |
@@ -46,7 +44,7 @@
| 273 | 0.14.0 | | decision | **Re-tune the E + I steps of `REVIEW_STEPS` for 6 to 8 once 10 finished chunks have scored an E + I of 6 or more, from how well E + I orders their review rounds and 🔴 findings.** | 1 | 2 | 2 | 3 | 2 | 1.1 by 2, 1.4 by 3 | 2.0 |
| 268 | 0.14.0 | | | **End a run whose release is ready to cut with a notice on loop-claude's terminal, in place of an interrupt that waits for an answer.** | 2 | 2 | 3 | 5 | 3 | 1 by 5 | 1.9 |
| 171 | 0.14.0 | | decision | **Group the routing figures' review rounds by the reviewers' rung as well as the worker's, so a call blames a rung only for rounds its own reviews raised.** | 3 | 2 | 2 | 5 | 4 | 1.2 by 3, 1.4 by 3 | 1.8 |
| 300 | 0.14.0 | | owner | **Reach the comprehension floor: restructure the places the comprehension seats found hardest to follow, so the project reads at 7.0 or above on every dimension, Locality and Self-sufficiency first; today the scoring run at 8f03747 scored Navigation 6.75, Locality 5.63, Shape 5.75, Self-sufficiency 5.63 and Overall 6.00.** | 4 | 2 | 3 | 7 | 8 | code health by 8 | 1.7 |
| 300 | 0.14.0 | | owner | **Reach the comprehension floor: restructure the places the comprehension seats found hardest to follow, so the project reads at 7.0 or above on every dimension, Locality and Self-sufficiency first; today the scoring run at bcb04e3 scored Navigation 6.75, Locality 5.63, Shape 5.88, Self-sufficiency 5.63 and Overall 6.00.** | 4 | 2 | 3 | 7 | 8 | code health by 8 | 1.7 |
| 264 | 0.14.0 | | | **Report the comprehension seats and the escalated subagents as subagent types of their own in `routing-figures.md`, with their dollars.** | 2 | 2 | 1 | 3 | 3 | 1.4 by 5 | 1.7 |
| 323 | 0.14.0 | | | **Count a release review as landed once its pull request has merged, whatever its commits are titled.** | 3 | 2 | 3 | 6 | 3 | 1.4 by 3, 1.5 by 2 | 1.7 |
| 342 | 0.14.0 | | | **Research the tooling agents read, search and run commands with once more, and file an item for each tool that cuts tokens a replay shows keep quality.** | 1 | 2 | 1 | 2 | 3 | 1.4 by 3, 1.5 by 2 | 1.7 |
@@ -59,6 +57,7 @@
| 5 | 0.14.0 | | decision | **Key a project on its checkout's full path, and refuse to start while another session uses that key.** | 4 | 2 | 3 | 7 | 5 | 1.1 by 6 | 1.4 |
| 291 | 0.14.0 | | owner | **Let `principles/technical-principles.md` → "Sane defaults" allow a library whose README goals ask that it work with no config to default the clock and randomness in its public constructor, where a documented option overrides each.** | 1 | 2 | 3 | 4 | 1 | 1.2 by 3 | 1.3 |
| 156 | 0.14.0 | | decision | **Drop `rank_todo.py`'s ranking of an old-shape table once no project under `~/code` holds one.** | 2 | 1 | 3 | 4 | 4 | 1.1 by 4 | 1.2 |
| 388 | 0.14.0 | | | **Refuse an agent's Write or Edit of a routing ladder file in rule-hook, since a change to the ladder is the human's.** | 1 | 1 | 3 | 3 | 2 | 1.2 by 3 | 1.2 |
| 260 | 0.14.0 | | decision | **Compare the first 20 chunks whose worker got the reading rule with the 20 before them, on review rounds past each pass's first, unfinished verdicts, 🔴, 🟡 and misread findings, dollars and hours per chunk, and drop the rule where any rose.** | 1 | 2 | 1 | 2 | 2 | 1.4 by 3 | 1.2 |
| 51 | 0.14.0 | | principle | **Hand loop-claude's terminal output to an injected effect, so no storage or retry function prints.** | 2 | 1 | 3 | 4 | 5 | 1.1 by 5 | 1.1 |
| 201 | 0.14.0 | | owner | **Save the human's tmux setups and restore them after a reboot, so work is up and running again quickly.** | 3 | 2 | 1 | 4 | 4 | 1.5 by 4 | 1.1 |
@@ -77,26 +76,6 @@
## Details
### 374. Merge open chunks one at a time: rebase, finish the item in todo.md and CHANGELOG.md, rerun the gate and the paired ruling, and keep a chunk waiting for approval in the queue without blocking the next.
lilleman's call, 2026-11-13, splitting item 361, which also asked that a chunk keep waiting for a human approval while others run. With several chunks open, `chunk-pr merge` merges one pull request at a time. For each it rebases the branch onto the default branch, then writes the item's `todo-item finish` and its changelog bullet, then reruns the gate, then merges. Moving those edits to merge time keeps `todo.md` and `CHANGELOG.md` out of every chunk's conflicts.
Where the rebase conflicts, the chunk's worker resolves it, and only the review passes whose triggers the resolution meets rerun (`larv-review` §3). The paired ruling reruns against the new base after every rebase that brought in another chunk's merge. This revises `docs/decisions.md`'s entry on the last measured commit, so a ruling never charges one chunk with another's change. A chunk whose pull request waits for the approvals item 360 waits for stays in the queue without blocking the next one. It resumes in its own session when a review comment arrives, answers it, and goes back to waiting.
`bin/chunk_preflight/choices.py:80` `forge_of` is a place the comprehension seats found hard: forge code split across tools. Where this item touches it, build on item 287's forge module if that has shipped.
### 386. Key project-record's copies per worktree, so two chunks of one project editing the same record kept outside a file don't overwrite each other's unsaved edit.
Found in item 372's chunk. `project-record open` writes a record kept on a Confluence page to a copy under `~/.local/state/project-record/<key>/`, keyed by the project alone (`bin/project_record/main.py`, `COPIES`). Two chunks of one project, running side by side as item 375 will run them, share that copy: the second `open` rewrites it, and the first chunk's unsaved edit is lost. Key the copy by the worktree as well as the project.
Touches:
- `bin/project_record/main.py`: `(module)` (small)
- `bin/project_record/test_project_record.py`
### 359. Tie a project's releases to what its config names: semver tags, Jira Fix Versions, sprints, or none.
lilleman's call, 2026-11-12: what a release is differs per client. With none, items name no release, and the architecture and principles passes the release review runs need another trigger, which this item settles and records. Readers: `rank_todo.py`'s release order, chunk-preflight's next release, loop-claude's "release ready to cut", larv-review's release review, `CLAUDE.md` → "Working loop". Cutting a release stays the human's.
### 382. Edit a Jira issue the loop filed, and score an unscored issue a teammate filed with a comment saying why.
Split from item 352 on 2026-11-15; lilleman's calls, 2026-11-12. The loop edits the summary, description and scores of issues it created, which the `Filed by` mark in the `plan-item` property tells apart, and never the summary or description of an issue a person filed. An issue a teammate files without scores gets scored like any item, with a short comment saying it was scored and why; its scope stays as written. The comment reaches the client's team, so it is in the project's `language`, and its reason comes from whoever scores: `PlanStore.edit` and `todo-item edit` gain a way to pass it, whose spelling a bench of readers picks. Say in `docs/decisions.md` whether the loop may re-score or move a person's issue that already holds scores; the calls name neither.
@@ -265,6 +244,12 @@ Both comprehension seats of PR #453's paired ruling (2026-11-09) named this web
Put the seven helpers in a folder named by what it holds, such as `bin/forge/`, and import them from there. Keep each helper's behaviour and its tests. `chunk_preflight/choices.py` keeps `pulls_command`, which is preflight's own. Check `docs/decisions.md` for a mention of where a helper lives, and update it.
### 387. Bind a project's rung to its ladder in one value, so the routing functions and `Cycle` take one argument for both.
Filed by PR #553, which made the routing ladder a file a project may replace. Its stability round 1 found two places the comprehension seats name as hard, touched and no easier to read: `bin/loop_claude/routing.py` `unfinished_route` took `ladder` as a fourth parameter, and `Cycle` in `bin/loop_claude/cycle/run.py` gained the field `ladder`. The patch threaded the ladder as an argument, since a wider change did not fit a patch cut during an outage.
12 functions in `routing.py` take `ladder` only to pass it on beside `project`, and 6 of `Ladder`'s methods in `bin/model_routing/ladder.py` take `project` first. One value that holds the project's rung with the ladder it stands on removes the extra argument from each, and gives `Cycle` back the field count it had. Make `unfinished_route` and `Cycle` easier to read while there: both are places the seats found hard.
### 338. Script each step that 0.9.0's chunks repeated by hand and a program can compute, filing one item per step, and file this audit again for the next release.
lilleman asked, on 2026-10-16, for a standing audit each release, so the loop keeps moving work a program does as well from the model to scripts (goals 1.4 and 1.5). This audit reads the archived transcripts of the chunks that shipped release 0.9.0 for every step that chunks repeated by hand, before, during or after review. It keeps the steps whose answer a program computes the same way each time, such as a lookup, a check, a prompt assembled for a reviewer, a cleanup. File one item per such step, with the time and tokens it cost, into the next release with items left. Leave a step that needs judgement with the model. Run `command-patterns 0.9.0` first; its table names the patterns, and `read_threads` and `calls` in `bin/command_patterns/tally.py` open the calls of one pattern, or `command-patterns 0.9.0 --calls <file>` dumps them all as JSON lines. The 0.7.0 audit found that most steps its chunks repeated were already scripted by that release's own tools, so a step a shipped item already covers is not filed.
@@ -329,28 +314,30 @@ Releases are the human's, and `CLAUDE.md` → "Working loop" already ends the lo
Raised by the goals audit of PR #296. `bin/routing_figures/calls.py` groups a chunk's review rounds by the rung its worker started on, and calls for a routing change when a lower rung took more of them. Since PR #296 the reviewers may run above the worker's rung, on the one their item's E + I picks, and no figure groups rounds by it, though the archived worker line names the E + I it follows from. A cheap worker on an item of high E + I gets stronger reviewers, who may raise more rounds, and a call could then blame the worker's rung for them: an interrupt of lilleman that settles nothing (goal 1.2).
### 300. Reach the comprehension floor: restructure the places the comprehension seats found hardest to follow, so the project reads at 7.0 or above on every dimension, Locality and Self-sufficiency first; today the scoring run at 8f03747 scored Navigation 6.75, Locality 5.63, Shape 5.75, Self-sufficiency 5.63 and Overall 6.00.
### 300. Reach the comprehension floor: restructure the places the comprehension seats found hardest to follow, so the project reads at 7.0 or above on every dimension, Locality and Self-sufficiency first; today the scoring run at bcb04e3 scored Navigation 6.75, Locality 5.63, Shape 5.88, Self-sufficiency 5.63 and Overall 6.00.
Filed by the comprehension check of PR #473 at 13d1550 (`larv-review record-scoring`), which printed `Floor:` and `Next:`, and refreshed from the second run of PR #520 at 8f03747. The lowest means are Locality and Self-sufficiency, 5.63 each: the seats name state shared across modules, such as the route and the archive order, and reasons that sit in `docs/decisions.md`, `CLAUDE.md` or `skills/larv-review/SKILL.md` rather than beside the code. Refresh this item's places and aim from the newest run before the chunk starts; do not file a second floor item.
Filed by the comprehension check of PR #473 at 13d1550 (`larv-review record-scoring`), which printed `Floor:` and `Next:`, and refreshed from the run of PR #554 at bcb04e3. The lowest means are Locality and Self-sufficiency, 5.63 each: the seats name state shared across modules, such as the route and the archive order, and reasons that sit in `docs/decisions.md`, `CLAUDE.md` or `skills/larv-review/SKILL.md` rather than beside the code. Refresh this item's places and aim from the newest run before the chunk starts; do not file a second floor item.
Aim: one ambitious refactor of the areas below, sized so every mean reaches 7.0 on the chunk's own scoring run. Where a place is already easier to read when the chunk starts, drop it.
Places the seats named, hardest first (`larv-review places`):
- Locality, Self-sufficiency: `bin/loop_claude/routing.py:93` `unfinished_route`, with `escalated_route`: the floor, the cap counted from `item_rung`, the escalation mark, the unfinished count and the E + I taken in are held at once across four files, and why they combine sits in the decision log. Every seat named it; three would least want to change it.
- Shape, Self-sufficiency: `bin/release_plan/release_standing.py:168` `next_release`, with `standing`: `str | None | Failure` fields in `LastCut`, the `BEFORE_FIRST_RELEASE` sentinel and `nothing_cut` meet in the `is_earliest` test, read as truth tables; four tools choose the next release through it.
- Locality: `bin/loop_claude/cycle/run.py:154` `rule`, with `:67` `run_cycle` and `:94` `archived`: archives twice in an order that matters and that nothing enforces, the archive helpers sit in the cycle runner though `loop/close.py` imports them, and `run_cycle` replaces `cycle.route` outside the state machine.
- Shape: `bin/release_plan/ranking.py:47` `rank`, `:134` `weigh`, `:229` `score` and `:240` `weight_of`: every function forks on `SHAPE` versus `OLD_SHAPE`, and the constants' reasons are only "docs/decisions.md records the choice".
- Shape: `bin/rule_hook/todo_check.py:22` `todo_breaches`, with `:42` `folder_breaches`: three paths, `held()` beside `located()`, the checkout's own script only under `same_repo`, and a blob hashed by hand.
- Locality, Self-sufficiency: `bin/larv_review/plan.py:66` `plan_reasons` and `bin/larv_review/owed.py:46` `shortfall`: the rule for when a scoring run is due is split between the 155-line help and the code, and the number owed hangs on the wording `EMPTIED_WORDS`.
- Self-sufficiency: `bin/loop_claude/cycle/judge.py:21` `INTERRUPT_RULES`, with `:196` `quotes_checked`: behaviour held in prompt text and schema descriptions the code can't explain, and prompts that quote `CLAUDE.md` wording.
- Self-sufficiency: `skills/larv-review/SKILL.md:82` "Round cap": dense rules that point at `CLAUDE.md`, `review-findings.md` and the rules files, read three times before the code matched.
- Self-sufficiency: `bin/rule_hook/round_cap.py:26` `earlier_titles`: fails open on the unattended path where git cannot list the branch's titles, and the round title is spelt by hand in SKILL.md, `larv_review/main.py` and `reviewer_header.py` beside `round_titles.py`.
- Locality, Shape: `bin/chunk_preflight/choices.py:80` `forge_of`: forge identity and forge calls live in two tool packages, so a second forge lands in three.
- Navigation, Shape: `README.md:131` `bin/`: about 63 entries at one level, the shared libraries told apart only by README prose.
- Shape: `bin/loop_claude/loop/reload.py:220` `decoded_route`: one dense guard, and renaming a `LoopRun` field stops a running loop.
- Shape: `README.md:3` trial folders: four finished experiments at the root beside the working areas.
- Self-sufficiency: the seats on this run name the decision-log titles that code cites for a constant's reason (`routing: …` in `routing.py`, `ladder.py`, `judge.py`) as the largest cost; state each reason beside its constant.
- Locality, Self-sufficiency: `bin/loop_claude/routing.py:113` `unfinished_route`, with `:128` `escalated_route`: five rungs, the escalation mark from `escalation_mark.py`, the unfinished count from `loop/close.py` and two step-up counters are held at once, and why they combine sits in the decision log. Three seats named it; one would least want to change it.
- Locality, Shape: `bin/chunk_pr/main.py:298` `merged`, with `:384` `levelled_and_finished`, `:349` `unplanned`, `:407` `finished` and `:438` `remeasure`: a while loop around the queue turn binds `ready`, `asked` and `done` only on some paths and states no invariant; `levelled_and_finished` does five things under a name that gives two; `unplanned` and `finished` match the error text of `todo-item show` where `plan_store` reads the plan; `remeasure` keeps its control flow in chained boolean expressions. Three seats named it; two would least want to change it, and one expects the next defect there.
- Shape, Self-sufficiency: `bin/release_plan/release_standing.py:162` `next_release`, with `:207` `standing`: `str | None | Failure` fields in `LastCut`, the `BEFORE_FIRST_RELEASE` sentinel and `nothing_cut` meet in the `is_earliest` test at `:184`, and the comments explain each branch alone.
- Locality, Shape: `bin/loop_claude/cycle/run.py:151` `rule`, with the 17-field `Cycle` at `:31`: judges, stamps, annotates, steps the rung up and archives in an order that matters and that no single unit owns, and `Cycle` is passed around whole.
- Shape: `bin/release_plan/ranking.py:48` `rank`, `:136` `weigh` and `:231` `score`: every function forks on `SHAPE` versus `OLD_SHAPE`, `Shape` is built from positional tuples of callables, and the defect rule sits in `weight_of`, far from where scores are read.
- Shape: `bin/chunk_preflight/main.py:128` `preflight`: lines 142-143 pack a conditional re-`located` and an eight-argument `Gathered` into two lines.
- Locality, Self-sufficiency: `skills/larv-review/SKILL.md:146` "Comprehension check", with `:82` "Round cap", `bin/larv_review/main.py:1` and `bin/larv_review/plan.py:77` `plan_reasons`: one rule is spread over skill prose, a 155-line help, a hook and the code, so rebuilding it means three files open.
- Navigation, Shape: `bin/larv_review/main.py:222` `COMMANDS` and `bin/rule_hook/round_cap.py:10` `round_cap_breaches`: the package named for the review mostly holds the comprehension check, part of which sits in `review_rules/comprehension_history.py`, and the round cap is enforced in the hook, where a reader looks last.
- Self-sufficiency: `bin/loop_claude/cycle/judge.py:22` `INTERRUPT_RULES`, with `:197` `quotes_checked`: behaviour held partly in prompt text and schema descriptions and partly in Python checks, with nothing saying which the code enforces.
- Locality, Shape: `bin/deploy_release/forge.py:1` and `bin/chunk_preflight/choices.py` `forge_of`: forge identity and forge calls live in two tool packages, neither a home the name gives.
- Navigation, Shape: `README.md:193` `bin/`: about 70 entries at one level, the shared libraries told apart only by README prose.
- Shape: `bin/rule_hook/rules.py:26` `RULES`: the registry and four rules' checkers in one file, so where a new rule goes is undecided.
- Locality: `bin/loop_claude/loop/reload.py:95` `exec_if_edited`, with `:67` `decoded_route`: an edit under `bin/` makes a running loop re-exec, and renaming a `LoopRun` field stops it.
- Shape: `bin/rule_hook/env_file.py:34` `reaching`: `and` and `or` mixed without parentheses, and four path spellings in one lookaround regex.
- Shape: `bin/loop_claude/loop/chunk_start.py:24` `fetched_todo`: nearly the same plan read as `:75` `fetched_plan`, told apart only by a docstring.
- Self-sufficiency: every seat names the decision-log titles and plan items that code cites for a reason (`routing.py`, `ladder.py`, `run.py:31`, `plan_store/stores.py:5` and `:50`, `chunk_start.py:86`) as the largest cost; state each reason beside its constant and keep the citation as a footnote.
Scored L 4 because the refactor touches several components that hold known defects, E 2 because review and a manual check see a regression, I 3 because every session runs these tools. The chunk runs a scoring run, since it is a floor item.
@@ -421,6 +408,12 @@ The key names the project's session, archive folder and models entry. `project_k
While `rank_todo.py` ranks two shapes, projects follow two sets of scoring rules, against goal 1.3. Once every project has reshaped, drop `OLD_SHAPE`'s weighing from `bin/release_plan/ranking.py`, `RESHAPE`, and the old shape's lines in `rank_todo.py --help` and `rules/todo-items.md`. Keep `todo_table` reading old tables: `score_outcomes` reads every past merge's `todo.md`. PR #283's paired ruling found the old-shape path made `ranking.py`'s `score`, `Scoring.weights`, `unknown_columns` and `todo_table.py`'s `Moves` harder to read; leave each easier, with one shape and moves that are always moves, and the Moves cell's rules in one place. Release 0.3.0's seats named `ranking.py`'s `score`, `weigh` and `rank` and `todo_table.py`'s `OLD_SHAPE` for the same fork: "every rule exists twice for the old table shape" (Mid A). Make `weigh` and `rank` easier to read too.
### 388. Refuse an agent's Write or Edit of a routing ladder file in rule-hook, since a change to the ladder is the human's.
Filed by PR #553, which made the routing ladder a file: `bin/model_routing/routing-ladder.json`, and a project's own `routing-ladder.json` in its config's folder. `CLAUDE.md` → "Working loop", "Ask, don't guess" reserves a change to the routing ladder for the human, and until PR #553 the ladder was code, which only a reviewed chunk changed. A worker can now write its project's file, and with it choose the rungs its own later cycles and reviews run on. The security pass of PR #553 noted that a ladder changed mid-cycle also makes rule-hook's `reviewer-rung` skip its check, since the rungs loop-claude handed are then off the ladder.
Project principle 4 asks that a rule a program can check is enforced by a program. Refuse a Write, an Edit and a MultiEdit of a file named `routing-ladder.json` under `~/.claude-projects/`, with no override, and say that the ladder is the human's to change. The shipped file stays editable in the setup's own checkout, where a chunk's review covers it.
### 260. Compare the first 20 chunks whose worker got the reading rule with the 20 before them, on review rounds past each pass's first, unfinished verdicts, 🔴, 🟡 and misread findings, dollars and hours per chunk, and drop the rule where any rose.
Start once 20 chunks have run under the rule. The rule is `READING_RULE` in `bin/loop_claude/cycle/prompts.py`, which every fresh worker prompt holds; `git log --first-parent -S READING_RULE` on the default branch finds the merge that added it. A chunk got it when its first worker started after that merge. Measure as `docs/decisions.md` → `loop-claude: the worker's claude compacts its context before it fills a 200k window…` measured the window: rounds past each pass's first and the 🔴, 🟡 and misread counts from the round commit titles, unfinished verdicts from the outcomes files, hours from the worker's first message to its last, and dollars from the chunk's `cost-state` entry. Compare means, since the decision weighs the rule by all spend.