Compare commits
181 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 9a5c24aa68 | |||
| 4447aabbb3 | |||
| fda48ac44c | |||
| ef57520cf3 | |||
| 5a495fd58e | |||
| c7139106c7 | |||
| fcf119ffec | |||
| 2ea929a8be | |||
| e787286a48 | |||
| 8587e4f160 | |||
| 353058defd | |||
| 6bb7b28b92 | |||
| eafcefe0da | |||
| 1605d80cc5 | |||
| f091d8b698 | |||
| 390d1f1f83 | |||
| 3081d50f0f | |||
| 8e0060be08 | |||
| 9e6715e0bf | |||
| 6e050148ef | |||
| 50edcca42f | |||
| 2a961f267c | |||
| 1bfc91559a | |||
| 78077a5896 | |||
| aa279a319a | |||
| d0758a0735 | |||
| e6223f7126 | |||
| ab93b7356e | |||
| dba2e74321 | |||
| 49e86fdbb9 | |||
| cfa16c65b5 | |||
| 6703d48800 | |||
| bf6300bcd5 | |||
| da17ed5c32 | |||
| 69e1c5f3f7 | |||
| 68c2cdfa8b | |||
| 56e9049938 | |||
| bc242b2998 | |||
| ec2a16b371 | |||
| 2fbd504734 | |||
| fc13a1100e | |||
| 2911d3f4cc | |||
| 207ba120b5 | |||
| 862137b1be | |||
| 8ef6dcb7a8 | |||
| 306b040b46 | |||
| eec084a4e8 | |||
| baefcbb037 | |||
| 0202bc60f9 | |||
| e652e7aed7 | |||
| 5bc3247aec | |||
| 2bba66ac0a | |||
| 1ed305f1e2 | |||
| 3a8e4e6f75 | |||
| 07369f1164 | |||
| 1601c92f09 | |||
| ca32d0d446 | |||
| e70f61dad4 | |||
| 2d07bbff63 | |||
| 9c9f26ba57 | |||
| fc7c2301b5 | |||
| 612ba0d4e4 | |||
| bb60e9dffd | |||
| 5a9b084bfb | |||
| 489465c56f | |||
| 9a1adcef42 | |||
| 917166e186 | |||
| a1089442c4 | |||
| c8f53bbcc4 | |||
| bdc1d463cb | |||
| 5d430dbd9a | |||
| bfdb886ef7 | |||
| 9bed420f21 | |||
| 2e518e0bcc | |||
| 9a28cba0be | |||
| ef454d263e | |||
| d0a50abc8b | |||
| f36eee0ec7 | |||
| 9eb26ed727 | |||
| d41d42baa5 | |||
| c9bfc96aaf | |||
| f0d4740367 | |||
| 1a433205a6 | |||
| 80a90a803e | |||
| 0462980bd4 | |||
| 2b0133af69 | |||
| 3eb3217a49 | |||
| 5eafe960e1 | |||
| a3aad5ead1 | |||
| 4c6194255f | |||
| 5866a0497a | |||
| 8510c06b2f | |||
| 686e2dcd42 | |||
| d44024d159 | |||
| e9cc88ed27 | |||
| ab081dd33f | |||
| 83701e20aa | |||
| 6cdace6ae3 | |||
| ca5edc2ae3 | |||
| 5bf3cba602 | |||
| ef1df926c4 | |||
| 6e0fda4ded | |||
| d0f6c806a3 | |||
| 6694d54e52 | |||
| e6363d1c56 | |||
| ac2ed4095a | |||
| c07e582212 | |||
| e15f96fcd8 | |||
| 63392cea66 | |||
| eae4ee9fb1 | |||
| 6479337ab1 | |||
| d1ca16e9fc | |||
| 1f0a046dd4 | |||
| c7a02c3be7 | |||
| e3933a92ff | |||
| 28a3f9c5e9 | |||
| ee6ef24d59 | |||
| a5a8ad5522 | |||
| ac33c733c7 | |||
| e074b8b235 | |||
| ec95acab64 | |||
| 1d8dd330bb | |||
| a4f81a1024 | |||
| f6f84e534b | |||
| 2b1d3707c8 | |||
| d361312edc | |||
| f8a51728a3 | |||
| 4fa90ee01a | |||
| 78843560cf | |||
| b6a3dc43a8 | |||
| 3928d84acb | |||
| 52b0e6dbf9 | |||
| d96f4a138a | |||
| 3adf58c619 | |||
| 8df46e3a85 | |||
| 27480e586f | |||
| 308434f826 | |||
| 55a062bbdc | |||
| 051e9a08d5 | |||
| 8ffe26a33d | |||
| 9207566328 | |||
| 3f6f0456fb | |||
| fed14bf2dd | |||
| fdd48bb1cd | |||
| dbaf32fc74 | |||
| 32eb16cd20 | |||
| 023380f5a5 | |||
| e291f6ca3d | |||
| 062af261d8 | |||
| 2760c50915 | |||
| d9fb90ee03 | |||
| 1f380af695 | |||
| e7f5443688 | |||
| c4a4f40aa6 | |||
| 2bb61f385a | |||
| 84e34b8e23 | |||
| 3229045af9 | |||
| 4b2d4a1734 | |||
| 44fa8a7fe6 | |||
| 96834412c7 | |||
| 831b9c63b6 | |||
| eddc5bec95 | |||
| e1239dfd19 | |||
| 81a07fe685 | |||
| 4e1df27698 | |||
| 528eee1996 | |||
| 2890399e45 | |||
| 24173eb17f | |||
| 5b536afdf9 | |||
| fc24e9bae2 | |||
| b120faacad | |||
| 2fbbc08094 | |||
| 89bbc9de18 | |||
| 7a30b818b7 | |||
| e8898534c1 | |||
| 9e6c4fc8c2 | |||
| e71f5b9406 | |||
| dcad6fc5b7 | |||
| 602a5fac16 | |||
| 1c503e8818 | |||
| 4474182174 |
+5
-3
@@ -18,6 +18,7 @@
|
||||
!agents/*.md
|
||||
!bin/
|
||||
!bin/chunk-preflight
|
||||
!bin/chunk_pick.py
|
||||
!bin/chunk_preflight/
|
||||
!bin/chunk_preflight/*.py
|
||||
!bin/claude_code/
|
||||
@@ -50,6 +51,10 @@
|
||||
!bin/reading_cost/*.py
|
||||
!bin/repo_checks/
|
||||
!bin/repo_checks/*.py
|
||||
!bin/review-replay
|
||||
!bin/review_folder.py
|
||||
!bin/review_replay/
|
||||
!bin/review_replay/*.py
|
||||
!bin/round_titles.py
|
||||
!bin/rule-hook
|
||||
!bin/routing_figures/
|
||||
@@ -62,9 +67,6 @@
|
||||
!bin/score_outcomes/
|
||||
!bin/score_outcomes/*.py
|
||||
!bin/shell_command.py
|
||||
!bin/stability-replay
|
||||
!bin/stability_replay/
|
||||
!bin/stability_replay/*.py
|
||||
!bin/statusline.py
|
||||
!bin/subagent-rung
|
||||
!bin/subagent_rung/
|
||||
|
||||
@@ -5,7 +5,7 @@ Decisions live in `docs/decisions.md`:
|
||||
- larv-review: a project lifting itself to the comprehension floor starts at the lowest dimension
|
||||
- loop-claude: a judge decides each interrupt and each quoted answer from the transcript, the README's premises, `AGENTS.md`, `docs/decisions.md`, `~/.claude/CLAUDE.md`, `~/.claude/rules/` and larv-review's standards, and holds a chunk open while an answer the human typed in it is recorded nowhere; the worker's own account of which goal settles a choice decides nothing
|
||||
- loop-claude: one session per project, its id derived from the checkout's path relative to `~/code`, or to `/` outside it
|
||||
- loop-claude: before an interrupt, it marks the checkout and each of its worktrees trusted in `~/.claude.json`
|
||||
- loop-claude: before it opens claude on the terminal, it marks the checkout and each of its worktrees trusted in `~/.claude.json`
|
||||
- bin/: the tests rerun themselves on a `uv`-fetched Python at README Install's floor
|
||||
- bin/: the tools and their tests run on the host's Python, with no container
|
||||
- comprehension floor: every dimension and the overall at 7.0 or above is the target, and blocks no merge or release
|
||||
@@ -15,7 +15,7 @@ Decisions live in `docs/decisions.md`:
|
||||
- review: a fix for a 🔴 or 🟡 reruns the pass that found it and each pass whose trigger names fixes like it; from round 2 a pass reviews only the answers to its last round's findings and any other pass's fix that re-entered it; a fix for a 🟢, a ❓ or a prose finding reruns none
|
||||
- review: the comprehension check records how hard a project is to read and blocks no merge: a paired ruling against the last measured commit where the architecture pass ran, and the four-seat scoring run, once when an item names the floor and twice on one head when a release's items run out
|
||||
- review: a project decision may suspend the comprehension check for the plan items it names
|
||||
- review: a project decision may opt every chunk out of the architect, the product-owner pass or the comprehension check
|
||||
- review: a project decision may opt every chunk out of the architect, the product-owner pass or the comprehension check, and a project opting out of the comprehension check voids code health
|
||||
- review: the principles audit runs on every chunk that changes code, config or tests, and on no other chunk
|
||||
- review: a pass skips only on a precedent: a decision, or a plan item crediting the pass, that the repo held before the chunk began
|
||||
- loop-claude: the archive keeps the raw transcript, and a failed archive stops the loop
|
||||
@@ -27,7 +27,7 @@ Decisions live in `docs/decisions.md`:
|
||||
- workflow-bench/: the remote may show the bench cases' names and commit SHAs
|
||||
- settings.json: Claude Code runs in auto mode with the dangerous-mode prompt skipped
|
||||
- the repo may name bender, bender-infra and ai-sandbox
|
||||
- todo.md: one table of items scored by the formula it states, each README achieve goal weighed by its position, the first heaviest, held to its bar, ranked by `bin/rank_todo.py`, which ranks each blocker above the items it blocks; the table's order is the plan's only order
|
||||
- todo.md: one table of items, scored by the formula it states, held to its bar and ranked by `bin/rank_todo.py`, which ranks each blocker above the items it blocks; each achieve goal weighs by its position, code health first and four times as heavy while the comprehension panel's overall is under 7.0 or unmeasured, then README.md's goals; the table's order is the plan's only order
|
||||
- todo.md: only a session or subagent on the project's rung or above scores or reshapes the plan; one below it drafts new items and changes to filed ones for a subagent at or above that rung to apply and score, and removes finished ones
|
||||
- reading cost: larv-review measures each finished chunk from loop-claude's archive and appends the figure to `docs/reading-cost.md` in the next chunk's PR
|
||||
- reading cost: a rise is the last 5 chunks' median above the 5 before them, and files or refreshes one plan item
|
||||
@@ -36,17 +36,18 @@ Decisions live in `docs/decisions.md`:
|
||||
- rules/: `CLAUDE.md` holds the worker's rules that no file path can scope, and each topic's rules for the worker live in a `rules/` file that Claude Code loads by its `paths:` frontmatter
|
||||
- worker: a chunk's worker writes the simplest change that solves its item, test first wherever a test can check the change, and reads a technical principle only where the item, a finding or its own record names it; larv-review's reviewers hold the change to the principles and to the standards in `skills/larv-review/standards/`
|
||||
- tests: each test earns its keep as the technical principles' test bullet says, and the worker takes a test's expected values from its item, never from the code
|
||||
- review: each reviewer under `agents/` writes its full report into the chunk's review folder under `~/.local/state/larv-review/` and returns the worker its verdict and one line per finding; rule-hook refuses its Edit and MultiEdit, and any Write outside `~/.local/state/larv-review/`
|
||||
- review: stability and product-owner report only a defect, a broken requirement of the plan or the goals, a breach of a technical principle, or for stability a hard place the change touches; each architect finding names a later change the PR makes harder; prose runs only on a chunk that changes prose
|
||||
- review: the stability pass mutation-tests the lines a chunk changes, in place of measuring test coverage
|
||||
- routing: one ladder of (model, effort) rungs, ordered by the Artificial Analysis Intelligence Index with Fable 5.1 at max on top; 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: a chunk's worker runs on the rung its item's L picks, below the project's rung too; its reviewers run on the highest of the worker's rung, the project's and the one picked by the highest E + I among the chunk's items, the seats and the security pass always on the project's
|
||||
- routing: a chunk's worker runs on the rung its item's L picks, below the project's rung too; its reviewers run on the highest of the worker's rung, the project's and the one picked by the highest E + I among the chunk's items, unless a replay lowered their pass; the seats and the security pass always on the project's
|
||||
- routing: the worker changes rung only as a chunk starts, after every second unfinished verdict, or when the judge reports a taken-in item that picks a higher rung or an escalation trigger the worker cites
|
||||
- routing: loop-claude measures review rounds and unfinished verdicts per rung every 20 cycles, and calls for a routing change when, of two rungs with 5 or more chunks each, the lower took more of either than the one above, or when 5 or more subagents of one type had reports longer than the tool results they read
|
||||
- routing: a worker delegates a task only where it needs just the task's conclusion, and each subagent runs on the rung its task's L picks from the project's rung, never below the project's rung when it files or scores todo.md items
|
||||
- routing: a worker hands a task one rung up on each escalation trigger, up to two rungs above the rung its item picks unless the human agrees, and opens the subagent's prompt with the trigger so the routing figures count it
|
||||
- routing: a worker whose run ends asking for a higher rung, citing an escalation trigger the judge finds in the transcript, resumes one rung up next cycle, up to two rungs above the rung its item picks
|
||||
- routing: a worker whose run ends asking for a higher rung, citing an escalation trigger the judge finds in the transcript, steps one rung up as the judge interrupts or quotes an answer, or next cycle, up to two rungs above the rung its item picks
|
||||
- routing: on a model judge-replay covered, the judge runs on the rung a review would get from the highest E + I among its chunk's items, never below the project's rung
|
||||
- routing: the stability reviewer runs no lower than the project's rung while the worker runs below it, until `stability-replay` shows a lower rung finding every 🔴 and 🟡 the project's rung finds
|
||||
- routing: a review pass runs below the project's rung only on a rung that a replay of its rounds shows finding every 🔴 and 🟡 the project's rung finds, and only where the E + I steps no review up and the worker runs no higher than the project's rung, then even below the worker's; no pass has such a rung
|
||||
|
||||
## Working rules
|
||||
|
||||
|
||||
+14
-3
@@ -1,14 +1,25 @@
|
||||
# Changelog
|
||||
|
||||
## Unreleased
|
||||
## 0.2.0
|
||||
|
||||
- Every project now shares one achieve goal, code health: the code is easy to understand and change safely. `CLAUDE.md` → "Shared goal" states it, with its signal and counter-signal. `rank_todo.py` ranks it first among a project's achieve goals. A project's overall is the overall mean of the newest scoring run in `docs/comprehension-history.md`, averaged with every other run on its commit. While that overall is under 7.0, or no run has measured the project, code health weighs four times as much as it does at 7.0 or above. An item's Moves cell names it as in `code health by 6`. A README voids it with `**Void:** code health, since <reason>.` under `## Goals`, and `rank_todo.py` then refuses an item that names it. `larv-review record-scoring` re-ranks `todo.md` after it appends a run, and exits 1 where `rank_todo.py` would, keeping the run. Expect items that make code easier to read to rank higher in every project. On upgrade:
|
||||
1. Move every machine to this release before any of them ranks a plan another machine shares: an older `rank_todo.py` scores it without code health and rejects a `code health` cell.
|
||||
2. Void code health in each project that opts out of the comprehension check, or `rank_todo.py` refuses its plan.
|
||||
3. Run `rank_todo.py` in each project that keeps code health. It re-scores every item, so until then `rank_todo.py --check` fails, and rule-hook holds the project's next `todo.md` commit.
|
||||
4. In each project whose README restates code health as a goal of its own, file an item to drop that goal and point the Moves cells citing it at `code health`. Dropping it renumbers the goals after it, so the same item repoints every Moves cell and decision citing them; `rank_todo.py` cannot tell a cell left pointing at the wrong goal.
|
||||
- `stability-replay <model>` is now `review-replay <pass> <model>`, and replays any pass an agent under `agents/` reviews, such as `review-replay prose claude-opus-5-5`. It now tries every rung below the project's, down to the ladder's lowest. Its runs on the prose and stability passes of Opus 5.5 projects found no rung below the project's that finds every 🔴 and 🟡 the project's rung finds: Sonnet 5.5 at high missed 12 of 27 prose findings and 11 of 20 stability findings. So every pass stays where it runs. A rung a future run finds lowers only its pass, once `REPLAYED` in `bin/model_routing/ladder.py` names it, and only where the chunk's E + I steps no review up and the worker runs no higher than the project's rung; there it may run below the worker's rung.
|
||||
- `chunk-preflight` names the release it finds finished and ready to cut, or to be planned first, wherever todo.md has named that release since the last cut.
|
||||
- Each reviewer under `agents/` now writes its full report to a file that larv-review names in the reviewer's prompt, in a folder per chunk under `~/.local/state/larv-review/`. It returns only its verdict and one line per finding, so a review takes less of the worker's context. The worker reads a finding's full entry before it fixes or answers a 🔴 or 🟡. Each reviewer now holds Write. `rule-hook` refuses a reviewer's Edit and MultiEdit, and any Write outside `~/.local/state/larv-review/`; no override waives this rule. Each chunk's folder stays after the merge, so `review-replay` can replay a round that reads an earlier round's report. It replays on a copy of the folder.
|
||||
- `loop-claude` asks an interrupt's question on its own terminal and resumes the worker headless with your one-line answer, so the loop no longer waits for you to leave a claude session. Type `/talk` instead to open the worker's session in claude, as every interrupt did before, to read the diff or discuss first. A release ready to cut opens that session at once. Pressing Enter on an empty answer stops the loop, exit 2. Keys typed before the question shows are dropped, and a pasted answer keeps only its first line; type `/talk` for a longer one. The judge counts that answer as yours, like one typed in claude: the chunk stays open until the answer is recorded, where a later chunk could need it.
|
||||
- `todo.md` may mark a renamed release in a `## Renamed` section, one line per rename, such as `- 0.2.1 renamed to 0.3.0`. `chunk-preflight` and `loop-claude` then skip that release when they pick the next one, and larv-review's scoring-run trigger calls no run for it. Without the mark, a release named since the last tag whose items all moved to other releases reads as finished: `chunk-preflight` says it is ready to cut and the loop stops for you, and the trigger calls a scoring run. `rank_todo.py` fails on a `## Renamed` line of another shape, and on an item filed under a release it marks. Before you move a machine to this release, add the line to the `todo.md` of every project that renamed a release since its last tag, or its loop stops for that release's cut.
|
||||
- When a worker's run ends with a question and a request for a higher rung, `loop-claude` now steps the worker one rung up as the judge interrupts, or as it answers the question with a quote from `README.md` or another file it may quote. The judge must quote a passage showing that the escalation trigger the run cites fired. Before, the step was lost for an answered question, and the worker carried on from the answer on its old rung. The step has the same limits as the step on an unfinished verdict. An escalation trigger that fired before the worker's last step-up doesn't step it again, so one trigger buys one step. A trigger that fires after the step steps the worker again, in the same cycle or a later one. A chunk left open across the upgrade to this release starts with no step-up on record, so a trigger that already stepped its worker may step it once more. The archive's interrupt and quoted-answer outcomes now name the worker's rung.
|
||||
- A scoring run due because a release's items ran out costs four more seats: it is done twice on one head. `larv-review agreement` compares how often Mid A and the inherited architect vote alike in paired rulings with how often their overall scores move the same way between the two runs. After 10 such pairs it gives a verdict, and on `Assumption fails:` larv-review asks you whether to keep the paired ruling.
|
||||
- `workflow-bench/bench.py` gives each run a fixed list of allowed tools. Before, it skipped every permission check. A run may launch agents, run `/security-review`, edit its clone (not the clone's `.git/` or `.claude/`) and its report, and read its clone and the copy of `~/.claude` it benches. For git it gets one command, `workflow-bench/review_git.py`, and no bare `git`. The wrapper runs `log`, `diff`, `show`, `status`, `ls-files`, `add` and `commit -m` on the run's clone, whatever the working directory. It allows only the options it lists for each, and refuses an argument that names a path outside the clone. git runs with no global or system config, hook, pager or editor. A run loads no settings or MCP servers from `~/.claude` or from the case's clone, so their hooks and extra directories do not apply to it. Every other call is denied. Expect a benched review that needs another git command, or to run a project's code or tests, to say in its report that it could not.
|
||||
- Every goal in `README.md` → Goals is marked `**Maintain:**`, a state to hold, or `**Achieve:**`, a direction to pursue. Each achieve goal has a signal, a counter-signal and a one-line reason under it. A change that breaks a maintain goal is redesigned or dropped, whatever it scores: `rules/todo-items.md` says so, and larv-review's goal alignment step no longer merges such a PR. `rules/goals-and-audience.md` states the form for every project's README. Expect larv-review to stop a PR on a maintain goal where it asked you before.
|
||||
- Reshape every project's `todo.md` to the new shape below: until it is reshaped, that is the project's only work, as it is while README.md lacks Goals and Audience, and `rank_todo.py` says so. First move every machine to this release: an older release rejects the new formula, so it fails on every reshaped `todo.md`. Then mark the README's goals `**Maintain:**` or `**Achieve:**`, score each item's L, E and I, and set a bar on the new scale below the score of every item to keep, since the old bar would drop most items. Until then, an old-shape `todo.md` still ranks by its own formula and weights.
|
||||
- `todo.md` ranks items by value per cost: this setup's own plan uses `Score = 100 * V / (2**S + 8)`, where 8 is a chunk's fixed cost, about one size-3 change, and `rank_todo.py --help` shows it. A Moves column replaces A, G and Goals, naming each achieve goal an item moves and how far, such as `1.1 by 8, 1.2 by 5`. V sums each named goal's weight times its move. `rank_todo.py` weighs each achieve goal by its position in README.md, the first heaviest, so the goal weights table goes. An item names the most specific goal it moves, never a goal beside its own sub-goal. `rules/todo-items.md` and `rank_todo.py --help` show the new shape.
|
||||
- `todo.md` ranks items by value per cost: this setup's own plan uses `Score = 100 * V / (2**S + 8)`, where 8 is a chunk's fixed cost, about one size-3 change, and `rank_todo.py --help` shows it. A Moves column replaces A, G and Goals, naming each achieve goal an item moves and how far, such as `1.1 by 8, 1.2 by 5`. V sums each named goal's weight times its move. `rank_todo.py` weighs each achieve goal 0.97 times the one above it in README.md, so a goal far down the list still counts almost as much as the first and the goal weights table goes. The weights sum to 1: 5 achieve goals weigh 0.212 down to 0.188, 15 weigh 0.082 down to 0.053. An item names the most specific goal it moves, never a goal beside its own sub-goal. `rules/todo-items.md` and `rank_todo.py --help` show the new shape.
|
||||
- L, E and I replace C, and set R. L is the chance the change holds a defect, from 1 to 4; E the chance a defect escapes tests and review, from 1 to 3; I the damage it would do, from 1 to 5, counting every project and session that runs the change. `rules/todo-items.md` defines each level in words, and `rank_todo.py` writes R as L + E + I − 2, at least 7 when I is 5 and at least 5 when I is 4. The table's score columns are `| L | E | I | R | S |`. `score-outcomes` takes `L E I S`, and reports how well L, E and I each order finished chunks by review rounds and 🔴 findings.
|
||||
- `loop-claude` routes a chunk's worker on its item's L, from two rungs below the project's rung at L 1 to one above it at L 4. It routes the reviewers on the highest E + I among the chunk's items, counting each item the worker takes in: one rung above the project's for each point past 4, never below the worker's rung. It runs the judge of an Opus 5.5 project on the rung that highest E + I picks, never below the project's, and keeps it there when the worker steps up. The comprehension seats and the security pass stay on the project's rung. rule-hook holds each reviewer launch to the reviewers' rung, which `loop-claude` hands the worker in `LOOP_CLAUDE_REVIEWER_RUNG`. A delegated task's subagent takes the rung its L picks: `subagent-rung` takes L in place of R + C. Until a project reshapes its `todo.md`, every chunk there runs on the project's rung. Expect reviews of items whose defects would escape far or break much to cost more, and escalation from an item of L 4 to reach Fable 5.1 only with your yes.
|
||||
- `loop-claude` routes a chunk's worker on its item's L, from two rungs below the project's rung at L 1 to one above it at L 4. It routes the reviewers on the highest E + I among the chunk's items, counting each item the worker takes in: one rung above the project's for each point past 4, never below the worker's rung. It runs the judge of an Opus 5.5 project on the rung that highest E + I picks, never below the project's, and keeps it there when the worker steps up. The comprehension seats and the security pass stay on the project's rung. rule-hook holds each reviewer launch to the reviewers' rung, which it works out from the E + I `loop-claude` hands the worker in `LOOP_CLAUDE_ESCAPE_AND_IMPACT`. A delegated task's subagent takes the rung its L picks: `subagent-rung` takes L in place of R + C. Until a project reshapes its `todo.md`, every chunk there runs on the project's rung. Expect reviews of items whose defects would escape far or break much to cost more, and escalation from an item of L 4 to reach Fable 5.1 only with your yes.
|
||||
- An item that restores a maintain goal the project breaks today is exempt as `defect`, and its Moves may name that maintain goal, weighed as the heaviest achieve goal. A defect ranks by its score like any item. Only two kinds rank ahead of the rest of their release: questions first, since an answer may change other items, then security items.
|
||||
- The stability reviewer applies `principles/technical-principles.md` as written, in place of its own copies of it. Its test-data check now asks for UUID v7, where it asked for randomised UUIDs.
|
||||
- larv-review's principles audit is a pass of its own, and runs on every chunk that changes code, config or tests, not only on one with an architectural decision. A chunk of prose or planning alone skips it.
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
How work proceeds in any repo, unless the repo's `AGENTS.md` says otherwise. The *next release* is the earliest one not yet cut. Other words, such as *chunk*, are defined under "Vocabulary" at the end of this file.
|
||||
|
||||
- **Until `README.md` has a `## Goals` and an `## Audience` section, writing them is the only work.** Not even planning in `todo.md`. Both are public: an outside reader judges a project by where it is heading and who it is for. Goals or an audience written anywhere else, such as `AGENTS.md` or `docs/`, do not count.
|
||||
- **Until `README.md` has a `## Goals` and an `## Audience` section, writing them is the only work.** Not even planning in `todo.md`. Both are public: an outside reader judges a project by where it is heading and who it is for. Goals or an audience written anywhere else, such as `AGENTS.md` or `docs/`, do not count; the one exception is code health, which "Shared goal" below states for every project.
|
||||
- **Plan `todo.md` as one scored table, in the shape whose example `~/.claude/bin/rank_todo.py --help` shows**: every item names the release that ships it. Until `todo.md` has that shape, reshaping it is the only work, and the human approves it.
|
||||
- **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, it 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 lands, into that release; never start a later release's items or plan a new one.
|
||||
@@ -20,6 +20,17 @@ How work proceeds in any repo, unless the repo's `AGENTS.md` says otherwise. The
|
||||
- **Open each `todo.md` 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 says nothing about what to do. Add "today X" only where the direction is otherwise ambiguous. GOOD: `**Accept undefined in MetadataValue and drop such keys on output.**` BANNED: `MetadataValue accepts undefined; such keys are dropped on output`.
|
||||
- **File a security finding the moment it is found.** A security finding — a leaked credential, secret or PII, an auth bypass, an injection — goes under the next release, marked `security`, naming the exposure and the path it reaches. `~/.claude/bin/rank_todo.py` ranks it first in its release, after only the open questions, which wait for me. Never among additive or nice-to-have items, never only in a chunk's summary, and never as a question about where it belongs: file it, say you did, and I will unmark it if I disagree. Fixing it inside an unrelated change is a separate call — say whether it is in the blast radius.
|
||||
|
||||
## Shared goal
|
||||
|
||||
Every project pursues the achieve goal below, ranked above every achieve goal its README states. A project whose code nobody will maintain voids it with one line under `## Goals`, before the numbered goals: `**Void:** code health, since <reason>.` So does a project that opts out of the comprehension check, since the goal then has no signal. An item's Moves cell names it as in `code health by 6`, and `rank_todo.py --help` says how much it weighs.
|
||||
|
||||
**Achieve:** Code health: the code is easy to understand and change safely.
|
||||
- Signal: the comprehension panel's overall score rises, always. Under 7.0 it is very important.
|
||||
- Counter-signal: defects keep reappearing in functionality that already shipped, or reviewers raise blockers because the implementer misunderstood the current system.
|
||||
- Why: a score that rises while changes still misread the code measures the wrong thing.
|
||||
|
||||
Fewer items shipped per release is a price this goal accepts, not a counter-signal.
|
||||
|
||||
## Prose
|
||||
|
||||
Everything written — chat, commit messages, comments, docs, code — is in **English**. Prose meets four priorities, in this order. When two pull against each other, the higher one wins.
|
||||
@@ -31,6 +42,8 @@ Everything written — chat, commit messages, comments, docs, code — is in **E
|
||||
|
||||
Write the thing, not an introduction to it. State what holds and stop; name a rejected alternative only where that stops a reader choosing it.
|
||||
|
||||
Write negations as people say them. BANNED: `stops nothing`, `changes nothing`, `reveals nothing`, `depends on no one`. GOOD: `doesn't stop anything`, `doesn't change anything`, `doesn't reveal anything`, `doesn't depend on anyone`.
|
||||
|
||||
Reviewers hold prose to the full rules, with examples: `~/.claude/skills/larv-review/standards/prose.md`.
|
||||
|
||||
## Public API specs
|
||||
@@ -64,7 +77,7 @@ The rules only reviewers apply, for quality, comments, READMEs and prose, live i
|
||||
4. A review rules the work below standard: systems-architect's BLOCK, a finding against larv-review's `standards/quality.md`, or a vote `record-ruling` counts as worse, in the report that stands after any relaunch one rung up (`larv-review` §3 → "Rung up").
|
||||
|
||||
When one fires, hand the hard part, edits included, to a subagent on the rung loop-claude's prompt names, one above yours. Open the subagent's prompt with the marker loop-claude's prompt gives, then the trigger's evidence. Each later subagent on that task runs on that rung or higher, and each further escalation trigger moves the task one rung higher, up to the highest rung loop-claude's prompt names. Ask the human before going higher. Where loop-claude's prompt names no escalation, as on the ladder's top rung or off it, keep the task in your own thread.
|
||||
- Give a subagent only the access its job needs, and state the limits in its prompt. One that only reads, such as a prose review, gets no shell and no edits. One that probes a build tags the image as throwaway and removes it afterwards, writes only to the session scratchpad, and removes no image or file it did not create.
|
||||
- Give a subagent only the access its job needs, and state the limits in its prompt. One that only reads, such as a prose review, gets no shell and no edits. A reviewer under `~/.claude/agents/` writes only its report, under `~/.local/state/larv-review/`, and rule-hook refuses it every other Write, every Edit and every MultiEdit. One that probes a build tags the image as throwaway and removes it afterwards, writes only to the session scratchpad, and removes no image or file it did not create.
|
||||
- Check `README.md` first for build, test, install, and codegen commands, and fix one that misbehaves in the same change. Refresh `README.md` whenever you change what it describes, keeping it true, not longer.
|
||||
- Where `~/.claude/bin/rule-hook` does not check it, such as an image named in test code, a Kubernetes manifest, a `docker run` line or a file a Bash command writes, pin a container image to its full patch version and a GitHub Action to a semver tag.
|
||||
|
||||
@@ -94,11 +107,11 @@ The rules only reviewers apply, for quality, comments, READMEs and prose, live i
|
||||
- **chunk** — the unit of work, shipped as one PR; "Working loop" says what it holds.
|
||||
- **cycle** — in `loop-claude`, worker runs and the judge's verdict on each, until the chunk closes or is left for the next cycle. In between, the human answers any interrupt, or the worker resumes with an answer the judge quoted from `README.md`, `AGENTS.md`, `docs/decisions.md`, `~/.claude/CLAUDE.md`, `~/.claude/rules/` or `~/.claude/skills/larv-review/standards/`.
|
||||
- **gate** — the merge gate: the checks a PR passes before it merges.
|
||||
- **interrupt** — `loop-claude` handing the terminal to the human, `claude --resume`, for a decision that is theirs.
|
||||
- **interrupt** — `loop-claude` asking the human, on its terminal, for a decision that is theirs. They type a one-line answer, or `/talk` to open the worker's session with `claude --resume`; a release ready to cut opens that session at once, and a routing call opens claude in `~/.claude`.
|
||||
- **judge** — the headless claude that reads a worker's transcript each cycle and decides whether to interrupt and whether the chunk is finished.
|
||||
- **pass** — one kind of review a chunk may take, run in rounds by its reviewers until clean; `larv-review` §3 lists them.
|
||||
- **plan** — `todo.md`.
|
||||
- **premises** — the goals and audience under `## Goals` and `## Audience` in the project's `README.md`.
|
||||
- **premises** — the goals and audience under `## Goals` and `## Audience` in the project's `README.md`, with code health ("Shared goal") first among the goals unless the README 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.
|
||||
- **release** — a semver version the human cuts.
|
||||
- **reviewer** — a reporter of findings: an agent under `~/.claude/agents/`, `/security-review` or a forge's auto-reviewer.
|
||||
|
||||
@@ -54,7 +54,7 @@ claude plugin install code-review@claude-plugins-official
|
||||
claude plugin install rust-analyzer-lsp@claude-plugins-official
|
||||
```
|
||||
|
||||
Link `loop-claude` onto `PATH`: `ln -s ~/.claude/bin/loop-claude ~/.local/bin/loop-claude`. Run `loop-claude` only in a sandbox with no direct access to a production environment, such as a dedicated VM: every claude it starts, the interrupt included, skips every permission prompt.
|
||||
Link `loop-claude` onto `PATH`: `ln -s ~/.claude/bin/loop-claude ~/.local/bin/loop-claude`. Run `loop-claude` only in a sandbox with no direct access to a production environment, such as a dedicated VM: every claude it starts, the interactive ones included, skips every permission prompt.
|
||||
|
||||
## Update
|
||||
|
||||
@@ -84,14 +84,14 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a
|
||||
|
||||
- `chunk-preflight` finds the mechanical facts a chunk starts from and makes its worktree; `loop-claude` runs it before it routes each chunk, and `chunk-preflight --help` lists the facts.
|
||||
- `judge-replay <model>` replays loop-claude's judge on archived verdicts of the projects run on the model, and prints the lowest rung that, like each rung above it, returns them; `judge-replay --help` states the replay.
|
||||
- `larv-review <command>` holds larv-review's mechanical rules: the paired ruling's base and vote count, each pass's round count, the scoring run's trigger, and the comprehension history's format and latest places, and its count of how often seats agree; `larv-review --help` states them.
|
||||
- `larv-review <command>` holds larv-review's mechanical rules: the chunk's review folder, the paired ruling's base and vote count, each pass's round count, the scoring run's trigger, and the comprehension history's format and latest places, and its count of how often seats agree; `larv-review --help` states them.
|
||||
- `loop-claude <task>` runs a project's next chunk cycle after cycle; `loop-claude --help` states its contract.
|
||||
- `metric-bench [history]` benches cheap static metrics of a project's Python against the places its comprehension history names as hardest; `metric-bench --help` states the metrics and the scores.
|
||||
- `rank_todo.py [--check] [todo.md]` scores and ranks a project's `todo.md`; `rank_todo.py --help` states the format.
|
||||
- `reading-cost [--reset] [record]` appends a figure for each chunk `loop-claude` finished to a project's `docs/reading-cost.md`, and says whether the figures rise; `reading-cost --help` states the measure.
|
||||
- `review-replay <pass> <model>` replays a review pass's archived rounds from the projects run on the model, on the code each reviewed, and prints the lowest rung below the project's that, like each rung above it, finds every 🔴 and 🟡 the project's rung finds again; `review-replay --help` states the replay. Run it only in a sandbox, like loop-claude: each replayed reviewer skips every permission prompt, stability-reviewer has Bash, and an archived prompt may name paths on the host.
|
||||
- `rule-hook [overrides]` blocks a tool call that breaks a rule a program can check, unless the call overrides the rule; `settings.json` → `hooks` runs it before each Bash, Edit, MultiEdit, Write and Agent call, and `rule-hook --help` states the rules and the override.
|
||||
- `score-outcomes [L E I S]` lists the finished items whose guessed scores sit nearest the given ones, and the shipped items the project's `docs/score-anchors.md` names for each level of L, E and I, each with what its chunk measured; then the median outcome at each guessed R and S, and how well L, E and I each order the chunks by review rounds and 🔴 findings; `score-outcomes --help` states the measures.
|
||||
- `stability-replay <model>` replays archived stability reviews of the projects run on the model, on the code each reviewed, and prints the lowest rung below the project's that, like each rung above it, finds every 🔴 and 🟡 the project's rung finds again; `stability-replay --help` states the replay. Run it only in a sandbox, like loop-claude: each replayed reviewer has Bash and skips every permission prompt, and an archived prompt may name paths on the host.
|
||||
- `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.
|
||||
|
||||
@@ -110,7 +110,7 @@ pytest_add_cli_args=-k
|
||||
|
||||
Then, in the copy: `uvx --with pytest 'mutmut>=3,<4' run && uvx --with pytest 'mutmut>=3,<4' results`, and `uvx --with pytest 'mutmut>=3,<4' show <mutant>` to see a mutant's change. The config keys are mutmut 3's.
|
||||
|
||||
`bin/` is the import root: each launcher puts it on `sys.path`, so a module imports another by its path under `bin/`, such as `from claude_code.entries import parse_entry`. Each tool's package holds its tests; `rank_todo.py` and `statusline.py` are tools of one file each, tested beside them, `rule_hook` imports `rank_todo.py`'s check, `score_outcomes` imports `reading_cost`'s record path, `judge_replay` imports `loop_claude`'s judge, and `loop_claude` runs `chunk-preflight` as a process of its own. `judge_replay` and `stability_replay` share `rung_replay/`: the rung search, and the argument, candidate rungs and exits. It reads `loop_claude`'s retry count and models file. The other non-test modules at `bin/`'s root, `claude_code/` and `transcript_archive/` serve more than one tool; `model_routing/` holds the routing ladder, which loop-claude and `subagent-rung` read. `routing_figures/` measures loop-claude's archive for loop-claude's routing calls. `test_env.py` serves the tests, and `repo_checks/` tests the repo itself.
|
||||
`bin/` is the import root: each launcher puts it on `sys.path`, so a module imports another by its path under `bin/`, such as `from claude_code.entries import parse_entry`. Each tool's package holds its tests; `rank_todo.py` and `statusline.py` are tools of one file each, tested beside them, `rule_hook` imports `rank_todo.py`'s check, `larv_review` imports `rank_todo.py`'s ranking, `score_outcomes` imports `reading_cost`'s record path, `judge_replay` imports `loop_claude`'s judge, and `loop_claude` runs `chunk-preflight` as a process of its own. `judge_replay` and `review_replay` share `rung_replay/`: the rung search, the argument reader, the candidate rungs and the exits. `rung_replay/` reads `loop_claude`'s retry count and models file. The other non-test modules at `bin/`'s root, `claude_code/` and `transcript_archive/` serve more than one tool; `model_routing/` holds the routing ladder, which loop-claude, `rule_hook`, both replay tools and `subagent-rung` read. `routing_figures/` measures loop-claude's archive for loop-claude's routing calls. `test_env.py` serves the tests, and `repo_checks/` tests the repo itself.
|
||||
|
||||
## Tracking a new file
|
||||
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
---
|
||||
name: override-reviewer
|
||||
description: "Use this agent for larv-review's overrides pass."
|
||||
tools: Read, Grep, Glob
|
||||
tools: Read, Grep, Glob, Write
|
||||
---
|
||||
|
||||
You rule on each override of a rule `~/.claude/bin/rule-hook` enforces. The prompt gives you the lines `rule-hook overrides` printed, each with its rule and reason, and the branch diff. Read each rule and its stated exceptions in `~/.claude/bin/rule_hook/rules.py` → `RULES`, how an override is written and logged in the docstring of `~/.claude/bin/rule_hook/main.py`, and the project's `README.md` → "Goals" and "Audience".
|
||||
You rule on each override of a rule `~/.claude/bin/rule-hook` enforces. The prompt gives you the lines `rule-hook overrides` printed, each with its rule and reason, and the branch diff. Read each rule and its stated exceptions in `~/.claude/bin/rule_hook/rules.py` → `RULES`, how an override is written and logged in the docstring of `~/.claude/bin/rule_hook/main.py`, and the project's `README.md` → "Goals" and "Audience", with code health (`~/.claude/CLAUDE.md` → "Shared goal") among the goals unless the README voids it.
|
||||
|
||||
For each override:
|
||||
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
---
|
||||
name: principles-auditor
|
||||
description: "Use this agent for larv-review's principles pass: one yardstick checked against the whole project."
|
||||
tools: Read, Grep, Glob
|
||||
tools: Read, Grep, Glob, Write
|
||||
---
|
||||
|
||||
You check one yardstick against the whole project: every principle in the file you are handed, or every goal under the project's `README.md` → `## Goals`.
|
||||
You check one yardstick against the whole project: every principle in the file you are handed, or every goal under the project's `README.md` → `## Goals`, with code health (`~/.claude/CLAUDE.md` → "Shared goal") unless the README voids it.
|
||||
|
||||
Verdict, severities and rounds: ~/.claude/skills/larv-review/review-findings.md. Read the yardstick, `README.md`, `docs/decisions.md` and `todo.md` first, then all of the project's code, config, tests and CI.
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
name: "product-owner-reviewer"
|
||||
description: "Use this agent when you need a product-focused review of changes that affect external-facing surfaces (REST APIs, web UIs, CLI commands, public SDKs, webhooks, etc.) from an end-customer perspective. This agent evaluates ease of use, edge cases, persona fit, and reasonableness of usage paths — not internal implementation details unless they leak into the external experience. Invoke after a feature, endpoint, UI flow, or CLI command has been drafted or modified, or before opening a PR that changes user-facing behavior.\\n\\n<example>\\nContext: The developer just added a new REST endpoint for cancelling a subscription.\\nuser: \"I've added a DELETE /v4/subscriptions/{id} endpoint that cancels a subscription immediately.\"\\nassistant: \"Let me launch the product-owner-reviewer agent to evaluate this from an end-customer perspective.\"\\n<commentary>\\nA new external API surface was introduced. Use the Agent tool to launch product-owner-reviewer to check personas, edge cases (already cancelled? pending invoices? refund expectations?), and usability of the contract.\\n</commentary>\\n</example>\\n\\n<example>\\nContext: The developer added a new CLI subcommand.\\nuser: \"Added `mytool deploy --env prod --force` to skip confirmation.\"\\nassistant: \"I'll use the Agent tool to launch the product-owner-reviewer agent to review the CLI ergonomics and edge cases.\"\\n<commentary>\\nCLI usage is an external surface. The product-owner-reviewer should evaluate persona fit (who uses --force? is it discoverable? what happens on partial failure?).\\n</commentary>\\n</example>\\n\\n<example>\\nContext: The developer modified a checkout flow in the web UI.\\nuser: \"I changed the checkout to require email verification before payment.\"\\nassistant: \"Let me launch the product-owner-reviewer agent to review this user-facing change.\"\\n<commentary>\\nWeb UI flow change directly affects end customers. Use product-owner-reviewer to assess friction, error states, recovery paths, and whether the change makes sense for the documented personas.\\n</commentary>\\n</example>"
|
||||
tools: Read, Grep, Glob
|
||||
tools: Read, Grep, Glob, Write
|
||||
---
|
||||
|
||||
You are a seasoned Product Owner with deep expertise in user experience, API design, and customer empathy. You have shipped consumer and B2B products across web, mobile, REST APIs, and developer-facing CLIs. Your superpower is putting yourself in the end customer's shoes and surfacing the friction, confusion, and edge cases that engineers tend to miss.
|
||||
@@ -46,7 +46,7 @@ Before anything else, **read the shared principles** at `~/.claude/principles/`.
|
||||
|
||||
## Your Output Format
|
||||
|
||||
Report only a defect a persona hits, a requirement of the plan or the README's goals that the change breaks, or a breach of a technical principle. Friction that is none of these is not a finding.
|
||||
Report only a defect a persona hits, a requirement of the plan, the README's goals or code health (`~/.claude/CLAUDE.md` → "Shared goal", unless the README voids it) that the change breaks, or a breach of a technical principle. Friction that is none of these is not a finding.
|
||||
|
||||
Verdict, severities and rounds: ~/.claude/skills/larv-review/review-findings.md. After the verdict:
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
name: prose-reviewer
|
||||
description: "Use this agent for larv-review's prose pass."
|
||||
tools: Read, Grep, Glob
|
||||
tools: Read, Grep, Glob, Write
|
||||
---
|
||||
|
||||
You read the prose as someone who did not write it: you see only what it says, never what the author meant.
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
name: "stability-reviewer"
|
||||
description: "Use this agent when code has been written or modified and needs review for stability, bug prevention, and adherence to coding best practices. This includes after implementing new features, refactoring existing code, or fixing bugs. The agent focuses on defensive programming, error handling, edge cases, and compliance with the project's technical principles.\\n\\nExamples:\\n\\n- user: \"Please implement a retry mechanism for our API client\"\\n assistant: \"Here is the retry mechanism implementation: [code written]\"\\n Since significant code was written, use the Agent tool to launch the stability-reviewer agent to review the new code for stability and best practices.\\n assistant: \"Now let me use the stability-reviewer agent to review this implementation for stability concerns.\"\\n\\n- user: \"Refactor the payment processing module to use the new gateway\"\\n assistant: \"I've refactored the payment processing module. Let me now use the Agent tool to launch the stability-reviewer agent to check for any stability issues or violations of our technical principles.\"\\n\\n- user: \"Can you review what I just wrote?\"\\n assistant: \"I'll use the Agent tool to launch the stability-reviewer agent to thoroughly review your recent changes.\"\\n\\n- After any significant code change, proactively launch the stability-reviewer agent to catch issues before they reach production."
|
||||
color: orange
|
||||
tools: Bash, Read, Grep, Glob
|
||||
tools: Bash, Read, Grep, Glob, Write
|
||||
---
|
||||
|
||||
You are an elite stability-focused code reviewer with deep expertise in defensive programming, fault-tolerant system design, and production incident prevention. You have decades of experience identifying subtle bugs, race conditions, edge cases, and architectural weaknesses that lead to outages and unexpected behavior. You think like a chaos engineer — always asking "what could go wrong?" — and like a maintainer of ten years, always asking "what will this cost to live with?" There are no bugs, and no security holes, in code that doesn't exist.
|
||||
@@ -12,7 +12,7 @@ You are an elite stability-focused code reviewer with deep expertise in defensiv
|
||||
1. **Scope the change.** You review every PR; a fresh invocation has no prior context, so determine the diff yourself. Diff the PR branch against its base (`gh pr diff`, or `git merge-base <base> HEAD` then `git diff`), and review the changed lines **plus enough surrounding code and callers** to judge correctness — read the whole changed file when practical; a diff alone hides whether a caller breaks. Read the PR description and, when the project uses an issue tracker (project-specific — check its docs) and the change references a ticket, that ticket: the diff is judged against its stated intent, and a scope mismatch in either direction is a finding — claimed-but-unimplemented, and implemented-but-unasked (#2).
|
||||
2. **Read every file under `~/.claude/principles/`**, the shared principles, and `~/.claude/skills/larv-review/standards/quality.md`. These are mandatory org guidelines; all code MUST comply with each that applies. A file's `Applies to` line says what it covers; one without the line covers every change. Re-read each time — they change. Flag violations prominently.
|
||||
3. **Read README.md, AGENTS.md and `docs/decisions.md`** in the current project for project-specific conventions, build instructions, tooling, and the accepted trade-offs a reviewer should honor rather than re-flag. Note the documented test, lint, and static-analysis commands — you will run them.
|
||||
4. **Verify, don't just read.** Run the test suite and static analysis/linters through the project's container tooling, unless a decision puts them on the host; tear down test containers afterwards. A full-suite run catches broken callers that diff-reading misses. When a suspected bug is cheap to confirm, reproduce it — a scratch script, a targeted test run — before reporting it. Put scratch work in a directory you create for this run, and delete it when done; delete nothing else, since a directory the prompt names may hold other agents' files. Leave the working tree exactly as you found it. Anything you could not run goes in Coverage & Verification, never silently skipped.
|
||||
4. **Verify, don't just read.** Run the test suite and static analysis/linters through the project's container tooling, unless a decision puts them on the host; tear down test containers afterwards. A full-suite run catches broken callers that diff-reading misses. When a suspected bug is cheap to confirm, reproduce it — a scratch script, a targeted test run — before reporting it. Make scratch work with Bash, since Write is for your report alone. Put it in a directory you create for this run, and delete it when done; delete nothing else, since a directory the prompt names may hold other agents' files. Leave the working tree exactly as you found it. Anything you could not run goes in Coverage & Verification, never silently skipped.
|
||||
5. **Mutation-test the changed lines.** Run the project's documented mutation command, or else a widely deployed mutation tool for the language: cargo-mutants for Rust, Infection for PHP, mutmut for Python, Stryker for JavaScript and TypeScript. Limit it to the lines the change adds or modifies, through the tool's own option where it has one (cargo-mutants `--in-diff <diff file>`, Infection `--git-diff-lines`, Stryker `--mutate <file>:<lines>`); otherwise mutate only the changed files and keep only the mutants on changed lines. Run it through the project's tooling, as in step 4, on a scratch copy: the tools write files. Report its wall time and mutant count in Coverage & Verification, or why nothing was mutated. Ignore a surviving mutant that leaves behaviour unchanged, or changes only message or log text no caller or user depends on. Report one 🟡 per test to add or strengthen, naming the surviving mutants it would catch.
|
||||
6. **Two passes minimum, then hunt absences.**
|
||||
- *Breadth:* every hunk in every changed file, no skimming. Track which files you have covered; batch large diffs, never truncate the review.
|
||||
@@ -129,7 +129,7 @@ Every PR gets at least this sweep.
|
||||
|
||||
## Output Format
|
||||
|
||||
Report only a defect, a requirement of the plan or the README's goals that the change breaks, a breach of a technical principle, and the places the prompt hands you. A finding that is none of these is noise, however true: leave it out.
|
||||
Report only a defect, a requirement of the plan, the README's goals or code health (`~/.claude/CLAUDE.md` → "Shared goal", unless the README voids it) that the change breaks, a breach of a technical principle, and the places the prompt hands you. A finding that is none of these is noise, however true: leave it out.
|
||||
|
||||
Verdict, severities and rounds: ~/.claude/skills/larv-review/review-findings.md. After the verdict, a short **Coverage & Verification** block: what you ran (tests, static analysis, mutation — and their results), what you could not verify and why, and any files that got a lighter pass — never let silence imply coverage. Then the findings, most severe first, each with:
|
||||
- **Location**: File and line/function
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
---
|
||||
name: systems-architect
|
||||
description: "Use this agent when designing new systems, planning major features, reviewing architectural decisions in PRs, or evaluating the high-level structure of a codebase. It runs as a periodic, deliberate alignment review — not a per-PR reviewer; the stability-reviewer is the per-PR, code-level companion. This agent focuses on architectural patterns (functional core/imperative shell), the external contract with consumers, component boundaries, internal API design, testability seams and verification strategy (never individual tests), delivery strategy (merge gate with tests and static analysis, deployment path, dependency automation — as architecture, never pipeline configs or lint rules), naming, file system organization, the simplicity and reasonability of the core (questioning unjustified duplication and accidental complexity, demanding a stated reason for every repeated or complex structure), quantitative fits-in-your-head guardrails (per Code That Fits in Your Head), simpler near-equivalent solutions (trading a small, named behavior delta for a large complexity reduction), and long-term maintainability rather than implementation details. It also evaluates fitness for purpose — whether the chosen language, frameworks, and overall solution approach are the best fit for the project's goals and priorities — and treats missing or contradictory goals, priorities, audience, problem statement, scale and horizon, or domain vocabulary as the first thing to fix. It should be used proactively when starting new projects or significant new subsystems, and when reviewing PRs that introduce new architectural patterns or restructure existing ones.\\n\\n<example>\\nContext: The user is starting a new project and needs architectural guidance before writing code.\\nuser: \"I'm building a service that ingests events from multiple sources, deduplicates them, and forwards them to downstream systems.\"\\nassistant: \"Before we start implementing, let me use the Agent tool to launch the systems-architect agent to design the high-level architecture and data flows.\"\\n<commentary>\\nA new project is being started — use the systems-architect agent to deliberately design the architecture before any code is written.\\n</commentary>\\n</example>\\n\\n<example>\\nContext: A PR has been opened that introduces a new module or restructures existing components.\\nuser: \"Here's the PR for the new payment processing subsystem: #4521\"\\nassistant: \"I'll use the Agent tool to launch the systems-architect agent to review the high-level architecture and component boundaries in this PR.\"\\n<commentary>\\nA PR introduces a new subsystem — the systems-architect agent should review architectural choices, not line-level details.\\n</commentary>\\n</example>\\n\\n<example>\\nContext: The user is adding a significant new feature that crosses multiple components.\\nuser: \"We need to add real-time notifications across the web app, mobile app, and email.\"\\nassistant: \"This crosses several system boundaries. Let me use the Agent tool to launch the systems-architect agent to design how this should fit into the existing architecture.\"\\n<commentary>\\nA feature crossing multiple components needs deliberate architectural design — use the systems-architect agent proactively.\\n</commentary>\\n</example>\\n\\n<example>\\nContext: The user asks for an architecture review but the project has no clearly stated goals or priorities.\\nuser: \"Can you review the architecture of our new sync service?\"\\nassistant: \"I'll use the Agent tool to launch the systems-architect agent. Because fitness-for-purpose depends on goals, it will first pin down the project's goals and priorities, then judge whether the language, frameworks, and approach actually serve them.\"\\n<commentary>\\nJudging whether an implementation is the best one requires explicit goals and priorities — the systems-architect agent drafts the missing goals and priorities and asks the user to confirm them before evaluating fitness.\\n</commentary>\\n</example>"
|
||||
tools: Read, Grep, Glob, WebFetch, WebSearch
|
||||
tools: Read, Grep, Glob, WebFetch, WebSearch, Write
|
||||
---
|
||||
You are an elite Systems Architect with decades of experience designing software systems that endure for as long as their horizon demands. Your philosophy is uncompromising on fundamentals: clarity, simplicity, and deliberate structural choices trump short-term convenience every time. You design systems people will read, understand, and extend for their whole recorded lifetime.
|
||||
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
"""The next chunk's pick: the item the chunk takes first, weighed against the last release cut, and what the default branch holds for the pick."""
|
||||
import dataclasses
|
||||
import re
|
||||
|
||||
from git_repo import commits_since, file_at, git, newest_release_tag
|
||||
from failure import Failure
|
||||
from todo_table import Item, items, next_item, renames
|
||||
from markdown_text import sections
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class LastCut:
|
||||
"""What the default branch holds about its last release, which chunk_item weighs the plan against."""
|
||||
# The newest v* tag, None where the branch has none.
|
||||
tag: str | None | Failure
|
||||
# CHANGELOG.md's text, empty where the branch holds none.
|
||||
changelog: str | Failure
|
||||
# How many commits follow the tag, or make up the branch where it has none.
|
||||
commits: int | Failure
|
||||
# todo.md's text at the tag and at each later commit that changed it, oldest first, as named_releases reads them; empty without a tag.
|
||||
todos_since: list[str] | Failure
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Next:
|
||||
"""The plan's earliest release is the next release: the earliest after the last cut that todo.md has named since that cut. Without a cut, the plan's earliest release is the next."""
|
||||
# None where the plan holds no item.
|
||||
release: tuple[int, int, int] | None
|
||||
# The item the next chunk takes first, next_item's pick; None where every item waits or the plan holds none.
|
||||
item: Item | None
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Cut:
|
||||
"""The plan's earliest release is the last cut's version or earlier."""
|
||||
release: tuple[int, int, int]
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Finished:
|
||||
"""The next release holds no item, and changes are unreleased."""
|
||||
# The next release, None where todo.md has named none since the cut.
|
||||
release: tuple[int, int, int] | None
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Unplanned:
|
||||
"""The next release holds no item, and no change is unreleased."""
|
||||
# The next release, None where todo.md has named none since the cut.
|
||||
release: tuple[int, int, int] | None
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Unknown:
|
||||
"""todo.md's texts since the cut, or the changes since it, cannot be read."""
|
||||
|
||||
|
||||
# How the plan stands to the last cut, the version x.y.z the newest v* tag names, with the item the next chunk takes first where there is one.
|
||||
Pick = Next | Cut | Finished | Unplanned | Unknown
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class DefaultPlan:
|
||||
"""What the default branch, as last fetched, holds for chunk_item."""
|
||||
# todo.md's text, empty where the branch holds none.
|
||||
todo: str | Failure
|
||||
cut: LastCut
|
||||
|
||||
|
||||
def default_plan(root: str, ref: str) -> DefaultPlan:
|
||||
"""What ref, the default branch as last fetched, holds for the pick, read in the checkout at root."""
|
||||
tag = newest_release_tag(ref, root)
|
||||
commits = tag if isinstance(tag, Failure) else commits_since(tag, ref, root)
|
||||
return DefaultPlan(file_at(ref, "todo.md", root), LastCut(tag, file_at(ref, "CHANGELOG.md", root), commits, todos_since(tag, ref, root)))
|
||||
|
||||
|
||||
def todos_since(tag: str | None | Failure, ref: str, cwd: str) -> list[str] | Failure:
|
||||
"""LastCut.todos_since, read from ref in cwd. A pull request's own commits do not count, only the merge that landed it: --first-parent."""
|
||||
if not isinstance(tag, str):
|
||||
return []
|
||||
changed = git("log", "--first-parent", "--reverse", "--format=%H", f"{tag}..{ref}", "--", "todo.md", cwd=cwd)
|
||||
if isinstance(changed, Failure):
|
||||
return changed
|
||||
texts = []
|
||||
for commit in [tag, *changed.split()]:
|
||||
text = file_at(commit, "todo.md", cwd)
|
||||
if isinstance(text, Failure):
|
||||
return text
|
||||
texts.append(text)
|
||||
return texts
|
||||
|
||||
|
||||
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."""
|
||||
return standing(cut.tag, unreleased_changes(cut), min((item.release for item in found), default=None), next_item(found), named_releases(cut.todos_since))
|
||||
|
||||
|
||||
def standing(tag: str | None | Failure, changes: int | Failure, earliest: tuple[int, int, int] | None, first: Item | None, named: set[tuple[int, int, int]] | Failure) -> Pick:
|
||||
"""How the plan stands to tag, the newest v* tag.
|
||||
|
||||
earliest is the plan's earliest release, None where the plan holds no item, and first is next_item's pick. changes counts the unreleased changes. named holds each release todo.md named since the tag.
|
||||
"""
|
||||
tagged = re.fullmatch(r"v([0-9]+)\.([0-9]+)\.([0-9]+)", tag) if isinstance(tag, str) else None
|
||||
if tagged is None:
|
||||
return Next(earliest, first)
|
||||
cut_version = tuple(int(part) for part in tagged.groups())
|
||||
if earliest is not None and earliest <= cut_version:
|
||||
return Cut(earliest)
|
||||
if isinstance(named, Failure):
|
||||
return Unknown()
|
||||
first_named = min((release for release in named if release > cut_version), default=None)
|
||||
if earliest is not None and (first_named is None or earliest <= first_named):
|
||||
return Next(earliest, first)
|
||||
if isinstance(changes, Failure):
|
||||
return Unknown()
|
||||
return Finished(first_named) if changes else Unplanned(first_named)
|
||||
|
||||
|
||||
def unreleased_changes(cut: LastCut) -> int | Failure:
|
||||
"""How many changes are unreleased, as `~/.claude/CLAUDE.md` → "Working loop" counts them: the entries under ## Unreleased, or the commits since the tag where CHANGELOG.md has no such section or cannot be read."""
|
||||
entries = unreleased_entries(cut.changelog) if isinstance(cut.changelog, str) else None
|
||||
return cut.commits if entries is None else entries
|
||||
|
||||
|
||||
def unreleased_entries(changelog: str) -> int | None:
|
||||
"""How many top-level `- ` entries CHANGELOG.md holds under ## Unreleased; None without that section."""
|
||||
found = sections(changelog).get("Unreleased")
|
||||
return None if found is None else sum(line.startswith("- ") for line in found[0].splitlines())
|
||||
|
||||
|
||||
def named_releases(todos: list[str] | Failure) -> set[tuple[int, int, int]] | Failure:
|
||||
"""Each release the todo.md texts, oldest first, file items under. A release leaves the set when a text marks it renamed, and returns when a later text files items under it again. A text whose items or marks do not parse names none, except the newest: where its marks do not parse, it returns that Failure, since the release they should have excluded would read as finished."""
|
||||
if isinstance(todos, Failure):
|
||||
return todos
|
||||
if todos and isinstance(newest := renames(todos[-1]), Failure):
|
||||
return newest
|
||||
named: set[tuple[int, int, int]] = set()
|
||||
for text in todos:
|
||||
plan, marked = items(text), renames(text)
|
||||
if isinstance(plan, list) and isinstance(marked, set):
|
||||
named = (named - marked) | {item.release for item in plan}
|
||||
return named
|
||||
@@ -0,0 +1,76 @@
|
||||
"""The pure choices the preflight's steps act on."""
|
||||
import pathlib
|
||||
import re
|
||||
|
||||
from chunk_pick import chunk_item, Cut, Finished, LastCut, Unknown, Unplanned
|
||||
from failure import Failure
|
||||
from chunk_preflight.gathered import Forge, NoItem, Plan
|
||||
from todo_table import item_details, items, version
|
||||
|
||||
# The command each forge's CLI lists pull requests with; pulls_command adds the flags that pick their rows and fields.
|
||||
PULLS_LIST: dict[Forge, tuple[str, ...]] = {"gh": ("gh", "pr", "list"), "tea": ("tea", "pulls", "list")}
|
||||
|
||||
|
||||
def planned(todo: str | Failure, cut: LastCut, default: str) -> Plan | NoItem:
|
||||
"""The plan in todo, the default branch's todo.md, with the item the next chunk takes first, chunk_pick.chunk_item's pick; else why there is none."""
|
||||
where = f"{default}'s todo.md"
|
||||
if isinstance(todo, Failure):
|
||||
return NoItem(f"{where} cannot be read: {todo.reason}.")
|
||||
found = items(todo)
|
||||
if isinstance(found, Failure):
|
||||
return NoItem(f"{where} cannot be read: {found.reason}.")
|
||||
if found is None:
|
||||
return NoItem(f"{where} holds no items table.")
|
||||
pick = chunk_item(found, cut)
|
||||
if isinstance(pick, Cut):
|
||||
return NoItem(f"{where} files items under release {version(pick.release)}, which is not after the last cut, {cut.tag}; ask the human which release they belong to.")
|
||||
if isinstance(pick, Unknown):
|
||||
return NoItem(f"{where} may hold no item for the next release after the last cut, {cut.tag}: todo.md's texts since then, or the count of changes since then, cannot be read. Find the next release yourself.")
|
||||
if isinstance(pick, Finished | Unplanned):
|
||||
upcoming = f"release {version(pick.release)}, the next after the last cut, {cut.tag}" if pick.release else f"the next release after the last cut, {cut.tag}"
|
||||
if isinstance(pick, Finished):
|
||||
return NoItem(f"{where} holds no item for {upcoming}, and changes are unreleased, so that release is finished and ready to cut. The working loop stops here. If todo.md renamed that release instead, add `- <old release> renamed to <new release>` to todo.md's `## Renamed` section.")
|
||||
return NoItem(f"{where} holds no item for {upcoming}, and no change is unreleased, so that release is to be planned first.")
|
||||
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.")
|
||||
details = item_details(todo)
|
||||
detail = details.get(first.id, "") if isinstance(details, dict) else f"(todo.md's details cannot be read: {details.reason})"
|
||||
return Plan(found, first, f"{first.tagline}\n\n{detail}".strip())
|
||||
|
||||
|
||||
def worktree_on(porcelain: str, branch: str) -> pathlib.Path | None:
|
||||
"""The worktree on branch, in what `git worktree list --porcelain` printed; None where none is."""
|
||||
for block in porcelain.split("\n\n"):
|
||||
fields = dict(line.partition(" ")[::2] for line in block.splitlines())
|
||||
if fields.get("branch") == f"refs/heads/{branch}":
|
||||
return pathlib.Path(fields["worktree"])
|
||||
return None
|
||||
|
||||
|
||||
def worktree_add(branch: str, path: pathlib.Path, default: str, local: bool, pushed: bool) -> tuple[list[str], str]:
|
||||
"""The git arguments that add branch's worktree at path, and how it comes to be: on the local branch, else on a new one tracking origin's, else on a new one off default."""
|
||||
if local:
|
||||
return ["worktree", "add", "--quiet", str(path), branch], f"added on the branch {branch}, which existed already."
|
||||
if pushed:
|
||||
return ["worktree", "add", "--quiet", "--track", "-b", branch, str(path), f"origin/{branch}"], f"added on the new branch {branch}, made off origin/{branch}."
|
||||
# --no-track: tracking the default branch would point a bare `git push` at it.
|
||||
return ["worktree", "add", "--quiet", "--no-track", "-b", branch, str(path), default], f"added on the new branch {branch}, made off {default}."
|
||||
|
||||
|
||||
def forge_of(origin_url: str) -> Forge:
|
||||
return "gh" if "github.com" in origin_url else "tea"
|
||||
|
||||
|
||||
def pulls_command(forge: Forge, branch: str) -> list[str]:
|
||||
"""The command that lists open pull requests: gh only branch's, by number and URL; tea every one, by index, head and URL, for facts.open_pulls to pick branch's."""
|
||||
if forge == "gh":
|
||||
return [*PULLS_LIST["gh"], "--head", branch, "--json", "number,url", "--template", "{{range .}}{{.number}}\t{{.url}}\n{{end}}"]
|
||||
return [*PULLS_LIST["tea"], "--fields", "index,head,url", "--output", "tsv"]
|
||||
|
||||
|
||||
def named_paths(text: str, tracked: list[str]) -> list[tuple[str, int]]:
|
||||
"""Each backticked span in text, in order and once, that names a tracked file or folder, with how many of the tracked files it holds: 1 for a file."""
|
||||
spans = dict.fromkeys(span.removesuffix("/") for span in re.findall(r"`([^`\s]+)`", text))
|
||||
held = ((span, sum(path == span or path.startswith(f"{span}/") for path in tracked)) for span in spans)
|
||||
return [(span, count) for span, count in held if count]
|
||||
@@ -1,7 +1,9 @@
|
||||
"""The lines the preflight prints, stated from what it gathered."""
|
||||
from todo_table import bundle_candidates, Item, LastCut, unreleased_entries
|
||||
from todo_table import bundle_candidates, Item, version
|
||||
from failure import Failure
|
||||
from chunk_preflight.gathered import Forge, Gathered, ItemFacts, NamedPath, NoItem, Plan, PULLS_LIST, Ran, version
|
||||
from chunk_preflight.gathered import Forge, Gathered, ItemFacts, NamedPath, NoItem, Plan, Ran
|
||||
from chunk_pick import LastCut, unreleased_entries
|
||||
from chunk_preflight.choices import PULLS_LIST
|
||||
from markdown_text import quoted
|
||||
|
||||
|
||||
|
||||
@@ -1,16 +1,14 @@
|
||||
"""What the preflight gathers, and the pure choices its steps act on; facts.render states it."""
|
||||
"""What the preflight gathers, which facts.render states."""
|
||||
import dataclasses
|
||||
import pathlib
|
||||
import re
|
||||
import typing
|
||||
|
||||
from todo_table import chunk_item, Item, item_details, items, LastCut
|
||||
from failure import Failure
|
||||
from todo_table import Item
|
||||
from chunk_pick import LastCut
|
||||
|
||||
# The CLI that lists a forge's pull requests: gh for a github.com origin, tea for any other.
|
||||
Forge = typing.Literal["gh", "tea"]
|
||||
# The command each forge's CLI lists pull requests with; pulls_command adds the flags that pick their rows and fields.
|
||||
PULLS_LIST: dict[Forge, tuple[str, ...]] = {"gh": ("gh", "pr", "list"), "tea": ("tea", "pulls", "list")}
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
@@ -79,72 +77,3 @@ class Gathered:
|
||||
cut: LastCut
|
||||
# What was found or made for the plan's first item; else why the plan names none.
|
||||
item: ItemFacts | NoItem
|
||||
|
||||
|
||||
def planned(todo: str | Failure, cut: LastCut, default: str) -> Plan | NoItem:
|
||||
"""The plan in todo, the default branch's todo.md, with the item the next chunk takes first, todo_table.chunk_item's pick; else why there is none."""
|
||||
where = f"{default}'s todo.md"
|
||||
if isinstance(todo, Failure):
|
||||
return NoItem(f"{where} cannot be read: {todo.reason}.")
|
||||
found = items(todo)
|
||||
if isinstance(found, Failure):
|
||||
return NoItem(f"{where} cannot be read: {found.reason}.")
|
||||
if found is None:
|
||||
return NoItem(f"{where} holds no items table.")
|
||||
earliest = min((item.release for item in found), default=None)
|
||||
stands, first = chunk_item(found, cut)
|
||||
if earliest is not None and stands == "cut":
|
||||
return NoItem(f"{where} files items under release {version(earliest)}, which is not after the last cut, {cut.tag}; ask the human which release they belong to.")
|
||||
gap = f"{where} holds no item for the next release after the last cut, {cut.tag}, and"
|
||||
if stands == "finished":
|
||||
return NoItem(f"{gap} work has landed since, so that release is finished and ready to cut, and the working loop stops here.")
|
||||
if stands == "unplanned":
|
||||
return NoItem(f"{gap} no work has landed since, so that release is to be planned first.")
|
||||
if stands == "unknown":
|
||||
return NoItem(f"{where} may hold no item for the next release after the last cut, {cut.tag}: todo.md's texts since then, or the count of work landed since then, cannot be read. Find the next release yourself.")
|
||||
if first is None:
|
||||
return NoItem(f"every item of release {version(earliest)} in {where} waits." if earliest is not None else f"{where}'s items table holds no item.")
|
||||
details = item_details(todo)
|
||||
detail = details.get(first.id, "") if isinstance(details, dict) else f"(todo.md's details cannot be read: {details.reason})"
|
||||
return Plan(found, first, f"{first.tagline}\n\n{detail}".strip())
|
||||
|
||||
|
||||
def version(release: tuple[int, int, int]) -> str:
|
||||
return ".".join(map(str, release))
|
||||
|
||||
|
||||
def worktree_on(porcelain: str, branch: str) -> pathlib.Path | None:
|
||||
"""The worktree on branch, in what `git worktree list --porcelain` printed; None where none is."""
|
||||
for block in porcelain.split("\n\n"):
|
||||
fields = dict(line.partition(" ")[::2] for line in block.splitlines())
|
||||
if fields.get("branch") == f"refs/heads/{branch}":
|
||||
return pathlib.Path(fields["worktree"])
|
||||
return None
|
||||
|
||||
|
||||
def worktree_add(branch: str, path: pathlib.Path, default: str, local: bool, pushed: bool) -> tuple[list[str], str]:
|
||||
"""The git arguments that add branch's worktree at path, and how it comes to be: on the local branch, else on a new one tracking origin's, else on a new one off default."""
|
||||
if local:
|
||||
return ["worktree", "add", "--quiet", str(path), branch], f"added on the branch {branch}, which existed already."
|
||||
if pushed:
|
||||
return ["worktree", "add", "--quiet", "--track", "-b", branch, str(path), f"origin/{branch}"], f"added on the new branch {branch}, made off origin/{branch}."
|
||||
# --no-track: tracking the default branch would point a bare `git push` at it.
|
||||
return ["worktree", "add", "--quiet", "--no-track", "-b", branch, str(path), default], f"added on the new branch {branch}, made off {default}."
|
||||
|
||||
|
||||
def forge_of(origin_url: str) -> Forge:
|
||||
return "gh" if "github.com" in origin_url else "tea"
|
||||
|
||||
|
||||
def pulls_command(forge: Forge, branch: str) -> list[str]:
|
||||
"""The command that lists open pull requests: gh only branch's, by number and URL; tea every one, by index, head and URL, for facts.open_pulls to pick branch's."""
|
||||
if forge == "gh":
|
||||
return [*PULLS_LIST["gh"], "--head", branch, "--json", "number,url", "--template", "{{range .}}{{.number}}\t{{.url}}\n{{end}}"]
|
||||
return [*PULLS_LIST["tea"], "--fields", "index,head,url", "--output", "tsv"]
|
||||
|
||||
|
||||
def named_paths(text: str, tracked: list[str]) -> list[tuple[str, int]]:
|
||||
"""Each backticked span in text, in order and once, that names a tracked file or folder, with how many of the tracked files it holds: 1 for a file."""
|
||||
spans = dict.fromkeys(span.removesuffix("/") for span in re.findall(r"`([^`\s]+)`", text))
|
||||
held = ((span, sum(path == span or path.startswith(f"{span}/") for path in tracked)) for span in spans)
|
||||
return [(span, count) for span, count in held if count]
|
||||
|
||||
@@ -13,9 +13,11 @@ holds it, the plan loop-claude routes on. It prints:
|
||||
- the next release and its first item that does not wait, the item loop-claude routes on, with
|
||||
its L and E + I. An item waits while it is marked question, or while an item still in todo.md
|
||||
blocks it. Where the newest tag names a version x.y.z, the next release is the earliest after
|
||||
x.y.z that todo.md has named at that tag or since; otherwise it is todo.md's earliest release.
|
||||
Where the next release holds no item, it says so: finished and ready to cut where work landed
|
||||
since the tag (the ## Unreleased entries, or else the commits), and else to be planned first.
|
||||
x.y.z that todo.md has named at that tag or since, less a release its ## Renamed section marks
|
||||
renamed. Otherwise it is todo.md's earliest release.
|
||||
Where the next release holds no item, it says so, naming it where todo.md named it since the tag:
|
||||
finished and ready to cut where changes are unreleased (the ## Unreleased entries, or else the
|
||||
commits since the tag), and else to be planned first.
|
||||
Where todo.md's earliest release is x.y.z or earlier, it says todo.md files items under a release
|
||||
already cut;
|
||||
- the item's worktree: a sibling of the checkout named <checkout>-item-<ID>, on the branch
|
||||
@@ -45,9 +47,11 @@ import subprocess
|
||||
import sys
|
||||
import typing
|
||||
|
||||
from git_repo import commit_exists, default_branch, default_plan, file_at, git, top
|
||||
from git_repo import commit_exists, default_branch, file_at, git, top
|
||||
from chunk_pick import default_plan
|
||||
from failure import Failure
|
||||
from chunk_preflight.gathered import Forge, forge_of, Gathered, ItemFacts, named_paths, NamedPath, NoItem, Plan, planned, pulls_command, Ran, Worktree, worktree_add, worktree_on
|
||||
from chunk_preflight.gathered import Forge, Gathered, ItemFacts, NamedPath, NoItem, Plan, Ran, Worktree
|
||||
from chunk_preflight.choices import forge_of, named_paths, planned, pulls_command, worktree_add, worktree_on
|
||||
from chunk_preflight.facts import render
|
||||
|
||||
BIN = pathlib.Path(__file__).resolve().parents[1]
|
||||
|
||||
@@ -9,14 +9,15 @@ import unittest
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from failure import Failure
|
||||
from chunk_preflight.gathered import forge_of, Gathered, ItemFacts, named_paths, NamedPath, NoItem, planned, Ran, Worktree, worktree_add
|
||||
from chunk_preflight.choices import forge_of, named_paths, planned, worktree_add
|
||||
from chunk_preflight.gathered import Gathered, ItemFacts, NamedPath, NoItem, Ran, Worktree
|
||||
from test_env import isolated_env
|
||||
from todo_table import LastCut, unreleased_entries
|
||||
from chunk_pick import LastCut
|
||||
from chunk_preflight.main import line_count, ran, seconds, TIMEOUT
|
||||
from chunk_preflight.facts import open_pulls, render
|
||||
|
||||
BIN = pathlib.Path(__file__).resolve().parents[1]
|
||||
README = "# Project\n\n## Goals\n\n1. **Achieve:** Work.\n\n## Audience\n\nMe.\n"
|
||||
README = "# Project\n\n## Goals\n\n**Void:** code health, since the plan's scores weigh goal 1 alone.\n\n1. **Achieve:** Work.\n\n## Audience\n\nMe.\n"
|
||||
# Item 3 is the next release's first item that does not wait; 7 waits only on 3, 5 is a question, 8 waits on 5, 9 is in a later release.
|
||||
TODO = """# todo
|
||||
|
||||
@@ -166,6 +167,18 @@ class ChunkPreflightTool(unittest.TestCase):
|
||||
self.assertNotIn("item 9", done.stdout)
|
||||
self.assertFalse((repo.temp / "proj-item-9").exists())
|
||||
|
||||
def test_takes_the_next_item_where_the_plan_marks_the_release_after_the_last_cut_renamed_and_calls_it_finished_where_it_does_not(self):
|
||||
for mark, fact, absent in (("\n## Renamed\n\n- 0.2.0 renamed to 0.3.0\n", "item 3", "finished"), ("", "finished and ready to cut", "item 3")):
|
||||
with self.subTest(mark=mark):
|
||||
repo = Repo(self)
|
||||
repo.write(repo.root, "todo.md", TODO.replace("| 0.3.0 |", "| 0.4.0 |").replace("| 0.2.0 |", "| 0.3.0 |") + mark)
|
||||
repo.commit(repo.root, "move 0.2.0's items to 0.3.0")
|
||||
repo.git(repo.root, "push", "--quiet", "origin", "main")
|
||||
done = repo.preflight()
|
||||
self.assertEqual(done.returncode, 0, done.stderr)
|
||||
self.assertIn(fact, done.stdout)
|
||||
self.assertNotIn(absent, done.stdout)
|
||||
|
||||
def test_weighs_todo_md_at_the_last_cut_and_on_the_default_branch_after_it_alone(self):
|
||||
"""Each case's plans: before the tag, at it, on a side branch merged after it, and after it, each committed in turn where given."""
|
||||
cases = (
|
||||
@@ -409,18 +422,21 @@ class Plans(unittest.TestCase):
|
||||
self.assertNotIn("no items table", empty)
|
||||
|
||||
def test_finds_the_release_after_the_last_cut_finished_or_to_be_planned_where_the_plan_holds_no_item_for_it(self):
|
||||
named = "release 0.2.0, the next after the last cut, v0.1.0"
|
||||
unnamed = "the next release after the last cut, v0.1.0"
|
||||
cases = (
|
||||
(LATER, 4, "finished and ready to cut"),
|
||||
(LATER, 0, "planned first"),
|
||||
(EMPTY, 4, "finished and ready to cut"),
|
||||
(EMPTY, 0, "planned first"),
|
||||
(LATER, Failure("count unreadable"), "cannot be read"),
|
||||
(LATER, 4, [TODO], "finished and ready to cut", named),
|
||||
(LATER, 0, [TODO], "planned first", named),
|
||||
(EMPTY, 4, [TODO], "finished and ready to cut", named),
|
||||
(EMPTY, 0, [TODO], "planned first", named),
|
||||
(EMPTY, 4, [EMPTY], "finished and ready to cut", unnamed),
|
||||
(LATER, Failure("count unreadable"), [TODO], "cannot be read", unnamed),
|
||||
)
|
||||
for todo, commits, fact in cases:
|
||||
with self.subTest(todo=todo, commits=commits):
|
||||
why = planned(todo, LastCut("v0.1.0", "", commits, [TODO]), "origin/main").why
|
||||
for todo, commits, todos, fact, release in cases:
|
||||
with self.subTest(todo=todo, commits=commits, todos=todos):
|
||||
why = planned(todo, LastCut("v0.1.0", "", commits, todos), "origin/main").why
|
||||
self.assertIn(fact, why)
|
||||
self.assertIn("v0.1.0", why)
|
||||
self.assertIn(release, why)
|
||||
|
||||
def test_says_what_todo_md_named_since_the_last_cut_cannot_be_read(self):
|
||||
self.assertIn("cannot be read", planned(LATER, LastCut("v0.1.0", "", 4, Failure("log unreadable")), "origin/main").why)
|
||||
@@ -439,11 +455,6 @@ class Plans(unittest.TestCase):
|
||||
|
||||
|
||||
class Gathering(unittest.TestCase):
|
||||
def test_counts_the_top_level_entries_under_unreleased(self):
|
||||
self.assertEqual(unreleased_entries(CHANGELOG), 2)
|
||||
self.assertEqual(unreleased_entries("# Changelog\n\n## Unreleased\n\n## 0.1.0\n\n- Old.\n"), 0)
|
||||
self.assertIsNone(unreleased_entries("# Changelog\n\n## 0.1.0\n\n- Old.\n"))
|
||||
|
||||
def test_names_each_tracked_file_or_folder_a_backticked_span_names_once_with_its_files(self):
|
||||
cases = (
|
||||
("`src/` and `src`", ["src/app.py", "srcfoo/x.py"], [("src", 1)]),
|
||||
|
||||
@@ -23,7 +23,7 @@ def queued(prompt, kind):
|
||||
|
||||
|
||||
class Render(unittest.TestCase):
|
||||
def test_joins_assistant_text_tool_calls_human_turns_and_loop_prompts_and_skips_the_rest(self):
|
||||
def test_joins_assistant_text_tool_calls_human_turns_and_loop_prompts_labelling_a_typed_answer_the_humans_and_skips_the_rest(self):
|
||||
said = transcript.render([
|
||||
human("do it"),
|
||||
assistant({"type": "text", "text": "Starting."}, {"type": "tool_use", "name": "Bash", "input": {"command": "ls"}}),
|
||||
@@ -34,8 +34,9 @@ class Render(unittest.TestCase):
|
||||
queued("B, while you work", "human"),
|
||||
queued("origin/main moved", "coordinator"),
|
||||
{**human("Continue the task; the previous run stopped before it was finished."), "promptSource": "sdk"},
|
||||
])
|
||||
self.assertEqual(said, '[human] do it\n\nStarting.\n\n[tool Bash] {"command": "ls"}\n\n[human] yes, merge it\n\n[human] B, while you work\n\n[loop] Continue the task; the previous run stopped before it was finished.')
|
||||
{**human("Answered: use B\nYour question: A or B?"), "promptSource": "sdk"},
|
||||
], lambda prompt: transcript.Typed(*reversed(prompt.removeprefix("Answered: ").split("\n"))) if prompt.startswith("Answered: ") else None)
|
||||
self.assertEqual(said, '[human] do it\n\nStarting.\n\n[tool Bash] {"command": "ls"}\n\n[human] yes, merge it\n\n[human] B, while you work\n\n[loop] Continue the task; the previous run stopped before it was finished.\n\n[loop] Your question: A or B?\n\n[human] use B')
|
||||
|
||||
|
||||
class FirstTimestampedLine(unittest.TestCase):
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import json
|
||||
import typing
|
||||
|
||||
from claude_code.entries import assistant_parts, human_text, loop_text, parse_entry, part_text, tool_call
|
||||
from failure import Failure
|
||||
@@ -6,6 +7,12 @@ from failure import Failure
|
||||
JUDGED_TOOL_INPUT = 400
|
||||
|
||||
|
||||
class Typed(typing.NamedTuple):
|
||||
"""A -p prompt of loop-claude's that carries an answer the human typed: loop-claude's words, and that answer."""
|
||||
loop_words: str
|
||||
answer: str
|
||||
|
||||
|
||||
def read_transcript(path: str) -> list[dict] | Failure:
|
||||
try:
|
||||
with open(path, "rb") as handle:
|
||||
@@ -24,14 +31,16 @@ def human_turns(entries: list[dict]) -> int:
|
||||
return sum(1 for entry in entries if human_text(entry) is not None)
|
||||
|
||||
|
||||
def render(entries: list[dict]) -> str:
|
||||
def render(entries: list[dict], typed_answer: typing.Callable[[str], Typed | None]) -> str:
|
||||
"""The transcript as the judge reads it. typed_answer splits the answer the human typed out of a -p prompt of loop-claude's, so that answer reads as the human's, like one typed in claude."""
|
||||
lines = []
|
||||
for entry in entries:
|
||||
lines += [line for part in assistant_parts(entry) if (line := part_line(part, JUDGED_TOOL_INPUT))]
|
||||
if (text := human_text(entry)) is not None:
|
||||
lines.append("[human] " + text)
|
||||
elif (text := loop_text(entry)) is not None:
|
||||
lines.append("[loop] " + text)
|
||||
typed = typed_answer(text)
|
||||
lines += ["[loop] " + text] if typed is None else ["[loop] " + typed.loop_words, "[human] " + typed.answer]
|
||||
return "\n\n".join(lines)
|
||||
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ from failure import Failure
|
||||
from file_writes import replace_json
|
||||
|
||||
|
||||
# A failure only warns: the interrupt still runs, and the human answers Claude Code's trust dialog.
|
||||
# A failure only warns: claude still opens, and the human answers Claude Code's trust dialog.
|
||||
def trust(config: pathlib.Path, roots: list[str]) -> None:
|
||||
try:
|
||||
with open(config, encoding="utf-8") as handle:
|
||||
|
||||
@@ -9,6 +9,8 @@ from utc_stamp import utc
|
||||
ARCHITECT = "Inherited architect"
|
||||
DECIDED_BY = "decided by"
|
||||
DIMENSIONS = ("Navigation", "Locality", "Shape", "Self-sufficiency", "Overall")
|
||||
# The comprehension floor, which every dimension and the overall should reach; docs/decisions.md → "comprehension floor" says it blocks nothing.
|
||||
FLOOR = decimal.Decimal("7.0")
|
||||
HARDEST_FIRST = "hardest first"
|
||||
HEADING = re.compile(r"^([^,]+), (.+) at ([0-9a-f]{7,40})(?:, against ([0-9a-f]{7,40}))?$")
|
||||
HISTORY = "docs/comprehension-history.md"
|
||||
@@ -104,15 +106,61 @@ def entries(history: str) -> list[Entry]:
|
||||
|
||||
|
||||
def latest_places(history: str) -> str | None:
|
||||
"""The places seats found hard from the oldest entry on the commit of the newest entry, by time, that is a scoring run or holds scoring seats' places: in it and each later entry, each ruled place opening with a dimension its seat's vote counted as worse, and every scoring seat's place. Each entry's places come under its heading, oldest first; with no such entry, it starts at the oldest entry. None when no place counts."""
|
||||
found = sorted(entries(history), key=lambda entry: entry.time)
|
||||
scored = [index for index, entry in enumerate(found) if not entry.paired or entry.scored_places]
|
||||
newest_commit = found[scored[-1]].commit if scored else None
|
||||
start = next((index for index in scored if found[index].commit == newest_commit), 0)
|
||||
"""The places seats found hard since the newest scored commit, under each entry's heading, oldest first; None when no place counts.
|
||||
|
||||
They start at the first of newest_scored's entries, so a rerun of one head adds to the run before it. Where no entry counts as scoring the project, they start at the oldest entry. From there, each entry gives every scoring seat's place, and each ruled place opening with a dimension its seat voted worse."""
|
||||
found = by_time(entries(history))
|
||||
newest = newest_scored(found)
|
||||
start = found.index(newest[0]) if newest else 0
|
||||
parts = [placed(entry, worse_places(entry) + labelled_bullets(entry.body, SCORED_PLACES)) for entry in found[start:]]
|
||||
return "\n".join(part for part in parts if part) or None
|
||||
|
||||
|
||||
def latest_overall(history: str) -> decimal.Decimal | Failure | None:
|
||||
"""The mean of the overall means of newest_scored's entries, since a rerun of one head measures it again; None where no entry counts as scoring the project."""
|
||||
overalls = []
|
||||
for entry in newest_scored(by_time(entries(history))):
|
||||
overall = run_overall(entry)
|
||||
if isinstance(overall, Failure):
|
||||
return overall
|
||||
overalls.append(overall)
|
||||
return sum(overalls, decimal.Decimal(0)) / len(overalls) if overalls else None
|
||||
|
||||
|
||||
def newest_scored(found: list[Entry]) -> list[Entry]:
|
||||
"""In found's order, the entries that count as scoring the project on the newest scored commit, the commit of the last such entry; empty where none counts. A commit matches by prefix, since a heading may write it at any length from 7 characters."""
|
||||
scoring = [entry for entry in found if scored(entry)]
|
||||
return [entry for entry in scoring if entry.commit.startswith(scoring[-1].commit) or scoring[-1].commit.startswith(entry.commit)] if scoring else []
|
||||
|
||||
|
||||
def run_overall(run: Entry) -> decimal.Decimal | Failure:
|
||||
"""The overall cell of the Mean row of an entry that counts as scoring the project."""
|
||||
try:
|
||||
overall = decimal.Decimal(overall_cells(run).get(MEAN, ""))
|
||||
except decimal.InvalidOperation:
|
||||
overall = None
|
||||
return overall if overall is not None and overall.is_finite() else Failure(f"{HISTORY}'s scoring run {run.heading} has no Mean row ending in its overall, which sets code health's weight")
|
||||
|
||||
|
||||
def overall_cells(entry: Entry) -> dict[str, str]:
|
||||
"""Each table row's last non-empty cell, by its first cell: a seat's overall vote in a ruling table, whether it has five votes or the older single `Vote`, or its overall score, or the Mean row's, in a scoring table."""
|
||||
return {name: cells[-1] for name, cells in table_rows(entry.body).items() if cells and cells[-1]}
|
||||
|
||||
|
||||
def scoring_runs(found: list[Entry]) -> list[Entry]:
|
||||
"""The scoring runs among the entries, oldest first. Unlike scored, it leaves out a ruling from before PR #255 that holds scoring seats' places: there overall_cells reads each voting seat's vote, not its score."""
|
||||
return [entry for entry in by_time(found) if not entry.paired]
|
||||
|
||||
|
||||
def by_time(found: list[Entry]) -> list[Entry]:
|
||||
return sorted(found, key=lambda entry: entry.time)
|
||||
|
||||
|
||||
def scored(entry: Entry) -> bool:
|
||||
"""Whether the entry counts as scoring the project: a scoring run, or a ruling from before PR #255 that holds scoring seats' places."""
|
||||
return not entry.paired or bool(entry.scored_places)
|
||||
|
||||
|
||||
def worse_places(entry: Entry) -> list[tuple[str, list[str]]]:
|
||||
"""Under each of a ruling's seat labels, the bullets that open with a dimension that seat's vote counted as worse; Overall counts as one."""
|
||||
worse = worse_votes(entry.body)
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
"""Run git, in the current directory or a given one, and read the checkout, its default branch and its files."""
|
||||
import dataclasses
|
||||
import re
|
||||
import subprocess
|
||||
|
||||
from failure import Failure
|
||||
from todo_table import LastCut
|
||||
|
||||
|
||||
def git(*args: str, cwd: str | None = None, timeout: float | None = None) -> str | Failure:
|
||||
@@ -62,37 +60,6 @@ def origin_head(cwd: str | None, timeout: float | None) -> str | Failure:
|
||||
return Failure("origin names no default branch; set it with `git remote set-head origin --auto`")
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class DefaultPlan:
|
||||
"""What the default branch, as last fetched, holds for picking the next chunk's item: todo_table.chunk_item's inputs."""
|
||||
# todo.md's text, empty where the branch holds none.
|
||||
todo: str | Failure
|
||||
cut: LastCut
|
||||
|
||||
|
||||
def default_plan(root: str, ref: str) -> DefaultPlan:
|
||||
"""What ref, the default branch as last fetched, holds for the pick, read in the checkout at root."""
|
||||
tag = newest_release_tag(ref, root)
|
||||
commits = tag if isinstance(tag, Failure) else commits_since(tag, ref, root)
|
||||
return DefaultPlan(file_at(ref, "todo.md", root), LastCut(tag, file_at(ref, "CHANGELOG.md", root), commits, todos_since(tag, ref, root)))
|
||||
|
||||
|
||||
def todos_since(tag: str | None | Failure, ref: str, cwd: str) -> list[str] | Failure:
|
||||
"""todo.md's text at tag and at each later commit on ref that changed it, read in cwd; empty where there is no tag. A pull request's own commits do not count, only the merge that landed it: --first-parent."""
|
||||
if not isinstance(tag, str):
|
||||
return []
|
||||
changed = git("log", "--first-parent", "--format=%H", f"{tag}..{ref}", "--", "todo.md", cwd=cwd)
|
||||
if isinstance(changed, Failure):
|
||||
return changed
|
||||
texts = []
|
||||
for commit in [tag, *changed.split()]:
|
||||
text = file_at(commit, "todo.md", cwd)
|
||||
if isinstance(text, Failure):
|
||||
return text
|
||||
texts.append(text)
|
||||
return texts
|
||||
|
||||
|
||||
def newest_release_tag(branch: str, cwd: str | None = None) -> str | None | Failure:
|
||||
"""The newest `v*` tag merged into branch, read in cwd, else in the current directory; None when it has none."""
|
||||
# Sorts v1.0.0-rc.1 below v1.0.0.
|
||||
|
||||
@@ -28,28 +28,29 @@ import typing
|
||||
|
||||
from transcript_archive.location import archive_root, transcript_of
|
||||
from transcript_archive.read import archived_outcomes
|
||||
from rung_replay.command import arguments_or_exit, down_from, failed, limited_exit, projects_on
|
||||
from judge_replay.replay import Case, case_from, Kind, report, reproduced, sample, verdict_kind
|
||||
from project_key import checkout_of
|
||||
from rung_replay.command import down_from, failed, limited_exit, project_rung_or_exit, projects_on
|
||||
from loop_claude.effects import Effects
|
||||
from failure import Failure
|
||||
from rung_replay.search import first_reply, replayed
|
||||
from loop_claude.cycle.judge import judge_once, Verdict
|
||||
from claude_code.reply import Limited
|
||||
from model_routing.ladder import lowest_worker_rung, project_rung, Rung
|
||||
from loop_claude.project.premises import read_premises
|
||||
from loop_claude.project.records import read_records
|
||||
from claude_code.transcript import read_transcript, render
|
||||
from model_routing.ladder import Rung
|
||||
from claude_code.transcript import read_transcript
|
||||
from loop_claude.stop import Stop
|
||||
|
||||
TOOL = "judge-replay"
|
||||
USAGE = f"{TOOL} <model>, a model on the routing ladder"
|
||||
PER_KIND = 15
|
||||
# The effort settings.json gave every judge before loop-claude routed it; the archived verdicts came from it.
|
||||
REFERENCE_EFFORT = "xhigh"
|
||||
|
||||
|
||||
def main(argv: list[str], env: typing.Mapping[str, str], home: pathlib.Path, effects: Effects) -> int:
|
||||
anchor = project_rung_or_exit(TOOL, argv, __doc__)
|
||||
anchor = arguments_or_exit(TOOL, argv, __doc__, USAGE, model_argument)
|
||||
if isinstance(anchor, int):
|
||||
return anchor
|
||||
cases = archived_cases(anchor.model, archive_root(home, env), home)
|
||||
@@ -59,13 +60,19 @@ def main(argv: list[str], env: typing.Mapping[str, str], home: pathlib.Path, eff
|
||||
return failed(TOOL, f"no archived verdicts of projects on {anchor.model} in {archive_root(home, env)}; run loop-claude on a project on that model first")
|
||||
cases = sample(cases, PER_KIND)
|
||||
reference = Rung(anchor.model, REFERENCE_EFFORT)
|
||||
replay = replayed(cases, reference, down_from(anchor), lambda found, rung: rule(found, rung, home / ".claude", effects), reproduced, "verdicts")
|
||||
# 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(anchor, lowest_worker_rung(anchor)), lambda found, rung: rule(found, rung, home / ".claude", effects), reproduced, "verdicts")
|
||||
if isinstance(replay, Limited):
|
||||
return limited_exit(TOOL, replay)
|
||||
print(report(anchor.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 archived_cases(model: str, root: pathlib.Path, home: pathlib.Path) -> list[Case] | Failure:
|
||||
projects = projects_on(model, home)
|
||||
if isinstance(projects, Failure):
|
||||
@@ -91,5 +98,6 @@ def rule(case: Case, rung: Rung, claude_dir: pathlib.Path, effects: Effects) ->
|
||||
return verdict_kind(Failure(records.reason))
|
||||
if isinstance(entries, Failure):
|
||||
return verdict_kind(entries)
|
||||
verdict: Verdict | Failure | Limited = first_reply(lambda: judge_once(case.root, case.task, premises, records, render(entries), rung, effects))
|
||||
# 0 for the route's mark, as before any step-up: the replay compares verdict kinds, and a mark changes only which escalation quotes count.
|
||||
verdict: Verdict | Failure | Limited = first_reply(lambda: judge_once(case.root, case.task, premises, records, entries, 0, rung, effects))
|
||||
return verdict if isinstance(verdict, Limited) else verdict_kind(verdict)
|
||||
|
||||
@@ -114,7 +114,7 @@ class Main(unittest.TestCase):
|
||||
result = reply(Rung(args[args.index("--model") + 1], args[args.index("--effort") + 1]), "said Verdict: interrupt" in prompt.rsplit("latest last:", 1)[-1])
|
||||
return subprocess.CompletedProcess(args, 0, json.dumps(result), "")
|
||||
|
||||
effects = Effects(claude=claude, claude_on_terminal=unused, execv=unused, git=unused, input=unused, local_time=unused, now=unused, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused)
|
||||
effects = Effects(claude=claude, claude_on_terminal=unused, discard_typed=unused, execv=unused, git=unused, input=unused, local_time=unused, now=unused, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused)
|
||||
out, err = io.StringIO(), io.StringIO()
|
||||
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
|
||||
code = main.main(argv, {}, self.home, effects)
|
||||
@@ -122,7 +122,7 @@ class Main(unittest.TestCase):
|
||||
|
||||
@staticmethod
|
||||
def verdict(interrupt, evidence):
|
||||
output = {"answer": "", "bundled": 0, "bundled_escape_and_impact": 0, "escalation": "", "evidence": evidence, "finished": not interrupt, "interrupt": interrupt, "question": "Which?" if interrupt else ""}
|
||||
output = {"answer": "", "bundled": 0, "bundled_escape_and_impact": 0, "escalation": "", "evidence": evidence, "finished": not interrupt, "interrupt": interrupt, "question": "Which?" if interrupt else "", "release_ready": False}
|
||||
return {"type": "result", "structured_output": output}
|
||||
|
||||
def test_replays_the_models_projects_on_the_reference_then_from_the_projects_rung_down_and_prints_the_lowest_that_returns_all(self):
|
||||
@@ -138,6 +138,14 @@ class Main(unittest.TestCase):
|
||||
self.assertTrue(out.endswith("returns every verdict the reference judge reproduces: claude-sonnet-5-5 at high effort\n"))
|
||||
for said in ("The task an agent was given:\nDo it.", "1. Ship.", "From ~/.claude/CLAUDE.md:\nBe kind."):
|
||||
self.assertIn(said, self.prompts[0])
|
||||
# The replay shows the judge the whole transcript, with no step-up marked in it.
|
||||
self.assertNotIn("[step]", self.prompts[0])
|
||||
|
||||
def test_tries_no_rung_below_the_lowest_a_worker_routes_to_where_every_rung_returns_every_verdict(self):
|
||||
code, out, err = self.run_main(["claude-opus-5-5"], lambda rung, interrupted: self.verdict(interrupted, f"said {INTERRUPTED if interrupted else FINISHED}"))
|
||||
self.assertEqual(code, 0, err)
|
||||
self.assertEqual([(model, effort) for model, effort, _ in self.calls[::2]][-1], ("claude-haiku-5-5", "max"))
|
||||
self.assertTrue(out.endswith("returns every verdict the reference judge reproduces: claude-haiku-5-5 at max effort\n"), out)
|
||||
|
||||
def test_stops_at_the_projects_rung_and_names_none_when_it_misses(self):
|
||||
code, out, _ = self.run_main(["claude-opus-5-5"], lambda rung, interrupted: self.verdict(interrupted and rung == REFERENCE, f"said {INTERRUPTED if interrupted else FINISHED}"))
|
||||
|
||||
@@ -1,17 +1,12 @@
|
||||
import decimal
|
||||
|
||||
from comprehension_history import counted_vote, entries, Entry, table_rows
|
||||
from comprehension_history import counted_vote, entries, Entry, overall_cells, scoring_runs
|
||||
from larv_review.seats import FIRST_SEATS
|
||||
|
||||
# Matches score-outcomes, which waits for 10 finished chunks before it shows a median.
|
||||
MIN_PAIRS = 10
|
||||
|
||||
|
||||
def overall_cells(entry: Entry) -> dict[str, str]:
|
||||
"""Each table row's last non-empty cell, by its first cell: a seat's overall vote in a ruling table, whether it has five votes or the older single `Vote`, or its overall score in a scoring table."""
|
||||
return {name: cells[-1] for name, cells in table_rows(entry.body).items() if cells and cells[-1]}
|
||||
|
||||
|
||||
def ruling_agreement(found: list[Entry]) -> list[bool]:
|
||||
"""For each paired ruling that holds both of the first seats' overall votes, whether they counted alike."""
|
||||
first, second = FIRST_SEATS
|
||||
@@ -23,7 +18,7 @@ def run_agreement(found: list[Entry]) -> list[bool]:
|
||||
"""For each commit scored at least twice, whether the first two seats' overall scores moved the same way, up, down or not at all, from its first run to its second. Both runs read one tree, so the pair is the ruling those seats would make from absolute scores on code that did not change."""
|
||||
first, second = FIRST_SEATS
|
||||
runs: dict[str, list[dict[str, decimal.Decimal]]] = {}
|
||||
for entry in sorted((each for each in found if not each.paired), key=lambda each: each.time):
|
||||
for entry in scoring_runs(found):
|
||||
cells = overall_cells(entry)
|
||||
if first in cells and second in cells:
|
||||
runs.setdefault(entry.commit, []).append({first: decimal.Decimal(cells[first]), second: decimal.Decimal(cells[second])})
|
||||
|
||||
@@ -22,7 +22,7 @@ def history_changes(default: str) -> list[HistoryChange] | Failure:
|
||||
return changes
|
||||
|
||||
|
||||
def landed_since_release(default: str) -> bool | Failure:
|
||||
def committed_since_release(default: str) -> bool | Failure:
|
||||
"""Whether the default branch holds a commit after its newest `v*` tag, or any commit when it has none."""
|
||||
newest = newest_release_tag(default)
|
||||
if isinstance(newest, Failure):
|
||||
|
||||
+43
-15
@@ -1,17 +1,21 @@
|
||||
"""Hold larv-review's mechanical rules: the paired ruling's base and vote count, each pass's rounds, the scoring run's trigger, and the comprehension history's format and latest places, and its count of how often seats agree.
|
||||
"""Hold larv-review's mechanical rules: the chunk's review folder, the paired ruling's base and vote count, each pass's rounds, the scoring run's trigger, and the comprehension history's format and latest places, and its count of how often seats agree.
|
||||
|
||||
usage: larv-review ruling-base | round-count | needs-scoring-run [<item ID>...] | record-ruling <votes file> | record-scoring <scores file> [<item ID>...] | places | agreement
|
||||
usage: larv-review review-folder | ruling-base | round-count | needs-scoring-run [<item ID>...] | record-ruling <votes file> | record-scoring <scores file> [<item ID>...] | places | agreement
|
||||
|
||||
The comprehension check records how hard a project is to read, two ways, and blocks no merge. In a
|
||||
paired ruling, simulated readers, the seats, read the branch's head beside a base and vote better,
|
||||
same or worse, overall and on each dimension. In a scoring run, four seats score the project from 1
|
||||
to 10. Each seat names the places it found hard.
|
||||
|
||||
Run it inside a project checkout or one of its worktrees. Each command but record-ruling, places and agreement
|
||||
first fetches origin, when the checkout has that remote, and takes origin's default branch, or else the
|
||||
local main or master, as the default branch. When the fetch fails, round-count reads origin as
|
||||
last fetched and says so on stderr; the other three exit 1. The history is
|
||||
docs/comprehension-history.md in the checkout.
|
||||
Run it inside a project checkout or one of its worktrees. Each command but review-folder,
|
||||
record-ruling, places and agreement first fetches origin, when the checkout has that remote, and
|
||||
takes origin's default branch, or else the local main or master, as the default branch. When the
|
||||
fetch fails, round-count reads origin as last fetched and says so on stderr; the other three exit 1.
|
||||
The history is docs/comprehension-history.md in the checkout.
|
||||
|
||||
review-folder makes the chunk's review folder, where each reviewer writes its report, and prints its
|
||||
path: ~/.local/state/larv-review/ followed by the worktree's path relative to ~, or to / outside it.
|
||||
It leaves ~/.local/state/larv-review readable by you alone.
|
||||
|
||||
ruling-base prints the commit a paired ruling reads against, then which of these found it. The last
|
||||
measured commit is the default branch's newest merged change that adds a paired ruling or a scoring
|
||||
@@ -29,7 +33,8 @@ an item whose tagline names the comprehension floor, or when it leaves a release
|
||||
the checkout's todo.md, less the shipped items, and work has landed towards that release. Work has
|
||||
landed when the chunk ships one of the release's items, or when the release is the earliest the
|
||||
default branch's todo.md names and the default branch has a commit after its newest v* tag, or has
|
||||
no v* tag.
|
||||
no v* tag. A release the checkout's todo.md marks renamed in its ## Renamed section, as
|
||||
`- 0.2.1 renamed to 0.3.0`, is due none.
|
||||
|
||||
A second scoring run of one head names itself `<PR or branch> rerun at <commit>`, so record-scoring
|
||||
does not refuse it as a repeat of the first.
|
||||
@@ -67,7 +72,9 @@ prints `Ruling:` and appends the ruling.
|
||||
record-scoring takes the scores file of a run needs-scoring-run calls, whose first line names no
|
||||
`, against`, and the same item IDs, and exits 1 when they call no run. It appends the seats' scores
|
||||
and their means, rounded half up to two decimals, prints the means and, when a mean is under the
|
||||
floor of {floor}, a line opening `Floor:` naming each one.
|
||||
floor of {floor}, a line opening `Floor:` naming each one. Then it ranks the checkout's todo.md as
|
||||
rank_todo.py does, since the overall sets the weight of code health, the goal every project shares,
|
||||
and exits 1 where rank_todo.py would, with the run recorded.
|
||||
|
||||
places prints the places seats found hard since the newest scored commit: the places of each scoring
|
||||
run on it, and,
|
||||
@@ -86,8 +93,10 @@ time and the seats file's first line. Each commit that line names must be in the
|
||||
when the history already holds an entry on what that line reads.
|
||||
|
||||
Exit 1, saying why, on unknown arguments, an unknown item ID, a seats file it cannot read or that
|
||||
breaks the shape above, or when git cannot start, finds no checkout or no default branch, cannot
|
||||
fetch origin for ruling-base, needs-scoring-run or record-scoring, or cannot read or write the history or todo.md.
|
||||
breaks the shape above, a todo.md that fails rank_todo.py after record-scoring records a run, or
|
||||
when git cannot start, finds no checkout or no default branch, cannot fetch origin for ruling-base,
|
||||
needs-scoring-run or record-scoring, or cannot read or write the history, todo.md or the review
|
||||
folder.
|
||||
"""
|
||||
import pathlib
|
||||
import re
|
||||
@@ -95,16 +104,17 @@ import sys
|
||||
import typing
|
||||
|
||||
from round_titles import CAP, PASSES, round_counts
|
||||
from git_repo import default_branch, git
|
||||
from git_repo import default_branch, git, top
|
||||
from failure import Failure
|
||||
from larv_review.scoring import FLOOR
|
||||
from comprehension_history import FLOOR
|
||||
from larv_review.git import history_changes
|
||||
from larv_review.ruling_base import measured_commit
|
||||
from larv_review.agreement import MIN_PAIRS
|
||||
from larv_review.plan import plan_reasons
|
||||
from larv_review.record import record_ruling, record_scoring, show_agreement, show_places
|
||||
from review_folder import REPORTS, review_folder
|
||||
|
||||
USAGE = "usage: larv-review ruling-base | round-count | needs-scoring-run [<item ID>...] | record-ruling <votes file> | record-scoring <scores file> [<item ID>...] | places | agreement"
|
||||
USAGE = "usage: larv-review review-folder | ruling-base | round-count | needs-scoring-run [<item ID>...] | record-ruling <votes file> | record-scoring <scores file> [<item ID>...] | places | agreement"
|
||||
|
||||
|
||||
def main(argv: list[str]) -> int:
|
||||
@@ -112,7 +122,9 @@ def main(argv: list[str]) -> int:
|
||||
print(__doc__.strip().format(cap=CAP, floor=FLOOR, pairs=MIN_PAIRS))
|
||||
return 0
|
||||
command, *given = argv or [""]
|
||||
if command == "ruling-base" and not given:
|
||||
if command == "review-folder" and not given:
|
||||
done = make_review_folder()
|
||||
elif command == "ruling-base" and not given:
|
||||
done = with_default_branch(show_ruling_base, stale_ok=False)
|
||||
elif command == "round-count" and not given:
|
||||
done = with_default_branch(round_count, stale_ok=True)
|
||||
@@ -152,6 +164,22 @@ def with_default_branch(command: typing.Callable[[str], Failure | None], stale_o
|
||||
return command(branch)
|
||||
|
||||
|
||||
def make_review_folder() -> Failure | None:
|
||||
worktree = top()
|
||||
if isinstance(worktree, Failure):
|
||||
return worktree
|
||||
home = pathlib.Path.home()
|
||||
folder = pathlib.Path(review_folder(str(home), worktree))
|
||||
try:
|
||||
(home / REPORTS).mkdir(parents=True, exist_ok=True)
|
||||
(home / REPORTS).chmod(0o700)
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
except OSError as failure:
|
||||
return Failure(f"could not make the review folder {folder}: {failure}")
|
||||
print(folder)
|
||||
return None
|
||||
|
||||
|
||||
def show_ruling_base(default: str) -> Failure | None:
|
||||
changes = history_changes(default)
|
||||
if isinstance(changes, Failure):
|
||||
|
||||
+16
-13
@@ -1,15 +1,15 @@
|
||||
import pathlib
|
||||
|
||||
from larv_review.git import committed_since_release
|
||||
from failure import Failure
|
||||
from git_repo import file_at, top
|
||||
from todo_table import Item, items
|
||||
from larv_review.git import landed_since_release
|
||||
from todo_table import Item, items, renames, version
|
||||
|
||||
|
||||
def scoring_run_due(before: list[Item], after: list[Item], ships: list[int], landed: bool) -> list[str] | Failure:
|
||||
"""Why the plan calls a scoring run, empty when it does not. before is the default branch's plan, after the chunk's, ships the IDs it ships, and landed whether the default branch holds a commit after its newest release tag.
|
||||
def scoring_run_due(before: list[Item], after: list[Item], ships: list[int], landed: bool, renamed: set[tuple[int, int, int]]) -> list[str] | Failure:
|
||||
"""Why the plan calls a scoring run, empty when it does not. before is the default branch's plan, after the chunk's, ships the IDs it ships, landed whether the default branch holds a commit after its newest release tag, and renamed the releases the chunk's plan marks renamed.
|
||||
|
||||
A chunk that ships an item naming the floor is due one, so it can prove the floor met. So is a chunk that empties a release after work has landed towards it, so no release ends unmeasured. Work has landed when the chunk ships one of the release's items, or when the release is the earliest one `before` names and `landed` holds. That covers a release whose last item moved to another release.
|
||||
A chunk that ships an item naming the floor is due one, so it can prove the floor met. So is a chunk that empties a release after work has landed towards it, so no release ends unmeasured, short of one renamed as below. Work has landed when the chunk ships one of the release's items, or when the release is the earliest one `before` names and `landed` holds. A release the chunk's plan marks renamed is due none.
|
||||
"""
|
||||
plan = {item.id: item for item in before + after}
|
||||
if unknown := sorted(set(ships) - set(plan)):
|
||||
@@ -17,18 +17,18 @@ def scoring_run_due(before: list[Item], after: list[Item], ships: list[int], lan
|
||||
shipped = [plan[id_] for id_ in ships]
|
||||
reasons = [f"ships item {item.id}, which names the comprehension floor" for item in shipped if "comprehension floor" in item.tagline.lower()]
|
||||
next_release = min((item.release for item in before), default=None)
|
||||
for release in emptied(before, after, shipped):
|
||||
for release in emptied(before, after, shipped, renamed):
|
||||
if any(item.release == release for item in shipped) or (release == next_release and landed):
|
||||
# SKILL.md → "Second run" keys on this wording.
|
||||
reasons.append(f"leaves release {'.'.join(map(str, release))} with no plan item")
|
||||
reasons.append(f"leaves release {version(release)} with no plan item")
|
||||
return reasons
|
||||
|
||||
|
||||
def emptied(before: list[Item], after: list[Item], shipped: list[Item]) -> list[tuple[int, int, int]]:
|
||||
"""Each release the default branch's plan or a shipped item names that the chunk's plan, less the shipped items, names no longer."""
|
||||
def emptied(before: list[Item], after: list[Item], shipped: list[Item], renamed: set[tuple[int, int, int]]) -> list[tuple[int, int, int]]:
|
||||
"""Each release the default branch's plan or a shipped item names that the chunk's plan, less the shipped items, names no longer, unless the chunk's plan marks it renamed."""
|
||||
named = {item.release for item in before + shipped}
|
||||
left = {item.release for item in after if item.id not in {ship.id for ship in shipped}}
|
||||
return sorted(named - left)
|
||||
kept = [item for item in after if item.id not in {ship.id for ship in shipped}]
|
||||
return sorted(named - {item.release for item in kept} - renamed)
|
||||
|
||||
|
||||
def plan_reasons(default: str, ids: list[int]) -> list[str] | Failure:
|
||||
@@ -52,7 +52,10 @@ def plan_reasons(default: str, ids: list[int]) -> list[str] | Failure:
|
||||
return Failure("the checkout's todo.md has no items table; rank_todo.py --help shows one")
|
||||
if isinstance(chunk, Failure):
|
||||
return Failure(f"the checkout's todo.md: {chunk.reason}")
|
||||
landed = landed_since_release(default)
|
||||
renamed = renames(after)
|
||||
if isinstance(renamed, Failure):
|
||||
return Failure(f"the checkout's todo.md: {renamed.reason}")
|
||||
landed = committed_since_release(default)
|
||||
if isinstance(landed, Failure):
|
||||
return landed
|
||||
return scoring_run_due(planned, chunk, ids, landed)
|
||||
return scoring_run_due(planned, chunk, ids, landed, renamed)
|
||||
|
||||
@@ -2,12 +2,13 @@ import pathlib
|
||||
import time
|
||||
|
||||
from larv_review.agreement import agreement_report
|
||||
from comprehension_history import appended, DIMENSIONS, heading, Heading, HISTORY, latest_places, recorded, ruling_entry, scoring_entry, ScoringRun, vote_text
|
||||
from comprehension_history import appended, DIMENSIONS, FLOOR, heading, Heading, HISTORY, latest_places, recorded, ruling_entry, scoring_entry, ScoringRun, vote_text
|
||||
from git_repo import commit_exists, top
|
||||
from larv_review.ruling import counted, overall, ruling, split, votes
|
||||
from failure import Failure
|
||||
from larv_review.scoring import FLOOR, means, under_floor
|
||||
from larv_review.scoring import means, under_floor
|
||||
from larv_review.plan import plan_reasons
|
||||
import rank_todo
|
||||
from file_writes import replace_file
|
||||
from larv_review.seats import scores, seats_file, SeatsFile
|
||||
|
||||
@@ -47,7 +48,23 @@ def record_scoring(default: str, scores_file: pathlib.Path, ids: list[int]) -> F
|
||||
print(f"Means: {', '.join(f'{name} {value}' for name, value in zip(DIMENSIONS, scoring.means))}.")
|
||||
if under := under_floor(scoring.means):
|
||||
print(f"Floor: {', '.join(under)} under the floor of {FLOOR}.")
|
||||
return append(given.read, scoring_entry(named.title, scoring))
|
||||
if unrecorded := append(given.read, scoring_entry(named.title, scoring)):
|
||||
return unrecorded
|
||||
return rerank()
|
||||
|
||||
|
||||
def rerank() -> Failure | None:
|
||||
"""Rank the checkout's todo.md again as rank_todo.py does, since the overall sets code health's weight, and fail where rank_todo.py would. The run stays recorded whatever happens, so those failures say to settle todo.md and run rank_todo.py on it, not to record the run again."""
|
||||
checkout = top()
|
||||
if isinstance(checkout, Failure):
|
||||
return checkout
|
||||
todo = pathlib.Path(checkout, "todo.md")
|
||||
ranked = rank_todo.rank_file(todo)
|
||||
if isinstance(ranked, Failure):
|
||||
return Failure(f"recorded the run, but rank_todo.py cannot rank {todo}: {ranked.reason}. Fix what that names, then run rank_todo.py on {todo}, not record-scoring again")
|
||||
if ranked.under_bar:
|
||||
return Failure(f"recorded the run and ranked {todo}, but the lines above name items now under the bar. Settle each as its line says, then run rank_todo.py on {todo}, not record-scoring again")
|
||||
return None
|
||||
|
||||
|
||||
def scored_seats(given: SeatsFile) -> ScoringRun | Failure:
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
import decimal
|
||||
|
||||
from comprehension_history import DIMENSIONS
|
||||
|
||||
FLOOR = decimal.Decimal("7.0")
|
||||
from comprehension_history import DIMENSIONS, FLOOR
|
||||
|
||||
|
||||
def means(lines: list[list[str]]) -> list[decimal.Decimal]:
|
||||
|
||||
@@ -161,6 +161,8 @@ class History(unittest.TestCase):
|
||||
first, rerun, other = (run.format(time=time, pr=pr, commit=commit, line=line) for time, pr, commit, line in (("2026-10-08T12:00:00Z", "PR #1", "aaaaaaa", 1), ("2026-10-08T13:00:00Z", "PR #1 rerun", "aaaaaaa", 2), ("2026-10-09T12:00:00Z", "PR #2", "bbbbbbb", 3)))
|
||||
self.assertEqual(latest_places(appended(appended("", first), rerun)), first + "\n" + rerun)
|
||||
self.assertEqual(latest_places(appended(appended(appended("", first), rerun), other)), other)
|
||||
in_full = rerun.replace("aaaaaaa", "aaaaaaa" + "0" * 33)
|
||||
self.assertEqual(latest_places(appended(appended("", first), in_full)), first + "\n" + in_full)
|
||||
|
||||
|
||||
def scored(time: str, pr: str, commit: str, mid: str, architect: str) -> str:
|
||||
@@ -263,27 +265,45 @@ class ScoringRunDue(unittest.TestCase):
|
||||
|
||||
def test_is_due_for_an_item_naming_the_floor(self):
|
||||
plan = [item(1, (0, 1, 0), "**Lift the project to the Comprehension floor.**"), item(2, (0, 1, 0))]
|
||||
self.assertEqual(scoring_run_due(plan, plan, [1], True), ["ships item 1, which names the comprehension floor"])
|
||||
self.assertIsInstance(scoring_run_due(plan, plan, [9], True), Failure)
|
||||
self.assertEqual(scoring_run_due(plan, plan, [1], True, set()), ["ships item 1, which names the comprehension floor"])
|
||||
self.assertIsInstance(scoring_run_due(plan, plan, [9], True, set()), Failure)
|
||||
|
||||
def test_is_due_when_the_chunk_ships_a_releases_last_item(self):
|
||||
plan = [item(1, (0, 1, 0)), item(2, (0, 2, 0))]
|
||||
self.assertEqual(scoring_run_due(plan, plan, [1], False), ["leaves release 0.1.0 with no plan item"])
|
||||
self.assertEqual(scoring_run_due(plan, plan + [item(3, (0, 1, 0))], [1], True), [])
|
||||
self.assertEqual(scoring_run_due(plan, plan, [1], False, set()), ["leaves release 0.1.0 with no plan item"])
|
||||
self.assertEqual(scoring_run_due(plan, plan + [item(3, (0, 1, 0))], [1], True, set()), [])
|
||||
|
||||
def test_is_due_when_the_chunk_removes_the_next_releases_last_item_after_work_landed(self):
|
||||
before = [item(1, (0, 1, 0)), item(2, (0, 1, 0)), item(3, (0, 2, 0))]
|
||||
after = [item(2, (0, 1, 0)), item(3, (0, 2, 0))]
|
||||
self.assertEqual(scoring_run_due(before, after, [2], True), ["leaves release 0.1.0 with no plan item"])
|
||||
self.assertEqual(scoring_run_due(before, after, [], True), [])
|
||||
self.assertEqual(scoring_run_due(before, after, [2], True, set()), ["leaves release 0.1.0 with no plan item"])
|
||||
self.assertEqual(scoring_run_due(before, after, [], True, set()), [])
|
||||
emptied = [item(3, (0, 2, 0))]
|
||||
self.assertEqual(scoring_run_due(before, emptied, [2], False), ["leaves release 0.1.0 with no plan item"])
|
||||
self.assertEqual(scoring_run_due(before, emptied, [], True), ["leaves release 0.1.0 with no plan item"])
|
||||
self.assertEqual(scoring_run_due(before, emptied, [], False), [])
|
||||
self.assertEqual(scoring_run_due(before, emptied, [2], False, set()), ["leaves release 0.1.0 with no plan item"])
|
||||
self.assertEqual(scoring_run_due(before, emptied, [], True, set()), ["leaves release 0.1.0 with no plan item"])
|
||||
self.assertEqual(scoring_run_due(before, emptied, [], False, set()), [])
|
||||
|
||||
def test_is_not_due_when_the_chunk_marks_the_next_release_renamed(self):
|
||||
before = [item(1, (0, 2, 1)), item(2, (0, 3, 0))]
|
||||
renamed = {(0, 2, 1)}
|
||||
self.assertEqual(scoring_run_due(before, [item(1, (0, 3, 0)), item(2, (0, 4, 0))], [], True, renamed), [])
|
||||
self.assertEqual(scoring_run_due(before, [item(1, (0, 3, 0)), item(2, (0, 3, 0))], [], True, renamed), [])
|
||||
dropped = [item(1, (0, 2, 1)), item(3, (0, 2, 1)), item(2, (0, 3, 0))]
|
||||
self.assertEqual(scoring_run_due(dropped, [item(1, (0, 3, 0)), item(2, (0, 3, 0))], [], True, renamed), [])
|
||||
|
||||
def test_is_due_when_the_chunk_defers_the_next_releases_last_items_unmarked(self):
|
||||
before = [item(1, (0, 2, 1)), item(2, (0, 3, 0))]
|
||||
self.assertEqual(scoring_run_due(before, [item(1, (0, 3, 0)), item(2, (0, 3, 0))], [], True, set()), ["leaves release 0.2.1 with no plan item"])
|
||||
|
||||
def test_words_the_emptied_release_reason_as_skill_md_s_second_run_quotes_it(self):
|
||||
skill = (pathlib.Path(__file__).resolve().parents[2] / "skills" / "larv-review" / "SKILL.md").read_text()
|
||||
self.assertIn("`leaves release … with no plan item`", skill)
|
||||
reasons = scoring_run_due([item(1, (0, 1, 0))], [], [], True, set())
|
||||
self.assertRegex(reasons[0], r"^leaves release [0-9.]+ with no plan item$")
|
||||
|
||||
def test_is_not_due_when_a_later_release_loses_its_last_item_unshipped(self):
|
||||
before = [item(1, (0, 1, 0)), item(3, (0, 2, 0))]
|
||||
self.assertEqual(scoring_run_due(before, before[:1], [], True), [])
|
||||
self.assertEqual(scoring_run_due(before, before[:1], [], True, set()), [])
|
||||
|
||||
|
||||
class LarvReviewTool(unittest.TestCase):
|
||||
@@ -352,6 +372,19 @@ class LarvReviewTool(unittest.TestCase):
|
||||
self.assertEqual(self.run_tool("needs-scoring-run").stdout, "No scoring run due.\n")
|
||||
self.assertIn("todo.md's ID column", self.run_tool("needs-scoring-run", "item-85").stderr)
|
||||
|
||||
def test_calls_a_scoring_run_for_a_deferred_release_and_none_for_one_the_checkouts_plan_marks_renamed(self):
|
||||
rows = ("| 1 | 0.2.0 | | **Do it.** | 1 | 1 | 3 | 1 | 1 | 1 | 9.0 |", "| 2 | 0.2.0 | | **Then this.** | 1 | 1 | 3 | 1 | 1 | 1 | 9.0 |", "| 3 | 0.2.0 | | **And this.** | 1 | 1 | 3 | 1 | 1 | 1 | 9.0 |")
|
||||
self.commit("Move 0.1.0's item to 0.2.0", {"todo.md": todo(*rows)})
|
||||
self.assertEqual(self.run_tool("needs-scoring-run").stdout, "Scoring run due: the chunk leaves release 0.1.0 with no plan item.\n")
|
||||
self.commit("Mark 0.1.0 renamed", {"todo.md": todo(*rows) + "\n## Renamed\n\n- 0.1.0 renamed to 0.2.0\n"})
|
||||
self.assertEqual(self.run_tool("needs-scoring-run").stdout, "No scoring run due.\n")
|
||||
|
||||
def test_refuses_a_checkout_plan_whose_renamed_section_does_not_parse(self):
|
||||
self.commit("Break the mark", {"todo.md": todo("| 1 | 0.2.0 | | **Do it.** | 1 | 1 | 3 | 1 | 1 | 1 | 9.0 |") + "\n## Renamed\n\nsoon\n"})
|
||||
broken = self.run_tool("needs-scoring-run")
|
||||
self.assertEqual(broken.returncode, 1)
|
||||
self.assertIn("## Renamed", broken.stderr)
|
||||
|
||||
def test_reads_a_default_branch_plan_without_a_table_as_empty_and_refuses_a_checkout_without_one(self):
|
||||
self.git("switch", "-q", "-c", "reshape", "main")
|
||||
self.commit("Plan as a list", {"todo.md": "# todo\n\n- [ ] Do it.\n"})
|
||||
@@ -407,6 +440,7 @@ class LarvReviewTool(unittest.TestCase):
|
||||
uncalled = self.run_tool("record-scoring", self.seats_file(f"PR #2 at {self.start}\n" + seats))
|
||||
self.assertEqual(uncalled.returncode, 1)
|
||||
self.assertIn("no plan item or release calls this scoring run", uncalled.stderr)
|
||||
self.plan()
|
||||
ran = self.run_tool("record-scoring", self.seats_file(f"PR #2 at {self.start}\n" + seats), "1")
|
||||
self.assertEqual(ran.returncode, 0, ran.stderr)
|
||||
self.assertIn("\nFloor: Locality 6.50, Self-sufficiency 6.50 under the floor of 7.0.\n", ran.stdout)
|
||||
@@ -416,6 +450,54 @@ class LarvReviewTool(unittest.TestCase):
|
||||
self.assertIn("Inherited architect, would restructure first:", text)
|
||||
self.assertEqual(entries(text)[0].scored_places, [Place("bin/a.py", "f")] * 4)
|
||||
|
||||
def plan(self, readme="# P\n\n## Goals\n\n1. **Achieve:** A.\n", bar="0.1"):
|
||||
"""Commit and push the README.md and a todo.md whose item 1, alone in release 0.1.0, moves code health, each item scored as before any scoring run."""
|
||||
header = "| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |\n|---|---|---|---|---|---|---|---|---|---|---|---|\n"
|
||||
# Before any scoring run code health weighs four times its weight at an overall of 7.0: 4 / 1.97 against goal 1's 0.97 / 1.97.
|
||||
rows = "| 1 | 0.1.0 | | | **Read easier.** | 1 | 1 | 1 | 1 | 1 | code health by 1 | 101.5 |\n| 2 | 0.2.0 | | | **Do A.** | 1 | 1 | 1 | 1 | 1 | 1 by 3 | 73.9 |\n"
|
||||
self.commit("Plan", {"README.md": readme, "todo.md": f"# todo\n\n## Scoring\n\n`Score = 100 * V / 2**S`\n\n`Bar = {bar}`\n\n`Next ID = 3`\n\n## Items\n\n" + header + rows})
|
||||
self.git("push", "-q", "origin", "HEAD:main")
|
||||
|
||||
def record_sevens(self):
|
||||
"""Run record-scoring for item 1 on a scores file in which every seat scores 7 throughout."""
|
||||
line = "Navigation 7, Locality 7, Shape 7, Self-sufficiency 7, Overall 7"
|
||||
seats = "".join(f"\n{seat}: {line}\n" for seat in ("Junior A", "Mid A", "Maintainability senior", "Inherited architect"))
|
||||
return self.run_tool("record-scoring", self.seats_file(f"PR #2 at {self.start}\n" + seats), "1")
|
||||
|
||||
def test_reports_a_plan_it_cannot_read_yet_keeps_the_run(self):
|
||||
# This checkout has no README.md beside its todo.md.
|
||||
ran = self.record_sevens()
|
||||
self.assertEqual(ran.returncode, 1)
|
||||
self.assertIn(f"recorded the run, but rank_todo.py cannot rank {self.checkout / 'todo.md'}: {self.checkout / 'README.md'}: not found", ran.stderr)
|
||||
self.assertIn("not record-scoring again", ran.stderr)
|
||||
self.assertEqual(len(entries((self.checkout / "docs" / "comprehension-history.md").read_text())), 1)
|
||||
|
||||
def test_reports_a_plan_it_reads_but_cannot_rank_yet_keeps_the_run(self):
|
||||
self.plan(readme="# P\n\n## Goals\n\n**Void:** code health, since it is a probe.\n\n1. **Achieve:** A.\n")
|
||||
ran = self.record_sevens()
|
||||
self.assertEqual(ran.returncode, 1)
|
||||
self.assertIn(f"recorded the run, but rank_todo.py cannot rank {self.checkout / 'todo.md'}: item 1 names code health, which README.md voids", ran.stderr)
|
||||
self.assertIn("not record-scoring again", ran.stderr)
|
||||
self.assertEqual(len(entries((self.checkout / "docs" / "comprehension-history.md").read_text())), 1)
|
||||
|
||||
def test_reranks_todo_md_by_the_overall_it_records(self):
|
||||
self.plan()
|
||||
ran = self.record_sevens()
|
||||
self.assertEqual(ran.returncode, 0, ran.stderr)
|
||||
self.assertIn("| code health by 1 | 25.4 |", (self.checkout / "todo.md").read_text())
|
||||
|
||||
def test_fails_once_its_re_rank_leaves_an_item_under_the_bar_yet_keeps_the_run(self):
|
||||
self.plan(bar="30")
|
||||
ran = self.record_sevens()
|
||||
self.assertEqual(ran.returncode, 1)
|
||||
todo = self.checkout / "todo.md"
|
||||
# At an overall of 7.0 item 1 falls from 101.5 to 25.4.
|
||||
self.assertIn(f"{todo}: item 1 scores 25.4, under the bar 30; delete it, or mark it with a reason the bar does not apply\n", ran.stderr)
|
||||
self.assertIn("recorded the run", ran.stderr)
|
||||
self.assertIn("not record-scoring again", ran.stderr)
|
||||
self.assertIn("| code health by 1 | 25.4 |", todo.read_text())
|
||||
self.assertEqual(len(entries((self.checkout / "docs" / "comprehension-history.md").read_text())), 1)
|
||||
|
||||
def test_prints_the_places_seats_found_hard_since_the_newest_scoring_run(self):
|
||||
self.assertEqual(self.run_tool("places").stdout, "Seats found no places hard.\n")
|
||||
self.commit("Record a scoring run", {"docs/comprehension-history.md": appended("", SCORING + "\nJunior A, hardest first:\n\n- `bin/b.py:4` `h`: long\n")})
|
||||
@@ -447,6 +529,34 @@ class LarvReviewTool(unittest.TestCase):
|
||||
self.git("remote", "set-head", "origin", "--delete")
|
||||
self.assertEqual(self.run_tool("needs-scoring-run", "2").stdout, "No scoring run due.\n")
|
||||
|
||||
def test_makes_and_prints_the_worktrees_review_folder_from_anywhere_in_it(self):
|
||||
reports = self.checkout.parent / ".local" / "state" / "larv-review"
|
||||
(self.checkout / "sub").mkdir()
|
||||
ran = subprocess.run([sys.executable, str(TOOL), "review-folder"], capture_output=True, cwd=self.checkout / "sub", env=self.env, text=True)
|
||||
self.assertEqual((ran.returncode, ran.stdout), (0, f"{reports}/proj\n"), ran.stderr)
|
||||
self.assertTrue((reports / "proj").is_dir())
|
||||
|
||||
def test_leaves_the_reports_folder_readable_by_the_user_alone_where_it_was_not(self):
|
||||
reports = self.checkout.parent / ".local" / "state" / "larv-review"
|
||||
reports.mkdir(parents=True, mode=0o755)
|
||||
self.assertEqual(self.run_tool("review-folder").returncode, 0)
|
||||
self.assertEqual(reports.stat().st_mode & 0o777, 0o700)
|
||||
|
||||
def test_fails_where_it_cannot_make_the_review_folder(self):
|
||||
(self.checkout.parent / ".local" / "state").mkdir(parents=True)
|
||||
(self.checkout.parent / ".local" / "state" / "larv-review").write_text("")
|
||||
ran = self.run_tool("review-folder")
|
||||
self.assertEqual(ran.returncode, 1)
|
||||
self.assertIn("could not make the review folder", ran.stderr)
|
||||
|
||||
def test_review_folder_fails_outside_a_checkout(self):
|
||||
ran = subprocess.run([sys.executable, str(TOOL), "review-folder"], capture_output=True, cwd=self.checkout.parent, env=self.env, text=True)
|
||||
self.assertEqual(ran.returncode, 1)
|
||||
self.assertNotIn("Traceback", ran.stderr)
|
||||
|
||||
def test_review_folder_takes_no_arguments(self):
|
||||
self.assertIn("unknown arguments", self.run_tool("review-folder", "x").stderr)
|
||||
|
||||
def test_takes_a_local_main_without_origin_and_reads_origin_as_last_fetched_when_the_fetch_fails(self):
|
||||
self.commit("Answer prose round 1: a")
|
||||
self.git("remote", "set-url", "origin", str(self.checkout.parent / "gone.git"))
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import dataclasses
|
||||
import sys
|
||||
import uuid
|
||||
|
||||
@@ -11,12 +12,37 @@ from claude_code.trust import trust
|
||||
from loop_claude.project.checkout import worktrees
|
||||
|
||||
ANSWER_QUESTION = "answer the question above"
|
||||
# TALK and ASK_ANSWER were picked on 2026-10-17 by a bench of three readers seated as the README's audience, as ~/.claude/CLAUDE.md → "Working loop" → "Bench a syntax with the people who write it." has it.
|
||||
TALK = "/talk"
|
||||
ASK_ANSWER = f"Answer ({TALK} opens claude, Enter stops the loop): "
|
||||
|
||||
|
||||
def interrupt(root: str, session_id: uuid.UUID, worker: Rung, path: str, question: str, paths: Paths, env: dict[str, str], effects: Effects) -> Stop | None:
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Talk:
|
||||
"""The human answers in the worker's claude session, which talk opens."""
|
||||
|
||||
|
||||
def put_question(question: str, answer_here: bool, effects: Effects) -> str | Talk | Stop:
|
||||
"""Prints question for the human. Where answer_here, returns the line they type at loop-claude's terminal, stripped, or Talk where they type TALK; else Talk at once. A Stop where loop-claude is off a terminal, or they type nothing, or the input ends."""
|
||||
print(f"\n{question}", file=sys.stderr)
|
||||
if stop := needs_terminal(ANSWER_QUESTION, effects.on_terminal()):
|
||||
return stop
|
||||
# Keys typed while the worker ran wait on the terminal, and would answer a question no one has read, here or in claude's session, which reads them too. Of a pasted answer, input takes the first line; the rest wait, and the next question drops them. A longer answer goes through TALK.
|
||||
effects.discard_typed()
|
||||
if not answer_here:
|
||||
return Talk()
|
||||
try:
|
||||
answer = effects.input(ASK_ANSWER).strip()
|
||||
except EOFError:
|
||||
print(file=sys.stderr)
|
||||
return needs_human(ANSWER_QUESTION, "the input ended")
|
||||
if not answer:
|
||||
return needs_human(ANSWER_QUESTION, "nothing was typed")
|
||||
return Talk() if answer == TALK else answer
|
||||
|
||||
|
||||
def talk(root: str, session_id: uuid.UUID, worker: Rung, path: str, paths: Paths, env: dict[str, str], effects: Effects) -> Stop | None:
|
||||
"""Resumes the worker's session in claude on the terminal; the human must type something there."""
|
||||
entries = read_transcript(path)
|
||||
if isinstance(entries, Failure):
|
||||
return Stop(1, entries.reason)
|
||||
|
||||
@@ -3,14 +3,16 @@ import json
|
||||
import re
|
||||
import typing
|
||||
|
||||
from loop_claude.cycle.prompts import ANSWER_DESTINATIONS, ANSWERS_RECORDED
|
||||
from loop_claude.cycle.prompts import ANSWER_DESTINATIONS, ANSWERS_RECORDED, typed_answer
|
||||
from claude_code.reply import claude_reply, Limited
|
||||
from loop_claude.effects import Effects
|
||||
from failure import Failure
|
||||
from loop_claude.project.records import HUMAN_RULE_NAMES
|
||||
from claude_code.entries import human_text, loop_text
|
||||
from todo_table import LEVELS
|
||||
from markdown_text import listed
|
||||
from model_routing.route import on_its_scale
|
||||
from claude_code.transcript import render
|
||||
from loop_claude.cycle.retry import retried
|
||||
from model_routing.ladder import Rung
|
||||
from loop_claude.stop import Stop
|
||||
@@ -18,7 +20,7 @@ from claude_code.entries import structured_output
|
||||
|
||||
# At 3 to 4 characters a token, 100,000 to 133,000 tokens, which leaves a 200,000-token context room for the reply; the largest session rendered here was 364,000 characters on 2026-10-03.
|
||||
JUDGE_PROMPT_CHARS = 400000
|
||||
JUDGE_RULES = (
|
||||
INTERRUPT_RULES = (
|
||||
"Decide whether the human must now be interrupted. interrupt=true when any of these appear:\n"
|
||||
"- the agent asks the human anything, seeks approval, or says a decision is the human's, and neither "
|
||||
"README.md nor the records settle the matter\n"
|
||||
@@ -37,11 +39,15 @@ JUDGE_RULES = (
|
||||
"is still open, never a question they already answered there. A [loop] line is what loop-claude told "
|
||||
"the agent, such as an answer quoted from README.md or the records.\n\n"
|
||||
"Where the agent asked or flagged something itself, the question is that one, in the agent's own "
|
||||
"wording; never construct another from facts it stated.\n\n"
|
||||
"wording; never construct another from facts it stated."
|
||||
)
|
||||
QUOTE_RULES = (
|
||||
"Where README.md or the records answer the agent's own question and no [loop] line has "
|
||||
"quoted that answer yet, set interrupt=false and quote the passage that answers it; the agent is "
|
||||
"then given that passage in place of the human's reply. An interrupt outranks a quoted answer, and either "
|
||||
"outranks finished.\n\n"
|
||||
"outranks finished."
|
||||
)
|
||||
FINISHED_RULES = (
|
||||
"The chunk is the piece of work the agent is on, shipped as one pull request. "
|
||||
"finished=true when the chunk is complete: merged, or nothing remains that the agent could do on "
|
||||
f"its own. Even then, it is finished only once {ANSWERS_RECORDED}. An answer counts as recorded "
|
||||
@@ -50,6 +56,9 @@ JUDGE_RULES = (
|
||||
f"{listed(HUMAN_RULE_NAMES, 'or')} does not count. finished=false when work remains that a further run can "
|
||||
"continue: an open PR, a review not yet run, CI not yet reported, an answer not yet recorded."
|
||||
)
|
||||
JUDGE_RULES = "\n\n".join((INTERRUPT_RULES, QUOTE_RULES, FINISHED_RULES))
|
||||
# The line judge_prompt shows the judge where an escalation last stepped the worker up, which Reply.escalation's description points at. Only the judge reads it, so it is no [loop] line.
|
||||
STEP_LINE = "[step] loop-claude stepped the agent up a rung here, so the escalation triggers that fired before this line are spent."
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
@@ -59,12 +68,14 @@ class Reply:
|
||||
bundled: int = dataclasses.field(metadata={"description": "The highest L the agent states for a todo.md item it took into this chunk; 0 when it states none."})
|
||||
# Routes the next cycle's judge and reviewers, as bundled routes the worker.
|
||||
bundled_escape_and_impact: int = dataclasses.field(metadata={"description": "The highest E + I the agent states for a todo.md item it took into this chunk; 0 when it states none."})
|
||||
# Routes the next cycle's worker one rung up: docs/decisions.md → `routing: a worker whose run ends asking for a higher rung`.
|
||||
escalation: str = dataclasses.field(metadata={"description": "Empty unless the chunk is unfinished and the agent's run ends asking loop-claude for a higher rung, citing an escalation trigger. Then: a verbatim quote, without elisions, of an earlier transcript passage showing the trigger fired after any earlier such request, such as a review round's commit title or the agent's report of the finding or failing test. Never the request itself."})
|
||||
# Routes the worker one rung up, as the judge interrupts or quotes an answer, or on the next cycle: docs/decisions.md → `routing: a worker whose run ends asking for a higher rung`.
|
||||
escalation: str = dataclasses.field(metadata={"description": "Empty unless the chunk is unfinished, interrupt is true or answer quotes a passage, and the agent's run ends asking loop-claude for a higher rung, citing an escalation trigger. Then: a verbatim quote, without elisions, of the transcript passage where the trigger fired, such as a review round's commit title or the agent's report of the finding or failing test. Where a [step] line says loop-claude stepped the agent up a rung, quote only the agent's own words after it, and leave this empty where the trigger fired only before it. Never a later mention of the trigger, and never the request itself."})
|
||||
evidence: str = dataclasses.field(metadata={"description": "A verbatim quote of the one transcript passage the verdict rests on, without elisions: what triggers the interrupt; for a quoted answer, the agent's question; else what shows the chunk finished or the work remaining."})
|
||||
finished: bool = dataclasses.field(metadata={"description": "Whether the chunk is finished."})
|
||||
interrupt: bool = dataclasses.field(metadata={"description": "Whether the human must now be interrupted."})
|
||||
question: str = dataclasses.field(metadata={"description": "With interrupt true, the single question to put to the human. With a quoted answer, the agent's question that the answer field answers. Empty otherwise."})
|
||||
# True opens claude's session at once, in place of the one-line answer (run.ask). The judge decides it, since loop-claude computes the plan's standing (chunk_pick.chunk_item) only when it routes a chunk on the ladder afresh: it would miss a release ready to cut in a resumed chunk or off the ladder. A wrong ruling costs the human one typed /talk, or answering in claude, which stops the loop if they leave it with nothing typed.
|
||||
release_ready: bool = dataclasses.field(metadata={"description": "With interrupt true, whether the question is about a release ready to cut, which only the human may publish. False otherwise."})
|
||||
|
||||
|
||||
REPLY_TYPES = typing.get_type_hints(Reply)
|
||||
@@ -87,6 +98,13 @@ class Rejected(Failure):
|
||||
class Interrupt:
|
||||
evidence: str
|
||||
question: str
|
||||
# The judge's quote showing that the worker's cited escalation trigger fired; empty for none.
|
||||
escalation: str = ""
|
||||
# The bundled L the judge saw, 0 for none, as on Unfinished: an escalation steps up from the rung that item picks.
|
||||
bundled: int = 0
|
||||
release_ready: bool = False
|
||||
# How many transcript entries the judge read, which judge_once stamps. An escalation the verdict carries moves the route's mark there; one on a verdict never stamped, None, steps nothing.
|
||||
entries_read: int | None = None
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
@@ -95,6 +113,10 @@ class QuotedAnswer:
|
||||
evidence: str
|
||||
question: str
|
||||
answer: str
|
||||
# As on Interrupt.
|
||||
escalation: str = ""
|
||||
bundled: int = 0
|
||||
entries_read: int | None = None
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
@@ -111,11 +133,28 @@ class Unfinished:
|
||||
escalation: str = ""
|
||||
# The bundled E + I the judge saw, 0 for none.
|
||||
bundled_escape_and_impact: int = 0
|
||||
# As on Interrupt.
|
||||
entries_read: int | None = None
|
||||
|
||||
|
||||
Verdict = Interrupt | QuotedAnswer | Finished | Unfinished
|
||||
|
||||
|
||||
class Grounds(typing.NamedTuple):
|
||||
"""What run_judge checks the judge's quotes against, word for word, since stitched fragments can say what their source does not."""
|
||||
# The transcript as the judge saw it. The evidence must quote it, its fragments in order: a misquote is Rejected, which judge retries.
|
||||
shown: str
|
||||
# The agent's own lines after the mark, all of them before any step-up. loop-claude's prompts and the human's lines are left out, since they repeat earlier passages, such as the judge's evidence or the agent's question. An escalation must quote both this and shown: a misquote, or a quote of a passage before the mark, drops the escalation, so the worker's rung holds.
|
||||
since_step: str
|
||||
# README.md's premises and the records. A quoted answer must quote them: a misquote puts the question to the human.
|
||||
quotable: str
|
||||
|
||||
|
||||
def escalation_mark(verdict: Interrupt | QuotedAnswer | Unfinished) -> int | None:
|
||||
"""Where the verdict's escalation would move the route's mark, if it steps the worker; None where it carries none."""
|
||||
return verdict.entries_read if verdict.escalation else None
|
||||
|
||||
|
||||
def verdict_from(output: object) -> Verdict | Failure:
|
||||
if not isinstance(output, dict):
|
||||
return Failure("the judge returned no reply")
|
||||
@@ -123,30 +162,31 @@ def verdict_from(output: object) -> Verdict | Failure:
|
||||
# type(), not isinstance(): JSON true is no integer.
|
||||
if type(output.get(name)) is not kind:
|
||||
return Failure(f"the judge's reply has no {name} of type {JSON_TYPES[kind]}")
|
||||
# A bundled level off its scale counts as none: holding the rung is safe, and three failures would stop an unattended loop.
|
||||
bundled = output["bundled"] if 0 <= output["bundled"] <= HIGHEST_L else 0
|
||||
if output["interrupt"]:
|
||||
if not output["question"].strip():
|
||||
return Failure("the judge interrupted without a question")
|
||||
return Interrupt(output["evidence"], output["question"])
|
||||
return Interrupt(output["evidence"], output["question"], output["escalation"], bundled, output["release_ready"])
|
||||
if output["answer"].strip():
|
||||
if not output["question"].strip():
|
||||
return Failure("the judge quoted an answer without a question")
|
||||
return QuotedAnswer(output["evidence"], output["question"], output["answer"])
|
||||
return QuotedAnswer(output["evidence"], output["question"], output["answer"], output["escalation"], bundled)
|
||||
if output["finished"]:
|
||||
return Finished(output["evidence"])
|
||||
# A bundled level off its scale counts as none: holding the rung is safe, and three failures would stop an unattended loop.
|
||||
bundled = output["bundled"] if 0 <= output["bundled"] <= HIGHEST_L else 0
|
||||
bundled_escape_and_impact = output["bundled_escape_and_impact"] if on_its_scale(output["bundled_escape_and_impact"]) else 0
|
||||
return Unfinished(output["evidence"], bundled, output["escalation"], bundled_escape_and_impact)
|
||||
|
||||
|
||||
def judge(root: str, task: str, premises: str, records: str, rendered_transcript: str, rung: Rung, effects: Effects, keep: typing.Callable[[Rejected], Stop | None]) -> Verdict | Stop:
|
||||
return retried("judge", lambda: judge_once(root, task, premises, records, rendered_transcript, rung, effects), effects, lambda failure: keep(failure) if isinstance(failure, Rejected) else None)
|
||||
def judge(root: str, task: str, premises: str, records: str, entries: list[dict], escalated_at: int, rung: Rung, effects: Effects, keep: typing.Callable[[Rejected], Stop | None]) -> Verdict | Stop:
|
||||
return retried("judge", lambda: judge_once(root, task, premises, records, entries, escalated_at, rung, effects), effects, lambda failure: keep(failure) if isinstance(failure, Rejected) else None)
|
||||
|
||||
|
||||
def judge_once(root: str, task: str, premises: str, records: str, rendered_transcript: str, rung: Rung, effects: Effects) -> Verdict | Failure | Limited:
|
||||
"""One judge run, as judge retries it; judge-replay replays it."""
|
||||
prompt, shown = judge_prompt(task, premises, records, rendered_transcript)
|
||||
return run_judge(root, judge_args(rung), prompt, shown, f"{premises}\n\n{records}", effects)
|
||||
def judge_once(root: str, task: str, premises: str, records: str, entries: list[dict], escalated_at: int, rung: Rung, effects: Effects) -> Verdict | Failure | Limited:
|
||||
"""One judge run on the transcript's entries, as judge retries it; judge-replay replays it. escalated_at is the route's mark: an escalation quote counts only from the entries after it."""
|
||||
prompt, grounds = judge_prompt(task, premises, records, entries, escalated_at)
|
||||
verdict = run_judge(root, judge_args(rung), prompt, grounds, effects)
|
||||
return dataclasses.replace(verdict, entries_read=len(entries)) if isinstance(verdict, Interrupt | QuotedAnswer | Unfinished) else verdict
|
||||
|
||||
|
||||
def judge_args(rung: Rung) -> list[str]:
|
||||
@@ -159,13 +199,8 @@ def judge_args(rung: Rung) -> list[str]:
|
||||
]
|
||||
|
||||
|
||||
def run_judge(root: str, args: list[str], prompt: str, shown: str, quotable: str, effects: Effects) -> Verdict | Failure | Limited:
|
||||
"""One judge run, its three quotes each checked against what they quote:
|
||||
- evidence, against shown, its fragments in order: a misquote is a Failure, which judge retries;
|
||||
- a quoted answer, against quotable, word for word: a misquote puts the question to the human;
|
||||
- an escalation, against shown, word for word: a misquote drops it, so the worker's rung holds.
|
||||
A misquoted answer or escalation is no Failure, which would otherwise exit an unattended loop. Neither may be elided, since stitched fragments can say what the records or the transcript do not.
|
||||
"""
|
||||
def run_judge(root: str, args: list[str], prompt: str, grounds: Grounds, effects: Effects) -> Verdict | Failure | Limited:
|
||||
"""One judge run, each quote in its verdict checked against grounds as Grounds says. quotes_checked checks the quoted answer and the escalation: neither misquote is a Failure, which would otherwise exit an unattended loop."""
|
||||
reply = claude_reply(effects.claude, args, root, prompt, "the judge")
|
||||
if isinstance(reply, Failure | Limited):
|
||||
return reply
|
||||
@@ -173,17 +208,24 @@ def run_judge(root: str, args: list[str], prompt: str, shown: str, quotable: str
|
||||
replied = json.dumps(reply, ensure_ascii=False)
|
||||
if isinstance(verdict, Failure):
|
||||
return Rejected(verdict.reason, replied)
|
||||
if not grounded(verdict.evidence, shown):
|
||||
if not grounded(verdict.evidence, grounds.shown):
|
||||
return Rejected(f"the judge quoted {verdict.evidence!r}, which is not in the transcript" + (f", for the question: {verdict.question}" if isinstance(verdict, Interrupt | QuotedAnswer) else ""), replied)
|
||||
if isinstance(verdict, QuotedAnswer) and not verbatim(verdict.answer, quotable):
|
||||
return Interrupt(verdict.evidence, verdict.question)
|
||||
if isinstance(verdict, Unfinished) and verdict.escalation and not verbatim(verdict.escalation, shown):
|
||||
return quotes_checked(verdict, grounds)
|
||||
|
||||
|
||||
def quotes_checked(verdict: Verdict, grounds: Grounds) -> Verdict:
|
||||
"""The verdict with its quoted answer and its escalation checked, as Grounds says; a quoted answer put to the human keeps the escalation it carried."""
|
||||
if isinstance(verdict, QuotedAnswer) and not verbatim(verdict.answer, grounds.quotable):
|
||||
verdict = Interrupt(verdict.evidence, verdict.question, verdict.escalation, verdict.bundled)
|
||||
if isinstance(verdict, Interrupt | QuotedAnswer | Unfinished) and verdict.escalation and not (verbatim(verdict.escalation, grounds.since_step) and verbatim(verdict.escalation, grounds.shown)):
|
||||
return dataclasses.replace(verdict, escalation="")
|
||||
return verdict
|
||||
|
||||
|
||||
def judge_prompt(task: str, premises: str, records: str, rendered_transcript: str) -> tuple[str, str]:
|
||||
"""The prompt, and the part of the transcript it shows, which the judge's evidence must quote."""
|
||||
def judge_prompt(task: str, premises: str, records: str, entries: list[dict], escalated_at: int) -> tuple[str, Grounds]:
|
||||
"""The prompt, and what the judge's quotes are checked against. Where escalated_at, the route's mark, is above 0, the prompt shows STEP_LINE after that many entries."""
|
||||
transcript = "\n\n".join(part for part in (render(entries[:escalated_at], typed_answer), STEP_LINE if escalated_at else "", render(entries[escalated_at:], typed_answer)) if part)
|
||||
agents_own = [entry for entry in entries[escalated_at:] if human_text(entry) is None and loop_text(entry) is None]
|
||||
head = (
|
||||
f"From README.md:\n{premises}\n\n"
|
||||
f"The records: the project's working rules and decisions, then the human's rules for every project:\n{records or 'none'}\n\n"
|
||||
@@ -192,8 +234,8 @@ def judge_prompt(task: str, premises: str, records: str, rendered_transcript: st
|
||||
)
|
||||
room = max(0, JUDGE_PROMPT_CHARS - len(head) - len(JUDGE_RULES) - 2)
|
||||
# The tail, where an interrupt or a finish lands; the session's transcript grows cycle over cycle.
|
||||
shown = rendered_transcript[max(0, len(rendered_transcript) - room):]
|
||||
return f"{head}{shown}\n\n{JUDGE_RULES}", shown
|
||||
shown = transcript[max(0, len(transcript) - room):]
|
||||
return f"{head}{shown}\n\n{JUDGE_RULES}", Grounds(shown, render(agents_own, typed_answer), f"{premises}\n\n{records}")
|
||||
|
||||
|
||||
def grounded(evidence: str, rendered_transcript: str) -> bool:
|
||||
|
||||
@@ -1,23 +1,27 @@
|
||||
from model_routing.ladder import climbed, LADDER, position, review_rungs, ReviewKind, Rung
|
||||
from model_routing.ladder import climbed, LADDER, position, review_rungs, REVIEWERS, reviewers_rung, ReviewKind, Rung
|
||||
from model_routing.route import ESCALATION_MARKER, HIGHEST_ESCAPE_AND_IMPACT, Route
|
||||
from loop_claude.routing import escalation_rungs
|
||||
from loop_claude.project.records import HUMAN_RULE_NAMES, RECORD_FILES
|
||||
from markdown_text import listed, quoted
|
||||
from claude_code.transcript import Typed
|
||||
|
||||
# Where the judge may quote an answer from, named as the human and the worker see them; of README.md the judge sees only the premises.
|
||||
QUOTE_SOURCES = listed(("README.md's Goals and Audience", *RECORD_FILES, *HUMAN_RULE_NAMES), "or")
|
||||
# Where the worker may write an answer the human typed, so it counts as recorded.
|
||||
ANSWER_DESTINATIONS = "README.md's Goals or Audience, " + ", ".join(RECORD_FILES) + ", todo.md or a comment"
|
||||
ANSWERS_RECORDED = f"every answer the human typed in it that a later chunk could need is recorded in {ANSWER_DESTINATIONS} at the one place it governs"
|
||||
# Each kind of review, as review_launches names those it launches.
|
||||
REVIEWS: tuple[tuple[str, ReviewKind], ...] = (("each reviewer", "reviewer"), ("each comprehension seat", "seat"), ("the security pass's subagent", "security"))
|
||||
# Each kind of review, as review_launches names those it launches: a row per pass, since a replay may lower one pass alone. "each reviewer" names every pass no replay lowered.
|
||||
REVIEWS: tuple[tuple[str, ReviewKind], ...] = (*((f"each {agent}", kind) for kind, agent in REVIEWERS.items()), ("each comprehension seat", "seat"), ("the security pass's subagent", "security"))
|
||||
|
||||
|
||||
AFTER_CODE_HEALTH = 'which rank after code health (~/.claude/CLAUDE.md → "Shared goal") unless README.md voids it'
|
||||
|
||||
|
||||
def fresh(task: str, premises: str, route: Route, anchor: Rung | None, facts: str) -> str:
|
||||
"""A chunk's first prompt; facts is preflight_facts' or preflight_failed's text."""
|
||||
escalated = f"{escalation(route, anchor)}{reruns(route, anchor)}".lstrip()
|
||||
routed = f"{routed_by(route, anchor)}{recount(route)}\n\n" if route.item else (f"{escalated}\n\n" if escalated else "")
|
||||
return f"{task}\n\nContinue any open draft PR or worktree for the chunk before creating a new one.\n\n{routed}{facts}\n\nThe chunk's todo.md items, or else the task above, set its scope. The goals below choose between ways to deliver that scope, and never widen it.\n\nFrom README.md:\n{premises}"
|
||||
return f"{task}\n\nContinue any open draft PR or worktree for the chunk before creating a new one.\n\n{routed}{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 README.md:\n{premises}"
|
||||
|
||||
|
||||
def routed_by(route: Route, anchor: Rung | None) -> str:
|
||||
@@ -40,21 +44,32 @@ def preflight_failed(reason: str) -> str:
|
||||
|
||||
|
||||
def review_launches(route: Route, anchor: Rung | None) -> str:
|
||||
"""Which reviews to launch on a rung other than the worker's, and on which; below the project's rung, anchor, also where to launch a subagent that files or scores todo.md items; then taken_in_launches, the reviewers' rung each higher E + I picks. Empty off the ladder.
|
||||
"""Which reviews to launch on a rung other than the worker's, and on which, then the rung of each pass a replay lowered; below the project's rung, anchor, also where to launch a subagent that files or scores todo.md items; then taken_in_launches, the reviewers' rung each higher E + I picks. Empty off the ladder.
|
||||
|
||||
For a worker on Sonnet 5.5 at high, on an Opus 5.5 project, routed by item 3 of E + I 5, it opens: ` Launch each reviewer with the Agent tool set to model opus, effort high, the rung item 3's E + I of 5 picks. Launch each comprehension seat and the security pass's subagent with the Agent tool set to model opus, effort medium, the project's rung.`
|
||||
For a worker on Sonnet 5.5 at high, on an Opus 5.5 project, routed by item 3 of E + I 5, it opens: ` Launch each reviewer with the Agent tool set to model opus, effort high, the rung item 3's E + I of 5 picks. Launch each comprehension seat and the security pass's subagent with the Agent tool set to model opus, effort medium, the project's rung.` Where a replay lowered the prose pass to Haiku 5.5 at low, and the E + I steps no review up, a sentence follows: ` Launch each prose-reviewer instead with the Agent tool set to model haiku, effort low, the rung the replay of its pass chose.`
|
||||
"""
|
||||
if anchor is None:
|
||||
return ""
|
||||
rungs = review_rungs(anchor, route.rung, route.reviewed_on())
|
||||
launched: dict[Rung, list[str]] = {}
|
||||
for reviews, kind in REVIEWS:
|
||||
if rungs[kind] != route.rung:
|
||||
launched.setdefault(rungs[kind], []).append(reviews)
|
||||
launches = "".join(f" Launch {listed(reviews, 'and')} with the Agent tool set to {rung.agent_args()}, {rung_named(rung, route, anchor)}." for rung, reviews in launched.items())
|
||||
rungs, reviewers = review_rungs(anchor, route.rung, route.reviewed_on()), reviewers_rung(anchor, route.rung, route.reviewed_on())
|
||||
lowered_launches = "".join(f" Launch {reviews} instead with the Agent tool set to {rung.agent_args()}, the rung the replay of its pass chose." for reviews, rung in lowered(rungs, reviewers))
|
||||
scan = " Run a full scan only from such a subagent, since the scan's agents run on the model that starts them." if rungs["security"] != route.rung else ""
|
||||
planning = 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 {anchor.model} <L>` prints." if position(route.rung) < position(anchor) else ""
|
||||
return f"{launches}{scan}{planning}{taken_in_launches(route, anchor)}"
|
||||
return f"{shared_launches(rungs, reviewers, route, anchor)}{lowered_launches}{scan}{planning}{taken_in_launches(route, anchor)}"
|
||||
|
||||
|
||||
def shared_launches(rungs: dict[ReviewKind, Rung], reviewers: Rung, route: Route, anchor: Rung) -> str:
|
||||
"""A sentence for each rung other than the worker's that a review runs on. "each reviewer" names every pass no replay lowered; those run on reviewers."""
|
||||
together = {"each reviewer": reviewers} | {reviews: rungs[kind] for reviews, kind in REVIEWS if kind not in REVIEWERS}
|
||||
launched: dict[Rung, list[str]] = {}
|
||||
for reviews, rung in together.items():
|
||||
if rung != route.rung:
|
||||
launched.setdefault(rung, []).append(reviews)
|
||||
return "".join(f" Launch {listed(reviews, 'and')} with the Agent tool set to {rung.agent_args()}, {rung_named(rung, route, anchor)}." for rung, reviews in launched.items())
|
||||
|
||||
|
||||
def lowered(rungs: dict[ReviewKind, Rung], reviewers: Rung) -> list[tuple[str, Rung]]:
|
||||
"""Each pass a replay put below reviewers, the rung of every other pass, as REVIEWS names it, with the rung the replay chose."""
|
||||
return [(reviews, rungs[kind]) for reviews, kind in REVIEWS if kind in REVIEWERS and rungs[kind] != reviewers]
|
||||
|
||||
|
||||
def taken_in_launches(route: Route, anchor: Rung) -> str:
|
||||
@@ -62,12 +77,12 @@ def taken_in_launches(route: Route, anchor: Rung) -> str:
|
||||
|
||||
For a worker on Opus 5.5 at medium, routed by an item of E + I 6, it reads: ` Where an item you take into the chunk has an E + I of 7 or more, launch each reviewer with the Agent tool set to `model opus, effort max` from 7 and `model fable, effort max` from 8.`
|
||||
"""
|
||||
reviewers = review_rungs(anchor, route.rung, route.reviewed_on())["reviewer"]
|
||||
now = review_rungs(anchor, route.rung, route.reviewed_on())
|
||||
higher: dict[Rung, int] = {}
|
||||
for escape_and_impact in range(route.reviewed_on() + 1, HIGHEST_ESCAPE_AND_IMPACT + 1):
|
||||
rung = review_rungs(anchor, route.rung, escape_and_impact)["reviewer"]
|
||||
if position(rung) > position(reviewers):
|
||||
higher.setdefault(rung, escape_and_impact)
|
||||
# An E + I that lifts any pass puts every pass on reviewers_rung, since a replay lowers a pass only where the E + I steps no review up.
|
||||
if review_rungs(anchor, route.rung, escape_and_impact) != now:
|
||||
higher.setdefault(reviewers_rung(anchor, route.rung, escape_and_impact), escape_and_impact)
|
||||
if not higher:
|
||||
return ""
|
||||
picks = [f"`{rung.agent_args()}` from {escape_and_impact}" for rung, escape_and_impact in higher.items()]
|
||||
@@ -84,25 +99,43 @@ def rung_named(rung: Rung, route: Route, anchor: Rung) -> str:
|
||||
|
||||
|
||||
def escalation(route: Route, anchor: Rung | None) -> str:
|
||||
"""The prompt's escalation sentences, the marker's among them. Empty 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."""
|
||||
"""The prompt's escalation sentences, the marker's among them, each led by a space. Empty 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 on Opus 5.5 at high, on an Opus 5.5 project, 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 `model opus, effort xhigh`, one rung above yours, and on each further trigger one rung higher, up to `model opus, effort max`; 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 opus, effort max`.`
|
||||
"""
|
||||
if anchor is None or route.rung not in LADDER[:-1]:
|
||||
return ""
|
||||
marked = f" Open the subagent's prompt with `{ESCALATION_MARKER} <n>:`, n the trigger's number."
|
||||
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(anchor, 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.{marked}"
|
||||
return " " + " ".join((
|
||||
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.",
|
||||
marked,
|
||||
))
|
||||
further = f", and on each further trigger one rung higher, up to {rungs[-1]}" if len(rungs) > 1 else ""
|
||||
resumed_higher = f" 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 such request: once the judge finds it in your transcript, the next cycle resumes you one rung up, up to {rungs[-1]}."
|
||||
return f" When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to {rungs[0]}, one rung above yours{further}; above that, ask the human first.{marked}{resumed_higher}"
|
||||
return " " + " ".join((
|
||||
f"When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to {rungs[0]}, one rung above yours{further}; above that, ask the human first.",
|
||||
marked,
|
||||
f"Where the hard part is the rest of the chunk, end your run instead, 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 {rungs[-1]}.",
|
||||
))
|
||||
|
||||
|
||||
def reruns(route: Route, anchor: Rung | None) -> str:
|
||||
"""The prompt's sentence naming the rung one above a reviewer's and a seat's, on which each reruns when it asks; empty off the ladder, and leaving out one already on the top rung."""
|
||||
"""The prompt's sentences naming the rung one above a review's, on which it reruns when it asks: shared_reruns' for a reviewer and a seat, then one for each pass a replay lowered. Empty off the ladder.
|
||||
|
||||
For a worker on Sonnet 5.5 at high, on an Opus 5.5 project whose prose pass a replay lowered to Haiku 5.5 at low, routed by an item of E + I 4, they read: ` A reviewer or comprehension seat that asks for a rerun one rung up reruns with the Agent tool set to `model opus, effort high`. Rerun each prose-reviewer that asks with the Agent tool set to `model haiku, effort medium` instead.`
|
||||
"""
|
||||
if anchor is None or route.rung not in LADDER:
|
||||
return ""
|
||||
rungs = review_rungs(anchor, route.rung, route.reviewed_on())
|
||||
launched = (("reviewer", rungs["reviewer"]), ("comprehension seat", rungs["seat"]))
|
||||
rungs, reviewers = review_rungs(anchor, route.rung, route.reviewed_on()), reviewers_rung(anchor, route.rung, route.reviewed_on())
|
||||
lowered_reruns = "".join(f" Rerun {reviews} that asks with the Agent tool set to `{climbed(rung, 1).agent_args()}` instead." for reviews, rung in lowered(rungs, reviewers))
|
||||
return f"{shared_reruns(reviewers, rungs['seat'])}{lowered_reruns}"
|
||||
|
||||
|
||||
def shared_reruns(reviewers: Rung, seats: Rung) -> str:
|
||||
"""The sentence naming the rung one above reviewers, the rung of each pass no replay lowered, and one above seats, leaving out one already on the top rung."""
|
||||
launched = (("reviewer", reviewers), ("comprehension seat", seats))
|
||||
rerun = {name: climbed(rung, 1) for name, rung in launched if rung != LADDER[-1]}
|
||||
if not rerun:
|
||||
return ""
|
||||
@@ -115,11 +148,40 @@ def resumed(unfinished_evidence: str, route: Route, anchor: 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 anchor 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}.{on}{review_launches(route, anchor)}{escalation(route, anchor)}{reruns(route, anchor)}"
|
||||
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}.{on}{rungs_held(route, anchor)}"
|
||||
|
||||
|
||||
def answered(question: str, answer: str) -> str:
|
||||
return f"Your question: {question}\n\n{QUOTE_SOURCES} answers it:\n\n{answer}\n\nContinue the task."
|
||||
def rungs_held(route: Route, anchor: Rung | None) -> str:
|
||||
"""The sentences that depend on the worker's rung: where its reviews run and rerun, and where its escalated subagents run."""
|
||||
return f"{review_launches(route, anchor)}{escalation(route, anchor)}{reruns(route, anchor)}"
|
||||
|
||||
|
||||
def answered(question: str, answer: str, route: Route, anchor: 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, anchor, stepped)}"
|
||||
|
||||
|
||||
def typed(question: str, answer: str, route: Route, anchor: 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, anchor, 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.
|
||||
TYPED_HERE = "The human answered your question at loop-claude's terminal:"
|
||||
|
||||
|
||||
def typed_answer(prompt: str) -> Typed | None:
|
||||
"""Splits a prompt from typed() into its answer and the rest, so the judge reads the answer as the human's; None for any other prompt."""
|
||||
opening = f"{TYPED_HERE}\n"
|
||||
if not prompt.startswith(opening):
|
||||
return None
|
||||
answer, _, rest = prompt.removeprefix(opening).partition("\n\n")
|
||||
return Typed(rest, answer)
|
||||
|
||||
|
||||
def stepped_to(route: Route, anchor: 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, anchor)}" if stepped else ""
|
||||
|
||||
|
||||
def past_the_cap(question: str, answer: str, cap: int) -> str:
|
||||
|
||||
@@ -2,18 +2,18 @@ import dataclasses
|
||||
import pathlib
|
||||
import typing
|
||||
|
||||
from loop_claude.cycle.states import Active, Archived, Closing, Ended, Event, HumanAnswered, Interrupting, Judging, QUOTED_ANSWERS_PER_CYCLE, Ruled, State, transition, WorkerRan, Working
|
||||
from loop_claude.cycle.states import Active, Archived, Closing, Ended, Event, HumanTalked, HumanTyped, Interrupting, Judging, QUOTED_ANSWERS_PER_CYCLE, Ruled, State, TalkChosen, Talking, transition, TypedAnswer, WorkerRan, Working
|
||||
from transcript_archive.write import archive
|
||||
from claude_code.session import delete_session, Session, session_open, transcript_file
|
||||
from loop_claude.effects import Effects
|
||||
from loop_claude.cycle.judge import escalation_mark, Finished, Interrupt, judge, QuotedAnswer, Rejected, Unfinished
|
||||
from failure import Failure
|
||||
from loop_claude.cycle.judge import Finished, Interrupt, judge, QuotedAnswer, Rejected, Unfinished
|
||||
from loop_claude.cycle.interrupt import interrupt
|
||||
from loop_claude.routing import judge_rung
|
||||
from loop_claude.routing import judge_rung, stepped_by_ruling
|
||||
from transcript_archive import outcomes
|
||||
from loop_claude.paths import Paths
|
||||
from loop_claude.cycle import prompts
|
||||
from claude_code.transcript import read_transcript, render
|
||||
from loop_claude.cycle.interrupt import put_question, talk, Talk
|
||||
from claude_code.transcript import read_transcript
|
||||
from loop_claude.cycle.retry import retried
|
||||
from model_routing.route import Route
|
||||
from loop_claude.cycle.worker import run_worker, worker_args
|
||||
@@ -40,19 +40,41 @@ class Cycle:
|
||||
anchor: Rung | None
|
||||
# Empty when the previous cycle's verdict was not Unfinished.
|
||||
unfinished_evidence: str
|
||||
# Only an interrupt's or a quoted answer's escalation changes the route within a cycle. No transition reads the route or the fields below, so they stay out of the states.
|
||||
# The route before that ruling stepped it up, for ask and keep_answer to archive and for worker_start to tell the worker; None unless the latest event is that ruling, or the answer the human typed to it.
|
||||
stepped_from: Route | None = None
|
||||
|
||||
|
||||
def run_cycle(cycle: Cycle) -> Stop | Finished | Unfinished:
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Concluded:
|
||||
"""How a cycle ended: its verdict, and the route it ended on, which an interrupt's or a quoted answer's escalation may have stepped up from the route it began on."""
|
||||
verdict: Finished | Unfinished
|
||||
route: Route
|
||||
|
||||
|
||||
def run_cycle(cycle: Cycle) -> Stop | Concluded:
|
||||
state: State = Working()
|
||||
try:
|
||||
while not isinstance(state, Ended):
|
||||
event = step(cycle, state)
|
||||
if isinstance(event, Stop):
|
||||
return stopped(cycle, event, event.reason)
|
||||
cycle = escalated(cycle, event)
|
||||
state = transition(state, event)
|
||||
except KeyboardInterrupt:
|
||||
return stopped(cycle, Stop(130, ""), "Ctrl-C")
|
||||
return state.verdict
|
||||
return Concluded(state.verdict, cycle.route)
|
||||
|
||||
|
||||
def escalated(cycle: Cycle, event: Event) -> Cycle:
|
||||
"""The cycle after event. Where the judge interrupted or quoted an answer with an escalation, its route steps up before the human is asked or the worker resumes, so the work after the answer runs on it. stepped_from holds through the answer the human types, so the worker resuming with it is told of the step; a copy on TypedAnswer would give the step a second owner."""
|
||||
if isinstance(event, HumanTyped):
|
||||
return cycle
|
||||
cycle = dataclasses.replace(cycle, stepped_from=None)
|
||||
if not (isinstance(event, Ruled) and isinstance(event.verdict, Interrupt | QuotedAnswer) and cycle.anchor):
|
||||
return cycle
|
||||
route = stepped_by_ruling(cycle.anchor, cycle.route, event.verdict.bundled, escalation_mark(event.verdict))
|
||||
return dataclasses.replace(cycle, route=route, stepped_from=cycle.route if route != cycle.route else None)
|
||||
|
||||
|
||||
def stopped(cycle: Cycle, stop: Stop, why: str) -> Stop:
|
||||
@@ -75,14 +97,16 @@ def step(cycle: Cycle, state: Active) -> Event | Stop:
|
||||
return rule(cycle, transcript_path)
|
||||
case Interrupting(transcript_path, ruling, _):
|
||||
return ask(cycle, transcript_path, ruling)
|
||||
case Talking(transcript_path, _):
|
||||
return talk(cycle.root, cycle.session.id, cycle.route.rung, transcript_path, cycle.paths, worker_environment(cycle), cycle.effects) or HumanTalked()
|
||||
case Closing(transcript_path, verdict):
|
||||
return close(cycle, transcript_path, verdict)
|
||||
case _:
|
||||
typing.assert_never(state)
|
||||
|
||||
|
||||
def work(cycle: Cycle, answered: QuotedAnswer | None) -> WorkerRan | Stop:
|
||||
if answered is not None:
|
||||
def work(cycle: Cycle, answered: QuotedAnswer | TypedAnswer | None) -> WorkerRan | Stop:
|
||||
if isinstance(answered, QuotedAnswer):
|
||||
print(f"\n=== {prompts.QUOTE_SOURCES} answered: {answered.question} ===\n{answered.answer}", flush=True)
|
||||
if stop := keep_answer(cycle, answered):
|
||||
return stop
|
||||
@@ -98,9 +122,11 @@ def worker_environment(cycle: Cycle) -> dict[str, str]:
|
||||
return worker_rungs.environment(cycle.anchor, cycle.route)
|
||||
|
||||
|
||||
def worker_start(cycle: Cycle, answered: QuotedAnswer | None) -> list[str]:
|
||||
if answered is not None:
|
||||
return worker_args(cycle.session, cycle.route.rung, prompts.answered(answered.question, answered.answer), resume=True)
|
||||
def worker_start(cycle: Cycle, answered: QuotedAnswer | TypedAnswer | None) -> list[str]:
|
||||
if isinstance(answered, QuotedAnswer):
|
||||
return worker_args(cycle.session, cycle.route.rung, prompts.answered(answered.question, answered.answer, cycle.route, cycle.anchor, cycle.stepped_from is not None), resume=True)
|
||||
if isinstance(answered, TypedAnswer):
|
||||
return worker_args(cycle.session, cycle.route.rung, prompts.typed(answered.question, answered.answer, cycle.route, cycle.anchor, cycle.stepped_from is not None), resume=True)
|
||||
if session_open(cycle.session):
|
||||
return worker_args(cycle.session, cycle.route.rung, prompts.resumed(cycle.unfinished_evidence, cycle.route, cycle.anchor), resume=True)
|
||||
return worker_args(cycle.session, cycle.route.rung, prompts.fresh(cycle.task, cycle.premises, cycle.route, cycle.anchor, cycle.facts), resume=False)
|
||||
@@ -108,7 +134,11 @@ def worker_start(cycle: Cycle, answered: QuotedAnswer | None) -> list[str]:
|
||||
|
||||
def keep_answer(cycle: Cycle, answered: QuotedAnswer) -> Stop | None:
|
||||
path = transcript_file(cycle.session)
|
||||
if path and (failure := archive(cycle.project_archive, path, cycle.task, outcomes.answered(answered.question, prompts.QUOTE_SOURCES, answered.answer, answered.evidence, str(judge_of(cycle))), cycle.effects.now())):
|
||||
if not path:
|
||||
return None
|
||||
# As in ask: the answer names the rung the worker ran on until then, and a step-up archived after it names the rung it runs on from then.
|
||||
quoted = outcomes.answered(answered.question, prompts.QUOTE_SOURCES, answered.answer, answered.evidence, answered.escalation, str(judge_of(cycle)), str(cycle.stepped_from or cycle.route))
|
||||
if failure := archive_stepped(cycle, path, quoted):
|
||||
return Stop(1, failure.reason)
|
||||
return None
|
||||
|
||||
@@ -117,7 +147,7 @@ def rule(cycle: Cycle, transcript_path: str) -> Ruled | Stop:
|
||||
entries = read_transcript(transcript_path)
|
||||
if isinstance(entries, Failure):
|
||||
return Stop(1, entries.reason)
|
||||
verdict = judge(cycle.root, cycle.task, cycle.premises, cycle.records, render(entries), judge_of(cycle), cycle.effects, lambda rejected: keep_rejection(cycle, transcript_path, rejected))
|
||||
verdict = judge(cycle.root, cycle.task, cycle.premises, cycle.records, entries, cycle.route.escalated_at, judge_of(cycle), cycle.effects, lambda rejected: keep_rejection(cycle, transcript_path, rejected))
|
||||
return verdict if isinstance(verdict, Stop) else Ruled(verdict)
|
||||
|
||||
|
||||
@@ -128,12 +158,27 @@ def keep_rejection(cycle: Cycle, transcript_path: str, rejected: Rejected) -> St
|
||||
return None
|
||||
|
||||
|
||||
def ask(cycle: Cycle, transcript_path: str, ruling: Interrupt | QuotedAnswer) -> HumanAnswered | Stop:
|
||||
def ask(cycle: Cycle, transcript_path: str, ruling: Interrupt | QuotedAnswer) -> HumanTyped | TalkChosen | Stop:
|
||||
question = question_for(ruling)
|
||||
# Archived now, so the transcript the question was asked on is kept with it; the human's answer then grows the transcript.
|
||||
if failure := archive(cycle.project_archive, transcript_path, cycle.task, outcomes.interrupted(question, ruling.evidence, str(judge_of(cycle))), cycle.effects.now()):
|
||||
# The interrupt names the rung the worker ran on before it; a step-up archived after it names the stepped rung, so the figures charge each stretch to its own rung.
|
||||
interrupted = outcomes.interrupted(question, ruling.evidence, str(judge_of(cycle)), ruling.escalation, str(cycle.stepped_from or cycle.route))
|
||||
if failure := archive_stepped(cycle, transcript_path, interrupted):
|
||||
return Stop(1, failure.reason)
|
||||
return interrupt(cycle.root, cycle.session.id, cycle.route.rung, transcript_path, question, cycle.paths, worker_environment(cycle), cycle.effects) or HumanAnswered()
|
||||
# Only the human may cut a release, so a release ready to cut opens claude's session at once.
|
||||
answer = put_question(question, not (isinstance(ruling, Interrupt) and ruling.release_ready), cycle.effects)
|
||||
if isinstance(answer, Stop):
|
||||
return answer
|
||||
# The worker gets the question it asked, not the one put to the human past the cap.
|
||||
return TalkChosen() if isinstance(answer, Talk) else HumanTyped(TypedAnswer(ruling.question, answer))
|
||||
|
||||
|
||||
def archive_stepped(cycle: Cycle, transcript_path: str, outcome: str) -> Failure | None:
|
||||
"""Archives the outcome of a ruling, then the step-up it caused when it stepped the route. The first failure is returned."""
|
||||
for kept in (outcome, outcomes.stepped_up(str(cycle.route))) if cycle.stepped_from else (outcome,):
|
||||
if failure := archive(cycle.project_archive, transcript_path, cycle.task, kept, cycle.effects.now()):
|
||||
return failure
|
||||
return None
|
||||
|
||||
|
||||
def question_for(ruling: Interrupt | QuotedAnswer) -> str:
|
||||
|
||||
@@ -6,10 +6,17 @@ from loop_claude.cycle.judge import Finished, Interrupt, QuotedAnswer, Unfinishe
|
||||
QUOTED_ANSWERS_PER_CYCLE = 3
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class TypedAnswer:
|
||||
"""The human's answer to an interrupt, typed at loop-claude's terminal."""
|
||||
question: str
|
||||
answer: str
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Working:
|
||||
"""The worker runs, resumed with an answer quoted from README.md or the records when there is one."""
|
||||
answered: QuotedAnswer | None = None
|
||||
"""The worker runs, resumed with an answer quoted from README.md or the records, or typed by the human, when there is one."""
|
||||
answered: QuotedAnswer | TypedAnswer | None = None
|
||||
quoted_answers: int = 0
|
||||
|
||||
|
||||
@@ -28,6 +35,13 @@ class Interrupting:
|
||||
quoted_answers: int = 0
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Talking:
|
||||
"""The human answers in the worker's claude session, on the terminal."""
|
||||
transcript_path: str
|
||||
quoted_answers: int = 0
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Closing:
|
||||
transcript_path: str
|
||||
@@ -39,7 +53,7 @@ class Ended:
|
||||
verdict: Finished | Unfinished
|
||||
|
||||
|
||||
Active = Working | Judging | Interrupting | Closing
|
||||
Active = Working | Judging | Interrupting | Talking | Closing
|
||||
State = Active | Ended
|
||||
|
||||
|
||||
@@ -54,8 +68,18 @@ class Ruled:
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class HumanAnswered:
|
||||
pass
|
||||
class HumanTyped:
|
||||
typed: TypedAnswer
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class TalkChosen:
|
||||
"""The human typed /talk, or the interrupt is for a release ready to cut."""
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class HumanTalked:
|
||||
"""The human typed in the worker's claude session."""
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
@@ -63,7 +87,7 @@ class Archived:
|
||||
pass
|
||||
|
||||
|
||||
Event = WorkerRan | Ruled | HumanAnswered | Archived
|
||||
Event = WorkerRan | Ruled | HumanTyped | TalkChosen | HumanTalked | Archived
|
||||
|
||||
|
||||
def transition(state: State, event: Event) -> State:
|
||||
@@ -78,8 +102,12 @@ def transition(state: State, event: Event) -> State:
|
||||
return Interrupting(transcript_path, ruling, quoted_answers)
|
||||
case Judging(transcript_path, _), Ruled(Finished() | Unfinished() as verdict):
|
||||
return Closing(transcript_path, verdict)
|
||||
# The human works in the interrupt's claude session, so the judge rules again on the transcript it leaves.
|
||||
case Interrupting(transcript_path, _, quoted_answers), HumanAnswered():
|
||||
case Interrupting(_, _, quoted_answers), HumanTyped(typed):
|
||||
return Working(typed, quoted_answers)
|
||||
case Interrupting(transcript_path, _, quoted_answers), TalkChosen():
|
||||
return Talking(transcript_path, quoted_answers)
|
||||
# The human worked in the worker's claude session, so the judge rules again on the transcript it leaves.
|
||||
case Talking(transcript_path, quoted_answers), HumanTalked():
|
||||
return Judging(transcript_path, quoted_answers)
|
||||
case Closing(_, verdict), Archived():
|
||||
return Ended(verdict)
|
||||
|
||||
@@ -2,6 +2,7 @@ import dataclasses
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import termios
|
||||
import time
|
||||
import typing
|
||||
|
||||
@@ -21,6 +22,8 @@ class Streaming(typing.Protocol):
|
||||
class Effects:
|
||||
claude: typing.Callable[[list[str], str, str], subprocess.CompletedProcess[str]]
|
||||
claude_on_terminal: typing.Callable[[list[str], str, dict[str, str]], int]
|
||||
# Drops what was typed on the terminal and not yet read.
|
||||
discard_typed: typing.Callable[[], None]
|
||||
execv: typing.Callable[[str, list[str]], None]
|
||||
git: typing.Callable[[list[str], str], subprocess.CompletedProcess[str]]
|
||||
input: typing.Callable[[str], str]
|
||||
@@ -49,6 +52,7 @@ def system_effects() -> Effects:
|
||||
return Effects(
|
||||
claude=lambda args, cwd, stdin: subprocess.run(["claude", *args], capture_output=True, cwd=cwd, input=stdin, text=True),
|
||||
claude_on_terminal=lambda args, cwd, env: subprocess.run(["claude", *args], cwd=cwd, env={**os.environ, **env}).returncode,
|
||||
discard_typed=lambda: termios.tcflush(sys.stdin, termios.TCIFLUSH),
|
||||
execv=os.execv,
|
||||
git=lambda args, cwd: subprocess.run(["git", *args], capture_output=True, cwd=cwd, text=True),
|
||||
input=input,
|
||||
|
||||
@@ -4,10 +4,11 @@ usage: loop-claude <task>
|
||||
|
||||
Run it anywhere inside a project checkout whose README.md has ## Goals and ## Audience, the
|
||||
premises; the task runs at the checkout root. Each cycle a worker runs the task. A chunk's first
|
||||
worker prompt also quotes the premises, which choose between ways to deliver the chunk's todo.md
|
||||
items, or else the task, and never widen them. A judge then reads the transcript's end, the
|
||||
premises, and the records: the project's AGENTS.md and docs/decisions.md, and the human's
|
||||
~/.claude/CLAUDE.md, ~/.claude/rules/*.md and
|
||||
worker prompt also quotes the premises. They, with code health
|
||||
(~/.claude/CLAUDE.md → "Shared goal") ranked first unless README.md voids it, choose between ways
|
||||
to deliver the chunk's todo.md items, or else the task, and never widen them. A judge then reads
|
||||
the transcript's end, the premises, and the records: the project's AGENTS.md and docs/decisions.md,
|
||||
and the human's ~/.claude/CLAUDE.md, ~/.claude/rules/*.md and
|
||||
~/.claude/skills/larv-review/standards/*.md, where they exist. It rules whether the chunk, the work
|
||||
of one PR, is finished. A chunk stays unfinished until each answer the human typed in it that a
|
||||
later chunk could need is recorded: the premises or the records hold it, or the transcript shows the worker
|
||||
@@ -16,13 +17,19 @@ worker made that the premises or the records settle is not asked about. When the
|
||||
question they answer, the judge quotes the answer, loop-claude prints it, and the worker resumes
|
||||
with it. A quote they do not hold word for word is dropped, and the question goes to the human. So
|
||||
does a question asked again after its answer. The fourth question they answer in one cycle goes to
|
||||
the human too, with the quote.
|
||||
A question only the human can answer, or a release ready to cut, is an interrupt: `claude --resume`
|
||||
on the terminal, every worktree first marked trusted in ~/.claude.json. An unfinished chunk resumes
|
||||
its session next cycle, and the worker is shown the passage the judge quoted as the work remaining.
|
||||
The next chunk starts a fresh session.
|
||||
the human too, with the quote. An unfinished chunk resumes its session next cycle, and the worker
|
||||
is shown the passage the judge quoted as the work remaining. The next chunk starts a fresh session.
|
||||
Cycles continue until an exit below or Ctrl-C. Words: ~/.claude/CLAUDE.md → "Vocabulary".
|
||||
|
||||
A question only the human can answer is an interrupt (bin/loop_claude/cycle/interrupt.py).
|
||||
loop-claude prints the question and reads a one-line answer on its terminal. The worker resumes
|
||||
headless with the answer. The judge reads it as the human's, so the chunk stays unfinished until the
|
||||
answer is recorded. An empty answer stops the loop. Typing /talk instead opens the worker's session
|
||||
on the terminal with `claude --resume`, to read the diff or discuss first. Once that claude exits,
|
||||
the judge rules on what was typed there. A release ready to cut opens that session at once, since
|
||||
only the human may cut it. Before claude opens, the checkout and each of its worktrees are marked
|
||||
trusted in ~/.claude.json.
|
||||
|
||||
As a chunk starts, before it is routed, loop-claude runs bin/chunk-preflight (bin/chunk_preflight/),
|
||||
which finds the chunk's facts and makes its worktree; chunk-preflight --help lists them, and
|
||||
prompts.preflight_facts in bin/loop_claude/cycle/prompts.py quotes them in the first prompt. A
|
||||
@@ -37,8 +44,8 @@ copied to $LOOP_CLAUDE_TRANSCRIPTS/<key>/<chunk>/<sha256>.jsonl (default
|
||||
line with a timestamp, the same for every cycle of a chunk. Beside the copy, <sha256>.outcomes.md
|
||||
holds the verdict, with the transcript passage the judge rested it on, any passage it quoted to
|
||||
show an escalation trigger fired, and the judge's rung; each answer the judge quoted, with the
|
||||
question it answers; each judge reply the loop rejected, with the reason and the reply as json;
|
||||
and why the loop stopped. Each of these opens with its UTC time. Claude Code keeps a folder per
|
||||
question it answers and any passage it quoted to show an escalation trigger fired; each judge
|
||||
reply the loop rejected, with the reason and the reply as json; and why the loop stopped. Each of these opens with its UTC time. Claude Code keeps a folder per
|
||||
session beside its transcript, holding the subagents' transcripts among other files; that folder,
|
||||
and every other file named after the session except the transcript, are copied into
|
||||
<chunk>/session/. A file there is replaced only by a version that grew from it. A file Claude Code
|
||||
@@ -46,46 +53,52 @@ rewrote lands beside its copy as <name>.<hash of its content>.
|
||||
|
||||
Every claude loop-claude starts runs the project's model, saved per <key> in
|
||||
~/.claude/loop-claude-models.json and read each cycle, unless routing, below, puts the worker,
|
||||
the interrupt and the judge on another rung; a project without an entry, as on its first
|
||||
the session /talk opens and the judge on another rung; a project without an entry, as on its first
|
||||
run, is asked for one. LOOP_CLAUDE_JUDGE_MODEL overrides it for the judge, LOOP_CLAUDE_WORKER_MODEL
|
||||
for the worker and the interrupt; with both set, nothing is asked.
|
||||
for the worker and the session /talk opens; with both set, nothing is asked.
|
||||
|
||||
Where that model is on the routing ladder (bin/model_routing/ladder.py), the worker and the
|
||||
interrupt run on one of the ladder's rungs: a model at an effort. As a chunk starts, it is routed
|
||||
session /talk opens run on one of the ladder's rungs: a model at an effort. As a chunk starts, it is routed
|
||||
on the item chunk-preflight names, read from todo.md on the default branch as the preflight just
|
||||
fetched it (todo_table.chunk_item). That item is the earliest release's top item that does not wait,
|
||||
fetched it (chunk_pick.chunk_item). That item is the earliest release's top item that does not wait,
|
||||
but only where that release is the next one: the earliest after the newest vX.Y.Z tag that todo.md
|
||||
has named at that tag or since, or any earliest release where no tag names a version. Otherwise no
|
||||
item routes the chunk. An item waits while it is marked
|
||||
question, or while an item that blocks it is still in the table. The item's L
|
||||
has named at that tag or since, skipping a release its ## Renamed section marks renamed, or, where
|
||||
no tag names a version, the earliest release. Otherwise no item routes the chunk. An item waits
|
||||
while it is marked question, or while an item that blocks it is still in the table. The item's L
|
||||
picks the worker's rung, stepping from the model's cheapest rung by WORKER_STEPS in
|
||||
bin/model_routing/ladder.py, below it for a low L; without such an item, or with its L, E or I
|
||||
unscored, the chunk runs on the model's cheapest rung. The
|
||||
item's E + I picks the reviewers' rung, stepping up from the cheapest rung by REVIEW_STEPS there,
|
||||
never below the worker's rung. The worker's first prompt names the rung and the item, and asks the
|
||||
never below the worker's rung. Where it steps none and the worker runs no higher than the cheapest
|
||||
rung, a pass REPLAYED there names runs on the rung it names, the lowest a review-replay run found
|
||||
finding what the cheapest rung finds, even below the worker's. The worker's first prompt names the rung and the item, and asks the
|
||||
worker to name each item the chunk takes, with its L and E + I, and to count the item's size again
|
||||
once it has read the code (prompts.recount). The prompt names the rung of each review that runs on
|
||||
a rung other than the worker's: the reviewers' rung for the reviewers, and the cheapest rung for
|
||||
each comprehension seat and the security pass. It also names the reviewers' rung
|
||||
a rung other than the worker's: the reviewers' rung or the replay's for each pass's reviewer, and
|
||||
the cheapest rung for each comprehension seat and the security pass. It also names the reviewers' rung
|
||||
each higher E + I picks, so the worker reviews an item it takes in on that rung in the same run.
|
||||
When the worker runs below the cheapest rung, the prompt has it launch each subagent that files or
|
||||
scores todo.md items on the rung subagent-rung --plan prints. The prompt after
|
||||
each unfinished verdict says this again, since a step-up may have moved the worker. A reviewer or
|
||||
seat that rules the work below standard may ask to rerun one rung up; each prompt names that rung.
|
||||
loop-claude hands the worker's claude its own rung, the project's and the reviewers', in
|
||||
LOOP_CLAUDE_WORKER_RUNG, LOOP_CLAUDE_PROJECT_RUNG and LOOP_CLAUDE_REVIEWER_RUNG, and rule-hook
|
||||
refuses a review launched below the rung named for it. The judge reports the highest L and the
|
||||
loop-claude hands the worker's claude its own rung, the project's and the reviews' E + I, in
|
||||
LOOP_CLAUDE_WORKER_RUNG, LOOP_CLAUDE_PROJECT_RUNG and LOOP_CLAUDE_ESCAPE_AND_IMPACT, and rule-hook
|
||||
refuses a review launched below the rung those pick for it. The judge reports the highest L and the
|
||||
highest E + I the worker states for an item it takes in. The next cycle steps the worker up to the
|
||||
rung that L picks, never down, and the reviewers to the rung picked by the higher of two: that
|
||||
E + I, or the routed item's (Route.reviewed_on in bin/model_routing/route.py). A level off its
|
||||
scale counts as none. Every second unfinished verdict on a chunk steps it up one rung
|
||||
(routing.stepped). So does an unfinished verdict on a worker that ended its run asking for a
|
||||
higher rung, once the judge quotes the transcript showing that the escalation trigger it named
|
||||
fired (~/.claude/CLAUDE.md → "Working with the codebase" lists them). That step stops two rungs
|
||||
above the rung the chunk's item picks, and the worker's prompts offer it only while the worker is
|
||||
below that limit. Each finished or unfinished verdict, stop and step-up in the archive names the
|
||||
worker's rung, with the item, L and E + I that routed the chunk, and any taken-in E + I that picks a
|
||||
higher review rung, which is archived as a step-up too. A rerun resumes an open chunk on the latest
|
||||
fired (~/.claude/CLAUDE.md → "Working with the codebase" lists them). An interrupt or a quoted answer
|
||||
with such a quote steps the rung as it comes in, before the human is asked or the worker resumes
|
||||
(routing.stepped_by_ruling). Each such step marks how many transcript entries the session held,
|
||||
and from then on the judge must quote the worker's own lines after that mark, where it reads a
|
||||
[step] line. Each step on an escalation stops two rungs above the rung the chunk's item picks, and the worker's prompts
|
||||
offer it only while the worker is below that limit. Each finished or unfinished verdict, interrupt,
|
||||
quoted answer, stop and step-up in the archive names the worker's rung, with the item, L and E + I
|
||||
that routed the chunk, any taken-in E + I that picks a higher review rung (archived as a step-up
|
||||
too), and the mark. A rerun resumes an open chunk on the latest
|
||||
route named there, and counts its unfinished verdicts afresh. A rung no longer on the ladder, or
|
||||
below the one its item's L picks, is dropped, and the chunk is routed afresh from todo.md. So is a
|
||||
chunk whose archived line names an R + C, as loop-claude wrote before it routed on L. A todo.md or
|
||||
@@ -144,7 +157,8 @@ Exit 1, saying why, when:
|
||||
Exit 2, when the human is needed and cannot answer:
|
||||
- stdin or stdout is not a terminal, when a model must be picked or an interrupt answered
|
||||
- the input ends while a model is picked
|
||||
- an interrupt ends with nothing typed
|
||||
- an interrupt's answer is empty, or the input ends before one is typed
|
||||
- the claude opened for /talk, or for a release ready to cut, ends with nothing typed
|
||||
Rerunning resumes any open session.
|
||||
|
||||
"""
|
||||
@@ -159,10 +173,11 @@ from loop_claude.loop.routing_check import check_routing
|
||||
from loop_claude.project.checkout import checkout_root
|
||||
from loop_claude.cycle.run import Cycle, run_cycle
|
||||
from loop_claude.loop.reload import decode_handed, exec_if_edited, fingerprint, LoopRun, RELOAD_FLAG
|
||||
from git_repo import default_plan, default_ref, DefaultPlan
|
||||
from chunk_pick import default_plan, DefaultPlan
|
||||
from git_repo import default_ref
|
||||
from loop_claude.effects import Effects
|
||||
from loop_claude.cycle.judge import escalation_mark, Finished, Unfinished
|
||||
from failure import Failure
|
||||
from loop_claude.cycle.judge import Finished, Unfinished
|
||||
from loop_claude.routing import first_route, kept, routed_item, stepped
|
||||
from loop_claude.project.model_choice import get_or_ask_models
|
||||
from todo_table import Item
|
||||
@@ -214,17 +229,18 @@ def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launc
|
||||
models = get_or_ask_models(key, paths, env, effects)
|
||||
if isinstance(models, Stop):
|
||||
return models
|
||||
# Before routing, which reads the plan as the preflight's fetch left it; after the reads above, so a loop that stops on one makes no worktree.
|
||||
facts = "" if session_open(session) else chunk_facts(launcher.with_name("chunk-preflight"), loop_run.root, effects)
|
||||
# After the reads above, so a loop that stops on one makes no worktree.
|
||||
facts, item = chunk_start(session, launcher.with_name("chunk-preflight"), loop_run.root, effects)
|
||||
anchor = project_rung(models.worker)
|
||||
root = loop_run.root
|
||||
loop_run = routed(loop_run, anchor, lambda: archived_route(archive_folder, session), lambda: plan_item(fetched_plan(root)))
|
||||
loop_run = routed(loop_run, anchor, lambda: archived_route(archive_folder, session), item)
|
||||
route = loop_run.route or Route(Rung(models.worker))
|
||||
print(f"\n=== cycle {loop_run.cycle_number}, worker on {route.rung} ===", flush=True)
|
||||
verdict = run_cycle(Cycle(anchor=anchor, effects=effects, facts=facts, judge_model=models.judge, paths=paths, premises=premises, project_archive=archive_folder, records=records, root=loop_run.root, route=route, session=session, task=loop_run.task, unfinished_evidence=loop_run.unfinished_evidence))
|
||||
if isinstance(verdict, Stop):
|
||||
return verdict
|
||||
before, loop_run = loop_run.route, after_verdict(loop_run, anchor, verdict)
|
||||
concluded = run_cycle(Cycle(anchor=anchor, effects=effects, facts=facts, judge_model=models.judge, paths=paths, premises=premises, project_archive=archive_folder, records=records, root=loop_run.root, route=route, session=session, task=loop_run.task, unfinished_evidence=loop_run.unfinished_evidence))
|
||||
if isinstance(concluded, Stop):
|
||||
return concluded
|
||||
# The route the cycle ended on, which a step-up at an interrupt or a quoted answer may have raised and archived, is the one the verdict steps from.
|
||||
ended = dataclasses.replace(loop_run, route=concluded.route if anchor else None)
|
||||
before, loop_run = ended.route, after_verdict(ended, anchor, concluded.verdict)
|
||||
if stop := archive_step(archive_folder, session, loop_run, before, effects):
|
||||
return stop
|
||||
if stop := check_routing(archive_root(paths.home, env), anchor or Rung(models.worker), paths, effects):
|
||||
@@ -243,7 +259,7 @@ def routed(loop_run: LoopRun, anchor: Rung | None, archived: typing.Callable[[],
|
||||
def after_verdict(loop_run: LoopRun, anchor: Rung | None, verdict: Finished | Unfinished) -> LoopRun:
|
||||
if isinstance(verdict, Finished):
|
||||
return dataclasses.replace(loop_run, route=None, unfinished_evidence="")
|
||||
route = stepped(anchor, loop_run.route, verdict.bundled, bool(verdict.escalation)).taking_in(verdict.bundled_escape_and_impact) if anchor and loop_run.route else loop_run.route
|
||||
route = stepped(anchor, loop_run.route, verdict.bundled, escalation_mark(verdict)).taking_in(verdict.bundled_escape_and_impact) if anchor and loop_run.route else loop_run.route
|
||||
return dataclasses.replace(loop_run, route=route, unfinished_evidence=verdict.evidence)
|
||||
|
||||
|
||||
@@ -266,6 +282,12 @@ def archived_route(archive_folder: pathlib.Path, session: Session) -> Route | No
|
||||
return route_from(worker) if worker else None
|
||||
|
||||
|
||||
def chunk_start(session: Session, preflight: pathlib.Path, root: str, effects: Effects) -> tuple[str, typing.Callable[[], Item | None]]:
|
||||
"""The facts for a fresh worker's prompt, empty where the session is open, and the reader of the item that routes the chunk. The reader reads the default branch as last fetched: for a fresh chunk, by the preflight that runs first; for an open session, which runs none, by whatever fetched last."""
|
||||
facts = "" if session_open(session) else chunk_facts(preflight, root, effects)
|
||||
return facts, lambda: plan_item(fetched_plan(root))
|
||||
|
||||
|
||||
def chunk_facts(preflight: pathlib.Path, root: str, effects: Effects) -> str:
|
||||
"""What chunk-preflight printed at the checkout root, for a fresh worker's prompt, or why it could not run."""
|
||||
done = effects.python([str(preflight)], root)
|
||||
@@ -275,13 +297,13 @@ def chunk_facts(preflight: pathlib.Path, root: str, effects: Effects) -> str:
|
||||
|
||||
|
||||
def fetched_plan(root: str) -> DefaultPlan | Failure:
|
||||
"""What the default branch, as chunk-preflight's fetch left it, holds for routing."""
|
||||
"""What the default branch, as last fetched, holds for routing."""
|
||||
ref = default_ref(root, ORIGIN_TIMEOUT)
|
||||
return ref if isinstance(ref, Failure) else default_plan(root, ref)
|
||||
|
||||
|
||||
def plan_item(plan: DefaultPlan | Failure) -> Item | None:
|
||||
"""The item that routes a chunk, todo_table.chunk_item's pick from the default branch; None without one, so the chunk runs on the project's rung."""
|
||||
"""The item that routes a chunk, chunk_pick.chunk_item's pick from the default branch; None without one, so the chunk runs on the project's rung."""
|
||||
if isinstance(plan, Failure):
|
||||
item: Item | Failure | None = plan
|
||||
elif isinstance(plan.todo, Failure):
|
||||
|
||||
+28
-11
@@ -1,9 +1,10 @@
|
||||
"""Which ladder rung a chunk's worker and judge run on: docs/decisions.md → `routing:`."""
|
||||
import dataclasses
|
||||
|
||||
from todo_table import chunk_item, Item, items, LastCut
|
||||
from chunk_pick import chunk_item, LastCut, Next
|
||||
from model_routing.ladder import climbed, highest, LADDER, position, project_rung, review_floor, Rung, stepped_up, worker_rung
|
||||
from failure import Failure
|
||||
from todo_table import Item, items
|
||||
from model_routing.route import Route
|
||||
|
||||
UNFINISHED_PER_STEP = 2
|
||||
@@ -14,11 +15,12 @@ JUDGE_REPLAYED = ("claude-opus-5-5",)
|
||||
|
||||
|
||||
def routed_item(todo: str, cut: LastCut) -> Item | Failure | None:
|
||||
"""The item todo_table.chunk_item picks from todo.md, weighed against the last cut; None when there is none, or it lacks L, E or I."""
|
||||
"""The item chunk_pick.chunk_item picks from todo.md, weighed against the last cut; None when there is none, or it lacks L, E or I."""
|
||||
found = items(todo)
|
||||
if isinstance(found, Failure):
|
||||
return found
|
||||
_, takes = chunk_item(found or [], cut)
|
||||
pick = chunk_item(found or [], cut)
|
||||
takes = pick.item if isinstance(pick, Next) else None
|
||||
return takes if takes and takes.likelihood and takes.escape_and_impact else None
|
||||
|
||||
|
||||
@@ -59,21 +61,36 @@ def escalation_cap(anchor: Rung, route: Route) -> Rung:
|
||||
return climbed(item_rung(anchor, route), ESCALATION_CAP)
|
||||
|
||||
|
||||
def stepped(anchor: Rung, route: Route, bundled: int, escalated: bool) -> Route:
|
||||
"""The route after one more unfinished verdict. Its rules, in order: the rung never falls below kept_rung; a bundled item lifts it to the rung that item's L picks; every second unfinished verdict steps it up one rung; so does an escalation the judge found, up to escalation_cap, two rungs above item_rung; and both steps on one verdict make one step.
|
||||
def stepped(anchor: Rung, route: Route, bundled: int, escalated_at: int | None) -> Route:
|
||||
"""The route after one more unfinished verdict. Its rung never falls below taken_in's. It steps up one rung on every second unfinished verdict, or on an escalation the judge found while the rung is below escalation_cap; where both fall on one verdict, it steps once.
|
||||
|
||||
bundled and escalated are the verdict's fields, not the verdict, since loop_claude.cycle.judge imports this module through prompts.
|
||||
bundled is the highest L the judge saw the worker take in, 0 for none. escalated_at is how many transcript entries the judge read where the verdict carries an escalation, None where it carries none. A step moves the route's mark, Route.escalated_at, to escalated_at; a step on the count of unfinished verdicts alone keeps the mark. They are passed in place of the verdict, since loop_claude.cycle.judge imports this module through prompts.
|
||||
"""
|
||||
rung = taken_in(anchor, route, bundled)
|
||||
unfinished = route.unfinished + 1
|
||||
counted_out = unfinished >= UNFINISHED_PER_STEP
|
||||
# The judge found the escalation trigger the worker cited in asking for a higher rung.
|
||||
escalates = escalated and position(rung) < position(escalation_cap(anchor, route))
|
||||
if counted_out or escalates:
|
||||
return dataclasses.replace(route, rung=stepped_up(rung), unfinished=0)
|
||||
if unfinished >= UNFINISHED_PER_STEP or (escalated_at is not None and below_cap(anchor, route, rung)):
|
||||
return one_rung_up(route, rung, route.escalated_at if escalated_at is None else escalated_at)
|
||||
return dataclasses.replace(route, rung=rung, unfinished=unfinished)
|
||||
|
||||
|
||||
def stepped_by_ruling(anchor: Rung, route: Route, bundled: int, escalated_at: int | None) -> Route:
|
||||
"""The route after the judge's interrupt or quoted answer, its arguments as stepped's: unchanged without an escalation; with one, taken_in's rung, one rung up while that is below escalation_cap. Neither is an unfinished verdict, so the count of those restarts only with a step."""
|
||||
if escalated_at is None:
|
||||
return route
|
||||
rung = taken_in(anchor, route, bundled)
|
||||
return one_rung_up(route, rung, escalated_at) if below_cap(anchor, route, rung) else dataclasses.replace(route, rung=rung)
|
||||
|
||||
|
||||
def one_rung_up(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)
|
||||
|
||||
|
||||
def below_cap(anchor: Rung, route: Route, rung: Rung) -> bool:
|
||||
"""Whether an escalation trigger may take the worker one rung up from rung without the human's yes: rung is below escalation_cap, two rungs above item_rung."""
|
||||
return position(rung) < position(escalation_cap(anchor, route))
|
||||
|
||||
|
||||
def taken_in(anchor: Rung, route: Route, bundled: int) -> Rung:
|
||||
"""kept_rung, raised to the rung bundled picks from anchor; bundled is the highest L the judge saw the worker take into the chunk, 0 for none."""
|
||||
return highest(kept_rung(anchor, route), worker_rung(anchor, bundled)) if bundled else kept_rung(anchor, route)
|
||||
|
||||
@@ -121,12 +121,16 @@ TODO = "## Items\n\n| ID | Release | Exempt | Item | L | E | I | R | S | Moves |
|
||||
CHEAP = TODO.replace("| 4 | 2 | 3 | 7 |", "| 2 | 1 | 2 | 3 |")
|
||||
|
||||
|
||||
# Waits for the interrupt's prompt before typing the answer, since loop-claude drops what was typed before it.
|
||||
ANSWERING = ("Answer (", lambda: None)
|
||||
|
||||
|
||||
def worker(**step):
|
||||
return {"role": "worker", **step}
|
||||
|
||||
|
||||
def judge(interrupt=False, finished=False, evidence="working", question="", bundled=0, bundled_escape_and_impact=0, escalation="", **step):
|
||||
verdict = {"answer": "", "bundled": bundled, "bundled_escape_and_impact": bundled_escape_and_impact, "escalation": escalation, "evidence": evidence, "finished": finished, "interrupt": interrupt, "question": question}
|
||||
def judge(interrupt=False, finished=False, evidence="working", question="", bundled=0, bundled_escape_and_impact=0, escalation="", release_ready=False, **step):
|
||||
verdict = {"answer": "", "bundled": bundled, "bundled_escape_and_impact": bundled_escape_and_impact, "escalation": escalation, "evidence": evidence, "finished": finished, "interrupt": interrupt, "question": question, "release_ready": release_ready}
|
||||
return {"role": "judge", "verdict": verdict, **step}
|
||||
|
||||
|
||||
@@ -196,7 +200,7 @@ class Checkout:
|
||||
self.git("add", "todo.md")
|
||||
self.git("commit", "--quiet", "-m", "plan")
|
||||
|
||||
def run(self, steps, argv=(TASK,), cwd=None, terminal_input=None, stdout_on_terminal=True, before_typing=None):
|
||||
def run(self, steps, argv=(TASK,), cwd=None, terminal_input=None, stdout_on_terminal=True, before_typing=None, typed_early=""):
|
||||
for name in ("FAKE_CLAUDE_LOG", "LOOP_TEST_LOG"):
|
||||
pathlib.Path(self.env[name]).unlink(missing_ok=True)
|
||||
pathlib.Path(self.env["FAKE_CLAUDE_SCENARIO"]).write_text(json.dumps(steps))
|
||||
@@ -206,7 +210,7 @@ class Checkout:
|
||||
done = subprocess.run(command, capture_output=True, cwd=cwd, env=self.env, stdin=subprocess.DEVNULL, text=True, timeout=60)
|
||||
code, stdout, stderr = done.returncode, done.stdout, done.stderr
|
||||
else:
|
||||
code, stdout, stderr = self.run_on_terminal(command, cwd, terminal_input, stdout_on_terminal, before_typing)
|
||||
code, stdout, stderr = self.run_on_terminal(command, cwd, terminal_input, stdout_on_terminal, before_typing, typed_early)
|
||||
started = lines(pathlib.Path(self.env["LOOP_TEST_LOG"]))
|
||||
return Run(
|
||||
calls=lines(pathlib.Path(self.env["FAKE_CLAUDE_LOG"])),
|
||||
@@ -217,8 +221,8 @@ class Checkout:
|
||||
stdout=stdout,
|
||||
)
|
||||
|
||||
def run_on_terminal(self, command, cwd, typed, stdout_on_terminal, before_typing):
|
||||
"""Types the input at once, or once stderr shows before_typing's text and its callback has run."""
|
||||
def run_on_terminal(self, command, cwd, typed, stdout_on_terminal, before_typing, typed_early):
|
||||
"""Types typed_early at once, then the input at once, or once stderr shows before_typing's text and its callback has run."""
|
||||
controller, terminal = pty.openpty()
|
||||
with tempfile.TemporaryFile() as stderr, tempfile.TemporaryFile() as stdout:
|
||||
try:
|
||||
@@ -226,6 +230,7 @@ class Checkout:
|
||||
finally:
|
||||
os.close(terminal)
|
||||
try:
|
||||
os.write(controller, typed_early.encode())
|
||||
prompt, callback = before_typing or (None, None)
|
||||
if prompt is None:
|
||||
os.write(controller, typed.encode())
|
||||
@@ -366,7 +371,7 @@ class Cycles(unittest.TestCase):
|
||||
self.assertIsNone(argument(workers[1], "--name"))
|
||||
self.assertEqual(argument(workers[2], "--session-id"), session)
|
||||
self.assertTrue(argument(workers[0], "-p").startswith(f"{TASK}\n\nContinue any open draft PR"))
|
||||
self.assertTrue(argument(workers[0], "-p").endswith("The chunk's todo.md items, or else the task above, set its scope. The goals below choose between ways to deliver that scope, and never widen it.\n\nFrom README.md:\n## Goals\n1. Work.\n\n## Audience\nMe."))
|
||||
self.assertTrue(argument(workers[0], "-p").endswith("The chunk's todo.md items, or else the task above, set its scope. The goals below, " 'which rank after code health (~/.claude/CLAUDE.md → "Shared goal") unless README.md voids it' ", choose between ways to deliver that scope, and never widen it.\n\nFrom README.md:\n## Goals\n1. Work.\n\n## Audience\nMe."))
|
||||
self.assertIn("main or master", argument(workers[0], "-p"))
|
||||
self.assertNotIn(TASK, argument(workers[1], "-p"))
|
||||
self.assertIn("Even then, it is finished only once every answer the human typed in it", argument(workers[1], "-p"))
|
||||
@@ -455,8 +460,26 @@ class Cycles(unittest.TestCase):
|
||||
("claude-opus-5-5", "high"),
|
||||
])
|
||||
outcomes = sorted(verdict.removeprefix(f"Task: {TASK}\n\n") for verdict in checkout.archived().values())
|
||||
self.assertIn("<UTC> Verdict: unfinished\n\nEvidence:\n> I ask for a higher rung.\n\nEscalation:\n> Stability round 2: a 🔴.\n\nJudge: judge-model\nWorker: claude-opus-5-5 at high effort, routed by item 4's L of 4 and E + I of 5\n\n<UTC> Stepped up\n\nWorker: claude-opus-5-5 at xhigh effort, routed by item 4's L of 4 and E + I of 5\n", outcomes)
|
||||
self.assertIn("<UTC> Verdict: unfinished\n\nEvidence:\n> I ask for a higher rung.\n\nJudge: judge-model\nWorker: claude-opus-5-5 at xhigh effort, routed by item 4's L of 4 and E + I of 5\n", outcomes)
|
||||
self.assertIn("<UTC> Verdict: unfinished\n\nEvidence:\n> I ask for a higher rung.\n\nEscalation:\n> Stability round 2: a 🔴.\n\nJudge: judge-model\nWorker: claude-opus-5-5 at high effort, routed by item 4's L of 4 and E + I of 5\n\n<UTC> Stepped up\n\nWorker: claude-opus-5-5 at xhigh effort, routed by item 4's L of 4 and E + I of 5, escalated at transcript entry 4\n", outcomes)
|
||||
self.assertIn("<UTC> Verdict: unfinished\n\nEvidence:\n> I ask for a higher rung.\n\nJudge: judge-model\nWorker: claude-opus-5-5 at xhigh effort, routed by item 4's L of 4 and E + I of 5, escalated at transcript entry 4\n", outcomes)
|
||||
|
||||
def test_steps_the_worker_up_once_as_the_judge_interrupts_when_the_run_also_cites_an_escalation_trigger(self):
|
||||
checkout = Checkout(self)
|
||||
checkout.env["LOOP_CLAUDE_WORKER_MODEL"] = "claude-opus-5-5"
|
||||
checkout.commit_plan(TODO)
|
||||
cited = "Stability round 2: a 🔴."
|
||||
run = checkout.run([
|
||||
worker(say=f"{cited} Trigger 3 fired; I ask for a higher rung. Shall I use A or B?"), judge(interrupt=True, evidence="Shall I use A or B?", question="A or B?", escalation=cited),
|
||||
interrupt(type="B"), judge(evidence="B", escalation="Trigger 3 fired; I ask for a higher rung."),
|
||||
worker(say="carrying on"),
|
||||
], terminal_input="/talk\n", before_typing=ANSWERING)
|
||||
self.assertEqual(run.code, 130)
|
||||
self.assertEqual(run.roles(), ["worker", "judge", "interrupt", "judge", "worker", "judge"])
|
||||
self.assertEqual([(argument(call, "--model"), argument(call, "--effort")) for call in run.calls if call["role"] != "judge"], [("claude-opus-5-5", "high"), ("claude-opus-5-5", "xhigh"), ("claude-opus-5-5", "xhigh")])
|
||||
outcomes = sorted(verdict.removeprefix(f"Task: {TASK}\n\n") for verdict in checkout.archived().values())
|
||||
self.assertIn("<UTC> Stepped up\n\nWorker: claude-opus-5-5 at xhigh effort, routed by item 4's L of 4 and E + I of 5, escalated at transcript entry 4\n", "".join(outcomes))
|
||||
self.assertNotIn("at max effort", "".join(outcomes))
|
||||
self.assertIn("Verdict: interrupt\n\nA or B?\n\nEvidence:\n> Shall I use A or B?\n\nEscalation:\n> Stability round 2: a 🔴.\n\nJudge: judge-model\nWorker: claude-opus-5-5 at high effort, routed by item 4's L of 4 and E + I of 5\n\n<UTC> Stepped up\n\nWorker: claude-opus-5-5 at xhigh effort, routed by item 4's L of 4 and E + I of 5, escalated at transcript entry 4\n", "".join(outcomes))
|
||||
|
||||
def test_runs_a_cheap_items_worker_below_the_projects_rung_with_its_reviewers_and_judge_on_it(self):
|
||||
checkout = Checkout(self)
|
||||
@@ -624,7 +647,7 @@ class Interrupt(unittest.TestCase):
|
||||
self.assertEqual(run.stderr.strip().splitlines()[-2:], ["A or B?", "the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun loop-claude on a terminal"])
|
||||
[(copy, verdict)] = checkout.archived().items()
|
||||
self.assertEqual(copy, (checkout.transcripts()[0]).read_text())
|
||||
self.assertEqual(verdict, f"Task: {TASK}\n\n<UTC> Verdict: interrupt\n\nA or B?\n\nEvidence:\n> Shall I use A or B?\n\nJudge: judge-model\n\n<UTC> Stopped: the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun loop-claude on a terminal\n\nWorker: worker-model\n")
|
||||
self.assertEqual(verdict, f"Task: {TASK}\n\n<UTC> Verdict: interrupt\n\nA or B?\n\nEvidence:\n> Shall I use A or B?\n\nJudge: judge-model\nWorker: worker-model\n\n<UTC> Stopped: the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun loop-claude on a terminal\n\nWorker: worker-model\n")
|
||||
self.assertEqual(stat.S_IMODE((checkout.temp / "deep").stat().st_mode), 0o700)
|
||||
self.assertIn(f"transcript: {checkout.archive() / 'proj'}/", run.stderr)
|
||||
session = argument(run.calls[0], "--session-id")
|
||||
@@ -637,6 +660,17 @@ class Interrupt(unittest.TestCase):
|
||||
self.assertEqual(run.code, 2)
|
||||
self.assertEqual(len(checkout.archived()), 2)
|
||||
|
||||
def test_resumes_the_worker_headless_with_the_answer_typed_at_its_terminal_not_with_keys_typed_before_it(self):
|
||||
checkout = Checkout(self)
|
||||
asked = [worker(say="Shall I use A or B?"), judge(interrupt=True, evidence="Shall I use A or B?", question="A or B?")]
|
||||
run = checkout.run([*asked, worker(say="Using B."), judge(evidence="Using B.")], terminal_input="B\n", before_typing=ANSWERING, typed_early="stray\n")
|
||||
self.assertEqual(run.code, 130)
|
||||
self.assertEqual(run.roles(), ["worker", "judge", "worker", "judge", "worker"])
|
||||
self.assertIn("A or B?\nAnswer (/talk opens claude, Enter stops the loop): ", run.stderr)
|
||||
self.assertEqual(argument(run.calls[2], "--resume"), argument(run.calls[0], "--session-id"))
|
||||
self.assertIn("[human] B\n\nUsing B.", run.calls[3]["stdin"])
|
||||
self.assertNotIn("stray", run.calls[3]["stdin"])
|
||||
|
||||
def test_hands_the_terminal_over_and_exits_2_when_nothing_is_typed(self):
|
||||
checkout = Checkout(self)
|
||||
checkout.git("commit", "--allow-empty", "--quiet", "-m", "start")
|
||||
@@ -645,7 +679,7 @@ class Interrupt(unittest.TestCase):
|
||||
checkout.claude_json().chmod(0o644)
|
||||
asked = [worker(say="Shall I use A or B?"), judge(interrupt=True, evidence="Shall I use A or B?", question="A or B?")]
|
||||
(checkout.root / "sub").mkdir()
|
||||
run = checkout.run([*asked, interrupt(type="B"), judge(evidence="B"), worker()], cwd=checkout.root / "sub", terminal_input="")
|
||||
run = checkout.run([*asked, interrupt(type="B"), judge(evidence="B"), worker()], cwd=checkout.root / "sub", terminal_input="/talk\n", before_typing=ANSWERING)
|
||||
self.assertEqual(run.code, 130)
|
||||
self.assertEqual(run.roles(), ["worker", "judge", "interrupt", "judge", "worker", "judge"])
|
||||
handed = run.calls[2]["argv"]
|
||||
@@ -663,13 +697,13 @@ class Interrupt(unittest.TestCase):
|
||||
|
||||
for transcript in checkout.transcripts():
|
||||
transcript.unlink()
|
||||
run = checkout.run([*asked, interrupt()], terminal_input="")
|
||||
run = checkout.run([*asked, interrupt()], terminal_input="/talk\n", before_typing=ANSWERING)
|
||||
self.assertEqual((run.code, run.roles()), (2, ["worker", "judge", "interrupt"]))
|
||||
self.assertEqual(run.stderr.strip().splitlines()[-1], "the human is needed to answer the question above, but the interrupt ended with nothing typed")
|
||||
self.assertTrue(run.stderr.strip().endswith("the human is needed to answer the question above, but the interrupt ended with nothing typed"))
|
||||
|
||||
run = checkout.run([worker(say="A or B?"), judge(interrupt=True, evidence="A or B?", question="A or B?", vanish=True)], terminal_input="")
|
||||
run = checkout.run([worker(say="A or B?"), judge(interrupt=True, evidence="A or B?", question="A or B?", vanish=True)], terminal_input="/talk\n", before_typing=ANSWERING)
|
||||
self.assertEqual((run.code, run.roles()), (1, ["worker", "judge"]))
|
||||
self.assertEqual(run.stderr.strip().splitlines()[-1], "could not start claude for the interrupt: No such file or directory")
|
||||
self.assertTrue(run.stderr.strip().endswith("could not start claude for the interrupt: No such file or directory"))
|
||||
|
||||
def test_says_why_the_trust_file_cannot_be_read_and_leaves_it_as_it_was(self):
|
||||
checkout = Checkout(self)
|
||||
@@ -687,14 +721,14 @@ class Interrupt(unittest.TestCase):
|
||||
checkout.claude_json().unlink(missing_ok=True)
|
||||
if text is not None:
|
||||
checkout.claude_json().write_text(text)
|
||||
run = checkout.run(asked, terminal_input="")
|
||||
run = checkout.run(asked, terminal_input="/talk\n", before_typing=ANSWERING)
|
||||
self.assertEqual(run.code, 2)
|
||||
self.assertIn(f"could not read {checkout.claude_json()}: {said}\n", run.stderr)
|
||||
self.assertEqual(checkout.claude_json().read_text() if checkout.claude_json().exists() else None, text)
|
||||
|
||||
trusted = json.dumps({"projects": {str(checkout.root): {"hasTrustDialogAccepted": True}}})
|
||||
checkout.claude_json().write_text(trusted)
|
||||
run = checkout.run(asked, terminal_input="")
|
||||
run = checkout.run(asked, terminal_input="/talk\n", before_typing=ANSWERING)
|
||||
self.assertNotIn(str(checkout.claude_json()), run.stderr)
|
||||
self.assertNotIn("trusted for the interrupt", run.stderr)
|
||||
self.assertEqual(checkout.claude_json().read_text(), trusted)
|
||||
@@ -707,7 +741,7 @@ class Interrupt(unittest.TestCase):
|
||||
checkout.run(asked[:2])
|
||||
checkout.home.chmod(0o500)
|
||||
self.addCleanup(checkout.home.chmod, 0o700)
|
||||
run = checkout.run([worker(), *asked[1:]], terminal_input="")
|
||||
run = checkout.run([worker(), *asked[1:]], terminal_input="/talk\n", before_typing=ANSWERING)
|
||||
self.assertEqual(run.code, 2)
|
||||
self.assertIn(f"could not write {checkout.claude_json()}: Permission denied\n", run.stderr)
|
||||
self.assertEqual(checkout.claude_json().read_text(), "{}")
|
||||
@@ -715,7 +749,7 @@ class Interrupt(unittest.TestCase):
|
||||
@unittest.skipIf(os.geteuid() == 0, "root reads an unreadable file")
|
||||
def test_exits_1_when_the_transcript_cannot_be_read_after_the_interrupt(self):
|
||||
checkout = Checkout(self)
|
||||
run = checkout.run([worker(say="A or B?"), judge(interrupt=True, evidence="A or B?", question="A or B?"), interrupt(type="B", unreadable=True)], terminal_input="")
|
||||
run = checkout.run([worker(say="A or B?"), judge(interrupt=True, evidence="A or B?", question="A or B?"), interrupt(type="B", unreadable=True)], terminal_input="/talk\n", before_typing=ANSWERING)
|
||||
self.assertEqual((run.code, run.roles()), (1, ["worker", "judge", "interrupt"]))
|
||||
self.assertRegex(run.stderr.strip().splitlines()[-1], r"^could not tell whether you typed anything: could not read the transcript .*\.jsonl: Permission denied$")
|
||||
|
||||
|
||||
@@ -12,20 +12,21 @@ import sys
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
import unittest.mock
|
||||
import uuid
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from routing_figures import archive
|
||||
from loop_claude.project import checkout, model_choice, records
|
||||
from git_repo import DefaultPlan
|
||||
from chunk_pick import DefaultPlan, LastCut
|
||||
from loop_claude.effects import Effects, PYTHON_TIMEOUT, run_python
|
||||
from claude_code import entries, reply, session
|
||||
from failure import Failure
|
||||
from loop_claude.cycle.judge import Finished, Interrupt, QuotedAnswer, Unfinished, verdict_from
|
||||
from loop_claude.cycle import interrupt, judge, prompts, retry, run, states, worker
|
||||
from model_routing import ladder
|
||||
from model_routing.ladder import LADDER, Rung
|
||||
from todo_table import LastCut
|
||||
from claude_code.reply import Limited
|
||||
from loop_claude.loop import main, reload, routing_check
|
||||
from transcript_archive import outcomes, write
|
||||
@@ -61,6 +62,7 @@ class FakeEffects:
|
||||
return Effects(
|
||||
claude=lambda args, cwd, stdin: self.answer("claude", (args, stdin)),
|
||||
claude_on_terminal=self.on_terminal_claude,
|
||||
discard_typed=lambda: self.calls.append(("discard_typed", None)),
|
||||
execv=self.execv,
|
||||
git=lambda args, cwd: self.answer("git", args),
|
||||
input=lambda prompt: self.answer("input", prompt),
|
||||
@@ -105,16 +107,19 @@ def ran(stdout="", code=0, stderr=""):
|
||||
return subprocess.CompletedProcess([], code, stdout, stderr)
|
||||
|
||||
|
||||
def judged(verdict, evidence="working", answer=""):
|
||||
reply = {"answer": answer, "bundled": 0, "bundled_escape_and_impact": 0, "escalation": "", "evidence": evidence, "finished": verdict == "finished", "interrupt": verdict == "interrupt", "question": "Which one?" if verdict in ("interrupt", "quoted") else ""}
|
||||
def judged(verdict, evidence="working", answer="", escalation="", release_ready=False):
|
||||
reply = {"answer": answer, "bundled": 0, "bundled_escape_and_impact": 0, "escalation": escalation, "evidence": evidence, "finished": verdict == "finished", "interrupt": verdict == "interrupt", "question": "Which one?" if verdict in ("interrupt", "quoted") else "", "release_ready": release_ready}
|
||||
return ran(json.dumps({"structured_output": reply}))
|
||||
|
||||
|
||||
class Worker:
|
||||
"""A worker claude: writes a line to the session's transcript, then streams a result."""
|
||||
|
||||
def __init__(self, home):
|
||||
def __init__(self, home, prompted=False, text="working"):
|
||||
self.home = home
|
||||
# Whether it records its -p prompt in the transcript first, as claude does.
|
||||
self.prompted = prompted
|
||||
self.text = text
|
||||
|
||||
def __call__(self, args):
|
||||
flag = "--session-id" if "--session-id" in args else "--resume"
|
||||
@@ -123,7 +128,9 @@ class Worker:
|
||||
with open(path, "a") as handle:
|
||||
if flag == "--session-id":
|
||||
handle.write(json.dumps({"type": "custom-title"}) + "\n" + json.dumps({"type": "queue-operation", "timestamp": str(uuid7())}) + "\n")
|
||||
handle.write(json.dumps(assistant({"type": "text", "text": "working"})) + "\n")
|
||||
if self.prompted:
|
||||
handle.write(json.dumps({**human(args[args.index("-p") + 1]), "promptSource": "sdk"}) + "\n")
|
||||
handle.write(json.dumps(assistant({"type": "text", "text": self.text})) + "\n")
|
||||
return Streamed(0)
|
||||
|
||||
|
||||
@@ -139,6 +146,9 @@ class Streamed:
|
||||
return self.code
|
||||
|
||||
|
||||
TYPED = states.TypedAnswer("Which one?", "Use B.")
|
||||
|
||||
|
||||
class Transitions(unittest.TestCase):
|
||||
def test_each_state_moves_on_its_events_and_only_on_them(self):
|
||||
answered = states.Ruled(QuotedAnswer("e", "Which one?", "A."))
|
||||
@@ -154,16 +164,21 @@ class Transitions(unittest.TestCase):
|
||||
(states.Judging("/t", 3), states.Ruled(Finished("e")), states.Closing("/t", Finished("e"))),
|
||||
(states.Judging("/t"), states.Ruled(Unfinished("e")), states.Closing("/t", Unfinished("e"))),
|
||||
(states.Judging("/t", 3), states.Ruled(Unfinished("e")), states.Closing("/t", Unfinished("e"))),
|
||||
(states.Interrupting("/t", Interrupt("e", "q")), states.HumanAnswered(), states.Judging("/t")),
|
||||
(states.Interrupting("/t", Interrupt("e", "q"), 3), states.HumanAnswered(), states.Judging("/t", 3)),
|
||||
(states.Interrupting("/t", Interrupt("e", "q")), states.TalkChosen(), states.Talking("/t")),
|
||||
(states.Interrupting("/t", Interrupt("e", "q"), 3), states.TalkChosen(), states.Talking("/t", 3)),
|
||||
(states.Talking("/t"), states.HumanTalked(), states.Judging("/t")),
|
||||
(states.Talking("/t", 3), states.HumanTalked(), states.Judging("/t", 3)),
|
||||
(states.Interrupting("/t", Interrupt("e", "q")), states.HumanTyped(TYPED), states.Working(TYPED)),
|
||||
(states.Interrupting("/t", Interrupt("e", "q"), 3), states.HumanTyped(TYPED), states.Working(TYPED, 3)),
|
||||
(states.Working(TYPED, 3), states.WorkerRan("/t"), states.Judging("/t", 3)),
|
||||
(states.Closing("/t", Finished("e")), states.Archived(), states.Ended(Finished("e"))),
|
||||
(states.Closing("/t", Unfinished("e")), states.Archived(), states.Ended(Unfinished("e"))),
|
||||
)
|
||||
for state, event, after in legal:
|
||||
with self.subTest(state=state, event=event):
|
||||
self.assertEqual(states.transition(state, event), after)
|
||||
every_state = (states.Working(), states.Working(QuotedAnswer("e", "Which one?", "A."), 3), states.Judging("/t"), states.Judging("/t", 3), states.Interrupting("/t", Interrupt("e", "q")), states.Interrupting("/t", Interrupt("e", "q"), 3), states.Closing("/t", Finished("e")), states.Ended(Finished("e")))
|
||||
every_event = (states.WorkerRan("/t"), states.Ruled(Interrupt("e", "Which one?")), answered, states.Ruled(Finished("e")), states.Ruled(Unfinished("e")), states.HumanAnswered(), states.Archived())
|
||||
every_state = (states.Working(), states.Working(QuotedAnswer("e", "Which one?", "A."), 3), states.Working(TYPED, 3), states.Judging("/t"), states.Judging("/t", 3), states.Interrupting("/t", Interrupt("e", "q")), states.Interrupting("/t", Interrupt("e", "q"), 3), states.Talking("/t"), states.Talking("/t", 3), states.Closing("/t", Finished("e")), states.Ended(Finished("e")))
|
||||
every_event = (states.WorkerRan("/t"), states.Ruled(Interrupt("e", "Which one?")), answered, states.Ruled(Finished("e")), states.Ruled(Unfinished("e")), states.TalkChosen(), states.HumanTalked(), states.HumanTyped(TYPED), states.Archived())
|
||||
for state in every_state:
|
||||
for event in every_event:
|
||||
if (state, event) not in [(state, event) for state, event, _ in legal]:
|
||||
@@ -194,41 +209,42 @@ class Cycles(unittest.TestCase):
|
||||
|
||||
def test_a_finished_chunk_is_archived_and_its_session_deleted(self):
|
||||
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("finished")])
|
||||
self.assertEqual(run.run_cycle(self.cycle(fake)), Finished("working"))
|
||||
self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Finished("working"))
|
||||
self.assertEqual(self.archived_outcomes(), ["Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: finished\n\nEvidence:\n> working\n\nJudge: judge-model\nWorker: worker-model\n"])
|
||||
self.assertIsNone(session.transcript_file(self.session))
|
||||
|
||||
def test_a_fresh_worker_reads_the_preflights_facts_and_a_resumed_one_does_not(self):
|
||||
worker = Worker(self.paths.claude_code_transcripts.parent)
|
||||
fake = FakeEffects(streams=[worker, worker], claude=[judged("unfinished"), judged("finished")])
|
||||
self.assertEqual(run.run_cycle(self.cycle(fake)), Unfinished("working"))
|
||||
self.assertEqual(run.run_cycle(self.cycle(fake, unfinished_evidence="working")), Finished("working"))
|
||||
self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Unfinished("working", entries_read=3))
|
||||
self.assertEqual(run.run_cycle(self.cycle(fake, unfinished_evidence="working")).verdict, Finished("working"))
|
||||
fresh, resumed = (args[args.index("-p") + 1] for args in fake.made("stream_claude"))
|
||||
self.assertIn("- A preflight fact.", fresh)
|
||||
self.assertNotIn("- A preflight fact.", resumed)
|
||||
|
||||
def test_a_worker_is_handed_the_projects_rung_its_own_and_its_reviewers_in_its_environment(self):
|
||||
def test_a_worker_is_handed_the_projects_rung_its_own_and_its_reviews_e_plus_i_in_its_environment(self):
|
||||
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("finished")])
|
||||
cycle = dataclasses.replace(self.cycle(fake), anchor=Rung("claude-opus-5-5", "medium"), route=Route(Rung("claude-haiku-5-5", "max"), 163, 1, 5))
|
||||
self.assertEqual(run.run_cycle(cycle), Finished("working"))
|
||||
self.assertEqual(fake.worker_environments, [{"LOOP_CLAUDE_PROJECT_RUNG": "claude-opus-5-5 at medium effort", "LOOP_CLAUDE_WORKER_RUNG": "claude-haiku-5-5 at max effort", "LOOP_CLAUDE_REVIEWER_RUNG": "claude-opus-5-5 at high effort"}])
|
||||
self.assertEqual(run.run_cycle(cycle).verdict, Finished("working"))
|
||||
self.assertEqual(fake.worker_environments, [{"LOOP_CLAUDE_PROJECT_RUNG": "claude-opus-5-5 at medium effort", "LOOP_CLAUDE_WORKER_RUNG": "claude-haiku-5-5 at max effort", "LOOP_CLAUDE_ESCAPE_AND_IMPACT": "5"}])
|
||||
|
||||
def test_the_claude_an_interrupt_resumes_is_handed_the_same_rungs_as_the_worker(self):
|
||||
def answer(args):
|
||||
with open(session.transcript_file(self.session), "a") as handle:
|
||||
handle.write(json.dumps(human("the second")) + "\n")
|
||||
return 0
|
||||
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("interrupt"), judged("finished")], on_terminal_claude=[answer], git=[ran()])
|
||||
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("interrupt"), judged("finished")], inputs=["/talk"], on_terminal_claude=[answer], git=[ran()])
|
||||
cycle = dataclasses.replace(self.cycle(fake), anchor=Rung("claude-opus-5-5", "medium"), route=Route(Rung("claude-haiku-5-5", "max"), 163, 1, 5))
|
||||
self.assertEqual(run.run_cycle(cycle), Finished("working"))
|
||||
with contextlib.redirect_stderr(io.StringIO()):
|
||||
self.assertEqual(run.run_cycle(cycle).verdict, Finished("working"))
|
||||
self.assertEqual(fake.terminal_environments, fake.worker_environments)
|
||||
self.assertEqual(fake.terminal_environments[0]["LOOP_CLAUDE_WORKER_RUNG"], "claude-haiku-5-5 at max effort")
|
||||
|
||||
def test_an_unfinished_chunks_transcript_is_archived_and_the_next_cycle_resumes_its_session_with_the_judges_evidence(self):
|
||||
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 2, claude=[judged("unfinished")] * 2)
|
||||
self.assertEqual(run.run_cycle(self.cycle(fake)), Unfinished("working"))
|
||||
self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Unfinished("working", entries_read=3))
|
||||
self.assertTrue(session.transcript_file(self.session))
|
||||
self.assertEqual(run.run_cycle(self.cycle(fake, unfinished_evidence="working")), Unfinished("working"))
|
||||
self.assertEqual(run.run_cycle(self.cycle(fake, unfinished_evidence="working")).verdict, Unfinished("working", entries_read=4))
|
||||
workers = fake.made("stream_claude")
|
||||
self.assertIn("--session-id", workers[0])
|
||||
self.assertIn("--resume", workers[1])
|
||||
@@ -246,7 +262,7 @@ class Cycles(unittest.TestCase):
|
||||
unfilled = ran(json.dumps({"structured_output": {"interrupt": False}}))
|
||||
misquoted = judged("finished", evidence="never said")
|
||||
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[unfilled, misquoted, judged("finished")])
|
||||
self.assertEqual(run.run_cycle(self.cycle(fake)), Finished("working"))
|
||||
self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Finished("working"))
|
||||
stamp = "2026-09-21T14:13:20Z"
|
||||
self.assertEqual(self.archived_outcomes(), [
|
||||
"Task: Do it.\n\n"
|
||||
@@ -279,7 +295,7 @@ class Cycles(unittest.TestCase):
|
||||
(folder / "custom-title.json").write_text("first")
|
||||
(folder.parent / f"{self.session.id}.orphaned-1.jsonl").write_text("o\n")
|
||||
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 3, claude=[judged("unfinished"), judged("finished"), judged("unfinished")])
|
||||
self.assertEqual(run.run_cycle(self.cycle(fake)), Unfinished("working"))
|
||||
self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Unfinished("working", entries_read=3))
|
||||
[chunk] = self.archive.iterdir()
|
||||
kept = chunk / "session" / str(self.session.id)
|
||||
self.assertEqual((chunk / "session" / f"{self.session.id}.orphaned-1.jsonl").read_text(), "o\n")
|
||||
@@ -287,7 +303,7 @@ class Cycles(unittest.TestCase):
|
||||
with open(folder / "subagents" / "agent-a.jsonl", "a") as handle:
|
||||
handle.write("more\n")
|
||||
(folder / "custom-title.json").write_text("second")
|
||||
self.assertEqual(run.run_cycle(self.cycle(fake)), Finished("working"))
|
||||
self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Finished("working"))
|
||||
self.assertFalse(folder.exists())
|
||||
self.assertEqual((kept / "subagents" / "agent-a.jsonl").read_text(), "a\nmore\n")
|
||||
self.assertEqual((kept / "subagents" / "workflows" / "journal.jsonl").stat().st_mtime, 0)
|
||||
@@ -295,7 +311,7 @@ class Cycles(unittest.TestCase):
|
||||
self.assertEqual(stat.S_IMODE((kept / "subagents" / "agent-a.jsonl").stat().st_mode), 0o600)
|
||||
folder.mkdir()
|
||||
(folder / "custom-title.json").write_text("third")
|
||||
self.assertEqual(run.run_cycle(self.cycle(fake)), Unfinished("working"))
|
||||
self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Unfinished("working", entries_read=3))
|
||||
[next_chunk] = set(self.archive.iterdir()) - {chunk}
|
||||
self.assertEqual(sorted(path.read_text() for path in (next_chunk / "session" / str(self.session.id)).glob("custom-title.json*")), ["third"])
|
||||
|
||||
@@ -308,14 +324,15 @@ class Cycles(unittest.TestCase):
|
||||
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("unfinished")])
|
||||
self.assertEqual(run.run_cycle(self.cycle(fake)), Stop(1, f"could not archive the transcript: {locked}: Permission denied"))
|
||||
|
||||
def test_an_interrupt_is_archived_answered_and_judged_again(self):
|
||||
def test_an_interrupt_talked_over_in_claude_is_archived_answered_and_judged_again(self):
|
||||
def answer(args):
|
||||
with open(session.transcript_file(self.session), "a") as handle:
|
||||
handle.write(json.dumps(human("the second")) + "\n")
|
||||
return 0
|
||||
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("interrupt"), judged("unfinished")], on_terminal_claude=[answer], git=[ran()])
|
||||
self.assertEqual(run.run_cycle(self.cycle(fake)), Unfinished("working"))
|
||||
self.assertEqual(self.archived_outcomes(), ["Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: interrupt\n\nWhich one?\n\nEvidence:\n> working\n\nJudge: judge-model\n", "Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: unfinished\n\nEvidence:\n> working\n\nJudge: judge-model\nWorker: worker-model\n"])
|
||||
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("interrupt"), judged("unfinished")], inputs=["/talk"], on_terminal_claude=[answer], git=[ran()])
|
||||
with contextlib.redirect_stderr(io.StringIO()):
|
||||
self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Unfinished("working", entries_read=4))
|
||||
self.assertEqual(self.archived_outcomes(), ["Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: interrupt\n\nWhich one?\n\nEvidence:\n> working\n\nJudge: judge-model\nWorker: worker-model\n", "Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: unfinished\n\nEvidence:\n> working\n\nJudge: judge-model\nWorker: worker-model\n"])
|
||||
self.assertIn(str(self.session.id), fake.made("claude_on_terminal")[0])
|
||||
judge_prompts = [stdin for args, stdin in fake.made("claude")]
|
||||
self.assertEqual(len(judge_prompts), 2)
|
||||
@@ -326,16 +343,130 @@ class Cycles(unittest.TestCase):
|
||||
|
||||
def test_a_question_the_records_answer_resumes_the_worker_with_the_answer_three_times_a_cycle(self):
|
||||
answered = judged("quoted", answer="Use *A*.")
|
||||
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 4, claude=[answered] * 4, on_terminal_claude=[0], git=[ran()])
|
||||
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 4, claude=[answered] * 4, inputs=[""])
|
||||
with contextlib.redirect_stderr(io.StringIO()) as said, contextlib.redirect_stdout(io.StringIO()) as printed:
|
||||
self.assertEqual(run.run_cycle(self.cycle(fake, records="From AGENTS.md:\nUse A.")), Stop(2, "the human is needed to answer the question above, but the interrupt ended with nothing typed"))
|
||||
self.assertEqual(run.run_cycle(self.cycle(fake, records="From AGENTS.md:\nUse A.")), Stop(2, "the human is needed to answer the question above, but nothing was typed"))
|
||||
resumed = fake.made("stream_claude")[1]
|
||||
self.assertEqual(resumed[resumed.index("-p") + 1], "Your question: Which one?\n\nREADME.md's Goals and Audience, AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/ or ~/.claude/skills/larv-review/standards/ answers it:\n\nUse *A*.\n\nContinue the task.")
|
||||
self.assertEqual(len(fake.made("stream_claude")), 4)
|
||||
self.assertEqual(printed.getvalue().count("=== README.md's Goals and Audience, AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/ or ~/.claude/skills/larv-review/standards/ answered: Which one? ===\nUse *A*."), 3)
|
||||
self.assertIn("Which one?\n\nREADME.md's Goals and Audience, AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/ or ~/.claude/skills/larv-review/standards/ says:\nUse *A*.\n\nThose files have answered 3 questions this cycle", said.getvalue())
|
||||
quoted = "2026-09-21T14:13:20Z Verdict: quoted answer\n\nWhich one?\n\nREADME.md's Goals and Audience, AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/ or ~/.claude/skills/larv-review/standards/ says:\n> Use *A*.\n\nEvidence:\n> working\n\nJudge: judge-model\n"
|
||||
self.assertEqual(self.archived_outcomes(), [f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: interrupt\n\nWhich one?\n\nREADME.md's Goals and Audience, AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/ or ~/.claude/skills/larv-review/standards/ says:\nUse *A*.\n\nThose files have answered 3 questions this cycle, the most allowed, so this one comes to you.\n\nEvidence:\n> working\n\nJudge: judge-model\n\n2026-09-21T14:13:20Z Stopped: the human is needed to answer the question above, but the interrupt ended with nothing typed\n\nWorker: worker-model\n", *[f"Task: Do it.\n\n{quoted}"] * 3])
|
||||
quoted = "2026-09-21T14:13:20Z Verdict: quoted answer\n\nWhich one?\n\nREADME.md's Goals and Audience, AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/ or ~/.claude/skills/larv-review/standards/ says:\n> Use *A*.\n\nEvidence:\n> working\n\nJudge: judge-model\nWorker: worker-model\n"
|
||||
self.assertEqual(self.archived_outcomes(), [f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: interrupt\n\nWhich one?\n\nREADME.md's Goals and Audience, AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/ or ~/.claude/skills/larv-review/standards/ says:\nUse *A*.\n\nThose files have answered 3 questions this cycle, the most allowed, so this one comes to you.\n\nEvidence:\n> working\n\nJudge: judge-model\nWorker: worker-model\n\n2026-09-21T14:13:20Z Stopped: the human is needed to answer the question above, but nothing was typed\n\nWorker: worker-model\n", *[f"Task: Do it.\n\n{quoted}"] * 3])
|
||||
|
||||
def test_a_quoted_answer_that_cites_an_escalation_trigger_steps_the_worker_up_before_it_resumes_and_archives_the_step(self):
|
||||
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 2, claude=[judged("quoted", answer="Use A.", escalation="working"), judged("finished")])
|
||||
cycle = dataclasses.replace(self.cycle(fake, records="From AGENTS.md:\nUse A."), anchor=Routing.OPUS, route=Route(Routing.SONNET, 179, 2, 5))
|
||||
with contextlib.redirect_stdout(io.StringIO()):
|
||||
concluded = run.run_cycle(cycle)
|
||||
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.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\nJudge: judge-model\nWorker: {Route(Routing.SONNET, 179, 2, 5)}\n"
|
||||
stepped = f"Stepped up\n\nWorker: {Route(Routing.OPUS, 179, 2, 5, escalated_at=3)}\n"
|
||||
kept = "".join(self.archived_outcomes())
|
||||
self.assertIn(f"Z {answered}\n20", kept)
|
||||
self.assertIn(f"Z {stepped}", kept)
|
||||
|
||||
def test_a_quoted_answer_past_the_cap_archives_the_escalation_it_carried_with_the_interrupt_and_steps_up(self):
|
||||
steps = [judged("quoted", answer="Use A.")] * 3 + [judged("quoted", answer="Use A.", escalation="working")]
|
||||
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 4, claude=steps, inputs=[""])
|
||||
cycle = dataclasses.replace(self.cycle(fake, records="From AGENTS.md:\nUse A."), anchor=Routing.OPUS, route=Route(Routing.SONNET, 179, 2, 5))
|
||||
with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):
|
||||
self.assertEqual(run.run_cycle(cycle), Stop(2, "the human is needed to answer the question above, but nothing was typed"))
|
||||
kept = "".join(self.archived_outcomes())
|
||||
self.assertIn(f"Evidence:\n> working\n\nEscalation:\n> working\n\nJudge: judge-model\nWorker: {Route(Routing.SONNET, 179, 2, 5)}\n", kept)
|
||||
self.assertIn(f"Stepped up\n\nWorker: {Route(Routing.OPUS, 179, 2, 5, escalated_at=6)}\n", kept)
|
||||
|
||||
def test_a_ruling_steps_the_route_only_on_an_escalation_from_the_rung_its_bundled_l_picks(self):
|
||||
cycle = dataclasses.replace(self.cycle(FakeEffects()), anchor=Routing.OPUS, route=Route(Routing.OPUS, 3, 3, 4))
|
||||
for ruling in (Interrupt("e", "q", entries_read=3), QuotedAnswer("e", "q", "A.", entries_read=3)):
|
||||
with self.subTest(ruling=ruling):
|
||||
self.assertEqual(run.escalated(cycle, states.Ruled(ruling)), cycle)
|
||||
stepped = run.escalated(cycle, states.Ruled(Interrupt("e", "q", "round 2: 🔴", 4, entries_read=3)))
|
||||
self.assertEqual((stepped.route, stepped.stepped_from), (Route(Routing.XHIGH, 3, 3, 4, escalated_at=3), cycle.route))
|
||||
|
||||
def test_an_escalation_after_an_interrupt_stepped_the_worker_steps_it_again_in_the_same_cycle(self):
|
||||
streams = [Worker(self.paths.claude_code_transcripts.parent, text="round 2: 🔴"), Worker(self.paths.claude_code_transcripts.parent), Worker(self.paths.claude_code_transcripts.parent)]
|
||||
rulings = [judged("interrupt", evidence="round 2: 🔴", escalation="round 2: 🔴"), judged("quoted", answer="Use A.", escalation="working"), judged("finished")]
|
||||
fake = FakeEffects(streams=streams, claude=rulings, inputs=["Use B."])
|
||||
cycle = dataclasses.replace(self.cycle(fake, records="From AGENTS.md:\nUse A."), anchor=Routing.OPUS, route=Route(Routing.SONNET, 179, 2, 5))
|
||||
with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):
|
||||
concluded = run.run_cycle(cycle)
|
||||
self.assertEqual(concluded.route, Route(Routing.HIGH, 179, 2, 5, escalated_at=4))
|
||||
self.assertEqual([args[args.index("--effort") + 1] for args in fake.made("stream_claude")], ["high", "medium", "high"])
|
||||
|
||||
def test_an_escalation_quoted_from_before_the_workers_last_step_up_steps_nothing_and_a_later_one_reaches_the_verdict(self):
|
||||
for escalation, verdict in (("round 2: 🔴", Unfinished("working", entries_read=4)), ("working", Unfinished("working", 0, "working", entries_read=4))):
|
||||
with self.subTest(escalation=escalation):
|
||||
self.session = session.session_named(f"A proj {escalation} loop-claude", self.paths.claude_code_transcripts)
|
||||
streams = [Worker(self.paths.claude_code_transcripts.parent, text="round 2: 🔴"), Worker(self.paths.claude_code_transcripts.parent)]
|
||||
rulings = [judged("interrupt", evidence="round 2: 🔴", escalation="round 2: 🔴"), judged("unfinished", escalation=escalation)]
|
||||
fake = FakeEffects(streams=streams, claude=rulings, inputs=["Use B."])
|
||||
cycle = dataclasses.replace(self.cycle(fake), anchor=Routing.OPUS, route=Route(Routing.SONNET, 179, 2, 5))
|
||||
with contextlib.redirect_stderr(io.StringIO()):
|
||||
concluded = run.run_cycle(cycle)
|
||||
self.assertEqual(concluded, run.Concluded(verdict, Route(Routing.OPUS, 179, 2, 5, escalated_at=3)))
|
||||
|
||||
def test_an_answer_typed_at_the_terminal_resumes_the_worker_headless_and_the_judge_reads_it_as_the_humans(self):
|
||||
worker = Worker(self.paths.claude_code_transcripts.parent, prompted=True)
|
||||
fake = FakeEffects(streams=[worker, worker], claude=[judged("interrupt"), judged("unfinished")], inputs=["Use B."])
|
||||
with contextlib.redirect_stderr(io.StringIO()) as said:
|
||||
self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Unfinished("working", entries_read=6))
|
||||
self.assertIn("\nWhich one?\n", said.getvalue())
|
||||
self.assertEqual(fake.made("claude_on_terminal"), [])
|
||||
resumed = fake.made("stream_claude")[1]
|
||||
self.assertEqual(resumed[resumed.index("--resume") + 1], str(self.session.id))
|
||||
typed = resumed[resumed.index("-p") + 1]
|
||||
self.assertEqual(prompts.typed_answer(typed).answer, "Use B.")
|
||||
self.assertIn("Which one?", typed)
|
||||
self.assertIn("Continue the task. The chunk is finished only once every answer the human typed in it", typed)
|
||||
judge_prompts = [stdin for args, stdin in fake.made("claude")]
|
||||
self.assertRegex(judge_prompts[1], r"(?s)\[loop\] Your question was: Which one\?.*\n\n\[human\] Use B\.\n\nworking\n\nDecide whether")
|
||||
self.assertNotIn("The human answered", judge_prompts[1])
|
||||
|
||||
def test_an_interrupt_that_steps_the_worker_up_names_its_new_rung_in_the_prompt_that_resumes_it_with_the_typed_answer(self):
|
||||
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 2, claude=[judged("interrupt", escalation="working"), judged("finished")], inputs=["Use B."])
|
||||
cycle = dataclasses.replace(self.cycle(fake), anchor=Routing.OPUS, route=Route(Routing.SONNET, 179, 2, 5))
|
||||
with contextlib.redirect_stderr(io.StringIO()):
|
||||
concluded = run.run_cycle(cycle)
|
||||
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"])
|
||||
typed = resumed[resumed.index("-p") + 1]
|
||||
self.assertIn("Your request for a higher rung went through: loop-claude runs you on claude-opus-5-5 at medium effort.", typed)
|
||||
self.assertIn(" Launch each reviewer with the Agent tool set to model opus, effort high, the rung item 179's E + I of 5 picks.", typed)
|
||||
self.assertNotIn("went through", first[first.index("-p") + 1])
|
||||
|
||||
def test_a_typed_answer_past_the_quoted_answers_cap_reaches_the_worker_with_its_own_question(self):
|
||||
worker = Worker(self.paths.claude_code_transcripts.parent)
|
||||
fake = FakeEffects(streams=[worker] * 5, claude=[judged("quoted", answer="Use A.")] * 4 + [judged("finished")], inputs=["Use B."])
|
||||
with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):
|
||||
self.assertEqual(run.run_cycle(self.cycle(fake, records="From AGENTS.md:\nUse A.")).verdict, Finished("working"))
|
||||
typed = fake.made("stream_claude")[4]
|
||||
self.assertIn("Your question was: Which one?\n\nContinue the task.", typed[typed.index("-p") + 1])
|
||||
self.assertNotIn("Those files have answered", typed[typed.index("-p") + 1])
|
||||
|
||||
def test_a_release_ready_to_cut_opens_claudes_session_without_asking_for_an_answer(self):
|
||||
def answer(args):
|
||||
with open(session.transcript_file(self.session), "a") as handle:
|
||||
handle.write(json.dumps(human("cut")) + "\n")
|
||||
return 0
|
||||
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("interrupt", release_ready=True), judged("finished")], on_terminal_claude=[answer], git=[ran()])
|
||||
with contextlib.redirect_stderr(io.StringIO()):
|
||||
self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Finished("working"))
|
||||
self.assertEqual(fake.made("input"), [])
|
||||
self.assertEqual(len(fake.made("claude_on_terminal")), 1)
|
||||
|
||||
def test_stops_when_an_interrupt_cannot_be_archived(self):
|
||||
self.archive.parent.mkdir(parents=True)
|
||||
self.archive.write_text("")
|
||||
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("interrupt")], inputs=["Use B."])
|
||||
stop = run.run_cycle(self.cycle(fake))
|
||||
self.assertRegex(stop.reason, f"^could not archive the transcript: {self.archive}/[0-9a-f]{{64}}: Not a directory$")
|
||||
self.assertEqual(fake.made("input"), [])
|
||||
|
||||
def test_stops_when_a_quoted_answer_cannot_be_archived(self):
|
||||
self.archive.parent.mkdir(parents=True)
|
||||
@@ -347,9 +478,9 @@ class Cycles(unittest.TestCase):
|
||||
self.assertEqual(len(fake.made("stream_claude")), 1)
|
||||
|
||||
def test_an_answer_the_records_do_not_hold_is_dropped_and_the_question_goes_to_the_human(self):
|
||||
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("quoted", answer="Use ... A.")], on_terminal_claude=[0], git=[ran()])
|
||||
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("quoted", answer="Use ... A.")], inputs=[""])
|
||||
with contextlib.redirect_stderr(io.StringIO()) as said:
|
||||
self.assertEqual(run.run_cycle(self.cycle(fake, records="From AGENTS.md:\nUse B. Use A.")), Stop(2, "the human is needed to answer the question above, but the interrupt ended with nothing typed"))
|
||||
self.assertEqual(run.run_cycle(self.cycle(fake, records="From AGENTS.md:\nUse B. Use A.")), Stop(2, "the human is needed to answer the question above, but nothing was typed"))
|
||||
self.assertEqual(len(fake.made("stream_claude")), 1)
|
||||
self.assertIn("\nWhich one?\n", said.getvalue())
|
||||
self.assertNotIn("Use ... A.", said.getvalue())
|
||||
@@ -424,7 +555,7 @@ class Limits(unittest.TestCase):
|
||||
def test_the_judge_reports_a_limit_whatever_its_exit_code(self):
|
||||
reply = json.dumps({"type": "result", "api_error_status": 429, "is_error": True, "result": "You've hit your session limit · resets 7:40pm (Europe/Stockholm)"})
|
||||
fake = FakeEffects(claude=[ran(reply, code=1, stderr="limited")])
|
||||
self.assertEqual(judge.run_judge("/r", [], "", "", "", fake.effects()), Limited(None, "You've hit your session limit · resets 7:40pm (Europe/Stockholm)"))
|
||||
self.assertEqual(judge.run_judge("/r", [], "", judge.Grounds("", "", ""), fake.effects()), Limited(None, "You've hit your session limit · resets 7:40pm (Europe/Stockholm)"))
|
||||
|
||||
def test_reads_only_a_rejecting_events_whole_seconds(self):
|
||||
for info, want in [({"status": "rejected", "resetsAt": NOW}, NOW), ({"status": "allowed", "resetsAt": NOW}, None), ({"status": "rejected", "resetsAt": True}, None), ({"status": "rejected"}, None), ("rejected", None)]:
|
||||
@@ -432,18 +563,40 @@ class Limits(unittest.TestCase):
|
||||
|
||||
|
||||
class Interrupts(unittest.TestCase):
|
||||
def test_stops_off_a_terminal_before_starting_claude(self):
|
||||
def put(self, fake, answer_here=True):
|
||||
with contextlib.redirect_stderr(io.StringIO()) as said:
|
||||
put = interrupt.put_question("Which one?", answer_here, fake.effects())
|
||||
return put, said.getvalue()
|
||||
|
||||
def test_stops_off_a_terminal_before_asking(self):
|
||||
fake = FakeEffects(on_terminal=False)
|
||||
stop = interrupt.interrupt("/r", uuid7(), Rung("m"), "/t", "Which one?", paths.paths_from(pathlib.Path("/h")), {}, fake.effects())
|
||||
self.assertEqual(stop, Stop(2, "the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun loop-claude on a terminal"))
|
||||
self.assertEqual(self.put(fake), (Stop(2, "the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun loop-claude on a terminal"), "\nWhich one?\n"))
|
||||
self.assertEqual(fake.calls, [])
|
||||
|
||||
def test_stops_when_nothing_was_typed_in_the_handover(self):
|
||||
def test_returns_the_line_typed_after_the_question_stripped_dropping_what_was_typed_before(self):
|
||||
fake = FakeEffects(inputs=[" Use B. "])
|
||||
self.assertEqual(self.put(fake), ("Use B.", "\nWhich one?\n"))
|
||||
self.assertEqual(fake.calls, [("discard_typed", None), ("input", "Answer (/talk opens claude, Enter stops the loop): ")])
|
||||
|
||||
def test_talks_on_talk_or_at_once_where_the_answer_is_not_asked_for_here(self):
|
||||
for typed, answer_here in (([" /talk "], True), ([], False)):
|
||||
with self.subTest(typed=typed):
|
||||
fake = FakeEffects(inputs=typed)
|
||||
self.assertEqual(self.put(fake, answer_here)[0], interrupt.Talk())
|
||||
self.assertEqual(len(fake.made("input")), len(typed))
|
||||
self.assertEqual(fake.calls[0], ("discard_typed", None))
|
||||
|
||||
def test_stops_on_an_empty_answer_or_the_inputs_end(self):
|
||||
for typed, why, said in ((" ", "nothing was typed", ""), (EOFError(), "the input ended", "\n")):
|
||||
with self.subTest(why=why):
|
||||
self.assertEqual(self.put(FakeEffects(inputs=[typed])), (Stop(2, f"the human is needed to answer the question above, but {why}"), f"\nWhich one?\n{said}"))
|
||||
|
||||
def test_stops_when_nothing_was_typed_in_the_session(self):
|
||||
with tempfile.TemporaryDirectory() as home:
|
||||
path = pathlib.Path(home, "t.jsonl")
|
||||
path.write_text(json.dumps(human("a")) + "\n")
|
||||
fake = FakeEffects(on_terminal_claude=[0], git=[ran()])
|
||||
stop = interrupt.interrupt(home, uuid7(), Rung("m", "high"), str(path), "Which one?", paths.paths_from(pathlib.Path(home)), {}, fake.effects())
|
||||
stop = interrupt.talk(home, uuid7(), Rung("m", "high"), str(path), paths.paths_from(pathlib.Path(home)), {}, fake.effects())
|
||||
self.assertEqual(fake.made("claude_on_terminal")[0][:4], ["--model", "m", "--effort", "high"])
|
||||
self.assertEqual(stop, Stop(2, "the human is needed to answer the question above, but the interrupt ended with nothing typed"))
|
||||
|
||||
@@ -453,7 +606,7 @@ class Interrupts(unittest.TestCase):
|
||||
path.write_text(json.dumps(human("a")) + "\n")
|
||||
fake = FakeEffects(on_terminal_claude=[0], git=[ran()])
|
||||
handed = {"LOOP_CLAUDE_PROJECT_RUNG": "claude-opus-5-5 at medium effort", "LOOP_CLAUDE_WORKER_RUNG": "claude-haiku-5-5 at max effort"}
|
||||
interrupt.interrupt(home, uuid7(), Rung("claude-haiku-5-5", "max"), str(path), "Which one?", paths.paths_from(pathlib.Path(home)), handed, fake.effects())
|
||||
interrupt.talk(home, uuid7(), Rung("claude-haiku-5-5", "max"), str(path), paths.paths_from(pathlib.Path(home)), handed, fake.effects())
|
||||
self.assertEqual(fake.terminal_environments, [handed])
|
||||
|
||||
|
||||
@@ -621,29 +774,47 @@ class Routing(unittest.TestCase):
|
||||
self.assertEqual(routing.first_route(self.OPUS, None), Route(self.OPUS))
|
||||
|
||||
def test_steps_up_a_rung_after_every_second_unfinished_verdict(self):
|
||||
once = routing.stepped(self.OPUS, Route(self.OPUS, 3, 3, 4), 0, False)
|
||||
once = routing.stepped(self.OPUS, Route(self.OPUS, 3, 3, 4), 0, None)
|
||||
self.assertEqual(once, Route(self.OPUS, 3, 3, 4, unfinished=1))
|
||||
self.assertEqual(routing.stepped(self.OPUS, once, 0, False), Route(self.HIGH, 3, 3, 4))
|
||||
self.assertEqual(routing.stepped(self.OPUS, Route(LADDER[-1], unfinished=1), 0, False).rung, LADDER[-1])
|
||||
self.assertEqual(routing.stepped(self.OPUS, once, 0, None), Route(self.HIGH, 3, 3, 4))
|
||||
self.assertEqual(routing.stepped(self.OPUS, Route(LADDER[-1], unfinished=1), 0, None).rung, LADDER[-1])
|
||||
|
||||
def test_steps_up_to_the_rung_a_bundled_items_l_picks_and_never_down(self):
|
||||
self.assertEqual(routing.stepped(self.OPUS, Route(self.OPUS), 4, False).rung, self.HIGH)
|
||||
self.assertEqual(routing.stepped(self.OPUS, Route(self.XHIGH), 4, False).rung, self.XHIGH)
|
||||
self.assertEqual(routing.stepped(self.OPUS, Route(self.OPUS, unfinished=1), 4, False).rung, self.XHIGH)
|
||||
self.assertEqual(routing.stepped(self.OPUS, Route(self.OPUS), 4, None).rung, self.HIGH)
|
||||
self.assertEqual(routing.stepped(self.OPUS, Route(self.XHIGH), 4, None).rung, self.XHIGH)
|
||||
self.assertEqual(routing.stepped(self.OPUS, Route(self.OPUS, unfinished=1), 4, None).rung, self.XHIGH)
|
||||
|
||||
def test_steps_up_from_a_rung_below_the_projects_one_rung_at_a_time(self):
|
||||
low = Route(Rung("claude-haiku-5-5", "max"), 3, 1, 3, unfinished=1)
|
||||
self.assertEqual(routing.stepped(self.OPUS, low, 0, False).rung, self.SONNET)
|
||||
self.assertEqual(routing.stepped(self.OPUS, Route(low.rung, 3, 1, 3), 0, False).rung, low.rung)
|
||||
self.assertEqual(routing.stepped(self.OPUS, Route(low.rung, 3, 1, 3), 2, False).rung, self.SONNET)
|
||||
self.assertEqual(routing.stepped(self.OPUS, low, 0, None).rung, self.SONNET)
|
||||
self.assertEqual(routing.stepped(self.OPUS, Route(low.rung, 3, 1, 3), 0, None).rung, low.rung)
|
||||
self.assertEqual(routing.stepped(self.OPUS, Route(low.rung, 3, 1, 3), 2, None).rung, self.SONNET)
|
||||
|
||||
def test_steps_up_a_rung_on_an_escalation_the_judge_found_up_to_two_above_the_items_rung(self):
|
||||
self.assertEqual(routing.stepped(self.OPUS, Route(self.HIGH, 3, 4, 5), 0, True), Route(self.XHIGH, 3, 4, 5))
|
||||
self.assertEqual(routing.stepped(self.OPUS, Route(self.XHIGH, 3, 4, 5), 0, True), Route(self.MAX, 3, 4, 5))
|
||||
self.assertEqual(routing.stepped(self.OPUS, Route(self.MAX, 3, 4, 5), 0, True), Route(self.MAX, 3, 4, 5, unfinished=1))
|
||||
self.assertEqual(routing.stepped(self.OPUS, Route(self.HIGH, 3, 4, 5, unfinished=1), 0, True), Route(self.XHIGH, 3, 4, 5))
|
||||
self.assertEqual(routing.stepped(self.OPUS, Route(self.XHIGH), 0, True), Route(self.XHIGH, unfinished=1))
|
||||
self.assertEqual(routing.stepped(self.OPUS, Route(self.SONNET, 3, 2, 4), 4, True), Route(self.HIGH, 3, 2, 4, unfinished=1))
|
||||
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.stepped(self.OPUS, Route(self.HIGH, 3, 4, 5), 0, 7), Route(self.XHIGH, 3, 4, 5, escalated_at=7))
|
||||
self.assertEqual(routing.stepped(self.OPUS, Route(self.XHIGH, 3, 4, 5, escalated_at=7), 0, 9), Route(self.MAX, 3, 4, 5, escalated_at=9))
|
||||
self.assertEqual(routing.stepped(self.OPUS, Route(self.MAX, 3, 4, 5, escalated_at=9), 0, 12), Route(self.MAX, 3, 4, 5, unfinished=1, escalated_at=9))
|
||||
self.assertEqual(routing.stepped(self.OPUS, Route(self.HIGH, 3, 4, 5, unfinished=1), 0, 7), Route(self.XHIGH, 3, 4, 5, escalated_at=7))
|
||||
self.assertEqual(routing.stepped(self.OPUS, Route(self.XHIGH), 0, 7), Route(self.XHIGH, unfinished=1))
|
||||
self.assertEqual(routing.stepped(self.OPUS, Route(self.SONNET, 3, 2, 4), 4, 7), Route(self.HIGH, 3, 2, 4, unfinished=1))
|
||||
|
||||
def test_keeps_the_mark_through_a_step_no_escalation_took(self):
|
||||
self.assertEqual(routing.stepped(self.OPUS, Route(self.OPUS, 3, 3, 4, unfinished=1, escalated_at=5), 0, None), Route(self.HIGH, 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.stepped_by_ruling(self.OPUS, Route(self.HIGH, 3, 4, 5, unfinished=1), 0, 7), Route(self.XHIGH, 3, 4, 5, escalated_at=7))
|
||||
self.assertEqual(routing.stepped_by_ruling(self.OPUS, Route(self.XHIGH, 3, 4, 5, escalated_at=7), 0, 9), Route(self.MAX, 3, 4, 5, escalated_at=9))
|
||||
self.assertEqual(routing.stepped_by_ruling(self.OPUS, Route(self.MAX, 3, 4, 5, unfinished=1, escalated_at=9), 0, 12), Route(self.MAX, 3, 4, 5, unfinished=1, escalated_at=9))
|
||||
self.assertEqual(routing.stepped_by_ruling(self.OPUS, Route(self.SONNET, 3, 2, 4), 0, 7), Route(self.OPUS, 3, 2, 4, escalated_at=7))
|
||||
self.assertEqual(routing.stepped_by_ruling(self.OPUS, Route(self.HIGH, 3, 4, 5, unfinished=1, escalated_at=2), 4, None), Route(self.HIGH, 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.stepped_by_ruling(self.OPUS, Route(self.OPUS, 3, 1, 3, escalated_at=2), 4, 7), Route(self.HIGH, 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.stepped_by_ruling(self.OPUS, Route(self.OPUS, 3, 3, 4), 4, 7), Route(self.XHIGH, 3, 3, 4, escalated_at=7))
|
||||
self.assertEqual(routing.stepped_by_ruling(self.OPUS, Route(self.XHIGH, 3, 4, 5), 4, 7), Route(self.MAX, 3, 4, 5, escalated_at=7))
|
||||
self.assertEqual(routing.stepped_by_ruling(self.OPUS, Route(self.MAX, 3, 4, 5, unfinished=1), 4, 7), Route(self.MAX, 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)
|
||||
@@ -658,8 +829,8 @@ 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.stepped(self.OPUS, Route(Rung("claude-opus-5-5", "low")), 0, False).rung, self.OPUS)
|
||||
self.assertEqual(routing.stepped(self.OPUS, Route(Rung("claude-opus-5-5", "low")), 2, False).rung, self.OPUS)
|
||||
self.assertEqual(routing.stepped(self.OPUS, Route(Rung("claude-opus-5-5", "low")), 0, None).rung, self.OPUS)
|
||||
self.assertEqual(routing.stepped(self.OPUS, Route(Rung("claude-opus-5-5", "low")), 2, None).rung, self.OPUS)
|
||||
|
||||
def test_runs_the_judge_on_the_rung_its_chunks_items_e_plus_i_picks_never_below_the_projects(self):
|
||||
self.assertEqual(routing.judge_rung("claude-opus-5-5", Route(self.OPUS, 3, 3, 5)), self.HIGH)
|
||||
@@ -708,6 +879,10 @@ class Routing(unittest.TestCase):
|
||||
self.assertEqual(route_from(str(unrouted)), unrouted)
|
||||
self.assertIsNone(route_from("claude-opus-5-5 at high effort, taking in an E + I of 9"))
|
||||
self.assertIsNone(route_from("claude-opus-5-5 at high effort, routed by item 3's L of 4 and E + I of 5, taking in an E + I of 5"))
|
||||
marked = Route(self.HIGH, 3, 4, 5, escalated_at=12, escape_and_impact_taken_in=7)
|
||||
self.assertEqual(str(marked), "claude-opus-5-5 at high effort, routed by item 3's L of 4 and E + I of 5, taking in an E + I of 7, escalated at transcript entry 12")
|
||||
self.assertEqual(route_from(str(marked)), marked)
|
||||
self.assertEqual(route_from(str(Route(self.HIGH, escalated_at=3))), Route(self.HIGH, escalated_at=3))
|
||||
|
||||
def test_reads_no_route_from_a_line_whose_levels_are_off_their_scales_or_an_r_plus_c_route_wrote(self):
|
||||
for line in ("claude-opus-5-5 at high effort, routed by item 3's L of 5 and E + I of 5", "claude-opus-5-5 at high effort, routed by item 3's L of 0 and E + I of 5", "claude-opus-5-5 at high effort, routed by item 3's L of 4 and E + I of 9", "claude-opus-5-5 at high effort, routed by item 3's L of 4 and E + I of 1", "claude-opus-5-5 at high effort, routed by item 3's R + C of 11"):
|
||||
@@ -774,6 +949,11 @@ class Steps(unittest.TestCase):
|
||||
self.assertEqual(main.after_verdict(run_with, self.OPUS, Finished("x")), dataclasses.replace(run_with, route=None, unfinished_evidence=""))
|
||||
self.assertEqual(main.after_verdict(run_with, self.OPUS, Unfinished("new", 4)), dataclasses.replace(run_with, route=Route(Rung("claude-opus-5-5", "high"), unfinished=1), unfinished_evidence="new"))
|
||||
|
||||
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(main.after_verdict(run_with, self.OPUS, Unfinished("new", 0, "round 2: 🔴", entries_read=9)).route, Route(Rung("claude-opus-5-5", "high"), 3, 3, 4, escalated_at=9))
|
||||
self.assertEqual(main.after_verdict(run_with, self.OPUS, Unfinished("new", entries_read=9)).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:
|
||||
opened = session.session_named("A proj loop-claude", pathlib.Path(home, "projects"))
|
||||
@@ -829,6 +1009,19 @@ class ChunkFacts(unittest.TestCase):
|
||||
self.assertIn("yourself", said)
|
||||
self.assertIn(why, said)
|
||||
|
||||
def test_runs_the_preflight_only_where_the_session_is_not_open(self):
|
||||
with tempfile.TemporaryDirectory() as home:
|
||||
opened = session.session_named("A proj loop-claude", pathlib.Path(home, "projects"))
|
||||
fresh = FakeEffects(python=[ran("- A fact.\n")])
|
||||
facts, _ = main.chunk_start(opened, self.PREFLIGHT, "/r", fresh.effects())
|
||||
self.assertEqual((fresh.made("python"), "- A fact." in facts), ([(["/b/chunk-preflight"], "/r")], True))
|
||||
transcript = pathlib.Path(home, "projects", "-fake", f"{opened.id}.jsonl")
|
||||
transcript.parent.mkdir(parents=True)
|
||||
transcript.write_text("")
|
||||
resumed = FakeEffects()
|
||||
facts, _ = main.chunk_start(opened, self.PREFLIGHT, "/r", resumed.effects())
|
||||
self.assertEqual((resumed.made("python"), facts), ([], ""))
|
||||
|
||||
|
||||
class PythonEffect(unittest.TestCase):
|
||||
def test_runs_a_script_in_the_given_directory(self):
|
||||
@@ -852,6 +1045,19 @@ class PythonEffect(unittest.TestCase):
|
||||
self.assertIn(gone, done.stderr)
|
||||
|
||||
|
||||
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))
|
||||
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)))
|
||||
|
||||
|
||||
class WorkerArgs(unittest.TestCase):
|
||||
SCAN = " Run a full scan only from such a subagent, since the scan's agents run on the model that starts them."
|
||||
SEATS = " Launch each comprehension seat and the security pass's subagent with the Agent tool set to model opus, effort medium, the project's rung."
|
||||
@@ -930,15 +1136,29 @@ class WorkerArgs(unittest.TestCase):
|
||||
self.assertIn("hand the hard part of the task to a subagent with the Agent tool set to `model opus, effort max`, one rung above yours;", prompts.resumed("", Route(Rung("claude-opus-5-5", "xhigh"), 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("before creating a new one.\n\nWhen an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `model opus, effort high`, one rung above yours, and on each further trigger one rung higher, up to `model opus, effort xhigh`; above that, ask the human first. Open the subagent's prompt with `Escalation trigger <n>:`, n the trigger's number. 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 such request: once the judge finds it in your transcript, the next cycle resumes you one rung up, up to `model opus, effort xhigh`. A reviewer", prompts.fresh("Do it.", "## Goals", Route(opus), opus, self.FACTS))
|
||||
self.assertIn("before creating a new one.\n\nWhen an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `model opus, effort high`, one rung above yours, and on each further trigger one rung higher, up to `model opus, effort xhigh`; above that, ask the human first. Open the subagent's prompt with `Escalation trigger <n>:`, n the trigger's number. 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 opus, effort xhigh`. A reviewer", prompts.fresh("Do it.", "## Goals", Route(opus), 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 such request: once the judge finds it in your transcript, the next cycle resumes you one rung up, up to `model opus, effort xhigh`."
|
||||
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 opus, effort xhigh`."
|
||||
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-opus-5-5", "high"), 3, 3, 4), opus))
|
||||
self.assertNotIn("Where the hard part", prompts.resumed("", Route(Rung("claude-opus-5-5", "xhigh"), 3, 3, 4), opus))
|
||||
|
||||
def test_launches_each_pass_a_replay_lowered_on_its_replays_rung_and_reruns_it_one_above(self):
|
||||
opus, haiku = Rung("claude-opus-5-5", "medium"), Rung("claude-haiku-5-5", "low")
|
||||
with unittest.mock.patch.dict(ladder.REPLAYED, {("prose", "claude-opus-5-5"): haiku}):
|
||||
below = prompts.fresh("Do it.", "## Goals", Route(Rung("claude-sonnet-5-5", "high"), 3, 2, 4), opus, self.FACTS)
|
||||
on_it = prompts.resumed("", Route(haiku, 3, 1, 4), opus)
|
||||
launched = " 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. Launch each prose-reviewer instead with the Agent tool set to model haiku, effort low, the rung the replay of its pass chose."
|
||||
rerun = " A reviewer or comprehension seat that asks for a rerun one rung up reruns with the Agent tool set to `model opus, effort high`. Rerun each prose-reviewer that asks with the Agent tool set to `model haiku, effort medium` instead."
|
||||
self.assertIn(f"whether or not it is item 3.{launched}", below)
|
||||
self.assertIn(" 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 opus, effort high` from 5,", below)
|
||||
self.assertIn(f"{rerun} After your first read", below)
|
||||
self.assertIn(f"loop-claude runs you on claude-haiku-5-5 at low effort.{launched}", on_it)
|
||||
self.assertIn(" Where an item you take into the chunk has an E + I of 5 or more,", on_it)
|
||||
self.assertTrue(on_it.endswith(rerun))
|
||||
|
||||
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 opus, effort high`."
|
||||
@@ -1006,11 +1226,35 @@ class Records(unittest.TestCase):
|
||||
|
||||
class JudgePrompt(unittest.TestCase):
|
||||
def test_shows_the_transcripts_tail_and_returns_what_it_showed(self):
|
||||
prompt, shown = judge.judge_prompt("Do it.", "## Goals", "", "old " + "x" * judge.JUDGE_PROMPT_CHARS + " new")
|
||||
self.assertTrue(shown.endswith(" new"))
|
||||
self.assertNotIn("old", shown)
|
||||
self.assertIn(shown, prompt)
|
||||
entries = [assistant({"type": "text", "text": "old " + "x" * judge.JUDGE_PROMPT_CHARS}), assistant({"type": "text", "text": "new"})]
|
||||
prompt, grounds = judge.judge_prompt("Do it.", "## Goals", "", entries, 0)
|
||||
self.assertTrue(grounds.shown.endswith("\n\nnew"))
|
||||
self.assertNotIn("old", grounds.shown)
|
||||
self.assertIn(grounds.shown, prompt)
|
||||
self.assertLessEqual(len(prompt), judge.JUDGE_PROMPT_CHARS)
|
||||
self.assertEqual(grounds.since_step, "old " + "x" * judge.JUDGE_PROMPT_CHARS + "\n\nnew")
|
||||
self.assertEqual(grounds.quotable, "## Goals\n\n")
|
||||
|
||||
def test_shows_the_judge_where_the_worker_last_stepped_up_and_checks_an_escalation_only_after_it(self):
|
||||
entries = [assistant({"type": "text", "text": "round 2: 🔴"}), assistant({"type": "text", "text": "round 3: 🔴"})]
|
||||
prompt, grounds = judge.judge_prompt("Do it.", "## Goals", "", entries, 1)
|
||||
self.assertRegex(prompt, "round 2: 🔴\n\n\\[step\\] [^\n]+\n\nround 3: 🔴\n\n")
|
||||
self.assertEqual(grounds.since_step, "round 3: 🔴")
|
||||
prompt, grounds = judge.judge_prompt("Do it.", "## Goals", "", entries, 0)
|
||||
self.assertNotIn("stepped the agent up", prompt)
|
||||
self.assertEqual(grounds.since_step, "round 2: 🔴\n\nround 3: 🔴")
|
||||
|
||||
def test_drops_an_escalation_quote_from_after_the_step_up_that_the_tail_it_shows_cuts_off(self):
|
||||
entries = [assistant({"type": "text", "text": "round 2: 🔴"}), assistant({"type": "text", "text": "old " + "x" * judge.JUDGE_PROMPT_CHARS}), assistant({"type": "text", "text": "new"})]
|
||||
_, grounds = judge.judge_prompt("Do it.", "## Goals", "", entries, 1)
|
||||
self.assertEqual(judge.quotes_checked(Unfinished("e", 0, "old x", entries_read=3), grounds), Unfinished("e", entries_read=3))
|
||||
self.assertEqual(judge.quotes_checked(Unfinished("e", 0, "new", entries_read=3), grounds), Unfinished("e", 0, "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)
|
||||
entries = [{**human(typed), "promptSource": "sdk"}, assistant({"type": "text", "text": "round 3: 🔴"})]
|
||||
_, grounds = judge.judge_prompt("Do it.", "## Goals", "", entries, 1)
|
||||
self.assertIn("\n\n[human] Use B.\n\n[step] ", grounds.shown)
|
||||
|
||||
|
||||
class Grounded(unittest.TestCase):
|
||||
@@ -1039,19 +1283,21 @@ class Grounded(unittest.TestCase):
|
||||
|
||||
class Verdict(unittest.TestCase):
|
||||
def test_needs_every_field_the_schema_requires(self):
|
||||
self.assertEqual(verdict_from({"bundled": 0, "bundled_escape_and_impact": 0, "escalation": "", "answer": "", "interrupt": False, "evidence": "e", "finished": True, "question": ""}), Finished("e"))
|
||||
self.assertEqual(verdict_from({"bundled": 0, "bundled_escape_and_impact": 0, "escalation": "", "answer": "", "interrupt": False, "evidence": "e", "finished": False, "question": "ignored"}), Unfinished("e"))
|
||||
self.assertEqual(verdict_from({"bundled": 0, "bundled_escape_and_impact": 0, "escalation": "", "answer": "", "interrupt": True, "evidence": "e", "finished": True, "question": "Which one?"}), Interrupt("e", "Which one?"))
|
||||
self.assertEqual(verdict_from({"bundled": 0, "bundled_escape_and_impact": 0, "escalation": "", "answer": "A.", "interrupt": False, "evidence": "e", "finished": False, "question": "Which one?"}), QuotedAnswer("e", "Which one?", "A."))
|
||||
self.assertEqual(verdict_from({"bundled": 0, "bundled_escape_and_impact": 0, "escalation": "", "answer": "A.", "interrupt": True, "evidence": "e", "finished": False, "question": "Which one?"}), Interrupt("e", "Which one?"))
|
||||
self.assertEqual(verdict_from({"bundled": 0, "bundled_escape_and_impact": 0, "escalation": "", "answer": "A.", "interrupt": False, "evidence": "e", "finished": True, "question": ""}), Failure("the judge quoted an answer without a question"))
|
||||
self.assertEqual(verdict_from({"bundled": 0, "bundled_escape_and_impact": 0, "escalation": "", "answer": "", "interrupt": "no", "evidence": "", "finished": True, "question": ""}), Failure("the judge's reply has no interrupt of type boolean"))
|
||||
self.assertEqual(verdict_from({"bundled": 0, "bundled_escape_and_impact": 0, "escalation": "", "answer": "", "interrupt": False, "evidence": None, "finished": True, "question": ""}), Failure("the judge's reply has no evidence of type string"))
|
||||
self.assertEqual(verdict_from({"bundled": 0, "bundled_escape_and_impact": 0, "escalation": "", "answer": "", "interrupt": True, "evidence": "x", "finished": False, "question": " "}), Failure("the judge interrupted without a question"))
|
||||
self.assertEqual(verdict_from({"bundled": 0, "bundled_escape_and_impact": 0, "escalation": "", "answer": "", "interrupt": False, "evidence": "e", "finished": True, "question": "", "release_ready": False}), Finished("e"))
|
||||
self.assertEqual(verdict_from({"bundled": 0, "bundled_escape_and_impact": 0, "escalation": "", "answer": "", "interrupt": False, "evidence": "e", "finished": False, "question": "ignored", "release_ready": False}), Unfinished("e"))
|
||||
self.assertEqual(verdict_from({"bundled": 0, "bundled_escape_and_impact": 0, "escalation": "", "answer": "", "interrupt": True, "evidence": "e", "finished": True, "question": "Which one?", "release_ready": False}), Interrupt("e", "Which one?"))
|
||||
self.assertEqual(verdict_from({"bundled": 0, "bundled_escape_and_impact": 0, "escalation": "", "answer": "", "interrupt": True, "evidence": "e", "finished": False, "question": "Cut 0.2.0?", "release_ready": True}), Interrupt("e", "Cut 0.2.0?", release_ready=True))
|
||||
self.assertEqual(verdict_from({"bundled": 0, "bundled_escape_and_impact": 0, "escalation": "", "answer": "", "interrupt": True, "evidence": "e", "finished": False, "question": "Cut 0.2.0?"}), Failure("the judge's reply has no release_ready of type boolean"))
|
||||
self.assertEqual(verdict_from({"bundled": 0, "bundled_escape_and_impact": 0, "escalation": "", "answer": "A.", "interrupt": False, "evidence": "e", "finished": False, "question": "Which one?", "release_ready": False}), QuotedAnswer("e", "Which one?", "A."))
|
||||
self.assertEqual(verdict_from({"bundled": 0, "bundled_escape_and_impact": 0, "escalation": "", "answer": "A.", "interrupt": True, "evidence": "e", "finished": False, "question": "Which one?", "release_ready": False}), Interrupt("e", "Which one?"))
|
||||
self.assertEqual(verdict_from({"bundled": 0, "bundled_escape_and_impact": 0, "escalation": "", "answer": "A.", "interrupt": False, "evidence": "e", "finished": True, "question": "", "release_ready": False}), Failure("the judge quoted an answer without a question"))
|
||||
self.assertEqual(verdict_from({"bundled": 0, "bundled_escape_and_impact": 0, "escalation": "", "answer": "", "interrupt": "no", "evidence": "", "finished": True, "question": "", "release_ready": False}), Failure("the judge's reply has no interrupt of type boolean"))
|
||||
self.assertEqual(verdict_from({"bundled": 0, "bundled_escape_and_impact": 0, "escalation": "", "answer": "", "interrupt": False, "evidence": None, "finished": True, "question": "", "release_ready": False}), Failure("the judge's reply has no evidence of type string"))
|
||||
self.assertEqual(verdict_from({"bundled": 0, "bundled_escape_and_impact": 0, "escalation": "", "answer": "", "interrupt": True, "evidence": "x", "finished": False, "question": " ", "release_ready": False}), Failure("the judge interrupted without a question"))
|
||||
self.assertEqual(verdict_from(None), Failure("the judge returned no reply"))
|
||||
|
||||
def test_takes_a_bundled_l_on_its_scale_and_counts_any_other_as_none(self):
|
||||
reply = {"answer": "", "bundled_escape_and_impact": 0, "escalation": "", "interrupt": False, "evidence": "e", "finished": False, "question": ""}
|
||||
reply = {"answer": "", "bundled_escape_and_impact": 0, "escalation": "", "interrupt": False, "evidence": "e", "finished": False, "question": "", "release_ready": False}
|
||||
self.assertEqual(verdict_from({**reply, "bundled": 4}), Unfinished("e", 4))
|
||||
self.assertEqual(verdict_from({**reply, "bundled": True}), Failure("the judge's reply has no bundled of type integer"))
|
||||
for bundled in (5, 13, -1):
|
||||
@@ -1060,7 +1306,7 @@ class Verdict(unittest.TestCase):
|
||||
|
||||
|
||||
def test_takes_a_bundled_e_plus_i_on_its_scale_and_counts_any_other_as_none(self):
|
||||
reply = {"answer": "", "bundled": 0, "escalation": "", "interrupt": False, "evidence": "e", "finished": False, "question": ""}
|
||||
reply = {"answer": "", "bundled": 0, "escalation": "", "interrupt": False, "evidence": "e", "finished": False, "question": "", "release_ready": False}
|
||||
self.assertEqual(verdict_from({**reply, "bundled_escape_and_impact": 6}), Unfinished("e", 0, bundled_escape_and_impact=6))
|
||||
self.assertEqual(verdict_from({**reply, "bundled_escape_and_impact": 2}), Unfinished("e", 0, bundled_escape_and_impact=2))
|
||||
self.assertEqual(verdict_from({**reply, "bundled_escape_and_impact": False}), Failure("the judge's reply has no bundled_escape_and_impact of type integer"))
|
||||
@@ -1069,11 +1315,60 @@ class Verdict(unittest.TestCase):
|
||||
self.assertEqual(verdict_from({**reply, "bundled_escape_and_impact": bundled}), Unfinished("e", 0))
|
||||
|
||||
def test_takes_an_escalation_quote_on_an_unfinished_verdict(self):
|
||||
reply = {"answer": "", "bundled": 0, "bundled_escape_and_impact": 0, "escalation": "round 2: 🔴", "interrupt": False, "evidence": "e", "finished": False, "question": ""}
|
||||
reply = {"answer": "", "bundled": 0, "bundled_escape_and_impact": 0, "escalation": "round 2: 🔴", "interrupt": False, "evidence": "e", "finished": False, "question": "", "release_ready": False}
|
||||
self.assertEqual(verdict_from(reply), Unfinished("e", 0, "round 2: 🔴"))
|
||||
self.assertEqual(verdict_from({**reply, "finished": True}), Finished("e"))
|
||||
self.assertEqual(verdict_from({**reply, "escalation": None}), Failure("the judge's reply has no escalation of type string"))
|
||||
|
||||
def test_takes_an_escalation_quote_on_an_interrupt(self):
|
||||
reply = {"answer": "", "bundled": 0, "bundled_escape_and_impact": 0, "escalation": "round 2: 🔴", "interrupt": True, "evidence": "e", "finished": False, "question": "Which one?", "release_ready": False}
|
||||
self.assertEqual(verdict_from(reply), Interrupt("e", "Which one?", "round 2: 🔴"))
|
||||
self.assertEqual(verdict_from({**reply, "bundled": 4}), Interrupt("e", "Which one?", "round 2: 🔴", 4))
|
||||
self.assertEqual(verdict_from({**reply, "bundled": 5}), Interrupt("e", "Which one?", "round 2: 🔴"))
|
||||
|
||||
def test_drops_an_escalation_quote_the_transcript_does_not_hold_word_for_word_from_an_interrupt_or_an_unfinished_verdict(self):
|
||||
shown = "The agent: round 2: 🔴. Which one?"
|
||||
self.assertEqual(judge.quotes_checked(Interrupt("e", "q", "round 2: 🔴"), judge.Grounds(shown, shown, "")), Interrupt("e", "q", "round 2: 🔴"))
|
||||
self.assertEqual(judge.quotes_checked(Interrupt("e", "q", "round 2: … 🔴"), judge.Grounds(shown, shown, "")), Interrupt("e", "q"))
|
||||
self.assertEqual(judge.quotes_checked(Unfinished("e", 0, "round 3: 🔴"), judge.Grounds(shown, shown, "")), Unfinished("e"))
|
||||
|
||||
def test_takes_an_escalation_quote_and_a_bundled_l_on_a_quoted_answer(self):
|
||||
reply = {"answer": "A.", "bundled": 4, "bundled_escape_and_impact": 0, "escalation": "round 2: 🔴", "interrupt": False, "evidence": "e", "finished": False, "question": "Which one?", "release_ready": False}
|
||||
self.assertEqual(verdict_from(reply), QuotedAnswer("e", "Which one?", "A.", "round 2: 🔴", 4))
|
||||
self.assertEqual(verdict_from({**reply, "bundled": 5}), QuotedAnswer("e", "Which one?", "A.", "round 2: 🔴"))
|
||||
|
||||
def test_drops_an_escalation_quote_the_transcript_does_not_hold_word_for_word_from_a_quoted_answer(self):
|
||||
shown = "The agent: round 2: 🔴. Which one?"
|
||||
self.assertEqual(judge.quotes_checked(QuotedAnswer("e", "q", "A.", "round 2: 🔴"), judge.Grounds(shown, shown, "A.")), QuotedAnswer("e", "q", "A.", "round 2: 🔴"))
|
||||
self.assertEqual(judge.quotes_checked(QuotedAnswer("e", "q", "A.", "round 2: … 🔴"), judge.Grounds(shown, shown, "A.")), QuotedAnswer("e", "q", "A."))
|
||||
|
||||
def test_puts_a_quoted_answer_the_records_do_not_hold_to_the_human_with_the_escalation_it_carried(self):
|
||||
self.assertEqual(judge.quotes_checked(QuotedAnswer("e", "q", "not there", "round 2: 🔴", 4), judge.Grounds("The agent: round 2: 🔴.", "The agent: round 2: 🔴.", "A.")), Interrupt("e", "q", "round 2: 🔴", 4))
|
||||
|
||||
def test_puts_a_quoted_answer_the_records_do_not_hold_word_for_word_to_the_human(self):
|
||||
self.assertEqual(judge.quotes_checked(QuotedAnswer("e", "q", "not there"), judge.Grounds("shown", "shown", "the records")), Interrupt("e", "q"))
|
||||
self.assertEqual(judge.quotes_checked(QuotedAnswer("e", "q", "the records"), judge.Grounds("shown", "shown", "From the records: the records")), QuotedAnswer("e", "q", "the records"))
|
||||
|
||||
def test_drops_an_escalation_quote_found_only_in_the_transcript_entries_before_the_workers_last_step_up(self):
|
||||
entries = [assistant({"type": "text", "text": "round 2: 🔴"}), assistant({"type": "text", "text": "round 3: 🔴"}), assistant({"type": "text", "text": "working"})]
|
||||
def judged_on(mark, escalation):
|
||||
return judge.judge_once("/r", "Do it.", "## Goals", "", entries, mark, Rung("judge-model"), FakeEffects(claude=[judged("unfinished", escalation=escalation)]).effects())
|
||||
self.assertEqual(judged_on(0, "round 2: 🔴"), Unfinished("working", 0, "round 2: 🔴", entries_read=3))
|
||||
self.assertEqual(judged_on(1, "round 2: 🔴"), Unfinished("working", entries_read=3))
|
||||
self.assertEqual(judged_on(1, "round 3: 🔴"), Unfinished("working", 0, "round 3: 🔴", entries_read=3))
|
||||
self.assertEqual(judged_on(1, "round 2: 🔴\n\nround 3: 🔴"), Unfinished("working", entries_read=3))
|
||||
self.assertEqual(judged_on(3, "round 3: 🔴"), Unfinished("working", entries_read=3))
|
||||
|
||||
def test_drops_an_escalation_quote_that_only_loop_claudes_prompts_or_the_humans_lines_repeat_after_the_step_up(self):
|
||||
entries = [assistant({"type": "text", "text": "round 2: 🔴"}), {**human("as the work remaining: round 2: 🔴"), "promptSource": "sdk"}, human("round 2: 🔴 again"), assistant({"type": "text", "text": "working"})]
|
||||
verdict = judge.judge_once("/r", "Do it.", "## Goals", "", entries, 1, Rung("judge-model"), FakeEffects(claude=[judged("unfinished", escalation="round 2: 🔴")]).effects())
|
||||
self.assertEqual(verdict, Unfinished("working", entries_read=4))
|
||||
|
||||
def test_takes_evidence_from_before_the_workers_last_step_up(self):
|
||||
entries = [assistant({"type": "text", "text": "round 2: 🔴"}), assistant({"type": "text", "text": "working"})]
|
||||
verdict = judge.judge_once("/r", "Do it.", "## Goals", "", entries, 1, Rung("judge-model"), FakeEffects(claude=[judged("unfinished", evidence="round 2: 🔴")]).effects())
|
||||
self.assertEqual(verdict, Unfinished("round 2: 🔴", entries_read=2))
|
||||
|
||||
|
||||
class LoopRuns(unittest.TestCase):
|
||||
def test_stops_naming_the_reload_when_it_hands_over_anything_but_the_state_with_a_task(self):
|
||||
@@ -1147,9 +1442,9 @@ class ExitContract(unittest.TestCase):
|
||||
unreadable = f"README.md, or {', '.join(names[:-1])} or {names[-1]} where they exist, cannot be read or is not UTF-8"
|
||||
# Every Stop whose code is not a literal 0, 2 or 130, in source order: path, function, code, start of reason, its --help clause.
|
||||
clauses = [
|
||||
("cycle/interrupt.py", "interrupt", "1", "entries.reason", read),
|
||||
("cycle/interrupt.py", "interrupt", "1", "f'could not start claude for the interrupt:", "claude cannot start for an interrupt"),
|
||||
("cycle/interrupt.py", "interrupt", "1", "f'could not tell whether you typed anything:", read),
|
||||
("cycle/interrupt.py", "talk", "1", "entries.reason", read),
|
||||
("cycle/interrupt.py", "talk", "1", "f'could not start claude for the interrupt:", "claude cannot start for an interrupt"),
|
||||
("cycle/interrupt.py", "talk", "1", "f'could not tell whether you typed anything:", read),
|
||||
("cycle/retry.py", "retried", "1", "f'the {who} failed three times running:", "the worker or the judge fails three times running"),
|
||||
("cycle/run.py", "stopped", "1", "f'{failure.reason}", read),
|
||||
("cycle/run.py", "work", "1", "f'claude left no transcript for session", "claude leaves no transcript"),
|
||||
|
||||
@@ -5,8 +5,10 @@ import typing
|
||||
|
||||
# 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")
|
||||
# What a review launch reviews: a reviewer, a comprehension seat or the security pass.
|
||||
ReviewKind = typing.Literal["reviewer", "seat", "security"]
|
||||
# A pass an agent under agents/ reviews, named as skills/larv-review/SKILL.md → "Passes" names it in lower case.
|
||||
ReviewedPass = typing.Literal["architecture", "principles", "overrides", "stability", "product-owner", "prose"]
|
||||
# What a review launch reviews: such a pass, a comprehension seat or the security pass.
|
||||
ReviewKind = ReviewedPass | typing.Literal["seat", "security"]
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
@@ -63,6 +65,10 @@ LADDER = (
|
||||
WORKER_STEPS = {1: -2, 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}
|
||||
# Each pass an agent under agents/ reviews, in the order of SKILL.md's pass table, and that agent.
|
||||
REVIEWERS: dict[ReviewedPass, str] = {"architecture": "systems-architect", "principles": "principles-auditor", "overrides": "override-reviewer", "stability": "stability-reviewer", "product-owner": "product-owner-reviewer", "prose": "prose-reviewer"}
|
||||
# The rung a pass's replay chose for the projects on a model: docs/decisions.md → `routing: a review pass runs below the project's rung only on a rung that a replay of its rounds shows finding every 🔴 and 🟡 the project's rung finds`.
|
||||
REPLAYED: dict[tuple[ReviewedPass, str], Rung] = {}
|
||||
|
||||
|
||||
def project_rung(model: str) -> Rung | None:
|
||||
@@ -96,14 +102,19 @@ def stepped_up(rung: Rung) -> Rung:
|
||||
|
||||
|
||||
def review_rungs(project: Rung, worker: Rung, escape_and_impact: int) -> dict[ReviewKind, Rung]:
|
||||
"""The rung each kind of review in a chunk runs on, where its worker runs on worker and its item has that E + I. The reviewers run on the higher of the worker's rung and review_floor's."""
|
||||
reviewers = highest(worker, review_floor(project, escape_and_impact))
|
||||
return {kind: review_rung(kind, project, reviewers) for kind in typing.get_args(ReviewKind)}
|
||||
"""The rung each kind of review in a chunk runs on, where its worker runs on worker and its item has that E + I.
|
||||
|
||||
A pass's reviewer runs on reviewers_rung. Where the E + I steps no review up and the worker runs no higher than the project's rung, a pass whose replay chose a rung for the project's model runs on that rung instead, even below the worker's: the replay compared reviews on the project's rung only, never on a rung an E + I stepped up, nor of a chunk whose worker climbed above the project's rung. 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.
|
||||
"""
|
||||
rungs: dict[ReviewKind, Rung] = {**dict.fromkeys(REVIEWERS, reviewers_rung(project, worker, escape_and_impact)), "seat": project, "security": project}
|
||||
if escape_and_impact not in REVIEW_STEPS and position(worker) <= position(project):
|
||||
rungs |= {kind: rung for (kind, model), rung in REPLAYED.items() if model == project.model}
|
||||
return rungs
|
||||
|
||||
|
||||
def review_rung(kind: ReviewKind, project: Rung, reviewers: Rung) -> Rung:
|
||||
"""The rung a review of kind runs on: a reviewer on the reviewers' rung; a seat or the security pass on the project's, so the seats score every chunk on one rung, and the security pass spends no more than the project chose."""
|
||||
return reviewers if kind == "reviewer" else project
|
||||
def reviewers_rung(project: Rung, worker: Rung, escape_and_impact: int) -> Rung:
|
||||
"""The rung of each pass's reviewer that no replay lowered: the higher of the worker's rung and review_floor's."""
|
||||
return highest(worker, review_floor(project, escape_and_impact))
|
||||
|
||||
|
||||
def highest(*rungs: Rung) -> Rung:
|
||||
|
||||
@@ -8,17 +8,24 @@ from model_routing.ladder import REVIEW_STEPS, Rung
|
||||
|
||||
# How a worker opens the prompt of a subagent it escalates a task to, `Escalation trigger 2: …`: docs/decisions.md → `routing: a worker hands a task one rung up`.
|
||||
ESCALATION_MARKER = "Escalation trigger"
|
||||
# An archived worker line: the rung, then the item and the levels that routed it, if any, then the E + I taken in, if any. A line an older loop-claude wrote names an R + C in place of L and E + I: archived_worker reads only its rung, for the routing figures; with no levels, route_from returns None and the chunk routes afresh.
|
||||
ROUTED = re.compile(r"(?P<rung>.+?)(?:, routed by item (?P<item>[0-9]+)'s (?:L of (?P<likelihood>[0-9]+) and E \+ I of (?P<escape_and_impact>[0-9]+)|.+?))?(?:, taking in an E \+ I of (?P<escape_and_impact_taken_in>[0-9]+))?")
|
||||
# An archived worker line. A line an older loop-claude wrote names an R + C in place of L and E + I: archived_worker reads only its rung, for the routing figures; with no levels, route_from returns None and the chunk routes afresh.
|
||||
# Each group reads one fragment of Route.__str__. A reworded fragment leaves the line unreadable, so the chunk routes afresh, its mark back at 0.
|
||||
ROUTED = re.compile(r"""
|
||||
(?P<rung>.+?) # the rung, lazy so the groups below take what follows it
|
||||
(?:,\ routed\ by\ item\ (?P<item>[0-9]+)'s\ (?:L\ of\ (?P<likelihood>[0-9]+)\ and\ E\ \+\ I\ of\ (?P<escape_and_impact>[0-9]+)|.+?))? # routed: `, routed by item 3's L of 4 and E + I of 5`, or an older line's R + C
|
||||
(?:,\ taking\ in\ an\ E\ \+\ I\ of\ (?P<escape_and_impact_taken_in>[0-9]+))? # taken_in: `, taking in an E + I of 6`
|
||||
(?:,\ escalated\ at\ transcript\ entry\ (?P<escalated_at>[0-9]+))? # escalated: `, escalated at transcript entry 12`
|
||||
""", re.VERBOSE)
|
||||
|
||||
|
||||
class ArchivedWorker(typing.NamedTuple):
|
||||
"""What an archived worker line names: the worker's rung, the item that routed it, its L and E + I, and the E + I taken in; 0 for each it does not name."""
|
||||
"""What an archived worker line names: the worker's rung, the item that routed it, its L and E + I, the E + I taken in and the escalation's mark; 0 for each it does not name."""
|
||||
rung: Rung
|
||||
item: int
|
||||
likelihood: int
|
||||
escape_and_impact: int
|
||||
escape_and_impact_taken_in: int
|
||||
escalated_at: int
|
||||
|
||||
|
||||
HIGHEST_ESCAPE_AND_IMPACT = LEVELS["E"] + LEVELS["I"]
|
||||
@@ -55,6 +62,8 @@ class Route:
|
||||
unfinished: int = 0
|
||||
# The highest E + I the judge saw the worker take in, kept only where it picks a higher review step than the item's; 0 otherwise.
|
||||
escape_and_impact_taken_in: int = 0
|
||||
# The mark: how many transcript entries the session held when an escalation last stepped the worker up, 0 before any. The judge's escalation quote counts only from the entries after it, so a passage that already bought a step cannot buy another; the session's transcript only grows, so the mark holds across cycles.
|
||||
escalated_at: int = 0
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
# Raises on a programming error only, so nothing catches it: route_from and the reload decoder check levels_fit before they build a route.
|
||||
@@ -78,7 +87,8 @@ class Route:
|
||||
"""What the archive records as each verdict's worker; ROUTED reads it back."""
|
||||
routed = f", routed by item {self.item}'s L of {self.likelihood} and E + I of {self.escape_and_impact}" if self.item else ""
|
||||
taken_in = f", taking in an E + I of {self.escape_and_impact_taken_in}" if self.escape_and_impact_taken_in else ""
|
||||
return f"{self.rung}{routed}{taken_in}"
|
||||
escalated = f", escalated at transcript entry {self.escalated_at}" if self.escalated_at else ""
|
||||
return f"{self.rung}{routed}{taken_in}{escalated}"
|
||||
|
||||
|
||||
def archived_worker(worker: str) -> ArchivedWorker | None:
|
||||
@@ -87,7 +97,7 @@ def archived_worker(worker: str) -> ArchivedWorker | None:
|
||||
rung = Rung.parse(found["rung"]) if found else None
|
||||
if not (found and rung):
|
||||
return None
|
||||
return ArchivedWorker(rung, *(int(found[name] or 0) for name in ("item", "likelihood", "escape_and_impact", "escape_and_impact_taken_in")))
|
||||
return ArchivedWorker(rung, *(int(found[name] or 0) for name in ("item", "likelihood", "escape_and_impact", "escape_and_impact_taken_in", "escalated_at")))
|
||||
|
||||
|
||||
def route_from(worker: str) -> Route | None:
|
||||
@@ -95,4 +105,4 @@ def route_from(worker: str) -> Route | None:
|
||||
archived = archived_worker(worker)
|
||||
if archived is None or not levels_fit(archived.item, archived.likelihood, archived.escape_and_impact, archived.escape_and_impact_taken_in):
|
||||
return None
|
||||
return Route(archived.rung, archived.item, archived.likelihood, archived.escape_and_impact, escape_and_impact_taken_in=archived.escape_and_impact_taken_in)
|
||||
return Route(archived.rung, archived.item, archived.likelihood, archived.escape_and_impact, escape_and_impact_taken_in=archived.escape_and_impact_taken_in, escalated_at=archived.escalated_at)
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
import pathlib
|
||||
import sys
|
||||
import typing
|
||||
import unittest
|
||||
import unittest.mock
|
||||
|
||||
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, review_rungs, Rung, stepped_up, worker_rung, WORKER_STEPS
|
||||
from model_routing.ladder import highest, LADDER, lowest_worker_rung, planning_rung, position, project_rung, review_floor, review_rungs, ReviewedPass, REVIEWERS, Rung, stepped_up, worker_rung, WORKER_STEPS
|
||||
from model_routing import ladder
|
||||
from todo_table import LEVELS
|
||||
|
||||
OPUS = Rung("claude-opus-5-5", "medium")
|
||||
@@ -94,20 +97,37 @@ class Ladder(unittest.TestCase):
|
||||
|
||||
def test_puts_reviewers_on_the_highest_of_the_projects_rung_the_workers_and_the_one_e_plus_i_picks(self):
|
||||
haiku, fable = LADDER[4], LADDER[-1]
|
||||
self.assertEqual(review_rungs(OPUS, haiku, 4)["reviewer"], OPUS)
|
||||
self.assertEqual(review_rungs(OPUS, haiku, 5)["reviewer"], Rung("claude-opus-5-5", "high"))
|
||||
self.assertEqual(review_rungs(OPUS, fable, 5)["reviewer"], fable)
|
||||
self.assertEqual(review_rungs(OPUS, Rung("claude-opus-5-5", "high"), 7)["reviewer"], Rung("claude-opus-5-5", "max"))
|
||||
self.assertEqual(review_rungs(OPUS, haiku, 4)["stability"], OPUS)
|
||||
self.assertEqual(review_rungs(OPUS, haiku, 5)["stability"], Rung("claude-opus-5-5", "high"))
|
||||
self.assertEqual(review_rungs(OPUS, fable, 5)["stability"], fable)
|
||||
self.assertEqual(review_rungs(OPUS, Rung("claude-opus-5-5", "high"), 7)["stability"], Rung("claude-opus-5-5", "max"))
|
||||
|
||||
def test_keeps_the_seats_and_the_security_pass_on_the_projects_rung_whatever_the_worker_or_e_plus_i(self):
|
||||
self.assertEqual(review_rungs(OPUS, LADDER[-1], 8), {"reviewer": LADDER[-1], "seat": OPUS, "security": OPUS})
|
||||
self.assertEqual(review_rungs(OPUS, LADDER[-1], 8), {**dict.fromkeys(REVIEWERS, LADDER[-1]), "seat": OPUS, "security": OPUS})
|
||||
|
||||
def test_holds_a_reviewer_to_the_reviewers_rung_and_anything_else_to_the_projects(self):
|
||||
fable = LADDER[-1]
|
||||
self.assertEqual(review_rung("reviewer", OPUS, fable), fable)
|
||||
for kind in ("seat", "security"):
|
||||
with self.subTest(kind=kind):
|
||||
self.assertEqual(review_rung(kind, OPUS, fable), OPUS)
|
||||
def test_names_every_kind_of_review_once_each_pass_with_its_agent_under_agents(self):
|
||||
self.assertEqual(list(REVIEWERS), list(typing.get_args(ReviewedPass)))
|
||||
agents = pathlib.Path(__file__).resolve().parents[2] / "agents"
|
||||
self.assertEqual(sorted(REVIEWERS.values()), sorted(path.stem for path in agents.glob("*.md")))
|
||||
|
||||
def test_runs_a_replayed_pass_on_its_replays_rung_below_the_workers_where_the_e_plus_i_steps_no_review_up_and_the_worker_runs_no_higher_than_the_project(self):
|
||||
sonnet, haiku, opus_high = Rung("claude-sonnet-5-5", "high"), LADDER[0], Rung("claude-opus-5-5", "high")
|
||||
with unittest.mock.patch.dict(ladder.REPLAYED, {("prose", "claude-opus-5-5"): haiku, ("stability", "claude-sonnet-5-5"): haiku}):
|
||||
self.assertEqual(review_rungs(OPUS, LADDER[4], 4), {**dict.fromkeys(REVIEWERS, OPUS), "prose": haiku, "seat": OPUS, "security": OPUS})
|
||||
self.assertEqual(review_rungs(OPUS, OPUS, 4)["prose"], haiku)
|
||||
self.assertEqual(review_rungs(OPUS, opus_high, 4)["prose"], opus_high)
|
||||
self.assertEqual(review_rungs(OPUS, sonnet, 5)["prose"], opus_high)
|
||||
self.assertEqual(review_rungs(OPUS, LADDER[-1], 5)["prose"], LADDER[-1])
|
||||
self.assertEqual((review_rungs(sonnet, sonnet, 4)["prose"], review_rungs(sonnet, sonnet, 4)["stability"]), (sonnet, haiku))
|
||||
|
||||
def test_holds_each_replayed_rung_below_its_models_project_rung_on_the_ladder(self):
|
||||
for (kind, model), rung in ladder.REPLAYED.items():
|
||||
with self.subTest(kind=kind, model=model):
|
||||
project = project_rung(model)
|
||||
self.assertIn(kind, REVIEWERS)
|
||||
self.assertIsNotNone(project)
|
||||
self.assertLess(position(rung), position(project) if project else 0)
|
||||
self.assertIn(rung, LADDER)
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@@ -9,20 +9,22 @@ class Environment(unittest.TestCase):
|
||||
PROJECT = Rung("claude-opus-5-5", "medium")
|
||||
WORKER = Rung("claude-haiku-5-5", "max")
|
||||
|
||||
def test_the_project_the_worker_and_the_reviewers_rungs_are_named_in_the_environment(self):
|
||||
self.assertEqual(environment(self.PROJECT, Route(self.WORKER, 3, 1, 5)), {"LOOP_CLAUDE_PROJECT_RUNG": "claude-opus-5-5 at medium effort", "LOOP_CLAUDE_WORKER_RUNG": "claude-haiku-5-5 at max effort", "LOOP_CLAUDE_REVIEWER_RUNG": "claude-opus-5-5 at high effort"})
|
||||
self.assertEqual(environment(self.PROJECT, Route(self.WORKER))["LOOP_CLAUDE_REVIEWER_RUNG"], "claude-opus-5-5 at medium effort")
|
||||
self.assertEqual(environment(self.PROJECT, Route(Rung("claude-opus-5-5", "xhigh"), 3, 4, 2))["LOOP_CLAUDE_REVIEWER_RUNG"], "claude-opus-5-5 at xhigh effort")
|
||||
self.assertEqual(environment(self.PROJECT, Route(self.WORKER, 3, 1, 5, escape_and_impact_taken_in=6))["LOOP_CLAUDE_REVIEWER_RUNG"], "claude-opus-5-5 at xhigh effort")
|
||||
def test_the_project_and_the_workers_rungs_and_the_e_plus_i_reviews_take_are_named_in_the_environment(self):
|
||||
self.assertEqual(environment(self.PROJECT, Route(self.WORKER, 3, 1, 5)), {"LOOP_CLAUDE_PROJECT_RUNG": "claude-opus-5-5 at medium effort", "LOOP_CLAUDE_WORKER_RUNG": "claude-haiku-5-5 at max effort", "LOOP_CLAUDE_ESCAPE_AND_IMPACT": "5"})
|
||||
self.assertEqual(environment(self.PROJECT, Route(self.WORKER))["LOOP_CLAUDE_ESCAPE_AND_IMPACT"], "0")
|
||||
self.assertEqual(environment(self.PROJECT, Route(self.WORKER, 3, 1, 5, escape_and_impact_taken_in=6))["LOOP_CLAUDE_ESCAPE_AND_IMPACT"], "6")
|
||||
|
||||
def test_a_project_off_the_ladder_is_handed_empty_rungs_so_none_is_inherited(self):
|
||||
self.assertEqual(environment(None, Route(self.WORKER)), {"LOOP_CLAUDE_PROJECT_RUNG": "", "LOOP_CLAUDE_WORKER_RUNG": "claude-haiku-5-5 at max effort", "LOOP_CLAUDE_REVIEWER_RUNG": ""})
|
||||
def test_a_project_off_the_ladder_is_handed_an_empty_rung_so_none_is_inherited(self):
|
||||
self.assertEqual(environment(None, Route(self.WORKER)), {"LOOP_CLAUDE_PROJECT_RUNG": "", "LOOP_CLAUDE_WORKER_RUNG": "claude-haiku-5-5 at max 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, Rung("claude-opus-5-5", "high")))
|
||||
self.assertEqual(handed(environment(None, Route(self.WORKER))), (None, self.WORKER, None))
|
||||
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))
|
||||
|
||||
def test_a_missing_or_unknown_rung_reads_as_none(self):
|
||||
self.assertEqual(handed({}), (None, None, None))
|
||||
self.assertEqual(handed({"LOOP_CLAUDE_WORKER_RUNG": "claude-haiku-5-5 bogus"}), (None, None, None))
|
||||
self.assertEqual(handed({"LOOP_CLAUDE_WORKER_RUNG": "claude-haiku-5-5 at bogus effort"}), (None, None, None))
|
||||
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))
|
||||
for bogus in ("", "five", "-1", "5.0", "²"):
|
||||
with self.subTest(bogus=bogus):
|
||||
self.assertEqual(handed({"LOOP_CLAUDE_ESCAPE_AND_IMPACT": bogus})[2], 0)
|
||||
|
||||
@@ -1,25 +1,26 @@
|
||||
"""The rungs loop-claude hands a worker's claude in its environment, so rule-hook holds each review launch to them: docs/decisions.md → `routing:`.
|
||||
"""The rungs and the E + I loop-claude hands a worker's claude in its environment, from which rule-hook works out the rung of each review launch: docs/decisions.md → `routing:`.
|
||||
|
||||
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, review_rungs, Rung
|
||||
from model_routing.ladder import LADDER, Rung
|
||||
from model_routing.route import Route
|
||||
|
||||
PROJECT_RUNG = "LOOP_CLAUDE_PROJECT_RUNG"
|
||||
WORKER_RUNG = "LOOP_CLAUDE_WORKER_RUNG"
|
||||
REVIEWER_RUNG = "LOOP_CLAUDE_REVIEWER_RUNG"
|
||||
# The E + I the chunk's reviews are routed on, from which review_rungs works out each review's rung.
|
||||
ESCAPE_AND_IMPACT = "LOOP_CLAUDE_ESCAPE_AND_IMPACT"
|
||||
|
||||
|
||||
def environment(project: Rung | None, route: Route) -> dict[str, str]:
|
||||
"""The variables a worker's claude on route starts with. A project off the ladder gets empty project and reviewer rungs, so none is inherited from the environment."""
|
||||
reviewers = review_rungs(project, route.rung, route.reviewed_on())["reviewer"] if project else None
|
||||
return {PROJECT_RUNG: str(project) if project else "", WORKER_RUNG: str(route.rung), REVIEWER_RUNG: str(reviewers) if reviewers else ""}
|
||||
"""The variables a worker's claude on route starts with. A project off the ladder gets an empty project rung, so none is inherited from the environment."""
|
||||
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, Rung | None]:
|
||||
"""The project's, the worker's and the reviewers' rungs, each None when unset or not on the ladder."""
|
||||
return on_the_ladder(environ.get(PROJECT_RUNG)), on_the_ladder(environ.get(WORKER_RUNG)), on_the_ladder(environ.get(REVIEWER_RUNG))
|
||||
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."""
|
||||
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
|
||||
|
||||
|
||||
def on_the_ladder(value: str | None) -> Rung | None:
|
||||
|
||||
+124
-60
@@ -1,15 +1,15 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Score todo.md's items by the formula it states, weighing each achieve goal by its position in README.md, and hold them to its bar.
|
||||
"""Score todo.md's items by the formula it states, weighing code health first and then README.md's achieve goals by their position, and hold them to its bar.
|
||||
|
||||
usage: rank_todo.py [--check] [todo.md]
|
||||
|
||||
Reads todo.md (default: ./todo.md), the README.md beside it, and docs/decisions.md when there is
|
||||
one. Rewrites each item's Score from the formula and sorts the items by release; within a release,
|
||||
question rows come first, then security rows, then the rest, each group by score from highest, then
|
||||
by ID. Then it moves each blocker, an item another's Blocked by cell names, that ranks below an item
|
||||
it blocks to just above the first such item. Orders the details to match. Writes each item's R, and
|
||||
adds the Blocked by and R columns to a table without them. --check writes nothing and fails when the
|
||||
file is not ranked as it would be.
|
||||
Reads todo.md (default: ./todo.md), the README.md beside it, and docs/decisions.md and
|
||||
docs/comprehension-history.md where they exist. Rewrites each item's Score from the formula and
|
||||
sorts the items by release; within a release, question rows come first, then security rows, then
|
||||
the rest, each group by score from highest, then by ID. Then it moves each blocker, an item
|
||||
another's Blocked by cell names, that ranks below an item it blocks to just above the first such
|
||||
item. Orders the details to match. Writes each item's R, and adds the Blocked by and R columns to a
|
||||
table without them. --check writes nothing and fails when the file is not ranked as it would be.
|
||||
|
||||
A valid todo.md; ## Details and each item's detail are optional:
|
||||
|
||||
@@ -37,10 +37,17 @@ A valid todo.md; ## Details and each item's detail are optional:
|
||||
|
||||
- The formula holds numbers, + - * / ** and parentheses over L, E, I, R, S and V.
|
||||
- V sums, over the goals in an item's Moves cell, each goal's weight times how far the item moves it.
|
||||
README.md marks each goal **Maintain:** or **Achieve:**. The one ranked k of n achieve goals, in
|
||||
reading order, a sub-goal such as 1.1 included, weighs (1/k) / (1 + 1/2 + ... + 1/n). Only an item
|
||||
marked defect may name a maintain goal, the one it restores, which weighs as the heaviest achieve
|
||||
goal.
|
||||
README.md marks each goal **Maintain:** or **Achieve:**. Code health, the achieve goal every
|
||||
project shares, ranks first; a Moves cell names it as in `code health by 6`. README.md's achieve
|
||||
goals follow in reading order, a sub-goal such as 1.1 included. Each weighs 0.97 times the one
|
||||
before, and the weights sum to 1. With 5 achieve goals the first weighs 0.212 and the last 0.188.
|
||||
With 15 they weigh 0.082 and 0.053. The overall is the mean of the overall means of every scoring
|
||||
run on docs/comprehension-history.md's newest scored commit. While it is under 7.0, or the history
|
||||
holds no scoring run, code health weighs 4 times its weight by position, and the other goals keep
|
||||
theirs. A line `**Void:** code health, since <reason>.` in README.md's ## Goals drops code health,
|
||||
and an item may not name it. A project must void it where its docs/decisions.md has a
|
||||
`## review opt-out:` title naming the comprehension check. Only an item marked defect may name a
|
||||
maintain goal, the one it restores, which weighs as the heaviest achieve goal.
|
||||
- The bar is judged on the Score as shown, to one decimal.
|
||||
- A new item takes Next ID, and Next ID then goes up by one; every ID stays below it.
|
||||
- An item's L, E and I are levels that ~/.claude/rules/todo-items.md defines: L from 1 to 4, E from 1
|
||||
@@ -64,24 +71,39 @@ A valid todo.md; ## Details and each item's detail are optional:
|
||||
- A table in the old shape, with C, A, G and Goals columns in place of L, E, I and Moves, still
|
||||
ranks, by a formula over R, S, A, G and W and a | Goal | W | table that weighs every README goal, W
|
||||
being the heaviest cited goal's weight; ranking it says to reshape it.
|
||||
- ## Renamed is optional: one line `- 0.2.1 renamed to 0.3.0` per renamed release. chunk-preflight,
|
||||
loop-claude and larv-review skip the line's first release, and ignore the second, which is for the
|
||||
reader. No item may sit under a marked release, and a line goes once a tag at or past its first
|
||||
release is cut. A release whose items all moved elsewhere without a line reads as finished.
|
||||
|
||||
Exit 1, saying why, on bad arguments, a file that cannot be read or written, a todo.md, README.md or
|
||||
docs/decisions.md that breaks the rules above, an item that is not exempt scoring under the bar, or
|
||||
--check finding the file unranked.
|
||||
docs/decisions.md that breaks the rules above, a scoring run on docs/comprehension-history.md's
|
||||
newest scored commit with no Mean row ending in its overall, an item that is not exempt scoring
|
||||
under the bar, or --check finding the file unranked.
|
||||
"""
|
||||
import ast
|
||||
import dataclasses
|
||||
import decimal
|
||||
import math
|
||||
import pathlib
|
||||
import re
|
||||
import sys
|
||||
import typing
|
||||
|
||||
from todo_table import BLOCKED_BY, cells, DETAILS, HEADER_START, Item, item_details, items_table, MOVES, OLD_SHAPE, parse_row, risk, Shape, SHAPE, shape_of, Table, table_rows
|
||||
from todo_table import BLOCKED_BY, cells, CODE_HEALTH, DETAILS, HEADER_START, Item, item_details, items_table, MOVES, OLD_SHAPE, parse_row, renames, risk, Shape, SHAPE, shape_of, Table, table_rows, version
|
||||
from failure import Failure
|
||||
from comprehension_history import FLOOR, HISTORY, latest_overall
|
||||
from markdown_text import listed, sections
|
||||
from file_writes import replace_file
|
||||
|
||||
# What each achieve goal weighs of the one above it; docs/decisions.md records the choice.
|
||||
GOAL_STEP = 0.97
|
||||
# Code health weighs this many times its weight by position while the comprehension panel's overall is under FLOOR, or unmeasured; lilleman's choice, which docs/decisions.md records.
|
||||
UNDER_FLOOR = 4
|
||||
# Any **Void:** line of README.md's ## Goals; ranked_goals accepts only `**Void:** code health, since <reason>.`, as ~/.claude/CLAUDE.md → "Shared goal" spells it.
|
||||
VOID = re.compile(r"^\*\*Void:\*\* (.*)$", re.M)
|
||||
# A docs/decisions.md title opting the project out of the comprehension check, as larv-review's SKILL.md → "Opt-out" spells it.
|
||||
OPTED_OUT = re.compile(r"^## review opt-out:.*\bcomprehension check\b", re.M)
|
||||
LARGEST_FORMULA = 200
|
||||
LONGEST_FORMULA = 4 * LARGEST_FORMULA
|
||||
OPERATORS = (ast.Add, ast.BinOp, ast.Div, ast.Expression, ast.Load, ast.Mult, ast.Pow, ast.Sub, ast.UAdd, ast.UnaryOp, ast.USub)
|
||||
@@ -99,9 +121,9 @@ class Scoring:
|
||||
formula: ast.Expression
|
||||
bar: float
|
||||
next_id: int
|
||||
# README.md's goals in reading order, each with its mark.
|
||||
# Every goal in rank order, each with its mark: code health first, unless README.md voids it, then README.md's goals in reading order. In OLD_SHAPE an item may name only the goals weights holds.
|
||||
goals: dict[str, Mark]
|
||||
# The weight of each goal an item may name: in OLD_SHAPE every goal, at the weight todo.md states; else each goal goal_weights weighs.
|
||||
# The weight of each goal an item may name: in OLD_SHAPE each of README.md's goals, at the weight todo.md states; else each goal goal_weights weighs.
|
||||
weights: dict[str, float]
|
||||
|
||||
|
||||
@@ -109,7 +131,7 @@ class Scoring:
|
||||
class Ranked:
|
||||
text: str
|
||||
under_bar: list[str]
|
||||
# What ranking prints and --check does not: an old-shape table's call to reshape, a README with no achieve goal, and each dropped blocker ID, since a mistyped ID drops the same way.
|
||||
# What ranking prints and --check does not: an old-shape table's call to reshape, a README that voids code health and marks no goal **Achieve:**, and each dropped blocker ID, since a mistyped ID drops the same way.
|
||||
notes: list[str]
|
||||
|
||||
|
||||
@@ -126,19 +148,25 @@ def main(argv: list[str]) -> int:
|
||||
for line in failures:
|
||||
print(line, file=sys.stderr)
|
||||
return 1 if failures else 0
|
||||
texts = read_all(todo)
|
||||
if isinstance(texts, Failure):
|
||||
return fail(texts)
|
||||
ranked = rank(*texts)
|
||||
ranked = rank_file(todo)
|
||||
if isinstance(ranked, Failure):
|
||||
return fail(ranked)
|
||||
if ranked.text != texts[0]:
|
||||
unwritten = write(todo, ranked.text)
|
||||
if unwritten:
|
||||
return fail(unwritten)
|
||||
return 1 if ranked.under_bar else 0
|
||||
|
||||
|
||||
def rank_file(todo: pathlib.Path) -> Ranked | Failure:
|
||||
"""Rank todo in place: rank what read_all reads, write todo where that changed it, and print the notes and under-bar lines on stderr."""
|
||||
texts = read_all(todo)
|
||||
if isinstance(texts, Failure):
|
||||
return texts
|
||||
ranked = rank(*texts)
|
||||
if isinstance(ranked, Failure):
|
||||
return ranked
|
||||
if ranked.text != texts[0] and (unwritten := write(todo, ranked.text)):
|
||||
return unwritten
|
||||
for line in ranked.notes + ranked.under_bar:
|
||||
print(f"{todo}: {line}", file=sys.stderr)
|
||||
return 1 if ranked.under_bar else 0
|
||||
return ranked
|
||||
|
||||
|
||||
def check_failures(todo: pathlib.Path) -> list[str]:
|
||||
@@ -165,10 +193,10 @@ def parse_args(argv: list[str]) -> tuple[bool, pathlib.Path] | Failure:
|
||||
return "--check" in argv, pathlib.Path(paths[0] if paths else "todo.md")
|
||||
|
||||
|
||||
def read_all(todo: pathlib.Path) -> tuple[str, str, str] | Failure:
|
||||
"""todo.md, the README.md beside it, and its docs/decisions.md, empty when there is none."""
|
||||
def read_all(todo: pathlib.Path) -> tuple[str, str, str, str] | Failure:
|
||||
"""todo.md, the README.md beside it, and its docs/decisions.md and docs/comprehension-history.md, each empty when there is none."""
|
||||
texts = []
|
||||
for path, missing in ((todo, "every project keeps a todo.md beside its README.md, and rank_todo.py --help shows one"), (todo.parent / "README.md", "rank_todo.py weighs goals from the README.md beside todo.md"), (todo.parent / "docs" / "decisions.md", None)):
|
||||
for path, missing in ((todo, "every project keeps a todo.md beside its README.md, and rank_todo.py --help shows one"), (todo.parent / "README.md", "rank_todo.py weighs goals from the README.md beside todo.md"), (todo.parent / "docs" / "decisions.md", None), (todo.parent / HISTORY, None)):
|
||||
try:
|
||||
texts.append(path.read_text(encoding="utf-8"))
|
||||
except FileNotFoundError:
|
||||
@@ -179,7 +207,7 @@ def read_all(todo: pathlib.Path) -> tuple[str, str, str] | Failure:
|
||||
return Failure(f"{path}: {failure.strerror}")
|
||||
except UnicodeDecodeError:
|
||||
return Failure(f"{path}: not UTF-8")
|
||||
return texts[0], texts[1], texts[2]
|
||||
return texts[0], texts[1], texts[2], texts[3]
|
||||
|
||||
|
||||
def write(path: pathlib.Path, text: str) -> Failure | None:
|
||||
@@ -187,13 +215,13 @@ def write(path: pathlib.Path, text: str) -> Failure | None:
|
||||
return Failure(f"{path}: {unwritten.reason}") if unwritten else None
|
||||
|
||||
|
||||
def rank(text: str, readme: str, decisions: str) -> Ranked | Failure:
|
||||
def rank(text: str, readme: str, decisions: str, history: str) -> Ranked | Failure:
|
||||
lines = text.split("\n")
|
||||
table = read_table(lines)
|
||||
if isinstance(table, Failure):
|
||||
return table
|
||||
shape = shape_of(table.columns)
|
||||
scoring = read_scoring(text, lines, readme, shape)
|
||||
scoring = read_scoring(text, lines, readme, decisions, history, shape)
|
||||
if isinstance(scoring, Failure):
|
||||
return scoring
|
||||
items = read_items(table, scoring)
|
||||
@@ -201,6 +229,10 @@ def rank(text: str, readme: str, decisions: str) -> Ranked | Failure:
|
||||
return items
|
||||
if uncited := check_citations(items, decisions):
|
||||
return uncited
|
||||
if isinstance(marked := renames(text), Failure):
|
||||
return marked
|
||||
if live := next((item for item in items if item.release in marked), None):
|
||||
return Failure(f"todo.md marks release {version(live.release)} renamed but files item {live.id} under it; drop the mark or move the item")
|
||||
scored = ordered(items, scoring)
|
||||
if isinstance(scored, Failure):
|
||||
return scored
|
||||
@@ -229,7 +261,7 @@ def notes(items: list[Item], scoring: Scoring) -> list[str]:
|
||||
if scoring.shape is OLD_SHAPE:
|
||||
return [RESHAPE] + dropped
|
||||
# Printed so the under-bar lines it causes do not read as items of low value.
|
||||
unweighed = [] if any(scoring.weights.values()) else ["README.md marks no goal **Achieve:**, so every item scores V 0"]
|
||||
unweighed = [] if any(scoring.weights.values()) else ["README.md voids code health and marks no goal **Achieve:**, so every item scores V 0"]
|
||||
return unweighed + dropped
|
||||
|
||||
|
||||
@@ -261,8 +293,8 @@ def under_the_bar(item: Item, value: float, bar: float, items: list[Item]) -> st
|
||||
return f"item {item.id} scores {value:.1f}, under the bar {bar:g}; delete it{blocked}, or mark it with a reason the bar does not apply"
|
||||
|
||||
|
||||
def read_scoring(text: str, lines: list[str], readme: str, shape: Shape) -> Scoring | Failure:
|
||||
goals = readme_goals(readme)
|
||||
def read_scoring(text: str, lines: list[str], readme: str, decisions: str, history: str, shape: Shape) -> Scoring | Failure:
|
||||
goals = ranked_goals(readme, decisions)
|
||||
if isinstance(goals, Failure):
|
||||
return goals
|
||||
formula = parse_formula(stated(text, "Score"), variables(shape))
|
||||
@@ -274,18 +306,41 @@ def read_scoring(text: str, lines: list[str], readme: str, shape: Shape) -> Scor
|
||||
next_id = stated(text, "Next ID")
|
||||
if isinstance(next_id, Failure) or not re.fullmatch(r"[0-9]+", next_id):
|
||||
return next_id if isinstance(next_id, Failure) else Failure(f"Next ID {next_id!r} is not a whole number")
|
||||
numbers = [number for number, _ in goals]
|
||||
if shape is OLD_SHAPE:
|
||||
weights = parse_weights(lines, numbers)
|
||||
elif WEIGHTS_HEADER in lines:
|
||||
weights = Failure(f"todo.md holds a goal weights table beside a {MOVES} column; drop the table, since rank_todo.py weighs each achieve goal by its position in README.md")
|
||||
else:
|
||||
weights = goal_weights(goals)
|
||||
weights = weigh(lines, history, goals, shape)
|
||||
if isinstance(weights, Failure):
|
||||
return weights
|
||||
return Scoring(shape, formula, bar, int(next_id), dict(goals), weights)
|
||||
|
||||
|
||||
def ranked_goals(readme: str, decisions: str) -> list[tuple[str, Mark]] | Failure:
|
||||
"""Every goal in rank order, each with its mark: code health first, unless README.md voids it, then README.md's goals in reading order. A **Void:** line other than `**Void:** code health, since <reason>.` fails, and so does a docs/decisions.md that opts out of the comprehension check where README.md keeps code health, since the goal then has no signal."""
|
||||
goals = readme_goals(readme)
|
||||
if isinstance(goals, Failure):
|
||||
return goals
|
||||
voids = VOID.findall("".join(sections(readme).get("Goals", [])))
|
||||
if other := [void for void in voids if not void.startswith(f"{CODE_HEALTH}, since ")]:
|
||||
if other[0].lower().startswith(CODE_HEALTH):
|
||||
return Failure(f"README.md's ## Goals voids code health as `{other[0]}`; spell the void exactly `**Void:** {CODE_HEALTH}, since <reason>.`")
|
||||
return Failure(f"README.md's ## Goals voids `{other[0]}`; only code health may be voided, as `**Void:** {CODE_HEALTH}, since <reason>.`")
|
||||
if voids:
|
||||
return goals
|
||||
if OPTED_OUT.search(decisions):
|
||||
return Failure(f"docs/decisions.md opts out of the comprehension check, so code health has no signal; void it in README.md's ## Goals with `**Void:** {CODE_HEALTH}, since <reason>.`, as ~/.claude/CLAUDE.md → 'Shared goal' says")
|
||||
return [(CODE_HEALTH, "Achieve"), *goals]
|
||||
|
||||
|
||||
def weigh(lines: list[str], history: str, goals: list[tuple[str, Mark]], shape: Shape) -> dict[str, float] | Failure:
|
||||
"""Each goal's weight. In OLD_SHAPE, README.md's goals weigh what todo.md states, and code health has no weight, so no item may name it. Otherwise goal_weights gives each its weight, at the overall latest_overall reads where the goals hold code health."""
|
||||
if shape is OLD_SHAPE:
|
||||
return parse_weights(lines, [number for number, _ in goals if number != CODE_HEALTH])
|
||||
if WEIGHTS_HEADER in lines:
|
||||
return Failure(f"todo.md holds a goal weights table beside a {MOVES} column; drop the table, since rank_todo.py weighs the goals itself, as its --help says")
|
||||
overall = latest_overall(history) if CODE_HEALTH in dict(goals) else None
|
||||
if isinstance(overall, Failure):
|
||||
return overall
|
||||
return goal_weights(goals, overall)
|
||||
|
||||
|
||||
def read_table(lines: list[str]) -> Table | Failure:
|
||||
"""The items table, held to its shape's columns and alone under ## Items."""
|
||||
if "## Items" not in lines:
|
||||
@@ -359,7 +414,7 @@ def blockers_first(scored: list[tuple[Item, float]]) -> list[tuple[Item, float]]
|
||||
for item, _ in scored:
|
||||
for blocker in item.blocked_by:
|
||||
if blocker in held and held[blocker][0].release > item.release:
|
||||
later, earlier = release_name(held[blocker][0]), release_name(item)
|
||||
later, earlier = version(held[blocker][0].release), version(item.release)
|
||||
return Failure(f"item {item.id}, in release {earlier}, is blocked by item {blocker}, in later release {later}; move item {blocker} to release {earlier} or earlier, or item {item.id} to release {later} or later")
|
||||
result: list[tuple[Item, float]] = []
|
||||
for item, _ in scored:
|
||||
@@ -388,10 +443,6 @@ def place(id_: int, held: dict[int, tuple[Item, float]], position: dict[int, int
|
||||
return [*added, (dataclasses.replace(item, blocked_by=tuple(sorted(blockers))), value)]
|
||||
|
||||
|
||||
def release_name(item: Item) -> str:
|
||||
return ".".join(str(part) for part in item.release)
|
||||
|
||||
|
||||
def check_citations(items: list[Item], decisions: str) -> Failure | None:
|
||||
"""Holds todo.md and docs/decisions.md to each other: a cited item is exempt, a decision row is cited."""
|
||||
cited = set(cited_items(decisions))
|
||||
@@ -425,13 +476,15 @@ def readme_goals(readme: str) -> list[tuple[str, Mark]] | Failure:
|
||||
return goals
|
||||
|
||||
|
||||
def goal_weights(goals: list[tuple[str, Mark]]) -> dict[str, float] | Failure:
|
||||
"""Each achieve goal's sum-reciprocal weight: the one ranked k of n in reading order weighs (1/k) / (1 + 1/2 + ... + 1/n). Each maintain goal weighs as the heaviest achieve goal, since a broken one outranks any achieve goal; only a defect that restores it may name it. Every weight is 0 where README.md marks no goal **Achieve:**, so every item scores V 0 and only an exempt one passes the bar."""
|
||||
def goal_weights(goals: list[tuple[str, Mark]], overall: decimal.Decimal | None) -> dict[str, float] | Failure:
|
||||
"""Each achieve goal's weight: the one ranked k of n weighs GOAL_STEP ** (k - 1) / (1 + GOAL_STEP + ... + GOAL_STEP ** (n - 1)), so the weights sum to 1. Code health, where goals holds it, then weighs UNDER_FLOOR times that while the overall is under FLOOR or None, and the other goals keep their weights. Each maintain goal weighs as the heaviest achieve goal, since a broken one outranks any achieve goal; only a defect that restores it may name it. Every weight is 0 where goals holds no achieve goal, as where README.md voids code health and marks no goal **Achieve:**, so every item scores V 0 and only an exempt one passes the bar."""
|
||||
if unmarked := [number for number, mark in goals if mark is None]:
|
||||
return Failure(f"README.md's goal {unmarked[0]} is marked neither **Maintain:** nor **Achieve:**; mark it, as ~/.claude/rules/goals-and-audience.md says, so rank_todo.py knows which goals score")
|
||||
achieve = [number for number, mark in goals if mark == "Achieve"]
|
||||
harmonic = sum(1 / rank for rank in range(1, len(achieve) + 1))
|
||||
weights = {number: 1 / rank / harmonic for rank, number in enumerate(achieve, 1)}
|
||||
total = sum(GOAL_STEP**rank for rank in range(len(achieve)))
|
||||
weights = {number: GOAL_STEP**rank / total for rank, number in enumerate(achieve)}
|
||||
if CODE_HEALTH in weights and (overall is None or overall < FLOOR):
|
||||
weights[CODE_HEALTH] *= UNDER_FLOOR
|
||||
heaviest = max(weights.values(), default=0.0)
|
||||
return weights | {number: heaviest for number, mark in goals if mark == "Maintain"}
|
||||
|
||||
@@ -555,25 +608,36 @@ def parse_weights(lines: list[str], goals: list[str]) -> dict[str, float] | Fail
|
||||
|
||||
|
||||
def parse_item(row: str, scoring: Scoring, table: Table) -> Item | Failure:
|
||||
"""The row as an item, refused where it names a goal it may not; in SHAPE, with the R its L, E and I give."""
|
||||
item = parse_row(row, table)
|
||||
if isinstance(item, Failure):
|
||||
return item
|
||||
if broken := cited_goals_failure(item, scoring):
|
||||
return broken
|
||||
if scoring.shape is OLD_SHAPE:
|
||||
if unknown := [goal for goal, _ in item.moves if goal not in scoring.weights]:
|
||||
return Failure(f"item {item.id} cites goal {', '.join(unknown)}, which the goal weights do not list")
|
||||
return item
|
||||
for goal, _ in item.moves:
|
||||
if goal not in scoring.goals:
|
||||
return Failure(f"item {item.id} cites goal {goal}, which README.md's ## Goals does not number")
|
||||
if scoring.goals[goal] == "Maintain" and item.exempt != "defect":
|
||||
return Failure(f"item {item.id} cites goal {goal}, a maintain goal, which only a defect that restores it may name; name the achieve goals the item moves")
|
||||
# R is written here, as the Score is, so --check finds a stale one, and a reader keeps the R the table stored.
|
||||
return dataclasses.replace(item, scores=item.scores | {"R": risk(item.scores["L"], item.scores["E"], item.scores["I"])})
|
||||
|
||||
|
||||
def cited_goals_failure(item: Item, scoring: Scoring) -> Failure | None:
|
||||
"""Why the item may not name one of the goals it names, such as one README.md voids or does not number; None when it may name each. todo_table's parse_moves holds the rules a Moves cell keeps on its own."""
|
||||
if scoring.shape is OLD_SHAPE:
|
||||
unknown = [goal for goal, _ in item.moves if goal not in scoring.weights]
|
||||
return Failure(f"item {item.id} cites goal {', '.join(unknown)}, which the goal weights do not list") if unknown else None
|
||||
for goal, _ in item.moves:
|
||||
if goal == CODE_HEALTH and goal not in scoring.goals:
|
||||
return Failure(f"item {item.id} names {CODE_HEALTH}, which README.md voids; drop it from the item's {MOVES}, or the void from README.md")
|
||||
if goal not in scoring.goals:
|
||||
return Failure(f"item {item.id} cites goal {goal}, which README.md's ## Goals does not number")
|
||||
if scoring.goals[goal] == "Maintain" and item.exempt != "defect":
|
||||
return Failure(f"item {item.id} cites goal {goal}, a maintain goal, which only a defect that restores it may name; name the achieve goals the item moves")
|
||||
return None
|
||||
|
||||
|
||||
def render_item(item: Item, value: float, shape: Shape, columns: tuple[str, ...]) -> str:
|
||||
"""The item's row, each cell under its column."""
|
||||
written = {"ID": str(item.id), "Release": release_name(item), BLOCKED_BY: ", ".join(map(str, item.blocked_by)), "Exempt": item.exempt, "Item": item.tagline, **{name: str(score) for name, score in item.scores.items()}, shape.goals_column: shape.write_goals(item.moves), "Score": f"{value:.1f}"}
|
||||
written = {"ID": str(item.id), "Release": version(item.release), BLOCKED_BY: ", ".join(map(str, item.blocked_by)), "Exempt": item.exempt, "Item": item.tagline, **{name: str(score) for name, score in item.scores.items()}, shape.goals_column: shape.write_goals(item.moves), "Score": f"{value:.1f}"}
|
||||
return "| " + " | ".join(written[column] for column in columns) + " |"
|
||||
|
||||
|
||||
|
||||
@@ -41,6 +41,10 @@ class Gitignore(unittest.TestCase):
|
||||
ignored = subprocess.run(["git", "ls-files", "-ci", "--exclude-standard"], capture_output=True, check=True, cwd=ROOT, text=True).stdout
|
||||
self.assertEqual(ignored, "")
|
||||
|
||||
def test_ignores_no_python_module_or_test_under_bin(self):
|
||||
ignored = subprocess.run(["git", "ls-files", "-oi", "--exclude-standard", "--", "bin/*.py", "bin/**/*.py"], capture_output=True, check=True, cwd=ROOT, text=True).stdout
|
||||
self.assertEqual(ignored, "")
|
||||
|
||||
def test_ignores_every_private_file(self):
|
||||
ignored = subprocess.run(["git", "check-ignore", "--no-index", "--stdin"], capture_output=True, cwd=ROOT, input="\n".join(PRIVATE), text=True).stdout
|
||||
self.assertEqual(ignored.splitlines(), PRIVATE)
|
||||
|
||||
@@ -5,20 +5,27 @@ import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from rule_hook.reviewer_rung import REVIEWERS, SEAT, SECURITY_OPENER
|
||||
from round_titles import PASSES
|
||||
from model_routing.ladder import REVIEWERS
|
||||
from repo_checks.test_python_floor import ROOT
|
||||
from rule_hook.reviewer_rung import SEAT, SECURITY_OPENER
|
||||
|
||||
OPENING = re.compile(r"^## Opening\n+```\n([^\n]+?\.)(?: |\n)", re.MULTILINE)
|
||||
REVIEWER_NAME = re.compile(r"\b[a-z]+(?:-[a-z]+)*-(?:reviewer|architect|auditor)\b")
|
||||
# A row of the pass table whose reviewer is an agent: its pass and that agent.
|
||||
REVIEWED_ROW = re.compile(r"^\| ([A-Z][a-z-]+) \| ([a-z]+(?:-[a-z]+)*-(?:reviewer|architect|auditor)) \|", re.MULTILINE)
|
||||
LARV_REVIEW = (ROOT / "skills" / "larv-review" / "SKILL.md").read_text(encoding="utf-8")
|
||||
|
||||
|
||||
class ReviewerLaunches(unittest.TestCase):
|
||||
"""rule-hook holds a review launch to its rung by recognising it; these fail when what it recognises drifts from what the skills launch."""
|
||||
|
||||
def test_the_reviewers_are_the_ones_larv_review_s_pass_table_names(self):
|
||||
def test_the_reviewers_are_the_passes_and_agents_larv_review_s_pass_table_names_in_its_order(self):
|
||||
passes = LARV_REVIEW.split("## 3. Passes", 1)[1].split("A comment is prose", 1)[0]
|
||||
self.assertEqual(set(REVIEWER_NAME.findall(passes)), REVIEWERS)
|
||||
self.assertEqual({name.lower(): agent for name, agent in REVIEWED_ROW.findall(passes)}, REVIEWERS)
|
||||
self.assertEqual([name.lower() for name, _ in REVIEWED_ROW.findall(passes)], list(REVIEWERS))
|
||||
|
||||
def test_each_reviewed_pass_is_a_pass_the_round_titles_count(self):
|
||||
self.assertEqual([name for name in PASSES if name in REVIEWERS], list(REVIEWERS))
|
||||
|
||||
def test_the_seat_opening_is_the_sentence_that_opens_every_seat_prompt(self):
|
||||
opening = OPENING.search((ROOT / "skills" / "comprehension-panel" / "seat-prompts.md").read_text(encoding="utf-8"))
|
||||
@@ -28,3 +35,6 @@ class ReviewerLaunches(unittest.TestCase):
|
||||
def test_the_security_opening_is_the_sentence_larv_review_has_the_security_pass_open_with(self):
|
||||
security = LARV_REVIEW.split("### Security", 1)[1].split("### Overrides", 1)[0]
|
||||
self.assertIn(SECURITY_OPENER, security)
|
||||
|
||||
def test_larv_review_has_the_tool_make_the_reports_folder_rule_hook_lets_a_reviewer_write_into(self):
|
||||
self.assertIn("`~/.claude/bin/larv-review review-folder`", LARV_REVIEW)
|
||||
|
||||
@@ -15,5 +15,5 @@ class Types(unittest.TestCase):
|
||||
self.assertIsNotNone(floor, "README.md's Install names `Python 3.N or newer`")
|
||||
if shutil.which("uv") is None:
|
||||
self.fail("uv on PATH fetches mypy; see README.md's Test line")
|
||||
ran = subprocess.run(["uv", "tool", "run", "--python", "%d.%d" % floor, "mypy==2.3.1", "--cache-dir=/dev/null", "--check-untyped-defs", "--disallow-untyped-defs", "--exclude", "/test_", "-p", "chunk_preflight", "-p", "claude_code", "-m", "comprehension_history", "-m", "git_repo", "-p", "judge_replay", "-p", "larv_review", "-p", "loop_claude", "-m", "markdown_text", "-p", "metric_bench", "-m", "project_key", "-m", "rank_todo", "-m", "round_titles", "-p", "reading_cost", "-p", "rule_hook", "-p", "rung_replay", "-p", "score_outcomes", "-p", "stability_replay", "-p", "subagent_rung", "-m", "shell_command", "-m", "statusline", "-m", "todo_table", "-p", "transcript_archive", "-m", "utc_stamp"], capture_output=True, cwd=ROOT / "bin", text=True)
|
||||
ran = subprocess.run(["uv", "tool", "run", "--python", "%d.%d" % floor, "mypy==2.3.1", "--cache-dir=/dev/null", "--check-untyped-defs", "--disallow-untyped-defs", "--exclude", "/test_", "-p", "chunk_preflight", "-p", "claude_code", "-m", "comprehension_history", "-m", "git_repo", "-p", "judge_replay", "-p", "larv_review", "-p", "loop_claude", "-m", "markdown_text", "-p", "metric_bench", "-m", "project_key", "-m", "rank_todo", "-m", "round_titles", "-p", "reading_cost", "-p", "review_replay", "-p", "rule_hook", "-p", "rung_replay", "-p", "score_outcomes", "-p", "subagent_rung", "-m", "shell_command", "-m", "statusline", "-m", "todo_table", "-p", "transcript_archive", "-m", "utc_stamp"], capture_output=True, cwd=ROOT / "bin", text=True)
|
||||
self.assertEqual(ran.returncode, 0, ran.stdout + ran.stderr)
|
||||
|
||||
@@ -5,7 +5,7 @@ import sys
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
|
||||
|
||||
from stability_replay import main
|
||||
from review_replay import main
|
||||
from loop_claude.effects import system_effects
|
||||
|
||||
sys.exit(main.main(sys.argv[1:], os.environ, pathlib.Path.home(), system_effects()))
|
||||
@@ -0,0 +1,11 @@
|
||||
"""The chunk's review folder, where each reviewer writes its report: skills/larv-review/SKILL.md → "Reports"."""
|
||||
import os
|
||||
|
||||
# Why here: docs/decisions.md → `review: each reviewer under agents/ writes its full report into the chunk's review folder`.
|
||||
REPORTS = ".local/state/larv-review"
|
||||
|
||||
|
||||
def review_folder(home: str, worktree: str) -> str:
|
||||
"""The review folder of the chunk whose worktree is at worktree: its path relative to home, or to / outside it, under REPORTS."""
|
||||
inside = worktree.startswith(home.rstrip("/") + "/")
|
||||
return os.path.join(home, REPORTS, os.path.relpath(worktree, home) if inside else worktree.lstrip("/"))
|
||||
@@ -0,0 +1,280 @@
|
||||
"""Replay a review pass's archived rounds on the rungs below the project's, to find which rungs may run its reviewer: docs/decisions.md → `routing: a review pass runs below the project's rung only on a rung that a replay of its rounds shows finding every 🔴 and 🟡 the project's rung finds`.
|
||||
|
||||
usage: review-replay <pass> <model>
|
||||
|
||||
<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
|
||||
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
|
||||
authored by the time the round began, on the branch the reviewer started on. The clone's default
|
||||
branch stands at the newest commit authored before the round's chunk began, so a diff against it
|
||||
shows the chunk's change. The prompt names the clone in place of the worktree it named, which the
|
||||
chunk has since removed. A round whose code it cannot find in this way is not replayed; stderr
|
||||
names it and why. The prompt also names a copy of the chunk's review folder in place of that
|
||||
folder, holding only the reports written after the chunk began and before the round did. A replay
|
||||
finds nothing where its prompt still names the review folder, or names a file there, other than a
|
||||
round's report, that the folder did not hold from the chunk's start until the round's.
|
||||
|
||||
It first replays every round on the project's rung, the reference reviewer. Findings on record
|
||||
that the reference reviewer does not raise again may rest on code or rules that have changed
|
||||
since; no rung is held to them. It then replays the rounds where the reference raised any, on each
|
||||
rung below, highest first, down to the ladder's lowest, and stops at the first rung that misses
|
||||
one. For each replay, claude on the project's rung matches the report to the findings on record,
|
||||
and counts a finding only where the report raises it as 🔴 or 🟡. The tool prints each finding a
|
||||
rung missed and the lowest rung that, like each rung above it, missed none. That rung is the
|
||||
evidence for running the pass's reviewer on it; the decision above records each run.
|
||||
|
||||
Like the loop, it tries claude three times running before it counts a reply as failed. A failed
|
||||
review or match finds nothing. Exit 1, saying why, on bad arguments, an unreadable archive or
|
||||
models file, no archived round to replay, or a usage limit.
|
||||
"""
|
||||
import dataclasses
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import typing
|
||||
|
||||
from transcript_archive.location import archive_root
|
||||
from rung_replay.command import arguments_or_exit, down_from, failed, limited_exit, projects_on
|
||||
from review_replay.rounds import authored_by, lost_inputs, report, reviewed_path, Round, round_from, sample, stamp_seconds
|
||||
from project_key import checkout_of
|
||||
from claude_code.reply import claude_reply, Limited
|
||||
from loop_claude.effects import Effects
|
||||
from failure import Failure
|
||||
from rung_replay.search import first_reply, replayed
|
||||
from claude_code.transcript import first_timestamped_line, read_transcript
|
||||
from model_routing.ladder import LADDER, project_rung, ReviewedPass, REVIEWERS, Rung
|
||||
from claude_code.entries import parse_entry, structured_output
|
||||
from review_folder import REPORTS, review_folder
|
||||
|
||||
TOOL = "review-replay"
|
||||
USAGE = f"{TOOL} <pass> <model>, <pass> one of {', '.join(REVIEWERS)} and <model> a model on the routing ladder"
|
||||
LATEST = 10
|
||||
MATCH_SCHEMA = {"type": "object", "properties": {"found": {"type": "array", "items": {"type": "integer"}}}, "required": ["found"], "additionalProperties": False}
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Code:
|
||||
"""Where a round's reviewer read the code, the commit it read, the default branch, and where that branch stood as the chunk began."""
|
||||
path: str
|
||||
reviewed: str
|
||||
default: str
|
||||
base: str
|
||||
|
||||
|
||||
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)
|
||||
if isinstance(read, int):
|
||||
return read
|
||||
reviewed, anchor = read
|
||||
rounds = archived_rounds(REVIEWERS[reviewed], anchor.model, archive_root(home, env), home)
|
||||
if isinstance(rounds, Failure):
|
||||
return failed(TOOL, rounds.reason)
|
||||
codes = codes_found(rounds, effects)
|
||||
if not codes:
|
||||
return failed(TOOL, f"no archived {reviewed} round of projects on {anchor.model} in {archive_root(home, env)} holds a 🔴 or 🟡 on code it can find")
|
||||
chosen = sample(list(codes), LATEST)
|
||||
# The project's rung is the reference, so the candidates start below it. They reach the ladder's lowest rung, below the lowest a worker routes to, since a pass may run below the worker's rung.
|
||||
candidates = down_from(anchor, LADDER[0])[1:]
|
||||
|
||||
def found_on(found: Round, rung: Rung) -> set[int] | Limited:
|
||||
return findings_found(found, codes[found], rung, anchor, home, effects)
|
||||
|
||||
replay = replayed(chosen, anchor, candidates, found_on, reproduced, f"{reviewed} rounds")
|
||||
if isinstance(replay, Limited):
|
||||
return limited_exit(TOOL, replay)
|
||||
print(report(reviewed, anchor.model, anchor, chosen, replay))
|
||||
return 0
|
||||
|
||||
|
||||
def pass_and_model(argv: list[str]) -> tuple[ReviewedPass, Rung] | None:
|
||||
"""The pass and the project's rung of the model argv names, as `<pass> <model>`; None for any other argv."""
|
||||
if len(argv) != 2:
|
||||
return None
|
||||
reviewed = next((kind for kind in REVIEWERS if kind == argv[0]), None)
|
||||
anchor = project_rung(argv[1])
|
||||
return (reviewed, anchor) if reviewed and anchor else None
|
||||
|
||||
|
||||
def codes_found(rounds: list[Round], effects: Effects) -> dict[Round, Code]:
|
||||
"""The code each round reviewed, as code_of finds it; stderr names each round left out, and why."""
|
||||
codes = {}
|
||||
for found in rounds:
|
||||
if isinstance(code := code_of(found, effects), Failure):
|
||||
print(f"{found.root} {found.at} is left out: {code.reason}", file=sys.stderr, flush=True)
|
||||
else:
|
||||
codes[found] = code
|
||||
return codes
|
||||
|
||||
|
||||
def reproduced(_: Round, found: set[int]) -> list[int]:
|
||||
"""The indexes of the round's findings that a replay on the reference reviewer found, which each lower rung is held to."""
|
||||
return sorted(found)
|
||||
|
||||
|
||||
def archived_rounds(reviewer: str, model: str, root: pathlib.Path, home: pathlib.Path) -> list[Round] | Failure:
|
||||
projects = projects_on(model, home)
|
||||
if isinstance(projects, Failure):
|
||||
return projects
|
||||
found = []
|
||||
try:
|
||||
for key in projects:
|
||||
for chunk in sorted(path for path in (root / key).glob("*") if path.is_dir()):
|
||||
found += chunk_rounds(reviewer, checkout_of(key, home), chunk)
|
||||
except (OSError, UnicodeDecodeError, ValueError) as failure:
|
||||
return Failure(f"could not read the archive {root}: {failure}")
|
||||
return found
|
||||
|
||||
|
||||
def chunk_rounds(reviewer: str, checkout: str, chunk: pathlib.Path) -> list[Round]:
|
||||
copies = sorted(chunk.glob("*.jsonl"))
|
||||
began = parse_entry(first_timestamped_line(copies[0].read_bytes())) if copies else None
|
||||
if not began or not isinstance(began.get("timestamp"), str):
|
||||
return []
|
||||
found = []
|
||||
for meta in sorted(chunk.glob("session/*/subagents/*.meta.json")):
|
||||
described = json.loads(meta.read_text(encoding="utf-8"))
|
||||
if not isinstance(described, dict) or described.get("agentType") != reviewer:
|
||||
continue
|
||||
entries = read_transcript(str(meta.with_name(meta.name.removesuffix(".meta.json") + ".jsonl")))
|
||||
if not isinstance(entries, Failure) and (one := round_from(reviewer, checkout, stamp_seconds(began["timestamp"]), entries)):
|
||||
found.append(one)
|
||||
return found
|
||||
|
||||
|
||||
def code_of(found: Round, effects: Effects) -> Code | Failure:
|
||||
"""Where, and at which commits, found's reviewer read the code, as the archive lets it be found again: the prompt's removed worktree, and the commits authored by then.
|
||||
|
||||
Recording the reviewed commit at review time would need no such reading, but then no round archived before that change could be replayed. A wrong guess costs no rung: the reference reviewer, replayed on that code, finds fewer findings on record, and no rung is held to those.
|
||||
"""
|
||||
if not os.path.isdir(found.root):
|
||||
return Failure("the project has no checkout")
|
||||
path = reviewed_path(found.prompt, found.root, os.path.exists)
|
||||
if path is None:
|
||||
return Failure("the prompt names neither one removed worktree nor the checkout")
|
||||
default = git(effects, found.root, "symbolic-ref", "--short", "refs/remotes/origin/HEAD")
|
||||
if isinstance(default, Failure):
|
||||
return default
|
||||
default = default.strip().removeprefix("origin/")
|
||||
log = git(effects, found.root, "log", "--format=%H %at", f"refs/remotes/origin/{default}")
|
||||
main_line = git(effects, found.root, "log", "--first-parent", "--format=%H %at", f"refs/remotes/origin/{default}")
|
||||
if isinstance(log, Failure):
|
||||
return log
|
||||
if isinstance(main_line, Failure):
|
||||
return main_line
|
||||
reviewed, base = authored_by(commit_log(log), found.seconds), authored_by(commit_log(main_line), found.began)
|
||||
if reviewed is None or base is None:
|
||||
return Failure("no commit was authored by then")
|
||||
return Code(path, reviewed, default, base)
|
||||
|
||||
|
||||
def commit_log(listed: str) -> list[tuple[str, float]]:
|
||||
return [(commit, float(authored)) for commit, authored in (line.split() for line in listed.splitlines())]
|
||||
|
||||
|
||||
def findings_found(found: Round, code: Code, rung: Rung, anchor: Rung, home: pathlib.Path, effects: Effects) -> set[int] | Limited:
|
||||
"""The indexes of the round's findings that its replay on rung reports, as the reviewer on anchor matches them."""
|
||||
reviewed: str | Failure | Limited = first_reply(lambda: review(found, code, rung, home, effects))
|
||||
if isinstance(reviewed, Limited):
|
||||
return reviewed
|
||||
matched: set[int] | Failure | Limited = reviewed if isinstance(reviewed, Failure) else first_reply(lambda: match(found.findings, reviewed, found.root, anchor, effects))
|
||||
if isinstance(matched, Failure):
|
||||
print(f" {found.root} {found.at} on {rung} found nothing: {matched.reason}", file=sys.stderr, flush=True)
|
||||
return set()
|
||||
return matched
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Copies:
|
||||
"""The throwaway copies a replay hands its reviewer: clone, of the project's checkout, and reports, of the chunk's review folder."""
|
||||
clone: str
|
||||
reports: str
|
||||
|
||||
|
||||
# The shell makes and removes the clone itself, and is tested on a temporary home as judge-replay's is; rounds.py's core takes the filesystem as an argument.
|
||||
def review(found: Round, code: Code, rung: Rung, home: pathlib.Path, effects: Effects) -> str | Failure | Limited:
|
||||
try:
|
||||
(home / REPORTS).mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
with tempfile.TemporaryDirectory(prefix="review-replay-", ignore_cleanup_errors=True) as clone, tempfile.TemporaryDirectory(prefix="review-replay-", dir=home / REPORTS, ignore_cleanup_errors=True) as reports:
|
||||
return reviewed_in(found, code, rung, Copies(clone, reports), home, effects)
|
||||
except OSError as failure:
|
||||
return Failure(f"could not prepare the replay: {failure}")
|
||||
|
||||
|
||||
def reviewed_in(found: Round, code: Code, rung: Rung, copies: Copies, home: pathlib.Path, effects: Effects) -> str | Failure | Limited:
|
||||
"""The report of found's reviewer on rung, replayed on code cloned into copies.clone, with its review folder copied into copies.reports."""
|
||||
folder = pathlib.Path(review_folder(str(home), code.path))
|
||||
copy_reports(found, folder, copies.reports)
|
||||
prompt = redirected(found.prompt, home, folder, code.path, copies)
|
||||
if isinstance(prompt, Failure):
|
||||
return prompt
|
||||
if lost := lost_inputs(prompt, copies.reports, lambda name: (pathlib.Path(copies.reports) / name).exists()):
|
||||
return Failure(f"the prompt names {', '.join(lost)}, which the review folder did not hold from the chunk's start until the round's")
|
||||
if isinstance(cloned := clone_reviewed(found, code, copies.clone, effects), Failure):
|
||||
return cloned
|
||||
reply = claude_reply(effects.claude, ["--agent", found.reviewer, *rung.flags()], copies.clone, prompt, "claude")
|
||||
if isinstance(reply, Failure | Limited):
|
||||
return reply
|
||||
return reply["result"] if isinstance(reply.get("result"), str) else Failure("the reviewer replied with no report")
|
||||
|
||||
|
||||
def copy_reports(found: Round, folder: pathlib.Path, reports: str) -> None:
|
||||
"""Copies into reports each report written to folder after found's chunk began and before its round did."""
|
||||
# The round's own report, any later one, and one from an earlier attempt at the item in the same worktree would each hand the reviewer the findings it is to find.
|
||||
for written in folder.iterdir() if folder.is_dir() else ():
|
||||
if written.is_file() and found.began <= written.stat().st_mtime < found.seconds:
|
||||
shutil.copy2(written, reports)
|
||||
|
||||
|
||||
def redirected(prompt: str, home: pathlib.Path, folder: pathlib.Path, worktree: str, copies: Copies) -> str | Failure:
|
||||
"""prompt naming copies.reports in place of the review folder, in either spelling, and copies.clone in place of the worktree; a Failure where it still names the review folder."""
|
||||
# Replace the folder's path first: outside home it contains the worktree's path, which replacing the worktree's would otherwise turn into the clone's.
|
||||
prompt = prompt.replace(str(folder), copies.reports).replace(f"~/{folder.relative_to(home)}", copies.reports).replace(worktree, copies.clone)
|
||||
# A spelling the rewrite misses, such as $HOME/, would leave the reviewer the live folder and the findings in it.
|
||||
if REPORTS in prompt.replace(copies.reports, ""):
|
||||
return Failure("the prompt names the review folder in a spelling the replay does not redirect")
|
||||
return prompt
|
||||
|
||||
|
||||
def clone_reviewed(found: Round, code: Code, clone: str, effects: Effects) -> Failure | None:
|
||||
"""Clones found's checkout into clone, on the commit its reviewer read, with the default branch where it stood as the chunk began."""
|
||||
for command in (
|
||||
("clone", "--quiet", "--shared", "--no-checkout", found.root, clone),
|
||||
("-C", clone, "update-ref", f"refs/remotes/origin/{code.default}", code.base),
|
||||
("-C", clone, "update-ref", f"refs/heads/{code.default}", code.base),
|
||||
("-C", clone, "checkout", "--quiet", *(("-B", found.branch) if found.branch and found.branch != code.default else ("--detach",)), code.reviewed),
|
||||
):
|
||||
if isinstance(ran := git(effects, found.root, *command), Failure):
|
||||
return ran
|
||||
return None
|
||||
|
||||
|
||||
def match(findings: tuple[str, ...], replay_report: str, root: str, rung: Rung, effects: Effects) -> set[int] | Failure | Limited:
|
||||
numbered = "\n\n".join(f"{n}. {finding}" for n, finding in enumerate(findings, 1))
|
||||
prompt = (
|
||||
"A code reviewer reported the numbered findings below. Another reviewer then reviewed the same change; its report follows them. "
|
||||
"List the number of each finding that the other report also raises as 🔴 or 🟡: the same defect, at the same place or from the same cause, however it is worded. "
|
||||
"A finding it raises only as 🟢 or ❓, or not at all, is not listed.\n\n"
|
||||
f"The findings:\n{numbered}\n\nThe other report:\n{replay_report}"
|
||||
)
|
||||
args = ["--json-schema", json.dumps(MATCH_SCHEMA), *rung.flags(), "--tools", ""]
|
||||
reply = claude_reply(effects.claude, args, root, prompt, "claude")
|
||||
if isinstance(reply, Failure | Limited):
|
||||
return reply
|
||||
output = structured_output(reply)
|
||||
numbers = output.get("found") if isinstance(output, dict) else None
|
||||
if not isinstance(numbers, list) or not all(isinstance(n, int) for n in numbers):
|
||||
return Failure(f"the match replied: {json.dumps(reply)}")
|
||||
return {n - 1 for n in numbers if 1 <= n <= len(findings)}
|
||||
|
||||
|
||||
def git(effects: Effects, cwd: str, *args: str) -> str | Failure:
|
||||
try:
|
||||
ran = effects.git(list(args), cwd)
|
||||
except OSError as failure:
|
||||
return Failure(f"git {' '.join(args)} could not start in {cwd}: {failure.strerror}")
|
||||
return ran.stdout if ran.returncode == 0 else Failure(f"git {' '.join(args)}: {ran.stderr.strip()}")
|
||||
@@ -1,4 +1,4 @@
|
||||
"""Which archived stability rounds to replay, the code each reviewed, and the report: docs/decisions.md → `routing: the stability reviewer runs no lower than the project's rung`."""
|
||||
"""Which archived rounds of a review pass to replay, the code each reviewed, and the report: docs/decisions.md → `routing: a review pass runs below the project's rung only on a rung that a replay of its rounds shows finding every 🔴 and 🟡 the project's rung finds`."""
|
||||
import dataclasses
|
||||
import datetime
|
||||
import pathlib
|
||||
@@ -14,11 +14,14 @@ FINDING = re.compile(r"^[\s#>*+|-]*(?:\d+[.)]\s*)?[*_]*\s*(?:🔴|🟡)")
|
||||
# An absolute path in a prompt, up to the quote, bracket or punctuation that ends it.
|
||||
PATH = re.compile(r"/[^\s`'\"()<>\[\],;]+")
|
||||
LINE_OR_STOP = re.compile(r"(?::\d+(?:-\d+)?)?[.:]?$")
|
||||
# A round's report, as skills/larv-review/SKILL.md → "Reports" names it, such as stability-round-2.md or principles-goals-round-1-rerun.md.
|
||||
ROUND_REPORT = re.compile(r"-round-\d+(?:-rerun)?\.md$")
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Round:
|
||||
"""One archived stability review of the checkout at root, at the UTC stamp at, in a chunk that began at began: its prompt, and the 🔴 and 🟡 findings its report holds, each with its lines up to the next blank line or finding."""
|
||||
"""One archived review by the agent reviewer of the checkout at root, at the UTC stamp at, in a chunk that began at began: its prompt, and the 🔴 and 🟡 findings its report holds, each with its lines up to the next blank line or finding."""
|
||||
reviewer: str
|
||||
root: str
|
||||
branch: str
|
||||
at: str
|
||||
@@ -31,15 +34,15 @@ class Round:
|
||||
return stamp_seconds(self.at)
|
||||
|
||||
|
||||
def round_from(root: str, began: float, entries: list[dict]) -> Round | None:
|
||||
"""The round a stability reviewer's transcript holds: its first entry's prompt, and its last text. None without a 🔴 or 🟡 finding to hold a rung to."""
|
||||
def round_from(reviewer: str, root: str, began: float, entries: list[dict]) -> Round | None:
|
||||
"""The round a reviewer's transcript holds: its first entry's prompt, and its last text. None without a 🔴 or 🟡 finding to hold a rung to."""
|
||||
reports = [text for found in entries for part in assistant_parts(found) if (text := part_text(part))]
|
||||
first = entries[0] if entries else {}
|
||||
if not stamped(first) or not reports or not (findings := recorded_findings(reports[-1])):
|
||||
return None
|
||||
prompt = content(first)
|
||||
prompt = prompt if isinstance(prompt, str) else "".join(part_text(part) or "" for part in parts(first))
|
||||
return Round(root, first.get("gitBranch", ""), first["timestamp"], began, prompt, tuple(findings))
|
||||
return Round(reviewer, root, first.get("gitBranch", ""), first["timestamp"], began, prompt, tuple(findings))
|
||||
|
||||
|
||||
def stamped(entry: dict) -> bool:
|
||||
@@ -84,6 +87,12 @@ def reviewed_path(prompt: str, root: str, exists: typing.Callable[[str], bool])
|
||||
return root if not gone and root in named else None
|
||||
|
||||
|
||||
def lost_inputs(prompt: str, reports: str, held: typing.Callable[[str], bool]) -> list[str]:
|
||||
"""The files the prompt names in reports, the copy of a round's review folder, that the copy does not hold, other than round reports. A report the copy lacks is the round's own or a later one, left out on purpose; any other file it lacks, such as a branch diff written again after the round began, would leave the replay without an input the round had."""
|
||||
named = [LINE_OR_STOP.sub("", path).removeprefix(reports + "/") for path in PATH.findall(prompt) if path.startswith(reports + "/")]
|
||||
return sorted({name for name in named if not ROUND_REPORT.search(name) and not held(name)})
|
||||
|
||||
|
||||
def authored_by(log: list[tuple[str, float]], seconds: float) -> str | None:
|
||||
"""The newest commit in log, which lists newest first, authored at or before seconds. A rebase keeps author times, so a merged branch's commits still say what it held."""
|
||||
return next((commit for commit, authored in log if authored <= seconds), None)
|
||||
@@ -94,10 +103,10 @@ def sample(rounds: list[Round], latest: int) -> list[Round]:
|
||||
return sorted(rounds, key=lambda found: (found.seconds, found.root))[-latest:]
|
||||
|
||||
|
||||
def report(model: str, reference: Rung, rounds: list[Round], replay: Replay[Round, int, set[int]]) -> str:
|
||||
def report(reviewed: str, model: str, reference: Rung, rounds: list[Round], replay: Replay[Round, int, set[int]]) -> str:
|
||||
total = sum(len(found_round.findings) for found_round in rounds)
|
||||
lines = [
|
||||
f"Replayed {len(rounds)} stability rounds of {model} projects, holding {total} 🔴 and 🟡 findings.",
|
||||
f"Replayed {len(rounds)} {reviewed} rounds of {model} projects, holding {total} 🔴 and 🟡 findings.",
|
||||
f"The reference reviewer, {reference}, found {sum(len(found) for found in replay.on_reference)} of them.",
|
||||
]
|
||||
for tried in replay.tried:
|
||||
+140
-30
@@ -10,17 +10,18 @@ import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
import unittest.mock
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from stability_replay.rounds import authored_by, recorded_findings, report, reviewed_path, Round, round_from, sample
|
||||
from review_replay.rounds import authored_by, lost_inputs, recorded_findings, report, reviewed_path, Round, round_from, sample, stamp_seconds
|
||||
from loop_claude.effects import Effects, system_effects
|
||||
from failure import Failure
|
||||
from stability_replay import main
|
||||
from review_replay import main
|
||||
from rung_replay.search import Miss, Replay, Tried
|
||||
from model_routing.ladder import Rung
|
||||
from model_routing.ladder import REVIEWERS, Rung
|
||||
|
||||
TOOL = pathlib.Path(__file__).resolve().parents[1] / "stability-replay"
|
||||
TOOL = pathlib.Path(__file__).resolve().parents[1] / "review-replay"
|
||||
REFERENCE = Rung("claude-opus-5-5", "medium")
|
||||
MIDDLE = Rung("claude-sonnet-5-5", "high")
|
||||
CHEAP = Rung("claude-haiku-5-5", "max")
|
||||
@@ -31,7 +32,7 @@ def entry(kind, text, **fields):
|
||||
|
||||
|
||||
def a_round(at, findings=("🔴 a",)):
|
||||
return Round("/code/p", "x", f"2026-10-14T10:00:0{at}Z", 0, "Review it.", tuple(findings))
|
||||
return Round("stability-reviewer", "/code/p", "x", f"2026-10-14T10:00:0{at}Z", 0, "Review it.", tuple(findings))
|
||||
|
||||
|
||||
class RecordedFindings(unittest.TestCase):
|
||||
@@ -50,19 +51,19 @@ class RoundFrom(unittest.TestCase):
|
||||
entry("assistant", "Reading."),
|
||||
entry("assistant", "BLOCK\n\n🔴 a.py:1 breaks"),
|
||||
]
|
||||
self.assertEqual(round_from("/code/p", 5.0, entries), Round("/code/p", "x", "2026-10-14T10:00:00.500Z", 5.0, "Review branch x in /code/p-x.", ("🔴 a.py:1 breaks",)))
|
||||
self.assertEqual(round_from("/code/p", 5.0, entries).seconds, 1791972000.5)
|
||||
self.assertEqual(round_from("stability-reviewer", "/code/p", 5.0, entries), Round("stability-reviewer", "/code/p", "x", "2026-10-14T10:00:00.500Z", 5.0, "Review branch x in /code/p-x.", ("🔴 a.py:1 breaks",)))
|
||||
self.assertEqual(round_from("stability-reviewer", "/code/p", 5.0, entries).seconds, 1791972000.5)
|
||||
|
||||
def test_reads_a_prompt_given_as_a_string(self):
|
||||
start = {"type": "user", "message": {"content": "Review branch x in /code/p-x."}, "timestamp": "2026-10-14T10:00:00Z", "gitBranch": "x"}
|
||||
self.assertEqual(round_from("/code/p", 5.0, [start, entry("assistant", "🔴 a")]).prompt, "Review branch x in /code/p-x.")
|
||||
self.assertEqual(round_from("stability-reviewer", "/code/p", 5.0, [start, entry("assistant", "🔴 a")]).prompt, "Review branch x in /code/p-x.")
|
||||
|
||||
def test_skips_a_round_with_no_red_or_yellow_finding_or_no_report(self):
|
||||
start = entry("user", "Review.", timestamp="2026-10-14T10:00:00Z", cwd="/code/p", gitBranch="x")
|
||||
self.assertIsNone(round_from("/code/p", 5.0, [start, entry("assistant", "APPROVE\n\n🟢 nit")]))
|
||||
self.assertIsNone(round_from("/code/p", 5.0, [start]))
|
||||
self.assertIsNone(round_from("/code/p", 5.0, []))
|
||||
self.assertIsNone(round_from("/code/p", 5.0, [{**start, "timestamp": "yesterday"}, entry("assistant", "🔴 a")]))
|
||||
self.assertIsNone(round_from("stability-reviewer", "/code/p", 5.0, [start, entry("assistant", "APPROVE\n\n🟢 nit")]))
|
||||
self.assertIsNone(round_from("stability-reviewer", "/code/p", 5.0, [start]))
|
||||
self.assertIsNone(round_from("stability-reviewer", "/code/p", 5.0, []))
|
||||
self.assertIsNone(round_from("stability-reviewer", "/code/p", 5.0, [{**start, "timestamp": "yesterday"}, entry("assistant", "🔴 a")]))
|
||||
|
||||
|
||||
class ReviewedPath(unittest.TestCase):
|
||||
@@ -78,6 +79,13 @@ class ReviewedPath(unittest.TestCase):
|
||||
self.assertIsNone(reviewed_path("Review /code/p-x and /code/p-43.", "/code/p", exists))
|
||||
|
||||
|
||||
class LostInputs(unittest.TestCase):
|
||||
def test_names_each_file_the_prompt_names_in_the_copy_that_it_lacks_other_than_a_round_report(self):
|
||||
prompt = "Read /c/branch.diff and /c/ls-files.txt:3. Earlier: /c/prose-round-1.md. Write /c/principles-goals-round-2-rerun.md; see /elsewhere/x.diff."
|
||||
self.assertEqual(lost_inputs(prompt, "/c", {"ls-files.txt"}.__contains__), ["branch.diff"])
|
||||
self.assertEqual(lost_inputs(prompt, "/c", {"branch.diff", "ls-files.txt"}.__contains__), [])
|
||||
|
||||
|
||||
class AuthoredBy(unittest.TestCase):
|
||||
def test_takes_the_newest_commit_authored_by_then(self):
|
||||
log = [("c3", 30), ("c2", 20), ("c1", 10)]
|
||||
@@ -95,7 +103,7 @@ class Sample(unittest.TestCase):
|
||||
class Report(unittest.TestCase):
|
||||
def test_counts_the_findings_and_names_each_miss_and_the_lowest_rung_that_missed_none(self):
|
||||
rounds = [a_round(1, ("🔴 a\nmore", "🟡 b")), a_round(2)]
|
||||
lines = report("claude-opus-5-5", REFERENCE, rounds, Replay([{0, 1}, set()], [Tried(MIDDLE, []), Tried(CHEAP, [Miss(rounds[0], 0, {1})])], MIDDLE)).splitlines()
|
||||
lines = report("stability", "claude-opus-5-5", REFERENCE, rounds, Replay([{0, 1}, set()], [Tried(MIDDLE, []), Tried(CHEAP, [Miss(rounds[0], 0, {1})])], MIDDLE)).splitlines()
|
||||
self.assertEqual(lines, [
|
||||
"Replayed 2 stability rounds of claude-opus-5-5 projects, holding 3 🔴 and 🟡 findings.",
|
||||
"The reference reviewer, claude-opus-5-5 at medium effort, found 2 of them.",
|
||||
@@ -104,8 +112,8 @@ class Report(unittest.TestCase):
|
||||
" /code/p 2026-10-14T10:00:01Z: 🔴 a",
|
||||
"Lowest rung that finds every finding the reference reviewer finds: claude-sonnet-5-5 at high effort",
|
||||
])
|
||||
self.assertEqual(report("claude-opus-5-5", REFERENCE, rounds, Replay([{0, 1}, {0}], [Tried(MIDDLE, [Miss(rounds[1], 0, set())])], None)).splitlines()[-1], "Lowest rung that finds every finding the reference reviewer finds: none below the project's rung")
|
||||
self.assertEqual(report("claude-opus-5-5", REFERENCE, rounds, Replay([set(), set()], [], None)).splitlines()[-1], "No rung tried: the reference reviewer found no finding to hold one to.")
|
||||
self.assertEqual(report("stability", "claude-opus-5-5", REFERENCE, rounds, Replay([{0, 1}, {0}], [Tried(MIDDLE, [Miss(rounds[1], 0, set())])], None)).splitlines()[-1], "Lowest rung that finds every finding the reference reviewer finds: none below the project's rung")
|
||||
self.assertEqual(report("stability", "claude-opus-5-5", REFERENCE, rounds, Replay([set(), set()], [], None)).splitlines()[-1], "No rung tried: the reference reviewer found no finding to hold one to.")
|
||||
|
||||
|
||||
class Match(unittest.TestCase):
|
||||
@@ -173,6 +181,7 @@ class Main(unittest.TestCase):
|
||||
for key in ("proj", "other"):
|
||||
self.write_chunk(key, "c1", "2026-10-14T10:00:00Z")
|
||||
self.reviews = []
|
||||
self.agents = set()
|
||||
|
||||
def write_chunk(self, key, chunk, at, began="2026-10-14T09:15:00Z"):
|
||||
"""A chunk that began at began, whose stability round began at at."""
|
||||
@@ -206,6 +215,7 @@ class Main(unittest.TestCase):
|
||||
if "--agent" in args:
|
||||
shown = [subprocess.run(["git", *command], cwd=cwd, capture_output=True, text=True).stdout for command in (["show", "HEAD:a.txt"], ["branch", "--show-current"], ["show", "origin/main:a.txt"])]
|
||||
self.reviews.append((rung, *shown, prompt, cwd))
|
||||
self.agents.add(args[args.index("--agent") + 1])
|
||||
result = review(rung)
|
||||
else:
|
||||
reviewed = Rung(*re.search(r"review on (\S+) (\S+)", prompt).groups())
|
||||
@@ -213,14 +223,14 @@ class Main(unittest.TestCase):
|
||||
result = result if "api_error_status" in result else {"type": "result", "structured_output": {"found": [n + 1 for n in result["found"]]}}
|
||||
return subprocess.CompletedProcess(args, 0, json.dumps(result), "")
|
||||
|
||||
effects = Effects(claude=claude, claude_on_terminal=unused, execv=unused, git=system_effects().git, input=unused, local_time=unused, now=unused, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused)
|
||||
effects = Effects(claude=claude, claude_on_terminal=unused, discard_typed=unused, execv=unused, git=system_effects().git, input=unused, local_time=unused, now=unused, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused)
|
||||
out, err = io.StringIO(), io.StringIO()
|
||||
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
|
||||
code = main.main(argv, {}, self.home, effects)
|
||||
return code, out.getvalue(), err.getvalue()
|
||||
|
||||
def test_replays_the_models_rounds_on_the_commit_reviewed_from_the_project_rung_down(self):
|
||||
code, out, err = self.run_main(["claude-opus-5-5"], lambda rung: {"found": [0] if rung.model == "claude-haiku-5-5" else [0, 1]})
|
||||
code, out, err = self.run_main(["stability", "claude-opus-5-5"], lambda rung: {"found": [0] if rung.model == "claude-haiku-5-5" else [0, 1]})
|
||||
self.assertEqual(code, 0, err)
|
||||
self.assertEqual([rung for rung, *_ in self.reviews], [REFERENCE, MIDDLE, CHEAP])
|
||||
_, reviewed, branch, base, prompt, cwd = self.reviews[0]
|
||||
@@ -232,15 +242,113 @@ class Main(unittest.TestCase):
|
||||
self.assertIn(f" {self.checkout} 2026-10-14T10:00:00Z: 🟡 slow", out)
|
||||
self.assertTrue(out.endswith("finds: claude-sonnet-5-5 at high effort\n"))
|
||||
|
||||
def test_replays_the_prose_pass_with_the_prose_reviewer(self):
|
||||
code, out, err = self.run_main(["prose", "claude-opus-5-5"], lambda rung: {"found": [0, 1]})
|
||||
self.assertEqual(code, 0, err)
|
||||
self.assertEqual(self.agents, {"prose-reviewer"})
|
||||
self.assertTrue(out.startswith("Replayed 1 prose rounds"), out)
|
||||
|
||||
def test_tries_each_rung_down_to_the_ladders_lowest_below_the_lowest_a_worker_routes_to(self):
|
||||
code, out, err = self.run_main(["prose", "claude-opus-5-5"], lambda rung: {"found": [0, 1]})
|
||||
self.assertEqual(code, 0, err)
|
||||
self.assertEqual([rung for rung, *_ in self.reviews], [REFERENCE, MIDDLE, CHEAP, *(Rung("claude-haiku-5-5", effort) for effort in ("xhigh", "high", "medium", "low"))])
|
||||
self.assertTrue(out.endswith("finds: claude-haiku-5-5 at low effort\n"), out)
|
||||
|
||||
def review_folder_with_round_1(self):
|
||||
"""The chunk's review folder, holding round 1's report from before the replayed round began at 10:00, that round's own and a later pass's reports, written after, and an earlier attempt's report, from before the chunk began at 09:15."""
|
||||
folder = self.home / ".local" / "state" / "larv-review" / "code" / "proj-x"
|
||||
folder.mkdir(parents=True)
|
||||
(folder / "stability-round-1.md").write_text("round 1\n")
|
||||
before = stamp_seconds("2026-10-14T09:50:00Z")
|
||||
os.utime(folder / "stability-round-1.md", (before, before))
|
||||
(folder / "stability-round-2.md").write_text("🔴 a.txt:1 wrong\n")
|
||||
(folder / "prose-round-1.md").write_text("later\n")
|
||||
(folder / "stability-round-3.md").write_text("🔴 a.txt:1 wrong\n")
|
||||
attempt = stamp_seconds("2026-10-14T09:00:00Z")
|
||||
os.utime(folder / "stability-round-3.md", (attempt, attempt))
|
||||
return folder
|
||||
|
||||
def test_points_the_prompts_review_folder_at_a_copy_of_the_reports_from_before_the_round_that_it_removes(self):
|
||||
folder = self.review_folder_with_round_1()
|
||||
self.set_prompt(f"Review branch x in {self.home}/code/proj-x. Write your report to ~/.local/state/larv-review/code/proj-x/stability-round-2.md; the last round's is ~/.local/state/larv-review/code/proj-x/stability-round-1.md.")
|
||||
seen = []
|
||||
|
||||
def review(rung):
|
||||
named = pathlib.Path(re.search(r"report to (\S+)/stability-round-2\.md", self.reviews[-1][4]).group(1))
|
||||
seen.append((named, sorted(path.name for path in named.iterdir()), (named / "stability-round-1.md").read_text()))
|
||||
(named / "stability-round-2.md").write_text("replayed\n")
|
||||
return {"type": "result", "result": f"review on {rung.model} {rung.effort}"}
|
||||
|
||||
code, _, err = self.run_main(["stability", "claude-opus-5-5"], lambda rung: {"found": [0, 1]}, review)
|
||||
self.assertEqual(code, 0, err)
|
||||
named, copied, earlier = seen[0]
|
||||
self.assertEqual(named.parent, folder.parents[1], "the copy sits in the reports folder, where rule-hook lets the reviewer write")
|
||||
self.assertNotEqual(named, folder)
|
||||
self.assertEqual(copied, ["stability-round-1.md"], "the round's own report, later ones and an earlier attempt's would hand the replayed reviewer its findings")
|
||||
self.assertEqual(earlier, "round 1\n")
|
||||
self.assertFalse(named.exists())
|
||||
self.assertEqual(sorted(path.name for path in folder.iterdir()), ["prose-round-1.md", "stability-round-1.md", "stability-round-2.md", "stability-round-3.md"])
|
||||
self.assertEqual((folder / "stability-round-2.md").read_text(), "🔴 a.txt:1 wrong\n")
|
||||
|
||||
def test_points_the_review_folders_absolute_path_at_the_copy(self):
|
||||
folder = self.review_folder_with_round_1()
|
||||
self.set_prompt(f"Review branch x in {self.home}/code/proj-x. Write your report to {folder}/stability-round-2.md.")
|
||||
code, _, err = self.run_main(["stability", "claude-opus-5-5"], lambda rung: {"found": [0, 1]})
|
||||
self.assertEqual(code, 0, err)
|
||||
prompt = self.reviews[0][4]
|
||||
self.assertNotIn(str(folder), prompt)
|
||||
self.assertRegex(prompt, rf"report to {folder.parents[1]}/review-replay-\w+/stability-round-2\.md\.$")
|
||||
|
||||
def test_replays_no_round_whose_prompt_still_names_the_review_folder_after_the_rewrite(self):
|
||||
self.review_folder_with_round_1()
|
||||
self.set_prompt(f"Review branch x in {self.home}/code/proj-x. Write your report to $HOME/.local/state/larv-review/code/proj-x/stability-round-2.md.")
|
||||
code, out, err = self.run_main(["stability", "claude-opus-5-5"], unused)
|
||||
self.assertEqual(code, 0, err)
|
||||
self.assertEqual(self.reviews, [])
|
||||
self.assertIn(f"on {REFERENCE} found nothing: the prompt names the review folder in a spelling the replay does not redirect", err)
|
||||
self.assertTrue(out.endswith("No rung tried: the reference reviewer found no finding to hold one to.\n"))
|
||||
|
||||
def test_replays_a_round_whose_prompt_names_an_input_written_before_it_began_naming_the_copy(self):
|
||||
folder = self.review_folder_with_round_1()
|
||||
(folder / "branch.diff").write_text("the diff\n")
|
||||
before = stamp_seconds("2026-10-14T09:50:00Z")
|
||||
os.utime(folder / "branch.diff", (before, before))
|
||||
self.set_prompt(f"Review branch x in {self.home}/code/proj-x. The diff is ~/.local/state/larv-review/code/proj-x/branch.diff. Write your report to ~/.local/state/larv-review/code/proj-x/stability-round-2.md.")
|
||||
code, _, err = self.run_main(["stability", "claude-opus-5-5"], lambda rung: {"found": [0, 1]})
|
||||
self.assertEqual(code, 0, err)
|
||||
self.assertRegex(self.reviews[0][4], rf"The diff is {folder.parents[1]}/review-replay-\w+/branch\.diff\.")
|
||||
|
||||
def test_replays_no_round_whose_prompt_names_an_input_the_folder_holds_only_as_rewritten_after_the_round_began(self):
|
||||
folder = self.review_folder_with_round_1()
|
||||
(folder / "branch.diff").write_text("a later diff\n")
|
||||
self.set_prompt(f"Review branch x in {self.home}/code/proj-x. The diff is ~/.local/state/larv-review/code/proj-x/branch.diff. Write your report to ~/.local/state/larv-review/code/proj-x/stability-round-2.md.")
|
||||
code, out, err = self.run_main(["stability", "claude-opus-5-5"], unused)
|
||||
self.assertEqual(code, 0, err)
|
||||
self.assertEqual(self.reviews, [])
|
||||
self.assertIn(f"on {REFERENCE} found nothing: the prompt names branch.diff, which the review folder did not hold from the chunk's start until the round's", err)
|
||||
|
||||
def test_finds_nothing_and_leaves_no_folder_behind_when_it_cannot_copy_the_reports(self):
|
||||
folder = self.review_folder_with_round_1()
|
||||
(folder / "stability-round-1.md").chmod(0)
|
||||
self.set_prompt(f"Review branch x in {self.home}/code/proj-x. Write your report to ~/.local/state/larv-review/code/proj-x/stability-round-2.md.")
|
||||
scratch = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory()))
|
||||
self.enterContext(unittest.mock.patch.object(tempfile, "tempdir", str(scratch)))
|
||||
code, _, err = self.run_main(["stability", "claude-opus-5-5"], unused)
|
||||
self.assertEqual(code, 0, err)
|
||||
self.assertEqual(self.reviews, [])
|
||||
self.assertIn(f"on {REFERENCE} found nothing: could not prepare the replay: ", err)
|
||||
self.assertEqual(list(scratch.iterdir()), [], "the clone is removed")
|
||||
self.assertEqual([path.name for path in folder.parent.parent.iterdir()], ["code"], "the copy is removed")
|
||||
|
||||
def test_replays_the_rounds_of_every_chunk(self):
|
||||
self.write_chunk("proj", "c2", "2026-10-14T10:30:00Z")
|
||||
code, out, err = self.run_main(["claude-opus-5-5"], lambda rung: {"found": [0, 1]})
|
||||
code, out, err = self.run_main(["stability", "claude-opus-5-5"], lambda rung: {"found": [0, 1]})
|
||||
self.assertEqual(code, 0, err)
|
||||
self.assertTrue(out.startswith("Replayed 2 stability rounds"), out)
|
||||
|
||||
def test_checks_out_the_commit_detached_when_the_reviewer_started_on_the_default_branch(self):
|
||||
self.set_branch("main")
|
||||
self.assertEqual(self.run_main(["claude-opus-5-5"], lambda rung: {"found": [0]})[0], 0)
|
||||
self.assertEqual(self.run_main(["stability", "claude-opus-5-5"], lambda rung: {"found": [0]})[0], 0)
|
||||
self.assertEqual(self.reviews[0][1:3], ("1\n", ""))
|
||||
|
||||
def test_sets_the_default_branch_to_its_own_line_and_not_to_a_branch_merged_after_the_chunk_began(self):
|
||||
@@ -252,20 +360,20 @@ class Main(unittest.TestCase):
|
||||
run_git(self.checkout, "checkout", "-q", "main")
|
||||
run_git(self.checkout, "merge", "-q", "--no-ff", "-m", "m", "side", at="2026-10-14T09:40:00Z")
|
||||
run_git(self.checkout, "push", "-qf", "origin", "main")
|
||||
self.assertEqual(self.run_main(["claude-opus-5-5"], lambda rung: {"found": [0]})[0], 0)
|
||||
self.assertEqual(self.run_main(["stability", "claude-opus-5-5"], lambda rung: {"found": [0]})[0], 0)
|
||||
self.assertEqual(self.reviews[0][1:4], ("s\n", "x\n", "0\n"))
|
||||
|
||||
def test_finds_nothing_in_a_round_whose_review_has_no_report(self):
|
||||
code, out, err = self.run_main(["claude-opus-5-5"], unused, review=lambda rung: {"type": "result"})
|
||||
code, out, err = self.run_main(["stability", "claude-opus-5-5"], unused, review=lambda rung: {"type": "result"})
|
||||
self.assertEqual(code, 0, err)
|
||||
self.assertEqual([rung for rung, *_ in self.reviews], [REFERENCE] * 3)
|
||||
self.assertIn(f" {self.checkout} 2026-10-14T10:00:00Z on {REFERENCE} found nothing: the reviewer replied with no report", err)
|
||||
self.assertTrue(out.endswith("No rung tried: the reference reviewer found no finding to hold one to.\n"))
|
||||
|
||||
def assert_no_round(self):
|
||||
code, _, err = self.run_main(["claude-opus-5-5"], unused)
|
||||
code, _, err = self.run_main(["stability", "claude-opus-5-5"], unused)
|
||||
self.assertEqual(code, 1)
|
||||
self.assertEqual(err.splitlines(), [f"stability-replay: no archived stability round of projects on claude-opus-5-5 in {self.archive} holds a 🔴 or 🟡 on code it can find"])
|
||||
self.assertEqual(err.splitlines(), [f"review-replay: no archived stability round of projects on claude-opus-5-5 in {self.archive} holds a 🔴 or 🟡 on code it can find"])
|
||||
|
||||
def test_skips_a_chunk_with_no_transcript_copy(self):
|
||||
(self.archive / "proj" / "c1" / "t0.jsonl").unlink()
|
||||
@@ -276,7 +384,7 @@ class Main(unittest.TestCase):
|
||||
self.assert_no_round()
|
||||
|
||||
def assert_left_out(self, reason, root=None):
|
||||
code, _, err = self.run_main(["claude-opus-5-5"], unused)
|
||||
code, _, err = self.run_main(["stability", "claude-opus-5-5"], unused)
|
||||
self.assertEqual(code, 1)
|
||||
self.assertIn(f"{root or self.checkout} 2026-10-14T10:00:00Z is left out: {reason}", err)
|
||||
|
||||
@@ -298,23 +406,25 @@ class Main(unittest.TestCase):
|
||||
self.assert_left_out("no commit was authored by then")
|
||||
|
||||
def test_exits_1_on_a_usage_limit_bad_arguments_or_no_round_to_replay(self):
|
||||
code, _, err = self.run_main(["claude-opus-5-5"], lambda rung: {"type": "result", "api_error_status": 429, "result": "You've hit your limit"})
|
||||
code, _, err = self.run_main(["stability", "claude-opus-5-5"], lambda rung: {"type": "result", "api_error_status": 429, "result": "You've hit your limit"})
|
||||
self.assertEqual(code, 1)
|
||||
self.assertIn("usage limit: You've hit your limit", err)
|
||||
for argv in ([], ["off-ladder"], ["claude-opus-5-5", "x"]):
|
||||
self.assertEqual(self.run_main(argv, unused)[0], 1)
|
||||
code, _, err = self.run_main(["claude-haiku-5-5"], unused)
|
||||
for argv in ([], ["claude-opus-5-5"], ["full scan", "claude-opus-5-5"], ["stability", "off-ladder"], ["stability", "claude-opus-5-5", "x"]):
|
||||
with self.subTest(argv=argv):
|
||||
self.assertEqual(self.run_main(argv, unused)[0], 1)
|
||||
code, _, err = self.run_main(["stability", "claude-haiku-5-5"], unused)
|
||||
self.assertEqual(code, 1)
|
||||
self.assertIn("no archived stability round of projects on claude-haiku-5-5", err)
|
||||
|
||||
def test_prints_the_help(self):
|
||||
code, out, _ = self.run_main(["-h"], unused)
|
||||
self.assertEqual((code, out.splitlines()[2]), (0, "usage: stability-replay <model>"))
|
||||
self.assertEqual((code, out.splitlines()[2]), (0, "usage: review-replay <pass> <model>"))
|
||||
self.assertIn(f"{', '.join(list(REVIEWERS)[:-1])} or {list(REVIEWERS)[-1]}.", " ".join(out.split()))
|
||||
|
||||
def test_the_launcher_prints_the_help(self):
|
||||
ran = subprocess.run([sys.executable, str(TOOL), "--help"], capture_output=True, text=True)
|
||||
self.assertEqual(ran.returncode, 0)
|
||||
self.assertIn("usage: stability-replay <model>", ran.stdout)
|
||||
self.assertIn("usage: review-replay <pass> <model>", ran.stdout)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
@@ -191,7 +191,7 @@ class Archive(unittest.TestCase):
|
||||
|
||||
def test_counts_the_verdicts_across_every_projects_chunks(self):
|
||||
self.chunk("home/x", "c1", stamped("2026-10-14T10:00:00Z", outcomes.unfinished("w", "e", "j", "")) + stamped("2026-10-14T10:01:00Z", outcomes.stopped("w", "Ctrl-C")) + stamped("2026-10-14T10:02:00Z", outcomes.finished("w", "e", "j")), [])
|
||||
self.chunk("log", "c2", stamped("2026-10-14T10:00:00Z", outcomes.interrupted("q", "e", "j")), [])
|
||||
self.chunk("log", "c2", stamped("2026-10-14T10:00:00Z", outcomes.interrupted("q", "e", "j", "", "w")), [])
|
||||
self.assertEqual(archive.cycles(self.root), 2)
|
||||
self.assertEqual(archive.cycles(self.root / "missing"), 0)
|
||||
|
||||
|
||||
@@ -11,6 +11,8 @@ class Call:
|
||||
tool: str
|
||||
given: dict[str, typing.Any]
|
||||
cwd: str
|
||||
# The subagent the call comes from, such as prose-reviewer; empty for the session's own agent.
|
||||
agent: str = ""
|
||||
|
||||
|
||||
def parsed_call(hook_input: object) -> Call | Failure:
|
||||
@@ -19,7 +21,8 @@ def parsed_call(hook_input: object) -> Call | Failure:
|
||||
tool, given, cwd = hook_input.get("tool_name"), hook_input.get("tool_input"), hook_input.get("cwd")
|
||||
if not isinstance(tool, str) or not isinstance(given, dict) or not isinstance(cwd, str):
|
||||
return Failure("the hook input has no string tool_name and cwd and object tool_input")
|
||||
return Call(tool, given, cwd)
|
||||
agent = hook_input.get("agent_type")
|
||||
return Call(tool, given, cwd, agent if isinstance(agent, str) else "")
|
||||
|
||||
|
||||
def text(given: dict[str, typing.Any], key: str) -> str:
|
||||
|
||||
@@ -8,7 +8,7 @@ subagent. The rules:
|
||||
|
||||
{rules}
|
||||
|
||||
A file a Bash command writes, such as through `cat > Dockerfile`, is not checked. The reviewer-rung rule takes no override.
|
||||
A file a Bash command writes, such as through `cat > Dockerfile`, is not checked.
|
||||
|
||||
A call overrides a rule with `# rule-override <rule>: <reason>`:
|
||||
|
||||
@@ -24,7 +24,7 @@ default branch lacks, and those logged under the branch's own name.
|
||||
|
||||
Run with no arguments in a terminal, it prints this help.
|
||||
|
||||
Exit 2 with the rule, why it holds and how to override it, when a rule blocks the call, or when an
|
||||
Exit 2 with the rule, why it holds and, where the rule takes an override, how to write one, when a rule blocks the call, or when an
|
||||
override cannot be logged; 0 otherwise. `rule-hook overrides` exits 1 when git cannot read the
|
||||
checkout or the branch's reflog. Exit 1, a non-blocking error to Claude Code, on input it
|
||||
cannot read.
|
||||
@@ -41,6 +41,7 @@ from rule_hook.rules import Breach, command_breaches, file_breaches, Outcome, ru
|
||||
from git_command import commits
|
||||
from failure import Failure
|
||||
from rule_hook.override_log import Log, log_path, logged, print_overrides, write_override
|
||||
from rule_hook.reviewer_report import report_breaches
|
||||
from rule_hook.reviewer_rung import reviewer_breaches
|
||||
from shell_command import simple_commands
|
||||
from rule_hook.todo_check import todo_breaches
|
||||
@@ -81,7 +82,7 @@ def breaches_of(call: Call, home: str, environ: typing.Mapping[str, str]) -> tup
|
||||
return None
|
||||
before = read(path)
|
||||
added, after = applied(call, before)
|
||||
return added, path, file_breaches(path, before, added, after)
|
||||
return added, path, report_breaches(call, path, home) + file_breaches(path, before, added, after)
|
||||
|
||||
|
||||
def answer(judged: Outcome, what: str, now: float) -> int:
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
"""Refuse a reviewer's file call other than a Write of its report into the reports folder: skills/larv-review/review-findings.md → "Report"."""
|
||||
import os
|
||||
import pathlib
|
||||
|
||||
from rule_hook.rules import Breach
|
||||
from rule_hook.call import Call
|
||||
from review_folder import REPORTS
|
||||
|
||||
# Each agent under agents/, read from the folder, so an agent the routing tables miss is still confined.
|
||||
REVIEWERS = frozenset(path.stem for path in (pathlib.Path(__file__).resolve().parents[2] / "agents").glob("*.md"))
|
||||
|
||||
|
||||
def report_breaches(call: Call, path: str, home: str) -> list[Breach]:
|
||||
"""The breach of a file call from a reviewer that is not a Write under REPORTS in home; none from any other agent."""
|
||||
if call.agent not in REVIEWERS:
|
||||
return []
|
||||
written = os.path.realpath(os.path.join(call.cwd, path))
|
||||
reports = os.path.realpath(os.path.join(home, REPORTS))
|
||||
if call.tool == "Write" and written.startswith(reports + "/"):
|
||||
return []
|
||||
return [Breach("reviewer-report", f"{call.agent} would {call.tool.lower()} {written}; write your report with Write to the path your prompt names, under {reports}/", call.cwd)]
|
||||
@@ -1,14 +1,13 @@
|
||||
"""Refuse an Agent call that launches a review below the rung it needs, worked out from the rungs loop-claude hands its worker: docs/decisions.md → `routing:`."""
|
||||
import pathlib
|
||||
"""Refuse an Agent 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:`."""
|
||||
import typing
|
||||
|
||||
from rule_hook.rules import Breach
|
||||
from rule_hook.call import Call, text
|
||||
from model_routing.worker_rungs import handed
|
||||
from model_routing.ladder import highest, position, review_rung, ReviewKind, Rung
|
||||
from model_routing.ladder import position, review_rungs, REVIEWERS, ReviewKind, Rung
|
||||
|
||||
# A reviewer is an agent under agents/, as CLAUDE.md → "Vocabulary" defines it.
|
||||
REVIEWERS = frozenset(path.stem for path in (pathlib.Path(__file__).resolve().parents[2] / "agents").glob("*.md"))
|
||||
# The pass each agent under agents/ reviews.
|
||||
PASS_OF = {agent: kind for kind, agent in REVIEWERS.items()}
|
||||
# The opening of every comprehension seat's prompt: skills/comprehension-panel/seat-prompts.md → "Opening".
|
||||
SEAT = "You are one seat of a comprehension panel."
|
||||
# The opening of the security pass's prompt: skills/larv-review/SKILL.md → "Security".
|
||||
@@ -18,23 +17,22 @@ SUBJECTS: dict[ReviewKind, str] = {"seat": "a comprehension seat", "security": "
|
||||
|
||||
def reviewer_breaches(call: Call, environ: typing.Mapping[str, 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, reviewers = handed(environ)
|
||||
project, worker, escape_and_impact = handed(environ)
|
||||
kind = review_kind(call.given)
|
||||
if kind is None or project is None or worker is None:
|
||||
return []
|
||||
# A worker an older loop-claude started was handed no reviewers' rung; its reviewers are held to the rung that loop-claude gave them.
|
||||
required = review_rung(kind, project, reviewers or highest(project, worker))
|
||||
required = review_rungs(project, worker, escape_and_impact)[kind]
|
||||
named = named_rung(call.given, worker)
|
||||
if position(named) >= position(required):
|
||||
return []
|
||||
subject = text(call.given, "subagent_type") if kind == "reviewer" else SUBJECTS[kind]
|
||||
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 review_kind(given: dict[str, typing.Any]) -> ReviewKind | None:
|
||||
"""What a launch reviews, a reviewer, a comprehension seat or the security pass; None for any other subagent."""
|
||||
if text(given, "subagent_type") in REVIEWERS:
|
||||
return "reviewer"
|
||||
"""What a launch reviews, a reviewer's pass, a comprehension seat or the security pass; None for any other subagent."""
|
||||
if pass_reviewed := PASS_OF.get(text(given, "subagent_type")):
|
||||
return pass_reviewed
|
||||
opening = text(given, "prompt").lstrip()
|
||||
if opening.startswith(SEAT):
|
||||
return "seat"
|
||||
|
||||
@@ -5,9 +5,10 @@ import typing
|
||||
|
||||
from git_command import commits
|
||||
from round_titles import lacks_counts
|
||||
from review_folder import REPORTS
|
||||
from shell_command import Simple
|
||||
|
||||
RuleName = typing.Literal["action-pin", "commit-one-line", "ignorefile-sorted", "image-pin", "no-ai-attribution", "reviewer-rung", "round-title-counts", "todo-rank-check"]
|
||||
RuleName = typing.Literal["action-pin", "commit-one-line", "ignorefile-sorted", "image-pin", "no-ai-attribution", "reviewer-report", "reviewer-rung", "round-title-counts", "todo-rank-check"]
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
@@ -39,6 +40,12 @@ RULES: dict[RuleName, Rule] = {
|
||||
"no commit, PR, issue comment or file carries a Claude or Anthropic attribution, such as a co-author trailer or a generated-with line",
|
||||
"a git, gh or tea command, and any file written",
|
||||
),
|
||||
# A reviewer only reports, so no marker waives it.
|
||||
"reviewer-report": Rule(
|
||||
f"a reviewer writes nothing but its report, with Write, into a file under ~/{REPORTS}/",
|
||||
"a Write, Edit or MultiEdit call from inside an agent under agents/",
|
||||
overridable=False,
|
||||
),
|
||||
# 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's subagent 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, so a worker below the project's rung cannot hand a review to its own cheaper model",
|
||||
@@ -180,4 +187,4 @@ def blocks(written: str) -> list[list[str]]:
|
||||
|
||||
|
||||
def rules_help() -> str:
|
||||
return "\n".join(f" {name}\n The rule: {rule.holds}.\n Checked in: {rule.checked}." for name, rule in RULES.items())
|
||||
return "\n".join(f" {name}\n The rule: {rule.holds}.\n Checked in: {rule.checked}." + ("" if rule.overridable else "\n Takes no override.") for name, rule in RULES.items())
|
||||
|
||||
@@ -5,6 +5,7 @@ import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
import unittest.mock
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
@@ -14,8 +15,10 @@ from rule_hook.call import Call
|
||||
from git_command import Commit, commit_message, commits
|
||||
from test_rank_todo import DECISIONS, README, TODO
|
||||
from test_env import isolated_env
|
||||
from model_routing import ladder
|
||||
from rule_hook.override_log import LogLine, parsed_entry, this_chunks
|
||||
from rule_hook.reviewer_rung import reviewer_breaches
|
||||
from model_routing.ladder import Rung
|
||||
from shell_command import simple_commands
|
||||
|
||||
HOOK = pathlib.Path(__file__).resolve().parents[1] / "rule-hook"
|
||||
@@ -167,9 +170,9 @@ class OverrideLog(unittest.TestCase):
|
||||
|
||||
class ReviewerRung(unittest.TestCase):
|
||||
# A worker routed to Haiku 5.5 at max, 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-haiku-5-5 at max effort", "LOOP_CLAUDE_REVIEWER_RUNG": "claude-opus-5-5 at medium effort"}
|
||||
# The same project, with a worker and its reviewers routed above it to Fable 5.1 at max.
|
||||
ABOVE = {"LOOP_CLAUDE_PROJECT_RUNG": "claude-opus-5-5 at medium effort", "LOOP_CLAUDE_WORKER_RUNG": "claude-fable-5-1 at max effort", "LOOP_CLAUDE_REVIEWER_RUNG": "claude-fable-5-1 at max effort"}
|
||||
ENVIRON = {"LOOP_CLAUDE_PROJECT_RUNG": "claude-opus-5-5 at medium effort", "LOOP_CLAUDE_WORKER_RUNG": "claude-haiku-5-5 at max effort", "LOOP_CLAUDE_ESCAPE_AND_IMPACT": "4"}
|
||||
# The same project, with a worker, and so its reviewers, routed above it to Fable 5.1 at max.
|
||||
ABOVE = {"LOOP_CLAUDE_PROJECT_RUNG": "claude-opus-5-5 at medium effort", "LOOP_CLAUDE_WORKER_RUNG": "claude-fable-5-1 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))
|
||||
@@ -200,20 +203,29 @@ class ReviewerRung(unittest.TestCase):
|
||||
def test_an_effort_off_the_ladder_for_its_model_is_refused(self):
|
||||
self.assertEqual(self.refused({"subagent_type": "prose-reviewer", "model": "opus", "effort": "low"}), ["reviewer-rung"])
|
||||
|
||||
def test_a_reviewer_is_held_to_the_reviewers_rung_where_that_is_higher(self):
|
||||
def test_a_reviewer_is_held_to_the_rung_its_e_plus_i_picks_where_that_is_higher(self):
|
||||
self.assertEqual(self.refused({"subagent_type": "stability-reviewer", "model": "opus", "effort": "medium"}, self.ABOVE), ["reviewer-rung"])
|
||||
self.assertEqual(self.refused({"subagent_type": "stability-reviewer", "model": "fable", "effort": "max"}, self.ABOVE), [])
|
||||
lifted = self.ENVIRON | {"LOOP_CLAUDE_REVIEWER_RUNG": "claude-opus-5-5 at high effort"}
|
||||
lifted = self.ENVIRON | {"LOOP_CLAUDE_ESCAPE_AND_IMPACT": "5"}
|
||||
self.assertEqual(self.refused({"subagent_type": "stability-reviewer", "model": "opus", "effort": "medium"}, lifted), ["reviewer-rung"])
|
||||
self.assertEqual(self.refused({"prompt": "You are one seat of a comprehension panel.", "model": "opus", "effort": "medium"}, lifted), [])
|
||||
|
||||
def test_holds_a_reviewer_to_the_higher_of_the_workers_and_the_projects_rung_where_loop_claude_handed_no_reviewers_rung(self):
|
||||
without = {name: rung for name, rung in self.ABOVE.items() if name != "LOOP_CLAUDE_REVIEWER_RUNG"}
|
||||
def test_holds_a_reviewer_to_the_higher_of_the_workers_and_the_projects_rung_where_loop_claude_handed_no_e_plus_i(self):
|
||||
without = {name: rung for name, rung in self.ABOVE.items() if name != "LOOP_CLAUDE_ESCAPE_AND_IMPACT"}
|
||||
self.assertEqual(self.refused({"subagent_type": "stability-reviewer", "model": "opus", "effort": "medium"}, without), ["reviewer-rung"])
|
||||
below = {name: rung for name, rung in self.ENVIRON.items() if name != "LOOP_CLAUDE_REVIEWER_RUNG"}
|
||||
below = {name: rung for name, rung in self.ENVIRON.items() if name != "LOOP_CLAUDE_ESCAPE_AND_IMPACT"}
|
||||
self.assertEqual(self.refused({"subagent_type": "stability-reviewer", "model": "sonnet", "effort": "high"}, below), ["reviewer-rung"])
|
||||
self.assertEqual(self.refused({"prompt": "You are one seat of a comprehension panel.", "model": "sonnet", "effort": "high"}, without), ["reviewer-rung"])
|
||||
|
||||
def test_a_replayed_passs_reviewer_is_held_to_its_replays_rung_below_the_workers_unless_the_e_plus_i_steps_reviews_up_or_the_worker_climbed(self):
|
||||
lowered = {"subagent_type": "prose-reviewer", "model": "haiku", "effort": "medium"}
|
||||
with unittest.mock.patch.dict(ladder.REPLAYED, {("prose", "claude-opus-5-5"): Rung("claude-haiku-5-5", "medium")}):
|
||||
self.assertEqual(self.refused(lowered), [])
|
||||
self.assertEqual(self.refused({"subagent_type": "prose-reviewer", "model": "haiku", "effort": "low"}), ["reviewer-rung"])
|
||||
self.assertEqual(self.refused({**lowered, "subagent_type": "stability-reviewer"}), ["reviewer-rung"])
|
||||
self.assertEqual(self.refused(lowered, self.ENVIRON | {"LOOP_CLAUDE_ESCAPE_AND_IMPACT": "5"}), ["reviewer-rung"])
|
||||
self.assertEqual(self.refused(lowered, self.ABOVE), ["reviewer-rung"])
|
||||
|
||||
def test_a_seat_or_a_security_launch_is_held_to_the_project_rung_alone(self):
|
||||
seat = {"prompt": "You are one seat of a comprehension panel. Tools: Read, Grep, Glob.", "model": "opus", "effort": "medium"}
|
||||
self.assertEqual(self.refused(seat, self.ABOVE), [])
|
||||
@@ -233,6 +245,41 @@ class ReviewerRung(unittest.TestCase):
|
||||
self.assertEqual(self.refused({"subagent_type": "stability-reviewer", "model": "haiku", "effort": "low"}, {}), [])
|
||||
|
||||
|
||||
class ReviewerReport(unittest.TestCase):
|
||||
def breached(self, tool: str, path: str, agent: str = "prose-reviewer", cwd: str = "/r") -> list[str]:
|
||||
given = {"file_path": path, "content": "BLOCK\n"} if tool == "Write" else {"file_path": path, "old_string": "a", "new_string": "b"}
|
||||
found = breaches_of(Call(tool, given, cwd, agent), "/h", {})
|
||||
return rules(found[2]) if found else []
|
||||
|
||||
def test_a_reviewer_writes_its_report_into_the_reports_folder(self):
|
||||
self.assertEqual(self.breached("Write", "/h/.local/state/larv-review/.claude-item-73/prose-round-1.md"), [])
|
||||
|
||||
def test_a_relative_path_resolves_against_the_calls_cwd(self):
|
||||
self.assertEqual(self.breached("Write", "prose-round-1.md", cwd="/h/.local/state/larv-review/x"), [])
|
||||
|
||||
def test_a_symlink_in_the_reports_folder_is_followed_to_where_it_points(self):
|
||||
home = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory()))
|
||||
(home / ".local" / "state" / "larv-review").mkdir(parents=True)
|
||||
(home / ".local" / "state" / "larv-review" / "out").symlink_to(home)
|
||||
found = breaches_of(Call("Write", {"file_path": f"{home}/.local/state/larv-review/out/a.md", "content": "x"}, "/r", "prose-reviewer"), str(home), {})
|
||||
self.assertEqual(rules(found[2]), ["reviewer-report"])
|
||||
|
||||
def test_a_reviewer_writing_anywhere_else_is_refused(self):
|
||||
for path in ["/r/README.md", "/h/.local/state/larv-review", "/h/.local/state/larv-review-x/a.md", "/h/.local/state/larv-review/../a.md", "/tmp/larv-review/a.md"]:
|
||||
with self.subTest(path):
|
||||
self.assertEqual(self.breached("Write", path), ["reviewer-report"])
|
||||
|
||||
def test_a_reviewer_edits_no_file_even_in_the_reports_folder(self):
|
||||
self.assertEqual(self.breached("Edit", "/h/.local/state/larv-review/x/prose-round-1.md"), ["reviewer-report"])
|
||||
|
||||
def test_a_reviewers_multiedit_is_refused(self):
|
||||
self.assertEqual(self.breached("MultiEdit", "/r/a.py", "stability-reviewer"), ["reviewer-report"])
|
||||
|
||||
def test_the_worker_and_other_subagents_write_anywhere(self):
|
||||
self.assertEqual(self.breached("Write", "/r/README.md", ""), [])
|
||||
self.assertEqual(self.breached("Write", "/r/README.md", "general-purpose"), [])
|
||||
|
||||
|
||||
class Hook(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.repo = tempfile.mkdtemp()
|
||||
@@ -307,6 +354,14 @@ class Hook(unittest.TestCase):
|
||||
call = {"cwd": self.repo, "tool_input": {"subagent_type": "stability-reviewer", "model": "opus", "effort": "medium", "prompt": "Review."}, "tool_name": "Agent"}
|
||||
self.assertEqual(hook(call, self.repo, ReviewerRung.ENVIRON).returncode, 0)
|
||||
|
||||
def test_a_reviewers_write_outside_the_reports_folder_is_refused_and_offers_no_override(self):
|
||||
call = {"agent_type": "prose-reviewer", "cwd": self.repo, "tool_input": {"file_path": f"{self.repo}/a.md", "content": "<!-- rule-override reviewer-report: trust me -->\n"}, "tool_name": "Write"}
|
||||
ran = hook(call, self.repo)
|
||||
self.assertEqual(ran.returncode, 2)
|
||||
self.assertIn("Blocked by rule reviewer-report: prose-reviewer would write ", ran.stderr)
|
||||
self.assertIn("/.local/state/larv-review/", ran.stderr)
|
||||
self.assertNotIn("rule-override", ran.stderr)
|
||||
|
||||
def test_a_commit_override_is_logged_in_the_commit_s_checkout(self):
|
||||
outside = tempfile.mkdtemp()
|
||||
self.addCleanup(subprocess.run, ["rm", "-rf", outside])
|
||||
@@ -370,5 +425,8 @@ class Hook(unittest.TestCase):
|
||||
|
||||
def test_help_lists_every_rule(self):
|
||||
helped = subprocess.run([str(HOOK), "--help"], capture_output=True, check=True, env=isolated_env(), text=True).stdout
|
||||
for rule in ["action-pin", "commit-one-line", "ignorefile-sorted", "image-pin", "no-ai-attribution", "round-title-counts", "todo-rank-check"]:
|
||||
for rule in ["action-pin", "commit-one-line", "ignorefile-sorted", "image-pin", "no-ai-attribution", "reviewer-report", "reviewer-rung", "round-title-counts", "todo-rank-check"]:
|
||||
self.assertIn(f" {rule}\n The rule: ", helped)
|
||||
self.assertIn("reviewer-report\n The rule: a reviewer writes nothing but its report", helped)
|
||||
self.assertRegex(helped, r" reviewer-report\n( .*\n){2} Takes no override\.\n")
|
||||
self.assertRegex(helped, r" image-pin\n( .*\n){2} \S", "a rule a marker waives says nothing of overrides")
|
||||
|
||||
+16
-11
@@ -1,22 +1,27 @@
|
||||
"""What judge-replay's and stability-replay's commands share: the argument, the projects on its model, the candidate rungs and the exits."""
|
||||
"""What judge-replay's and review-replay's commands share: reading the arguments, the projects on a model, the candidate rungs and the exits."""
|
||||
import pathlib
|
||||
import sys
|
||||
import typing
|
||||
|
||||
from failure import Failure
|
||||
from model_routing.ladder import LADDER, lowest_worker_rung, position, project_rung, Rung
|
||||
from model_routing.ladder import LADDER, position, Rung
|
||||
from claude_code.reply import Limited
|
||||
from loop_claude.project.model_choice import read_models_file
|
||||
from loop_claude.stop import Stop
|
||||
|
||||
def project_rung_or_exit(tool: str, argv: list[str], help_text: str) -> Rung | int:
|
||||
"""The project's rung of the model argv names, or the exit code: 0 after printing help_text for -h or --help, 1 after saying why argv cannot be read."""
|
||||
# What a tool reads from its arguments, such as the project's rung of the model they name.
|
||||
Parsed = typing.TypeVar("Parsed")
|
||||
|
||||
|
||||
def arguments_or_exit(tool: str, argv: list[str], help_text: str, usage: str, read: typing.Callable[[list[str]], Parsed | None]) -> Parsed | int:
|
||||
"""What read makes of argv, or the exit code: 0 after printing help_text for -h or --help, 1 after saying, with usage, that argv cannot be read, where read gives None."""
|
||||
if argv[:1] in (["-h"], ["--help"]):
|
||||
print(help_text.strip())
|
||||
return 0
|
||||
anchor = project_rung(argv[0]) if len(argv) == 1 else None
|
||||
if anchor is None:
|
||||
return failed(tool, f"cannot read the arguments{' ' + ' '.join(argv) if argv else ''}; usage: {tool} <model>, a model on the routing ladder")
|
||||
return anchor
|
||||
arguments = read(argv)
|
||||
if arguments is None:
|
||||
return failed(tool, f"cannot read the arguments{' ' + ' '.join(argv) if argv else ''}; usage: {usage}")
|
||||
return arguments
|
||||
|
||||
|
||||
def projects_on(model: str, home: pathlib.Path) -> list[str] | Failure:
|
||||
@@ -27,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) -> list[Rung]:
|
||||
"""top, the project's rung, and each rung below it, highest first, down to the lowest rung a worker routes to: no route uses a rung below it, so a replay there could change no routing."""
|
||||
return list(LADDER[position(lowest_worker_rung(top)):position(top) + 1])[::-1]
|
||||
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 limited_exit(tool: str, limited: Limited) -> int:
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""The rung search judge-replay and stability-replay share: replay archived cases on a reference rung, then hold each candidate rung to what the reference reproduced."""
|
||||
"""The rung search judge-replay and review-replay share: replay archived cases on a reference rung, then hold each candidate rung to what the reference reproduced."""
|
||||
import concurrent.futures
|
||||
import dataclasses
|
||||
import sys
|
||||
|
||||
@@ -63,8 +63,9 @@ class FirstReply(unittest.TestCase):
|
||||
|
||||
|
||||
class DownFrom(unittest.TestCase):
|
||||
def test_runs_from_the_projects_rung_down_to_the_lowest_rung_a_worker_routes_to(self):
|
||||
self.assertEqual(down_from(REFERENCE), [REFERENCE, MIDDLE, CHEAP])
|
||||
def test_runs_from_the_projects_rung_down_to_the_floor_highest_first(self):
|
||||
self.assertEqual(down_from(REFERENCE, CHEAP), [REFERENCE, MIDDLE, CHEAP])
|
||||
self.assertEqual(down_from(REFERENCE, MIDDLE), [REFERENCE, MIDDLE])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -1,207 +0,0 @@
|
||||
"""Replay archived stability rounds on the rungs below the project's, to find which rungs may run the stability reviewer: docs/decisions.md → `routing: the stability reviewer runs no lower than the project's rung`.
|
||||
|
||||
usage: stability-replay <model>
|
||||
|
||||
<model> is a project model on the routing ladder, such as claude-opus-5-5. The tool replays the
|
||||
latest 10 archived stability rounds 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
|
||||
authored by the time the round began, on the branch the reviewer started on. The clone's default
|
||||
branch stands at the newest commit authored before the round's chunk began, so a diff against it
|
||||
shows the chunk's change. The prompt names the clone in place of the worktree it named, which the
|
||||
chunk has since removed. A round whose code it cannot find in this way is not replayed; stderr
|
||||
names it and why.
|
||||
|
||||
It first replays every round on the project's rung, the reference reviewer. Findings on record
|
||||
that the reference reviewer does not raise again may rest on code or rules that have changed
|
||||
since; no rung is held to them. It then replays the rounds where the reference raised any, on each
|
||||
rung below, highest first, down to the lowest rung a worker routes to, and stops at the first rung
|
||||
that misses one. For each replay, claude on the project's rung matches the report to the findings
|
||||
on record, and counts a finding only where the report raises it as 🔴 or 🟡. The tool prints each
|
||||
finding a rung missed and the lowest rung that, like each rung above it, missed none. That rung is
|
||||
the evidence for running the stability reviewer on the worker's rung whenever the worker runs at
|
||||
or above it; docs/decisions.md → `routing: the stability reviewer runs no lower than the project's rung`
|
||||
records the run.
|
||||
|
||||
Like the loop, it tries claude three times running before it counts a reply as failed. A failed
|
||||
review or match finds nothing. Exit 1, saying why, on bad arguments, an unreadable archive or
|
||||
models file, no archived round to replay, or a usage limit.
|
||||
"""
|
||||
import dataclasses
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import typing
|
||||
|
||||
from transcript_archive.location import archive_root
|
||||
from stability_replay.rounds import authored_by, report, reviewed_path, Round, round_from, sample, stamp_seconds
|
||||
from project_key import checkout_of
|
||||
from claude_code.reply import claude_reply, Limited
|
||||
from rung_replay.command import down_from, failed, limited_exit, project_rung_or_exit, projects_on
|
||||
from loop_claude.effects import Effects
|
||||
from failure import Failure
|
||||
from rung_replay.search import first_reply, replayed
|
||||
from claude_code.transcript import first_timestamped_line, read_transcript
|
||||
from claude_code.entries import parse_entry, structured_output
|
||||
from model_routing.ladder import Rung
|
||||
|
||||
TOOL = "stability-replay"
|
||||
LATEST = 10
|
||||
REVIEWER = "stability-reviewer"
|
||||
MATCH_SCHEMA = {"type": "object", "properties": {"found": {"type": "array", "items": {"type": "integer"}}}, "required": ["found"], "additionalProperties": False}
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Code:
|
||||
"""Where a round's reviewer read the code, the commit it read, the default branch, and where that branch stood as the chunk began."""
|
||||
path: str
|
||||
reviewed: str
|
||||
default: str
|
||||
base: str
|
||||
|
||||
|
||||
def main(argv: list[str], env: typing.Mapping[str, str], home: pathlib.Path, effects: Effects) -> int:
|
||||
anchor = project_rung_or_exit(TOOL, argv, __doc__)
|
||||
if isinstance(anchor, int):
|
||||
return anchor
|
||||
rounds = archived_rounds(anchor.model, archive_root(home, env), home)
|
||||
if isinstance(rounds, Failure):
|
||||
return failed(TOOL, rounds.reason)
|
||||
codes = {}
|
||||
for found in rounds:
|
||||
if isinstance(code := code_of(found, effects), Failure):
|
||||
print(f"{found.root} {found.at} is left out: {code.reason}", file=sys.stderr, flush=True)
|
||||
else:
|
||||
codes[found] = code
|
||||
if not codes:
|
||||
return failed(TOOL, f"no archived stability round of projects on {anchor.model} in {archive_root(home, env)} holds a 🔴 or 🟡 on code it can find")
|
||||
chosen = sample(list(codes), LATEST)
|
||||
# The project's rung is the reference, so the candidates start below it.
|
||||
replay = replayed(chosen, anchor, down_from(anchor)[1:], lambda found, rung: findings_found(found, codes[found], rung, anchor, effects), lambda _, found: sorted(found), "stability rounds")
|
||||
if isinstance(replay, Limited):
|
||||
return limited_exit(TOOL, replay)
|
||||
print(report(anchor.model, anchor, chosen, replay))
|
||||
return 0
|
||||
|
||||
|
||||
def archived_rounds(model: str, root: pathlib.Path, home: pathlib.Path) -> list[Round] | Failure:
|
||||
projects = projects_on(model, home)
|
||||
if isinstance(projects, Failure):
|
||||
return projects
|
||||
found = []
|
||||
try:
|
||||
for key in projects:
|
||||
for chunk in sorted(path for path in (root / key).glob("*") if path.is_dir()):
|
||||
found += chunk_rounds(checkout_of(key, home), chunk)
|
||||
except (OSError, UnicodeDecodeError, ValueError) as failure:
|
||||
return Failure(f"could not read the archive {root}: {failure}")
|
||||
return found
|
||||
|
||||
|
||||
def chunk_rounds(checkout: str, chunk: pathlib.Path) -> list[Round]:
|
||||
copies = sorted(chunk.glob("*.jsonl"))
|
||||
began = parse_entry(first_timestamped_line(copies[0].read_bytes())) if copies else None
|
||||
if not began or not isinstance(began.get("timestamp"), str):
|
||||
return []
|
||||
found = []
|
||||
for meta in sorted(chunk.glob("session/*/subagents/*.meta.json")):
|
||||
described = json.loads(meta.read_text(encoding="utf-8"))
|
||||
if not isinstance(described, dict) or described.get("agentType") != REVIEWER:
|
||||
continue
|
||||
entries = read_transcript(str(meta.with_name(meta.name.removesuffix(".meta.json") + ".jsonl")))
|
||||
if not isinstance(entries, Failure) and (one := round_from(checkout, stamp_seconds(began["timestamp"]), entries)):
|
||||
found.append(one)
|
||||
return found
|
||||
|
||||
|
||||
def code_of(found: Round, effects: Effects) -> Code | Failure:
|
||||
"""Where, and at which commits, found's reviewer read the code, as the archive lets it be found again: the prompt's removed worktree, and the commits authored by then.
|
||||
|
||||
Recording the reviewed commit at review time would need no such reading, but then no round archived before that change could be replayed. A wrong guess costs no rung: the reference reviewer, replayed on that code, finds fewer findings on record, and no rung is held to those.
|
||||
"""
|
||||
if not os.path.isdir(found.root):
|
||||
return Failure("the project has no checkout")
|
||||
path = reviewed_path(found.prompt, found.root, os.path.exists)
|
||||
if path is None:
|
||||
return Failure("the prompt names neither one removed worktree nor the checkout")
|
||||
default = git(effects, found.root, "symbolic-ref", "--short", "refs/remotes/origin/HEAD")
|
||||
if isinstance(default, Failure):
|
||||
return default
|
||||
default = default.strip().removeprefix("origin/")
|
||||
log = git(effects, found.root, "log", "--format=%H %at", f"refs/remotes/origin/{default}")
|
||||
main_line = git(effects, found.root, "log", "--first-parent", "--format=%H %at", f"refs/remotes/origin/{default}")
|
||||
if isinstance(log, Failure):
|
||||
return log
|
||||
if isinstance(main_line, Failure):
|
||||
return main_line
|
||||
reviewed, base = authored_by(commit_log(log), found.seconds), authored_by(commit_log(main_line), found.began)
|
||||
if reviewed is None or base is None:
|
||||
return Failure("no commit was authored by then")
|
||||
return Code(path, reviewed, default, base)
|
||||
|
||||
|
||||
def commit_log(listed: str) -> list[tuple[str, float]]:
|
||||
return [(commit, float(authored)) for commit, authored in (line.split() for line in listed.splitlines())]
|
||||
|
||||
|
||||
def findings_found(found: Round, code: Code, rung: Rung, anchor: Rung, effects: Effects) -> set[int] | Limited:
|
||||
"""The indexes of the round's findings that its replay on rung reports, as the reviewer on anchor matches them."""
|
||||
reviewed: str | Failure | Limited = first_reply(lambda: review(found, code, rung, effects))
|
||||
if isinstance(reviewed, Limited):
|
||||
return reviewed
|
||||
matched: set[int] | Failure | Limited = reviewed if isinstance(reviewed, Failure) else first_reply(lambda: match(found.findings, reviewed, found.root, anchor, effects))
|
||||
if isinstance(matched, Failure):
|
||||
print(f" {found.root} {found.at} on {rung} found nothing: {matched.reason}", file=sys.stderr, flush=True)
|
||||
return set()
|
||||
return matched
|
||||
|
||||
|
||||
# The shell makes and removes the clone itself, and is tested on a temporary home as judge-replay's is; rounds.py's core takes the filesystem as an argument.
|
||||
def review(found: Round, code: Code, rung: Rung, effects: Effects) -> str | Failure | Limited:
|
||||
clone = tempfile.mkdtemp(prefix="stability-replay-")
|
||||
try:
|
||||
for command in (
|
||||
("clone", "--quiet", "--shared", "--no-checkout", found.root, clone),
|
||||
("-C", clone, "update-ref", f"refs/remotes/origin/{code.default}", code.base),
|
||||
("-C", clone, "update-ref", f"refs/heads/{code.default}", code.base),
|
||||
("-C", clone, "checkout", "--quiet", *(("-B", found.branch) if found.branch and found.branch != code.default else ("--detach",)), code.reviewed),
|
||||
):
|
||||
if isinstance(ran := git(effects, found.root, *command), Failure):
|
||||
return ran
|
||||
args = ["--agent", REVIEWER, *rung.flags()]
|
||||
reply = claude_reply(effects.claude, args, clone, found.prompt.replace(code.path, clone), "claude")
|
||||
if isinstance(reply, Failure | Limited):
|
||||
return reply
|
||||
return reply["result"] if isinstance(reply.get("result"), str) else Failure("the reviewer replied with no report")
|
||||
finally:
|
||||
shutil.rmtree(clone, ignore_errors=True)
|
||||
|
||||
|
||||
def match(findings: tuple[str, ...], replay_report: str, root: str, rung: Rung, effects: Effects) -> set[int] | Failure | Limited:
|
||||
numbered = "\n\n".join(f"{n}. {finding}" for n, finding in enumerate(findings, 1))
|
||||
prompt = (
|
||||
"A code reviewer reported the numbered findings below. Another reviewer then reviewed the same change; its report follows them. "
|
||||
"List the number of each finding that the other report also raises as 🔴 or 🟡: the same defect, at the same place or from the same cause, however it is worded. "
|
||||
"A finding it raises only as 🟢 or ❓, or not at all, is not listed.\n\n"
|
||||
f"The findings:\n{numbered}\n\nThe other report:\n{replay_report}"
|
||||
)
|
||||
args = ["--json-schema", json.dumps(MATCH_SCHEMA), *rung.flags(), "--tools", ""]
|
||||
reply = claude_reply(effects.claude, args, root, prompt, "claude")
|
||||
if isinstance(reply, Failure | Limited):
|
||||
return reply
|
||||
output = structured_output(reply)
|
||||
numbers = output.get("found") if isinstance(output, dict) else None
|
||||
if not isinstance(numbers, list) or not all(isinstance(n, int) for n in numbers):
|
||||
return Failure(f"the match replied: {json.dumps(reply)}")
|
||||
return {n - 1 for n in numbers if 1 <= n <= len(findings)}
|
||||
|
||||
|
||||
def git(effects: Effects, cwd: str, *args: str) -> str | Failure:
|
||||
try:
|
||||
ran = effects.git(list(args), cwd)
|
||||
except OSError as failure:
|
||||
return Failure(f"git {' '.join(args)} could not start in {cwd}: {failure.strerror}")
|
||||
return ran.stdout if ran.returncode == 0 else Failure(f"git {' '.join(args)}: {ran.stderr.strip()}")
|
||||
@@ -0,0 +1,84 @@
|
||||
import pathlib
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
|
||||
|
||||
import chunk_pick
|
||||
from failure import Failure
|
||||
import todo_table
|
||||
|
||||
|
||||
class Standing(unittest.TestCase):
|
||||
def test_takes_the_earliest_release_where_it_is_the_earliest_named_since_the_last_cut_and_names_the_next_release(self):
|
||||
cases = (
|
||||
("v1.2.3", 4, (1, 2, 4), set(), chunk_pick.Next((1, 2, 4), None)),
|
||||
("v1.2.3", 4, (1, 3, 0), {(1, 3, 0)}, chunk_pick.Next((1, 3, 0), None)),
|
||||
("v1.2.3", 4, (1, 2, 4), {(1, 3, 0)}, chunk_pick.Next((1, 2, 4), None)),
|
||||
("v1.2.3", 4, (1, 3, 0), {(1, 2, 3), (1, 3, 0)}, chunk_pick.Next((1, 3, 0), None)),
|
||||
("v0.2.0", 4, (0, 4, 0), set(), chunk_pick.Next((0, 4, 0), None)),
|
||||
(None, 4, (0, 2, 0), set(), chunk_pick.Next((0, 2, 0), None)),
|
||||
(None, 4, None, set(), chunk_pick.Next(None, None)),
|
||||
("v1.2.3-rc.1", 4, (1, 2, 3), set(), chunk_pick.Next((1, 2, 3), None)),
|
||||
(Failure("tags unreadable"), 4, (0, 2, 0), set(), chunk_pick.Next((0, 2, 0), None)),
|
||||
("v1.2.3", 4, (1, 2, 3), set(), chunk_pick.Cut((1, 2, 3))),
|
||||
("v1.2.3", 4, (1, 2, 2), {(1, 2, 4)}, chunk_pick.Cut((1, 2, 2))),
|
||||
("v1.2.3", 4, (1, 3, 0), {(1, 2, 4), (1, 3, 0)}, chunk_pick.Finished((1, 2, 4))),
|
||||
("v0.9.2", 4, (1, 0, 0), {(0, 9, 3)}, chunk_pick.Finished((0, 9, 3))),
|
||||
("v1.2.3", 4, (1, 4, 0), {(1, 2, 2), (1, 3, 0)}, chunk_pick.Finished((1, 3, 0))),
|
||||
("v1.2.3", 4, None, {(1, 3, 0)}, chunk_pick.Finished((1, 3, 0))),
|
||||
("v1.2.3", 4, None, set(), chunk_pick.Finished(None)),
|
||||
("v1.2.3", 0, (1, 3, 0), {(1, 2, 4)}, chunk_pick.Unplanned((1, 2, 4))),
|
||||
("v1.2.3", 0, None, set(), chunk_pick.Unplanned(None)),
|
||||
("v1.2.3", Failure("count unreadable"), None, set(), chunk_pick.Unknown()),
|
||||
("v1.2.3", 4, (1, 3, 0), Failure("log unreadable"), chunk_pick.Unknown()),
|
||||
("v1.2.3", 4, (1, 2, 3), Failure("log unreadable"), chunk_pick.Cut((1, 2, 3))),
|
||||
)
|
||||
for tag, landed, earliest, named, stands in cases:
|
||||
with self.subTest(tag=tag, landed=landed, earliest=earliest, named=named):
|
||||
self.assertEqual(chunk_pick.standing(tag, landed, earliest, None, named), stands)
|
||||
|
||||
def test_takes_the_first_item_only_where_the_earliest_release_is_next(self):
|
||||
first = todo_table.Item(1, (1, 2, 4), "", "**Do 1.**", {}, (), ())
|
||||
self.assertEqual(chunk_pick.standing("v1.2.3", 4, (1, 2, 4), first, set()), chunk_pick.Next((1, 2, 4), first))
|
||||
self.assertEqual(chunk_pick.standing("v1.2.3", 4, (1, 2, 3), first, set()), chunk_pick.Cut((1, 2, 3)))
|
||||
|
||||
def test_counts_the_changes_unreleased_since_the_last_cut_by_unreleased_entries_and_else_by_commits(self):
|
||||
changelog = "# Changelog\n\n## Unreleased\n\n- One.\n - A nested line.\n- Two.\n\n## 0.1.0\n\n- Old.\n"
|
||||
self.assertEqual(chunk_pick.unreleased_changes(chunk_pick.LastCut("v0.1.0", changelog, 5, [])), 2)
|
||||
self.assertEqual(chunk_pick.unreleased_changes(chunk_pick.LastCut("v0.1.0", "# Changelog\n\n## Unreleased\n\n## 0.1.0\n", 5, [])), 0)
|
||||
self.assertEqual(chunk_pick.unreleased_changes(chunk_pick.LastCut("v0.1.0", "# Changelog\n\n## 0.1.0\n", 5, [])), 5)
|
||||
self.assertEqual(chunk_pick.unreleased_changes(chunk_pick.LastCut("v0.1.0", Failure("unreadable"), 5, [])), 5)
|
||||
|
||||
def test_counts_the_top_level_entries_under_unreleased(self):
|
||||
self.assertEqual(chunk_pick.unreleased_entries("# Changelog\n\n## Unreleased\n\n- One.\n - A nested line.\n- Two.\n\n## 0.1.0\n\n- Old.\n"), 2)
|
||||
self.assertEqual(chunk_pick.unreleased_entries("# Changelog\n\n## Unreleased\n\n## 0.1.0\n\n- Old.\n"), 0)
|
||||
self.assertIsNone(chunk_pick.unreleased_entries("# Changelog\n\n## 0.1.0\n\n- Old.\n"))
|
||||
|
||||
def test_names_each_release_a_todo_md_since_the_last_cut_filed_items_under(self):
|
||||
row = "| {id} | {release} | | | **Do {id}.** | 1 | 1 | 1 | 1 | 1 | 1 by 1 | 10.0 |\n"
|
||||
header = "## Items\n\n| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |\n|---|---|---|---|---|---|---|---|---|---|---|---|\n"
|
||||
texts = [header + row.format(id=1, release="0.2.0"), "", "not a table | x |", header + row.format(id=2, release="0.3.0")]
|
||||
self.assertEqual(chunk_pick.named_releases(texts), {(0, 2, 0), (0, 3, 0)})
|
||||
self.assertEqual(chunk_pick.named_releases(Failure("log unreadable")), Failure("log unreadable"))
|
||||
|
||||
def test_leaves_out_a_release_the_plan_marks_renamed_and_keeps_one_whose_items_moved_unmarked(self):
|
||||
row = "| {id} | {release} | | | **Do {id}.** | 1 | 1 | 1 | 1 | 1 | 1 by 1 | 10.0 |\n"
|
||||
header = "## Items\n\n| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |\n|---|---|---|---|---|---|---|---|---|---|---|---|\n"
|
||||
plan = lambda *rows, renamed=(): header + "".join(row.format(id=id_, release=release) for id_, release in rows) + ("\n## Renamed\n\n" + "".join(f"- {old} renamed to {new}\n" for old, new in renamed) if renamed else "")
|
||||
cases = (
|
||||
("renamed", [plan((1, "0.2.1")), plan((1, "0.3.0"), renamed=[("0.2.1", "0.3.0")])], {(0, 3, 0)}),
|
||||
("deferred: its items moved without a mark", [plan((1, "0.2.1"), (2, "0.3.0")), plan((1, "0.3.0"), (2, "0.3.0"))], {(0, 2, 1), (0, 3, 0)}),
|
||||
("renamed in a change that also dropped one of its items", [plan((1, "0.2.1"), (3, "0.2.1")), plan((1, "0.3.0"), renamed=[("0.2.1", "0.3.0")])], {(0, 3, 0)}),
|
||||
("the plan shifted one minor", [plan((1, "0.2.1"), (2, "0.3.0")), plan((1, "0.3.0"), (2, "0.4.0"), renamed=[("0.2.1", "0.3.0"), ("0.3.0", "0.4.0")])], {(0, 3, 0), (0, 4, 0)}),
|
||||
("the mark stays in later plans", [plan((1, "0.2.1")), plan((1, "0.3.0"), renamed=[("0.2.1", "0.3.0")]), plan((1, "0.3.0"), (2, "0.3.0"), renamed=[("0.2.1", "0.3.0")])], {(0, 3, 0)}),
|
||||
("renamed, then named again", [plan((1, "0.2.1")), plan((1, "0.3.0"), renamed=[("0.2.1", "0.3.0")]), plan((1, "0.3.0"), (3, "0.2.1"), renamed=[("0.2.1", "0.3.0")])], {(0, 2, 1), (0, 3, 0)}),
|
||||
("an older plan's mark that does not parse", [plan((1, "0.2.1")), plan((1, "0.3.0")) + "\n## Renamed\n\nsoon\n", plan((1, "0.3.0"))], {(0, 2, 1), (0, 3, 0)}),
|
||||
)
|
||||
for name, texts, named in cases:
|
||||
with self.subTest(name):
|
||||
self.assertEqual(chunk_pick.named_releases(texts), named)
|
||||
|
||||
def test_fails_to_name_releases_when_the_newest_plan_marks_one_in_a_form_it_cannot_read(self):
|
||||
plan = "## Items\n\n| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |\n|---|---|---|---|---|---|---|---|---|---|---|---|\n| 1 | 0.3.0 | | | **Do 1.** | 1 | 1 | 1 | 1 | 1 | 1 by 1 | 10.0 |\n"
|
||||
self.assertIsInstance(chunk_pick.named_releases([plan, plan + "\n## Renamed\n\nsoon\n"]), Failure)
|
||||
+191
-78
@@ -13,7 +13,10 @@ import rank_todo
|
||||
from repo_checks.test_python_floor import ROOT
|
||||
import todo_table
|
||||
|
||||
README = "# P\n\n## Goals\n\n1. **Achieve:** Fast.\n2. **Maintain:** Correct.\n 1. **Achieve:** Tested.\n\n## Audience\n\nMe.\n"
|
||||
# Voids code health, so these tests weigh only the project's own goals; class CodeHealth weighs it.
|
||||
VOID = "**Void:** code health, since a test project has no code to read.\n\n"
|
||||
|
||||
README = "# P\n\n## Goals\n\n" + VOID + "1. **Achieve:** Fast.\n2. **Maintain:** Correct.\n 1. **Achieve:** Tested.\n\n## Audience\n\nMe.\n"
|
||||
|
||||
DECISIONS = "## A choice\n\nStands until `todo.md` item 5 ends it.\n"
|
||||
|
||||
@@ -33,7 +36,7 @@ TODO = """# todo
|
||||
|---|---|---|---|---|---|---|---|---|---|---|---|
|
||||
| 1 | 0.2.0 | | | **Ship the later thing.** | 1 | 1 | 1 | 1 | 1 | 1 by 9 | 0 |
|
||||
| 2 | 0.1.0 | | | **Tighten the tests.** | 1 | 2 | 1 | 2 | 4 | 2.1 by 1 | 0 |
|
||||
| 3 | 0.1.0 | | | **Make it fast, `a \\| b`.** | 2 | 1 | 2 | 3 | 8 | 2.1 by 8, 1 by 6 | 0 |
|
||||
| 3 | 0.1.0 | | | **Make it fast, `a \\| b`.** | 2 | 1 | 2 | 3 | 7 | 2.1 by 8, 1 by 6 | 0 |
|
||||
| 4 | 0.1.0 | | security | **Rotate the leaked key.** | 3 | 3 | 5 | 9 | 2 | 2.1 by 1 | 0 |
|
||||
| 5 | 0.1.0 | | decision | **Move the writes out.** | 1 | 1 | 4 | 5 | 5 | 2.1 by 1 | 0 |
|
||||
|
||||
@@ -96,15 +99,15 @@ Kept as written.
|
||||
|
||||
class Rank(unittest.TestCase):
|
||||
def ranked(self, todo=TODO, readme=README, decisions=DECISIONS):
|
||||
return rank_todo.rank(todo, readme, decisions)
|
||||
return rank_todo.rank(todo, readme, decisions, "")
|
||||
|
||||
def test_scores_and_sorts_by_release_then_security_then_score_and_orders_the_details_to_match(self):
|
||||
ranked = self.ranked()
|
||||
self.assertIn("""| 4 | 0.1.0 | | security | **Rotate the leaked key.** | 3 | 3 | 5 | 9 | 2 | 2.1 by 1 | 8.3 |
|
||||
| 3 | 0.1.0 | | | **Make it fast, `a \\| b`.** | 2 | 1 | 2 | 3 | 8 | 2.1 by 8, 1 by 6 | 2.6 |
|
||||
| 2 | 0.1.0 | | | **Tighten the tests.** | 1 | 2 | 1 | 2 | 4 | 2.1 by 1 | 2.1 |
|
||||
| 5 | 0.1.0 | | decision | **Move the writes out.** | 1 | 1 | 4 | 5 | 5 | 2.1 by 1 | 1.0 |
|
||||
| 1 | 0.2.0 | | | **Ship the later thing.** | 1 | 1 | 1 | 1 | 1 | 1 by 9 | 300.0 |
|
||||
self.assertIn("""| 4 | 0.1.0 | | security | **Rotate the leaked key.** | 3 | 3 | 5 | 9 | 2 | 2.1 by 1 | 12.3 |
|
||||
| 3 | 0.1.0 | | | **Make it fast, `a \\| b`.** | 2 | 1 | 2 | 3 | 7 | 2.1 by 8, 1 by 6 | 5.5 |
|
||||
| 2 | 0.1.0 | | | **Tighten the tests.** | 1 | 2 | 1 | 2 | 4 | 2.1 by 1 | 3.1 |
|
||||
| 5 | 0.1.0 | | decision | **Move the writes out.** | 1 | 1 | 4 | 5 | 5 | 2.1 by 1 | 1.5 |
|
||||
| 1 | 0.2.0 | | | **Ship the later thing.** | 1 | 1 | 1 | 1 | 1 | 1 by 9 | 228.4 |
|
||||
""", ranked.text)
|
||||
self.assertTrue(ranked.text.endswith("## Details\n\n### 3. Make it fast, `a | b`.\n\nFast detail.\n\n### 1. Ship the later thing.\n\nLater detail.\n\n## Notes\n\nKept as written.\n"))
|
||||
self.assertEqual(ranked.under_bar, [])
|
||||
@@ -115,12 +118,24 @@ class Rank(unittest.TestCase):
|
||||
quoting = TODO.replace("Fast detail.", " ## Goals\n\nFast detail.")
|
||||
self.assertIn("### 3. Make it fast, `a | b`.\n\n ## Goals\n\nFast detail.\n", self.ranked(quoting).text)
|
||||
|
||||
def test_weighs_each_achieve_goal_by_its_sum_reciprocal_rank(self):
|
||||
def test_weighs_each_achieve_goal_97_percent_of_the_one_above_and_a_defects_maintain_goal_as_the_first(self):
|
||||
readme = "## Goals\n\n1. **Achieve:** A.\n 1. **Maintain:** B.\n 2. **Achieve:** C.\n2. **Achieve:** D.\n"
|
||||
self.assertEqual({goal: round(weight, 4) for goal, weight in rank_todo.goal_weights(rank_todo.readme_goals(readme)).items()}, {"1": 0.5455, "1.1": 0.5455, "1.2": 0.2727, "2": 0.1818})
|
||||
self.assertEqual({goal: round(weight, 4) for goal, weight in rank_todo.goal_weights(rank_todo.readme_goals(readme), None).items()}, {"1": 0.3435, "1.1": 0.3435, "1.2": 0.3332, "2": 0.3232})
|
||||
|
||||
def test_weighs_5_achieve_goals_from_0212_to_0188_and_15_from_0082_to_0053_as_the_help_says(self):
|
||||
for count, first, last in ((5, 0.212, 0.188), (15, 0.082, 0.053)):
|
||||
with self.subTest(count=count):
|
||||
goals = rank_todo.readme_goals("## Goals\n\n" + "".join(f"{number}. **Achieve:** G.\n" for number in range(1, count + 1)))
|
||||
weights = list(rank_todo.goal_weights(goals, None).values())
|
||||
self.assertEqual((round(weights[0], 3), round(weights[-1], 3), round(sum(weights), 6)), (first, last, 1))
|
||||
for figure in (rank_todo.GOAL_STEP, first, last):
|
||||
self.assertIn(str(figure), rank_todo.__doc__)
|
||||
self.assertIn(f"While it is under {rank_todo.FLOOR}, or the history holds no scoring run, code health weighs {rank_todo.UNDER_FLOOR} times its weight by position, and the other goals keep theirs.", " ".join(rank_todo.__doc__.split()))
|
||||
|
||||
def test_scores_an_item_by_the_weights_of_the_goals_it_moves(self):
|
||||
readme = "## Goals\n\n" + VOID + "1. **Achieve:** A.\n 1. **Maintain:** B.\n 2. **Achieve:** C.\n2. **Achieve:** D.\n"
|
||||
todo = TODO.replace("2.1 by 8, 1 by 6", "1.2 by 2, 2 by 3").replace("| 2.1 by 1 |", "| 1 by 1 |")
|
||||
ranked = self.ranked(todo, readme)
|
||||
self.assertIn("| **Make it fast, `a \\| b`.** | 2 | 1 | 2 | 3 | 8 | 1.2 by 2, 2 by 3 | 0.4 |", ranked.text)
|
||||
self.assertIn("| **Make it fast, `a \\| b`.** | 2 | 1 | 2 | 3 | 7 | 1.2 by 2, 2 by 3 | 1.3 |", self.ranked(todo, readme).text)
|
||||
|
||||
def test_scores_an_item_that_moves_no_goal_zero(self):
|
||||
ranked = self.ranked(TODO.replace("| 1 | 2 | 1 | 2 | 4 | 2.1 by 1 |", "| 1 | 2 | 1 | 2 | 4 | |"))
|
||||
@@ -133,11 +148,11 @@ class Rank(unittest.TestCase):
|
||||
self.assertEqual(gone.reason, "docs/decisions.md cites \"`todo.md` item 5\", which todo.md no longer holds; revise that decision to say what holds now")
|
||||
|
||||
def test_names_each_item_under_the_bar_that_is_not_exempt(self):
|
||||
ranked = self.ranked(TODO.replace("`Bar = 2`", "`Bar = 2.5`"))
|
||||
self.assertEqual(ranked.under_bar, ["item 2 scores 2.1, under the bar 2.5; delete it, or mark it with a reason the bar does not apply"])
|
||||
self.assertEqual(self.ranked(TODO.replace("`Bar = 2`", "`Bar = 2.1`")).under_bar, [])
|
||||
blocking = self.ranked(TODO.replace("`Bar = 2`", "`Bar = 2.5`").replace("| 3 | 0.1.0 | |", "| 3 | 0.1.0 | 2 |").replace("| 5 | 0.1.0 | |", "| 5 | 0.1.0 | 3 |"))
|
||||
self.assertEqual(blocking.under_bar, ["item 2 scores 2.1, under the bar 2.5; delete it and the items it blocks, directly or through another (3, 5), or mark it with a reason the bar does not apply"])
|
||||
ranked = self.ranked(TODO.replace("`Bar = 2`", "`Bar = 3.5`"))
|
||||
self.assertEqual(ranked.under_bar, ["item 2 scores 3.1, under the bar 3.5; delete it, or mark it with a reason the bar does not apply"])
|
||||
self.assertEqual(self.ranked(TODO.replace("`Bar = 2`", "`Bar = 3.1`")).under_bar, [])
|
||||
blocking = self.ranked(TODO.replace("`Bar = 2`", "`Bar = 3.5`").replace("| 3 | 0.1.0 | |", "| 3 | 0.1.0 | 2 |").replace("| 5 | 0.1.0 | |", "| 5 | 0.1.0 | 3 |"))
|
||||
self.assertEqual(blocking.under_bar, ["item 2 scores 3.1, under the bar 3.5; delete it and the items it blocks, directly or through another (3, 5), or mark it with a reason the bar does not apply"])
|
||||
self.assertEqual(self.ranked(ranked.text.replace("| 2 | 0.1.0 | | |", "| 2 | 0.1.0 | | principle |")).under_bar, [])
|
||||
self.assertEqual(self.ranked(ranked.text.replace("| 2 | 0.1.0 | | |", "| 2 | 0.1.0 | | owner |")).under_bar, [])
|
||||
|
||||
@@ -166,10 +181,10 @@ class Rank(unittest.TestCase):
|
||||
|
||||
def test_weighs_the_maintain_goal_a_defect_restores_as_the_heaviest_achieve_goal(self):
|
||||
ranked = self.ranked(TODO.replace("| 2 | 0.1.0 | | | **Tighten the tests.** | 1 | 2 | 1 | 2 | 4 | 2.1 by 1 |", "| 2 | 0.1.0 | | defect | **Tighten the tests.** | 1 | 2 | 1 | 2 | 4 | 2 by 3 |"))
|
||||
self.assertIn("| **Tighten the tests.** | 1 | 2 | 1 | 2 | 4 | 2 by 3 | 12.5 |", ranked.text)
|
||||
self.assertIn("| **Tighten the tests.** | 1 | 2 | 1 | 2 | 4 | 2 by 3 | 9.5 |", ranked.text)
|
||||
|
||||
def test_refuses_a_goal_named_beside_its_own_sub_goal(self):
|
||||
readme = "## Goals\n\n1. **Achieve:** A.\n 1. **Maintain:** B.\n 2. **Achieve:** C.\n2. **Achieve:** D.\n"
|
||||
readme = "## Goals\n\n" + VOID + "1. **Achieve:** A.\n 1. **Maintain:** B.\n 2. **Achieve:** C.\n2. **Achieve:** D.\n"
|
||||
todo = TODO.replace("2.1 by 8, 1 by 6", "1.2 by 2, 1 by 3").replace("| 2.1 by 1 |", "| 2 by 1 |")
|
||||
self.assertEqual(self.ranked(todo, readme), Failure("item 3 names goal 1 and its sub-goal 1.2; name one, never both: the sub-goal where the move serves it, else the parent"))
|
||||
self.assertIsInstance(self.ranked(todo.replace("1.2 by 2, 1 by 3", "1.2 by 2, 2 by 3"), readme), rank_todo.Ranked)
|
||||
@@ -177,15 +192,15 @@ class Rank(unittest.TestCase):
|
||||
def test_scores_every_item_zero_where_readme_marks_no_goal_achieve(self):
|
||||
ranked = self.ranked(TODO.replace("2.1 by 8, 1 by 6", "").replace("| 2.1 by 1 |", "| |").replace("| 1 by 9 |", "| |"), README.replace("**Achieve:**", "**Maintain:**"))
|
||||
self.assertEqual([line.split(" scores ")[0] for line in ranked.under_bar], ["item 2", "item 3", "item 1"])
|
||||
self.assertEqual(ranked.notes, ["README.md marks no goal **Achieve:**, so every item scores V 0"])
|
||||
self.assertEqual(ranked.notes, ["README.md voids code health and marks no goal **Achieve:**, so every item scores V 0"])
|
||||
|
||||
def test_accepts_a_move_of_ten_and_a_variable_base(self):
|
||||
ranked = self.ranked(TODO.replace("| 1 by 9 |", "| 1 by 10 |").replace("100 * V / 2**S", "V * S ** 2"))
|
||||
self.assertIn("| **Ship the later thing.** | 1 | 1 | 1 | 1 | 1 | 1 by 10 | 6.7 |", ranked.text)
|
||||
self.assertIn("| **Ship the later thing.** | 1 | 1 | 1 | 1 | 1 | 1 by 10 | 5.1 |", ranked.text)
|
||||
|
||||
def test_asks_to_drop_a_goal_weights_table_from_a_table_with_moves(self):
|
||||
weighted = TODO.replace("## Items\n", "| Goal | W |\n|---|---|\n| 1 | 1.00 |\n\n## Items\n")
|
||||
self.assertEqual(self.ranked(weighted), Failure("todo.md holds a goal weights table beside a Moves column; drop the table, since rank_todo.py weighs each achieve goal by its position in README.md"))
|
||||
self.assertEqual(self.ranked(weighted), Failure("todo.md holds a goal weights table beside a Moves column; drop the table, since rank_todo.py weighs the goals itself, as its --help says"))
|
||||
|
||||
def test_refuses_a_formula_that_is_more_than_arithmetic_over_the_scores(self):
|
||||
for formula in ("__import__('os')", "R.real", "X + 1", "C + 1", "A + V", "G + V", "W * V", "R ^ 2", "R +", "R / (S - 2)", "R\x00", "1" * 400, " + ".join(["R"] * 300), "-" * 100000 + "R", "10 ** 10 ** 10", "(-8) ** (1 / 3)", "0 ** -1"):
|
||||
@@ -195,7 +210,7 @@ class Rank(unittest.TestCase):
|
||||
self.assertEqual(self.ranked(TODO.replace("100 * V / 2**S", "1 ** (1 / (S - S))")), Failure("the formula gives item 1 no finite score"))
|
||||
self.assertEqual(self.ranked(TODO.replace("100 * V / 2**S", "(1 / (S - S)) ** 0")), Failure("the formula gives item 1 no finite score"))
|
||||
self.assertEqual(self.ranked(TODO.replace("100 * V / 2**S", "W")), Failure("the formula 'W' may hold only numbers, E, I, L, R, S, V, + - * / ** and parentheses"))
|
||||
self.assertEqual(self.ranked(TODO.replace("2.1 by 8, 1 by 6", "2.1: 8, 1: 6")), Failure("item 3's Moves '2.1: 8, 1: 6' is not empty or goals such as `1.1 by 8, 1.2 by 5`, each moved by a whole number from 1 to 10"))
|
||||
self.assertEqual(self.ranked(TODO.replace("2.1 by 8, 1 by 6", "2.1: 8, 1: 6")), Failure("item 3's Moves '2.1: 8, 1: 6' is not empty or goals such as `1.1 by 8, code health by 5`, each moved by a whole number from 1 to 10"))
|
||||
|
||||
def test_refuses_a_file_off_the_format(self):
|
||||
row = "| 2 | 0.1.0 | | | **Tighten the tests.** | 1 | 2 | 1 | 2 | 4 | 2.1 by 1 | 0 |"
|
||||
@@ -210,7 +225,7 @@ class Rank(unittest.TestCase):
|
||||
"Move the writes out.** | 1 | 1 | 4 | 5 | 5 | 2.1 by 1": "Move the writes out.** | 1 | 1 | 4 | 5 | 5 | 2.1 by 0",
|
||||
"2.1 by 8, 1 by 6": "2.1: 8, 1: 6",
|
||||
"2.1 by 8, 1 by 6 ": "2.1 by 8,1 by 6 ",
|
||||
"| 2 | 1 | 2 | 3 | 8 | 2.1 by 8, 1 by 6 |": "| 2 | 1 | 2 | 3 | 8 | 2.1, 1 |",
|
||||
"| 2 | 1 | 2 | 3 | 7 | 2.1 by 8, 1 by 6 |": "| 2 | 1 | 2 | 3 | 7 | 2.1, 1 |",
|
||||
row + "\n": row.replace("2 | 4 |", "2 | ² |") + "\n",
|
||||
"| 2.1 by 1 | 0 |\n\n## Details": "| 2.1 by 1 | 0 |\n\n| 9 | 0.1.0 | | | **Stray.** | 1 | 1 | 1 | 1 | 1 | 1 by 1 | 0 |\n\n## Details",
|
||||
"| 4 | 0.1.0 | | security |": "| 4 | 0.1.0 | | later |",
|
||||
@@ -229,28 +244,134 @@ class Rank(unittest.TestCase):
|
||||
self.assertIsInstance(self.ranked(TODO.replace(old, new)), Failure)
|
||||
|
||||
|
||||
# A scoring run of the project whose overall mean is {overall}.
|
||||
SCORED = "# Comprehension history\n\n## 2026-10-08T12:00:00Z, PR #1 at aaaaaaa\n\n| Seat | Overall |\n|---|---|\n| Mid A | 6 |\n| Mean | {overall} |\n"
|
||||
|
||||
|
||||
class CodeHealth(unittest.TestCase):
|
||||
readme = "## Goals\n\n1. **Achieve:** A.\n"
|
||||
todo = TODO.split("| 1 | 0.2.0", 1)[0].replace("`Bar = 2`", "`Bar = 0.1`") + "| 1 | 0.1.0 | | | **Read easier.** | 1 | 1 | 1 | 1 | 1 | code health by 1 | 0 |\n| 2 | 0.1.0 | | | **Do A.** | 1 | 1 | 1 | 1 | 1 | 1 by 1 | 0 |\n"
|
||||
|
||||
def scores(self, history, readme=readme):
|
||||
ranked = rank_todo.rank(self.todo, readme, "", history)
|
||||
return ranked if isinstance(ranked, Failure) else {line.split(" | ")[0]: line.rsplit(" | ", 1)[1].rstrip(" |") for line in ranked.text.splitlines() if line.startswith("| ") and " 0.1.0 " in line}
|
||||
|
||||
def entry(self, overall, at="2026-10-08T12", read="PR #1 at aaaaaaa"):
|
||||
"""A scoring run's entry, without the history's title."""
|
||||
return SCORED.format(overall=overall).removeprefix("# Comprehension history\n\n").replace("2026-10-08T12", at).replace("PR #1 at aaaaaaa", read)
|
||||
|
||||
def test_ranks_code_health_first_among_the_achieve_goals_at_an_overall_of_7_or_above(self):
|
||||
# Code health, then goal 1: weights 1 / 1.97 and 0.97 / 1.97, an item moving one by 1 at S 1 scoring 50 times its weight.
|
||||
self.assertEqual(self.scores(SCORED.format(overall="7.00")), {"| 1": "25.4", "| 2": "24.6"})
|
||||
|
||||
def test_weighs_code_health_four_times_as_much_under_an_overall_of_7_and_before_any_scoring_run(self):
|
||||
for history in (SCORED.format(overall="6.99"), "", "# Comprehension history\n\n## 2026-10-09T12:00:00Z, PR #2 at bbbbbbb, against aaaaaaa\n\nRuling: better\n"):
|
||||
with self.subTest(history=history):
|
||||
self.assertEqual(self.scores(history), {"| 1": "101.5", "| 2": "24.6"})
|
||||
|
||||
def test_weighs_by_the_newest_scored_commit_wherever_the_file_holds_it(self):
|
||||
older = self.entry("6.50")
|
||||
newer = self.entry("7.25", "2026-10-10T12", "PR #1 at bbbbbbb")
|
||||
for history in (f"{older}\n{newer}", f"{newer}\n{older}"):
|
||||
with self.subTest(history=history):
|
||||
self.assertEqual(self.scores(history)["| 1"], "25.4")
|
||||
|
||||
def test_weighs_by_the_mean_overall_of_every_run_on_the_newest_scored_commit(self):
|
||||
# 7.13 and 6.88 average 7.005, at the floor or above; 7.10 and 6.80 average 6.95, under it.
|
||||
for first, rerun, value in (("7.13", "6.88", "25.4"), ("7.10", "6.80", "101.5")):
|
||||
with self.subTest(first=first, rerun=rerun):
|
||||
self.assertEqual(self.scores(f"{self.entry(first)}\n{self.entry(rerun, '2026-10-08T13', 'PR #1 rerun at aaaaaaa')}")["| 1"], value)
|
||||
later = self.entry("6.50", "2026-10-09T12", "PR #2 at bbbbbbb")
|
||||
self.assertEqual(self.scores(f"{self.entry('7.13')}\n{self.entry('6.88', '2026-10-08T13', 'PR #1 rerun at aaaaaaa')}\n{later}")["| 1"], "101.5")
|
||||
|
||||
def test_matches_a_commit_whichever_length_a_heading_writes_it_at(self):
|
||||
full = "aaaaaaa" + "0" * 33
|
||||
# As runs of one commit, 7.13 and 6.88 average 7.005; the newer alone is under the floor.
|
||||
for first, rerun in (("aaaaaaa", full), (full, "aaaaaaa")):
|
||||
with self.subTest(first=first, rerun=rerun):
|
||||
self.assertEqual(self.scores(f"{self.entry('7.13', read=f'PR #1 at {first}')}\n{self.entry('6.88', '2026-10-08T13', f'PR #1 rerun at {rerun}')}")["| 1"], "25.4")
|
||||
|
||||
def test_weighs_by_a_ruling_that_holds_scoring_seats_places(self):
|
||||
# A ruling recorded before PR #255 scored the project too: below its votes, a scores table with a Mean row, and each scoring seat's places.
|
||||
ruling = "## 2026-10-10T12:00:00Z, PR #2 at bbbbbbb, against aaaaaaa\n\nRuling: better\n\n| Seat | Overall |\n|---|---|\n| Mid A | better |\n\n| Seat | Overall |\n|---|---|\n| Mid A | 7.5 |\n| Mean | 7.25 |\n\nJunior A, hardest first:\n\n- `bin/a.py:1` `f`: long\n"
|
||||
self.assertEqual(self.scores(f"{self.entry('6.50')}\n{ruling}")["| 1"], "25.4")
|
||||
|
||||
def test_refuses_a_newest_scoring_run_with_no_overall_mean(self):
|
||||
for history in (SCORED.format(overall="high"), SCORED.split("| Mean")[0]):
|
||||
with self.subTest(history=history):
|
||||
self.assertEqual(self.scores(history), Failure("docs/comprehension-history.md's scoring run 2026-10-08T12:00:00Z, PR #1 at aaaaaaa has no Mean row ending in its overall, which sets code health's weight"))
|
||||
|
||||
def test_drops_code_health_where_readme_voids_it(self):
|
||||
voided = "## Goals\n\n**Void:** code health, since it is a one-off script.\n\n1. **Achieve:** A.\n"
|
||||
self.assertEqual(self.scores("", voided), Failure("item 1 names code health, which README.md voids; drop it from the item's Moves, or the void from README.md"))
|
||||
ranked = rank_todo.rank(self.todo.replace("code health by 1", "1 by 2"), voided, "", "")
|
||||
self.assertIn("| **Read easier.** | 1 | 1 | 1 | 1 | 1 | 1 by 2 | 100.0 |", ranked.text)
|
||||
|
||||
def test_weighs_a_defects_maintain_goal_as_code_health_four_times_over_under_an_overall_of_7(self):
|
||||
readme = "## Goals\n\n1. **Achieve:** A.\n2. **Maintain:** B.\n"
|
||||
todo = self.todo.replace("| 2 | 0.1.0 | | | **Do A.** | 1 | 1 | 1 | 1 | 1 | 1 by 1 |", "| 2 | 0.1.0 | | defect | **Restore B.** | 1 | 1 | 1 | 1 | 1 | 2 by 1 |")
|
||||
for history, value in (("", "101.5"), (SCORED.format(overall="7.00"), "25.4")):
|
||||
with self.subTest(history=history):
|
||||
self.assertIn(f"| **Restore B.** | 1 | 1 | 1 | 1 | 1 | 2 by 1 | {value} |", rank_todo.rank(todo, readme, "", history).text)
|
||||
|
||||
def test_refuses_a_plan_whose_project_opts_out_of_the_comprehension_check_yet_keeps_code_health(self):
|
||||
opted_out = "## review opt-out: the architect and the comprehension check\n\nCosts rounds.\n"
|
||||
self.assertEqual(rank_todo.rank(self.todo, self.readme, opted_out, ""), Failure("docs/decisions.md opts out of the comprehension check, so code health has no signal; void it in README.md's ## Goals with `**Void:** code health, since <reason>.`, as ~/.claude/CLAUDE.md → 'Shared goal' says"))
|
||||
self.assertIsInstance(rank_todo.rank(self.todo, self.readme, opted_out.replace(" and the comprehension check", ""), ""), rank_todo.Ranked)
|
||||
voided = "## Goals\n\n**Void:** code health, since nobody reads the probes.\n\n1. **Achieve:** A.\n"
|
||||
self.assertIsInstance(rank_todo.rank(self.todo.replace("code health by 1", "1 by 2"), voided, opted_out, ""), rank_todo.Ranked)
|
||||
|
||||
def test_ranks_a_project_that_voids_code_health_whatever_its_history_holds(self):
|
||||
voided = "## Goals\n\n**Void:** code health, since it is a one-off script.\n\n1. **Achieve:** A.\n"
|
||||
self.assertIsInstance(rank_todo.rank(self.todo.replace("code health by 1", "1 by 2"), voided, "", SCORED.format(overall="high")), rank_todo.Ranked)
|
||||
|
||||
def test_refuses_a_void_of_anything_but_code_health(self):
|
||||
self.assertEqual(self.scores("", "## Goals\n\n**Void:** speed, since nobody waits.\n\n1. **Achieve:** A.\n"), Failure("README.md's ## Goals voids `speed, since nobody waits.`; only code health may be voided, as `**Void:** code health, since <reason>.`"))
|
||||
|
||||
def test_shows_the_spelling_of_a_void_of_code_health_that_misses_it(self):
|
||||
for void in ("code health.", "Code health, since it is a one-off script.", "code health since it is a one-off script."):
|
||||
with self.subTest(void=void):
|
||||
self.assertEqual(self.scores("", f"## Goals\n\n**Void:** {void}\n\n1. **Achieve:** A.\n"), Failure(f"README.md's ## Goals voids code health as `{void}`; spell the void exactly `**Void:** code health, since <reason>.`"))
|
||||
|
||||
def test_parses_code_health_in_a_moves_cell(self):
|
||||
self.assertEqual(todo_table.parse_moves("1", "code health by 4, 1.1 by 2"), (("code health", 4), ("1.1", 2)))
|
||||
self.assertIsInstance(todo_table.parse_moves("1", "code health by 11"), Failure)
|
||||
self.assertIsInstance(todo_table.parse_moves("1", "health by 4"), Failure)
|
||||
|
||||
def test_reads_the_history_beside_todo_md(self):
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
todo = pathlib.Path(temp, "todo.md")
|
||||
todo.write_text(self.todo)
|
||||
pathlib.Path(temp, "README.md").write_text(self.readme)
|
||||
pathlib.Path(temp, "docs").mkdir()
|
||||
pathlib.Path(temp, "docs", "comprehension-history.md").write_text(SCORED.format(overall="7.00"))
|
||||
with contextlib.redirect_stderr(io.StringIO()):
|
||||
self.assertEqual(rank_todo.main([str(todo)]), 0)
|
||||
self.assertIn("| code health by 1 | 25.4 |", todo.read_text())
|
||||
|
||||
|
||||
class Risk(unittest.TestCase):
|
||||
"""R is L + E + I - 2, which rank_todo.py writes, at least 7 when I is 5 and at least 5 when I is 4."""
|
||||
def ranked(self, todo):
|
||||
return rank_todo.rank(todo, README, DECISIONS)
|
||||
return rank_todo.rank(todo, README, DECISIONS, "")
|
||||
|
||||
def test_writes_r_from_l_e_and_i_over_a_stale_or_missing_r(self):
|
||||
ranked = self.ranked(TODO).text
|
||||
for levels, risk in (("| 1 | 1 | 1 |", 1), ("| 2 | 1 | 2 |", 3), ("| 1 | 2 | 1 |", 2)):
|
||||
with self.subTest(levels=levels):
|
||||
self.assertIn(f"{levels} {risk} |", ranked)
|
||||
stale = TODO.replace("| 2 | 1 | 2 | 3 | 8 |", "| 2 | 1 | 2 | 10 | 8 |")
|
||||
stale = TODO.replace("| 2 | 1 | 2 | 3 | 7 |", "| 2 | 1 | 2 | 10 | 7 |")
|
||||
self.assertEqual(self.ranked(stale).text, ranked)
|
||||
without_r = TODO.replace("| I | R | S |", "| I | S |").replace("|---|---|---|---|---|---|---|---|---|---|---|---|", "|---|---|---|---|---|---|---|---|---|---|---|")
|
||||
without_r = re.sub(r"(\*\* \| \d+ \| \d+ \| \d+) \| \d+ \|", r"\1 |", without_r)
|
||||
self.assertEqual(self.ranked(without_r).text, ranked)
|
||||
|
||||
def test_writes_r_into_a_blank_r_cell(self):
|
||||
blank = TODO.replace("| 2 | 1 | 2 | 3 | 8 |", "| 2 | 1 | 2 | | 8 |")
|
||||
blank = TODO.replace("| 2 | 1 | 2 | 3 | 7 |", "| 2 | 1 | 2 | | 7 |")
|
||||
self.assertEqual(self.ranked(blank).text, self.ranked(TODO).text)
|
||||
|
||||
def test_leaves_a_stale_r_to_ranking_so_a_reader_keeps_the_r_the_table_stored(self):
|
||||
stale = TODO.replace("| 2 | 1 | 2 | 3 | 8 |", "| 2 | 1 | 2 | 10 | 8 |")
|
||||
stale = TODO.replace("| 2 | 1 | 2 | 3 | 7 |", "| 2 | 1 | 2 | 10 | 7 |")
|
||||
self.assertEqual(next(item for item in todo_table.items(stale) if item.id == 3).scores["R"], 10)
|
||||
self.assertNotEqual(self.ranked(stale).text, stale)
|
||||
|
||||
@@ -281,7 +402,7 @@ class Risk(unittest.TestCase):
|
||||
class OldShape(unittest.TestCase):
|
||||
"""A table with A, G and Goals, from before the Moves column, ranks by the formula and goal weights it states until its project reshapes it."""
|
||||
def ranked(self, todo=OLD_SHAPE, readme=README):
|
||||
return rank_todo.rank(todo, readme, DECISIONS)
|
||||
return rank_todo.rank(todo, readme, DECISIONS, "")
|
||||
|
||||
def test_scores_by_the_stated_weights_and_says_to_reshape(self):
|
||||
ranked = self.ranked()
|
||||
@@ -308,7 +429,7 @@ class OldShape(unittest.TestCase):
|
||||
|
||||
def test_ranks_a_table_from_before_c_joined_and_says_to_reshape_it(self):
|
||||
legacy = OLD_SHAPE.split("## Items")[0] + "## Items\n\n| ID | Release | Exempt | Item | R | S | A | G | Goals | Score |\n|---|---|---|---|---|---|---|---|---|---|\n| 2 | 0.1.0 | | **Tighten the tests.** | 2 | 4 | 5 | 5 | 2.1 | 0 |\n"
|
||||
self.assertEqual(rank_todo.rank(legacy, README, "").notes, [rank_todo.RESHAPE])
|
||||
self.assertEqual(rank_todo.rank(legacy, README, "", "").notes, [rank_todo.RESHAPE])
|
||||
|
||||
def test_refuses_a_table_with_both_moves_and_goals(self):
|
||||
both = OLD_SHAPE.replace("| Goals | Score |\n|---|", "| Goals | Moves | Score |\n|---|---|").replace(" | 0 |\n", " | 1 by 1 | 0 |\n")
|
||||
@@ -318,22 +439,22 @@ class OldShape(unittest.TestCase):
|
||||
|
||||
def test_names_the_goals_column_a_table_misspells_by_its_shape(self):
|
||||
misspelt = TODO.replace("| S | Moves |", "| S | Move |")
|
||||
self.assertEqual(rank_todo.rank(misspelt, README, DECISIONS), Failure("todo.md's items table has no Moves column; rank_todo.py --help shows a valid one"))
|
||||
self.assertEqual(rank_todo.rank(misspelt, README, DECISIONS, ""), Failure("todo.md's items table has no Moves column; rank_todo.py --help shows a valid one"))
|
||||
self.assertEqual(todo_table.items(misspelt), Failure("todo.md's items table has no Moves column; rank_todo.py --help shows a valid one"))
|
||||
self.assertEqual(self.ranked(OLD_SHAPE.replace("| G | Goals |", "| G | Goal |")), Failure("todo.md's items table has no Goals column; rank_todo.py --help shows a valid one"))
|
||||
|
||||
|
||||
class Blockers(unittest.TestCase):
|
||||
def ranked(self, todo):
|
||||
return rank_todo.rank(todo, README, DECISIONS)
|
||||
return rank_todo.rank(todo, README, DECISIONS, "")
|
||||
|
||||
def test_ranks_each_blocker_just_above_the_first_item_it_blocks(self):
|
||||
ranked = self.ranked(TODO.replace("| 3 | 0.1.0 | |", "| 3 | 0.1.0 | 5, 2 |"))
|
||||
self.assertIn("""| 4 | 0.1.0 | | security | **Rotate the leaked key.** | 3 | 3 | 5 | 9 | 2 | 2.1 by 1 | 8.3 |
|
||||
| 2 | 0.1.0 | | | **Tighten the tests.** | 1 | 2 | 1 | 2 | 4 | 2.1 by 1 | 2.1 |
|
||||
| 5 | 0.1.0 | | decision | **Move the writes out.** | 1 | 1 | 4 | 5 | 5 | 2.1 by 1 | 1.0 |
|
||||
| 3 | 0.1.0 | 2, 5 | | **Make it fast, `a \\| b`.** | 2 | 1 | 2 | 3 | 8 | 2.1 by 8, 1 by 6 | 2.6 |
|
||||
| 1 | 0.2.0 | | | **Ship the later thing.** | 1 | 1 | 1 | 1 | 1 | 1 by 9 | 300.0 |
|
||||
self.assertIn("""| 4 | 0.1.0 | | security | **Rotate the leaked key.** | 3 | 3 | 5 | 9 | 2 | 2.1 by 1 | 12.3 |
|
||||
| 2 | 0.1.0 | | | **Tighten the tests.** | 1 | 2 | 1 | 2 | 4 | 2.1 by 1 | 3.1 |
|
||||
| 5 | 0.1.0 | | decision | **Move the writes out.** | 1 | 1 | 4 | 5 | 5 | 2.1 by 1 | 1.5 |
|
||||
| 3 | 0.1.0 | 2, 5 | | **Make it fast, `a \\| b`.** | 2 | 1 | 2 | 3 | 7 | 2.1 by 8, 1 by 6 | 5.5 |
|
||||
| 1 | 0.2.0 | | | **Ship the later thing.** | 1 | 1 | 1 | 1 | 1 | 1 by 9 | 228.4 |
|
||||
""", ranked.text)
|
||||
self.assertEqual(self.ranked(ranked.text), ranked)
|
||||
|
||||
@@ -415,47 +536,28 @@ class Blockers(unittest.TestCase):
|
||||
self.assertEqual(todo_table.items(f"## Items\n\n{header}"), Failure(f"the table under {header} has no |---| divider line"))
|
||||
|
||||
|
||||
class Standing(unittest.TestCase):
|
||||
def test_takes_the_earliest_release_where_it_is_the_earliest_named_since_the_last_cut(self):
|
||||
cases = (
|
||||
("v1.2.3", 4, (1, 2, 4), set(), "next"),
|
||||
("v1.2.3", 4, (1, 3, 0), {(1, 3, 0)}, "next"),
|
||||
("v1.2.3", 4, (1, 3, 0), {(1, 2, 3), (1, 3, 0)}, "next"),
|
||||
("v0.2.0", 4, (0, 4, 0), set(), "next"),
|
||||
(None, 4, (0, 2, 0), set(), "next"),
|
||||
(None, 4, None, set(), "next"),
|
||||
("v1.2.3-rc.1", 4, (1, 2, 3), set(), "next"),
|
||||
(Failure("tags unreadable"), 4, (0, 2, 0), set(), "next"),
|
||||
("v1.2.3", 4, (1, 2, 3), set(), "cut"),
|
||||
("v1.2.3", 4, (1, 2, 2), {(1, 2, 4)}, "cut"),
|
||||
("v1.2.3", 4, (1, 3, 0), {(1, 2, 4), (1, 3, 0)}, "finished"),
|
||||
("v0.9.2", 4, (1, 0, 0), {(0, 9, 3)}, "finished"),
|
||||
("v1.2.3", 4, (1, 4, 0), {(1, 2, 2), (1, 3, 0)}, "finished"),
|
||||
("v1.2.3", 4, None, {(1, 3, 0)}, "finished"),
|
||||
("v1.2.3", 4, None, set(), "finished"),
|
||||
("v1.2.3", 0, (1, 3, 0), {(1, 2, 4)}, "unplanned"),
|
||||
("v1.2.3", 0, None, set(), "unplanned"),
|
||||
("v1.2.3", Failure("count unreadable"), None, set(), "unknown"),
|
||||
("v1.2.3", 4, (1, 3, 0), Failure("log unreadable"), "unknown"),
|
||||
("v1.2.3", 4, (1, 2, 3), Failure("log unreadable"), "cut"),
|
||||
)
|
||||
for tag, landed, earliest, named, stands in cases:
|
||||
with self.subTest(tag=tag, landed=landed, earliest=earliest, named=named):
|
||||
self.assertEqual(todo_table.standing(tag, landed, earliest, named), stands)
|
||||
class Renamed(unittest.TestCase):
|
||||
def test_reads_the_releases_the_renamed_section_names(self):
|
||||
self.assertEqual(todo_table.renames("## Items\n\n## Details\n"), set())
|
||||
self.assertEqual(todo_table.renames("## Renamed\n\n- 0.2.1 renamed to 0.3.0\n- 0.3.0 renamed to 0.4.0\n\n## Details\n"), {(0, 2, 1), (0, 3, 0)})
|
||||
self.assertEqual(todo_table.renames("## Renamed\n\n- 0.2.1 renamed to 0.3.0 \n"), {(0, 2, 1)})
|
||||
for bad in ("soon", "- 0.2.1 is now 0.3.0", "- 0.2 renamed to 0.3.0", "- 0.2.1 renamed to 0.3.0 later", "- 0.2.1 renamed to 0.2.1"):
|
||||
with self.subTest(bad):
|
||||
self.assertIsInstance(todo_table.renames(f"## Renamed\n\n{bad}\n"), Failure)
|
||||
|
||||
def test_counts_work_landed_since_the_last_cut_by_unreleased_entries_and_else_by_commits(self):
|
||||
changelog = "# Changelog\n\n## Unreleased\n\n- One.\n - A nested line.\n- Two.\n\n## 0.1.0\n\n- Old.\n"
|
||||
self.assertEqual(todo_table.landed(todo_table.LastCut("v0.1.0", changelog, 5, [])), 2)
|
||||
self.assertEqual(todo_table.landed(todo_table.LastCut("v0.1.0", "# Changelog\n\n## Unreleased\n\n## 0.1.0\n", 5, [])), 0)
|
||||
self.assertEqual(todo_table.landed(todo_table.LastCut("v0.1.0", "# Changelog\n\n## 0.1.0\n", 5, [])), 5)
|
||||
self.assertEqual(todo_table.landed(todo_table.LastCut("v0.1.0", Failure("unreadable"), 5, [])), 5)
|
||||
def test_fails_on_a_renamed_section_that_does_not_parse(self):
|
||||
failed = rank_todo.rank(TODO + "\n## Renamed\n\nsoon\n", README, DECISIONS, "")
|
||||
self.assertIsInstance(failed, Failure)
|
||||
self.assertIn("## Renamed", failed.reason)
|
||||
|
||||
def test_ranks_a_plan_with_a_valid_renamed_section(self):
|
||||
self.assertIsInstance(rank_todo.rank(TODO + "\n## Renamed\n\n- 0.3.0 renamed to 0.4.0\n", README, DECISIONS, ""), rank_todo.Ranked)
|
||||
|
||||
def test_fails_on_an_item_filed_under_a_release_the_plan_marks_renamed(self):
|
||||
live = rank_todo.rank(TODO + "\n## Renamed\n\n- 0.2.0 renamed to 0.3.0\n", README, DECISIONS, "")
|
||||
self.assertIsInstance(live, Failure)
|
||||
self.assertIn("marks release 0.2.0 renamed but files item 1 under it", live.reason)
|
||||
|
||||
def test_names_each_release_a_todo_md_since_the_last_cut_filed_items_under(self):
|
||||
row = "| {id} | {release} | | | **Do {id}.** | 1 | 1 | 1 | 1 | 1 | 1 by 1 | 10.0 |\n"
|
||||
header = "## Items\n\n| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |\n|---|---|---|---|---|---|---|---|---|---|---|---|\n"
|
||||
texts = [header + row.format(id=1, release="0.2.0"), "", "not a table | x |", header + row.format(id=2, release="0.3.0")]
|
||||
self.assertEqual(todo_table.named_releases(texts), {(0, 2, 0), (0, 3, 0)})
|
||||
self.assertEqual(todo_table.named_releases(Failure("log unreadable")), Failure("log unreadable"))
|
||||
|
||||
|
||||
class Main(unittest.TestCase):
|
||||
@@ -480,6 +582,17 @@ class Main(unittest.TestCase):
|
||||
pathlib.Path(temp, "README.md").unlink()
|
||||
self.assertEqual(self.run_main(str(todo)), (1, f"{temp}/README.md: not found; rank_todo.py weighs goals from the README.md beside todo.md\n"))
|
||||
|
||||
def test_writes_the_ranked_file_yet_fails_on_an_item_under_the_bar(self):
|
||||
under = "item 2 scores 3.1, under the bar 4; delete it, or mark it with a reason the bar does not apply"
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
todo = pathlib.Path(temp, "todo.md")
|
||||
todo.write_text(TODO.replace("`Bar = 2`", "`Bar = 4`"))
|
||||
pathlib.Path(temp, "README.md").write_text(README)
|
||||
pathlib.Path(temp, "docs").mkdir()
|
||||
pathlib.Path(temp, "docs", "decisions.md").write_text(DECISIONS)
|
||||
self.assertEqual(self.run_main(str(todo)), (1, f"{todo}: {under}\n"))
|
||||
self.assertEqual(self.run_main("--check", str(todo)), (1, f"{todo}: {under}\n"))
|
||||
|
||||
def test_says_to_reshape_an_old_shape_table_but_passes_the_check(self):
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
todo = pathlib.Path(temp, "todo.md")
|
||||
@@ -493,7 +606,7 @@ class Main(unittest.TestCase):
|
||||
def test_shows_a_valid_file_in_help_and_names_arguments_it_cannot_read(self):
|
||||
self.assertEqual(self.run_main("--help")[0], 0)
|
||||
skeleton = "\n".join(line[4:] for line in rank_todo.__doc__.split("\n") if line.startswith(" "))
|
||||
ranked = rank_todo.rank(skeleton, "## Goals\n\n1. **Achieve:** Work.\n", "")
|
||||
ranked = rank_todo.rank(skeleton, "## Goals\n\n1. **Achieve:** Work.\n", "", "")
|
||||
self.assertIsInstance(ranked, rank_todo.Ranked)
|
||||
self.assertEqual((ranked.under_bar, ranked.notes), ([], []))
|
||||
self.assertEqual(self.run_main("--fix"), (1, "rank_todo.py: cannot read the arguments --fix; usage: rank_todo.py [--check] [todo.md]\n"))
|
||||
@@ -502,5 +615,5 @@ class Main(unittest.TestCase):
|
||||
class ThisRepo(unittest.TestCase):
|
||||
def test_todo_md_is_ranked_with_nothing_under_the_bar(self):
|
||||
text = (ROOT / "todo.md").read_text(encoding="utf-8")
|
||||
ranked = rank_todo.rank(text, (ROOT / "README.md").read_text(encoding="utf-8"), (ROOT / "docs" / "decisions.md").read_text(encoding="utf-8"))
|
||||
ranked = rank_todo.rank(text, *((ROOT / name).read_text(encoding="utf-8") for name in ("README.md", "docs/decisions.md", "docs/comprehension-history.md")))
|
||||
self.assertEqual(ranked, rank_todo.Ranked(text, [], []))
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
import pathlib
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
|
||||
|
||||
from review_folder import review_folder
|
||||
|
||||
|
||||
class ReviewFolder(unittest.TestCase):
|
||||
def test_keys_a_worktree_under_home_by_its_path_relative_to_home(self):
|
||||
self.assertEqual(review_folder("/h", "/h/code/proj-item-3"), "/h/.local/state/larv-review/code/proj-item-3")
|
||||
|
||||
def test_keys_a_worktree_outside_home_by_its_path_relative_to_the_root(self):
|
||||
self.assertEqual(review_folder("/h", "/srv/proj-item-3"), "/h/.local/state/larv-review/srv/proj-item-3")
|
||||
self.assertEqual(review_folder("/h", "/hx/proj"), "/h/.local/state/larv-review/hx/proj", "a sibling of home that shares its prefix is outside it")
|
||||
+35
-64
@@ -15,14 +15,16 @@ EXEMPTIONS = ("", "decision", "defect", "owner", "principle", "question", "secur
|
||||
BLOCKED_BY = "Blocked by"
|
||||
# The column naming each achieve goal an item moves and how far, such as `1.1 by 8, 1.2 by 5`.
|
||||
MOVES = "Moves"
|
||||
# The achieve goal every project shares, which ~/.claude/CLAUDE.md → "Shared goal" states, and a Moves cell names by these words, since it has no number in any README.
|
||||
CODE_HEALTH = "code health"
|
||||
# How the items table's header opens, which tells it from any other table in todo.md.
|
||||
HEADER_START = "| ID | Release |"
|
||||
# How the plan's earliest release stands to the version x.y.z the newest tag names, the last cut. "next": it is the earliest release after x.y.z that todo.md has named at that tag or since, or no tag names a version, or the tag cannot be read. "cut": it is x.y.z or earlier.
|
||||
# Else the next release, the earliest named since the cut, holds no item: "finished" where work landed since the cut, and "unplanned" where none did. "unknown": todo.md's texts since the cut, or the count of work landed since it, cannot be read.
|
||||
# A release named since the cut stays the next until a tag cuts it, even once its items moved to a later release, as larv_review/plan.py's emptied counts such a release emptied too.
|
||||
Standing = typing.Literal["next", "cut", "finished", "unplanned", "unknown"]
|
||||
# todo.md's ## Details section, its body the first group.
|
||||
DETAILS = re.compile(r"^## Details\n(.*?)(?=^## |\Z)", re.M | re.S)
|
||||
# A release's version, such as 0.2.1.
|
||||
RELEASE = r"[0-9]+\.[0-9]+\.[0-9]+"
|
||||
# One line of todo.md's ## Renamed section: the release it renamed and the one it became.
|
||||
RENAME = re.compile(rf"- ({RELEASE}) renamed to ({RELEASE})")
|
||||
# Each goal an item names, in its order, with how far the item moves it; None in OLD_SHAPE, whose Goals cell names no move.
|
||||
Moves = tuple[tuple[str, int | None], ...]
|
||||
|
||||
@@ -55,11 +57,11 @@ class Shape:
|
||||
|
||||
|
||||
def parse_moves(id_: str, cell: str) -> Moves | Failure:
|
||||
"""A Moves cell: empty, or each goal the item moves, named once, and how far."""
|
||||
matches = [re.fullmatch(r"([0-9]+(?:\.[0-9]+)*) by ([0-9]+)", move) for move in cell.split(", ")] if cell else []
|
||||
"""A Moves cell: empty, or each goal the item moves, named once, and how far. rank_todo.py's cited_goals_failure holds the rules that need README.md."""
|
||||
matches = [re.fullmatch(rf"([0-9]+(?:\.[0-9]+)*|{CODE_HEALTH}) by ([0-9]+)", move) for move in cell.split(", ")] if cell else []
|
||||
moves = tuple((match.group(1), int(match.group(2))) for match in matches if match)
|
||||
if len(moves) < len(matches) or any(not 1 <= by <= TOP_SCORE for _, by in moves):
|
||||
return Failure(f"item {id_}'s {MOVES} {cell!r} is not empty or goals such as `1.1 by 8, 1.2 by 5`, each moved by a whole number from 1 to {TOP_SCORE}")
|
||||
return Failure(f"item {id_}'s {MOVES} {cell!r} is not empty or goals such as `1.1 by 8, {CODE_HEALTH} by 5`, each moved by a whole number from 1 to {TOP_SCORE}")
|
||||
goals = [goal for goal, _ in moves]
|
||||
if repeated := [goal for goal in goals if goals.count(goal) > 1]:
|
||||
return Failure(f"item {id_} cites goal {repeated[0]} twice; name each goal once")
|
||||
@@ -169,7 +171,7 @@ def waiting(found: list[Item], done: set[int]) -> set[int]:
|
||||
|
||||
|
||||
def next_item(found: list[Item]) -> Item | None:
|
||||
"""The earliest release's first row that does not wait, as waiting says, in the table's order; chunk_item takes it as the next chunk's first item where its release is the next."""
|
||||
"""The earliest release's first row that does not wait, as waiting says, in the table's order; chunk_pick.chunk_item takes it as the next chunk's first item where its release is the next."""
|
||||
if not found:
|
||||
return None
|
||||
release = min(item.release for item in found)
|
||||
@@ -177,59 +179,18 @@ def next_item(found: list[Item]) -> Item | None:
|
||||
return next((item for item in found if item.release == release and item.id not in waits), None)
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class LastCut:
|
||||
"""What the default branch holds about its last release, which chunk_item weighs the plan against."""
|
||||
# The newest v* tag, None where the branch has none.
|
||||
tag: str | None | Failure
|
||||
# CHANGELOG.md's text, empty where the branch holds none.
|
||||
changelog: str | Failure
|
||||
# How many commits follow the tag, or make up the branch where it has none.
|
||||
commits: int | Failure
|
||||
# todo.md's text at the tag and at each later commit that changed it; empty without a tag.
|
||||
todos_since: list[str] | Failure
|
||||
|
||||
|
||||
def unreleased_entries(changelog: str) -> int | None:
|
||||
"""How many top-level `- ` entries CHANGELOG.md holds under ## Unreleased; None without that section."""
|
||||
found = sections(changelog).get("Unreleased")
|
||||
return None if found is None else sum(line.startswith("- ") for line in found[0].splitlines())
|
||||
|
||||
|
||||
def landed(cut: LastCut) -> int | Failure:
|
||||
"""How much work has landed since the last cut: the entries under ## Unreleased, or the commits since the tag where CHANGELOG.md has no such section, as `~/.claude/CLAUDE.md` → "Working loop" counts unreleased changes."""
|
||||
entries = unreleased_entries(cut.changelog) if isinstance(cut.changelog, str) else None
|
||||
return cut.commits if entries is None else entries
|
||||
|
||||
|
||||
def named_releases(todos: list[str] | Failure) -> set[tuple[int, int, int]] | Failure:
|
||||
"""Each release the todo.md texts file items under; a text that does not parse names none."""
|
||||
if isinstance(todos, Failure):
|
||||
return todos
|
||||
return {item.release for parsed in map(items, todos) if isinstance(parsed, list) for item in parsed}
|
||||
|
||||
|
||||
def standing(tag: str | None | Failure, landed: int | Failure, earliest: tuple[int, int, int] | None, named: set[tuple[int, int, int]] | Failure) -> Standing:
|
||||
"""How the plan's earliest release, None where the plan holds no item, stands to the newest v* tag, as Standing says. named holds each release todo.md named since that tag, and landed the work landed since it."""
|
||||
cut = re.fullmatch(r"v([0-9]+)\.([0-9]+)\.([0-9]+)", tag) if isinstance(tag, str) else None
|
||||
if cut is None:
|
||||
return "next"
|
||||
version = tuple(int(part) for part in cut.groups())
|
||||
if earliest is not None and earliest <= version:
|
||||
return "cut"
|
||||
if isinstance(named, Failure):
|
||||
return "unknown"
|
||||
if earliest is not None and earliest == min(release for release in named | {earliest} if release > version):
|
||||
return "next"
|
||||
if isinstance(landed, Failure):
|
||||
return "unknown"
|
||||
return "finished" if landed else "unplanned"
|
||||
|
||||
|
||||
def chunk_item(found: list[Item], cut: LastCut) -> tuple[Standing, Item | None]:
|
||||
"""The item the next chunk takes first, next_item's pick, where standing finds the plan's earliest release the next; else None. Routing and chunk-preflight both pick with it, so they name one item. It returns the standing too, so a caller can say why there is none."""
|
||||
stands = standing(cut.tag, landed(cut), min((item.release for item in found), default=None), named_releases(cut.todos_since))
|
||||
return stands, next_item(found) if stands == "next" else None
|
||||
def renames(todo: str) -> set[tuple[int, int, int]] | Failure:
|
||||
"""Each release todo.md's ## Renamed section says was renamed, as `- 0.2.1 renamed to 0.3.0`, so never finished; the tools read only the old release. `docs/decisions.md` → `todo.md: one table …` gives the rule and the spelling's pick."""
|
||||
marked: set[tuple[int, int, int]] = set()
|
||||
for body in sections(todo).get("Renamed", []):
|
||||
for line in body.splitlines():
|
||||
rename = RENAME.fullmatch(line.strip())
|
||||
if rename is None:
|
||||
return Failure(f"todo.md's ## Renamed section holds {line.strip()!r}, not a line such as `- 0.2.1 renamed to 0.3.0`")
|
||||
if rename.group(1) == rename.group(2):
|
||||
return Failure(f"todo.md's ## Renamed section renames {rename.group(1)} to itself; name the release it became")
|
||||
marked.add(release_of(rename.group(1)))
|
||||
return marked
|
||||
|
||||
|
||||
def bundle_candidates(found: list[Item], first: Item) -> list[Item]:
|
||||
@@ -298,8 +259,18 @@ def parse_row(row: str, table: Table) -> Item | Failure:
|
||||
moves = shape.read_goals(named["ID"], named[shape.goals_column])
|
||||
if isinstance(moves, Failure):
|
||||
return moves
|
||||
major, minor, patch = (int(part) for part in named["Release"].split("."))
|
||||
return Item(int(named["ID"]), (major, minor, patch), named["Exempt"], named["Item"], scores, moves, blocked_by)
|
||||
return Item(int(named["ID"]), release_of(named["Release"]), named["Exempt"], named["Item"], scores, moves, blocked_by)
|
||||
|
||||
|
||||
def release_of(version: str) -> tuple[int, int, int]:
|
||||
"""The release a RELEASE-shaped version names."""
|
||||
major, minor, patch = (int(part) for part in version.split("."))
|
||||
return major, minor, patch
|
||||
|
||||
|
||||
def version(release: tuple[int, int, int]) -> str:
|
||||
"""The version a release names, such as 0.2.1: release_of's inverse."""
|
||||
return ".".join(map(str, release))
|
||||
|
||||
|
||||
def check_cells(row: str, named: dict[str, str]) -> Failure | None:
|
||||
@@ -307,7 +278,7 @@ def check_cells(row: str, named: dict[str, str]) -> Failure | None:
|
||||
id_, release, exempt, tagline = named["ID"], named["Release"], named["Exempt"], named["Item"]
|
||||
if not re.fullmatch(r"[0-9]+", id_) or int(id_) < 1:
|
||||
return Failure(f"the ID {id_!r} is not a positive whole number: {row}")
|
||||
if not re.fullmatch(r"[0-9]+\.[0-9]+\.[0-9]+", release):
|
||||
if not re.fullmatch(RELEASE, release):
|
||||
return Failure(f"item {id_}'s release {release!r} is not a semver version")
|
||||
if exempt not in EXEMPTIONS:
|
||||
return Failure(f"item {id_}'s Exempt {exempt!r} is not empty or one of {', '.join(EXEMPTIONS[1:])}")
|
||||
|
||||
@@ -16,30 +16,38 @@ FINISHED_AT = re.compile(rf"^({STAMPED}) {re.escape(FINISHED)}$", re.MULTILINE)
|
||||
UNFINISHED_AT = re.compile(rf"^{STAMPED} {re.escape(UNFINISHED)}$", re.MULTILINE)
|
||||
# A verdict closes each cycle the judge ruled on; an interrupt or a stop closes none.
|
||||
VERDICT_AT = re.compile(rf"^{STAMPED} (?:{re.escape(FINISHED)}|{re.escape(UNFINISHED)})$", re.MULTILINE)
|
||||
# An outcome opens with its UTC stamp; a verdict that closes a cycle, a stop, or a step up ends with the worker line.
|
||||
# An outcome opens with its UTC stamp; a verdict that closes a cycle, an interrupt, a quoted answer, a stop, or a step up ends with the worker line.
|
||||
OUTCOME_AT = re.compile(rf"^({STAMPED}) ", re.MULTILINE)
|
||||
NAMES_A_WORKER = ("Verdict: finished\n", "Verdict: unfinished\n", "Stopped: ", "Stepped up\n")
|
||||
NAMES_A_WORKER = (*(f"{verdict}\n" for verdict in (FINISHED, UNFINISHED, INTERRUPTED, ANSWERED)), "Stopped: ", "Stepped up\n")
|
||||
WORKER = "Worker: "
|
||||
# The rung that judged a verdict.
|
||||
JUDGE = "Judge: "
|
||||
|
||||
|
||||
def escalation_block(escalation: str) -> str:
|
||||
return f"Escalation:\n{quoted(escalation)}\n\n" if escalation else ""
|
||||
|
||||
|
||||
def finished(worker: str, evidence: str, judge: str) -> str:
|
||||
return f"{FINISHED}\n\nEvidence:\n{quoted(evidence)}\n\n{JUDGE}{judge}\n{WORKER}{worker}"
|
||||
|
||||
|
||||
def unfinished(worker: str, evidence: str, judge: str, escalation: str) -> str:
|
||||
"""escalation is the judge's quote showing that the worker's cited escalation trigger fired; empty for none."""
|
||||
escalated = f"Escalation:\n{quoted(escalation)}\n\n" if escalation else ""
|
||||
escalated = escalation_block(escalation)
|
||||
return f"{UNFINISHED}\n\nEvidence:\n{quoted(evidence)}\n\n{escalated}{JUDGE}{judge}\n{WORKER}{worker}"
|
||||
|
||||
|
||||
def interrupted(question: str, evidence: str, judge: str) -> str:
|
||||
return f"{INTERRUPTED}\n\n{question}\n\nEvidence:\n{quoted(evidence)}\n\n{JUDGE}{judge}"
|
||||
def interrupted(question: str, evidence: str, judge: str, escalation: str, worker: str) -> str:
|
||||
"""escalation is the judge's quote showing that the worker's cited escalation trigger fired; empty for none. worker is the rung the worker ran on until the interrupt."""
|
||||
escalated = escalation_block(escalation)
|
||||
return f"{INTERRUPTED}\n\n{question}\n\nEvidence:\n{quoted(evidence)}\n\n{escalated}{JUDGE}{judge}\n{WORKER}{worker}"
|
||||
|
||||
|
||||
def answered(question: str, sources: str, answer: str, evidence: str, judge: str) -> str:
|
||||
return f"{ANSWERED}\n\n{question}\n\n{sources} says:\n{quoted(answer)}\n\nEvidence:\n{quoted(evidence)}\n\n{JUDGE}{judge}"
|
||||
def answered(question: str, sources: str, answer: str, evidence: str, escalation: str, judge: str, worker: str) -> str:
|
||||
"""escalation and worker are as on interrupted."""
|
||||
escalated = escalation_block(escalation)
|
||||
return f"{ANSWERED}\n\n{question}\n\n{sources} says:\n{quoted(answer)}\n\nEvidence:\n{quoted(evidence)}\n\n{escalated}{JUDGE}{judge}\n{WORKER}{worker}"
|
||||
|
||||
|
||||
def rejected(why: str, reply: str, judge: str) -> str:
|
||||
|
||||
@@ -47,23 +47,33 @@ class Outcomes(unittest.TestCase):
|
||||
def test_the_archive_stamps_what_it_reads_back(self):
|
||||
self.assertRegex(f"{utc(NOW)} {outcomes.finished('m', 'merged', 'j')}", outcomes.FINISHED_AT)
|
||||
|
||||
def test_reads_back_the_worker_of_each_outcome_that_closes_a_cycle(self):
|
||||
def test_reads_back_the_worker_of_each_outcome_that_names_one(self):
|
||||
kept = "Task: Do it.\n\n" + "\n".join(f"{utc(NOW + offset)} {outcome}\n" for offset, outcome in enumerate([
|
||||
outcomes.unfinished("w1", "Worker: not this", "j", ""),
|
||||
outcomes.interrupted("Which one?\nWorker: nor this", "e", "j"),
|
||||
outcomes.interrupted("Which one?\nWorker: nor this", "e", "j", "", "w1b"),
|
||||
outcomes.stopped("w2", "the judge failed\nthree times"),
|
||||
outcomes.finished("w3", "merged", "j"),
|
||||
]))
|
||||
self.assertEqual(outcomes.workers(kept), [(utc(NOW), "w1"), (utc(NOW + 2), "w2"), (utc(NOW + 3), "w3")])
|
||||
self.assertEqual(outcomes.workers(kept), [(utc(NOW), "w1"), (utc(NOW + 1), "w1b"), (utc(NOW + 2), "w2"), (utc(NOW + 3), "w3")])
|
||||
|
||||
def test_archives_the_escalation_an_unfinished_verdict_quotes_beside_its_evidence(self):
|
||||
self.assertEqual(outcomes.unfinished("w", "e", "j", "round 2: 🔴"), "Verdict: unfinished\n\nEvidence:\n> e\n\nEscalation:\n> round 2: 🔴\n\nJudge: j\nWorker: w")
|
||||
self.assertEqual(outcomes.unfinished("w", "e", "j", ""), "Verdict: unfinished\n\nEvidence:\n> e\n\nJudge: j\nWorker: w")
|
||||
|
||||
def test_archives_the_escalation_an_interrupt_quotes_beside_its_evidence(self):
|
||||
self.assertEqual(outcomes.interrupted("q?", "e", "j", "round 2: 🔴", "w"), "Verdict: interrupt\n\nq?\n\nEvidence:\n> e\n\nEscalation:\n> round 2: 🔴\n\nJudge: j\nWorker: w")
|
||||
self.assertEqual(outcomes.interrupted("q?", "e", "j", "", "w"), "Verdict: interrupt\n\nq?\n\nEvidence:\n> e\n\nJudge: j\nWorker: w")
|
||||
|
||||
def test_archives_the_escalation_and_the_worker_a_quoted_answer_names(self):
|
||||
self.assertEqual(outcomes.answered("q?", "AGENTS.md", "A.", "e", "round 2: 🔴", "j", "w"), "Verdict: quoted answer\n\nq?\n\nAGENTS.md says:\n> A.\n\nEvidence:\n> e\n\nEscalation:\n> round 2: 🔴\n\nJudge: j\nWorker: w")
|
||||
self.assertEqual(outcomes.answered("q?", "AGENTS.md", "A.", "e", "", "j", "w"), "Verdict: quoted answer\n\nq?\n\nAGENTS.md says:\n> A.\n\nEvidence:\n> e\n\nJudge: j\nWorker: w")
|
||||
self.assertEqual(outcomes.workers(f"{utc(NOW)} {outcomes.answered('q?', 'AGENTS.md', 'A.', 'e', '', 'j', 'w')}\n"), [(utc(NOW), "w")])
|
||||
|
||||
def test_reads_no_worker_from_an_outcome_written_before_the_worker_line(self):
|
||||
kept = f"Task: Do it.\n\n{utc(NOW)} Stopped: Ctrl-C\n\n{utc(NOW)} Verdict: unfinished\n\nEvidence:\n> Worker: no\n"
|
||||
self.assertEqual(outcomes.workers(kept), [])
|
||||
self.assertEqual(outcomes.workers(f"{utc(NOW)} {outcomes.stepped_up('w')}\n"), [(utc(NOW), "w")])
|
||||
self.assertEqual(outcomes.workers(f"{utc(NOW)} Verdict: quoted answer\n\nq?\n\nAGENTS.md says:\n> A.\n\nEvidence:\n> e\n\nJudge: j\n"), [])
|
||||
|
||||
def test_takes_the_outcome_written_last_within_one_second(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
|
||||
@@ -2119,3 +2119,319 @@ Inherited architect, decided by:
|
||||
- Locality: `skills/larv-review/SKILL.md:118` "Second run" and `bin/larv_review/plan.py:22` `scoring_run_due`: the second run keys on the exact wording of a reason string, with no test or import linking the two
|
||||
- Locality: `bin/larv_review/agreement.py:10` `overall_cells`: the last cell means overall only through `table_rows`' first-row-wins rule and the pre-#232 `Vote` table, described at `comprehension_history.py:82`
|
||||
- Locality: `bin/larv_review/main.py:81` `__doc__`: the help hard-codes 10 pairs where `MIN_PAIRS` holds the number
|
||||
|
||||
## 2026-10-17T22:03:15Z, PR #308 at 023380f, against 59344de
|
||||
|
||||
Ruling: worse
|
||||
|
||||
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|
||||
|---|---|---|---|---|---|
|
||||
| Mid A | same | worse | same | same | worse |
|
||||
| Inherited architect | same | worse | worse | same | worse |
|
||||
|
||||
Mid A, decided by:
|
||||
|
||||
- Locality, Overall: `bin/loop_claude/cycle/run.py:43` `Cycle.stepped_from` and `escalated`: the cycle carries route state outside its state machine, which `escalated` rewrites before every transition, keeping `stepped_from` only through `HumanTyped`, so `ask`, `keep_answer` and `worker_start` trust the event before them
|
||||
- Locality: `bin/loop_claude/cycle/run.py:156` `unspent`: whether a verdict keeps its escalation depends on `escalation_spent`, set by an earlier ruling of the cycle; escalation now spans `escalated`, `unspent` and `loop/main.py`'s step from `concluded.route`
|
||||
- Locality: `bin/loop_claude/cycle/prompts.py:132` `typed` / `typed_answer`: the typed answer is written into a prompt and parsed back out of the transcript, and `render` takes a callback the generic `claude_code` module cannot make sense of alone
|
||||
|
||||
Inherited architect, decided by:
|
||||
|
||||
- Locality, Overall: `bin/loop_claude/cycle/run.py:71` `escalated`: the route now also changes inside a cycle, through two fields kept out of the state machine; "why did the worker resume on this rung" spans `escalated`, `unspent`, `routing.stepped_by_ruling`, `after_verdict` and two archive-the-step sites
|
||||
- Locality: `bin/loop_claude/cycle/prompts.py:138` `TYPED_HERE` / `typed_answer`: the resume prompt doubles as a data channel back to the judge, resting on `typed`'s layout, the blank-line partition and `put_question` returning one line, in three modules linked only by a comment
|
||||
- Shape: `bin/loop_claude/routing.py:80` `stepped_from`: returns the stepped route, while `Cycle.stepped_from` holds the route before the step; `escalated` is likewise a function, a bool parameter and a local string
|
||||
- Shape: `bin/loop_claude/cycle/judge.py:95` `Interrupt`: shares `escalation` and `bundled` with `Unfinished` in the opposite positional order, and both are built positionally
|
||||
|
||||
## 2026-10-18T07:20:58Z, PR #310 at 1d8dd33, against fdd48bb
|
||||
|
||||
Ruling: same
|
||||
|
||||
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|
||||
|---|---|---|---|---|---|
|
||||
| Mid A | better | same | same | same | same |
|
||||
| Inherited architect | same | same | same | same | same |
|
||||
|
||||
Mid A, decided by:
|
||||
|
||||
- Navigation: `bin/review_folder.py:5` `REPORTS`: the review folder's path is one constant in a module named for it, imported by `make_review_folder`, `report_breaches` and `reviewed_in`, so where reports go and who enforces it is found from one name
|
||||
|
||||
Inherited architect, decided by:
|
||||
|
||||
- Locality: `bin/todo_table.py:216` `renamed`: one function now holds the renamed-never-finished rule that `named_releases` and `plan.py`'s `emptied` both call, where a comment kept two files in step by hand
|
||||
- Locality: `bin/todo_table.py:205` `named_releases`: now a fold whose answer depends on the texts' order, fixed far away by `--reverse` in `git_repo.py`'s `todos_since` and enforced by nothing
|
||||
- Locality, Self-sufficiency: `bin/stability_replay/main.py:183` `reviewed_in`: three chained replaces that must run in a fixed order, and the copy placed under REPORTS for a reason that lives only in `reviewer_report.py`
|
||||
- Shape: `bin/stability_replay/main.py:175` `reviewed_in`: seven positional parameters with `clone` and `reports` adjacent strings, and REPORTS meaning the root, its realpath and one round's copy in three files
|
||||
- Locality: `bin/review_folder.py:5` `REPORTS`: the path is spelled again in `settings.json`, SKILL.md, CLAUDE.md and larv-review's help, and only the Python reads the constant
|
||||
|
||||
## 2026-10-18T07:59:13Z, PR #312 at 6694d54, against e074b8b
|
||||
|
||||
Ruling: better
|
||||
|
||||
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|
||||
|---|---|---|---|---|---|
|
||||
| Mid A | same (voted better, no place naming Navigation) | better | same | same | better |
|
||||
| Inherited architect | better | better | same | better | better |
|
||||
|
||||
Mid A, decided by:
|
||||
|
||||
- Locality, Overall: `bin/todo_table.py:223` `renames`: one explicit `## Renamed` line in one text replaces a rename inferred from two plan snapshots
|
||||
- Locality: `bin/todo_table.py:209` `named_releases`: an unparseable mark fails the result only in the newest text, an order dependence to keep in mind
|
||||
|
||||
Inherited architect, decided by:
|
||||
|
||||
- Locality, Overall: `bin/todo_table.py:223` `renames`: the answer sits in the file read, where `renamed` replayed the plan's history
|
||||
- Locality: `bin/larv_review/plan.py:27` `emptied`: renamed is a parameter, no hidden second derivation
|
||||
- Navigation, Self-sufficiency: `bin/chunk_preflight/gathered.py:100` `planned`: the stop names the fix and where it goes
|
||||
|
||||
## 2026-10-18T09:10:02Z, PR #316 at 3eb3217, against 6e0fda4
|
||||
|
||||
Ruling: better
|
||||
|
||||
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|
||||
|---|---|---|---|---|---|
|
||||
| Mid A | better | better | better | same | better |
|
||||
| Inherited architect | better | better | better | same | better |
|
||||
|
||||
Mid A, decided by:
|
||||
|
||||
- Navigation, Locality, Shape: `bin/chunk_pick.py:92` `chunk_item`: returns one of five dataclasses, each carrying its release, where 6e0fda4's `(Standing, Item | None)` tuple made `planned` recompute the earliest release; the pick lives in one module named for it
|
||||
- Shape, Navigation: `bin/git_repo.py:1` `git_repo`: the git wrapper no longer imports the plan model or builds todo.md objects; `default_plan` and `todos_since` sit beside the logic that reads them
|
||||
- Shape, Locality: `bin/chunk_pick.py:97` `standing`: names `first_named` and states the rule plainly, where 6e0fda4's `min(... named | {earliest} ...)` had to be decoded
|
||||
- Shape: `bin/chunk_preflight/choices.py:1` `choices`: the pure decisions left `gathered.py`, so each module's name tells what it holds
|
||||
- Locality, Navigation: `bin/todo_table.py:269` `version`: one release formatter beside `release_of`, where 6e0fda4 had three
|
||||
- Shape: `bin/chunk_pick.py:118` `unreleased_changes`: with `committed_since_release`, the names say what is counted, where "landed" hid it
|
||||
|
||||
Inherited architect, decided by:
|
||||
|
||||
- Navigation, Locality: `bin/chunk_pick.py:97` `standing`: "preflight says a release is ready to cut and it isn't" now lands in one module, where 6e0fda4 spread it over a table parser, a git wrapper importing it, and the preflight's wording
|
||||
- Locality, Shape: `bin/chunk_preflight/choices.py:24` `planned`: each pick variant carries its release, so the messages read straight off it, where 6e0fda4 paired a recomputed `earliest` with a string by hand
|
||||
- Shape: `bin/chunk_preflight/gathered.py:1` `gathered`: data only, with the choices in `choices.py`, though `facts.py` imports `PULLS_LIST` from the decision module
|
||||
- Shape: `bin/chunk_pick.py:118` `unreleased_changes`: with `committed_since_release` and one `version`, the names say what they count
|
||||
|
||||
## 2026-10-18T12:16:18Z, PR #321 at 862137b, against 0462980
|
||||
|
||||
Ruling: same
|
||||
|
||||
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|
||||
|---|---|---|---|---|---|
|
||||
| Mid A | same | worse | better | better | same |
|
||||
| Inherited architect | same | worse | better | better | better |
|
||||
| Maintainability senior | same | better | better | better | better |
|
||||
| Junior A | same | worse | same | better | same |
|
||||
|
||||
Mid A, decided by:
|
||||
|
||||
- Locality: `bin/loop_claude/cycle/judge.py:153` `escalation_mark`: "one trigger buys one step" was one flag and one function in `run.py`'s `unspent`; now a mark across cycles read through `Route.escalated_at`, `entries_read` stamped late by `judge_once`, None versus 0, `STEP_LINE`, `Grounds.since_step` and the routing steps, over three modules
|
||||
- Locality: `bin/loop_claude/cycle/judge.py:216` `quotes_checked`: turns a `QuotedAnswer` into an `Interrupt` without `entries_read`, correct only because `judge_once` stamps after `run_judge`, which nothing here says
|
||||
- Locality: `bin/model_routing/route.py:12` `ROUTED`: the mark survives only by round-tripping through `Route.__str__`, so rewording one fragment resets it to 0 at a distance
|
||||
- Shape, Self-sufficiency: `bin/model_routing/route.py:13` `ROUTED`: a verbose regex with each group naming the `__str__` fragment it reads, in place of one dense line
|
||||
- Shape: `bin/loop_claude/cycle/judge.py:143` `Grounds`: one named tuple whose fields document their own checks, in place of loose strings and a docstring list
|
||||
- Shape: `bin/loop_claude/routing.py:84` `one_rung_up`: no longer shares its name with `Cycle.stepped_from`, which means the route before the step
|
||||
- Self-sufficiency: `bin/loop_claude/cycle/prompts.py:87` `escalation`: the docstring shows the full sentences it renders for a concrete rung
|
||||
|
||||
Inherited architect, decided by:
|
||||
|
||||
- Locality: `bin/loop_claude/cycle/judge.py:185` `judge_once`: "one trigger buys one step" runs through five units in four modules and outlives the run via the archive line, with three "nothing" values for one idea: 0 for no mark, None for no escalation, None for never stamped
|
||||
- Locality: `bin/loop_claude/cycle/judge.py:219` `quotes_checked`: builds an `Interrupt` without `entries_read`, safe only because the stamp comes later; swapped, the escalation is silently dropped
|
||||
- Shape, Self-sufficiency: `bin/loop_claude/cycle/judge.py:143` `Grounds`: each checked text is a named field with its rule and penalty beside it, so the judge-rejection path reads easier
|
||||
- Shape: `bin/loop_claude/routing.py:84` `one_rung_up`: the name says what it does, and its `escalated_at` parameter shows it moves the mark, where `stepped_from` clashed with `Cycle.stepped_from`
|
||||
- Locality, Shape: `bin/loop_claude/cycle/run.py:69` `escalated`: `Cycle` lost the cycle-scoped `escalation_spent` and `rule` no longer filters through `unspent`, so `run.py` reads on its own
|
||||
- Self-sufficiency: `bin/model_routing/route.py:13` `ROUTED`: each group labelled by the fragment it reads, with a warning that a reword resets the mark
|
||||
- Self-sufficiency: `bin/loop_claude/cycle/prompts.py:88` `escalation`: the docstring shows the rendered text for one concrete route
|
||||
- Self-sufficiency: `bin/loop_claude/cycle/judge.py:61` `STEP_LINE`: defined beside the slicing that inserts it, with the entries-only-grow assumption written on `Route.escalated_at`
|
||||
|
||||
Maintainability senior, decided by:
|
||||
|
||||
- Locality: `bin/model_routing/route.py:66` `Route.escalated_at`: one persisted mark that holds across cycles replaces a cycle-scoped flag and a filter in `rule` that rewrote the judge's verdict outside the judge
|
||||
- Locality: `bin/loop_claude/routing.py:76` `stepped_by_ruling`: "no escalation, no step" now lives in routing, so `run.py`'s `escalated` reads straighter; offset in part by `judge_once` stamping `entries_read` after `quotes_checked` rebuilds an `Interrupt`, an order that matters
|
||||
- Self-sufficiency: `bin/loop_claude/cycle/judge.py:143` `Grounds`: each checked text a named field with its own comment, in place of two positional strings and a docstring list
|
||||
- Self-sufficiency: `bin/model_routing/route.py:13` `ROUTED`: each group commented with the `Route.__str__` fragment it reads back
|
||||
- Self-sufficiency: `bin/loop_claude/cycle/prompts.py:87` `escalation`: the docstring quotes the sentences it produces, and the body joins whole parts in place of space-led fragments
|
||||
- Shape: `bin/loop_claude/routing.py:84` `one_rung_up`: renamed from `stepped_from`, which meant the opposite of `Cycle.stepped_from` beside it
|
||||
|
||||
Junior A, decided by:
|
||||
|
||||
- Locality: `bin/model_routing/route.py:66` `Route.escalated_at`: "one trigger buys one step" moved from one file's cycle-local flag and `unspent` filter to a mark threaded through six files
|
||||
- Locality: `bin/loop_claude/cycle/judge.py:189` `judge_once`: stamps `entries_read` after the run, an unstamped None silently steps nothing, and "none" is 0 on the route but None in `stepped` and `stepped_by_ruling`
|
||||
- Self-sufficiency: `bin/model_routing/route.py:13` `ROUTED`: a verbose pattern whose groups name the fragments they read, in place of one dense line
|
||||
- Self-sufficiency, Shape: `bin/loop_claude/cycle/judge.py:143` `Grounds`: each field documents what must quote it and what a misquote does, though `judge` and `judge_once` grow to nine positional parameters
|
||||
- Shape: `bin/loop_claude/routing.py:84` `one_rung_up`: removes the name it shared with `Cycle.stepped_from`, which meant the opposite
|
||||
- Self-sufficiency: `bin/loop_claude/cycle/prompts.py:87` `escalation`: a worked example of the exact sentences, as its neighbours already had
|
||||
|
||||
## 2026-10-18T16:57:38Z, PR #322 at 49e86fd, against 2911d3f
|
||||
|
||||
Ruling: same
|
||||
|
||||
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|
||||
|---|---|---|---|---|---|
|
||||
| Mid A | better | same | better | same | better |
|
||||
| Inherited architect | same | worse | better | same | same |
|
||||
| Maintainability senior | same | better | worse | same | same |
|
||||
| Junior A | better | better | same | same | better |
|
||||
|
||||
Mid A, decided by:
|
||||
|
||||
- Navigation, Shape: `bin/review_replay/main.py:1` `review_replay`: the tool takes any pass and its name says so, with `REVIEWERS` listing the passes and the usage printing them, where the old name pointed at stability alone
|
||||
- Shape: `bin/review_replay/main.py:208` `reviewed_in`: copy, rewrite, clone and run are each a named step with a docstring, where `bin/stability_replay/main.py:175` did all four in one body; `codes_found` takes the left-out loop out of `main`
|
||||
- Locality: `bin/rule_hook/reviewer_rung.py:18` `reviewer_breaches`: asks `review_rungs(...)[kind]` directly, without the older loop-claude fallback or the filesystem glob
|
||||
- Locality: `bin/loop_claude/cycle/prompts.py:72` `taken_in_launches`: compares whole `review_rungs` dicts, right only because of a condition inside `ladder.review_rungs` that a comment states
|
||||
- Locality: `bin/model_routing/ladder.py:71` `REPLAYED`: an empty table that `review_rungs`, `lowered`, `shared_launches` and `reruns` all branch on, so a reader follows a path no data drives
|
||||
- Shape: `bin/rule_hook/reviewer_report.py:10` `REVIEWERS`: a frozenset of agent files, while `ladder.py`'s `REVIEWERS` is a dict from pass to agent; one name for two shapes
|
||||
- Shape: `bin/loop_claude/cycle/prompts.py:43` `review_launches`: fan-out grows by four units and "each reviewer" becomes a magic key, but stays bounded with docstring examples
|
||||
|
||||
Inherited architect, decided by:
|
||||
|
||||
- Locality: `bin/loop_claude/cycle/prompts.py:43` `review_launches`: one launch sentence now needs `REVIEWS`' per-pass rows, `shared_launches` skipping them for an `"each reviewer"` key, and `lowered` putting them back, where the base was one loop over three rows
|
||||
- Locality: `bin/loop_claude/cycle/prompts.py:78` `taken_in_launches`: compares the whole `review_rungs` dict, correct only by a rule enforced in `ladder.review_rungs`
|
||||
- Locality: `bin/model_routing/ladder.py:71` `REPLAYED`: a hand-edited table, empty today, that overrides a pass's rung below the worker's under a combined E + I and worker condition; a second source of truth
|
||||
- Shape: `bin/review_replay/main.py:208` `reviewed_in`: split into `copy_reports`, `redirected` and `clone_reviewed`, each with a docstring; `codes_found` and `pass_and_model` take inline loops and lambdas out of `main`
|
||||
- Shape: `bin/rung_replay/command.py:16` `arguments_or_exit`: argument parsing is no longer hard-wired to one model, and `down_from(top, floor)` makes judge-replay's floor show at its call site
|
||||
- Shape: `bin/rule_hook/reviewer_report.py:10` `REVIEWERS`: shares its name with `ladder.py`'s hand-kept dict of a different shape
|
||||
|
||||
Maintainability senior, decided by:
|
||||
|
||||
- Shape: `bin/loop_claude/cycle/prompts.py:14` `REVIEWS`: six rows built from `REVIEWERS`, a separate `"each reviewer"` entry, a `kind not in REVIEWERS` filter and a `lowered` list re-joined in two places, all serving an empty `REPLAYED`
|
||||
- Shape: `bin/model_routing/ladder.py:69` `REVIEWERS`: two modules on one rule-hook call path each hold a `REVIEWERS` of a different type and meaning, where the base had one
|
||||
- Shape: `bin/model_routing/ladder.py:104` `review_rungs`: fans out to every pass then overlays `REPLAYED` under a condition only a dense docstring paragraph explains; `taken_in_launches` compares whole dicts
|
||||
- Locality: `bin/review_replay/main.py:208` `reviewed_in`: copy, rewrite and clone are named units, and the lambdas passed to `replayed` are named functions
|
||||
- Locality: `bin/rung_replay/command.py:35` `down_from`: takes the floor as an argument, so each caller states its own floor where the base hid judge-replay's policy in the shared helper
|
||||
|
||||
Junior A, decided by:
|
||||
|
||||
- Locality: `bin/rule_hook/reviewer_rung.py:24` `reviewer_breaches`: the required rung comes straight from `review_rungs`, the function the prompts use, where the base passed it through an environment variable and a fallback
|
||||
- Locality: `bin/rule_hook/reviewer_report.py:10` `REVIEWERS`: report confinement reads `agents/` itself, no longer importing its set from a module about rungs
|
||||
- Locality, Shape: `bin/review_replay/main.py:208` `reviewed_in`: four jobs and seven arguments became named units with docstrings, and `main`'s loop and lambdas are named
|
||||
- Navigation: `README.md:113`: the import map now names every reader of `model_routing/` and what `rung_replay/` holds, and the tool's name leads to it for any pass
|
||||
- Shape: `bin/loop_claude/cycle/prompts.py:57` `shared_launches`: five helpers, a made-up `"each reviewer"` key and paths an empty `REPLAYED` never runs, against `ReviewKind` naming the real passes
|
||||
|
||||
## 2026-10-18T19:59:26Z, PR #324 at c713910, against e6223f7
|
||||
|
||||
Ruling: same
|
||||
|
||||
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|
||||
|---|---|---|---|---|---|
|
||||
| Mid A | same | worse | better | same | same |
|
||||
| Inherited architect | same | worse | better | same | same |
|
||||
|
||||
Mid A, decided by:
|
||||
|
||||
- Locality: `bin/larv_review/record.py:56` `rerank`: recording a scoring run now also rewrites the checkout's todo.md and can exit 1 on items under the bar, so changing record-scoring needs rank_todo.rank_file's whole contract, where the base only appended to the history
|
||||
- Locality: `bin/rank_todo.py:338` `weigh`: an item's score now depends on docs/comprehension-history.md's newest scored commit and on a `## review opt-out:` title in docs/decisions.md, so scores and --check can change without anyone editing todo.md or README.md
|
||||
- Shape: `bin/rank_todo.py:315` `ranked_goals`: the base's inline three-way weights branch in read_scoring is a named weigh, with the code-health and void rules in ranked_goals, each easier alone, at the cost of three similar names weigh, goal_weights and parse_weights
|
||||
- Shape: `bin/rank_todo.py:623` `cited_goals_failure`: the base's parse_item mixed goal checks with writing R, and main inlined read, rank, write and print; each is now a unit with one purpose, and rank_file is reusable
|
||||
- Shape: `bin/comprehension_history.py:130` `newest_scored`: the base's index arithmetic in latest_places is a named helper latest_overall shares, and overall_cells and FLOOR moved to the module that parses the table they read
|
||||
|
||||
Inherited architect, decided by:
|
||||
|
||||
- Locality: `bin/rank_todo.py:196` `read_all`: ranking now also depends on the newest scoring run in docs/comprehension-history.md, so a passing --check can fail with nobody touching todo.md, and nothing at the call site shows that a history append moves code health's weight
|
||||
- Locality: `bin/larv_review/record.py:56` `rerank`: recording a scoring run now writes todo.md through rank_todo.rank_file, which prints its notes to stderr, and the message pointing at "the lines above" reads right only if rank_file printed first
|
||||
- Locality: `bin/rank_todo.py:106` `OPTED_OUT`: ranking now matches a docs/decisions.md title spelled in larv-review's SKILL.md → "Opt-out", so rewording that heading silently changes whether rank_todo refuses a plan
|
||||
- Locality: `bin/loop_claude/cycle/prompts.py:17` `AFTER_CODE_HEALTH`: the caveat that code health ranks first unless the README voids it is repeated in prose across about eight files, so one change to the shared goal edits all of them
|
||||
- Shape: `bin/comprehension_history.py:130` `newest_scored`: replaces the base's index juggling in latest_places with two truthfully named predicates serving latest_places and latest_overall
|
||||
- Shape: `bin/comprehension_history.py:145` `overall_cells`: FLOOR and overall_cells now have one home next to DIMENSIONS, and agreement's inline sort became the named scoring_runs
|
||||
- Shape: `bin/rank_todo.py:332` `weigh`: weigh, cited_goals_failure and rank_file are pulled out of read_scoring, parse_item and main, each doing one thing
|
||||
|
||||
## 2026-10-18T19:59:40Z, PR #324 at c713910
|
||||
|
||||
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|
||||
|---|---|---|---|---|---|
|
||||
| Junior A | 7 | 5.5 | 6 | 6.5 | 6 |
|
||||
| Mid A | 7 | 5.5 | 6 | 6.5 | 6 |
|
||||
| Maintainability senior | 7 | 6 | 6.5 | 6.5 | 6.5 |
|
||||
| Inherited architect | 7 | 6 | 6 | 7 | 6.5 |
|
||||
| Mean | 7.00 | 5.75 | 6.13 | 6.63 | 6.25 |
|
||||
|
||||
Junior A, hardest first:
|
||||
|
||||
- `bin/model_routing/route.py:66` `Route.escalated_at`: the escalation mark lives in six units across four files, with judge_once stamping entries_read, escalation_mark, stepped and judge_prompt's STEP_LINE held at once
|
||||
- `bin/loop_claude/loop/main.py:1` "loop-claude --help": a 164-line docstring is the loop's real spec, its routing paragraphs packing every rule into one block that routed and after_verdict need open
|
||||
- `bin/loop_claude/cycle/prompts.py:46` `review_launches`: prompt sentences assembled from rung comparisons over replay-lowered passes, the project's rung, the top rung and higher E + I
|
||||
- `bin/model_routing/route.py:13` `ROUTED`: stored state persisted as prose and parsed back by regexes in four places, so rewording one string silently changes routing
|
||||
- `bin/rank_todo.py:568` `score`: a 660-line file carrying two table shapes, with OLD_SHAPE forks in scoring, weights, goal parsing and column checks
|
||||
- `bin/chunk_pick.py:97` `standing`: five inputs become five outcomes, and chunk_pick.Finished shares its name with judge.Finished
|
||||
- `bin/review_replay/rounds.py:73` `reviewed_path`: rebuilds the code a past reviewer read from prompt text and author times, a heuristic
|
||||
- `bin/comprehension_history.py:159` `scored`: legacy formats from before PR #255 and #232 leak into the reading
|
||||
|
||||
Mid A, hardest first:
|
||||
|
||||
- `bin/loop_claude/routing.py:64` `stepped`: seven small functions, each defined through another, with six inputs held at once to predict one rung, and an import cycle shaping the signature
|
||||
- `bin/loop_claude/loop/main.py:259` `after_verdict`: the 164-line docstring is the only full map of routing, and after_verdict chains it all in one expression
|
||||
- `bin/loop_claude/cycle/run.py:45` `Cycle.stepped_from`: the route changes outside the state machine, cleared on every event but HumanTyped, so it outlives exactly one hop
|
||||
- `bin/loop_claude/cycle/judge.py:216` `quotes_checked`: three bodies of text to check quotes against, fuzzy matching, and three ways a failed check is handled
|
||||
- `bin/loop_claude/cycle/prompts.py:46` `review_launches`: fragments that each start with a space, so no whole prompt is visible without running it in your head
|
||||
- `bin/model_routing/route.py:13` `ROUTED`: a saved string format parsed back by a verbose regex that still accepts an older format
|
||||
- `bin/rank_todo.py:568` `score`: two table shapes share every path, the goal term W in one and V in the other
|
||||
- `bin/loop_claude/loop/reload.py:43` `decoded_as`: a generic decoder with two sentinels and a duck-typed fits hook defined on Route
|
||||
|
||||
Maintainability senior, hardest first:
|
||||
|
||||
- `bin/loop_claude/routing.py:64` `stepped`: four things held at once, the unfinished count, the taken-in L, the escalation cap from item_rung and the mark threaded through judge.py's escalation_mark, STEP_LINE and Grounds.since_step
|
||||
- `bin/model_routing/route.py:86` `Route.__str__`: the route written as English and parsed back by ROUTED and outcomes.workers, so a sentence's wording is a storage schema shared by four tools
|
||||
- `bin/loop_claude/loop/main.py:1` "loop-claude --help": a 160-line spec whose routing paragraph carries about 15 rules, re-describing what routing.py, ladder.py and retry.py enforce
|
||||
- `bin/loop_claude/cycle/prompts.py:46` `review_launches`: each sentence built conditionally with a leading-space convention, and taken_in_launches scanning every higher E + I
|
||||
- `bin/loop_claude/cycle/judge.py:216` `quotes_checked`: three grounds with three failure consequences, and the demotion to an interrupt loses release_ready
|
||||
- `bin/review_replay/rounds.py:73` `reviewed_path`: guesses which removed worktree a reviewer read, and redirected depends on the order of its replacements
|
||||
- `bin/comprehension_history.py:150` `scoring_runs`: near-synonyms scored and scoring_runs differ only on a ruling from before PR #255
|
||||
- `bin/rank_todo.py:332` `weigh`: the goal term is W or V by shape, so every scoring path asks which shape
|
||||
|
||||
Inherited architect, would restructure first:
|
||||
|
||||
- `bin/round_titles.py:4` `CAP`: no program loops the reviewers; the cap lives in SKILL.md prose and the code only counts rounds and prints a note
|
||||
- `bin/git_command.py:16` `commits`: parses git commit messages for rule-hook while git_repo.py, rule_hook/git.py, larv_review/git.py and Effects.git each run git, and git_repo bypasses Effects
|
||||
- `bin/transcript_archive/outcomes.py:39` `outcomes`: shares its name with score_outcomes/outcomes.py, which measures finished chunks instead
|
||||
- `bin/loop_claude/routing.py:64` `stepped`: routing has four homes, ladder.py, route.py, routing.py and routing_check with routing_figures, and prompts.py restates the ladder as sentences
|
||||
- `bin/rank_todo.py:196` `read_all`: a 658-line library as well as a tool, imported by rule_hook and larv_review, and now reading four documents, so a todo.md commit in any project depends on its comprehension history
|
||||
- `bin/loop_claude/cycle/judge.py:68` `Reply.bundled`: the taken-in L is also called bundled, and the project's rung is also called anchor
|
||||
- `bin/chunk_pick.py:97` `standing`: "next release" is computed two ways, here and in larv_review/plan.py's scoring_run_due, which may diverge after a rename
|
||||
|
||||
## 2026-10-18T19:59:40Z, PR #324 rerun at c713910
|
||||
|
||||
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|
||||
|---|---|---|---|---|---|
|
||||
| Junior A | 7 | 5.5 | 6.5 | 6 | 6 |
|
||||
| Mid A | 7.5 | 6 | 6.5 | 7 | 6.5 |
|
||||
| Maintainability senior | 7.5 | 6 | 6.5 | 6.5 | 6.5 |
|
||||
| Inherited architect | 6.5 | 6 | 5.5 | 6.5 | 6 |
|
||||
| Mean | 7.13 | 5.88 | 6.25 | 6.50 | 6.25 |
|
||||
|
||||
Junior A, hardest first:
|
||||
|
||||
- `bin/loop_claude/cycle/prompts.py:46` `review_launches`: the worker's English instructions built from how the worker's, the project's, the reviewers' and any replay-lowered rung relate, with ladder.review_rungs, REPLAYED and escalation_rungs open at once
|
||||
- `bin/loop_claude/routing.py:64` `stepped`: seven small functions defined through each other, bundled learned only from judge.Reply, and escalated_at both an argument and a Route field with different meanings
|
||||
- `bin/model_routing/route.py:13` `ROUTED`: routing state lives as English sentences in outcomes.md, read back by a regex, with the newest file by mtime deciding
|
||||
- `bin/loop_claude/loop/main.py:1` "loop-claude --help": about 160 lines and the only full account of routing, step-ups, the archive layout, reloads and the routing figures in one unbroken paragraph
|
||||
- `bin/loop_claude/cycle/run.py:69` `escalated`: stepped_from must survive a HumanTyped event and reset on every other, and archive_stepped writes one outcome or two depending on it
|
||||
- `bin/loop_claude/cycle/judge.py:216` `quotes_checked`: three quote checks follow different rules, and an escalation that fails is silently dropped
|
||||
- `bin/chunk_pick.py:97` `standing`: two separate notions of the next release and of work having landed, here and in larv_review/plan.py's scoring_run_due
|
||||
- `bin/rank_todo.py:332` `weigh`: old-shape support forks behaviour throughout a 659-line file
|
||||
|
||||
Mid A, hardest first:
|
||||
|
||||
- `bin/model_routing/route.py:66` `Route.escalated_at`: the escalation mark is one concept spread over five files, the entry count, the injected step line, a double quote check and the cap from item_rung held at once
|
||||
- `bin/loop_claude/cycle/run.py:69` `escalated`: state outside the state machine, cleared on every event but HumanTyped and read by ask, keep_answer and archive_stepped, depending on its order before transition
|
||||
- `bin/loop_claude/cycle/prompts.py:46` `review_launches`: routing policy and English wording interleaved, much of the branching serving an empty REPLAYED
|
||||
- `bin/loop_claude/loop/main.py:210` `run_loop`: the route passed as lazy thunks and re-derived every cycle, with an anchor-is-None branch in three places
|
||||
- `bin/model_routing/route.py:86` `Route.__str__`: the archive's human-readable lines are what reruns, the routing figures and the replays parse back
|
||||
- `bin/comprehension_history.py:150` `scoring_runs`: two near-identical predicates differing only for a ruling from before PR #255
|
||||
- `bin/rank_todo.py:568` `score`: every rule exists twice for the old table shape
|
||||
- `bin/review_replay/main.py:149` `code_of`: rebuilds which worktree a reviewer read by the first missing directory among its prompt's paths
|
||||
|
||||
Maintainability senior, hardest first:
|
||||
|
||||
- `bin/loop_claude/routing.py:64` `stepped`: seven one-line rung functions each defined by the others, four inputs held together, and an import cycle steering the interface
|
||||
- `bin/loop_claude/cycle/judge.py:153` `escalation_mark`: the escalation mark spread over route.py, judge.py's Grounds and judge_prompt and run.py's escalated, and no single place states that one trigger buys one step
|
||||
- `bin/loop_claude/cycle/prompts.py:46` `review_launches`: which conditional sentences reach which prompt means tracing fresh, routed_by, resumed, rungs_held and stepped_to
|
||||
- `bin/loop_claude/loop/main.py:1` "loop-claude --help": the routing paragraph is one block covering the ladder, the judge, replays, rule-hook's variables, step rules, archive lines and legacy R + C
|
||||
- `bin/model_routing/route.py:13` `ROUTED`: routing state survives restarts as English sentences parsed back by regex, a hidden contract across three packages
|
||||
- `bin/rank_todo.py:218` `rank`: every stage branches on the old table shape, about half a 660-line file read and then discarded
|
||||
- `bin/comprehension_history.py:130` `newest_scored`: four near-identical names over two concepts, split by a legacy case only the docstrings explain
|
||||
- `bin/chunk_pick.py:97` `standing`: five inputs, three of which may be Failure, produce five outcomes, the order of the Failure checks carrying meaning
|
||||
|
||||
Inherited architect, would restructure first:
|
||||
|
||||
- `bin/round_titles.py:5` `PASSES`: the pass list lives in four places, PASSES, ladder.ReviewedPass, REVIEWERS and SKILL.md's table, kept in sync by hand
|
||||
- `bin/rule_hook/rules.py:55` `round-title-counts`: no program blocks a fourth review round; rule-hook checks only the counts inside a round's title
|
||||
- `bin/git_repo.py:8` `git`: bin/'s root holds about 43 entries, with 13 loose modules such as git_repo, git_command, chunk_pick and todo_table not grouped by purpose
|
||||
- `bin/loop_claude/cycle/judge.py:68` `Reply.bundled`: the taken-in L and E + I are bundled in the judge's reply and taken in on Route and in routing.taken_in
|
||||
- `bin/model_routing/route.py:86` `Route.__str__`: the archive's text format is written in two modules and parsed back by ROUTED, routing_figures, reading_cost, score_outcomes and judge_replay
|
||||
- `bin/todo_table.py:89` `OLD_SHAPE`: the old todo.md shape is the largest dead weight in rank_todo.py
|
||||
|
||||
+58
-22
@@ -22,11 +22,13 @@
|
||||
|
||||
2026-10-13, implementing todo item 104: the judge reads each file under `~/.claude/skills/larv-review/standards/` whole too, for the same reason, as the `worker:` decision moved rules there.
|
||||
|
||||
2026-10-17, implementing todo item 168: the human answers an interrupt on loop-claude's terminal, and the worker resumes headless with the answer in a `-p` prompt. The judge reads that answer as a `[human]` line, not a `[loop]` one, so it holds the chunk open until the answer is recorded, as it does for an answer typed in claude.
|
||||
|
||||
## loop-claude: one session per project, its id derived from the checkout's path relative to `~/code`, or to `/` outside it
|
||||
|
||||
2026-09-21, lilleman; revised 2026-09-30 by lilleman. Serves goal 1. One fixed id per project keeps the session picker at one entry per project and makes any transcript under that id loop-claude's own to delete. A checkout outside `~/code` mirroring a path inside it shares that id, and a second loop on it is not refused. Once `todo.md` item 5 lands, the id comes from the full path, so no two checkouts share one, and `loop-claude` refuses to start while another session on that id is active. Moving the checkout orphans its open sessions, archive folder and models entry: sessions stay in the picker until the human deletes them, migration code not being worth a one-human audience. Valid while claude takes `--session-id` and resumes by it.
|
||||
|
||||
## loop-claude: before an interrupt, it marks the checkout and each of its worktrees trusted in `~/.claude.json`
|
||||
## loop-claude: before it opens claude on the terminal, it marks the checkout and each of its worktrees trusted in `~/.claude.json`
|
||||
|
||||
2026-09-21, lilleman; the lost-write risk accepted 2026-09-24 by larv-review. Serves goal 1. A write by another claude inside `trust`'s read-modify-write window is lost.
|
||||
|
||||
@@ -34,6 +36,8 @@
|
||||
|
||||
2026-09-30, lilleman: Claude Code owns and writes that file, so `loop-claude` is to move out of it, bringing each case that must stay to the human. Stands until `todo.md` item 6 ends it.
|
||||
|
||||
2026-10-17, implementing todo item 168: the human answers an interrupt on loop-claude's own terminal. claude now opens on the terminal only for `/talk`, a release ready to cut and the routing calls, and the trust is marked only then.
|
||||
|
||||
## bin/: the tests rerun themselves on a `uv`-fetched Python at README Install's floor
|
||||
|
||||
2026-09-26, larv-review. Serves goal 2. The suite reruns itself on a `uv`-fetched interpreter of the version Install names: `ast.parse(feature_version=)` on the host's Python accepts the nested f-string 186181a fixed, a compile check passes a call newer than the floor, like 3.12's `itertools.batched`, and a `python3.N` on `PATH` is installed by hand on every machine and again at each bump. Valid while `uv` can fetch the floor interpreter and no machine taking the checkout ships an older Python.
|
||||
@@ -76,7 +80,7 @@ Valid while the ladder orders its rungs by competence.
|
||||
|
||||
## review: the comprehension check records how hard a project is to read and blocks no merge: a paired ruling against the last measured commit where the architecture pass ran, and the four-seat scoring run, once when an item names the floor and twice on one head when a release's items run out
|
||||
|
||||
2026-10-08, lilleman. Serves goals 1.1 and 1.4. Two independent four-seat runs moved up to 0.4 on near-identical code, so a fall within that noise forced rounds that changed nothing (PR #224). A seat reading both versions judges the difference on the same material, so the noise the versions share cancels. No conventional significance level lets a sign test settle with four votes, so the human chose a lead of two votes over every other ruling, same included. Two seats that agree settle it, so a PR that leaves the reading as it was costs two seats. A third seat alone can never settle it, so the third and fourth launch together. The human chose the last measured commit on the architect's finding that with a merge base as the base, chunks without an architecture pass, and a suspended restructure's steps, could each lower comprehension unseen. Reading the default branch one merged change at a time keeps the rule working for merge commits and squash merges alike. The scoring run also runs on a chunk shipping an item that names the floor, so the chunk that lifts a project to the floor can prove it. A chunk that removes a release's last item without shipping it runs it too, so no release ends unmeasured. Valid while seats reading both versions agree more often than two absolute runs do.
|
||||
2026-10-08, lilleman. Serves goals 1.1 and 1.4. Two independent four-seat runs moved up to 0.4 on near-identical code, so a fall within that noise forced rounds that changed nothing (PR #224). A seat reading both versions judges the difference on the same material, so the noise the versions share cancels. No conventional significance level lets a sign test settle with four votes, so the human chose a lead of two votes over every other ruling, same included. Two seats that agree settle it, so a PR that leaves the reading as it was costs two seats. A third seat alone can never settle it, so the third and fourth launch together. The human chose the last measured commit on the architect's finding that with a merge base as the base, chunks without an architecture pass, and a suspended restructure's steps, could each lower comprehension unseen. Reading the default branch one merged change at a time keeps the rule working for merge commits and squash merges alike. The scoring run also runs on a chunk shipping an item that names the floor, so the chunk that lifts a project to the floor can prove it. A chunk that removes a release's last item without shipping it runs the scoring run too, so no release ends unmeasured, unless `todo.md` marks that release renamed in a `## Renamed` section (`bin/todo_table.py` → `renames`). Valid while seats reading both versions agree more often than two absolute runs do.
|
||||
|
||||
2026-10-13, lilleman. No published study validates simulated reader panels as a measure of how easy code is to understand, and no test of whether the panel's signal beats its noise has run. So no ruling, score or floor blocks a merge. The runs go on, so the history keeps the scores and the places the seats found hard, for later measurement. The architect, the stability reviewer and a session filing an item read the newest places, since those places are what a chunk can improve. With nothing to block, the check runs once per chunk, on the branch as review left it, in place of a run in each architecture round and a rescore after later commits. A fallen dimension no longer calls the four scoring seats either: their scores only decided the block. The base is now the newest merged change that adds any ruling or scoring run: with worse rulings merging, a base left behind them would charge one chunk's ruling with earlier chunks' falls. The newest places are the newest scoring run's and each later ruling's places a seat voted worse, so they change with each ruling. A chunk that leaves a touched place as hard says why in its PR summary, not in a decline's record, which would outlive the place.
|
||||
|
||||
@@ -86,9 +90,9 @@ Valid while the ladder orders its rungs by competence.
|
||||
|
||||
2026-10-04, lilleman. Serves goal 1.4. In a restructure, each step's scoring run measures code the next step deletes. It costs a run and, below the floor, blocks the step, yet says nothing about what the restructure buys. The scoring run after the last step measures that. 2026-10-08: the paired ruling replaced the scoring run in most chunks, and the suspension covers it too; the ruling after the last step compares with the commit measured before the first step. 2026-10-13, lilleman: the comprehension check blocks nothing now, so a suspension saves only the runs. Valid while such a decision names its items and the plan item that ends it.
|
||||
|
||||
## review: a project decision may opt every chunk out of the architect, the product-owner pass or the comprehension check
|
||||
## review: a project decision may opt every chunk out of the architect, the product-owner pass or the comprehension check, and a project opting out of the comprehension check voids code health
|
||||
|
||||
2026-10-11, lilleman. Serves goal 1.4. A research repo's PR, in a repo with no consumer for the product-owner pass and no product for the architect, spent rounds of both, and of the comprehension check, on a probe. The opt-out is the project's to make, and only an entry titled `review opt-out:` makes it, so a project without one is reviewed as before (goal 1.3). No opted-out reviewer works against a goal or a technical principle: the principles audit, which has no opt-out, still judges KISS and every other principle, so the entry names no plan item that ends it. 2026-10-13, lilleman: an opt-out of the comprehension check no longer ends with a chunk that ships an item naming the floor, since the floor blocks nothing. Valid while the principles audit judges every chunk that changes code, config or tests, and while the architect's and the product-owner's findings matter only to a product with consumers.
|
||||
2026-10-11, lilleman. Serves goal 1.4. A research repo's PR, in a repo with no consumer for the product-owner pass and no product for the architect, spent rounds of both, and of the comprehension check, on a probe. The opt-out is the project's to make, and only an entry titled `review opt-out:` makes it, so a project without one is reviewed as before (goal 1.3). No opted-out reviewer works against a goal or a technical principle: the principles audit, which has no opt-out, still judges KISS and every other principle, so the entry names no plan item that ends it. 2026-10-13, lilleman: an opt-out of the comprehension check no longer ends with a chunk that ships an item naming the floor, since the floor blocks nothing. 2026-10-18, lilleman, answering the review of PR #324: a project that opts out of the comprehension check voids code health in its README too: without the check the goal has no signal, and, never measured, it would weigh four times its weight forever. `rank_todo.py` refuses the plan of such a project until its README voids it. Valid while the principles audit judges every chunk that changes code, config or tests, and while the architect's and the product-owner's findings matter only to a product with consumers.
|
||||
|
||||
## review: the principles audit runs on every chunk that changes code, config or tests, and on no other chunk
|
||||
|
||||
@@ -112,7 +116,7 @@ Valid while the ladder orders its rungs by competence.
|
||||
|
||||
## loop-claude: every claude it starts bypasses permissions inside its sandbox
|
||||
|
||||
2026-09-30, lilleman. Applies "Always grant explicit access to data": the sandbox `loop-claude` runs in is where access is granted, so the worker and the interrupt run with `bypassPermissions`. The worker may read `~/.claude/.credentials.json`: it holds Claude Code's own credentials, which claude reads to run anyway. Its one seam to production is the forge: what it pushes or merges can publish through CI. Valid while `loop-claude` runs only in the sandbox README → Install names.
|
||||
2026-09-30, lilleman. Applies "Always grant explicit access to data": the sandbox `loop-claude` runs in is where access is granted, so the worker and the claude an interrupt opens run with `bypassPermissions`. The worker may read `~/.claude/.credentials.json`: it holds Claude Code's own credentials, which claude reads to run anyway. Its one seam to production is the forge: what it pushes or merges can publish through CI. Valid while `loop-claude` runs only in the sandbox README → Install names.
|
||||
|
||||
## review: `/security-review` is the security pass of record, except where the full scan runs on the same change and replaces it
|
||||
|
||||
@@ -128,20 +132,24 @@ Valid while the ladder orders its rungs by competence.
|
||||
|
||||
2026-10-02, lilleman. Serves goal 4, which keeps credentials, transcripts and memory files off the remote; a private project's name and commit ids are none of those. Valid while the bench names only cases and commits, never their code or results.
|
||||
|
||||
## todo.md: one table of items scored by the formula it states, each README achieve goal weighed by its position, the first heaviest, held to its bar, ranked by `bin/rank_todo.py`, which ranks each blocker above the items it blocks; the table's order is the plan's only order
|
||||
## todo.md: one table of items, scored by the formula it states, held to its bar and ranked by `bin/rank_todo.py`, which ranks each blocker above the items it blocks; each achieve goal weighs by its position, code health first and four times as heavy while the comprehension panel's overall is under 7.0 or unmeasured, then README.md's goals; the table's order is the plan's only order
|
||||
|
||||
2026-10-02, lilleman. Serves goal 1: findings were filed faster than chunks closed them, so the plan grew without telling what mattered. Each item is scored as `~/.claude/rules/todo-items.md` says; this repo's formula counts value highest and size least. An item under the bar is not kept; this repo's bar started at 10 and was set to 9 the same day, purging the 17 items under it. An Exempt cell keeps a row past the bar where a rule needs it kept. lilleman retired the two decisions whose plans the purge removed: the stats line in the transcript archive, and three benches before a workflow change merges. A finding under the bar is recorded nowhere, so a later review may raise it again, and the run rescores it. That costs one scoring; a ledger of dropped findings would regrow the list the bar caps. larv-review's "Round cap" → "Done" counts a finding named under the bar as settled, so one raised again holds no pass open. `rank_todo.py --check` is part of larv-review's gate, since only a check keeps the stored Score from going stale. The format is mandatory in every project, as the premises are (goal 1.3); the formula and bar are each project's own. A script ranks the table so a re-rank after each addition or edit is deterministic and cheap. A 🟡 against a technical principle is exempt as `principle`, because its audience value scores low and the bar would drop every one. A 🟢 against a principle is scored like any other finding. 2026-10-08, lilleman: the goal weights in `todo.md` depart from an even spread by position, which would weigh goal 4, leaking nothing, at 0.11. Valid while one human sets the bar and reads the ranking, and while the items marked `principle` stay few enough to rank.
|
||||
|
||||
2026-10-15, lilleman: the scores get a researched method, which `todo.md` items 149 and 151 build, after PR #283 shipped the ranking, PR #296 the risk scores and PR #298 the anchors each project names for each level in `docs/score-anchors.md`; the evidence is in `docs/scoring-and-goals-research.md`. R becomes L + E + I − 2: the chance the change holds a defect, set first by its size; the chance the defect escapes tests, review and monitoring; and the worst impact dimension, each about ×10 per level. I5, irreversible, holds R at 7 or more, and I4 at 5 or more, since a severe enough consequence outranks how unlikely it is. C goes from every table and tool: what it scored beyond size, spread and novelty, which L already holds, is complexity, which adds almost nothing once size is accounted for. Items rank by value per cost, V / 2^S, and V sums each cited achieve goal's sum-reciprocal weight times how far the item moves it. A goes, and the Audience says whose value the goals serve. R stays out of the ranking and sets how carefully an item is done; an item that lowers risk scores it as value. Each release fills by priority up to a capacity it states, in place of the bar. Each README goal is `maintain`, which vetoes an item that breaks it, or `achieve`, with a signal, a counter-signal and a one-line reason, as this README's Goals now mark them; each project keeps settled decisions to test its goals against. Each part of this method holds once the item that builds it ships. 2026-10-16, lilleman: a task's L and E + I pick its rungs in place of R, as `routing: one ladder` records.
|
||||
2026-10-15, lilleman: the scores get a researched method, which `todo.md` items 149 and 151 build, after PR #283 shipped the ranking, PR #296 the risk scores and PR #298 the anchors each project names for each level in `docs/score-anchors.md`; the evidence is in `docs/scoring-and-goals-research.md`. R becomes L + E + I − 2: the chance the change holds a defect, set first by its size; the chance the defect escapes tests, review and monitoring; and the worst impact dimension, each about ×10 per level. I5, irreversible, holds R at 7 or more, and I4 at 5 or more, since a severe enough consequence outranks how unlikely it is. C goes from every table and tool: what it scored beyond size, spread and novelty, which L already holds, is complexity, which adds almost nothing once size is accounted for. Items rank by value per cost, V / 2^S, and V sums each cited achieve goal's weight times how far the item moves it. A goes, and the Audience says whose value the goals serve. R stays out of the ranking and sets how carefully an item is done; an item that lowers risk scores it as value. Each release fills by priority up to a capacity it states, in place of the bar. Each README goal is `maintain`, which vetoes an item that breaks it, or `achieve`, with a signal, a counter-signal and a one-line reason, as this README's Goals now mark them; each project keeps settled decisions to test its goals against. Each part of this method holds once the item that builds it ships. 2026-10-16, lilleman: a task's L and E + I pick its rungs in place of R, as `routing: one ladder` records.
|
||||
|
||||
2026-10-16, PR #283: items rank by `Score = 100 * V / 2**S`. 2**S is the cost; the 100 lets a score read to one decimal. V sums, over the achieve goals an item's Moves cell names, each goal's weight times how far the item moves it, 1 to 10. The goal ranked k of n achieve goals in reading order weighs (1/k) / (1 + 1/2 + … + 1/n), the sum-reciprocal weight. A Moves column replaces A, G and Goals, and `rank_todo.py` derives the weights from README.md, so the goal weights table and the 2026-10-08 weights are gone. An item that cited only maintain goals now names the achieve goal it moves, or, as a defect restoring one, that maintain goal, as the entry below says. A panel of three readers seated as lilleman picked the spelling: two put a Moves column holding `1.1 by 8, 1.2 by 5` first, and one put `1.1: 8` first; two chose `2**S`, since a Python reader takes `^` for XOR; all three chose one decimal of `100 * V / 2**S` over three significant digits or a log. The bar moved to 0.1, lilleman's call answering the review of PR #283: on one-decimal scores it drops an item scoring under 0.05, in practice one that moves no achieve goal, and item 149 revisits it. A table in the old shape still ranks by the formula and weights it states, and ranking it says to reshape it, so no other project's commits stop; reshaping it is that project's only work until done, as `CLAUDE.md` → "Working loop" says. PR #296 dropped the C column, and put L, E and I right before R, which `rank_todo.py` writes from them: of three readers seated as lilleman, two ranked that order first, since a reader meets each level before the R it builds and R sits beside S, and the third ranked it second, after an order with S before the levels. The old shape's ranking is valid until `todo.md` item 156.
|
||||
2026-10-16, PR #283: items rank by `Score = 100 * V / 2**S`. 2**S is the cost; the 100 lets a score read to one decimal. V sums, over the achieve goals an item's Moves cell names, each goal's weight times how far the item moves it, 1 to 10. Each achieve goal, in reading order, weighs 0.97 times the one before it, and the weights sum to 1. 2026-10-18, lilleman: goals should weigh almost the same. This replaced the sum-reciprocal weight, under which the goal ranked k of n achieve goals weighed (1/k) / (1 + 1/2 + … + 1/n), so the last of twelve goals weighed a twelfth of the first. The step departs from `docs/scoring-and-goals-research.md`, where sum-reciprocal weights came closest to the weights people gave. PR #319 restored the sum-reciprocal weights on a misreading of lilleman's answer, and lilleman then confirmed the step, so the sum-reciprocal weights stay dropped. The worker picked 0.97; `GOAL_STEP` sets it. A Moves column replaces A, G and Goals, and `rank_todo.py` derives the weights from README.md, so the goal weights table and the 2026-10-08 weights are gone. An item that cited only maintain goals now names the achieve goal it moves, or, as a defect restoring one, that maintain goal, as the entry below says. A panel of three readers seated as lilleman picked the spelling: two put a Moves column holding `1.1 by 8, 1.2 by 5` first, and one put `1.1: 8` first; two chose `2**S`, since a Python reader takes `^` for XOR; all three chose one decimal of `100 * V / 2**S` over three significant digits or a log. The bar moved to 0.1, lilleman's call answering the review of PR #283: on one-decimal scores it drops an item scoring under 0.05, in practice one that moves no achieve goal, and item 149 revisits it. A table in the old shape still ranks by the formula and weights it states, and ranking it says to reshape it, so no other project's commits stop; reshaping it is that project's only work until done, as `CLAUDE.md` → "Working loop" says. PR #296 dropped the C column, and put L, E and I right before R, which `rank_todo.py` writes from them: of three readers seated as lilleman, two ranked that order first, since a reader meets each level before the R it builds and R sits beside S, and the third ranked it second, after an order with S before the levels. The old shape's ranking is valid until `todo.md` item 156.
|
||||
|
||||
2026-10-16, lilleman, answering the review of PR #283. An item that restores a maintain goal the project breaks today is a defect: exempt as `defect`. Its Moves name that maintain goal and how much of it is broken, and the goal weighs as the heaviest achieve goal, since a broken maintain goal outranks any achieve goal. Every defect ranks by its score, so a trivial one waits behind valuable work. Only questions and then security findings rank first in their release: a question's answer may change other items, and a question waits for the human anyway, so ranking it first delays no chunk. An item names the most specific goal it moves, and a parent only for a move none of its sub-goals covers, so a sub-goal's move does not count twice; `rank_todo.py` refuses a goal named beside its own sub-goal. Each project reshapes its own `todo.md`; `CLAUDE.md` → "Working loop" makes the reshape the only work until done, as it makes writing missing premises. An item that makes this project easier to read moves goal 1.4 as well as 1.1, since reading cost is measured in tokens per chunk; a goal of its own for readability is left for later. Cost gains a fixed part, F in `Score = 100 * V / (2**S + F)`: every chunk carries a cost its size does not shrink, the reading before its first commit, about 130k tokens, and its review passes, so `2**S` alone overrated tiny items. F is 8, about one S 3 change, until `todo.md` item 158 measures it.
|
||||
2026-10-16, lilleman, answering the review of PR #283. An item that restores a maintain goal the project breaks today is a defect: exempt as `defect`. Its Moves name that maintain goal and how much of it is broken, and the goal weighs as the heaviest achieve goal, since a broken maintain goal outranks any achieve goal. Every defect ranks by its score, so a trivial one waits behind valuable work. Only questions and then security findings rank first in their release: a question's answer may change other items, and a question waits for the human anyway, so ranking it first delays no chunk. An item names the most specific goal it moves, and a parent only for a move none of its sub-goals covers, so a sub-goal's move does not count twice; `rank_todo.py` refuses a goal named beside its own sub-goal. Each project reshapes its own `todo.md`; `CLAUDE.md` → "Working loop" makes the reshape the only work until done, as it makes writing missing premises. An item that makes this project easier to read moves code health, as the 2026-10-18 paragraph below says, and goal 1.4, since reading cost is measured in tokens per chunk. Cost gains a fixed part, F in `Score = 100 * V / (2**S + F)`: every chunk carries a cost its size does not shrink, the reading before its first commit, about 130k tokens, and its review passes, so `2**S` alone overrated tiny items. F is 8, about one S 3 change, until `todo.md` item 158 measures it.
|
||||
|
||||
2026-10-16, lilleman, ruling on the plan in PR #283: release 0.2.0 takes plan items 146, 152, 73, 50, 65, 84, 153 and 67, the split of `routing: one ladder`, and the question of how many chunks `score-outcomes` and the reading-cost trend wait for, ahead of their scores, to put budget and efficiency in the other projects first. A standing goal cannot capture that priority for now, so it is a one-time ruling: the later releases, and every release after 0.2.0, fill from the score again.
|
||||
|
||||
2026-10-18, lilleman. Serves goal 1.1: every project shares one achieve goal, code health, which `CLAUDE.md` → "Shared goal" states once and which replaces each project's own readability goal. It ranks first among a project's achieve goals, since lilleman rates it very important while the comprehension panel's overall is under 7.0. While that overall is under 7.0, or no scoring run has measured the project, it weighs four times its weight at 7.0 or above, as `UNDER_FLOOR` sets. The overall is the mean of the overall means of every scoring run on the newest scored commit in `docs/comprehension-history.md`, as `newest_scored` finds them. Two runs of one head measure it twice, and the newest alone would let their noise flip the weight: 7.13 and 6.88 on one head of another project would have. The review of PR #324 raised this choice. Weighing code health four times as much leaves the other achieve goals' weights as they are. So crossing 7.0 changes only the scores of the items that move code health, and of the defects, since a broken maintain goal weighs as the heaviest achieve goal. `larv-review record-scoring` re-ranks `todo.md` after it appends a run. A project that opts out of the comprehension check voids the goal, as `review: a project decision may opt every chunk out …` records. A README voids the goal with `**Void:** code health, since <reason>.` under `## Goals`, and an item's Moves cell names it as in `code health by 6`. A panel of three readers seated as lilleman picked both 3-0: `code health` over `code`, `health`, `C` and `0`, and the bold `Void:` line over a sentence under `## Goals` or a line under `## Audience`. The counter-signal is stated now and counted once `todo.md` item 198 ships, since no tool yet records why a finding arose. Valid while the comprehension panel's overall is how a project measures how hard it is to read.
|
||||
|
||||
2026-10-15, lilleman. Serves goal 1.4: loop-claude routes a chunk's first cycle on the item the chunk takes (`routing: a chunk's worker runs on the rung its item's L picks`). An item lists the items that must be done before it starts in a Blocked by column, and `rank_todo.py` ranks each blocker above every item it blocks. The table's order is `todo.md`'s only order: `rank_todo.py` fails on text beside the table under `## Items`, since a prose order there, "Release 0.3.0 takes items 125, 114 and 124 first", contradicted the table and loop-claude could not read it. A decision that wants an order sets the scores instead. An item waits while it is marked `question` or a blocker of it is still in the table, whatever the rows' order, so a release's first row that does not wait is the item a chunk takes. A blocker the table no longer holds was finished or deleted, and is dropped, so the cell shows what still blocks. A panel of three readers seated as lilleman picked the spelling: two ranked "Blocked by" first, as the cell lists only what still blocks, and all three chose bare IDs such as `12, 14` in a column right after Release, read before the tagline and kept apart from the scores. `rank_todo.py` adds the column to a table without it. The tools read cells by column name, so a later column leaves a reader on an older release working; `rank_todo.py`, which writes every column, fails on one it does not know rather than drop it.
|
||||
|
||||
2026-10-18, PR #312. Serves goals 1.5 and 1.1: adf-codec renamed its next release, 0.2.1, to 0.3.0, and `chunk-preflight` then called 0.2.1 finished and stopped the loop on every cycle. A change that moves a release's last items elsewhere reads the same whether it renamed the release or deferred its leftovers, so the plan says which: a `## Renamed` section holds one line `- 0.2.1 renamed to 0.3.0` per rename, which `bin/todo_table.py`'s `renames` reads. `chunk-preflight`, `loop-claude` and larv-review's scoring-run trigger skip a marked release; they read only the first version. A release whose items moved unmarked reads as finished: the loop stops, says so and names the fix, and the trigger calls a scoring run once work has landed. So a forgotten mark costs one interrupt and never lets a release end unmeasured. `rank_todo.py` fails on a line of another shape and on an item filed under a marked release, and a newest plan whose marks do not parse leaves the next release unknown. A line goes once a tag at or past its release is cut. Only a rename is marked, since an unmarked move is the deferral. A panel of three readers seated as lilleman picked the spelling 3-0 over `- 0.2.1 → 0.3.0` under `## Releases` and a `Renamed 0.2.1 = 0.3.0` line under `## Scoring`: plain words need no special character to type. Valid while a rename is the only move of a release's items that the tools must tell from finishing it.
|
||||
|
||||
## todo.md: only a session or subagent on the project's rung or above scores or reshapes the plan; one below it drafts new items and changes to filed ones for a subagent at or above that rung to apply and score, and removes finished ones
|
||||
|
||||
2026-10-15, lilleman. Serves goal 1.1: a cheaper rung writes worse scores, and a wrong score routes a chunk onto the wrong rung, ranks the plan wrong and drops an item under the bar that should stay. Below the project's rung, a session or subagent may not score an item, move it between releases, split a milestone, delete an item under the bar, or rewrite a filed item. It drafts each new item, and each change to a filed item, such as a refresh a rule asks for. Before the next commit, one subagent on the project's rung or above applies and scores the drafts. One launch covers all of a chunk's drafts (goal 1.4). A security finding gets that subagent at once, since it is filed the moment it is found. Removing a finished item closes work and plans none, so any rung does it. Scoring a delegated task's L runs on any rung too: a launch on the project's rung to score each delegation would cost more than the cheaper task saves (goal 1.4).
|
||||
@@ -214,6 +222,22 @@ The decision `worker: a chunk's worker writes the simplest change…` has the wo
|
||||
|
||||
Valid while the worker writes the tests that larv-review's reviewers hold to the principles.
|
||||
|
||||
## review: each reviewer under `agents/` writes its full report into the chunk's review folder under `~/.local/state/larv-review/` and returns the worker its verdict and one line per finding; rule-hook refuses its Edit and MultiEdit, and any Write outside `~/.local/state/larv-review/`
|
||||
|
||||
2026-10-18, lilleman through todo item 73. Serves goal 1.4: a report the worker does not need line by line no longer fills its context. Goal 1.1 holds because the worker reads a finding's full entry before it answers a 🔴 or 🟡.
|
||||
|
||||
Each reviewer holds Write for its report. Claude Code passes a subagent's type to a PreToolUse hook as `agent_type`. So `bin/rule_hook/reviewer_report.py` refuses a reviewer's Edit and MultiEdit, and any Write outside `~/.local/state/larv-review/`; no marker overrides it. A reviewer's Bash, as stability-reviewer holds, is not confined.
|
||||
|
||||
The folder is fixed, since loop-claude's headless sessions have no scratchpad. It sits outside every checkout, so no project sees a report. It survives a reboot, unlike `/tmp`, so a resumed chunk still reads its earlier rounds. It is in the user's home, so no other local user plants a symlink that widens it. A report may quote a secret, so `larv-review review-folder`, which makes the chunk's folder, leaves `~/.local/state/larv-review` readable by the user alone.
|
||||
|
||||
A chunk keeps its folder after the merge. `review-replay` hands a replayed reviewer a copy holding only the reports written after the chunk began and before the round did. So the replay reads the earlier rounds its prompt names, never the findings it is to find. The chunk's own reports stay as they were.
|
||||
|
||||
Claude Code's own subagent prompt tells a subagent to return findings rather than write report files. `review-findings.md` → "Report" overrides that, since the file is the worker's input; a prose-reviewer probed on 2026-10-18 wrote the file its prompt named. A general-purpose wrapper that launches the reviewer was not tried: Claude Code's documentation says a subagent cannot start another.
|
||||
|
||||
Before this change, reports took a median 19k tokens per chunk, 8% of the worker's peak context, and lines carrying a severity mark were 9–24% of a report (2026-10-08, over 68 archived transcripts). `review-replay` still counts each 🔴 and 🟡 by its line in the reviewer's reply, now a one-line summary. todo.md item 187 is to measure what the worker reads of the reports instead.
|
||||
|
||||
Valid while Claude Code passes `agent_type` to hooks inside a subagent. Without it, the rule refuses nothing, and a reviewer may write anywhere.
|
||||
|
||||
## review: stability and product-owner report only a defect, a broken requirement of the plan or the goals, a breach of a technical principle, or for stability a hard place the change touches; each architect finding names a later change the PR makes harder; prose runs only on a chunk that changes prose
|
||||
|
||||
2026-10-13, lilleman through todo item 97, implemented by claude. Serves goals 1.4 and 1.5. Anthropic's Claude Code best practices: "A reviewer prompted to find gaps will usually report some, even when the work is sound… Chasing every finding leads to over-engineering." 320 of this repo's 876 commits answered a review round. So stability and product-owner drop a finding that is none of these, and stability leaves the style of comments to prose, which reads every comment a chunk touches. An architect finding that names no later change it makes harder cannot be checked, so it is dropped. The architecture pass and the comprehension check keep their whole-project view, which guards goal 1.1 as a project grows. Valid while the findings these rules drop keep changing nothing a user would notice.
|
||||
@@ -238,15 +262,15 @@ A project's rung is its model's cheapest rung, which for Opus 5.5 is its default
|
||||
|
||||
Valid while the index ranks these models, and while no newer model joins the catalog.
|
||||
|
||||
## routing: a chunk's worker runs on the rung its item's L picks, below the project's rung too; its reviewers run on the highest of the worker's rung, the project's and the one picked by the highest E + I among the chunk's items, the seats and the security pass always on the project's
|
||||
## routing: a chunk's worker runs on the rung its item's L picks, below the project's rung too; its reviewers run on the highest of the worker's rung, the project's and the one picked by the highest E + I among the chunk's items, unless a replay lowered their pass; the seats and the security pass always on the project's
|
||||
|
||||
2026-10-14, lilleman. Serves goals 1.1 and 1.4.
|
||||
|
||||
Only chunks run below the project's rung can prove that a cheaper worker holds quality (goal 1.1). So on 2026-10-14 lilleman chose a trial on real chunks: a replay of past chunks would spend on work that never ships (goal 1.4). Review holds quality meanwhile. While the worker runs below the project's rung, loop-claude's prompt has it launch each comprehension seat and the security pass's subagent on the project's rung, and each reviewer there too unless the highest E + I among its items picks a higher rung, through the Agent tool's model and effort. The worker runs a full scan only from such a subagent, because the `claude-security` plugin's researchers and verifiers inherit the model that starts them. A subagent that cannot run the scan leaves it unavailable, so larv-review runs `/security-review` in its place. lilleman chose the project's rung, medium, knowing `settings.json` runs Opus 5.5 at xhigh, so a routed worker runs below the effort an interactive session takes.
|
||||
Only chunks run below the project's rung can prove that a cheaper worker holds quality (goal 1.1). So on 2026-10-14 lilleman chose a trial on real chunks: a replay of past chunks would spend on work that never ships (goal 1.4). Review holds quality meanwhile. While the worker runs below the project's rung, loop-claude's prompt has it launch each comprehension seat and the security pass's subagent on the project's rung, and each reviewer there too unless the highest E + I among its items picks a higher rung or a replay lowered its pass, through the Agent tool's model and effort. The worker runs a full scan only from such a subagent, because the `claude-security` plugin's researchers and verifiers inherit the model that starts them. A subagent that cannot run the scan leaves it unavailable, so larv-review runs `/security-review` in its place. lilleman chose the project's rung, medium, knowing `settings.json` runs Opus 5.5 at xhigh, so a routed worker runs below the effort an interactive session takes.
|
||||
|
||||
While the worker runs above the project's rung, loop-claude's prompt has it launch the comprehension seats and the security pass's subagent on the project's rung too. So the seats score every chunk on one rung, and the security pass spends no more than the project chose. The prompt after each unfinished verdict repeats this, since a step-up may have taken the worker above the project's rung. The other reviewers never run below the worker's rung: a worker climbs because its chunk proved harder than its score said, which is when a cheaper reviewer is the bigger risk. A reviewer or seat that rules the work below standard may rerun one rung up: `review: a reviewer or comprehension seat that rules the work below standard`.
|
||||
While the worker runs above the project's rung, loop-claude's prompt has it launch the comprehension seats and the security pass's subagent on the project's rung too. So the seats score every chunk on one rung, and the security pass spends no more than the project chose. The prompt after each unfinished verdict repeats this, since a step-up may have taken the worker above the project's rung. The other reviewers never run below the worker's rung while it runs above the project's: a worker climbs because its chunk proved harder than its score said, which is when a cheaper reviewer is the bigger risk. A reviewer or seat that rules the work below standard may rerun one rung up: `review: a reviewer or comprehension seat that rules the work below standard`.
|
||||
|
||||
On 2026-10-16 lilleman routed the reviewers on their item's E + I as well, on either side of the project's rung, which may lift them above both the worker's rung and the project's: how far a defect would escape, and what it would break, set how hard review must look (goal 1.1). loop-claude names that rung in the worker's prompt, and hands it to the worker's claude beside the project's and the worker's, so rule-hook holds each reviewer launch to it. A low E + I never steps a reviewer below the project's rung: lilleman chose to lower a pass only where a replay shows a lower rung finding every 🔴 and 🟡 the project's rung finds, which `todo.md` item 159 measures for each pass. An item the worker takes in beyond the routed one counts too, since its E + I scores its defects as the routed item's scores theirs. The worker's prompt names the reviewers' rung each higher E + I picks, so the worker reviews a taken-in item on it in the same run. The judge reports the highest E + I the worker states for a taken-in item. From the next cycle loop-claude routes on that E + I, and archives it with the route so a rerun keeps it.
|
||||
On 2026-10-16 lilleman routed the reviewers on their item's E + I as well, on either side of the project's rung, which may lift them above both the worker's rung and the project's: how far a defect would escape, and what it would break, set how hard review must look (goal 1.1). loop-claude names that rung in the worker's prompt. It hands the E + I to the worker's claude beside the project's rung and the worker's, so rule-hook works out each review's rung as the prompt does and holds each launch to it. A low E + I never steps a reviewer below the project's rung: only a replay lowers a pass, as `routing: a review pass runs below the project's rung only on a rung that a replay of its rounds shows finding every 🔴 and 🟡 the project's rung finds…` records. An item the worker takes in beyond the routed one counts too, since its E + I scores its defects as the routed item's scores theirs. The worker's prompt names the reviewers' rung each higher E + I picks, so the worker reviews a taken-in item on it in the same run. The judge reports the highest E + I the worker states for a taken-in item. From the next cycle loop-claude routes on that E + I, and archives it with the route so a rerun keeps it.
|
||||
|
||||
Valid until the trial on real chunks shows whether a worker below the project's rung holds quality.
|
||||
|
||||
@@ -284,17 +308,21 @@ loop-claude's prompt names the rungs a trigger opens, so the worker computes no
|
||||
|
||||
Valid while the ladder orders its rungs by competence.
|
||||
|
||||
## routing: a worker whose run ends asking for a higher rung, citing an escalation trigger the judge finds in the transcript, resumes one rung up next cycle, up to two rungs above the rung its item picks
|
||||
## routing: a worker whose run ends asking for a higher rung, citing an escalation trigger the judge finds in the transcript, steps one rung up as the judge interrupts or quotes an answer, or next cycle, up to two rungs above the rung its item picks
|
||||
|
||||
2026-10-15, lilleman asked for it. Serves goals 1.1 and 1.4: when the hard part is the rest of the chunk, handing it to subagents piece by piece leaves the worker, which reads and checks each of their diffs, on a rung that proved too low. The worker climbs only once its run records a trigger.
|
||||
|
||||
loop-claude's prompt offers the step beside the escalated subagent of `routing: a worker hands a task one rung up`, as long as the limit leaves a rung that subagent may take without the human's yes. The worker then ends its run asking loop-claude for a higher rung and naming the trigger. The judge quotes an earlier passage that shows the trigger fired, such as a review round's commit title or the worker's report of the failing test, never the request itself. The trigger must have fired since any earlier such request, so one trigger buys one step. The judge sees the worker's text and tool calls but no tool results, so the quote shows that the run recorded the trigger, not that a tool's output bears it out. loop-claude checks the quote word for word, as it checks a quoted answer, since stitched fragments can make up a trigger. Without such a quote, the rung holds. A misquote is no failure, since holding the rung is safe and three failures stop an unattended loop. The next prompt names the worker's rung, so the worker learns whether the step went through.
|
||||
loop-claude's prompt offers the step beside the escalated subagent of `routing: a worker hands a task one rung up`, as long as the limit leaves a rung that subagent may take without the human's yes. The worker then ends its run asking loop-claude for a higher rung and naming the trigger. The judge quotes the earlier passage where the trigger fired, such as a review round's commit title or the worker's report of the failing test, never a later mention of it and never the request itself. The quoted passage must sit after the worker's last step-up, which loop-claude checks, so one passage buys one step. The judge sees the worker's text and tool calls but no tool results, so the quote shows that the run recorded the trigger, not that a tool's output bears it out. loop-claude checks the quote word for word, as it checks a quoted answer, since stitched fragments can make up a trigger. Without such a quote, the rung holds. A misquote is no failure, since holding the rung is safe and three failures stop an unattended loop. The next cycle's prompt names the worker's rung, so the worker learns whether the step went through. When a quoted answer, or an interrupt the human answers on loop-claude's terminal, steps the worker up, the prompt that resumes it with the answer names the new rung, so the worker learns of the step sooner.
|
||||
|
||||
A run that asks for a higher rung may also ask a question. The judge then interrupts, or quotes the answer from README.md or the records, and either ruling carries the escalation quote too, checked the same way. loop-claude steps the rung as the ruling comes in, before the human is asked or the worker resumes with the quoted answer, since the work after the answer is work the stepped rung should do. An interrupt or a quoted answer is no unfinished verdict, so it adds to no count.
|
||||
|
||||
The judge may quote a different passage for the trigger that already stepped the rung, and loop-claude cannot tell from the quote alone whether the trigger is new. So it goes by where the quoted passage sits in the transcript. When an escalation steps the worker, the route marks how many transcript entries the session held: the mark. loop-claude then accepts an escalation quote only from the worker's own lines after the mark, never from its own prompts or the human's lines, which repeat earlier passages. The judge reads a `[step]` line at the mark saying the triggers before it are spent, so it quotes a passage the check accepts. The session's transcript only grows, so the mark holds across cycles. The trigger that bought a step, and any rewording of it before the mark, cannot buy another. A trigger that fires after the step steps the worker again, in the same cycle or a later one. One risk remains: a worker on the stepped rung may restate an old trigger after the mark, and the judge may quote that. The cap two rungs above the rung the item picks limits what this costs. Before the mark, once an interrupt or a quoted answer had taken an escalation, no later ruling of that cycle carried one, so a trigger that fired after the answer was lost. lilleman chose the mark on 2026-10-18 over two alternatives: lifting that rule when a worker run ended would have let one trigger buy two steps, and telling the worker its request was dropped would still have lost the step.
|
||||
|
||||
The step is one rung up from the rung the worker would otherwise hold: its own, or the rung an item the judge saw it take in picks, whichever is higher. It resets the count of unfinished verdicts, so the step every second one takes counts afresh; when both steps fall on one verdict, the worker steps once. It stops at the limit escalated subagents stop at, two rungs above the rung the chunk started on. Past that limit the rung holds: loop-claude takes no yes from the human between cycles, so a worker there asks the human for an escalated subagent instead. The judge keeps its rung, as `routing: on a model judge-replay covered` says.
|
||||
|
||||
The archive quotes the judge's passage under `Escalation:` in the unfinished verdict, beside any step-up it causes. `bin/routing_figures/` counts that verdict as unfinished, not as an escalation by trigger, which it counts only from subagent prompts.
|
||||
The archive quotes the judge's passage under `Escalation:` in the unfinished verdict, the interrupt or the quoted answer. The step an unfinished verdict causes is archived after it. The step an interrupt or a quoted answer causes is archived with it, at once: the interrupt or answer names the rung the worker ran on until then, and a step-up archived beside it names the rung it runs on from then. So the routing figures charge each stretch to its own rung, and a loop that dies while the human answers resumes on the stepped rung. Each archived worker line names the mark once there is one, so a resumed loop keeps it. `bin/routing_figures/` counts none of these steps as an escalation by trigger, which it counts only from subagent prompts.
|
||||
|
||||
Valid while the worker reports in its transcript the triggers that fired.
|
||||
Valid while the worker reports in its transcript the triggers that fired, and while a chunk's session transcript only grows.
|
||||
|
||||
## routing: on a model judge-replay covered, the judge runs on the rung a review would get from the highest E + I among its chunk's items, never below the project's rung
|
||||
|
||||
@@ -308,12 +336,20 @@ Only Opus 5.5 was replayed, so the judge of a project on another model keeps the
|
||||
|
||||
Valid while the archived verdicts show what a judge should return, and until a new model joins the ladder: replay then.
|
||||
|
||||
## routing: the stability reviewer runs no lower than the project's rung while the worker runs below it, until `stability-replay` shows a lower rung finding every 🔴 and 🟡 the project's rung finds
|
||||
## routing: a review pass runs below the project's rung only on a rung that a replay of its rounds shows finding every 🔴 and 🟡 the project's rung finds, and only where the E + I steps no review up and the worker runs no higher than the project's rung, then even below the worker's; no pass has such a rung
|
||||
|
||||
2026-10-15, lilleman proposed running the stability reviewer on the worker's rung; the replay that gates it is the agent's proposal. Serves goals 1.1 and 1.4: the stability pass is the only one that mutation-tests the changed lines, so a defect it misses may merge, and a cheaper reviewer saves money only where it misses nothing.
|
||||
2026-10-15, lilleman proposed running the stability reviewer on the worker's rung, and the agent proposed the replay that gates it. On 2026-10-16 lilleman asked for the prose pass to run on the worker's rung or lower, and, answering PR #296, for every pass to drop below the project's rung only where a replay shows it may. Serves goal 1.4 without giving up goal 1.1: a cheaper reviewer saves money only where it misses nothing.
|
||||
|
||||
`bin/stability-replay <model>` replays archived stability rounds on the code each reviewed, first on the project's rung, then on each rung below it, highest first, and stops at the first that misses a finding the project's rung found again. A rung qualifies only where it finds every such 🔴 and 🟡.
|
||||
`bin/review-replay <pass> <model>` replays a pass's archived rounds on the code each reviewed. It replays them first on the project's rung, then on each rung below it, highest first, down to the ladder's lowest. It stops at the first rung that misses a finding the project's rung found again. A rung qualifies only where it and each rung above it find every such 🔴 and 🟡.
|
||||
|
||||
On 2026-10-15, `bin/stability-replay claude-opus-5-5` replayed the latest 10 rounds holding a 🔴 or 🟡, 40 findings in all, 8 of the rounds from this repo. Opus 5.5 at medium, the project's rung, found 29 of them again. Sonnet 5.5 at high missed 13 of those 29, 2 of them 🔴, so no rung below the project's rung qualifies, and Haiku 5.5, below Sonnet on the ladder, was not tried. So the stability reviewer runs where `routing: a chunk's worker runs on the rung its item's L picks` puts every reviewer: never below the project's rung while the worker runs below it.
|
||||
`REPLAYED` in `bin/model_routing/ladder.py` holds each qualifying rung, by pass and project model. Where the chunk's E + I steps no review up and the worker runs no higher than the project's rung, the pass runs on that rung, even below the worker's. Otherwise the pass runs where every other pass does: the replay compared reviews on the project's rung only, never reviews on a rung an E + I stepped up, nor of a chunk whose worker climbed above the project's rung.
|
||||
|
||||
Valid until a new model joins the ladder, or the archive holds rounds a new reviewer prompt produced: replay then.
|
||||
The runs, each on the latest 10 rounds of Opus 5.5 projects that hold a 🔴 or 🟡:
|
||||
|
||||
- 2026-10-15, stability: 40 findings, 8 of the rounds from this repo. Opus 5.5 at medium, the project's rung, found 29 of them again. Sonnet 5.5 at high missed 13 of those 29, 2 of them 🔴. No rung qualifies.
|
||||
- 2026-10-18, prose: 39 findings. The project's rung found 27 of them again. Sonnet 5.5 at high missed 12 of those 27. No rung qualifies.
|
||||
- 2026-10-18, stability again, since that day's change to the reviewer prompts expired the first run: 29 findings. The project's rung found 20 of them again. Sonnet 5.5 at high missed 11 of those 20, 1 of them 🔴. No rung qualifies.
|
||||
|
||||
The prose pass went first: a missed prose finding breaks no behaviour, and a later change fixes it cheaply. Sonnet 5.5 missed 44 to 55% of what the project's rung found again, in the prose pass as in both stability runs. Nothing suggests the other passes' findings are easier to find. So the architecture, principles, overrides and product-owner passes are not replayed yet: a replay would spend money with little chance of a qualifying rung (goal 1.4). `todo.md` item 196 keeps their replays in the plan. Every pass runs where `routing: a chunk's worker runs on the rung its item's L picks` puts every reviewer.
|
||||
|
||||
Valid until a new model joins the ladder, which calls for a replay of every pass, or a pass's reviewer prompt changes, which calls for a replay of that pass.
|
||||
|
||||
@@ -620,3 +620,60 @@ Read most (opens and searches):
|
||||
- `bin/loop_claude/routing.py` 2
|
||||
- `bin/markdown_text.py` 2
|
||||
- `bin/todo_table.py` 2
|
||||
|
||||
## Reading cost, chunk 819681d5ebae, finished 2026-10-17T19:47:42Z
|
||||
|
||||
98148 new input tokens before the first commit.
|
||||
|
||||
## Reading cost, chunk 3721394862b1, finished 2026-10-17T20:18:33Z
|
||||
|
||||
133110 new input tokens before the first commit.
|
||||
|
||||
Read most (opens and searches):
|
||||
|
||||
- `rules/todo-items.md` 1
|
||||
|
||||
## Reading cost, chunk 055546870eaf, finished 2026-10-17T20:46:45Z
|
||||
|
||||
100998 new input tokens before the first commit.
|
||||
|
||||
## Reading cost, chunk 6ab072ca20a3, finished 2026-10-17T22:04:13Z
|
||||
|
||||
248782 new input tokens before the first commit.
|
||||
|
||||
Read most (opens and searches):
|
||||
|
||||
- `todo.md` 4
|
||||
- `rules/todo-items.md` 1
|
||||
|
||||
## Reading cost, chunk cec7aa03e832, finished 2026-10-18T07:21:37Z
|
||||
|
||||
88622 new input tokens before the first commit.
|
||||
|
||||
Read most (opens and searches):
|
||||
|
||||
- `rules/decisions.md` 1
|
||||
|
||||
## Reading cost, chunk d905b642140f, finished 2026-10-18T08:20:12Z
|
||||
|
||||
187066 new input tokens before the first commit.
|
||||
|
||||
## Reading cost, chunk e7a12c46be6e, finished 2026-10-18T09:10:49Z
|
||||
|
||||
115559 new input tokens before the first commit.
|
||||
|
||||
## Reading cost, chunk b897b24d5e70, finished 2026-10-18T11:15:04Z
|
||||
|
||||
87043 new input tokens before the first commit.
|
||||
|
||||
## Reading cost, chunk 9f9579dd30bb, finished 2026-10-18T12:17:04Z
|
||||
|
||||
163028 new input tokens before the first commit.
|
||||
|
||||
## Reading cost, chunk 9fdabb34de02, finished 2026-10-18T17:00:58Z
|
||||
|
||||
416077 new input tokens before the first commit.
|
||||
|
||||
Read most (opens and searches):
|
||||
|
||||
- `rules/decisions.md` 1
|
||||
|
||||
@@ -7,4 +7,5 @@ paths:
|
||||
|
||||
- **Goals** state the project's aim and intent, not promises: one numbered line each, like slogans, in priority order; a sub-goal is indented under its goal — "1. Blazing fast performance. 2. Correctness is more important than many features." A goal names no step of the work, such as a check to run first, and rarely an implementation. How a goal is met goes in a method section further down the README and names the goal it serves. BANNED as a goal: `Kill weak candidates early, with the cheap checks first.` GOOD: the goal `Keep research on a budget, so it scales in both time and cost.`, with the cheap checks moved to the method section, naming that goal.
|
||||
- **Mark each goal `**Maintain:**` or `**Achieve:**`.** A maintain goal is a state to hold: a change that breaks it is redesigned or dropped, whatever its value to other goals. An achieve goal is a direction to pursue, weighed against the other achieve goals. Under each achieve goal, three indented bullets: `Signal:` what moving towards it looks like, `Counter-signal:` what shows it is bought at a wrong price, and `Why:` one line on how the two connect. A goal with sub-goals states its own signal. A maintain goal has no bullets. BANNED: an unmarked goal; an achieve goal with no signal; `**Achieve:** Delivery speed.` with the signal `faster`. GOOD: `**Achieve:** Delivery speed.` with `Signal: hours from a chunk's start to its merge fall.`, `Counter-signal: 🔴 findings per chunk rise.` and `Why: speed bought by skipping review shows up as defects.`
|
||||
- **Leave code health out of the README.** `~/.claude/CLAUDE.md` → "Shared goal" states it for every project, ranked first, and says when and how a README voids it. File an item to drop a README goal that restates it: the goals after it renumber, and every Moves cell and decision citing them must follow.
|
||||
- **Audience** names who depends on the project and what they may rely on.
|
||||
|
||||
+2
-2
@@ -5,7 +5,7 @@ paths:
|
||||
|
||||
# Todo items (`todo.md`)
|
||||
|
||||
- **`todo.md` is mandatory in every project, in the shape `rank_todo.py --help` shows**, which `~/.claude/bin/rank_todo.py` checks and ranks; its `--help` shows a valid file. `## Scoring` holds the formula and the bar; `## Items` is one table of every item; `## Details` holds each item's detail under its ID. Cite an item by its ID. The formula and bar are the project's own to tune.
|
||||
- **`todo.md` is mandatory in every project, in the shape `rank_todo.py --help` shows**, which `~/.claude/bin/rank_todo.py` checks and ranks; its `--help` shows a valid file. `## Scoring` holds the formula and the bar; `## Items` is one table of every item; `## Details` holds each item's detail under its ID. `## Renamed` marks each renamed release with a line such as `- 0.2.1 renamed to 0.3.0`; `rank_todo.py --help` says what a mark does. Cite an item by its ID. The formula and bar are the project's own to tune.
|
||||
- **Order items only by score and the Blocked by column.** An item's Blocked by cell lists the IDs of the items that must be done before it starts, such as `12, 14`; `rank_todo.py --help` says how it ranks them. No text in `todo.md` outside the table orders items: where an item must go first, score it so, and say why in its detail.
|
||||
- **Plan only on the project's rung or above.** loop-claude's prompt tells you when you run below it. Below it, never score or re-score an item, move it between releases, split a milestone into items, delete an item under the bar, rewrite a filed item's tagline or detail, or choose or replace an item in `docs/score-anchors.md`. Draft each new item, each change to a filed item, and each change to the anchors, instead. Before your next commit, launch one subagent to apply the drafts, score them and set their release. Launch it on the rung `CLAUDE.md`'s delegation rule gives a subagent that files or scores items. Keep the scores and releases it writes. For a security finding, launch it at once. Any rung may remove a finished item's row and detail, and score a delegated task's L. A subagent launched for another task leaves `todo.md` alone.
|
||||
- **An item's release allows the bump that semver read strictly asks for.** An item that changes what exists needs a major, or before 1.0.0 a minor. One that only adds needs a minor, and a fix a patch.
|
||||
@@ -20,7 +20,7 @@ paths:
|
||||
| 5 | — | — | irreversible: data lost for good, or a one-way door |
|
||||
|
||||
- **I's reach counts every project and session that runs the change.** A change to a hook or a tool that every session runs is I level 3, every consumer affected, even where one person uses it.
|
||||
- **Name in Moves each achieve goal in `README.md` → `## Goals` the item moves, and how far,** from 1 to 10, judged by its value to the audience in `## Audience`: `1.1 by 8, 1.2 by 5`. Name the most specific goal it moves, and a parent goal only for a move none of its sub-goals covers, never beside its own sub-goal. Leave out every maintain goal, which vetoes, except on an item marked `defect` that restores it: name that goal, and how much of it is broken. `rank_todo.py --help` says how it weighs each goal.
|
||||
- **Name in Moves each achieve goal in `README.md` → `## Goals` the item moves, and how far,** from 1 to 10, judged by its value to the audience in `## Audience`: `1.1 by 8, 1.2 by 5`. Where the item moves code health, the goal in `CLAUDE.md` → "Shared goal", name it as in `code health by 6`, unless the README voids it. Name the most specific goal it moves, and a parent goal only for a move none of its sub-goals covers, never beside its own sub-goal. Leave out every maintain goal, which vetoes, except on an item marked `defect` that restores it: name that goal, and how much of it is broken. `rank_todo.py --help` says how it weighs each goal.
|
||||
- **A table with C, A, G and Goals in place of L, E, I and Moves is in the old shape.** Reshaping it is the project's only work until done, as `CLAUDE.md` → "Working loop" says, and `rank_todo.py` says how. Until then, A is the item's value to the audience and G its value to the goals it cites.
|
||||
- **Score L, E and I against the project's anchors, and check every score against finished chunks.** Guess the scores, then run `~/.claude/bin/score-outcomes <L> <E> <I> <S>` in the project. It lists the finished items guessed nearest and the project's anchors, the shipped items its `docs/score-anchors.md` names for each level, each with what its chunk measured; then the median outcome at each guessed R and S, and how well L, E and I each order the chunks by review rounds and 🔴 findings. Compare the item with each anchor in turn: is it more or less likely to hold a defect, to let one escape, or to do damage? Give it the level whose anchors it matches; where a level has no anchor, judge by the level's words in the table above. Set S to the value guessed for the finished items whose outcome matches what you expect of this one. Keep your guess when no listed item resembles the one you are scoring.
|
||||
- **Anchor each level of L, E and I with two or three items the project shipped,** in `docs/score-anchors.md`: a table whose Level column names a level, such as `L 1`, and whose Items column lists the anchors' IDs, such as `12, 14`. Choose an L anchor whose chunk, as `score-outcomes` measured it, fits the level's words: its lines changed and the components it touched. Choose an E or I anchor by the level's words and what followed its release, since no tool measures either yet. Leave out a level no shipped item shows. Replace a level's anchors when the items scored at it turn out about ten times more likely, or ten times less likely, than its words say: to hold a defect, to let one escape, or to do damage.
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
"permissions": {
|
||||
"defaultMode": "auto",
|
||||
"additionalDirectories": [
|
||||
"~/.local/state/larv-review",
|
||||
"~/code"
|
||||
]
|
||||
},
|
||||
|
||||
@@ -45,7 +45,9 @@ A comment is prose, not code. Passes run in this order: line-level polish on cod
|
||||
|
||||
Give a reviewer without Bash the branch diff and `git ls-files`'s output in its prompt: some harnesses grant it Read alone.
|
||||
|
||||
`~/.claude/bin/larv-review` holds this section's mechanical rules: the round count, the paired ruling's base and vote count, the scoring run's trigger, and the history's format and latest places, and its count of how often seats agree. Run it in the chunk's worktree; `~/.claude/bin/larv-review --help` states each rule. On exit 1, repair what its message names and run it again; when you cannot, ask the user.
|
||||
`~/.claude/bin/larv-review` holds this section's mechanical rules: the chunk's review folder, the round count, the paired ruling's base and vote count, the scoring run's trigger, and the history's format and latest places, and its count of how often seats agree. Run it in the chunk's worktree; `~/.claude/bin/larv-review --help` states each rule. On exit 1, repair what its message names and run it again; when you cannot, ask the user.
|
||||
|
||||
**Reports.** Run `~/.claude/bin/larv-review review-folder` in the chunk's worktree: it makes the chunk's review folder and prints its path. In each prompt to an agent under `~/.claude/agents/`, name the file in that folder for its full report: `<pass>-round-<n>.md`. For a principles-auditor, use `principles-<yardstick>-round-<n>.md`. For a relaunch one rung up, add `-rerun` before `.md`. Before you answer a 🔴 or 🟡, read its entry: Grep the report for the finding's place, with the lines after it, rather than Read the whole report. rule-hook refuses a reviewer's Edit and MultiEdit, and any Write outside `~/.local/state/larv-review/`. Keep the folder after the merge: `review-replay` replays a round from the reports its prompt names.
|
||||
|
||||
**Precedent, then ask** — for the architecture pass and the full scan:
|
||||
|
||||
@@ -55,7 +57,7 @@ Give a reviewer without Bash the branch diff and `git ls-files`'s output in its
|
||||
|
||||
**Opt-out** — for the architect, the product-owner pass and the comprehension check:
|
||||
|
||||
- **Entry.** A project opts out only through a `docs/decisions.md` entry, held before the chunk began, whose title opens `review opt-out:` and names one or more of the three. The entry names the project goal that skipping them serves.
|
||||
- **Entry.** A project opts out only through a `docs/decisions.md` entry, held before the chunk began, whose title opens `review opt-out:` and names one or more of the three. The entry names the project goal that skipping them serves. A project that opts out of the comprehension check voids code health in its README, as `~/.claude/CLAUDE.md` → "Shared goal" says; `rank_todo.py` refuses its plan until it does.
|
||||
- **Skip.** Every chunk skips each reviewer the entry names, even where its trigger, a 🔀 or a due scoring run calls for it, and the chunk's summary cites the entry. Unlike a suspension, an opt-out needs no plan item to end it.
|
||||
- **Malformed.** A title naming another reviewer, or an entry naming no goal, is a finding of the pass the chunk runs, and the chunk runs every pass its trigger fires.
|
||||
|
||||
@@ -64,7 +66,7 @@ Give a reviewer without Bash the branch diff and `git ls-files`'s output in its
|
||||
- **Round.** A round is one review by a pass's reviewer: the first, each re-entry, and the rerun after the architect returns Stage 0 questions ("Architecture" below). A relaunch one rung up ("Rung up" below) stays in its round.
|
||||
- **Auto-reviewer.** The external auto-reviewer (§4) is a pass of its own, each review it posts a round.
|
||||
- **Count.** Close each round with one commit that holds the round's fixes. Title it `Answer <pass> round <n>: <k> 🔴, <m> 🟡; …`: `<pass>` is the pass's name in lower case, such as `full scan`, and `<k>` and `<m>` are the 🔴 and 🟡 findings all the round's reviewers reported. Example: `Answer stability round 1: 1 🔴, 2 🟡; flag a deleted test`. A round that changed nothing gets an empty commit (`git commit --allow-empty`). Push the commits when §4 runs next, where there is a remote. `~/.claude/bin/larv-review round-count` prints each pass's count and marks a pass at the cap. The auto-reviewer's count is the number of its reviews on the PR, less its reviews of a `Record the comprehension check:` commit.
|
||||
- **Later rounds.** From round 2, an agent under `~/.claude/agents/` reviews only the answers to its last round's findings, and each fix from another pass that re-entered its pass. Prompt it with its last round's findings verbatim, each with its answer: the fix's diff, or the reason it was dismissed. Give it each other pass's fix as `git diff <the commit before that fix> <the fix's commit>`, since the fixes may be unpushed, with the finding it answered. It reports only an answer that is plainly wrong or worse than the change it answered, so its pass converges in its second round. Other reviewers review the branch as their tool does.
|
||||
- **Later rounds.** From round 2, an agent under `~/.claude/agents/` reviews only the answers to its last round's findings, and each fix from another pass that re-entered its pass. Prompt it with the path of its last round's report and each finding's answer: the fix's diff, or the reason it was dismissed. Give it each other pass's fix as `git diff <the commit before that fix> <the fix's commit>`, since the fixes may be unpushed, with the finding it answered. It reports only an answer that is plainly wrong or worse than the change it answered, so its pass converges in its second round. Other reviewers review the branch as their tool does.
|
||||
- **Done.** A pass is done when its latest round leaves no 🔴 or 🟡 standing: none was reported, or each was shown factually wrong, declined, filed, or named under the bar per "Findings", or settled in the PR summary per "Comprehension check" → "Places", or, for the prose pass, fixed. Resolve that round's 🟢s and ❓s per "Findings" too.
|
||||
- **Cap.** A pass takes at most three rounds per chunk. Instead of a fourth, list what is open and ask the user. For the auto-reviewer, ask before the push that would summon its fourth, and hold the fixes unpushed until the answer.
|
||||
- **Answer.** A yes grants that pass one more round, after which the ask repeats; a no leaves the PR unmerged.
|
||||
@@ -78,7 +80,7 @@ Give a reviewer without Bash the branch diff and `git ls-files`'s output in its
|
||||
**Rung up.** A reviewer rules the work below standard when its report holds systems-architect's BLOCK or a finding against `standards/quality.md`. A comprehension seat does when `record-ruling` counts one of its votes as worse.
|
||||
|
||||
- **Ask.** Such a reviewer or seat may end its report asking for a rerun one rung up. Relaunch it only on the rung loop-claude's prompt names for it; where the prompt names none, the report stands.
|
||||
- **Relaunch.** Relaunch a reviewer on that rung with the same prompt and the report that asked; its report stands in place of that one, in the same round. Relaunch a seat with the same prompt alone; its line replaces the one that asked in the votes file, before `record-ruling` runs. A relaunch cannot ask again.
|
||||
- **Relaunch.** Relaunch a reviewer on that rung with the same prompt, except that it names the `-rerun` report file per "Reports", plus the path of the report that asked; its report stands in place of that one, in the same round. Relaunch a seat with the same prompt alone; its line replaces the one that asked in the votes file, before `record-ruling` runs. A relaunch cannot ask again.
|
||||
- **Escalate.** A below-standard ruling in the report that stands is escalation trigger 4 in `~/.claude/CLAUDE.md` → "Working with the codebase".
|
||||
|
||||
**Findings.** A reviewer rates each finding 🔴 must fix, 🟡 should fix, 🟢 nit, ❓ question, or 🔀 escalation naming the reviewer whose concern it is.
|
||||
@@ -100,7 +102,7 @@ Launch systems-architect: review the system as a whole entered through this chan
|
||||
|
||||
### Principles
|
||||
|
||||
Launch principles-auditor on the trigger in §3: one for the README's goals, and one per file in `~/.claude/principles/` whose `Applies to` line the project meets, judged from the README, `git ls-files` and the branch diff. A file without the line applies to every project. Unsure → launch it.
|
||||
Launch principles-auditor on the trigger in §3: one for the README's goals and code health (`~/.claude/CLAUDE.md` → "Shared goal") unless the README voids it, and one per file in `~/.claude/principles/` whose `Applies to` line the project meets, judged from the README, `git ls-files` and the branch diff. A file without the line applies to every project. Unsure → launch it.
|
||||
|
||||
### Comprehension check
|
||||
|
||||
@@ -110,7 +112,7 @@ The comprehension check records how hard the project is to read, and blocks no m
|
||||
|
||||
- **Base.** The last measured commit, which `~/.claude/bin/larv-review ruling-base` prints.
|
||||
- **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 your scratchpad, 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.
|
||||
- **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`.
|
||||
|
||||
@@ -118,7 +120,7 @@ The comprehension check records how hard the project is to read, and blocks no m
|
||||
- **Second run.** Where `needs-scoring-run` printed that the chunk `leaves release … with no plan item`, launch the same four seats afresh on the same head. Their scores file's first line is `<PR or branch> rerun at <commit>`. Record it with the same `record-scoring` command.
|
||||
- **Agreement.** After the second run, run `~/.claude/bin/larv-review agreement` and put its counts in the summary. On `Assumption fails:`, ask the user whether to keep the paired ruling or change the decision `review: the comprehension check records …`. Record the answer as a decision in the repo whose history was counted, with the counts that led to the ask. A later run asks again only when the rulings' rate falls, or the runs' rate rises, against the recorded counts.
|
||||
|
||||
**Record.** `docs/comprehension-history.md` keeps every paired ruling and scoring run, which `larv-review` appends; never edit one. Commit what it appends in one commit titled `Record the comprehension check: …`, push it, and wait for the forge's checks (§4 step 4), not for an auto-review; it re-enters no pass. Resolve a merge conflict in the file by putting the default branch's entries first. Put each ruling with its base and votes, and each run's five scores, in the summary.
|
||||
**Record.** `docs/comprehension-history.md` keeps every paired ruling and scoring run, which `larv-review` appends; never edit one. Commit what it appends, with the `todo.md` that `record-scoring` re-ranks, in one commit titled `Record the comprehension check: …`, push it, and wait for the forge's checks (§4 step 4), not for an auto-review; it re-enters no pass. Resolve a merge conflict in the file by putting the default branch's entries first. Put each ruling with its base and votes, and each run's five scores, in the summary.
|
||||
|
||||
**Places.** Give systems-architect and stability-reviewer what `~/.claude/bin/larv-review places` prints: the places seats found hard since the newest scored commit. Ask each to report, as a 🟡, each of those places the change touches without making it easier to read, matching a place by its path and the function or section it names, since its line may have moved. Fix such a 🟡, or say in the PR summary why not; that reason settles it in place of a decline's record.
|
||||
|
||||
@@ -158,7 +160,7 @@ 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 README goals: 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.
|
||||
1. Read the finished PR against the README goals and code health, unless the README 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. Aligned, every pass done and everything green → **merge**. Follow the repo's merge method (`AGENTS.md`; ff-only where that is the convention). A repo withholds this in its `AGENTS.md` → leave the PR ready and unmerged, and say which line withheld it.
|
||||
4. Merged → remove the chunk's items from `todo.md` per `~/.claude/CLAUDE.md` → "Working loop".
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
Words: `~/.claude/CLAUDE.md` → "Vocabulary".
|
||||
|
||||
A reviewer reads and reports; it edits nothing. Read `docs/decisions.md` and `todo.md` first: a finding declined or disproved in `docs/decisions.md` or in a comment at the code it concerns, or filed in `todo.md`, is not raised again, unless the decline works against a goal or a technical principle and names no `todo.md` item ending it.
|
||||
A reviewer reads and reports; it edits nothing. It writes no file but its report, except the scratch files that a reviewer holding Bash makes with Bash. Read `docs/decisions.md` and `todo.md` first: a finding declined or disproved in `docs/decisions.md` or in a comment at the code it concerns, or filed in `todo.md`, is not raised again, unless the decline works against a goal or a technical principle and names no `todo.md` item ending it.
|
||||
|
||||
## Severity
|
||||
|
||||
@@ -26,9 +26,21 @@ A review's first line, derived from the findings:
|
||||
|
||||
Where your report holds a finding against `~/.claude/skills/larv-review/standards/quality.md`, or you are systems-architect and return BLOCK, you may end it with the line `Rerun one rung up` when you want a more capable reviewer to check that ruling.
|
||||
|
||||
## Report
|
||||
|
||||
Write your full report with the Write tool to the file your prompt names. The file is the worker's input, which it searches for each finding's entry, so write it even where your harness says to return findings directly. It holds the verdict, then every finding with its place, its evidence and its fix, as your agent file shapes them. Then return only:
|
||||
|
||||
- the verdict line
|
||||
- one line per finding, in this order: its severity mark, its place, and what is wrong, in one sentence. Where the finding breaks `standards/quality.md` or a file under `~/.claude/principles/`, end the line with that file's name. For a 🔀, end it with the reviewer it names. Example: ``🟡 `bin/example.py:42` `parse`: an empty line raises IndexError (technical-principles.md)``
|
||||
- for stability-reviewer, whether the tests passed, and at which commit
|
||||
- `Rerun one rung up`, where your report ends with it
|
||||
- the report's path
|
||||
|
||||
A prompt that names no file, or a Write that fails, gets the full report as your reply.
|
||||
|
||||
## Rounds
|
||||
|
||||
- Handed neither earlier findings nor another pass's fix: surface everything.
|
||||
- Handed an earlier round's findings, each with its fix or the reason it was dismissed: review only those answers. Check each fix — re-run the scenario, never trust the claim — and each dismissal's reason. Report only a fix or a dismissal that is plainly wrong, or worse than the change it answered; a fix you would have written differently is not a finding.
|
||||
- Handed an earlier round's report, with each finding's fix or the reason it was dismissed: review only those answers. Check each fix — re-run the scenario, never trust the claim — and each dismissal's reason. Report only a fix or a dismissal that is plainly wrong, or worse than the change it answered; a fix you would have written differently is not a finding.
|
||||
- Handed a fix from another pass: review its diff as a first round would, limited to its lines.
|
||||
- Handed a report that asked to `Rerun one rung up`: confirm or dismiss each of its findings, with a reason, then review the rest of what your prompt scopes, as the round you rerun would. Do not ask again.
|
||||
|
||||
@@ -6,131 +6,92 @@
|
||||
|
||||
`Bar = 0.1`
|
||||
|
||||
`Next ID = 179`
|
||||
`Next ID = 199`
|
||||
|
||||
## Items
|
||||
|
||||
| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |
|
||||
|---|---|---|---|---|---|---|---|---|---|---|---|
|
||||
| 178 | 0.2.0 | | defect | **Step the worker one rung up as the judge interrupts, when the interrupted run also asked loop-claude for a higher rung and the judge finds the escalation trigger that run cites.** | 2 | 2 | 2 | 4 | 4 | 1.3 by 3, 1.1 by 3 | 8.2 |
|
||||
| 168 | 0.2.0 | | | **Have the human answer an interrupt on loop-claude's terminal and resume the worker headless with the answer, opening the interactive session only when they ask for it.** | 4 | 2 | 3 | 7 | 5 | 1.5 by 8 | 1.8 |
|
||||
| 73 | 0.2.0 | | | **Have each reviewer write its full report to a file and return the worker only its findings' one-line summaries.** | 3 | 2 | 3 | 6 | 5 | 1.4 by 4 | 1.1 |
|
||||
| 159 | 0.2.0 | | decision | **Run each review pass on the lowest rung that a replay of its archived rounds shows finding every 🔴 and 🟡 the project's rung finds, even below the worker's rung.** | 4 | 2 | 3 | 7 | 6 | 1.4 by 7 | 1.1 |
|
||||
| 80 | 0.3.0 | | defect | **State in README → Install that every machine taking this checkout must be a sandbox, as `settings.json`'s auto mode assumes.** | 1 | 2 | 1 | 2 | 1 | 2 by 4 | 17.5 |
|
||||
| 21 | 0.3.0 | | defect | **Give `settings.json`'s model one writer, and sort its keys.** | 3 | 3 | 3 | 7 | 3 | 2 by 5 | 13.7 |
|
||||
| 29 | 0.3.0 | | | **Make the contributor a standing member of every project's audience, unless its `## Audience` says maintainability does not matter.** | 2 | 2 | 3 | 5 | 2 | 1.1 by 5, 1.4 by 5 | 13.7 |
|
||||
| 119 | 0.3.0 | | | **Retitle the comprehension-floor decision so it says a chunk lifting a project towards the floor works first on its lowest-scoring dimension, and that the floor blocks nothing.** | 1 | 2 | 1 | 2 | 1 | 1.1 by 4, 1.4 by 4 | 13.1 |
|
||||
| 127 | 0.3.0 | | | **Define seat, place, paired ruling, scoring run and the judge's records in `CLAUDE.md` → "Vocabulary".** | 1 | 2 | 3 | 4 | 1 | 1.1 by 4, 1.4 by 4 | 13.1 |
|
||||
| 129 | 0.3.0 | | | **Explain `bin/rule_hook/rules.py`'s `OVERRIDE` pattern beside it: why the reason is lazy, what the lookahead splits and why `-->` is stripped.** | 1 | 2 | 1 | 2 | 1 | 1.1 by 4, 1.4 by 4 | 13.1 |
|
||||
| 114 | 0.3.0 | | decision | **Run git through `git_repo.py` in `rule_hook`, `metric_bench`, `reading_cost`, `stability_replay` and `loop_claude`, keeping rule-hook's guards as an option, so one module owns how a tool runs git.** | 3 | 1 | 3 | 5 | 4 | 1.1 by 9, 1.4 by 9 | 12.3 |
|
||||
| 120 | 0.3.0 | | | **Rewrite larv-review §3's "Round cap" and "Re-entry" as one table that says, for each kind of fix, which passes rerun and what a round reviews.** | 2 | 2 | 3 | 5 | 4 | 1.1 by 6, 1.2 by 6, 1.4 by 6 | 11.9 |
|
||||
| 49 | 0.3.0 | | principle | **Check that `AGENTS.md` lists exactly the titles of `docs/decisions.md`.** | 1 | 1 | 1 | 1 | 2 | 1.1 by 6 | 10.9 |
|
||||
| 117 | 0.3.0 | | | **Give `todo_table.items` one way to say a plan has no items table, so no caller tells it from an empty plan by truthiness.** | 1 | 1 | 3 | 3 | 2 | 1.1 by 4, 1.4 by 4 | 10.9 |
|
||||
| 126 | 0.3.0 | | | **State when work has landed towards a release once, in `bin/larv_review/plan.py`, and have larv-review's help point to it.** | 1 | 2 | 1 | 2 | 2 | 1.1 by 4, 1.4 by 4 | 10.9 |
|
||||
| 131 | 0.3.0 | | | **Describe the transcript archive's layout in `bin/transcript_archive/`, which owns it, and have loop-claude's help point there.** | 1 | 2 | 1 | 2 | 2 | 1.1 by 4, 1.4 by 4 | 10.9 |
|
||||
| 133 | 0.3.0 | | | **Show, beside `bin/rule_hook/override_log.py`'s `this_chunks`, one example per case it decides: an amended or rebased commit, a renamed branch, and a commit on the default branch.** | 1 | 2 | 1 | 2 | 2 | 1.1 by 4, 1.4 by 4 | 10.9 |
|
||||
| 134 | 0.3.0 | | | **Name in `bin/shell_command.py`'s `segments` the shell forms it does not parse, so a caller knows what it misses.** | 1 | 2 | 1 | 2 | 2 | 1.1 by 4, 1.4 by 4 | 10.9 |
|
||||
| 154 | 0.3.0 | | defect | **Have `bin/shell_command.py`'s `segments` keep a command's words together across a redirect, so `git > out commit` reads as one git commit.** | 1 | 1 | 3 | 3 | 2 | 1.1 by 6 | 10.9 |
|
||||
| 157 | 0.3.0 | | | **Split `docs/decisions.md` → `todo.md: one table of items …`'s 2026-10-02 paragraph into one paragraph per choice.** | 1 | 2 | 1 | 2 | 2 | 1.1 by 4, 1.4 by 4 | 10.9 |
|
||||
| 106 | 0.3.0 | | | **Make larv-review's "Do not over-read a clean result" cite a rule that says Renovate or Dependabot owns dependency CVEs, or drop the citation.** | 1 | 2 | 1 | 2 | 1 | 1.1 by 5 | 10.9 |
|
||||
| 167 | 0.3.0 | | | **Refuse a `/security-review` or `/claude-security` Skill call below the project's rung, as rule-hook refuses such an Agent call.** | 3 | 2 | 3 | 6 | 2 | 1.1 by 4 | 7.3 |
|
||||
| 176 | 0.3.0 | | | **Give `loop-claude --help`'s routing paragraph sub-headings, such as Routing, Judge rung and Routing figures, so a reader finds a rule without reading 39 lines.** | 1 | 2 | 1 | 2 | 2 | 1.1 by 3, 1.4 by 2 | 7.3 |
|
||||
| 172 | 0.3.0 | | | **Name the project's rung `project` across `bin/loop_claude`, in place of `anchor`, as `bin/model_routing/ladder.py` names it.** | 2 | 1 | 3 | 4 | 3 | 1.1 by 3, 1.4 by 3 | 6.2 |
|
||||
| 82 | 0.3.0 | | principle | **Sort `AGENTS.md`'s decision titles and `docs/decisions.md`'s entries by title.** | 2 | 2 | 1 | 3 | 4 | 1.1 by 4, 1.4 by 4 | 5.5 |
|
||||
| 119 | 0.3.0 | | | **Retitle the comprehension-floor decision so it says a chunk lifting a project towards the floor works first on its lowest-scoring dimension, and that the floor blocks nothing.** | 1 | 2 | 1 | 2 | 1 | code health by 4, 1.4 by 4 | 35.1 |
|
||||
| 127 | 0.3.0 | | | **Define seat, place, paired ruling, scoring run and the judge's records in `CLAUDE.md` → "Vocabulary".** | 1 | 2 | 3 | 4 | 1 | code health by 4, 1.4 by 4 | 35.1 |
|
||||
| 129 | 0.3.0 | | | **Explain `bin/rule_hook/rules.py`'s `OVERRIDE` pattern beside it: why the reason is lazy, what the lookahead splits and why `-->` is stripped.** | 1 | 2 | 1 | 2 | 1 | code health by 4, 1.4 by 4 | 35.1 |
|
||||
| 114 | 0.3.0 | | decision | **Run git through `git_repo.py` in `rule_hook`, `metric_bench`, `reading_cost`, `review_replay` and `loop_claude`, keeping rule-hook's guards as an option, so one module owns how a tool runs git.** | 3 | 1 | 3 | 5 | 4 | code health by 9, 1.4 by 9 | 32.9 |
|
||||
| 117 | 0.3.0 | | | **Give `todo_table.items` one way to say a plan has no items table, so no caller tells it from an empty plan by truthiness.** | 1 | 1 | 3 | 3 | 2 | code health by 4, 1.4 by 4 | 29.2 |
|
||||
| 126 | 0.3.0 | | | **State when work has landed towards a release once, in `bin/larv_review/plan.py`, and have larv-review's help point to it.** | 1 | 2 | 1 | 2 | 2 | code health by 4, 1.4 by 4 | 29.2 |
|
||||
| 131 | 0.3.0 | | | **Describe the transcript archive's layout in `bin/transcript_archive/`, which owns it, and have loop-claude's help point there.** | 1 | 2 | 1 | 2 | 2 | code health by 4, 1.4 by 4 | 29.2 |
|
||||
| 133 | 0.3.0 | | | **Show, beside `bin/rule_hook/override_log.py`'s `this_chunks`, one example per case it decides: an amended or rebased commit, a renamed branch, and a commit on the default branch.** | 1 | 2 | 1 | 2 | 2 | code health by 4, 1.4 by 4 | 29.2 |
|
||||
| 134 | 0.3.0 | | | **Name in `bin/shell_command.py`'s `segments` the shell forms it does not parse, so a caller knows what it misses.** | 1 | 2 | 1 | 2 | 2 | code health by 4, 1.4 by 4 | 29.2 |
|
||||
| 157 | 0.3.0 | | | **Split `docs/decisions.md` → `todo.md: one table of items …`'s 2026-10-02 paragraph into one paragraph per choice.** | 1 | 2 | 1 | 2 | 2 | code health by 4, 1.4 by 4 | 29.2 |
|
||||
| 80 | 0.3.0 | | defect | **State in README → Install that every machine taking this checkout must be a sandbox, as `settings.json`'s auto mode assumes.** | 1 | 2 | 1 | 2 | 1 | 2 by 4 | 28.7 |
|
||||
| 120 | 0.3.0 | | | **Rewrite larv-review §3's "Round cap" and "Re-entry" as one table that says, for each kind of fix, which passes rerun and what a round reviews.** | 2 | 2 | 3 | 5 | 4 | code health by 6, 1.2 by 6, 1.4 by 6 | 26.0 |
|
||||
| 21 | 0.3.0 | | defect | **Give `settings.json`'s model one writer, and sort its keys.** | 3 | 3 | 3 | 7 | 3 | 2 by 5 | 22.5 |
|
||||
| 176 | 0.3.0 | | | **Give `loop-claude --help`'s routing paragraph sub-headings, such as Routing, Judge rung and Routing figures, so a reader finds a rule without reading 39 lines.** | 1 | 2 | 1 | 2 | 2 | code health by 3, 1.4 by 2 | 20.6 |
|
||||
| 172 | 0.3.0 | | | **Name the project's rung `project` across `bin/loop_claude`, in place of `anchor`, as `bin/model_routing/ladder.py` names it.** | 2 | 1 | 3 | 4 | 3 | code health by 3, 1.4 by 3 | 16.5 |
|
||||
| 190 | 0.3.0 | | | **Rewrite the `docs/decisions.md` entries `todo.md: one table …` and `loop-claude: a judge decides …` as the current state, so a reader no longer replays superseded paragraphs to learn what holds.** | 2 | 2 | 1 | 3 | 3 | code health by 3, 1.4 by 2 | 15.5 |
|
||||
| 82 | 0.3.0 | | principle | **Sort `AGENTS.md`'s decision titles and `docs/decisions.md`'s entries by title.** | 2 | 2 | 1 | 3 | 4 | code health by 4, 1.4 by 4 | 14.6 |
|
||||
| 29 | 0.3.0 | | | **Make the contributor a standing member of every project's audience, unless its README voids code health.** | 2 | 2 | 3 | 5 | 2 | 1.1 by 5, 1.4 by 5 | 13.7 |
|
||||
| 106 | 0.3.0 | | | **Make larv-review's "Do not over-read a clean result" cite a rule that says Renovate or Dependabot owns dependency CVEs, or drop the citation.** | 1 | 2 | 1 | 2 | 1 | 1.1 by 5 | 8.4 |
|
||||
| 49 | 0.3.0 | | principle | **Check that `AGENTS.md` lists exactly the titles of `docs/decisions.md`.** | 1 | 1 | 1 | 1 | 2 | 1.1 by 6 | 8.4 |
|
||||
| 154 | 0.3.0 | | defect | **Have `bin/shell_command.py`'s `segments` keep a command's words together across a redirect, so `git > out commit` reads as one git commit.** | 1 | 1 | 3 | 3 | 2 | 1.1 by 6 | 8.4 |
|
||||
| 162 | 0.3.0 | | owner | **Script each step that 0.2.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.** | 2 | 2 | 1 | 3 | 3 | 1.4 by 4, 1.5 by 4 | 7.8 |
|
||||
| 175 | 0.3.0 | | | **Compare the first five chunks loop-claude starts with `chunk-preflight` against the five before them, and file an item where the preflight did not pay off.** | 1 | 2 | 1 | 2 | 2 | 1.4 by 3, 1.5 by 3 | 7.8 |
|
||||
| 183 | 0.3.0 | | | **Merge the two 2026-10-13 paragraphs of `docs/decisions.md` → `loop-claude: a judge decides each interrupt …` into one.** | 1 | 1 | 1 | 1 | 1 | code health by 1 | 7.2 |
|
||||
| 184 | 0.3.0 | | | **Rewrap the lines of `loop-claude --help` that run past the column the rest of it wraps at.** | 1 | 1 | 1 | 1 | 1 | code health by 1 | 7.2 |
|
||||
| 186 | 0.3.0 | | | **Point every file a session parks outside its checkout, such as the comprehension panel's detached worktree and a build probe's output, at a folder a headless session has, since loop-claude's sessions have no scratchpad.** | 1 | 2 | 2 | 3 | 2 | 1.1 by 3, 1.5 by 2 | 6.8 |
|
||||
| 198 | 0.3.0 | | decision | **Count, per finished chunk, the findings that arose from misreading code that had already shipped, so code health's counter-signal shows.** | 3 | 2 | 2 | 5 | 5 | code health by 3, 1.1 by 2 | 6.2 |
|
||||
| 167 | 0.3.0 | | | **Refuse a `/security-review` or `/claude-security` Skill call below the project's rung, as rule-hook refuses such an Agent call.** | 3 | 2 | 3 | 6 | 2 | 1.1 by 4 | 5.6 |
|
||||
| 173 | 0.3.0 | | | **Have rule-hook's `todo-rank-check` run a worktree's own `bin/rank_todo.py` when the worktree is of this repo, so a branch that changes `todo.md`'s shape commits without an override.** | 2 | 1 | 3 | 4 | 2 | 1.1 by 2, 1.4 by 2 | 5.5 |
|
||||
| 162 | 0.3.0 | | owner | **Script each step that 0.2.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.** | 2 | 2 | 1 | 3 | 3 | 1.4 by 4, 1.5 by 4 | 4.9 |
|
||||
| 175 | 0.3.0 | | | **Compare the first five chunks loop-claude starts with `chunk-preflight` against the five before them, and file an item where the preflight did not pay off.** | 1 | 2 | 1 | 2 | 2 | 1.4 by 3, 1.5 by 3 | 4.9 |
|
||||
| 177 | 0.3.0 | | | **Move the next chunk's pick, from `LastCut` and `standing` to `chunk_item` and `default_plan`, into one module named for it, so `git_repo` only runs git and `todo_table` only parses the plan.** | 3 | 1 | 3 | 5 | 4 | 1.1 by 4 | 3.6 |
|
||||
| 171 | 0.3.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 | 3.2 |
|
||||
| 165 | 0.3.0 | | | **Make this repo's tests assert the facts a prompt or help text carries in place of its sentences, and drop the tests that scan source or assert a constant.** | 3 | 2 | 1 | 4 | 5 | 1.1 by 4, 1.4 by 3 | 3.0 |
|
||||
| 169 | 0.3.0 | | | **Have rule-hook's `todo-rank-check` catch a `todo.md` that the same Bash call edits and then commits.** | 3 | 1 | 3 | 5 | 3 | 1.1 by 2 | 2.7 |
|
||||
| 174 | 0.3.0 | | | **In a chunk no item routed, ask the worker to name each todo.md item it takes, with its L and E + I, so loop-claude can route on an item it takes in.** | 1 | 2 | 3 | 4 | 2 | 1.1 by 1 | 1.8 |
|
||||
| 122 | 0.4.0 | | | **Assemble the judge's prompt in `bin/loop_claude/cycle/judge.py`, importing only wording the worker also sees, and call the worker "the worker" in it.** | 2 | 2 | 3 | 5 | 3 | 1.1 by 5, 1.4 by 5 | 10.3 |
|
||||
| 171 | 0.3.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 | 4.0 |
|
||||
| 196 | 0.3.0 | | decision | **Replay the architecture, principles, overrides and product-owner passes with `review-replay` on Opus 5.5 projects, record each run in the review-replay routing decision, and add any rung a run qualifies to `REPLAYED`.** | 2 | 2 | 3 | 5 | 2 | 1.4 by 3 | 4.0 |
|
||||
| 181 | 0.3.0 | | principle | **Have the test of a quoted answer's step-up assert the stepped rung's facts as literals, not through `prompts.rungs_held`.** | 1 | 1 | 1 | 1 | 1 | 1.1 by 2 | 3.4 |
|
||||
| 192 | 0.3.0 | | principle | **Sort `.gitignore`'s allowlist block, from `!.claude/` to `!workflow-bench/test_review_git.py`, by code point, so rule-hook's `ignorefile-sorted` checks later edits to it again.** | 1 | 1 | 1 | 1 | 1 | 1.1 by 2 | 3.4 |
|
||||
| 193 | 0.3.0 | | | **Narrow `readme_goals`'s mark to `Mark` by a typed lookup in place of `typing.cast`, so a mark added to the regex but not the lookup fails at run time, and one added to the lookup but not `Mark` fails mypy.** | 1 | 1 | 3 | 3 | 1 | 1.1 by 2 | 3.4 |
|
||||
| 194 | 0.3.0 | | | **Make `test_waits_out_a_usage_limit_which_ends_a_run_of_failures` expect a usage-limit wait independent of the wall-clock time that passes during the run.** | 1 | 1 | 1 | 1 | 1 | 1.1 by 2 | 3.4 |
|
||||
| 187 | 0.3.0 | | | **Count the tokens a worker spends reading reviewers' reports, so goal 1.4's signal shows whether report files lowered what a review costs the worker's context.** | 2 | 2 | 1 | 3 | 3 | 1.4 by 3 | 3.0 |
|
||||
| 165 | 0.3.0 | | | **Make this repo's tests assert the facts a prompt or help text carries in place of its sentences, and drop the tests that scan source or assert a constant.** | 3 | 2 | 1 | 4 | 5 | 1.1 by 4, 1.4 by 3 | 2.9 |
|
||||
| 182 | 0.3.0 | | | **Let the human edit an interrupt's answer with the arrow keys, so Left moves the cursor instead of typing ^[[D into the answer.** | 2 | 2 | 1 | 3 | 2 | 1.1 by 2 | 2.8 |
|
||||
| 155 | 0.3.0 | | | **Lower the reading cost of the files a chunk reads most before its first commit.** | 3 | 2 | 2 | 5 | 5 | 1.4 by 6 | 2.4 |
|
||||
| 169 | 0.3.0 | | | **Have rule-hook's `todo-rank-check` catch a `todo.md` that the same Bash call edits and then commits.** | 3 | 1 | 3 | 5 | 3 | 1.1 by 2 | 2.1 |
|
||||
| 197 | 0.3.0 | | | **Let the human edit what they type at loop-claude's terminal questions with the arrow keys, so Left moves the cursor in place of printing `^[[D`.** | 1 | 2 | 3 | 4 | 1 | 1.5 by 1 | 1.5 |
|
||||
| 174 | 0.3.0 | | | **In a chunk no item routed, ask the worker to name each todo.md item it takes, with its L and E + I, so loop-claude can route on an item it takes in.** | 1 | 2 | 3 | 4 | 2 | 1.1 by 1 | 1.4 |
|
||||
| 122 | 0.4.0 | | | **Assemble the judge's prompt in `bin/loop_claude/cycle/judge.py`, importing only wording the worker also sees, and call the worker "the worker" in it.** | 2 | 2 | 3 | 5 | 3 | code health by 5, 1.4 by 5 | 27.4 |
|
||||
| 130 | 0.4.0 | | | **Move the vote counting out of `bin/larv_review/ruling.py`'s `votes`, so reading a votes file decides nothing.** | 2 | 1 | 2 | 3 | 3 | code health by 4, 1.4 by 4 | 21.9 |
|
||||
| 125 | 0.4.0 | | decision | **Give "record", "outcome" and "places" one meaning each across `bin/`, and rename `bin/larv_review/git.py` by what it holds.** | 3 | 1 | 3 | 5 | 5 | code health by 9, 1.4 by 9 | 19.7 |
|
||||
| 137 | 0.4.0 | | | **Archive a chunk's route as a record loop-claude reads back field by field, in place of the `Worker:` prose `ROUTED` parses, and name `stepped` and the judge's `bundled` by what they do.** | 4 | 2 | 3 | 7 | 4 | code health by 4, 1.4 by 4 | 14.6 |
|
||||
| 139 | 0.4.0 | | | **Split `bin/routing_figures/measure.py` by concern, and keep the figures' measured cycle and each raised call as fields loop-claude reads back, not as the prose it renders.** | 3 | 1 | 2 | 4 | 5 | code health by 5, 1.4 by 5 | 11.0 |
|
||||
| 170 | 0.4.0 | | decision | **Re-tune `WORKER_STEPS` and `REVIEW_STEPS` once 10 chunks have shipped under them, from how well L, E and I order their review rounds and 🔴 findings.** | 2 | 2 | 3 | 5 | 2 | 1.1 by 3, 1.4 by 5 | 10.9 |
|
||||
| 158 | 0.4.0 | | decision | **Measure the fixed cost of a chunk from loop-claude's archive, in tokens and hours against its items' S, and set F in `Score = 100 * V / (2**S + F)` to it.** | 2 | 2 | 1 | 3 | 3 | 1.1 by 5, 1.4 by 5 | 10.3 |
|
||||
| 170 | 0.4.0 | | decision | **Re-tune `WORKER_STEPS` and `REVIEW_STEPS` once 10 chunks have shipped under them, from how well L, E and I order their review rounds and 🔴 findings.** | 2 | 2 | 3 | 5 | 2 | 1.1 by 3, 1.4 by 5 | 10.0 |
|
||||
| 116 | 0.4.0 | | | **Report L by the share of chunks with a 🔴, once 10 chunks that each shipped one item record finding counts and most record no 🔴.** | 1 | 1 | 2 | 2 | 2 | 1.1 by 5 | 9.1 |
|
||||
| 121 | 0.4.0 | | | **Check that `bin/round_titles.py`'s `PASSES` lists exactly the passes of larv-review §3's table.** | 1 | 1 | 1 | 1 | 2 | 1.1 by 5 | 9.1 |
|
||||
| 112 | 0.4.0 | | | **Count an item as shipped only where its chunk built it, so an item a chunk dropped from the plan gets no outcome.** | 3 | 2 | 2 | 5 | 3 | 1.1 by 6 | 8.2 |
|
||||
| 130 | 0.4.0 | | | **Move the vote counting out of `bin/larv_review/ruling.py`'s `votes`, so reading a votes file decides nothing.** | 2 | 1 | 2 | 3 | 3 | 1.1 by 4, 1.4 by 4 | 8.2 |
|
||||
| 125 | 0.4.0 | | decision | **Give "record", "outcome" and "places" one meaning each across `bin/`, and rename `bin/larv_review/git.py` by what it holds.** | 3 | 1 | 3 | 5 | 5 | 1.1 by 9, 1.4 by 9 | 7.4 |
|
||||
| 81 | 0.4.0 | | principle | **Have `workflow-bench/bench.py` return each run's failure as a value, so one failed clone does not hide the later runs' results.** | 1 | 2 | 1 | 2 | 2 | 1.1 by 4 | 7.3 |
|
||||
| 102 | 0.4.0 | | | **Give loop-claude's retry delay an environment override, so the black-box test stops replacing `time.sleep` through `sitecustomize`.** | 1 | 1 | 2 | 2 | 2 | 1.1 by 4 | 7.3 |
|
||||
| 66 | 0.4.0 | | principle | **Hold systems-architect's method thresholds only while the comprehension panel finds the flagged code hard.** | 2 | 2 | 3 | 5 | 3 | 1.1 by 5 | 6.8 |
|
||||
| 101 | 0.4.0 | | principle | **Have `larv_review/record.py`'s `read_seats` take the time, the commit check and the history as inputs, so it parses and decides without effects.** | 2 | 1 | 2 | 3 | 3 | 1.1 by 5 | 6.8 |
|
||||
| 111 | 0.4.0 | | | **Measure the chunks of a project that merges by squash or fast-forward, which `score-outcomes` skips today.** | 3 | 2 | 2 | 5 | 3 | 1.1 by 5 | 6.8 |
|
||||
| 116 | 0.4.0 | | | **Report L by the share of chunks with a 🔴, once 10 chunks that each shipped one item record finding counts and most record no 🔴.** | 1 | 1 | 2 | 2 | 2 | 1.1 by 5 | 7.0 |
|
||||
| 121 | 0.4.0 | | | **Check that `bin/round_titles.py`'s `PASSES` lists exactly the passes of larv-review §3's table.** | 1 | 1 | 1 | 1 | 2 | 1.1 by 5 | 7.0 |
|
||||
| 113 | 0.4.0 | | | **Compute an item's S from the code it names, where it names any, and show it beside the finished items `score-outcomes` lists.** | 3 | 2 | 2 | 5 | 4 | 1.1 by 5, 1.4 by 5 | 6.8 |
|
||||
| 137 | 0.4.0 | | | **Archive a chunk's route as a record loop-claude reads back field by field, in place of the `Worker:` prose `ROUTED` parses, and name `stepped` and the judge's `bundled` by what they do.** | 4 | 2 | 3 | 7 | 4 | 1.1 by 4, 1.4 by 4 | 5.5 |
|
||||
| 112 | 0.4.0 | | | **Count an item as shipped only where its chunk built it, so an item a chunk dropped from the plan gets no outcome.** | 3 | 2 | 2 | 5 | 3 | 1.1 by 6 | 6.3 |
|
||||
| 81 | 0.4.0 | | principle | **Have `workflow-bench/bench.py` return each run's failure as a value, so one failed clone does not hide the later runs' results.** | 1 | 2 | 1 | 2 | 2 | 1.1 by 4 | 5.6 |
|
||||
| 102 | 0.4.0 | | | **Give loop-claude's retry delay an environment override, so the black-box test stops replacing `time.sleep` through `sitecustomize`.** | 1 | 1 | 2 | 2 | 2 | 1.1 by 4 | 5.6 |
|
||||
| 66 | 0.4.0 | | principle | **Hold systems-architect's method thresholds only while the comprehension panel finds the flagged code hard.** | 2 | 2 | 3 | 5 | 3 | 1.1 by 5 | 5.3 |
|
||||
| 101 | 0.4.0 | | principle | **Have `larv_review/record.py`'s `read_seats` take the time, the commit check and the history as inputs, so it parses and decides without effects.** | 2 | 1 | 2 | 3 | 3 | 1.1 by 5 | 5.3 |
|
||||
| 111 | 0.4.0 | | | **Measure the chunks of a project that merges by squash or fast-forward, which `score-outcomes` skips today.** | 3 | 2 | 2 | 5 | 3 | 1.1 by 5 | 5.3 |
|
||||
| 110 | 0.4.0 | | | **Count, for each finished chunk, the later changes that fixed code it wrote, and show them beside its guessed E.** | 3 | 2 | 2 | 5 | 5 | 1.1 by 6, 1.4 by 6 | 4.9 |
|
||||
| 139 | 0.4.0 | | | **Split `bin/routing_figures/measure.py` by concern, and keep the figures' measured cycle and each raised call as fields loop-claude reads back, not as the prose it renders.** | 3 | 1 | 2 | 4 | 5 | 1.1 by 5, 1.4 by 5 | 4.1 |
|
||||
| 149 | 0.4.0 | | decision | **Fill each release by priority up to a capacity it states, in place of the bar, and move what does not fit to a later release.** | 4 | 2 | 3 | 7 | 5 | 1.1 by 7 | 3.8 |
|
||||
| 12 | 0.5.0 | | | **Run the test suite in CI on every PR, or record in `docs/decisions.md` why the local run is enough.** | 3 | 2 | 1 | 4 | 4 | 1.1 by 6 | 5.5 |
|
||||
| 105 | 0.5.0 | | decision | **Compare review rounds per pass and reading cost for the five chunks before and after the `worker:` decision moved the principles out of the worker's context, and file an item if either rose.** | 1 | 2 | 1 | 2 | 2 | 1.4 by 6 | 5.5 |
|
||||
| 135 | 0.5.0 | | | **Fingerprint only the modules loop-claude imports, so editing another tool's code no longer reloads a running loop.** | 2 | 2 | 3 | 5 | 3 | 1.1 by 4 | 5.5 |
|
||||
| 68 | 0.5.0 | | principle | **Test `workflow-bench/compare.py`'s blinding and `bench.py`'s run plan.** | 2 | 1 | 1 | 2 | 4 | 1.1 by 5 | 4.6 |
|
||||
| 4 | 0.5.0 | | | **Name each chunk's archive folder by the chunk's start time, so `<key>/` lists chunks in the order they ran.** | 3 | 2 | 3 | 6 | 3 | 1.1 by 3 | 4.1 |
|
||||
| 59 | 0.5.0 | | | **Bound a run of unfinished verdicts on one chunk, so a worker and judge that disagree cannot cycle unattended without end.** | 2 | 1 | 3 | 4 | 3 | 1.4 by 6 | 4.1 |
|
||||
| 123 | 0.5.0 | | | **Have `bin/comprehension_history.py` parse each history entry once into seats, votes and places, so `latest_places`, `worse_places` and `worse_votes` neither depend on table order nor split a label to find a seat.** | 2 | 1 | 2 | 3 | 5 | 1.1 by 5, 1.4 by 5 | 4.1 |
|
||||
| 132 | 0.5.0 | | | **Lift each dimension still under the comprehension floor after release 0.2.0's scoring run, at the places that run names.** | 3 | 2 | 2 | 5 | 5 | 1.1 by 5, 1.4 by 5 | 4.1 |
|
||||
| 124 | 0.5.0 | | decision | **Group the shared modules at `bin/`'s root into packages named by purpose, so the root holds only launchers and stand-alone tools.** | 4 | 1 | 3 | 6 | 6 | 1.1 by 9, 1.4 by 9 | 4.1 |
|
||||
| 156 | 0.5.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 | 3.6 |
|
||||
| 155 | 0.5.0 | | | **Lower the reading cost of the files a chunk reads most before its first commit.** | 3 | 2 | 2 | 5 | 5 | 1.4 by 6 | 1.6 |
|
||||
| 149 | 0.4.0 | | decision | **Fill each release by priority up to a capacity it states, in place of the bar, and move what does not fit to a later release.** | 4 | 2 | 3 | 7 | 5 | 1.1 by 7 | 3.0 |
|
||||
| 123 | 0.5.0 | | | **Have `bin/comprehension_history.py` parse each history entry once into seats, votes and places, so `latest_places`, `worse_places` and `worse_votes` neither depend on table order nor split a label to find a seat.** | 2 | 1 | 2 | 3 | 5 | code health by 5, 1.4 by 5 | 11.0 |
|
||||
| 124 | 0.5.0 | | decision | **Group the shared modules at `bin/`'s root into packages named by purpose, so the root holds only launchers and stand-alone tools.** | 4 | 1 | 3 | 6 | 6 | code health by 9, 1.4 by 9 | 11.0 |
|
||||
| 132 | 0.5.0 | | | **Lift each dimension still under the comprehension floor after release 0.2.0's scoring run, at the places that run names.** | 3 | 2 | 2 | 5 | 5 | code health by 5, 1.4 by 5 | 11.0 |
|
||||
| 105 | 0.5.0 | | decision | **Compare review rounds per pass and reading cost for the five chunks before and after the `worker:` decision moved the principles out of the worker's context, and file an item if either rose.** | 1 | 2 | 1 | 2 | 2 | 1.4 by 6 | 8.0 |
|
||||
| 59 | 0.5.0 | | | **Bound a run of unfinished verdicts on one chunk, so a worker and judge that disagree cannot cycle unattended without end.** | 2 | 1 | 3 | 4 | 3 | 1.4 by 6 | 6.0 |
|
||||
| 12 | 0.5.0 | | | **Run the test suite in CI on every PR, or record in `docs/decisions.md` why the local run is enough.** | 3 | 2 | 1 | 4 | 4 | 1.1 by 6 | 4.2 |
|
||||
| 135 | 0.5.0 | | | **Fingerprint only the modules loop-claude imports, so editing another tool's code no longer reloads a running loop.** | 2 | 2 | 3 | 5 | 3 | 1.1 by 4 | 4.2 |
|
||||
| 68 | 0.5.0 | | principle | **Test `workflow-bench/compare.py`'s blinding and `bench.py`'s run plan.** | 2 | 1 | 1 | 2 | 4 | 1.1 by 5 | 3.5 |
|
||||
| 4 | 0.5.0 | | | **Name each chunk's archive folder by the chunk's start time, so `<key>/` lists chunks in the order they ran.** | 3 | 2 | 3 | 6 | 3 | 1.1 by 3 | 3.2 |
|
||||
| 156 | 0.5.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 | 2.8 |
|
||||
| 1 | 0.6.0 | | question | **Say in README → Install how the transcript archive is backed up, once bender-infra backs up ai-sandbox's data volume.** | 1 | 2 | 1 | 2 | 1 | | 0.0 |
|
||||
| 6 | 0.6.0 | | decision | **Move what `loop-claude` writes out of `~/.claude.json`, and ask the human about each write that must stay.** | 3 | 3 | 3 | 7 | 3 | 1.1 by 5 | 6.8 |
|
||||
| 5 | 0.6.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 | 3.3 |
|
||||
| 6 | 0.6.0 | | decision | **Move what `loop-claude` writes out of `~/.claude.json`, and ask the human about each write that must stay.** | 3 | 3 | 3 | 7 | 3 | 1.1 by 5 | 5.3 |
|
||||
| 77 | 0.6.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 | 3.2 |
|
||||
| 51 | 0.6.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 | 2.7 |
|
||||
| 151 | 0.6.0 | | decision | **Keep 10 to 20 settled decisions per project as its goals' test set, and rerun them after a goal changes.** | 3 | 2 | 2 | 5 | 5 | 1.2 by 7 | 2.6 |
|
||||
| 52 | 0.6.0 | | principle | **Record why this checkout lives in Claude Code's own directory, or move it out and link it in.** | 4 | 3 | 4 | 9 | 6 | 1.1 by 4 | 1.2 |
|
||||
| 151 | 0.6.0 | | decision | **Keep 10 to 20 settled decisions per project as its goals' test set, and rerun them after a goal changes.** | 3 | 2 | 2 | 5 | 5 | 1.2 by 7 | 2.9 |
|
||||
| 5 | 0.6.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 | 2.5 |
|
||||
| 51 | 0.6.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 | 2.1 |
|
||||
| 52 | 0.6.0 | | principle | **Record why this checkout lives in Claude Code's own directory, or move it out and link it in.** | 4 | 3 | 4 | 9 | 6 | 1.1 by 4 | 0.9 |
|
||||
|
||||
## Details
|
||||
|
||||
### 178. Step the worker one rung up as the judge interrupts, when the interrupted run also asked loop-claude for a higher rung and the judge finds the escalation trigger that run cites.
|
||||
|
||||
A defect against goal 1.3, the same rules in every session: the escalation rule (`docs/decisions.md` → `routing: a worker whose run ends asking for a higher rung…`) does not hold when the run that asks for a higher rung also asks the human something only they can answer. Only an `Unfinished` verdict carries an escalation, the judge's quote of the trigger the worker cites (`bin/loop_claude/cycle/judge.py`), and only `after_verdict` (`bin/loop_claude/loop/main.py`) calls `stepped`, on an unfinished verdict. An interrupt carries none, so `bin/loop_claude/cycle/run.py` opens the interrupt on the worker's current rung, and the step-up is lost. The worker cannot ask again: a step-up needs a trigger that fired since its last request.
|
||||
|
||||
Have the judge's interrupt carry an escalation, checked word for word as on `Unfinished`. Step the worker's rung up as the judge's interrupt comes in, before the human is asked. The worker then carries on from the answer on the stepped rung. Today that is in the interactive session the interrupt opens. Once item 168 lands, it is the headless run that resumes with the answer, or the session `/talk` opens. The step obeys the decision's limits: one rung, at most two above the item's rung, and one step per trigger, so the verdict the judge gives after the interrupt does not step again on the same quote. An interrupt does not count as an unfinished verdict. The change touches two places the comprehension seats found hard, `routing.py`'s `stepped` and `judge.py`'s `run_judge`. Leave each easier to read.
|
||||
|
||||
It happened in item 84's chunk on 2026-10-17. The worker, on Sonnet 5.5 at high, ended its run asking loop-claude for a higher rung. It cited trigger 4: the architect's BLOCK, which stood after the architect's rerun one rung up. In the same run it asked the human about a cost, and the judge ruled interrupt. After the human's answer, the worker did the redesign the BLOCK asked for in the interactive session on Sonnet 5.5 at high, one rung below the Opus 5.5 at medium the step would have given.
|
||||
|
||||
### 168. Have the human answer an interrupt on loop-claude's terminal and resume the worker headless with the answer, opening the interactive session only when they ask for it.
|
||||
|
||||
Today an interrupt runs `claude --resume` on the terminal and waits for it to exit (`bin/loop_claude/cycle/interrupt.py`). Once the human answers, the worker carries on in that interactive session, so the loop waits until the human exits it, often for the rest of the chunk. Instead, the loop prints the question and reads the answer on its own terminal. The next cycle resumes the worker headless with a prompt like `prompts.answered`'s, saying the human gave the answer. A word typed in place of an answer, such as `/talk`, opens today's interactive session, for when the human wants to read the diff or discuss first. An empty answer stops the loop, as an interrupt with nothing typed does today. A release ready to cut still opens the interactive session. Bench the word, and the line that asks for the answer, as `CLAUDE.md` says.
|
||||
|
||||
The judge must treat an answer typed at the loop's terminal as the human's. `bin/claude_code/transcript.py`'s `render` labels every `-p` prompt `[loop]`, so an answer passed on headless would read as one quoted from the records. The judge would then never hold the chunk open until that answer is recorded. The change touches two places the comprehension seats found hard: `bin/loop_claude/cycle/judge.py`'s `run_judge` and `bin/loop_claude/loop/main.py`'s help. Leave each easier to read.
|
||||
|
||||
### 73. Have each reviewer write its full report to a file and return the worker only its findings' one-line summaries.
|
||||
|
||||
2026-10-08, lilleman: rescored from A10/G8 to A4/G4 on the measurement below, so other items that lower token use go first.
|
||||
|
||||
Measured over the 68 transcripts in loop-claude's archive on 2026-10-08, matching each Agent call to its tool result and to any `<task-notification>` naming its tool-use id. No report reached the worker twice: 813 arrived once as the hand-back, and 363 once as a notification after Claude Code ran the agent in the background. Reports took a median 19k tokens per chunk, 8% of the worker's peak context (24% at most). Lines carrying a severity mark are 9–24% of a reviewer's report, and the worker would still open the file for each 🔴 or 🟡 it fixes. A third of the report volume is the comprehension seats', whose votes and places the worker copies into the history. File reads fill more of the worker's context: `sed -n` output is 30% of its Bash results and `grep` output 11%, which `reading-cost` targets.
|
||||
|
||||
The reports would live in the session's scratchpad, such as `<scratchpad>/larv-review/prose-round-1.md`, so no project's checkout sees them. A later round gets the path of that pass's earlier report in place of the findings pasted in. How a report reaches the file:
|
||||
|
||||
- **Write access.** Grant each reviewer Write. No reviewer under `agents/` holds it today, an agent's tool list cannot confine Write to one folder, and `~/.claude/CLAUDE.md` → "Working with the codebase" denies edits to a reviewer that only reads. Check whether a PreToolUse hook can tell a subagent's call from the worker's and deny a Write outside the scratchpad.
|
||||
- **A wrapper.** A general-purpose subagent launches the reviewer, saves the report and returns only the summary lines. Claude Code's documentation says a subagent cannot start another; drop this route unless a test shows one can.
|
||||
|
||||
This risks goal 1.1: a worker fixing from a one-line summary can miss context it needs.
|
||||
|
||||
### 159. Run each review pass on the lowest rung that a replay of its archived rounds shows finding every 🔴 and 🟡 the project's rung finds, even below the worker's rung.
|
||||
|
||||
lilleman asked, on 2026-10-16, for the prose pass to run on the worker's rung or lower, and the same day, answering PR #296, for every pass to drop below the project's rung only where a replay shows it may. Today `bin/loop_claude/cycle/prompts.py`'s `review_launches` keeps every reviewer at or above the project's rung whatever the item's E + I, so a docs-only chunk such as item 140's, routed to Haiku 5.5, runs its reviewers on Opus 5.5.
|
||||
|
||||
Whether a pass runs cheaper without lowering quality (goal 1.4 against 1.1) is measured, as `docs/decisions.md` → `routing: the stability reviewer runs no lower than the project's rung…` measures the stability reviewer: replay a pass's archived rounds on the code each reviewed, first on the project's rung, then on each rung below it, and take the lowest rung that, like each rung above it, finds every 🔴 and 🟡 the project's rung finds again. A missed prose finding breaks no behaviour and a later change fixes it cheaply, so replay the prose pass first. Generalise `bin/stability-replay` to take the pass, in place of a replay tool per pass. Record each run and the rung it chose in a `routing:` decision, valid until a new model joins the ladder or the pass's prompt changes. Give each pass a row of its own in `REVIEWS`, `review_launches`' table of review kinds in `bin/loop_claude/cycle/prompts.py`, rather than a branch.
|
||||
|
||||
### 80. State in README → Install that every machine taking this checkout must be a sandbox, as `settings.json`'s auto mode assumes.
|
||||
|
||||
A defect: goal 2, keeping the setup shareable between computers, does not hold while a new machine is never told it must be a sandbox. Raised by the principles audit of PR #224. The `settings.json` decision is valid while every machine taking this checkout is a sandbox, but Install asks for a sandbox only for `loop-claude`.
|
||||
|
||||
### 21. Give `settings.json`'s model one writer, and sort its keys.
|
||||
|
||||
A defect: goal 2, keeping the setup shareable between computers, does not hold while one machine's model choice overwrites every other's. Claude Code rewrites `"model"` in this tracked file whenever a model is picked, so one `/model` dirties the checkout and overrides the synced choice.
|
||||
|
||||
Every write Claude Code makes to the file rewrites `"model"`, `claude plugin install` included: Claude Code 2.1.288 turned `"opus"` into `"opus[1m]"`. Each write also puts the keys back in Claude Code's own order, so a sorted file stays sorted only until the next write.
|
||||
|
||||
### 29. Make the contributor a standing member of every project's audience, unless its `## Audience` says maintainability does not matter.
|
||||
|
||||
State that in `~/.claude/rules/goals-and-audience.md` → "Goals and Audience", and have larv-review's comprehension check name the contributor as the reader it serves. The check then runs in a project whose audience includes the contributor, and a project that drops them skips it.
|
||||
|
||||
### 119. Retitle the comprehension-floor decision so it says a chunk lifting a project towards the floor works first on its lowest-scoring dimension, and that the floor blocks nothing.
|
||||
|
||||
Today's title, "a project lifting itself to the comprehension floor starts at the lowest dimension", reads as either where the project scores or where work begins. Beside the title saying the check blocks no merge, a reader cannot tell whether `Floor:` means stop; a seat named `AGENTS.md:5` among the places it found hard. "First" means within such a chunk, not across a release: since the decision's 2026-10-16 line, items that lift the lowest dimension compete with the others like any item.
|
||||
@@ -143,19 +104,11 @@ Two seats of PR #257's scoring run assembled these terms from four files: `bin/l
|
||||
|
||||
The maintainability senior of PR #257's scoring run named `bin/rule_hook/rules.py:49` `OVERRIDE`: nothing in the code explains the pattern. Make `OVERRIDE` easier to read.
|
||||
|
||||
### 114. Run git through `git_repo.py` in `rule_hook`, `metric_bench`, `reading_cost`, `stability_replay` and `loop_claude`, keeping rule-hook's guards as an option, so one module owns how a tool runs git.
|
||||
### 114. Run git through `git_repo.py` in `rule_hook`, `metric_bench`, `reading_cost`, `review_replay` and `loop_claude`, keeping rule-hook's guards as an option, so one module owns how a tool runs git.
|
||||
|
||||
Shape is the lowest dimension, so this item moves goal 1.1 by 9, per `docs/decisions.md` → `larv-review: a project lifting itself to the comprehension floor starts at the lowest dimension`.
|
||||
Shape is the lowest dimension, so this item moves code health by 9, per `docs/decisions.md` → `larv-review: a project lifting itself to the comprehension floor starts at the lowest dimension`.
|
||||
|
||||
The comprehension seats on PR #254 found five git runners with different contracts: `git_repo.git`, `rule_hook/git.py`'s guarded one, `metric_bench/main.py`'s, `reading_cost/main.py`'s `located` and `loop_claude/effects.py`'s. PR #276 added a sixth, `stability_replay/main.py`'s `git`. The inherited architect of PR #257's scoring run named `bin/git_repo.py:8` `git` again. Make `git_repo.git` easier to read.
|
||||
|
||||
### 120. Rewrite larv-review §3's "Round cap" and "Re-entry" as one table that says, for each kind of fix, which passes rerun and what a round reviews.
|
||||
|
||||
Junior A, Mid A and the maintainability senior of PR #257's scoring run named `skills/larv-review/SKILL.md:63` "Round cap" hardest, two of them with `:74` "Re-entry"; the inherited architect named `:71` "Cap". A reader holds the trigger table's "a fix, only where …" clauses, the cap, later rounds' scope and the prose, 🟢 and ❓ exceptions at once. Junior A could not say what a fix to a stability 🟡 that also touches a comment reruns. Make those sections easier to read.
|
||||
|
||||
### 49. Check that `AGENTS.md` lists exactly the titles of `docs/decisions.md`.
|
||||
|
||||
DRY, in `principles/technical-principles.md`: the list is copied by hand, and sessions work from the copy.
|
||||
The comprehension seats on PR #254 found five git runners with different contracts: `git_repo.git`, `rule_hook/git.py`'s guarded one, `metric_bench/main.py`'s, `reading_cost/main.py`'s `located` and `loop_claude/effects.py`'s. PR #276 added a sixth, `review_replay/main.py`'s `git`. The inherited architect of PR #257's scoring run named `bin/git_repo.py:8` `git` again. Make `git_repo.git` easier to read.
|
||||
|
||||
### 117. Give `todo_table.items` one way to say a plan has no items table, so no caller tells it from an empty plan by truthiness.
|
||||
|
||||
@@ -177,21 +130,23 @@ Junior A, Mid A and the maintainability senior of PR #257's scoring run named `b
|
||||
|
||||
Junior A and Mid A of PR #257's scoring run named `bin/shell_command.py:31` `segments`: a hand-rolled tokenizer with dense regexes and a second lexing path for unbalanced quotes, which the rule hook and `reading-cost` both depend on. Its comments state each quirk but not its limits. Make `segments` easier to read.
|
||||
|
||||
### 154. Have `bin/shell_command.py`'s `segments` keep a command's words together across a redirect, so `git > out commit` reads as one git commit.
|
||||
|
||||
`segments('echo hi > f arg')` returns `arg` as a command of its own, and `segments('git > /tmp/x commit -m hi')` returns `git` and `commit -m hi` apart, though the shell runs one `git commit`. rule-hook's commit rules read the commands `segments` finds, so such a commit escapes `commit-one-line`, `no-ai-attribution`, `round-title-counts` and `todo-rank-check`. The comprehension seats' scoring run in PR #280 found it.
|
||||
|
||||
### 157. Split `docs/decisions.md` → `todo.md: one table of items …`'s 2026-10-02 paragraph into one paragraph per choice.
|
||||
|
||||
Raised by PR #283's prose pass. The paragraph runs about 330 words and holds six choices: the bar, the purge, re-raising findings, the gate check, the `principle` exemption and the 2026-10-08 weights note. A reader after one of them reads all six.
|
||||
|
||||
### 106. Make larv-review's "Do not over-read a clean result" cite a rule that says Renovate or Dependabot owns dependency CVEs, or drop the citation.
|
||||
### 80. State in README → Install that every machine taking this checkout must be a sandbox, as `settings.json`'s auto mode assumes.
|
||||
|
||||
Found by the goals audit of PR #245. `skills/larv-review/SKILL.md` §3 → "Security" says Renovate or Dependabot owns dependency CVEs per `CLAUDE.md` → "Working with the codebase", which says nothing about either.
|
||||
A defect: goal 2, keeping the setup shareable between computers, does not hold while a new machine is never told it must be a sandbox. Raised by the principles audit of PR #224. The `settings.json` decision is valid while every machine taking this checkout is a sandbox, but Install asks for a sandbox only for `loop-claude`.
|
||||
|
||||
### 167. Refuse a `/security-review` or `/claude-security` Skill call below the project's rung, as rule-hook refuses such an Agent call.
|
||||
### 120. Rewrite larv-review §3's "Round cap" and "Re-entry" as one table that says, for each kind of fix, which passes rerun and what a round reviews.
|
||||
|
||||
rule-hook checks Agent calls (item 163) but no Skill calls. A worker that invokes `/security-review` in its own context, instead of in a subagent, runs the pass on its own rung, and nothing blocks it. Check Skill calls too: `breaches_of` in bin/rule_hook/main.py takes a Skill call whose skill is `security-review` or `claude-security` as a review launch, and settings.json's PreToolUse matcher gains Skill. Found by the systems-architect's review of PR #295.
|
||||
Junior A, Mid A and the maintainability senior of PR #257's scoring run named `skills/larv-review/SKILL.md:63` "Round cap" hardest, two of them with `:74` "Re-entry"; the inherited architect named `:71` "Cap". A reader holds the trigger table's "a fix, only where …" clauses, the cap, later rounds' scope and the prose, 🟢 and ❓ exceptions at once. Junior A could not say what a fix to a stability 🟡 that also touches a comment reruns. Make those sections easier to read.
|
||||
|
||||
### 21. Give `settings.json`'s model one writer, and sort its keys.
|
||||
|
||||
A defect: goal 2, keeping the setup shareable between computers, does not hold while one machine's model choice overwrites every other's. Claude Code rewrites `"model"` in this tracked file whenever a model is picked, so one `/model` dirties the checkout and overrides the synced choice.
|
||||
|
||||
Every write Claude Code makes to the file rewrites `"model"`, `claude plugin install` included: Claude Code 2.1.288 turned `"opus"` into `"opus[1m]"`. Each write also puts the keys back in Claude Code's own order, so a sorted file stays sorted only until the next write.
|
||||
|
||||
### 176. Give `loop-claude --help`'s routing paragraph sub-headings, such as Routing, Judge rung and Routing figures, so a reader finds a rule without reading 39 lines.
|
||||
|
||||
@@ -201,13 +156,29 @@ Raised by the prose pass of PR #302: the help, the docstring of `bin/loop_claude
|
||||
|
||||
The architecture pass of PR #296 found one rung under two names: `bin/model_routing/ladder.py` calls it `project`, while `bin/loop_claude/routing.py`, `cycle/prompts.py`, `cycle/run.py`'s `Cycle.anchor` and `loop/main.py` call it `anchor`, and gloss it as "anchor, the project's rung" in docstring after docstring. A reader works out that the two are one rung each time. Make `bin/loop_claude/routing.py`'s `first_route` easier to read.
|
||||
|
||||
### 190. Rewrite the `docs/decisions.md` entries `todo.md: one table …` and `loop-claude: a judge decides …` as the current state, so a reader no longer replays superseded paragraphs to learn what holds.
|
||||
|
||||
Found by the prose review of PR #312, which judged both entries to read as amendment logs, each paragraph correcting an earlier one. The rewrite keeps each paragraph's date and reason only where it still explains a rule that holds, and drops superseded states. It covers items 157 and 183, which reshape paragraphs of the same two entries.
|
||||
|
||||
### 82. Sort `AGENTS.md`'s decision titles and `docs/decisions.md`'s entries by title.
|
||||
|
||||
"Deterministic order", in `principles/technical-principles.md`, raised by the principles audit of PR #224: their order carries no meaning, so two chunks adding a decision conflict at the end, and a reader cannot find a title by scanning.
|
||||
|
||||
### 173. Have rule-hook's `todo-rank-check` run a worktree's own `bin/rank_todo.py` when the worktree is of this repo, so a branch that changes `todo.md`'s shape commits without an override.
|
||||
### 29. Make the contributor a standing member of every project's audience, unless its README voids code health.
|
||||
|
||||
Raised by the overrides pass of PR #296. The hook imports the main checkout's `rank_todo.py`, so while a branch of this repo changes the table's shape, every commit touching `todo.md` needs a `todo-rank-check` override: 33 log lines across four branches, the score-outcomes, plan-136, plan-148 and item-146 ones. The hook then checks nothing, and the rule rests on the worker chaining the branch's own check. Run another repo's `bin/rank_todo.py` never: that would run its code before every commit.
|
||||
State that in `~/.claude/rules/goals-and-audience.md` → "Goals and Audience", and have larv-review's comprehension check name the contributor as the reader it serves. The `**Void:** code health` line (`~/.claude/CLAUDE.md` → "Shared goal") is the one place a project says maintainability does not matter: it drops the contributor. A project that opts out of the comprehension check must already write that line.
|
||||
|
||||
### 106. Make larv-review's "Do not over-read a clean result" cite a rule that says Renovate or Dependabot owns dependency CVEs, or drop the citation.
|
||||
|
||||
Found by the goals audit of PR #245. `skills/larv-review/SKILL.md` §3 → "Security" says Renovate or Dependabot owns dependency CVEs per `CLAUDE.md` → "Working with the codebase", which says nothing about either.
|
||||
|
||||
### 49. Check that `AGENTS.md` lists exactly the titles of `docs/decisions.md`.
|
||||
|
||||
DRY, in `principles/technical-principles.md`: the list is copied by hand, and sessions work from the copy.
|
||||
|
||||
### 154. Have `bin/shell_command.py`'s `segments` keep a command's words together across a redirect, so `git > out commit` reads as one git commit.
|
||||
|
||||
`segments('echo hi > f arg')` returns `arg` as a command of its own, and `segments('git > /tmp/x commit -m hi')` returns `git` and `commit -m hi` apart, though the shell runs one `git commit`. rule-hook's commit rules read the commands `segments` finds, so such a commit escapes `commit-one-line`, `no-ai-attribution`, `round-title-counts` and `todo-rank-check`. The comprehension seats' scoring run in PR #280 found it.
|
||||
|
||||
### 162. Script each step that 0.2.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.
|
||||
|
||||
@@ -219,28 +190,78 @@ The chunk that ships this item files a copy of it in the release after the one i
|
||||
|
||||
Item 161 put `chunk-preflight`'s facts into a fresh worker's prompt, so the worker no longer finds them itself. Before that, in item 140's chunk, the worker spent 5 min 46 s of 30 min, 16 of its 68 messages and 226k of its 491k fresh tokens before its first edit, through 12 Bash and 5 Read calls. Measure those figures from loop-claude's archive, as medians over the first five chunks that started with the preflight and the five before them: one chunk is too noisy a baseline, as `docs/decisions.md` → `reading cost: a rise is …` records. Measure the counter-signals beside them: goal 1.4's review rounds and unfinished verdicts, and goal 1.5's 🔴 findings, per chunk, since a worker that reads less may start sooner and need more rounds or let more defects through. Where time or tokens did not fall, or a counter-signal rose, file an item naming the facts the workers still found by hand, or what the preflight got wrong.
|
||||
|
||||
### 177. Move the next chunk's pick, from `LastCut` and `standing` to `chunk_item` and `default_plan`, into one module named for it, so `git_repo` only runs git and `todo_table` only parses the plan.
|
||||
### 183. Merge the two 2026-10-13 paragraphs of `docs/decisions.md` → `loop-claude: a judge decides each interrupt …` into one.
|
||||
|
||||
Raised by PR #302's paired ruling, where two of four seats read the project as worse at these places. Item 161 put the pick in `bin/todo_table.py` (`Standing`, `LastCut`, `unreleased_entries`, `landed`, `named_releases`, `standing`, `chunk_item`) and its reader in `bin/git_repo.py` (`DefaultPlan`, `default_plan`, `todos_since`), so the git module now imports the plan model and the table parser decides how a release stands. Make each of those places easier to read:
|
||||
They say the same thing for `~/.claude/rules/` (item 95) and `~/.claude/skills/larv-review/standards/` (item 104), and the entry grows a paragraph per chunk. Raised by the prose review of PR #308.
|
||||
|
||||
- `bin/git_repo.py` → `DefaultPlan`: the git module knows todo.md and CHANGELOG.md.
|
||||
- `bin/todo_table.py` → `standing`: a five-state literal whose three-line comment must be decoded first.
|
||||
- `bin/todo_table.py` → `landed`: it counts ## Unreleased entries first, while `bin/larv_review/git.py` → `landed_since_release` counts commits only, two meanings of "work has landed"; give them one meaning or two names.
|
||||
- `bin/loop_claude/loop/main.py` → `run_loop`: routing reads the plan as chunk-preflight's fetch left it, an order only a comment states.
|
||||
- `bin/chunk_preflight/gathered.py`: the name covers the data, not the pure choices it also holds.
|
||||
### 184. Rewrap the lines of `loop-claude --help` that run past the column the rest of it wraps at.
|
||||
|
||||
In `bin/loop_claude/loop/main.py`'s docstring, the line holding "of one PR, is finished" and the one ending "Each of these opens with its UTC time." run to 107 and 159 columns. Raised by the prose review of PR #308.
|
||||
|
||||
### 186. Point every file a session parks outside its checkout, such as the comprehension panel's detached worktree and a build probe's output, at a folder a headless session has, since loop-claude's sessions have no scratchpad.
|
||||
|
||||
`skills/comprehension-panel/SKILL.md` puts the base version's detached worktree "in your scratchpad", and `CLAUDE.md` → "Working with the codebase" lets a build-probing subagent write "only to the session scratchpad". A probe on 2026-10-18 found no `scratchpad_dir` in a headless `claude -p` session's hook input, and neither the session nor its subagent knew a scratchpad path. larv-review now parks its reports and votes file in the chunk's review folder under `~/.local/state/larv-review/`, per `docs/decisions.md` → `review: each reviewer under agents/ writes its full report into the chunk's review folder`. Found by the architecture review of PR #310.
|
||||
|
||||
### 198. Count, per finished chunk, the findings that arose from misreading code that had already shipped, so code health's counter-signal shows.
|
||||
|
||||
Code health's counter-signal (`CLAUDE.md` → "Shared goal") has no count, since no tool records why a finding arose. Have each reviewer tag a finding that arose because the implementer misread code that had already shipped, and have `score-outcomes` count the tagged findings per finished chunk. Item 110's later fixes stand for the defects that keep reappearing.
|
||||
|
||||
### 167. Refuse a `/security-review` or `/claude-security` Skill call below the project's rung, as rule-hook refuses such an Agent call.
|
||||
|
||||
rule-hook checks Agent calls (item 163) but no Skill calls. A worker that invokes `/security-review` in its own context, instead of in a subagent, runs the pass on its own rung, and nothing blocks it. Check Skill calls too: `breaches_of` in bin/rule_hook/main.py takes a Skill call whose skill is `security-review` or `claude-security` as a review launch, and settings.json's PreToolUse matcher gains Skill. Found by the systems-architect's review of PR #295.
|
||||
|
||||
### 173. Have rule-hook's `todo-rank-check` run a worktree's own `bin/rank_todo.py` when the worktree is of this repo, so a branch that changes `todo.md`'s shape commits without an override.
|
||||
|
||||
Raised by the overrides pass of PR #296. The hook imports the main checkout's `rank_todo.py`, so while a branch of this repo changes the table's shape, every commit touching `todo.md` needs a `todo-rank-check` override: 33 log lines across four branches, the score-outcomes, plan-136, plan-148 and item-146 ones. The hook then checks nothing, and the rule rests on the worker chaining the branch's own check. Run another repo's `bin/rank_todo.py` never: that would run its code before every commit.
|
||||
|
||||
### 171. 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.
|
||||
|
||||
Raised by the goals audit of PR #296. `bin/routing_figures/measure.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).
|
||||
|
||||
### 196. Replay the architecture, principles, overrides and product-owner passes with `review-replay` on Opus 5.5 projects, record each run in the review-replay routing decision, and add any rung a run qualifies to `REPLAYED`.
|
||||
|
||||
Item 159's chunk, PR #322, replayed only the prose and stability passes. Sonnet 5.5 at high missed 44 to 55% of what the project's rung found again in each, so the agent judged a replay of the other four unlikely to qualify a rung. The product-owner review of PR #322 asked that the plan keep them, so the ranking decides when they run. Each run costs hours of reviewer replays (goal 1.4), so the score keeps it low until a cheaper model joins the ladder. `docs/decisions.md` → `routing: a review pass runs below the project's rung only on a rung that a replay of its rounds shows finding every 🔴 and 🟡 the project's rung finds…` records the runs so far.
|
||||
|
||||
### 181. Have the test of a quoted answer's step-up assert the stepped rung's facts as literals, not through `prompts.rungs_held`.
|
||||
|
||||
`bin/loop_claude/test_loop_claude.py`'s `test_a_quoted_answer_that_cites_an_escalation_trigger_steps_the_worker_up_before_it_resumes_and_archives_the_step` builds its expected prompt from `prompts.rungs_held`, the code under test, so a bug there passes it. The technical principles' test bullet bans that shape. Assert the new rung and one review launch as literals, as the typed answer's step-up test does. Raised by the principles audit of PR #308.
|
||||
|
||||
### 192. Sort `.gitignore`'s allowlist block, from `!.claude/` to `!workflow-bench/test_review_git.py`, by code point, so rule-hook's `ignorefile-sorted` checks later edits to it again.
|
||||
|
||||
Found by review of PR #317. `.gitignore:56-58` holds `!bin/rule-hook` above `!bin/routing_figures/` and `!bin/routing_figures/*.py`, but `o` sorts before `u`. `ignore_breaches` in `bin/rule_hook/rules.py` skips a block that was already unsorted before an edit, so while this one stays unsorted no later edit to it is checked. The unsorted block breaches the technical principle "Deterministic order wherever order carries no meaning".
|
||||
|
||||
### 193. Narrow `readme_goals`'s mark to `Mark` by a typed lookup in place of `typing.cast`, so a mark added to the regex but not the lookup fails at run time, and one added to the lookup but not `Mark` fails mypy.
|
||||
|
||||
Found by review of PR #317. `bin/rank_todo.py`'s `readme_goals` writes `typing.cast(Mark, mark or None)`, which asserts the type `goal_weights` branches on without checking it: a mark added to the regex reaches `goal_weights` as a value `Mark` lacks. mypy does not read the regex, so no lookup lets it catch that. Replace the cast with a lookup typed `dict[str, Mark]`, from each mark the regex captures, and `""` for none, to its `Mark` value. A mark added to the regex but not the lookup then raises `KeyError` at run time, and a value added to the lookup but not `Mark` fails mypy.
|
||||
|
||||
### 194. Make `test_waits_out_a_usage_limit_which_ends_a_run_of_failures` expect a usage-limit wait independent of the wall-clock time that passes during the run.
|
||||
|
||||
Found by review of PR #317. `bin/loop_claude/test_black_box.py:569-575` sets `resets_at` from the test's `time.time()` and expects the wait, rounded to tens, to be 3720. When more than about 5 s pass between that read and the loop's, the wait rounds to 3710 and the test fails with no bug. Item 102 covers only replacing the `time.sleep` swap; this item changes the expected value, for example by asserting the wait against `resets_at + 120` minus the time the loop read, or a bound on it.
|
||||
|
||||
### 187. Count the tokens a worker spends reading reviewers' reports, so goal 1.4's signal shows whether report files lowered what a review costs the worker's context.
|
||||
|
||||
Before PR #310, reports reached the worker as the Agent call's result, a median 19k tokens per chunk (2026-10-08, 68 archived transcripts). Now a reviewer returns its verdict and one line per finding, and the worker reads a 🔴 or 🟡 finding's entry from the report file. `reading-cost` counts only tracked files (`bin/reading_cost/measure.py`), and `routing-figures` counts only the Agent call's result (`bin/routing_figures/measure.py`), so neither sees the report reads. Found by the architecture review of PR #310.
|
||||
|
||||
### 165. Make this repo's tests assert the facts a prompt or help text carries in place of its sentences, and drop the tests that scan source or assert a constant.
|
||||
|
||||
A test audit across lilleman's projects on 2026-10-16 found 10 of 33 sampled tests in this repo pinning wording that is not the contract. Examples of these and other weak tests: `bin/loop_claude/test_loop_claude.py:165`, `:271` and most asserts in `:664` to `:687` pin whole sentences of the question, archive or prompt text, up to about 750 characters, and `:864` asserts help-text wording. `:906` and `:936` parse the source with `ast` and list each `Stop(...)` and `Failure(...)` call by function name. `bin/model_routing/test_ladder.py:16` asserts `len(LADDER) == 11`. Rewrite each to the technical principles' test bullet: assert the facts the text must carry, such as an item ID, a rung or a model argument, and delete a test no real bug could fail. Before and after rewriting a test, run the mutation tool on the code it covers: every mutant the old test killed, the new one kills.
|
||||
|
||||
### 182. Let the human edit an interrupt's answer with the arrow keys, so Left moves the cursor instead of typing ^[[D into the answer.
|
||||
|
||||
`bin/loop_claude/cycle/interrupt.py`'s `put_question` reads the answer with `input()`, and nothing under `bin/` imports `readline`, so Left types `^[[D` into the answer the worker gets. Importing `readline` gives line editing, at two costs. It writes the prompt to stdout, not stderr. And its bracketed paste can return several lines, while `prompts.typed_answer` ends the answer at its first blank line and shows the judge the rest as loop-claude's words. Raised by the product-owner review of PR #308.
|
||||
|
||||
### 155. Lower the reading cost of the files a chunk reads most before its first commit.
|
||||
|
||||
`bin/reading-cost` on 2026-10-18: the median of the last 5 chunks is 163,028 new input tokens before their first commit, up from 100,998 for the 5 before them. Read most over the last 5, by opens and searches: `rules/decisions.md` 1. The chunk that ships this item runs `bin/reading-cost --reset`.
|
||||
|
||||
### 169. Have rule-hook's `todo-rank-check` catch a `todo.md` that the same Bash call edits and then commits.
|
||||
|
||||
The hook judges a call before it runs, and `changed` in `bin/rule_hook/todo_check.py` compares `todo.md` with the index and HEAD as they stand then. A call that edits `todo.md` and commits it, such as a heredoc script followed by `git commit`, passes unchecked: PR #296's commit 149108e did, and the override marker it carried was never logged. larv-review's gate still runs `rank_todo.py --check`, so an unranked plan stops at merge rather than at commit. A git pre-commit hook would see the staged file.
|
||||
|
||||
### 197. Let the human edit what they type at loop-claude's terminal questions with the arrow keys, so Left moves the cursor in place of printing `^[[D`.
|
||||
|
||||
`bin/loop_claude/effects.py` reads each answer with Python's builtin `input`, and nothing imports `readline`, so the terminal gets no line editing: fixing a typo means erasing back to it. Importing `readline` in `effects.py` gives `input` that editing, for the interrupt's answer and the question that asks for the project's model alike. lilleman, 2026-10-18: "Not super-important, but a bit irritating."
|
||||
|
||||
### 174. In a chunk no item routed, ask the worker to name each todo.md item it takes, with its L and E + I, so loop-claude can route on an item it takes in.
|
||||
|
||||
The principles pass of PR #301 found that only `routed_by` in `bin/loop_claude/cycle/prompts.py` asks the worker to name each item it takes with its L and E + I, and `fresh` uses it only where an item routed the chunk. In an unrouted chunk the judge has no levels to report, so neither the taken-in L nor the taken-in E + I lifts the worker, the reviewers or the judge, and the first prompt names no reviewers' rung for a higher E + I.
|
||||
@@ -249,14 +270,32 @@ The principles pass of PR #301 found that only `routed_by` in `bin/loop_claude/c
|
||||
|
||||
All four seats of PR #257's scoring run named `bin/loop_claude/cycle/judge.py:16` `JUDGE_RULES`. The prompt is spliced from constants in `cycle/prompts.py` (`ANSWER_DESTINATIONS`, `ANSWERS_RECORDED`, `either`) and `project/records.py` (`HUMAN_RULE_NAMES`), so a reader rebuilds it from three files. It says "the agent" where the code and `CLAUDE.md` → "Vocabulary" say "worker". Wording the worker also sees, such as `ANSWER_DESTINATIONS` in `prompts.resumed`, may stay in `cycle/prompts.py`. Make `JUDGE_RULES` easier to read.
|
||||
|
||||
### 158. Measure the fixed cost of a chunk from loop-claude's archive, in tokens and hours against its items' S, and set F in `Score = 100 * V / (2**S + F)` to it.
|
||||
### 130. Move the vote counting out of `bin/larv_review/ruling.py`'s `votes`, so reading a votes file decides nothing.
|
||||
|
||||
F is 8 until then, about one S 3 change, lilleman's call in PR #283. A chunk costs more than its size: the worker reads about 130k tokens before its first commit whatever the item, and every chunk takes its review passes. Fit cost against 2**S from the finished chunks `score-outcomes` measures, in the same units `2**S` counts, and say in `docs/decisions.md` → `todo.md: …` how far the fit holds. A chunk bundling tiny items shares F between them.
|
||||
Mid A of PR #257's scoring run named `bin/larv_review/ruling.py:8` `votes`. It calls `counted` while validating, to reject the maintainability senior's and Junior A's lines when Mid A and the inherited architect already agree overall: a ruling hidden in a parser. The counting rule is spread over `seats.py`, `ruling.py`, `comprehension_history.place_dimensions` and the help. Make `votes` easier to read.
|
||||
|
||||
### 125. Give "record", "outcome" and "places" one meaning each across `bin/`, and rename `bin/larv_review/git.py` by what it holds.
|
||||
|
||||
Shape is the lowest dimension, so this item moves code health by 9, per `docs/decisions.md` → `larv-review: a project lifting itself to the comprehension floor starts at the lowest dimension`.
|
||||
|
||||
The inherited architect of PR #257's scoring run named `bin/reading_cost/measure.py:16` `Reading` and `bin/larv_review/git.py:6` `history_changes`, and found each word used for several concepts. "Record": the history writer `larv_review/record.py`, the judge's `loop_claude/project/records.py`, and `reading_cost/figures.py`'s `RECORD`. "Outcome": `transcript_archive/outcomes.py`, `score_outcomes/outcomes.py` `Outcome` and `rule_hook/rules.py` `Outcome`. "Places": `comprehension_history.Place` and `Reading.places`. `larv_review/git.py` holds history logic, not a git runner. Make `Reading` and `history_changes` easier to read.
|
||||
|
||||
### 137. Archive a chunk's route as a record loop-claude reads back field by field, in place of the `Worker:` prose `ROUTED` parses, and name `stepped` and the judge's `bundled` by what they do.
|
||||
|
||||
PR #262's paired ruling found the project reads worse: a rerun resumes on its rung only by parsing `Rung.__str__`'s and `Route.__str__`'s wording back with `bin/loop_claude/routing.py`'s `ROUTED`, a string contract over four files, where a reword silently routes afresh. Write the route as a structured line, such as JSON after `Worker:`, that `transcript_archive` reads into fields. `stepped` both raises to a bundled item's rung and counts towards a one-rung step; `Reply.bundled` names neither L nor highest. Make `bin/loop_claude/loop/main.py`'s `run_loop` easier to read where it threads the route. The structured line must keep the escalation's mark, archived today as `escalated at transcript entry N`: without it, a trigger that already stepped the worker could step it again.
|
||||
|
||||
### 139. Split `bin/routing_figures/measure.py` by concern, and keep the figures' measured cycle and each raised call as fields loop-claude reads back, not as the prose it renders.
|
||||
|
||||
The paired ruling on PR #265 ruled worse. Make these places easier to read: `measure.py` `measured` and `render` (token attribution, subagent rungs, round counting, calls and rendering in one module; `measured`, `Measured` and `measure_archive` side by side); `calls` with `archive.py` `raised` and `last_measured`, where a call's identity is its sentence and the measured cycle is read back from rendered markdown; and `Reports.searches`, which holds characters, not searches.
|
||||
|
||||
### 170. Re-tune `WORKER_STEPS` and `REVIEW_STEPS` once 10 chunks have shipped under them, from how well L, E and I order their review rounds and 🔴 findings.
|
||||
|
||||
`docs/decisions.md` → `routing: one ladder…` calls the steps lilleman approved on 2026-10-16 a first guess. Once 10 chunks that each shipped one item scored with L, E and I have merged, read `score-outcomes`' rank correlations for L, E and I and the routed-chunks table of `routing-figures.md`, and propose new steps to lilleman, whose call they are.
|
||||
|
||||
### 158. Measure the fixed cost of a chunk from loop-claude's archive, in tokens and hours against its items' S, and set F in `Score = 100 * V / (2**S + F)` to it.
|
||||
|
||||
F is 8 until then, about one S 3 change, lilleman's call in PR #283. A chunk costs more than its size: the worker reads about 130k tokens before its first commit whatever the item, and every chunk takes its review passes. Fit cost against 2**S from the finished chunks `score-outcomes` measures, in the same units `2**S` counts, and say in `docs/decisions.md` → `todo.md: …` how far the fit holds. A chunk bundling tiny items shares F between them.
|
||||
|
||||
### 116. Report L by the share of chunks with a 🔴, once 10 chunks that each shipped one item record finding counts and most record no 🔴.
|
||||
|
||||
`score-outcomes` reports the median 🔴 count at each guessed R, and how well L orders chunks by 🔴 findings; the part of R a 🔴 tests is L. Where most chunks have no 🔴, every median reads 0 and the rank correlation rests on the few that have one, which tells a scorer little. No round title held counts before PR #254, so how often a chunk has a 🔴 is not yet known.
|
||||
@@ -265,20 +304,14 @@ F is 8 until then, about one S 3 change, lilleman's call in PR #283. A chunk cos
|
||||
|
||||
The inherited architect of PR #257's scoring run named `bin/round_titles.py:5` `PASSES`: it repeats `skills/larv-review/SKILL.md:33` with no check tying them. It leaves out the auto-reviewer, whose rounds `SKILL.md:68` counts by hand. A test under `bin/repo_checks/` can hold the two lists together. Make `PASSES` easier to read.
|
||||
|
||||
### 113. Compute an item's S from the code it names, where it names any, and show it beside the finished items `score-outcomes` lists.
|
||||
|
||||
`score-outcomes` grounds L, E, I and S in finished chunks only. Where an item names files or units, their size bounds what the change can touch.
|
||||
|
||||
### 112. Count an item as shipped only where its chunk built it, so an item a chunk dropped from the plan gets no outcome.
|
||||
|
||||
`score-outcomes` counts every item a merge removed from `todo.md` as shipped. A merge that changed only the plan ships nothing, but one that built an item and also dropped another gives the dropped item the built one's outcome, as PR #253 did with item 69. Mark a dropped item in the change that drops it, such as by the commit or merge title, and leave it out.
|
||||
|
||||
### 130. Move the vote counting out of `bin/larv_review/ruling.py`'s `votes`, so reading a votes file decides nothing.
|
||||
|
||||
Mid A of PR #257's scoring run named `bin/larv_review/ruling.py:8` `votes`. It calls `counted` while validating, to reject the maintainability senior's and Junior A's lines when Mid A and the inherited architect already agree overall: a ruling hidden in a parser. The counting rule is spread over `seats.py`, `ruling.py`, `comprehension_history.place_dimensions` and the help. Make `votes` easier to read.
|
||||
|
||||
### 125. Give "record", "outcome" and "places" one meaning each across `bin/`, and rename `bin/larv_review/git.py` by what it holds.
|
||||
|
||||
Shape is the lowest dimension, so this item moves goal 1.1 by 9, per `docs/decisions.md` → `larv-review: a project lifting itself to the comprehension floor starts at the lowest dimension`.
|
||||
|
||||
The inherited architect of PR #257's scoring run named `bin/reading_cost/measure.py:16` `Reading` and `bin/larv_review/git.py:6` `history_changes`, and found each word used for several concepts. "Record": the history writer `larv_review/record.py`, the judge's `loop_claude/project/records.py`, and `reading_cost/figures.py`'s `RECORD`. "Outcome": `transcript_archive/outcomes.py`, `score_outcomes/outcomes.py` `Outcome` and `rule_hook/rules.py` `Outcome`. "Places": `comprehension_history.Place` and `Reading.places`. `larv_review/git.py` holds history logic, not a git runner. Make `Reading` and `history_changes` easier to read.
|
||||
|
||||
### 81. Have `workflow-bench/bench.py` return each run's failure as a value, so one failed clone does not hide the later runs' results.
|
||||
|
||||
"Errors as values", in `principles/technical-principles.md`, raised by the principles audit of PR #224: `bench.py` raises `KeyError` and `CalledProcessError`, and `pool.map` re-raises the first while the other threads run on unreported.
|
||||
@@ -299,36 +332,42 @@ Found by the principles audit of PR #242, against "Functional core, imperative s
|
||||
|
||||
`score-outcomes` reads a chunk from a merge commit: its branch's round titles, and its change against the first parent. Two of the projects under `~/code` merge without merge commits, so their scorers see no finished item.
|
||||
|
||||
### 113. Compute an item's S from the code it names, where it names any, and show it beside the finished items `score-outcomes` lists.
|
||||
|
||||
`score-outcomes` grounds L, E, I and S in finished chunks only. Where an item names files or units, their size bounds what the change can touch.
|
||||
|
||||
### 137. Archive a chunk's route as a record loop-claude reads back field by field, in place of the `Worker:` prose `ROUTED` parses, and name `stepped` and the judge's `bundled` by what they do.
|
||||
|
||||
PR #262's paired ruling found the project reads worse: a rerun resumes on its rung only by parsing `Rung.__str__`'s and `Route.__str__`'s wording back with `bin/loop_claude/routing.py`'s `ROUTED`, a string contract over four files, where a reword silently routes afresh. Write the route as a structured line, such as JSON after `Worker:`, that `transcript_archive` reads into fields. `stepped` both raises to a bundled item's rung and counts towards a one-rung step; `Reply.bundled` names neither L nor highest. Make `bin/loop_claude/loop/main.py`'s `run_loop` easier to read where it threads the route.
|
||||
|
||||
### 110. Count, for each finished chunk, the later changes that fixed code it wrote, and show them beside its guessed E.
|
||||
|
||||
`score-outcomes` measures risk only by the 🔴 findings review caught. A serious bug review missed shows later, as a change that fixes code the chunk wrote: the defect that escaped, which E guesses.
|
||||
|
||||
### 139. Split `bin/routing_figures/measure.py` by concern, and keep the figures' measured cycle and each raised call as fields loop-claude reads back, not as the prose it renders.
|
||||
|
||||
The paired ruling on PR #265 ruled worse. Make these places easier to read: `measure.py` `measured` and `render` (token attribution, subagent rungs, round counting, calls and rendering in one module; `measured`, `Measured` and `measure_archive` side by side); `calls` with `archive.py` `raised` and `last_measured`, where a call's identity is its sentence and the measured cycle is read back from rendered markdown; and `Reports.searches`, which holds characters, not searches.
|
||||
|
||||
### 149. Fill each release by priority up to a capacity it states, in place of the bar, and move what does not fit to a later release.
|
||||
|
||||
A release's capacity is a sum of its items' cost, as the formula counts it. Each project states its own; the human sets the first value per project. Nothing is deleted by score.
|
||||
|
||||
### 123. Have `bin/comprehension_history.py` parse each history entry once into seats, votes and places, so `latest_places`, `worse_places` and `worse_votes` neither depend on table order nor split a label to find a seat.
|
||||
|
||||
Three seats of PR #257's scoring run named `bin/comprehension_history.py:106` `latest_places`; the logic it rests on is `:114` `worse_places` and `:126` `worse_votes`. They regex the markdown the module writes. `worse_votes` keeps a seat's first row through `setdefault`, because the votes table comes first. `worse_places` recovers the seat with `label.split(",")[0]`. `Entry` still holds scoring seats' places for rulings recorded before PR #255. Make these functions easier to read.
|
||||
|
||||
### 124. Group the shared modules at `bin/`'s root into packages named by purpose, so the root holds only launchers and stand-alone tools.
|
||||
|
||||
Shape is the lowest dimension, so this item moves code health by 9, per `docs/decisions.md` → `larv-review: a project lifting itself to the comprehension floor starts at the lowest dimension`.
|
||||
|
||||
PR #257's scoring run put Shape at 6.25, the lowest dimension. `bin/` holds about 30 entries: 6 launchers, 6 tool packages, 3 shared packages and 15 root modules. Two root modules are tools (`rank_todo.py`, `statusline.py`) and 13 are shared libraries, and nothing in the layout tells them apart; only README's import-root paragraph maps them. Candidate packages: git running and parsing, the todo table with `rank_todo.py`'s formula language and goal weighing, and the comprehension history with round titles. `rank_todo.py` keeps its path, which every project's rules name. The `.gitignore` allowlist and README follow the move.
|
||||
|
||||
### 132. Lift each dimension still under the comprehension floor after release 0.2.0's scoring run, at the places that run names.
|
||||
|
||||
Replaces item 62, which release 0.3.0's items split. PR #257's scoring run put Locality and Self-sufficiency at 6.63, Shape at 6.25 and the overall at 6.50, against the floor of 7.0 in `docs/decisions.md` → `comprehension floor: …`. Split this into items, one per place, once 0.3.0's scoring run has named them.
|
||||
|
||||
### 105. Compare review rounds per pass and reading cost for the five chunks before and after the `worker:` decision moved the principles out of the worker's context, and file an item if either rose.
|
||||
|
||||
The `worker:` decision is valid while review rounds per pass do not rise. Count the rounds from each PR's `Answer <pass> round <n>:` commits, and take reading cost from `docs/reading-cost.md`. Run it once five chunks have merged after the one that recorded the decision.
|
||||
|
||||
### 59. Bound a run of unfinished verdicts on one chunk, so a worker and judge that disagree cannot cycle unattended without end.
|
||||
|
||||
Raised by the product-owner review of PR #211. The resumed worker gets the judge's quote of the work remaining, but a worker that still thinks the chunk done can answer each cycle the same way, and each cycle costs a worker and a judge run (goal 1.4).
|
||||
|
||||
### 12. Run the test suite in CI on every PR, or record in `docs/decisions.md` why the local run is enough.
|
||||
|
||||
The repo has no CI, so larv-review's gate is the local run, and larv-review's Gate skips even that when the last stability round left the suite green: an unattended chunk can merge on the worker's own word.
|
||||
|
||||
When CI runs a rule check, such as one of `bin/rule-hook`'s, let `<!-- rule-override <rule>: <reason> -->` in the PR body override it.
|
||||
|
||||
### 105. Compare review rounds per pass and reading cost for the five chunks before and after the `worker:` decision moved the principles out of the worker's context, and file an item if either rose.
|
||||
|
||||
The `worker:` decision is valid while review rounds per pass do not rise. Count the rounds from each PR's `Answer <pass> round <n>:` commits, and take reading cost from `docs/reading-cost.md`. Run it once five chunks have merged after the one that recorded the decision.
|
||||
|
||||
### 135. Fingerprint only the modules loop-claude imports, so editing another tool's code no longer reloads a running loop.
|
||||
|
||||
The maintainability senior and the inherited architect of PR #257's scoring run named `bin/loop_claude/loop/reload.py:38` `fingerprint` and `:50` `exec_if_edited`: the fingerprint covers every `bin/**/*.py`, so editing `statusline.py` or `rank_todo.py` re-execs a running loop. Make `fingerprint` easier to read.
|
||||
@@ -343,32 +382,10 @@ The tests also cover `workflow-bench/bench.py`'s `permission_flags`, with a prob
|
||||
|
||||
Today the folder is the SHA-256 of the transcript's first timestamped line, which tells the human nothing; that line carries the start time. Drop the fallback to the first line, which every chunk of a project shares, and give the tests' fake transcripts ISO timestamps. `bin/reading-cost` takes a chunk's id from the folder's first 12 characters and skips a chunk whose id `docs/reading-cost.md` holds, so give it a way to match a figure written under the old name.
|
||||
|
||||
### 59. Bound a run of unfinished verdicts on one chunk, so a worker and judge that disagree cannot cycle unattended without end.
|
||||
|
||||
Raised by the product-owner review of PR #211. The resumed worker gets the judge's quote of the work remaining, but a worker that still thinks the chunk done can answer each cycle the same way, and each cycle costs a worker and a judge run (goal 1.4).
|
||||
|
||||
### 123. Have `bin/comprehension_history.py` parse each history entry once into seats, votes and places, so `latest_places`, `worse_places` and `worse_votes` neither depend on table order nor split a label to find a seat.
|
||||
|
||||
Three seats of PR #257's scoring run named `bin/comprehension_history.py:106` `latest_places`; the logic it rests on is `:114` `worse_places` and `:126` `worse_votes`. They regex the markdown the module writes. `worse_votes` keeps a seat's first row through `setdefault`, because the votes table comes first. `worse_places` recovers the seat with `label.split(",")[0]`. `Entry` still holds scoring seats' places for rulings recorded before PR #255. Make these functions easier to read.
|
||||
|
||||
### 132. Lift each dimension still under the comprehension floor after release 0.2.0's scoring run, at the places that run names.
|
||||
|
||||
Replaces item 62, which release 0.3.0's items split. PR #257's scoring run put Locality and Self-sufficiency at 6.63, Shape at 6.25 and the overall at 6.50, against the floor of 7.0 in `docs/decisions.md` → `comprehension floor: …`. Split this into items, one per place, once 0.3.0's scoring run has named them.
|
||||
|
||||
### 124. Group the shared modules at `bin/`'s root into packages named by purpose, so the root holds only launchers and stand-alone tools.
|
||||
|
||||
Shape is the lowest dimension, so this item moves goal 1.1 by 9, per `docs/decisions.md` → `larv-review: a project lifting itself to the comprehension floor starts at the lowest dimension`.
|
||||
|
||||
PR #257's scoring run put Shape at 6.25, the lowest dimension. `bin/` holds about 30 entries: 6 launchers, 6 tool packages, 3 shared packages and 13 root modules. Two root modules are tools (`rank_todo.py`, `statusline.py`) and 11 are shared libraries, and nothing in the layout tells them apart; only README's import-root paragraph maps them. Candidate packages: git running and parsing, the todo table with `rank_todo.py`'s formula language and goal weighing, and the comprehension history with round titles. `rank_todo.py` keeps its path, which every project's rules name. The `.gitignore` allowlist and README follow the move.
|
||||
|
||||
### 156. Drop `rank_todo.py`'s ranking of an old-shape table once no project under `~/code` holds one.
|
||||
|
||||
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 `rank_todo.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 `rank_todo.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.
|
||||
|
||||
### 155. Lower the reading cost of the files a chunk reads most before its first commit.
|
||||
|
||||
`bin/reading-cost` on 2026-10-16: the median of the last 5 chunks is 189,487 new input tokens before their first commit, up from 146,584 for the 5 before them. Read most over the last 5, by opens and searches: `todo.md` 51, `README.md` 12, `CHANGELOG.md` 11, `bin/loop_claude/test_loop_claude.py` 11, `AGENTS.md` 7, `bin/todo_table.py` 7, `docs/decisions.md` 7, `agents/stability-reviewer.md` 6, `bin/loop_claude/cycle/judge.py` 5, `bin/rule_hook/test_rule_hook.py` 5. The chunk that ships this item runs `bin/reading-cost --reset`.
|
||||
|
||||
### 1. Say in README → Install how the transcript archive is backed up, once bender-infra backs up ai-sandbox's data volume.
|
||||
|
||||
It lives under `~/.claude`, which `.gitignore` keeps from the remote, so a lost disk loses every unattended run's record. Back it up only to a destination private to me and encrypted at rest: the worker runs with permissions bypassed, so the archived tool results can hold credentials it read.
|
||||
@@ -381,12 +398,6 @@ The README line covers the bench's transcripts in `workflow-bench/logs/` too (go
|
||||
|
||||
Claude Code owns that file and writes it. `trust` reads it, changes it and writes it back, so a write that lands in between is lost.
|
||||
|
||||
### 5. Key a project on its checkout's full path, and refuse to start while another session uses that key.
|
||||
|
||||
The key names the project's session, archive folder and models entry. `project_key` drops the leading `/`, so `~/code/a` and `/a` share all three, and one loop can resume or delete the other's session.
|
||||
|
||||
`bin/reading-cost` keys the archive by the main checkout, the parent of git's common dir, since it runs in a chunk's worktree; `loop-claude` keys it by `--show-toplevel`, so a loop started inside a worktree archives where `reading-cost` never looks. Derive both keys one way.
|
||||
|
||||
### 77. 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.
|
||||
|
||||
2026-10-08, lilleman: no metric enters review until a rerun on more data shows it tracking the panel.
|
||||
@@ -417,14 +428,20 @@ Claude's misses ranked the named units at a coin toss. Top k scores 0.50 by chan
|
||||
|
||||
Claude's answers overlapped the truth by a median Jaccard index of 0.76. A run took in 62,643 new input tokens and cost $0.70; it did not record which model answered. Grep answers these questions whatever the code's shape, so no question enters review; a new question bench would need questions that take understanding the code, not finding it.
|
||||
|
||||
### 51. Hand loop-claude's terminal output to an injected effect, so no storage or retry function prints.
|
||||
|
||||
"Functional core, imperative shell", in `principles/technical-principles.md`: `archive`, `trust`, `retried`, the worker, `interrupt` and `model_choice` print to stderr themselves, and the tests swap the global stream.
|
||||
|
||||
### 151. Keep 10 to 20 settled decisions per project as its goals' test set, and rerun them after a goal changes.
|
||||
|
||||
Each case is a question the project settled and the answer it chose. A fresh-context agent given only the README's premises answers each case; a case it answers differently says the goals no longer decide it. Written guidance can fail to change behaviour, which is why the goals get a test.
|
||||
|
||||
### 5. Key a project on its checkout's full path, and refuse to start while another session uses that key.
|
||||
|
||||
The key names the project's session, archive folder and models entry. `project_key` drops the leading `/`, so `~/code/a` and `/a` share all three, and one loop can resume or delete the other's session.
|
||||
|
||||
`bin/reading-cost` keys the archive by the main checkout, the parent of git's common dir, since it runs in a chunk's worktree; `loop-claude` keys it by `--show-toplevel`, so a loop started inside a worktree archives where `reading-cost` never looks. Derive both keys one way.
|
||||
|
||||
### 51. Hand loop-claude's terminal output to an injected effect, so no storage or retry function prints.
|
||||
|
||||
"Functional core, imperative shell", in `principles/technical-principles.md`: `archive`, `trust`, `retried`, the worker, `put_question` and `model_choice` print to stderr themselves, and the tests swap the global stream.
|
||||
|
||||
### 52. Record why this checkout lives in Claude Code's own directory, or move it out and link it in.
|
||||
|
||||
"One owner per value" and "Prefer the vendor-neutral option", in `principles/technical-principles.md`: git, Claude Code and loop-claude all write `~/.claude`, kept apart only by the `.gitignore` allowlist, and the repo's records live in a vendor directory.
|
||||
|
||||
Reference in New Issue
Block a user