Compare commits
81 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| b348e8be5f | |||
| 075259814b | |||
| 7570af6191 | |||
| ac69f6da6d | |||
| fe4c4f3729 | |||
| 02f4a698b5 | |||
| d8338e71ed | |||
| 7827ff2f05 | |||
| 5fc6fdd2c1 | |||
| ccfc8873f7 | |||
| cad17204da | |||
| 2dd346f40d | |||
| eee8d534a5 | |||
| c2697c6281 | |||
| a9a19fdbae | |||
| a5eba3944b | |||
| 4d8f348e2d | |||
| e0f577b5b4 | |||
| 8ce49c5b21 | |||
| ca133057d8 | |||
| c184c7f650 | |||
| 11f4c5ab17 | |||
| e2fe71b842 | |||
| b9c9162093 | |||
| 016fbb2441 | |||
| 450f0b3851 | |||
| abe4658e9e | |||
| a0e190553b | |||
| 71ab3174d4 | |||
| 9aa0d4b4b2 | |||
| c6733cc282 | |||
| 70dcd47ed8 | |||
| 9af5ee7ee0 | |||
| c28e72bfc2 | |||
| 3ed118b3ea | |||
| c08a55f6a4 | |||
| 00a0f750b2 | |||
| a012f38617 | |||
| 28a8741a10 | |||
| 1956fb45f4 | |||
| a0d4fc3d15 | |||
| d91484c80b | |||
| b793f22499 | |||
| 298096ea5f | |||
| 157ca50733 | |||
| 5b7da27a5a | |||
| 545f3c3478 | |||
| 10b0bca037 | |||
| d64ebd0db3 | |||
| 0f71e33dfe | |||
| 1283bf61d3 | |||
| 798bf505b2 | |||
| 62eba5f513 | |||
| 5b19233f37 | |||
| 45cb331a49 | |||
| 3de24d2933 | |||
| 60760fd995 | |||
| ccc6b8adb2 | |||
| d671053b21 | |||
| e08f8d7ef8 | |||
| aab268c0a9 | |||
| aa7529b03f | |||
| 2f5d7a469d | |||
| 501fc8c606 | |||
| ddb86cb7ec | |||
| a2bf2a7cd9 | |||
| f643a14550 | |||
| 89a7485684 | |||
| 8705c05043 | |||
| 1204acacaa | |||
| 2752c2dae3 | |||
| 17f94b461a | |||
| 44d882f9e2 | |||
| c2a4757d56 | |||
| 4f722d94f4 | |||
| 7cce6e7ae1 | |||
| ae7161d2f4 | |||
| 6f3fdcb993 | |||
| 7fa8292239 | |||
| 9fa570a0f5 | |||
| f705fa626f |
@@ -53,10 +53,15 @@
|
||||
!bin/routing_figures/*.py
|
||||
!bin/rule_hook/
|
||||
!bin/rule_hook/*.py
|
||||
!bin/rung_replay/
|
||||
!bin/rung_replay/*.py
|
||||
!bin/score-outcomes
|
||||
!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/
|
||||
|
||||
@@ -26,7 +26,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 and goal weights it states, held to its bar, ranked by `bin/rank_todo.py`
|
||||
- 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: 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
|
||||
@@ -37,7 +37,9 @@ Decisions live in `docs/decisions.md`:
|
||||
- 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 R + C picks a rung by fixed bands, counted from the cheapest rung of the project's model, and a chunk's worker may run below that rung, launching its reviewers on that rung; the worker routes each subagent it delegates to by the R + C of the subagent's task
|
||||
- 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: on a model judge-replay covered, the judge runs on the rung its chunk's item picks, never below the project's rung
|
||||
- routing: the stability reviewer stays on 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
|
||||
|
||||
## Working rules
|
||||
|
||||
|
||||
+12
-1
@@ -2,10 +2,21 @@
|
||||
|
||||
## Unreleased
|
||||
|
||||
- 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:**`, 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.
|
||||
- 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.
|
||||
|
||||
## 0.1.0
|
||||
|
||||
- `todo.md`'s items table has a Blocked by column, right after Release, listing the IDs of the items that must be done before an item starts, such as `12, 14`. Move every machine to this release before any of them ranks a plan another machine shares: an older release reads the new table as no plan. `rank_todo.py` ranks each blocker above every item it blocks, drops an ID once that item leaves the table, and adds the column to a table without it. It does not turn a line such as "Needs 12" in an item's detail into a Blocked by cell; move each into the column by hand. It now fails on text beside the table under `## Items`, such as a line naming items to take first: put an order in the scores or the column. It reads the table's cells by column name, and fails on a column it does not know rather than drop it. `loop-claude` routes a chunk on the next release's first item that is neither marked `question` nor blocked by an item still in the table, which is the item the worker takes, so the first cycle runs on that item's rung.
|
||||
- The new `bin/stability-replay <model>` replays archived stability reviews of the projects run on the model, each on the code it reviewed, first on the project's rung and then on each rung below, and prints the lowest rung that, like each rung above it, finds every 🔴 and 🟡 finding the project's rung finds. It shares its search with `judge-replay`, which now tries rungs from the project's rung down, where it tried them from the cheapest up. Its first run, on Opus 5.5 projects, found none: Sonnet 5.5 at high missed 13 of the 29 findings the project's rung found again. So the stability reviewer stays on the project's rung while the worker runs below it.
|
||||
- A `todo.md` item you tell a session to keep is marked `owner` in its Exempt cell, and stays whatever its score.
|
||||
- A `loop-claude` worker hands a task that proves too hard for its rung to a subagent one rung up, edits included, when a trigger fires: a re-score of the item on the project's rung or above picks a higher rung, the same failing test or finding survives two fix attempts, or a review pass reports a 🔴 in round 2 or later. Each further trigger climbs one more rung, to at most two rungs above the rung the chunk's `todo.md` item picks, unless you agree. `CLAUDE.md` states the rule, and `loop-claude`'s prompt names the rungs a trigger opens. The worker opens the subagent's prompt with `Escalation trigger <n>:`, and `routing-figures.md` counts the escalations by trigger. Expect a chunk that gets stuck to spend more on the stuck part, and fewer unfinished verdicts.
|
||||
- A loop-claude worker may end its run asking for a higher rung, citing an escalation trigger. Once the judge quotes the transcript passage that shows the trigger fired, the next cycle resumes the worker one rung up, up to two rungs above the rung the chunk's `todo.md` item picks. The archive quotes that passage under `Escalation:` in the unfinished verdict.
|
||||
- A reviewer that rules a chunk's work below standard, with systems-architect's BLOCK or a finding against larv-review's `standards/quality.md`, may ask to rerun one rung up, as may a comprehension seat whose vote in a paired ruling `record-ruling` counts as worse. The worker relaunches it once, on the rung `loop-claude`'s prompt names. A relaunched reviewer gets the report that asked and confirms or dismisses each of its findings. The relaunch's report stands in place of the one that asked, in the same round, so it adds no round. The ruling that stands is a fourth escalation trigger in `CLAUDE.md`. Expect a chunk whose work falls below standard to spend more on its review and its fix.
|
||||
- A session or subagent below the project's rung, the cheapest rung of the project's model, no longer scores or reshapes `todo.md`: it drafts each new item and each change to a filed item, and before its next commit one subagent on the project's rung or above applies and scores the drafts and sets their release. It may still remove finished items. `rules/todo-items.md` states the rule. `CLAUDE.md` has a session launch a subagent that files or scores items on the rung the new `bin/subagent-rung --plan <model> <R+C>` prints, never below the project's rung, and `loop-claude`'s prompt to a worker below that rung names the command. Expect one extra subagent in a chunk that files items while its worker runs below the project's rung.
|
||||
- `loop-claude` runs the judge of an Opus 5.5 project on the rung the chunk's `todo.md` item picks, never below Opus 5.5 at medium effort, the project's rung. Before, the judge ran at the effort `settings.json` sets, xhigh. A replay of 39 archived verdicts found every cheaper rung missing verdicts. The judge keeps its rung when the worker steps up or takes in another item, and runs on the project's rung when no item routed the chunk. A project on another model keeps its judge at its settings' effort. Each verdict in the archive now names the judge's rung on a `Judge:` line. The new `bin/judge-replay <model>` replays the judge on archived verdicts and prints the cheapest rung that returns them. Expect the judge to cost less on items of R + C 12 or less, and more on items of R + C 15 or more.
|
||||
- `loop-claude` runs the judge of an Opus 5.5 project on the rung the chunk's `todo.md` item picks, never below Opus 5.5 at medium effort, the project's rung. Before, the judge ran at the effort `settings.json` sets, xhigh. A replay of 39 archived verdicts found every cheaper rung missing verdicts. The judge keeps its rung when the worker steps up or takes in another item, and runs on the project's rung when no item routed the chunk. A project on another model keeps its judge at its settings' effort. Each verdict in the archive now names the judge's rung on a `Judge:` line. The new `bin/judge-replay <model>` replays the judge on archived verdicts and prints the lowest rung that, like each rung above it, returns them. Expect the judge to cost less on items of R + C 12 or less, and more on items of R + C 15 or more.
|
||||
- Every 20 cycles across all projects, `loop-claude` measures every finished chunk in its archive, with no model run, and writes the figures to `routing-figures.md` at the archive's root: tokens by project, subagent type, rung and tool, and, for each chunk a `todo.md` item routed, grouped by the rung it started on: its review rounds past each pass's first, its unfinished verdicts and its subagents' rungs. It interrupts you, with `claude` on the project's model on the terminal in `~/.claude`, when chunks routed onto a rung took more review rounds or unfinished verdicts than chunks routed onto the next rung up, each rung with 5 chunks or more, or when 5 or more subagents of one type wrote reports longer than the tool results they read. Each call is raised once, then listed in `routing-calls-raised.md` beside the figures; the next chunk of this repo files a `todo.md` item for it. Off a terminal, the calls are said on stderr and the loop goes on. They are raised at the next measurement on a terminal. After a routing change, a `- <UTC time> Reset` line in that file makes the figures count only chunks finished after it, and lets its calls be raised again. Expect a pause of about ten seconds at each measurement.
|
||||
- A session delegates a task to a subagent only when it needs just the task's conclusion, such as a search across many files, and keeps edits in its own thread. It scores the task's R and C as for a `todo.md` item, and launches the subagent on the model and effort that the new `bin/subagent-rung <model> <R+C>` picks from the project's model, such as `model sonnet, effort high`. `CLAUDE.md` states the rule. Expect searches to run on cheaper models, and less of each session's context to fill with search output.
|
||||
- `loop-claude` routes each chunk's worker on a ladder of model and effort rungs, from Haiku 5.5 at low effort to Fable 5.1 at max, when the project's model is on it. As a chunk starts, the R + C of `todo.md`'s top item in the next release picks the rung: 11–12 picks one rung above the project's rung, so Opus 5.5 at high for an Opus 5.5 project, and so on up to four rungs. An item of R + C 10 or less runs the worker at or below the project's model's cheapest rung, which for Opus 5.5 is medium effort, below the xhigh `settings.json` sets. While the worker runs below the project's model's cheapest rung, it launches every reviewer, comprehension seat and security pass, the full scan included, in a subagent on that rung. While it runs above that rung, it launches each comprehension seat and the security pass on that rung. It steps up one rung after every second unfinished verdict on a chunk, and to a higher rung when it takes in an item of higher R + C. Each cycle's header, and each finished or unfinished verdict, stop and step-up in the archive, name the worker's rung; a rerun resumes an open chunk on the latest rung archived for it. `docs/decisions.md` → `routing:` gives the ladder, its source and the bands. Expect a chunk on an easy item to cost much less than under xhigh, and perhaps to take more review rounds, and one on an item of R + C 15 or more to cost more.
|
||||
|
||||
@@ -5,20 +5,20 @@
|
||||
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.
|
||||
- **Plan `todo.md` as one scored table**: every item names the release that ships it. If `todo.md` has another shape, reshaping it is the chunk, and the human approves it.
|
||||
- **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.
|
||||
- **Open every chunk with one line:** the last version cut, how many changes are unreleased (the entries under `CHANGELOG.md` → `## Unreleased`, or else the commits since the last tag), and the release this chunk ships into. A repo that publishes nothing says so once.
|
||||
- **Read the README's `## Goals` and `## Audience` before starting a chunk, unless your prompt quotes them.** The chunk's items set its scope. The goals choose between ways to deliver those items, and never add to them.
|
||||
- **Read the plan and the decisions only as far as the chunk needs.** Run `grep -n '^## Details' todo.md`, then read `todo.md` with the Read tool up to the line it prints, or whole when it prints none. Then read the details of only the items the chunk takes. `AGENTS.md` lists every decision's title. Read the entry under a title in `docs/decisions.md` only where the title leaves open what the chunk or the review needs.
|
||||
- **Work one chunk at a time, and make it as large as one purpose allows.** Every review has a fixed cost, so a chunk takes the next plan item plus every other item for which three things hold: one PR title states what they achieve together, without listing them; they name one release; and they fire the same review passes (`larv-review` §3). Tiny items, a few lines of change each, need neither a shared purpose nor the same passes: bundle up to ten that name one release into one chunk. Split a milestone into items in `todo.md` before starting it. Fix a finding in the chunk's own change within the chunk. File a finding about anything else in `todo.md`. An item marked `question` waits for the human; take the next item.
|
||||
- **Work one chunk at a time, and make it as large as one purpose allows.** Every review has a fixed cost, so a chunk takes the next plan item plus every other item for which four things hold: one PR title states what they achieve together, without listing them; they name one release; they fire the same review passes (`larv-review` §3); and no item outside the chunk blocks one of them. The next plan item is the first that does not wait: an item waits while it is marked `question`, until the human answers, or while an item that blocks it is still in the plan. Tiny items, a few lines of change each, need neither a shared purpose nor the same passes: bundle up to ten that name one release, and that no item outside the chunk blocks, into one chunk. Split a milestone into items in `todo.md` before starting it. Fix a finding in the chunk's own change within the chunk. File a finding about anything else in `todo.md`.
|
||||
- **Ask, don't guess.** First check whether the goals already answer the question. If they nearly do, propose a change to the goals and show how it answers this case: an answer settles one question, a goal settles every question like it. Write every answer once, where it belongs, never only in chat: a goal in `README.md`, a working rule in `AGENTS.md`, a standing choice in a comment at the one place it governs, or in `docs/decisions.md` once made in more than one place. When an answer holds a goal and a choice, write the goal in the README, and record as a choice only what the goal leaves open.
|
||||
- **Bench a syntax with the people who write it.** Before a new or changed spelling of something users read or write ships — markdown, HTML, a config key, a CLI flag — a panel of fresh-context readers, seated as those users from the README's `## Audience`, picks it.
|
||||
- **Implement the simplest change that solves the item, and ship it with `/larv-review`.** Whenever a test can check the change, write that test first and see it fail. larv-review's reviewers hold the change to the technical principles, and a finding against one names it. Read a file under `~/.claude/principles/` only when the item changes it, a finding or a record you write names it, or you decline a finding.
|
||||
- **Remove a finished item's row and detail from `todo.md`, and revise any decision that cites it.** If the repo publishes something others consume — a package, an image, an API — reword the item for them and move it to `CHANGELOG.md` under `## Unreleased`. A changelog is for the public, never for the next agent. Otherwise delete it; git history is the record.
|
||||
- **Releases are the human's.** The version bump and the publishing credentials are theirs, whatever another rule says. Prepare everything else, so cutting a release is one decision.
|
||||
- **Open each `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. 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.
|
||||
- **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.
|
||||
|
||||
## Prose
|
||||
|
||||
|
||||
@@ -4,15 +4,30 @@ My personal `~/.claude`, version controlled: `CLAUDE.md`, `AGENTS.md` and `rules
|
||||
|
||||
## Goals
|
||||
|
||||
1. Get the highest quality out of Claude Code while interrupting me the least, so development scales.
|
||||
1. Proven, stellar output quality: code, documentation and plans.
|
||||
2. Decide by the project's goals when confident; ask me when not, and never the same thing twice.
|
||||
3. The same rules in every project and every session.
|
||||
4. Add cost only where it meaningfully raises quality; otherwise work to lower cost.
|
||||
5. Delivery speed.
|
||||
2. Make my claude setup shareable between computers.
|
||||
3. Keep my claude setup and the transcripts of unattended runs, the bench's included, backed up.
|
||||
4. Leak nothing to the remote — no credentials, no transcripts, no memory files.
|
||||
1. **Achieve:** Get the highest quality out of Claude Code while interrupting me the least, so development scales.
|
||||
- Signal: interrupts of me per finished chunk fall.
|
||||
- Counter-signal: findings that a later change fixes, per finished chunk, rise.
|
||||
- Why: fewer asks buy nothing if the output gets worse.
|
||||
1. **Achieve:** Proven, stellar output quality: code, documentation and plans.
|
||||
- Signal: 🔴 and 🟡 findings that review raises per chunk fall.
|
||||
- Counter-signal: later changes that fix a chunk's code rise.
|
||||
- Why: review findings show the first draft's quality, later fixes show what review missed.
|
||||
2. **Achieve:** Decide by the project's goals when confident; ask me when not, and never the same thing twice.
|
||||
- Signal: asks that a goal or decision already settled fall to zero.
|
||||
- Counter-signal: decisions I reverse rise.
|
||||
- Why: guessing instead of asking saves an interrupt only if the guess holds.
|
||||
3. **Maintain:** The same rules in every project and every session.
|
||||
4. **Achieve:** Add cost only where it meaningfully raises quality; otherwise work to lower cost.
|
||||
- Signal: tokens per finished chunk fall.
|
||||
- Counter-signal: review rounds or unfinished verdicts per chunk rise.
|
||||
- Why: a cheaper run that needs more rounds costs more.
|
||||
5. **Achieve:** Delivery speed.
|
||||
- Signal: hours from a chunk's start to its merge fall.
|
||||
- Counter-signal: 🔴 findings per chunk rise.
|
||||
- Why: speed bought by skipping review shows up as defects.
|
||||
2. **Maintain:** Make my claude setup shareable between computers.
|
||||
3. **Maintain:** Keep my claude setup and the transcripts of unattended runs, the bench's included, backed up.
|
||||
4. **Maintain:** Leak nothing to the remote — no credentials, no transcripts, no memory files.
|
||||
|
||||
## Audience
|
||||
|
||||
@@ -67,7 +82,7 @@ Rename `## Unreleased` in `CHANGELOG.md` to the version, commit, tag that commit
|
||||
|
||||
Install puts only `loop-claude` on `PATH`; call the others by their path, such as `~/.claude/bin/metric-bench`, from the project's checkout.
|
||||
|
||||
- `judge-replay <model>` replays loop-claude's judge on archived verdicts of the projects run on the model, and prints the cheapest rung that returns them; `judge-replay --help` states the replay.
|
||||
- `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; `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.
|
||||
@@ -75,6 +90,7 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a
|
||||
- `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.
|
||||
- `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 and Write call, and `rule-hook --help` states the rules and the override.
|
||||
- `score-outcomes [R S C]` lists the finished items whose guessed R, S and C sit nearest the given scores, with what their chunks measured, and each score's median outcome; `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> <R+C>` prints the Agent tool's model and effort for a subagent's task, picked by its R + C from the project's model, and with `--plan` never below the project's rung; `subagent-rung --help` states the rule.
|
||||
|
||||
@@ -93,7 +109,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, and `judge_replay` imports `loop_claude`'s judge. 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, `score_outcomes` imports `reading_cost`'s record path, `judge_replay` imports `loop_claude`'s judge. `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.
|
||||
|
||||
## Tracking a new file
|
||||
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
"""One `claude -p --output-format json` run, as loop-claude's judge and the replays start it."""
|
||||
import dataclasses
|
||||
import subprocess
|
||||
import typing
|
||||
|
||||
from failure import Failure
|
||||
from claude_code.entries import hit_limit, limit_said, parse_entry
|
||||
|
||||
# Effects.claude: claude's arguments, its working directory and the prompt it reads on stdin.
|
||||
Claude = typing.Callable[[list[str], str, str], subprocess.CompletedProcess[str]]
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Limited:
|
||||
"""claude hit a usage limit; said is claude's message about it, and resets_at is when the limit resets, in seconds since the epoch, or None when unknown."""
|
||||
resets_at: int | None
|
||||
said: str
|
||||
|
||||
|
||||
# The json reply claude_reply parses; no persistence, so its runs stay out of the session picker; no permission prompt, as no one answers it.
|
||||
HEADLESS = ["--no-session-persistence", "--output-format", "json", "--permission-mode", "bypassPermissions"]
|
||||
|
||||
|
||||
def claude_reply(claude: Claude, args: list[str], cwd: str, prompt: str, who: str) -> dict | Failure | Limited:
|
||||
"""claude's json reply to `claude -p <args>` and HEADLESS, or why there is none; who, such as "the judge", names the run in the message for a non-zero exit or a reply that is no json."""
|
||||
try:
|
||||
proc = claude(["-p", *args, *HEADLESS], cwd, prompt)
|
||||
except OSError as failure:
|
||||
return Failure(f"could not start claude: {failure.strerror}")
|
||||
reply = parse_entry(proc.stdout)
|
||||
# The json output names the reset only in prose, such as "resets 7:40pm (Europe/Stockholm)", so its limit carries no reset time.
|
||||
if reply is not None and hit_limit(reply):
|
||||
return Limited(None, limit_said(reply))
|
||||
if proc.returncode != 0:
|
||||
return Failure(proc.stderr.strip() or f"{who} exited {proc.returncode}")
|
||||
if reply is None:
|
||||
return Failure(f"{who} printed no json reply; it printed: {proc.stdout.strip() or 'nothing'}")
|
||||
return reply
|
||||
@@ -1,11 +1,13 @@
|
||||
import json
|
||||
import pathlib
|
||||
import subprocess
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from claude_code import entries, transcript, trust
|
||||
from claude_code import entries, reply, transcript, trust
|
||||
from failure import Failure
|
||||
|
||||
|
||||
def assistant(*parts):
|
||||
@@ -80,6 +82,37 @@ class Parse(unittest.TestCase):
|
||||
self.assertIsNone(entries.parse_entry("[1, 2]"))
|
||||
|
||||
|
||||
class ClaudeReply(unittest.TestCase):
|
||||
@staticmethod
|
||||
def claude(*outcomes):
|
||||
def run(args, cwd, prompt):
|
||||
outcome = outcomes[0]
|
||||
if isinstance(outcome, OSError):
|
||||
raise outcome
|
||||
return subprocess.CompletedProcess(args, *outcome)
|
||||
return run
|
||||
|
||||
def test_runs_claude_headless_with_the_args_in_cwd_on_the_prompt(self):
|
||||
asked = []
|
||||
|
||||
def run(args, cwd, prompt):
|
||||
asked.append((args, cwd, prompt))
|
||||
return subprocess.CompletedProcess(args, 0, "{}", "")
|
||||
|
||||
reply.claude_reply(run, ["--tools", ""], "/r", "p", "the judge")
|
||||
self.assertEqual(asked, [(["-p", "--tools", "", "--no-session-persistence", "--output-format", "json", "--permission-mode", "bypassPermissions"], "/r", "p")])
|
||||
|
||||
def test_returns_the_json_reply_a_usage_limit_whatever_the_exit_code_or_why_there_is_none(self):
|
||||
self.assertEqual(reply.claude_reply(self.claude((0, '{"result": "ok"}', "")), [], "/r", "p", "the judge"), {"result": "ok"})
|
||||
self.assertEqual(reply.claude_reply(self.claude((0, "Warning: hook said hi\n", "")), [], "/r", "p", "the judge"), Failure("the judge printed no json reply; it printed: Warning: hook said hi"))
|
||||
self.assertEqual(reply.claude_reply(self.claude((0, "", "")), [], "/r", "p", "the judge"), Failure("the judge printed no json reply; it printed: nothing"))
|
||||
limit = json.dumps({"type": "result", "api_error_status": 429, "result": "You've hit your limit"})
|
||||
self.assertEqual(reply.claude_reply(self.claude((1, limit, "")), [], "/r", "p", "the judge"), reply.Limited(None, "You've hit your limit"))
|
||||
self.assertEqual(reply.claude_reply(self.claude((2, "", " ")), [], "/r", "p", "the judge"), Failure("the judge exited 2"))
|
||||
self.assertEqual(reply.claude_reply(self.claude((2, "", "boom\n")), [], "/r", "p", "the judge"), Failure("boom"))
|
||||
self.assertEqual(reply.claude_reply(self.claude(FileNotFoundError(2, "No such file or directory")), [], "/r", "p", "claude"), Failure("could not start claude: No such file or directory"))
|
||||
|
||||
|
||||
class MarkTrusted(unittest.TestCase):
|
||||
def test_returns_the_updated_config_and_leaves_the_one_it_was_handed(self):
|
||||
config = {"other": 1, "projects": {"/a": {"hasTrustDialogAccepted": True}, "/b": {"kept": True}}}
|
||||
|
||||
+28
-65
@@ -1,4 +1,4 @@
|
||||
"""Replay loop-claude's judge on archived verdicts, to find the cheapest rung that returns them: docs/decisions.md → `routing: on a model judge-replay covered`.
|
||||
"""Replay loop-claude's judge on archived verdicts, to find the lowest rung that returns them: docs/decisions.md → `routing: on a model judge-replay covered`.
|
||||
|
||||
usage: judge-replay <model>
|
||||
|
||||
@@ -11,104 +11,78 @@ with the task, premises and records each project holds now.
|
||||
It first replays every verdict on the reference judge: the model at xhigh effort, the rung the
|
||||
judge ran on before loop-claude routed it. A verdict the reference judge returns another kind on
|
||||
may rest on records or judge rules that have changed since; either way no rung is held to it. It
|
||||
then replays the rest on each candidate rung, cheapest first: from the rung the lowest R + C picks
|
||||
up to the model's cheapest rung. It stops at the first rung that returns all of them. It prints
|
||||
each verdict the reference judge did not reproduce, each verdict a rung missed, and the cheapest
|
||||
rung that missed none. A rung it names is the evidence to add the model to JUDGE_REPLAYED in
|
||||
bin/loop_claude/routing.py, which routes that model's judge, and to record the run in
|
||||
docs/decisions.md → `routing: on a model judge-replay covered`.
|
||||
then replays the rest on each candidate rung, highest first: from the model's cheapest rung down
|
||||
to the rung the lowest R + C picks. It stops at the first rung that misses one. It prints each
|
||||
verdict the reference judge did not reproduce, each verdict a rung missed, and the lowest rung
|
||||
that, like each rung above it, missed none. A rung it names is the evidence to add the model to
|
||||
JUDGE_REPLAYED in bin/loop_claude/routing.py, which routes that model's judge, and to record the
|
||||
run in docs/decisions.md → `routing: on a model judge-replay covered`.
|
||||
|
||||
Like the loop, it tries a judge three times running before it counts the reply as failed. A
|
||||
verdict whose project or transcript cannot be read replays as failed too. Exit 1, saying why, on
|
||||
bad arguments, an unreadable archive or models file, no archived verdict of the model's projects,
|
||||
or a usage limit.
|
||||
"""
|
||||
import concurrent.futures
|
||||
import pathlib
|
||||
import sys
|
||||
import typing
|
||||
|
||||
from transcript_archive.location import archive_root, transcript_of
|
||||
from transcript_archive.read import archived_outcomes
|
||||
from judge_replay.replay import Case, case_from, Kind, replayed, report, sample, verdict_kind
|
||||
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 loop_claude.cycle.retry import FAILURES_RUNNING, Limited
|
||||
from rung_replay.search import first_reply, replayed
|
||||
from loop_claude.cycle.judge import judge_once, Verdict
|
||||
from model_routing.ladder import LADDER, picked, position, project_rung, Rung
|
||||
from loop_claude.project.model_choice import read_models_file
|
||||
from claude_code.reply import Limited
|
||||
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 loop_claude.stop import Stop
|
||||
|
||||
TOOL = "judge-replay"
|
||||
PER_KIND = 15
|
||||
# The effort settings.json gave every judge before loop-claude routed it; the archived verdicts came from it.
|
||||
REFERENCE_EFFORT = "xhigh"
|
||||
# Judges replayed at once.
|
||||
AT_ONCE = 4
|
||||
LOWEST_R_PLUS_C = 2
|
||||
USAGE = "usage: judge-replay <model>, a model on the routing ladder"
|
||||
|
||||
|
||||
def main(argv: list[str], env: typing.Mapping[str, str], home: pathlib.Path, effects: Effects) -> int:
|
||||
if argv[:1] in (["-h"], ["--help"]):
|
||||
print(__doc__.strip())
|
||||
return 0
|
||||
anchor = project_rung(argv[0]) if len(argv) == 1 else None
|
||||
if anchor is None:
|
||||
print(f"judge-replay: cannot read the arguments{' ' + ' '.join(argv) if argv else ''}; {USAGE}", file=sys.stderr)
|
||||
return 1
|
||||
cases = archived_cases(argv[0], archive_root(home, env), home)
|
||||
anchor = project_rung_or_exit(TOOL, argv, __doc__)
|
||||
if isinstance(anchor, int):
|
||||
return anchor
|
||||
cases = archived_cases(anchor.model, archive_root(home, env), home)
|
||||
if isinstance(cases, Failure):
|
||||
print(f"judge-replay: {cases.reason}", file=sys.stderr)
|
||||
return 1
|
||||
return failed(TOOL, cases.reason)
|
||||
if not cases:
|
||||
print(f"judge-replay: no archived verdicts of projects on {argv[0]} in {archive_root(home, env)}; run loop-claude on a project on that model first", file=sys.stderr)
|
||||
return 1
|
||||
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(argv[0], REFERENCE_EFFORT)
|
||||
candidates = list(LADDER[position(picked(anchor, LOWEST_R_PLUS_C)):position(anchor) + 1])
|
||||
replay = replayed(cases, reference, candidates, lambda on, rung: rule_all(on, rung, home / ".claude", effects))
|
||||
reference = Rung(anchor.model, REFERENCE_EFFORT)
|
||||
replay = replayed(cases, reference, down_from(anchor), lambda found, rung: rule(found, rung, home / ".claude", effects), reproduced, "verdicts")
|
||||
if isinstance(replay, Limited):
|
||||
print(f"judge-replay: claude hit a usage limit: {replay.said}; replay again once it resets", file=sys.stderr)
|
||||
return 1
|
||||
print(report(argv[0], reference, cases, replay))
|
||||
return limited_exit(TOOL, replay)
|
||||
print(report(anchor.model, reference, cases, replay))
|
||||
return 0
|
||||
|
||||
|
||||
def archived_cases(model: str, root: pathlib.Path, home: pathlib.Path) -> list[Case] | Failure:
|
||||
models = read_models_file(home / ".claude" / "loop-claude-models.json")
|
||||
if isinstance(models, Stop):
|
||||
return Failure(models.reason)
|
||||
projects = projects_on(model, home)
|
||||
if isinstance(projects, Failure):
|
||||
return projects
|
||||
listed = archived_outcomes(root)
|
||||
if isinstance(listed, Failure):
|
||||
return listed
|
||||
found = []
|
||||
try:
|
||||
for key, outcomes in listed:
|
||||
case = case_from(checkout_of(key, home), outcomes.read_text(encoding="utf-8"), transcript_of(outcomes)) if models.get(key) == model else None
|
||||
case = case_from(checkout_of(key, home), outcomes.read_text(encoding="utf-8"), transcript_of(outcomes)) if key in projects else None
|
||||
found += [case] if case else []
|
||||
except (OSError, UnicodeDecodeError) as failure:
|
||||
return Failure(f"could not read the archive {root}: {failure}")
|
||||
return found
|
||||
|
||||
|
||||
def rule_all(cases: list[Case], rung: Rung, claude_dir: pathlib.Path, effects: Effects) -> list[Kind] | Limited:
|
||||
print(f"replaying {len(cases)} verdicts on {rung}", file=sys.stderr, flush=True)
|
||||
with concurrent.futures.ThreadPoolExecutor(AT_ONCE) as pool:
|
||||
running = [pool.submit(rule, found, rung, claude_dir, effects) for found in cases]
|
||||
kinds = []
|
||||
for future in running:
|
||||
kind = future.result()
|
||||
if isinstance(kind, Limited):
|
||||
pool.shutdown(cancel_futures=True)
|
||||
return kind
|
||||
kinds.append(kind)
|
||||
return kinds
|
||||
|
||||
|
||||
def rule(case: Case, rung: Rung, claude_dir: pathlib.Path, effects: Effects) -> Kind | Limited:
|
||||
premises, records, entries = read_premises(case.root), read_records(case.root, claude_dir), read_transcript(str(case.transcript))
|
||||
if isinstance(premises, Stop):
|
||||
@@ -117,16 +91,5 @@ 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 = first_reply(lambda: judge_once(case.root, case.task, premises, records, render(entries), rung, effects))
|
||||
verdict: Verdict | Failure | Limited = first_reply(lambda: judge_once(case.root, case.task, premises, records, render(entries), rung, effects))
|
||||
return verdict if isinstance(verdict, Limited) else verdict_kind(verdict)
|
||||
|
||||
|
||||
def first_reply(attempt: typing.Callable[[], Verdict | Failure | Limited]) -> Verdict | Failure | Limited:
|
||||
"""The first reply that is no Failure, or the last of FAILURES_RUNNING failures.
|
||||
|
||||
It counts failures as the loop's retried does, but neither waits between attempts nor waits out a usage limit, which ends the replay.
|
||||
"""
|
||||
for _ in range(FAILURES_RUNNING - 1):
|
||||
if not isinstance(verdict := attempt(), Failure):
|
||||
return verdict
|
||||
return attempt()
|
||||
|
||||
+12
-40
@@ -1,4 +1,4 @@
|
||||
"""Which archived verdicts to replay, the cheapest rung that returns them, and the report: docs/decisions.md → `routing: on a model judge-replay covered`."""
|
||||
"""Which archived verdicts to replay, what a replay reproduces, and the report: docs/decisions.md → `routing: on a model judge-replay covered`."""
|
||||
import collections
|
||||
import dataclasses
|
||||
import pathlib
|
||||
@@ -7,7 +7,7 @@ import typing
|
||||
from transcript_archive.outcomes import ANSWERED, FINISHED, first_verdict, INTERRUPTED, task_of, UNFINISHED
|
||||
from failure import Failure
|
||||
from loop_claude.cycle.judge import Finished, Interrupt, QuotedAnswer, Unfinished, Verdict
|
||||
from loop_claude.cycle.retry import Limited
|
||||
from rung_replay.search import Replay
|
||||
from model_routing.ladder import Rung
|
||||
|
||||
# claude's reply as the replay compares it: a verdict as the archive words it, such as FINISHED, or a failure with its reason.
|
||||
@@ -24,21 +24,6 @@ class Case:
|
||||
on_record: Kind
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Tried:
|
||||
"""A rung, and each case it returned another kind on, with that kind."""
|
||||
rung: Rung
|
||||
missed: list[tuple[Case, Kind]]
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Replay:
|
||||
"""unreproduced holds each case the reference judge returned another kind on; tried, each rung tried, cheapest first; cheapest, the first rung that missed none, or None."""
|
||||
unreproduced: list[tuple[Case, Kind]]
|
||||
tried: list[Tried]
|
||||
cheapest: Rung | None
|
||||
|
||||
|
||||
def case_from(root: str, outcomes: str, transcript: pathlib.Path) -> Case | None:
|
||||
"""The first verdict an outcomes file holds: the judge ruled on the transcript copy beside it as the copy stands. None when it holds none.
|
||||
|
||||
@@ -77,39 +62,26 @@ def verdict_kind(verdict: Verdict | Failure) -> Kind:
|
||||
typing.assert_never(verdict)
|
||||
|
||||
|
||||
def replayed(cases: list[Case], reference: Rung, candidates: list[Rung], rule_all: typing.Callable[[list[Case], Rung], list[Kind] | Limited]) -> Replay | Limited:
|
||||
"""Replays the cases on the reference rung, then only those it reproduces on each candidate, cheapest first, until one returns every verdict."""
|
||||
ruled = rule_all(cases, reference)
|
||||
if isinstance(ruled, Limited):
|
||||
return ruled
|
||||
reproduced = [found for found, kind in zip(cases, ruled) if kind == found.on_record]
|
||||
unreproduced = [(found, kind) for found, kind in zip(cases, ruled) if kind != found.on_record]
|
||||
tried: list[Tried] = []
|
||||
# With no verdict to hold a rung to, every rung would miss none.
|
||||
for rung in candidates if reproduced else []:
|
||||
ruled = rule_all(reproduced, rung)
|
||||
if isinstance(ruled, Limited):
|
||||
return ruled
|
||||
tried.append(Tried(rung, [(found, kind) for found, kind in zip(reproduced, ruled) if kind != found.on_record]))
|
||||
if not tried[-1].missed:
|
||||
return Replay(unreproduced, tried, rung)
|
||||
return Replay(unreproduced, tried, None)
|
||||
def reproduced(case: Case, kind: Kind) -> list[Kind]:
|
||||
"""The kind on record, where the reply returns it: a rung is held only to a verdict the reference judge reproduces."""
|
||||
return [kind] if kind == case.on_record else []
|
||||
|
||||
|
||||
def report(model: str, reference: Rung, cases: list[Case], replay: Replay) -> str:
|
||||
def report(model: str, reference: Rung, cases: list[Case], replay: Replay[Case, Kind, Kind]) -> str:
|
||||
kinds = collections.Counter(found.on_record for found in cases)
|
||||
unreproduced = [(found, kind) for found, kind in zip(cases, replay.on_reference) if not reproduced(found, kind)]
|
||||
lines = [
|
||||
f"Replayed {len(cases)} verdicts of {model} projects: {', '.join(f'{count} {kind}' for kind, count in sorted(kinds.items()))}.",
|
||||
f"The reference judge, {reference}, reproduced {len(cases) - len(replay.unreproduced)}{'. It returned another kind on:' if replay.unreproduced else '.'}",
|
||||
*missed_lines(replay.unreproduced),
|
||||
f"The reference judge, {reference}, reproduced {len(cases) - len(unreproduced)}{'. It returned another kind on:' if unreproduced else '.'}",
|
||||
*missed_lines(unreproduced),
|
||||
]
|
||||
for tried in replay.tried:
|
||||
lines += [f"{tried.rung} missed {len(tried.missed)}{':' if tried.missed else '.'}", *missed_lines(tried.missed)]
|
||||
lines += [f"{tried.rung} missed {len(tried.missed)}{':' if tried.missed else '.'}", *missed_lines([(miss.case, miss.reply) for miss in tried.missed])]
|
||||
if not replay.tried:
|
||||
lines.append("No rung tried: the reference judge reproduced no verdict to hold one to.")
|
||||
else:
|
||||
cheapest = replay.cheapest or "none up to the project's rung"
|
||||
lines.append(f"Cheapest rung that returns every verdict the reference judge reproduces: {cheapest}")
|
||||
lowest = replay.lowest or "none, the project's rung misses one"
|
||||
lines.append(f"Lowest rung that, like each rung above it, returns every verdict the reference judge reproduces: {lowest}")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
|
||||
@@ -10,12 +10,12 @@ import unittest
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from transcript_archive.outcomes import ANSWERED, FINISHED, INTERRUPTED, UNFINISHED
|
||||
from judge_replay.replay import Case, case_from, Replay, replayed, report, sample, Tried, verdict_kind
|
||||
from judge_replay.replay import Case, case_from, report, reproduced, sample, verdict_kind
|
||||
from loop_claude.effects import Effects
|
||||
from failure import Failure
|
||||
from loop_claude.cycle.judge import Finished, Interrupt, QuotedAnswer, Unfinished
|
||||
from loop_claude.cycle.retry import Limited
|
||||
from judge_replay import main
|
||||
from rung_replay.search import Miss, Replay, Tried
|
||||
from model_routing.ladder import Rung
|
||||
|
||||
TOOL = pathlib.Path(__file__).resolve().parents[1] / "judge-replay"
|
||||
@@ -59,52 +59,29 @@ class VerdictKind(unittest.TestCase):
|
||||
self.assertEqual(verdict_kind(Failure("the judge quoted x")), "failed: the judge quoted x")
|
||||
|
||||
|
||||
class Replayed(unittest.TestCase):
|
||||
def test_tries_rungs_cheapest_first_on_the_verdicts_the_reference_reproduces_and_stops_at_the_first_that_returns_all(self):
|
||||
cases = [case("2026-10-14T10:00:00Z", FINISHED), case("2026-10-14T10:00:01Z", INTERRUPTED), case("2026-10-14T10:00:02Z", FINISHED)]
|
||||
replies = {REFERENCE: [FINISHED, INTERRUPTED, UNFINISHED], CHEAP: [FINISHED, FINISHED], MIDDLE: [FINISHED, INTERRUPTED]}
|
||||
asked = []
|
||||
|
||||
def rule_all(on, rung):
|
||||
asked.append((len(on), rung))
|
||||
return replies[rung]
|
||||
|
||||
replay = replayed(cases, REFERENCE, [CHEAP, MIDDLE, Rung("claude-opus-5-5", "medium")], rule_all)
|
||||
self.assertEqual(replay, Replay([(cases[2], UNFINISHED)], [Tried(CHEAP, [(cases[1], FINISHED)]), Tried(MIDDLE, [])], MIDDLE))
|
||||
self.assertEqual(asked, [(3, REFERENCE), (2, CHEAP), (2, MIDDLE)])
|
||||
|
||||
def test_names_no_rung_when_every_candidate_misses_a_verdict(self):
|
||||
cases = [case("2026-10-14T10:00:00Z", FINISHED)]
|
||||
replay = replayed(cases, REFERENCE, [CHEAP], lambda on, rung: [FINISHED] if rung == REFERENCE else [INTERRUPTED])
|
||||
self.assertEqual(replay, Replay([], [Tried(CHEAP, [(cases[0], INTERRUPTED)])], None))
|
||||
|
||||
def test_tries_no_rung_when_the_reference_reproduces_no_verdict(self):
|
||||
cases = [case("2026-10-14T10:00:00Z", FINISHED)]
|
||||
self.assertEqual(replayed(cases, REFERENCE, [CHEAP], lambda on, rung: [INTERRUPTED] * len(on)), Replay([(cases[0], INTERRUPTED)], [], None))
|
||||
|
||||
def test_stops_at_a_usage_limit(self):
|
||||
limit = Limited(None, "limit")
|
||||
self.assertEqual(replayed([case("2026-10-14T10:00:00Z", FINISHED)], REFERENCE, [CHEAP], lambda on, rung: limit), limit)
|
||||
self.assertEqual(replayed([case("2026-10-14T10:00:00Z", FINISHED)], REFERENCE, [CHEAP], lambda on, rung: [FINISHED] if rung == REFERENCE else limit), limit)
|
||||
class Reproduced(unittest.TestCase):
|
||||
def test_holds_a_rung_to_a_verdict_only_where_the_reference_returned_the_kind_on_record(self):
|
||||
self.assertEqual(reproduced(case("2026-10-14T10:00:00Z", FINISHED), FINISHED), [FINISHED])
|
||||
self.assertEqual(reproduced(case("2026-10-14T10:00:00Z", FINISHED), INTERRUPTED), [])
|
||||
|
||||
|
||||
class Report(unittest.TestCase):
|
||||
def test_counts_the_verdicts_and_names_each_miss_and_the_cheapest_rung(self):
|
||||
def test_counts_the_verdicts_and_names_each_miss_and_the_lowest_rung(self):
|
||||
cases = [case("2026-10-14T10:00:00Z", FINISHED), case("2026-10-14T10:00:01Z", INTERRUPTED)]
|
||||
replay = Replay([(cases[0], UNFINISHED)], [Tried(CHEAP, [(cases[1], FINISHED)]), Tried(MIDDLE, [])], MIDDLE)
|
||||
replay = Replay([UNFINISHED, INTERRUPTED], [Tried(MIDDLE, []), Tried(CHEAP, [Miss(cases[1], INTERRUPTED, FINISHED)])], MIDDLE)
|
||||
self.assertEqual(report("claude-opus-5-5", REFERENCE, cases, replay).splitlines(), [
|
||||
"Replayed 2 verdicts of claude-opus-5-5 projects: 1 Verdict: finished, 1 Verdict: interrupt.",
|
||||
"The reference judge, claude-opus-5-5 at xhigh effort, reproduced 1. It returned another kind on:",
|
||||
" /code/p 2026-10-14T10:00:00Z: on record Verdict: finished, replayed Verdict: unfinished",
|
||||
"claude-sonnet-5-5 at high effort missed 0.",
|
||||
"claude-haiku-5-5 at xhigh effort missed 1:",
|
||||
" /code/p 2026-10-14T10:00:01Z: on record Verdict: interrupt, replayed Verdict: finished",
|
||||
"claude-sonnet-5-5 at high effort missed 0.",
|
||||
"Cheapest rung that returns every verdict the reference judge reproduces: claude-sonnet-5-5 at high effort",
|
||||
"Lowest rung that, like each rung above it, returns every verdict the reference judge reproduces: claude-sonnet-5-5 at high effort",
|
||||
])
|
||||
missed_all = report("claude-opus-5-5", REFERENCE, cases, Replay([], [Tried(CHEAP, [(cases[1], FINISHED)])], None)).splitlines()
|
||||
missed_all = report("claude-opus-5-5", REFERENCE, cases, Replay([FINISHED, INTERRUPTED], [Tried(MIDDLE, [Miss(cases[1], INTERRUPTED, FINISHED)])], None)).splitlines()
|
||||
self.assertEqual(missed_all[1], "The reference judge, claude-opus-5-5 at xhigh effort, reproduced 2.")
|
||||
self.assertEqual(missed_all[-1], "Cheapest rung that returns every verdict the reference judge reproduces: none up to the project's rung")
|
||||
self.assertEqual(report("claude-opus-5-5", REFERENCE, cases, Replay([(cases[0], UNFINISHED), (cases[1], FINISHED)], [], None)).splitlines()[-1], "No rung tried: the reference judge reproduced no verdict to hold one to.")
|
||||
self.assertEqual(missed_all[-1], "Lowest rung that, like each rung above it, returns every verdict the reference judge reproduces: none, the project's rung misses one")
|
||||
self.assertEqual(report("claude-opus-5-5", REFERENCE, cases, Replay([UNFINISHED, FINISHED], [], None)).splitlines()[-1], "No rung tried: the reference judge reproduced no verdict to hold one to.")
|
||||
|
||||
|
||||
def unused(*_):
|
||||
@@ -145,28 +122,28 @@ class Main(unittest.TestCase):
|
||||
|
||||
@staticmethod
|
||||
def verdict(interrupt, evidence):
|
||||
output = {"answer": "", "bundled": 0, "evidence": evidence, "finished": not interrupt, "interrupt": interrupt, "question": "Which?" if interrupt else ""}
|
||||
output = {"answer": "", "bundled": 0, "escalation": "", "evidence": evidence, "finished": not interrupt, "interrupt": interrupt, "question": "Which?" if interrupt else ""}
|
||||
return {"type": "result", "structured_output": output}
|
||||
|
||||
def test_replays_the_models_projects_on_the_reference_then_cheapest_first_and_prints_the_rung_that_returns_all(self):
|
||||
# Haiku misses the interrupt; Sonnet returns both.
|
||||
def test_replays_the_models_projects_on_the_reference_then_from_the_projects_rung_down_and_prints_the_lowest_that_returns_all(self):
|
||||
# Haiku misses the interrupt; Sonnet and Opus return both.
|
||||
def reply(rung, interrupted):
|
||||
return self.verdict(interrupted and rung.model != "claude-haiku-5-5", f"said {INTERRUPTED if interrupted else FINISHED}")
|
||||
|
||||
code, out, err = self.run_main(["claude-opus-5-5"], reply)
|
||||
self.assertEqual(code, 0, err)
|
||||
self.assertEqual({cwd for _, _, cwd in self.calls}, {str(self.home / "code" / "proj")})
|
||||
self.assertEqual([(model, effort) for model, effort, _ in self.calls[::2]], [("claude-opus-5-5", "xhigh"), ("claude-haiku-5-5", "xhigh"), ("claude-haiku-5-5", "max"), ("claude-sonnet-5-5", "high")])
|
||||
self.assertEqual([(model, effort) for model, effort, _ in self.calls[::2]], [("claude-opus-5-5", "xhigh"), ("claude-opus-5-5", "medium"), ("claude-sonnet-5-5", "high"), ("claude-haiku-5-5", "max")])
|
||||
self.assertIn("The reference judge, claude-opus-5-5 at xhigh effort, reproduced 2.", out)
|
||||
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])
|
||||
|
||||
def test_tries_rungs_up_to_the_models_cheapest_and_names_none_when_all_miss(self):
|
||||
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}"))
|
||||
self.assertEqual(code, 0)
|
||||
self.assertEqual(self.calls[-1][:2], ("claude-opus-5-5", "medium"))
|
||||
self.assertTrue(out.endswith(": none up to the project's rung\n"))
|
||||
self.assertEqual({(model, effort) for model, effort, _ in self.calls[2:]}, {("claude-opus-5-5", "medium")})
|
||||
self.assertTrue(out.endswith(": none, the project's rung misses one\n"))
|
||||
|
||||
def test_replays_a_verdict_whose_transcript_is_gone_as_failed(self):
|
||||
(self.home / ".claude" / "loop-claude-transcripts" / "proj" / "c1" / "t0.jsonl").unlink()
|
||||
@@ -174,14 +151,16 @@ class Main(unittest.TestCase):
|
||||
self.assertEqual(code, 0)
|
||||
self.assertIn("replayed failed: could not read the transcript", out)
|
||||
|
||||
def test_tries_up_to_the_models_cheapest_rung_and_retries_a_failed_reply_as_the_loop_does(self):
|
||||
def test_tries_the_projects_rung_first_and_retries_a_failed_reply_as_the_loop_does(self):
|
||||
def reply(rung, interrupted):
|
||||
return self.verdict(interrupted, "not in the transcript" if rung.model != "claude-opus-5-5" else f"said {INTERRUPTED if interrupted else FINISHED}")
|
||||
|
||||
code, out, _ = self.run_main(["claude-opus-5-5"], reply)
|
||||
self.assertEqual(code, 0)
|
||||
self.assertEqual(sum(model == "claude-sonnet-5-5" for model, _, _ in self.calls), 6)
|
||||
self.assertNotIn("claude-haiku-5-5", {model for model, _, _ in self.calls})
|
||||
self.assertIn("claude-opus-5-5 at medium effort missed 0.", out)
|
||||
self.assertTrue(out.endswith(": claude-opus-5-5 at medium effort\n"))
|
||||
|
||||
def test_exits_1_on_a_usage_limit_bad_arguments_or_an_unreadable_models_file(self):
|
||||
code, _, err = self.run_main(["claude-opus-5-5"], lambda rung, interrupted: {"type": "result", "api_error_status": 429, "result": "You've hit your limit"})
|
||||
|
||||
@@ -34,7 +34,7 @@ def said(overall: str, locality: str = "same") -> str:
|
||||
|
||||
|
||||
def item(id_: int, release: tuple[int, int, int], tagline: str = "**Do it.**") -> Item:
|
||||
return Item(id_, release, "", tagline, {"R": 1, "S": 1, "C": 3, "A": 1, "G": 1}, ("1",))
|
||||
return Item(id_, release, "", tagline, {"R": 1, "S": 1, "C": 3, "A": 1, "G": 1}, (("1", None),), ())
|
||||
|
||||
|
||||
def todo(*rows: str) -> str:
|
||||
|
||||
@@ -4,13 +4,14 @@ import re
|
||||
import typing
|
||||
|
||||
from loop_claude.cycle.prompts import ANSWER_DESTINATIONS, ANSWERS_RECORDED, either
|
||||
from claude_code.reply import claude_reply, Limited
|
||||
from loop_claude.effects import Effects
|
||||
from failure import Failure
|
||||
from claude_code.entries import hit_limit, limit_said, parse_entry, structured_output
|
||||
from loop_claude.project.records import HUMAN_RULE_NAMES
|
||||
from loop_claude.cycle.retry import Limited, retried
|
||||
from loop_claude.cycle.retry import retried
|
||||
from model_routing.ladder import Rung
|
||||
from loop_claude.stop import Stop
|
||||
from claude_code.entries import structured_output
|
||||
from todo_table import TOP_SCORE
|
||||
|
||||
# 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.
|
||||
@@ -29,15 +30,16 @@ JUDGE_RULES = (
|
||||
"- it chose between alternatives that neither README.md nor the records discriminate "
|
||||
"between - neither rules the rejected one out - and the choice materially changes the deliverable\n"
|
||||
"interrupt=false otherwise. Bookkeeping the agent settled silently - what to document, wording, "
|
||||
"where a note goes - is not on its own a reason to interrupt. The human may have replied inside the transcript, on a [human] line: judge only what "
|
||||
"where a note goes - is not on its own a reason to interrupt. A run that ends asking loop-claude for a higher "
|
||||
"rung is no reason to interrupt either; one that asks the human's yes to a higher rung is. The human may have replied inside the transcript, on a [human] line: judge only what "
|
||||
"is still open, never a question they already answered there. A [loop] line is what loop-claude told "
|
||||
"the agent, such as an answer quoted from README.md or the records.\n"
|
||||
"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"
|
||||
"wording; never construct another from facts it stated.\n\n"
|
||||
"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"
|
||||
"outranks finished.\n\n"
|
||||
"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 "
|
||||
@@ -53,6 +55,8 @@ class Reply:
|
||||
answer: str = dataclasses.field(metadata={"description": "With interrupt false, the passage of README.md or the records that answers the agent's question, quoted verbatim, without elisions. Empty otherwise."})
|
||||
# Routes the next cycle's worker. Counting the item the chunk was routed on is harmless: loop-claude never steps the worker down.
|
||||
bundled: int = dataclasses.field(metadata={"description": "The highest R + C 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."})
|
||||
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."})
|
||||
@@ -93,6 +97,8 @@ class Unfinished:
|
||||
evidence: str
|
||||
# The bundled R + C the judge saw, 0 for none.
|
||||
bundled: int = 0
|
||||
# The judge's quote showing that the worker's cited escalation trigger fired; empty for none.
|
||||
escalation: str = ""
|
||||
|
||||
|
||||
Verdict = Interrupt | QuotedAnswer | Finished | Unfinished
|
||||
@@ -117,7 +123,7 @@ def verdict_from(output: object) -> Verdict | Failure:
|
||||
return Finished(output["evidence"])
|
||||
if not 0 <= output["bundled"] <= HIGHEST_R_PLUS_C:
|
||||
return Failure(f"the judge's bundled R + C {output['bundled']} is not from 0 to {HIGHEST_R_PLUS_C}")
|
||||
return Unfinished(output["evidence"], output["bundled"])
|
||||
return Unfinished(output["evidence"], output["bundled"], output["escalation"])
|
||||
|
||||
|
||||
def judge(root: str, task: str, premises: str, records: str, rendered_transcript: str, rung: Rung, effects: Effects) -> Verdict | Stop:
|
||||
@@ -132,37 +138,33 @@ def judge_once(root: str, task: str, premises: str, records: str, rendered_trans
|
||||
|
||||
def judge_args(rung: Rung) -> list[str]:
|
||||
# --json-schema has claude check its reply against the schema and return it as the json result's structured_output.
|
||||
# No tools, so the verdict rests on the transcript grounded() checks it against; no persistence, so its runs stay out of the session picker.
|
||||
# No tools, so the verdict rests on the transcript grounded() checks it against.
|
||||
return [
|
||||
"-p",
|
||||
"--json-schema", json.dumps(JUDGE_SCHEMA),
|
||||
*rung.flags(),
|
||||
"--no-session-persistence",
|
||||
"--output-format", "json",
|
||||
"--permission-mode", "bypassPermissions",
|
||||
"--tools", "",
|
||||
]
|
||||
|
||||
|
||||
def run_judge(root: str, args: list[str], prompt: str, shown: str, quotable: str, effects: Effects) -> Verdict | Failure | Limited:
|
||||
try:
|
||||
proc = effects.claude(args, root, prompt)
|
||||
except OSError as failure:
|
||||
return Failure(f"could not start claude: {failure.strerror}")
|
||||
reply = parse_entry(proc.stdout) or {}
|
||||
# The json output names the reset only in prose, such as "resets 7:40pm (Europe/Stockholm)", so the judge's limit carries no reset time.
|
||||
if hit_limit(reply):
|
||||
return Limited(None, limit_said(reply))
|
||||
if proc.returncode != 0:
|
||||
return Failure(proc.stderr.strip() or f"the judge exited {proc.returncode}")
|
||||
"""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.
|
||||
"""
|
||||
reply = claude_reply(effects.claude, args, root, prompt, "the judge")
|
||||
if isinstance(reply, Failure | Limited):
|
||||
return reply
|
||||
verdict = verdict_from(structured_output(reply))
|
||||
if isinstance(verdict, Failure):
|
||||
return Failure(f"{verdict.reason}; it replied: {proc.stdout.strip() or 'nothing'}")
|
||||
return Failure(f"{verdict.reason}; it replied: {json.dumps(reply, ensure_ascii=False)}")
|
||||
if not grounded(verdict.evidence, shown):
|
||||
return Failure(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 ""))
|
||||
# Not a Failure: a misquote would otherwise exit an unattended loop. Never elided: stitched fragments can say what the records do not.
|
||||
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 dataclasses.replace(verdict, escalation="")
|
||||
return verdict
|
||||
|
||||
|
||||
|
||||
@@ -38,15 +38,17 @@ def off_the_projects_rung(route: Route, anchor: Rung | None) -> str:
|
||||
|
||||
|
||||
def escalation(route: Route, anchor: Rung | None) -> str:
|
||||
"""The prompt's escalation sentence: the rungs escalation_rungs opens, and the marker; empty off the ladder or on its top rung."""
|
||||
"""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."""
|
||||
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."
|
||||
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.{marked}"
|
||||
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}"
|
||||
further = f", and on each further trigger one rung higher, up to {rungs[-1]}" if len(rungs) > 1 else ""
|
||||
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 = 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}"
|
||||
|
||||
|
||||
def reruns(route: Route, anchor: Rung | None) -> str:
|
||||
@@ -64,9 +66,10 @@ def reruns(route: Route, anchor: Rung | None) -> str:
|
||||
|
||||
|
||||
def resumed(unfinished_evidence: str, route: Route, anchor: Rung | None) -> str:
|
||||
"""Names the project's rung again, since a step-up between cycles may have taken the worker above it."""
|
||||
"""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}.{off_the_projects_rung(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}{off_the_projects_rung(route, anchor)}{escalation(route, anchor)}{reruns(route, anchor)}"
|
||||
|
||||
|
||||
def answered(question: str, answer: str) -> str:
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import dataclasses
|
||||
import sys
|
||||
import typing
|
||||
|
||||
from loop_claude.effects import Effects
|
||||
from failure import Failure
|
||||
from claude_code.reply import Limited
|
||||
from loop_claude.stop import Stop
|
||||
|
||||
T = typing.TypeVar("T")
|
||||
@@ -14,13 +14,6 @@ RETRY_DELAY = 60
|
||||
UNKNOWN_RESET_POLL = 600
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Limited:
|
||||
"""claude hit a usage limit; said is claude's message about it, and resets_at is when the limit resets, in seconds since the epoch, or None when unknown."""
|
||||
resets_at: int | None
|
||||
said: str
|
||||
|
||||
|
||||
def retried(who: str, attempt: typing.Callable[[], T | Failure | Limited], effects: Effects) -> T | Stop:
|
||||
failures = 0
|
||||
while True:
|
||||
|
||||
@@ -128,9 +128,9 @@ def question_for(ruling: Interrupt | QuotedAnswer) -> str:
|
||||
|
||||
|
||||
def close(cycle: Cycle, transcript_path: str, verdict: Finished | Unfinished) -> Archived | Stop:
|
||||
finished = isinstance(verdict, Finished)
|
||||
if failure := archive(cycle.project_archive, transcript_path, cycle.task, outcomes.finished(str(cycle.route), verdict.evidence, str(judge_of(cycle))) if finished else outcomes.unfinished(str(cycle.route), verdict.evidence, str(judge_of(cycle))), cycle.effects.now()):
|
||||
outcome = outcomes.finished(str(cycle.route), verdict.evidence, str(judge_of(cycle))) if isinstance(verdict, Finished) else outcomes.unfinished(str(cycle.route), verdict.evidence, str(judge_of(cycle)), verdict.escalation)
|
||||
if failure := archive(cycle.project_archive, transcript_path, cycle.task, outcome, cycle.effects.now()):
|
||||
return Stop(1, failure.reason)
|
||||
if finished and (failure := delete_session(cycle.session)):
|
||||
if isinstance(verdict, Finished) and (failure := delete_session(cycle.session)):
|
||||
return Stop(1, failure.reason)
|
||||
return Archived()
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
from claude_code.entries import assistant_parts, ends_stream, hit_limit, limit_said, parse_entry, rejected_until
|
||||
from loop_claude.effects import Effects
|
||||
from failure import Failure
|
||||
from loop_claude.cycle.retry import Limited
|
||||
from claude_code.reply import Limited
|
||||
from claude_code.transcript import part_line
|
||||
from model_routing.ladder import Rung
|
||||
from claude_code.session import Session
|
||||
|
||||
@@ -28,9 +28,9 @@ interrupt, and as every cycle ends, Ctrl-C and a failure included, the session's
|
||||
copied to $LOOP_CLAUDE_TRANSCRIPTS/<key>/<chunk>/<sha256>.jsonl (default
|
||||
~/.claude/loop-claude-transcripts), named by its hash. <chunk> is the hash of the transcript's first
|
||||
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 and the judge's rung; each
|
||||
answer the judge quoted, with the question it answers; 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'
|
||||
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; 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 rewrote lands beside its copy as <name>.<hash of its content>.
|
||||
@@ -43,7 +43,8 @@ for the worker and the interrupt; 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, the R + C of
|
||||
todo.md's top item in the next release, skipping an item marked question, picks the rung. It
|
||||
todo.md's top item in the next release that does not wait picks the rung: an item waits while it is
|
||||
marked question, or while an item that blocks it is still in the table. The R + C
|
||||
counts from the model's cheapest rung, and an R + C of 8 or less picks a rung below it; without
|
||||
such an item, or with a C missing, the chunk runs on the model's cheapest rung. The worker's first
|
||||
prompt names the rung and the item, and asks the worker to name each item the chunk takes, with its
|
||||
@@ -54,7 +55,11 @@ the cheapest rung. The prompt after each unfinished verdict
|
||||
says this again, since a step-up may have taken the worker above the cheapest rung. A reviewer or
|
||||
seat that rules the work below standard may ask to rerun one rung up; each prompt names that rung. The
|
||||
judge reports the highest R + C the worker states, and the next cycle steps up to the rung that
|
||||
R + C picks, never down. Every second unfinished verdict on a chunk steps it up one rung. Each
|
||||
R + C picks, never down. Every second unfinished verdict on a chunk steps it up one rung. 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 and R + C that routed the chunk; a rerun resumes an open chunk on the latest rung named there,
|
||||
and counts its unfinished verdicts afresh. A rung no longer on the ladder, or below the one its
|
||||
@@ -102,10 +107,10 @@ Exit 1, saying why, when:
|
||||
handover
|
||||
- the worker or the judge fails three times running, retried a minute apart within the cycle. A
|
||||
worker fails when claude cannot start, exits non-zero, is killed, or ends without a result event;
|
||||
a judge when claude cannot start or exits non-zero, or its reply misses or mistypes a field,
|
||||
interrupts or quotes an answer without a question, gives an unfinished verdict an R + C outside
|
||||
0 to 20, or quotes a passage the transcript does not hold; it holds an elided passage when each
|
||||
fragment appears in order.
|
||||
a judge when claude cannot start, exits non-zero or prints no json reply, or its reply misses or
|
||||
mistypes a field, interrupts or quotes an answer without a question, gives an unfinished verdict
|
||||
an R + C outside 0 to 20, or quotes a passage the transcript does not hold; it holds an elided
|
||||
passage when each fragment appears in order.
|
||||
A usage limit is not a failure, and restarts the count of three: the worker or the judge is
|
||||
retried 2 minutes after the limit resets, or every 10 minutes when the reset time is unknown or
|
||||
more than 2 minutes past. The judge's reply gives its reset time only as text, so the judge is
|
||||
@@ -206,7 +211,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) if anchor and loop_run.route else loop_run.route
|
||||
route = stepped(anchor, loop_run.route, verdict.bundled, bool(verdict.escalation)) if anchor and loop_run.route else loop_run.route
|
||||
return dataclasses.replace(loop_run, route=route, unfinished_evidence=verdict.evidence)
|
||||
|
||||
|
||||
|
||||
+43
-22
@@ -1,25 +1,26 @@
|
||||
"""Which ladder rung a chunk's worker and judge run on: docs/decisions.md → `routing:`."""
|
||||
import dataclasses
|
||||
|
||||
from model_routing.ladder import climbed, floored, highest, LADDER, picked, position, project_rung, Rung, stepped_up
|
||||
from model_routing.ladder import climbed, highest, LADDER, picked, position, project_rung, Rung, stepped_up
|
||||
from failure import Failure
|
||||
from todo_table import Item, items
|
||||
from todo_table import Item, items, waiting
|
||||
from model_routing.route import Route
|
||||
|
||||
UNFINISHED_PER_STEP = 2
|
||||
# How many rungs above item_rung the worker may escalate a task without the human's yes: docs/decisions.md → `routing: a worker hands a task one rung up`.
|
||||
# How many rungs above item_rung an escalation trigger takes the worker or a task without the human's yes, as escalation_cap counts them.
|
||||
ESCALATION_CAP = 2
|
||||
# The models `judge-replay` found returning, on their cheapest rung, every verdict the reference judge reproduced: docs/decisions.md → `routing: on a model judge-replay covered`.
|
||||
JUDGE_REPLAYED = ("claude-opus-5-5",)
|
||||
|
||||
|
||||
def routed_item(todo: str) -> Item | Failure | None:
|
||||
"""The next release's first row that waits on no question, in the table's order, which rank_todo.py keeps ranked; None when there is none, or it has no C."""
|
||||
"""The next release's first row that does not wait, as todo_table.waiting says, in the table's order; None when there is none, or it has no C."""
|
||||
found = items(todo)
|
||||
if isinstance(found, Failure) or not found:
|
||||
return found if isinstance(found, Failure) else None
|
||||
next_release = min(item.release for item in found)
|
||||
takes = next((item for item in found if item.release == next_release and item.exempt != "question"), None)
|
||||
waits = waiting(found)
|
||||
takes = next((item for item in found if item.release == next_release and item.id not in waits), None)
|
||||
return takes if takes and takes.risk_and_complexity else None
|
||||
|
||||
|
||||
@@ -31,8 +32,13 @@ def first_route(anchor: Rung, item: Item | None) -> Route:
|
||||
|
||||
|
||||
def kept(route: Route, anchor: Rung) -> bool:
|
||||
"""Whether a chunk keeps route: its rung is on the ladder at or above item_rung."""
|
||||
return highest(route.rung, item_rung(anchor, route)) == route.rung
|
||||
"""Whether a chunk keeps route: its rung is on the ladder and at or above item_rung."""
|
||||
return kept_rung(anchor, route) == route.rung
|
||||
|
||||
|
||||
def kept_rung(anchor: Rung, route: Route) -> Rung:
|
||||
"""The route's rung, raised to item_rung where it is lower or off the ladder."""
|
||||
return highest(route.rung, item_rung(anchor, route))
|
||||
|
||||
|
||||
def item_rung(anchor: Rung, route: Route) -> Rung:
|
||||
@@ -41,33 +47,48 @@ def item_rung(anchor: Rung, route: Route) -> Rung:
|
||||
|
||||
|
||||
def escalation_rungs(anchor: Rung, route: Route) -> tuple[Rung, ...]:
|
||||
"""The rungs an escalation trigger opens to the worker, least competent first: from one above its own up to ESCALATION_CAP above item_rung; none off the ladder.
|
||||
|
||||
A step-up between cycles raises the worker but not that limit, as lilleman set it from the rung the chunk started on.
|
||||
"""
|
||||
"""The rungs an escalation trigger opens to the worker, least competent first: from one above its own up to escalation_cap; none off the ladder."""
|
||||
if route.rung not in LADDER:
|
||||
return ()
|
||||
return LADDER[position(route.rung) + 1:position(climbed(item_rung(anchor, route), ESCALATION_CAP)) + 1]
|
||||
return LADDER[position(route.rung) + 1:position(escalation_cap(anchor, route)) + 1]
|
||||
|
||||
|
||||
def stepped(anchor: Rung, route: Route, bundled: int) -> Route:
|
||||
"""The route after one more unfinished verdict; bundled is the highest R + C the judge saw the worker take into the chunk, 0 for none."""
|
||||
# An archived rung since removed from LADDER restarts from the project's rung.
|
||||
rung = route.rung if route.rung in LADDER else anchor
|
||||
rung = highest(rung, picked(anchor, bundled)) if bundled else rung
|
||||
if route.unfinished + 1 >= UNFINISHED_PER_STEP:
|
||||
def escalation_cap(anchor: Rung, route: Route) -> Rung:
|
||||
"""The highest rung an escalation trigger takes the worker or a task to without the human's yes: docs/decisions.md → `routing: a worker hands a task one rung up`.
|
||||
|
||||
It counts from item_rung, the rung the chunk started on, so a step-up between cycles narrows what the worker may climb without a yes, and never widens it.
|
||||
"""
|
||||
return climbed(item_rung(anchor, route), ESCALATION_CAP)
|
||||
|
||||
|
||||
def stepped(anchor: Rung, route: Route, bundled: int, escalated: bool) -> Route:
|
||||
"""The route after one more unfinished verdict, never on a lower rung.
|
||||
|
||||
bundled and escalated are the verdict's fields, not 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)
|
||||
return dataclasses.replace(route, rung=rung, unfinished=route.unfinished + 1)
|
||||
return dataclasses.replace(route, rung=rung, unfinished=unfinished)
|
||||
|
||||
|
||||
def taken_in(anchor: Rung, route: Route, bundled: int) -> Rung:
|
||||
"""kept_rung, raised to the rung bundled picks from anchor; bundled is the highest R + C the judge saw the worker take into the chunk, 0 for none."""
|
||||
return highest(kept_rung(anchor, route), picked(anchor, bundled)) if bundled else kept_rung(anchor, route)
|
||||
|
||||
|
||||
def judge_rung(judge_model: str, route: Route) -> Rung:
|
||||
"""The rung the route's item picks from the judge model's cheapest rung, never below that rung, whatever rung the worker stepped to.
|
||||
"""The rung the route's item picks, counted from the judge model's cheapest rung and never below it, whatever rung the worker stepped to.
|
||||
|
||||
An item the worker takes in moves the worker's rung but not the judge's, until todo.md item 136 routes the chunk on the item the worker takes.
|
||||
An item the worker takes in beyond the routed one lifts the worker's rung, through taken_in, but not the judge's, until todo.md item 153 lifts the judge too.
|
||||
|
||||
A model off the ladder, or not in JUDGE_REPLAYED, gets no effort flag, so claude runs it at the effort its settings give.
|
||||
"""
|
||||
anchor = project_rung(judge_model)
|
||||
if anchor is None or judge_model not in JUDGE_REPLAYED:
|
||||
return Rung(judge_model)
|
||||
return floored(anchor, route.risk_and_complexity) if route.item else anchor
|
||||
return highest(anchor, item_rung(anchor, route))
|
||||
|
||||
@@ -123,8 +123,8 @@ def worker(**step):
|
||||
return {"role": "worker", **step}
|
||||
|
||||
|
||||
def judge(interrupt=False, finished=False, evidence="working", question="", bundled=0, **step):
|
||||
verdict = {"answer": "", "bundled": bundled, "evidence": evidence, "finished": finished, "interrupt": interrupt, "question": question}
|
||||
def judge(interrupt=False, finished=False, evidence="working", question="", bundled=0, escalation="", **step):
|
||||
verdict = {"answer": "", "bundled": bundled, "escalation": escalation, "evidence": evidence, "finished": finished, "interrupt": interrupt, "question": question}
|
||||
return {"role": "judge", "verdict": verdict, **step}
|
||||
|
||||
|
||||
@@ -395,6 +395,28 @@ class Cycles(unittest.TestCase):
|
||||
self.assertIn("<UTC> Verdict: unfinished\n\nEvidence:\n> three\n\nJudge: judge-model\nWorker: claude-opus-5-5 at xhigh effort, routed by item 4's R + C of 11\n\n<UTC> Stepped up\n\nWorker: claude-fable-5-1 at max effort, routed by item 4's R + C of 11\n", outcomes)
|
||||
self.assertIn("<UTC> Verdict: finished\n\nEvidence:\n> four\n\nJudge: judge-model\nWorker: claude-fable-5-1 at max effort, routed by item 4's R + C of 11\n", outcomes)
|
||||
|
||||
def test_steps_the_worker_up_a_rung_when_the_judge_finds_in_the_transcript_the_escalation_trigger_it_cites(self):
|
||||
checkout = Checkout(self)
|
||||
checkout.env["LOOP_CLAUDE_WORKER_MODEL"] = "claude-opus-5-5"
|
||||
(checkout.root / "todo.md").write_text(TODO)
|
||||
run = checkout.run([
|
||||
worker(say="Stability round 2: a 🔴. Trigger 3 fired; I ask for a higher rung."), judge(evidence="I ask for a higher rung.", escalation="Stability round 2: a 🔴."),
|
||||
worker(say="Trigger 2 fired; I ask for a higher rung."), judge(evidence="I ask for a higher rung.", escalation="Trigger 2 fired; … a higher rung."),
|
||||
worker(say="merged"), judge(finished=True, evidence="merged"),
|
||||
worker(say="next chunk"),
|
||||
])
|
||||
self.assertEqual(run.code, 130)
|
||||
workers = [call for call in run.calls if call["role"] == "worker"]
|
||||
self.assertEqual([(argument(call, "--model"), argument(call, "--effort")) for call in workers], [
|
||||
("claude-opus-5-5", "high"),
|
||||
("claude-opus-5-5", "xhigh"),
|
||||
("claude-opus-5-5", "xhigh"),
|
||||
("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 R + C of 11\n\n<UTC> Stepped up\n\nWorker: claude-opus-5-5 at xhigh effort, routed by item 4's R + C of 11\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 R + C of 11\n", outcomes)
|
||||
|
||||
def test_runs_a_cheap_items_worker_below_the_projects_rung_with_its_reviewers_and_judge_on_it(self):
|
||||
checkout = Checkout(self)
|
||||
checkout.env["LOOP_CLAUDE_WORKER_MODEL"] = checkout.env["LOOP_CLAUDE_JUDGE_MODEL"] = "claude-opus-5-5"
|
||||
@@ -455,7 +477,7 @@ class Cycles(unittest.TestCase):
|
||||
self.assertEqual(run.roles(), ["worker", "judge", "judge", "judge"])
|
||||
self.assertEqual(run.sleeps, [60, 60])
|
||||
self.assertIn("retrying the judge in a minute: judge down", run.stderr)
|
||||
self.assertIn("retrying the judge in a minute: the judge returned no reply; it replied: nothing\n", run.stderr)
|
||||
self.assertIn("retrying the judge in a minute: the judge printed no json reply; it printed: nothing\n", run.stderr)
|
||||
self.assertEqual(run.stderr.strip().splitlines()[-1], 'the judge failed three times running: the judge\'s reply has no answer of type string; it replied: {"structured_output": {"interrupt": false}}')
|
||||
|
||||
def test_waits_out_a_usage_limit_which_ends_a_run_of_failures(self):
|
||||
|
||||
@@ -19,12 +19,12 @@ 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 loop_claude.effects import Effects
|
||||
from claude_code import entries, session
|
||||
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.ladder import LADDER, Rung
|
||||
from loop_claude.cycle.retry import Limited
|
||||
from claude_code.reply import Limited
|
||||
from loop_claude.loop import main, reload, routing_check
|
||||
from transcript_archive import outcomes, write
|
||||
from loop_claude import paths, routing
|
||||
@@ -94,7 +94,7 @@ def ran(stdout="", code=0, stderr=""):
|
||||
|
||||
|
||||
def judged(verdict, evidence="working", answer=""):
|
||||
reply = {"answer": answer, "bundled": 0, "evidence": evidence, "finished": verdict == "finished", "interrupt": verdict == "interrupt", "question": "Which one?" if verdict in ("interrupt", "quoted") else ""}
|
||||
reply = {"answer": answer, "bundled": 0, "escalation": "", "evidence": evidence, "finished": verdict == "finished", "interrupt": verdict == "interrupt", "question": "Which one?" if verdict in ("interrupt", "quoted") else ""}
|
||||
return ran(json.dumps({"structured_output": reply}))
|
||||
|
||||
|
||||
@@ -384,7 +384,7 @@ class RoutingCheck(unittest.TestCase):
|
||||
folder = self.root / project / f"c{number}"
|
||||
subagents = folder / "session" / "s" / "subagents"
|
||||
subagents.mkdir(parents=True)
|
||||
kept = "".join(f"2026-10-14T10:0{verdict}:00Z {outcomes.unfinished('w', 'e', 'j')}\n" for verdict in range(verdicts - 1))
|
||||
kept = "".join(f"2026-10-14T10:0{verdict}:00Z {outcomes.unfinished('w', 'e', 'j', '')}\n" for verdict in range(verdicts - 1))
|
||||
(folder / "copy.outcomes.md").write_text(f"Task: t\n\n{kept}2026-10-14T11:00:00Z {outcomes.finished('w', 'm', 'j')}\n")
|
||||
launch = {"type": "assistant", "timestamp": "2026-10-14T09:00:00Z", "message": {"id": "m", "content": [{"type": "tool_use", "id": "a", "name": "Agent", "input": {"subagent_type": "Explore"}}]}}
|
||||
report = {"type": "user", "message": {"content": [{"type": "tool_result", "tool_use_id": "a", "content": "long report"}]}}
|
||||
@@ -508,6 +508,13 @@ class Routing(unittest.TestCase):
|
||||
self.assertIsNone(routing.routed_item(without_c))
|
||||
self.assertEqual(routing.routed_item(TODO.replace("| 5 | 3 |", "| x | 3 |")), Failure("item 3's R 'x' is not a whole number from 1 to 10"))
|
||||
|
||||
def test_routes_past_an_item_a_waiting_item_blocks(self):
|
||||
todo = "## Items\n\n| ID | Release | Blocked by | Exempt | Item | R | S | C | A | G | Goals | Score |\n|---|---|---|---|---|---|---|---|---|---|---|---|\n| 7 | 0.2.0 | | question | **Ask first.** | 9 | 1 | 9 | 9 | 9 | 1 | 30 |\n| 8 | 0.2.0 | 7 | | **Use the answer.** | 1 | 1 | 1 | 9 | 9 | 1 | 30 |\n| 9 | 0.2.0 | 8 | | **Build on it.** | 1 | 1 | 1 | 9 | 9 | 1 | 30 |\n| 3 | 0.2.0 | | | **Do the next thing.** | 5 | 3 | 6 | 8 | 9 | 1 | 25 |\n"
|
||||
self.assertEqual(routing.routed_item(todo).id, 3)
|
||||
self.assertEqual(routing.routed_item(todo.replace("| question |", "| |")).id, 7)
|
||||
unranked = todo.replace("| 7 | 0.2.0 | | question | **Ask first.** | 9 | 1 | 9 | 9 | 9 | 1 | 30 |\n", "") + "| 7 | 0.2.0 | | question | **Ask first.** | 9 | 1 | 9 | 9 | 9 | 1 | 30 |\n"
|
||||
self.assertEqual(routing.routed_item(unranked).id, 3)
|
||||
|
||||
def test_starts_a_chunk_on_the_rung_its_items_r_plus_c_picks_below_the_projects_too(self):
|
||||
self.assertEqual(routing.first_route(self.OPUS, routing.routed_item(TODO)), Route(self.HIGH, 3, 11))
|
||||
cheap = routing.routed_item(TODO.replace("| 5 | 3 | 6 |", "| 1 | 3 | 1 |"))
|
||||
@@ -515,25 +522,33 @@ 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, 9), 0)
|
||||
once = routing.stepped(self.OPUS, Route(self.OPUS, 3, 9), 0, False)
|
||||
self.assertEqual(once, Route(self.OPUS, 3, 9, 1))
|
||||
self.assertEqual(routing.stepped(self.OPUS, once, 0), Route(self.HIGH, 3, 9, 0))
|
||||
self.assertEqual(routing.stepped(self.OPUS, Route(LADDER[-1], unfinished=1), 0).rung, LADDER[-1])
|
||||
self.assertEqual(routing.stepped(self.OPUS, once, 0, False), Route(self.HIGH, 3, 9, 0))
|
||||
self.assertEqual(routing.stepped(self.OPUS, Route(LADDER[-1], unfinished=1), 0, False).rung, LADDER[-1])
|
||||
|
||||
def test_steps_up_to_the_rung_a_bundled_items_r_plus_c_picks_and_never_down(self):
|
||||
self.assertEqual(routing.stepped(self.OPUS, Route(self.OPUS), 13).rung, self.XHIGH)
|
||||
self.assertEqual(routing.stepped(self.OPUS, Route(self.XHIGH), 11).rung, self.XHIGH)
|
||||
self.assertEqual(routing.stepped(self.OPUS, Route(self.OPUS, unfinished=1), 13).rung, Rung("claude-opus-5-5", "max"))
|
||||
self.assertEqual(routing.stepped(self.OPUS, Route(self.OPUS), 13, False).rung, self.XHIGH)
|
||||
self.assertEqual(routing.stepped(self.OPUS, Route(self.XHIGH), 11, False).rung, self.XHIGH)
|
||||
self.assertEqual(routing.stepped(self.OPUS, Route(self.OPUS, unfinished=1), 13, False).rung, Rung("claude-opus-5-5", "max"))
|
||||
|
||||
def test_steps_up_from_a_rung_below_the_projects_one_rung_at_a_time(self):
|
||||
low = Route(Rung("claude-haiku-5-5", "xhigh"), 3, 2, 1)
|
||||
self.assertEqual(routing.stepped(self.OPUS, low, 0).rung, Rung("claude-haiku-5-5", "max"))
|
||||
self.assertEqual(routing.stepped(self.OPUS, Route(low.rung, 3, 2), 0).rung, low.rung)
|
||||
self.assertEqual(routing.stepped(self.OPUS, Route(low.rung, 3, 2), 7).rung, Rung("claude-sonnet-5-5", "high"))
|
||||
self.assertEqual(routing.stepped(self.OPUS, low, 0, False).rung, Rung("claude-haiku-5-5", "max"))
|
||||
self.assertEqual(routing.stepped(self.OPUS, Route(low.rung, 3, 2), 0, False).rung, low.rung)
|
||||
self.assertEqual(routing.stepped(self.OPUS, Route(low.rung, 3, 2), 7, False).rung, Rung("claude-sonnet-5-5", "high"))
|
||||
|
||||
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, 11), 0, True), Route(self.XHIGH, 3, 11, 0))
|
||||
self.assertEqual(routing.stepped(self.OPUS, Route(self.XHIGH, 3, 11), 0, True), Route(Rung("claude-opus-5-5", "max"), 3, 11, 0))
|
||||
self.assertEqual(routing.stepped(self.OPUS, Route(Rung("claude-opus-5-5", "max"), 3, 11), 0, True), Route(Rung("claude-opus-5-5", "max"), 3, 11, 1))
|
||||
self.assertEqual(routing.stepped(self.OPUS, Route(self.HIGH, 3, 11, 1), 0, True), Route(self.XHIGH, 3, 11, 0))
|
||||
self.assertEqual(routing.stepped(self.OPUS, Route(self.XHIGH), 0, True), Route(self.XHIGH, unfinished=1))
|
||||
self.assertEqual(routing.stepped(self.OPUS, Route(self.OPUS, 3, 9), 13, True), Route(self.XHIGH, 3, 9, 1))
|
||||
|
||||
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).rung, self.OPUS)
|
||||
self.assertEqual(routing.stepped(self.OPUS, Route(Rung("claude-opus-5-5", "low")), 2).rung, self.OPUS)
|
||||
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)
|
||||
|
||||
def test_runs_the_judge_on_the_rung_its_chunks_item_picks_never_below_the_projects(self):
|
||||
self.assertEqual(routing.judge_rung("claude-opus-5-5", Route(self.HIGH, 3, 11)), self.HIGH)
|
||||
@@ -594,7 +609,7 @@ class RouteSources(unittest.TestCase):
|
||||
self.assertIsNone(main.archived_route(archive, opened))
|
||||
route = Route(Rung("claude-opus-5-5", "high"), 3, 11)
|
||||
with contextlib.redirect_stderr(io.StringIO()):
|
||||
self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.unfinished(str(route), "working", "j"), NOW))
|
||||
self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.unfinished(str(route), "working", "j", ""), NOW))
|
||||
self.assertEqual(main.archived_route(archive, opened), route)
|
||||
(chunk,) = archive.iterdir()
|
||||
chunk.chmod(0)
|
||||
@@ -623,7 +638,7 @@ class Steps(unittest.TestCase):
|
||||
transcript.write_text(json.dumps({"type": "queue-operation", "timestamp": "1"}) + "\n")
|
||||
before = Route(self.OPUS, 3, 9)
|
||||
with contextlib.redirect_stderr(io.StringIO()):
|
||||
self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.unfinished(str(before), "working", "j"), NOW))
|
||||
self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.unfinished(str(before), "working", "j", ""), NOW))
|
||||
after = main.after_verdict(main.LoopRun(cycle_number=1, root="/r", task="Do it.", unfinished_evidence="", route=before), self.OPUS, Unfinished("working", 13))
|
||||
self.assertIsNone(main.archive_step(archive, opened, after, before, FakeEffects().effects()))
|
||||
self.assertEqual(main.archived_route(archive, opened), Route(Rung("claude-opus-5-5", "xhigh"), 3, 9))
|
||||
@@ -655,6 +670,8 @@ class WorkerArgs(unittest.TestCase):
|
||||
stepped_up = prompts.resumed("", Route(Rung("claude-opus-5-5", "high"), 3, 9), opus)
|
||||
self.assertIn(" Your rung is above the project's, claude-opus-5-5 at medium effort: launch each comprehension seat and the security pass's subagent with the Agent tool set to model opus, effort medium. Run a full scan only from such a subagent, since the scan's agents run on the model that starts them. When an escalation trigger", stepped_up)
|
||||
self.assertNotIn("the project's", prompts.resumed("", Route(opus, 3, 9), opus))
|
||||
self.assertIn(f"{prompts.ANSWERS_RECORDED}. loop-claude runs you on claude-opus-5-5 at high effort. Your rung is above", stepped_up)
|
||||
self.assertNotIn("runs you on", prompts.resumed("", Route(Rung("m")), None))
|
||||
self.assertIn("whether or not it is item 3. Your rung is above the project's, claude-opus-5-5 at medium effort: launch each comprehension seat and the security pass's subagent with the Agent tool set to model opus, effort medium. Run a full scan only from such a subagent, since the scan's agents run on the model that starts them. When an escalation trigger", above)
|
||||
|
||||
def test_names_the_rungs_an_escalation_trigger_lets_the_worker_hand_a_task_to_at_most_two_above_its_items(self):
|
||||
@@ -662,19 +679,26 @@ class WorkerArgs(unittest.TestCase):
|
||||
fresh = prompts.fresh("Do it.", "## Goals", Route(opus, 3, 9), opus)
|
||||
self.assertIn("whether or not it is item 3. 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 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.", fresh)
|
||||
self.assertIn(" When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `model opus, effort xhigh`, one rung above yours; above that, ask the human first. Open the subagent's prompt with `Escalation trigger <n>:`, n the trigger's number.", prompts.resumed("", Route(Rung("claude-opus-5-5", "high"), 3, 9), opus))
|
||||
self.assertIn(" An escalation trigger in `~/.claude/CLAUDE.md` lets you hand the hard part of a task to a subagent with the Agent tool set to `model opus, effort max`, one rung above yours, only once the human agrees. Open the subagent's prompt with `Escalation trigger <n>:`, n the trigger's number.", prompts.resumed("", Route(Rung("claude-opus-5-5", "xhigh"), 3, 9), opus))
|
||||
self.assertIn(" An escalation trigger in `~/.claude/CLAUDE.md` lets you hand the hard part of a task to a subagent with the Agent tool set to `model opus, effort max`, one rung above yours, only once the human agrees; loop-claude will not resume you higher for a trigger either, so ask the human for that yes. Open the subagent's prompt with `Escalation trigger <n>:`, n the trigger's number.", prompts.resumed("", Route(Rung("claude-opus-5-5", "xhigh"), 3, 9), opus))
|
||||
self.assertNotIn("escalation", prompts.resumed("", Route(Rung("claude-fable-5-1", "max"), 3, 20), opus))
|
||||
self.assertIn("hand the hard part of the task to a subagent with the Agent tool set to `model fable, effort max`, one rung above yours;", prompts.resumed("", Route(Rung("claude-opus-5-5", "max"), 3, 13), opus))
|
||||
self.assertNotIn("escalation", prompts.resumed("", Route(Rung("m")), None))
|
||||
self.assertNotIn("escalation", prompts.resumed("", Route(Rung("claude-opus-5-5", "low"), 3, 9), 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. A reviewer", prompts.fresh("Do it.", "## Goals", Route(opus), 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))
|
||||
|
||||
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`."
|
||||
self.assertIn(f"`Escalation trigger <n>:`, n the trigger's number.{offer}", prompts.fresh("Do it.", "## Goals", Route(opus, 3, 9), opus))
|
||||
self.assertIn(f"`Escalation trigger <n>:`, n the trigger's number.{offer}", prompts.resumed("", Route(Rung("claude-opus-5-5", "high"), 3, 9), opus))
|
||||
self.assertNotIn("Where the hard part", prompts.resumed("", Route(Rung("claude-opus-5-5", "xhigh"), 3, 9), opus))
|
||||
|
||||
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`."
|
||||
self.assertTrue(prompts.resumed("", Route(opus, 3, 9), opus).endswith(both))
|
||||
self.assertTrue(prompts.resumed("", Route(Rung("claude-sonnet-5-5", "high"), 3, 5), opus).endswith(both))
|
||||
self.assertIn(f"`Escalation trigger <n>:`, n the trigger's number.{both}\n\nThe chunk's", prompts.fresh("Do it.", "## Goals", Route(opus), opus))
|
||||
self.assertTrue(prompts.fresh("Do it.", "## Goals", Route(opus), opus).split("\n\nThe chunk's")[0].endswith(both))
|
||||
self.assertTrue(prompts.resumed("", Route(Rung("claude-opus-5-5", "high"), 3, 11), opus).endswith(" A reviewer that asks for a rerun one rung up reruns with the Agent tool set to `model opus, effort xhigh`, and a comprehension seat with `model opus, effort high`."))
|
||||
self.assertTrue(prompts.resumed("", Route(Rung("claude-fable-5-1", "max"), 3, 20), opus).endswith(" A comprehension seat that asks for a rerun one rung up reruns with the Agent tool set to `model opus, effort high`."))
|
||||
self.assertNotIn("rerun", prompts.resumed("", Route(Rung("m")), None))
|
||||
@@ -768,19 +792,19 @@ class Grounded(unittest.TestCase):
|
||||
|
||||
class Verdict(unittest.TestCase):
|
||||
def test_needs_every_field_the_schema_requires(self):
|
||||
self.assertEqual(verdict_from({"bundled": 0, "answer": "", "interrupt": False, "evidence": "e", "finished": True, "question": ""}), Finished("e"))
|
||||
self.assertEqual(verdict_from({"bundled": 0, "answer": "", "interrupt": False, "evidence": "e", "finished": False, "question": "ignored"}), Unfinished("e"))
|
||||
self.assertEqual(verdict_from({"bundled": 0, "answer": "", "interrupt": True, "evidence": "e", "finished": True, "question": "Which one?"}), Interrupt("e", "Which one?"))
|
||||
self.assertEqual(verdict_from({"bundled": 0, "answer": "A.", "interrupt": False, "evidence": "e", "finished": False, "question": "Which one?"}), QuotedAnswer("e", "Which one?", "A."))
|
||||
self.assertEqual(verdict_from({"bundled": 0, "answer": "A.", "interrupt": True, "evidence": "e", "finished": False, "question": "Which one?"}), Interrupt("e", "Which one?"))
|
||||
self.assertEqual(verdict_from({"bundled": 0, "answer": "A.", "interrupt": False, "evidence": "e", "finished": True, "question": ""}), Failure("the judge quoted an answer without a question"))
|
||||
self.assertEqual(verdict_from({"bundled": 0, "answer": "", "interrupt": "no", "evidence": "", "finished": True, "question": ""}), Failure("the judge's reply has no interrupt of type boolean"))
|
||||
self.assertEqual(verdict_from({"bundled": 0, "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, "answer": "", "interrupt": True, "evidence": "x", "finished": False, "question": " "}), Failure("the judge interrupted without a question"))
|
||||
self.assertEqual(verdict_from({"bundled": 0, "escalation": "", "answer": "", "interrupt": False, "evidence": "e", "finished": True, "question": ""}), Finished("e"))
|
||||
self.assertEqual(verdict_from({"bundled": 0, "escalation": "", "answer": "", "interrupt": False, "evidence": "e", "finished": False, "question": "ignored"}), Unfinished("e"))
|
||||
self.assertEqual(verdict_from({"bundled": 0, "escalation": "", "answer": "", "interrupt": True, "evidence": "e", "finished": True, "question": "Which one?"}), Interrupt("e", "Which one?"))
|
||||
self.assertEqual(verdict_from({"bundled": 0, "escalation": "", "answer": "A.", "interrupt": False, "evidence": "e", "finished": False, "question": "Which one?"}), QuotedAnswer("e", "Which one?", "A."))
|
||||
self.assertEqual(verdict_from({"bundled": 0, "escalation": "", "answer": "A.", "interrupt": True, "evidence": "e", "finished": False, "question": "Which one?"}), Interrupt("e", "Which one?"))
|
||||
self.assertEqual(verdict_from({"bundled": 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, "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, "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, "escalation": "", "answer": "", "interrupt": True, "evidence": "x", "finished": False, "question": " "}), Failure("the judge interrupted without a question"))
|
||||
self.assertEqual(verdict_from(None), Failure("the judge returned no reply"))
|
||||
|
||||
def test_takes_a_bundled_r_plus_c_from_0_to_20_on_an_unfinished_verdict(self):
|
||||
reply = {"answer": "", "interrupt": False, "evidence": "e", "finished": False, "question": ""}
|
||||
reply = {"answer": "", "escalation": "", "interrupt": False, "evidence": "e", "finished": False, "question": ""}
|
||||
self.assertEqual(verdict_from({**reply, "bundled": 20}), Unfinished("e", 20))
|
||||
self.assertEqual(verdict_from({**reply, "bundled": True}), Failure("the judge's reply has no bundled of type integer"))
|
||||
for bundled in (21, -1):
|
||||
@@ -788,6 +812,13 @@ class Verdict(unittest.TestCase):
|
||||
self.assertEqual(verdict_from({**reply, "bundled": bundled}), Failure(f"the judge's bundled R + C {bundled} is not from 0 to 20"))
|
||||
|
||||
|
||||
def test_takes_an_escalation_quote_on_an_unfinished_verdict(self):
|
||||
reply = {"answer": "", "bundled": 0, "escalation": "round 2: 🔴", "interrupt": False, "evidence": "e", "finished": False, "question": ""}
|
||||
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"))
|
||||
|
||||
|
||||
class LoopRuns(unittest.TestCase):
|
||||
def test_stops_naming_the_reload_when_it_hands_over_anything_but_the_state_with_a_task(self):
|
||||
for handed in (["3", "2", "/r", "do it"], ["3"], ["[1]"], [json.dumps({"cycle_number": 3, "root": "/r", "unfinished_evidence": ""})], [json.dumps({"cycle_number": 3, "root": "/r", "task": "", "unfinished_evidence": ""})], [json.dumps({"cycle_number": "3", "root": "/r", "task": "do it", "unfinished_evidence": ""})], [json.dumps({"cycle_number": 3, "root": "", "task": "do it", "unfinished_evidence": ""})], [json.dumps({"cycle_number": 3, "root": "/r", "task": "do it", "turns": 1, "unfinished_evidence": ""})], [json.dumps({"cycle_number": 3, "failures": 0, "root": "/r", "task": "do it", "unfinished_evidence": ""})]):
|
||||
@@ -885,21 +916,25 @@ class ExitContract(unittest.TestCase):
|
||||
|
||||
class JudgeFailures(unittest.TestCase):
|
||||
def test_every_failed_judge_run_has_its_clause_in_help(self):
|
||||
started, field, unasked = "claude cannot start or exits non-zero", "its reply misses or mistypes a field", "interrupts or quotes an answer without a question"
|
||||
# Every Failure the judge's run returns, in source order: path, function, start of reason, its --help clause.
|
||||
started, exited, unparsed = "claude cannot start", "exits non-zero", "prints no json reply"
|
||||
field, unasked = "its reply misses or mistypes a field", "interrupts or quotes an answer without a question"
|
||||
# Every Failure the judge's run returns, in source order of judge.py, then of the claude run it calls: function, start of reason, its --help clause.
|
||||
clauses = [
|
||||
("verdict_from", "'the judge returned no reply'", field),
|
||||
("verdict_from", 'f"the judge\'s reply has no {name}', field),
|
||||
("verdict_from", "'the judge interrupted without a question'", unasked),
|
||||
("verdict_from", "'the judge quoted an answer without a question'", unasked),
|
||||
("verdict_from", 'f"the judge\'s bundled R + C', "gives an unfinished verdict an R + C outside 0 to 20"),
|
||||
("run_judge", "f'could not start claude:", started),
|
||||
("run_judge", "proc.stderr.strip() or f'the judge exited", started),
|
||||
("run_judge", 'f"{verdict.reason}; it replied:', field),
|
||||
("run_judge", "f'{verdict.reason}; it replied:", field),
|
||||
("run_judge", "f'the judge quoted {verdict.evidence!r}, which is not in the transcript", "quotes a passage the transcript does not hold"),
|
||||
("claude_reply", "f'could not start claude:", started),
|
||||
("claude_reply", "proc.stderr.strip() or f'{who} exited", exited),
|
||||
("claude_reply", 'f"{who} printed no json reply', unparsed),
|
||||
]
|
||||
functions = [node for node in ast.walk(ast.parse(pathlib.Path(judge.__file__).read_text())) if isinstance(node, ast.FunctionDef)]
|
||||
found = sorted((call.lineno, function.name, ast.unparse(call.args[0])) for function in functions for call in ast.walk(function) if isinstance(call, ast.Call) and getattr(call.func, "id", None) == "Failure")
|
||||
found = []
|
||||
for module in (judge, reply):
|
||||
functions = [node for node in ast.walk(ast.parse(pathlib.Path(module.__file__).read_text())) if isinstance(node, ast.FunctionDef)]
|
||||
found += sorted((call.lineno, function.name, ast.unparse(call.args[0])) for function in functions for call in ast.walk(function) if isinstance(call, ast.Call) and getattr(call.func, "id", None) == "Failure")
|
||||
self.assertEqual(len(found), len(clauses), found)
|
||||
for (_, function, reason), (want_function, reason_start, _) in zip(found, clauses):
|
||||
self.assertEqual(function, want_function)
|
||||
|
||||
+266
-78
@@ -1,12 +1,14 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Score todo.md's items by the formula and goal weights it states, and hold them to its bar.
|
||||
"""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.
|
||||
|
||||
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,
|
||||
security rows come first, then the rest by score from highest, then by ID. Orders the details to
|
||||
match. --check writes nothing and fails when the file is not ranked as it would be.
|
||||
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. Adds the Blocked by column
|
||||
to a table without it. --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:
|
||||
|
||||
@@ -14,21 +16,17 @@ A valid todo.md; ## Details and each item's detail are optional:
|
||||
|
||||
## Scoring
|
||||
|
||||
`Score = -R - S/4 + 2*A + 2*G*W`
|
||||
`Score = 100 * V / (2**S + 8)`
|
||||
|
||||
`Bar = 9`
|
||||
`Bar = 1`
|
||||
|
||||
`Next ID = 2`
|
||||
|
||||
| Goal | W |
|
||||
|---|---|
|
||||
| 1 | 1.00 |
|
||||
|
||||
## Items
|
||||
|
||||
| ID | Release | Exempt | Item | R | S | C | A | G | Goals | Score |
|
||||
|---|---|---|---|---|---|---|---|---|---|---|
|
||||
| 1 | 0.1.0 | | **Make the first thing work.** | 2 | 3 | 4 | 8 | 9 | 1 | 0 |
|
||||
| ID | Release | Blocked by | Exempt | Item | R | S | C | Moves | Score |
|
||||
|---|---|---|---|---|---|---|---|---|---|
|
||||
| 1 | 0.1.0 | | | **Make the first thing work.** | 2 | 3 | 4 | 1 by 9 | 0 |
|
||||
|
||||
## Details
|
||||
|
||||
@@ -36,16 +34,33 @@ A valid todo.md; ## Details and each item's detail are optional:
|
||||
|
||||
What the tagline cannot say.
|
||||
|
||||
- The formula holds numbers, + - * / and parentheses over R, S, A, G and W.
|
||||
- The formula holds numbers, + - * / ** and parentheses over 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.
|
||||
- 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.
|
||||
- The goal weights list README.md's numbered goals in order, a sub-goal such as 1.1 included.
|
||||
- An item's R, S, C, A and G are whole numbers from 1 to 10; Goals lists goal numbers, comma separated.
|
||||
C, how hard the change is to get right, stays out of the formula.
|
||||
- An item's Exempt cell is empty, or names why the bar does not apply: decision, defect,
|
||||
- An item's R, S and C are whole numbers from 1 to 10. C, how hard the change is to get right, stays
|
||||
out of the formula.
|
||||
- An item's Moves cell is empty, or names each goal it moves and how far, a whole number from 1 to
|
||||
10, such as `1.1 by 8, 1.2 by 5`: the most specific goal, and a parent only for a move none of its
|
||||
sub-goals covers, so never a goal beside its own sub-goal. An empty cell scores V 0.
|
||||
- An item's Exempt cell is empty, or names why the bar does not apply: decision, defect, owner,
|
||||
principle, question or security. An item docs/decisions.md cites as "`todo.md` item N" must be
|
||||
exempt, and a row marked decision must be cited there.
|
||||
- An item's Item cell is one bold tagline; its detail, if any, sits under its ID in ## Details.
|
||||
- An item's Blocked by cell is empty, or lists IDs such as `12, 14`: each must be done before the
|
||||
item starts, so no blocker may sit in a later release, and no item may block itself or form a
|
||||
loop. An ID at or above Next ID fails; one below it that the table no longer holds was finished
|
||||
or deleted, and is dropped.
|
||||
- ## Items holds the table and nothing else: an order goes in the scores or the Blocked by column.
|
||||
- The table holds the columns above. A table without Blocked by gains it. One without C fails, and so
|
||||
does one with a column this version does not know, since writing it would drop that column.
|
||||
- A table in the old shape, with A, G and Goals columns in place of 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.
|
||||
|
||||
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
|
||||
@@ -57,24 +72,33 @@ import math
|
||||
import pathlib
|
||||
import re
|
||||
import sys
|
||||
import typing
|
||||
|
||||
from todo_table import cells, Item, ITEMS_HEADER, parse_row, table_rows, WITHOUT_C
|
||||
from todo_table import BLOCKED_BY, cells, HEADER_START, Item, items_table, MOVES, OLD_SHAPE, parse_row, Shape, shape_of, Table, table_rows
|
||||
from failure import Failure
|
||||
from markdown_text import FENCE, sections
|
||||
from file_writes import replace_file
|
||||
|
||||
LARGEST_FORMULA = 200
|
||||
LONGEST_FORMULA = 4 * LARGEST_FORMULA
|
||||
OPERATORS = (ast.Add, ast.BinOp, ast.Div, ast.Expression, ast.Load, ast.Mult, ast.Sub, ast.UAdd, ast.UnaryOp, ast.USub)
|
||||
VARIABLES = ("A", "G", "R", "S", "W")
|
||||
OPERATORS = (ast.Add, ast.BinOp, ast.Div, ast.Expression, ast.Load, ast.Mult, ast.Pow, ast.Sub, ast.UAdd, ast.UnaryOp, ast.USub)
|
||||
WEIGHTS_HEADER = "| Goal | W |"
|
||||
# The Exempt reasons that rank ahead of the rest of their release, in this order: a question first, since its answer may change other items, then a security finding.
|
||||
FIRST = {"question": 0, "security": 1}
|
||||
# How README.md marks a goal; None where it marks it neither way.
|
||||
Mark = typing.Literal["Maintain", "Achieve"] | None
|
||||
RESHAPE = f"todo.md's items table is in the old shape, scoring A and G against goal weights todo.md states. Until todo.md has the shape rank_todo.py --help shows, reshaping it is the project's only work, as ~/.claude/CLAUDE.md → 'Working loop' says: mark README.md's goals **Maintain:** or **Achieve:**, name each item's {MOVES}, and set the bar below the score of every item to keep"
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Scoring:
|
||||
shape: Shape
|
||||
formula: ast.Expression
|
||||
bar: float
|
||||
next_id: int
|
||||
# README.md's goals in reading order, each with its mark.
|
||||
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.
|
||||
weights: dict[str, float]
|
||||
|
||||
|
||||
@@ -82,6 +106,8 @@ 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.
|
||||
notes: list[str]
|
||||
|
||||
|
||||
def main(argv: list[str]) -> int:
|
||||
@@ -107,7 +133,7 @@ def main(argv: list[str]) -> int:
|
||||
unwritten = write(todo, ranked.text)
|
||||
if unwritten:
|
||||
return fail(unwritten)
|
||||
for line in ranked.under_bar:
|
||||
for line in ranked.notes + ranked.under_bar:
|
||||
print(f"{todo}: {line}", file=sys.stderr)
|
||||
return 1 if ranked.under_bar else 0
|
||||
|
||||
@@ -160,40 +186,79 @@ def write(path: pathlib.Path, text: str) -> Failure | None:
|
||||
|
||||
def rank(text: str, readme: str, decisions: str) -> Ranked | Failure:
|
||||
lines = text.split("\n")
|
||||
scoring = read_scoring(text, lines, readme)
|
||||
if isinstance(scoring, Failure):
|
||||
return scoring
|
||||
table = read_items(lines, scoring)
|
||||
table = read_table(lines)
|
||||
if isinstance(table, Failure):
|
||||
return table
|
||||
items, start = table
|
||||
shape = shape_of(table.columns)
|
||||
scoring = read_scoring(text, lines, readme, shape)
|
||||
if isinstance(scoring, Failure):
|
||||
return scoring
|
||||
items = read_items(table, scoring)
|
||||
if isinstance(items, Failure):
|
||||
return items
|
||||
if uncited := check_citations(items, decisions):
|
||||
return uncited
|
||||
scored = []
|
||||
for item in items:
|
||||
value = score(scoring.formula, item, scoring.weights)
|
||||
if isinstance(value, Failure):
|
||||
return value
|
||||
scored.append((item, value))
|
||||
scored.sort(key=lambda pair: (pair[0].release, pair[0].exempt != "security", -pair[1], pair[0].id))
|
||||
lines[start:start + len(scored)] = [render_item(item, value) for item, value in scored]
|
||||
ranked = rank_details("\n".join(lines), [item for item, _ in scored])
|
||||
scored = ordered(items, scoring)
|
||||
if isinstance(scored, Failure):
|
||||
return scored
|
||||
ranked = rank_details(rewrite_table(lines, table, shape, scored), [item for item, _ in scored])
|
||||
if isinstance(ranked, Failure):
|
||||
return ranked
|
||||
under_bar = [f"item {item.id} scores {value:.1f}, under the bar {scoring.bar:g}; delete it and any item that needs it, or mark it with a reason the bar does not apply" for item, value in scored if not item.exempt and round(value, 1) < scoring.bar]
|
||||
return Ranked(ranked, under_bar)
|
||||
under_bar = [under_the_bar(item, value, scoring.bar, items) for item, value in scored if not item.exempt and round(value, 1) < scoring.bar]
|
||||
return Ranked(ranked, under_bar, notes(items, scoring))
|
||||
|
||||
|
||||
def read_scoring(text: str, lines: list[str], readme: str) -> Scoring | Failure:
|
||||
if ITEMS_HEADER not in lines and "## Items" not in lines:
|
||||
return Failure("todo.md is not in the scored-table format; rank_todo.py --help shows a valid one")
|
||||
# A table without C fails, so no chunk starts on an unscored item.
|
||||
if WITHOUT_C in lines:
|
||||
return Failure("todo.md's items table has no C column; add one after S, and score each item's C from 1 to 10 per rank_todo.py --help")
|
||||
def rewrite_table(lines: list[str], table: Table, shape: Shape, scored: list[tuple[Item, float]]) -> str:
|
||||
"""lines with the table's rows in scored's order, under a header naming every column of shape, so a table from before BLOCKED_BY joined gains the column."""
|
||||
columns = shape.columns
|
||||
header = ["| " + " | ".join(columns) + " |", "|" + "---|" * len(columns)]
|
||||
rows = [render_item(item, value, shape) for item, value in scored]
|
||||
return "\n".join(lines[:table.header] + header + rows + lines[table.start + len(table.rows):])
|
||||
|
||||
|
||||
def notes(items: list[Item], scoring: Scoring) -> list[str]:
|
||||
held = {item.id for item in items}
|
||||
dropped = [f"item {item.id}: dropped {', '.join(map(str, gone))} from its {BLOCKED_BY}; the table no longer holds {'it' if len(gone) == 1 else 'them'}" for item in items if (gone := sorted(set(item.blocked_by) - held))]
|
||||
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"]
|
||||
return unweighed + dropped
|
||||
|
||||
|
||||
def blocked_through(id_: int, items: list[Item]) -> set[int]:
|
||||
"""The IDs of the items id_ blocks, and of those they block in turn."""
|
||||
found: set[int] = set()
|
||||
reached = {id_}
|
||||
while reached:
|
||||
reached = {other.id for other in items if reached.intersection(other.blocked_by)} - found
|
||||
found |= reached
|
||||
return found
|
||||
|
||||
|
||||
def ordered(items: list[Item], scoring: Scoring) -> list[tuple[Item, float]] | Failure:
|
||||
"""Each item with its score, by release, then questions and security findings first, then by score from highest, then by ID; then each blocker above every item it blocks."""
|
||||
by_score = []
|
||||
for item in items:
|
||||
value = score(scoring.formula, item, scoring)
|
||||
if isinstance(value, Failure):
|
||||
return value
|
||||
by_score.append((item, value))
|
||||
by_score.sort(key=lambda pair: (pair[0].release, FIRST.get(pair[0].exempt, len(FIRST)), -pair[1], pair[0].id))
|
||||
return blockers_first(by_score)
|
||||
|
||||
|
||||
def under_the_bar(item: Item, value: float, bar: float, items: list[Item]) -> str:
|
||||
blocks = [str(id_) for id_ in sorted(blocked_through(item.id, items))]
|
||||
blocked = f" and the items it blocks, directly or through another ({', '.join(blocks)})" if blocks else ""
|
||||
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)
|
||||
if isinstance(goals, Failure):
|
||||
return goals
|
||||
formula = parse_formula(stated(text, "Score"))
|
||||
formula = parse_formula(stated(text, "Score"), variables(shape))
|
||||
if isinstance(formula, Failure):
|
||||
return formula
|
||||
bar = number(stated(text, "Bar"), "the bar")
|
||||
@@ -202,22 +267,50 @@ def read_scoring(text: str, lines: list[str], readme: str) -> Scoring | Failure:
|
||||
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")
|
||||
weights = parse_weights(lines, goals)
|
||||
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)
|
||||
if isinstance(weights, Failure):
|
||||
return weights
|
||||
return Scoring(formula, bar, int(next_id), weights)
|
||||
return Scoring(shape, formula, bar, int(next_id), dict(goals), weights)
|
||||
|
||||
|
||||
def read_items(lines: list[str], scoring: Scoring) -> tuple[list[Item], int] | Failure:
|
||||
"""The items, and the index of the first row in lines."""
|
||||
table = table_rows(lines, ITEMS_HEADER)
|
||||
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:
|
||||
return Failure("todo.md is not in the scored-table format; rank_todo.py --help shows a valid one")
|
||||
table = items_table(lines)
|
||||
if table is None:
|
||||
return Failure(f"## Items holds no table whose header opens {HEADER_START}; rank_todo.py --help shows a valid one")
|
||||
if isinstance(table, Failure):
|
||||
return table
|
||||
if stray_row(lines[table.start + len(table.rows):]):
|
||||
return Failure("## Items holds a row outside its table; keep the rows together under the header")
|
||||
# A table without C fails, so no chunk starts on an unscored item.
|
||||
if "C" not in table.columns:
|
||||
return Failure("todo.md's items table has no C column; add one after S, and score each item's C from 1 to 10 per rank_todo.py --help")
|
||||
return unknown_columns(table) or outside_items(lines, table) or table
|
||||
|
||||
|
||||
def unknown_columns(table: Table) -> Failure | None:
|
||||
"""Why ranking, which writes only the columns of the table's shape, would drop one of the table's columns; None when it would drop none."""
|
||||
known = shape_of(table.columns).columns
|
||||
unknown = [column for column in table.columns if column not in known]
|
||||
if old := [column for column in unknown if column in OLD_SHAPE.columns]:
|
||||
listed = old[0] if len(old) == 1 else f"{', '.join(old[:-1])} and {old[-1]}"
|
||||
kind = f"a column of the old shape that {MOVES} replaced; drop it" if len(old) == 1 else f"columns of the old shape that {MOVES} replaced; drop them"
|
||||
return Failure(f"todo.md's items table has {listed}, {kind}")
|
||||
if unknown:
|
||||
return Failure(f"todo.md's items table has the column {', '.join(unknown)}, which this rank_todo.py does not know; the columns it knows are {', '.join(known)}. Rename it, or move this machine to the release that added it")
|
||||
return None
|
||||
|
||||
|
||||
def read_items(table: Table, scoring: Scoring) -> list[Item] | Failure:
|
||||
items = []
|
||||
for row in table.rows:
|
||||
item = parse_item(row, scoring.weights)
|
||||
item = parse_item(row, scoring, table)
|
||||
if isinstance(item, Failure):
|
||||
return item
|
||||
items.append(item)
|
||||
@@ -226,13 +319,64 @@ def read_items(lines: list[str], scoring: Scoring) -> tuple[list[Item], int] | F
|
||||
return Failure("two items share an ID")
|
||||
if ids and max(ids) >= scoring.next_id:
|
||||
return Failure(f"item {max(ids)} is not under Next ID {scoring.next_id}; raise Next ID past every ID")
|
||||
return items, table.start
|
||||
for item in items:
|
||||
if unheld := [blocker for blocker in item.blocked_by if blocker >= scoring.next_id]:
|
||||
return Failure(f"item {item.id} is blocked by item {unheld[0]}, which is not under Next ID {scoring.next_id}; name an item the table holds or held")
|
||||
return items
|
||||
|
||||
|
||||
def stray_row(after: list[str]) -> bool:
|
||||
"""Whether a table row follows the table before the next ## heading."""
|
||||
def outside_items(lines: list[str], table: Table) -> Failure | None:
|
||||
"""Why the table does not stand alone under ## Items: the table's order is todo.md's only order."""
|
||||
heading = max((index for index in range(table.header) if lines[index].startswith("## ")), default=None)
|
||||
if heading is None:
|
||||
return Failure("the items table sits under no ## heading; move it under ## Items")
|
||||
if lines[heading] != "## Items":
|
||||
return Failure(f"the items table sits under {lines[heading]}, not ## Items; move it under ## Items")
|
||||
after = lines[table.start + len(table.rows):]
|
||||
section = after[:next((index for index, line in enumerate(after) if line.startswith("## ")), len(after))]
|
||||
return any(line.startswith("|") for line in section)
|
||||
if any(line.strip() for line in lines[heading + 1:table.header] + section):
|
||||
return Failure(f"## Items holds text beside its table; an order goes in the scores or the {BLOCKED_BY} column, and a note in the item's detail")
|
||||
return None
|
||||
|
||||
|
||||
def blockers_first(scored: list[tuple[Item, float]]) -> list[tuple[Item, float]] | Failure:
|
||||
"""scored, each blocker that ranks below an item it blocks moved up to just above the first such item; a blocker the table no longer holds was finished or deleted, and is dropped."""
|
||||
held = {item.id: (item, value) for item, value in scored}
|
||||
position = {item.id: index for index, (item, _) in enumerate(scored)}
|
||||
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)
|
||||
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:
|
||||
placed = place(item.id, held, position, {placed.id for placed, _ in result}, [])
|
||||
if isinstance(placed, Failure):
|
||||
return placed
|
||||
result += placed
|
||||
return result
|
||||
|
||||
|
||||
def place(id_: int, held: dict[int, tuple[Item, float]], position: dict[int, int], placed: set[int], path: list[int]) -> list[tuple[Item, float]] | Failure:
|
||||
"""The item id_ preceded by those of its blockers not yet placed, each in score order, and theirs before them; path holds the items waiting on this one, to find a loop."""
|
||||
if id_ in path:
|
||||
loop = sorted(path[path.index(id_):])
|
||||
return Failure(f"items {', '.join(map(str, loop[:-1]))} and {loop[-1]} block each other in a loop; drop one of the blockers")
|
||||
if id_ in placed:
|
||||
return []
|
||||
item, value = held[id_]
|
||||
blockers = sorted((blocker for blocker in set(item.blocked_by) if blocker in held), key=position.__getitem__)
|
||||
added: list[tuple[Item, float]] = []
|
||||
for blocker in blockers:
|
||||
before = place(blocker, held, position, placed | {entry.id for entry, _ in added}, [*path, id_])
|
||||
if isinstance(before, Failure):
|
||||
return before
|
||||
added += before
|
||||
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:
|
||||
@@ -248,25 +392,37 @@ def check_citations(items: list[Item], decisions: str) -> Failure | None:
|
||||
return None
|
||||
|
||||
|
||||
def readme_goals(readme: str) -> list[str] | Failure:
|
||||
"""The numbers of README.md's goals in reading order, a sub-goal as 4.1."""
|
||||
def readme_goals(readme: str) -> list[tuple[str, Mark]] | Failure:
|
||||
"""README.md's goals in reading order: each one's number, a sub-goal as 4.1, and its mark, Maintain, Achieve or None."""
|
||||
found = sections(readme).get("Goals", [])
|
||||
if len(found) != 1:
|
||||
return Failure(f"README.md has ## Goals {len(found)} times; it needs it once")
|
||||
goals: list[str] = []
|
||||
goals: list[tuple[str, Mark]] = []
|
||||
path: list[tuple[int, str]] = []
|
||||
for indent, position in re.findall(r"^([ \t]*)(\d+)\. ", found[0].expandtabs(4), re.M):
|
||||
for indent, position, mark in re.findall(r"^([ \t]*)(\d+)\. (?:\*\*(Maintain|Achieve):\*\*)?", found[0].expandtabs(4), re.M):
|
||||
while path and path[-1][0] >= len(indent):
|
||||
path.pop()
|
||||
path.append((len(indent), position))
|
||||
goals.append(".".join(part for _, part in path))
|
||||
goals.append((".".join(part for _, part in path), typing.cast(Mark, mark or None)))
|
||||
numbers = [number for number, _ in goals]
|
||||
if not goals:
|
||||
return Failure("README.md's ## Goals has no numbered goal")
|
||||
if len(set(goals)) < len(goals):
|
||||
return Failure(f"README.md's ## Goals numbers {', '.join(goals)}; number each goal by its position")
|
||||
if len(set(numbers)) < len(numbers):
|
||||
return Failure(f"README.md's ## Goals numbers {', '.join(numbers)}; number each goal by its position")
|
||||
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."""
|
||||
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)}
|
||||
heaviest = max(weights.values(), default=0.0)
|
||||
return weights | {number: heaviest for number, mark in goals if mark == "Maintain"}
|
||||
|
||||
|
||||
def cited_items(decisions: str) -> list[int]:
|
||||
return [int(id_) for cited in re.findall(r"`todo\.md` items? (\d+(?:(?:, | and )\d+)*)", decisions) for id_ in re.findall(r"\d+", cited)]
|
||||
|
||||
@@ -278,7 +434,7 @@ def stated(text: str, name: str) -> str | Failure:
|
||||
return found[0]
|
||||
|
||||
|
||||
def parse_formula(source: str | Failure) -> ast.Expression | Failure:
|
||||
def parse_formula(source: str | Failure, variables: tuple[str, ...]) -> ast.Expression | Failure:
|
||||
if isinstance(source, Failure):
|
||||
return source
|
||||
# Deep nesting makes the parser itself run out of memory before LARGEST_FORMULA can count the parts.
|
||||
@@ -293,13 +449,13 @@ def parse_formula(source: str | Failure) -> ast.Expression | Failure:
|
||||
return Failure(f"the formula {source!r} holds more than {LARGEST_FORMULA} parts")
|
||||
for node in nodes:
|
||||
numeric = isinstance(node, ast.Constant) and isinstance(node.value, (int, float)) and not isinstance(node.value, bool) and abs(node.value) < 1e300
|
||||
if not (isinstance(node, OPERATORS) or numeric or (isinstance(node, ast.Name) and node.id in VARIABLES)):
|
||||
return Failure(f"the formula {source!r} may hold only numbers, {', '.join(VARIABLES)}, + - * / and parentheses")
|
||||
if not (isinstance(node, OPERATORS) or numeric or (isinstance(node, ast.Name) and node.id in variables)):
|
||||
return Failure(f"the formula {source!r} may hold only numbers, {', '.join(variables)}, + - * / ** and parentheses")
|
||||
return tree
|
||||
|
||||
|
||||
def evaluate(node: ast.AST, values: dict[str, float]) -> float:
|
||||
"""Evaluates a tree parse_formula accepted; a division by zero gives nan."""
|
||||
"""Evaluates a tree parse_formula accepted; a division by zero, and a power that overflows or has no real value, give nan."""
|
||||
match node:
|
||||
case ast.Expression(body):
|
||||
return evaluate(body, values)
|
||||
@@ -320,12 +476,37 @@ def evaluate(node: ast.AST, values: dict[str, float]) -> float:
|
||||
case ast.BinOp(left, ast.Div(), right):
|
||||
divisor = evaluate(right, values)
|
||||
return evaluate(left, values) / divisor if divisor else math.nan
|
||||
case ast.BinOp(left, ast.Pow(), right):
|
||||
# math.pow raises on a negative base with a fractional exponent, zero to a negative power, and overflow; one catch covers all three.
|
||||
base, exponent = evaluate(left, values), evaluate(right, values)
|
||||
# A nan from a zero divisor stays nan, though math.pow(1, nan) and math.pow(nan, 0) give 1.
|
||||
if math.isnan(base) or math.isnan(exponent):
|
||||
return math.nan
|
||||
try:
|
||||
return math.pow(base, exponent)
|
||||
except (OverflowError, ValueError):
|
||||
return math.nan
|
||||
return math.nan
|
||||
|
||||
|
||||
def score(formula: ast.Expression, item: Item, weights: dict[str, float]) -> float | Failure:
|
||||
# An item serving several goals is weighed by the heaviest; summing them would reward citing more.
|
||||
value = evaluate(formula, {**item.scores, "W": max(weights[goal] for goal in item.goals)})
|
||||
def goal_term(shape: Shape) -> str:
|
||||
"""The name of the formula's goal term, which score builds: W in OLD_SHAPE, V in the current shape."""
|
||||
return "W" if shape is OLD_SHAPE else "V"
|
||||
|
||||
|
||||
def variables(shape: Shape) -> tuple[str, ...]:
|
||||
"""The names the formula may use: the shape's scores but C, which stays out of the formula, and its goal term."""
|
||||
return tuple(sorted({*shape.score_columns} - {"C"} | {goal_term(shape)}))
|
||||
|
||||
|
||||
def score(formula: ast.Expression, item: Item, scoring: Scoring) -> float | Failure:
|
||||
if goal_term(scoring.shape) == "W":
|
||||
# The old shape weighs an item by its heaviest cited goal.
|
||||
term = max(scoring.weights[goal] for goal, _ in item.moves)
|
||||
else:
|
||||
# Only an OLD_SHAPE item names a goal without a move.
|
||||
term = sum(scoring.weights[goal] * (by or 0) for goal, by in item.moves)
|
||||
value = evaluate(formula, {**item.scores, goal_term(scoring.shape): term})
|
||||
return value if math.isfinite(value) else Failure(f"the formula gives item {item.id} no finite score")
|
||||
|
||||
|
||||
@@ -360,19 +541,26 @@ def parse_weights(lines: list[str], goals: list[str]) -> dict[str, float] | Fail
|
||||
return weights
|
||||
|
||||
|
||||
def parse_item(row: str, weights: dict[str, float]) -> Item | Failure:
|
||||
item = parse_row(row)
|
||||
def parse_item(row: str, scoring: Scoring, table: Table) -> Item | Failure:
|
||||
item = parse_row(row, table)
|
||||
if isinstance(item, Failure):
|
||||
return item
|
||||
if unknown := [goal for goal in item.goals if goal not in weights]:
|
||||
return Failure(f"item {item.id} cites goal {', '.join(unknown)}, which the goal weights do not list")
|
||||
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")
|
||||
return item
|
||||
|
||||
|
||||
def render_item(item: Item, value: float) -> str:
|
||||
release = ".".join(str(part) for part in item.release)
|
||||
scores = " | ".join(str(item.scores[name]) for name in "RSCAG")
|
||||
return f"| {item.id} | {release} | {item.exempt} | {item.tagline} | {scores} | {', '.join(item.goals)} | {value:.1f} |"
|
||||
def render_item(item: Item, value: float, shape: Shape) -> str:
|
||||
"""The item's row, each cell under its column of shape."""
|
||||
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(item.scores[name]) for name in shape.score_columns}, shape.goals_column: shape.write_goals(item.moves), "Score": f"{value:.1f}"}
|
||||
return "| " + " | ".join(written[column] for column in shape.columns) + " |"
|
||||
|
||||
|
||||
def rank_details(text: str, items: list[Item]) -> str | Failure:
|
||||
|
||||
@@ -133,7 +133,7 @@ class ReadingCostTool(unittest.TestCase):
|
||||
def test_appends_each_finished_chunk_once_in_the_order_they_finished_from_a_worktree(self):
|
||||
self.archive_chunk(1790000200)
|
||||
self.archive_chunk(1790000100)
|
||||
self.archive_chunk(1790000000, outcomes.unfinished)
|
||||
self.archive_chunk(1790000000, lambda *fields: outcomes.unfinished(*fields, ""))
|
||||
chunks = finished_chunks(self.archive)
|
||||
self.assertEqual([chunk.finished for chunk in chunks], ["2026-09-21T14:15:00Z", "2026-09-21T14:16:40Z"])
|
||||
worktree = self.home / "code" / "proj-wt"
|
||||
|
||||
@@ -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", "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", "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)
|
||||
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", "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)
|
||||
self.assertEqual(ran.returncode, 0, ran.stdout + ran.stderr)
|
||||
|
||||
@@ -49,7 +49,7 @@ class Measured(unittest.TestCase):
|
||||
message("m2", "2026-10-14T10:05:00.000Z", {"type": "text", "text": "done"}),
|
||||
message("m3", "2026-10-14T11:00:00.000Z", {"type": "text", "text": "on"}),
|
||||
]
|
||||
kept = stamped("2026-10-14T10:30:00Z", outcomes.unfinished(LOW_ROUTE, "e", "j")) + stamped("2026-10-14T10:30:00Z", outcomes.stepped_up(str(HIGH))) + stamped("2026-10-14T12:00:00Z", outcomes.finished(str(HIGH), "merged", "j"))
|
||||
kept = stamped("2026-10-14T10:30:00Z", outcomes.unfinished(LOW_ROUTE, "e", "j", "")) + stamped("2026-10-14T10:30:00Z", outcomes.stepped_up(str(HIGH))) + stamped("2026-10-14T12:00:00Z", outcomes.finished(str(HIGH), "merged", "j"))
|
||||
found = measured(Chunk("log", [kept], worker, []), "/h")
|
||||
self.assertEqual(found.tokens["project"], {"log": 333})
|
||||
self.assertEqual(found.tokens["subagent type"], {"worker": 333})
|
||||
@@ -92,7 +92,7 @@ class Measured(unittest.TestCase):
|
||||
|
||||
|
||||
def test_puts_a_subagent_on_the_model_it_ran_at_the_effort_of_the_cycle_that_launched_it(self):
|
||||
kept = stamped("2026-10-14T10:00:00Z", outcomes.unfinished(LOW_ROUTE, "e", "j")) + stamped("2026-10-14T11:00:00Z", outcomes.finished(str(HIGH), "m", "j"))
|
||||
kept = stamped("2026-10-14T10:00:00Z", outcomes.unfinished(LOW_ROUTE, "e", "j", "")) + stamped("2026-10-14T11:00:00Z", outcomes.finished(str(HIGH), "m", "j"))
|
||||
worker = [
|
||||
message("m1", "2026-10-14T10:00:00.900Z"),
|
||||
message("m2", "2026-10-14T10:30:00Z", call("Agent", "a1", subagent_type="Explore", model="sonnet")),
|
||||
@@ -183,14 +183,14 @@ class Archive(unittest.TestCase):
|
||||
(folder / "session" / "s" / "subagents" / "agent-a.meta.json").write_text(json.dumps(meta))
|
||||
|
||||
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("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.assertEqual(archive.cycles(self.root), 2)
|
||||
self.assertEqual(archive.cycles(self.root / "missing"), 0)
|
||||
|
||||
def test_measures_each_finished_chunk_keyed_by_its_project(self):
|
||||
self.chunk("home/x", "c1", stamped("2026-10-14T10:00:00Z", outcomes.finished(LOW_ROUTE, "m", "j")), [message("m1", "2026-10-14T09:00:00Z", call("Agent", "a1", subagent_type="Explore"))], ({"agentType": "Explore", "toolUseId": "a1"}, [message("s1", "2026-10-14T09:00:01Z")]))
|
||||
self.chunk("log", "c2", stamped("2026-10-14T10:00:00Z", outcomes.unfinished(LOW_ROUTE, "e", "j")), [message("m1", "2026-10-14T09:00:00Z")])
|
||||
self.chunk("log", "c2", stamped("2026-10-14T10:00:00Z", outcomes.unfinished(LOW_ROUTE, "e", "j", "")), [message("m1", "2026-10-14T09:00:00Z")])
|
||||
found = archive.measure_archive(self.root, "/h", "")
|
||||
self.assertEqual([chunk.tokens["project"] for chunk in found.chunks], [{"home/x": 222}])
|
||||
self.assertEqual(found.chunks[0].tokens["subagent type"], {"worker": 111, "Explore": 111})
|
||||
@@ -202,7 +202,7 @@ class Archive(unittest.TestCase):
|
||||
first = message("m1", "2026-09-21T00:00:00Z")
|
||||
transcript.write_text(json.dumps(first) + "\n")
|
||||
with contextlib.redirect_stderr(io.StringIO()):
|
||||
self.assertIsNone(write.archive(kept / "log", str(transcript), "t", outcomes.unfinished(LOW_ROUTE, "e", "j"), 1790000000))
|
||||
self.assertIsNone(write.archive(kept / "log", str(transcript), "t", outcomes.unfinished(LOW_ROUTE, "e", "j", ""), 1790000000))
|
||||
transcript.write_text(json.dumps(first) + "\n" + json.dumps(message("m2", "2099-01-01T00:00:00Z")) + "\n")
|
||||
self.assertIsNone(write.archive(kept / "log", str(transcript), "t", outcomes.finished(str(HIGH), "m", "j"), 4070908800))
|
||||
(found,) = archive.measure_archive(kept, "/h", "").chunks
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
"""What judge-replay's and stability-replay's commands share: the argument, the projects on its model, the candidate rungs and the exits."""
|
||||
import pathlib
|
||||
import sys
|
||||
|
||||
from failure import Failure
|
||||
from model_routing.ladder import LADDER, picked, position, project_rung, Rung
|
||||
from claude_code.reply import Limited
|
||||
from loop_claude.project.model_choice import read_models_file
|
||||
from loop_claude.stop import Stop
|
||||
|
||||
LOWEST_R_PLUS_C = 2
|
||||
|
||||
|
||||
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."""
|
||||
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
|
||||
|
||||
|
||||
def projects_on(model: str, home: pathlib.Path) -> list[str] | Failure:
|
||||
"""The keys of the projects ~/.claude/loop-claude-models.json runs on model, sorted."""
|
||||
models = read_models_file(home / ".claude" / "loop-claude-models.json")
|
||||
if isinstance(models, Stop):
|
||||
return Failure(models.reason)
|
||||
return sorted(key for key, on in models.items() if on == model)
|
||||
|
||||
|
||||
def down_from(top: Rung) -> list[Rung]:
|
||||
"""top and each rung below it, down to the rung the lowest R + C picks from top, highest first."""
|
||||
return list(LADDER[position(picked(top, LOWEST_R_PLUS_C)):position(top) + 1])[::-1]
|
||||
|
||||
|
||||
def limited_exit(tool: str, limited: Limited) -> int:
|
||||
return failed(tool, f"claude hit a usage limit: {limited.said}; replay again once it resets")
|
||||
|
||||
|
||||
def failed(tool: str, reason: str) -> int:
|
||||
print(f"{tool}: {reason}", file=sys.stderr)
|
||||
return 1
|
||||
@@ -0,0 +1,101 @@
|
||||
"""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."""
|
||||
import concurrent.futures
|
||||
import dataclasses
|
||||
import sys
|
||||
import typing
|
||||
|
||||
from failure import Failure
|
||||
from loop_claude.cycle.retry import FAILURES_RUNNING
|
||||
from claude_code.reply import Limited
|
||||
from model_routing.ladder import Rung
|
||||
|
||||
# Cases replayed at once.
|
||||
AT_ONCE = 4
|
||||
|
||||
Case = typing.TypeVar("Case")
|
||||
# What of a case's record a reply reproduces, such as a verdict's kind or a finding's index.
|
||||
Item = typing.TypeVar("Item")
|
||||
Reply = typing.TypeVar("Reply")
|
||||
T = typing.TypeVar("T")
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Miss(typing.Generic[Case, Item, Reply]):
|
||||
"""An item of case that the reference reproduced and a rung's reply missed."""
|
||||
case: Case
|
||||
item: Item
|
||||
reply: Reply
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Tried(typing.Generic[Case, Item, Reply]):
|
||||
rung: Rung
|
||||
missed: list[Miss[Case, Item, Reply]]
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Replay(typing.Generic[Case, Item, Reply]):
|
||||
"""on_reference holds the reference's reply on each case; tried, each candidate tried, highest first; lowest, the lowest rung that, like each candidate above it, missed nothing, or None."""
|
||||
on_reference: list[Reply]
|
||||
tried: list[Tried[Case, Item, Reply]]
|
||||
lowest: Rung | None
|
||||
|
||||
|
||||
def replayed(
|
||||
cases: list[Case],
|
||||
reference: Rung,
|
||||
candidates: list[Rung],
|
||||
replay_one: typing.Callable[[Case, Rung], Reply | Limited],
|
||||
reproduced: typing.Callable[[Case, Reply], list[Item]],
|
||||
what: str,
|
||||
) -> Replay[Case, Item, Reply] | Limited:
|
||||
"""Replays the cases on the reference rung, then each candidate, highest first, on the cases where the reference reproduced anything, until one misses an item it reproduced.
|
||||
|
||||
Going down, every rung at or above the one named was tried and missed nothing, so the result needs no assumption that a higher rung does at least as well; and a miss high up spares the cheaper rungs their replays.
|
||||
"""
|
||||
on_reference = replayed_on(cases, reference, replay_one, what)
|
||||
if isinstance(on_reference, Limited):
|
||||
return on_reference
|
||||
held = [(case, aim) for case, reply in zip(cases, on_reference) if (aim := reproduced(case, reply))]
|
||||
tried: list[Tried[Case, Item, Reply]] = []
|
||||
lowest = None
|
||||
# With nothing to hold a rung to, every rung would miss nothing.
|
||||
for rung in candidates if held else []:
|
||||
replies = replayed_on([case for case, _ in held], rung, replay_one, what)
|
||||
if isinstance(replies, Limited):
|
||||
return replies
|
||||
misses: list[Miss[Case, Item, Reply]] = []
|
||||
for (case, aim), reply in zip(held, replies):
|
||||
got = reproduced(case, reply)
|
||||
misses += [Miss(case, item, reply) for item in aim if item not in got]
|
||||
tried.append(Tried(rung, misses))
|
||||
if misses:
|
||||
break
|
||||
lowest = rung
|
||||
return Replay(on_reference, tried, lowest)
|
||||
|
||||
|
||||
def replayed_on(cases: list[Case], rung: Rung, replay_one: typing.Callable[[Case, Rung], Reply | Limited], what: str) -> list[Reply] | Limited:
|
||||
"""Each case's reply on rung, AT_ONCE at a time; a usage limit cancels the rest."""
|
||||
print(f"replaying {len(cases)} {what} on {rung}", file=sys.stderr, flush=True)
|
||||
with concurrent.futures.ThreadPoolExecutor(AT_ONCE) as pool:
|
||||
running = [pool.submit(replay_one, case, rung) for case in cases]
|
||||
replies: list[Reply] = []
|
||||
for future in running:
|
||||
reply = future.result()
|
||||
if isinstance(reply, Limited):
|
||||
pool.shutdown(cancel_futures=True)
|
||||
return reply
|
||||
replies.append(reply)
|
||||
return replies
|
||||
|
||||
|
||||
def first_reply(attempt: typing.Callable[[], T | Failure | Limited]) -> T | Failure | Limited:
|
||||
"""The first reply that is no Failure, or the last of FAILURES_RUNNING failures.
|
||||
|
||||
It counts failures as loop-claude's retried does, but neither waits between attempts nor waits out a usage limit, which ends a replay.
|
||||
"""
|
||||
for _ in range(FAILURES_RUNNING - 1):
|
||||
if not isinstance(reply := attempt(), Failure):
|
||||
return reply
|
||||
return attempt()
|
||||
@@ -0,0 +1,71 @@
|
||||
import contextlib
|
||||
import io
|
||||
import pathlib
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from rung_replay.command import down_from
|
||||
from failure import Failure
|
||||
from rung_replay.search import first_reply, Miss, Replay, replayed, Tried
|
||||
from claude_code.reply import Limited
|
||||
from model_routing.ladder import Rung
|
||||
|
||||
REFERENCE = Rung("claude-opus-5-5", "medium")
|
||||
MIDDLE = Rung("claude-sonnet-5-5", "high")
|
||||
CHEAP = Rung("claude-haiku-5-5", "max")
|
||||
LOWER = Rung("claude-haiku-5-5", "xhigh")
|
||||
|
||||
|
||||
def search(cases, candidates, replies):
|
||||
"""replayed on cases named by strings, where replies[rung][case] is the set of items a rung reproduces in the case."""
|
||||
asked = []
|
||||
|
||||
def replay_one(case, rung):
|
||||
asked.append((case, rung))
|
||||
reply = replies[rung]
|
||||
return reply if isinstance(reply, Limited) else reply[case]
|
||||
|
||||
with contextlib.redirect_stderr(io.StringIO()):
|
||||
return replayed(cases, REFERENCE, candidates, replay_one, lambda _, reply: sorted(reply), "cases"), asked
|
||||
|
||||
|
||||
class Replayed(unittest.TestCase):
|
||||
def test_holds_each_candidate_highest_first_to_what_the_reference_reproduced_and_stops_at_the_first_that_misses(self):
|
||||
replies = {REFERENCE: {"a": {0, 1}, "b": set()}, MIDDLE: {"a": {0, 1}}, CHEAP: {"a": {1}}}
|
||||
replay, asked = search(["a", "b"], [MIDDLE, CHEAP, LOWER], replies)
|
||||
self.assertEqual(replay, Replay([{0, 1}, set()], [Tried(MIDDLE, []), Tried(CHEAP, [Miss("a", 0, {1})])], MIDDLE))
|
||||
self.assertEqual(sorted(asked, key=lambda pair: (pair[1] != REFERENCE, pair[0])), [("a", REFERENCE), ("b", REFERENCE), ("a", MIDDLE), ("a", CHEAP)])
|
||||
|
||||
def test_names_no_rung_when_the_first_misses_and_tries_none_when_the_reference_reproduced_nothing(self):
|
||||
self.assertEqual(search(["a"], [MIDDLE, CHEAP], {REFERENCE: {"a": {0}}, MIDDLE: {"a": set()}})[0], Replay([{0}], [Tried(MIDDLE, [Miss("a", 0, set())])], None))
|
||||
self.assertEqual(search(["a"], [MIDDLE], {REFERENCE: {"a": set()}}), (Replay([set()], [], None), [("a", REFERENCE)]))
|
||||
|
||||
def test_counts_a_miss_in_any_case_not_only_the_last(self):
|
||||
replies = {REFERENCE: {"a": {0}, "b": {0}}, MIDDLE: {"a": set(), "b": {0}}}
|
||||
self.assertEqual(search(["a", "b"], [MIDDLE], replies)[0], Replay([{0}, {0}], [Tried(MIDDLE, [Miss("a", 0, set())])], None))
|
||||
|
||||
def test_stops_at_a_usage_limit(self):
|
||||
limit = Limited(None, "limit")
|
||||
self.assertEqual(search(["a"], [MIDDLE], {REFERENCE: limit})[0], limit)
|
||||
self.assertEqual(search(["a"], [MIDDLE, CHEAP], {REFERENCE: {"a": {0}}, MIDDLE: limit})[0], limit)
|
||||
|
||||
|
||||
class FirstReply(unittest.TestCase):
|
||||
def test_tries_three_times_and_returns_the_first_reply_that_is_no_failure(self):
|
||||
replies = [Failure("one"), Failure("two"), "done"]
|
||||
self.assertEqual(first_reply(lambda: replies.pop(0)), "done")
|
||||
replies = [Failure("one"), Limited(None, "limit")]
|
||||
self.assertEqual(first_reply(lambda: replies.pop(0)), Limited(None, "limit"))
|
||||
replies = [Failure("one"), Failure("two"), Failure("three"), "unasked"]
|
||||
self.assertEqual(first_reply(lambda: replies.pop(0)), Failure("three"))
|
||||
|
||||
|
||||
class DownFrom(unittest.TestCase):
|
||||
def test_runs_from_the_projects_rung_down_to_the_rung_the_lowest_r_plus_c_picks(self):
|
||||
self.assertEqual(down_from(REFERENCE), [REFERENCE, MIDDLE, CHEAP, LOWER])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -23,7 +23,7 @@ def todo(*rows: str, header: str = HEADER) -> str:
|
||||
|
||||
|
||||
def item(id_: int, scores: dict[str, int]) -> Item:
|
||||
return Item(id_, (0, 1, 0), "", f"**Item {id_}.**", scores, ("1",))
|
||||
return Item(id_, (0, 1, 0), "", f"**Item {id_}.**", scores, (("1", None),), ())
|
||||
|
||||
|
||||
def outcome(id_: int, r: int, s: int, c: int | None, lines: int = 10, rounds: int = 1, findings: tuple[int, int] | None = (0, 0), merged: str = "2026-10-13T10:00:00Z", shipped_with: tuple[int, ...] = ()) -> Outcome:
|
||||
|
||||
Executable
+11
@@ -0,0 +1,11 @@
|
||||
#!/usr/bin/env python3
|
||||
import os
|
||||
import pathlib
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
|
||||
|
||||
from stability_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,207 @@
|
||||
"""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 stays on 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 rung the lowest R + C picks, 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 stays on 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,110 @@
|
||||
"""Which archived stability rounds to replay, the code each reviewed, and the report: docs/decisions.md → `routing: the stability reviewer stays on the project's rung`."""
|
||||
import dataclasses
|
||||
import datetime
|
||||
import pathlib
|
||||
import re
|
||||
import typing
|
||||
|
||||
from claude_code.entries import assistant_parts, content, part_text, parts
|
||||
from rung_replay.search import Replay
|
||||
from model_routing.ladder import Rung
|
||||
|
||||
# A line that opens with a 🔴 or 🟡 mark, after any list, table, heading or bold markup, as review-findings.md has reviewers report them.
|
||||
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+)?)?[.:]?$")
|
||||
|
||||
|
||||
@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."""
|
||||
root: str
|
||||
branch: str
|
||||
at: str
|
||||
began: float
|
||||
prompt: str
|
||||
findings: tuple[str, ...]
|
||||
|
||||
@property
|
||||
def seconds(self) -> float:
|
||||
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."""
|
||||
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))
|
||||
|
||||
|
||||
def stamped(entry: dict) -> bool:
|
||||
try:
|
||||
return isinstance(entry.get("timestamp"), str) and bool(stamp_seconds(entry["timestamp"]))
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
|
||||
def stamp_seconds(stamp: str) -> float:
|
||||
return datetime.datetime.fromisoformat(stamp.replace("Z", "+00:00")).timestamp()
|
||||
|
||||
|
||||
def recorded_findings(report_text: str) -> list[str]:
|
||||
findings: list[list[str]] = []
|
||||
open_finding = False
|
||||
for line in report_text.splitlines():
|
||||
if FINDING.match(line):
|
||||
findings.append([line])
|
||||
open_finding = True
|
||||
elif open_finding and line.strip():
|
||||
findings[-1].append(line)
|
||||
else:
|
||||
open_finding = False
|
||||
return ["\n".join(lines) for lines in findings]
|
||||
|
||||
|
||||
def reviewed_path(prompt: str, root: str, exists: typing.Callable[[str], bool]) -> str | None:
|
||||
"""Where the reviewer read the code: the one gone directory the prompt names beside the checkout or inside it, as a removed worktree, else the checkout when the prompt names it; None when it names neither, or two gone ones."""
|
||||
checkout = pathlib.PurePath(root)
|
||||
# A path that ends a sentence or names a line, such as /code/p/a.py:3, loses that ending.
|
||||
named = [LINE_OR_STOP.sub("", path) for path in PATH.findall(prompt)]
|
||||
gone = set()
|
||||
for path in map(pathlib.PurePath, named):
|
||||
# The path's directories from the top down, without the filesystem root; the first one gone is what a removed worktree took with it.
|
||||
down_the_path = [*reversed(path.parents), path][1:]
|
||||
first_gone = next((prefix for prefix in down_the_path if not exists(str(prefix))), None)
|
||||
if first_gone and (first_gone.parent == checkout.parent or checkout in first_gone.parents):
|
||||
gone.add(str(first_gone))
|
||||
if len(gone) == 1:
|
||||
return gone.pop()
|
||||
return root if not gone and root in named else None
|
||||
|
||||
|
||||
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)
|
||||
|
||||
|
||||
def sample(rounds: list[Round], latest: int) -> list[Round]:
|
||||
"""The latest rounds, in the order they ran."""
|
||||
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:
|
||||
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"The reference reviewer, {reference}, found {sum(len(found) for found in replay.on_reference)} of them.",
|
||||
]
|
||||
for tried in replay.tried:
|
||||
lines += [f"{tried.rung} missed {len(tried.missed)}{':' if tried.missed else '.'}", *(f" {miss.case.root} {miss.case.at}: {miss.case.findings[miss.item].splitlines()[0]}" for miss in tried.missed)]
|
||||
if not replay.tried:
|
||||
lines.append("No rung tried: the reference reviewer found no finding to hold one to.")
|
||||
else:
|
||||
lowest = replay.lowest or "none below the project's rung"
|
||||
lines.append(f"Lowest rung that finds every finding the reference reviewer finds: {lowest}")
|
||||
return "\n".join(lines)
|
||||
@@ -0,0 +1,321 @@
|
||||
import contextlib
|
||||
import dataclasses
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
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 loop_claude.effects import Effects, system_effects
|
||||
from failure import Failure
|
||||
from stability_replay import main
|
||||
from rung_replay.search import Miss, Replay, Tried
|
||||
from model_routing.ladder import Rung
|
||||
|
||||
TOOL = pathlib.Path(__file__).resolve().parents[1] / "stability-replay"
|
||||
REFERENCE = Rung("claude-opus-5-5", "medium")
|
||||
MIDDLE = Rung("claude-sonnet-5-5", "high")
|
||||
CHEAP = Rung("claude-haiku-5-5", "max")
|
||||
|
||||
|
||||
def entry(kind, text, **fields):
|
||||
return {"type": kind, "message": {"content": [{"type": "text", "text": 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))
|
||||
|
||||
|
||||
class RecordedFindings(unittest.TestCase):
|
||||
def test_takes_each_red_and_yellow_finding_with_the_lines_up_to_the_next_blank_line_or_finding(self):
|
||||
report_text = "BLOCK\n\n1 🔴, 2 🟡 in all.\n\n1. 🔴 **Loop** at a.py:3\nnever ends.\n- 🟡 b.py:1 slow\n| 🟡 | c.py | odd |\n\n🟢 nit\n### 🔴 Heading\n**🟡 Bold**"
|
||||
self.assertEqual(recorded_findings(report_text), ["1. 🔴 **Loop** at a.py:3\nnever ends.", "- 🟡 b.py:1 slow", "| 🟡 | c.py | odd |", "### 🔴 Heading", "**🟡 Bold**"])
|
||||
|
||||
def test_skips_a_count_or_verdict_line_that_names_the_marks(self):
|
||||
self.assertEqual(recorded_findings("APPROVE\n\nNo 🔴 or 🟡 findings.\n0 🔴, 0 🟡"), [])
|
||||
|
||||
|
||||
class RoundFrom(unittest.TestCase):
|
||||
def test_reads_the_prompt_the_last_report_and_when_the_reviewer_started(self):
|
||||
entries = [
|
||||
entry("user", "Review branch x in /code/p-x.", timestamp="2026-10-14T10:00:00.500Z", cwd="/code/p-x", gitBranch="x"),
|
||||
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)
|
||||
|
||||
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.")
|
||||
|
||||
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")]))
|
||||
|
||||
|
||||
class ReviewedPath(unittest.TestCase):
|
||||
def test_names_the_worktree_the_prompt_names_that_is_gone(self):
|
||||
exists = {"/code", "/code/p", "/code/p/worktrees", "/tmp"}.__contains__
|
||||
self.assertEqual(reviewed_path("Review /code/p-x/src/a.py:3-5; the diff is at /tmp/s/x.diff; /code/p is older.", "/code/p", exists), "/code/p-x")
|
||||
self.assertEqual(reviewed_path("Review `/code/p/worktrees/x`.", "/code/p", exists), "/code/p/worktrees/x")
|
||||
|
||||
def test_names_the_checkout_when_the_prompt_names_no_gone_worktree_and_none_when_it_names_neither_or_two(self):
|
||||
exists = {"/code", "/code/p"}.__contains__
|
||||
self.assertEqual(reviewed_path("Review /code/p.", "/code/p", exists), "/code/p")
|
||||
self.assertIsNone(reviewed_path("Review the branch.", "/code/p", exists))
|
||||
self.assertIsNone(reviewed_path("Review /code/p-x and /code/p-43.", "/code/p", exists))
|
||||
|
||||
|
||||
class AuthoredBy(unittest.TestCase):
|
||||
def test_takes_the_newest_commit_authored_by_then(self):
|
||||
log = [("c3", 30), ("c2", 20), ("c1", 10)]
|
||||
self.assertEqual(authored_by(log, 25), "c2")
|
||||
self.assertEqual(authored_by(log, 30), "c3")
|
||||
self.assertIsNone(authored_by(log, 5))
|
||||
|
||||
|
||||
class Sample(unittest.TestCase):
|
||||
def test_keeps_the_latest_rounds_in_the_order_they_ran(self):
|
||||
rounds = [a_round(2), a_round(1), a_round(3)]
|
||||
self.assertEqual(sample(rounds, 2), [rounds[0], rounds[2]])
|
||||
|
||||
|
||||
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()
|
||||
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.",
|
||||
"claude-sonnet-5-5 at high effort missed 0.",
|
||||
"claude-haiku-5-5 at max effort missed 1:",
|
||||
" /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.")
|
||||
|
||||
|
||||
class Match(unittest.TestCase):
|
||||
def run_match(self, stdout):
|
||||
self.asked = []
|
||||
|
||||
def claude(args, cwd, prompt):
|
||||
self.asked.append((args, cwd, prompt))
|
||||
return subprocess.CompletedProcess(args, 0, stdout, "")
|
||||
|
||||
return main.match(("🔴 a", "🟡 b"), "the other report", "/code/p", REFERENCE, dataclasses.replace(system_effects(), claude=claude))
|
||||
|
||||
def test_asks_for_the_numbered_findings_the_other_report_raises_as_json_with_no_tools(self):
|
||||
self.run_match("{}")
|
||||
[(args, cwd, prompt)] = self.asked
|
||||
self.assertEqual(cwd, "/code/p")
|
||||
self.assertIn("1. 🔴 a\n\n2. 🟡 b\n\nThe other report:\nthe other report", prompt)
|
||||
self.assertEqual(json.loads(args[args.index("--json-schema") + 1]), main.MATCH_SCHEMA)
|
||||
self.assertEqual(args[args.index("--tools") + 1], "")
|
||||
self.assertEqual(args[args.index("--model"):args.index("--model") + 4], REFERENCE.flags())
|
||||
|
||||
def test_takes_the_numbers_in_range_and_fails_on_a_reply_of_another_shape(self):
|
||||
self.assertEqual(self.run_match(json.dumps({"type": "result", "structured_output": {"found": [2, 0, 3, 1]}})), {0, 1})
|
||||
for output in ({"found": ["1"]}, {"found": 1}, [1]):
|
||||
with self.subTest(output):
|
||||
self.assertIsInstance(self.run_match(json.dumps({"type": "result", "structured_output": output})), Failure)
|
||||
|
||||
|
||||
class Git(unittest.TestCase):
|
||||
def test_says_why_git_cannot_start_in_a_directory_that_is_gone(self):
|
||||
def gone(args, cwd):
|
||||
raise FileNotFoundError(2, "No such file or directory")
|
||||
|
||||
ran = main.git(dataclasses.replace(system_effects(), git=gone), "/code/gone", "log")
|
||||
self.assertEqual(ran, Failure("git log could not start in /code/gone: No such file or directory"))
|
||||
|
||||
|
||||
def unused(*_):
|
||||
raise AssertionError("not called")
|
||||
|
||||
|
||||
def run_git(cwd, *args, at=None):
|
||||
"""at, when given, is the commit's author and committer time, so git log lists the commits in a fixed order."""
|
||||
env = {**os.environ, "GIT_AUTHOR_DATE": at, "GIT_COMMITTER_DATE": at} if at else None
|
||||
subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", *args], cwd=cwd, check=True, capture_output=True, env=env)
|
||||
|
||||
|
||||
class Main(unittest.TestCase):
|
||||
"""The tool on a temporary home: a chunk that began after the checkout's first commit, and whose stability reviewer reviewed branch x at its second, from a worktree since removed; a prose reviewer's files sort before the stability reviewer's."""
|
||||
|
||||
def setUp(self):
|
||||
self.home = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory()))
|
||||
self.archive = self.home / ".claude" / "loop-claude-transcripts"
|
||||
(self.home / ".claude").mkdir()
|
||||
(self.home / ".claude" / "loop-claude-models.json").write_text(json.dumps({"proj": "claude-opus-5-5", "other": "claude-sonnet-5-5"}))
|
||||
origin, self.checkout = self.home / "origin.git", self.home / "code" / "proj"
|
||||
run_git(self.home, "init", "-q", "--bare", "-b", "main", str(origin))
|
||||
run_git(self.home, "clone", "-q", str(origin), str(self.checkout))
|
||||
for n, stamp in enumerate(("2026-10-14T09:00:00Z", "2026-10-14T09:30:00Z", "2026-10-14T11:00:00Z")):
|
||||
(self.checkout / "a.txt").write_text(f"{n}\n")
|
||||
run_git(self.checkout, "add", "a.txt")
|
||||
run_git(self.checkout, "commit", "-qm", f"c{n}", at=stamp)
|
||||
run_git(self.checkout, "push", "-q", "origin", "main")
|
||||
run_git(self.checkout, "remote", "set-head", "origin", "main")
|
||||
for key in ("proj", "other"):
|
||||
self.write_chunk(key, "c1", "2026-10-14T10:00:00Z")
|
||||
self.reviews = []
|
||||
|
||||
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."""
|
||||
subagents = self.archive / key / chunk / "session" / "s" / "subagents"
|
||||
subagents.mkdir(parents=True, exist_ok=True)
|
||||
(subagents.parents[2] / "t0.jsonl").write_text(json.dumps({"type": "summary"}) + "\n" + json.dumps(entry("user", "Do the next chunk.", timestamp=began)) + "\n")
|
||||
(subagents / "agent-a.meta.json").write_text(json.dumps({"agentType": "prose-reviewer"}))
|
||||
(subagents / "agent-b.meta.json").write_text(json.dumps({"agentType": "stability-reviewer"}))
|
||||
gone = self.home / "code" / "proj-x"
|
||||
lines = [entry("user", f"Review branch x in {gone}.", timestamp=at, cwd=str(gone), gitBranch="x"), entry("assistant", "BLOCK\n\n🔴 a.txt:1 wrong\n\n🟡 slow")]
|
||||
for name in ("agent-a.jsonl", "agent-b.jsonl"):
|
||||
(subagents / name).write_text("".join(json.dumps(line) + "\n" for line in lines))
|
||||
|
||||
def rewrite_round(self, change):
|
||||
path = self.archive / "proj" / "c1" / "session" / "s" / "subagents" / "agent-b.jsonl"
|
||||
lines = [json.loads(line) for line in path.read_text().splitlines()]
|
||||
change(lines[0])
|
||||
path.write_text("".join(json.dumps(line) + "\n" for line in lines))
|
||||
|
||||
def set_branch(self, branch):
|
||||
self.rewrite_round(lambda first: first.update(gitBranch=branch))
|
||||
|
||||
def set_prompt(self, prompt):
|
||||
self.rewrite_round(lambda first: first["message"]["content"][0].update(text=prompt))
|
||||
|
||||
def run_main(self, argv, found, review=lambda rung: {"type": "result", "result": f"review on {rung.model} {rung.effort}"}):
|
||||
"""found(rung) is the indexes of the recorded findings the reviewer on rung finds; review(rung), that reviewer's reply."""
|
||||
|
||||
def claude(args, cwd, prompt):
|
||||
rung = Rung(args[args.index("--model") + 1], args[args.index("--effort") + 1])
|
||||
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))
|
||||
result = review(rung)
|
||||
else:
|
||||
reviewed = Rung(*re.search(r"review on (\S+) (\S+)", prompt).groups())
|
||||
result = found(reviewed)
|
||||
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)
|
||||
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]})
|
||||
self.assertEqual(code, 0, err)
|
||||
self.assertEqual([rung for rung, *_ in self.reviews], [REFERENCE, MIDDLE, CHEAP])
|
||||
_, reviewed, branch, base, prompt, cwd = self.reviews[0]
|
||||
# The default branch stands where it stood when the chunk began, so the prompt's diff against it shows the branch's change.
|
||||
self.assertEqual((reviewed, branch, base), ("1\n", "x\n", "0\n"))
|
||||
self.assertEqual(prompt, f"Review branch x in {cwd}.")
|
||||
self.assertFalse(pathlib.Path(cwd).exists())
|
||||
self.assertIn("The reference reviewer, claude-opus-5-5 at medium effort, found 2 of them.", out)
|
||||
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_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]})
|
||||
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.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):
|
||||
# Branch side's commit was authored before the chunk began, but the default branch held it only once merged, after.
|
||||
run_git(self.checkout, "reset", "-q", "--hard", "HEAD~2")
|
||||
run_git(self.checkout, "checkout", "-qb", "side")
|
||||
(self.checkout / "a.txt").write_text("s\n")
|
||||
run_git(self.checkout, "commit", "-qam", "s", at="2026-10-14T09:10:00Z")
|
||||
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.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"})
|
||||
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)
|
||||
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"])
|
||||
|
||||
def test_skips_a_chunk_with_no_transcript_copy(self):
|
||||
(self.archive / "proj" / "c1" / "t0.jsonl").unlink()
|
||||
self.assert_no_round()
|
||||
|
||||
def test_skips_a_chunk_whose_transcript_copy_has_no_timestamp(self):
|
||||
(self.archive / "proj" / "c1" / "t0.jsonl").write_text(json.dumps({"type": "summary"}) + "\n")
|
||||
self.assert_no_round()
|
||||
|
||||
def assert_left_out(self, reason, root=None):
|
||||
code, _, err = self.run_main(["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)
|
||||
|
||||
def test_leaves_out_a_round_whose_prompt_names_no_worktree(self):
|
||||
self.set_prompt("Review the branch.")
|
||||
self.assert_left_out("the prompt names neither one removed worktree nor the checkout")
|
||||
|
||||
def test_leaves_out_a_round_whose_checkout_names_no_default_branch(self):
|
||||
run_git(self.checkout, "remote", "set-head", "origin", "-d")
|
||||
self.assert_left_out("git symbolic-ref --short refs/remotes/origin/HEAD: ")
|
||||
|
||||
def test_leaves_out_a_round_whose_checkout_is_gone(self):
|
||||
shutil.rmtree(self.checkout)
|
||||
# With no folder under ~/code, the key names /proj.
|
||||
self.assert_left_out("the project has no checkout", "/proj")
|
||||
|
||||
def test_leaves_out_a_round_whose_chunk_began_before_the_checkouts_first_commit(self):
|
||||
self.write_chunk("proj", "c1", "2026-10-14T10:00:00Z", began="2026-10-14T08:00:00Z")
|
||||
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"})
|
||||
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)
|
||||
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>"))
|
||||
|
||||
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)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
+279
-42
@@ -1,6 +1,7 @@
|
||||
import contextlib
|
||||
import io
|
||||
import pathlib
|
||||
import re
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
@@ -10,8 +11,9 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
|
||||
from failure import Failure
|
||||
import rank_todo
|
||||
from repo_checks.test_python_floor import ROOT
|
||||
import todo_table
|
||||
|
||||
README = "# P\n\n## Goals\n\n1. Fast.\n2. Correct.\n 1. Tested.\n\n## Audience\n\nMe.\n"
|
||||
README = "# P\n\n## Goals\n\n1. **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"
|
||||
|
||||
@@ -19,6 +21,41 @@ TODO = """# todo
|
||||
|
||||
## Scoring
|
||||
|
||||
`Score = 100 * V / 2**S`
|
||||
|
||||
`Bar = 2`
|
||||
|
||||
`Next ID = 6`
|
||||
|
||||
## Items
|
||||
|
||||
| ID | Release | Blocked by | Exempt | Item | R | S | C | Moves | Score |
|
||||
|---|---|---|---|---|---|---|---|---|---|
|
||||
| 1 | 0.2.0 | | | **Ship the later thing.** | 1 | 1 | 3 | 1 by 9 | 0 |
|
||||
| 2 | 0.1.0 | | | **Tighten the tests.** | 2 | 4 | 3 | 2.1 by 1 | 0 |
|
||||
| 3 | 0.1.0 | | | **Make it fast, `a \\| b`.** | 3 | 8 | 3 | 2.1 by 8, 1 by 6 | 0 |
|
||||
| 4 | 0.1.0 | | security | **Rotate the leaked key.** | 9 | 2 | 3 | 2.1 by 1 | 0 |
|
||||
| 5 | 0.1.0 | | decision | **Move the writes out.** | 5 | 5 | 3 | 2.1 by 1 | 0 |
|
||||
|
||||
## Details
|
||||
|
||||
### 1. stale heading
|
||||
|
||||
Later detail.
|
||||
|
||||
### 3. Make it fast.
|
||||
|
||||
Fast detail.
|
||||
|
||||
## Notes
|
||||
|
||||
Kept as written.
|
||||
"""
|
||||
|
||||
OLD_SHAPE = """# todo
|
||||
|
||||
## Scoring
|
||||
|
||||
`Score = -R - S/4 + 2*A + 2*G*W`
|
||||
|
||||
`Bar = 9`
|
||||
@@ -33,13 +70,13 @@ TODO = """# todo
|
||||
|
||||
## Items
|
||||
|
||||
| ID | Release | Exempt | Item | R | S | C | A | G | Goals | Score |
|
||||
|---|---|---|---|---|---|---|---|---|---|---|
|
||||
| 1 | 0.2.0 | | **Ship the later thing.** | 1 | 1 | 3 | 9 | 9 | 1 | 0 |
|
||||
| 2 | 0.1.0 | | **Tighten the tests.** | 2 | 4 | 3 | 5 | 5 | 2.1 | 0 |
|
||||
| 3 | 0.1.0 | | **Make it fast, `a \\| b`.** | 3 | 8 | 3 | 6 | 8 | 2.1, 1 | 0 |
|
||||
| 4 | 0.1.0 | security | **Rotate the leaked key.** | 9 | 2 | 3 | 1 | 1 | 2.1 | 0 |
|
||||
| 5 | 0.1.0 | decision | **Move the writes out.** | 5 | 5 | 3 | 4 | 5 | 2.1 | 0 |
|
||||
| ID | Release | Blocked by | Exempt | Item | R | S | C | A | G | Goals | Score |
|
||||
|---|---|---|---|---|---|---|---|---|---|---|---|
|
||||
| 1 | 0.2.0 | | | **Ship the later thing.** | 1 | 1 | 3 | 9 | 9 | 1 | 0 |
|
||||
| 2 | 0.1.0 | | | **Tighten the tests.** | 2 | 4 | 3 | 5 | 5 | 2.1 | 0 |
|
||||
| 3 | 0.1.0 | | | **Make it fast, `a \\| b`.** | 3 | 8 | 3 | 6 | 8 | 2.1, 1 | 0 |
|
||||
| 4 | 0.1.0 | | security | **Rotate the leaked key.** | 9 | 2 | 3 | 1 | 1 | 2.1 | 0 |
|
||||
| 5 | 0.1.0 | | decision | **Move the writes out.** | 5 | 5 | 3 | 4 | 5 | 2.1 | 0 |
|
||||
|
||||
## Details
|
||||
|
||||
@@ -63,67 +100,257 @@ class Rank(unittest.TestCase):
|
||||
|
||||
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.** | 9 | 2 | 3 | 1 | 1 | 2.1 | -6.8 |
|
||||
| 3 | 0.1.0 | | **Make it fast, `a \\| b`.** | 3 | 8 | 3 | 6 | 8 | 2.1, 1 | 23.0 |
|
||||
| 2 | 0.1.0 | | **Tighten the tests.** | 2 | 4 | 3 | 5 | 5 | 2.1 | 10.3 |
|
||||
| 5 | 0.1.0 | decision | **Move the writes out.** | 5 | 5 | 3 | 4 | 5 | 2.1 | 5.1 |
|
||||
| 1 | 0.2.0 | | **Ship the later thing.** | 1 | 1 | 3 | 9 | 9 | 1 | 34.8 |
|
||||
self.assertIn("""| 4 | 0.1.0 | | security | **Rotate the leaked key.** | 9 | 2 | 3 | 2.1 by 1 | 8.3 |
|
||||
| 3 | 0.1.0 | | | **Make it fast, `a \\| b`.** | 3 | 8 | 3 | 2.1 by 8, 1 by 6 | 2.6 |
|
||||
| 2 | 0.1.0 | | | **Tighten the tests.** | 2 | 4 | 3 | 2.1 by 1 | 2.1 |
|
||||
| 5 | 0.1.0 | | decision | **Move the writes out.** | 5 | 5 | 3 | 2.1 by 1 | 1.0 |
|
||||
| 1 | 0.2.0 | | | **Ship the later thing.** | 1 | 1 | 3 | 1 by 9 | 300.0 |
|
||||
""", 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, [])
|
||||
self.assertEqual(ranked.notes, [])
|
||||
self.assertEqual(self.ranked(ranked.text), ranked)
|
||||
|
||||
def test_weighs_each_achieve_goal_by_its_sum_reciprocal_rank(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})
|
||||
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`.** | 3 | 8 | 3 | 1.2 by 2, 2 by 3 | 0.4 |", ranked.text)
|
||||
|
||||
def test_scores_an_item_that_moves_no_goal_zero(self):
|
||||
ranked = self.ranked(TODO.replace("| 2 | 4 | 3 | 2.1 by 1 |", "| 2 | 4 | 3 | |"))
|
||||
self.assertIn("| **Tighten the tests.** | 2 | 4 | 3 | | 0.0 |", ranked.text)
|
||||
self.assertEqual(ranked.under_bar, ["item 2 scores 0.0, under the bar 2; delete it, or mark it with a reason the bar does not apply"])
|
||||
|
||||
def test_holds_each_item_a_decision_cites_and_says_how_to_settle_a_finished_one(self):
|
||||
self.assertIsInstance(self.ranked(decisions=DECISIONS + "Until `todo.md` item 4 lands.\n"), rank_todo.Ranked)
|
||||
gone = self.ranked(TODO.replace("| 5 | 0.1.0 | decision | **Move the writes out.** | 5 | 5 | 3 | 4 | 5 | 2.1 | 0 |\n", ""))
|
||||
gone = self.ranked(TODO.replace("| 5 | 0.1.0 | | decision | **Move the writes out.** | 5 | 5 | 3 | 2.1 by 1 | 0 |\n", ""))
|
||||
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 = 9`", "`Bar = 11`"))
|
||||
self.assertEqual(ranked.under_bar, ["item 2 scores 10.3, under the bar 11; delete it and any item that needs it, 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, [])
|
||||
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"])
|
||||
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, [])
|
||||
|
||||
def test_reads_goals_and_sub_goals_in_reading_order(self):
|
||||
self.assertEqual(rank_todo.readme_goals(README), ["1", "2", "2.1"])
|
||||
self.assertEqual(rank_todo.readme_goals(README.replace(" 1.", "\t1.")), ["1", "2", "2.1"])
|
||||
self.assertEqual(rank_todo.readme_goals(README.replace("2. Correct.", "```\n## Goals\n```\n2. Correct.")), ["1", "2", "2.1"])
|
||||
self.assertIsInstance(rank_todo.readme_goals(README.replace("2. Correct.", "1. Correct.")), Failure)
|
||||
self.assertEqual(rank_todo.readme_goals(README), [("1", "Achieve"), ("2", "Maintain"), ("2.1", "Achieve")])
|
||||
self.assertEqual(rank_todo.readme_goals(README.replace(" 1.", "\t1.")), [("1", "Achieve"), ("2", "Maintain"), ("2.1", "Achieve")])
|
||||
self.assertEqual(rank_todo.readme_goals(README.replace("2. **Maintain:** Correct.", "```\n## Goals\n```\n2. Correct.")), [("1", "Achieve"), ("2", None), ("2.1", "Achieve")])
|
||||
self.assertEqual(rank_todo.readme_goals(README.replace("2. **Maintain:**", "1. **Maintain:**")), Failure("README.md's ## Goals numbers 1, 1, 1.1; number each goal by its position"))
|
||||
self.assertEqual(rank_todo.readme_goals("## Goals\n\n1. **Achieve:** A.\n 1. **Achieve:** B.\n\t2. **Achieve:** C.\n"), [("1", "Achieve"), ("1.1", "Achieve"), ("1.2", "Achieve")])
|
||||
|
||||
def test_prints_the_positional_weights_when_they_stop_listing_the_readmes_goals(self):
|
||||
failure = self.ranked(readme=README.replace(" 1. Tested.", " 1. Tested.\n3. Small."))
|
||||
self.assertIn("| 1 | 1.00 |\n| 2 | 0.75 |\n| 2.1 | 0.50 |\n| 3 | 0.25 |", failure.reason)
|
||||
def test_refuses_a_goal_it_cannot_weigh(self):
|
||||
cases = {
|
||||
(TODO.replace("2.1 by 8, 1 by 6", "1 by 8, 2 by 6"), README): "item 3 cites goal 2, a maintain goal, which only a defect that restores it may name; name the achieve goals the item moves",
|
||||
(TODO.replace("2.1 by 8, 1 by 6", "2.1 by 8, 3 by 6"), README): "item 3 cites goal 3, which README.md's ## Goals does not number",
|
||||
(TODO.replace("2.1 by 8, 1 by 6", "2.1 by 8, 2.1 by 6"), README): "item 3 cites goal 2.1 twice; name each goal once",
|
||||
(TODO, README.replace("**Maintain:** Correct", "Correct")): "README.md's goal 2 is marked neither **Maintain:** nor **Achieve:**; mark it, as ~/.claude/rules/goals-and-audience.md says, so rank_todo.py knows which goals score",
|
||||
}
|
||||
for (todo, readme), reason in cases.items():
|
||||
with self.subTest(reason=reason):
|
||||
self.assertEqual(self.ranked(todo, readme), Failure(reason))
|
||||
|
||||
def test_ranks_questions_first_then_security_whatever_they_score_and_a_defect_by_its_score(self):
|
||||
todo = TODO.replace("| 2 | 0.1.0 | | |", "| 2 | 0.1.0 | | defect |").replace("| 9 | 2 | 3 | 2.1 by 1 |", "| 9 | 8 | 3 | 2.1 by 1 |").replace("| 5 | 0.1.0 | | decision |", "| 5 | 0.1.0 | | question |")
|
||||
rows = [line.split(" | ")[0] for line in self.ranked(todo, decisions="").text.splitlines() if line.startswith("| ") and " | 0." in line]
|
||||
self.assertEqual(rows, ["| 5", "| 4", "| 3", "| 2", "| 1"])
|
||||
|
||||
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.** | 2 | 4 | 3 | 2.1 by 1 |", "| 2 | 0.1.0 | | defect | **Tighten the tests.** | 2 | 4 | 3 | 2 by 3 |"))
|
||||
self.assertIn("| **Tighten the tests.** | 2 | 4 | 3 | 2 by 3 | 12.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"
|
||||
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)
|
||||
|
||||
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"])
|
||||
|
||||
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 | 3 | 1 by 10 | 6.7 |", 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"))
|
||||
|
||||
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", "R ** 2", "R +", "R / (S - 2)", "R\x00", "1" * 400, " + ".join(["R"] * 300), "-" * 100000 + "R"):
|
||||
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"):
|
||||
with self.subTest(formula=formula):
|
||||
self.assertIsInstance(self.ranked(TODO.replace("-R - S/4 + 2*A + 2*G*W", formula)), Failure)
|
||||
|
||||
def test_asks_for_a_c_column_in_a_table_without_one(self):
|
||||
legacy = TODO.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(self.ranked(legacy, decisions="").reason, "todo.md's items table has no C column; add one after S, and score each item's C from 1 to 10 per rank_todo.py --help")
|
||||
self.assertIsInstance(self.ranked(TODO.replace("100 * V / 2**S", formula)), Failure)
|
||||
self.assertIn("| 1 by 9 | 2.0 |", self.ranked(TODO.replace("100 * V / 2**S", "R + S / S")).text)
|
||||
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, 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"))
|
||||
|
||||
def test_refuses_a_file_off_the_format(self):
|
||||
row = "| 2 | 0.1.0 | | **Tighten the tests.** | 2 | 4 | 3 | 5 | 5 | 2.1 | 0 |"
|
||||
row = "| 2 | 0.1.0 | | | **Tighten the tests.** | 2 | 4 | 3 | 2.1 by 1 | 0 |"
|
||||
broken = {
|
||||
row: row.replace("0.1.0", "0.1"),
|
||||
"| 2 | 4 | 3 | 5 | 5 |": "| 2 | 4 | 11 | 5 | 5 |",
|
||||
row + "\n": row.replace("5 | 5", "5 | ²") + "\n",
|
||||
"| 2.1 | 0 |\n\n## Details": "| 2.1 | 0 |\n\n| 9 | 0.1.0 | | **Stray.** | 1 | 1 | 3 | 1 | 1 | 1 | 0 |\n\n## Details",
|
||||
"| 4 | 0.1.0 | security |": "| 4 | 0.1.0 | later |",
|
||||
"| 5 | 0.1.0 | decision |": "| 5 | 0.1.0 | |",
|
||||
"| 2 | 4 | 3 | 2.1 by 1 |": "| 2 | 4 | 11 | 2.1 by 1 |",
|
||||
"Tighten the tests.** | 2 | 4 | 3 | 2.1 by 1": "Tighten the tests.** | 2 | 4 | 3 | 2.1 by 11",
|
||||
"Move the writes out.** | 5 | 5 | 3 | 2.1 by 1": "Move the writes out.** | 5 | 5 | 3 | 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 ",
|
||||
"| 3 | 8 | 3 | 2.1 by 8, 1 by 6 |": "| 3 | 8 | 3 | 2.1, 1 |",
|
||||
row + "\n": row.replace("4 | 3", "4 | ²") + "\n",
|
||||
"| 2.1 by 1 | 0 |\n\n## Details": "| 2.1 by 1 | 0 |\n\n| 9 | 0.1.0 | | | **Stray.** | 1 | 1 | 3 | 1 by 1 | 0 |\n\n## Details",
|
||||
"| 4 | 0.1.0 | | security |": "| 4 | 0.1.0 | | later |",
|
||||
"| 5 | 0.1.0 | | decision |": "| 5 | 0.1.0 | | |",
|
||||
"`Next ID = 6`": "`Next ID = 5`",
|
||||
"`Next ID = 6`\n": "`Next ID = 6.5`\n",
|
||||
"| 4 | 0.1.0 | security | **Rotate": "| 4 | 0.1.0 | decision | **Rotate",
|
||||
"| 4 | 0.1.0 | | security | **Rotate": "| 4 | 0.1.0 | | decision | **Rotate",
|
||||
"Fast detail.": "```\n## Goals\n```",
|
||||
"### 3. Make it fast.": "### 7. Make it fast.",
|
||||
"`Bar = 9`": "`Bar = nan`",
|
||||
"## Items\n\n| ID | Release | Exempt |": "## Plan\n\n| ID | Release |",
|
||||
"`Bar = 2`": "`Bar = nan`",
|
||||
"## Items\n\n| ID | Release | Blocked by |": "## Plan\n\n| ID | Release |",
|
||||
}
|
||||
for old, new in broken.items():
|
||||
with self.subTest(new=new):
|
||||
self.assertIn(old, TODO)
|
||||
self.assertIsInstance(self.ranked(TODO.replace(old, new)), Failure)
|
||||
|
||||
|
||||
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)
|
||||
|
||||
def test_scores_by_the_stated_weights_and_says_to_reshape(self):
|
||||
ranked = self.ranked()
|
||||
self.assertIn("""| 4 | 0.1.0 | | security | **Rotate the leaked key.** | 9 | 2 | 3 | 1 | 1 | 2.1 | -6.8 |
|
||||
| 3 | 0.1.0 | | | **Make it fast, `a \\| b`.** | 3 | 8 | 3 | 6 | 8 | 2.1, 1 | 23.0 |
|
||||
| 2 | 0.1.0 | | | **Tighten the tests.** | 2 | 4 | 3 | 5 | 5 | 2.1 | 10.3 |
|
||||
| 5 | 0.1.0 | | decision | **Move the writes out.** | 5 | 5 | 3 | 4 | 5 | 2.1 | 5.1 |
|
||||
| 1 | 0.2.0 | | | **Ship the later thing.** | 1 | 1 | 3 | 9 | 9 | 1 | 34.8 |
|
||||
""", ranked.text)
|
||||
self.assertEqual(ranked.notes, [rank_todo.RESHAPE])
|
||||
self.assertEqual(self.ranked(ranked.text), ranked)
|
||||
unmarked = "# P\n\n## Goals\n\n1. Fast.\n2. Correct.\n 1. Tested.\n"
|
||||
self.assertEqual(self.ranked(readme=unmarked), ranked)
|
||||
|
||||
def test_prints_the_positional_weights_when_they_stop_listing_the_readmes_goals(self):
|
||||
failure = self.ranked(readme=README.replace(" 1. **Achieve:** Tested.", " 1. **Achieve:** Tested.\n3. Small."))
|
||||
self.assertIn("| 1 | 1.00 |\n| 2 | 0.75 |\n| 2.1 | 0.50 |\n| 3 | 0.25 |", failure.reason)
|
||||
|
||||
def test_refuses_an_item_citing_a_goal_the_weights_do_not_list(self):
|
||||
self.assertEqual(self.ranked(OLD_SHAPE.replace("| 2.1, 1 | 0 |", "| 2.1, 9 | 0 |")), Failure("item 3 cites goal 9, which the goal weights do not list"))
|
||||
|
||||
def test_refuses_a_formula_over_v(self):
|
||||
self.assertEqual(self.ranked(OLD_SHAPE.replace("-R - S/4 + 2*A + 2*G*W", "V")), Failure("the formula 'V' may hold only numbers, A, G, R, S, W, + - * / ** and parentheses"))
|
||||
|
||||
def test_asks_for_a_c_column_in_a_table_without_one(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, "").reason, "todo.md's items table has no C column; add one after S, and score each item's C from 1 to 10 per rank_todo.py --help")
|
||||
|
||||
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")
|
||||
self.assertEqual(self.ranked(both), Failure("todo.md's items table has A, G and Goals, columns of the old shape that Moves replaced; drop them"))
|
||||
one = TODO.replace("| Moves | Score |\n|---|", "| Moves | G | Score |\n|---|---|").replace(" | 0 |\n", " | 1 | 0 |\n")
|
||||
self.assertEqual(self.ranked(one), Failure("todo.md's items table has G, a column of the old shape that Moves replaced; drop it"))
|
||||
|
||||
def test_names_the_goals_column_a_table_misspells_by_its_shape(self):
|
||||
misspelt = TODO.replace("| C | Moves |", "| C | 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(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)
|
||||
|
||||
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.** | 9 | 2 | 3 | 2.1 by 1 | 8.3 |
|
||||
| 2 | 0.1.0 | | | **Tighten the tests.** | 2 | 4 | 3 | 2.1 by 1 | 2.1 |
|
||||
| 5 | 0.1.0 | | decision | **Move the writes out.** | 5 | 5 | 3 | 2.1 by 1 | 1.0 |
|
||||
| 3 | 0.1.0 | 2, 5 | | **Make it fast, `a \\| b`.** | 3 | 8 | 3 | 2.1 by 8, 1 by 6 | 2.6 |
|
||||
| 1 | 0.2.0 | | | **Ship the later thing.** | 1 | 1 | 3 | 1 by 9 | 300.0 |
|
||||
""", ranked.text)
|
||||
self.assertEqual(self.ranked(ranked.text), ranked)
|
||||
|
||||
def test_ranks_an_items_blockers_in_score_order(self):
|
||||
rows = [line.split(" | ")[0] for line in self.ranked(TODO.replace("| 4 | 0.1.0 | |", "| 4 | 0.1.0 | 2, 3 |")).text.splitlines() if re.match(r"\| \d \| 0\.\d\.0 \|", line)]
|
||||
self.assertEqual(rows, ["| 3", "| 2", "| 4", "| 5", "| 1"])
|
||||
|
||||
def test_ranks_a_blocker_above_its_blockers_blocker_and_takes_one_in_an_earlier_release_as_it_is(self):
|
||||
chained = TODO.replace("| 3 | 0.1.0 | |", "| 3 | 0.1.0 | 5 |").replace("| 5 | 0.1.0 | |", "| 5 | 0.1.0 | 2 |").replace("| 1 | 0.2.0 | |", "| 1 | 0.2.0 | 3 |")
|
||||
rows = [line.split(" | ")[0] for line in self.ranked(chained).text.splitlines() if re.match(r"\| \d \| 0\.\d\.0 \|", line)]
|
||||
self.assertEqual(rows, ["| 4", "| 2", "| 5", "| 3", "| 1"])
|
||||
|
||||
def test_drops_a_blocker_the_table_no_longer_holds_as_finished(self):
|
||||
finished = TODO.replace("| 4 | 0.1.0 | | security | **Rotate the leaked key.** | 9 | 2 | 3 | 2.1 by 1 | 0 |\n", "").replace("| 2 | 0.1.0 | |", "| 2 | 0.1.0 | 4 |")
|
||||
ranked = self.ranked(finished)
|
||||
self.assertIn("| 2 | 0.1.0 | | | **Tighten the tests.**", ranked.text)
|
||||
self.assertEqual(ranked.notes, ["item 2: dropped 4 from its Blocked by; the table no longer holds it"])
|
||||
self.assertEqual(self.ranked(ranked.text).notes, [])
|
||||
|
||||
def test_refuses_a_blocker_in_a_later_release_a_loop_and_an_id_past_next_id(self):
|
||||
cases = {
|
||||
"| 3 | 0.1.0 | 1 |": "item 3, in release 0.1.0, is blocked by item 1, in later release 0.2.0; move item 1 to release 0.1.0 or earlier, or item 3 to release 0.2.0 or later",
|
||||
"| 3 | 0.1.0 | 3 |": "item 3 is blocked by itself; drop 3 from its Blocked by",
|
||||
"| 3 | 0.1.0 | 9 |": "item 3 is blocked by item 9, which is not under Next ID 6; name an item the table holds or held",
|
||||
"| 3 | 0.1.0 | 6 |": "item 3 is blocked by item 6, which is not under Next ID 6; name an item the table holds or held",
|
||||
}
|
||||
for cell, reason in cases.items():
|
||||
with self.subTest(cell=cell):
|
||||
self.assertEqual(self.ranked(TODO.replace("| 3 | 0.1.0 | |", cell)), Failure(reason))
|
||||
looped = TODO.replace("| 3 | 0.1.0 | |", "| 3 | 0.1.0 | 2 |").replace("| 2 | 0.1.0 | |", "| 2 | 0.1.0 | 5 |").replace("| 5 | 0.1.0 | |", "| 5 | 0.1.0 | 3 |")
|
||||
self.assertEqual(self.ranked(looped), Failure("items 2, 3 and 5 block each other in a loop; drop one of the blockers"))
|
||||
self.assertEqual(self.ranked(TODO.replace("| 3 | 0.1.0 | |", "| 3 | 0.1.0 | 2 and 5 |")), Failure("item 3's Blocked by '2 and 5' is not empty or IDs separated by \", \""))
|
||||
|
||||
def test_adds_the_column_to_a_table_without_it(self):
|
||||
without = TODO.replace("| Blocked by ", "").replace("|---|---|---|---|---|---|---|---|---|---|", "|---|---|---|---|---|---|---|---|---|")
|
||||
without = re.sub(r"\| (\d) \| (0\.[12]\.0) \| \| ", r"| \1 | \2 | ", without)
|
||||
self.assertEqual(self.ranked(without), self.ranked(TODO))
|
||||
unscored = TODO.replace(" | Score |", " |").replace("|---|---|---|---|---|---|---|---|---|---|", "|---|---|---|---|---|---|---|---|---|").replace(" | 0 |\n", " |\n")
|
||||
self.assertEqual(self.ranked(unscored), self.ranked(TODO))
|
||||
|
||||
def test_refuses_a_column_it_does_not_know_rather_than_drop_it_and_asks_for_c_beside_blocked_by(self):
|
||||
extra = TODO.replace("| Moves | Score |\n|---|", "| Moves | Score | Later |\n|---|---|").replace(" | 0 |\n", " | 0 | x |\n")
|
||||
self.assertEqual(self.ranked(extra), Failure("todo.md's items table has the column Later, which this rank_todo.py does not know; the columns it knows are ID, Release, Blocked by, Exempt, Item, R, S, C, Moves, Score. Rename it, or move this machine to the release that added it"))
|
||||
self.assertEqual([item.id for item in todo_table.items(extra)], [1, 2, 3, 4, 5])
|
||||
without_c = TODO.replace("| R | S | C |", "| R | S |").replace("|---|---|---|---|---|---|---|---|---|---|", "|---|---|---|---|---|---|---|---|---|")
|
||||
without_c = re.sub(r"(\*\* \| \d+ \| \d+) \| \d+ \|", r"\1 |", without_c)
|
||||
self.assertEqual(self.ranked(without_c).reason, "todo.md's items table has no C column; add one after S, and score each item's C from 1 to 10 per rank_todo.py --help")
|
||||
|
||||
def test_refuses_text_under_items_beside_the_table(self):
|
||||
last = TODO.split("\n## Details")[0] + "\n"
|
||||
self.assertIsInstance(self.ranked(last), rank_todo.Ranked)
|
||||
beside = Failure("## Items holds text beside its table; an order goes in the scores or the Blocked by column, and a note in the item's detail")
|
||||
for ordered in (TODO.replace("## Items\n\n", "## Items\n\nRelease 0.1.0 takes item 5 first.\n\n"), TODO.replace("## Items\n\n", "## Items\nTake item 5 first.\n\n"), TODO.replace("| 2.1 by 1 | 0 |\n\n## Details", "| 2.1 by 1 | 0 |\n\nTake item 5 first.\n\n## Details"), last + "\nTake item 5 first.\n"):
|
||||
with self.subTest(ordered=ordered[-60:]):
|
||||
self.assertEqual(self.ranked(ordered), beside)
|
||||
|
||||
def test_refuses_an_items_table_outside_items_a_second_one_and_a_repeated_column(self):
|
||||
self.assertEqual(self.ranked(TODO.replace("## Items\n", "## Plan\n")).reason, "todo.md is not in the scored-table format; rank_todo.py --help shows a valid one")
|
||||
outside = TODO.replace("## Items\n\n", "## Items\n\n## Rows\n\n")
|
||||
self.assertEqual(self.ranked(outside).reason, "the items table sits under ## Rows, not ## Items; move it under ## Items")
|
||||
table = TODO[TODO.index("| ID | Release |"):TODO.index("\n\n## Details")] + "\n"
|
||||
above = table + "\n" + TODO.replace(table, "")
|
||||
self.assertEqual(self.ranked(above).reason, "the items table sits under no ## heading; move it under ## Items")
|
||||
header = "| ID | Release | Blocked by | Exempt | Item | R | S | C | Moves | Score |\n|---|---|---|---|---|---|---|---|---|---|\n"
|
||||
self.assertEqual(todo_table.items(TODO + "\n" + header.replace("| Score |", "| Later |")), Failure("todo.md holds 2 tables whose header opens | ID | Release |; keep one items table"))
|
||||
repeated = TODO.replace("| Moves | Score |\n|---|", "| Moves | Score | Exempt |\n|---|---|").replace(" | 0 |\n", " | 0 | x |\n")
|
||||
self.assertEqual(todo_table.items(repeated), Failure("todo.md's items table names the column Exempt twice; keep one"))
|
||||
|
||||
def test_reads_an_empty_table_and_fails_on_a_header_with_no_divider(self):
|
||||
header = "| ID | Release | Blocked by | Exempt | Item | R | S | C | Moves | Score |"
|
||||
self.assertEqual(todo_table.items(f"## Items\n\n{header}\n|---|---|---|---|---|---|---|---|---|---|\n\n## Details\n"), [])
|
||||
self.assertEqual(todo_table.items(f"## Items\n\n{header}"), Failure(f"the table under {header} has no |---| divider line"))
|
||||
|
||||
|
||||
class Main(unittest.TestCase):
|
||||
def run_main(self, *argv):
|
||||
with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()) as said:
|
||||
@@ -146,12 +373,22 @@ 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_says_to_reshape_an_old_shape_table_but_passes_the_check(self):
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
todo = pathlib.Path(temp, "todo.md")
|
||||
todo.write_text(OLD_SHAPE)
|
||||
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)), (0, f"{todo}: {rank_todo.RESHAPE}\n"))
|
||||
self.assertEqual(self.run_main("--check", str(todo)), (0, ""))
|
||||
|
||||
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. Work.\n", "")
|
||||
ranked = rank_todo.rank(skeleton, "## Goals\n\n1. **Achieve:** Work.\n", "")
|
||||
self.assertIsInstance(ranked, rank_todo.Ranked)
|
||||
self.assertEqual(ranked.under_bar, [])
|
||||
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"))
|
||||
|
||||
|
||||
@@ -159,4 +396,4 @@ 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"))
|
||||
self.assertEqual(ranked, rank_todo.Ranked(text, []))
|
||||
self.assertEqual(ranked, rank_todo.Ranked(text, [], []))
|
||||
|
||||
+152
-30
@@ -1,15 +1,73 @@
|
||||
import dataclasses
|
||||
import re
|
||||
import typing
|
||||
|
||||
from failure import Failure
|
||||
|
||||
# Each of R, S, C, A and G runs from 1 to TOP_SCORE.
|
||||
# Each score a Shape names, and each goal's move, runs from 1 to TOP_SCORE.
|
||||
TOP_SCORE = 10
|
||||
EXEMPTIONS = ("", "decision", "defect", "principle", "question", "security")
|
||||
COLUMNS = ("ID", "Release", "Exempt", "Item", "R", "S", "C", "A", "G", "Goals", "Score")
|
||||
ITEMS_HEADER = "| " + " | ".join(COLUMNS) + " |"
|
||||
# Tables in git history from before C joined lack it; items() still parses them, though rank_todo refuses one in a checkout.
|
||||
WITHOUT_C = "| " + " | ".join(column for column in COLUMNS if column != "C") + " |"
|
||||
EXEMPTIONS = ("", "decision", "defect", "owner", "principle", "question", "security")
|
||||
# The column naming the items that block an item: each must be done before the item starts.
|
||||
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"
|
||||
# How the items table's header opens, which tells it from any other table in todo.md.
|
||||
HEADER_START = "| ID | 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], ...]
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Shape:
|
||||
"""A shape of the items table: its columns, and how its goals cell reads and writes."""
|
||||
# The score columns, in the order the table holds them.
|
||||
score_columns: tuple[str, ...]
|
||||
# The column naming the goals an item serves; read_goals reads it, given the item's ID to name in a failure, and write_goals writes it back.
|
||||
goals_column: str
|
||||
read_goals: typing.Callable[[str, str], Moves | Failure]
|
||||
write_goals: typing.Callable[[Moves], str]
|
||||
|
||||
@property
|
||||
def columns(self) -> tuple[str, ...]:
|
||||
"""Every column of the shape, in order. A reader takes cells by column name, so it reads a table from before BLOCKED_BY or C joined, or with a column a later release adds."""
|
||||
return ("ID", "Release", BLOCKED_BY, "Exempt", "Item", *self.score_columns, self.goals_column, "Score")
|
||||
|
||||
@property
|
||||
def needed(self) -> tuple[str, ...]:
|
||||
"""The columns without which no row can be read: a missing BLOCKED_BY reads as blocked by nothing, a missing C as no C, and a missing Score as no score yet."""
|
||||
return tuple(column for column in self.columns if column not in (BLOCKED_BY, "C", "Score"))
|
||||
|
||||
|
||||
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 []
|
||||
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}")
|
||||
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")
|
||||
if nested := [(parent, goal) for parent in goals for goal in goals if goal.startswith(parent + ".")]:
|
||||
return Failure(f"item {id_} names goal {nested[0][0]} and its sub-goal {nested[0][1]}; name one, never both: the sub-goal where the move serves it, else the parent")
|
||||
return moves
|
||||
|
||||
|
||||
def write_moves(moves: Moves) -> str:
|
||||
return ", ".join(f"{goal} by {by}" for goal, by in moves)
|
||||
|
||||
|
||||
def parse_cited(id_: str, cell: str) -> Moves:
|
||||
"""An old-shape Goals cell, such as `2.1, 1`: each goal it cites, with no move."""
|
||||
return tuple((goal.strip(), None) for goal in cell.split(","))
|
||||
|
||||
|
||||
def write_cited(moves: Moves) -> str:
|
||||
return ", ".join(goal for goal, _ in moves)
|
||||
|
||||
|
||||
SHAPE = Shape(("R", "S", "C"), MOVES, parse_moves, write_moves)
|
||||
# The shape from before MOVES replaced A, G and Goals, which older todo.md files hold.
|
||||
OLD_SHAPE = Shape(("R", "S", "C", "A", "G"), "Goals", parse_cited, write_cited)
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
@@ -19,7 +77,8 @@ class Item:
|
||||
exempt: str
|
||||
tagline: str
|
||||
scores: dict[str, int]
|
||||
goals: tuple[str, ...]
|
||||
moves: Moves
|
||||
blocked_by: tuple[int, ...]
|
||||
|
||||
@property
|
||||
def risk_and_complexity(self) -> int:
|
||||
@@ -29,39 +88,73 @@ class Item:
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Table:
|
||||
"""Body rows of a markdown table, and the index of the first row in the file's lines."""
|
||||
start: int
|
||||
"""A markdown table: the index of its header in the file's lines, its column names, and its body rows."""
|
||||
header: int
|
||||
columns: tuple[str, ...]
|
||||
rows: list[str]
|
||||
|
||||
@property
|
||||
def start(self) -> int:
|
||||
"""The index of the first body row, below the header and the divider."""
|
||||
return self.header + 2
|
||||
|
||||
|
||||
def shape_of(columns: tuple[str, ...]) -> Shape:
|
||||
"""OLD_SHAPE where the columns include A, G or Goals and not MOVES; else SHAPE, so a misspelt MOVES is reported missing."""
|
||||
old_only = set(OLD_SHAPE.columns) - set(SHAPE.columns)
|
||||
return OLD_SHAPE if MOVES not in columns and old_only.intersection(columns) else SHAPE
|
||||
|
||||
|
||||
def items(todo: str) -> list[Item] | None | Failure:
|
||||
"""Each row of a todo.md's items table, with C or without it; None where todo.md holds no items table."""
|
||||
lines = todo.splitlines()
|
||||
headers = [header for header in (ITEMS_HEADER, WITHOUT_C) if header in lines]
|
||||
if not headers:
|
||||
return None
|
||||
table = table_rows(lines, headers[0])
|
||||
if isinstance(table, Failure):
|
||||
"""Each row of a todo.md's items table; None where todo.md holds no items table."""
|
||||
table = items_table(todo.splitlines())
|
||||
if table is None or isinstance(table, Failure):
|
||||
return table
|
||||
found = []
|
||||
for row in table.rows:
|
||||
item = parse_row(row, headers[0])
|
||||
item = parse_row(row, table)
|
||||
if isinstance(item, Failure):
|
||||
return item
|
||||
found.append(item)
|
||||
return found
|
||||
|
||||
|
||||
def items_table(lines: list[str]) -> Table | None | Failure:
|
||||
"""The table whose header opens with HEADER_START; None where there is none."""
|
||||
headers = [line for line in lines if line.startswith(HEADER_START)]
|
||||
if not headers:
|
||||
return None
|
||||
if len(headers) > 1:
|
||||
return Failure(f"todo.md holds {len(headers)} tables whose header opens {HEADER_START}; keep one items table")
|
||||
table = table_rows(lines, headers[0])
|
||||
if isinstance(table, Failure):
|
||||
return table
|
||||
if repeated := sorted({column for column in table.columns if table.columns.count(column) > 1}):
|
||||
return Failure(f"todo.md's items table names the column {', '.join(repeated)} twice; keep one")
|
||||
if missing := [column for column in shape_of(table.columns).needed if column not in table.columns]:
|
||||
return Failure(f"todo.md's items table has no {', '.join(missing)} column; rank_todo.py --help shows a valid one")
|
||||
return table
|
||||
|
||||
|
||||
def waiting(found: list[Item]) -> set[int]:
|
||||
"""The IDs of the items that wait: each marked question, or blocked by an item the table still holds. Row order does not change the result."""
|
||||
held = {item.id for item in found}
|
||||
return {item.id for item in found if item.exempt == "question" or held.intersection(item.blocked_by)}
|
||||
|
||||
|
||||
def table_rows(lines: list[str], header: str) -> Table | Failure:
|
||||
if lines.count(header) != 1:
|
||||
return Failure(f"todo.md needs the table header {header} once")
|
||||
start = lines.index(header) + 2
|
||||
if start > len(lines) or not re.fullmatch(r"\|(-+\|)+", lines[start - 1].replace(" ", "")):
|
||||
at = lines.index(header)
|
||||
if at + 2 > len(lines) or not re.fullmatch(r"\|(-+\|)+", lines[at + 1].replace(" ", "")):
|
||||
return Failure(f"the table under {header} has no |---| divider line")
|
||||
end = start
|
||||
end = at + 2
|
||||
while end < len(lines) and lines[end].startswith("|"):
|
||||
end += 1
|
||||
return Table(start, lines[start:end])
|
||||
columns = cells(header, header.count("|") - 1)
|
||||
if isinstance(columns, Failure):
|
||||
return columns
|
||||
return Table(at, tuple(columns), lines[at + 2:end])
|
||||
|
||||
|
||||
def cells(row: str, count: int) -> list[str] | Failure:
|
||||
@@ -69,13 +162,30 @@ def cells(row: str, count: int) -> list[str] | Failure:
|
||||
return found if len(found) == count else Failure(f"this row needs {count} cells: {row}")
|
||||
|
||||
|
||||
def parse_row(row: str, header: str = ITEMS_HEADER) -> Item | Failure:
|
||||
"""An item row under header, every cell checked but the goals it cites."""
|
||||
names = header.strip("| ").split(" | ")
|
||||
found = cells(row, len(names))
|
||||
def parse_row(row: str, table: Table) -> Item | Failure:
|
||||
"""An item row of table, every cell checked but whether README.md numbers and weighs the goals it names."""
|
||||
found = cells(row, len(table.columns))
|
||||
if isinstance(found, Failure):
|
||||
return found
|
||||
named = dict(zip(names, found))
|
||||
named = dict(zip(table.columns, found))
|
||||
if misformed := check_cells(row, named):
|
||||
return misformed
|
||||
shape = shape_of(table.columns)
|
||||
scores = parse_scores(named["ID"], named, shape.score_columns)
|
||||
if isinstance(scores, Failure):
|
||||
return scores
|
||||
blocked_by = parse_blockers(named["ID"], named.get(BLOCKED_BY, ""))
|
||||
if isinstance(blocked_by, Failure):
|
||||
return blocked_by
|
||||
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)
|
||||
|
||||
|
||||
def check_cells(row: str, named: dict[str, str]) -> Failure | None:
|
||||
"""Holds the row's ID, Release, Exempt and Item cells to the format: why one breaks it, None when none does."""
|
||||
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}")
|
||||
@@ -85,13 +195,25 @@ def parse_row(row: str, header: str = ITEMS_HEADER) -> Item | Failure:
|
||||
return Failure(f"item {id_}'s Exempt {exempt!r} is not empty or one of {', '.join(EXEMPTIONS[1:])}")
|
||||
if not re.fullmatch(r"\*\*[^*].*[^*]\*\*", tagline):
|
||||
return Failure(f"item {id_}'s Item cell is not one bold tagline: {tagline}")
|
||||
return None
|
||||
|
||||
|
||||
def parse_scores(id_: str, named: dict[str, str], names: tuple[str, ...]) -> dict[str, int] | Failure:
|
||||
"""Each score in names that the row holds; only C may be missing, since the table holds every needed column."""
|
||||
scores: dict[str, int] = {}
|
||||
for name in ("R", "S", "C", "A", "G"):
|
||||
for name in names:
|
||||
if name not in named:
|
||||
continue
|
||||
if not re.fullmatch(r"[0-9]+", named[name]) or not 1 <= int(named[name]) <= TOP_SCORE:
|
||||
return Failure(f"item {id_}'s {name} {named[name]!r} is not a whole number from 1 to {TOP_SCORE}")
|
||||
scores[name] = int(named[name])
|
||||
cited = tuple(goal.strip() for goal in named["Goals"].split(","))
|
||||
major, minor, patch = (int(part) for part in release.split("."))
|
||||
return Item(int(id_), (major, minor, patch), exempt, tagline, scores, cited)
|
||||
return scores
|
||||
|
||||
|
||||
def parse_blockers(id_: str, cell: str) -> tuple[int, ...] | Failure:
|
||||
if not re.fullmatch(r"([0-9]+(, [0-9]+)*)?", cell):
|
||||
return Failure(f"item {id_}'s {BLOCKED_BY} {cell!r} is not empty or IDs separated by \", \"")
|
||||
blocked_by = tuple(int(blocker) for blocker in cell.split(", ") if blocker)
|
||||
if int(id_) in blocked_by:
|
||||
return Failure(f"item {id_} is blocked by itself; drop {id_} from its {BLOCKED_BY}")
|
||||
return blocked_by
|
||||
|
||||
@@ -27,8 +27,10 @@ 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) -> str:
|
||||
return f"{UNFINISHED}\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 ""
|
||||
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:
|
||||
|
||||
@@ -24,7 +24,7 @@ class Archive(unittest.TestCase):
|
||||
transcript = pathlib.Path(root, "t.jsonl")
|
||||
transcript.write_text('{"timestamp": "2026-10-03T00:00:00Z"}\n')
|
||||
with contextlib.redirect_stderr(io.StringIO()):
|
||||
self.assertIsNone(write.archive(kept, str(transcript), "Do it.", outcomes.unfinished("m", "working", "j"), NOW))
|
||||
self.assertIsNone(write.archive(kept, str(transcript), "Do it.", outcomes.unfinished("m", "working", "j", ""), NOW))
|
||||
(kept_outcomes,) = kept.glob("*/*.outcomes.md")
|
||||
kept_outcomes.unlink()
|
||||
self.assertIsNone(write.archive(kept, str(transcript), "Do it.", outcomes.stopped("m", "Ctrl-C"), NOW))
|
||||
@@ -49,13 +49,17 @@ class Outcomes(unittest.TestCase):
|
||||
|
||||
def test_reads_back_the_worker_of_each_outcome_that_closes_a_cycle(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.unfinished("w1", "Worker: not this", "j", ""),
|
||||
outcomes.interrupted("Which one?\nWorker: nor this", "e", "j"),
|
||||
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")])
|
||||
|
||||
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_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), [])
|
||||
@@ -68,7 +72,7 @@ class Outcomes(unittest.TestCase):
|
||||
transcript.write_text('{"timestamp": "2026-10-03T00:00:00Z"}\n')
|
||||
with contextlib.redirect_stderr(io.StringIO()):
|
||||
for worker in ("z-first", "a-last"):
|
||||
self.assertIsNone(write.archive(kept, str(transcript), "Do it.", outcomes.unfinished(worker, "working", "j"), NOW))
|
||||
self.assertIsNone(write.archive(kept, str(transcript), "Do it.", outcomes.unfinished(worker, "working", "j", ""), NOW))
|
||||
self.assertEqual(read.latest_worker(kept, str(transcript)), "a-last")
|
||||
|
||||
def test_names_the_worker_the_latest_outcome_of_the_transcripts_chunk_records(self):
|
||||
@@ -78,7 +82,7 @@ class Outcomes(unittest.TestCase):
|
||||
transcript.write_text('{"timestamp": "2026-10-03T00:00:00Z"}\n')
|
||||
self.assertIsNone(read.latest_worker(kept, str(transcript)))
|
||||
with contextlib.redirect_stderr(io.StringIO()):
|
||||
self.assertIsNone(write.archive(kept, str(transcript), "Do it.", outcomes.unfinished("w1", "working", "j"), NOW))
|
||||
self.assertIsNone(write.archive(kept, str(transcript), "Do it.", outcomes.unfinished("w1", "working", "j", ""), NOW))
|
||||
transcript.write_text('{"timestamp": "2026-10-03T00:00:00Z"}\n{"more": 1}\n')
|
||||
self.assertIsNone(write.archive(kept, str(transcript), "Do it.", outcomes.stopped("w2", "Ctrl-C"), NOW + 1))
|
||||
self.assertEqual(read.latest_worker(kept, str(transcript)), "w2")
|
||||
|
||||
@@ -1770,3 +1770,194 @@ Junior A, decided by:
|
||||
- Self-sufficiency: `bin/routing_figures/measure.py:23` `ESCALATION`: trigger numbers mean something only in `CLAUDE.md:60`'s list, and renumbering it would silently change old figures
|
||||
- Self-sufficiency, Shape: `CLAUDE.md:60` "Working with the codebase": "trigger" now names an escalation condition as well as the review-pass condition Vocabulary defines
|
||||
- Self-sufficiency, Locality: `bin/loop_claude/cycle/prompts.py:40` `escalation`: the past-the-cap branch is missing from the docstring, and the off-ladder guard differs from `escalation_rungs`'s
|
||||
|
||||
## 2026-10-15T19:39:18Z, PR #276 at f643a14, against eb23048
|
||||
|
||||
Ruling: same
|
||||
|
||||
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|
||||
|---|---|---|---|---|---|
|
||||
| Mid A | same | worse | worse | same | worse |
|
||||
| Inherited architect | same | same | worse | better | same |
|
||||
| Maintainability senior | same | same | worse | same | same |
|
||||
| Junior A | same | same | worse | same | same |
|
||||
|
||||
Mid A, decided by:
|
||||
|
||||
- Shape, Locality: `bin/rung_replay/search.py:44` `replayed`: generic over `Case`, `Item` and `Reply` with a `reproduced` callback returning a list of items, worked through `held`, `aim` and `got`; for the judge the list is only `[kind]` or `[]`, so the reader decodes an abstraction built for two consumers before following one
|
||||
- Locality: `bin/judge_replay/replay.py:70` `report`: rebuilds the unreproduced verdicts by calling `reproduced` again on `replay.on_reference`, so it is right only while `main.py` passes that same function to `replayed`
|
||||
- Shape: `bin/stability_replay/main.py:83` `main`: `found` names a `Round`, a `set[int]` and a list in one file, and one call packs the reference, the candidates, a closure over `codes` and an inline lambda
|
||||
- Shape: `bin/rung_replay/command.py:14` `project_rung_or_exit`: returns `Rung | int`, the int an exit code, so each caller tests `isinstance(anchor, int)`
|
||||
|
||||
Inherited architect, decided by:
|
||||
|
||||
- Shape: `bin/rung_replay/search.py:44` `replayed`: generic over its type variables, so a reader works out what `reproduced` returns before the search reads; it was a concrete comparison of kinds
|
||||
- Shape: `bin/judge_replay/replay.py:65` `reproduced`: returns a list of zero or one kinds where a yes or no would do, to fit the generic shape
|
||||
- Shape: `bin/stability_replay/main.py:83` `main`: `found` is a `Round` in one lambda and a `set[int]` in the next, and an accumulator list elsewhere in the file
|
||||
- Self-sufficiency: `bin/rung_replay/search.py:52` `replayed`: the docstring says why the search goes down from the highest rung and stops at the first miss, which the cheapest-first search assumed unsaid
|
||||
- Self-sufficiency: `bin/stability_replay/main.py:120` `code_of`: says what it guesses and what a wrong guess costs, so no record is needed beside it
|
||||
|
||||
Maintainability senior, decided by:
|
||||
|
||||
- Shape: `bin/rung_replay/search.py:44` `replayed`: generic as `Replay[Case, Item, Reply]` with a `reproduced` callback returning a list, which judge-replay fits only with a list of one or none and stability-replay with an inline adapter; following one `report` line takes three files and the generics
|
||||
- Shape: `bin/stability_replay/main.py:66` `main`: one file walks the archive, rebuilds the reviewed commits from two git logs, clones, reviews and matches, with long lines packing the `replayed` call, a nested conditional over `first_reply` and a starred conditional checkout command
|
||||
|
||||
Junior A, decided by:
|
||||
|
||||
- Shape: `bin/rung_replay/search.py:37` `Replay`: the search is generic over three type parameters with two callbacks and a label, so a reader works out what `Item` and `Reply` are for each caller before the loop makes sense
|
||||
- Shape: `bin/judge_replay/replay.py:65` `reproduced`: returns `[kind]` or `[]` only to fit the generic shape, and `report` rebuilds the unreproduced list by calling it again
|
||||
- Shape: `bin/rung_replay/command.py:1` `command`: the name says little, and the module mixes argument parsing, a models-file lookup, rung arithmetic and stderr exits
|
||||
|
||||
## 2026-10-15T20:33:16Z, PR #278 at 0f71e33, against ddb86cb
|
||||
|
||||
Ruling: same
|
||||
|
||||
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|
||||
|---|---|---|---|---|---|
|
||||
| Mid A | same | better | same | better | better |
|
||||
| Inherited architect | same | same | worse | better | same |
|
||||
| Maintainability senior | same | same | worse | better | same |
|
||||
| Junior A | same | same | same | better | better |
|
||||
|
||||
Mid A, decided by:
|
||||
|
||||
- Locality: `bin/loop_claude/routing.py:38` `kept_rung`: one rule now raises a route's rung to item_rung for both `kept` and `stepped`, where the base handled the off-ladder case in two places with two different targets
|
||||
- Locality, Self-sufficiency: `bin/loop_claude/routing.py:55` `escalation_cap`: the escalation step and the prompt's offered rungs share one named cap, whose docstring gives the reason it counts from item_rung instead of naming who set it
|
||||
- Self-sufficiency: `bin/loop_claude/cycle/judge.py:149` `run_judge`: a docstring lists the three quotes, what each is checked against and what a misquote does, where the base had one comment covering only the quoted answer
|
||||
- Self-sufficiency: `bin/loop_claude/routing.py:63` `stepped`: the docstring says why it takes the verdict's fields and not the verdict, an import cycle through prompts
|
||||
|
||||
Inherited architect, decided by:
|
||||
|
||||
- Shape: `bin/loop_claude/routing.py:63` `stepped`: the starting rung now takes three helper hops, `taken_in`, `kept_rung`, `highest`, where the base had two inline lines, and the off-ladder handling is said only in `kept_rung`'s docstring
|
||||
- Shape: `bin/loop_claude/routing.py:78` `taken_in`: used once, its name does not say what it returns, and `kept(route, anchor)` and `kept_rung(anchor, route)` take their arguments in different orders
|
||||
- Self-sufficiency: `bin/loop_claude/routing.py:55` `escalation_cap`: the cap's reason is now in the code, and it is computed once for `escalation_rungs` and `stepped`
|
||||
- Self-sufficiency: `bin/loop_claude/cycle/judge.py:149` `run_judge`: the docstring lists all three quote checks and why no misquote but the evidence's is a failure, which answers the 3am question without opening anything else
|
||||
- Self-sufficiency: `bin/loop_claude/routing.py:66` `stepped`: the docstring explains the import cycle that keeps the verdict type out of routing
|
||||
|
||||
Maintainability senior, decided by:
|
||||
|
||||
- Self-sufficiency: `bin/loop_claude/cycle/judge.py:149` `run_judge`: the docstring lists the three quote checks, what each is checked against and what a misquote does, where the base had one comment covering only the answer
|
||||
- Self-sufficiency: `bin/loop_claude/routing.py:63` `stepped`: the docstring states the import cycle that keeps the verdict type out, and `escalation_cap` says why the cap counts from item_rung
|
||||
- Shape: `bin/loop_claude/routing.py:11` `ESCALATION_CAP`: differs only in case from `escalation_cap` at `:55`, an int against a function returning a `Rung`, and its comment ends in a stray "yes,."
|
||||
- Shape: `bin/loop_claude/routing.py:78` `taken_in`: `stepped` no longer reads top to bottom; it chases `taken_in`, `kept_rung`, `item_rung` and `picked`, and the off-ladder rule lives only in `kept_rung`'s docstring
|
||||
|
||||
Junior A, decided by:
|
||||
|
||||
- Self-sufficiency, Overall: `bin/loop_claude/cycle/judge.py:149` `run_judge`: the docstring lists the three quote checks, how strictly each is checked and what a misquote does, where the base made the reader work out why grounded and verbatim differ
|
||||
- Self-sufficiency: `bin/loop_claude/routing.py:55` `escalation_cap`: the limit is its own named function whose docstring says why it counts from item_rung, and `stepped` names `counted_out` and `escalates`
|
||||
|
||||
## 2026-10-15T21:39:57Z, PR #280 at 9af5ee7, against 545f3c3
|
||||
|
||||
Ruling: same
|
||||
|
||||
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|
||||
|---|---|---|---|---|---|
|
||||
| Mid A | same | better | same | same | better |
|
||||
| Inherited architect | same | same | worse | same | same |
|
||||
| Maintainability senior | same | better | same | same | same |
|
||||
| Junior A | same | better | same | same | better |
|
||||
|
||||
Mid A, decided by:
|
||||
|
||||
- Locality, Overall: `bin/todo_table.py:64` `items_table`: reads the items table once and takes each cell by column name, where the base needed a second header constant that `items`, `read_scoring` and `read_items` each had to know
|
||||
- Locality, Overall: `bin/todo_table.py:81` `waiting`: names the rule for skipping an item once, used by `routed_item`, where the base wrote it inline
|
||||
- Locality: `bin/loop_claude/routing.py:84` `judge_rung`: calls `item_rung`, so the judge's and the worker's rung share one definition
|
||||
|
||||
Inherited architect, decided by:
|
||||
|
||||
- Shape: `bin/rank_todo.py:311` `place`: five parameters, recursion, a set rebuilt per call, and a name that hides that it also finds loops and prunes `blocked_by`
|
||||
- Locality: `bin/rank_todo.py:194` `rank`: the rule that a blocker that left the table no longer counts is worked out here, in `place` and in `todo_table.waiting`
|
||||
- Locality: `bin/rank_todo.py:274` `read_items`: the Blocked by checks are spread over `parse_row`, `read_items`, `blockers_first` and `place`
|
||||
- Locality, Shape: `bin/todo_table.py:64` `items_table`: cells read by column name, with the C check beside the column, where the base split the header text by position
|
||||
- Locality: `bin/loop_claude/routing.py:16` `routed_item`: asks the pure `waiting`, where the base leaned on an order rank_todo kept
|
||||
- Shape: `bin/rank_todo.py:187` `rank`: the two-line header replacement keeps `found.start` right only because header and divider are two lines, and the module's fan-out grows past 25 functions
|
||||
|
||||
Maintainability senior, decided by:
|
||||
|
||||
- Locality: `bin/todo_table.py:107` `parse_row`: reads each cell by the column name in the table's own header, where the base found the table by exact header strings kept in mind across two modules
|
||||
- Locality: `bin/rank_todo.py:247` `read_items`: the C and unknown-column checks sit where the table is read, where the base checked raw lines in the formula reader
|
||||
- Locality: `bin/rank_todo.py:311` `place`: a partial offset; dropping a blocker that left the table happens in `place`, `blockers_first` and `rank`, and `place` threads five parameters
|
||||
- Locality: `bin/loop_claude/routing.py:16` `routed_item`: defers to the named, order-free `todo_table.waiting`, where the base leaned on rank_todo's order
|
||||
|
||||
Junior A, decided by:
|
||||
|
||||
- Locality, Overall: `bin/todo_table.py:64` `items_table`: one function finds the table, checks repeated and missing columns, and rows are read by column name, where the base kept two header variants in step
|
||||
- Locality: `bin/rank_todo.py:247` `read_items`: the table's shape checks sit where the table is read, where the base rejected a table in the scoring reader
|
||||
- Locality: `bin/loop_claude/routing.py:16` `routed_item`: the waiting rule is one named function, `todo_table.waiting`
|
||||
- Locality: `bin/loop_claude/routing.py:84` `judge_rung`: builds the judge's rung from `item_rung`, one definition fewer to keep in step
|
||||
- Locality: `bin/rank_todo.py:311` `place`: the counterweight; a two-stage ranking with a five-parameter recursion, and the dropped-blocker rule written three times
|
||||
|
||||
## 2026-10-15T21:39:57Z, PR #280 at 9af5ee7
|
||||
|
||||
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|
||||
|---|---|---|---|---|---|
|
||||
| Junior A | 7 | 6 | 6 | 6 | 6 |
|
||||
| Mid A | 7 | 6.5 | 6.5 | 6 | 6.5 |
|
||||
| Maintainability senior | 7 | 6 | 6 | 7 | 6.5 |
|
||||
| Inherited architect | 7 | 7 | 6 | 7 | 6.5 |
|
||||
| Mean | 7.00 | 6.38 | 6.13 | 6.50 | 6.38 |
|
||||
|
||||
Junior A, hardest first:
|
||||
|
||||
- `bin/loop_claude/routing.py:64` `stepped`: six one-line helpers held at once to learn the next cycle's rung, each docstring defined by the others
|
||||
- `bin/loop_claude/cycle/prompts.py:40` `escalation`: the worker's prompt glued from space-led fragments over several cases, with no example of the final string
|
||||
- `bin/comprehension_history.py:106` `latest_places`: hand-shaped markdown read back by regexes, an in-a-list flag and history from before PR #255
|
||||
- `bin/loop_claude/cycle/judge.py:149` `run_judge`: three quote checks with three consequences, and a JUDGE_RULES prose wall built from constants in other modules
|
||||
- `bin/transcript_archive/outcomes.py:53` `workers`: a chunk resumes its rung by regex-parsing archive prose, with the verdict strings repeated by hand
|
||||
- `bin/routing_figures/measure.py:77` `measured`: timestamps cut to 19 characters, tools carried between iterations, totals into four counters
|
||||
- `bin/stability_replay/rounds.py:70` `reviewed_path`: guesses a removed worktree from absolute paths with a first-prefix-gone rule
|
||||
- `bin/rank_todo.py:311` `place`: recursive placement with a loop-detecting path and a placed set rebuilt per call
|
||||
|
||||
Mid A, hardest first:
|
||||
|
||||
- `bin/loop_claude/routing.py:64` `stepped`: five functions pick a rung from four reference points, and the why is a pointer to the decision log
|
||||
- `bin/loop_claude/cycle/prompts.py:40` `escalation`: conditional f-string fragments relying on leading spaces and lstrip, output unknowable from the code
|
||||
- `bin/transcript_archive/outcomes.py:53` `workers`: resume rests on a parsed Worker line, and NAMES_A_WORKER repeats the verdicts as literals
|
||||
- `bin/comprehension_history.py:106` `latest_places`: a five-clause docstring, table-order dependence and an implicit line state machine
|
||||
- `skills/larv-review/SKILL.md:63` "Round cap": the fourth-round rule lives in cross-referenced prose that no code enforces
|
||||
- `bin/routing_figures/measure.py:77` `measured`: dense one-liners and a timestamp format assumed silently in `rung_at`
|
||||
- `bin/rule_hook/override_log.py:36` `this_chunks`: which overrides belong to the chunk rests on reflog semantics
|
||||
- `bin/rank_todo.py:311` `place`: recursive blocker placement with a loop-detecting path, resolved after one reread
|
||||
|
||||
Maintainability senior, hardest first:
|
||||
|
||||
- `bin/loop_claude/routing.py:64` `stepped`: seven functions over three inputs, and the never-down and two-above rules emerge only from their composition
|
||||
- `bin/loop_claude/cycle/prompts.py:29` `off_the_projects_rung`: prompt fragments and rung arithmetic over three branches in each of three functions
|
||||
- `bin/loop_claude/loop/main.py:1` "loop-claude --help": a 120-line contract, the only end-to-end routing story, with no pointers to the modules it maps onto
|
||||
- `skills/larv-review/SKILL.md:63` "Round cap": which passes rerun after a fix spans the pass table, the fix clauses and the cap
|
||||
- `bin/model_routing/ladder.py:19` `Rung.__str__`: the archive's rung format is written and parsed across four files, and a reworded string breaks resume
|
||||
- `bin/routing_figures/measure.py:77` `measured`: tokens charged to the previous message's tools, and timestamps cut to compare with stamps
|
||||
- `bin/shell_command.py:31` `segments`: a hand-rolled splitter whose words after a redirect target open a new segment
|
||||
- `bin/comprehension_history.py:106` `latest_places`: a four-clause docstring, a seat name split from a label and a votes table assumed first
|
||||
|
||||
Inherited architect, would restructure first:
|
||||
|
||||
- `bin/round_titles.py:4` `CAP`: the round cap lives here for its regex's other readers, and no program enforces it; `SKILL.md` "Round cap" does in prose
|
||||
- `bin/loop_claude/effects.py:18` `Effects`: the process shell, `Stop` and the models-file reader that three other tools reach into loop_claude for
|
||||
- `bin/git_repo.py:8` `git`: one of seven ways to run git, alongside `metric_bench/main.py:150`, `stability_replay/main.py:202` and `reading_cost/main.py:114`
|
||||
- `bin/score_outcomes/outcomes.py:156` `outcomes_of`: shares its name and module name with `transcript_archive`'s, with a different meaning
|
||||
- `bin/loop_claude/routing.py:28` `first_route`: the parameter anchor means the project's rung, re-glossed in nearly every docstring
|
||||
- `bin/model_routing/ladder.py:19` `Rung.__str__`: parsed back to resume routing, so a wording change silently re-routes chunks
|
||||
- `bin/loop_claude/cycle/prompts.py:25` `routed_by`: the routing policy stated a third time, beside main.py's help and routing.py's logic
|
||||
|
||||
## 2026-10-16T02:11:33Z, PR #283 at 7570af6, against 9aa0d4b
|
||||
|
||||
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/rank_todo.py:502` `score`: the score depends on the table's shape, branched on a string through `goal_term`, with the same old-versus-new check in `notes`, `read_scoring` and `parse_item`
|
||||
- Locality: `bin/rank_todo.py:94` `Scoring`: `weights` means different things by shape, so a reader of `scoring.weights` must check `scoring.shape` first
|
||||
- Locality: `bin/todo_table.py:17` `Moves`: an old-shape Goals cell is stored as moves with distance None, so `score` falls back with `(by or 0)`, and `parse_cited` takes an unused `id_`
|
||||
|
||||
Inherited architect, decided by:
|
||||
|
||||
- Locality: `bin/rank_todo.py:502` `score`: reading one score needs the shape, decided elsewhere; `weights` holds two things by shape and `(by or 0)` holds only because `parse_cited` returns None moves
|
||||
- Locality, Shape: `bin/rank_todo.py:301` `unknown_columns`: the old-shape path is checked at six sites across `rank_todo.py` with its own reader and writer in `todo_table.py`, and nothing ties them together for whoever retires it
|
||||
- Shape: `bin/todo_table.py:16` `Moves`: the name lies for old-shape rows, and the goals cell is parsed by a callable stored on a dataclass
|
||||
- Locality: `bin/todo_table.py:41` `parse_moves`: the rules for a Moves cell are split between `parse_moves` and `rank_todo.py`'s `parse_item`
|
||||
|
||||
+38
-8
@@ -4,11 +4,9 @@
|
||||
|
||||
2026-09-20, lilleman. Serves goal 1. Across six projects scored with the four seats, Locality or Self-sufficiency was the lowest dimension at every seat and Navigation at none, so a layout fix would not lift a project under the floor. Valid while the scoring run keeps those four seats.
|
||||
|
||||
2026-10-13, lilleman: PR #257's scoring run found Shape lowest, at 6.25, so release 0.1.0's chunks take the Shape items, `todo.md` items 114, 124 and 125, before the release's other items, whatever their scores.
|
||||
2026-10-15, lilleman: an item that lifts the lowest dimension scores G 9, since the lowest dimension caps the overall and lifting it is worth the most to the floor. PR #257's scoring run found Shape lowest, at 6.25. The Shape items are `todo.md` items 114, 124 and 125. When PR #283 replaces G, the chunk that ships it carries this rule into the new score.
|
||||
|
||||
2026-10-14, lilleman: the Shape items moved to release 0.2.0 with the release's other readability items, so 0.1.0 ships the model router first; they still go before 0.2.0's other items.
|
||||
|
||||
2026-10-15, lilleman: the Shape items moved to release 0.3.0 with the readability items, so 0.2.0 ships the outcome measures first; they still go before 0.3.0's other items.
|
||||
2026-10-16, PR #283: such an item moves each goal it cites by 9, in place of G 9. lilleman, answering that PR's review: such items compete with the others like any item, so they no longer rank first.
|
||||
|
||||
## 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
|
||||
|
||||
@@ -124,9 +122,19 @@ 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 and goal weights it states, held to its bar, ranked by `bin/rank_todo.py`
|
||||
## 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
|
||||
|
||||
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, bar and weights 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-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 146, 149, 151 and 152 build, after PR #283 shipped the ranking; 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. A task's R alone then picks its rung. Items rank by V / C, value per cost, the cost being 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, 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. The C column stays until `todo.md` item 146 drops it. 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, ruling on the plan in PR #283: release 0.2.0 takes plan items 146, 152, 73, 50, 65, 84, 153, 67, 115 and 140 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-15, lilleman. Serves goal 1.4: loop-claude routes a chunk's first cycle on the item the chunk takes (`routing: one ladder`). 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.
|
||||
|
||||
## 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
|
||||
|
||||
@@ -204,7 +212,7 @@ A model off the ladder routes nothing: claude runs it at the effort its settings
|
||||
|
||||
The worker delegates a task only when it needs just the task's conclusion: a search or read across many files, or work independent enough to run in parallel. Edits, and whatever it must check line by line, stay in its own thread, since it would read a delegated diff again to check it. Measured over archived worker transcripts, subagent reports cost a median 8% of the worker's peak context, and `sed -n` and `grep` output made up 41% of its Bash results, so delegated searches save the most context. It scores each delegated task's R and C as for an item, and `bin/subagent-rung` turns them into the Agent tool's model and effort, counted from the project's rung. The rule names both, because the Agent tool sets a subagent's effort only when instructions ask. `CLAUDE.md` states the rule, since it holds in every session. A task that proves too hard for the worker's rung goes one rung up instead: `routing: a worker hands a task one rung up`.
|
||||
|
||||
The worker changes rung only as the chunk starts, after every second unfinished verdict, or when the judge reports a taken-in item whose R + C picks a higher rung, because a model switch inside a session discards its prompt cache. loop-claude routes on the first row of the next release in `todo.md`'s table that waits on no question. It reads neither an order the plan states in prose nor the task, so a chunk may start on another item's rung: a higher one costs money, and a lower one holds until the judge reports the item the worker took in, after the first cycle. `todo.md` item 136 ends this, routing on the item the worker says it takes.
|
||||
Because a model switch inside a session discards its prompt cache, the worker changes rung only as the chunk starts, after every second unfinished verdict, when the judge reports a taken-in item whose R + C picks a higher rung, or when the judge finds the escalation trigger a worker cites in asking for a higher rung (`routing: a worker whose run ends asking for a higher rung`). loop-claude routes on the first row of the next release in `todo.md`'s table that does not wait: an item waits while it is marked `question` or a blocker of it is still in the table. Since `todo.md` holds no order but its table's (`todo.md: one table`), that row is the item the worker takes. An item the worker takes in beyond that row lifts the worker's rung once the judge reports it, after the first cycle.
|
||||
|
||||
Valid while the index ranks these models, and while no newer model joins the catalog.
|
||||
|
||||
@@ -218,6 +226,18 @@ 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
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
Valid while the worker reports in its transcript the triggers that fired.
|
||||
|
||||
## routing: on a model judge-replay covered, the judge runs on the rung its chunk's item picks, never below the project's rung
|
||||
|
||||
2026-10-15, lilleman's plan, settled by the replay below. Serves goals 1.2 and 1.4, under the ladder and bands of `routing: one ladder`.
|
||||
@@ -226,6 +246,16 @@ On a model listed in `JUDGE_REPLAYED` in `bin/loop_claude/routing.py`, the judge
|
||||
|
||||
On 2026-10-15, `bin/judge-replay claude-opus-5-5` replayed the latest 15 archived verdicts of each kind from the Opus 5.5 projects, 39 in all. The reference judge, Opus 5.5 at the xhigh effort `settings.json` gave every judge before, reproduced 31 of them. The other 8 may rest on records or judge rules that have changed since; either way no rung is held to them. On the 31, Haiku 5.5 missed 7 at xhigh and 8 at max. That run tried each judge once. 4 of Haiku's misses, 1 at xhigh and 3 at max, misquoted the transcript, which the loop and `judge-replay` now retry; without them it missed 6 and 5. Sonnet 5.5 at high returned another kind on 3 interrupts, and Opus 5.5 at medium missed none. A missed interrupt lets the worker settle a decision that is lilleman's (goal 1.2), so the judge never runs below the project's rung.
|
||||
|
||||
Only Opus 5.5 was replayed, so the judge of a project on another model keeps the effort its settings give until `judge-replay` covers that model (goal 1.1). Every routed chunk on record had an item of R + C 9, so the replay could not show that the project's rung suffices for harder items, and the judge climbs with the routed item as the worker does. For R + C 11 to 14 it still runs at or below xhigh (goal 1.4); from 15, `routing: one ladder` records that lilleman wants the highest quality at any price. An item the worker takes in later lifts the worker, not the judge, until `todo.md` item 136 routes a chunk on the item its worker takes.
|
||||
Only Opus 5.5 was replayed, so the judge of a project on another model keeps the effort its settings give until `judge-replay` covers that model (goal 1.1). Every routed chunk on record had an item of R + C 9, so the replay could not show that the project's rung suffices for harder items, and the judge climbs with the routed item as the worker does. For R + C 11 to 14 it still runs at or below xhigh (goal 1.4); from 15, `routing: one ladder` records that lilleman wants the highest quality at any price. An item the worker takes in beyond the routed one lifts the worker's rung but not the judge's, until `todo.md` item 153 lifts the judge too.
|
||||
|
||||
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 stays on 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
|
||||
|
||||
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.
|
||||
|
||||
`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 🟡.
|
||||
|
||||
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: one ladder` puts every reviewer: on the project's rung while the worker runs below it.
|
||||
|
||||
Valid until a new model joins the ladder, or the archive holds rounds a new reviewer prompt produced: replay then.
|
||||
|
||||
@@ -384,3 +384,71 @@ Read most (opens and searches):
|
||||
- `AGENTS.md` 1
|
||||
- `bin/loop_claude/routing.py` 1
|
||||
- `bin/model_routing/ladder.py` 1
|
||||
|
||||
## Reading cost, chunk d1481c54d520, finished 2026-10-15T17:52:35Z
|
||||
|
||||
90662 new input tokens before the first commit.
|
||||
|
||||
Read most (opens and searches):
|
||||
|
||||
- `todo.md` 6
|
||||
- `docs/decisions.md` 5
|
||||
- `skills/larv-review/SKILL.md` 3
|
||||
- `CLAUDE.md` 2
|
||||
- `README.md` 2
|
||||
- `bin/loop_claude/cycle/prompts.py` 2
|
||||
- `bin/loop_claude/loop/main.py` 2
|
||||
- `bin/loop_claude/test_loop_claude.py` 2
|
||||
- `skills/comprehension-panel/SKILL.md` 2
|
||||
- `skills/comprehension-panel/seat-prompts.md` 2
|
||||
|
||||
## Reading cost, chunk dbd1e7538163, finished 2026-10-15T19:40:18Z
|
||||
|
||||
146584 new input tokens before the first commit.
|
||||
|
||||
Read most (opens and searches):
|
||||
|
||||
- `README.md` 5
|
||||
- `skills/larv-review/SKILL.md` 4
|
||||
- `todo.md` 4
|
||||
- `bin/judge_replay/main.py` 3
|
||||
- `bin/loop_claude/cycle/retry.py` 3
|
||||
- `docs/decisions.md` 3
|
||||
- `CHANGELOG.md` 2
|
||||
- `bin/claude_code/entries.py` 2
|
||||
- `bin/failure.py` 2
|
||||
- `bin/judge_replay/test_judge_replay.py` 2
|
||||
|
||||
## Reading cost, chunk 224f2177e487, finished 2026-10-15T21:46:26Z
|
||||
|
||||
133254 new input tokens before the first commit.
|
||||
|
||||
Read most (opens and searches):
|
||||
|
||||
- `bin/loop_claude/test_loop_claude.py` 7
|
||||
- `todo.md` 6
|
||||
- `bin/loop_claude/cycle/judge.py` 4
|
||||
- `docs/decisions.md` 4
|
||||
- `bin/loop_claude/cycle/prompts.py` 3
|
||||
- `bin/loop_claude/test_black_box.py` 3
|
||||
- `AGENTS.md` 2
|
||||
- `CHANGELOG.md` 2
|
||||
- `README.md` 2
|
||||
- `bin/loop_claude/loop/main.py` 2
|
||||
|
||||
## Reading cost, chunk 6b0c8adf366b, finished 2026-10-15T21:55:23Z
|
||||
|
||||
139738 new input tokens before the first commit.
|
||||
|
||||
Read most (opens and searches):
|
||||
|
||||
- `todo.md` 7
|
||||
- `README.md` 5
|
||||
- `docs/decisions.md` 5
|
||||
- `CHANGELOG.md` 3
|
||||
- `docs/scoring-and-goals-research.md` 3
|
||||
- `bin/rank_todo.py` 2
|
||||
- `skills/larv-review/SKILL.md` 2
|
||||
- `skills/larv-review/standards/readme.md` 2
|
||||
- `AGENTS.md` 1
|
||||
- `CLAUDE.md` 1
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
# Scoring and goals research
|
||||
|
||||
The evidence behind how `todo.md` scores an item and how a README states its goals. Read it only when changing that method; daily work needs only `rules/todo-items.md` and `rules/goals-and-audience.md`. `docs/decisions.md` → `todo.md: …` records what was chosen from it. Gathered on 2026-10-15 by web research; a source marked † was read only as an abstract or a secondary summary.
|
||||
|
||||
## Risk is likelihood, escape and impact, added on log scales
|
||||
|
||||
- **Multiplying 1–10 labels misleads.** FMEA's risk priority number, S × O × D, gives one product for different risks (2×6×5 = 3×4×5), because ordinal codes carry order, not size (Stevens 1946, *Science* 103:677). AIAG-VDA replaced it in 2019 with a lookup that ranks severity first†. Risk matrices compress ranges and can rank worse than chance when likelihood and impact move oppositely (Cox 2008, *Risk Analysis*, doi:10.1111/j.1539-6924.2008.01030.x).
|
||||
- **Give each level a real quantity, about ×10 per step, and add the levels.** Adding log-scale levels multiplies the underlying probability and cost, which is what risk is (Kaplan & Garrick 1981, *Risk Analysis*, doi:10.1111/j.1539-6924.1981.tb01350.x†).
|
||||
- **Take the worst impact dimension, not a sum.** NIST defines impact level as "the assessed worst-case potential impact" (csrc.nist.gov/glossary/term/impact_level). CVSS v4 buckets impacts by their High values (first.org/cvss/v4-0/specification-document).
|
||||
- **Impact dimensions:** confidentiality, integrity and availability (CVSS v4); reach, the people and systems a failure spreads to (NIST; CVSS "subsequent systems"; Hyrum's law, hyrumslaw.com); reversibility, one-way versus two-way doors (Bezos, 2015 shareholder letter); duration, until users stop feeling pain (Google Cloud blog, 2019).
|
||||
- **Count detection once, as its own axis.** FMEA rates detection apart from severity†. DORA's change failure rate measures likelihood, not impact (dora.dev/guides/dora-metrics).
|
||||
|
||||
## What predicts that a change brings a defect
|
||||
|
||||
Every study below predicts from the diff or history, none from a description, so for a planned item these are priors.
|
||||
|
||||
1. **Size**, the strongest. Added lines alone beat CC2Vec and DeepJIT on over 310,000 changes (Zeng et al. 2021, ISSTA, doi:10.1145/3460319.3464819). Relative churn predicts well (Nagappan & Ball 2005, ICSE†).
|
||||
2. **Spread** across subsystems, directories and files (Kamei et al. 2013, TSE, doi:10.1109/TSE.2012.70†; Hassan 2009, ICSE, change entropy†).
|
||||
3. **Defect history** of the touched code: about a tenth of files held 73–95% of faults (Kim et al. 2007, ICSE†).
|
||||
4. **Familiarity and ownership** (Bird et al. 2011, FSE†; contested in open source, Foucault et al. 2014†).
|
||||
5. **Review coverage and participation** (McIntosh et al. 2016, EMSE).
|
||||
6. **Live config or infrastructure as code.** About 70% of Google's outages come from changes to a live system (sre.google/sre-book/introduction). Syntax and configuration defects were 36.5–62.7% of IaC defects at four organisations (Rahman et al. 2018, arXiv:1809.07937).
|
||||
7. **New technology or AI-written code**, with mixed evidence (Pearce et al. 2022, S&P†; Perry et al. 2023, CCS†; Spracklen et al. 2025, USENIX Security).
|
||||
|
||||
Complexity metrics add almost nothing once size is accounted for (El Emam et al. 2001, TSE, doi:10.1109/32.935855†). So a separate difficulty score beside size, spread and novelty measures nothing new.
|
||||
|
||||
## Value per cost, not a sum
|
||||
|
||||
- **Order by value over cost.** Weight over duration minimises total weighted waiting time on one machine (Smith's rule, 1956†); WSJF is that rule with cost of delay as the weight (Reinertsen, *The Principles of Product Development Flow*, 2009). An additive score has no such derivation, and its order changes with the unit of size.
|
||||
- **WSJF counts reducing risk as value** (framework.scaledagile.com/wsjf).
|
||||
- **No source grounds a fixed score bar.** DSDM fills a timebox by priority up to its capacity† (MoSCoW, DSDM v4.2, 2006).
|
||||
- **Pairwise comparison is the best-supported method** (Karlsson, Wohlin & Regnell 1998, IST, doi:10.1016/S0950-5849(97)00053-0; Bukhsh et al. 2020, *Computer Standards & Interfaces*, doi:10.1016/j.csi.2019.103389).
|
||||
- **LLM scorers:** absolute ratings bunch near the middle or top (arXiv:2509.24678†); pairwise prompting beat pointwise by over 10% on document ranking (Qin et al., arXiv:2306.17563); worked examples cut story-point error about 59% (Tawosi et al., arXiv:2403.08430†); swapping the order of two candidates can flip a judgement (Wang et al., arXiv:2305.17926).
|
||||
|
||||
## Goals and audience
|
||||
|
||||
Almost none of this is tested on software projects; the firmer evidence is goal-setting in general.
|
||||
|
||||
- **Specific, difficult goals beat vague ones** (Locke & Latham 2002†; Epton et al. 2017, 141 RCT papers, d = .34†). A narrow goal neglects what it leaves out (Ordóñez et al. 2009, "Goals gone wild"†), and a metric made a target gets gamed (Manheim & Garrabrant 2018, arXiv:1803.04585).
|
||||
- **Maintain goals differ from achieve goals.** KAOS separates goals that hold a state from goals that reach one (van Lamsweerde 2001, RE'01). Anthropic's constitution keeps its hard limits outside its weighing (anthropic.com/constitution).
|
||||
- **Weights from a ranking:** against weights people actually gave, sum-reciprocal weights did best and rank-order centroid worst of the rank rules (Burk & Nehring 2023, *Decision Analysis*†).
|
||||
- **Written guidance can fail to change behaviour.** Repository context files did not generally raise agents' task success and added over 20% inference cost (arXiv:2602.11988†), so a project's goals need a test that they still decide cases.
|
||||
- **Personas** have uneven, weakly evidenced use (Nielsen & Hansen 2014, CHI†; arXiv:2403.15917).
|
||||
|
||||
## Calibrating scores against outcomes
|
||||
|
||||
- **Log each guess with an outcome window fixed in advance**, such as a 🔴 in review or a later fix within N days, and compare guesses with what happened. The Brier score measures it (Brier 1950, doi:10.1175/1520-0493(1950)078<0001:VOFEIT>2.0.CO;2†); Murphy (1973†) splits it into reliability (do L3 items fail about as often as L3 says?) and resolution (do higher scores fail more?).
|
||||
- **When a level misses by a factor of ten, fix its anchor, not the formula**, as reference-class forecasting corrects estimates against similar past cases (Flyvbjerg 2006†; Lovallo & Kahneman 2003†).
|
||||
- **Anchor each level to observable cases**, two or three already built (Smith & Kendall 1963, "unambiguous anchors for rating scales"†), and keep the axes' weights equal (Dawes 1979†).
|
||||
- **Expect overconfidence:** people's "90%" ranges hold about 11 times in 20 (Hubbard, *How to Measure Anything*†).
|
||||
- **Routing confounds outcomes:** a high score buys more review, which finds more. Meta randomised review on a slice of risky diffs to measure it (arXiv:2410.06351†).
|
||||
|
||||
## This repo's own measurements
|
||||
|
||||
`score-outcomes` on 2026-10-15: the median lines changed by a chunk at guessed S 3, 4, 5, 6 and 7 were 16, 78, 160.5, 511.5 and 1149, roughly ×2.5 per step.
|
||||
@@ -6,4 +6,5 @@ paths:
|
||||
# Goals and Audience
|
||||
|
||||
- **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.`
|
||||
- **Audience** names who depends on the project and what they may rely on.
|
||||
|
||||
+7
-6
@@ -5,17 +5,18 @@ paths:
|
||||
|
||||
# Todo items (`todo.md`)
|
||||
|
||||
- **`todo.md` is mandatory in every project, in one shape**, which `~/.claude/bin/rank_todo.py` checks and ranks; its `--help` shows a valid file. `## Scoring` holds the formula, the bar and the goal weights; `## Items` is one table of every item; `## Details` holds each item's detail under its ID. Cite an item by its ID. The formula, bar and weights 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. 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, or rewrite a filed item's tagline or detail. Draft each new item, and each change to a filed item, 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 R + C. 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.
|
||||
- **Score an item when it is filed or edited.** Each of R, S, C, A and G is a whole number from 1 to 10:
|
||||
- **Score an item when it is filed or edited.** Each of R, S and C is a whole number from 1 to 10:
|
||||
- **R** — the risk that the change creates serious bugs or issues.
|
||||
- **S** — the size of the change.
|
||||
- **C** — how hard the change is to get right: novel design, subtle invariants, many interacting parts. A huge rename is low C; a ten-line lock fix can be high. C stays out of the score.
|
||||
- **A** — its value to the audience in `README.md` → `## Audience`.
|
||||
- **G** — its value to the goals it cites in the Goals column; W is the weight of the heaviest of them.
|
||||
- **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.
|
||||
- **A table with A, G and Goals in place of 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.
|
||||
- **Check R, S and C against finished chunks.** Guess them, then run `~/.claude/bin/score-outcomes <R> <S> <C>` in the project. It lists the finished items guessed nearest, what their chunks measured, and the median outcome at each guessed value. Set each score 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.
|
||||
- **Read the places the comprehension seats found hard before filing an item.** `~/.claude/bin/larv-review places`, run in the project, prints them. Where the item's change touches one, its detail says to make that place easier to read.
|
||||
- **An item scoring under the bar is deleted, with every item that needs it, and a finding under the bar is not filed.** The chunk's summary names each, with its score.
|
||||
- **The Exempt cell keeps an item whatever its score:** `security` for a security finding, `defect` for a 🔴 finding, `question` for a question only the human can answer, `decision` for an item `docs/decisions.md` cites, and, where no other reason fits, `principle` for a 🟡 finding against a file under `~/.claude/principles/`, whose item's detail names that principle. Every item `docs/decisions.md` cites carries one of these reasons.
|
||||
- **Unless the project has a reason to differ, weigh goals by position, the first heaviest.** When the weights stop listing the README's goals, `rank_todo.py` fails and prints those weights.
|
||||
- **The Exempt cell keeps an item whatever its score:** `security` for a security finding, `defect` for a 🔴 finding or an item that restores a maintain goal the project breaks today, `question` for a question only the human can answer, which ranks first in its release, `decision` for an item `docs/decisions.md` cites, `owner` for an item the human told you to keep, and, where no other reason fits, `principle` for a 🟡 finding against a file under `~/.claude/principles/`, whose item's detail names that principle. Every item `docs/decisions.md` cites carries one of these reasons.
|
||||
- **A maintain goal vetoes an item that breaks it,** whatever the item scores: redesign the item so it holds the goal, or drop it.
|
||||
|
||||
@@ -154,7 +154,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? Misaligned → do not merge; ask the human, stating the conflict.
|
||||
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.
|
||||
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,173 +2,190 @@
|
||||
|
||||
## Scoring
|
||||
|
||||
`Score = -R - S/4 + 2*A + 2*G*W`
|
||||
`Score = 100 * V / (2**S + 8)`
|
||||
|
||||
`Bar = 9`
|
||||
`Bar = 0.1`
|
||||
|
||||
`Next ID = 146`
|
||||
|
||||
| Goal | W |
|
||||
|---|---|
|
||||
| 1 | 1.00 |
|
||||
| 1.1 | 0.99 |
|
||||
| 1.2 | 0.98 |
|
||||
| 1.3 | 0.97 |
|
||||
| 1.4 | 0.96 |
|
||||
| 1.5 | 0.95 |
|
||||
| 2 | 0.90 |
|
||||
| 3 | 0.85 |
|
||||
| 4 | 0.80 |
|
||||
`Next ID = 159`
|
||||
|
||||
## Items
|
||||
|
||||
Release 0.3.0 takes items 125, 114 and 124 first, whatever their scores: Shape is the lowest dimension, per `docs/decisions.md` → `larv-review: a project lifting itself to the comprehension floor starts at the lowest dimension`.
|
||||
|
||||
| ID | Release | Exempt | Item | R | S | C | A | G | Goals | Score |
|
||||
|---|---|---|---|---|---|---|---|---|---|---|
|
||||
| 145 | 0.1.0 | | **Run the stability reviewer on the worker's rung while the worker runs below the project's rung, once a replay of past stability rounds on that rung finds the 🔴 and 🟡 findings on record.** | 4 | 5 | 6 | 6 | 7 | 1.4 | 20.2 |
|
||||
| 143 | 0.1.0 | | **Resume a worker one rung up in the next cycle when its run ends asking for a higher rung and the judge finds the escalation trigger it cites in the transcript.** | 5 | 5 | 7 | 6 | 7 | 1.1, 1.4 | 19.6 |
|
||||
| 136 | 0.1.0 | decision | **Route a chunk on the item its worker says it takes, in place of the next release's first row.** | 2 | 3 | 4 | 4 | 5 | 1.4 | 14.8 |
|
||||
| 105 | 0.2.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 | 3 | 5 | 6 | 1.4 | 20.0 |
|
||||
| 112 | 0.2.0 | | **Count an item as shipped only where its chunk built it, so an item a chunk dropped from the plan gets no outcome.** | 2 | 3 | 5 | 5 | 6 | 1.1 | 19.1 |
|
||||
| 110 | 0.2.0 | | **Count, for each finished chunk, the later changes that fixed code it wrote, and show them beside its guessed R.** | 2 | 4 | 6 | 5 | 6 | 1.1, 1.4 | 18.9 |
|
||||
| 115 | 0.2.0 | question | **Confirm or set how many finished chunks that each shipped one item `score-outcomes` waits for before it shows a score's medians, today 10.** | 1 | 1 | 2 | 4 | 5 | 1.2 | 16.6 |
|
||||
| 116 | 0.2.0 | | **Report R by the share of chunks with a 🔴, once 10 chunks that each shipped one item record finding counts and most record no 🔴.** | 1 | 2 | 2 | 4 | 5 | 1.1 | 16.4 |
|
||||
| 111 | 0.2.0 | | **Measure the chunks of a project that merges by squash or fast-forward, which `score-outcomes` skips today.** | 3 | 3 | 5 | 4 | 5 | 1.3 | 13.9 |
|
||||
| 113 | 0.2.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 | 4 | 6 | 4 | 5 | 1.1, 1.4 | 13.9 |
|
||||
| 118 | 0.2.0 | | **Have `score-outcomes` count review rounds only from chunks merged after 2026-10-13, when review passes were narrowed, so C's medians compare chunks reviewed under one rule.** | 2 | 2 | 3 | 3 | 4 | 1.4 | 11.2 |
|
||||
| 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 | 4 | 5 | 5 | 6 | 1.1, 1.2 | 18.9 |
|
||||
| 121 | 0.3.0 | | **Check that `bin/round_titles.py`'s `PASSES` lists exactly the passes of larv-review §3's table.** | 1 | 3 | 2 | 4 | 5 | 1.1, 1.3 | 16.1 |
|
||||
| 122 | 0.3.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.** | 3 | 4 | 4 | 4 | 5 | 1.1 | 13.9 |
|
||||
| 123 | 0.3.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.** | 3 | 5 | 5 | 4 | 5 | 1.1 | 13.7 |
|
||||
| 139 | 0.3.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.** | 2 | 3 | 3 | 3 | 5 | 1.1 | 13.2 |
|
||||
| 127 | 0.3.0 | | **Define seat, place, paired ruling, scoring run and the judge's records in `CLAUDE.md` → "Vocabulary".** | 1 | 1 | 1 | 3 | 4 | 1.1 | 12.7 |
|
||||
| 125 | 0.3.0 | decision | **Give "record", "outcome" and "places" one meaning each across `bin/`, and rename `bin/larv_review/git.py` by what it holds.** | 2 | 5 | 3 | 3 | 5 | 1.1 | 12.7 |
|
||||
| 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 | 2 | 3 | 4 | 1.1 | 12.4 |
|
||||
| 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 | 3 | 4 | 1.1 | 12.4 |
|
||||
| 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 | 2 | 3 | 4 | 1.1 | 12.4 |
|
||||
| 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 | 2 | 3 | 4 | 1.1 | 12.4 |
|
||||
| 140 | 0.3.0 | | **Split `docs/decisions.md` → `routing: one ladder` into one entry per decision, so a reader finds the rules for the ladder, the worker's rung, the routing figures and delegation by their titles.** | 1 | 2 | 1 | 3 | 4 | 1.1 | 12.4 |
|
||||
| 114 | 0.3.0 | decision | **Run git through `git_repo.py` in `rule_hook`, `metric_bench`, `reading_cost` and `loop_claude`, keeping rule-hook's guards as an option, so one module owns how a tool runs git.** | 3 | 4 | 4 | 3 | 5 | 1.1 | 11.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.** | 2 | 2 | 3 | 3 | 4 | 1.1 | 11.4 |
|
||||
| 124 | 0.3.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.** | 3 | 6 | 3 | 3 | 5 | 1.1 | 11.4 |
|
||||
| 130 | 0.3.0 | | **Move the vote counting out of `bin/larv_review/ruling.py`'s `votes`, so reading a votes file decides nothing.** | 2 | 3 | 3 | 3 | 4 | 1.1 | 11.2 |
|
||||
| 137 | 0.3.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.** | 2 | 3 | 3 | 3 | 4 | 1.1 | 11.2 |
|
||||
| 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 | 1 | 1 | 2 | 4 | 1.1 | 10.7 |
|
||||
| 135 | 0.3.0 | | **Fingerprint only the modules loop-claude imports, so editing another tool's code no longer reloads a running loop.** | 3 | 3 | 4 | 3 | 4 | 1.1 | 10.2 |
|
||||
| 1 | 0.4.0 | question | **Say in README → Install how the transcript archive is backed up, once bender-infra backs up ai-sandbox's data volume.** | 3 | 5 | 2 | 8 | 9 | 3, 4 | 27.0 |
|
||||
| 21 | 0.4.0 | | **Give `settings.json`'s model one writer, and sort its keys.** | 3 | 3 | 4 | 6 | 7 | 1.3 | 21.8 |
|
||||
| 49 | 0.4.0 | principle | **Check that `AGENTS.md` lists exactly the titles of `docs/decisions.md`.** | 1 | 2 | 2 | 5 | 6 | 1.3 | 20.1 |
|
||||
| 59 | 0.4.0 | | **Bound a run of unfinished verdicts on one chunk, so a worker and judge that disagree cannot cycle unattended without end.** | 3 | 3 | 5 | 6 | 6 | 1.4 | 19.8 |
|
||||
| 12 | 0.4.0 | | **Run the test suite in CI on every PR, or record in `docs/decisions.md` why the local run is enough.** | 2 | 4 | 3 | 4 | 6 | 1.1 | 16.9 |
|
||||
| 80 | 0.4.0 | | **State in README → Install that every machine taking this checkout must be a sandbox, as `settings.json`'s auto mode assumes.** | 1 | 1 | 1 | 5 | 5 | 4 | 16.8 |
|
||||
| 5 | 0.4.0 | decision | **Key a project on its checkout's full path, and refuse to start while another session uses that key.** | 5 | 5 | 7 | 5 | 6 | 1.1 | 15.6 |
|
||||
| 84 | 0.4.0 | | **Check, at each release's scoring run, that seats in a paired ruling agree more often than two scoring runs on near-identical code do, as the paired-ruling decision assumes.** | 2 | 2 | 5 | 4 | 5 | 1.4 | 15.1 |
|
||||
| 67 | 0.4.0 | principle | **Point stability-reviewer at the technical principles in place of its own restatement of them.** | 2 | 3 | 2 | 4 | 5 | 1.3 | 14.9 |
|
||||
| 106 | 0.4.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 | 1 | 1 | 3 | 5 | 1.1 | 14.7 |
|
||||
| 66 | 0.4.0 | principle | **Hold systems-architect's method thresholds only while the comprehension panel finds the flagged code hard.** | 3 | 3 | 4 | 4 | 5 | 1.1 | 14.2 |
|
||||
| 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.** | 3 | 3 | 3 | 4 | 5 | 1.1 | 14.2 |
|
||||
| 132 | 0.4.0 | | **Lift each dimension still under the comprehension floor after release 0.2.0's scoring run, at the places that run names.** | 3 | 5 | 5 | 4 | 5 | 1.1 | 13.7 |
|
||||
| 29 | 0.4.0 | | **Make the contributor a standing member of every project's audience, unless its `## Audience` says maintainability does not matter.** | 2 | 2 | 3 | 3 | 5 | 1.1, 1.4 | 13.4 |
|
||||
| 68 | 0.4.0 | principle | **Test `workflow-bench/compare.py`'s blinding and `bench.py`'s run plan.** | 2 | 4 | 4 | 3 | 5 | 1.1 | 12.9 |
|
||||
| 119 | 0.4.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 | 1 | 1 | 3 | 4 | 1.1 | 12.7 |
|
||||
| 65 | 0.4.0 | | **Archive each judge reply the loop rejects.** | 3 | 4 | 3 | 4 | 5 | 3 | 12.5 |
|
||||
| 82 | 0.4.0 | principle | **Sort `AGENTS.md`'s decision titles and `docs/decisions.md`'s entries by title.** | 1 | 2 | 2 | 3 | 4 | 1.3 | 12.3 |
|
||||
| 73 | 0.4.0 | | **Have each reviewer write its full report to a file and return the worker only its findings' one-line summaries.** | 3 | 4 | 4 | 4 | 4 | 1.4 | 11.7 |
|
||||
| 6 | 0.4.0 | decision | **Move what `loop-claude` writes out of `~/.claude.json`, and ask the human about each write that must stay.** | 5 | 5 | 6 | 4 | 5 | 1.1 | 11.7 |
|
||||
| 51 | 0.4.0 | principle | **Hand loop-claude's terminal output to an injected effect, so no storage or retry function prints.** | 3 | 5 | 5 | 3 | 5 | 1.1 | 11.7 |
|
||||
| 102 | 0.4.0 | | **Give loop-claude's retry delay an environment override, so the black-box test stops replacing `time.sleep` through `sitecustomize`.** | 2 | 2 | 2 | 3 | 4 | 1.1 | 11.4 |
|
||||
| 50 | 0.4.0 | principle | **Grant the bench's runs only the tools a review needs, in place of skipping every permission.** | 2 | 2 | 3 | 3 | 4 | 4 | 9.9 |
|
||||
| 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.** | 2 | 2 | 3 | 3 | 4 | 4 | 9.9 |
|
||||
| 4 | 0.4.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 | 4 | 3 | 3 | 9.6 |
|
||||
| 52 | 0.4.0 | principle | **Record why this checkout lives in Claude Code's own directory, or move it out and link it in.** | 6 | 6 | 4 | 3 | 5 | 2 | 7.5 |
|
||||
| 77 | 0.5.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.** | 3 | 6 | 6 | 6 | 7 | 1.1, 1.4 | 21.4 |
|
||||
| ID | Release | Blocked by | Exempt | Item | R | S | C | Moves | Score |
|
||||
|---|---|---|---|---|---|---|---|---|---|
|
||||
| 115 | 0.2.0 | | question | **Confirm or set how many finished chunks that each shipped one item `score-outcomes` waits for before it shows a score's medians, today 10.** | 1 | 1 | 2 | 1.2 by 5 | 7.3 |
|
||||
| 140 | 0.2.0 | | | **Split `docs/decisions.md` → `routing: one ladder` into one entry per decision, so a reader finds the rules for the ladder, the worker's rung, the routing figures and delegation by their titles.** | 1 | 2 | 1 | 1.1 by 4, 1.4 by 4 | 10.9 |
|
||||
| 67 | 0.2.0 | | principle | **Point stability-reviewer at the technical principles in place of its own restatement of them.** | 2 | 3 | 2 | 1.1 by 5 | 6.8 |
|
||||
| 146 | 0.2.0 | | decision | **Score R as L + E + I − 2 from anchored levels, at least 7 at I5 and 5 at I4, with L, E and I in their own columns and `rank_todo.py` computing R, drop C, and route a task's model and effort on its R alone.** | 6 | 7 | 7 | 1.1 by 8, 1.2 by 8, 1.4 by 8 | 2.8 |
|
||||
| 152 | 0.2.0 | 146 | decision | **Anchor each score level in `rules/todo-items.md` with words, and each project's with two or three items it shipped, and have a scorer compare a new item against them.** | 2 | 4 | 3 | 1.1 by 7 | 6.4 |
|
||||
| 50 | 0.2.0 | | principle | **Grant the bench's runs only the tools a review needs, in place of skipping every permission.** | 2 | 2 | 3 | 1.1 by 3 | 5.5 |
|
||||
| 65 | 0.2.0 | | defect | **Archive each judge reply the loop rejects.** | 3 | 4 | 3 | 3 by 3 | 5.5 |
|
||||
| 84 | 0.2.0 | | | **Check, at each release's scoring run, that seats in a paired ruling agree more often than two scoring runs on near-identical code do, as the paired-ruling decision assumes.** | 2 | 2 | 5 | 1.4 by 5 | 4.6 |
|
||||
| 153 | 0.2.0 | | decision | **Run the judge on the rung the highest R + C in its chunk picks, an item the worker takes in included.** | 2 | 3 | 4 | 1.2 by 5 | 4.6 |
|
||||
| 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 | 4 | 4 | 1.4 by 4 | 1.8 |
|
||||
| 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 | 1 | 1 | 2 by 4 | 17.5 |
|
||||
| 21 | 0.3.0 | | defect | **Give `settings.json`'s model one writer, and sort its keys.** | 3 | 3 | 4 | 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 | 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 | 1 | 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 | 1 | 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 | 1 | 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 | 4 | 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 | 4 | 5 | 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 | 2 | 2 | 1.1 by 6 | 10.9 |
|
||||
| 82 | 0.3.0 | | principle | **Sort `AGENTS.md`'s decision titles and `docs/decisions.md`'s entries by title.** | 1 | 2 | 2 | 1.1 by 4, 1.4 by 4 | 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.** | 2 | 2 | 3 | 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 | 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 | 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 | 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 | 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.** | 2 | 2 | 3 | 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 | 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 | 1 | 1 | 1.1 by 5 | 10.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.** | 2 | 3 | 3 | 1.1 by 5, 1.4 by 5 | 10.3 |
|
||||
| 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.** | 1 | 3 | 4 | 1.1 by 5, 1.4 by 5 | 10.3 |
|
||||
| 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.** | 3 | 3 | 3 | 1.1 by 7 | 9.6 |
|
||||
| 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 | 2 | 2 | 1.1 by 5 | 9.1 |
|
||||
| 110 | 0.4.0 | | | **Count, for each finished chunk, the later changes that fixed code it wrote, and show them beside its guessed E.** | 2 | 4 | 6 | 1.1 by 6, 1.4 by 6 | 8.2 |
|
||||
| 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.** | 2 | 3 | 5 | 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 | 3 | 3 | 1.1 by 4, 1.4 by 4 | 8.2 |
|
||||
| 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.** | 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.** | 2 | 5 | 3 | 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.** | 2 | 2 | 3 | 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`.** | 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.** | 3 | 3 | 4 | 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.** | 3 | 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 | 3 | 5 | 1.1 by 5 | 6.8 |
|
||||
| 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 | 4 | 6 | 1.1 by 5, 1.4 by 5 | 6.8 |
|
||||
| 121 | 0.4.0 | | | **Check that `bin/round_titles.py`'s `PASSES` lists exactly the passes of larv-review §3's table.** | 1 | 3 | 2 | 1.1 by 5 | 6.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.** | 3 | 4 | 4 | 1.1 by 5, 1.4 by 5 | 6.8 |
|
||||
| 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 | 1.1 by 3 | 5.5 |
|
||||
| 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.** | 2 | 4 | 3 | 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 | 3 | 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.** | 3 | 3 | 4 | 1.1 by 4 | 5.5 |
|
||||
| 156 | 0.5.0 | | decision | **Drop `rank_todo.py`'s ranking of an old-shape table once no project under `~/code` holds one.** | 2 | 3 | 2 | 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 | 4 | 4 | 1.1 by 5 | 4.6 |
|
||||
| 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.** | 3 | 3 | 5 | 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.** | 3 | 5 | 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 | 5 | 5 | 1.1 by 5, 1.4 by 5 | 4.1 |
|
||||
| 155 | 0.5.0 | | | **Lower the reading cost of the files a chunk reads most before its first commit.** | 2 | 3 | 4 | 1.4 by 6 | 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.** | 3 | 6 | 3 | 1.1 by 9, 1.4 by 9 | 4.1 |
|
||||
| 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.** | 3 | 5 | 2 | | 0.0 |
|
||||
| 5 | 0.6.0 | | decision | **Key a project on its checkout's full path, and refuse to start while another session uses that key.** | 5 | 5 | 7 | 1.1 by 6 | 3.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.** | 3 | 6 | 6 | 1.1 by 7, 1.4 by 7 | 3.2 |
|
||||
| 6 | 0.6.0 | | decision | **Move what `loop-claude` writes out of `~/.claude.json`, and ask the human about each write that must stay.** | 5 | 5 | 6 | 1.1 by 5 | 2.7 |
|
||||
| 51 | 0.6.0 | | principle | **Hand loop-claude's terminal output to an injected effect, so no storage or retry function prints.** | 3 | 5 | 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 | 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.** | 6 | 6 | 4 | 1.1 by 4 | 1.2 |
|
||||
|
||||
## Details
|
||||
|
||||
### 145. Run the stability reviewer on the worker's rung while the worker runs below the project's rung, once a replay of past stability rounds on that rung finds the 🔴 and 🟡 findings on record.
|
||||
|
||||
On 2026-10-15 the human proposed running the stability reviewer on the worker's rung; the replay gate is the agent's proposal. Today a worker below the project's rung launches every reviewer on the project's rung. Under this item, the stability reviewer runs on the worker's rung instead. Every other reviewer, the comprehension seats and the security pass's subagent stay on the project's rung, so a change that fires their triggers is still reviewed on that rung.
|
||||
|
||||
The stability pass is the only one that mutation-tests the changed lines, so a defect it misses may merge. Before the switch, replay archived stability rounds on each rung below the project's, as `bin/judge-replay` does for the judge. Route the reviewer onto a rung only where it finds every 🔴 and 🟡 on record that a replay on the project's rung also finds. A rung that misses one keeps the reviewer on the project's rung. In the judge's replay on 2026-10-15, Haiku 5.5 at xhigh missed 7 of 31 verdicts, Sonnet 5.5 at high missed 3 interrupts, and Opus 5.5 at medium missed none.
|
||||
|
||||
This revises `docs/decisions.md` → `routing: one ladder`.
|
||||
|
||||
### 143. Resume a worker one rung up in the next cycle when its run ends asking for a higher rung and the judge finds the escalation trigger it cites in the transcript.
|
||||
|
||||
The human asked for this on 2026-10-15. A worker may end its run asking for a higher rung, citing an escalation trigger of `CLAUDE.md` → "Working with the codebase". The judge looks for that trigger in the transcript. Where it finds it, the next cycle resumes the session one rung up; otherwise the rung holds. The worker never steps down within a chunk, and goes at most two rungs above the rung it started the chunk on unless the human agrees.
|
||||
|
||||
This revises `docs/decisions.md` → `routing: one ladder`, where the worker steps up only after every second unfinished verdict or when the judge reports a taken-in item that picks a higher rung. This item adds a third way.
|
||||
|
||||
The comprehension seats found two places it touches hard to read. Word the new check so that `bin/loop_claude/cycle/judge.py`'s `JUDGE_RULES` gets easier to read. `bin/loop_claude/routing.py`'s `kept` and `stepped` use different floors, and `stepped` does two jobs; make them easier to read where the new step joins them.
|
||||
|
||||
### 136. Route a chunk on the item its worker says it takes, in place of the next release's first row.
|
||||
|
||||
loop-claude routes on the first row of the next release, while the worker takes the item the plan's prose orders first, or a prerequisite, as the chunk that shipped item 88, a prerequisite, took item 88 in place of the first row. A first row of higher R + C pays for a dearer rung all chunk; one of lower R + C holds until the judge reports the item taken in. The judge reports the item the worker takes only after the first cycle, so routing the first cycle right needs the item before the worker starts.
|
||||
|
||||
Once this lands, the judge follows the item the worker takes too, since `judge_rung` routes on the chunk's item.
|
||||
|
||||
### 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.
|
||||
|
||||
### 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.
|
||||
|
||||
### 110. Count, for each finished chunk, the later changes that fixed code it wrote, and show them beside its guessed R.
|
||||
|
||||
`score-outcomes` measures R only by the 🔴 findings review caught. A serious bug review missed shows later, as a change that fixes code the chunk wrote.
|
||||
|
||||
### 115. Confirm or set how many finished chunks that each shipped one item `score-outcomes` waits for before it shows a score's medians, today 10.
|
||||
|
||||
`ENOUGH` in `bin/score_outcomes/outcomes.py` matches the 10 figures the reading-cost trend waits for. No published standard sets either, and `CLAUDE.md` → "Web research" asks the human for a threshold a consumer relies on.
|
||||
|
||||
### 116. Report R by the share of chunks with a 🔴, once 10 chunks that each shipped one item record finding counts and most record no 🔴.
|
||||
### 140. Split `docs/decisions.md` → `routing: one ladder` into one entry per decision, so a reader finds the rules for the ladder, the worker's rung, the routing figures and delegation by their titles.
|
||||
|
||||
`score-outcomes` reports R as the median 🔴 count at each guessed R. Where most chunks have no 🔴, every median reads 0 and tells a scorer nothing. No round title held counts before PR #254, so how often a chunk has a 🔴 is not yet known.
|
||||
The entry holds 7 paragraphs under one title of about 70 words chaining three decisions: the ladder and bands, the worker below the project's rung with its reviewers, the routing figures and calls, delegation, and when the worker changes rung. A reader after one rule reads the whole entry. The prose pass of the chunk that split out the judge's rung asked for the rest. Once split, the delegation entry's title names the floor that `todo.md: only a session or subagent on the project's rung or above scores or reshapes the plan…` puts under a subagent that files or scores items.
|
||||
|
||||
### 111. Measure the chunks of a project that merges by squash or fast-forward, which `score-outcomes` skips today.
|
||||
### 67. Point stability-reviewer at the technical principles in place of its own restatement of them.
|
||||
|
||||
`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.
|
||||
DRY, in `principles/technical-principles.md`: `agents/stability-reviewer.md` restates principles in its own words, and the copy has drifted: it asks for "properly randomised UUIDs" where the principle requires UUID v7.
|
||||
|
||||
### 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.
|
||||
### 146. Score R as L + E + I − 2 from anchored levels, at least 7 at I5 and 5 at I4, with L, E and I in their own columns and `rank_todo.py` computing R, drop C, and route a task's model and effort on its R alone.
|
||||
|
||||
`score-outcomes` grounds R, S and C in finished chunks only. Where an item names files or units, their size bounds what the change can touch.
|
||||
Each level is about ×10 of a real quantity; `docs/decisions.md` → `todo.md: …` says why. The anchors, for `rules/todo-items.md`:
|
||||
|
||||
### 118. Have `score-outcomes` count review rounds only from chunks merged after 2026-10-13, when review passes were narrowed, so C's medians compare chunks reviewed under one rule.
|
||||
| Level | L — chance the change holds a defect | E — chance the defect escapes | I — damage, worst of availability, data, secrets, reach and reversibility |
|
||||
|---|---|---|---|
|
||||
| 1 | S 1–2, and nothing new | a test or the gate fails on it | one person's tooling or something cosmetic; a revert fixes it in minutes |
|
||||
| 2 | S 3–5, in one component, a pattern the repo already has | only review or a manual check sees it | one feature or service degraded; a revert within the hour |
|
||||
| 3 | one of: S 6 or more, several components, a new tool or pattern, live config or state | nothing checks it before users hit it | a service down, or every consumer affected; hours to restore |
|
||||
| 4 | two or more of level 3's, or a rewrite of code with known defects | — | everything down, a backup restore, or a secret or PII exposed |
|
||||
| 5 | — | — | irreversible: data lost for good, or a one-way door |
|
||||
|
||||
Since 2026-10-13 (`docs/decisions.md` → "review: stability and product-owner report only…"), reviewers report fewer findings and later rounds review only the answers to earlier ones, to cut rounds. A chunk merged before that date took more rounds for the same C, so mixing both eras skews C's medians.
|
||||
`rank_todo.py` ranks a table with C and without L, E and I until its project reshapes it, and says so, as it does for the old shape since PR #283, so no project's commits stop the day this lands. Reshaping is then that project's only work until done, as `CLAUDE.md` → "Working loop" says.
|
||||
|
||||
### 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.
|
||||
C goes in the same chunk, so no reshaped table meets bands built for R + C: R alone runs 1 to 10, and the R + C bands would step most tasks well down the ladder. The bands (`docs/decisions.md` → `routing: one ladder…`) become bands over R, spread across the R values the rescored plans hold. The bands are the human's call, so the chunk proposes them and waits, and puts one option beside them: the worker routed on L and its reviewers on E + I, since impact makes a task riskier, not harder. `CLAUDE.md`'s delegation rule, `subagent-rung` and its `--plan`, loop-claude's chunk routing and prompts, the judge's rung, escalation trigger 1 and `score-outcomes` drop C. The routing decision's "S never moves a rung" no longer holds, since size sets L, so the chunk revises it. Once it merges, append a `Reset` to `routing-calls-raised.md`, as `AGENTS.md` says of a band change, so the routing figures count only chunks routed on R.
|
||||
|
||||
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.
|
||||
### 152. Anchor each score level in `rules/todo-items.md` with words, and each project's with two or three items it shipped, and have a scorer compare a new item against them.
|
||||
|
||||
### 121. Check that `bin/round_titles.py`'s `PASSES` lists exactly the passes of larv-review §3's table.
|
||||
LLM ratings drift to the middle of an unanchored scale, and worked examples cut estimation error. A project's anchors are shipped items, cited by ID and commit, chosen from what `score-outcomes` measured for them.
|
||||
|
||||
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.
|
||||
### 50. Grant the bench's runs only the tools a review needs, in place of skipping every permission.
|
||||
|
||||
### 122. 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.
|
||||
"Always grant explicit access to data", in `principles/technical-principles.md`: `workflow-bench/bench.py` starts claude with `--dangerously-skip-permissions`, and no rule confines it to a sandbox, so a run on the host reaches the host's credentials and other checkouts.
|
||||
|
||||
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.
|
||||
### 65. Archive each judge reply the loop rejects.
|
||||
|
||||
### 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.
|
||||
A defect: goal 3, keeping unattended runs' transcripts backed up, does not hold while a rejected judge reply reaches only stderr. Raised by the principles audit of PR #215: the judge runs with `--no-session-persistence`, so the archive cannot answer the 3am question of why the loop rejected a verdict.
|
||||
|
||||
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.
|
||||
### 84. Check, at each release's scoring run, that seats in a paired ruling agree more often than two scoring runs on near-identical code do, as the paired-ruling decision assumes.
|
||||
|
||||
### 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.
|
||||
Raised by the principles audit of PR #228: the `review: the comprehension check records …` entry in `docs/decisions.md` is valid only while that holds, and `docs/comprehension-history.md` keeps every vote, yet nothing reads the agreement rate. Scoring runs on near-identical code are rare now, so compare with those already in the history, such as PR #224's and PR #225's, or make a second run for the check.
|
||||
|
||||
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.
|
||||
### 153. Run the judge on the rung the highest R + C in its chunk picks, an item the worker takes in included.
|
||||
|
||||
The judge reports the R + C of an item the worker takes in, and `routing.stepped` lifts the worker to the rung it picks, but `judge_rung` reads only the routed item's R + C, which the archived route line holds. So when the worker takes in a harder item, the judge stays on a lower rung than the work, where a missed interrupt lets the worker settle a decision that is lilleman's (goal 1.2). The route must carry the highest R + C taken in, archived so a rerun keeps it.
|
||||
|
||||
### 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.
|
||||
|
||||
### 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.
|
||||
|
||||
### 127. Define seat, place, paired ruling, scoring run and the judge's records in `CLAUDE.md` → "Vocabulary".
|
||||
|
||||
Two seats of PR #257's scoring run assembled these terms from four files: `bin/larv_review/main.py`'s help, `skills/larv-review/SKILL.md:99`, `bin/comprehension_history.py:82` and `skills/comprehension-panel/seat-prompts.md`. "Records" is defined only in a comment at `bin/loop_claude/project/records.py:6`.
|
||||
|
||||
### 125. Give "record", "outcome" and "places" one meaning each across `bin/`, and rename `bin/larv_review/git.py` by what it holds.
|
||||
### 129. Explain `bin/rule_hook/rules.py`'s `OVERRIDE` pattern beside it: why the reason is lazy, what the lookahead splits and why `-->` is stripped.
|
||||
|
||||
Shape is the lowest dimension, so this item goes before 0.3.0's other items, per `docs/decisions.md` → `larv-review: a project lifting itself to the comprehension floor starts at the lowest dimension`.
|
||||
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.
|
||||
|
||||
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.
|
||||
### 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.
|
||||
|
||||
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 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.
|
||||
|
||||
### 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.
|
||||
|
||||
### 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.
|
||||
|
||||
The comprehension seats on PR #254 found `items` returning a list, None or a Failure, and `larv_review/plan.py` `plan_reasons` reading None through `items(before) or []`, which works only because a Failure is truthy.
|
||||
|
||||
### 126. State when work has landed towards a release once, in `bin/larv_review/plan.py`, and have larv-review's help point to it.
|
||||
|
||||
@@ -186,25 +203,41 @@ 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.
|
||||
|
||||
### 140. Split `docs/decisions.md` → `routing: one ladder` into one entry per decision, so a reader finds the rules for the ladder, the worker's rung, the routing figures and delegation by their titles.
|
||||
### 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.
|
||||
|
||||
The entry holds 7 paragraphs under one title of about 70 words chaining three decisions: the ladder and bands, the worker below the project's rung with its reviewers, the routing figures and calls, delegation, and when the worker changes rung. A reader after one rule reads the whole entry. The prose pass of the chunk that split out the judge's rung asked for the rest. Once split, the delegation entry's title names the floor that `todo.md: only a session or subagent on the project's rung or above scores or reshapes the plan…` puts under a subagent that files or scores items.
|
||||
`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.
|
||||
|
||||
### 114. Run git through `git_repo.py` in `rule_hook`, `metric_bench`, `reading_cost` and `loop_claude`, keeping rule-hook's guards as an option, so one module owns how a tool runs git.
|
||||
### 157. Split `docs/decisions.md` → `todo.md: one table of items …`'s 2026-10-02 paragraph into one paragraph per choice.
|
||||
|
||||
Shape is the lowest dimension, so this item goes before 0.3.0's other items, per `docs/decisions.md` → `larv-review: a project lifting itself to the comprehension floor starts at the lowest dimension`.
|
||||
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.
|
||||
|
||||
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. The inherited architect of PR #257's scoring run named `bin/git_repo.py:8` `git` again. Make `git_repo.git` easier to read.
|
||||
### 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.
|
||||
|
||||
### 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.
|
||||
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.
|
||||
|
||||
The comprehension seats on PR #254 found `items` returning a list, None or a Failure, and `larv_review/plan.py` `plan_reasons` reading None through `items(before) or []`, which works only because a Failure is truthy.
|
||||
### 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.
|
||||
|
||||
### 124. Group the shared modules at `bin/`'s root into packages named by purpose, so the root holds only launchers and stand-alone tools.
|
||||
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.
|
||||
|
||||
Shape is the lowest dimension, so this item goes before 0.3.0's other items, per `docs/decisions.md` → `larv-review: a project lifting itself to the comprehension floor starts at the lowest dimension`.
|
||||
### 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.
|
||||
|
||||
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, and the comprehension history with round titles. The `.gitignore` allowlist and README follow the move.
|
||||
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.
|
||||
|
||||
### 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' C. Each project states its own; the human sets the first value per project. Nothing is deleted by score.
|
||||
|
||||
### 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 risk as the median 🔴 count at each guessed R; after item 146, the part of R a 🔴 tests is L. Where most chunks have no 🔴, every median reads 0 and tells a scorer nothing. No round title held counts before PR #254, so how often a chunk has a 🔴 is not yet known.
|
||||
|
||||
### 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 (item 146).
|
||||
|
||||
### 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.
|
||||
|
||||
@@ -214,63 +247,19 @@ Mid A of PR #257's scoring run named `bin/larv_review/ruling.py:8` `votes`. It c
|
||||
|
||||
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 R + C nor highest. Make `bin/loop_claude/loop/main.py`'s `run_loop` easier to read where it threads the route.
|
||||
|
||||
### 129. Explain `bin/rule_hook/rules.py`'s `OVERRIDE` pattern beside it: why the reason is lazy, what the lookahead splits and why `-->` is stripped.
|
||||
### 125. Give "record", "outcome" and "places" one meaning each across `bin/`, and rename `bin/larv_review/git.py` by what it holds.
|
||||
|
||||
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.
|
||||
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`.
|
||||
|
||||
### 135. Fingerprint only the modules loop-claude imports, so editing another tool's code no longer reloads a running loop.
|
||||
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.
|
||||
|
||||
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.
|
||||
### 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.
|
||||
|
||||
### 1. Say in README → Install how the transcript archive is backed up, once bender-infra backs up ai-sandbox's data volume.
|
||||
"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.
|
||||
|
||||
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.
|
||||
### 102. Give loop-claude's retry delay an environment override, so the black-box test stops replacing `time.sleep` through `sitecustomize`.
|
||||
|
||||
2026-10-02, the human: ai-sandbox is the VM `loop-claude` will run on, hosted on the server bender. bender-infra, the infrastructure-as-code project that manages bender, will back up ai-sandbox's data volume once ai-sandbox is rebuilt. The item waits for the human to say the rebuild has landed; do not remind them. Before writing the README line, check that `~/.claude` lives on that volume and that the backup is private and encrypted at rest.
|
||||
|
||||
The README line covers the bench's transcripts in `workflow-bench/logs/` too (goal 3).
|
||||
|
||||
### 21. Give `settings.json`'s model one writer, and sort its keys.
|
||||
|
||||
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.
|
||||
|
||||
### 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.
|
||||
|
||||
### 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.
|
||||
|
||||
### 80. State in README → Install that every machine taking this checkout must be a sandbox, as `settings.json`'s auto mode assumes.
|
||||
|
||||
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`, so a new machine is never told.
|
||||
|
||||
### 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.
|
||||
|
||||
### 84. Check, at each release's scoring run, that seats in a paired ruling agree more often than two scoring runs on near-identical code do, as the paired-ruling decision assumes.
|
||||
|
||||
Raised by the principles audit of PR #228: the `review: the comprehension check records …` entry in `docs/decisions.md` is valid only while that holds, and `docs/comprehension-history.md` keeps every vote, yet nothing reads the agreement rate. Scoring runs on near-identical code are rare now, so compare with those already in the history, such as PR #224's and PR #225's, or make a second run for the check.
|
||||
|
||||
### 67. Point stability-reviewer at the technical principles in place of its own restatement of them.
|
||||
|
||||
DRY, in `principles/technical-principles.md`: `agents/stability-reviewer.md` restates principles in its own words, and the copy has drifted: it asks for "properly randomised UUIDs" where the principle requires UUID v7.
|
||||
|
||||
### 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.
|
||||
Found by the principles audit of PR #242. `bin/loop_claude/test_black_box.py:113-114` swaps the global `time.sleep`, the shape "Functional core, imperative shell" bans. An override of the delay lets the test run the code as production runs it.
|
||||
|
||||
### 66. Hold systems-architect's method thresholds only while the comprehension panel finds the flagged code hard.
|
||||
|
||||
@@ -280,70 +269,83 @@ KISS, in `principles/technical-principles.md`, which keeps a limit only while re
|
||||
|
||||
Found by the principles audit of PR #242, against "Functional core, imperative shell" (`principles/technical-principles.md`). `bin/larv_review/record.py:67` reads `time.time()`, then checks git (`:70`, `commit_exists`) and the history file (`:75`) inside the function that parses the seats file and decides. A test cannot fix the heading's time, and every test of `read_seats` touches the real checkout.
|
||||
|
||||
### 132. Lift each dimension still under the comprehension floor after release 0.2.0's scoring run, at the places that run names.
|
||||
### 111. Measure the chunks of a project that merges by squash or fast-forward, which `score-outcomes` skips today.
|
||||
|
||||
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.
|
||||
`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.
|
||||
|
||||
### 29. Make the contributor a standing member of every project's audience, unless its `## Audience` says maintainability does not matter.
|
||||
### 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.
|
||||
|
||||
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.
|
||||
`score-outcomes` grounds R, S and C in finished chunks only. Where an item names files or units, their size bounds what the change can touch.
|
||||
|
||||
### 68. Test `workflow-bench/compare.py`'s blinding and `bench.py`'s run plan.
|
||||
### 121. Check that `bin/round_titles.py`'s `PASSES` lists exactly the passes of larv-review §3's table.
|
||||
|
||||
"Most, if not all, code should have automated tests", in `principles/technical-principles.md`: `compare.blind()` keeps the comparison blind, and a version name it misses invalidates the bench silently.
|
||||
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.
|
||||
|
||||
### 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.
|
||||
### 122. 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.
|
||||
|
||||
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.
|
||||
|
||||
### 65. Archive each judge reply the loop rejects.
|
||||
|
||||
Goal 3, raised by the principles audit of PR #215: the judge runs with `--no-session-persistence`, and the first two rejected replies reach only stderr, so the archive cannot answer the 3am question of why the loop rejected a verdict.
|
||||
|
||||
### 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.
|
||||
|
||||
### 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.
|
||||
|
||||
### 6. Move what `loop-claude` writes out of `~/.claude.json`, and ask the human about each write that must stay.
|
||||
|
||||
Claude Code owns that file and writes it. `trust` reads it, changes it and writes it back, so a write that lands in between is lost.
|
||||
|
||||
### 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.
|
||||
|
||||
### 102. Give loop-claude's retry delay an environment override, so the black-box test stops replacing `time.sleep` through `sitecustomize`.
|
||||
|
||||
Found by the principles audit of PR #242. `bin/loop_claude/test_black_box.py:113-114` swaps the global `time.sleep`, the shape "Functional core, imperative shell" bans. An override of the delay lets the test run the code as production runs it.
|
||||
|
||||
### 50. Grant the bench's runs only the tools a review needs, in place of skipping every permission.
|
||||
|
||||
"Always grant explicit access to data", in `principles/technical-principles.md`: `workflow-bench/bench.py` starts claude with `--dangerously-skip-permissions`, and no rule confines it to a sandbox, so a run on the host reaches the host's credentials and other checkouts.
|
||||
|
||||
### 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.
|
||||
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.
|
||||
|
||||
### 4. Name each chunk's archive folder by the chunk's start time, so `<key>/` lists chunks in the order they ran.
|
||||
|
||||
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.
|
||||
|
||||
### 52. Record why this checkout lives in Claude Code's own directory, or move it out and link it in.
|
||||
### 12. Run the test suite in CI on every PR, or record in `docs/decisions.md` why the local run is enough.
|
||||
|
||||
"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.
|
||||
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.
|
||||
|
||||
### 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.
|
||||
|
||||
### 68. Test `workflow-bench/compare.py`'s blinding and `bench.py`'s run plan.
|
||||
|
||||
"Most, if not all, code should have automated tests", in `principles/technical-principles.md`: `compare.blind()` keeps the comparison blind, and a version name it misses invalidates the bench silently.
|
||||
|
||||
### 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.
|
||||
|
||||
### 155. Lower the reading cost of the files a chunk reads most before its first commit.
|
||||
|
||||
`bin/reading-cost` on 2026-10-16: the last 5 chunks' median is 133254 new input tokens before their first commit, the 5 before them 120770. Read most over the last 5, by opens and searches: `todo.md` 30, `README.md` 18, `docs/decisions.md` 17, `bin/loop_claude/test_loop_claude.py` 11, `CHANGELOG.md` 9, `skills/larv-review/SKILL.md` 9, `bin/loop_claude/cycle/prompts.py` 8, `CLAUDE.md` 6, `AGENTS.md` 4, `bin/loop_claude/cycle/judge.py` 4. The chunk that ships this item runs `bin/reading-cost --reset`.
|
||||
|
||||
### 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.
|
||||
|
||||
### 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.
|
||||
|
||||
2026-10-02, the human: ai-sandbox is the VM `loop-claude` will run on, hosted on the server bender. bender-infra, the infrastructure-as-code project that manages bender, will back up ai-sandbox's data volume once ai-sandbox is rebuilt. The item waits for the human to say the rebuild has landed; do not remind them. Before writing the README line, check that `~/.claude` lives on that volume and that the backup is private and encrypted at rest.
|
||||
|
||||
The README line covers the bench's transcripts in `workflow-bench/logs/` too (goal 3).
|
||||
|
||||
### 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.
|
||||
|
||||
@@ -374,3 +376,19 @@ Claude's misses ranked the named units at a coin toss. Top k scores 0.50 by chan
|
||||
| Change spread | 0.57 | 0.54 |
|
||||
|
||||
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.
|
||||
|
||||
### 6. Move what `loop-claude` writes out of `~/.claude.json`, and ask the human about each write that must stay.
|
||||
|
||||
Claude Code owns that file and writes it. `trust` reads it, changes it and writes it back, so a write that lands in between is lost.
|
||||
|
||||
### 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.
|
||||
|
||||
### 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