Compare commits
146 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 525f9ccb9d | |||
| 0c98931df0 | |||
| 4a1ffd17e0 | |||
| bbd56306b5 | |||
| 3070f09663 | |||
| e705fd8867 | |||
| d5a9576fff | |||
| c8c3702eb8 | |||
| 6a617f5a2c | |||
| 3f7f4e74fc | |||
| 7b10fd6e58 | |||
| d97846c60e | |||
| 0a26bcb807 | |||
| 9a260d22c0 | |||
| 14e6756a53 | |||
| 7e29dc0014 | |||
| 95fb0d03cf | |||
| 5c37027046 | |||
| 9066f477a4 | |||
| 41e91e341c | |||
| 913accfe14 | |||
| fba48f324c | |||
| 62faf321ce | |||
| 76348eac2e | |||
| 8f8d340c09 | |||
| a4fc833b2b | |||
| 59a8fe9f45 | |||
| 74f3199df1 | |||
| d2ca49bf00 | |||
| e3a6ae0e42 | |||
| bad2f0c555 | |||
| d81da4d413 | |||
| 545a57f01c | |||
| 4ab80160b6 | |||
| 2fa7040006 | |||
| 18a73b1bf1 | |||
| 6156e0b9cc | |||
| 08d4be4bae | |||
| b2ddebce7a | |||
| a61afc567d | |||
| 1f31ebd8ac | |||
| b03bfab121 | |||
| 2294916343 | |||
| c010b12c5a | |||
| 6ff139f67c | |||
| 7b0e428eec | |||
| dd7e9b9929 | |||
| 02bde923e5 | |||
| 87ffd81d21 | |||
| 2770de2744 | |||
| 058f4ca7aa | |||
| d55b1e4ad5 | |||
| 4fc822c346 | |||
| cbe99537e2 | |||
| fa54ed46b1 | |||
| 72d9a9f652 | |||
| d449c552c6 | |||
| 67e272d5ef | |||
| ec0b17b03f | |||
| 1fc7bf0f52 | |||
| 3c4cedd389 | |||
| 8dc82fcf95 | |||
| 1f8b33d485 | |||
| 1d1172098f | |||
| 58133e69fe | |||
| 37f19d1677 | |||
| 22942308f6 | |||
| eaa67bfcd9 | |||
| c04864b6f0 | |||
| 90773cfa5f | |||
| f299bf332b | |||
| 876e0afb45 | |||
| 6e2656d83d | |||
| 2ab44beca2 | |||
| 0d32cab386 | |||
| e86a0cbc0c | |||
| e4e3d8cff0 | |||
| b19ecc459e | |||
| afba2d0bbb | |||
| bf0f0c5ecf | |||
| 9efcdab4f8 | |||
| 9439d7ec5c | |||
| 0ca23f5612 | |||
| 7b93108618 | |||
| ed914030f8 | |||
| 34689413ac | |||
| 5ccb51f763 | |||
| 4132d8cf18 | |||
| 0d05c9b2d8 | |||
| 9bc6abdf91 | |||
| 2db70062dc | |||
| 35911bde8f | |||
| 4adcadcddb | |||
| 2922d70a45 | |||
| 9196aeb5c7 | |||
| 07aa4b9f83 | |||
| 9c11fefe45 | |||
| 384b1bbc63 | |||
| 4c971a7cc4 | |||
| 348abfec59 | |||
| 2556fdace9 | |||
| 6817b074bd | |||
| 46436f2ee0 | |||
| e1e99645be | |||
| 45fd66d3ab | |||
| 66b9651d68 | |||
| 7a7dc4b75d | |||
| 39a8a57b76 | |||
| 58517a0c54 | |||
| c61997f7b7 | |||
| 75c9c2718a | |||
| 1a60de25ab | |||
| 304a2ea988 | |||
| 79f6334c7f | |||
| 4ab5b629ea | |||
| afcd6801a1 | |||
| 46803b7e81 | |||
| 042f48a0f4 | |||
| e0634e52bb | |||
| 595e2f8c4b | |||
| 70cb7bd1be | |||
| c1f08668b7 | |||
| 05806b517d | |||
| 93c81c48ab | |||
| a713fd6a88 | |||
| 6e67cc59fa | |||
| 071d6cf1cd | |||
| 8e46ef69b1 | |||
| 968cc37661 | |||
| 2ca4d0f8db | |||
| 4d132e9a3c | |||
| 3f1967a24f | |||
| d2d5e10e19 | |||
| b6c14ba223 | |||
| 313e129b20 | |||
| 23af106b47 | |||
| aacfe7d3d3 | |||
| a0b8cf7882 | |||
| f5201cb638 | |||
| 14ae30a731 | |||
| f10170bf8b | |||
| 5588270e43 | |||
| b1037248a5 | |||
| c9514fe8b4 | |||
| 079c651105 | |||
| 9da3431e25 |
+16
@@ -64,6 +64,9 @@
|
||||
!bin/loop_state/**/*.py
|
||||
!bin/machine_load/
|
||||
!bin/machine_load/*.py
|
||||
!bin/mattermost-dm
|
||||
!bin/mattermost_dm/
|
||||
!bin/mattermost_dm/*.py
|
||||
!bin/metric-bench
|
||||
!bin/metric_bench/
|
||||
!bin/metric_bench/*.py
|
||||
@@ -93,10 +96,13 @@
|
||||
!bin/rule_hook/
|
||||
!bin/rule_hook/*.py
|
||||
!bin/run-heavy
|
||||
!bin/run-tests
|
||||
!bin/run_heavy/
|
||||
!bin/run_heavy/*.py
|
||||
!bin/run_heavy/path_entry/
|
||||
!bin/run_heavy/path_entry/docker
|
||||
!bin/run_tests/
|
||||
!bin/run_tests/*.py
|
||||
!bin/rung_replay/
|
||||
!bin/rung_replay/*.py
|
||||
!bin/score-outcomes
|
||||
@@ -114,6 +120,9 @@
|
||||
!bin/todo_item/*.py
|
||||
!bin/transcript_archive/
|
||||
!bin/transcript_archive/*.py
|
||||
!bin/wait-for
|
||||
!bin/wait_for/
|
||||
!bin/wait_for/*.py
|
||||
!docs/
|
||||
!docs/*.md
|
||||
!judge-field-trials/
|
||||
@@ -140,12 +149,19 @@
|
||||
!skills/larv-review/*.md
|
||||
!skills/larv-review/standards/
|
||||
!skills/larv-review/standards/*.md
|
||||
!stability-skip-count/
|
||||
!stability-skip-count/README.md
|
||||
!stability-skip-count/count.py
|
||||
!workflow-bench/
|
||||
!workflow-bench/advisor-judge-prompt.md
|
||||
!workflow-bench/advisor-run-prompt.md
|
||||
!workflow-bench/advisor_bench.py
|
||||
!workflow-bench/bench.py
|
||||
!workflow-bench/compare-prompt.md
|
||||
!workflow-bench/compare.py
|
||||
!workflow-bench/review_git.py
|
||||
!workflow-bench/run-prompt.md
|
||||
!workflow-bench/setup.cfg
|
||||
!workflow-bench/test_advisor_bench.py
|
||||
!workflow-bench/test_bench.py
|
||||
!workflow-bench/test_review_git.py
|
||||
|
||||
@@ -2,6 +2,31 @@
|
||||
|
||||
## Unreleased
|
||||
|
||||
- larv-review takes an item as a floor item only where its tagline opens with `Reach the comprehension floor:`. A tagline that quotes the floor elsewhere, such as in a decision title, no longer makes its chunk due a scoring run. Reword each open floor item's tagline in every project's `todo.md` to open with the phrase.
|
||||
|
||||
## 0.9.0
|
||||
|
||||
- larv-review skips stability round 2 where round 1 reported a 🔴 and every 🔴 and 🟡 asked only that a named mutant be killed or a named failing test pass, once the tests and the mutation command run clean on the fixes.
|
||||
- `review-replay` now qualifies a rung whose share of a pass's archived findings is no more than 10 points below the mean of two replays on the project's rung, over at least 8 rounds, where it misses no 🔴 that both found. It used to demand every finding the project's rung found again, which the project's rung itself failed. It tries the project's model at each lower effort first, then the ladder below. Its run on the prose pass of Opus 5.5 projects qualified no rung: Opus 5.5 at low effort found 49% against a bar of 66%.
|
||||
- loop-claude records beside each verdict, interrupt and quoted answer the claude-config release and commit that ran it, the tokens the worker, each subagent and the judge spent, by model and kind, with the list prices in force, and any typed answer of yours the judge quotes as reversing a choice the worker took on its own recommendation; `score-outcomes` counts those reversals per finished chunk.
|
||||
- `larv-review prepare-scoring` makes a scoring run's worktree and writes each seat's prompt; `record-scoring` removes both once it has recorded the run.
|
||||
- `deploy-release` moves a checkout whose `settings.json` differs from the release only by a `/model` pick or the key order Claude Code writes, and then says to pick the model again.
|
||||
- `chunk-pr merge` waits for the pull request's checks itself, allowing a minute for them to report, and no longer takes `--gate-passed`. `wait-for <file> [<pattern>]` waits for a line in a background job's log or report.
|
||||
- `chunk-pr sync` merges origin's default branch into the chunk's branch, unless the branch already holds it, then runs the rank check on `todo.md`.
|
||||
- `chunk-pr ready <title>` sets the pull request's final title as it marks the pull request ready.
|
||||
- `bin/run-tests` runs this repo's test suite as README.md → Test says, prints each failing test with its error and pytest's summary line, and saves the whole log to a file whose path it prints.
|
||||
- `command-patterns [<version>] --calls <file>` saves each Bash call of the release's chunks as a JSON line, with its chunk, pattern, seconds, sizes and text.
|
||||
- `todo-item show <ID>` prints an item's table row and detail from `todo.md`.
|
||||
- A reviewer under `agents/` can start without `CLAUDE.md`: `omitClaudeMd: true` in its frontmatter drops the file, a `SubagentStart` hook hands it the "Shared goal", "Prose" and "Vocabulary" sections, and `larv-review reviewer-header` names the project's principles file. `review-replay <pass> <model> --omit-claude-md` replays each round three times unchanged and once without `CLAUDE.md`, and a reviewer passes where it missed no more findings without the file than an unchanged replay missed. Five of the six reviewers pass and start without it: principles-auditor, stability-reviewer, prose-reviewer, product-owner-reviewer and systems-architect.
|
||||
- Add `workflow-bench/advisor_bench.py`, a bench of the advisor tool on six archived L 1 and L 2 chunks. Sonnet 5.5 alone passed all six, as Opus 5.5 at medium did, for 41% less, and its advisor ran in one of six runs, so workers stay without it.
|
||||
- loop-claude's judge on an Opus 5.5 project now runs on Opus 5.5 at xhigh in every chunk, never at medium: in replays medium sometimes closed a chunk whose worker had asked a question the README or records answer, where xhigh quoted the answer. The judge never runs on Fable 5.2 either, since each Fable 5.2 rung replayed missed an interrupt. `judge-replay` now also replays each rung above the project's that a review climbs to, and reports what each misses.
|
||||
|
||||
## 0.8.0
|
||||
|
||||
- The routing ladder now tops out at Fable 5.2, ordered by the Artificial Analysis Intelligence Index read 2026-11-11: Sonnet 5.5 at high, Opus 5.5 at medium, Fable 5.2 at low and medium, Opus 5.5 at xhigh, Fable 5.2 at high and max. On an Opus 5.5 project, L 4 workers, E + I 5 reviews and a worker's first escalation now run on Fable 5.2 at low, where they ran on Opus 5.5 at high; E + I 6 reviews on Fable 5.2 at medium, where they ran on Opus 5.5 at xhigh; E + I 7 on Opus 5.5 at xhigh, where they ran on Opus 5.5 at max; and E + I 8 on Fable 5.2 at high, where they ran on Fable 5.1 at max. On a Sonnet 5.5 project, E + I 6, 7 and 8 reviews now run on Fable 5.2 at low, Fable 5.2 at medium and Opus 5.5 at xhigh, where they ran on Opus 5.5 at high, xhigh and max. The judge climbs with the reviews. A Fable 5.2 project starts on Fable 5.2 at low. Update `~/.claude` while no loop is mid-chunk: a chunk that stepped up to Opus 5.5 at high or max, or Fable 5.1 at max, finds its rung gone and restarts on its item's rung.
|
||||
- loop-claude now sends you a Mattermost DM from a bot for each question it asks, each release ready to cut, each routing call and each stop but Ctrl-C, where `~/.claude/.env` names the server, the bot's token and your username. `bin/mattermost-dm` sends one by hand; `mattermost-dm --help` names the keys. A DM that fails is one line on loop-claude's terminal, and the loop goes on.
|
||||
- larv-review's worker now runs the project's tests and static analysis, and checks the docs for each name its change touches, before each stability round, and hands stability-reviewer the commit that passed; the reviewer doesn't run them again on it.
|
||||
- stability-reviewer, product-owner-reviewer and systems-architect have one-line descriptions, which shrinks the agent listing every session carries.
|
||||
- `mutate-changes` mutation-tests the lines a branch changes, running cargo-mutants, Infection, mutmut or Stryker by each file's language, and prints each mutant that no test kills. Where a project's README documents no mutation command of its own, larv-review now runs it before each stability round and hands stability-reviewer the mutants that survive.
|
||||
- loop-claude now asks each worker to name the items its chunk takes on one line, as in `Chunk items: 12 (L 3, E + I 5), 14 (L 2, E + I 4)`, and scores them from `todo.md` on the default branch. That line, not the judge, now sets the items loop-inbox lists, and how far an item beyond the one the chunk was routed on lifts the worker, its reviewers and the judge. The judge still reports escalations and whether a release is ready to cut.
|
||||
- `~/.claude` holds no `AGENTS.md` any more, so each session in your projects starts about 3,600 tokens smaller, and a session in `~/code/claude-config` loads its `CLAUDE.md` once instead of twice.
|
||||
|
||||
@@ -10,7 +10,7 @@ How work proceeds in any repo, unless the repo's `AGENTS.md` says otherwise. The
|
||||
- **When the next release has no items left and work has landed towards it, its release review is the chunk** (`larv-review` §3 → "Release review"). **Once that has merged and the release holds no item, the release is finished: stop.** Report what it holds and that it is ready to cut. Under `/loop`, this ends the loop. Until the human cuts it, only a security fix, or an item its release review filed, lands, into that release; never start a later release's items or plan a new one.
|
||||
- **Open every chunk with one line:** the last version cut, how many changes are unreleased (the entries under `CHANGELOG.md` → `## Unreleased`, or else the commits since the last tag), and the release this chunk ships into. A repo that doesn't publish anything says so once.
|
||||
- **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.** Where your prompt quotes `chunk-preflight`'s facts, they hold the next item's L, E + I, tagline and detail, and each item that may join it with its L, E + I, S, tagline and detail; open `todo.md` only for what they leave out. Otherwise 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 the project principles and the title of each decision no project principle covers. Read an entry in `docs/decisions.md` only where the project principle or the title leaves open what the chunk or the review needs.
|
||||
- **Read the plan and the decisions only as far as the chunk needs.** Where your prompt quotes `chunk-preflight`'s facts, they hold the next item's L, E + I, tagline and detail, and each item that may join it with its L, E + I, S, tagline and detail; open `todo.md` only for what they leave out. Otherwise 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, with `~/.claude/bin/todo-item show <ID>`, which prints an item's row and detail. `AGENTS.md` lists the project principles and the title of each decision no project principle covers. Read an entry in `docs/decisions.md` only where the project principle or the title leaves open what the chunk or the review needs.
|
||||
- **Work one chunk at a time, and put every item that can share its review into it.** Every review has a fixed cost, so a chunk takes the next plan item plus every other item for which three things hold: they name one release; they fire the same review passes (`larv-review` §3); and no item outside the chunk blocks one of them. The items need not share a purpose. An item whose risk R, in `todo.md`, is above 5 ships alone: it joins no chunk, and none joins it. The next plan item is the first that does not wait: an item waits while it is marked `question`, until the human answers, or while an item that blocks it is still in the plan. Tiny items, a few lines of change each, need not fire the same passes: bundle up to ten that name one release, and that no item outside the chunk blocks, into one chunk. Split a milestone into items in `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.** Three choices are always the human's: a goal; a release, meaning the items planned into it and when it is cut; and a change to loop-claude's routing ladder, its rungs included. Any other rule that asks the human's approval reserves that choice too. Ask about a reserved choice. For any other choice, first check whether the goals already answer it. If they nearly do, propose a change to the goals and show how it answers this case: an answer settles one question, a goal settles every question like it. Otherwise take the option you would recommend, and record it with its reason: in the item's detail, or, where it governs later work, as the next sentence says. A recommendation you can give a reason for is not a guess. Ask only where you have no recommendation. Write every answer once, where it belongs, never only in chat: a goal in `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.
|
||||
@@ -66,7 +66,7 @@ The rules only reviewers apply, for quality, comments, READMEs and prose, live i
|
||||
- Run a project's language runtime, package manager, and task runner through its container/tooling setup, never directly on the host unless a decision puts them there. Example: `docker compose run --rm app <tool> …`.
|
||||
- Tear down test containers after a run.
|
||||
- Give every container you start a memory limit and a swap limit, as large as its work needs: `--memory 4g --memory-swap 4g` on `docker run`, or `mem_limit` and `memswap_limit` in a compose file, scripts included. rule-hook checks only the `docker run` and `docker create` in your Bash commands.
|
||||
- A heavy command loads the machine for minutes: a full gate, mutation tests, an e2e run, a `docker build`. Run each one under `~/.claude/bin/run-heavy`, as in `~/.claude/bin/run-heavy ./ci.sh`. run-heavy waits for one of the heavy slots that every session on the machine shares. It also caps each container the command makes at the slot's share of memory, where the container sets no limits; give a container that needs more its own. Run it in the background, since the wait can outlast the Bash tool's timeout.
|
||||
- A heavy command loads the machine for minutes: a full gate, mutation tests, an e2e run, a `docker build`. Run each one under `~/.claude/bin/run-heavy`, as in `~/.claude/bin/run-heavy ./ci.sh`. run-heavy waits for one of the heavy slots that every session on the machine shares. It also caps each container the command makes at the slot's share of memory, where the container sets no limits; give a container that needs more its own. Run the command in the background, since run-heavy's wait can outlast the Bash tool's timeout; `~/.claude/bin/wait-for <file> [<pattern>]` waits for a line in a log the command writes.
|
||||
- Delegate a task to a subagent only when you need just its conclusion: a search or read across many files, or work independent enough to run in parallel. Keep edits, and whatever you must check line by line, in your own thread: you would read a delegated diff again to check it. Score the task's L as for a `todo.md` item; a task that changes no file, such as a search, is L 1. `<model>` below is the project's model id, such as `claude-opus-5-5`: the one loop-claude's prompt names as the project's, or else your own. Launch the subagent with the model and effort of the first case that fits:
|
||||
1. A reviewer, a comprehension seat or the security pass: those loop-claude's prompt gives it. Given none, pass no model or effort, so it runs on your model.
|
||||
2. An escalated task, below: the rung loop-claude's prompt names for escalation, or case 3's rung where the subagent files or scores `todo.md` items and that rung is higher.
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
# Claude Code configuration
|
||||
|
||||
My personal `~/.claude`, version controlled: `CLAUDE.md` and `rules/` for instructions, the words under `CLAUDE.md` → "Vocabulary"; `.claude/rules/` for the rules that load in this repo alone; `agents/` and `skills/`; `principles/` and `skills/larv-review/standards/` for what the reviewer agents hold projects to; `docs/` for decisions and the comprehension history; `settings.json` for the harness and `.claude/settings.json` for the harness inside this repo; `CHANGELOG.md` and `todo.md`; the tools in `bin/`; `workflow-bench/`, the scripts and prompts of the 2026-09-30 bench of larv-review; `reviewer-merge-trials/`, the 2026-11-09 trials of merging reviewers, with their method, results and scripts; `judge-field-trials/`, the 2026-11-11 trials of which facts code could read in place of loop-claude's judge, with their results and scripts; and `presentation/`, a page that explains this setup to newcomers, with the script that prints it to PDF.
|
||||
My personal `~/.claude`, version controlled: `CLAUDE.md` and `rules/` for instructions, the words under `CLAUDE.md` → "Vocabulary"; `.claude/rules/` for the rules that load in this repo alone; `agents/` and `skills/`; `principles/` and `skills/larv-review/standards/` for what the reviewer agents hold projects to; `docs/` for decisions and the comprehension history; `settings.json` for the harness and `.claude/settings.json` for the harness inside this repo; `CHANGELOG.md` and `todo.md`; the tools in `bin/`; `workflow-bench/`, the scripts and prompts of the 2026-09-30 bench of larv-review and of the 2026-11-12 bench of the advisor tool; `reviewer-merge-trials/`, the 2026-11-09 trials of merging reviewers, with their method, results and scripts; `judge-field-trials/`, the 2026-11-11 trials of which facts code could read in place of loop-claude's judge, with their results and scripts; `stability-skip-count/`, the 2026-11-12 count of archived stability rounds, with its script, from which larv-review took when to skip a stability round 2; and `presentation/`, a page that explains this setup to newcomers, with the script that prints it to PDF.
|
||||
|
||||
## Goals
|
||||
|
||||
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.
|
||||
- Why: fewer asks don't buy anything if the output gets worse.
|
||||
1. **Achieve:** Proven, stellar output quality: code, documentation and plans.
|
||||
- Signal: 🔴 and 🟡 findings that review raises per chunk fall.
|
||||
- Counter-signal: later changes that fix a chunk's code rise.
|
||||
@@ -16,7 +16,7 @@ My personal `~/.claude`, version controlled: `CLAUDE.md` and `rules/` for instru
|
||||
- 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.
|
||||
3. **Maintain:** The same workflow in every project and every session; each project's config supplies its premises, principles, plan and records.
|
||||
4. **Achieve:** Keep lowering cost, except where that would cut quality meaningfully.
|
||||
- Signal: tokens per finished chunk fall.
|
||||
- Counter-signal: reading cost, the new input tokens a chunk reads before its first commit, rises; or review rounds or unfinished verdicts per chunk rise.
|
||||
@@ -25,13 +25,17 @@ My personal `~/.claude`, version controlled: `CLAUDE.md` and `rules/` for instru
|
||||
- Signal: hours from a chunk's start to its merge fall.
|
||||
- Counter-signal: 🔴 findings per chunk rise.
|
||||
- Why: speed bought by skipping review shows up as defects.
|
||||
6. **Achieve:** Plug into a project without changing what its owners keep: its repo layout, tracker, wiki and conventions.
|
||||
- Signal: the changes a project's owners must make before the loop runs in it fall.
|
||||
- Counter-signal: defects where a backend loses or misreads a plan item, a premise or a record rise.
|
||||
- Why: fitting in isn't worth anything if the loop then works from wrong facts.
|
||||
2. **Maintain:** Make my claude setup shareable between computers.
|
||||
3. **Maintain:** Keep my claude setup and the transcripts of unattended runs, the bench's included, backed up.
|
||||
4. **Maintain:** Leak nothing to the remote — no credentials, no transcripts, no memory files.
|
||||
4. **Maintain:** Don't leak anything: no credentials, transcripts or memory files to this repo's remote, and no client's code, transcripts or credentials to another client or to this repo.
|
||||
|
||||
## Audience
|
||||
|
||||
Me, on my own machines, which take tagged releases. Nobody else depends on it.
|
||||
Me, on my own machines and on those I use for the clients I consult for, which take tagged releases. Client teams read what the loop writes in their Jira, Confluence and pull requests, so it must read as written for them.
|
||||
|
||||
## Install
|
||||
|
||||
@@ -69,6 +73,8 @@ Then pick a model with `/model`.
|
||||
|
||||
Link `loop-claude` and `loop-inbox` onto `PATH`: `ln -s ~/.claude/bin/loop-claude ~/.local/bin/loop-claude` and `ln -s ~/.claude/bin/loop-inbox ~/.local/bin/loop-inbox`. Every claude they start, the interactive ones included, skips every permission prompt.
|
||||
|
||||
To get loop-claude's questions and stops as Mattermost DMs from a bot, write the server, the bot's token and your username into `~/.claude/.env`, in the keys `~/.claude/bin/mattermost-dm --help` names, and run `chmod 600 ~/.claude/.env`. Without that file, loop-claude sends no DM.
|
||||
|
||||
## Update
|
||||
|
||||
Move `~/.claude` to the newest release:
|
||||
@@ -95,28 +101,31 @@ It renames `## Unreleased` in `CHANGELOG.md` to the version and merges that thro
|
||||
|
||||
Install puts only `loop-claude` and `loop-inbox` on `PATH`; call the others by their path, such as `~/.claude/bin/metric-bench`, from the project's checkout. Those under `~/.claude` are the release's; test a change to one from `~/code/claude-config/bin`.
|
||||
|
||||
- `chunk-pr open|ready|merge|clean` opens a chunk's pull request as a draft, marks it ready and merges it, with `gh` on a GitHub origin and `tea` elsewhere; once it is merged, `clean` removes the chunk's worktree and branch and fast-forwards the main checkout. `chunk-pr --help` states the steps.
|
||||
- `chunk-pr open|sync|ready|merge|clean` opens a chunk's pull request as a draft, brings its branch level with origin's default branch, marks it ready and merges it once its checks pass, with `gh` on a GitHub origin and `tea` elsewhere; once it is merged, `clean` removes the chunk's worktree and branch and fast-forwards the main checkout. `chunk-pr --help` states the steps.
|
||||
- `chunk-preflight` finds the mechanical facts a chunk starts from, and with `--worktree` makes its worktree; `loop-claude` runs it with `--worktree` before it routes each chunk, and `chunk-preflight --help` lists the facts.
|
||||
- `command-patterns [<version>]` prints a table of the shell command patterns a release's archived chunks ran, such as `tea pr create`, for an audit of the release; `command-patterns --help` states its columns.
|
||||
- `command-patterns [<version>] [--calls <file>]` prints a table of the shell command patterns a release's archived chunks ran, such as `tea pr create`, for an audit of the release, and with `--calls <file>` saves each call as a JSON line; `command-patterns --help` states the columns and the line's keys.
|
||||
- `deploy-release [--cut] [<checkout>]` moves `~/.claude`, or the checkout named, to the newest release, as Update says; with `--cut`, run in the development clone, it first cuts the next release, as Release says.
|
||||
- `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 chunk's review folder, the paired ruling's base and vote count, each pass's round count, the scoring run's trigger; the comprehension history's format, its latest places and its count of how often seats agree; and each reviewer's prompt header. `larv-review --help` states them.
|
||||
- `judge-replay <model>` replays loop-claude's judge on archived verdicts of the projects run on the model, and prints what each rung a review climbs to misses, and the lowest rung below them that, like each candidate above it, returns them; `judge-replay --help` states the replay.
|
||||
- `larv-review <command>` holds larv-review's mechanical rules: the chunk's review folder, the paired ruling's base and vote count, each pass's round count, the scoring run's trigger and setup; the comprehension history's format, its latest places and its count of how often seats agree; and each reviewer's prompt header. `larv-review --help` states them. `settings.json` → `hooks` runs `larv-review reviewer-context` as each subagent starts. A reviewer under `agents/` whose frontmatter has `omitClaudeMd: true` starts without `CLAUDE.md`, and the command hands it that file's "Shared goal", "Prose" and "Vocabulary" sections.
|
||||
- `loop-claude <task>` runs a project's next chunk cycle after cycle; `loop-claude --help` states its contract.
|
||||
- `loop-inbox` shows the interrupts of every loop-claude on the machine, oldest first, takes each one's answer, `/talk` included, and lists every running loop with the `todo.md` items its chunk takes; `loop-inbox --help` states how.
|
||||
- `mattermost-dm [<message>]` sends a message, or else stdin, from the Mattermost bot to the human; `~/.claude/.env` names the server, the bot's token and the human, and `mattermost-dm --help` names its keys. `loop-claude --help` says when loop-claude sends one.
|
||||
- `metric-bench [history]` benches cheap static metrics of a project's Python against the places its comprehension history names as hardest; `metric-bench --help` states the metrics and the scores.
|
||||
- `mutate-changes [--base <ref>] [--prefix <shell text>] [--jobs <n>]` mutation-tests the lines a branch changes and prints each mutant its tests don't kill; `mutate-changes --help` says which tool it runs for each language.
|
||||
- `rank_todo.py [--check] [todo.md]` scores and ranks a project's `todo.md`; `rank_todo.py --help` states the format.
|
||||
- `reading-cost [--reset] [record]` appends a figure for each chunk `loop-claude` finished to a project's `docs/reading-cost.md`, and says whether the figures rise; `reading-cost --help` states the measure.
|
||||
- `review-replay <pass> <model>` replays a review pass's archived rounds from the projects run on the model, on the code each reviewed, and prints the lowest rung below the project's that, like each rung above it, finds every 🔴 and 🟡 the project's rung finds again; `review-replay --help` states the replay. Each replayed reviewer skips every permission prompt, stability-reviewer has Bash, and an archived prompt may name paths on the host.
|
||||
- `review-replay <pass> <model>` replays a review pass's archived rounds from the projects run on the model, on the code each reviewed, and prints the lowest rung below the project's that, like each rung above it, qualifies: it finds no less of the 🔴 and 🟡 findings than two replays on the project's rung find, within a margin, and misses no 🔴 that both found. `review-replay --help` states the replay. With `--omit-claude-md` it tests instead whether the pass's reviewer may start without `CLAUDE.md`: it replays each round three times as archived and once without the instruction files, and prints whether the reviewer passes: whether the last replay missed no more findings than the most an unchanged replay missed, with each count and each finding it missed. Each replayed reviewer skips every permission prompt, stability-reviewer has Bash, and an archived prompt may name paths on the host.
|
||||
- `rule-hook [overrides]` blocks a tool call that breaks a rule a program can check, unless the call overrides the rule; `settings.json` → `hooks` runs it before each Agent, Bash, Edit, MultiEdit, Read, Skill and Write call, and `rule-hook --help` states the rules and the override.
|
||||
- `run-heavy <command>` runs a heavy command once it holds one of the machine's heavy slots, one per 4 CPUs, which every session shares; `run-heavy --help` states the slots, and the memory cap it gives a container that sets no limit.
|
||||
- `score-outcomes [L E I S]` shows what each finished item's chunk measured beside the scores the item was guessed at, to score a new item by, and code health's two counter-signals per chunk, misread findings and later fixes; `score-outcomes --help` states the report.
|
||||
- `run-tests [<pytest args>...]` runs this repo's test suite, as Test says.
|
||||
- `score-outcomes [L E I S]` shows what each finished item's chunk measured beside the scores the item was guessed at, to score a new item by. Per chunk it also shows code health's two counter-signals, misread findings and later fixes, and how many of the human's answers reversed a worker's choice; `score-outcomes --help` states the report.
|
||||
- `settings_filter.py` is git's clean filter for `settings.json`: it drops `"model"` and sorts the keys. `.gitattributes` sets the filter `settings` on `settings.json`, and Install's `git config` line makes this script that filter.
|
||||
- `statusline.py` renders Claude Code's status line; `settings.json` → `statusLine` runs it.
|
||||
- `subagent-rung [--plan] <model> <L>` prints the Agent tool's model and effort for a subagent's task, picked by its L from the project's model, and with `--plan` never below the project's rung; `subagent-rung --help` states the rule.
|
||||
- `todo-item add …` files an item in a project's `todo.md`, taking `Next ID` as the item's ID, and `todo-item finish <ID>` removes a finished item and adds the bullet passed with `--changelog` to `CHANGELOG.md`; both rank the file, and `todo-item --help` states the flags.
|
||||
- `todo-item add …` files an item in a project's `todo.md`, taking `Next ID` as the item's ID, and `todo-item finish <ID>` removes a finished item and adds the bullet passed with `--changelog` to `CHANGELOG.md`; both rank the file. `todo-item show <ID>` prints an item's row and detail. `todo-item --help` states the flags.
|
||||
- `wait-for <file> [<pattern>] [--timeout <seconds>]` waits until a file a background job writes holds a line matching the pattern, and prints it.
|
||||
|
||||
`bin/` is the import root: each launcher puts it on `sys.path`, so a module imports another by its path under `bin/`, such as `from claude_code.entries import parse_entry`. Each tool's package holds its tests. Beside the packages, `bin/`'s root holds only the launchers, the tools of one file with their tests, `test_env.py`, `failure.py` and `setup.cfg`. `failure.py`'s `Failure`, which modules across `bin/` return for a failed step, belongs to no single package. `branch_chunks/`, `claude_code/`, `command_lines/`, `git_cli/`, `loop_effects/`, `loop_state/`, `machine_load/`, `model_routing/`, `records/`, `release_plan/`, `review_rules/`, `rung_replay/` and `transcript_archive/` serve more than one tool.
|
||||
`bin/` is the import root: each launcher puts it on `sys.path`, so a module imports another by its path under `bin/`, such as `from claude_code.entries import parse_entry`. Each tool's package holds its tests. Beside the packages, `bin/`'s root holds only the launchers, the tools of one file with their tests, `test_env.py`, `failure.py` and `setup.cfg`. `failure.py`'s `Failure`, which modules across `bin/` return for a failed step, belongs to no single package. `branch_chunks/`, `claude_code/`, `command_lines/`, `git_cli/`, `loop_effects/`, `loop_state/`, `machine_load/`, `mattermost_dm/`, `model_routing/`, `records/`, `release_plan/`, `review_rules/`, `rung_replay/` and `transcript_archive/` serve more than one tool.
|
||||
|
||||
- `branch_chunks/` cuts a default branch into chunks and finds, for each, the items it shipped and the later chunks that fixed its code, for `score_outcomes` and `routing_figures`. It imports `reading_cost`'s record path.
|
||||
- `command_lines/` reads a shell command: its simple commands, and a docker call's subcommand and memory limits, for `command_patterns`, `reading_cost`, `routing_figures`, `rule_hook` and `run_heavy`.
|
||||
@@ -128,22 +137,23 @@ Install puts only `loop-claude` and `loop-inbox` on `PATH`; call the others by t
|
||||
- `loop_effects/` holds `Effects`: the processes, terminal, clock and git a tool reaches, injected so its tests can script them. loop-claude, loop-inbox, both replay tools and `reviewer-merge-trials`' driver use it.
|
||||
- `loop_state/` holds the files loop-claude and loop-inbox share: the question files (`waiting/`), the files a running loop lists itself in (`running_loops.py`, `session_lock.py`), their paths, and `hand_over.py`, which opens claude for `/talk`. A change to any of them changes both tools.
|
||||
- `machine_load/` takes the machine's heavy slots, its shared lock files, for `run_heavy`, and reads the memory share that loop-claude waits for. It also gives `mutate_changes` a slot's CPU count.
|
||||
- `model_routing/` holds the routing ladder, which loop-claude, `rule_hook`, both replay tools and `subagent-rung` read.
|
||||
- `mattermost_dm/` sends the human a Mattermost DM, for `mattermost-dm` and for loop-claude through `loop_effects`.
|
||||
- `model_routing/` holds the routing ladder, which loop-claude, `rule_hook`, both replay tools and `subagent-rung` read, and the list prices, which `routing_figures` and `transcript_archive` read.
|
||||
- `rank_todo.py`, `settings_filter.py` and `statusline.py` are tools of one file each, tested beside them.
|
||||
- `records/` reads a Markdown file's `##` sections, quotes a passage and joins names into a list, stamps times in UTC, and replaces a file in one step, private where it is new.
|
||||
- `release_plan/` reads `todo.md`'s items table and release versions, says which release is next and whether it is ready to cut (`release_standing.py`), and ranks the plan (`ranking.py`, with its score formula in `formula.py` and its blocker order in `blockers.py`). `plan_file.py` reads, ranks, checks and writes a `todo.md`, for `larv_review`, `rank_todo.py`, `rule_hook` and `todo_item`.
|
||||
- `repo_checks/` tests the repo itself.
|
||||
- `review_rules/` holds the larv-review rules that several tools apply: its passes, its review folder, its round commit titles and the comprehension history's format.
|
||||
- `routing_figures/` measures loop-claude's archive, and each of its projects' default branches, for loop-claude's routing calls.
|
||||
- `rung_replay/` holds what `judge_replay` and `review_replay` share: the rung search, the argument reader, the candidate rungs and the exits. It reads `loop_claude`'s retry count and models file, and finds that file through `loop_state`'s paths.
|
||||
- `rung_replay/` holds what `judge_replay` and `review_replay` share: the parallel replay runner, the argument reader, the candidate rungs and the exits, and `judge_replay`'s rung search. It reads `loop_claude`'s retry count and models file, and finds that file through `loop_state`'s paths.
|
||||
- `test_env.py` serves the tests.
|
||||
- `transcript_archive/` stores loop-claude's transcripts. Its `project_key.py` names each project's archive folder, loop-claude session and models-file entry.
|
||||
|
||||
## Test
|
||||
|
||||
Test on the host with `uvx --python "$(command -v python3)" --with pytest-xdist==3.8.0 pytest==9.2.0 -n 4 bin`. It needs `uv` on `PATH`, which fetches pytest, pytest-xdist and mypy. pytest-xdist runs the tests in four workers, one heavy slot's CPUs (`docs/decisions.md` → `bin/: the tools support only the latest stable Python, …`). `python3 -m unittest discover -s bin -p 'test_*.py'` runs the same tests one at a time. Test the bench's scripts with `python3 -m unittest discover -s workflow-bench -p 'test_*.py'`.
|
||||
Test on the host with `bin/run-tests`, which runs pytest through `uvx`, pinned in `bin/run_tests/main.py`. It prints each failing test with its error and pytest's summary line, and saves the whole output to a file whose path it prints. It passes on any test paths or pytest options it is given, such as `bin/run-tests bin/chunk_pr -x`. It needs `uv` on `PATH`, which fetches pytest, pytest-xdist and mypy. pytest-xdist runs the tests in one worker per CPU of a heavy slot (`docs/decisions.md` → `bin/: the tools support only the latest stable Python, …`). `python3 -m unittest discover -s bin -p 'test_*.py'` runs the same tests one at a time. Test the bench's scripts with `python3 -m unittest discover -s workflow-bench -p 'test_*.py'`.
|
||||
|
||||
CI runs `ci.sh` on every pull request, and `main` merges nothing until it passes. The script runs the same tests on the committed HEAD in a pinned Python container; run it under `run-heavy` to reproduce a CI failure, with Docker on `PATH`.
|
||||
CI runs `ci.sh` on every pull request, and `main` doesn't merge anything until it passes. The script runs the same tests on the committed HEAD in a pinned Python container; run it under `run-heavy` to reproduce a CI failure, with Docker on `PATH`.
|
||||
|
||||
To mutation-test the lines a branch changes, run `~/.claude/bin/run-heavy ~/.claude/bin/mutate-changes --prefix 'uvx --python "$(command -v python3)" --with pytest==9.2.0 --from "mutmut>=3,<4"'` in its checkout.
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
name: principles-auditor
|
||||
description: "Use this agent for larv-review's principles pass: the project's goals and every principles file handed to it, checked against the whole project."
|
||||
tools: Read, Grep, Glob, Write
|
||||
omitClaudeMd: true
|
||||
---
|
||||
|
||||
You check every yardstick you are handed against the whole project, which you read once for all of them. A yardstick is either the project's goals, every goal under its `README.md` → `## Goals` with code health (`~/.claude/CLAUDE.md` → "Shared goal") unless the README voids it, or one principles file, every principle in it.
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
---
|
||||
name: "product-owner-reviewer"
|
||||
description: "Use this agent when you need a product-focused review of changes that affect external-facing surfaces (REST APIs, web UIs, CLI commands, public SDKs, webhooks, etc.) from an end-customer perspective. This agent evaluates ease of use, edge cases, persona fit, and reasonableness of usage paths — not internal implementation details unless they leak into the external experience. Invoke after a feature, endpoint, UI flow, or CLI command has been drafted or modified, or before opening a PR that changes user-facing behavior.\\n\\n<example>\\nContext: The developer just added a new REST endpoint for cancelling a subscription.\\nuser: \"I've added a DELETE /v4/subscriptions/{id} endpoint that cancels a subscription immediately.\"\\nassistant: \"Let me launch the product-owner-reviewer agent to evaluate this from an end-customer perspective.\"\\n<commentary>\\nA new external API surface was introduced. Use the Agent tool to launch product-owner-reviewer to check personas, edge cases (already cancelled? pending invoices? refund expectations?), and usability of the contract.\\n</commentary>\\n</example>\\n\\n<example>\\nContext: The developer added a new CLI subcommand.\\nuser: \"Added `mytool deploy --env prod --force` to skip confirmation.\"\\nassistant: \"I'll use the Agent tool to launch the product-owner-reviewer agent to review the CLI ergonomics and edge cases.\"\\n<commentary>\\nCLI usage is an external surface. The product-owner-reviewer should evaluate persona fit (who uses --force? is it discoverable? what happens on partial failure?).\\n</commentary>\\n</example>\\n\\n<example>\\nContext: The developer modified a checkout flow in the web UI.\\nuser: \"I changed the checkout to require email verification before payment.\"\\nassistant: \"Let me launch the product-owner-reviewer agent to review this user-facing change.\"\\n<commentary>\\nWeb UI flow change directly affects end customers. Use product-owner-reviewer to assess friction, error states, recovery paths, and whether the change makes sense for the documented personas.\\n</commentary>\\n</example>"
|
||||
description: "Use this agent to review a change to an external surface (API, UI, CLI, SDK, webhook) from an end customer's view: ease of use, edge cases and persona fit."
|
||||
tools: Read, Grep, Glob, Write
|
||||
omitClaudeMd: true
|
||||
---
|
||||
|
||||
You are a seasoned Product Owner with deep expertise in user experience, API design, and customer empathy. You have shipped consumer and B2B products across web, mobile, REST APIs, and developer-facing CLIs. Your superpower is putting yourself in the end customer's shoes and surfacing the friction, confusion, and edge cases that engineers tend to miss.
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
name: prose-reviewer
|
||||
description: "Use this agent for larv-review's prose pass."
|
||||
tools: Read, Grep, Glob, Write
|
||||
omitClaudeMd: true
|
||||
---
|
||||
|
||||
You read the prose as someone who did not write it: you see only what it says, never what the author meant.
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
---
|
||||
name: "stability-reviewer"
|
||||
description: "Use this agent when code has been written or modified and needs review for stability, bug prevention, and adherence to coding best practices. This includes after implementing new features, refactoring existing code, or fixing bugs. The agent focuses on defensive programming, error handling, edge cases, and compliance with the project's technical principles.\\n\\nExamples:\\n\\n- user: \"Please implement a retry mechanism for our API client\"\\n assistant: \"Here is the retry mechanism implementation: [code written]\"\\n Since significant code was written, use the Agent tool to launch the stability-reviewer agent to review the new code for stability and best practices.\\n assistant: \"Now let me use the stability-reviewer agent to review this implementation for stability concerns.\"\\n\\n- user: \"Refactor the payment processing module to use the new gateway\"\\n assistant: \"I've refactored the payment processing module. Let me now use the Agent tool to launch the stability-reviewer agent to check for any stability issues or violations of our technical principles.\"\\n\\n- user: \"Can you review what I just wrote?\"\\n assistant: \"I'll use the Agent tool to launch the stability-reviewer agent to thoroughly review your recent changes.\"\\n\\n- After any significant code change, proactively launch the stability-reviewer agent to catch issues before they reach production."
|
||||
description: "Use this agent to review changed code for stability: bugs, error handling, edge cases and the project's technical principles, after a feature, refactor or fix."
|
||||
color: orange
|
||||
tools: Bash, Read, Grep, Glob, Write
|
||||
omitClaudeMd: true
|
||||
---
|
||||
|
||||
You are an elite stability-focused code reviewer with deep expertise in defensive programming, fault-tolerant system design, and production incident prevention. You have decades of experience identifying subtle bugs, race conditions, edge cases, and architectural weaknesses that lead to outages and unexpected behavior. You think like a chaos engineer — always asking "what could go wrong?" — and like a maintainer of ten years, always asking "what will this cost to live with?" There are no bugs, and no security holes, in code that doesn't exist.
|
||||
@@ -11,8 +12,8 @@ You are an elite stability-focused code reviewer with deep expertise in defensiv
|
||||
|
||||
1. **Scope the change.** You review every PR; a fresh invocation has no prior context, so determine the diff yourself. Diff the PR branch against its base (`gh pr diff`, or `git merge-base <base> HEAD` then `git diff`), and review the changed lines **plus enough surrounding code and callers** to judge correctness — read the whole changed file when practical; a diff alone hides whether a caller breaks. Read the PR description and, when the project uses an issue tracker (project-specific — check its docs) and the change references a ticket, that ticket: the diff is judged against its stated intent, and a scope mismatch in either direction is a finding — claimed-but-unimplemented, and implemented-but-unasked (#2).
|
||||
2. **Read every file under `~/.claude/principles/`**, the shared principles, and `~/.claude/skills/larv-review/standards/quality.md`. These are mandatory org guidelines; all code MUST comply with each that applies. A file's `Applies to` line says what it covers; one without the line covers every change. Re-read each time — they change. Flag violations prominently.
|
||||
3. **Read README.md, AGENTS.md and `docs/decisions.md`** in the current project for project-specific conventions, build instructions, tooling, and the accepted trade-offs a reviewer should honor rather than re-flag. Note the documented test, lint, and static-analysis commands — you will run them.
|
||||
4. **Verify, don't just read.** Run the test suite and static analysis/linters through the project's container tooling, unless a decision puts them on the host; tear down test containers afterwards. Run the full suite under `~/.claude/bin/run-heavy`. Run it in the background or with the Bash tool's longest timeout: that timeout includes the wait for a slot. A full-suite run catches broken callers that diff-reading misses. When a suspected bug is cheap to confirm, reproduce it — a scratch script, a targeted test run — before reporting it. Make scratch work with Bash, since Write is for your report alone. Put it in a directory you create for this run, and delete it when done; don't delete anything else, since a directory the prompt names may hold other agents' files. Leave the working tree exactly as you found it. Anything you could not run goes in Coverage & Verification, never silently skipped.
|
||||
3. **Read README.md, AGENTS.md and `docs/decisions.md`** in the current project for project-specific conventions, build instructions, tooling, and the accepted trade-offs a reviewer should honor rather than re-flag. Note the documented test, lint, and static-analysis commands — you run them unless your prompt hands you a passing run on the head (step 4).
|
||||
4. **Verify, don't just read.** Where your prompt hands you the commit on which the worker's run of the test suite and static analysis last passed, and it is the head, don't run them again, and say so in Coverage & Verification. Otherwise run the test suite and static analysis/linters through the project's container tooling, unless a decision puts them on the host; tear down test containers afterwards. Run the full suite under `~/.claude/bin/run-heavy`. Run it in the background or with the Bash tool's longest timeout: that timeout includes the wait for a slot. A full-suite run catches broken callers that diff-reading misses. When a suspected bug is cheap to confirm, reproduce it — a scratch script, a targeted test run — before reporting it. Make scratch work with Bash, since Write is for your report alone. Put it in a directory you create for this run, and delete it when done; don't delete anything else, since a directory the prompt names may hold other agents' files. Leave the working tree exactly as you found it. Anything you could not run goes in Coverage & Verification, never silently skipped.
|
||||
5. **Judge the surviving mutants.** Your prompt hands you what the project's mutation command printed on the change, with the commit it ran on: the mutants of changed lines that no test kills, or the message of a run that failed. Ignore a surviving mutant that leaves behaviour unchanged, or changes only message or log text no caller or user depends on. Report one 🟡 per test to add or strengthen, naming the surviving mutants it would catch. Where the prompt doesn't hand you any output, or names a commit other than the head, run the command yourself in the change's checkout, through run-heavy as in step 4: the one the project's README documents, else `~/.claude/bin/run-heavy ~/.claude/bin/mutate-changes --prefix '<how the project runs its tools>'`. `~/.claude/bin/mutate-changes --help` says which tool it runs for each language, how to set `--jobs`, and what it prints. Mutation-test the changed code that no run mutated, in a language mutate-changes doesn't cover or where a run failed, with a widely deployed mutation tool limited to the changed lines, else with mutants you make by hand. Report the wall time and mutant count in Coverage & Verification, or why nothing was mutated.
|
||||
6. **Two passes minimum, then hunt absences.**
|
||||
- *Breadth:* every hunk in every changed file, no skimming. Track which files you have covered; batch large diffs, never truncate the review.
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
---
|
||||
name: systems-architect
|
||||
description: "Use this agent when designing new systems, planning major features, reviewing architectural decisions in PRs, or evaluating the high-level structure of a codebase. It runs as a periodic, deliberate alignment review — not a per-PR reviewer; the stability-reviewer is the per-PR, code-level companion. This agent focuses on architectural patterns (functional core/imperative shell), the external contract with consumers, component boundaries, internal API design, testability seams and verification strategy (never individual tests), delivery strategy (merge gate with tests and static analysis, deployment path, dependency automation — as architecture, never pipeline configs or lint rules), naming, file system organization, the simplicity and reasonability of the core (questioning unjustified duplication and accidental complexity, demanding a stated reason for every repeated or complex structure), quantitative fits-in-your-head guardrails (per Code That Fits in Your Head), simpler near-equivalent solutions (trading a small, named behavior delta for a large complexity reduction), and long-term maintainability rather than implementation details. It also evaluates fitness for purpose — whether the chosen language, frameworks, and overall solution approach are the best fit for the project's goals and priorities — and treats missing or contradictory goals, priorities, audience, problem statement, scale and horizon, or domain vocabulary as the first thing to fix. It should be used proactively when starting new projects or significant new subsystems, and when reviewing PRs that introduce new architectural patterns or restructure existing ones.\\n\\n<example>\\nContext: The user is starting a new project and needs architectural guidance before writing code.\\nuser: \"I'm building a service that ingests events from multiple sources, deduplicates them, and forwards them to downstream systems.\"\\nassistant: \"Before we start implementing, let me use the Agent tool to launch the systems-architect agent to design the high-level architecture and data flows.\"\\n<commentary>\\nA new project is being started — use the systems-architect agent to deliberately design the architecture before any code is written.\\n</commentary>\\n</example>\\n\\n<example>\\nContext: A PR has been opened that introduces a new module or restructures existing components.\\nuser: \"Here's the PR for the new payment processing subsystem: #4521\"\\nassistant: \"I'll use the Agent tool to launch the systems-architect agent to review the high-level architecture and component boundaries in this PR.\"\\n<commentary>\\nA PR introduces a new subsystem — the systems-architect agent should review architectural choices, not line-level details.\\n</commentary>\\n</example>\\n\\n<example>\\nContext: The user is adding a significant new feature that crosses multiple components.\\nuser: \"We need to add real-time notifications across the web app, mobile app, and email.\"\\nassistant: \"This crosses several system boundaries. Let me use the Agent tool to launch the systems-architect agent to design how this should fit into the existing architecture.\"\\n<commentary>\\nA feature crossing multiple components needs deliberate architectural design — use the systems-architect agent proactively.\\n</commentary>\\n</example>\\n\\n<example>\\nContext: The user asks for an architecture review but the project has no clearly stated goals or priorities.\\nuser: \"Can you review the architecture of our new sync service?\"\\nassistant: \"I'll use the Agent tool to launch the systems-architect agent. Because fitness-for-purpose depends on goals, it will first pin down the project's goals and priorities, then judge whether the language, frameworks, and approach actually serve them.\"\\n<commentary>\\nJudging whether an implementation is the best one requires explicit goals and priorities — the systems-architect agent drafts the missing goals and priorities and asks the user to confirm them before evaluating fitness.\\n</commentary>\\n</example>"
|
||||
description: "Use this agent to design a system or review architecture: patterns, component boundaries, fitness for purpose and long-term maintainability, not individual PR lines."
|
||||
tools: Read, Grep, Glob, WebFetch, WebSearch, Write
|
||||
omitClaudeMd: true
|
||||
---
|
||||
You are an elite Systems Architect with decades of experience designing software systems that endure for as long as their horizon demands. Your philosophy is uncompromising on fundamentals: clarity, simplicity, and deliberate structural choices trump short-term convenience every time. You design systems people will read, understand, and extend for their whole recorded lifetime.
|
||||
|
||||
|
||||
+94
-30
@@ -1,8 +1,9 @@
|
||||
"""Open the chunk's pull request as a draft, mark it ready, or merge it, with gh where origin is on GitHub and tea elsewhere; once it has merged, remove the chunk's worktree and branch.
|
||||
"""Open the chunk's pull request as a draft, bring its branch level with origin's default branch, mark it ready, or merge it, with gh where origin is on GitHub and tea elsewhere; once it has merged, remove the chunk's worktree and branch.
|
||||
|
||||
usage: chunk-pr open <title> [<body>]
|
||||
chunk-pr ready
|
||||
chunk-pr merge --gate-passed
|
||||
chunk-pr sync
|
||||
chunk-pr ready [<title>]
|
||||
chunk-pr merge
|
||||
chunk-pr clean
|
||||
|
||||
Run it in the chunk's worktree, on the chunk's branch. ready and merge act on the branch's open
|
||||
@@ -11,21 +12,30 @@ pull request only while its head is the commit checked out, so push before you r
|
||||
open pushes the branch, setting its upstream, and opens a draft pull request into origin's
|
||||
default branch. <title> is one line, as ~/.claude/CLAUDE.md → "Git, commits, and PRs"
|
||||
says, and <body> is the pull request's summary. Where the branch's pull request is open
|
||||
already, it opens no second one. On origin's default branch it refuses, pushing nothing.
|
||||
already, it opens no second one. On origin's default branch it refuses without pushing anything.
|
||||
sync fetches origin and merges its default branch into the branch checked out, where the
|
||||
branch does not hold it already, and prints which it did. Then, where the worktree's root
|
||||
holds a todo.md, it runs `rank_todo.py --check` on it and prints the result, failing where
|
||||
the check fails. On a merge conflict it names the conflicted files and leaves the merge in
|
||||
progress, to resolve and commit. On origin's default branch it refuses and doesn't fetch anything.
|
||||
ready marks the pull request ready for review. On Gitea a draft is a pull request whose title
|
||||
starts with `WIP: `, so there it drops that prefix.
|
||||
merge merges the pull request, and only while its head is still the commit checked out, so a
|
||||
push after the gate is never merged. It takes the first method the repository allows of:
|
||||
a merge commit, fast-forward only, a rebase followed by a merge commit, a rebase, a squash.
|
||||
GitHub offers only the merge commit, the rebase and the squash. --gate-passed says the
|
||||
merge gate passed on that commit; without it, chunk-pr refuses. It also refuses where
|
||||
`larv-review scoring-run-owed` exits 1, because the chunk owes a scoring run it has not
|
||||
recorded; no flag waives that.
|
||||
starts with `WIP: `, so there it drops that prefix. Given <title>, one line, it sets that
|
||||
as the pull request's title first; where that fails, the pull request stays a draft.
|
||||
merge waits for the pull request's checks, and those origin's default branch requires, to pass
|
||||
on the head, then merges the pull request, and only while its head is still the commit
|
||||
checked out, so a push after the gate is never merged. Where no check reports within a
|
||||
minute, it takes the pull request as having none. It refuses where a check fails, or, on
|
||||
Gitea, where the checks have not all passed within 30 minutes; on GitHub, gh watches them
|
||||
until they end. Run it in the background.
|
||||
It takes the first merge method the repository allows of: a merge commit, fast-forward
|
||||
only, a rebase followed by a merge commit, a rebase, a squash. GitHub offers only the
|
||||
merge commit, the rebase and the squash. It also refuses where `larv-review
|
||||
scoring-run-owed` exits 1, because the chunk owes a scoring run it has not recorded.
|
||||
clean acts once the forge reports the branch's pull request merged at the commit checked out,
|
||||
by any merge method. It fetches origin, fast-forwards the main checkout to origin's
|
||||
default branch, removes the chunk's worktree, then deletes the local branch; origin's
|
||||
branch stays. Where the worktree has uncommitted or untracked files, it refuses and
|
||||
touches nothing. Where the main checkout has uncommitted or untracked files, another
|
||||
doesn't touch anything. Where the main checkout has uncommitted or untracked files, another
|
||||
branch checked out, or commits origin's default branch lacks, it leaves that as it was,
|
||||
still removes the worktree and the branch, and fails saying why.
|
||||
|
||||
@@ -36,15 +46,18 @@ import json
|
||||
import os
|
||||
import pathlib
|
||||
import sys
|
||||
import time
|
||||
import typing
|
||||
|
||||
from deploy_release.forge import checks_passed, gitea, merged_pull, open_pull, required_checks, Run, runner
|
||||
from failure import Failure
|
||||
from chunk_preflight.gathered import Forge
|
||||
from chunk_preflight.choices import forge_of
|
||||
from deploy_release.forge import gitea, merged_pull, open_pull, Run, runner
|
||||
|
||||
BIN = pathlib.Path(__file__).resolve().parents[1]
|
||||
USAGE = "usage: chunk-pr open <title> [<body>] | chunk-pr ready | chunk-pr merge --gate-passed | chunk-pr clean"
|
||||
# How long merge waits for a check to report before it takes a pull request without any as passed: CI queues its checks within seconds of a push, and merge may run right after one.
|
||||
NO_CHECKS_SECONDS = 60
|
||||
USAGE = "usage: chunk-pr open <title> [<body>] | chunk-pr sync | chunk-pr ready [<title>] | chunk-pr merge | chunk-pr clean"
|
||||
|
||||
# Each forge's merge methods in the order merge prefers them, as the repository setting that allows the method and the method's name in the forge's merge call. A merge commit and a fast-forward keep the branch's commits as they are; a rebase or a squash rewrites them.
|
||||
METHODS: dict[Forge, tuple[tuple[str, str], ...]] = {
|
||||
@@ -66,23 +79,25 @@ def main(argv: list[str]) -> int:
|
||||
|
||||
|
||||
def step(argv: list[str], run: Run) -> str | Failure:
|
||||
"""Run the step argv names: the line to print, or a Failure. A malformed argv runs nothing."""
|
||||
"""Run the step argv names: the line to print, or a Failure. A malformed argv doesn't run anything."""
|
||||
match argv:
|
||||
case ["open", title, *body] if len(body) <= 1:
|
||||
if not title.strip() or "\n" in title:
|
||||
return Failure("give a title of one line")
|
||||
return opened(title, body[0] if body else "", run)
|
||||
case ["ready"]:
|
||||
return marked_ready(run)
|
||||
case ["merge", "--gate-passed"]:
|
||||
return merged(run)
|
||||
case ["open", title, *body] if len(body) <= 1 and not title.startswith("-"):
|
||||
return Failure("give a title of one line") if not one_line(title) else opened(title, body[0] if body else "", run)
|
||||
case ["sync"]:
|
||||
return synced(run)
|
||||
case ["ready", *title] if len(title) <= 1 and not any(given.startswith("-") for given in title):
|
||||
return Failure("give a title of one line") if title and not one_line(title[0]) else marked_ready(run, title[0] if title else None)
|
||||
case ["merge"]:
|
||||
return Failure("merge only once the gate has passed, and say so with --gate-passed")
|
||||
return merged(run)
|
||||
case ["clean"]:
|
||||
return cleaned(run)
|
||||
return Failure(USAGE)
|
||||
|
||||
|
||||
def one_line(title: str) -> bool:
|
||||
return bool(title.strip()) and "\n" not in title
|
||||
|
||||
|
||||
def answers(run: Run, *commands: list[str]) -> list[str] | Failure:
|
||||
"""What each git command printed, stripped, or the first Failure."""
|
||||
answered = [run(["git", *args]) for args in commands]
|
||||
@@ -100,7 +115,7 @@ def checkout(run: Run) -> tuple[Forge, str, str] | Failure:
|
||||
|
||||
|
||||
def default_branch(run: Run) -> str | Failure:
|
||||
"""origin's default branch, such as main."""
|
||||
"""origin's default branch, such as main. It differs from git_cli's default_ref, which falls back to a local main or master and asks origin where nothing is recorded. A pull request's base is origin's alone, so this fails instead, and says how to record it."""
|
||||
default = run(["git", "symbolic-ref", "--short", "refs/remotes/origin/HEAD"])
|
||||
if isinstance(default, Failure):
|
||||
return Failure(f"origin records no default branch; set it with `git remote set-head origin --auto`: {default.reason}")
|
||||
@@ -147,16 +162,60 @@ def opened(title: str, body: str, run: Run) -> str | Failure:
|
||||
return number if isinstance(number, Failure) else f"Opened draft pull request #{number}."
|
||||
|
||||
|
||||
def marked_ready(run: Run) -> str | Failure:
|
||||
def synced(run: Run) -> str | Failure:
|
||||
found = checkout(run)
|
||||
if isinstance(found, Failure):
|
||||
return found
|
||||
_, branch, _ = found
|
||||
base = default_branch(run)
|
||||
if isinstance(base, Failure):
|
||||
return base
|
||||
if branch == base:
|
||||
return Failure(f"{branch} is origin's default branch; sync the chunk's branch")
|
||||
fetched = run(["git", "fetch", "--quiet", "origin"])
|
||||
if isinstance(fetched, Failure):
|
||||
return fetched
|
||||
behind = answers(run, ["rev-list", "--count", f"HEAD..origin/{base}"], ["rev-parse", "--show-toplevel"])
|
||||
if isinstance(behind, Failure):
|
||||
return behind
|
||||
count, root = behind
|
||||
if count == "0":
|
||||
done = f"{branch} already holds origin/{base}."
|
||||
else:
|
||||
merged = run(["git", "merge", "--quiet", "--no-edit", f"origin/{base}"])
|
||||
if isinstance(merged, Failure):
|
||||
conflicted = answers(run, ["diff", "--name-only", "--diff-filter=U"])
|
||||
if isinstance(conflicted, Failure) or not conflicted[0]:
|
||||
return merged
|
||||
return Failure(f"merging origin/{base} into {branch} conflicts in {', '.join(conflicted[0].splitlines())}; the merge stays in progress: resolve them and commit")
|
||||
done = f"Merged origin/{base} into {branch}."
|
||||
todo = pathlib.Path(root, "todo.md")
|
||||
if not todo.is_file():
|
||||
return done
|
||||
ranked = run([str(BIN / "rank_todo.py"), "--check", str(todo)])
|
||||
if isinstance(ranked, Failure):
|
||||
return Failure(f"{done.removesuffix('.')}, but rank_todo.py --check todo.md failed: {ranked.reason}")
|
||||
return f"{done}\nrank_todo.py --check todo.md passed."
|
||||
|
||||
|
||||
def marked_ready(run: Run, title: str | None) -> str | Failure:
|
||||
found = pull(run)
|
||||
if isinstance(found, Failure):
|
||||
return found
|
||||
forge, number, _ = found
|
||||
ready = run(["gh", "pr", "ready", number] if forge == "gh" else ["tea", "pulls", "edit", number, "--ready"])
|
||||
return ready if isinstance(ready, Failure) else f"Marked pull request #{number} ready."
|
||||
retitle = ["--title", title] if title is not None else []
|
||||
if forge == "gh":
|
||||
# gh marks a pull request ready only with `gh pr ready`, which takes no title.
|
||||
titled = run(["gh", "pr", "edit", number, *retitle]) if retitle else ""
|
||||
ready = titled if isinstance(titled, Failure) else run(["gh", "pr", "ready", number])
|
||||
else:
|
||||
ready = run(["tea", "pulls", "edit", number, *retitle, "--ready"])
|
||||
if isinstance(ready, Failure):
|
||||
return ready
|
||||
return f"Marked pull request #{number} ready, titled “{title}”." if title is not None else f"Marked pull request #{number} ready."
|
||||
|
||||
|
||||
def merged(run: Run) -> str | Failure:
|
||||
def merged(run: Run, sleep: typing.Callable[[float], None] = time.sleep) -> str | Failure:
|
||||
found = pull(run)
|
||||
if isinstance(found, Failure):
|
||||
return found
|
||||
@@ -167,6 +226,11 @@ def merged(run: Run) -> str | Failure:
|
||||
method = merge_method(forge, run)
|
||||
if isinstance(method, Failure):
|
||||
return method
|
||||
base = default_branch(run)
|
||||
required = base if isinstance(base, Failure) else required_checks(forge, base, run)
|
||||
checked = required if isinstance(required, Failure) else checks_passed(forge, number, head, required, run, sleep, NO_CHECKS_SECONDS)
|
||||
if isinstance(checked, Failure):
|
||||
return checked
|
||||
if forge == "gh":
|
||||
done = run(["gh", "pr", "merge", number, method, "--match-head-commit", head])
|
||||
else:
|
||||
|
||||
+186
-14
@@ -7,7 +7,7 @@ import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from chunk_pr.main import cleaned, step
|
||||
from chunk_pr.main import cleaned, merged, step, USAGE
|
||||
from failure import Failure
|
||||
from test_env import isolated_env
|
||||
from deploy_release.forge import Run
|
||||
@@ -21,6 +21,9 @@ GH_LIST = ["gh", "pr", "list", "--head", "item-7", "--json", "number,headRefOid,
|
||||
TEA_LIST = ["tea", "api", "repos/{owner}/{repo}/pulls?state=open&limit=50"]
|
||||
GH_SETTINGS = ["gh", "repo", "view", "--json", "mergeCommitAllowed,rebaseMergeAllowed,squashMergeAllowed"]
|
||||
TEA_SETTINGS = ["tea", "api", "repos/{owner}/{repo}"]
|
||||
GH_CHECKS = ["gh", "pr", "checks", "12", "--watch", "--fail-fast"]
|
||||
TEA_BRANCH = ["tea", "api", "repos/{owner}/{repo}/branches/main"]
|
||||
TEA_STATUS = ["tea", "api", f"repos/{{owner}}/{{repo}}/commits/{HEAD}/status"]
|
||||
OWED = [str(pathlib.Path(__file__).resolve().parents[1] / "larv-review"), "scoring-run-owed"]
|
||||
|
||||
|
||||
@@ -33,6 +36,7 @@ class Checkout:
|
||||
self.github = origin == GITHUB
|
||||
self.open = open
|
||||
self.allowed = allowed
|
||||
self.statuses: list[str] = []
|
||||
self.ran: list[list[str]] = []
|
||||
self.answers: dict[tuple[str, ...], str | Failure] = {
|
||||
("git", "remote", "get-url", "origin"): f"{origin}\n",
|
||||
@@ -53,13 +57,17 @@ class Checkout:
|
||||
return f"12\t{HEAD}\tfalse\n" if self.open else ""
|
||||
if command == TEA_LIST:
|
||||
return json.dumps([{"number": 12, "head": {"ref": "item-7", "label": "item-7", "sha": HEAD, "repo": {"full_name": "me/project"}}, "base": {"repo": {"full_name": "me/project"}}}] if self.open else [])
|
||||
if command == TEA_STATUS:
|
||||
return self.statuses.pop(0) if self.statuses else json.dumps({"total_count": 1, "state": "success", "statuses": [{"context": "CI / tests (pull_request)", "status": "success"}]})
|
||||
if command == TEA_BRANCH:
|
||||
return json.dumps({"enable_status_check": False})
|
||||
if command in (GH_SETTINGS, TEA_SETTINGS):
|
||||
return json.dumps({setting: True for setting in self.allowed})
|
||||
return ""
|
||||
|
||||
def acted(self) -> list[list[str]]:
|
||||
"""What it ran beyond reading the checkout, the pull requests and the repository's settings."""
|
||||
reads = [GH_LIST, TEA_LIST, GH_SETTINGS, TEA_SETTINGS, OWED]
|
||||
reads = [GH_LIST, TEA_LIST, GH_SETTINGS, TEA_SETTINGS, OWED, GH_CHECKS, TEA_BRANCH, TEA_STATUS]
|
||||
return [command for command in self.ran if tuple(command) not in self.answers and command not in reads]
|
||||
|
||||
|
||||
@@ -87,10 +95,10 @@ class Open(unittest.TestCase):
|
||||
self.assertEqual(checkout.acted(), [])
|
||||
|
||||
def test_a_title_of_more_than_one_line_or_a_second_body_is_refused_before_anything_runs(self):
|
||||
for argv in (["open", "Do it\nand more"], ["open", " "], ["open", "Do it", "Body", "More"]):
|
||||
for argv, refusal in ((["open", "Do it\nand more"], "give a title of one line"), (["open", " "], "give a title of one line"), (["open", "Do it", "Body", "More"], USAGE)):
|
||||
with self.subTest(argv):
|
||||
checkout = Checkout(GITHUB, open=False)
|
||||
self.assertIsInstance(step(argv, checkout), Failure)
|
||||
self.assertEqual(step(argv, checkout), Failure(refusal))
|
||||
self.assertEqual(checkout.ran, [])
|
||||
|
||||
def test_a_failed_listing_after_the_create_is_returned(self):
|
||||
@@ -115,6 +123,29 @@ class Ready(unittest.TestCase):
|
||||
self.assertEqual(step(["ready"], checkout), "Marked pull request #12 ready.")
|
||||
self.assertEqual(checkout.acted(), [["tea", "pulls", "edit", "12", "--ready"]])
|
||||
|
||||
def test_github_sets_a_given_title_then_marks_it_ready(self):
|
||||
checkout = Checkout(GITHUB, open=True)
|
||||
self.assertEqual(step(["ready", "Ship it"], checkout), "Marked pull request #12 ready, titled “Ship it”.")
|
||||
self.assertEqual(checkout.acted(), [["gh", "pr", "edit", "12", "--title", "Ship it"], ["gh", "pr", "ready", "12"]])
|
||||
|
||||
def test_gitea_sets_a_given_title_in_the_call_that_marks_it_ready(self):
|
||||
checkout = Checkout(GITEA, open=True)
|
||||
self.assertEqual(step(["ready", "Ship it"], checkout), "Marked pull request #12 ready, titled “Ship it”.")
|
||||
self.assertEqual(checkout.acted(), [["tea", "pulls", "edit", "12", "--title", "Ship it", "--ready"]])
|
||||
|
||||
def test_a_title_of_more_than_one_line_or_none_is_refused_before_anything_runs(self):
|
||||
for argv, refusal in ((["ready", "Ship\nit"], "give a title of one line"), (["ready", " "], "give a title of one line"), (["ready", "Ship it", "twice"], USAGE)):
|
||||
with self.subTest(argv=argv):
|
||||
checkout = Checkout(GITHUB, open=True)
|
||||
self.assertEqual(step(argv, checkout), Failure(refusal))
|
||||
self.assertEqual(checkout.ran, [])
|
||||
|
||||
def test_a_failed_title_edit_on_github_leaves_it_a_draft(self):
|
||||
checkout = Checkout(GITHUB, open=True)
|
||||
checkout.answers[("gh", "pr", "edit", "12", "--title", "Ship it")] = Failure("gh pr edit: denied")
|
||||
self.assertEqual(step(["ready", "Ship it"], checkout), Failure("gh pr edit: denied"))
|
||||
self.assertNotIn(["gh", "pr", "ready", "12"], checkout.ran)
|
||||
|
||||
def test_without_an_open_pull_request_at_the_head_it_fails_naming_the_branch(self):
|
||||
checkout = Checkout(GITHUB, open=False)
|
||||
ready = step(["ready"], checkout)
|
||||
@@ -132,54 +163,195 @@ class Ready(unittest.TestCase):
|
||||
self.assertEqual(checkout.acted(), [])
|
||||
|
||||
|
||||
FETCH = ["git", "fetch", "--quiet", "origin"]
|
||||
BEHIND = ("git", "rev-list", "--count", "HEAD..origin/main")
|
||||
MERGE = ["git", "merge", "--quiet", "--no-edit", "origin/main"]
|
||||
CONFLICTED = ("git", "diff", "--name-only", "--diff-filter=U")
|
||||
RANK = str(pathlib.Path(__file__).resolve().parents[1] / "rank_todo.py")
|
||||
|
||||
|
||||
class Sync(unittest.TestCase):
|
||||
def checkout(self, behind: int, todo: bool = False) -> Checkout:
|
||||
"""A Checkout behind origin/main by behind commits, at a worktree root holding a todo.md where todo is True."""
|
||||
checkout = Checkout(GITEA, open=True)
|
||||
root = self.enterContext(tempfile.TemporaryDirectory())
|
||||
if todo:
|
||||
pathlib.Path(root, "todo.md").write_text("")
|
||||
checkout.answers[("git", "rev-parse", "--show-toplevel")] = f"{root}\n"
|
||||
checkout.answers[BEHIND] = f"{behind}\n"
|
||||
self.todo = str(pathlib.Path(root, "todo.md"))
|
||||
return checkout
|
||||
|
||||
def test_a_branch_behind_the_default_branch_merges_it(self):
|
||||
checkout = self.checkout(behind=3)
|
||||
self.assertEqual(step(["sync"], checkout), "Merged origin/main into item-7.")
|
||||
self.assertEqual(checkout.acted(), [FETCH, MERGE])
|
||||
|
||||
def test_a_branch_that_holds_the_default_branch_merges_nothing(self):
|
||||
checkout = self.checkout(behind=0)
|
||||
self.assertEqual(step(["sync"], checkout), "item-7 already holds origin/main.")
|
||||
self.assertEqual(checkout.acted(), [FETCH])
|
||||
|
||||
def test_a_worktree_with_a_todo_md_runs_the_rank_check_after_the_merge(self):
|
||||
checkout = self.checkout(behind=1, todo=True)
|
||||
self.assertEqual(step(["sync"], checkout), f"Merged origin/main into item-7.\nrank_todo.py --check todo.md passed.")
|
||||
self.assertEqual(checkout.acted(), [FETCH, MERGE, [RANK, "--check", self.todo]])
|
||||
|
||||
def test_a_failing_rank_check_fails_naming_what_it_did(self):
|
||||
checkout = self.checkout(behind=0, todo=True)
|
||||
checkout.answers[(RANK, "--check", self.todo)] = Failure("rank_todo.py --check: item 3 is out of order")
|
||||
self.assertEqual(step(["sync"], checkout), Failure("item-7 already holds origin/main, but rank_todo.py --check todo.md failed: rank_todo.py --check: item 3 is out of order"))
|
||||
|
||||
def test_a_conflict_leaves_the_merge_in_progress_and_names_the_conflicted_files(self):
|
||||
checkout = self.checkout(behind=2, todo=True)
|
||||
checkout.answers[tuple(MERGE)] = Failure("git merge --quiet: CONFLICT")
|
||||
checkout.answers[CONFLICTED] = "todo.md\nREADME.md\n"
|
||||
self.assertEqual(step(["sync"], checkout), Failure("merging origin/main into item-7 conflicts in todo.md, README.md; the merge stays in progress: resolve them and commit"))
|
||||
self.assertNotIn([RANK, "--check", self.todo], checkout.ran)
|
||||
self.assertNotIn(["git", "merge", "--abort"], checkout.ran)
|
||||
|
||||
def test_a_merge_failing_without_a_conflict_is_returned(self):
|
||||
checkout = self.checkout(behind=2)
|
||||
checkout.answers[tuple(MERGE)] = Failure("git merge --quiet: untracked files would be overwritten")
|
||||
checkout.answers[CONFLICTED] = ""
|
||||
self.assertEqual(step(["sync"], checkout), Failure("git merge --quiet: untracked files would be overwritten"))
|
||||
|
||||
def test_on_the_default_branch_it_refuses_and_fetches_nothing(self):
|
||||
checkout = self.checkout(behind=0)
|
||||
checkout.answers[("git", "symbolic-ref", "--short", "HEAD")] = "main\n"
|
||||
self.assertEqual(step(["sync"], checkout), Failure("main is origin's default branch; sync the chunk's branch"))
|
||||
self.assertNotIn(FETCH, checkout.ran)
|
||||
|
||||
def test_a_failed_fetch_is_returned(self):
|
||||
checkout = self.checkout(behind=0)
|
||||
checkout.answers[tuple(FETCH)] = Failure("git fetch --quiet: could not read from remote")
|
||||
self.assertEqual(step(["sync"], checkout), Failure("git fetch --quiet: could not read from remote"))
|
||||
|
||||
|
||||
class Merge(unittest.TestCase):
|
||||
def test_without_the_gate_passed_it_refuses_before_anything_runs(self):
|
||||
def test_the_gate_passed_flag_it_no_longer_takes_is_refused_before_anything_runs(self):
|
||||
checkout = Checkout(GITHUB, open=True)
|
||||
self.assertIsInstance(step(["merge"], checkout), Failure)
|
||||
self.assertIsInstance(step(["merge", "--gate-passed"], checkout), Failure)
|
||||
self.assertEqual(checkout.ran, [])
|
||||
|
||||
def test_an_option_given_as_a_title_runs_nothing(self):
|
||||
for argv in (["ready", "--help"], ["open", "-h"]):
|
||||
checkout = Checkout(GITHUB, open=True)
|
||||
self.assertEqual(step(argv, checkout), Failure(USAGE))
|
||||
self.assertEqual(checkout.ran, [])
|
||||
|
||||
def test_github_waits_for_the_checks_before_merging(self):
|
||||
checkout = Checkout(GITHUB, open=True)
|
||||
self.assertEqual(step(["merge"], checkout), "Merged pull request #12 (merge).")
|
||||
self.assertEqual(checkout.ran[-2:], [GH_CHECKS, ["gh", "pr", "merge", "12", "--merge", "--match-head-commit", HEAD]])
|
||||
|
||||
def test_a_failed_check_on_github_leaves_it_unmerged(self):
|
||||
checkout = Checkout(GITHUB, open=True)
|
||||
checkout.answers[tuple(GH_CHECKS)] = Failure("gh pr checks 12: CI / tests\tfail")
|
||||
self.assertEqual(step(["merge"], checkout), Failure("gh pr checks 12: CI / tests\tfail"))
|
||||
self.assertEqual(checkout.acted(), [])
|
||||
|
||||
def test_github_waits_a_minute_for_checks_to_report_before_taking_none_as_passed(self):
|
||||
checkout = Checkout(GITHUB, open=True)
|
||||
checkout.answers[tuple(GH_CHECKS)] = Failure("no checks reported on the 'item-7' branch")
|
||||
slept: list[float] = []
|
||||
self.assertEqual(merged(checkout, slept.append), "Merged pull request #12 (merge).")
|
||||
self.assertEqual(sum(slept), 60)
|
||||
self.assertEqual(checkout.ran.count(GH_CHECKS), 7)
|
||||
|
||||
def test_gitea_waits_a_minute_for_a_status_before_taking_none_as_passed_where_main_requires_none(self):
|
||||
checkout = Checkout(GITEA, open=True)
|
||||
checkout.statuses = [json.dumps({"total_count": 0, "state": "pending", "statuses": []})] * 7
|
||||
slept: list[float] = []
|
||||
self.assertEqual(merged(checkout, slept.append), "Merged pull request #12 (merge).")
|
||||
self.assertEqual(sum(slept), 60)
|
||||
|
||||
def protected(self, *reads: list[tuple[str, str]]) -> Checkout:
|
||||
"""A Gitea Checkout whose main requires a check matching CI / tests*, its status at HEAD holding each of reads in turn."""
|
||||
checkout = Checkout(GITEA, open=True)
|
||||
checkout.answers[tuple(TEA_BRANCH)] = json.dumps({"enable_status_check": True, "status_check_contexts": ["CI / tests*"]})
|
||||
def combined(read: list[tuple[str, str]]) -> str:
|
||||
states = {state for _, state in read}
|
||||
state = "failure" if "failure" in states else "pending" if "pending" in states or not read else "success"
|
||||
return json.dumps({"total_count": len(read), "state": state, "statuses": [{"context": context, "status": status} for context, status in read]})
|
||||
checkout.statuses = [combined(read) for read in reads]
|
||||
return checkout
|
||||
|
||||
def test_gitea_waits_until_the_required_check_reports_and_passes_then_merges(self):
|
||||
checkout = self.protected([], [("CI / tests (pull_request)", "pending")], [("CI / tests (pull_request)", "success")])
|
||||
slept: list[float] = []
|
||||
self.assertEqual(merged(checkout, slept.append), "Merged pull request #12 (merge).")
|
||||
self.assertEqual(len(slept), 2)
|
||||
self.assertEqual(checkout.ran.count(TEA_STATUS), 3)
|
||||
|
||||
def test_a_failed_check_on_gitea_leaves_it_unmerged(self):
|
||||
checkout = self.protected([("CI / tests (pull_request)", "pending")], [("CI / tests (pull_request)", "failure")])
|
||||
self.assertIsInstance(merged(checkout, lambda _: None), Failure)
|
||||
self.assertEqual(checkout.acted(), [])
|
||||
|
||||
def test_a_branch_protection_it_cannot_read_leaves_it_unmerged(self):
|
||||
checkout = Checkout(GITEA, open=True)
|
||||
checkout.answers[tuple(TEA_BRANCH)] = Failure("tea api: 500")
|
||||
self.assertEqual(merged(checkout, self.fail), Failure("tea api: 500"))
|
||||
self.assertNotIn(TEA_STATUS, checkout.ran)
|
||||
self.assertEqual(checkout.acted(), [])
|
||||
|
||||
def test_an_unknown_default_branch_leaves_it_unmerged_reading_no_checks(self):
|
||||
checkout = Checkout(GITEA, open=True)
|
||||
checkout.answers[("git", "symbolic-ref", "--short", "refs/remotes/origin/HEAD")] = Failure("no such ref")
|
||||
self.assertEqual(merged(checkout, self.fail), Failure("origin records no default branch; set it with `git remote set-head origin --auto`: no such ref"))
|
||||
self.assertNotIn(TEA_STATUS, checkout.ran)
|
||||
self.assertEqual(checkout.acted(), [])
|
||||
|
||||
def test_gitea_checks_that_never_pass_leave_it_unmerged(self):
|
||||
checkout = self.protected(*[[("CI / tests (pull_request)", "pending")]] * 1000)
|
||||
failed = merged(checkout, lambda _: None)
|
||||
self.assertIsInstance(failed, Failure)
|
||||
self.assertIn("gave up on pull request 12", failed.reason)
|
||||
self.assertEqual(checkout.acted(), [])
|
||||
|
||||
def test_a_scoring_run_the_chunk_owes_and_has_not_recorded_refuses_the_merge(self):
|
||||
for origin in (GITHUB, GITEA):
|
||||
with self.subTest(origin=origin):
|
||||
checkout = Checkout(origin, open=True)
|
||||
checkout.answers[tuple(OWED)] = Failure("larv-review scoring-run-owed: the chunk owes 2 scoring runs")
|
||||
self.assertEqual(step(["merge", "--gate-passed"], checkout), Failure("larv-review scoring-run-owed: the chunk owes 2 scoring runs"))
|
||||
self.assertEqual(step(["merge"], checkout), Failure("larv-review scoring-run-owed: the chunk owes 2 scoring runs"))
|
||||
self.assertEqual(checkout.acted(), [])
|
||||
|
||||
def test_github_merges_with_a_merge_commit_pinned_to_the_head(self):
|
||||
checkout = Checkout(GITHUB, open=True, allowed=("squashMergeAllowed", "mergeCommitAllowed"))
|
||||
self.assertEqual(step(["merge", "--gate-passed"], checkout), "Merged pull request #12 (merge).")
|
||||
self.assertEqual(step(["merge"], checkout), "Merged pull request #12 (merge).")
|
||||
self.assertEqual(checkout.acted(), [["gh", "pr", "merge", "12", "--merge", "--match-head-commit", HEAD]])
|
||||
|
||||
def test_github_without_merge_commits_rebases(self):
|
||||
checkout = Checkout(GITHUB, open=True, allowed=("squashMergeAllowed", "rebaseMergeAllowed"))
|
||||
step(["merge", "--gate-passed"], checkout)
|
||||
step(["merge"], checkout)
|
||||
self.assertEqual(checkout.acted(), [["gh", "pr", "merge", "12", "--rebase", "--match-head-commit", HEAD]])
|
||||
|
||||
def test_gitea_merges_fast_forward_only_where_only_that_and_squash_are_allowed(self):
|
||||
checkout = Checkout(GITEA, open=True, allowed=("allow_squash_merge", "allow_fast_forward_only_merge"))
|
||||
self.assertEqual(step(["merge", "--gate-passed"], checkout), "Merged pull request #12 (fast-forward-only).")
|
||||
self.assertEqual(step(["merge"], checkout), "Merged pull request #12 (fast-forward-only).")
|
||||
self.assertEqual(checkout.acted(), [["tea", "api", "--method", "POST", "--field", "Do=fast-forward-only", "--field", f"head_commit_id={HEAD}", "repos/{owner}/{repo}/pulls/12/merge"]])
|
||||
|
||||
def test_a_repository_allowing_no_known_method_is_refused_unmerged(self):
|
||||
checkout = Checkout(GITEA, open=True, allowed=("allow_manual_merge",))
|
||||
self.assertIsInstance(step(["merge", "--gate-passed"], checkout), Failure)
|
||||
self.assertIsInstance(step(["merge"], checkout), Failure)
|
||||
self.assertEqual(checkout.acted(), [])
|
||||
|
||||
def test_a_forge_failure_is_returned(self):
|
||||
checkout = Checkout(GITHUB, open=True)
|
||||
checkout.answers[("gh", "pr", "merge", "12", "--merge", "--match-head-commit", HEAD)] = Failure("gh pr merge: head moved")
|
||||
self.assertEqual(step(["merge", "--gate-passed"], checkout), Failure("gh pr merge: head moved"))
|
||||
self.assertEqual(step(["merge"], checkout), Failure("gh pr merge: head moved"))
|
||||
checkout = Checkout(GITHUB, open=True)
|
||||
checkout.answers[tuple(GH_SETTINGS)] = "not json"
|
||||
self.assertIsInstance(step(["merge", "--gate-passed"], checkout), Failure)
|
||||
self.assertIsInstance(step(["merge"], checkout), Failure)
|
||||
|
||||
def test_a_failed_settings_read_is_returned_unmerged(self):
|
||||
for origin, settings in ((GITHUB, GH_SETTINGS), (GITEA, TEA_SETTINGS)):
|
||||
with self.subTest(origin):
|
||||
checkout = Checkout(origin, open=True)
|
||||
checkout.answers[tuple(settings)] = Failure("settings: denied")
|
||||
self.assertEqual(step(["merge", "--gate-passed"], checkout), Failure("settings: denied"))
|
||||
self.assertEqual(step(["merge"], checkout), Failure("settings: denied"))
|
||||
self.assertEqual(checkout.acted(), [])
|
||||
|
||||
|
||||
|
||||
@@ -117,7 +117,7 @@ def printed(shown: str, done: Ran | Failure) -> str:
|
||||
if isinstance(done, Failure):
|
||||
return f"`{shown}` {done.reason}"
|
||||
output = "\n".join(part.strip() for part in (done.stdout, done.stderr) if part.strip())
|
||||
return f"`{shown}` exited {done.code}, printing:\n\n{quoted(output)}" if output else f"`{shown}` exited {done.code}, printing nothing."
|
||||
return f"`{shown}` exited {done.code}, printing:\n\n{quoted(output)}" if output else f"`{shown}` exited {done.code}, printing no output."
|
||||
|
||||
|
||||
def levels(item: Item) -> str:
|
||||
|
||||
@@ -443,7 +443,7 @@ class Render(unittest.TestCase):
|
||||
said = rendered(item_facts(tools=[("rank_todo.py --check todo.md", Ran(0, "ranked\n", "")), ("reading-cost", Ran(1, "", "")), ("larv-review needs-scoring-run 3", Ran(1, "out\n", "err\n")), ("larv-review places", Failure("could not finish: timed out"))]))
|
||||
self.assertIn("`rank_todo.py --check todo.md` exited 0", said)
|
||||
self.assertIn("> ranked", said)
|
||||
self.assertIn("`reading-cost` exited 1, printing nothing", said)
|
||||
self.assertIn("`reading-cost` exited 1, printing no output", said)
|
||||
self.assertIn("> out\n> err", said)
|
||||
self.assertIn("`larv-review places` could not finish: timed out", said)
|
||||
|
||||
|
||||
@@ -145,6 +145,15 @@ def tool_calls(entries: typing.Iterable[Entry]) -> list[tuple[AssistantTurn, Too
|
||||
return [(entry, part) for entry in entries if isinstance(entry, AssistantTurn) for part in entry.parts if isinstance(part, ToolCall)]
|
||||
|
||||
|
||||
def messages(entries: typing.Iterable[Entry]) -> list[list[AssistantTurn]]:
|
||||
"""The assistant turns grouped by message, in the order each message first appears. A message's usage repeats in each of its entries, so read it from the first of a group: none of 1,681 multi-entry messages in the archive of 2026-10-28 differed."""
|
||||
grouped: dict[str, list[AssistantTurn]] = {}
|
||||
for entry in entries:
|
||||
if isinstance(entry, AssistantTurn):
|
||||
grouped.setdefault(entry.message_id or entry.uuid, []).append(entry)
|
||||
return list(grouped.values())
|
||||
|
||||
|
||||
def field(found: dict, key: str) -> str:
|
||||
return value if isinstance(value := found.get(key), str) else ""
|
||||
|
||||
@@ -222,7 +231,7 @@ def tool_result(part: object) -> ToolResult | None:
|
||||
def result_text(content: object) -> str:
|
||||
if isinstance(content, str):
|
||||
return content
|
||||
# Claude Code may split one text across blocks, even inside a line, so the blocks join with nothing between them.
|
||||
# Claude Code may split one text across blocks, even inside a line, so the blocks join without anything between them.
|
||||
return "".join(part_text(part) or "" for part in content) if isinstance(content, list) else ""
|
||||
|
||||
|
||||
@@ -256,7 +265,7 @@ def rejected_until(event: dict) -> int | None:
|
||||
return resets_at if isinstance(resets_at, int) and not isinstance(resets_at, bool) else None
|
||||
|
||||
|
||||
# A count Claude Code left out or wrote as another type adds nothing, so one odd entry leaves the rest of a figure standing.
|
||||
# A count Claude Code left out or wrote as another type doesn't add anything, so one odd entry leaves the rest of a figure standing.
|
||||
def usage_count(usage: dict, field: str) -> int:
|
||||
"""One token count of a message's usage: {"input_tokens": 2, "cache_creation_input_tokens": 14541, "output_tokens": 8, ...}"""
|
||||
value = usage.get(field)
|
||||
|
||||
@@ -148,6 +148,13 @@ class EntryKinds(unittest.TestCase):
|
||||
uuid="u", parts=(entries.Text("Starting."), entries.ToolCall("toolu_1", "Bash", {"command": "ls"})), message_id="msg_1", model="claude-opus-5-5", usage={"input_tokens": 2},
|
||||
))
|
||||
|
||||
def test_messages_group_the_turns_that_share_a_message_id_and_fall_back_to_the_uuid_where_there_is_none(self):
|
||||
first = entries.AssistantTurn(uuid="a", message_id="msg_1", usage={"input_tokens": 1})
|
||||
other = entries.AssistantTurn(uuid="b", message_id="msg_2")
|
||||
again = entries.AssistantTurn(uuid="c", message_id="msg_1", usage={"input_tokens": 2})
|
||||
bare = entries.AssistantTurn(uuid="d")
|
||||
self.assertEqual(entries.messages([first, entries.HumanTurn(text="hi"), other, again, bare]), [[first, again], [other], [bare]])
|
||||
|
||||
def test_parses_tool_results_and_cost_states_and_reads_queued_notifications_and_other_kinds_as_plain_entries(self):
|
||||
self.assertEqual(entries.entry_from(human([{"type": "tool_result", "tool_use_id": "toolu_1", "content": "hi", "is_error": True}])), entries.ToolResults(results=(entries.ToolResult("toolu_1", "hi", True),)))
|
||||
self.assertEqual(entries.entry_from(queued("<task-notification>done</task-notification>", "task-notification")), entries.Entry())
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
"""The tokens a message's usage counts, by kind."""
|
||||
import dataclasses
|
||||
|
||||
from claude_code.entries import usage_count
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Tokens:
|
||||
"""Raw token counts by kind. Claude Code's usage doesn't count thinking apart from output, so output holds both."""
|
||||
input: int = 0
|
||||
write_5m: int = 0
|
||||
write_1h: int = 0
|
||||
read: int = 0
|
||||
output: int = 0
|
||||
|
||||
def plus(self, other: "Tokens") -> "Tokens":
|
||||
return Tokens(*(mine + theirs for mine, theirs in zip(dataclasses.astuple(self), dataclasses.astuple(other))))
|
||||
|
||||
|
||||
# {"input_tokens": 2, "cache_creation": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 25919}, "cache_read_input_tokens": 10365, "output_tokens": 193, ...}
|
||||
def tokens_of(usage: object) -> Tokens:
|
||||
"""The tokens of one message's usage, or of a json reply's; none where it is no object."""
|
||||
if not isinstance(usage, dict):
|
||||
return Tokens()
|
||||
written = usage.get("cache_creation")
|
||||
# A write without the split by lifetime counts as a five-minute one.
|
||||
five, hour = (usage_count(written, "ephemeral_5m_input_tokens"), usage_count(written, "ephemeral_1h_input_tokens")) if isinstance(written, dict) else (usage_count(usage, "cache_creation_input_tokens"), 0)
|
||||
return Tokens(usage_count(usage, "input_tokens"), five, hour, usage_count(usage, "cache_read_input_tokens"), usage_count(usage, "output_tokens"))
|
||||
@@ -60,6 +60,17 @@ def render(entries: list[Entry], typed_answer: typing.Callable[[str], Typed | No
|
||||
return "\n\n".join(lines)
|
||||
|
||||
|
||||
def human_answers(entries: list[Entry], typed_answer: typing.Callable[[str], Typed | None]) -> list[str]:
|
||||
"""Each answer the human typed, whole, as render shows it on a [human] line, latest last."""
|
||||
found = []
|
||||
for entry in entries:
|
||||
if isinstance(entry, HumanTurn):
|
||||
found.append(entry.text)
|
||||
elif isinstance(entry, LoopPrompt) and (typed := typed_answer(entry.text)):
|
||||
found.append(typed.answer)
|
||||
return found
|
||||
|
||||
|
||||
def assistant_lines(turn: AssistantTurn) -> list[str]:
|
||||
"""The turn's text and tool calls as the judge reads them."""
|
||||
return [line for part in turn.parts if (line := part_line(part, JUDGED_TOOL_INPUT))]
|
||||
|
||||
@@ -52,7 +52,7 @@ def segments(command: str) -> list[list[str]]:
|
||||
- a file descriptor before a redirect, as in `2>&1`, stays a word;
|
||||
- a heredoc's body is dropped;
|
||||
- variables, aliases and functions are not expanded;
|
||||
- a line with an unbalanced quote yields nothing."""
|
||||
- a line with an unbalanced quote doesn't yield anything."""
|
||||
text = uncommented(HEREDOC.sub(lambda heredoc: heredoc.group(0).split("\n", 1)[0], command))
|
||||
tokens = lexed(text)
|
||||
if tokens is None:
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"""Print a table of the shell command patterns a release's chunks ran.
|
||||
|
||||
usage: command-patterns [<version>]
|
||||
usage: command-patterns [<version>] [--calls <file>]
|
||||
|
||||
Run it inside a project checkout or one of its worktrees. It reads loop-claude's archive of the
|
||||
project, as reading-cost does, and takes each chunk that finished in the release's window: after
|
||||
@@ -17,9 +17,18 @@ The table has one row per pattern, most calls first. Its columns are the chunks
|
||||
pattern, its calls, and the tokens of its commands and of their results. Tokens are estimated at
|
||||
four characters each. The last column sums the seconds from each call to its result.
|
||||
|
||||
Exit 1, saying why, on unknown arguments, a version no tag names, or when git cannot start or finds
|
||||
no checkout, or the archive cannot be read.
|
||||
With --calls <file>, it first writes the file, replacing any it holds, with one line per Bash call:
|
||||
a JSON object with `chunk` (the chunk's number in the window, from 1, in the order the archive lists
|
||||
the chunks), `pattern` (as above), `seconds` (as in the table), `command_characters`,
|
||||
`result_characters` and `command`, the command's text. Lines follow the chunks in that order, and each
|
||||
chunk's threads. The file is readable by its owner alone. Commands may carry a secret, so write it
|
||||
outside any folder git tracks. Where it cannot be written, no table is printed.
|
||||
|
||||
Exit 1, saying why, on unknown arguments or --calls without a file; on a version no tag names; when git
|
||||
cannot start or finds no checkout; when the archive cannot be read; and when the --calls file cannot
|
||||
be written.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import sys
|
||||
@@ -28,23 +37,31 @@ from failure import Failure
|
||||
from transcript_archive.read import finished_chunks, read_threads
|
||||
from git_cli.git_repo import git
|
||||
from transcript_archive.location import project_archive
|
||||
from command_patterns.tally import records, table, tally
|
||||
from records.utc_stamp import seconds
|
||||
from command_patterns.tally import table, tally
|
||||
|
||||
USAGE = "usage: command-patterns [<version>]"
|
||||
USAGE = "usage: command-patterns [<version>] [--calls <file>]"
|
||||
|
||||
|
||||
def main(argv: list[str]) -> int:
|
||||
if argv in (["-h"], ["--help"]):
|
||||
print(__doc__.strip())
|
||||
return 0
|
||||
calls_file = None
|
||||
if "--calls" in argv:
|
||||
at = argv.index("--calls")
|
||||
if at + 1 == len(argv) or argv[at + 1].startswith("-"):
|
||||
print(f"command-patterns: --calls needs a file; {USAGE}", file=sys.stderr)
|
||||
return 1
|
||||
calls_file = pathlib.Path(argv[at + 1])
|
||||
argv = argv[:at] + argv[at + 2:]
|
||||
if any(word.startswith("-") for word in argv):
|
||||
print(f"command-patterns: unknown option in {' '.join(argv)}; {USAGE}", file=sys.stderr)
|
||||
return 1
|
||||
if len(argv) > 1:
|
||||
print(f"command-patterns: takes one version at most, not {' '.join(argv)}; {USAGE}", file=sys.stderr)
|
||||
return 1
|
||||
printed = report(argv[0] if argv else None)
|
||||
printed = report(argv[0] if argv else None, calls_file)
|
||||
if isinstance(printed, Failure):
|
||||
print(f"command-patterns: {printed.reason}", file=sys.stderr)
|
||||
return 1
|
||||
@@ -52,7 +69,7 @@ def main(argv: list[str]) -> int:
|
||||
return 0
|
||||
|
||||
|
||||
def report(version: str | None) -> str | Failure:
|
||||
def report(version: str | None, calls_file: pathlib.Path | None) -> str | Failure:
|
||||
common = git("rev-parse", "--path-format=absolute", "--git-common-dir")
|
||||
if isinstance(common, Failure):
|
||||
return common
|
||||
@@ -72,10 +89,25 @@ def report(version: str | None) -> str | Failure:
|
||||
if isinstance(read, Failure):
|
||||
return read
|
||||
threads.append(read)
|
||||
if calls_file is not None:
|
||||
saved = save_calls(calls_file, "".join(json.dumps(each) + "\n" for each in records(threads)))
|
||||
if saved:
|
||||
return saved
|
||||
named = f"v{version}" if version else "the release not yet cut"
|
||||
return f"Shell command patterns of {len(threads)} chunk{'' if len(threads) == 1 else 's'} in {named}:\n\n{table(tally(threads))}"
|
||||
|
||||
|
||||
def save_calls(path: pathlib.Path, text: str) -> Failure | None:
|
||||
"""Write text to path for its owner alone, since a command may carry a secret; path keeps no wider mode it already had."""
|
||||
try:
|
||||
with open(os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600), "w", encoding="utf-8") as file:
|
||||
os.fchmod(file.fileno(), 0o600)
|
||||
file.write(text)
|
||||
except OSError as failure:
|
||||
return Failure(f"{path}: {failure.strerror}")
|
||||
return None
|
||||
|
||||
|
||||
def window(version: str | None, cwd: str) -> tuple[int | None, int | None] | Failure:
|
||||
"""The release's window as tag dates in seconds since the epoch: after the tag before it, up to its own; None where it is open."""
|
||||
listed = git("-c", "versionsort.suffix=-", "tag", "--list", "v*", "--sort=-v:refname", "--format=%(refname:short) %(creatordate:unix)", cwd=cwd)
|
||||
|
||||
@@ -70,13 +70,21 @@ def elapsed(start: str, end: str) -> float:
|
||||
return 0.0
|
||||
|
||||
|
||||
def each_call(chunks: list[list[bytes]]) -> list[tuple[int, Call]]:
|
||||
"""Every Bash call, with its chunk's number from 1: chunks gives each chunk as the list of its threads, and the calls follow in that order."""
|
||||
return [(index, each) for index, threads in enumerate(chunks, 1) for thread in threads for each in calls(thread)]
|
||||
|
||||
|
||||
def records(chunks: list[list[bytes]]) -> list[dict[str, str | int | float]]:
|
||||
"""One record per Bash call, for `command-patterns --calls`: its chunk's number, pattern, seconds, command's and result's characters, and command's text."""
|
||||
return [{"chunk": index, "pattern": pattern(each.command), "seconds": each.seconds, "command_characters": len(each.command), "result_characters": len(each.result), "command": each.command} for index, each in each_call(chunks)]
|
||||
|
||||
|
||||
def tally(chunks: list[list[bytes]]) -> list[Row]:
|
||||
"""One row per pattern over the chunks, each given as its threads, most calls first."""
|
||||
found: dict[str, list[tuple[int, Call]]] = {}
|
||||
for index, threads in enumerate(chunks):
|
||||
for thread in threads:
|
||||
for each in calls(thread):
|
||||
found.setdefault(pattern(each.command), []).append((index, each))
|
||||
for index, each in each_call(chunks):
|
||||
found.setdefault(pattern(each.command), []).append((index, each))
|
||||
rows = [Row(name, len({index for index, _ in made}), len(made), sum(len(each.command) for _, each in made) // CHARACTERS_PER_TOKEN, sum(len(each.result) for _, each in made) // CHARACTERS_PER_TOKEN, round(sum(each.seconds for _, each in made))) for name, made in found.items()]
|
||||
return sorted(rows, key=lambda row: (-row.calls, row.pattern))
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ import unittest
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from test_env import isolated_env
|
||||
from command_patterns.tally import pattern, Row, tally
|
||||
from command_patterns.tally import pattern, records, Row, tally
|
||||
|
||||
TOOL = pathlib.Path(__file__).resolve().parents[1] / "command-patterns"
|
||||
|
||||
@@ -60,6 +60,20 @@ class Tally(unittest.TestCase):
|
||||
self.assertEqual(rows, [Row("ls", chunks=1, calls=1, command_tokens=0, result_tokens=1, seconds=1)])
|
||||
|
||||
|
||||
class Records(unittest.TestCase):
|
||||
def test_gives_each_call_its_chunk_pattern_seconds_sizes_and_text(self):
|
||||
first = [thread(call("a", "cd /x && git status --short", "2026-11-01T10:00:00Z"), result("a", "x" * 7, "2026-11-01T10:00:03Z"))]
|
||||
second = [thread(call("b", "ls", "2026-11-02T10:00:00Z"))]
|
||||
self.assertEqual(records([first, second]), [
|
||||
{"chunk": 1, "pattern": "git status", "seconds": 3.0, "command_characters": 27, "result_characters": 7, "command": "cd /x && git status --short"},
|
||||
{"chunk": 2, "pattern": "ls", "seconds": 0.0, "command_characters": 2, "result_characters": 0, "command": "ls"},
|
||||
])
|
||||
|
||||
def test_keeps_a_chunks_calls_from_each_of_its_threads_under_its_number(self):
|
||||
both = [thread(call("a", "ls", "2026-11-01T10:00:00Z")), thread(call("b", "pwd", "2026-11-01T11:00:00Z"))]
|
||||
self.assertEqual([(each["chunk"], each["command"]) for each in records([both])], [(1, "ls"), (1, "pwd")])
|
||||
|
||||
|
||||
class Main(unittest.TestCase):
|
||||
"""A checkout tagged v0.1.0 at 2026-11-01 and v0.2.0 at 2026-11-05, and three archived chunks, finished before, between and after them."""
|
||||
|
||||
@@ -108,6 +122,37 @@ class Main(unittest.TestCase):
|
||||
self.assertIn("| make old | 1 | 1 |", ran.stdout)
|
||||
self.assertNotIn("tea pr create", ran.stdout)
|
||||
|
||||
def test_writes_each_call_as_a_json_line_beside_the_table(self):
|
||||
saved = self.home / "calls.jsonl"
|
||||
ran = self.run_tool("0.2.0", "--calls", str(saved))
|
||||
self.assertEqual(ran.returncode, 0, ran.stderr)
|
||||
self.assertIn("| tea pr create | 1 | 1 |", ran.stdout)
|
||||
self.assertEqual([json.loads(line) for line in saved.read_text().splitlines()], [{"chunk": 1, "pattern": "tea pr create", "seconds": 0.0, "command_characters": 13, "result_characters": 2, "command": "tea pr create"}])
|
||||
|
||||
def test_makes_the_calls_file_readable_by_its_owner_alone_even_where_it_existed(self):
|
||||
saved = self.home / "calls.jsonl"
|
||||
saved.write_text("old")
|
||||
saved.chmod(0o644)
|
||||
self.assertEqual(self.run_tool("0.2.0", "--calls", str(saved)).returncode, 0)
|
||||
self.assertEqual(saved.stat().st_mode & 0o777, 0o600)
|
||||
self.assertNotIn("old", saved.read_text())
|
||||
|
||||
def test_takes_the_calls_flag_before_the_version_too(self):
|
||||
saved = self.home / "calls.jsonl"
|
||||
self.assertEqual(self.run_tool("--calls", str(saved), "0.2.0").returncode, 0)
|
||||
self.assertEqual(len(saved.read_text().splitlines()), 1)
|
||||
|
||||
def test_refuses_a_calls_flag_without_a_file(self):
|
||||
ran = self.run_tool("--calls")
|
||||
self.assertEqual(ran.returncode, 1)
|
||||
self.assertIn("--calls", ran.stderr)
|
||||
|
||||
def test_fails_where_the_calls_file_cannot_be_written(self):
|
||||
ran = self.run_tool("--calls", str(self.home / "no-such-folder" / "calls.jsonl"))
|
||||
self.assertEqual(ran.returncode, 1)
|
||||
self.assertIn("no-such-folder", ran.stderr)
|
||||
self.assertEqual(ran.stdout, "")
|
||||
|
||||
def test_refuses_a_release_no_tag_names(self):
|
||||
ran = self.run_tool("0.9.0")
|
||||
self.assertEqual(ran.returncode, 1)
|
||||
|
||||
@@ -34,9 +34,14 @@ def deploy(checkout: str) -> str | Failure:
|
||||
if isinstance(git("merge-base", "--is-ancestor", "HEAD", tag, cwd=checkout), Failure):
|
||||
return Failure(f"{tag} doesn't hold the checkout's commit, so the move would drop work no release holds: cut a release that holds it first")
|
||||
settings_changed = isinstance(git("diff", "--quiet", "HEAD", tag, "--", "settings.json", cwd=checkout), Failure)
|
||||
# The tag holds each uncommitted change, so undoing them loses nothing, and lets the checkout below take the tag's copy.
|
||||
if changed.split():
|
||||
restored = git("checkout", "--quiet", "HEAD", "--", *changed.split(), cwd=checkout)
|
||||
# The tag holds each uncommitted change, so undoing them doesn't lose anything, and lets the checkout below take the tag's copy.
|
||||
# A settings.json the clean filter shows unchanged may still differ on disk, by a model pick or Claude Code's key order, which checkout refuses to overwrite; the pick is asked for again below.
|
||||
tracked = git("ls-files", "--", "settings.json", cwd=checkout)
|
||||
if isinstance(tracked, Failure):
|
||||
return tracked
|
||||
set_aside = sorted({*changed.split(), *tracked.split()} if settings_changed else set(changed.split()))
|
||||
if set_aside:
|
||||
restored = git("checkout", "--quiet", "HEAD", "--", *set_aside, cwd=checkout)
|
||||
if isinstance(restored, Failure):
|
||||
return restored
|
||||
moved = git("checkout", "--quiet", "--detach", tag, cwd=checkout)
|
||||
|
||||
@@ -98,15 +98,20 @@ def required_checks(forge: Forge, base: str, run: Run) -> set[str] | Failure:
|
||||
return Failure(f"tea api answered branch {base} in a shape that can't be read: {str(branch)[:200]}")
|
||||
|
||||
|
||||
def checks_passed(forge: Forge, number: str, head: str, required: set[str], run: Run, sleep: typing.Callable[[float], None] = time.sleep) -> Failure | None:
|
||||
"""None once every check on pull request number, whose head commit is head, has passed, or where it has none; a Failure where one fails, or where they have not all passed within WAIT_SECONDS.
|
||||
def checks_passed(forge: Forge, number: str, head: str, required: set[str], run: Run, sleep: typing.Callable[[float], None] = time.sleep, settle: int = 0) -> Failure | None:
|
||||
"""None once every check on pull request number, whose head commit is head, has passed, or where it has none for settle seconds; a Failure where one fails, or where they have not all passed within WAIT_SECONDS.
|
||||
|
||||
On Gitea it also waits for a passed check to match each of required: a check CI has yet to queue is no status at all.
|
||||
"""
|
||||
if forge == "gh":
|
||||
watched = run(["gh", "pr", "checks", number, "--watch", "--fail-fast"])
|
||||
if isinstance(watched, Failure) and "no checks reported" not in watched.reason:
|
||||
return watched
|
||||
for waited in range(0, settle + 1, POLL_SECONDS):
|
||||
watched = run(["gh", "pr", "checks", number, "--watch", "--fail-fast"])
|
||||
if not isinstance(watched, Failure):
|
||||
return None
|
||||
if "no checks reported" not in watched.reason:
|
||||
return watched
|
||||
if waited < settle:
|
||||
sleep(POLL_SECONDS)
|
||||
return None
|
||||
for _ in range(WAIT_SECONDS // POLL_SECONDS + 1):
|
||||
status = gitea(run, f"repos/{{owner}}/{{repo}}/commits/{head}/status")
|
||||
@@ -121,7 +126,7 @@ def checks_passed(forge: Forge, number: str, head: str, required: set[str], run:
|
||||
return Failure(f"a check on pull request {number} ended in {state}")
|
||||
# Gitea matches a required context as a glob, and reads a commit with no status as pending, with total_count 0.
|
||||
missing = sorted(pattern for pattern in required if not fnmatch.filter(passed, pattern))
|
||||
if (count == 0 or state == "success") and not missing:
|
||||
if (count == 0 and _ * POLL_SECONDS >= settle or state == "success") and not missing:
|
||||
return None
|
||||
if _ < WAIT_SECONDS // POLL_SECONDS:
|
||||
sleep(POLL_SECONDS)
|
||||
|
||||
@@ -17,7 +17,7 @@ the move would drop work no release holds. Untracked files, such as Claude Code'
|
||||
memory, stay as they are.
|
||||
|
||||
--cut runs in the development clone, and refuses where that clone's origin isn't <checkout>'s. It cuts the next release, as chunk-preflight works it out, and
|
||||
refuses, changing nothing, unless that release holds no item in todo.md, its release review has
|
||||
refuses without changing anything, unless that release holds no item in todo.md, its release review has
|
||||
landed and changes are unreleased. The release names the version; the tool doesn't choose one.
|
||||
1. On a fresh origin/main, it renames ## Unreleased in CHANGELOG.md to the version, commits that
|
||||
titled `Cut release <version>`, and pushes it as the branch release-<version>. The clone's own
|
||||
|
||||
@@ -122,6 +122,20 @@ class DeployRelease(unittest.TestCase):
|
||||
self.assertEqual(self.head(), "v0.3.0")
|
||||
self.assertIn('"model"', (self.target / "settings.json").read_text(), "a release that leaves settings.json as it was keeps the pick")
|
||||
|
||||
def test_moves_a_settings_json_that_differs_only_by_a_model_pick_and_key_order_where_the_release_changes_it(self):
|
||||
self.release("0.2.0", "- Second.\n", '{\n "permissions": {},\n "theme": "dark"\n}\n')
|
||||
self.git(self.target, "fetch", "-q", "--tags", "origin")
|
||||
self.git(self.target, "checkout", "-q", "--detach", "v0.2.0")
|
||||
(self.target / ".gitattributes").write_text("/settings.json filter=settings\n")
|
||||
self.git(self.target, "config", "filter.settings.clean", f"{sys.executable} {TOOL.parent / 'settings_filter.py'}")
|
||||
(self.target / "settings.json").write_text('{\n "theme": "dark",\n "model": "opus",\n "permissions": {}\n}\n')
|
||||
self.release("0.3.0", "- Third.\n", '{\n "permissions": {},\n "theme": "light"\n}\n')
|
||||
ran = self.deploy()
|
||||
self.assertEqual(ran.returncode, 0, ran.stderr)
|
||||
self.assertEqual(self.head(), "v0.3.0")
|
||||
self.assertEqual((self.target / "settings.json").read_text(), '{\n "permissions": {},\n "theme": "light"\n}\n')
|
||||
self.assertIn("settings.json changed: pick the model again with /model.", ran.stdout)
|
||||
|
||||
def test_asks_for_the_model_again_where_the_release_changes_settings_json(self):
|
||||
self.release("0.2.0", "- Second.\n", '{"theme": "light"}\n')
|
||||
ran = self.deploy()
|
||||
|
||||
@@ -76,7 +76,7 @@ class Guarded(unittest.TestCase):
|
||||
|
||||
|
||||
class StalledOrigin(unittest.TestCase):
|
||||
"""A checkout whose origin, run through git's ext transport, answers nothing for 10 s, and which records no default branch for it."""
|
||||
"""A checkout whose origin, run through git's ext transport, doesn't answer for 10 s, and which records no default branch for it."""
|
||||
|
||||
def setUp(self):
|
||||
temp = tempfile.TemporaryDirectory()
|
||||
|
||||
@@ -11,12 +11,18 @@ 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, highest first: from the model's cheapest rung down
|
||||
to the lowest rung a worker routes to. 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`.
|
||||
then replays the rest on each rung above the model's cheapest that a chunk's E + I raises a
|
||||
review to, except the reference judge's rung. Then it replays them on each candidate rung,
|
||||
highest first: from the model's cheapest rung down to the lowest rung a worker routes to. It stops
|
||||
at the first candidate that misses one. It prints each verdict the reference judge did not
|
||||
reproduce, each verdict a rung missed, and the lowest candidate that, like each candidate above
|
||||
it, missed none.
|
||||
|
||||
Record each run in docs/decisions.md → `routing: on a model judge-replay covered`. Where the
|
||||
model's cheapest rung misses no interrupt, the run is the evidence to add the model to
|
||||
JUDGE_REPLAYED in bin/loop_claude/routing.py, which routes that model's judge. judge_rung there
|
||||
keeps the judge to its own model's rungs; a rung above them that misses no interrupt is the
|
||||
evidence to let the judge climb onto it.
|
||||
|
||||
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
|
||||
@@ -36,7 +42,7 @@ from loop_effects.effects import Effects
|
||||
from failure import Failure
|
||||
from rung_replay.search import first_reply, replayed
|
||||
from claude_code.reply import Limited
|
||||
from model_routing.ladder import lowest_worker_rung, project_rung, Rung
|
||||
from model_routing.ladder import lowest_worker_rung, position, project_rung, review_floor, REVIEW_STEPS, Rung
|
||||
from loop_claude.project.premises import read_premises
|
||||
from loop_claude.project.records import read_records
|
||||
from claude_code.transcript import read_transcript
|
||||
@@ -61,7 +67,7 @@ def main(argv: list[str], env: typing.Mapping[str, str], home: pathlib.Path, eff
|
||||
cases = sample(cases, PER_KIND)
|
||||
reference = Rung(project.model, REFERENCE_EFFORT)
|
||||
# The candidates stop at the lowest rung a worker routes to: no route uses a rung below it for the judge.
|
||||
replay = replayed(cases, reference, down_from(project, lowest_worker_rung(project)), lambda found, rung: rule(found, rung, home / ".claude", effects), reproduced, "verdicts")
|
||||
replay = replayed(cases, reference, down_from(project, lowest_worker_rung(project)), lambda found, rung: rule(found, rung, home / ".claude", effects), reproduced, "verdicts", climbs(project, reference))
|
||||
if isinstance(replay, Limited):
|
||||
return limited_exit(TOOL, replay)
|
||||
print(report(project.model, reference, cases, replay))
|
||||
@@ -73,6 +79,11 @@ def model_argument(argv: list[str]) -> Rung | None:
|
||||
return project_rung(argv[0]) if len(argv) == 1 else None
|
||||
|
||||
|
||||
def climbs(project: Rung, reference: Rung) -> list[Rung]:
|
||||
"""The rungs above the project's rung that an E + I raises a review to, except the reference's, lowest first."""
|
||||
return sorted({review_floor(project, score) for score in REVIEW_STEPS} - {project, reference}, key=position)
|
||||
|
||||
|
||||
def archived_cases(model: str, root: pathlib.Path, home: pathlib.Path) -> list[Case] | Failure:
|
||||
projects = projects_on(model, home)
|
||||
if isinstance(projects, Failure):
|
||||
|
||||
@@ -75,13 +75,15 @@ def report(model: str, reference: Rung, cases: list[Case], replay: Replay[Case,
|
||||
f"The reference judge, {reference}, reproduced {len(cases) - len(unreproduced)}{'. It returned another kind on:' if unreproduced else '.'}",
|
||||
*missed_lines(unreproduced),
|
||||
]
|
||||
for climb in replay.climbed:
|
||||
lines += [f"{climb.rung}, a rung a review climbs to, missed {len(climb.missed)}{':' if climb.missed else '.'}", *missed_lines([(miss.case, miss.reply) for miss in climb.missed])]
|
||||
for tried in replay.tried:
|
||||
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:
|
||||
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}")
|
||||
lines.append(f"Lowest candidate that, like each candidate above it, returns every verdict the reference judge reproduces: {lowest}")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
|
||||
@@ -77,13 +77,22 @@ class Report(unittest.TestCase):
|
||||
"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: archived Verdict: interrupt, replayed Verdict: finished",
|
||||
"Lowest rung that, like each rung above it, returns every verdict the reference judge reproduces: claude-sonnet-5-5 at high effort",
|
||||
"Lowest candidate that, like each candidate 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([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], "Lowest rung that, like each rung above it, returns every verdict the reference judge reproduces: none, the project's rung misses one")
|
||||
self.assertEqual(missed_all[-1], "Lowest candidate that, like each candidate 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 test_names_each_miss_of_each_rung_the_judge_climbs_to_before_the_search_down(self):
|
||||
cases = [case("2026-10-14T10:00:00Z", FINISHED), case("2026-10-14T10:00:01Z", INTERRUPTED)]
|
||||
climbs = [Tried(Rung("claude-fable-5-2", "low"), [Miss(cases[1], INTERRUPTED, FINISHED)]), Tried(Rung("claude-fable-5-2", "high"), [])]
|
||||
self.assertEqual(report("claude-opus-5-5", REFERENCE, cases, Replay([FINISHED, INTERRUPTED], [Tried(MIDDLE, [])], MIDDLE, climbs)).splitlines()[2:5], [
|
||||
"claude-fable-5-2 at low effort, a rung a review climbs to, missed 1:",
|
||||
" /code/p 2026-10-14T10:00:01Z: archived Verdict: interrupt, replayed Verdict: finished",
|
||||
"claude-fable-5-2 at high effort, a rung a review climbs to, missed 0.",
|
||||
])
|
||||
|
||||
|
||||
def unused(*_):
|
||||
raise AssertionError("not called")
|
||||
@@ -115,7 +124,7 @@ class Main(unittest.TestCase):
|
||||
result = reply(Rung(args[args.index("--model") + 1], args[args.index("--effort") + 1]), "said Verdict: interrupt" in prompt.rsplit("latest last:", 1)[-1])
|
||||
return subprocess.CompletedProcess(args, 0, json.dumps(result), "")
|
||||
|
||||
effects = Effects(alive=unused, claude=claude, claude_on_terminal=unused, discard_typed=unused, execv=unused, git=unused, input=unused, input_or=unused, local_time=unused, memory=unused, new_id=unused, now=unused, on_terminal=unused, pid=unused, python=unused, sleep=unused, stream_claude=unused)
|
||||
effects = Effects(alive=unused, claude=claude, claude_on_terminal=unused, discard_typed=unused, dm=unused, execv=unused, git=unused, input=unused, input_or=unused, local_time=unused, memory=unused, new_id=unused, now=unused, on_terminal=unused, pid=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)
|
||||
@@ -123,19 +132,24 @@ class Main(unittest.TestCase):
|
||||
|
||||
@staticmethod
|
||||
def verdict(interrupt, evidence):
|
||||
output = {"answer": "", "escalation": "", "evidence": evidence, "finished": not interrupt, "interrupt": interrupt, "question": "Which?" if interrupt else "", "answered_before": "", "left_open": "", "release_ready": False}
|
||||
output = {"answer": "", "escalation": "", "evidence": evidence, "finished": not interrupt, "interrupt": interrupt, "question": "Which?" if interrupt else "", "answered_before": "", "left_open": "", "reversed": "", "release_ready": False}
|
||||
return {"type": "result", "structured_output": output}
|
||||
|
||||
def test_replays_the_models_projects_on_the_reference_then_from_the_projects_rung_down_and_prints_the_lowest_that_returns_all(self):
|
||||
# Sonnet misses the interrupt; Opus returns both.
|
||||
def test_replays_the_models_projects_on_the_reference_then_on_each_rung_the_judge_climbs_to_then_from_the_projects_rung_down_and_prints_the_lowest_that_returns_all(self):
|
||||
# Sonnet and Fable at medium miss the interrupt; Opus returns both.
|
||||
def reply(rung, interrupted):
|
||||
return self.verdict(interrupted and rung.model != "claude-sonnet-5-5", f"said {INTERRUPTED if interrupted else FINISHED}")
|
||||
return self.verdict(interrupted and rung not in (MIDDLE, Rung("claude-fable-5-2", "medium")), 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-opus-5-5", "medium"), ("claude-sonnet-5-5", "high")])
|
||||
self.assertEqual([(model, effort) for model, effort, _ in self.calls[::2]], [
|
||||
("claude-opus-5-5", "xhigh"),
|
||||
("claude-fable-5-2", "low"), ("claude-fable-5-2", "medium"), ("claude-fable-5-2", "high"),
|
||||
("claude-opus-5-5", "medium"), ("claude-sonnet-5-5", "high"),
|
||||
])
|
||||
self.assertIn("The reference judge, claude-opus-5-5 at xhigh effort, reproduced 2.", out)
|
||||
self.assertIn("claude-fable-5-2 at low effort, a rung a review climbs to, missed 0.\nclaude-fable-5-2 at medium effort, a rung a review climbs to, missed 1:", out)
|
||||
self.assertTrue(out.endswith("returns every verdict the reference judge reproduces: claude-opus-5-5 at medium effort\n"))
|
||||
for said in ("The task the worker was given:\nDo it.", "1. Ship.", "From ~/.claude/CLAUDE.md:\nBe kind."):
|
||||
with self.subTest(said=said):
|
||||
@@ -151,18 +165,19 @@ class Main(unittest.TestCase):
|
||||
self.assertEqual([(model, effort) for model, effort, _ in self.calls[::2]][-1], ("claude-sonnet-5-5", "high"))
|
||||
self.assertTrue(out.endswith("returns every verdict the reference judge reproduces: claude-sonnet-5-5 at high effort\n"), out)
|
||||
|
||||
def test_a_fable_project_tries_no_rung_below_opus_at_max_and_its_report_names_fable(self):
|
||||
(self.home / ".claude" / "loop-claude-models.json").write_text(json.dumps({"proj": "claude-opus-5-5", "other": "claude-fable-5-1"}))
|
||||
code, out, err = self.run_main(["claude-fable-5-1"], lambda rung, interrupted: self.verdict(interrupted, f"said {INTERRUPTED if interrupted else FINISHED}"))
|
||||
def test_a_fable_project_tries_no_rung_below_opus_at_medium_and_its_report_names_fable(self):
|
||||
(self.home / ".claude" / "loop-claude-models.json").write_text(json.dumps({"proj": "claude-opus-5-5", "other": "claude-fable-5-2"}))
|
||||
code, out, err = self.run_main(["claude-fable-5-2"], lambda rung, interrupted: self.verdict(interrupted, f"said {INTERRUPTED if interrupted else FINISHED}"))
|
||||
self.assertEqual(code, 0, err)
|
||||
self.assertEqual([(model, effort) for model, effort, _ in self.calls][-1], ("claude-opus-5-5", "max"))
|
||||
self.assertTrue(out.splitlines()[0].startswith("Replayed 1 verdicts of claude-fable-5-1 projects"), out)
|
||||
self.assertTrue(out.endswith("returns every verdict the reference judge reproduces: claude-opus-5-5 at max effort\n"), out)
|
||||
self.assertEqual([(model, effort) for model, effort, _ in self.calls][-1], ("claude-opus-5-5", "medium"))
|
||||
self.assertTrue(out.splitlines()[0].startswith("Replayed 1 verdicts of claude-fable-5-2 projects"), out)
|
||||
self.assertTrue(out.endswith("returns every verdict the reference judge reproduces: claude-opus-5-5 at medium effort\n"), out)
|
||||
|
||||
def test_stops_at_the_projects_rung_and_names_none_when_it_misses(self):
|
||||
code, out, _ = self.run_main(["claude-opus-5-5"], lambda rung, interrupted: self.verdict(interrupted and rung == REFERENCE, f"said {INTERRUPTED if interrupted else FINISHED}"))
|
||||
self.assertEqual(code, 0)
|
||||
self.assertEqual({(model, effort) for model, effort, _ in self.calls[2:]}, {("claude-opus-5-5", "medium")})
|
||||
# The reference and the three rungs a review climbs to each replay both verdicts first.
|
||||
self.assertEqual({(model, effort) for model, effort, _ in self.calls[8:]}, {("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):
|
||||
@@ -192,9 +207,9 @@ class Main(unittest.TestCase):
|
||||
self.assertEqual(self.run_main(argv, unused)[0], 1)
|
||||
|
||||
def test_exits_1_for_a_model_no_project_runs_on(self):
|
||||
code, _, err = self.run_main(["claude-fable-5-1"], unused)
|
||||
code, _, err = self.run_main(["claude-fable-5-2"], unused)
|
||||
self.assertEqual(code, 1)
|
||||
self.assertIn("no archived verdicts of projects on claude-fable-5-1", err)
|
||||
self.assertIn("no archived verdicts of projects on claude-fable-5-2", err)
|
||||
|
||||
def test_exits_1_on_an_unreadable_models_file(self):
|
||||
(self.home / ".claude" / "loop-claude-models.json").write_text("[")
|
||||
|
||||
@@ -11,6 +11,7 @@ from failure import Failure
|
||||
from larv_review.seats import FIRST_SEATS, scores, seats_file, SeatsFile
|
||||
from larv_review.scoring import floor_step, means, under_floor
|
||||
from release_plan import plan_file
|
||||
from larv_review.scoring_setup import removed_setup
|
||||
from records.file_writes import replace_file
|
||||
|
||||
|
||||
@@ -61,7 +62,9 @@ def record_scoring(default: str, scores_file: pathlib.Path, ids: list[int]) -> F
|
||||
print(floor_step(scoring.means, plan, ids))
|
||||
if unrecorded := append(given.read, scoring_entry(named.title, scoring)):
|
||||
return unrecorded
|
||||
return rerank()
|
||||
reranked = rerank()
|
||||
removed = removed_setup(checkout)
|
||||
return reranked or (removed and Failure(f"recorded the run, but {removed.reason}"))
|
||||
|
||||
|
||||
def rerank() -> Failure | None:
|
||||
|
||||
+112
-38
@@ -1,6 +1,6 @@
|
||||
"""Hold larv-review's mechanical rules: the chunk's review folder, the paired ruling's base and vote count, each pass's rounds, the scoring run's trigger; the comprehension history's format, its latest places and its count of how often seats agree; and the header of each reviewer's prompt.
|
||||
"""Hold larv-review's mechanical rules: the chunk's review folder, the paired ruling's base and vote count, each pass's rounds, the scoring run's trigger and setup; the comprehension history's format, its latest places and its count of how often seats agree; and the header of each reviewer's prompt.
|
||||
|
||||
usage: larv-review review-folder | ruling-base | round-count | needs-scoring-run [<item ID>...] | scoring-run-owed | record-ruling <votes file> | record-scoring <scores file> [<item ID>...] | places | agreement | reviewer-header <pass> [--rerun]
|
||||
usage: larv-review {commands}
|
||||
|
||||
The comprehension check records how hard a project is to read, two ways, and no score blocks a merge. In a
|
||||
paired ruling, simulated readers, the seats, read the branch's head beside a base and vote better,
|
||||
@@ -32,8 +32,8 @@ each name in such a title that is not a pass.
|
||||
|
||||
needs-scoring-run takes the IDs of the todo.md items the chunk ships, none when it ships none, and
|
||||
prints why the chunk is due a scoring run, or `No scoring run due.` It is due when the chunk ships
|
||||
an item whose tagline names the comprehension floor. It is also due when the chunk leaves a release
|
||||
with no item in the checkout's todo.md, once the shipped items are set aside, and work has landed
|
||||
a floor item, one whose tagline opens with `Reach the comprehension floor:`. It is also due when the
|
||||
chunk leaves a release with no item in the checkout's todo.md, once the shipped items are set aside, and work has landed
|
||||
towards that release; bin/larv_review/plan.py's `work_landed` and `landed_towards` say when. A release the checkout's
|
||||
todo.md marks renamed in its ## Renamed section, as `- 0.2.1 renamed to 0.3.0`, is due none.
|
||||
A chunk is also due one while no scoring run in the default branch's history is newer than the
|
||||
@@ -43,7 +43,7 @@ docs/decisions.md opts out of the comprehension check is never due one.
|
||||
scoring-run-owed prints `No scoring run owed.` or exits 1 naming the runs the chunk owes and has
|
||||
not recorded. chunk-pr merge runs it and refuses to merge on exit 1, so a due line read earlier in
|
||||
the chunk can't stand in for it. It applies needs-scoring-run's rule to the checkout's todo.md and the committed history, against the
|
||||
merge base with the default branch, so a default branch that has moved on adds nothing: the items
|
||||
merge base with the default branch, so a default branch that has moved on doesn't add anything: the items
|
||||
the merge base's todo.md holds and the checkout's does not count as shipped. A chunk that empties a
|
||||
release owes two runs, any other due chunk one. The chunk has recorded the scoring runs that its
|
||||
committed docs/comprehension-history.md holds beyond the merge base's. A project that opts out or
|
||||
@@ -78,19 +78,31 @@ better, same or worse. Each place opens with the names from the seat's line that
|
||||
`, ` and followed by `: `. A dimension's vote counts as same unless one of the seat's places opens
|
||||
with that dimension and holds a `path:line` in backticks; the overall vote counts as same unless any
|
||||
place holds one. The printed votes say so. When the two counted overall votes differ, it appends
|
||||
nothing and prints `Split:`, saying to add the maintainability senior's and Junior A's lines.
|
||||
no line and prints `Split:`, saying to add the maintainability senior's and Junior A's lines.
|
||||
Otherwise the ruling is the overall vote that leads each other vote by two or more, else same. It
|
||||
prints `Ruling:` and appends the ruling.
|
||||
|
||||
prepare-scoring sets up a scoring run in the chunk's review folder: a detached worktree of the
|
||||
checkout's HEAD, which the seats read, and one prompt file per seat beside it, as
|
||||
skills/comprehension-panel/seat-prompts.md builds them. It prints the worktree's path and each
|
||||
prompt's. It takes {{language}}, {{kind}}, {{domain}}, {{domain docs}} and {{3am question}} from the
|
||||
checkout's AGENTS.md → "Scoring run". claude-config keeps no AGENTS.md, so there it takes them from
|
||||
seat-prompts.md → "claude-config's values". It fills the other placeholders from the worktree and
|
||||
the panel's SKILL.md. --preloaded replaces {{preloaded}}, which by default names each CLAUDE.md the main checkout's claudeMdExcludes doesn't exclude, its
|
||||
imports and each rule file without `paths:` that Claude Code loads into a seat. Where any one of
|
||||
the five values is missing, it exits 1 and doesn't write anything. Where a setup that
|
||||
record-scoring never removed is still there, it removes it first and says so.
|
||||
|
||||
record-scoring takes the scores file of a run needs-scoring-run calls, whose first line names no
|
||||
`, against`, and the same item IDs, and exits 1 when they call no run. It appends the seats' scores
|
||||
and their means, rounded half up to two decimals, prints the means and, when a mean is under the
|
||||
floor of {floor}, a line opening `Floor:` naming each one. A line opening `Next:` follows it. It
|
||||
says to file a floor item, one whose tagline holds `comprehension floor`, aimed at the lowest of the
|
||||
four dimensions. Where the checkout's todo.md holds such an item other than those given, it says to
|
||||
says to file a floor item aimed at the lowest of the four dimensions, and names the tagline's opening
|
||||
`Reach the comprehension floor:`. Where the checkout's todo.md holds such an item other than those given, it says to
|
||||
refresh that item instead. Then it ranks the checkout's todo.md as rank_todo.py does, since the
|
||||
overall sets the weight of code health, the goal every project shares, and exits 1 where
|
||||
rank_todo.py would, with the run recorded.
|
||||
rank_todo.py would, with the run recorded. Last, it removes what prepare-scoring set up, so a
|
||||
second run of one head runs prepare-scoring again.
|
||||
|
||||
record-ruling and record-scoring append each entry to the history, created when missing, under a
|
||||
heading of the current UTC time and the seats file's first line. Each commit that line names must be
|
||||
@@ -112,13 +124,22 @@ reviewer-header takes the name of a pass that an agent under agents/ reviews, sp
|
||||
prints it, such as stability. It prints the header of the prompt that launches the pass's reviewer
|
||||
in its next round: the pass and round, the branch's open pull request at its pushed head, the
|
||||
worktree and branch, the merge base of HEAD and the default branch, and the paths of the reviewer's
|
||||
report, the branch diff and, for architecture and stability, the places. It writes the diff, from
|
||||
report, the branch diff and, for architecture and stability, the places. For a reviewer whose
|
||||
definition under ~/.claude/agents/ has `omitClaudeMd: true`, it then names the file that holds the
|
||||
project principles and decision titles, where the project keeps one. It writes the diff, from
|
||||
that base to HEAD, into the chunk's review folder as branch-<short HEAD>.diff, and writes what
|
||||
places prints into places.md; a file whose text is unchanged is left as it is. With --rerun, the
|
||||
header names the report of a relaunch one rung up, in the same round, and the report that asked for
|
||||
it. It exits 1 when the pass takes no more rounds, or, with --rerun, when the report that asked is
|
||||
missing.
|
||||
|
||||
reviewer-context is the SubagentStart hook. It reads the hook's input on stdin. For a reviewer
|
||||
whose definition under ~/.claude/agents/ has `omitClaudeMd: true`, and so starts without CLAUDE.md,
|
||||
it prints the hook reply that hands the agent the Shared goal, Prose and Vocabulary sections of
|
||||
~/.claude/CLAUDE.md; for any other agent it doesn't print anything. Where it cannot read the file
|
||||
or a section, the reply tells the reviewer to open its report with that failure, and it exits 0,
|
||||
since Claude Code starts the subagent whatever the hook exits with.
|
||||
|
||||
Exit 1, saying why, on unknown arguments, an unknown item ID, a seats file it cannot read or that
|
||||
breaks the shape above, a todo.md that fails rank_todo.py after record-scoring records a run, or
|
||||
when git cannot start, finds no checkout or no default branch, cannot fetch origin for ruling-base,
|
||||
@@ -135,50 +156,90 @@ from review_rules.round_titles import cap, CAP, RELEASE_REVIEW_CAP, round_counts
|
||||
from failure import Failure
|
||||
from review_rules.comprehension_history import FLOOR
|
||||
from larv_review.history_changes import history_changes
|
||||
from review_rules.reviewer_context import hook_reply
|
||||
from review_rules.review_folder import made_review_folder
|
||||
from larv_review.ruling_base import measured_commit
|
||||
from larv_review.agreement import MIN_PAIRS
|
||||
from larv_review.owed import owed_scoring_run
|
||||
from review_rules.review_passes import PASSES, REVIEWERS
|
||||
from larv_review.plan import plan_reasons
|
||||
from larv_review.scoring_setup import prepare_scoring
|
||||
from larv_review.history_commands import record_ruling, record_scoring, show_agreement, show_places
|
||||
from larv_review.reviewer_header import reviewer_header
|
||||
|
||||
USAGE = "usage: larv-review review-folder | ruling-base | round-count | needs-scoring-run [<item ID>...] | scoring-run-owed | record-ruling <votes file> | record-scoring <scores file> [<item ID>...] | places | agreement | reviewer-header <pass> [--rerun]"
|
||||
|
||||
class Command(typing.NamedTuple):
|
||||
"""One subcommand: how the usage line spells it, whether the arguments after its name fit, and what it does with them. Where it ends in item IDs, ids_from is the number of arguments before them, so main can name the arguments that aren't IDs."""
|
||||
shape: str
|
||||
fits: typing.Callable[[list[str]], bool]
|
||||
run: typing.Callable[[list[str]], Failure | None]
|
||||
ids_from: int | None = None
|
||||
|
||||
|
||||
ITEM_ID = re.compile(r"[0-9]+")
|
||||
|
||||
|
||||
def no_arguments(given: list[str]) -> bool:
|
||||
return not given
|
||||
|
||||
|
||||
def are_ids(given: list[str]) -> bool:
|
||||
return all(ITEM_ID.fullmatch(id_) for id_ in given)
|
||||
|
||||
|
||||
def run_needs_scoring_run(given: list[str]) -> Failure | None:
|
||||
return with_default_branch(lambda default: needs_scoring_run(default, [int(id_) for id_ in given]), stale_ok=False)
|
||||
|
||||
|
||||
def fits_prepare_scoring(given: list[str]) -> bool:
|
||||
return not given or len(given) == 2 and given[0] == "--preloaded"
|
||||
|
||||
|
||||
def run_record_scoring(given: list[str]) -> Failure | None:
|
||||
return with_default_branch(lambda default: record_scoring(default, pathlib.Path(given[0]), [int(id_) for id_ in given[1:]]), stale_ok=False)
|
||||
|
||||
|
||||
def fits_reviewer_header(given: list[str]) -> bool:
|
||||
return bool(given) and given[0] in REVIEWERS and given[1:] in ([], ["--rerun"])
|
||||
|
||||
|
||||
def run_reviewer_header(given: list[str]) -> Failure | None:
|
||||
return with_default_branch(lambda default: reviewer_header(default, given[0], given[1:] == ["--rerun"]), stale_ok=True)
|
||||
|
||||
|
||||
# One row per subcommand: main, USAGE and `--help` all read this table.
|
||||
COMMANDS = {
|
||||
"review-folder": Command("review-folder", no_arguments, lambda given: make_review_folder()),
|
||||
"ruling-base": Command("ruling-base", no_arguments, lambda given: with_default_branch(show_ruling_base, stale_ok=False)),
|
||||
"round-count": Command("round-count", no_arguments, lambda given: with_default_branch(round_count, stale_ok=True)),
|
||||
"needs-scoring-run": Command("needs-scoring-run [<item ID>...]", are_ids, run_needs_scoring_run, ids_from=0),
|
||||
"scoring-run-owed": Command("scoring-run-owed", no_arguments, lambda given: with_default_branch(owed, stale_ok=False)),
|
||||
"record-ruling": Command("record-ruling <votes file>", lambda given: len(given) == 1, lambda given: record_ruling(pathlib.Path(given[0]))),
|
||||
"prepare-scoring": Command("prepare-scoring [--preloaded <text>]", fits_prepare_scoring, lambda given: prepared_scoring(given[1] if given else None)),
|
||||
"record-scoring": Command("record-scoring <scores file> [<item ID>...]", lambda given: bool(given) and are_ids(given[1:]), run_record_scoring, ids_from=1),
|
||||
"places": Command("places", no_arguments, lambda given: show_places()),
|
||||
"agreement": Command("agreement", no_arguments, lambda given: show_agreement()),
|
||||
"reviewer-header": Command("reviewer-header <pass> [--rerun]", fits_reviewer_header, run_reviewer_header),
|
||||
"reviewer-context": Command("reviewer-context", no_arguments, lambda given: printed(hook_reply(sys.stdin.read(), pathlib.Path.home()))),
|
||||
}
|
||||
SHAPES = " | ".join(command.shape for command in COMMANDS.values())
|
||||
USAGE = f"usage: larv-review {SHAPES}"
|
||||
|
||||
|
||||
def main(argv: list[str]) -> int:
|
||||
if argv in (["-h"], ["--help"]):
|
||||
print(__doc__.strip().format(cap=CAP, release_cap=RELEASE_REVIEW_CAP, floor=FLOOR, pairs=MIN_PAIRS))
|
||||
print(__doc__.strip().format(commands=SHAPES, cap=CAP, release_cap=RELEASE_REVIEW_CAP, floor=FLOOR, pairs=MIN_PAIRS))
|
||||
return 0
|
||||
command, *given = argv or [""]
|
||||
if command == "review-folder" and not given:
|
||||
done = make_review_folder()
|
||||
elif command == "ruling-base" and not given:
|
||||
done = with_default_branch(show_ruling_base, stale_ok=False)
|
||||
elif command == "round-count" and not given:
|
||||
done = with_default_branch(round_count, stale_ok=True)
|
||||
elif command == "needs-scoring-run" and all(re.fullmatch(r"[0-9]+", id_) for id_ in given):
|
||||
done = with_default_branch(lambda default: needs_scoring_run(default, [int(id_) for id_ in given]), stale_ok=False)
|
||||
elif command == "scoring-run-owed" and not given:
|
||||
done = with_default_branch(owed, stale_ok=False)
|
||||
elif command == "record-ruling" and len(given) == 1:
|
||||
done = record_ruling(pathlib.Path(given[0]))
|
||||
elif command == "record-scoring" and given and all(re.fullmatch(r"[0-9]+", id_) for id_ in given[1:]):
|
||||
done = with_default_branch(lambda default: record_scoring(default, pathlib.Path(given[0]), [int(id_) for id_ in given[1:]]), stale_ok=False)
|
||||
elif command == "places" and not given:
|
||||
done = show_places()
|
||||
elif command == "agreement" and not given:
|
||||
done = show_agreement()
|
||||
elif command == "reviewer-header" and given[:1] and given[0] in REVIEWERS and given[1:] in ([], ["--rerun"]):
|
||||
done = with_default_branch(lambda default: reviewer_header(default, given[0], given[1:] == ["--rerun"]), stale_ok=True)
|
||||
elif command in ("needs-scoring-run", "record-scoring") and given:
|
||||
named = given[1:] if command == "record-scoring" else given
|
||||
print(f"{command} takes item IDs, the numbers in todo.md's ID column, not {' '.join(id_ for id_ in named if not re.fullmatch(r'[0-9]+', id_))}; {USAGE}", file=sys.stderr)
|
||||
return 1
|
||||
elif not argv:
|
||||
if not argv:
|
||||
print(USAGE, file=sys.stderr)
|
||||
return 1
|
||||
name, *given = argv
|
||||
command = COMMANDS.get(name)
|
||||
if command and command.fits(given):
|
||||
done = command.run(given)
|
||||
elif command and command.ids_from is not None and (named := [id_ for id_ in given[command.ids_from:] if not ITEM_ID.fullmatch(id_)]):
|
||||
print(f"{name} takes item IDs, the numbers in todo.md's ID column, not {' '.join(named)}; {USAGE}", file=sys.stderr)
|
||||
return 1
|
||||
else:
|
||||
print(f"unknown arguments {' '.join(argv)}; {USAGE}", file=sys.stderr)
|
||||
return 1
|
||||
@@ -188,6 +249,14 @@ def main(argv: list[str]) -> int:
|
||||
return 0
|
||||
|
||||
|
||||
def printed(reply: str | Failure) -> Failure | None:
|
||||
if isinstance(reply, Failure):
|
||||
return reply
|
||||
if reply:
|
||||
print(reply)
|
||||
return None
|
||||
|
||||
|
||||
def with_default_branch(command: typing.Callable[[str], Failure | None], stale_ok: bool) -> Failure | None:
|
||||
default = default_branch(stale_ok)
|
||||
if isinstance(default, Failure):
|
||||
@@ -198,6 +267,11 @@ def with_default_branch(command: typing.Callable[[str], Failure | None], stale_o
|
||||
return command(branch)
|
||||
|
||||
|
||||
def prepared_scoring(preloaded: str | None) -> Failure | None:
|
||||
worktree = top()
|
||||
return worktree if isinstance(worktree, Failure) else printed(prepare_scoring(worktree, preloaded))
|
||||
|
||||
|
||||
def make_review_folder() -> Failure | None:
|
||||
worktree = top()
|
||||
if isinstance(worktree, Failure):
|
||||
|
||||
@@ -10,7 +10,7 @@ from release_plan.todo_table import items, NoItemsTable
|
||||
def owed_scoring_run(default: str) -> Failure | None:
|
||||
"""A Failure saying which scoring runs the chunk owes and has not recorded; None where it owes none.
|
||||
|
||||
The chunk owes the runs `plan_reasons` calls, two where it empties a release, else one. It has recorded the scoring runs its committed history holds beyond those at the merge base, so a default branch that has moved on since the branch began counts for nothing. A project with no plan owes none. A missing run blocks the merge and a low score never does, which keeps the decision `review: the comprehension check records …`: it bars only scores from blocking.
|
||||
The chunk owes the runs `plan_reasons` calls, two where it empties a release, else one. It has recorded the scoring runs its committed history holds beyond those at the merge base, so a default branch that has moved on since the branch began doesn't count. A project with no plan owes none. A missing run blocks the merge and a low score never does, which keeps the decision `review: the comprehension check records …`: it bars only scores from blocking.
|
||||
"""
|
||||
checkout = top()
|
||||
if isinstance(checkout, Failure):
|
||||
|
||||
@@ -3,7 +3,7 @@ import pathlib
|
||||
from release_plan.release_standing import Cut, default_plan, LastCut, next_release, Unknown
|
||||
from failure import Failure
|
||||
from git_cli.git_repo import file_at, top
|
||||
from larv_review.scoring import FLOOR_ITEM
|
||||
from larv_review.scoring import is_floor_item
|
||||
from release_plan.todo_table import Item, items, NoItemsTable, renames
|
||||
from release_plan.ranking import OPTED_OUT
|
||||
from release_plan.release import Release, version
|
||||
@@ -17,7 +17,7 @@ EMPTIED_WORDS = "with no plan item"
|
||||
def scoring_run_due(before: list[Item], after: list[Item], ships: list[int], landed_release: Release | None, renamed: set[Release], unmeasured: str | None = None) -> list[str] | Failure:
|
||||
"""Why the plan calls a scoring run, empty when it does not.
|
||||
|
||||
A chunk that ships an item naming the floor is due one, so it can prove the floor met. So is a chunk that empties a release after work has landed towards it, so no release ends unmeasured. A release the chunk's plan marks renamed is due none. A chunk after a release `unmeasured_cut` names is due one too, so a release cut with no scoring run is caught up.
|
||||
A chunk that ships a floor item is due one, so it can prove the floor met. So is a chunk that empties a release after work has landed towards it, so no release ends unmeasured. A release the chunk's plan marks renamed is due none. A chunk after a release `unmeasured_cut` names is due one too, so a release cut with no scoring run is caught up.
|
||||
|
||||
before is the default branch's plan and after the chunk's. ships holds the IDs of the items the chunk ships. landed_release is the next release where work has landed towards it, else None (`landed_towards`). renamed holds the releases the chunk's plan marks renamed. unmeasured is `unmeasured_cut`'s answer.
|
||||
"""
|
||||
@@ -25,7 +25,7 @@ def scoring_run_due(before: list[Item], after: list[Item], ships: list[int], lan
|
||||
if unknown := sorted(set(ships) - set(plan)):
|
||||
return Failure(f"neither plan holds item {', '.join(map(str, unknown))}")
|
||||
shipped = [plan[id_] for id_ in ships]
|
||||
reasons = [f"ships item {item.id}, which names the comprehension floor" for item in shipped if FLOOR_ITEM in item.tagline.lower()]
|
||||
reasons = [f"ships item {item.id}, a floor item" for item in shipped if is_floor_item(item)]
|
||||
if unmeasured:
|
||||
reasons.append(f"follows {unmeasured}")
|
||||
for release in emptied(before, after, shipped, renamed):
|
||||
|
||||
@@ -9,6 +9,8 @@ from chunk_preflight.choices import forge_of
|
||||
from larv_review.history_commands import history_file, places_report
|
||||
from review_rules.review_folder import made_review_folder
|
||||
from deploy_release.forge import open_pull, runner
|
||||
from review_rules.reviewer_context import principles_line, starts_bare
|
||||
from review_rules.review_passes import REVIEWERS
|
||||
|
||||
# The passes whose reviewer is given the places: skills/larv-review/SKILL.md → "Comprehension check" → "Places".
|
||||
TAKE_PLACES = ("architecture", "stability")
|
||||
@@ -27,6 +29,7 @@ class Launch:
|
||||
default: str
|
||||
folder: pathlib.Path
|
||||
diff: pathlib.Path
|
||||
bare: bool
|
||||
|
||||
def asked(self) -> pathlib.Path:
|
||||
"""The round's report, which asks for the rerun where there is one."""
|
||||
@@ -43,6 +46,7 @@ class Launch:
|
||||
f"Report: write it to {report}.",
|
||||
f"Diff: {self.diff}",
|
||||
*([f"Places: {self.folder / 'places.md'}"] if self.pass_ in TAKE_PLACES else []),
|
||||
*([principles] if self.bare and (principles := principles_line(self.worktree)) else []),
|
||||
])
|
||||
|
||||
|
||||
@@ -70,7 +74,7 @@ def reviewer_header(default: str, pass_: str, rerun: bool) -> Failure | None:
|
||||
folder = made_review_folder(worktree)
|
||||
if isinstance(folder, Failure):
|
||||
return folder
|
||||
launch = Launch(pass_, round_, rerun, pull_named(worktree, branch), worktree, branch, base, default, folder, folder / f"branch-{head}.diff")
|
||||
launch = Launch(pass_, round_, rerun, pull_named(worktree, branch), worktree, branch, base, default, folder, folder / f"branch-{head}.diff", starts_bare(next((agent for name, agent in REVIEWERS.items() if name == pass_), ""), pathlib.Path.home()))
|
||||
if rerun and not launch.asked().exists():
|
||||
return Failure(f"no report asked for a rerun of {pass_}'s round {round_}: {launch.asked()} is missing; relaunch before you commit the round's answers")
|
||||
written = write_inputs(launch, base)
|
||||
|
||||
@@ -3,8 +3,13 @@ import decimal
|
||||
from review_rules.comprehension_history import DIMENSIONS, FLOOR
|
||||
from release_plan.todo_table import Item
|
||||
|
||||
# A floor item's tagline holds these words, and plan.scoring_run_due keys on them too, so each floor item's chunk runs a scoring run.
|
||||
FLOOR_ITEM = "comprehension floor"
|
||||
# A floor item's tagline opens with this phrase, which a tagline quoting or mentioning the floor never does; a floor item's chunk runs a scoring run.
|
||||
FLOOR_ITEM = "Reach the comprehension floor:"
|
||||
|
||||
|
||||
def is_floor_item(item: Item) -> bool:
|
||||
"""Whether the item's tagline, which keeps its `**` bold markers, opens with FLOOR_ITEM."""
|
||||
return item.tagline.removeprefix("**").startswith(FLOOR_ITEM)
|
||||
|
||||
|
||||
def means(lines: list[list[str]]) -> list[decimal.Decimal]:
|
||||
@@ -32,6 +37,6 @@ def floor_step(found: list[decimal.Decimal], plan: list[Item], ships: list[int])
|
||||
names = " and ".join(filter(None, [", ".join(lowest[:-1]), lowest[-1]]))
|
||||
aim = f"{names}, the lowest dimension{'s' if len(lowest) > 1 else ''}"
|
||||
rule = 'as larv-review §3 → "Floor item" says.'
|
||||
if open_items := [item for item in plan if FLOOR_ITEM in item.tagline.lower() and item.id not in ships]:
|
||||
if open_items := [item for item in plan if is_floor_item(item) and item.id not in ships]:
|
||||
return f"Next: refresh floor item {open_items[0].id} to lift {aim}, with this run's places, and file no other, {rule}"
|
||||
return f"Next: file one floor item, a refactor lifting {aim}, until every mean reaches {FLOOR}, {rule}"
|
||||
return f"Next: file one floor item, a refactor lifting {aim}, with a tagline that opens with `{FLOOR_ITEM}`, until every mean reaches {FLOOR}, {rule}"
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
"""Set up a scoring run: the worktree its seats read and each seat's prompt, filled from skills/comprehension-panel/seat-prompts.md."""
|
||||
import json
|
||||
import pathlib
|
||||
import re
|
||||
import shutil
|
||||
|
||||
from review_rules.comprehension_history import DIMENSIONS
|
||||
from failure import Failure
|
||||
from records.markdown_text import FENCE, listed, section
|
||||
from git_cli.git_repo import git
|
||||
from review_rules.review_folder import made_review_folder, review_folder
|
||||
|
||||
CLAUDE_MD = "CLAUDE.md"
|
||||
PANEL = pathlib.Path(__file__).resolve().parents[2] / "skills" / "comprehension-panel"
|
||||
# The file name of each seat's prompt, its label in seat-prompts.md → "Backgrounds", and the heading of its report there.
|
||||
SEATS = (
|
||||
("junior-a", "Junior A", "Report: Junior A, Mid A and the maintainability senior"),
|
||||
("mid-a", "Mid A", "Report: Junior A, Mid A and the maintainability senior"),
|
||||
("maintainability-senior", "Senior, maintainability", "Report: Junior A, Mid A and the maintainability senior"),
|
||||
("inherited-architect", "Architect, inherited", "Report: the inherited architect"),
|
||||
)
|
||||
# The dimensions a seat scores beside the overall, which comes last in DIMENSIONS.
|
||||
PANEL_DIMENSIONS = DIMENSIONS[:-1]
|
||||
VALUE_NAMES = ("language", "kind", "domain", "domain docs", "3am question")
|
||||
FORBIDDEN_FILES = ("todo.md", "docs/decisions.md", "docs/comprehension-history.md", "docs/reading-cost.md")
|
||||
FORBIDDEN = "todo.md, docs/decisions.md, docs/comprehension-history.md or docs/reading-cost.md (the plan, the decision log, past panels' records and past chunks' reading cost)"
|
||||
TEST_FILE = re.compile(r"(^|/)(tests?/|test_[^/]*$|[^/]*_test\.[^/]*$|[^/]*\.(test|spec)\.[^/]*$)")
|
||||
TEST_FILES = "test files being `test_*`, `*_test.*`, `*.test.*`, `*.spec.*` and those under a `test` or `tests` folder"
|
||||
|
||||
|
||||
def bullets(lines: list[str]) -> list[list[str]]:
|
||||
"""Each run of `- ` bullets in lines, each bullet joined onto one line with its indented continuation lines."""
|
||||
groups: list[list[str]] = []
|
||||
inside = False
|
||||
for line in lines:
|
||||
if line.startswith("- "):
|
||||
if not inside:
|
||||
groups.append([])
|
||||
groups[-1].append(line.rstrip())
|
||||
inside = True
|
||||
elif inside and line.startswith(" ") and line.strip():
|
||||
groups[-1][-1] += " " + line.strip()
|
||||
else:
|
||||
inside = False
|
||||
return groups
|
||||
|
||||
|
||||
ANCHOR = re.compile(r"- \*\*\d+ — ")
|
||||
DIMENSION = re.compile(r"- \*\*([^*]+)\*\* — ")
|
||||
|
||||
|
||||
def score_bullets(skill: str) -> tuple[list[str], list[str]] | Failure:
|
||||
"""The six anchor bullets and the four dimension bullets of SKILL.md → "The score", without bold, each on one line. A bullet is an anchor or a dimension by how it opens, `- **<n> — ` or `- **<name>** — `; the other bullets in the section are skipped, and the dimensions must come in the panel's order."""
|
||||
lines = [line for group in bullets(section(skill, "The score") or []) for line in group]
|
||||
anchors = [line.replace("**", "") for line in lines if ANCHOR.match(line)]
|
||||
dimensions = [(match[1], line) for line in lines if (match := DIMENSION.match(line))]
|
||||
if len(anchors) != 6 or tuple(name for name, _ in dimensions) != PANEL_DIMENSIONS:
|
||||
return Failure(f"{PANEL / 'SKILL.md'} → \"The score\" no longer holds six bullets opening `- **<n> — ` and one opening `- **<name>** — ` for each of {listed(list(PANEL_DIMENSIONS), 'and')}, in that order")
|
||||
return anchors, [line.replace("**", "") for _, line in dimensions]
|
||||
|
||||
|
||||
def project_values(text: str, source: str) -> dict[str, str] | Failure:
|
||||
"""Each value seat-prompts.md fills from the project, from the section of text, read from source, headed `Scoring run` or `<name>'s values`."""
|
||||
lines = section(text, r"(\d+\.\s+)?Scoring run|.+'s values")
|
||||
if lines is None:
|
||||
return Failure(f"{source} has no \"Scoring run\" section to fill the seats' prompts from; add one with {listed([f'{{{name}}}' for name in VALUE_NAMES], 'and')}")
|
||||
values = {}
|
||||
for bullet in (line for group in bullets(lines) for line in group):
|
||||
key, colon, value = bullet[2:].partition(":")
|
||||
name = key.strip(" `*{}").lower()
|
||||
if colon and name in VALUE_NAMES:
|
||||
value = value.strip(" *")
|
||||
values[name] = value[:-1] if value.endswith(".") and not value.endswith("..") else value
|
||||
if missing := [name for name in VALUE_NAMES if name not in values]:
|
||||
return Failure(f"{source} → \"Scoring run\" gives no {listed([f'{{{name}}}' for name in missing], 'or')}; add them as seat-prompts.md lists them")
|
||||
return {name: values[name] for name in VALUE_NAMES}
|
||||
|
||||
|
||||
def file_globs(paths: list[str]) -> str:
|
||||
"""Every tracked file of paths a seat reads, as one glob per top-level folder and each top-level file, with the test files the globs leave out."""
|
||||
read = [path for path in paths if path not in FORBIDDEN_FILES and not TEST_FILE.search(path)]
|
||||
folders = sorted({path.split("/")[0] for path in read if "/" in path})
|
||||
tested = {path.split("/")[0] for path in paths if "/" in path and TEST_FILE.search(path)}
|
||||
globs = [f"`{folder}/**`" + (" except test files" if folder in tested else "") for folder in folders]
|
||||
return listed(globs + sorted(f"`{path}`" for path in read if "/" not in path), "and") + (f", {TEST_FILES}" if tested & set(folders) else "")
|
||||
|
||||
|
||||
def preloaded_files(main: pathlib.Path, home: pathlib.Path) -> str:
|
||||
"""The files Claude Code loads into a seat started in main before its first tool call: each CLAUDE.md, the files it imports, and each rule file without `paths:`, leaving out those `claudeMdExcludes` names."""
|
||||
excludes = claude_md_excludes(main, home)
|
||||
found = []
|
||||
|
||||
def kept(path: pathlib.Path) -> bool:
|
||||
return not any(path.full_match(pattern) for pattern in excludes)
|
||||
|
||||
for shown, claude_md, rules in (("~/.claude/", home / ".claude" / CLAUDE_MD, home / ".claude" / "rules"), ("", main / CLAUDE_MD, main / ".claude" / "rules")):
|
||||
if claude_md.is_file() and kept(claude_md):
|
||||
found.append(f"`{shown}{CLAUDE_MD}`")
|
||||
found += [f"`{shown}{name}`, which it imports" for name in re.findall(r"^@(\S+)", claude_md.read_text(), re.M)]
|
||||
found += [f"`{shown}{rule.relative_to(claude_md.parent)}`" for rule in sorted(rules.glob("*.md")) if kept(rule) and not re.search(r"^paths:", rule.read_text(), re.M)]
|
||||
return listed(found, "and") if found else "none"
|
||||
|
||||
|
||||
def claude_md_excludes(main: pathlib.Path, home: pathlib.Path) -> list[str]:
|
||||
"""The `claudeMdExcludes` globs of the user's settings and main's project and local settings, merged as Claude Code merges them across layers.
|
||||
|
||||
Managed settings are left out, since they may come from the claude.ai console or an MDM policy, where no file shows them."""
|
||||
globs = []
|
||||
for path in (home / ".claude" / "settings.json", main / ".claude" / "settings.json", main / ".claude" / "settings.local.json"):
|
||||
try:
|
||||
settings = json.loads(path.read_text())
|
||||
except (OSError, ValueError):
|
||||
continue
|
||||
excludes = settings.get("claudeMdExcludes") if isinstance(settings, dict) else None
|
||||
globs += [glob for glob in excludes if isinstance(glob, str)] if isinstance(excludes, list) else []
|
||||
return globs
|
||||
|
||||
|
||||
def prompt_parts() -> dict[str, str] | Failure:
|
||||
"""seat-prompts.md's opening, shared brief and each report as their fenced text, and each seat's background, keyed by heading or label."""
|
||||
path = PANEL / "seat-prompts.md"
|
||||
try:
|
||||
text = path.read_text()
|
||||
except OSError as failure:
|
||||
return Failure(f"cannot read {path}: {failure}")
|
||||
parts = {}
|
||||
for title in ("Opening", "Shared brief", *{report for _, _, report in SEATS}):
|
||||
lines = section(text, re.escape(title)) or []
|
||||
fences = [at for at, line in enumerate(lines) if FENCE.match(line)]
|
||||
if len(fences) < 2:
|
||||
return Failure(f"{path} → \"{title}\" holds no fenced prompt text")
|
||||
parts[title] = "\n".join(lines[fences[0] + 1:fences[1]])
|
||||
for line in (line for group in bullets(section(text, "Backgrounds") or []) for line in group):
|
||||
label, _, background = line[2:].partition(": ")
|
||||
parts[label] = background.strip("`")
|
||||
if missing := [label for _, label, _ in SEATS if label not in parts]:
|
||||
return Failure(f"{path} → \"Backgrounds\" names no {listed(missing, 'or')}")
|
||||
return parts
|
||||
|
||||
|
||||
def scoring_folder(worktree: str, home: pathlib.Path) -> pathlib.Path:
|
||||
return pathlib.Path(review_folder(str(home), worktree)) / "scoring"
|
||||
|
||||
|
||||
def prepare_scoring(worktree: str, preloaded: str | None) -> str | Failure:
|
||||
"""Makes the scoring run's worktree at worktree's HEAD and writes each seat's prompt beside it, in the chunk's review folder; what it made, as the tool prints it."""
|
||||
home = pathlib.Path.home()
|
||||
folder = scoring_folder(worktree, home)
|
||||
# A setup record-scoring never removed, as where the seats failed, would otherwise block every later run.
|
||||
replaced = folder.exists()
|
||||
if replaced and isinstance(removed := removed_setup(worktree), Failure):
|
||||
return removed
|
||||
# Where AGENTS.md is missing, this repo keeps the values in seat-prompts.md: .claude/rules/this-repo-keeps-no-agents-md.md.
|
||||
source = pathlib.Path(worktree) / "AGENTS.md"
|
||||
if not source.is_file() and (own := pathlib.Path(worktree) / "skills" / "comprehension-panel" / "seat-prompts.md").is_file():
|
||||
source = own
|
||||
values = project_values(source.read_text() if source.is_file() else "", source.name)
|
||||
if isinstance(values, Failure):
|
||||
return values
|
||||
parts = prompt_parts()
|
||||
if isinstance(parts, Failure):
|
||||
return parts
|
||||
score = score_bullets((PANEL / "SKILL.md").read_text())
|
||||
if isinstance(score, Failure):
|
||||
return score
|
||||
listing = git("worktree", "list", "--porcelain", cwd=worktree)
|
||||
branch = git("symbolic-ref", "--short", "-q", "HEAD", cwd=worktree)
|
||||
head = git("rev-parse", "--short", "HEAD", cwd=worktree)
|
||||
if isinstance(listing, Failure):
|
||||
return listing
|
||||
if isinstance(head, Failure):
|
||||
return head
|
||||
main = listing.splitlines()[0].removeprefix("worktree ")
|
||||
made = made_review_folder(worktree)
|
||||
if isinstance(made, Failure):
|
||||
return made
|
||||
checkout = folder / "checkout"
|
||||
# The seats score the chunk's head, which holds origin's default branch since larv-review §4 step 1, as larv-review → "Scoring run" says.
|
||||
added = git("worktree", "add", "--quiet", "--detach", str(checkout), "HEAD", cwd=worktree)
|
||||
tracked = added if isinstance(added, Failure) else git("ls-files", cwd=str(checkout))
|
||||
if isinstance(tracked, Failure):
|
||||
shutil.rmtree(folder, ignore_errors=True)
|
||||
return tracked
|
||||
filled = {
|
||||
**values,
|
||||
"checkout": str(checkout),
|
||||
"branch": head.strip() if isinstance(branch, Failure) else branch.strip(),
|
||||
"main": main,
|
||||
"forbidden": FORBIDDEN,
|
||||
"git": f"`git -C {checkout} ls-files`",
|
||||
"files": file_globs(tracked.splitlines()),
|
||||
"preloaded": preloaded if preloaded is not None else preloaded_files(pathlib.Path(main), home),
|
||||
"anchors": "\n".join(score[0]),
|
||||
"dimensions": "\n".join(score[1]),
|
||||
}
|
||||
placeholder = re.compile(r"\{(" + "|".join(re.escape(name) for name in filled) + r")\}")
|
||||
written = []
|
||||
for name, label, report in SEATS:
|
||||
prompt = "\n\n".join((parts["Opening"], parts[label], parts["Shared brief"], parts[report]))
|
||||
path = folder / f"{name}.md"
|
||||
path.write_text(placeholder.sub(lambda found: filled[found.group(1)], prompt) + "\n")
|
||||
written.append(str(path))
|
||||
before = f"Removed the scoring run set up before in {folder}.\n" if replaced else ""
|
||||
return before + f"Scoring worktree, at {head.strip()}: {checkout}\nPrompts:\n" + "\n".join(written)
|
||||
|
||||
|
||||
def removed_setup(worktree: str) -> Failure | None:
|
||||
"""Removes the scoring worktree and prompts prepare_scoring made for the chunk at worktree, where they exist."""
|
||||
folder = scoring_folder(worktree, pathlib.Path.home())
|
||||
if not folder.exists():
|
||||
return None
|
||||
if (folder / "checkout").exists() and isinstance(removed := git("worktree", "remove", "--force", str(folder / "checkout"), cwd=worktree), Failure):
|
||||
return Failure(f"could not remove the scoring worktree {folder / 'checkout'}: {removed.reason}")
|
||||
shutil.rmtree(folder, ignore_errors=True)
|
||||
return None
|
||||
@@ -1,5 +1,6 @@
|
||||
import decimal
|
||||
import itertools
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import subprocess
|
||||
@@ -117,10 +118,11 @@ class Seats(unittest.TestCase):
|
||||
|
||||
def test_floor_step_files_one_item_at_the_lowest_dimension_unless_one_is_open(self):
|
||||
found = [decimal.Decimal(mean) for mean in ("7.38", "6.63", "7.00", "6.50", "6.88")]
|
||||
floor_item = item(5, (0, 2, 0), "**Restructure the reload, lifting Locality to the comprehension floor.**")
|
||||
floor_item = item(5, (0, 2, 0), "**Reach the comprehension floor: restructure the reload, lifting Locality.**")
|
||||
with self.subTest("none open"):
|
||||
step = floor_step(found, [item(1, (0, 1, 0))], [])
|
||||
self.assertTrue(step.startswith("Next: file one floor item"), step)
|
||||
self.assertIn("with a tagline that opens with `Reach the comprehension floor:`,", step)
|
||||
self.assertIn(" Self-sufficiency, the lowest dimension,", step)
|
||||
self.assertIn('"Floor item"', step)
|
||||
with self.subTest("one open"):
|
||||
@@ -133,6 +135,9 @@ class Seats(unittest.TestCase):
|
||||
with self.subTest("a tie names both"):
|
||||
tied = [decimal.Decimal(mean) for mean in ("7.38", "6.50", "7.00", "6.50", "6.88")]
|
||||
self.assertIn(" Locality and Self-sufficiency, the lowest dimensions,", floor_step(tied, [], []))
|
||||
with self.subTest("a tagline that only mentions the floor is no floor item"):
|
||||
quoting = item(6, (0, 2, 0), "**Rename the decision `comprehension floor: …` in the log.**")
|
||||
self.assertTrue(floor_step(found, [quoting], []).startswith("Next: file one floor item"))
|
||||
with self.subTest("none under the floor"):
|
||||
self.assertIsNone(floor_step([decimal.Decimal("7.00")] * 5, [floor_item], []))
|
||||
with self.subTest("only the overall under the floor"):
|
||||
@@ -356,9 +361,13 @@ class ScoringRunDue(unittest.TestCase):
|
||||
self.assertIsInstance(items("# todo\n"), Failure)
|
||||
self.assertIsInstance(items(todo("| 0 | 0.1.0 | | **Do it.** | 1 | 1 | 3 | 1 | 1 | 1 | 9.0 |")), Failure)
|
||||
|
||||
def test_is_due_for_an_item_naming_the_floor(self):
|
||||
plan = [item(1, (0, 1, 0), "**Lift the project to the Comprehension floor.**"), item(2, (0, 1, 0))]
|
||||
self.assertEqual(scoring_run_due(plan, plan, [1], (0, 1, 0), set()), ["ships item 1, which names the comprehension floor"])
|
||||
def test_is_not_due_for_an_item_whose_tagline_only_mentions_the_floor(self):
|
||||
plan = [item(1, (0, 1, 0), "**Call a scoring run for an item whose tagline makes the comprehension floor its target.**"), item(2, (0, 1, 0))]
|
||||
self.assertEqual(scoring_run_due(plan, plan, [1], (0, 1, 0), set()), [])
|
||||
|
||||
def test_is_due_for_a_floor_item(self):
|
||||
plan = [item(1, (0, 1, 0), "**Reach the comprehension floor: lift the project.**"), item(2, (0, 1, 0))]
|
||||
self.assertEqual(scoring_run_due(plan, plan, [1], (0, 1, 0), set()), ["ships item 1, a floor item"])
|
||||
self.assertIsInstance(scoring_run_due(plan, plan, [9], (0, 1, 0), set()), Failure)
|
||||
|
||||
def test_is_due_when_the_chunk_ships_a_releases_last_item(self):
|
||||
@@ -432,7 +441,7 @@ class Shortfall(unittest.TestCase):
|
||||
|
||||
def test_a_chunk_that_empties_a_release_owes_two_runs_and_any_other_reason_one(self):
|
||||
emptied = ["leaves release 0.1.0 with no plan item"]
|
||||
floor = ["ships item 2, which names the comprehension floor"]
|
||||
floor = ["ships item 2, a floor item"]
|
||||
self.assertIn("owes 2 scoring runs and the branch's committed history records 1", shortfall(emptied + floor, 1).reason)
|
||||
self.assertIn("owes 1 scoring run and", shortfall(floor, 0).reason)
|
||||
self.assertIn("records 0:", shortfall(floor, -1).reason)
|
||||
@@ -534,10 +543,10 @@ class LarvReviewTool(unittest.TestCase):
|
||||
def test_a_scoring_run_the_floor_calls_is_owed_once(self):
|
||||
row = "| 1 | 0.1.0 | | **Do it.** | 1 | 1 | 3 | 1 | 1 | 1 | 9.0 |"
|
||||
other = "| 3 | 0.2.0 | | **And this.** | 1 | 1 | 3 | 1 | 1 | 1 | 9.0 |"
|
||||
self.commit("Plan the floor item", {"todo.md": todo(row, "| 2 | 0.2.0 | | **Reach the comprehension floor.** | 1 | 1 | 3 | 1 | 1 | 1 | 9.0 |", other)})
|
||||
self.commit("Plan the floor item", {"todo.md": todo(row, "| 2 | 0.2.0 | | **Reach the comprehension floor: do it.** | 1 | 1 | 3 | 1 | 1 | 1 | 9.0 |", other)})
|
||||
self.git("push", "-q", "origin", "HEAD:main")
|
||||
self.commit("Ship it", {"todo.md": todo(row, other)})
|
||||
self.assertIn("names the comprehension floor", self.run_tool("scoring-run-owed").stderr)
|
||||
self.assertIn("a floor item", self.run_tool("scoring-run-owed").stderr)
|
||||
self.commit("Record a run", {"docs/comprehension-history.md": "# Comprehension history\n\n" + SCORING})
|
||||
self.assertEqual(self.run_tool("scoring-run-owed").returncode, 0)
|
||||
|
||||
@@ -620,9 +629,9 @@ class LarvReviewTool(unittest.TestCase):
|
||||
history = "# Comprehension history\n\n"
|
||||
due = "Scoring run due: the chunk follows v0.0.2, cut with no scoring run since v0.0.1.\n"
|
||||
self.release("v0.0.2", "2026-10-20T12:00:00Z", {"docs/comprehension-history.md": history + paired("2026-10-21T12:00:00Z", "better") + "\n" + SCORING.replace("2026-10-08T12:00:00Z", "2026-10-09T12:00:00Z")})
|
||||
self.assertEqual(self.run_tool("needs-scoring-run", "2").stdout, due, "a ruling, and a run at the earlier tag's own second, end nothing")
|
||||
self.assertEqual(self.run_tool("needs-scoring-run", "2").stdout, due, "a ruling, and a run at the earlier tag's own second, don't end anything")
|
||||
self.release("v0.0.3", "2026-10-21T12:00:00Z", {"docs/comprehension-history.md": history + SCORING.replace("2026-10-08T12:00:00Z", "2026-10-30")})
|
||||
self.assertEqual(self.run_tool("needs-scoring-run", "2").stdout, due.replace("v0.0.2", "v0.0.3").replace("v0.0.1", "v0.0.2"), "a run whose time doesn't parse ends nothing")
|
||||
self.assertEqual(self.run_tool("needs-scoring-run", "2").stdout, due.replace("v0.0.2", "v0.0.3").replace("v0.0.1", "v0.0.2"), "a run whose time doesn't parse doesn't end anything")
|
||||
|
||||
def test_an_unmeasured_release_is_judged_by_the_default_branch_alone_and_names_a_release_over_its_candidate(self):
|
||||
self.release("v0.0.1", "2026-10-09T12:00:00Z")
|
||||
@@ -745,7 +754,7 @@ class LarvReviewTool(unittest.TestCase):
|
||||
def test_record_scoring_refreshes_the_open_floor_item_unless_the_chunk_ships_it(self):
|
||||
line = "Navigation 7, Locality 6.5, Shape 7, Self-sufficiency 7, Overall 7"
|
||||
seats = "".join(f"\n{seat}: {line}\n" for seat in ("Junior A", "Mid A", "Maintainability senior", "Inherited architect"))
|
||||
self.plan(second="**Lift Locality to the comprehension floor.**")
|
||||
self.plan(second="**Reach the comprehension floor: lift Locality.**")
|
||||
ran = self.run_tool("record-scoring", self.seats_file(f"PR #2 at {self.start}\n" + seats), "1")
|
||||
self.assertEqual(ran.returncode, 0, ran.stderr)
|
||||
self.assertIn("\nNext: refresh floor item 2 to lift Locality, the lowest dimension,", ran.stdout)
|
||||
@@ -767,6 +776,52 @@ class LarvReviewTool(unittest.TestCase):
|
||||
seats = "".join(f"\n{seat}: {line}\n" for seat in ("Junior A", "Mid A", "Maintainability senior", "Inherited architect"))
|
||||
return self.run_tool("record-scoring", self.seats_file(f"PR #2 at {self.start}\n" + seats), "1")
|
||||
|
||||
def test_record_scoring_removes_the_worktree_and_prompts_prepare_scoring_made(self):
|
||||
self.commit("Values", {"AGENTS.md": "## Scoring run\n\n- Language: Python\n- Kind: a CLI\n- Domain: parsing\n- Domain docs: the spec\n- 3am question: the parse hangs\n"})
|
||||
prepared = self.run_tool("prepare-scoring")
|
||||
self.assertEqual(prepared.returncode, 0, prepared.stderr)
|
||||
self.assertEqual(len(self.git("worktree", "list").splitlines()), 2)
|
||||
self.plan()
|
||||
ran = self.record_sevens()
|
||||
self.assertEqual(ran.returncode, 0, ran.stderr)
|
||||
self.assertFalse((self.checkout.parent / ".local" / "state" / "larv-review" / "proj" / "scoring").exists())
|
||||
self.assertEqual(len(self.git("worktree", "list").splitlines()), 1)
|
||||
|
||||
VALUES = {"AGENTS.md": "## Scoring run\n\n- Language: Python\n- Kind: a CLI\n- Domain: parsing\n- Domain docs: the spec\n- 3am question: the parse hangs\n"}
|
||||
|
||||
def test_prepare_scoring_puts_the_preloaded_text_it_is_given_in_the_seats_prompts(self):
|
||||
self.commit("Values", self.VALUES)
|
||||
prepared = self.run_tool("prepare-scoring", "--preloaded", "the files the harness loaded")
|
||||
self.assertEqual(prepared.returncode, 0, prepared.stderr)
|
||||
prompts = [path.read_text() for path in (self.checkout.parent / ".local" / "state" / "larv-review").rglob("*.md") if "scoring" in path.parts]
|
||||
self.assertTrue(any("the files the harness loaded" in prompt for prompt in prompts), prepared.stdout)
|
||||
|
||||
def test_prepare_scoring_refuses_a_preloaded_flag_without_its_text_and_any_other_arguments(self):
|
||||
self.commit("Values", self.VALUES)
|
||||
for given in (["--preloaded"], ["text"], ["text", "--preloaded"], ["--preloaded", "text", "more"], ["--other", "text"]):
|
||||
with self.subTest(given=given):
|
||||
ran = self.run_tool("prepare-scoring", *given)
|
||||
self.assertEqual((ran.returncode, ran.stdout), (1, ""))
|
||||
self.assertTrue(ran.stderr.startswith("unknown arguments prepare-scoring"), ran.stderr)
|
||||
|
||||
def test_record_scoring_without_a_scores_file_and_an_empty_item_ID_print_the_usage_line(self):
|
||||
bare = self.run_tool("record-scoring")
|
||||
self.assertEqual(bare.returncode, 1)
|
||||
self.assertTrue(bare.stderr.startswith("unknown arguments record-scoring; usage: larv-review "), bare.stderr)
|
||||
empty = self.run_tool("needs-scoring-run", "")
|
||||
self.assertEqual(empty.returncode, 1)
|
||||
self.assertIn("takes item IDs", empty.stderr)
|
||||
|
||||
def test_the_commands_that_judge_a_branch_refuse_a_failed_fetch_instead_of_reading_origin_as_last_fetched(self):
|
||||
self.git("remote", "set-url", "origin", str(self.checkout.parent / "gone.git"))
|
||||
seats = self.seats_file(f"PR #2 at {self.start}\n")
|
||||
for given in (["ruling-base"], ["needs-scoring-run"], ["needs-scoring-run", "1"], ["scoring-run-owed"], ["record-scoring", seats], ["record-scoring", seats, "1"]):
|
||||
with self.subTest(given=given):
|
||||
ran = self.run_tool(*given)
|
||||
self.assertEqual(ran.returncode, 1)
|
||||
self.assertNotIn("reading origin as last fetched", ran.stderr)
|
||||
self.assertEqual(ran.stdout, "")
|
||||
|
||||
def test_reports_a_plan_it_cannot_read_yet_keeps_the_run(self):
|
||||
# This checkout has no README.md beside its todo.md.
|
||||
ran = self.record_sevens()
|
||||
@@ -860,6 +915,23 @@ class LarvReviewTool(unittest.TestCase):
|
||||
def test_review_folder_takes_no_arguments(self):
|
||||
self.assertIn("unknown arguments", self.run_tool("review-folder", "x").stderr)
|
||||
|
||||
def assert_names_the_non_id(self, named, *args):
|
||||
ran = self.run_tool(*args)
|
||||
self.assertEqual(ran.returncode, 1)
|
||||
self.assertIn(f"takes item IDs, the numbers in todo.md's ID column, not {named};", ran.stderr)
|
||||
|
||||
def test_needs_scoring_run_names_the_argument_that_is_not_an_item_id(self):
|
||||
self.assert_names_the_non_id("x", "needs-scoring-run", "3", "x")
|
||||
|
||||
def test_record_scoring_names_the_argument_after_its_file_that_is_not_an_item_id(self):
|
||||
self.assert_names_the_non_id("y1", "record-scoring", "scores.md", "4", "y1")
|
||||
|
||||
def test_help_and_the_usage_line_list_the_same_commands(self):
|
||||
usage = next(line for line in self.run_tool("--help").stdout.splitlines() if line.startswith("usage: larv-review "))
|
||||
listed = usage.removeprefix("usage: larv-review ").split(" | ")
|
||||
self.assertEqual([shape.split()[0] for shape in listed], ["review-folder", "ruling-base", "round-count", "needs-scoring-run", "scoring-run-owed", "record-ruling", "prepare-scoring", "record-scoring", "places", "agreement", "reviewer-header", "reviewer-context"])
|
||||
self.assertIn(f"usage: larv-review {' | '.join(listed)}", self.run_tool().stderr)
|
||||
|
||||
def test_takes_a_local_main_without_origin_and_reads_origin_as_last_fetched_when_the_fetch_fails(self):
|
||||
self.commit("Answer prose round 1: a")
|
||||
self.git("remote", "set-url", "origin", str(self.checkout.parent / "gone.git"))
|
||||
@@ -990,5 +1062,32 @@ class LarvReviewTool(unittest.TestCase):
|
||||
folder = self.checkout.parent / ".local" / "state" / "larv-review" / "proj"
|
||||
self.assertEqual(self.header_line("Places:", "architecture"), f"Places: {folder}/places.md")
|
||||
|
||||
def test_reviewer_header_names_the_file_that_holds_the_principles_last_where_the_project_keeps_one(self):
|
||||
self.assertIsNone(self.header_line("Principles:", "prose"))
|
||||
(self.checkout / "AGENTS.md").write_text("")
|
||||
self.assertIsNone(self.header_line("Principles:", "prose"))
|
||||
self.bare("prose-reviewer")
|
||||
ran = self.run_tool("reviewer-header", "prose")
|
||||
self.assertEqual(ran.stdout.splitlines()[-1], f"Principles: read {self.checkout}/AGENTS.md first, for the project principles and the decision titles.")
|
||||
|
||||
def bare(self, agent):
|
||||
(self.checkout.parent / ".claude" / "agents").mkdir(parents=True, exist_ok=True)
|
||||
(self.checkout.parent / ".claude" / "agents" / f"{agent}.md").write_text("---\nomitClaudeMd: true\n---\n")
|
||||
|
||||
def test_reviewer_context_hands_a_reviewer_the_sections_or_what_kept_it_from_them(self):
|
||||
def hook(agent):
|
||||
return subprocess.run([sys.executable, str(TOOL), "reviewer-context"], capture_output=True, env=self.env, input=json.dumps({"agent_type": agent}), text=True)
|
||||
|
||||
self.bare("prose-reviewer")
|
||||
missing = hook("prose-reviewer")
|
||||
self.assertEqual((missing.returncode, missing.stderr), (0, ""))
|
||||
self.assertIn("failed: could not read", json.loads(missing.stdout)["hookSpecificOutput"]["additionalContext"])
|
||||
(self.checkout.parent / ".claude").mkdir(exist_ok=True)
|
||||
(self.checkout.parent / ".claude" / "CLAUDE.md").write_text("## Shared goal\n\nHealth.\n\n## Prose\n\nShort.\n\n## Vocabulary\n\nWords.\n")
|
||||
ran = hook("prose-reviewer")
|
||||
self.assertEqual(ran.returncode, 0, ran.stderr)
|
||||
self.assertIn("## Prose\n\nShort.\n\n## Vocabulary\n\nWords.", json.loads(ran.stdout)["hookSpecificOutput"]["additionalContext"])
|
||||
self.assertEqual((hook("Explore").returncode, hook("Explore").stdout), (0, ""))
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@@ -0,0 +1,205 @@
|
||||
from unittest import mock
|
||||
import os
|
||||
import pathlib
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from larv_review.scoring_setup import bullets, CLAUDE_MD, file_globs, preloaded_files, prepare_scoring, project_values, removed_setup, score_bullets
|
||||
from failure import Failure
|
||||
from test_env import isolated_env
|
||||
|
||||
TOOL = pathlib.Path(__file__).resolve().parents[1] / "larv-review"
|
||||
SKILL = pathlib.Path(__file__).resolve().parents[2] / "skills" / "comprehension-panel" / "SKILL.md"
|
||||
VALUES = {"language": "Python", "kind": "a CLI", "domain": "parsing", "domain docs": "the spec", "3am question": "the parse hangs"}
|
||||
|
||||
|
||||
class ScoreBullets(unittest.TestCase):
|
||||
def test_gives_the_six_anchors_and_four_dimensions_unbolded_each_on_one_line(self):
|
||||
anchors, dimensions = score_bullets(SKILL.read_text())
|
||||
self.assertEqual(len(anchors), 6)
|
||||
self.assertEqual(anchors[0], "- 1 — Spaghetti. No boundary holds. Finding where a behaviour lives is grep archaeology; changing it safely is guesswork, and the reliable technique is to change it and see what breaks. No map the reader builds survives contact with the code.")
|
||||
self.assertTrue(anchors[5].startswith("- 10 — Duress-proof. Hungover,"))
|
||||
self.assertEqual([line.split(" — ")[0] for line in dimensions], ["- Navigation", "- Locality", "- Shape", "- Self-sufficiency"])
|
||||
self.assertEqual(dimensions[1], "- Locality — understanding and changing one piece without holding the rest: hidden state, order dependence, action at a distance.")
|
||||
|
||||
def test_reads_the_bullets_by_how_they_open_whatever_else_the_section_holds(self):
|
||||
skill = SKILL.read_text()
|
||||
with_extra = skill.replace("## The score\n\n", "## The score\n\n- A bullet before the anchors.\n\n", 1)
|
||||
self.assertEqual(score_bullets(with_extra), score_bullets(skill))
|
||||
|
||||
def test_fails_where_an_anchor_is_missing(self):
|
||||
self.assertIsInstance(score_bullets(SKILL.read_text().replace("- **10 — Duress-proof.**", "- Dropped:", 1)), Failure)
|
||||
|
||||
def test_fails_where_a_dimension_is_missing(self):
|
||||
self.assertIsInstance(score_bullets(SKILL.read_text().replace("- **Shape** —", "- Dropped:", 1)), Failure)
|
||||
|
||||
def test_fails_where_a_fifth_dimension_is_added(self):
|
||||
skill = SKILL.read_text()
|
||||
self.assertIsInstance(score_bullets(skill.replace("- **Shape** —", "- **Extra** — a new one.\n- **Shape** —", 1)), Failure)
|
||||
|
||||
|
||||
class ProjectValues(unittest.TestCase):
|
||||
def test_reads_each_spelling_the_projects_use(self):
|
||||
for spelling in (
|
||||
"## Scoring run\n\nThe values:\n\n- `{language}`: Python\n- `{kind}`: a CLI\n- `{domain}`: parsing\n- `{domain docs}`: the spec\n- `{3am question}`: the parse\n hangs\n\n## Next\n\n- `{kind}`: other\n",
|
||||
"# Scoring run\n\n- **Language:** Python\n- **Kind:** a CLI\n- **Domain:** parsing\n- **Domain docs:** the spec\n- **3am question:** the parse hangs\n",
|
||||
"## 8. Scoring run\n\n- Language: Python.\n- Kind: a CLI.\n- Domain: parsing.\n- Domain docs: the spec.\n- 3am question: the parse hangs.\n",
|
||||
):
|
||||
with self.subTest(spelling=spelling[:20]):
|
||||
self.assertEqual(project_values(spelling, "AGENTS.md"), VALUES)
|
||||
|
||||
def test_keeps_a_colon_an_x_and_an_ellipsis_in_a_value_and_skips_a_bullet_without_a_colon(self):
|
||||
text = "## Scoring run\n\n- Language: Python\n- Kind: a CLI: small\n- Kind\n- Domain: LaTeX\n- Domain docs: the spec\n- 3am question: it hangs...\n"
|
||||
self.assertEqual(project_values(text, "AGENTS.md"), {**VALUES, "kind": "a CLI: small", "domain": "LaTeX", "3am question": "it hangs..."})
|
||||
|
||||
def test_names_the_values_a_section_lacks_and_a_file_without_one(self):
|
||||
self.assertEqual(project_values("## Scoring run\n\n- Language: Python\n- Kind: a CLI\n", "AGENTS.md"), Failure("AGENTS.md → \"Scoring run\" gives no {domain}, {domain docs} or {3am question}; add them as seat-prompts.md lists them"))
|
||||
self.assertEqual(project_values("# P\n", "AGENTS.md"), Failure("AGENTS.md has no \"Scoring run\" section to fill the seats' prompts from; add one with {language}, {kind}, {domain}, {domain docs} and {3am question}"))
|
||||
|
||||
|
||||
class FileGlobs(unittest.TestCase):
|
||||
def test_names_no_test_files_where_every_glob_holds_none(self):
|
||||
self.assertEqual(file_globs(["bin/a.py", "tests/x.py", "README.md"]), "`bin/**` and `README.md`")
|
||||
|
||||
def test_gives_one_glob_per_directory_and_each_top_level_file_leaving_out_tests_and_the_forbidden_files(self):
|
||||
paths = ["README.md", "ci.sh", "bin/run", "bin/a/main.py", "bin/a/test_main.py", "docs/decisions.md", "docs/guide.md", "todo.md", "tests/x.py", "web/app.test.ts"]
|
||||
self.assertEqual(file_globs(paths), "`bin/**` except test files, `docs/**`, `README.md` and `ci.sh`, test files being `test_*`, `*_test.*`, `*.test.*`, `*.spec.*` and those under a `test` or `tests` folder")
|
||||
|
||||
|
||||
class Bullets(unittest.TestCase):
|
||||
def test_joins_continuations_and_splits_runs_at_other_lines(self):
|
||||
lines = [" stray", "- a ", " more", "Text", "- b", "", "- c"]
|
||||
self.assertEqual(bullets(lines), [["- a more"], ["- b"], ["- c"]])
|
||||
|
||||
|
||||
class PrepareScoring(unittest.TestCase):
|
||||
def setUp(self):
|
||||
temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(temp.cleanup)
|
||||
self.root = pathlib.Path(os.path.realpath(temp.name))
|
||||
self.env = {**isolated_env(), "GIT_CONFIG_GLOBAL": os.devnull, "HOME": str(self.root)}
|
||||
self.checkout = self.root / "proj"
|
||||
self.checkout.mkdir()
|
||||
self.git("init", "-q", "-b", "item-9")
|
||||
(self.checkout / "README.md").write_text("# P\n")
|
||||
(self.checkout / "bin").mkdir()
|
||||
(self.checkout / "bin" / "tool.py").write_text("")
|
||||
|
||||
def git(self, *args):
|
||||
return subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", *args], cwd=self.checkout, check=True, env=self.env, capture_output=True, text=True).stdout
|
||||
|
||||
def commit(self, agents=None):
|
||||
if agents is not None:
|
||||
(self.checkout / "AGENTS.md").write_text(agents)
|
||||
self.git("add", "-A")
|
||||
self.git("commit", "-q", "-m", "start")
|
||||
|
||||
def prepare(self, preloaded=None):
|
||||
"""What prepare-scoring returns in the checkout, run in this process so mutation tests see the lines it runs."""
|
||||
with mock.patch.dict(os.environ, self.env, clear=True):
|
||||
return prepare_scoring(str(self.checkout), preloaded)
|
||||
|
||||
def run_tool(self, *args):
|
||||
return subprocess.run([sys.executable, str(TOOL), *args], capture_output=True, cwd=self.checkout, env=self.env, text=True)
|
||||
|
||||
def test_writes_each_seats_prompt_with_every_placeholder_filled_and_a_worktree_at_head(self):
|
||||
self.commit("# A\n\n## Scoring run\n\n- Language: Python\n- Kind: a CLI\n- Domain: parsing\n- Domain docs: the spec\n- 3am question: the parse hangs\n")
|
||||
ran = self.prepare("`README.md`")
|
||||
folder = self.root / ".local" / "state" / "larv-review" / "proj" / "scoring"
|
||||
worktree = folder / "checkout"
|
||||
prompts = [folder / f"{seat}.md" for seat in ("junior-a", "mid-a", "maintainability-senior", "inherited-architect")]
|
||||
self.assertEqual(ran, f"Scoring worktree, at {self.git('rev-parse', '--short', 'HEAD').strip()}: {worktree}\nPrompts:\n" + "\n".join(str(prompt) for prompt in prompts))
|
||||
self.assertEqual(subprocess.run(["git", "rev-parse", "HEAD"], cwd=worktree, env=self.env, capture_output=True, text=True).stdout, self.git("rev-parse", "HEAD"))
|
||||
junior, _, senior, architect = (prompt.read_text() for prompt in prompts)
|
||||
for prompt in (junior, architect):
|
||||
self.assertEqual(re.findall(r"\{[a-z0-9 ]+\}", prompt), [])
|
||||
self.assertTrue(junior.startswith(f"You are one seat of a comprehension panel. Tools: Read, Grep, Glob, and Bash only for `git -C {worktree} ls-files` and `ls`."))
|
||||
self.assertIn("\n\nYour background: ~2 years in Python, first codebase of this kind (a CLI); no exposure to the domain at all.\n\n", junior)
|
||||
self.assertIn(f"Target: the project checked out at {worktree} (branch `item-9`). Read ONLY there — never {self.checkout}, which is a different version.", junior)
|
||||
self.assertIn("every non-test tracked file: `bin/**`, `AGENTS.md` and `README.md`. Do NOT open todo.md, docs/decisions.md,", junior)
|
||||
self.assertIn("from a DIFFERENT version (main): `README.md`.", junior)
|
||||
self.assertIn("\n- 7 — Predictable. The layout answers", junior)
|
||||
self.assertIn("Report, in this shape:", senior)
|
||||
self.assertIn("~15 years taking over other people's systems", architect)
|
||||
self.assertIn("The 3am question: the parse hangs — walking in cold", architect)
|
||||
self.assertNotIn("Report, in this shape:", architect)
|
||||
(folder / "mid-a.md").write_text("stale")
|
||||
again = self.prepare()
|
||||
self.assertTrue(again.startswith(f"Removed the scoring run set up before in {folder}.\nScoring worktree, at "))
|
||||
self.assertNotEqual((folder / "mid-a.md").read_text(), "stale")
|
||||
self.assertEqual(len(self.git("worktree", "list").splitlines()), 2)
|
||||
|
||||
def test_says_it_could_not_remove_a_checkout_git_does_not_hold(self):
|
||||
self.commit()
|
||||
checkout = self.root / ".local" / "state" / "larv-review" / "proj" / "scoring" / "checkout"
|
||||
checkout.mkdir(parents=True)
|
||||
with mock.patch.dict(os.environ, self.env, clear=True):
|
||||
removed = removed_setup(str(self.checkout))
|
||||
self.assertIsInstance(removed, Failure)
|
||||
self.assertTrue(removed.reason.startswith(f"could not remove the scoring worktree {checkout}: "), removed.reason)
|
||||
self.assertTrue(checkout.exists())
|
||||
|
||||
def test_refuses_writing_nothing_where_the_project_gives_no_values(self):
|
||||
self.commit()
|
||||
ran = self.run_tool("prepare-scoring")
|
||||
self.assertEqual(ran.returncode, 1)
|
||||
self.assertIn("AGENTS.md has no \"Scoring run\" section", ran.stderr)
|
||||
self.assertFalse((self.root / ".local" / "state" / "larv-review" / "proj" / "scoring").exists())
|
||||
self.assertEqual(len(self.git("worktree", "list").splitlines()), 1)
|
||||
|
||||
def test_lists_the_harness_files_where_no_preloaded_is_given(self):
|
||||
(self.checkout / "CLAUDE.md").write_text("@AGENTS.md\n")
|
||||
self.commit("## Scoring run\n\n- Language: Python\n- Kind: a CLI\n- Domain: parsing\n- Domain docs: the spec\n- 3am question: the parse hangs\n")
|
||||
self.assertNotIsInstance(self.prepare(), Failure)
|
||||
junior = (self.root / ".local" / "state" / "larv-review" / "proj" / "scoring" / "junior-a.md").read_text()
|
||||
self.assertIn("from a DIFFERENT version (main): `CLAUDE.md` and `AGENTS.md`, which it imports.", junior)
|
||||
|
||||
def test_leaves_out_a_claude_md_the_project_settings_exclude(self):
|
||||
(self.root / ".claude").mkdir()
|
||||
(self.root / ".claude" / "CLAUDE.md").write_text("# Home\n")
|
||||
(self.root / ".claude" / "rules").mkdir()
|
||||
rule = "always"
|
||||
(self.root / ".claude" / "rules" / f"{rule}.md").write_text("# Always\n")
|
||||
(self.checkout / ".claude").mkdir()
|
||||
(self.checkout / ".claude" / "settings.json").write_text('{"claudeMdExcludes": ["**/.claude/CLAUDE.md"]}\n')
|
||||
(self.checkout / ".claude" / "settings.local.json").write_text("not json")
|
||||
self.assertEqual(preloaded_files(self.checkout, self.root), f"`~/.claude/rules/{rule}.md`")
|
||||
(self.checkout / ".claude" / "settings.json").write_text('{"claudeMdExcludes": [3]}\n')
|
||||
self.assertEqual(preloaded_files(self.checkout, self.root), f"`~/.claude/CLAUDE.md` and `~/.claude/rules/{rule}.md`")
|
||||
|
||||
def test_names_each_import_and_each_rule_without_paths_leaving_out_what_the_user_settings_exclude(self):
|
||||
(self.root / ".claude" / "rules").mkdir(parents=True)
|
||||
(self.root / ".claude" / "settings.json").write_text('{"claudeMdExcludes": ["**/rules/skipped.md"]}')
|
||||
(self.root / ".claude" / "rules" / "skipped.md").write_text("# Skipped\n")
|
||||
(self.checkout / "CLAUDE.md").write_text("# Project\n\n@AGENTS.md\n@docs/x.md\n")
|
||||
(self.checkout / ".claude" / "rules").mkdir(parents=True)
|
||||
(self.checkout / ".claude" / "rules" / "always.md").write_text("# Always\n")
|
||||
(self.checkout / ".claude" / "rules" / "scoped.md").write_text("---\npaths: ['*.py']\n---\n")
|
||||
imports, rule = "`AGENTS.md`, which it imports, `docs/x.md`, which it imports", "always"
|
||||
self.assertEqual(preloaded_files(self.checkout, self.root), f"`{CLAUDE_MD}`, {imports} and `.claude/rules/{rule}.md`")
|
||||
|
||||
def test_reads_the_excludes_of_both_settings_files_and_names_none_where_nothing_loads(self):
|
||||
(self.root / ".claude").mkdir()
|
||||
(self.root / ".claude" / "CLAUDE.md").write_text("# Home\n")
|
||||
(self.checkout / "CLAUDE.md").write_text("# Project\n")
|
||||
(self.checkout / ".claude").mkdir()
|
||||
settings, local = self.checkout / ".claude" / "settings.json", self.checkout / ".claude" / "settings.local.json"
|
||||
for first, second in (("not json", '{"claudeMdExcludes": ["**/.claude/*.md", "**/proj/*.md"]}'), ('{"claudeMdExcludes": ["**/.claude/*.md"]}', '{"claudeMdExcludes": ["**/proj/*.md"]}')):
|
||||
with self.subTest(first=first):
|
||||
settings.write_text(first)
|
||||
local.write_text(second)
|
||||
self.assertEqual(preloaded_files(self.checkout, self.root), "none")
|
||||
for odd in ("[1]", '{"claudeMdExcludes": 3}'):
|
||||
with self.subTest(odd=odd):
|
||||
settings.write_text(odd)
|
||||
local.write_text(odd)
|
||||
self.assertEqual(preloaded_files(self.checkout, self.root), f"`~/.claude/{CLAUDE_MD}` and `{CLAUDE_MD}`")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -10,7 +10,7 @@ def unmeasured_cut(default: str, checkout: str) -> str | None | Failure:
|
||||
|
||||
The reason ends once a run follows the earlier tag, so it asks only after a release was cut with none; it lets the chunk that finds the gap record the run.
|
||||
|
||||
A scoring run counts by the time its history heading records, against the tag's commit time; a heading whose time doesn't parse counts for nothing, so the run is asked for again.
|
||||
A scoring run counts by the time its history heading records, against the tag's commit time; a heading whose time doesn't parse doesn't count, so the run is asked for again.
|
||||
"""
|
||||
# Sorts v1.0.0-rc.1 below v1.0.0, as release.newest_tag does.
|
||||
tags = git("-c", "versionsort.suffix=-", "tag", "--list", "v*", "--merged", default, "--sort=-v:refname", cwd=checkout)
|
||||
|
||||
@@ -14,6 +14,7 @@ from loop_state.waiting.listing import listed, shown
|
||||
from loop_state.waiting.talk import make_way, TALK
|
||||
from loop_claude.stop import needs_human, needs_terminal, Stop
|
||||
from model_routing.ladder import Rung
|
||||
from loop_claude.direct_message import tell
|
||||
|
||||
ANSWER_QUESTION = "answer the question above"
|
||||
# ASK_ANSWER was picked on 2026-10-17 by a bench of three readers seated as the README's audience, as ~/.claude/CLAUDE.md → "Working loop" → "Bench a syntax with the people who write it." has it.
|
||||
@@ -40,12 +41,16 @@ class Talked:
|
||||
|
||||
|
||||
def interrupt(question: str, answer_here: bool, session: WorkerSession, questions: pathlib.Path, effects: Effects) -> str | Talked | Stop:
|
||||
"""Prints question for the human and returns their answer: where answer_here, the first line typed at loop-claude's terminal or in loop-inbox, stripped, or Talked once they typed in the worker's claude session, which TALK opens; else Talked once they typed in that session, which opens at once on the terminal. loop-inbox lists the question meanwhile. A Stop where loop-claude is off a terminal, or they type nothing, or the input ends."""
|
||||
"""Prints question for the human and returns their answer: where answer_here, the first line typed at loop-claude's terminal or in loop-inbox, stripped, or Talked once they typed in the worker's claude session, which TALK opens; else Talked once they typed in that session, which opens at once on the terminal. loop-inbox lists the question meanwhile. A Stop where loop-claude is off a terminal, or they type no answer, or the input ends."""
|
||||
say(f"\n{question}", effects)
|
||||
if stop := needs_terminal(ANSWER_QUESTION, effects.on_terminal()):
|
||||
on_terminal = effects.on_terminal()
|
||||
if on_terminal:
|
||||
# Keys typed while the worker ran wait on the terminal, and would answer a question no one has read, here or in claude's session, which reads them too. Of a pasted answer, the first line answers; the rest wait, and the next question drops them. A longer answer goes through TALK.
|
||||
effects.discard_typed()
|
||||
# After the discard, so an answer typed while the DM sends counts; before the terminal check, so a loop that cannot ask still tells the human what it would have asked.
|
||||
tell(f"loop-claude in {session.root} asks:\n\n{question}", effects)
|
||||
if stop := needs_terminal(ANSWER_QUESTION, on_terminal):
|
||||
return stop
|
||||
# Keys typed while the worker ran wait on the terminal, and would answer a question no one has read, here or in claude's session, which reads them too. Of a pasted answer, the first line answers; the rest wait, and the next question drops them. A longer answer goes through TALK.
|
||||
effects.discard_typed()
|
||||
ask = Ask(effects.new_id(), str(session.id), session.root, question, effects.now(), Asking(session.claude_command()) if answer_here else OpenOnTerminal())
|
||||
with listed(questions, ask, effects):
|
||||
answer = first_answer(ask, questions, effects) if answer_here else OpenOnTerminal()
|
||||
@@ -55,7 +60,7 @@ def interrupt(question: str, answer_here: bool, session: WorkerSession, question
|
||||
|
||||
|
||||
def first_answer(ask: Ask, questions: pathlib.Path, effects: Effects) -> str | OpenOnTerminal | OpenInInbox | Stop:
|
||||
"""The first answer to ask, from loop-claude's terminal or loop-inbox: the line typed, stripped, or where claude is to open for it. A Stop where they type nothing, or the input ends."""
|
||||
"""The first answer to ask, from loop-claude's terminal or loop-inbox: the line typed, stripped, or where claude is to open for it. A Stop where they type no answer, or the input ends."""
|
||||
try:
|
||||
# Annotated since mypy infers input_or's T as object from the lambda.
|
||||
answer: str | Answer = effects.input_or(ASK_ANSWER, lambda: answered(questions, ask))
|
||||
@@ -105,4 +110,4 @@ def human_typed(transcript_path: str, held_open: typing.Callable[[], Stop | None
|
||||
entries = read_transcript(transcript_path)
|
||||
if isinstance(entries, Failure):
|
||||
return Stop(1, f"could not tell whether you typed anything: {entries.reason}")
|
||||
return None if human_turns(entries) > before else needs_human(ANSWER_QUESTION, "the interrupt ended with nothing typed")
|
||||
return None if human_turns(entries) > before else needs_human(ANSWER_QUESTION, "the interrupt ended without anything typed")
|
||||
|
||||
@@ -9,11 +9,12 @@ from loop_effects.effects import Effects
|
||||
from claude_code.entries import Entry, structured_output
|
||||
from loop_claude import escalation_mark
|
||||
from failure import Failure
|
||||
from loop_claude.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished, Verdict
|
||||
from claude_code.transcript import plain, verbatim
|
||||
from loop_claude.verdicts import Finished, Interrupt, Judged, QuotedAnswer, Unfinished, Verdict
|
||||
from claude_code.transcript import human_answers, plain, verbatim
|
||||
from loop_claude.cycle.retry import retried
|
||||
from model_routing.ladder import Rung
|
||||
from loop_claude.stop import Stop
|
||||
from claude_code.tokens import tokens_of
|
||||
|
||||
# At 3 to 4 characters a token, 100,000 to 133,000 tokens, which leaves a 200,000-token context room for the reply; the largest session rendered here was 364,000 characters on 2026-10-03.
|
||||
JUDGE_PROMPT_CHARS = 400000
|
||||
@@ -75,8 +76,10 @@ class Reply:
|
||||
answered_before: str = dataclasses.field(metadata={"description": "With interrupt true, a [human] line from earlier in the chunk that answered the question the worker asks now, quoted verbatim, without elisions. Empty otherwise."})
|
||||
left_open: str = dataclasses.field(metadata={"description": "With answered_before set, the words of that line that leave open what the question asks, quoted verbatim; the question ends with them. Empty otherwise."})
|
||||
question: str = dataclasses.field(metadata={"description": "With interrupt true, the single question to put to the human. With a quoted answer, the worker's question that the answer field answers. Empty otherwise."})
|
||||
# True opens claude's session at once, in place of the one-line answer (run.ask). The judge decides it, since loop-claude computes the plan's standing (release_standing.chunk_item) only when it routes a chunk on the ladder afresh: it would miss a release ready to cut in a resumed chunk or off the ladder. A wrong ruling costs the human one typed /talk, or answering in claude, which stops the loop if they leave it with nothing typed.
|
||||
# True opens claude's session at once, in place of the one-line answer (run.ask). The judge decides it, since loop-claude computes the plan's standing (release_standing.chunk_item) only when it routes a chunk on the ladder afresh: it would miss a release ready to cut in a resumed chunk or off the ladder. A wrong ruling costs the human one typed /talk, or answering in claude, which stops the loop if they leave it without typing anything.
|
||||
release_ready: bool = dataclasses.field(metadata={"description": "With interrupt true, whether the question is about a release ready to cut, which only the human may publish. False otherwise."})
|
||||
# Finds the answer that reverses a choice the worker took on its own recommendation. score-outcomes counts these answers per chunk: they are the counter-signal the 2026-11-08 entry of docs/decisions.md → `loop-claude: a judge decides each interrupt and each quoted answer…` stays valid by.
|
||||
reversed: str = dataclasses.field(metadata={"description": "The latest [human] line that overrides a choice the worker took on its own recommendation and recorded with its reason, quoted verbatim, without elisions. Empty where none does; a line that answers a question the worker left open doesn't override anything."})
|
||||
|
||||
|
||||
REPLY_TYPES = typing.get_type_hints(Reply)
|
||||
@@ -103,6 +106,8 @@ class Grounds(typing.NamedTuple):
|
||||
after_mark: str
|
||||
# README.md's premises and the records.
|
||||
quotable: str
|
||||
# Each answer the human typed, whole, latest last (transcript.human_answers).
|
||||
typed: tuple[str, ...] = ()
|
||||
|
||||
|
||||
class Brief(typing.NamedTuple):
|
||||
@@ -164,7 +169,8 @@ def run_judge(root: str, args: list[str], prompt: str, grounds: Grounds, effects
|
||||
reply = claude_reply(effects.claude, args, root, prompt, "the judge")
|
||||
if isinstance(reply, Failure | Limited):
|
||||
return reply
|
||||
verdict = verdict_from(structured_output(reply))
|
||||
output = structured_output(reply)
|
||||
verdict = verdict_from(output)
|
||||
replied = json.dumps(reply, ensure_ascii=False)
|
||||
cost = cost_of(reply)
|
||||
if isinstance(verdict, Failure):
|
||||
@@ -172,7 +178,13 @@ def run_judge(root: str, args: list[str], prompt: str, grounds: Grounds, effects
|
||||
checked = quotes_checked(verdict, grounds)
|
||||
if isinstance(checked, Failure):
|
||||
return Rejected(checked.reason, replied, cost)
|
||||
return dataclasses.replace(checked, judge_cost=cost)
|
||||
return dataclasses.replace(checked, judged=Judged(cost, tokens_of(reply.get("usage")), reversal_of(output, grounds.typed)))
|
||||
|
||||
|
||||
def reversal_of(output: object, typed: tuple[str, ...]) -> str:
|
||||
"""The latest answer the human typed that holds the reply's reversed quote, whole, so the same answer archives the same way however the judge quotes it; empty where none does. verdict_from has checked the field is a str."""
|
||||
quote = output.get("reversed") if isinstance(output, dict) else None
|
||||
return next((answer for answer in reversed(typed) if isinstance(quote, str) and verbatim(quote, answer)), "")
|
||||
|
||||
|
||||
def cost_of(reply: dict) -> float:
|
||||
@@ -191,6 +203,7 @@ def quotes_checked(verdict: Verdict, grounds: Grounds) -> Verdict | Failure:
|
||||
| its left_open | answered_before and the question | the interrupt becomes an Unfinished that quotes answered_before back to the worker | re_ask_checked |
|
||||
| a quoted answer | grounds.quotable | the question goes to the human as an interrupt, which keeps the escalation the answer carried | answer_checked |
|
||||
| the escalation | grounds.shown and grounds.after_mark | the escalation is dropped, so the worker's rung holds | escalation_mark.checked |
|
||||
| the reversal | one of grounds.typed | the reversal is dropped; run_judge, after this check | reversal_of |
|
||||
|
||||
Only a misquoted evidence fails. A Failure for any other would exit an unattended loop, so each changes the verdict instead.
|
||||
"""
|
||||
@@ -252,5 +265,6 @@ def judge_prompt(brief: Brief) -> tuple[str, Grounds]:
|
||||
shown=shown,
|
||||
after_mark=escalation_mark.after_mark(brief.entries, brief.escalated_at),
|
||||
quotable=f"{brief.premises}\n\n{brief.records}",
|
||||
typed=tuple(human_answers(brief.entries, typed_answer)),
|
||||
)
|
||||
return f"{head}{shown}\n\n{JUDGE_RULES}", grounds
|
||||
@@ -88,7 +88,7 @@ def markdown_launch(choice: ReviewChoice) -> list[str]:
|
||||
def shared_launches(choice: ReviewChoice, route: Route, project: Rung) -> list[str]:
|
||||
"""A sentence for each rung, other than the worker's, that the reviewers, the seats or the security pass run on.
|
||||
|
||||
For a worker on Sonnet 5.5 at high, on an Opus 5.5 project, routed by item 3 of E + I 5, they read: `Launch each reviewer with the Agent tool set to model opus, effort high, the rung item 3's E + I of 5 picks.` and `Launch each comprehension seat and the security pass's subagent with the Agent tool set to model opus, effort medium, the project's rung.`
|
||||
For a worker one rung below the project's, routed by item 3 of E + I 5, they read: `Launch each reviewer with the Agent tool set to <rung>, the rung item 3's E + I of 5 picks.` and `Launch each comprehension seat and the security pass's subagent with the Agent tool set to <rung>, the project's rung.`
|
||||
"""
|
||||
together = {EACH_REVIEWER: choice.reviewers, EACH_SEAT: choice.seat, THE_SECURITY_PASS: choice.security}
|
||||
launched: dict[Rung, list[str]] = {}
|
||||
@@ -101,7 +101,7 @@ def shared_launches(choice: ReviewChoice, route: Route, project: Rung) -> list[s
|
||||
def taken_in_launches(choice: ReviewChoice) -> list[str]:
|
||||
"""The sentence naming the reviewers' rung each higher E + I picks, so the worker reviews an item it takes in on that rung in the same run, since loop-claude reads a taken-in item's E + I only as the cycle ends, and routes on it from the next cycle. None where no higher E + I picks a higher rung.
|
||||
|
||||
For a worker on Opus 5.5 at medium, on an Opus 5.5 project, routed by an item of E + I 6, it reads: `Where an item you take into the chunk has an E + I of 7 or more, launch each reviewer with the Agent tool set to `model opus, effort max` from 7 and `model fable, effort max` from 8.`
|
||||
For a worker on the project's rung, routed by an item of E + I 6, it reads: `Where an item you take into the chunk has an E + I of 7 or more, launch each reviewer with the Agent tool set to `<rung>` from 7 and `<rung>` from 8.`
|
||||
"""
|
||||
if not choice.higher:
|
||||
return []
|
||||
@@ -122,7 +122,7 @@ def escalation(route: Route, project: Rung | None) -> list[str]:
|
||||
"""The prompt's escalation sentences, the marker's among them. None off the ladder or on its top rung. Where escalation_rungs opens none, the worker escalates only with the human's yes.
|
||||
Else they name the rungs escalation_rungs opens to a subagent, and offer to resume the worker one rung up for the rest of the chunk, up to the highest of those rungs.
|
||||
|
||||
For a worker on Opus 5.5 at high, on an Opus 5.5 project, routed by item 3 of L 4, they read: `When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `model opus, effort xhigh`, one rung above yours, and on each further trigger one rung higher, up to `model opus, effort max`; above that, ask the human first.`, `Open the subagent's prompt with `Escalation trigger <n>:`, n the trigger's number.` and `Where the hard part is the rest of the chunk, end your run instead, asking loop-claude for a higher rung and naming a trigger that fired since your last step-up, if any: once the judge finds it in your transcript, the next cycle resumes you one rung up, up to `model opus, effort max`.`
|
||||
For a worker one rung above the project's, routed by item 3 of L 4, they read: `When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `<rung>`, one rung above yours, and on each further trigger one rung higher, up to `<rung>`; above that, ask the human first.`, `Open the subagent's prompt with `Escalation trigger <n>:`, n the trigger's number.` and `Where the hard part is the rest of the chunk, end your run instead, asking loop-claude for a higher rung and naming a trigger that fired since your last step-up, if any: once the judge finds it in your transcript, the next cycle resumes you one rung up, up to `<rung>`.`
|
||||
"""
|
||||
if project is None or route.rung not in LADDER[:-1]:
|
||||
return []
|
||||
@@ -144,7 +144,7 @@ def escalation(route: Route, project: Rung | None) -> list[str]:
|
||||
def reruns(route: Route, project: Rung | None) -> list[str]:
|
||||
"""The sentence naming the rung one above a reviewer's and the one above a seat's, on which each reruns when it asks, leaving out either that is already on the top rung. None off the ladder.
|
||||
|
||||
For a worker on Sonnet 5.5 at high, on an Opus 5.5 project, routed by an item of E + I 4, it reads: `A reviewer or comprehension seat that asks for a rerun one rung up reruns with the Agent tool set to `model opus, effort high`.`
|
||||
For a worker one rung below the project's, routed by an item of E + I 4, it reads: `A reviewer or comprehension seat that asks for a rerun one rung up reruns with the Agent tool set to `<rung>`.`
|
||||
"""
|
||||
if project is None or route.rung not in LADDER:
|
||||
return []
|
||||
|
||||
@@ -9,16 +9,19 @@ from loop_claude.cycle.judge import Brief, judge, Rejected
|
||||
from loop_claude.cycle import chunk_items
|
||||
from claude_code.session import delete_session, Session, session_open, transcript_file
|
||||
from loop_effects.effects import Effects, say
|
||||
from claude_code.entries import Entry
|
||||
from failure import Failure
|
||||
from loop_claude.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished, Verdict
|
||||
from loop_claude.verdicts import Finished, Interrupt, Judged, QuotedAnswer, Unfinished, Verdict
|
||||
from loop_claude.cycle.interrupt import interrupt, Talked, WorkerSession
|
||||
from loop_claude.routing import judge_rung, next_route, step_up, StepUp
|
||||
from transcript_archive.read import last_spent
|
||||
from transcript_archive import outcomes
|
||||
from loop_claude.cycle import prompts
|
||||
from claude_code.transcript import read_transcript
|
||||
from loop_claude.cycle.retry import retried
|
||||
from model_routing.route import Route
|
||||
from model_routing.ladder import Rung
|
||||
from loop_claude.cycle import spend
|
||||
from loop_claude.stop import Stop
|
||||
from model_routing import worker_rungs
|
||||
|
||||
@@ -29,6 +32,8 @@ class Cycle:
|
||||
|
||||
Each step reads the few fields it needs by name, so the fields stay at one level. docs/decisions.md → `principles: about seven things per level, …` allows more than seven where a reader finds them by name.
|
||||
"""
|
||||
# The claude-config release and commit the cycle runs under, such as `v0.8.0 (<sha>)`, or why they are unknown: loop/main.py's setup_version.
|
||||
config: str
|
||||
effects: Effects
|
||||
# What chunk-preflight found, or why it could not run, for a fresh worker's prompt; empty when the session was open as the cycle began.
|
||||
facts: str
|
||||
@@ -100,7 +105,7 @@ def archived(project_archive: pathlib.Path, transcript_path: str, task: str, out
|
||||
|
||||
def judge_of(cycle: Cycle) -> Rung:
|
||||
"""The judge's rung, which the archive names beside each verdict."""
|
||||
return judge_rung(cycle.judge_model, cycle.route)
|
||||
return judge_rung(cycle.judge_model)
|
||||
|
||||
|
||||
def step(cycle: Cycle, state: Active) -> Event | Stop:
|
||||
@@ -158,17 +163,32 @@ def rule(cycle: Cycle, transcript_path: str, quoted_answers: int) -> Ruled | Sto
|
||||
verdict = dataclasses.replace(verdict, taken_in=chunk_items.taken_in(entries, cycle.todo))
|
||||
if not isinstance(verdict, Interrupt | QuotedAnswer):
|
||||
return Ruled(verdict)
|
||||
annotation = annotation_of(cycle, transcript_path, entries, verdict.judged)
|
||||
if isinstance(annotation, Failure):
|
||||
return Stop(1, annotation.reason)
|
||||
stepped = ruling_step_up(cycle, verdict)
|
||||
if failure := archive_stepped(cycle, transcript_path, ruling_outcome(cycle, verdict, quoted_answers), stepped):
|
||||
if failure := archive_stepped(cycle, transcript_path, ruling_outcome(cycle, verdict, quoted_answers, annotation), stepped):
|
||||
return Stop(1, failure.reason)
|
||||
return Ruled(verdict, stepped.after if stepped else None)
|
||||
|
||||
|
||||
def ruling_outcome(cycle: Cycle, ruling: Interrupt | QuotedAnswer, quoted_answers: int) -> str:
|
||||
def annotation_of(cycle: Cycle, transcript_path: str, entries: list[Entry], judged: Judged) -> outcomes.Annotation | Failure:
|
||||
"""What a verdict, an interrupt or a quoted answer records beside its judge lines: the setup, the stretch's spend as spend.py counts it, and the reversal the judge found."""
|
||||
since = last_spent(cycle.project_archive, transcript_path)
|
||||
if isinstance(since, Failure):
|
||||
return since
|
||||
subagents = spend.subagents(transcript_path)
|
||||
if isinstance(subagents, Failure):
|
||||
return subagents
|
||||
spent = spend.spent(since, entries, subagents, judge_of(cycle).model, judged.tokens)
|
||||
return outcomes.Annotation(cycle.config, outcomes.spent_block(since, spent), judged.reversed)
|
||||
|
||||
|
||||
def ruling_outcome(cycle: Cycle, ruling: Interrupt | QuotedAnswer, quoted_answers: int, annotation: outcomes.Annotation) -> str:
|
||||
"""The archive's outcome for a ruling: interrupted where it goes to the human, with the question put to them, and else answered from README.md or the records."""
|
||||
if isinstance(ruling, QuotedAnswer) and not to_the_human(ruling, quoted_answers):
|
||||
return outcomes.answered(question=ruling.question, sources=prompts.QUOTE_SOURCES, answer=ruling.answer, evidence=ruling.evidence, escalation=ruling.escalation, judge=str(judge_of(cycle)), worker=cycle.route.worker_line(), judge_cost=ruling.judge_cost)
|
||||
return outcomes.interrupted(question_for(ruling), ruling.evidence, str(judge_of(cycle)), ruling.escalation, cycle.route.worker_line(), ruling.judge_cost)
|
||||
return outcomes.answered(question=ruling.question, sources=prompts.QUOTE_SOURCES, answer=ruling.answer, evidence=ruling.evidence, escalation=ruling.escalation, judge=str(judge_of(cycle)), worker=cycle.route.worker_line(), judge_cost=ruling.judged.cost, annotation=annotation)
|
||||
return outcomes.interrupted(question_for(ruling), ruling.evidence, str(judge_of(cycle)), ruling.escalation, cycle.route.worker_line(), ruling.judged.cost, annotation)
|
||||
|
||||
|
||||
def keep_rejection(cycle: Cycle, transcript_path: str, rejected: Rejected) -> Stop | None:
|
||||
@@ -212,7 +232,11 @@ def question_for(ruling: Interrupt | QuotedAnswer) -> str:
|
||||
|
||||
|
||||
def close(cycle: Cycle, transcript_path: str, verdict: Finished | Unfinished) -> Archived | Stop:
|
||||
outcome = outcomes.finished(cycle.route.worker_line(), verdict.evidence, str(judge_of(cycle)), verdict.judge_cost) if isinstance(verdict, Finished) else outcomes.unfinished(cycle.route.worker_line(), verdict.evidence, str(judge_of(cycle)), verdict.escalation, verdict.judge_cost)
|
||||
entries = read_transcript(transcript_path)
|
||||
annotation = entries if isinstance(entries, Failure) else annotation_of(cycle, transcript_path, entries, verdict.judged)
|
||||
if isinstance(annotation, Failure):
|
||||
return Stop(1, annotation.reason)
|
||||
outcome = outcomes.finished(cycle.route.worker_line(), verdict.evidence, str(judge_of(cycle)), verdict.judged.cost, annotation) if isinstance(verdict, Finished) else outcomes.unfinished(cycle.route.worker_line(), verdict.evidence, str(judge_of(cycle)), verdict.escalation, verdict.judged.cost, annotation)
|
||||
if failure := archived(cycle.project_archive, transcript_path, cycle.task, outcome, cycle.effects):
|
||||
return Stop(1, failure.reason)
|
||||
if isinstance(verdict, Finished) and (failure := delete_session(cycle.session)):
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
"""What a stretch of the chunk's work spent, in raw tokens by model and kind, which the archive records beside each verdict, interrupt and quoted answer: docs/decisions.md → `loop-claude: each verdict records the claude-config release and commit that ran it…`.
|
||||
|
||||
A stretch runs from the previous outcome that recorded a spend, or from the chunk's start, to the ruling. It counts the worker's main thread, each subagent and the judge run that ruled, each message once. Dollars are left to be derived from the model and the tokens, at the prices recorded beside them.
|
||||
"""
|
||||
import datetime
|
||||
import json
|
||||
import pathlib
|
||||
import typing
|
||||
|
||||
from claude_code.entries import AssistantTurn, Entry, messages
|
||||
from failure import Failure
|
||||
from claude_code.transcript import read_transcript
|
||||
from transcript_archive.outcomes import Spender
|
||||
from claude_code.tokens import Tokens, tokens_of
|
||||
|
||||
WORKER = "worker"
|
||||
JUDGE = "judge"
|
||||
|
||||
|
||||
class Subagent(typing.NamedTuple):
|
||||
"""A subagent's transcript, named by the agent type and the description its .meta.json gives: {"agentType": "Explore", "description": "Search the hooks", ...}."""
|
||||
name: str
|
||||
entries: list[Entry]
|
||||
|
||||
|
||||
def spent(since: str, worker: list[Entry], subagents: list[Subagent], judge_model: str, judge: Tokens) -> dict[Spender, Tokens]:
|
||||
"""The tokens each spender spent after since, a UTC stamp, or in the whole transcript where since is empty."""
|
||||
found: dict[Spender, Tokens] = {}
|
||||
for name, entries in ((WORKER, worker), *subagents):
|
||||
for model, tokens in thread_spend(entries, since).items():
|
||||
found[name, model] = found.get((name, model), Tokens()).plus(tokens)
|
||||
found[JUDGE, judge_model] = judge
|
||||
return {spender: tokens for spender, tokens in found.items() if tokens != Tokens()}
|
||||
|
||||
|
||||
def thread_spend(entries: list[Entry], since: str) -> dict[str, Tokens]:
|
||||
"""Each model's tokens in one transcript's messages written after since. Each message counts once."""
|
||||
start = moment(since) if since else None
|
||||
found: dict[str, Tokens] = {}
|
||||
for turn, *_ in messages(entry for entry in entries if isinstance(entry, AssistantTurn) and entry.model and (start is None or later(entry.timestamp, start))):
|
||||
found[turn.model] = found.get(turn.model, Tokens()).plus(tokens_of(turn.usage))
|
||||
return found
|
||||
|
||||
|
||||
def moment(stamp: str) -> datetime.datetime:
|
||||
return datetime.datetime.fromisoformat(stamp)
|
||||
|
||||
|
||||
# An outcome's stamp runs to the second, so a message written earlier in that second would count in both stretches. The worker writes none then, since the judge runs for seconds after its last message. A subagent or a /talk session still running may write one, and that message is then counted twice.
|
||||
def later(timestamp: str, start: datetime.datetime) -> bool:
|
||||
"""Whether timestamp is after start; False where it is no time, or names no time zone to compare by."""
|
||||
try:
|
||||
return moment(timestamp) > start
|
||||
except (TypeError, ValueError):
|
||||
return False
|
||||
|
||||
|
||||
def subagents(transcript_path: str) -> list[Subagent] | Failure:
|
||||
"""The subagents' transcripts Claude Code keeps beside the worker's: <session>/subagents/agent-<id>.jsonl, each with its .meta.json."""
|
||||
found = []
|
||||
for path in sorted(pathlib.Path(transcript_path.removesuffix(".jsonl"), "subagents").glob("*.jsonl")):
|
||||
entries = read_transcript(str(path))
|
||||
if isinstance(entries, Failure):
|
||||
return entries
|
||||
found.append(Subagent(subagent_name(path), entries))
|
||||
return found
|
||||
|
||||
|
||||
def subagent_name(transcript: pathlib.Path) -> str:
|
||||
"""The agent type and the quoted description; `subagent` where the meta is missing or names neither."""
|
||||
try:
|
||||
meta = json.loads(transcript.with_name(transcript.name.removesuffix(".jsonl") + ".meta.json").read_text(encoding="utf-8"))
|
||||
except (OSError, UnicodeDecodeError, ValueError):
|
||||
meta = {}
|
||||
meta = meta if isinstance(meta, dict) else {}
|
||||
# One line for the type, since a line break could forge an archive line such as `Config: `; json.dumps escapes the description's.
|
||||
kind, description = " ".join(str(meta.get("agentType") or "subagent").split()), str(meta.get("description") or "")
|
||||
return f"{kind} {json.dumps(description, ensure_ascii=False)}" if description else kind
|
||||
@@ -0,0 +1,7 @@
|
||||
from loop_effects.effects import Effects, say
|
||||
|
||||
|
||||
def tell(text: str, effects: Effects) -> None:
|
||||
"""DMs text to the human. Where the DM fails, it says why on stderr and goes on: the DM only copies what the terminal shows, so its failure never stops the loop."""
|
||||
if failed := effects.dm(text):
|
||||
say(f"could not DM you on Mattermost: {failed.reason}", effects)
|
||||
@@ -12,6 +12,7 @@ from loop_claude.loop.reload import decode_handed, exec_if_edited, fingerprint,
|
||||
from loop_effects.effects import Effects, say
|
||||
from failure import Failure
|
||||
from loop_claude.project.model_choice import get_or_ask_models
|
||||
from git_cli.git_repo import Git
|
||||
from loop_claude.loop.usage import HELP
|
||||
from loop_claude.loop.this_loop import Loop
|
||||
from loop_state.paths import Paths
|
||||
@@ -22,7 +23,7 @@ from loop_claude.project.records import read_records
|
||||
from claude_code.session import session_named
|
||||
from loop_state.running_loops import shown_running
|
||||
from loop_claude.stop import Stop
|
||||
|
||||
from loop_claude.direct_message import tell
|
||||
|
||||
|
||||
def main(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launcher: pathlib.Path, cwd: pathlib.Path, effects: Effects) -> int:
|
||||
@@ -30,8 +31,14 @@ def main(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launcher:
|
||||
stop = run_loop(argv, env, paths, launcher, cwd, effects)
|
||||
except KeyboardInterrupt:
|
||||
stop = Stop(130, "")
|
||||
except Exception as crash:
|
||||
tell(f"loop-claude in {cwd} crashed: {crash!r}", effects)
|
||||
raise
|
||||
if stop.reason:
|
||||
say(stop.reason, effects, stdout=not stop.code)
|
||||
# Every stop but the human's own Ctrl-C and the help is DMed, so a loop left overnight never ends unseen. A loop given no task prints the help.
|
||||
if stop.code != 130 and stop.reason != HELP:
|
||||
tell(f"loop-claude in {cwd} stopped: {stop.reason}", effects)
|
||||
return stop.code
|
||||
|
||||
|
||||
@@ -83,7 +90,7 @@ def next_cycle(loop_run: LoopRun, loop: Loop) -> Cycle | Stop:
|
||||
todo = fetched_todo(loop)
|
||||
show_taken_in = shown_items(loop, todo, route.item)
|
||||
show_taken_in(loop_run.items_taken_in)
|
||||
return Cycle(effects=loop.effects, facts=facts, judge_model=models.judge, premises=premises, project=project, project_archive=archive_folder, questions=loop.listed.folder, records=records, root=loop.root, route=route, session=loop.session, show_taken_in=show_taken_in, task=loop_run.task, todo=todo, unfinished_evidence=loop_run.unfinished_evidence)
|
||||
return Cycle(config=setup_version(loop.paths.claude_dir, loop.effects.git), effects=loop.effects, facts=facts, judge_model=models.judge, premises=premises, project=project, project_archive=archive_folder, questions=loop.listed.folder, records=records, root=loop.root, route=route, session=loop.session, show_taken_in=show_taken_in, task=loop_run.task, todo=todo, unfinished_evidence=loop_run.unfinished_evidence)
|
||||
|
||||
|
||||
def loop_run_from(argv: list[str], cwd: pathlib.Path, effects: Effects) -> LoopRun | Stop:
|
||||
@@ -97,3 +104,19 @@ def loop_run_from(argv: list[str], cwd: pathlib.Path, effects: Effects) -> LoopR
|
||||
if not (loop_run and loop_run.root and loop_run.task):
|
||||
return Stop(1, f"the edited loop-claude cannot read the state the running one handed it, likely because the edit changed that handover; rerun loop-claude <task>. Handed: {' '.join(argv[1:])}")
|
||||
return loop_run
|
||||
|
||||
|
||||
def setup_version(claude_dir: pathlib.Path, git: Git) -> str:
|
||||
"""The release and commit of this setup that the worker's claude reads, as `v0.8.0 (<sha>)`; a commit past the latest release reads as git describe gives it, such as `v0.8.0-3-g1a2b3c4 (<sha>)`. Where git can't tell, `unknown` and why."""
|
||||
described = git("describe", "--tags", "--match", "v*", "--always", cwd=str(claude_dir))
|
||||
commit = git("rev-parse", "HEAD", cwd=str(claude_dir))
|
||||
if isinstance(described, Failure):
|
||||
return unknown_version(described)
|
||||
if isinstance(commit, Failure):
|
||||
return unknown_version(commit)
|
||||
return f"{described.strip()} ({commit.strip()})"
|
||||
|
||||
|
||||
def unknown_version(failure: Failure) -> str:
|
||||
# One line, since the archive reads the line after it as the judge's.
|
||||
return f"unknown: {' '.join(failure.reason.split())}"
|
||||
|
||||
@@ -14,6 +14,7 @@ from routing_figures.render import render
|
||||
from model_routing.ladder import Rung
|
||||
from routing_figures import state
|
||||
from loop_claude.stop import Stop
|
||||
from loop_claude.direct_message import tell
|
||||
from records.utc_stamp import utc
|
||||
|
||||
|
||||
@@ -54,10 +55,11 @@ def raise_calls(root: pathlib.Path, new: list[Call], rung: Rung, loop: Loop) ->
|
||||
bullets = "".join(f"- {call.sentence()}\n" for call in new)
|
||||
question = f"loop-claude's routing figures call for a routing change:\n{bullets}The figures: {root / archive.FIGURES}"
|
||||
say(f"\n{question}", loop.effects)
|
||||
tell(f"loop-claude in {loop.root} asks:\n\n{question}", loop.effects)
|
||||
if not loop.effects.on_terminal():
|
||||
say("Not on a terminal: the calls are raised again at the next measurement.", loop.effects)
|
||||
return None
|
||||
prompt = f"Put these calls for a routing change from loop-claude's figures to the human, and change nothing until they answer:\n{bullets}The figures are in {root / archive.FIGURES}. The ladder, its steps and the delegation rule are docs/decisions.md → `routing:`, and a change to them is the human's. Record what they decide in this checkout, the development clone, as ~/.claude/CLAUDE.md says; the next chunk of this repo files the plan item for these calls."
|
||||
prompt = f"Put these calls for a routing change from loop-claude's figures to the human, and don't change anything until they answer:\n{bullets}The figures are in {root / archive.FIGURES}. The ladder, its steps and the delegation rule are docs/decisions.md → `routing:`, and a change to them is the human's. Record what they decide in this checkout, the development clone, as ~/.claude/CLAUDE.md says; the next chunk of this repo files the plan item for these calls."
|
||||
ask = Ask(loop.effects.new_id(), str(loop.session.id), loop.root, question, loop.effects.now(), OpenOnTerminal())
|
||||
with listed(loop.listed.folder, ask, loop.effects):
|
||||
unstarted = hand_over(ClaudeCommand(claude_args(rung, [prompt]), str(loop.paths.config_clone), {}), loop.effects)
|
||||
|
||||
@@ -33,6 +33,9 @@ interrupts of every loop on the machine. The first answer counts, from either pl
|
||||
- Enter alone, on loop-claude's terminal: stops the loop.
|
||||
A release ready to cut opens that session on the terminal at once, since only the human may cut it;
|
||||
loop-inbox lists it too. While claude is open, Ctrl-C reaches it alone, and the loop goes on.
|
||||
Where ~/.claude/.env exists, loop-claude also sends the human each question, each release ready
|
||||
to cut and each stop as a Mattermost DM, as bin/mattermost-dm sends it. Two stops are left out:
|
||||
Ctrl-C, and printing this help. A DM that fails is said on stderr, and the loop goes on.
|
||||
|
||||
While it runs, loop-claude also lists itself in loop-inbox, with the todo.md items its chunk takes,
|
||||
as bin/loop_state/running_loops.py describes.
|
||||
@@ -119,7 +122,7 @@ Exit 2, when the human is needed to go on:
|
||||
- stdin or stdout is not a terminal, when a model must be picked or an interrupt answered
|
||||
- the input ends while a model is picked
|
||||
- an interrupt's answer is empty, or the input ends before one is typed
|
||||
- the claude opened for /talk, here or in loop-inbox, or for a release ready to cut, ends with
|
||||
nothing typed
|
||||
- the claude opened for /talk, here or in loop-inbox, or for a release ready to cut, ends without
|
||||
anything typed
|
||||
- the judge rules a chunk unfinished 6 cycles running; rerun to give it 6 more
|
||||
Rerunning resumes any open session."""
|
||||
|
||||
@@ -16,5 +16,5 @@ def read_premises(root: str) -> str | Failure:
|
||||
if len(bodies) > 1:
|
||||
return Failure(f"README.md has ## {name} more than once - no premises.")
|
||||
if not bodies[0]:
|
||||
return Failure(f"README.md has nothing under ## {name} - no premises.")
|
||||
return Failure(f"README.md has no text under ## {name} - no premises.")
|
||||
return f"## Goals\n{found['Goals'][0]}\n\n## Audience\n{found['Audience'][0]}"
|
||||
|
||||
@@ -10,7 +10,7 @@ The worker, and the session /talk opens, run on a Route (model_routing/route.py)
|
||||
import dataclasses
|
||||
|
||||
from release_plan.release_standing import chunk_item, LastCut, Next
|
||||
from model_routing.ladder import climbed, highest, LADDER, position, project_rung, review_floor, Rung, stepped_up, worker_rung
|
||||
from model_routing.ladder import climbed, highest, LADDER, position, project_rung, Rung, stepped_up, worker_rung
|
||||
from loop_claude import escalation_mark
|
||||
from failure import Failure
|
||||
from loop_claude.verdicts import Interrupt, QuotedAnswer, Unfinished
|
||||
@@ -20,7 +20,7 @@ from model_routing.route import Route
|
||||
UNFINISHED_PER_STEP = 2
|
||||
# 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`.
|
||||
# The models whose cheapest rung, in a `judge-replay` run, returned every interrupt the reference judge reproduced: docs/decisions.md → `routing: on a model judge-replay covered`.
|
||||
JUDGE_REPLAYED = ("claude-opus-5-5",)
|
||||
|
||||
|
||||
@@ -137,12 +137,8 @@ def one_rung_up(route: Route, rung: Rung, escalated_at: int) -> Route:
|
||||
return dataclasses.replace(route, rung=stepped_up(rung), unfinished=0, escalated_at=escalated_at)
|
||||
|
||||
|
||||
def judge_rung(judge_model: str, route: Route) -> Rung:
|
||||
"""The rung the route's reviewed_on E + I picks for a review, counted from the judge model's cheapest rung and never below it, whatever rung the worker stepped to.
|
||||
|
||||
A model off the ladder, or not in JUDGE_REPLAYED, gets no effort flag, so claude runs it at the effort its settings give.
|
||||
"""
|
||||
cheapest = project_rung(judge_model)
|
||||
if cheapest is None or judge_model not in JUDGE_REPLAYED:
|
||||
def judge_rung(judge_model: str) -> Rung:
|
||||
"""The highest of the judge model's own rungs: docs/decisions.md → `routing: on a model judge-replay covered`. A model off the ladder, or not in JUDGE_REPLAYED, gets no effort flag, so claude runs it at the effort its settings give."""
|
||||
if project_rung(judge_model) is None or judge_model not in JUDGE_REPLAYED:
|
||||
return Rung(judge_model)
|
||||
return review_floor(cheapest, route.reviewed_on())
|
||||
return highest(*(rung for rung in LADDER if rung.model == judge_model))
|
||||
|
||||
@@ -137,7 +137,7 @@ PREMISES = "# Project\n\n## Goals\n\n1. Work.\n\n## Audience\n\nMe.\n"
|
||||
TODO = "## Items\n\n| ID | Release | Exempt | Item | L | E | I | R | S | Moves | Score |\n|---|---|---|---|---|---|---|---|---|---|---|\n| 4 | 0.1.0 | | **Do it.** | 4 | 2 | 3 | 7 | 2 | 1 by 9 | 25 |\n"
|
||||
# Item 4's L of 2 steps one rung down.
|
||||
CHEAP = TODO.replace("| 4 | 2 | 3 | 7 |", "| 2 | 1 | 2 | 3 |")
|
||||
# Item 9 follows CHEAP's item 4, and a worker routed by item 4 may take it in: at L 4 it picks a higher rung for the worker, and at E + I 6 for the judge and the reviewers. At E + I 3, or at L 2, it picks the rung item 4 picks.
|
||||
# Item 9 follows CHEAP's item 4, and a worker routed by item 4 may take it in: at L 4 it picks a higher rung for the worker, and at E + I 6 for the reviewers. At E + I 3, or at L 2, it picks the rung item 4 picks.
|
||||
TAKEN_IN_AT_L_4 = CHEAP + "| 9 | 0.1.0 | | **Do more.** | 4 | 1 | 2 | 5 | 2 | 1 by 9 | 20 |\n"
|
||||
TAKEN_IN_AT_E_PLUS_I_6 = CHEAP + "| 9 | 0.1.0 | | **Do more.** | 2 | 3 | 3 | 6 | 2 | 1 by 9 | 20 |\n"
|
||||
|
||||
@@ -151,7 +151,7 @@ def worker(**step):
|
||||
|
||||
|
||||
def judge(interrupt=False, finished=False, evidence="working", question="", escalation="", release_ready=False, **step):
|
||||
verdict = {"answer": "", "escalation": escalation, "evidence": evidence, "finished": finished, "interrupt": interrupt, "question": question, "answered_before": "", "left_open": "", "release_ready": release_ready}
|
||||
verdict = {"answer": "", "escalation": escalation, "evidence": evidence, "finished": finished, "interrupt": interrupt, "question": question, "answered_before": "", "left_open": "", "release_ready": release_ready, "reversed": ""}
|
||||
return {"role": "judge", "verdict": verdict, **step}
|
||||
|
||||
|
||||
@@ -299,7 +299,7 @@ class Checkout:
|
||||
return pathlib.Path(self.env.get("LOOP_CLAUDE_TRANSCRIPTS", self.home / ".claude" / "loop-claude-transcripts"))
|
||||
|
||||
def archived(self):
|
||||
"""Each archived transcript's outcomes, with every UTC stamp replaced by <UTC>, after checking the copy is named by its content hash."""
|
||||
"""Each archived transcript's outcomes, with every UTC stamp replaced by <UTC> and every setup version by <config>, after checking the copy is named by its content hash."""
|
||||
outcomes = {}
|
||||
for folder in (self.archive(), self.archive() / "proj", *(self.archive() / "proj").iterdir()):
|
||||
self.test.assertEqual(stat.S_IMODE(folder.stat().st_mode), 0o700, folder)
|
||||
@@ -308,7 +308,8 @@ class Checkout:
|
||||
kept = copy.with_suffix(".outcomes.md")
|
||||
for archived in (copy, kept):
|
||||
self.test.assertEqual(stat.S_IMODE(archived.stat().st_mode), 0o600)
|
||||
outcomes[copy.read_text()] = re.sub(r"^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ ", "<UTC> ", kept.read_text(), flags=re.MULTILINE)
|
||||
stamped = re.sub(r"^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ ", "<UTC> ", kept.read_text(), flags=re.MULTILINE)
|
||||
outcomes[copy.read_text()] = re.sub(r"^Config: .*$", "Config: <config>", stamped, flags=re.MULTILINE)
|
||||
return outcomes
|
||||
|
||||
|
||||
@@ -341,7 +342,7 @@ class Premises(unittest.TestCase):
|
||||
b"# P\n## Goals\n1. g\xff\n## Audience\nme\n": "README.md in {root} is not UTF-8 on line 3 - no premises.",
|
||||
b"# P\n## Audience\nme\n": "README.md has no ## Goals heading - no premises.",
|
||||
b"# P\n## Goals\n1. g\n": "README.md has no ## Audience heading - no premises.",
|
||||
b"# P\n## Goals\n\n## Audience\nme\n": "README.md has nothing under ## Goals - no premises.",
|
||||
b"# P\n## Goals\n\n## Audience\nme\n": "README.md has no text under ## Goals - no premises.",
|
||||
b"# P\n## Goals\n1. g\n## Audience\nme\n## Audience\nyou\n": "README.md has ## Audience more than once - no premises.",
|
||||
}
|
||||
(checkout.root / "sub").mkdir()
|
||||
@@ -422,8 +423,8 @@ class Cycles(unittest.TestCase):
|
||||
self.assertIn("=== cycle 3, worker on worker-model ===", run.stdout)
|
||||
self.assertEqual(len(re.findall(rf"(?m)^{STAMP} === cycle 3, worker on worker-model ===$", run.raw_stdout)), 1)
|
||||
copies = {verdict.removeprefix(f"Task: {TASK}\n\n"): copy for copy, verdict in checkout.archived().items()}
|
||||
self.assertEqual(sorted(copies), [f"<UTC> Stopped: Ctrl-C\n\nWorker: {OFF_LADDER}\n", f"<UTC> Verdict: finished\n\nEvidence:\n> landed-it\n\nJudge: judge-model\nWorker: {OFF_LADDER}\n", f"<UTC> Verdict: unfinished\n\nEvidence:\n> started\n\nJudge: judge-model\nWorker: {OFF_LADDER}\n"])
|
||||
self.assertIn('"text": "landed-it"', copies[f"<UTC> Verdict: finished\n\nEvidence:\n> landed-it\n\nJudge: judge-model\nWorker: {OFF_LADDER}\n"])
|
||||
self.assertEqual(sorted(copies), [f"<UTC> Stopped: Ctrl-C\n\nWorker: {OFF_LADDER}\n", f"<UTC> Verdict: finished\n\nEvidence:\n> landed-it\n\nConfig: <config>\nJudge: judge-model\nWorker: {OFF_LADDER}\n", f"<UTC> Verdict: unfinished\n\nEvidence:\n> started\n\nConfig: <config>\nJudge: judge-model\nWorker: {OFF_LADDER}\n"])
|
||||
self.assertIn('"text": "landed-it"', copies[f"<UTC> Verdict: finished\n\nEvidence:\n> landed-it\n\nConfig: <config>\nJudge: judge-model\nWorker: {OFF_LADDER}\n"])
|
||||
self.assertIn('"text": "next chunk"', copies[f"<UTC> Stopped: Ctrl-C\n\nWorker: {OFF_LADDER}\n"])
|
||||
self.assertEqual(len(list(checkout.archive().glob(f"proj/*/session/{session}.orphaned-1-ab.jsonl"))), 1)
|
||||
|
||||
@@ -444,15 +445,15 @@ class Cycles(unittest.TestCase):
|
||||
("claude-sonnet-5-5", "high"),
|
||||
("claude-sonnet-5-5", "high"),
|
||||
("claude-opus-5-5", "medium"),
|
||||
("claude-opus-5-5", "high"),
|
||||
("claude-fable-5-2", "low"),
|
||||
("claude-sonnet-5-5", "high"),
|
||||
])
|
||||
self.assertEqual({(argument(call, "--model"), argument(call, "--effort")) for call in run.calls if call["role"] == "judge"}, {("judge-model", None)})
|
||||
self.assertIn("loop-claude runs you on claude-sonnet-5-5 at high effort, routed by item 4's L of 2.", argument(workers[0], "-p"))
|
||||
self.assertIn("on one line, as in `Chunk items: ", argument(workers[0], "-p"))
|
||||
outcomes = sorted(verdict.removeprefix(f"Task: {TASK}\n\n") for verdict in checkout.archived().values())
|
||||
self.assertIn('<UTC> Verdict: unfinished\n\nEvidence:\n> three\n\nJudge: judge-model\nWorker: {"model": "claude-opus-5-5", "effort": "medium", "item": 4, "likelihood": 2, "escape_and_impact": 3}\n\n<UTC> Stepped up\n\nWorker: {"model": "claude-opus-5-5", "effort": "high", "item": 4, "likelihood": 2, "escape_and_impact": 3}\n', outcomes)
|
||||
self.assertIn('<UTC> Verdict: finished\n\nEvidence:\n> four\n\nJudge: judge-model\nWorker: {"model": "claude-opus-5-5", "effort": "high", "item": 4, "likelihood": 2, "escape_and_impact": 3}\n', outcomes)
|
||||
self.assertIn('<UTC> Verdict: unfinished\n\nEvidence:\n> three\n\nConfig: <config>\nJudge: judge-model\nWorker: {"model": "claude-opus-5-5", "effort": "medium", "item": 4, "likelihood": 2, "escape_and_impact": 3}\n\n<UTC> Stepped up\n\nWorker: {"model": "claude-fable-5-2", "effort": "low", "item": 4, "likelihood": 2, "escape_and_impact": 3}\n', outcomes)
|
||||
self.assertIn('<UTC> Verdict: finished\n\nEvidence:\n> four\n\nConfig: <config>\nJudge: judge-model\nWorker: {"model": "claude-fable-5-2", "effort": "low", "item": 4, "likelihood": 2, "escape_and_impact": 3}\n', outcomes)
|
||||
|
||||
def test_routes_on_and_states_the_same_item_from_the_fetched_default_branch_whatever_the_checkout_holds(self):
|
||||
checkout = Checkout(self)
|
||||
@@ -501,14 +502,14 @@ class Cycles(unittest.TestCase):
|
||||
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"),
|
||||
("claude-fable-5-2", "low"),
|
||||
("claude-fable-5-2", "medium"),
|
||||
("claude-fable-5-2", "medium"),
|
||||
("claude-fable-5-2", "low"),
|
||||
])
|
||||
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: {"model": "claude-opus-5-5", "effort": "high", "item": 4, "likelihood": 4, "escape_and_impact": 5}\n\n<UTC> Stepped up\n\nWorker: {"model": "claude-opus-5-5", "effort": "xhigh", "item": 4, "likelihood": 4, "escape_and_impact": 5, "escalated_at": 4}\n', outcomes)
|
||||
self.assertIn('<UTC> Verdict: unfinished\n\nEvidence:\n> I ask for a higher rung.\n\nJudge: judge-model\nWorker: {"model": "claude-opus-5-5", "effort": "xhigh", "item": 4, "likelihood": 4, "escape_and_impact": 5, "escalated_at": 4}\n', outcomes)
|
||||
self.assertIn('<UTC> Verdict: unfinished\n\nEvidence:\n> I ask for a higher rung.\n\nEscalation:\n> Stability round 2: a 🔴.\n\nConfig: <config>\nJudge: judge-model\nWorker: {"model": "claude-fable-5-2", "effort": "low", "item": 4, "likelihood": 4, "escape_and_impact": 5}\n\n<UTC> Stepped up\n\nWorker: {"model": "claude-fable-5-2", "effort": "medium", "item": 4, "likelihood": 4, "escape_and_impact": 5, "escalated_at": 4}\n', outcomes)
|
||||
self.assertIn('<UTC> Verdict: unfinished\n\nEvidence:\n> I ask for a higher rung.\n\nConfig: <config>\nJudge: judge-model\nWorker: {"model": "claude-fable-5-2", "effort": "medium", "item": 4, "likelihood": 4, "escape_and_impact": 5, "escalated_at": 4}\n', outcomes)
|
||||
|
||||
def test_steps_the_worker_up_once_as_the_judge_interrupts_when_the_run_also_cites_an_escalation_trigger(self):
|
||||
checkout = Checkout(self)
|
||||
@@ -522,13 +523,13 @@ class Cycles(unittest.TestCase):
|
||||
], terminal_input="/talk\n", before_typing=ANSWERING)
|
||||
self.assertEqual(run.code, 130)
|
||||
self.assertEqual(run.roles(), ["worker", "judge", "interrupt", "judge", "worker", "judge"])
|
||||
self.assertEqual([(argument(call, "--model"), argument(call, "--effort")) for call in run.calls if call["role"] != "judge"], [("claude-opus-5-5", "high"), ("claude-opus-5-5", "xhigh"), ("claude-opus-5-5", "xhigh")])
|
||||
self.assertEqual([(argument(call, "--model"), argument(call, "--effort")) for call in run.calls if call["role"] != "judge"], [("claude-fable-5-2", "low"), ("claude-fable-5-2", "medium"), ("claude-fable-5-2", "medium")])
|
||||
outcomes = sorted(verdict.removeprefix(f"Task: {TASK}\n\n") for verdict in checkout.archived().values())
|
||||
self.assertIn('<UTC> Stepped up\n\nWorker: {"model": "claude-opus-5-5", "effort": "xhigh", "item": 4, "likelihood": 4, "escape_and_impact": 5, "escalated_at": 4}\n', "".join(outcomes))
|
||||
self.assertIn('<UTC> Stepped up\n\nWorker: {"model": "claude-fable-5-2", "effort": "medium", "item": 4, "likelihood": 4, "escape_and_impact": 5, "escalated_at": 4}\n', "".join(outcomes))
|
||||
self.assertNotIn("at max effort", "".join(outcomes))
|
||||
self.assertIn('Verdict: interrupt\n\nA or B?\n\nEvidence:\n> Shall I use A or B?\n\nEscalation:\n> Stability round 2: a 🔴.\n\nJudge: judge-model\nWorker: {"model": "claude-opus-5-5", "effort": "high", "item": 4, "likelihood": 4, "escape_and_impact": 5}\n\n<UTC> Stepped up\n\nWorker: {"model": "claude-opus-5-5", "effort": "xhigh", "item": 4, "likelihood": 4, "escape_and_impact": 5, "escalated_at": 4}\n', "".join(outcomes))
|
||||
self.assertIn('Verdict: interrupt\n\nA or B?\n\nEvidence:\n> Shall I use A or B?\n\nEscalation:\n> Stability round 2: a 🔴.\n\nConfig: <config>\nJudge: judge-model\nWorker: {"model": "claude-fable-5-2", "effort": "low", "item": 4, "likelihood": 4, "escape_and_impact": 5}\n\n<UTC> Stepped up\n\nWorker: {"model": "claude-fable-5-2", "effort": "medium", "item": 4, "likelihood": 4, "escape_and_impact": 5, "escalated_at": 4}\n', "".join(outcomes))
|
||||
|
||||
def test_runs_a_cheap_items_worker_below_the_projects_rung_with_its_reviewers_and_judge_on_it(self):
|
||||
def test_runs_a_cheap_items_worker_below_the_projects_rung_with_its_reviewers_on_it_and_its_judge_on_the_models_highest(self):
|
||||
checkout = Checkout(self)
|
||||
checkout.env["LOOP_CLAUDE_WORKER_MODEL"] = checkout.env["LOOP_CLAUDE_JUDGE_MODEL"] = "claude-opus-5-5"
|
||||
checkout.commit_plan(CHEAP)
|
||||
@@ -537,11 +538,11 @@ class Cycles(unittest.TestCase):
|
||||
first = next(call for call in run.calls if call["role"] == "worker")
|
||||
self.assertEqual((argument(first, "--model"), argument(first, "--effort")), ("claude-sonnet-5-5", "high"))
|
||||
ruling = next(call for call in run.calls if call["role"] == "judge")
|
||||
self.assertEqual((argument(ruling, "--model"), argument(ruling, "--effort")), ("claude-opus-5-5", "medium"))
|
||||
self.assertIn('Judge: claude-opus-5-5 at medium effort\nWorker: {"model": "claude-sonnet-5-5", "effort": "high", ', "".join(checkout.archived().values()))
|
||||
self.assertEqual((argument(ruling, "--model"), argument(ruling, "--effort")), ("claude-opus-5-5", "xhigh"))
|
||||
self.assertIn('Judge: claude-opus-5-5 at xhigh effort\nWorker: {"model": "claude-sonnet-5-5", "effort": "high", ', "".join(checkout.archived().values()))
|
||||
self.assertIn("Launch each reviewer, each comprehension seat and the security pass's subagent with the Agent tool set to model opus, effort medium, the project's rung.", argument(first, "-p"))
|
||||
|
||||
def test_routes_the_judge_and_the_reviewers_on_the_highest_e_plus_i_the_worker_takes_in(self):
|
||||
def test_routes_the_reviewers_on_the_highest_e_plus_i_the_worker_takes_in_and_keeps_the_judge_on_the_models_highest(self):
|
||||
checkout = Checkout(self)
|
||||
checkout.env["LOOP_CLAUDE_WORKER_MODEL"] = checkout.env["LOOP_CLAUDE_JUDGE_MODEL"] = "claude-opus-5-5"
|
||||
checkout.commit_plan(TAKEN_IN_AT_E_PLUS_I_6)
|
||||
@@ -551,10 +552,10 @@ class Cycles(unittest.TestCase):
|
||||
worker(say="next chunk"),
|
||||
])
|
||||
self.assertEqual(run.code, 130)
|
||||
self.assertEqual([argument(call, "--effort") for call in run.calls if call["role"] == "judge"], ["medium", "xhigh", "medium"])
|
||||
self.assertEqual([(argument(call, "--model"), argument(call, "--effort")) for call in run.calls if call["role"] == "judge"], [("claude-opus-5-5", "xhigh")] * 3)
|
||||
workers = [call for call in run.calls if call["role"] == "worker"]
|
||||
self.assertEqual({argument(call, "--effort") for call in workers}, {"high"})
|
||||
self.assertIn("Launch each reviewer with the Agent tool set to model opus, effort xhigh, the rung picked by an item of E + I 6 taken into the chunk.", argument(workers[1], "-p"))
|
||||
self.assertIn("Launch each reviewer with the Agent tool set to model fable, effort medium, the rung picked by an item of E + I 6 taken into the chunk.", argument(workers[1], "-p"))
|
||||
outcomes = "".join(checkout.archived().values())
|
||||
self.assertIn('<UTC> Stepped up\n\nWorker: {"model": "claude-sonnet-5-5", "effort": "high", "item": 4, "likelihood": 2, "escape_and_impact": 3, "escape_and_impact_taken_in": 6}\n', outcomes)
|
||||
self.assertIn('Judge: claude-opus-5-5 at xhigh effort\nWorker: {"model": "claude-sonnet-5-5", "effort": "high", "item": 4, "likelihood": 2, "escape_and_impact": 3, "escape_and_impact_taken_in": 6}\n', outcomes)
|
||||
@@ -565,12 +566,12 @@ class Cycles(unittest.TestCase):
|
||||
checkout.commit_plan(TODO)
|
||||
run = checkout.run([worker(), judge(), worker(), judge()])
|
||||
self.assertEqual(run.code, 130)
|
||||
self.assertEqual(argument(run.calls[-1], "--effort"), "xhigh")
|
||||
self.assertEqual((argument(run.calls[-1], "--model"), argument(run.calls[-1], "--effort")), ("claude-fable-5-2", "medium"))
|
||||
checkout.git("rm", "--quiet", "todo.md")
|
||||
checkout.git("commit", "--quiet", "-m", "drop the plan")
|
||||
run = checkout.run([worker()])
|
||||
self.assertIsNotNone(argument(run.calls[0], "--resume"))
|
||||
self.assertEqual((argument(run.calls[0], "--model"), argument(run.calls[0], "--effort")), ("claude-opus-5-5", "xhigh"))
|
||||
self.assertEqual((argument(run.calls[0], "--model"), argument(run.calls[0], "--effort")), ("claude-fable-5-2", "medium"))
|
||||
|
||||
def test_exits_1_when_the_transcript_cannot_be_archived_and_resumes_on_the_next_run(self):
|
||||
checkout = Checkout(self)
|
||||
@@ -702,10 +703,10 @@ class Cycles(unittest.TestCase):
|
||||
checkout.commit_plan(CHEAP)
|
||||
run = checkout.run([step for _ in range(6) for step in (worker(), judge())] + [worker()])
|
||||
self.assertEqual(run.code, 2)
|
||||
stepped = '<UTC> Stepped up\n\nWorker: {"model": "claude-opus-5-5", "effort": "xhigh", "item": 4, "likelihood": 2, "escape_and_impact": 3}\n\n<UTC> Stopped: '
|
||||
stepped = '<UTC> Stepped up\n\nWorker: {"model": "claude-fable-5-2", "effort": "medium", "item": 4, "likelihood": 2, "escape_and_impact": 3}\n\n<UTC> Stopped: '
|
||||
self.assertEqual(len([outcome for outcome in checkout.archived().values() if stepped in outcome]), 1)
|
||||
run = checkout.run([worker()])
|
||||
self.assertEqual([(argument(call, "--model"), argument(call, "--effort")) for call in run.calls if call["role"] == "worker"], [("claude-opus-5-5", "xhigh")])
|
||||
self.assertEqual([(argument(call, "--model"), argument(call, "--effort")) for call in run.calls if call["role"] == "worker"], [("claude-fable-5-2", "medium")])
|
||||
|
||||
def test_five_unfinished_verdicts_and_a_finished_one_do_not_add_up_to_six(self):
|
||||
checkout = Checkout(self)
|
||||
@@ -724,7 +725,7 @@ class Interrupt(unittest.TestCase):
|
||||
self.assertEqual(run.stderr.strip().splitlines()[-2:], ["A or B?", "the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun loop-claude on a terminal"])
|
||||
[(copy, verdict)] = checkout.archived().items()
|
||||
self.assertEqual(copy, (checkout.transcripts()[0]).read_text())
|
||||
self.assertEqual(verdict, f"Task: {TASK}\n\n<UTC> Verdict: interrupt\n\nA or B?\n\nEvidence:\n> Shall I use A or B?\n\nJudge: judge-model\nWorker: {OFF_LADDER}\n\n<UTC> Stopped: the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun loop-claude on a terminal\n\nWorker: {OFF_LADDER}\n")
|
||||
self.assertEqual(verdict, f"Task: {TASK}\n\n<UTC> Verdict: interrupt\n\nA or B?\n\nEvidence:\n> Shall I use A or B?\n\nConfig: <config>\nJudge: judge-model\nWorker: {OFF_LADDER}\n\n<UTC> Stopped: the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun loop-claude on a terminal\n\nWorker: {OFF_LADDER}\n")
|
||||
self.assertEqual(stat.S_IMODE((checkout.temp / "deep").stat().st_mode), 0o700)
|
||||
self.assertIn(f"transcript: {checkout.archive() / 'proj'}/", run.stderr)
|
||||
self.assertRegex(run.raw_stderr, rf"(?m)^{STAMP} transcript: ")
|
||||
@@ -800,7 +801,7 @@ class Interrupt(unittest.TestCase):
|
||||
transcript.unlink()
|
||||
run = checkout.run([*asked, interrupt()], terminal_input="/talk\n", before_typing=ANSWERING)
|
||||
self.assertEqual((run.code, run.roles()), (2, ["worker", "judge", "interrupt"]))
|
||||
self.assertTrue(run.stderr.strip().endswith("the human is needed to answer the question above, but the interrupt ended with nothing typed"))
|
||||
self.assertTrue(run.stderr.strip().endswith("the human is needed to answer the question above, but the interrupt ended without anything typed"))
|
||||
|
||||
run = checkout.run([worker(say="A or B?"), judge(interrupt=True, evidence="A or B?", question="A or B?", vanish=True)], terminal_input="/talk\n", before_typing=ANSWERING)
|
||||
self.assertEqual((run.code, run.roles()), (1, ["worker", "judge"]))
|
||||
|
||||
+352
-131
@@ -28,9 +28,10 @@ from release_plan.release_standing import DefaultPlan, LastCut
|
||||
from loop_effects.effects import Effects, POLL_SECONDS, PYTHON_TIMEOUT
|
||||
from claude_code import entries, reply, session
|
||||
from failure import Failure
|
||||
from loop_claude.verdicts import Finished, Interrupt, QuotedAnswer, TakenIn, Unfinished
|
||||
from loop_claude.verdicts import Finished, Interrupt, Judged, QuotedAnswer, TakenIn, Unfinished
|
||||
from git_cli.git_repo import git
|
||||
from loop_state import hand_over, paths, running_loops, session_lock
|
||||
from loop_claude.cycle import interrupt, judge, prompts, retry, run, states, worker
|
||||
from loop_claude.cycle import interrupt, judge, prompts, retry, run, spend, states, worker
|
||||
from model_routing.ladder import LADDER, Rung
|
||||
from claude_code.reply import Limited
|
||||
from loop_claude.loop import main, reload, routing_check, this_loop, usage
|
||||
@@ -42,12 +43,15 @@ from model_routing.route import Route, route_from, WorkerLine
|
||||
from loop_claude import routing
|
||||
from loop_claude.stop import Stop
|
||||
from loop_state.running_loops import Taken
|
||||
from claude_code.tokens import Tokens, tokens_of
|
||||
from records.utc_stamp import utc
|
||||
from loop_claude.cycle.judge import verdict_from
|
||||
from loop_state.waiting.listing import waiting
|
||||
|
||||
# How the archive records a worker that runs off the ladder.
|
||||
OFF_LADDER = '{"model": "worker-model"}'
|
||||
# The claude-config release and commit each cycle the tests run is under.
|
||||
CONFIG = "v0.8.0 (abc123)"
|
||||
# How it records routes by item 179's L of 2 and E + I of 5, on Routing's rungs.
|
||||
SONNET_179 = '{"model": "claude-sonnet-5-5", "effort": "high", "item": 179, "likelihood": 2, "escape_and_impact": 5}'
|
||||
OPUS_179_AT_3 = '{"model": "claude-opus-5-5", "effort": "medium", "item": 179, "likelihood": 2, "escape_and_impact": 5, "escalated_at": 3}'
|
||||
@@ -92,8 +96,11 @@ def a_loop(effects, **fields):
|
||||
class FakeEffects:
|
||||
"""Effects that record each call and answer from a script, one answer per call."""
|
||||
|
||||
def __init__(self, claude=(), on_terminal_claude=(), git=(), inputs=(), python=(), streams=(), on_terminal=True, free_memory=()):
|
||||
def __init__(self, claude=(), on_terminal_claude=(), git=(), inputs=(), python=(), streams=(), on_terminal=True, free_memory=(), dm_failures=()):
|
||||
self.calls = []
|
||||
# Each direct message sent. They stay out of self.calls, so a test that lists every call doesn't list them. Without a script, each is sent.
|
||||
self.dms = []
|
||||
self.dm_failures = list(dm_failures)
|
||||
self.scripts = {"claude": list(claude), "claude_on_terminal": list(on_terminal_claude), "git": list(git), "input": list(inputs), "python": list(python), "stream_claude": list(streams)}
|
||||
# Without a script, every read finds all memory available.
|
||||
self.free_memory = list(free_memory)
|
||||
@@ -108,6 +115,7 @@ class FakeEffects:
|
||||
claude=lambda args, cwd, stdin: self.answer("claude", (args, stdin)),
|
||||
claude_on_terminal=self.on_terminal_claude,
|
||||
discard_typed=lambda: self.calls.append(("discard_typed", None)),
|
||||
dm=self.dm,
|
||||
execv=self.execv,
|
||||
git=lambda *args, cwd=None, timeout=None, guarded=False, errors="strict": self.answer("git", list(args)),
|
||||
input=lambda prompt: self.answer("input", prompt),
|
||||
@@ -123,6 +131,10 @@ class FakeEffects:
|
||||
stream_claude=self.stream,
|
||||
)
|
||||
|
||||
def dm(self, text):
|
||||
self.dms.append(text)
|
||||
return self.dm_failures.pop(0) if self.dm_failures else None
|
||||
|
||||
def memory(self):
|
||||
self.calls.append(("memory", None))
|
||||
return self.free_memory.pop(0) if self.free_memory else memory.Memory(available=16, total=16)
|
||||
@@ -163,19 +175,21 @@ def ran(stdout="", code=0, stderr=""):
|
||||
return subprocess.CompletedProcess([], code, stdout, stderr)
|
||||
|
||||
|
||||
def judged(verdict, evidence="working", answer="", escalation="", release_ready=False, cost=None):
|
||||
reply = {"answer": answer, "escalation": escalation, "evidence": evidence, "finished": verdict == "finished", "interrupt": verdict == "interrupt", "question": "Which one?" if verdict in ("interrupt", "quoted") else "", "answered_before": "", "left_open": "", "release_ready": release_ready}
|
||||
def judged(verdict, evidence="working", answer="", escalation="", release_ready=False, cost=None, reversed=""):
|
||||
reply = {"answer": answer, "escalation": escalation, "evidence": evidence, "finished": verdict == "finished", "interrupt": verdict == "interrupt", "question": "Which one?" if verdict in ("interrupt", "quoted") else "", "answered_before": "", "left_open": "", "release_ready": release_ready, "reversed": reversed}
|
||||
return ran(json.dumps({"structured_output": reply, **({} if cost is None else {"total_cost_usd": cost})}))
|
||||
|
||||
|
||||
class Worker:
|
||||
"""A worker claude: writes a line to the session's transcript, then streams a result."""
|
||||
|
||||
def __init__(self, home, prompted=False, text="working"):
|
||||
def __init__(self, home, prompted=False, text="working", usage=None):
|
||||
self.home = home
|
||||
# Whether it records its -p prompt in the transcript first, as claude does.
|
||||
self.prompted = prompted
|
||||
self.text = text
|
||||
# The usage its message records, twice as Claude Code writes a message of two blocks; none where None.
|
||||
self.usage = usage
|
||||
|
||||
def __call__(self, args):
|
||||
flag = "--session-id" if "--session-id" in args else "--resume"
|
||||
@@ -186,7 +200,10 @@ class Worker:
|
||||
handle.write(json.dumps({"type": "custom-title"}) + "\n" + json.dumps({"type": "queue-operation", "timestamp": str(uuid.uuid7())}) + "\n")
|
||||
if self.prompted:
|
||||
handle.write(json.dumps({**human(args[args.index("-p") + 1]), "promptSource": "sdk"}) + "\n")
|
||||
handle.write(json.dumps(assistant({"type": "text", "text": self.text})) + "\n")
|
||||
said = assistant({"type": "text", "text": self.text})
|
||||
if self.usage is not None:
|
||||
said["message"] |= {"id": "msg-1", "model": "claude-opus-5-5", "usage": self.usage}
|
||||
handle.write((json.dumps(said) + "\n") * (1 if self.usage is None else 2))
|
||||
return Streamed(0)
|
||||
|
||||
|
||||
@@ -240,7 +257,7 @@ class Transitions(unittest.TestCase):
|
||||
states.transition(state, event)
|
||||
|
||||
def test_a_rulings_step_up_reaches_the_worker_it_resumes_through_the_answer_the_human_types_and_no_further(self):
|
||||
stepped_to = Route(Rung("claude-opus-5-5", "high"), escalated_at=3)
|
||||
stepped_to = Route(Rung("claude-fable-5-2", "low"), escalated_at=3)
|
||||
interrupt, quoted = Interrupt("e", "q", "round 2: 🔴"), QuotedAnswer("e", "q", "A.", "round 2: 🔴")
|
||||
for state, event, after in (
|
||||
(states.Judging("/t"), states.Ruled(quoted, stepped_to), states.Working(quoted, 1, True)),
|
||||
@@ -270,7 +287,7 @@ class Cycles(unittest.TestCase):
|
||||
self.archive = project_archive(str(self.home / "code" / "proj"), self.home, {})
|
||||
|
||||
def cycle(self, fake, records="", unfinished_evidence="", facts="- A preflight fact."):
|
||||
return run.Cycle(effects=fake.effects(), facts=facts, judge_model="judge-model", premises="## Goals", project=None, project_archive=self.archive, questions=self.paths.waiting, records=records, root=str(self.home), route=Route(Rung("worker-model")), session=self.session, show_taken_in=lambda items: None, task="Do it.", todo="", unfinished_evidence=unfinished_evidence)
|
||||
return run.Cycle(config=CONFIG, effects=fake.effects(), facts=facts, judge_model="judge-model", premises="## Goals", project=None, project_archive=self.archive, questions=self.paths.waiting, records=records, root=str(self.home), route=Route(Rung("worker-model")), session=self.session, show_taken_in=lambda items: None, task="Do it.", todo="", unfinished_evidence=unfinished_evidence)
|
||||
|
||||
def archived_outcomes(self):
|
||||
return sorted(path.read_text() for path in self.archive.glob("*/*.outcomes.md"))
|
||||
@@ -278,14 +295,38 @@ class Cycles(unittest.TestCase):
|
||||
def test_a_finished_chunk_is_archived_and_its_session_deleted(self):
|
||||
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("finished")])
|
||||
self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Finished("working"))
|
||||
self.assertEqual(self.archived_outcomes(), [f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: finished\n\nEvidence:\n> working\n\nJudge: judge-model\nWorker: {OFF_LADDER}\n"])
|
||||
self.assertEqual(self.archived_outcomes(), [f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: finished\n\nEvidence:\n> working\n\nConfig: {CONFIG}\nJudge: judge-model\nWorker: {OFF_LADDER}\n"])
|
||||
|
||||
def test_archives_the_cost_the_judges_reply_records_beside_its_verdict(self):
|
||||
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("finished", cost=0.25)])
|
||||
self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Finished("working", judge_cost=0.25))
|
||||
self.assertEqual(self.archived_outcomes(), [f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: finished\n\nEvidence:\n> working\n\nJudge: judge-model\nJudge cost: 0.2500\nWorker: {OFF_LADDER}\n"])
|
||||
self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Finished("working", judged=Judged(cost=0.25)))
|
||||
self.assertEqual(self.archived_outcomes(), [f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: finished\n\nEvidence:\n> working\n\nConfig: {CONFIG}\nJudge: judge-model\nJudge cost: 0.2500\nWorker: {OFF_LADDER}\n"])
|
||||
self.assertIsNone(session.transcript_file(self.session))
|
||||
|
||||
def test_archives_what_the_worker_and_the_judge_spent_beside_the_verdict(self):
|
||||
worker = Worker(self.paths.claude_code_transcripts.parent, usage={"input_tokens": 1, "cache_creation": {"ephemeral_5m_input_tokens": 2, "ephemeral_1h_input_tokens": 3}, "cache_read_input_tokens": 4, "output_tokens": 5})
|
||||
answer = json.loads(judged("finished").stdout)
|
||||
fake = FakeEffects(streams=[worker], claude=[ran(json.dumps({**answer, "usage": {"input_tokens": 6, "output_tokens": 7}}))])
|
||||
run.run_cycle(self.cycle(fake))
|
||||
self.assertEqual(self.archived_outcomes(), [f"""Task: Do it.
|
||||
|
||||
2026-09-21T14:13:20Z Verdict: finished
|
||||
|
||||
Evidence:
|
||||
> working
|
||||
|
||||
Spent since the chunk began, in tokens of input, cache write 5m, cache write 1h, cache read, output:
|
||||
- worker, claude-opus-5-5: 1, 2, 3, 4, 5
|
||||
- judge, judge-model: 6, 0, 0, 0, 7
|
||||
|
||||
List prices in dollars per million tokens of input, cache write 5m, cache write 1h, cache read, output:
|
||||
- claude-opus-5-5: 4, 5, 8, 0.2, 20
|
||||
|
||||
Config: {CONFIG}
|
||||
Judge: judge-model
|
||||
Worker: {OFF_LADDER}
|
||||
"""])
|
||||
|
||||
def test_shows_the_items_each_ruling_finds_the_worker_names_on_its_chunk_items_line(self):
|
||||
worker = Worker(self.paths.claude_code_transcripts.parent, text="working\nChunk items: 14 (L 2, E + I 3), 3 (L 1, E + I 2)")
|
||||
fake = FakeEffects(streams=[worker], claude=[judged("unfinished")])
|
||||
@@ -336,7 +377,7 @@ class Cycles(unittest.TestCase):
|
||||
self.assertIn("--session-id", workers[0])
|
||||
self.assertIn("--resume", workers[1])
|
||||
self.assertIn("as the work remaining:\n\n> working\n\nThe chunk is finished once", workers[1][workers[1].index("-p") + 1])
|
||||
self.assertEqual(self.archived_outcomes(), [f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: unfinished\n\nEvidence:\n> working\n\nJudge: judge-model\nWorker: {OFF_LADDER}\n"] * 2)
|
||||
self.assertEqual(self.archived_outcomes(), [f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: unfinished\n\nEvidence:\n> working\n\nConfig: {CONFIG}\nJudge: judge-model\nWorker: {OFF_LADDER}\n"] * 2)
|
||||
|
||||
def test_a_cycle_stopped_by_a_failure_or_ctrl_c_archives_what_its_session_holds(self):
|
||||
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[ran(code=1)] * 3)
|
||||
@@ -355,12 +396,13 @@ class Cycles(unittest.TestCase):
|
||||
"Task: Do it.\n\n"
|
||||
f"{stamp} Judge reply rejected: the judge's reply has no answer of type string\n\nReply:\n> {unfilled.stdout}\n\nJudge: judge-model\n\n"
|
||||
f"{stamp} Judge reply rejected: the judge quoted 'never said', which is not in the transcript\n\nReply:\n> {misquoted.stdout}\n\nJudge: judge-model\n\n"
|
||||
f"{stamp} Verdict: finished\n\nEvidence:\n> working\n\nJudge: judge-model\nWorker: {OFF_LADDER}\n"])
|
||||
f"{stamp} Verdict: finished\n\nEvidence:\n> working\n\nConfig: {CONFIG}\nJudge: judge-model\nWorker: {OFF_LADDER}\n"])
|
||||
|
||||
def test_archives_what_each_judge_run_cost_on_an_interrupt_a_quoted_answer_and_a_rejected_misquote(self):
|
||||
for first, then, inputs in (
|
||||
(judged("interrupt", cost=0.25), judged("finished"), ["Use B."]),
|
||||
(judged("quoted", answer="Use A.", cost=0.25), judged("finished"), []),
|
||||
(judged("unfinished", cost=0.25), judged("finished"), []),
|
||||
(judged("finished", evidence="never said", cost=0.25), judged("finished"), []),
|
||||
):
|
||||
with self.subTest(first=first.stdout), tempfile.TemporaryDirectory() as archive:
|
||||
@@ -370,6 +412,36 @@ class Cycles(unittest.TestCase):
|
||||
kept = "".join(path.read_text() for path in pathlib.Path(archive).glob("*/*.outcomes.md"))
|
||||
self.assertEqual(kept.count("Judge cost: 0.2500\n"), 1, kept)
|
||||
|
||||
def test_stops_with_exit_1_where_a_subagents_transcript_cannot_be_read_for_the_spend(self):
|
||||
for verdict in ("interrupt", "finished"):
|
||||
with self.subTest(verdict=verdict), tempfile.TemporaryDirectory() as archive:
|
||||
unreadable = self.paths.claude_code_transcripts / "-fake" / str(self.session.id) / "subagents" / "agent-x.jsonl"
|
||||
unreadable.mkdir(parents=True)
|
||||
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged(verdict)], inputs=["Use B."])
|
||||
with contextlib.redirect_stderr(io.StringIO()):
|
||||
stop = run.run_cycle(dataclasses.replace(self.cycle(fake), project_archive=pathlib.Path(archive)))
|
||||
self.assertEqual((stop.code, stop.reason), (1, f"could not read the transcript {unreadable}: Is a directory"))
|
||||
shutil.rmtree(unreadable.parent.parent)
|
||||
(self.paths.claude_code_transcripts / "-fake" / f"{self.session.id}.jsonl").unlink()
|
||||
|
||||
def test_counts_the_spend_since_the_last_outcome_that_recorded_one_and_archives_the_reversal(self):
|
||||
transcript = self.paths.claude_code_transcripts / "-fake" / f"{self.session.id}.jsonl"
|
||||
transcript.parent.mkdir(parents=True)
|
||||
old = {"type": "assistant", "timestamp": "2026-09-21T14:13:19Z", "message": {"id": "old", "model": "claude-opus-5-5", "content": [], "usage": {"output_tokens": 100}}}
|
||||
new = {"type": "assistant", "timestamp": "2026-09-21T14:13:21Z", "message": {"id": "new", "model": "claude-opus-5-5", "content": [], "usage": {"output_tokens": 5}}}
|
||||
transcript.write_text("\n".join(json.dumps(entry) for entry in [{"type": "queue-operation", "timestamp": "2026-09-21T14:00:00Z"}, old, human("No, keep the old name."), new]) + "\n")
|
||||
with contextlib.redirect_stderr(io.StringIO()):
|
||||
self.assertIsNone(write.archive(self.archive, str(transcript), "Do it.", outcomes.unfinished("w", "e", "j", "", annotation=outcomes.Annotation("c", "Spent since the chunk began, in tokens of x:\n- worker, m: 1")), NOW))
|
||||
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("unfinished", reversed="No, keep the old name.")])
|
||||
run.run_cycle(self.cycle(fake))
|
||||
latest = max(self.archived_outcomes(), key=len)
|
||||
self.assertIn(f"""Reversed:
|
||||
> No, keep the old name.
|
||||
|
||||
Spent since 2026-09-21T14:13:20Z, in tokens of input, cache write 5m, cache write 1h, cache read, output:
|
||||
- worker, claude-opus-5-5: 0, 0, 0, 0, 5
|
||||
""", latest)
|
||||
|
||||
def test_stops_with_exit_1_asking_nothing_where_an_interrupt_cannot_be_archived(self):
|
||||
self.archive.parent.mkdir(parents=True)
|
||||
self.archive.write_text("")
|
||||
@@ -442,7 +514,7 @@ class Cycles(unittest.TestCase):
|
||||
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("interrupt"), judged("unfinished")], inputs=["/talk"], on_terminal_claude=[answer])
|
||||
with contextlib.redirect_stderr(io.StringIO()):
|
||||
self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Unfinished("working", entries_read=4))
|
||||
self.assertEqual(self.archived_outcomes(), [f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: interrupt\n\nWhich one?\n\nEvidence:\n> working\n\nJudge: judge-model\nWorker: {OFF_LADDER}\n", f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: unfinished\n\nEvidence:\n> working\n\nJudge: judge-model\nWorker: {OFF_LADDER}\n"])
|
||||
self.assertEqual(self.archived_outcomes(), [f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: interrupt\n\nWhich one?\n\nEvidence:\n> working\n\nConfig: {CONFIG}\nJudge: judge-model\nWorker: {OFF_LADDER}\n", f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: unfinished\n\nEvidence:\n> working\n\nConfig: {CONFIG}\nJudge: judge-model\nWorker: {OFF_LADDER}\n"])
|
||||
self.assertIn(str(self.session.id), fake.made("claude_on_terminal")[0])
|
||||
judge_prompts = [stdin for args, stdin in fake.made("claude")]
|
||||
self.assertEqual(len(judge_prompts), 2)
|
||||
@@ -461,8 +533,8 @@ class Cycles(unittest.TestCase):
|
||||
self.assertEqual(len(fake.made("stream_claude")), 4)
|
||||
self.assertEqual(printed.getvalue().count("=== README.md's Goals and Audience, AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/ or ~/.claude/skills/larv-review/standards/ answered: Which one? ===\nUse *A*."), 3)
|
||||
self.assertIn("Which one?\n\nREADME.md's Goals and Audience, AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/ or ~/.claude/skills/larv-review/standards/ says:\nUse *A*.\n\nThose files have answered 3 questions this cycle", said.getvalue())
|
||||
quoted = f"2026-09-21T14:13:20Z Verdict: quoted answer\n\nWhich one?\n\nREADME.md's Goals and Audience, AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/ or ~/.claude/skills/larv-review/standards/ says:\n> Use *A*.\n\nEvidence:\n> working\n\nJudge: judge-model\nWorker: {OFF_LADDER}\n"
|
||||
self.assertEqual(self.archived_outcomes(), [f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: interrupt\n\nWhich one?\n\nREADME.md's Goals and Audience, AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/ or ~/.claude/skills/larv-review/standards/ says:\nUse *A*.\n\nThose files have answered 3 questions this cycle, the most allowed, so this one comes to you.\n\nEvidence:\n> working\n\nJudge: judge-model\nWorker: {OFF_LADDER}\n\n2026-09-21T14:13:20Z Stopped: the human is needed to answer the question above, but nothing was typed\n\nWorker: {OFF_LADDER}\n", *[f"Task: Do it.\n\n{quoted}"] * 3])
|
||||
quoted = f"2026-09-21T14:13:20Z Verdict: quoted answer\n\nWhich one?\n\nREADME.md's Goals and Audience, AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/ or ~/.claude/skills/larv-review/standards/ says:\n> Use *A*.\n\nEvidence:\n> working\n\nConfig: {CONFIG}\nJudge: judge-model\nWorker: {OFF_LADDER}\n"
|
||||
self.assertEqual(self.archived_outcomes(), [f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: interrupt\n\nWhich one?\n\nREADME.md's Goals and Audience, AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/ or ~/.claude/skills/larv-review/standards/ says:\nUse *A*.\n\nThose files have answered 3 questions this cycle, the most allowed, so this one comes to you.\n\nEvidence:\n> working\n\nConfig: {CONFIG}\nJudge: judge-model\nWorker: {OFF_LADDER}\n\n2026-09-21T14:13:20Z Stopped: the human is needed to answer the question above, but nothing was typed\n\nWorker: {OFF_LADDER}\n", *[f"Task: Do it.\n\n{quoted}"] * 3])
|
||||
|
||||
def test_a_quoted_answer_that_cites_an_escalation_trigger_steps_the_worker_up_before_it_resumes_and_archives_the_step(self):
|
||||
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 2, claude=[judged("quoted", answer="Use A.", escalation="working"), judged("finished")])
|
||||
@@ -474,7 +546,7 @@ class Cycles(unittest.TestCase):
|
||||
self.assertEqual([args[args.index("--effort") + 1] for args in (first, resumed)], ["high", "medium"])
|
||||
self.assertTrue(resumed[resumed.index("-p") + 1].endswith(f"Continue the task. Your request for a higher rung went through: loop-claude runs you on {Routing.OPUS}. The escalation triggers that fired before this step are spent.{prompts.rungs_held(concluded.route, Routing.OPUS)}"))
|
||||
self.assertNotIn("went through", first[first.index("-p") + 1])
|
||||
answered = f"Verdict: quoted answer\n\nWhich one?\n\n{prompts.QUOTE_SOURCES} says:\n> Use A.\n\nEvidence:\n> working\n\nEscalation:\n> working\n\nJudge: judge-model\nWorker: {SONNET_179}\n"
|
||||
answered = f"Verdict: quoted answer\n\nWhich one?\n\n{prompts.QUOTE_SOURCES} says:\n> Use A.\n\nEvidence:\n> working\n\nEscalation:\n> working\n\nConfig: {CONFIG}\nJudge: judge-model\nWorker: {SONNET_179}\n"
|
||||
stepped = f"Stepped up\n\nWorker: {OPUS_179_AT_3}\n"
|
||||
kept = "".join(self.archived_outcomes())
|
||||
self.assertIn(f"Z {answered}\n20", kept)
|
||||
@@ -487,7 +559,7 @@ class Cycles(unittest.TestCase):
|
||||
with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):
|
||||
self.assertEqual(run.run_cycle(cycle), Stop(2, "the human is needed to answer the question above, but nothing was typed"))
|
||||
kept = "".join(self.archived_outcomes())
|
||||
self.assertIn(f"Evidence:\n> working\n\nEscalation:\n> working\n\nJudge: judge-model\nWorker: {SONNET_179}\n", kept)
|
||||
self.assertIn(f"Evidence:\n> working\n\nEscalation:\n> working\n\nConfig: {CONFIG}\nJudge: judge-model\nWorker: {SONNET_179}\n", kept)
|
||||
self.assertIn(f"Stepped up\n\nWorker: {OPUS_179_AT_6}\n", kept)
|
||||
|
||||
def test_a_ruling_steps_the_route_only_on_an_escalation_from_the_rung_its_taken_in_l_picks(self):
|
||||
@@ -495,7 +567,7 @@ class Cycles(unittest.TestCase):
|
||||
for ruling in (Interrupt("e", "q", entries_read=3), QuotedAnswer("e", "q", "A.", entries_read=3)):
|
||||
with self.subTest(ruling=ruling):
|
||||
self.assertIsNone(run.ruling_step_up(cycle, ruling))
|
||||
self.assertEqual(run.ruling_step_up(cycle, Interrupt("e", "q", "round 2: 🔴", TakenIn(highest_likelihood=4), entries_read=3)), routing.StepUp(cycle.route, Route(Routing.XHIGH, 3, 3, 4, escalated_at=3)))
|
||||
self.assertEqual(run.ruling_step_up(cycle, Interrupt("e", "q", "round 2: 🔴", TakenIn(highest_likelihood=4), entries_read=3)), routing.StepUp(cycle.route, Route(Routing.TWO_UP, 3, 3, 4, escalated_at=3)))
|
||||
|
||||
def test_an_escalation_after_an_interrupt_stepped_the_worker_steps_it_again_in_the_same_cycle(self):
|
||||
streams = [Worker(self.paths.claude_code_transcripts.parent, text="round 2: 🔴"), Worker(self.paths.claude_code_transcripts.parent), Worker(self.paths.claude_code_transcripts.parent)]
|
||||
@@ -504,8 +576,8 @@ class Cycles(unittest.TestCase):
|
||||
cycle = dataclasses.replace(self.cycle(fake, records="From AGENTS.md:\nUse A."), project=Routing.OPUS, route=Route(Routing.SONNET, 179, 2, 5))
|
||||
with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):
|
||||
concluded = run.run_cycle(cycle)
|
||||
self.assertEqual(concluded.route, Route(Routing.HIGH, 179, 2, 5, escalated_at=4))
|
||||
self.assertEqual([args[args.index("--effort") + 1] for args in fake.made("stream_claude")], ["high", "medium", "high"])
|
||||
self.assertEqual(concluded.route, Route(Routing.ONE_UP, 179, 2, 5, escalated_at=4))
|
||||
self.assertEqual([args[args.index("--effort") + 1] for args in fake.made("stream_claude")], ["high", "medium", "low"])
|
||||
|
||||
def test_an_escalation_quoted_from_before_the_workers_last_step_up_steps_nothing_and_a_later_one_reaches_the_verdict(self):
|
||||
for escalation, verdict in (("round 2: 🔴", Unfinished("working", entries_read=4)), ("working", Unfinished("working", "working", entries_read=4))):
|
||||
@@ -546,7 +618,7 @@ class Cycles(unittest.TestCase):
|
||||
self.assertEqual([args[args.index("--effort") + 1] for args in (first, resumed)], ["high", "medium"])
|
||||
typed = resumed[resumed.index("-p") + 1]
|
||||
self.assertIn("Your request for a higher rung went through: loop-claude runs you on claude-opus-5-5 at medium effort.", typed)
|
||||
self.assertIn(" Launch each reviewer with the Agent tool set to model opus, effort high, the rung item 179's E + I of 5 picks.", typed)
|
||||
self.assertIn(" Launch each reviewer with the Agent tool set to model fable, effort low, the rung item 179's E + I of 5 picks.", typed)
|
||||
self.assertNotIn("went through", first[first.index("-p") + 1])
|
||||
|
||||
def test_a_typed_answer_past_the_quoted_answers_cap_reaches_the_worker_with_its_own_question(self):
|
||||
@@ -604,7 +676,7 @@ class Cycles(unittest.TestCase):
|
||||
stop = run.run_cycle(self.cycle(fake))
|
||||
self.assertEqual(stop, Stop(1, f"could not delete {folder}: Permission denied; delete every file and folder matching {folder}*, then rerun loop-claude; a rerun before that resumes the finished chunk's session"))
|
||||
self.assertTrue(session.session_open(self.session))
|
||||
self.assertEqual(self.archived_outcomes(), [f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: finished\n\nEvidence:\n> working\n\nJudge: judge-model\nWorker: {OFF_LADDER}\n\n2026-09-21T14:13:20Z Stopped: {stop.reason}\n\nWorker: {OFF_LADDER}\n"])
|
||||
self.assertEqual(self.archived_outcomes(), [f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: finished\n\nEvidence:\n> working\n\nConfig: {CONFIG}\nJudge: judge-model\nWorker: {OFF_LADDER}\n\n2026-09-21T14:13:20Z Stopped: {stop.reason}\n\nWorker: {OFF_LADDER}\n"])
|
||||
|
||||
def test_stops_when_the_worker_leaves_no_transcript(self):
|
||||
fake = FakeEffects(streams=[Streamed(0)])
|
||||
@@ -727,6 +799,24 @@ class Interrupts(unittest.TestCase):
|
||||
self.assertEqual(self.put(fake), (Stop(2, "the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun loop-claude on a terminal"), f"\n{STAMP} Which one?\n"))
|
||||
self.assertEqual(fake.calls, [])
|
||||
|
||||
def test_dms_the_question_naming_the_project_on_a_terminal_or_off_one(self):
|
||||
for on_terminal in (True, False):
|
||||
with self.subTest(on_terminal=on_terminal):
|
||||
fake = FakeEffects(inputs=["Use B."], on_terminal=on_terminal)
|
||||
self.put(fake)
|
||||
self.assertEqual(fake.dms, [f"loop-claude in {self.home} asks:\n\nWhich one?"])
|
||||
|
||||
def test_drops_the_keys_typed_before_the_question_ahead_of_the_dm_so_an_answer_typed_while_it_sends_counts(self):
|
||||
fake = FakeEffects(inputs=["Use B."])
|
||||
seen = []
|
||||
effects = dataclasses.replace(fake.effects(), dm=lambda text: seen.append(list(fake.calls)))
|
||||
self.assertEqual(self.put(fake, effects=effects)[0], "Use B.")
|
||||
self.assertEqual(seen, [[("discard_typed", None)]])
|
||||
|
||||
def test_says_why_a_dm_failed_and_still_takes_the_answer(self):
|
||||
fake = FakeEffects(inputs=["Use B."], dm_failures=[Failure("cannot reach https://chat.example: timed out")])
|
||||
self.assertEqual(self.put(fake), ("Use B.", f"\n{STAMP} Which one?\n{STAMP} could not DM you on Mattermost: cannot reach https://chat.example: timed out\n"))
|
||||
|
||||
def test_returns_the_line_typed_after_the_question_stripped_dropping_what_was_typed_before(self):
|
||||
fake = FakeEffects(inputs=[" Use B. "])
|
||||
self.assertEqual(self.put(fake), ("Use B.", f"\n{STAMP} Which one?\n"))
|
||||
@@ -772,7 +862,7 @@ class Interrupts(unittest.TestCase):
|
||||
self.assertEqual(answer, "Use B.")
|
||||
self.assertIn(f"loop-inbox cannot show this question: cannot make {self.paths.waiting}: File exists", said)
|
||||
stop, _ = self.put(FakeEffects(inputs=["/talk"], on_terminal_claude=[0]))
|
||||
self.assertEqual(stop, Stop(2, "the human is needed to answer the question above, but the interrupt ended with nothing typed"))
|
||||
self.assertEqual(stop, Stop(2, "the human is needed to answer the question above, but the interrupt ended without anything typed"))
|
||||
|
||||
def test_makes_way_only_warns_where_loop_inbox_cannot_list_the_open_claude(self):
|
||||
self.paths.waiting.parent.mkdir(parents=True)
|
||||
@@ -802,7 +892,7 @@ class Interrupts(unittest.TestCase):
|
||||
send(self.paths.waiting, self.ask(), ClaudeEnded())
|
||||
fake = FakeEffects(inputs=[self.opening])
|
||||
stop, _ = self.put(fake, effects=dataclasses.replace(fake.effects(), alive=alive, sleep=ended))
|
||||
self.assertEqual((stop, looked, slept), (Stop(2, "the human is needed to answer the question above, but the interrupt ended with nothing typed"), [INBOX], [POLL_SECONDS]))
|
||||
self.assertEqual((stop, looked, slept), (Stop(2, "the human is needed to answer the question above, but the interrupt ended without anything typed"), [INBOX], [POLL_SECONDS]))
|
||||
|
||||
def test_stops_when_loop_inbox_is_gone_with_nothing_typed(self):
|
||||
looked = []
|
||||
@@ -812,7 +902,7 @@ class Interrupts(unittest.TestCase):
|
||||
return pid == INBOX and len(looked) == 1
|
||||
fake = FakeEffects(inputs=[self.opening])
|
||||
stop, _ = self.put(fake, effects=dataclasses.replace(fake.effects(), alive=alive))
|
||||
self.assertEqual((stop, looked, fake.made("sleep")), (Stop(2, "the human is needed to answer the question above, but the interrupt ended with nothing typed"), [INBOX, INBOX], [POLL_SECONDS]))
|
||||
self.assertEqual((stop, looked, fake.made("sleep")), (Stop(2, "the human is needed to answer the question above, but the interrupt ended without anything typed"), [INBOX, INBOX], [POLL_SECONDS]))
|
||||
|
||||
def test_lists_the_claude_open_on_its_terminal_in_loop_inbox_while_it_runs(self):
|
||||
for typed, answer_here in (([" /talk "], True), ([], False)):
|
||||
@@ -829,7 +919,7 @@ class Interrupts(unittest.TestCase):
|
||||
fake = FakeEffects(inputs=["/talk"], on_terminal_claude=[0])
|
||||
stop, _ = self.put(fake)
|
||||
self.assertEqual(fake.made("claude_on_terminal")[0][:4], ["--model", "m", "--effort", "high"])
|
||||
self.assertEqual(stop, Stop(2, "the human is needed to answer the question above, but the interrupt ended with nothing typed"))
|
||||
self.assertEqual(stop, Stop(2, "the human is needed to answer the question above, but the interrupt ended without anything typed"))
|
||||
|
||||
def test_hands_the_claude_that_takes_the_terminal_the_workers_environment(self):
|
||||
fake = FakeEffects(inputs=["/talk"], on_terminal_claude=[0])
|
||||
@@ -904,7 +994,7 @@ class RoutingCheck(unittest.TestCase):
|
||||
self.assertIn(f"- {call}", (self.root / "routing-figures.md").read_text())
|
||||
((args),) = fake.made("claude_on_terminal")
|
||||
self.assertEqual(args[:6], ["--model", "m", "--effort", "high", "--permission-mode", "bypassPermissions"])
|
||||
self.assertIn(f"change nothing until they answer:\n- {call}", args[6])
|
||||
self.assertIn(f"don't change anything until they answer:\n- {call}", args[6])
|
||||
self.assertEqual(fake.terminal_environments, [{"CLAUDE_CODE_SANDBOXED": "1"}])
|
||||
self.assertEqual(fake.terminal_folders, [str(self.home / "code" / "claude-config")], "the development clone, since ~/.claude holds only a release")
|
||||
self.assertIn("Record what they decide in this checkout, the development clone", args[6])
|
||||
@@ -961,9 +1051,11 @@ class RoutingCheck(unittest.TestCase):
|
||||
with contextlib.redirect_stderr(io.StringIO()) as said, unittest.mock.patch.object(state, "mark_raised", return_value=Failure("full")):
|
||||
self.assertIsNone(routing_check.raise_calls(self.root, new, Rung("m", "high"), self.loop(fake)))
|
||||
((args),) = fake.made("claude_on_terminal")
|
||||
self.assertIn(f"change nothing until they answer:\n- {new[0].sentence()}\n- {new[1].sentence()}\nThe figures", args[6])
|
||||
self.assertIn(f"don't change anything until they answer:\n- {new[0].sentence()}\n- {new[1].sentence()}\nThe figures", args[6])
|
||||
self.assertIn(f"call for a routing change:\n- {new[0].sentence()}\n- {new[1].sentence()}\n", said.getvalue())
|
||||
self.assertIn("routing figures: full", said.getvalue())
|
||||
[sent] = fake.dms
|
||||
self.assertTrue(sent.startswith(f"loop-claude in {self.loop(fake).root} asks:\n\nloop-claude's routing figures call for a routing change:\n- {new[0].sentence()}\n"), sent)
|
||||
|
||||
|
||||
class ModelPrompt(unittest.TestCase):
|
||||
@@ -1011,9 +1103,9 @@ def interrupted(likelihood=0, escalated_at=None):
|
||||
|
||||
class Routing(unittest.TestCase):
|
||||
OPUS = Rung("claude-opus-5-5", "medium")
|
||||
HIGH = Rung("claude-opus-5-5", "high")
|
||||
XHIGH = Rung("claude-opus-5-5", "xhigh")
|
||||
MAX = Rung("claude-opus-5-5", "max")
|
||||
ONE_UP = Rung("claude-fable-5-2", "low")
|
||||
TWO_UP = Rung("claude-fable-5-2", "medium")
|
||||
THREE_UP = Rung("claude-opus-5-5", "xhigh")
|
||||
SONNET = Rung("claude-sonnet-5-5", "high")
|
||||
|
||||
def test_routes_on_the_next_releases_top_item_that_waits_on_no_question(self):
|
||||
@@ -1041,7 +1133,7 @@ class Routing(unittest.TestCase):
|
||||
self.assertEqual(routing.routed_item(todo.replace(first, "") + first, NO_CUT).id, 3)
|
||||
|
||||
def test_starts_a_chunk_on_the_rung_its_items_l_picks_below_the_projects_too(self):
|
||||
self.assertEqual(routing.first_route(self.OPUS, routing.routed_item(TODO, NO_CUT)), Route(self.HIGH, 3, 4, 5))
|
||||
self.assertEqual(routing.first_route(self.OPUS, routing.routed_item(TODO, NO_CUT)), Route(self.ONE_UP, 3, 4, 5))
|
||||
cheap = routing.routed_item(TODO.replace("| 4 | 2 | 3 |", "| 1 | 2 | 3 |"), NO_CUT)
|
||||
self.assertEqual(routing.first_route(self.OPUS, cheap), Route(Rung("claude-sonnet-5-5", "high"), 3, 1, 5))
|
||||
self.assertEqual(routing.first_route(self.OPUS, None), Route(self.OPUS))
|
||||
@@ -1049,13 +1141,13 @@ class Routing(unittest.TestCase):
|
||||
def test_steps_up_a_rung_after_every_second_unfinished_verdict(self):
|
||||
once = routing.next_route(self.OPUS, Route(self.OPUS, 3, 3, 4), unfinished())
|
||||
self.assertEqual(once, Route(self.OPUS, 3, 3, 4, unfinished=1))
|
||||
self.assertEqual(routing.next_route(self.OPUS, once, unfinished()), Route(self.HIGH, 3, 3, 4))
|
||||
self.assertEqual(routing.next_route(self.OPUS, once, unfinished()), Route(self.ONE_UP, 3, 3, 4))
|
||||
self.assertEqual(routing.next_route(self.OPUS, Route(LADDER[-1], unfinished=1), unfinished()).rung, LADDER[-1])
|
||||
|
||||
def test_steps_up_to_the_rung_a_taken_in_items_l_picks_and_never_down(self):
|
||||
self.assertEqual(routing.next_route(self.OPUS, Route(self.OPUS), unfinished(4)).rung, self.HIGH)
|
||||
self.assertEqual(routing.next_route(self.OPUS, Route(self.XHIGH), unfinished(4)).rung, self.XHIGH)
|
||||
self.assertEqual(routing.next_route(self.OPUS, Route(self.OPUS, unfinished=1), unfinished(4)).rung, self.XHIGH)
|
||||
self.assertEqual(routing.next_route(self.OPUS, Route(self.OPUS), unfinished(4)).rung, self.ONE_UP)
|
||||
self.assertEqual(routing.next_route(self.OPUS, Route(self.TWO_UP), unfinished(4)).rung, self.TWO_UP)
|
||||
self.assertEqual(routing.next_route(self.OPUS, Route(self.OPUS, unfinished=1), unfinished(4)).rung, self.TWO_UP)
|
||||
|
||||
def test_steps_up_from_a_rung_below_the_projects_one_rung_at_a_time(self):
|
||||
low = Route(self.SONNET, 3, 1, 3, unfinished=1)
|
||||
@@ -1064,30 +1156,30 @@ class Routing(unittest.TestCase):
|
||||
self.assertEqual(routing.next_route(self.OPUS, Route(low.rung, 3, 1, 3), unfinished(3)).rung, self.OPUS)
|
||||
|
||||
def test_steps_up_a_rung_on_an_escalation_the_judge_found_up_to_two_above_the_items_rung_marking_the_transcript_entries_it_read(self):
|
||||
self.assertEqual(routing.next_route(self.OPUS, Route(self.HIGH, 3, 4, 5), unfinished(escalated_at=7)), Route(self.XHIGH, 3, 4, 5, escalated_at=7))
|
||||
self.assertEqual(routing.next_route(self.OPUS, Route(self.XHIGH, 3, 4, 5, escalated_at=7), unfinished(escalated_at=9)), Route(self.MAX, 3, 4, 5, escalated_at=9))
|
||||
self.assertEqual(routing.next_route(self.OPUS, Route(self.MAX, 3, 4, 5, escalated_at=9), unfinished(escalated_at=12)), Route(self.MAX, 3, 4, 5, unfinished=1, escalated_at=9))
|
||||
self.assertEqual(routing.next_route(self.OPUS, Route(self.HIGH, 3, 4, 5, unfinished=1), unfinished(escalated_at=7)), Route(self.XHIGH, 3, 4, 5, escalated_at=7))
|
||||
self.assertEqual(routing.next_route(self.OPUS, Route(self.XHIGH), unfinished(escalated_at=7)), Route(self.XHIGH, unfinished=1))
|
||||
self.assertEqual(routing.next_route(self.OPUS, Route(self.SONNET, 3, 2, 4), unfinished(4, escalated_at=7)), Route(self.HIGH, 3, 2, 4, unfinished=1))
|
||||
self.assertEqual(routing.next_route(self.OPUS, Route(self.ONE_UP, 3, 4, 5), unfinished(escalated_at=7)), Route(self.TWO_UP, 3, 4, 5, escalated_at=7))
|
||||
self.assertEqual(routing.next_route(self.OPUS, Route(self.TWO_UP, 3, 4, 5, escalated_at=7), unfinished(escalated_at=9)), Route(self.THREE_UP, 3, 4, 5, escalated_at=9))
|
||||
self.assertEqual(routing.next_route(self.OPUS, Route(self.THREE_UP, 3, 4, 5, escalated_at=9), unfinished(escalated_at=12)), Route(self.THREE_UP, 3, 4, 5, unfinished=1, escalated_at=9))
|
||||
self.assertEqual(routing.next_route(self.OPUS, Route(self.ONE_UP, 3, 4, 5, unfinished=1), unfinished(escalated_at=7)), Route(self.TWO_UP, 3, 4, 5, escalated_at=7))
|
||||
self.assertEqual(routing.next_route(self.OPUS, Route(self.TWO_UP), unfinished(escalated_at=7)), Route(self.TWO_UP, unfinished=1))
|
||||
self.assertEqual(routing.next_route(self.OPUS, Route(self.SONNET, 3, 2, 4), unfinished(4, escalated_at=7)), Route(self.ONE_UP, 3, 2, 4, unfinished=1))
|
||||
|
||||
def test_keeps_the_mark_through_a_step_no_escalation_took(self):
|
||||
self.assertEqual(routing.next_route(self.OPUS, Route(self.OPUS, 3, 3, 4, unfinished=1, escalated_at=5), unfinished()), Route(self.HIGH, 3, 3, 4, escalated_at=5))
|
||||
self.assertEqual(routing.next_route(self.OPUS, Route(self.OPUS, 3, 3, 4, unfinished=1, escalated_at=5), unfinished()), Route(self.ONE_UP, 3, 3, 4, escalated_at=5))
|
||||
|
||||
def test_steps_up_a_rung_as_the_judge_interrupts_up_to_two_above_the_items_rung_without_counting_an_unfinished_verdict(self):
|
||||
self.assertEqual(routing.next_route(self.OPUS, Route(self.HIGH, 3, 4, 5, unfinished=1), interrupted(escalated_at=7)), Route(self.XHIGH, 3, 4, 5, escalated_at=7))
|
||||
self.assertEqual(routing.next_route(self.OPUS, Route(self.XHIGH, 3, 4, 5, escalated_at=7), interrupted(escalated_at=9)), Route(self.MAX, 3, 4, 5, escalated_at=9))
|
||||
self.assertEqual(routing.next_route(self.OPUS, Route(self.MAX, 3, 4, 5, unfinished=1, escalated_at=9), interrupted(escalated_at=12)), Route(self.MAX, 3, 4, 5, unfinished=1, escalated_at=9))
|
||||
self.assertEqual(routing.next_route(self.OPUS, Route(self.ONE_UP, 3, 4, 5, unfinished=1), interrupted(escalated_at=7)), Route(self.TWO_UP, 3, 4, 5, escalated_at=7))
|
||||
self.assertEqual(routing.next_route(self.OPUS, Route(self.TWO_UP, 3, 4, 5, escalated_at=7), interrupted(escalated_at=9)), Route(self.THREE_UP, 3, 4, 5, escalated_at=9))
|
||||
self.assertEqual(routing.next_route(self.OPUS, Route(self.THREE_UP, 3, 4, 5, unfinished=1, escalated_at=9), interrupted(escalated_at=12)), Route(self.THREE_UP, 3, 4, 5, unfinished=1, escalated_at=9))
|
||||
self.assertEqual(routing.next_route(self.OPUS, Route(self.SONNET, 3, 2, 4), interrupted(escalated_at=7)), Route(self.OPUS, 3, 2, 4, escalated_at=7))
|
||||
self.assertEqual(routing.next_route(self.OPUS, Route(self.HIGH, 3, 4, 5, unfinished=1, escalated_at=2), interrupted(4)), Route(self.HIGH, 3, 4, 5, unfinished=1, escalated_at=2))
|
||||
self.assertEqual(routing.next_route(self.OPUS, Route(self.ONE_UP, 3, 4, 5, unfinished=1, escalated_at=2), interrupted(4)), Route(self.ONE_UP, 3, 4, 5, unfinished=1, escalated_at=2))
|
||||
|
||||
def test_raises_the_worker_to_a_taken_in_items_rung_above_the_escalation_cap_without_a_step_as_the_judge_interrupts(self):
|
||||
self.assertEqual(routing.next_route(self.OPUS, Route(self.OPUS, 3, 1, 3, escalated_at=2), interrupted(4, escalated_at=7)), Route(self.HIGH, 3, 1, 3, escalated_at=2))
|
||||
self.assertEqual(routing.next_route(self.OPUS, Route(self.OPUS, 3, 1, 3, escalated_at=2), interrupted(4, escalated_at=7)), Route(self.ONE_UP, 3, 1, 3, escalated_at=2))
|
||||
|
||||
def test_steps_up_from_the_rung_a_taken_in_item_picks_as_the_judge_interrupts(self):
|
||||
self.assertEqual(routing.next_route(self.OPUS, Route(self.OPUS, 3, 3, 4), interrupted(4, escalated_at=7)), Route(self.XHIGH, 3, 3, 4, escalated_at=7))
|
||||
self.assertEqual(routing.next_route(self.OPUS, Route(self.XHIGH, 3, 4, 5), interrupted(4, escalated_at=7)), Route(self.MAX, 3, 4, 5, escalated_at=7))
|
||||
self.assertEqual(routing.next_route(self.OPUS, Route(self.MAX, 3, 4, 5, unfinished=1), interrupted(4, escalated_at=7)), Route(self.MAX, 3, 4, 5, unfinished=1))
|
||||
self.assertEqual(routing.next_route(self.OPUS, Route(self.OPUS, 3, 3, 4), interrupted(4, escalated_at=7)), Route(self.TWO_UP, 3, 3, 4, escalated_at=7))
|
||||
self.assertEqual(routing.next_route(self.OPUS, Route(self.TWO_UP, 3, 4, 5), interrupted(4, escalated_at=7)), Route(self.THREE_UP, 3, 4, 5, escalated_at=7))
|
||||
self.assertEqual(routing.next_route(self.OPUS, Route(self.THREE_UP, 3, 4, 5, unfinished=1), interrupted(4, escalated_at=7)), Route(self.THREE_UP, 3, 4, 5, unfinished=1))
|
||||
|
||||
def test_keeps_an_e_plus_i_taken_in_only_where_it_picks_a_higher_review_rung(self):
|
||||
taken = Route(self.OPUS, 3, 3, 4).taking_in(6)
|
||||
@@ -1105,66 +1197,59 @@ class Routing(unittest.TestCase):
|
||||
self.assertEqual(routing.next_route(self.OPUS, Route(Rung("claude-opus-5-5", "low")), unfinished()).rung, self.OPUS)
|
||||
self.assertEqual(routing.next_route(self.OPUS, Route(Rung("claude-opus-5-5", "low")), unfinished(2)).rung, self.OPUS)
|
||||
|
||||
def test_runs_the_judge_on_the_rung_its_chunks_items_e_plus_i_picks_never_below_the_projects(self):
|
||||
self.assertEqual(routing.judge_rung("claude-opus-5-5", Route(self.OPUS, 3, 3, 5)), self.HIGH)
|
||||
self.assertEqual(routing.judge_rung("claude-opus-5-5", Route(self.XHIGH, 3, 4, 5)), self.HIGH)
|
||||
self.assertEqual(routing.judge_rung("claude-opus-5-5", Route(self.SONNET, 3, 2, 7)), self.MAX)
|
||||
self.assertEqual(routing.judge_rung("claude-opus-5-5", Route(Rung("claude-haiku-5-5", "max"), 3, 1, 3)), self.OPUS)
|
||||
self.assertEqual(routing.judge_rung("claude-opus-5-5", Route(self.HIGH)), self.OPUS)
|
||||
self.assertEqual(routing.judge_rung("judge-model", Route(self.HIGH, 3, 4, 5)), Rung("judge-model"))
|
||||
self.assertEqual(routing.judge_rung("claude-sonnet-5-5", Route(self.HIGH, 3, 4, 5)), Rung("claude-sonnet-5-5"))
|
||||
|
||||
def test_runs_the_judge_on_the_rung_the_highest_e_plus_i_taken_in_picks(self):
|
||||
self.assertEqual(routing.judge_rung("claude-opus-5-5", Route(self.OPUS, 3, 3, 4, escape_and_impact_taken_in=6)), self.XHIGH)
|
||||
self.assertEqual(routing.judge_rung("claude-opus-5-5", Route(self.OPUS, escape_and_impact_taken_in=5)), self.HIGH)
|
||||
def test_runs_the_judge_of_a_replayed_model_on_its_models_highest_rung(self):
|
||||
self.assertEqual(routing.judge_rung("claude-opus-5-5"), self.THREE_UP)
|
||||
# A model off the ladder, or not replayed, gets no effort flag.
|
||||
self.assertEqual(routing.judge_rung("judge-model"), Rung("judge-model"))
|
||||
self.assertEqual(routing.judge_rung("claude-sonnet-5-5"), Rung("claude-sonnet-5-5"))
|
||||
|
||||
def test_refuses_a_route_whose_item_has_levels_off_their_scales_or_levels_without_an_item(self):
|
||||
for item, likelihood, escape_and_impact in ((3, 0, 5), (3, 5, 5), (3, 4, 1), (3, 4, 9), (0, 4, 5), (0, 4, 0), (0, 0, 5)):
|
||||
with self.subTest(item=item, likelihood=likelihood, escape_and_impact=escape_and_impact):
|
||||
with self.assertRaises(ValueError):
|
||||
Route(self.HIGH, item, likelihood, escape_and_impact)
|
||||
Route(self.ONE_UP, item, likelihood, escape_and_impact)
|
||||
|
||||
def test_refuses_a_route_taking_in_an_e_plus_i_off_its_scale_or_not_above_its_items(self):
|
||||
for taken_in in (1, 9, -1, 5, 4):
|
||||
with self.subTest(taken_in=taken_in):
|
||||
with self.assertRaises(ValueError):
|
||||
Route(self.HIGH, 3, 4, 5, escape_and_impact_taken_in=taken_in)
|
||||
Route(self.ONE_UP, 3, 4, 5, escape_and_impact_taken_in=taken_in)
|
||||
|
||||
def test_takes_a_route_whose_item_holds_each_levels_lowest_value(self):
|
||||
self.assertEqual(Route(self.HIGH, 3, 1, 2).escape_and_impact, 2)
|
||||
self.assertEqual(Route(self.ONE_UP, 3, 1, 2).escape_and_impact, 2)
|
||||
|
||||
def test_routes_nothing_on_an_item_without_e_or_i(self):
|
||||
without_i = TODO.replace("| E | I | R |", "| E | R |").replace("|---|---|---|---|---|---|---|---|---|---|---|", "|---|---|---|---|---|---|---|---|---|---|").replace("| 4 | 3 | 5 | 10 |", "| 4 | 3 | 10 |").replace("| 4 | 2 | 3 | 7 |", "| 4 | 2 | 7 |").replace("| 1 | 1 | 1 | 1 |", "| 1 | 1 | 1 |")
|
||||
self.assertIsNone(routing.routed_item(without_i, NO_CUT))
|
||||
|
||||
def test_archives_the_route_as_a_json_worker_line_it_reads_back_field_by_field(self):
|
||||
route = Route(self.HIGH, 3, 4, 5)
|
||||
self.assertEqual(route.worker_line(), '{"model": "claude-opus-5-5", "effort": "high", "item": 3, "likelihood": 4, "escape_and_impact": 5}')
|
||||
route = Route(self.ONE_UP, 3, 4, 5)
|
||||
self.assertEqual(route.worker_line(), '{"model": "claude-fable-5-2", "effort": "low", "item": 3, "likelihood": 4, "escape_and_impact": 5}')
|
||||
self.assertEqual(route_from(route.worker_line()), route)
|
||||
self.assertEqual(Route(Rung("worker-model")).worker_line(), '{"model": "worker-model"}')
|
||||
self.assertEqual(route_from('{"model": "worker-model"}'), Route(Rung("worker-model")))
|
||||
marked = Route(self.HIGH, 3, 4, 5, escape_and_impact_taken_in=7, escalated_at=12)
|
||||
self.assertEqual(marked.worker_line(), '{"model": "claude-opus-5-5", "effort": "high", "item": 3, "likelihood": 4, "escape_and_impact": 5, "escape_and_impact_taken_in": 7, "escalated_at": 12}')
|
||||
marked = Route(self.ONE_UP, 3, 4, 5, escape_and_impact_taken_in=7, escalated_at=12)
|
||||
self.assertEqual(marked.worker_line(), '{"model": "claude-fable-5-2", "effort": "low", "item": 3, "likelihood": 4, "escape_and_impact": 5, "escape_and_impact_taken_in": 7, "escalated_at": 12}')
|
||||
self.assertEqual(route_from(marked.worker_line()), marked)
|
||||
self.assertEqual(route_from(Route(self.HIGH, escalated_at=3).worker_line()), Route(self.HIGH, escalated_at=3))
|
||||
self.assertEqual(route_from(Route(self.ONE_UP, escalated_at=3).worker_line()), Route(self.ONE_UP, escalated_at=3))
|
||||
|
||||
def test_leaves_the_count_of_unfinished_verdicts_out_of_the_worker_line_so_a_rerun_restarts_it(self):
|
||||
self.assertEqual(route_from(Route(self.HIGH, 3, 4, 5, unfinished=1).worker_line()), Route(self.HIGH, 3, 4, 5))
|
||||
self.assertEqual(route_from(Route(self.ONE_UP, 3, 4, 5, unfinished=1).worker_line()), Route(self.ONE_UP, 3, 4, 5))
|
||||
|
||||
def test_reads_no_route_from_a_worker_line_that_route_worker_line_could_not_have_written(self):
|
||||
for line in ('{"effort": "high"}', '{"model": "claude-opus-5-5", "effort": "high", "unfinished": 1}', '{"model": "claude-opus-5-5", "item": "3"}', '{"model": "claude-opus-5-5", "effort": 3}', '{"model": 5}', '{"model": "claude-opus-5-5", "effort": "high", "escalated_at": -3}', '{"model": "claude-opus-5-5", "item": true, "likelihood": 4, "escape_and_impact": 5}', '{"model": "claude-opus-5-5", "effort": "high", "item": 3, "likelihood": 5, "escape_and_impact": 5}', '{"model": "claude-opus-5-5", "effort": "high", "escape_and_impact_taken_in": 9}', '["claude-opus-5-5"]', '{"model": ', "worker-model", "claude-opus-5-5 at high effort, routed by item 3's L of 4 and E + I of 5"):
|
||||
for line in ('{"effort": "high"}', '{"model": "claude-opus-5-5", "effort": "high", "unfinished": 1}', '{"model": "claude-opus-5-5", "item": "3"}', '{"model": "claude-opus-5-5", "effort": 3}', '{"model": 5}', '{"model": "claude-opus-5-5", "effort": "high", "escalated_at": -3}', '{"model": "claude-opus-5-5", "item": true, "likelihood": 4, "escape_and_impact": 5}', '{"model": "claude-opus-5-5", "effort": "high", "item": 3, "likelihood": 5, "escape_and_impact": 5}', '{"model": "claude-opus-5-5", "effort": "high", "escape_and_impact_taken_in": 9}', '["claude-opus-5-5"]', '{"model": ', "worker-model", "claude-fable-5-2 at low effort, routed by item 3's L of 4 and E + I of 5"):
|
||||
with self.subTest(line=line):
|
||||
self.assertIsNone(route_from(line))
|
||||
|
||||
def test_keeps_a_chunks_route_or_its_archived_one_at_or_above_the_rung_its_item_picks_and_else_routes_afresh(self):
|
||||
item = routing.routed_item(TODO, NO_CUT)
|
||||
archived = Route(self.XHIGH, 3, 4, 5)
|
||||
archived = Route(self.TWO_UP, 3, 4, 5)
|
||||
def never():
|
||||
raise AssertionError("not asked")
|
||||
self.assertEqual(chunk_start.routed(archived, None, "worker-model", never, never), Route(Rung("worker-model")))
|
||||
self.assertEqual(chunk_start.routed(archived, self.OPUS, "claude-opus-5-5", never, never), archived)
|
||||
self.assertEqual(chunk_start.routed(None, self.OPUS, "claude-opus-5-5", lambda: archived, never), archived)
|
||||
self.assertEqual(chunk_start.routed(None, self.OPUS, "claude-opus-5-5", lambda: None, lambda: item), Route(self.HIGH, 3, 4, 5))
|
||||
self.assertEqual(chunk_start.routed(None, self.OPUS, "claude-opus-5-5", lambda: None, lambda: item), Route(self.ONE_UP, 3, 4, 5))
|
||||
self.assertEqual(chunk_start.routed(Route(self.SONNET), self.OPUS, "claude-opus-5-5", never, lambda: None), Route(self.OPUS))
|
||||
cheap = Route(self.SONNET, 4, 2, 3)
|
||||
self.assertEqual(chunk_start.routed(cheap, self.OPUS, "claude-opus-5-5", never, never), cheap)
|
||||
@@ -1196,7 +1281,7 @@ class RouteSources(unittest.TestCase):
|
||||
opened = session.session_named("A proj loop-claude", pathlib.Path(home, "projects"))
|
||||
archive = pathlib.Path(home, "archive")
|
||||
transcript = pathlib.Path(home, "projects", "-fake", f"{opened.id}.jsonl")
|
||||
route = Route(Rung("claude-opus-5-5", "high"), 3, 4, 5)
|
||||
route = Route(Rung("claude-fable-5-2", "low"), 3, 4, 5)
|
||||
with contextlib.redirect_stderr(io.StringIO()) as stderr:
|
||||
self.assertIsNone(chunk_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened)))
|
||||
transcript.parent.mkdir(parents=True)
|
||||
@@ -1229,7 +1314,7 @@ class Steps(unittest.TestCase):
|
||||
run_with = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="old", route=Route(self.OPUS))
|
||||
self.assertEqual(close.after_verdict(run_with, self.OPUS, run.Concluded(Finished("x"), run_with.route)), dataclasses.replace(run_with, route=None, unfinished_evidence=""))
|
||||
self.assertEqual(close.after_verdict(dataclasses.replace(run_with, unfinished_run=3), self.OPUS, run.Concluded(Finished("x"), run_with.route)).unfinished_run, 0)
|
||||
self.assertEqual(close.after_verdict(run_with, self.OPUS, run.Concluded(Unfinished("new", taken_in=TakenIn(highest_likelihood=4)), run_with.route)), dataclasses.replace(run_with, route=Route(Rung("claude-opus-5-5", "high"), unfinished=1), unfinished_evidence="new", unfinished_run=1))
|
||||
self.assertEqual(close.after_verdict(run_with, self.OPUS, run.Concluded(Unfinished("new", taken_in=TakenIn(highest_likelihood=4)), run_with.route)), dataclasses.replace(run_with, route=Route(Rung("claude-fable-5-2", "low"), unfinished=1), unfinished_evidence="new", unfinished_run=1))
|
||||
|
||||
def test_an_unfinished_chunk_keeps_the_items_its_verdict_found_taken_in_and_a_finished_one_drops_them(self):
|
||||
run_with = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="", route=Route(self.OPUS), items_taken_in=(3,))
|
||||
@@ -1238,7 +1323,7 @@ class Steps(unittest.TestCase):
|
||||
|
||||
def test_steps_from_the_route_its_cycle_ended_on_which_a_ruling_may_have_raised(self):
|
||||
run_with = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="", route=Route(self.OPUS, 3, 3, 4))
|
||||
raised = Route(Rung("claude-opus-5-5", "high"), 3, 3, 4, escalated_at=5)
|
||||
raised = Route(Rung("claude-fable-5-2", "low"), 3, 3, 4, escalated_at=5)
|
||||
self.assertEqual(close.after_verdict(run_with, self.OPUS, run.Concluded(Unfinished("new"), raised)).route, dataclasses.replace(raised, unfinished=1))
|
||||
|
||||
def test_keeps_the_route_its_cycle_ended_on_off_the_ladder(self):
|
||||
@@ -1248,7 +1333,7 @@ class Steps(unittest.TestCase):
|
||||
|
||||
def test_an_unfinished_verdicts_escalation_marks_the_transcript_entries_the_judge_read(self):
|
||||
run_with = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="", route=Route(self.OPUS, 3, 3, 4, escalated_at=2))
|
||||
self.assertEqual(close.after_verdict(run_with, self.OPUS, run.Concluded(Unfinished("new", "round 2: 🔴", entries_read=9), run_with.route)).route, Route(Rung("claude-opus-5-5", "high"), 3, 3, 4, escalated_at=9))
|
||||
self.assertEqual(close.after_verdict(run_with, self.OPUS, run.Concluded(Unfinished("new", "round 2: 🔴", entries_read=9), run_with.route)).route, Route(Rung("claude-fable-5-2", "low"), 3, 3, 4, escalated_at=9))
|
||||
self.assertEqual(close.after_verdict(run_with, self.OPUS, run.Concluded(Unfinished("new", entries_read=9), run_with.route)).route, Route(self.OPUS, 3, 3, 4, unfinished=1, escalated_at=2))
|
||||
|
||||
def test_archives_a_step_up_as_it_happens_so_a_rerun_resumes_on_it(self):
|
||||
@@ -1262,10 +1347,10 @@ class Steps(unittest.TestCase):
|
||||
with contextlib.redirect_stderr(io.StringIO()):
|
||||
self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.unfinished(before.worker_line(), "working", "j", ""), NOW))
|
||||
after = close.closed_cycle(main.LoopRun(cycle_number=1, root="/r", task="Do it.", unfinished_evidence=""), self.OPUS, run.Concluded(Unfinished("working", taken_in=TakenIn(highest_likelihood=4)), before), archive, a_loop(FakeEffects().effects(), session=opened))
|
||||
self.assertEqual(chunk_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened)), Route(Rung("claude-opus-5-5", "high"), 3, 3, 4))
|
||||
self.assertEqual(chunk_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened)), Route(Rung("claude-fable-5-2", "low"), 3, 3, 4))
|
||||
with contextlib.redirect_stderr(io.StringIO()):
|
||||
close.closed_cycle(after, self.OPUS, run.Concluded(Finished("done"), after.route), archive, a_loop(FakeEffects().effects(), session=opened))
|
||||
self.assertEqual(chunk_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened)), Route(Rung("claude-opus-5-5", "high"), 3, 3, 4))
|
||||
self.assertEqual(chunk_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened)), Route(Rung("claude-fable-5-2", "low"), 3, 3, 4))
|
||||
blocked = pathlib.Path(home, "blocked")
|
||||
blocked.write_text("")
|
||||
stop = close.closed_cycle(main.LoopRun(cycle_number=1, root="/r", task="Do it.", unfinished_evidence=""), self.OPUS, run.Concluded(Unfinished("working", taken_in=TakenIn(highest_likelihood=4)), before), blocked, a_loop(FakeEffects().effects(), session=opened))
|
||||
@@ -1382,80 +1467,80 @@ class WorkerArgs(unittest.TestCase):
|
||||
def test_keeps_every_review_on_the_projects_rung_while_the_worker_runs_below_it(self):
|
||||
opus = Rung("claude-opus-5-5", "medium")
|
||||
below = prompts.fresh("Do it.", "## Goals", Route(Rung("claude-sonnet-5-5", "high"), 3, 2, 4), opus, self.FACTS)
|
||||
self.assertIn(f"item 3's L of 2. Launch each reviewer, each comprehension seat and the security pass's subagent with the Agent tool set to model opus, effort medium, the project's rung.{self.SCAN} Your rung is below the project's: launch each subagent that files or scores todo.md items on the rung `~/.claude/bin/subagent-rung --plan claude-opus-5-5 <L>` prints. Where an item you take into the chunk has an E + I of 5 or more, launch each reviewer with the Agent tool set to `model opus, effort high` from 5, `model opus, effort xhigh` from 6, `model opus, effort max` from 7 and `model fable, effort max` from 8. When an escalation trigger", below)
|
||||
self.assertIn(f"item 3's L of 2. Launch each reviewer, each comprehension seat and the security pass's subagent with the Agent tool set to model opus, effort medium, the project's rung.{self.SCAN} Your rung is below the project's: launch each subagent that files or scores todo.md items on the rung `~/.claude/bin/subagent-rung --plan claude-opus-5-5 <L>` prints. Where an item you take into the chunk has an E + I of 5 or more, launch each reviewer with the Agent tool set to `model fable, effort low` from 5, `model fable, effort medium` from 6, `model opus, effort xhigh` from 7 and `model fable, effort high` from 8. When an escalation trigger", below)
|
||||
self.assertNotIn("Launch each", prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 4), opus, self.FACTS))
|
||||
|
||||
def test_launches_reviewers_on_the_rung_the_items_e_plus_i_picks_above_the_workers(self):
|
||||
opus = Rung("claude-opus-5-5", "medium")
|
||||
level = prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 6), opus, self.FACTS)
|
||||
self.assertIn(f"item 3's L of 3. Launch each reviewer with the Agent tool set to model opus, effort xhigh, the rung item 3's E + I of 6 picks. Where an item you take into the chunk has an E + I of 7 or more, launch each reviewer with the Agent tool set to `model opus, effort max` from 7 and `model fable, effort max` from 8.{self.MARKDOWN} When an escalation trigger", level)
|
||||
self.assertIn(f"item 3's L of 3. Launch each reviewer with the Agent tool set to model fable, effort medium, the rung item 3's E + I of 6 picks. Where an item you take into the chunk has an E + I of 7 or more, launch each reviewer with the Agent tool set to `model opus, effort xhigh` from 7 and `model fable, effort high` from 8.{self.MARKDOWN} When an escalation trigger", level)
|
||||
below = prompts.fresh("Do it.", "## Goals", Route(Rung("claude-sonnet-5-5", "high"), 3, 2, 5), opus, self.FACTS)
|
||||
self.assertIn(f"item 3's L of 2. Launch each reviewer with the Agent tool set to model opus, effort high, the rung item 3's E + I of 5 picks.{self.SEATS}{self.SCAN} Your rung is below the project's:", below)
|
||||
self.assertNotIn("Launch each reviewer", prompts.resumed("", Route(Rung("claude-opus-5-5", "xhigh"), 3, 4, 6), opus))
|
||||
self.assertIn(f"item 3's L of 2. Launch each reviewer with the Agent tool set to model fable, effort low, the rung item 3's E + I of 5 picks.{self.SEATS}{self.SCAN} Your rung is below the project's:", below)
|
||||
self.assertNotIn("Launch each reviewer", prompts.resumed("", Route(Rung("claude-fable-5-2", "medium"), 3, 4, 6), opus))
|
||||
|
||||
def test_names_the_reviewers_rung_each_higher_e_plus_i_an_item_taken_in_picks(self):
|
||||
opus = Rung("claude-opus-5-5", "medium")
|
||||
taking_in = " Where an item you take into the chunk has an E + I of 5 or more, launch each reviewer with the Agent tool set to `model opus, effort high` from 5, `model opus, effort xhigh` from 6, `model opus, effort max` from 7 and `model fable, effort max` from 8."
|
||||
taking_in = " Where an item you take into the chunk has an E + I of 5 or more, launch each reviewer with the Agent tool set to `model fable, effort low` from 5, `model fable, effort medium` from 6, `model opus, effort xhigh` from 7 and `model fable, effort high` from 8."
|
||||
self.assertIn(f"item 3's L of 3.{taking_in} When an escalation trigger", prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 4), opus, self.FACTS))
|
||||
self.assertIn(" Where an item you take into the chunk has an E + I of 7 or more, launch each reviewer with the Agent tool set to `model opus, effort max` from 7 and `model fable, effort max` from 8.", prompts.resumed("", Route(opus, 3, 3, 6), opus))
|
||||
self.assertIn(" Where an item you take into the chunk has an E + I of 7 or more, launch each reviewer with the Agent tool set to `model opus, effort max` from 7 and `model fable, effort max` from 8.", prompts.resumed("", Route(Rung("claude-opus-5-5", "xhigh"), 3, 4, 4), opus))
|
||||
self.assertIn(" Where an item you take into the chunk has an E + I of 7 or more, launch each reviewer with the Agent tool set to `model opus, effort xhigh` from 7 and `model fable, effort high` from 8.", prompts.resumed("", Route(opus, 3, 3, 6), opus))
|
||||
self.assertIn(" Where an item you take into the chunk has an E + I of 7 or more, launch each reviewer with the Agent tool set to `model opus, effort xhigh` from 7 and `model fable, effort high` from 8.", prompts.resumed("", Route(Rung("claude-fable-5-2", "medium"), 3, 4, 4), opus))
|
||||
self.assertNotIn("Where an item you take into", prompts.resumed("", Route(opus, 3, 3, 8), opus))
|
||||
self.assertNotIn("Where an item you take into", prompts.resumed("", Route(Rung("m")), None))
|
||||
|
||||
def test_launches_reviewers_on_the_rung_the_highest_e_plus_i_taken_in_picks(self):
|
||||
opus = Rung("claude-opus-5-5", "medium")
|
||||
self.assertIn(f"loop-claude runs you on claude-opus-5-5 at medium effort. Launch each reviewer with the Agent tool set to model opus, effort max, the rung picked by an item of E + I 7 taken into the chunk. Where an item you take into the chunk has an E + I of 8 or more, launch each reviewer with the Agent tool set to `model fable, effort max` from 8.{self.MARKDOWN} When an escalation trigger", prompts.resumed("", Route(opus, 3, 3, 5, escape_and_impact_taken_in=7), opus))
|
||||
self.assertIn(" Launch each reviewer with the Agent tool set to model opus, effort high, the rung picked by an item of E + I 5 taken into the chunk.", prompts.resumed("", Route(opus, escape_and_impact_taken_in=5), opus))
|
||||
self.assertIn(f"loop-claude runs you on claude-opus-5-5 at medium effort. Launch each reviewer with the Agent tool set to model opus, effort xhigh, the rung picked by an item of E + I 7 taken into the chunk. Where an item you take into the chunk has an E + I of 8 or more, launch each reviewer with the Agent tool set to `model fable, effort high` from 8.{self.MARKDOWN} When an escalation trigger", prompts.resumed("", Route(opus, 3, 3, 5, escape_and_impact_taken_in=7), opus))
|
||||
self.assertIn(" Launch each reviewer with the Agent tool set to model fable, effort low, the rung picked by an item of E + I 5 taken into the chunk.", prompts.resumed("", Route(opus, escape_and_impact_taken_in=5), opus))
|
||||
|
||||
def test_keeps_seats_and_the_security_pass_on_the_projects_rung_while_the_worker_runs_above_it(self):
|
||||
opus = Rung("claude-opus-5-5", "medium")
|
||||
above = prompts.fresh("Do it.", "## Goals", Route(Rung("claude-opus-5-5", "high"), 3, 4, 4), opus, self.FACTS)
|
||||
stepped_up = prompts.resumed("", Route(Rung("claude-opus-5-5", "high"), 3, 3, 4), opus)
|
||||
self.assertIn(f"{prompts.ANSWERS_RECORDED}. {prompts.NAME_THE_ITEMS} loop-claude runs you on claude-opus-5-5 at high effort.{self.SEATS}{self.SCAN} Where an item you take into the chunk has an E + I of 6 or more, launch each reviewer with the Agent tool set to `model opus, effort xhigh` from 6, `model opus, effort max` from 7 and `model fable, effort max` from 8.{self.MARKDOWN} When an escalation trigger", stepped_up)
|
||||
above = prompts.fresh("Do it.", "## Goals", Route(Rung("claude-fable-5-2", "low"), 3, 4, 4), opus, self.FACTS)
|
||||
stepped_up = prompts.resumed("", Route(Rung("claude-fable-5-2", "low"), 3, 3, 4), opus)
|
||||
self.assertIn(f"{prompts.ANSWERS_RECORDED}. {prompts.NAME_THE_ITEMS} loop-claude runs you on claude-fable-5-2 at low effort.{self.SEATS}{self.SCAN} Where an item you take into the chunk has an E + I of 6 or more, launch each reviewer with the Agent tool set to `model fable, effort medium` from 6, `model opus, effort xhigh` from 7 and `model fable, effort high` from 8.{self.MARKDOWN} When an escalation trigger", stepped_up)
|
||||
self.assertNotIn("the project's", prompts.resumed("", Route(opus, 3, 3, 4), opus))
|
||||
self.assertNotIn("runs you on", prompts.resumed("", Route(Rung("m")), None))
|
||||
self.assertIn(f"item 3's L of 4.{self.SEATS}{self.SCAN} Where an item you take into the chunk has an E + I of 6 or more, launch each reviewer with the Agent tool set to `model opus, effort xhigh` from 6, `model opus, effort max` from 7 and `model fable, effort max` from 8.{self.MARKDOWN} When an escalation trigger", above)
|
||||
self.assertIn(f"item 3's L of 4.{self.SEATS}{self.SCAN} Where an item you take into the chunk has an E + I of 6 or more, launch each reviewer with the Agent tool set to `model fable, effort medium` from 6, `model opus, effort xhigh` from 7 and `model fable, effort high` from 8.{self.MARKDOWN} When an escalation trigger", above)
|
||||
|
||||
def test_names_the_rungs_an_escalation_trigger_lets_the_worker_hand_a_task_to_at_most_two_above_its_items(self):
|
||||
opus = Rung("claude-opus-5-5", "medium")
|
||||
fresh = prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 4), opus, self.FACTS)
|
||||
self.assertIn("item 3's L of 3. Where an item you take into the chunk has an E + I of 5 or more, launch each reviewer with the Agent tool set to `model opus, effort high` from 5, `model opus, effort xhigh` from 6, `model opus, effort max` from 7 and `model fable, effort max` from 8. When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `model 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, 3, 4), opus))
|
||||
self.assertIn(" An escalation trigger in `~/.claude/CLAUDE.md` lets you hand the hard part of a task to a subagent with the Agent tool set to `model opus, effort 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, 3, 4), opus))
|
||||
self.assertNotIn("escalation", prompts.resumed("", Route(Rung("claude-fable-5-1", "max"), 3, 4, 8), opus))
|
||||
self.assertIn("only once the human agrees", prompts.resumed("", Route(Rung("claude-opus-5-5", "max"), 3, 4, 5), opus))
|
||||
self.assertIn("hand the hard part of the task to a subagent with the Agent tool set to `model opus, effort max`, one rung above yours;", prompts.resumed("", Route(Rung("claude-opus-5-5", "xhigh"), 3, 4, 5), opus))
|
||||
self.assertIn("item 3's L of 3. Where an item you take into the chunk has an E + I of 5 or more, launch each reviewer with the Agent tool set to `model fable, effort low` from 5, `model fable, effort medium` from 6, `model opus, effort xhigh` from 7 and `model fable, effort high` from 8. When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `model fable, effort low`, one rung above yours, and on each further trigger one rung higher, up to `model fable, effort medium`; above that, ask the human first. Open the subagent's prompt with `Escalation trigger <n>:`, n the trigger's number.", fresh)
|
||||
self.assertIn(" When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `model fable, effort medium`, one rung above yours; above that, ask the human first. Open the subagent's prompt with `Escalation trigger <n>:`, n the trigger's number.", prompts.resumed("", Route(Rung("claude-fable-5-2", "low"), 3, 3, 4), opus))
|
||||
self.assertIn(" An escalation trigger in `~/.claude/CLAUDE.md` lets you hand the hard part of a task to a subagent with the Agent tool set to `model opus, effort xhigh`, one rung above yours, only once the human agrees; loop-claude will not resume you higher for a trigger either, so ask the human for that yes. Open the subagent's prompt with `Escalation trigger <n>:`, n the trigger's number.", prompts.resumed("", Route(Rung("claude-fable-5-2", "medium"), 3, 3, 4), opus))
|
||||
self.assertNotIn("escalation", prompts.resumed("", Route(Rung("claude-fable-5-2", "max"), 3, 4, 8), opus))
|
||||
self.assertIn("only once the human agrees", prompts.resumed("", Route(Rung("claude-opus-5-5", "xhigh"), 3, 4, 5), opus))
|
||||
self.assertIn("hand the hard part of the task to a subagent with the Agent tool set to `model opus, effort xhigh`, one rung above yours;", prompts.resumed("", Route(Rung("claude-fable-5-2", "medium"), 3, 4, 5), opus))
|
||||
self.assertNotIn("escalation", prompts.resumed("", Route(Rung("m")), None))
|
||||
self.assertNotIn("escalation", prompts.resumed("", Route(Rung("claude-opus-5-5", "low"), 3, 3, 4), opus))
|
||||
self.assertIn(f"{prompts.READING_RULE} {prompts.NAME_THE_ITEMS}\n\nWhere an item you take into the chunk has an E + I of 5 or more, launch each reviewer with the Agent tool set to `model opus, effort high` from 5, `model opus, effort xhigh` from 6, `model opus, effort max` from 7 and `model fable, effort max` from 8. When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `model opus, effort high`, one rung above yours, and on each further trigger one rung higher, up to `model opus, effort xhigh`; above that, ask the human first. Open the subagent's prompt with `Escalation trigger <n>:`, n the trigger's number. Where the hard part is the rest of the chunk, end your run instead, asking loop-claude for a higher rung and naming a trigger that fired since your last step-up, if any: once the judge finds it in your transcript, the next cycle resumes you one rung up, up to `model opus, effort xhigh`. A reviewer", prompts.fresh("Do it.", "## Goals", Route(opus), opus, self.FACTS))
|
||||
self.assertIn(f"{prompts.READING_RULE} {prompts.NAME_THE_ITEMS}\n\nWhere an item you take into the chunk has an E + I of 5 or more, launch each reviewer with the Agent tool set to `model fable, effort low` from 5, `model fable, effort medium` from 6, `model opus, effort xhigh` from 7 and `model fable, effort high` from 8. When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `model fable, effort low`, one rung above yours, and on each further trigger one rung higher, up to `model fable, effort medium`; above that, ask the human first. Open the subagent's prompt with `Escalation trigger <n>:`, n the trigger's number. Where the hard part is the rest of the chunk, end your run instead, asking loop-claude for a higher rung and naming a trigger that fired since your last step-up, if any: once the judge finds it in your transcript, the next cycle resumes you one rung up, up to `model fable, effort medium`. A reviewer", prompts.fresh("Do it.", "## Goals", Route(opus), opus, self.FACTS))
|
||||
|
||||
def test_offers_the_worker_a_higher_rung_for_the_rest_of_the_chunk_up_to_the_escalation_cap(self):
|
||||
opus = Rung("claude-opus-5-5", "medium")
|
||||
offer = " Where the hard part is the rest of the chunk, end your run instead, asking loop-claude for a higher rung and naming a trigger that fired since your last step-up, if any: once the judge finds it in your transcript, the next cycle resumes you one rung up, up to `model opus, effort xhigh`."
|
||||
offer = " Where the hard part is the rest of the chunk, end your run instead, asking loop-claude for a higher rung and naming a trigger that fired since your last step-up, if any: once the judge finds it in your transcript, the next cycle resumes you one rung up, up to `model fable, effort medium`."
|
||||
self.assertIn(f"`Escalation trigger <n>:`, n the trigger's number.{offer}", prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 4), opus, self.FACTS))
|
||||
self.assertIn(f"`Escalation trigger <n>:`, n the trigger's number.{offer}", prompts.resumed("", Route(Rung("claude-opus-5-5", "high"), 3, 3, 4), opus))
|
||||
self.assertNotIn("Where the hard part", prompts.resumed("", Route(Rung("claude-opus-5-5", "xhigh"), 3, 3, 4), opus))
|
||||
self.assertIn(f"`Escalation trigger <n>:`, n the trigger's number.{offer}", prompts.resumed("", Route(Rung("claude-fable-5-2", "low"), 3, 3, 4), opus))
|
||||
self.assertNotIn("Where the hard part", prompts.resumed("", Route(Rung("claude-fable-5-2", "medium"), 3, 3, 4), opus))
|
||||
|
||||
def test_lets_a_markdown_only_branch_review_on_the_projects_rung_where_the_reviewers_run_above_it(self):
|
||||
opus = Rung("claude-opus-5-5", "medium")
|
||||
markdown = " Where your branch changes only Markdown, none of it `CLAUDE.md`, `AGENTS.md`, `workflow-bench/*-prompt.md` or under `agents/`, `principles/`, `rules/` or `skills/`, launch each reviewer on the project's rung instead, with the Agent tool set to model opus, effort medium."
|
||||
self.assertIn(markdown, prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 7), opus, self.FACTS))
|
||||
self.assertIn(markdown, prompts.resumed("", Route(Rung("claude-opus-5-5", "high"), 3, 4, 4), opus))
|
||||
self.assertIn(markdown, prompts.resumed("", Route(Rung("claude-fable-5-2", "low"), 3, 4, 4), opus))
|
||||
self.assertNotIn("only Markdown", prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 4), opus, self.FACTS))
|
||||
|
||||
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`."
|
||||
both = " A reviewer or comprehension seat that asks for a rerun one rung up reruns with the Agent tool set to `model fable, effort low`."
|
||||
self.assertTrue(prompts.resumed("", Route(opus, 3, 3, 4), opus).endswith(both))
|
||||
self.assertTrue(prompts.resumed("", Route(Rung("claude-sonnet-5-5", "high"), 3, 2, 4), opus).endswith(both))
|
||||
self.assertTrue(prompts.fresh("Do it.", "## Goals", Route(opus), opus, self.FACTS).split(f"\n\n{self.FACTS}")[0].endswith(both))
|
||||
self.assertTrue(prompts.resumed("", Route(Rung("claude-opus-5-5", "high"), 3, 4, 4), 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(opus, 3, 3, 7), opus).endswith(" A reviewer that asks for a rerun one rung up reruns with the Agent tool set to `model fable, effort max`, and a comprehension seat with `model opus, effort high`."))
|
||||
self.assertTrue(prompts.resumed("", Route(Rung("claude-fable-5-1", "max"), 3, 4, 8), opus).endswith(" A comprehension seat that asks for a rerun one rung up reruns with the Agent tool set to `model opus, effort high`."))
|
||||
self.assertTrue(prompts.resumed("", Route(Rung("claude-fable-5-2", "low"), 3, 4, 4), opus).endswith(" A reviewer that asks for a rerun one rung up reruns with the Agent tool set to `model fable, effort medium`, and a comprehension seat with `model fable, effort low`."))
|
||||
self.assertTrue(prompts.resumed("", Route(opus, 3, 3, 7), opus).endswith(" A reviewer that asks for a rerun one rung up reruns with the Agent tool set to `model fable, effort high`, and a comprehension seat with `model fable, effort low`."))
|
||||
self.assertTrue(prompts.resumed("", Route(Rung("claude-fable-5-2", "max"), 3, 4, 8), opus).endswith(" A comprehension seat that asks for a rerun one rung up reruns with the Agent tool set to `model fable, effort low`."))
|
||||
self.assertNotIn("rerun", prompts.resumed("", Route(Rung("m")), None))
|
||||
self.assertNotIn("rerun", prompts.fresh("Do it.", "## Goals", Route(Rung("m", "high"), 3, 4, 5), None, self.FACTS))
|
||||
self.assertIn(f"{both} After your first read", prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 4), opus, self.FACTS))
|
||||
fable = Rung("claude-fable-5-1", "max")
|
||||
fable = Rung("claude-fable-5-2", "max")
|
||||
self.assertNotIn("rerun", prompts.resumed("", Route(fable), fable))
|
||||
|
||||
def test_opens_a_fresh_session_by_name_and_resumes_an_open_one(self):
|
||||
@@ -1556,6 +1641,98 @@ class JudgePrompt(unittest.TestCase):
|
||||
self.assertIn("\n\n[human] Use B.\n\n[step] ", grounds.shown)
|
||||
|
||||
|
||||
def turn(message_id, model, at, **usage):
|
||||
return entries.AssistantTurn(message_id=message_id, model=model, timestamp=at, usage=usage)
|
||||
|
||||
|
||||
class Spend(unittest.TestCase):
|
||||
def test_reads_the_cache_writes_by_lifetime_and_counts_one_without_the_split_as_five_minutes(self):
|
||||
self.assertEqual(tokens_of({"input_tokens": 1, "cache_creation_input_tokens": 9, "cache_creation": {"ephemeral_5m_input_tokens": 2, "ephemeral_1h_input_tokens": 3}, "cache_read_input_tokens": 4, "output_tokens": 5}), Tokens(1, 2, 3, 4, 5))
|
||||
self.assertEqual(tokens_of({"input_tokens": 1, "cache_creation_input_tokens": 9}), Tokens(1, 9, 0, 0, 0))
|
||||
self.assertEqual(tokens_of(None), Tokens())
|
||||
|
||||
def test_counts_a_message_written_in_the_stamped_second_or_without_a_readable_time_as_before_since(self):
|
||||
thread = [turn("m1", "a", "2026-11-01T10:00:01Z", output_tokens=7), turn("m2", "a", "not a time", output_tokens=3), turn("m3", "a", "2026-11-01T10:00:02Z", output_tokens=1)]
|
||||
self.assertEqual(spend.spent("2026-11-01T10:00:01Z", thread, [], "j", Tokens()), {("worker", "a"): Tokens(output=1)})
|
||||
|
||||
def test_sums_two_subagents_of_one_name_on_one_model(self):
|
||||
helpers = [spend.Subagent("Explore", [turn("s1", "b", "2026-11-01T10:00:00Z", input_tokens=3)]), spend.Subagent("Explore", [turn("s2", "b", "2026-11-01T10:00:00Z", input_tokens=4)])]
|
||||
self.assertEqual(spend.spent("", [], helpers, "j", Tokens()), {("Explore", "b"): Tokens(input=7)})
|
||||
|
||||
def test_counts_each_message_once_by_its_id_and_only_after_since(self):
|
||||
thread = [
|
||||
turn("m1", "a", "2026-11-01T10:00:00Z", output_tokens=7),
|
||||
turn("m2", "a", "2026-11-01T10:00:02Z", input_tokens=1, output_tokens=2),
|
||||
turn("m2", "a", "2026-11-01T10:00:02Z", input_tokens=1, output_tokens=2),
|
||||
turn("m3", "b", "2026-11-01T10:00:03Z", cache_read_input_tokens=5),
|
||||
]
|
||||
self.assertEqual(spend.thread_spend(thread, "2026-11-01T10:00:01Z"), {"a": Tokens(1, 0, 0, 0, 2), "b": Tokens(0, 0, 0, 5, 0)})
|
||||
self.assertEqual(spend.thread_spend(thread, ""), {"a": Tokens(1, 0, 0, 0, 9), "b": Tokens(0, 0, 0, 5, 0)})
|
||||
|
||||
def test_names_each_spender_and_leaves_out_one_that_spent_nothing(self):
|
||||
worker = [turn("m1", "a", "2026-11-01T10:00:00Z", output_tokens=7)]
|
||||
helper = spend.Subagent('Explore "Search"', [turn("s1", "b", "2026-11-01T10:00:00Z", input_tokens=3)])
|
||||
self.assertEqual(spend.spent("", worker, [helper], "j", Tokens()), {("worker", "a"): Tokens(output=7), ('Explore "Search"', "b"): Tokens(input=3)})
|
||||
self.assertEqual(spend.spent("", [], [], "j", Tokens(input=1)), {("judge", "j"): Tokens(input=1)})
|
||||
|
||||
def test_names_a_subagent_by_its_agent_type_and_description(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
folder = pathlib.Path(root, "s", "subagents")
|
||||
folder.mkdir(parents=True)
|
||||
for name, meta in [("agent-a", {"agentType": "Explore", "description": "Search the hooks"}), ("agent-b", None), ("agent-c", ["Explore"]), ("agent-d", {"description": "Läs"}), ("agent-e", {"agentType": "Ex\nConfig: x"})]:
|
||||
(folder / f"{name}.jsonl").write_text(json.dumps({"type": "assistant", "message": {"id": name, "model": "m", "content": [], "usage": {"output_tokens": 1}}, "timestamp": "2026-11-01T10:00:00Z"}) + "\n")
|
||||
if meta:
|
||||
(folder / f"{name}.meta.json").write_text(json.dumps(meta))
|
||||
found = spend.subagents(str(pathlib.Path(root, "s.jsonl")))
|
||||
self.assertEqual([subagent.name for subagent in found], ['Explore "Search the hooks"', "subagent", "subagent", 'subagent "Läs"', "Ex Config: x"])
|
||||
self.assertEqual(spend.spent("", [], found[:2], "j", Tokens()), {('Explore "Search the hooks"', "m"): Tokens(output=1), ("subagent", "m"): Tokens(output=1)})
|
||||
self.assertEqual(spend.subagents(str(pathlib.Path(root, "none.jsonl"))), [])
|
||||
|
||||
def test_renders_the_spend_then_the_list_prices_of_each_model_it_knows(self):
|
||||
found = {("worker", "claude-opus-5-5"): Tokens(1, 2, 3, 4, 5), ("judge", "unpriced"): Tokens(input=6)}
|
||||
self.assertEqual(outcomes.spent_block("2026-11-01T10:00:00Z", found), """Spent since 2026-11-01T10:00:00Z, in tokens of input, cache write 5m, cache write 1h, cache read, output:
|
||||
- worker, claude-opus-5-5: 1, 2, 3, 4, 5
|
||||
- judge, unpriced: 6, 0, 0, 0, 0
|
||||
|
||||
List prices in dollars per million tokens of input, cache write 5m, cache write 1h, cache read, output:
|
||||
- claude-opus-5-5: 4, 5, 8, 0.2, 20""")
|
||||
self.assertEqual(outcomes.spent_block("", {("judge", "unpriced"): Tokens(input=6)}), "Spent since the chunk began, in tokens of input, cache write 5m, cache write 1h, cache read, output:\n- judge, unpriced: 6, 0, 0, 0, 0")
|
||||
self.assertEqual(outcomes.spent_block("", {}), "")
|
||||
|
||||
def test_keeps_the_whole_typed_answer_that_holds_the_judges_quote_and_its_tokens(self):
|
||||
shown = "[human] Use A.\n[human] No, keep the old name. Use X.\nworking: keep the new name"
|
||||
typed = ("Use A.", "No, keep the old name. Use X.")
|
||||
for quoted, kept in [("No, keep the old name. Use X.", "No, keep the old name. Use X."), ("keep the old name", "No, keep the old name. Use X."), ("Use", "No, keep the old name. Use X."), ("keep the new name", ""), ("No, keep the name.", "")]:
|
||||
with self.subTest(quoted=quoted):
|
||||
answer = json.loads(judged("unfinished", reversed=quoted).stdout)
|
||||
fake = FakeEffects(claude=[ran(json.dumps({**answer, "usage": {"input_tokens": 2, "output_tokens": 3}}))])
|
||||
self.assertEqual(judge.run_judge("/r", [], "", judge.Grounds(shown, shown, "", typed), fake.effects()), Unfinished("working", judged=Judged(tokens=Tokens(input=2, output=3), reversed=kept)))
|
||||
|
||||
|
||||
class SetupVersion(unittest.TestCase):
|
||||
def test_names_the_release_and_the_commit_or_why_git_cannot_tell(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
isolated = {"GIT_CONFIG_GLOBAL": os.devnull, "GIT_CONFIG_NOSYSTEM": "1", "GIT_CEILING_DIRECTORIES": root}
|
||||
with unittest.mock.patch.dict(os.environ, isolated):
|
||||
gone = main.setup_version(pathlib.Path(root), git)
|
||||
self.assertRegex(gone, r"^unknown: [^\n]*not a git repository")
|
||||
for step in (["init", "-q"], ["-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "--allow-empty", "-m", "one"]):
|
||||
self.assertIsInstance(git(*step, cwd=root), str)
|
||||
head = git("rev-parse", "HEAD", cwd=root).strip()
|
||||
self.assertEqual(main.setup_version(pathlib.Path(root), git), f"{head[:7]} ({head})")
|
||||
git("tag", "v0.1.0", cwd=root)
|
||||
self.assertEqual(main.setup_version(pathlib.Path(root), git), f"v0.1.0 ({head})")
|
||||
git("-c", "user.name=t", "-c", "user.email=t@t", "commit", "-q", "--allow-empty", "-m", "two", cwd=root)
|
||||
head = git("rev-parse", "HEAD", cwd=root).strip()
|
||||
self.assertEqual(main.setup_version(pathlib.Path(root), git), f"v0.1.0-1-g{head[:7]} ({head})")
|
||||
|
||||
def test_names_why_git_cannot_name_the_commit_on_one_line(self):
|
||||
def fake_git(*args, cwd=None):
|
||||
return Failure("fatal: bad HEAD\nhint: repair it") if args[0] == "rev-parse" else "v0.1.0\n"
|
||||
|
||||
self.assertEqual(main.setup_version(pathlib.Path("/r"), fake_git), "unknown: fatal: bad HEAD hint: repair it")
|
||||
|
||||
|
||||
class Grounded(unittest.TestCase):
|
||||
def test_every_verdict_must_quote_the_transcript(self):
|
||||
self.assertTrue(judge.grounded("Needs you: x", "so.\n\nNeeds you: x\n"))
|
||||
@@ -1618,32 +1795,32 @@ class ChunkItems(unittest.TestCase):
|
||||
|
||||
class Verdict(unittest.TestCase):
|
||||
def test_needs_every_field_the_schema_requires(self):
|
||||
self.assertEqual(verdict_from({"escalation": "", "answer": "", "interrupt": False, "evidence": "e", "finished": True, "question": "", "answered_before": "", "left_open": "", "release_ready": False}), Finished("e"))
|
||||
self.assertEqual(verdict_from({"escalation": "", "answer": "", "interrupt": False, "evidence": "e", "finished": False, "question": "ignored", "answered_before": "", "left_open": "", "release_ready": False}), Unfinished("e"))
|
||||
self.assertEqual(verdict_from({"escalation": "", "answer": "", "interrupt": True, "evidence": "e", "finished": True, "question": "Which one?", "answered_before": "", "left_open": "", "release_ready": False}), Interrupt("e", "Which one?"))
|
||||
self.assertEqual(verdict_from({"escalation": "", "answer": "", "interrupt": True, "evidence": "e", "finished": False, "question": "Cut 0.2.0?", "answered_before": "", "left_open": "", "release_ready": True}), Interrupt("e", "Cut 0.2.0?", release_ready=True))
|
||||
self.assertEqual(verdict_from({"escalation": "", "answered_before": "", "left_open": "", "answer": "", "interrupt": True, "evidence": "e", "finished": False, "question": "Cut 0.2.0?"}), Failure("the judge's reply has no release_ready of type boolean"))
|
||||
self.assertEqual(verdict_from({"escalation": "", "answer": "A.", "interrupt": False, "evidence": "e", "finished": False, "question": "Which one?", "answered_before": "", "left_open": "", "release_ready": False}), QuotedAnswer("e", "Which one?", "A."))
|
||||
self.assertEqual(verdict_from({"escalation": "", "answer": "A.", "interrupt": True, "evidence": "e", "finished": False, "question": "Which one?", "answered_before": "", "left_open": "", "release_ready": False}), Interrupt("e", "Which one?"))
|
||||
self.assertEqual(verdict_from({"escalation": "", "answer": "A.", "interrupt": False, "evidence": "e", "finished": True, "question": "", "answered_before": "", "left_open": "", "release_ready": False}), Failure("the judge quoted an answer without a question"))
|
||||
self.assertEqual(verdict_from({"escalation": "", "answer": "", "interrupt": "no", "evidence": "", "finished": True, "question": "", "answered_before": "", "left_open": "", "release_ready": False}), Failure("the judge's reply has no interrupt of type boolean"))
|
||||
self.assertEqual(verdict_from({"escalation": "", "answer": "", "interrupt": False, "evidence": None, "finished": True, "question": "", "answered_before": "", "left_open": "", "release_ready": False}), Failure("the judge's reply has no evidence of type string"))
|
||||
self.assertEqual(verdict_from({"escalation": "", "answer": "", "interrupt": True, "evidence": "x", "finished": False, "question": " ", "answered_before": "", "left_open": "", "release_ready": False}), Failure("the judge interrupted without a question"))
|
||||
self.assertEqual(verdict_from({"escalation": "", "answer": "", "interrupt": False, "evidence": "e", "finished": True, "question": "", "answered_before": "", "left_open": "", "reversed": "", "release_ready": False}), Finished("e"))
|
||||
self.assertEqual(verdict_from({"escalation": "", "answer": "", "interrupt": False, "evidence": "e", "finished": False, "question": "ignored", "answered_before": "", "left_open": "", "reversed": "", "release_ready": False}), Unfinished("e"))
|
||||
self.assertEqual(verdict_from({"escalation": "", "answer": "", "interrupt": True, "evidence": "e", "finished": True, "question": "Which one?", "answered_before": "", "left_open": "", "reversed": "", "release_ready": False}), Interrupt("e", "Which one?"))
|
||||
self.assertEqual(verdict_from({"escalation": "", "answer": "", "interrupt": True, "evidence": "e", "finished": False, "question": "Cut 0.2.0?", "answered_before": "", "left_open": "", "reversed": "", "release_ready": True}), Interrupt("e", "Cut 0.2.0?", release_ready=True))
|
||||
self.assertEqual(verdict_from({"escalation": "", "answered_before": "", "left_open": "", "reversed": "", "answer": "", "interrupt": True, "evidence": "e", "finished": False, "question": "Cut 0.2.0?"}), Failure("the judge's reply has no release_ready of type boolean"))
|
||||
self.assertEqual(verdict_from({"escalation": "", "answer": "A.", "interrupt": False, "evidence": "e", "finished": False, "question": "Which one?", "answered_before": "", "left_open": "", "reversed": "", "release_ready": False}), QuotedAnswer("e", "Which one?", "A."))
|
||||
self.assertEqual(verdict_from({"escalation": "", "answer": "A.", "interrupt": True, "evidence": "e", "finished": False, "question": "Which one?", "answered_before": "", "left_open": "", "reversed": "", "release_ready": False}), Interrupt("e", "Which one?"))
|
||||
self.assertEqual(verdict_from({"escalation": "", "answer": "A.", "interrupt": False, "evidence": "e", "finished": True, "question": "", "answered_before": "", "left_open": "", "reversed": "", "release_ready": False}), Failure("the judge quoted an answer without a question"))
|
||||
self.assertEqual(verdict_from({"escalation": "", "answer": "", "interrupt": "no", "evidence": "", "finished": True, "question": "", "answered_before": "", "left_open": "", "reversed": "", "release_ready": False}), Failure("the judge's reply has no interrupt of type boolean"))
|
||||
self.assertEqual(verdict_from({"escalation": "", "answer": "", "interrupt": False, "evidence": None, "finished": True, "question": "", "answered_before": "", "left_open": "", "reversed": "", "release_ready": False}), Failure("the judge's reply has no evidence of type string"))
|
||||
self.assertEqual(verdict_from({"escalation": "", "answer": "", "interrupt": True, "evidence": "x", "finished": False, "question": " ", "answered_before": "", "left_open": "", "reversed": "", "release_ready": False}), Failure("the judge interrupted without a question"))
|
||||
self.assertEqual(verdict_from(None), Failure("the judge returned no reply"))
|
||||
|
||||
def test_carries_the_earlier_answer_an_interrupt_names(self):
|
||||
reply = {"answer": "", "escalation": "", "interrupt": True, "evidence": "e", "finished": False, "release_ready": False, "answered_before": "Grant one more round.", "left_open": "one more", "question": "Which one?"}
|
||||
reply = {"answer": "", "escalation": "", "interrupt": True, "evidence": "e", "finished": False, "release_ready": False, "answered_before": "Grant one more round.", "left_open": "one more", "question": "Which one?", "reversed": ""}
|
||||
self.assertEqual(verdict_from(reply), Interrupt("e", "Which one?", answered_before="Grant one more round.", left_open="one more"))
|
||||
self.assertEqual(verdict_from({**reply, "interrupt": False, "finished": True}), Finished("e"))
|
||||
|
||||
def test_takes_an_escalation_quote_on_an_unfinished_verdict(self):
|
||||
reply = {"answer": "", "escalation": "round 2: 🔴", "interrupt": False, "evidence": "e", "finished": False, "question": "", "answered_before": "", "left_open": "", "release_ready": False}
|
||||
reply = {"answer": "", "escalation": "round 2: 🔴", "interrupt": False, "evidence": "e", "finished": False, "question": "", "answered_before": "", "left_open": "", "reversed": "", "release_ready": False}
|
||||
self.assertEqual(verdict_from(reply), Unfinished("e", "round 2: 🔴"))
|
||||
self.assertEqual(verdict_from({**reply, "finished": True}), Finished("e"))
|
||||
self.assertEqual(verdict_from({**reply, "escalation": None}), Failure("the judge's reply has no escalation of type string"))
|
||||
|
||||
def test_takes_an_escalation_quote_on_an_interrupt(self):
|
||||
reply = {"answer": "", "escalation": "round 2: 🔴", "interrupt": True, "evidence": "e", "finished": False, "question": "Which one?", "answered_before": "", "left_open": "", "release_ready": False}
|
||||
reply = {"answer": "", "escalation": "round 2: 🔴", "interrupt": True, "evidence": "e", "finished": False, "question": "Which one?", "answered_before": "", "left_open": "", "reversed": "", "release_ready": False}
|
||||
self.assertEqual(verdict_from(reply), Interrupt("e", "Which one?", "round 2: 🔴"))
|
||||
|
||||
def test_drops_an_escalation_quote_the_transcript_does_not_hold_word_for_word_from_an_interrupt_or_an_unfinished_verdict(self):
|
||||
@@ -1669,7 +1846,7 @@ class Verdict(unittest.TestCase):
|
||||
self.assertEqual(judge.quotes_checked(unnamed, grounds), unnamed)
|
||||
|
||||
def test_takes_an_escalation_quote_on_a_quoted_answer(self):
|
||||
reply = {"answer": "A.", "escalation": "round 2: 🔴", "interrupt": False, "evidence": "e", "finished": False, "question": "Which one?", "answered_before": "", "left_open": "", "release_ready": False}
|
||||
reply = {"answer": "A.", "escalation": "round 2: 🔴", "interrupt": False, "evidence": "e", "finished": False, "question": "Which one?", "answered_before": "", "left_open": "", "reversed": "", "release_ready": False}
|
||||
self.assertEqual(verdict_from(reply), QuotedAnswer("e", "Which one?", "A.", "round 2: 🔴"))
|
||||
|
||||
def test_drops_an_escalation_quote_the_transcript_does_not_hold_word_for_word_from_a_quoted_answer(self):
|
||||
@@ -1712,12 +1889,12 @@ class LoopRuns(unittest.TestCase):
|
||||
self.assertEqual(main.loop_run_from([main.RELOAD_FLAG, *handed], CWD, FakeEffects().effects()), Stop(1, f"the edited loop-claude cannot read the state the running one handed it, likely because the edit changed that handover; rerun loop-claude <task>. Handed: {' '.join(handed)}"))
|
||||
|
||||
def test_decodes_every_field_of_the_state_and_its_route(self):
|
||||
state = main.LoopRun(cycle_number=2, root="/r", task="do it", unfinished_evidence="old", route=Route(Rung("claude-opus-5-5", "high"), 3, 4, 5, 1, 7, 9), unfinished_run=2, items_taken_in=(12, 14))
|
||||
state = main.LoopRun(cycle_number=2, root="/r", task="do it", unfinished_evidence="old", route=Route(Rung("claude-fable-5-2", "low"), 3, 4, 5, 1, 7, 9), unfinished_run=2, items_taken_in=(12, 14))
|
||||
self.assertEqual(reload.decode_handed(json.dumps(dataclasses.asdict(state))), state)
|
||||
self.assertEqual(set(reload.LOOP_RUN_FIELDS), {field.name for field in dataclasses.fields(main.LoopRun)})
|
||||
|
||||
def test_rejects_a_field_of_another_type_or_an_unknown_field(self):
|
||||
state = dataclasses.asdict(main.LoopRun(cycle_number=2, root="/r", task="do it", unfinished_evidence="", route=Route(Rung("claude-opus-5-5", "high"), 3, 4, 5, 1, 7, 9), unfinished_run=2))
|
||||
state = dataclasses.asdict(main.LoopRun(cycle_number=2, root="/r", task="do it", unfinished_evidence="", route=Route(Rung("claude-fable-5-2", "low"), 3, 4, 5, 1, 7, 9), unfinished_run=2))
|
||||
for path, wrong in ((("unfinished_run",), "2"), (("unfinished_run",), True), (("route", "unfinished"), 1.0), (("route", "escalated_at"), "9"), (("route", "item"), True), (("route", "rung"), "claude-opus-5-5"), (("route", "rung", "model"), None), (("route",), "r"), (("route", "extra"), 1), (("route", "model"), "claude-opus-5-5"), (("route", "effort"), "high")):
|
||||
with self.subTest(path=path, wrong=wrong):
|
||||
handed = json.loads(json.dumps(state))
|
||||
@@ -1728,7 +1905,7 @@ class LoopRuns(unittest.TestCase):
|
||||
self.assertIsNone(reload.decode_handed(json.dumps(handed)))
|
||||
|
||||
def test_rejects_a_state_or_rung_missing_a_required_field(self):
|
||||
state = dataclasses.asdict(main.LoopRun(cycle_number=2, root="/r", task="do it", unfinished_evidence="", route=Route(Rung("claude-opus-5-5", "high"))))
|
||||
state = dataclasses.asdict(main.LoopRun(cycle_number=2, root="/r", task="do it", unfinished_evidence="", route=Route(Rung("claude-fable-5-2", "low"))))
|
||||
for path in (("cycle_number",), ("root",), ("task",), ("unfinished_evidence",), ("route", "rung"), ("route", "rung", "model")):
|
||||
with self.subTest(path=path):
|
||||
handed = json.loads(json.dumps(state))
|
||||
@@ -1746,7 +1923,7 @@ class LoopRuns(unittest.TestCase):
|
||||
self.assertIsNone(reload.decode_handed("not json"))
|
||||
|
||||
def test_decodes_a_route_inside_the_state_or_none(self):
|
||||
state = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="", route=Route(Rung("claude-opus-5-5", "high"), 3, 4, 5, 1))
|
||||
state = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="", route=Route(Rung("claude-fable-5-2", "low"), 3, 4, 5, 1))
|
||||
self.assertEqual(reload.decode_handed(json.dumps(dataclasses.asdict(state))), state)
|
||||
unrouted = dataclasses.replace(state, route=None)
|
||||
self.assertEqual(reload.decode_handed(json.dumps(dataclasses.asdict(unrouted))), unrouted)
|
||||
@@ -1787,6 +1964,48 @@ class LoopRuns(unittest.TestCase):
|
||||
self.assertEqual(reload.exec_if_edited(a_loop(fake.effects(), launcher=launcher), "stale", main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="")), Stop(1, "could not reload loop-claude: No such file or directory; rerun loop-claude <task>"))
|
||||
|
||||
|
||||
class StopDms(unittest.TestCase):
|
||||
def run_main(self, argv, fake):
|
||||
with tempfile.TemporaryDirectory() as home, contextlib.redirect_stderr(io.StringIO()) as said, contextlib.redirect_stdout(io.StringIO()):
|
||||
code = main.main(argv, {}, paths.paths_from(pathlib.Path(home)), pathlib.Path(home, "loop-claude"), CWD, fake.effects())
|
||||
return code, said.getvalue()
|
||||
|
||||
def test_dms_the_reason_of_a_stop_with_exit_2_such_as_a_chunk_left_unfinished_too_often(self):
|
||||
fake = FakeEffects()
|
||||
with unittest.mock.patch.object(main, "run_loop", return_value=Stop(2, "the human is needed to look at the chunk, but it stayed unfinished")):
|
||||
self.assertEqual(self.run_main(["do it"], fake)[0], 2)
|
||||
self.assertEqual(fake.dms, [f"loop-claude in {CWD} stopped: the human is needed to look at the chunk, but it stayed unfinished"])
|
||||
|
||||
def test_skips_the_dm_where_ctrl_c_stopped_the_loop(self):
|
||||
fake = FakeEffects()
|
||||
with unittest.mock.patch.object(main, "run_loop", side_effect=KeyboardInterrupt):
|
||||
self.assertEqual(self.run_main(["do it"], fake)[0], 130)
|
||||
self.assertEqual(fake.dms, [])
|
||||
|
||||
def test_dms_a_crash_before_it_reaches_the_terminal(self):
|
||||
fake = FakeEffects()
|
||||
with unittest.mock.patch.object(main, "run_loop", side_effect=RuntimeError("boom")), self.assertRaises(RuntimeError):
|
||||
self.run_main(["do it"], fake)
|
||||
self.assertEqual(fake.dms, [f"loop-claude in {CWD} crashed: RuntimeError('boom')"])
|
||||
|
||||
def test_dms_the_reason_where_a_loop_given_a_task_stops_with_exit_1(self):
|
||||
fake = FakeEffects()
|
||||
code, said = self.run_main([main.RELOAD_FLAG, "3"], fake)
|
||||
self.assertEqual(code, 1)
|
||||
self.assertEqual(fake.dms, [f"loop-claude in {CWD} stopped: the edited loop-claude cannot read the state the running one handed it, likely because the edit changed that handover; rerun loop-claude <task>. Handed: 3"])
|
||||
|
||||
def test_says_why_the_dm_of_a_stop_failed_after_the_reason(self):
|
||||
fake = FakeEffects(dm_failures=[Failure("cannot reach https://chat.example: timed out")])
|
||||
self.assertTrue(self.run_main([main.RELOAD_FLAG, "3"], fake)[1].endswith(f"Handed: 3\n{STAMP} could not DM you on Mattermost: cannot reach https://chat.example: timed out\n"))
|
||||
|
||||
def test_skips_the_dm_where_it_prints_its_help(self):
|
||||
for argv, code in (([], 1), (["--help"], 0)):
|
||||
with self.subTest(argv=argv):
|
||||
fake = FakeEffects()
|
||||
self.assertEqual(self.run_main(argv, fake)[0], code)
|
||||
self.assertEqual(fake.dms, [])
|
||||
|
||||
|
||||
class HelpLimits(unittest.TestCase):
|
||||
def test_help_wraps_at_100_columns(self):
|
||||
self.assertEqual([line for line in usage.HELP.splitlines() if len(line) > 100], [])
|
||||
@@ -1820,8 +2039,10 @@ class ExitContract(unittest.TestCase):
|
||||
("cycle/run.py", "archived_stop", "1", "f'{failure.reason}", read),
|
||||
("cycle/run.py", "work", "1", "f'claude left no transcript for session", "claude leaves no transcript"),
|
||||
("cycle/run.py", "rule", "1", "entries.reason", read),
|
||||
("cycle/run.py", "rule", "1", "annotation.reason", read),
|
||||
("cycle/run.py", "rule", "1", "failure.reason", read),
|
||||
("cycle/run.py", "keep_rejection", "1", "unkept.reason", read),
|
||||
("cycle/run.py", "close", "1", "annotation.reason", read),
|
||||
("cycle/run.py", "close", "1", "failure.reason", read),
|
||||
("cycle/run.py", "close", "1", "failure.reason", "a finished chunk's session cannot be deleted"),
|
||||
("loop/close.py", "closed_cycle", "1", "failure.reason", read),
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
"""The verdicts cycle.judge.verdict_from builds from the judge's reply; cycle.run.rule then stamps every verdict but Finished with the items the chunk takes. They sit outside cycle/, since routing reads them and cycle imports routing."""
|
||||
import dataclasses
|
||||
|
||||
from claude_code.tokens import Tokens
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class TakenIn:
|
||||
@@ -9,10 +11,21 @@ class TakenIn:
|
||||
items: tuple[int, ...] = ()
|
||||
# The highest L among them, 0 for none: an escalation steps up from the rung that L picks, and an unfinished verdict also raises the worker to it.
|
||||
highest_likelihood: int = 0
|
||||
# The highest E + I among them, 0 for none: after an unfinished verdict, it routes the next cycle's judge and reviewers.
|
||||
# The highest E + I among them, 0 for none: after an unfinished verdict, it routes the next cycle's reviewers.
|
||||
highest_escape_and_impact: int = 0
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Judged:
|
||||
"""What the judge run that gave a verdict found beside it, which the cycle archives with the verdict."""
|
||||
# In dollars, as its reply records; 0 where it records none.
|
||||
cost: float = 0.0
|
||||
# Its reply's usage, on the judge's model.
|
||||
tokens: Tokens = Tokens()
|
||||
# The human's whole typed answer that holds the judge's quote of a reversal of a choice the worker took on its own recommendation; empty for none, and where no typed answer holds the quote.
|
||||
reversed: str = ""
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Interrupt:
|
||||
evidence: str
|
||||
@@ -23,8 +36,7 @@ class Interrupt:
|
||||
release_ready: bool = False
|
||||
# How many transcript entries the judge read, which escalation_mark.stamped stamps. An escalation the verdict carries moves the route's mark there. None means it was never stamped, and then its escalation doesn't step the worker.
|
||||
entries_read: int | None = None
|
||||
# What the judge run that gave this verdict cost in dollars, as its reply records; 0 where it records none. The cycle archives it beside the verdict.
|
||||
judge_cost: float = 0.0
|
||||
judged: Judged = Judged()
|
||||
# The [human] line from earlier in the chunk that answered the same question, and the words of it that leave the question open; empty for none. cycle.judge.re_ask_checked turns the Interrupt into an Unfinished where the question doesn't quote them.
|
||||
answered_before: str = ""
|
||||
left_open: str = ""
|
||||
@@ -40,15 +52,13 @@ class QuotedAnswer:
|
||||
escalation: str = ""
|
||||
taken_in: TakenIn = TakenIn()
|
||||
entries_read: int | None = None
|
||||
# As on Interrupt. What the judge run that gave this verdict cost in dollars, as its reply records; 0 where it records none. The cycle archives it beside the verdict.
|
||||
judge_cost: float = 0.0
|
||||
judged: Judged = Judged()
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Finished:
|
||||
evidence: str
|
||||
# As on Interrupt. What the judge run that gave this verdict cost in dollars, as its reply records; 0 where it records none. The cycle archives it beside the verdict.
|
||||
judge_cost: float = 0.0
|
||||
judged: Judged = Judged()
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
@@ -58,8 +68,7 @@ class Unfinished:
|
||||
escalation: str = ""
|
||||
taken_in: TakenIn = TakenIn()
|
||||
entries_read: int | None = None
|
||||
# As on Interrupt. What the judge run that gave this verdict cost in dollars, as its reply records; 0 where it records none. The cycle archives it beside the verdict.
|
||||
judge_cost: float = 0.0
|
||||
judged: Judged = Judged()
|
||||
|
||||
|
||||
Verdict = Interrupt | QuotedAnswer | Finished | Unfinished
|
||||
|
||||
@@ -4,6 +4,7 @@ A change here, such as to how input reads a line, changes every tool that runs o
|
||||
"""
|
||||
import dataclasses
|
||||
import os
|
||||
import pathlib
|
||||
import select
|
||||
import signal
|
||||
import subprocess
|
||||
@@ -13,6 +14,8 @@ import time
|
||||
import typing
|
||||
import uuid
|
||||
|
||||
from mattermost_dm.dm import dm, http_json
|
||||
from failure import Failure
|
||||
from git_cli import git_repo
|
||||
from machine_load.memory import Memory, read_memory
|
||||
|
||||
@@ -44,6 +47,8 @@ class Effects:
|
||||
claude_on_terminal: typing.Callable[[list[str], str, dict[str, str]], int]
|
||||
# Drops what was typed on the terminal and not yet read.
|
||||
discard_typed: typing.Callable[[], None]
|
||||
# Sends the human a direct message on Mattermost, as `mattermost-dm` does; a Failure where it could not.
|
||||
dm: typing.Callable[[str], Failure | None]
|
||||
execv: typing.Callable[[str, list[str]], None]
|
||||
git: git_repo.Git
|
||||
input: typing.Callable[[str], str]
|
||||
@@ -80,6 +85,7 @@ def system_effects() -> Effects:
|
||||
claude=lambda args, cwd, stdin: subprocess.run(["claude", *args], capture_output=True, cwd=cwd, input=stdin, text=True),
|
||||
claude_on_terminal=claude_on_terminal,
|
||||
discard_typed=lambda: termios.tcflush(sys.stdin, termios.TCIFLUSH),
|
||||
dm=lambda text: dm(text, pathlib.Path.home(), http_json),
|
||||
execv=os.execv,
|
||||
git=git_repo.git,
|
||||
input=input,
|
||||
|
||||
@@ -12,7 +12,7 @@ of its question as fits; the loop's terminal shows it whole. Answer as on the lo
|
||||
line is sent, and the rest is dropped; a longer answer goes through /talk.
|
||||
- /talk opens the worker's claude session here, with `claude --resume`, as /talk does on the loop's
|
||||
terminal. Once that claude ends, the loop goes on if you typed there, and the judge rules on what
|
||||
you typed; if you typed nothing, the loop stops.
|
||||
you typed; if you typed no answer, the loop stops.
|
||||
- Enter alone, or Esc, goes back to the list; unlike on the loop's terminal, it doesn't stop the loop.
|
||||
|
||||
The loop takes whichever answer comes first, here or on its terminal, so it keeps working with no
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""The files loop-claude and loop-inbox share: a running loop lists itself (running_loops.py, session_lock.py) and its question (waiting/), and both read the same paths (paths.py) and open claude for the human the same way (hand_over.py).
|
||||
|
||||
A change here changes both tools. It imports nothing from loop_claude/.
|
||||
A change here changes both tools. It doesn't import anything from loop_claude/.
|
||||
"""
|
||||
|
||||
Executable
+9
@@ -0,0 +1,9 @@
|
||||
#!/usr/bin/env python3
|
||||
import pathlib
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
|
||||
|
||||
from mattermost_dm import dm, main
|
||||
|
||||
sys.exit(main.main(sys.argv[1:], sys.stdin, lambda: dm.read_config(dm.env_file(pathlib.Path.home())), dm.http_json, sys.stderr))
|
||||
@@ -0,0 +1,135 @@
|
||||
"""Sends a direct message from a Mattermost bot to one user, through Mattermost's REST API v4."""
|
||||
import dataclasses
|
||||
import http.client
|
||||
import json
|
||||
import pathlib
|
||||
import typing
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
from failure import Failure
|
||||
|
||||
KEYS = ("MATTERMOST_URL", "MATTERMOST_TOKEN", "MATTERMOST_RECIPIENT")
|
||||
# Seconds each connect and each read may wait, so an unreachable server holds loop-claude's interrupt only briefly.
|
||||
TIMEOUT = 10
|
||||
|
||||
# Sends a request, the body as JSON where there is one, and returns the JSON answer, or a Failure saying why there is none.
|
||||
Http = typing.Callable[[str, str, str, object], object]
|
||||
|
||||
|
||||
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
||||
"""Refuses every redirect, which Mattermost's API never sends: urllib would resend the token to the new location, even one off https."""
|
||||
|
||||
def redirect_request(self, *args: typing.Any, **kwargs: typing.Any) -> None:
|
||||
return None
|
||||
|
||||
|
||||
OPENER = urllib.request.build_opener(NoRedirect)
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Config:
|
||||
url: str
|
||||
token: str
|
||||
recipient: str
|
||||
|
||||
|
||||
def env_file(home: pathlib.Path) -> pathlib.Path:
|
||||
return home / ".claude" / ".env"
|
||||
|
||||
|
||||
def read_config(path: pathlib.Path) -> Config | Failure:
|
||||
"""The server, bot token and recipient that path's KEY=value lines hold."""
|
||||
try:
|
||||
mode = path.stat().st_mode
|
||||
text = path.read_text(encoding="utf-8")
|
||||
except FileNotFoundError:
|
||||
return Failure(f"{path} does not exist; it needs {', '.join(KEYS[:-1])} and {KEYS[-1]}")
|
||||
except (OSError, UnicodeDecodeError) as failure:
|
||||
return Failure(f"cannot read {path}: {failure}")
|
||||
if mode & 0o077:
|
||||
return Failure(f"{path} holds the bot's token, so only its owner may read it; run chmod 600 {path}")
|
||||
values = parse_env(text)
|
||||
if missing := [key for key in KEYS if not values.get(key)]:
|
||||
return Failure(f"{path} lacks {' and '.join(missing)}")
|
||||
url, token, recipient = (values[key] for key in KEYS)
|
||||
if not url.startswith("https://"):
|
||||
return Failure(f"{path} → MATTERMOST_URL must start with https://, so the token is never sent in the clear")
|
||||
return Config(url.rstrip("/"), token, recipient)
|
||||
|
||||
|
||||
def parse_env(text: str) -> dict[str, str]:
|
||||
values = {}
|
||||
for line in text.splitlines():
|
||||
key, equals, value = line.partition("=")
|
||||
if not equals or key.lstrip().startswith("#"):
|
||||
continue
|
||||
value = value.strip()
|
||||
if len(value) >= 2 and value[0] == value[-1] and value[0] in "'\"":
|
||||
value = value[1:-1]
|
||||
values[key.strip()] = value
|
||||
return values
|
||||
|
||||
|
||||
def send(config: Config, message: str, http: Http) -> Failure | None:
|
||||
api = f"{config.url}/api/v4"
|
||||
bot = id_of(http("GET", f"{api}/users/me", config.token, None), "GET /api/v4/users/me")
|
||||
if isinstance(bot, Failure):
|
||||
return bot
|
||||
recipient = id_of(http("GET", f"{api}/users/username/{urllib.parse.quote(config.recipient)}", config.token, None), f"GET /api/v4/users/username/{config.recipient}")
|
||||
if isinstance(recipient, Failure):
|
||||
return recipient
|
||||
channel = id_of(http("POST", f"{api}/channels/direct", config.token, [bot, recipient]), "POST /api/v4/channels/direct")
|
||||
if isinstance(channel, Failure):
|
||||
return channel
|
||||
posted = id_of(http("POST", f"{api}/posts", config.token, {"channel_id": channel, "message": message}), "POST /api/v4/posts")
|
||||
return posted if isinstance(posted, Failure) else None
|
||||
|
||||
|
||||
def id_of(answer: object, request: str) -> str | Failure:
|
||||
if isinstance(answer, Failure):
|
||||
return answer
|
||||
found = answer.get("id") if isinstance(answer, dict) else None
|
||||
return found if isinstance(found, str) and found else Failure(f"{request} answered without an id")
|
||||
|
||||
|
||||
def http_json(method: str, url: str, token: str, body: object) -> object:
|
||||
"""The JSON that url answers; a Failure naming the server where it cannot be reached, and the request where it answers an error, breaks HTTP or answers something other than JSON."""
|
||||
request_name = f"{method} {urllib.parse.urlsplit(url).path}"
|
||||
data = None if body is None else json.dumps(body).encode()
|
||||
request = urllib.request.Request(url, data, {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}, method=method)
|
||||
try:
|
||||
with OPENER.open(request, timeout=TIMEOUT) as response:
|
||||
raw = response.read()
|
||||
except urllib.error.HTTPError as failure:
|
||||
with failure:
|
||||
return Failure(f"{request_name} answered {failure.code}: {error_message(failure) or failure.reason}")
|
||||
except http.client.HTTPException as failure:
|
||||
return Failure(f"{request_name} got a broken answer: {failure!r}")
|
||||
except (OSError, ValueError) as failure:
|
||||
server = urllib.parse.urlunsplit(urllib.parse.urlsplit(url)[:2] + ("", "", ""))
|
||||
return Failure(f"cannot reach {server}: {getattr(failure, 'reason', failure)}")
|
||||
try:
|
||||
return json.loads(raw)
|
||||
except ValueError:
|
||||
return Failure(f"{request_name} answered with something other than JSON")
|
||||
|
||||
|
||||
def error_message(failure: urllib.error.HTTPError) -> str:
|
||||
"""Mattermost's message in an error answer; empty where the body is cut short, breaks HTTP or holds none."""
|
||||
try:
|
||||
answer = json.loads(failure.read())
|
||||
except (http.client.HTTPException, OSError, ValueError):
|
||||
return ""
|
||||
message = answer.get("message") if isinstance(answer, dict) else None
|
||||
return message if isinstance(message, str) else ""
|
||||
|
||||
|
||||
def dm(text: str, home: pathlib.Path, http: Http) -> Failure | None:
|
||||
"""Sends text as home's .claude/.env configures it. A machine without that file hasn't asked for DMs, so there the DM is skipped."""
|
||||
path = env_file(home)
|
||||
if not path.exists():
|
||||
return None
|
||||
config = read_config(path)
|
||||
return config if isinstance(config, Failure) else send(config, text, http)
|
||||
@@ -0,0 +1,43 @@
|
||||
"""Send a direct message from the Mattermost bot to the human.
|
||||
|
||||
usage: mattermost-dm [<message>]
|
||||
|
||||
Sends <message>, or else stdin, from the bot to the recipient that ~/.claude/.env names. That file
|
||||
holds three KEY=value lines, and only its owner may read it, since it holds the bot's token:
|
||||
|
||||
MATTERMOST_URL=https://chat.example
|
||||
MATTERMOST_TOKEN=<the bot's access token>
|
||||
MATTERMOST_RECIPIENT=<the recipient's username>
|
||||
|
||||
Exit 0 once the message is sent.
|
||||
Exit 1, saying why, when Mattermost cannot be reached or refuses the message.
|
||||
Exit 2, saying why, on misuse: bad arguments, an empty message, or a ~/.claude/.env that is
|
||||
missing or unreadable, lacks a key, names a server off https, or that others may read.
|
||||
"""
|
||||
import typing
|
||||
|
||||
from mattermost_dm.dm import Config, Http, send
|
||||
from failure import Failure
|
||||
|
||||
USAGE = "usage: mattermost-dm [<message>]"
|
||||
|
||||
|
||||
def main(argv: list[str], stdin: typing.TextIO, config: typing.Callable[[], Config | Failure], http: Http, stderr: typing.TextIO) -> int:
|
||||
if argv[:1] in (["-h"], ["--help"]):
|
||||
print(__doc__.strip())
|
||||
return 0
|
||||
if len(argv) > 1:
|
||||
print(f"mattermost-dm: takes one message, or none to read stdin; got {len(argv)} arguments\n{USAGE}", file=stderr)
|
||||
return 2
|
||||
message = (argv[0] if argv else stdin.read()).strip()
|
||||
if not message:
|
||||
print("mattermost-dm: the message is empty", file=stderr)
|
||||
return 2
|
||||
found = config()
|
||||
if isinstance(found, Failure):
|
||||
print(f"mattermost-dm: {found.reason}", file=stderr)
|
||||
return 2
|
||||
if failed := send(found, message, http):
|
||||
print(f"mattermost-dm: {failed.reason}", file=stderr)
|
||||
return 1
|
||||
return 0
|
||||
@@ -0,0 +1,268 @@
|
||||
import http.server
|
||||
import io
|
||||
import json
|
||||
import pathlib
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import unittest
|
||||
import unittest.mock
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from mattermost_dm import dm, main
|
||||
from failure import Failure
|
||||
from test_env import isolated_env
|
||||
|
||||
TOOL = pathlib.Path(__file__).resolve().parents[1] / "mattermost-dm"
|
||||
CONFIG = dm.Config("https://chat.example", "secret-token", "lilleman")
|
||||
|
||||
|
||||
def env_file(folder: str, text: str, mode: int = 0o600) -> pathlib.Path:
|
||||
path = pathlib.Path(folder) / ".env"
|
||||
path.write_text(text)
|
||||
path.chmod(mode)
|
||||
return path
|
||||
|
||||
|
||||
class FakeServer:
|
||||
"""Mattermost's answers by method and path, recording each request it gets."""
|
||||
|
||||
def __init__(self, answers: dict[tuple[str, str], object]) -> None:
|
||||
self.answers = answers
|
||||
self.requests: list[tuple[str, str, str, object]] = []
|
||||
|
||||
def __call__(self, method: str, url: str, token: str, body: object) -> object:
|
||||
self.requests.append((method, url, token, body))
|
||||
return self.answers[(method, url.removeprefix("https://chat.example"))]
|
||||
|
||||
|
||||
def mattermost() -> FakeServer:
|
||||
return FakeServer({
|
||||
("GET", "/api/v4/users/me"): {"id": "bot-id"},
|
||||
("GET", "/api/v4/users/username/lilleman"): {"id": "human-id"},
|
||||
("POST", "/api/v4/channels/direct"): {"id": "channel-id"},
|
||||
("POST", "/api/v4/posts"): {"id": "post-id"},
|
||||
})
|
||||
|
||||
|
||||
class ReadConfig(unittest.TestCase):
|
||||
def test_reads_the_server_the_token_and_the_recipient_skipping_blanks_comments_and_quotes(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
path = env_file(folder, '# larvit-bot\n\nMATTERMOST_URL = https://chat.example/\nMATTERMOST_TOKEN="secret-token"\nMATTERMOST_RECIPIENT=\'lilleman\'\nOTHER=1\n')
|
||||
self.assertEqual(dm.read_config(path), dm.Config("https://chat.example", "secret-token", "lilleman"))
|
||||
|
||||
def test_names_the_file_and_the_keys_it_needs_where_the_file_is_missing(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
path = pathlib.Path(folder) / ".env"
|
||||
self.assertEqual(dm.read_config(path), Failure(f"{path} does not exist; it needs MATTERMOST_URL, MATTERMOST_TOKEN and MATTERMOST_RECIPIENT"))
|
||||
|
||||
def test_names_each_key_missing_or_empty(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
path = env_file(folder, "MATTERMOST_URL=https://chat.example\nMATTERMOST_TOKEN=\n")
|
||||
self.assertEqual(dm.read_config(path), Failure(f"{path} lacks MATTERMOST_TOKEN and MATTERMOST_RECIPIENT"))
|
||||
|
||||
def test_refuses_a_file_that_group_or_others_can_read_since_it_holds_the_token(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
for mode in (0o640, 0o604):
|
||||
with self.subTest(mode=oct(mode)):
|
||||
path = env_file(folder, "MATTERMOST_URL=https://chat.example\nMATTERMOST_TOKEN=t\nMATTERMOST_RECIPIENT=r\n", mode)
|
||||
self.assertEqual(dm.read_config(path), Failure(f"{path} holds the bot's token, so only its owner may read it; run chmod 600 {path}"))
|
||||
|
||||
def test_refuses_a_server_off_https_which_would_send_the_token_in_the_clear(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
path = env_file(folder, "MATTERMOST_URL=http://chat.example\nMATTERMOST_TOKEN=t\nMATTERMOST_RECIPIENT=r\n")
|
||||
self.assertEqual(dm.read_config(path), Failure(f"{path} → MATTERMOST_URL must start with https://, so the token is never sent in the clear"))
|
||||
|
||||
|
||||
class Send(unittest.TestCase):
|
||||
def test_finds_both_users_opens_their_direct_channel_and_posts_the_message_there(self):
|
||||
server = mattermost()
|
||||
self.assertIsNone(dm.send(CONFIG, "Which one?", server))
|
||||
self.assertEqual(server.requests, [
|
||||
("GET", "https://chat.example/api/v4/users/me", "secret-token", None),
|
||||
("GET", "https://chat.example/api/v4/users/username/lilleman", "secret-token", None),
|
||||
("POST", "https://chat.example/api/v4/channels/direct", "secret-token", ["bot-id", "human-id"]),
|
||||
("POST", "https://chat.example/api/v4/posts", "secret-token", {"channel_id": "channel-id", "message": "Which one?"}),
|
||||
])
|
||||
|
||||
def test_stops_at_the_first_failed_request(self):
|
||||
server = mattermost()
|
||||
server.answers[("GET", "/api/v4/users/username/lilleman")] = Failure("GET /api/v4/users/username/lilleman answered 404: Unable to find an existing account matching your username.")
|
||||
self.assertEqual(dm.send(CONFIG, "Which one?", server), Failure("GET /api/v4/users/username/lilleman answered 404: Unable to find an existing account matching your username."))
|
||||
self.assertEqual(len(server.requests), 2)
|
||||
|
||||
def test_fails_on_an_answer_without_an_id_or_one_that_is_not_an_object(self):
|
||||
for answer in ({"status": "OK"}, ["channel-id"], {"id": ""}):
|
||||
with self.subTest(answer=answer):
|
||||
server = mattermost()
|
||||
server.answers[("POST", "/api/v4/channels/direct")] = answer
|
||||
self.assertEqual(dm.send(CONFIG, "Which one?", server), Failure("POST /api/v4/channels/direct answered without an id"))
|
||||
self.assertEqual(len(server.requests), 3)
|
||||
|
||||
def test_fails_where_the_post_itself_fails(self):
|
||||
server = mattermost()
|
||||
server.answers[("POST", "/api/v4/posts")] = Failure("POST /api/v4/posts answered 403: You do not have the appropriate permissions.")
|
||||
self.assertEqual(dm.send(CONFIG, "Which one?", server), Failure("POST /api/v4/posts answered 403: You do not have the appropriate permissions."))
|
||||
|
||||
|
||||
class Recorded(http.server.BaseHTTPRequestHandler):
|
||||
"""Answers each request with the server's next scripted status and body, recording what it got."""
|
||||
|
||||
def do_GET(self) -> None:
|
||||
self.answer()
|
||||
|
||||
def do_POST(self) -> None:
|
||||
self.answer()
|
||||
|
||||
def answer(self) -> None:
|
||||
length = int(self.headers.get("Content-Length") or 0)
|
||||
self.server.got.append((self.command, self.path, dict(self.headers), self.rfile.read(length))) # type: ignore[attr-defined]
|
||||
status, body = self.server.script.pop(0) # type: ignore[attr-defined]
|
||||
if status is None:
|
||||
# Raw bytes, as a server that breaks HTTP sends them.
|
||||
self.wfile.write(body)
|
||||
self.close_connection = True
|
||||
return
|
||||
self.send_response(status)
|
||||
if 300 <= status < 400:
|
||||
self.send_header("Location", "/elsewhere")
|
||||
self.send_header("Content-Type", "application/json")
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def log_message(self, format: str, *args: object) -> None:
|
||||
pass
|
||||
|
||||
|
||||
class HttpJson(unittest.TestCase):
|
||||
def serve(self, *script: tuple[int, bytes]) -> str:
|
||||
server = http.server.HTTPServer(("127.0.0.1", 0), Recorded)
|
||||
server.script = list(script) # type: ignore[attr-defined]
|
||||
server.got = [] # type: ignore[attr-defined]
|
||||
threading.Thread(target=server.serve_forever, daemon=True).start()
|
||||
self.addCleanup(server.server_close)
|
||||
self.addCleanup(server.shutdown)
|
||||
self.server = server
|
||||
return f"http://127.0.0.1:{server.server_port}"
|
||||
|
||||
def test_sends_the_token_as_a_bearer_and_the_body_as_json_and_reads_the_json_answer(self):
|
||||
base = self.serve((201, b'{"id": "post-id"}'))
|
||||
self.assertEqual(dm.http_json("POST", f"{base}/api/v4/posts", "secret-token", {"message": "hi"}), {"id": "post-id"})
|
||||
[(method, path, headers, body)] = self.server.got # type: ignore[attr-defined]
|
||||
self.assertEqual((method, path, headers["Authorization"], headers["Content-Type"], json.loads(body)), ("POST", "/api/v4/posts", "Bearer secret-token", "application/json", {"message": "hi"}))
|
||||
|
||||
def test_names_the_request_the_status_and_mattermosts_message_on_an_error(self):
|
||||
base = self.serve((401, b'{"message": "Invalid or expired session, please login again."}'))
|
||||
self.assertEqual(dm.http_json("GET", f"{base}/api/v4/users/me", "bad", None), Failure("GET /api/v4/users/me answered 401: Invalid or expired session, please login again."))
|
||||
|
||||
def test_follows_no_redirect_so_the_token_goes_only_to_the_server_named(self):
|
||||
base = self.serve((302, b"{}"))
|
||||
self.assertEqual(dm.http_json("GET", f"{base}/api/v4/users/me", "t", None), Failure("GET /api/v4/users/me answered 302: Found"))
|
||||
self.assertEqual(len(self.server.got), 1) # type: ignore[attr-defined]
|
||||
|
||||
def test_sends_no_body_with_a_get(self):
|
||||
base = self.serve((200, b'{"id": "bot-id"}'))
|
||||
dm.http_json("GET", f"{base}/api/v4/users/me", "t", None)
|
||||
[(_, _, headers, body)] = self.server.got # type: ignore[attr-defined]
|
||||
self.assertEqual((headers.get("Content-Length"), body), (None, b""))
|
||||
|
||||
def test_fails_on_an_answer_that_breaks_http(self):
|
||||
for raw in (b"garbage\r\n\r\n", b"HTTP/1.1 200 OK\r\nContent-Length: 100\r\n\r\n{}"):
|
||||
with self.subTest(raw=raw):
|
||||
base = self.serve((None, raw))
|
||||
failed = dm.http_json("GET", f"{base}/api/v4/users/me", "t", None)
|
||||
self.assertTrue(isinstance(failed, Failure) and failed.reason.startswith("GET /api/v4/users/me got a broken answer: "), failed)
|
||||
|
||||
def test_names_the_status_of_an_error_whose_body_is_cut_short(self):
|
||||
base = self.serve((None, b"HTTP/1.1 500 Internal Server Error\r\nContent-Length: 100\r\n\r\n{}"))
|
||||
self.assertEqual(dm.http_json("GET", f"{base}/api/v4/users/me", "t", None), Failure("GET /api/v4/users/me answered 500: Internal Server Error"))
|
||||
|
||||
def test_gives_up_on_a_server_that_never_answers_after_the_timeout(self):
|
||||
silent = socket.socket()
|
||||
self.addCleanup(silent.close)
|
||||
silent.bind(("127.0.0.1", 0))
|
||||
silent.listen(1)
|
||||
base = f"http://127.0.0.1:{silent.getsockname()[1]}"
|
||||
with unittest.mock.patch.object(dm, "TIMEOUT", 0.2):
|
||||
self.assertEqual(dm.http_json("GET", f"{base}/api/v4/users/me", "t", None), Failure(f"cannot reach {base}: timed out"))
|
||||
|
||||
def test_fails_on_an_answer_that_is_not_json(self):
|
||||
base = self.serve((200, b"<html>"))
|
||||
self.assertEqual(dm.http_json("GET", f"{base}/api/v4/users/me", "t", None), Failure("GET /api/v4/users/me answered with something other than JSON"))
|
||||
|
||||
def test_fails_naming_the_server_it_cannot_reach(self):
|
||||
base = self.serve()
|
||||
self.server.server_close()
|
||||
failed = dm.http_json("GET", f"{base}/api/v4/users/me", "t", None)
|
||||
self.assertIsInstance(failed, Failure)
|
||||
self.assertTrue(str(getattr(failed, "reason", "")).startswith(f"cannot reach {base}: "), failed)
|
||||
|
||||
|
||||
class Dm(unittest.TestCase):
|
||||
def home_with(self, home: str, text: str) -> pathlib.Path:
|
||||
folder = pathlib.Path(home, ".claude")
|
||||
folder.mkdir()
|
||||
return env_file(str(folder), text)
|
||||
|
||||
def test_sends_through_the_env_file_under_home(self):
|
||||
with tempfile.TemporaryDirectory() as home:
|
||||
self.home_with(home, "MATTERMOST_URL=https://chat.example\nMATTERMOST_TOKEN=secret-token\nMATTERMOST_RECIPIENT=lilleman\n")
|
||||
server = mattermost()
|
||||
self.assertIsNone(dm.dm("Which one?", pathlib.Path(home), server))
|
||||
self.assertEqual(server.requests[-1], ("POST", "https://chat.example/api/v4/posts", "secret-token", {"channel_id": "channel-id", "message": "Which one?"}))
|
||||
|
||||
def test_skips_the_dm_on_a_machine_without_the_env_file(self):
|
||||
with tempfile.TemporaryDirectory() as home:
|
||||
server = mattermost()
|
||||
self.assertIsNone(dm.dm("Which one?", pathlib.Path(home), server))
|
||||
self.assertEqual(server.requests, [])
|
||||
|
||||
def test_fails_naming_the_mistake_where_the_env_file_is_there_but_wrong(self):
|
||||
with tempfile.TemporaryDirectory() as home:
|
||||
path = self.home_with(home, "MATTERMOST_URL=https://chat.example\n")
|
||||
self.assertEqual(dm.dm("Which one?", pathlib.Path(home), mattermost()), Failure(f"{path} lacks MATTERMOST_TOKEN and MATTERMOST_RECIPIENT"))
|
||||
|
||||
|
||||
class Main(unittest.TestCase):
|
||||
def run_main(self, argv: list[str], stdin: str = "", config: object = CONFIG, server: object = None) -> tuple[int, str]:
|
||||
stderr = io.StringIO()
|
||||
sent = server or mattermost()
|
||||
code = main.main(argv, io.StringIO(stdin), lambda: config, sent, stderr) # type: ignore[arg-type]
|
||||
return code, stderr.getvalue()
|
||||
|
||||
def test_sends_its_argument_or_else_stdin_and_exits_0(self):
|
||||
for argv, stdin in ((["Which one?"], ""), ([], "Which one?\n")):
|
||||
with self.subTest(argv=argv):
|
||||
server = mattermost()
|
||||
self.assertEqual(self.run_main(argv, stdin, server=server), (0, ""))
|
||||
self.assertEqual(server.requests[-1][3], {"channel_id": "channel-id", "message": "Which one?"})
|
||||
|
||||
def test_exits_2_on_misuse_naming_it(self):
|
||||
missing = Failure("/h/.claude/.env does not exist; it needs MATTERMOST_URL, MATTERMOST_TOKEN and MATTERMOST_RECIPIENT")
|
||||
for argv, stdin, config, said in (
|
||||
([], " \n", CONFIG, "mattermost-dm: the message is empty\n"),
|
||||
(["a", "b"], "", CONFIG, f"mattermost-dm: takes one message, or none to read stdin; got 2 arguments\n{main.USAGE}\n"),
|
||||
(["hi"], "", missing, f"mattermost-dm: {missing.reason}\n"),
|
||||
):
|
||||
with self.subTest(argv=argv, stdin=stdin):
|
||||
self.assertEqual(self.run_main(argv, stdin, config), (2, said))
|
||||
|
||||
def test_exits_1_naming_why_the_send_failed(self):
|
||||
server = mattermost()
|
||||
server.answers[("GET", "/api/v4/users/me")] = Failure("GET /api/v4/users/me answered 401: Invalid or expired session, please login again.")
|
||||
self.assertEqual(self.run_main(["hi"], server=server), (1, "mattermost-dm: GET /api/v4/users/me answered 401: Invalid or expired session, please login again.\n"))
|
||||
|
||||
def test_the_launcher_prints_help_and_reads_the_env_file_under_home(self):
|
||||
with tempfile.TemporaryDirectory() as home:
|
||||
env = {**isolated_env(), "HOME": home}
|
||||
helped = subprocess.run([sys.executable, str(TOOL), "--help"], capture_output=True, text=True, env=env)
|
||||
self.assertEqual((helped.returncode, helped.stdout.splitlines()[0]), (0, main.__doc__.strip().splitlines()[0]))
|
||||
sent = subprocess.run([sys.executable, str(TOOL), "hi"], capture_output=True, text=True, env=env)
|
||||
self.assertEqual((sent.returncode, sent.stderr), (2, f"mattermost-dm: {home}/.claude/.env does not exist; it needs MATTERMOST_URL, MATTERMOST_TOKEN and MATTERMOST_RECIPIENT\n"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -51,10 +51,11 @@ class Rung:
|
||||
LADDER = (
|
||||
Rung("claude-sonnet-5-5", "high"),
|
||||
Rung("claude-opus-5-5", "medium"),
|
||||
Rung("claude-opus-5-5", "high"),
|
||||
Rung("claude-fable-5-2", "low"),
|
||||
Rung("claude-fable-5-2", "medium"),
|
||||
Rung("claude-opus-5-5", "xhigh"),
|
||||
Rung("claude-opus-5-5", "max"),
|
||||
Rung("claude-fable-5-1", "max"),
|
||||
Rung("claude-fable-5-2", "high"),
|
||||
Rung("claude-fable-5-2", "max"),
|
||||
)
|
||||
# The rungs a task's L steps its worker from the project's rung.
|
||||
WORKER_STEPS = {1: -1, 2: -1, 3: 0, 4: 1}
|
||||
@@ -95,7 +96,7 @@ def stepped_up(rung: Rung) -> Rung:
|
||||
def review_rung(project: Rung, worker: Rung, escape_and_impact: int, kind: ReviewKind, markdown_only: bool = False) -> Rung:
|
||||
"""The rung a review of this kind runs on in a chunk whose worker runs on worker and whose item has that E + I; markdown_only where the branch changes only Markdown no agent follows.
|
||||
|
||||
A pass's reviewer runs on reviewers_rung; no replay has qualified a lower rung for any pass, docs/decisions.md → `routing: a review pass runs below the project's rung only on a rung that a replay …`. A seat and the security pass run on the project's rung, so the seats score every chunk on one rung, and the security pass spends no more than the project chose.
|
||||
A pass's reviewer runs on reviewers_rung; no replay has qualified a lower rung for any pass, docs/decisions.md → `routing: a review pass runs below the project's rung only on a rung whose replay of its rounds finds a share of their 🔴 and 🟡 findings no more than a margin below the project's rung's own replay`. A seat and the security pass run on the project's rung, so the seats score every chunk on one rung, and the security pass spends no more than the project chose.
|
||||
"""
|
||||
return project if kind in ("seat", "security") else reviewers_rung(project, worker, escape_and_impact, markdown_only)
|
||||
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
"""What a message costs at list prices. They weight how a chunk's recorded cost splits between its messages, and a Spent block records them beside what a stretch spent, so a wrong price stays wrong in every outcome written after it."""
|
||||
import dataclasses
|
||||
|
||||
from claude_code.tokens import tokens_of
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Price:
|
||||
"""Dollars per million tokens. A cache write costs 1.25 times the input for a five-minute cache and 2 times for an hour's, as Opus 5.5's $5 and $8 show."""
|
||||
input: float
|
||||
read: float
|
||||
output: float
|
||||
|
||||
@property
|
||||
def write_5m(self) -> float:
|
||||
return self.input * 1.25
|
||||
|
||||
@property
|
||||
def write_1h(self) -> float:
|
||||
return self.input * 2
|
||||
|
||||
|
||||
# Anthropic's list prices as the claude-api skill lists them (cached 2026-10-06, and Fable 5.2's on 2026-11-03), with Opus 5.5's cache prices from `docs/decisions.md` → `loop-claude: the worker's claude compacts…`. Haiku 5.5's cache read is assumed at a tenth of its input, and its dearer prompts above 200k tokens are left out. Keep each price current with that list: the prices are archived as the ones in force.
|
||||
PRICES = {
|
||||
# Archived chunks that ran on Fable 5.1 are still priced from here.
|
||||
"claude-fable-5-1": Price(10, 0.25, 50),
|
||||
"claude-fable-5-2": Price(8, 0.2, 40),
|
||||
"claude-haiku-5-5": Price(0.1, 0.01, 0.5),
|
||||
"claude-opus-5-5": Price(4, 0.2, 20),
|
||||
"claude-sonnet-5-5": Price(2, 0.2, 10),
|
||||
}
|
||||
|
||||
|
||||
def listed(model: str, usage: object) -> float:
|
||||
"""The cost of one message's usage at the model's list price; 0 for a model without one."""
|
||||
price = PRICES.get(model)
|
||||
if not price:
|
||||
return 0.0
|
||||
tokens = tokens_of(usage)
|
||||
return (tokens.input * price.input + tokens.write_5m * price.write_5m + tokens.write_1h * price.write_1h + tokens.read * price.read + tokens.output * price.output) / 1_000_000
|
||||
@@ -33,7 +33,7 @@ def levels_fit(item: int, likelihood: int, escape_and_impact: int, escape_and_im
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Route:
|
||||
"""A chunk's worker rung and the plan item that picked it, 0 for none. The item's L picked the worker's rung; reviewed_on, the higher of its E + I and the highest E + I the worker took in, picks the reviewers' and the judge's. A route holds only levels that levels_fit, so no rung is picked from a level off its scale.
|
||||
"""A chunk's worker rung and the plan item that picked it, 0 for none. The item's L picked the worker's rung; reviewed_on, the higher of its E + I and the highest E + I the worker took in, picks the reviewers'. A route holds only levels that levels_fit, so no rung is picked from a level off its scale.
|
||||
|
||||
unfinished counts the unfinished verdicts towards the next one-rung step; a reload hands it over with the rung.
|
||||
"""
|
||||
@@ -63,7 +63,7 @@ class Route:
|
||||
return dataclasses.replace(self, escape_and_impact_taken_in=escape_and_impact) if REVIEW_STEPS.get(escape_and_impact, 0) > REVIEW_STEPS.get(self.reviewed_on(), 0) else self
|
||||
|
||||
def reviewed_on(self) -> int:
|
||||
"""The E + I that picks the reviewers' and the judge's rung: the routed item's or the highest taken in, whichever is higher; 0 for neither."""
|
||||
"""The E + I that picks the reviewers' rung: the routed item's or the highest taken in, whichever is higher; 0 for neither."""
|
||||
return max(self.escape_and_impact, self.escape_and_impact_taken_in)
|
||||
|
||||
def worker_line(self) -> WorkerLine:
|
||||
|
||||
@@ -9,19 +9,17 @@ from release_plan.todo_table import LEVELS
|
||||
from review_rules.review_passes import REVIEWERS
|
||||
|
||||
OPUS = Rung("claude-opus-5-5", "medium")
|
||||
FABLE_LOW = Rung("claude-fable-5-2", "low")
|
||||
|
||||
|
||||
class Ladder(unittest.TestCase):
|
||||
def test_runs_from_sonnet_at_high_effort_to_fable_at_max_with_opus_at_medium_between(self):
|
||||
self.assertEqual(LADDER[0], Rung("claude-sonnet-5-5", "high"))
|
||||
self.assertEqual(LADDER[1], OPUS)
|
||||
self.assertEqual(LADDER[-1], Rung("claude-fable-5-1", "max"))
|
||||
self.assertEqual(len(LADDER), 6)
|
||||
def test_holds_each_rung_once_since_a_rung_s_position_sets_every_step(self):
|
||||
self.assertEqual(len(set(LADDER)), len(LADDER))
|
||||
|
||||
def test_puts_a_project_on_its_models_cheapest_rung_and_none_off_the_ladder(self):
|
||||
self.assertEqual(project_rung("claude-opus-5-5"), OPUS)
|
||||
self.assertEqual(project_rung("claude-sonnet-5-5"), Rung("claude-sonnet-5-5", "high"))
|
||||
self.assertEqual(project_rung("claude-fable-5-2"), FABLE_LOW)
|
||||
self.assertIsNone(project_rung("claude-opus-5"))
|
||||
self.assertIsNone(project_rung("opus"))
|
||||
|
||||
@@ -39,7 +37,7 @@ class Ladder(unittest.TestCase):
|
||||
self.assertEqual(worker_rung(LADDER[0], 1), LADDER[0])
|
||||
self.assertEqual(review_floor(Rung("claude-opus-5-5", "xhigh"), 8), LADDER[-1])
|
||||
self.assertEqual(stepped_up(LADDER[-1]), LADDER[-1])
|
||||
self.assertEqual(stepped_up(OPUS), Rung("claude-opus-5-5", "high"))
|
||||
self.assertEqual(stepped_up(OPUS), FABLE_LOW)
|
||||
|
||||
def test_steps_a_worker_for_every_level_on_ls_scale(self):
|
||||
self.assertEqual(set(WORKER_STEPS), set(range(1, LEVELS["L"] + 1)))
|
||||
@@ -49,7 +47,7 @@ class Ladder(unittest.TestCase):
|
||||
|
||||
def test_plans_on_the_rung_l_picks_but_never_below_the_projects(self):
|
||||
self.assertEqual(planning_rung(OPUS, 1), OPUS)
|
||||
self.assertEqual(planning_rung(OPUS, 4), Rung("claude-opus-5-5", "high"))
|
||||
self.assertEqual(planning_rung(OPUS, 4), FABLE_LOW)
|
||||
|
||||
def test_names_each_rung_by_a_family_the_agent_tool_takes(self):
|
||||
self.assertEqual({rung.agent_args().split(",")[0] for rung in LADDER}, {"model sonnet", "model opus", "model fable"})
|
||||
@@ -89,7 +87,7 @@ class Ladder(unittest.TestCase):
|
||||
self.assertEqual(Rung.from_agent("sonnet", ""), Rung("claude-sonnet-5-5", "high"))
|
||||
|
||||
def test_reads_an_unknown_family_or_an_effort_off_the_ladder_as_a_rung_off_it(self):
|
||||
for model, effort in (("gpt", "high"), ("gpt", ""), ("opus", "low"), ("haiku", "bogus")):
|
||||
for model, effort in (("gpt", "high"), ("gpt", ""), ("opus", "low"), ("opus", "high"), ("haiku", "bogus")):
|
||||
with self.subTest(model=model, effort=effort):
|
||||
self.assertNotIn(Rung.from_agent(model, effort), LADDER)
|
||||
self.assertEqual(Rung.from_agent("opus", "low"), Rung("claude-opus-5-5", "low"))
|
||||
@@ -97,9 +95,9 @@ class Ladder(unittest.TestCase):
|
||||
def test_puts_reviewers_on_the_highest_of_the_projects_rung_the_workers_and_the_one_e_plus_i_picks(self):
|
||||
sonnet, fable = LADDER[0], LADDER[-1]
|
||||
self.assertEqual(review_rung(OPUS, sonnet, 4, "stability"), OPUS)
|
||||
self.assertEqual(review_rung(OPUS, sonnet, 5, "stability"), Rung("claude-opus-5-5", "high"))
|
||||
self.assertEqual(review_rung(OPUS, sonnet, 5, "stability"), FABLE_LOW)
|
||||
self.assertEqual(review_rung(OPUS, fable, 5, "stability"), fable)
|
||||
self.assertEqual(review_rung(OPUS, Rung("claude-opus-5-5", "high"), 7, "stability"), Rung("claude-opus-5-5", "max"))
|
||||
self.assertEqual(review_rung(OPUS, FABLE_LOW, 7, "stability"), Rung("claude-opus-5-5", "xhigh"))
|
||||
|
||||
def test_keeps_the_seats_and_the_security_pass_on_the_projects_rung_whatever_the_worker_or_e_plus_i(self):
|
||||
self.assertEqual([review_rung(OPUS, LADDER[-1], 8, kind) for kind in (*REVIEWERS, "seat", "security")], [LADDER[-1]] * len(REVIEWERS) + [OPUS, OPUS])
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import pathlib
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from model_routing.ladder import LADDER
|
||||
from model_routing.prices import PRICES
|
||||
|
||||
|
||||
class Prices(unittest.TestCase):
|
||||
def test_every_model_on_the_ladder_has_a_price_since_a_model_without_one_is_left_out_of_every_figure(self):
|
||||
self.assertEqual(sorted({rung.model for rung in LADDER} - set(PRICES)), [])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -5,7 +5,7 @@ from model_routing.route import Route
|
||||
from model_routing.ladder import Rung
|
||||
|
||||
OPUS = Rung("claude-opus-5-5", "medium")
|
||||
FABLE = Rung("claude-fable-5-1", "max")
|
||||
FABLE = Rung("claude-fable-5-2", "max")
|
||||
|
||||
|
||||
class Chosen(unittest.TestCase):
|
||||
|
||||
+2
-2
@@ -9,7 +9,7 @@ sorts the items by release; within a release, question rows come first, then sec
|
||||
the rest, each group by score from highest, then by ID. Then it moves each blocker, an item
|
||||
another's Blocked by cell names, that ranks below an item it blocks to just above the first such
|
||||
item. Orders the details to match. Writes each item's R, and adds the Blocked by and R columns to a
|
||||
table without them. --check writes nothing and fails when the file is not ranked as it would be.
|
||||
table without them. --check doesn't write anything and fails when the file is not ranked as it would be.
|
||||
|
||||
A valid todo.md; ## Details and each item's detail are optional:
|
||||
|
||||
@@ -69,7 +69,7 @@ A valid todo.md; ## Details and each item's detail are optional:
|
||||
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.
|
||||
- ## Items holds only the table: an order goes in the scores or the Blocked by column.
|
||||
- The table holds the columns above. One missing L, E or I 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 C, A, G and Goals columns in place of L, E, I and Moves, still
|
||||
|
||||
@@ -2,14 +2,12 @@ import collections
|
||||
import dataclasses
|
||||
import re
|
||||
|
||||
from claude_code.entries import AssistantTurn, Entry, parse_entry, tool_calls, ToolCall, usage_count
|
||||
from claude_code.entries import AssistantTurn, Entry, messages, parse_entry, tool_calls, ToolCall, usage_count
|
||||
from git_cli.git_command import commits
|
||||
from reading_cost.shell_reads import Reads, shell_reads
|
||||
from command_lines.shell_command import resolved, simple_commands
|
||||
|
||||
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Reading:
|
||||
"""What the worker and its subagents took in before the worker's first commit: tokens counts the new input tokens, and files counts how often each tracked file was opened or searched, by its path in the checkout."""
|
||||
@@ -46,8 +44,7 @@ def commit_time(worker: list[Entry], home: str) -> str | None:
|
||||
|
||||
|
||||
def tokens_in(turns: list[AssistantTurn]) -> int:
|
||||
usages = {turn.message_id or turn.uuid: turn.usage for turn in turns}
|
||||
return sum(usage_count(usage, "input_tokens") + usage_count(usage, "cache_creation_input_tokens") for usage in usages.values())
|
||||
return sum(usage_count(first.usage, "input_tokens") + usage_count(first.usage, "cache_creation_input_tokens") for first, *_ in messages(turns))
|
||||
|
||||
|
||||
def reads_of(call: ToolCall, cwd: str, home: str) -> Reads:
|
||||
|
||||
@@ -2,10 +2,12 @@ import re
|
||||
import typing
|
||||
|
||||
FENCE = re.compile(r"^ {0,3}(`{3,}|~{3,})", re.M)
|
||||
HEADING = re.compile(r"^(#+)\s+(.*?)\s*$")
|
||||
|
||||
|
||||
def sections(text: str) -> dict[str, list[str]]:
|
||||
blocks: list[tuple[str | None, list[str]]] = []
|
||||
def fenced_lines(text: str) -> list[tuple[str, bool]]:
|
||||
"""Each line of text with whether a code fence holds it, the fence's own lines included. A fence closes only on a line of its own marker, as long as the opener or longer."""
|
||||
found = []
|
||||
opener = ""
|
||||
for line in text.splitlines():
|
||||
if fence := FENCE.match(line):
|
||||
@@ -14,7 +16,13 @@ def sections(text: str) -> dict[str, list[str]]:
|
||||
opener = marker
|
||||
elif marker[0] == opener[0] and len(marker) >= len(opener) and not line[fence.end():].strip():
|
||||
opener = ""
|
||||
fenced = bool(opener or fence)
|
||||
found.append((line, bool(opener or fence)))
|
||||
return found
|
||||
|
||||
|
||||
def sections(text: str) -> dict[str, list[str]]:
|
||||
blocks: list[tuple[str | None, list[str]]] = []
|
||||
for line, fenced in fenced_lines(text):
|
||||
if not fenced and line.startswith("## "):
|
||||
blocks.append((line.strip()[3:], []))
|
||||
elif not fenced and line.startswith("# "):
|
||||
@@ -28,6 +36,22 @@ def sections(text: str) -> dict[str, list[str]]:
|
||||
return found
|
||||
|
||||
|
||||
def section(text: str, title: str) -> list[str] | None:
|
||||
"""The lines under the first heading whose text fullmatches the pattern title, up to the next heading of its level or above, blank lines kept; None where none does."""
|
||||
found: list[str] | None = None
|
||||
level = 0
|
||||
for line, fenced in fenced_lines(text):
|
||||
heading = None if fenced else HEADING.match(line)
|
||||
if found is None:
|
||||
if heading and re.fullmatch(title, heading.group(2)):
|
||||
found, level = [], len(heading.group(1))
|
||||
elif heading and len(heading.group(1)) <= level:
|
||||
break
|
||||
else:
|
||||
found.append(line)
|
||||
return found
|
||||
|
||||
|
||||
# Blockquoted, so a passage holding blank lines still ends visibly where the text after it starts.
|
||||
def quoted(passage: str) -> str:
|
||||
return "\n".join(f"> {line}" for line in passage.splitlines())
|
||||
|
||||
@@ -21,6 +21,17 @@ class Sections(unittest.TestCase):
|
||||
self.assertEqual(markdown_text.quoted("merged\n\nPR #1"), "> merged\n> \n> PR #1")
|
||||
|
||||
|
||||
class Section(unittest.TestCase):
|
||||
def test_holds_deeper_headings_and_fenced_lines_and_ends_at_its_own_level(self):
|
||||
text = "# P\n\n## Scoring run\n\na\n\n### Sub\n\n```\n## fenced\n```\n\n## Next\n\nb\n"
|
||||
self.assertEqual(markdown_text.section(text, "Scoring run"), ["", "a", "", "### Sub", "", "```", "## fenced", "```", ""])
|
||||
self.assertIsNone(markdown_text.section(text, "Missing"))
|
||||
|
||||
def test_a_fence_closes_only_on_its_own_marker_here_too(self):
|
||||
text = "## A\n````md\n```\n## Quoted\n````\n## B\n"
|
||||
self.assertEqual(markdown_text.section(text, "A"), ["````md", "```", "## Quoted", "````"])
|
||||
|
||||
|
||||
class Listed(unittest.TestCase):
|
||||
def test_joins_names_with_commas_and_the_conjunction_before_the_last(self):
|
||||
self.assertEqual(markdown_text.listed(["a"], "and"), "a")
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""The formula todo.md states its score in: arithmetic over an item's scores, parsed so that it can hold nothing else, and evaluated to a float."""
|
||||
"""The formula todo.md states its score in: arithmetic over an item's scores, parsed so that it can't hold anything else, and evaluated to a float."""
|
||||
import ast
|
||||
import math
|
||||
|
||||
|
||||
@@ -37,7 +37,7 @@ 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 columns a reader does without: a missing BLOCKED_BY reads as blocked by nothing, a missing score column as that score unset, and a missing Score column as not yet ranked.
|
||||
# The columns a reader does without: a missing BLOCKED_BY reads as not blocked, a missing score column as that score unset, and a missing Score column as not yet ranked.
|
||||
optional: tuple[str, ...]
|
||||
# The columns rank_todo.py needs to rank a row, so no chunk starts on an item whose risk is unscored.
|
||||
risk_columns: tuple[str, ...]
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import pathlib
|
||||
|
||||
# Each module here checks a convention of the repo's own files, as a linter does, so it reads source or Markdown. technical-principles.md bans scanning source only in a test of a unit's behaviour.
|
||||
|
||||
# The checkout root.
|
||||
ROOT = pathlib.Path(__file__).resolve().parents[2]
|
||||
|
||||
@@ -1,16 +0,0 @@
|
||||
import pathlib
|
||||
import re
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from machine_load.slots import CPUS_PER_SLOT
|
||||
from repo_checks import ROOT
|
||||
|
||||
|
||||
class TestLine(unittest.TestCase):
|
||||
def test_the_readme_runs_the_tests_in_one_heavy_slots_cpus(self):
|
||||
workers = re.search(r"pytest==\S+ -n (\d+) bin`", (ROOT / "README.md").read_text(encoding="utf-8"))
|
||||
self.assertIsNotNone(workers, "README.md's Test line runs `pytest==X -n N bin`")
|
||||
self.assertEqual(int(workers.group(1)), CPUS_PER_SLOT)
|
||||
+64
-224
@@ -1,6 +1,6 @@
|
||||
"""Replay a review pass's archived rounds on the rungs below the project's, to find which rungs may run its reviewer: docs/decisions.md → `routing: a review pass runs below the project's rung only on a rung that a replay of its rounds shows finding every 🔴 and 🟡 the project's rung finds`.
|
||||
"""Replay a review pass's archived rounds on the rungs below the project's, to find which rungs may run its reviewer: docs/decisions.md → `routing: a review pass runs below the project's rung only on a rung whose replay of its rounds finds a share of their 🔴 and 🟡 findings no more than a margin below the project's rung's own replay`.
|
||||
|
||||
usage: review-replay <pass> <model>
|
||||
usage: review-replay <pass> <model> [--omit-claude-md]
|
||||
|
||||
<pass> is one of architecture, principles, overrides, stability, product-owner or prose.
|
||||
<model> is a project model on the routing ladder, such as claude-opus-5-5. The tool replays the
|
||||
@@ -13,65 +13,70 @@ shows the chunk's change. The prompt names the clone in place of the worktree it
|
||||
chunk has since removed. A round whose code it cannot find in this way is not replayed; stderr
|
||||
names it and why. The prompt also names a copy of the chunk's review folder in place of that
|
||||
folder, holding only the reports written after the chunk began and before the round did. A replay
|
||||
finds nothing where its prompt still names the review folder, or names a file there, other than a
|
||||
round's report, that the folder did not hold from the chunk's start until the round's.
|
||||
fails where its prompt still names the review folder, or names a file there, other than a round's
|
||||
report, that the folder did not hold from the chunk's start until the round's.
|
||||
|
||||
It first replays every round on the project's rung, the reference reviewer. Archived findings
|
||||
that the reference reviewer does not raise again may rest on code or rules that have changed
|
||||
since; no rung is held to them. It then replays the rounds where the reference raised any, on each
|
||||
rung below, highest first, down to the ladder's lowest, and stops at the first rung that misses
|
||||
one. For each replay, claude on the project's rung matches the report to the archived findings,
|
||||
and counts a finding only where the report raises it as 🔴 or 🟡. The tool prints each finding a
|
||||
rung missed and the lowest rung that, like each rung above it, missed none. That rung is the
|
||||
evidence for running the pass's reviewer on it; the decision above records each run.
|
||||
It replays every round twice on the project's rung. Even that rung finds only part of its own
|
||||
archived findings again, so the bar for a rung below is the mean share of those two replays, less
|
||||
a margin of 10 percentage points. Rounds that either replay failed on are left out, and where
|
||||
fewer than 8 remain, or the bar is zero or below, no rung is tried. It
|
||||
then replays the rounds on each rung below, highest first: the project's model at each lower
|
||||
effort, which the ladder leaves out, then each ladder rung down to the ladder's lowest. It stops at
|
||||
the first rung that doesn't qualify. A rung qualifies where it finds as many findings as reach the
|
||||
bar and misses no 🔴 that both replays on the project's rung found; a replay that failed on it
|
||||
finds none. For
|
||||
each replay, claude on the project's rung matches the report to the archived findings, and counts
|
||||
a finding only where the report raises it as 🔴 or 🟡. The tool prints each rung's count, each 🔴
|
||||
it missed, and the lowest rung that, like each rung above it, qualifies. That rung is the evidence
|
||||
for running the pass's reviewer on it; the decision above records each run.
|
||||
|
||||
With --omit-claude-md it tests instead whether the pass's reviewer may start without CLAUDE.md:
|
||||
docs/decisions.md → `agents/: a reviewer starts without CLAUDE.md only where a replay of its pass
|
||||
missed…`. It replays every round four times on the project's rung: three as archived, then once
|
||||
without the instruction files. The unchanged reviewer does not find the same findings twice, so
|
||||
each unchanged replay is a control: the tool prints how many findings it missed that both of the
|
||||
other two found. The replay without CLAUDE.md is held to the findings both of the first two found,
|
||||
and passes where it missed no more of them than the most any unchanged replay missed. It prints
|
||||
how many findings each replay found, how many the replay without CLAUDE.md is held to, and each of
|
||||
those it missed. A round that any of the four replays failed on is left out, and where the first
|
||||
two share no finding the last line says there is no evidence.
|
||||
Claude Code ignores an agent's `omitClaudeMd` where the agent runs the session, as it does in a
|
||||
replay, and runs no SubagentStart hook there. So the replay without CLAUDE.md turns the
|
||||
instruction files off in its settings and opens the prompt with what the hook hands a reviewer, and
|
||||
closes it with the header's line on the project principles.
|
||||
|
||||
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.
|
||||
review or match leaves its round out, except on a rung below the project's, where it finds
|
||||
none. Exit 1, saying why, on bad arguments, an unreadable archive or models file, no archived
|
||||
round to replay, or a usage limit.
|
||||
"""
|
||||
import dataclasses
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import typing
|
||||
|
||||
from transcript_archive.location import archive_root
|
||||
from rung_replay.command import arguments_or_exit, down_from, failed, limited_exit, projects_on
|
||||
from review_replay.rounds import authored_by, lost_inputs, report, reviewed_path, Round, round_from, sample, stamp_seconds
|
||||
from transcript_archive.project_key import checkout_of
|
||||
from claude_code.reply import claude_reply, Limited
|
||||
from review_replay.rounds import archived_rounds, Round, sample
|
||||
from rung_replay.command import arguments_or_exit, failed, limited_exit
|
||||
from review_replay.replay import codes_found, findings_replayed
|
||||
from review_replay.omit_comparison import compared
|
||||
from loop_effects.effects import Effects
|
||||
from failure import Failure
|
||||
from rung_replay.search import first_reply, replayed
|
||||
from claude_code.transcript import first_timestamped_line, read_transcript
|
||||
from model_routing.ladder import LADDER, project_rung, Rung
|
||||
from claude_code.entries import parse_entry, structured_output
|
||||
from review_rules.review_folder import REPORTS, review_folder
|
||||
from claude_code.reply import Limited
|
||||
from model_routing.ladder import project_rung, Rung
|
||||
from review_replay.recall import recall_report, recalled
|
||||
from review_rules.review_passes import ReviewedPass, REVIEWERS
|
||||
|
||||
TOOL = "review-replay"
|
||||
USAGE = f"{TOOL} <pass> <model>, <pass> one of {', '.join(REVIEWERS)} and <model> a model on the routing ladder"
|
||||
OMIT = "--omit-claude-md"
|
||||
USAGE = f"{TOOL} <pass> <model> [{OMIT}], <pass> one of {', '.join(REVIEWERS)} and <model> a model on the routing ladder"
|
||||
LATEST = 10
|
||||
MATCH_SCHEMA = {"type": "object", "properties": {"found": {"type": "array", "items": {"type": "integer"}}}, "required": ["found"], "additionalProperties": False}
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Code:
|
||||
"""Where a round's reviewer read the code, the commit it read, the default branch, and where that branch stood as the chunk began."""
|
||||
path: str
|
||||
reviewed: str
|
||||
default: str
|
||||
base: str
|
||||
|
||||
|
||||
def main(argv: list[str], env: typing.Mapping[str, str], home: pathlib.Path, effects: Effects) -> int:
|
||||
read = arguments_or_exit(TOOL, argv, __doc__, USAGE, pass_and_model)
|
||||
if isinstance(read, int):
|
||||
return read
|
||||
reviewed, project = read
|
||||
reviewed, project, without = read
|
||||
rounds = archived_rounds(REVIEWERS[reviewed], project.model, archive_root(home, env), home)
|
||||
if isinstance(rounds, Failure):
|
||||
return failed(TOOL, rounds.reason)
|
||||
@@ -79,195 +84,30 @@ def main(argv: list[str], env: typing.Mapping[str, str], home: pathlib.Path, eff
|
||||
if not codes:
|
||||
return failed(TOOL, f"no archived {reviewed} round of projects on {project.model} in {archive_root(home, env)} holds a 🔴 or 🟡 on code it can find")
|
||||
chosen = sample(list(codes), LATEST)
|
||||
# The project's rung is the reference, so the candidates start below it. They reach the ladder's lowest rung, below the lowest a worker routes to, since a pass may run below the worker's rung.
|
||||
candidates = down_from(project, LADDER[0])[1:]
|
||||
if without:
|
||||
report = compared(reviewed, project, chosen, lambda found, bare: findings_replayed(found, codes[found], project, project, home, effects, bare))
|
||||
if isinstance(report, Limited):
|
||||
return limited_exit(TOOL, report)
|
||||
print(report)
|
||||
return 0
|
||||
|
||||
def found_on(found: Round, rung: Rung) -> set[int] | Limited:
|
||||
return findings_found(found, codes[found], rung, project, home, effects)
|
||||
def replay_one(found: Round, rung: Rung) -> set[int] | Failure | Limited:
|
||||
matched = findings_replayed(found, codes[found], rung, project, home, effects, False)
|
||||
if isinstance(matched, Failure):
|
||||
print(f" {found.root} {found.at} on {rung} failed: {matched.reason}", file=sys.stderr, flush=True)
|
||||
return matched
|
||||
|
||||
replay = replayed(chosen, project, candidates, found_on, reproduced, f"{reviewed} rounds")
|
||||
if isinstance(replay, Limited):
|
||||
return limited_exit(TOOL, replay)
|
||||
print(report(reviewed, project.model, project, chosen, replay))
|
||||
recall = recalled(chosen, project, replay_one, f"{reviewed} rounds")
|
||||
if isinstance(recall, Limited):
|
||||
return limited_exit(TOOL, recall)
|
||||
print(recall_report(reviewed, project, recall))
|
||||
return 0
|
||||
|
||||
|
||||
def pass_and_model(argv: list[str]) -> tuple[ReviewedPass, Rung] | None:
|
||||
"""The pass and the project's rung of the model argv names, as `<pass> <model>`; None for any other argv."""
|
||||
if len(argv) != 2:
|
||||
def pass_and_model(argv: list[str]) -> tuple[ReviewedPass, Rung, bool] | None:
|
||||
"""The pass, the project's rung of the model, and whether OMIT follows, as argv names them in `<pass> <model> [--omit-claude-md]`; None for any other argv."""
|
||||
if argv[2:] not in ([], [OMIT]) or len(argv) < 2:
|
||||
return None
|
||||
reviewed = next((kind for kind in REVIEWERS if kind == argv[0]), None)
|
||||
project = project_rung(argv[1])
|
||||
return (reviewed, project) if reviewed and project else None
|
||||
|
||||
|
||||
def codes_found(rounds: list[Round], effects: Effects) -> dict[Round, Code]:
|
||||
"""The code each round reviewed, as code_of finds it; stderr names each round left out, and why."""
|
||||
codes = {}
|
||||
for found in rounds:
|
||||
if isinstance(code := code_of(found, effects), Failure):
|
||||
print(f"{found.root} {found.at} is left out: {code.reason}", file=sys.stderr, flush=True)
|
||||
else:
|
||||
codes[found] = code
|
||||
return codes
|
||||
|
||||
|
||||
def reproduced(_: Round, found: set[int]) -> list[int]:
|
||||
"""The indexes of the round's findings that a replay on the reference reviewer found, which each lower rung is held to."""
|
||||
return sorted(found)
|
||||
|
||||
|
||||
def archived_rounds(reviewer: str, model: str, root: pathlib.Path, home: pathlib.Path) -> list[Round] | Failure:
|
||||
projects = projects_on(model, home)
|
||||
if isinstance(projects, Failure):
|
||||
return projects
|
||||
found = []
|
||||
try:
|
||||
for key in projects:
|
||||
for chunk in sorted(path for path in (root / key).glob("*") if path.is_dir()):
|
||||
found += chunk_rounds(reviewer, checkout_of(key, home), chunk)
|
||||
except (OSError, UnicodeDecodeError, ValueError) as failure:
|
||||
return Failure(f"could not read the archive {root}: {failure}")
|
||||
return found
|
||||
|
||||
|
||||
def chunk_rounds(reviewer: str, checkout: str, chunk: pathlib.Path) -> list[Round]:
|
||||
copies = sorted(chunk.glob("*.jsonl"))
|
||||
began = parse_entry(first_timestamped_line(copies[0].read_bytes())) if copies else None
|
||||
if not began or not began.timestamp:
|
||||
return []
|
||||
found = []
|
||||
for meta in sorted(chunk.glob("session/*/subagents/*.meta.json")):
|
||||
described = json.loads(meta.read_text(encoding="utf-8"))
|
||||
if not isinstance(described, dict) or described.get("agentType") != reviewer:
|
||||
continue
|
||||
entries = read_transcript(str(meta.with_name(meta.name.removesuffix(".meta.json") + ".jsonl")))
|
||||
if not isinstance(entries, Failure) and (one := round_from(reviewer, checkout, stamp_seconds(began.timestamp), entries)):
|
||||
found.append(one)
|
||||
return found
|
||||
|
||||
|
||||
def code_of(found: Round, effects: Effects) -> Code | Failure:
|
||||
"""Where, and at which commits, found's reviewer read the code, as the archive lets it be found again: the folder rounds.reviewed_path guesses from the prompt, 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 of the archived findings, 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 = effects.git("symbolic-ref", "--short", "refs/remotes/origin/HEAD", cwd=found.root)
|
||||
if isinstance(default, Failure):
|
||||
return default
|
||||
default = default.strip().removeprefix("origin/")
|
||||
log = effects.git("log", "--format=%H %at", f"refs/remotes/origin/{default}", cwd=found.root)
|
||||
main_line = effects.git("log", "--first-parent", "--format=%H %at", f"refs/remotes/origin/{default}", cwd=found.root)
|
||||
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, project: Rung, home: pathlib.Path, effects: Effects) -> set[int] | Limited:
|
||||
"""The indexes of the round's findings that its replay on rung reports, as claude on the project's rung matches them."""
|
||||
reviewed: str | Failure | Limited = first_reply(lambda: review(found, code, rung, home, effects))
|
||||
if isinstance(reviewed, Limited):
|
||||
return reviewed
|
||||
matched: set[int] | Failure | Limited = reviewed if isinstance(reviewed, Failure) else first_reply(lambda: match(found.findings, reviewed, found.root, project, effects))
|
||||
if isinstance(matched, Failure):
|
||||
print(f" {found.root} {found.at} on {rung} found nothing: {matched.reason}", file=sys.stderr, flush=True)
|
||||
return set()
|
||||
return matched
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Copies:
|
||||
"""The throwaway copies a replay hands its reviewer: clone, of the project's checkout, and reports, of the chunk's review folder."""
|
||||
clone: str
|
||||
reports: str
|
||||
|
||||
|
||||
# The shell makes and removes the clone itself, and is tested on a temporary home as judge-replay's is; rounds.py's core takes the filesystem as an argument.
|
||||
def review(found: Round, code: Code, rung: Rung, home: pathlib.Path, effects: Effects) -> str | Failure | Limited:
|
||||
try:
|
||||
(home / REPORTS).mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
with tempfile.TemporaryDirectory(prefix="review-replay-", ignore_cleanup_errors=True) as clone, tempfile.TemporaryDirectory(prefix="review-replay-", dir=home / REPORTS, ignore_cleanup_errors=True) as reports:
|
||||
return reviewed_in(found, code, rung, Copies(clone, reports), home, effects)
|
||||
except OSError as failure:
|
||||
return Failure(f"could not prepare the replay: {failure}")
|
||||
|
||||
|
||||
def reviewed_in(found: Round, code: Code, rung: Rung, copies: Copies, home: pathlib.Path, effects: Effects) -> str | Failure | Limited:
|
||||
"""The report of found's reviewer on rung, replayed on code cloned into copies.clone, with its review folder copied into copies.reports."""
|
||||
folder = pathlib.Path(review_folder(str(home), code.path))
|
||||
copy_reports(found, folder, copies.reports)
|
||||
prompt = redirected(found.prompt, home, folder, code.path, copies)
|
||||
if isinstance(prompt, Failure):
|
||||
return prompt
|
||||
if lost := lost_inputs(prompt, copies.reports, lambda name: (pathlib.Path(copies.reports) / name).exists()):
|
||||
return Failure(f"the prompt names {', '.join(lost)}, which the review folder did not hold from the chunk's start until the round's")
|
||||
if isinstance(cloned := clone_reviewed(found, code, copies.clone, effects), Failure):
|
||||
return cloned
|
||||
reply = claude_reply(effects.claude, ["--agent", found.reviewer, *rung.flags()], copies.clone, prompt, "claude")
|
||||
if isinstance(reply, Failure | Limited):
|
||||
return reply
|
||||
return reply["result"] if isinstance(reply.get("result"), str) else Failure("the reviewer replied with no report")
|
||||
|
||||
|
||||
def copy_reports(found: Round, folder: pathlib.Path, reports: str) -> None:
|
||||
"""Copies into reports each report written to folder after found's chunk began and before its round did."""
|
||||
# The round's own report, any later one, and one from an earlier attempt at the item in the same worktree would each hand the reviewer the findings it is to find.
|
||||
for written in folder.iterdir() if folder.is_dir() else ():
|
||||
if written.is_file() and found.began <= written.stat().st_mtime < found.seconds:
|
||||
shutil.copy2(written, reports)
|
||||
|
||||
|
||||
def redirected(prompt: str, home: pathlib.Path, folder: pathlib.Path, worktree: str, copies: Copies) -> str | Failure:
|
||||
"""prompt naming copies.reports in place of the review folder, in either spelling, and copies.clone in place of the worktree; a Failure where it still names the review folder."""
|
||||
# Replace the folder's path first: outside home it contains the worktree's path, which replacing the worktree's would otherwise turn into the clone's.
|
||||
prompt = prompt.replace(str(folder), copies.reports).replace(f"~/{folder.relative_to(home)}", copies.reports).replace(worktree, copies.clone)
|
||||
# A spelling the rewrite misses, such as $HOME/, would leave the reviewer the live folder and the findings in it.
|
||||
if REPORTS in prompt.replace(copies.reports, ""):
|
||||
return Failure("the prompt names the review folder in a spelling the replay does not redirect")
|
||||
return prompt
|
||||
|
||||
|
||||
def clone_reviewed(found: Round, code: Code, clone: str, effects: Effects) -> Failure | None:
|
||||
"""Clones found's checkout into clone, on the commit its reviewer read, with the default branch where it stood as the chunk began."""
|
||||
for command in (
|
||||
("clone", "--quiet", "--shared", "--no-checkout", found.root, clone),
|
||||
("-C", clone, "update-ref", f"refs/remotes/origin/{code.default}", code.base),
|
||||
("-C", clone, "update-ref", f"refs/heads/{code.default}", code.base),
|
||||
("-C", clone, "checkout", "--quiet", *(("-B", found.branch) if found.branch and found.branch != code.default else ("--detach",)), code.reviewed),
|
||||
):
|
||||
if isinstance(ran := effects.git(*command, cwd=found.root), Failure):
|
||||
return ran
|
||||
return None
|
||||
|
||||
|
||||
def match(findings: tuple[str, ...], replay_report: str, root: str, rung: Rung, effects: Effects) -> set[int] | Failure | Limited:
|
||||
numbered = "\n\n".join(f"{n}. {finding}" for n, finding in enumerate(findings, 1))
|
||||
prompt = (
|
||||
"A code reviewer reported the numbered findings below. Another reviewer then reviewed the same change; its report follows them. "
|
||||
"List the number of each finding that the other report also raises as 🔴 or 🟡: the same defect, at the same place or from the same cause, however it is worded. "
|
||||
"A finding it raises only as 🟢 or ❓, or not at all, is not listed.\n\n"
|
||||
f"The findings:\n{numbered}\n\nThe other report:\n{replay_report}"
|
||||
)
|
||||
args = ["--json-schema", json.dumps(MATCH_SCHEMA), *rung.flags(), "--tools", ""]
|
||||
reply = claude_reply(effects.claude, args, root, prompt, "claude")
|
||||
if isinstance(reply, Failure | Limited):
|
||||
return reply
|
||||
output = structured_output(reply)
|
||||
numbers = output.get("found") if isinstance(output, dict) else None
|
||||
if not isinstance(numbers, list) or not all(isinstance(n, int) for n in numbers):
|
||||
return Failure(f"the match replied: {json.dumps(reply)}")
|
||||
return {n - 1 for n in numbers if 1 <= n <= len(findings)}
|
||||
return (reviewed, project, argv[2:] == [OMIT]) if reviewed and project else None
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
"""The experiment behind review-replay's --omit-claude-md: three replays of a pass's rounds with CLAUDE.md, one without, and the report that holds the one without to what the others found: docs/decisions.md → `agents/: a reviewer starts without CLAUDE.md only where a replay of its pass missed no more findings than the most an unchanged replay missed`."""
|
||||
import sys
|
||||
import typing
|
||||
|
||||
from failure import Failure
|
||||
from claude_code.reply import Limited
|
||||
from rung_replay.search import replayed_on
|
||||
from review_replay.rounds import Round
|
||||
from model_routing.ladder import Rung
|
||||
|
||||
|
||||
def compared(reviewed: str, project: Rung, chosen: list[Round], found_on: typing.Callable[[Round, bool], set[int] | Failure | Limited]) -> str | Limited:
|
||||
"""Replays chosen three times with CLAUDE.md and once without, as found_on(round, bare) finds, and reports the comparison of the rounds no replay failed on; the Limited where claude hit its usage limit."""
|
||||
runs: list[list[set[int] | Failure]] = []
|
||||
for bare in (False, False, False, True):
|
||||
def replay_one(one: Round, _: Rung, bare: bool = bare) -> set[int] | Failure | Limited:
|
||||
found = found_on(one, bare)
|
||||
if isinstance(found, Failure):
|
||||
print(f" {one.root} {one.at} {'without' if bare else 'with'} the instruction files failed, so the round is left out: {found.reason}", file=sys.stderr, flush=True)
|
||||
return found
|
||||
|
||||
found: list[set[int] | Failure] | Limited = replayed_on(chosen, project, replay_one, f"{reviewed} rounds {'without' if bare else 'with'} the instruction files")
|
||||
if isinstance(found, Limited):
|
||||
return found
|
||||
runs.append(found)
|
||||
# A failed replay found no findings, which would lower the bar where it had CLAUDE.md and count as misses where it had none.
|
||||
kept = rounds_without_failure(chosen, runs)
|
||||
first, second, third, without = ([found[run] for _, found in kept] for run in range(4))
|
||||
return comparison(reviewed, project, [one for one, _ in kept], (first, second, third), without, len(chosen) - len(kept))
|
||||
|
||||
|
||||
def rounds_without_failure(chosen: list[Round], runs: list[list[set[int] | Failure]]) -> list[tuple[Round, list[set[int]]]]:
|
||||
"""Each round of chosen that no run failed on, with what each run found in it."""
|
||||
kept = []
|
||||
for one, *found in zip(chosen, *runs):
|
||||
finds = [each for each in found if not isinstance(each, Failure)]
|
||||
if len(finds) == len(found):
|
||||
kept.append((one, finds))
|
||||
return kept
|
||||
|
||||
|
||||
def comparison(reviewed: str, reference: Rung, rounds: list[Round], with_it: tuple[list[set[int]], list[set[int]], list[set[int]]], without: list[set[int]], left_out: int) -> str:
|
||||
"""What the three replays with CLAUDE.md and the one without found in rounds. Each replay with it missed some findings the other two found: the control, the noise of an unchanged reviewer. The one without it is held to the findings the first two found, as the third is, and passes where it missed no more than the most a replay with it did. left_out counts the rounds a replay failed on, which rounds leaves out."""
|
||||
first, second, third = with_it
|
||||
|
||||
def shared(one: list[set[int]], other: list[set[int]]) -> list[set[int]]:
|
||||
return [found_by_one & found_by_other for found_by_one, found_by_other in zip(one, other)]
|
||||
|
||||
def missing(held: list[set[int]], run: list[set[int]]) -> list[tuple[Round, int]]:
|
||||
return [(found_round, index) for found_round, held_in_round, found in zip(rounds, held, run) for index in sorted(held_in_round - found)]
|
||||
|
||||
def count(run: list[set[int]]) -> int:
|
||||
return sum(len(found) for found in run)
|
||||
|
||||
both = shared(first, second)
|
||||
missed = missing(both, without)
|
||||
control = [len(missing(shared(one, other), run)) for run, one, other in ((first, second, third), (second, first, third), (third, first, second))]
|
||||
passes = len(missed) <= max(control)
|
||||
return "\n".join([
|
||||
f"Replayed {len(rounds)} {reviewed} rounds of {reference.model} projects, which hold {sum(len(found_round.findings) for found_round in rounds)} 🔴 and 🟡 findings, four times on {reference}: three with CLAUDE.md, one without.",
|
||||
*([f"Left out {left_out} more, which a replay failed on; stderr says why."] if left_out else []),
|
||||
f"With CLAUDE.md the three replays found {count(first)}, {count(second)} and {count(third)} of them, and missed {control[0]}, {control[1]} and {control[2]} of the findings that both of the other two found.",
|
||||
*([f"Without CLAUDE.md it found {count(without)} of them, and missed {len(missed)} of the {count(both)} findings that both of the first two found{':' if missed else '.'}"] if count(both) else [f"Without CLAUDE.md it found {count(without)} of them. No evidence: the first two replays with CLAUDE.md found none in common, so there is no finding to hold it to."]),
|
||||
*(f" {found_round.root} {found_round.at}: {found_round.findings[index].splitlines()[0]}" for found_round, index in missed),
|
||||
*([f"It {'passes' if passes else 'fails'}: {len(missed)} missed is {'no more' if passes else 'more'} than the most a replay with CLAUDE.md missed, {max(control)}."] if count(both) else []),
|
||||
])
|
||||
@@ -0,0 +1,127 @@
|
||||
"""The bar review-replay holds a rung to, and its report: docs/decisions.md → `routing: a review pass runs below the project's rung only on a rung whose replay of its rounds finds a share of their 🔴 and 🟡 findings no more than a margin below the project's rung's own replay`."""
|
||||
import dataclasses
|
||||
from rung_replay.command import down_from
|
||||
from failure import Failure
|
||||
from fractions import Fraction
|
||||
from review_replay.rounds import is_red, Round
|
||||
from model_routing.ladder import LADDER, Rung
|
||||
from claude_code.reply import Limited
|
||||
import math
|
||||
from rung_replay.search import replayed_on
|
||||
import typing
|
||||
|
||||
# A rung qualifies with a share of the archived findings up to this far below the project's rung's. The project's rung found 69 to 78% of its own findings again, and its two replays of the same rounds differed by up to 4 points.
|
||||
MARGIN = Fraction(1, 10)
|
||||
# The fewest rounds a rung is tried on: 8 of the 10 the tool samples, so up to two may fail on the project's rung.
|
||||
ENOUGH_ROUNDS = 8
|
||||
# Lowest first, as Claude Code's --effort takes them.
|
||||
EFFORTS = ("low", "medium", "high", "xhigh", "max")
|
||||
# The two replays on the project's rung. Each lists, round by round, the indexes of the findings it found.
|
||||
Reference = tuple[list[set[int]], list[set[int]]]
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class RungRecall:
|
||||
"""A rung's replay: how many of the archived findings it found, and each 🔴 it missed that both of the project's rung's replays found, as a round and the finding's index."""
|
||||
rung: Rung
|
||||
found: int
|
||||
missed_red: list[tuple[Round, int]]
|
||||
qualifies: bool
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Recall:
|
||||
"""rounds, the rounds no replay on the project's rung failed on; left_out, how many more it failed on; tried, each candidate tried, highest first; lowest, the lowest that, like each above it, qualifies."""
|
||||
rounds: list[Round]
|
||||
reference: Reference
|
||||
left_out: int
|
||||
tried: list[RungRecall]
|
||||
lowest: Rung | None
|
||||
|
||||
|
||||
def candidates(project: Rung) -> list[Rung]:
|
||||
"""The rungs tried below the project's, highest first: its model at each lower effort, which the ladder leaves out, then each ladder rung below it, down to the ladder's lowest. That reaches below the lowest a worker routes to, since a pass may run below the worker's rung."""
|
||||
lower_efforts = [Rung(project.model, effort) for effort in reversed(EFFORTS[:EFFORTS.index(project.effort)])]
|
||||
return lower_efforts + down_from(project, LADDER[0])[1:]
|
||||
|
||||
|
||||
def enough(rounds: list[Round]) -> bool:
|
||||
return len(rounds) >= ENOUGH_ROUNDS
|
||||
|
||||
|
||||
def count(found: list[set[int]]) -> int:
|
||||
return sum(map(len, found))
|
||||
|
||||
|
||||
def held(rounds: list[Round]) -> int:
|
||||
"""How many findings rounds hold."""
|
||||
return sum(len(one.findings) for one in rounds)
|
||||
|
||||
|
||||
def mean_share(rounds: list[Round], reference: Reference) -> Fraction:
|
||||
"""The mean share of rounds' findings that the project's rung's two replays found; rounds is never empty, and each holds a finding."""
|
||||
return Fraction(count(reference[0]) + count(reference[1]), 2 * held(rounds))
|
||||
|
||||
|
||||
def needed(rounds: list[Round], reference: Reference) -> int:
|
||||
"""How many of rounds' findings a rung needs to find: the fewest that reach the project's rung's mean share less MARGIN. Zero or below, no rung is tried, since a rung that found none would qualify."""
|
||||
return math.ceil((mean_share(rounds, reference) - MARGIN) * held(rounds))
|
||||
|
||||
|
||||
def tried(rung: Rung, rounds: list[Round], reference: Reference, found: list[set[int]]) -> RungRecall:
|
||||
"""rung's recall, from the indexes of each round's findings it found. It qualifies finding as many as needed, missing no 🔴 that both of the project's rung's replays found."""
|
||||
missed_red = [(one, index) for one, first, second, got in zip(rounds, *reference, found) for index in sorted((first & second) - got) if is_red(one.findings[index])]
|
||||
return RungRecall(rung, count(found), missed_red, 0 < needed(rounds, reference) <= count(found) and not missed_red)
|
||||
|
||||
|
||||
def recall_report(reviewed: str, project: Rung, recall: Recall) -> str:
|
||||
rounds, (first, second) = recall.rounds, recall.reference
|
||||
lines = [
|
||||
f"Replayed {len(rounds)} {reviewed} rounds of {project.model} projects, which hold {held(rounds)} 🔴 and 🟡 findings, twice on the project's rung, {project}.",
|
||||
*([f"Left out {recall.left_out} more, which a replay on the project's rung failed on; stderr says why."] if recall.left_out else []),
|
||||
]
|
||||
if not enough(rounds):
|
||||
return "\n".join([*lines, f"No rung tried: fewer than {ENOUGH_ROUNDS} rounds were replayed on the project's rung without a failure."])
|
||||
if needed(rounds, recall.reference) <= 0:
|
||||
return "\n".join([*lines, "No rung tried: the project's rung found too few of them to hold a rung to."])
|
||||
lines.append(f"The project's rung found {count(first)} and then {count(second)} of the {held(rounds)}, {percent(mean_share(rounds, recall.reference))} on average, so a rung qualifies finding {needed(rounds, recall.reference)} or more of them, missing no 🔴 that both of its replays found.")
|
||||
for one in recall.tried:
|
||||
verdict = "it qualifies" if one.qualifies else "it doesn't qualify"
|
||||
lines += [f"{one.rung} found {one.found}, {percent(Fraction(one.found, held(rounds)))}, and missed {len(one.missed_red) or 'no'} such 🔴: {verdict}.", *(f" {at.root} {at.at}: {at.findings[index].splitlines()[0]}" for at, index in one.missed_red)]
|
||||
lowest = recall.lowest or "none below the project's rung"
|
||||
lines.append(f"Lowest rung that qualifies: {lowest}")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def percent(fraction: Fraction) -> str:
|
||||
return f"{float(fraction):.0%}"
|
||||
|
||||
|
||||
def recalled(chosen: list[Round], project: Rung, replay_one: typing.Callable[[Round, Rung], set[int] | Failure | Limited], what: str) -> Recall | Limited:
|
||||
"""Replays chosen twice on the project's rung, then each candidate, highest first, on the rounds neither of those failed on, until one doesn't qualify."""
|
||||
runs: list[list[set[int] | Failure]] = []
|
||||
for _ in range(2):
|
||||
found: list[set[int] | Failure] | Limited = replayed_on(chosen, project, replay_one, what)
|
||||
if isinstance(found, Limited):
|
||||
return found
|
||||
runs.append(found)
|
||||
rounds: list[Round] = []
|
||||
reference: Reference = ([], [])
|
||||
for one, first, second in zip(chosen, *runs):
|
||||
if not isinstance(first, Failure) and not isinstance(second, Failure):
|
||||
rounds.append(one)
|
||||
reference[0].append(first)
|
||||
reference[1].append(second)
|
||||
recalls: list[RungRecall] = []
|
||||
lowest = None
|
||||
for rung in candidates(project) if enough(rounds) and needed(rounds, reference) > 0 else []:
|
||||
on_rung: list[set[int] | Failure] | Limited = replayed_on(rounds, rung, replay_one, what)
|
||||
if isinstance(on_rung, Limited):
|
||||
return on_rung
|
||||
# A failed replay on a candidate found none, so it lowers that rung's count and never lifts it to what a rung needs.
|
||||
one = tried(rung, rounds, reference, [set() if isinstance(found, Failure) else found for found in on_rung])
|
||||
recalls.append(one)
|
||||
if not one.qualifies:
|
||||
break
|
||||
lowest = rung
|
||||
return Recall(rounds, reference, len(chosen) - len(rounds), recalls, lowest)
|
||||
@@ -0,0 +1,179 @@
|
||||
"""Replay one archived review round on one rung: the code the round reviewed, found again in a throwaway clone, the reviewer's report on it, and the match of that report to the round's archived findings: docs/decisions.md → `routing: a review pass runs below the project's rung only on a rung whose replay of its rounds finds a share of their 🔴 and 🟡 findings no more than a margin below the project's rung's own replay`."""
|
||||
import dataclasses
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
from review_replay.rounds import authored_by, lost_inputs, reviewed_path, Round
|
||||
from claude_code.reply import claude_reply, Limited
|
||||
from git_cli.git_repo import default_ref
|
||||
from loop_effects.effects import Effects
|
||||
from failure import Failure
|
||||
from rung_replay.search import first_reply
|
||||
from review_rules.reviewer_context import principles_line, reviewer_context
|
||||
from review_rules.review_folder import REPORTS, review_folder
|
||||
from model_routing.ladder import Rung
|
||||
from claude_code.entries import structured_output
|
||||
|
||||
# Starts claude without its instruction files, as `omitClaudeMd` starts a subagent.
|
||||
NO_CLAUDE_MD = ["--settings", json.dumps({"env": {"CLAUDE_CODE_DISABLE_CLAUDE_MDS": "1"}})]
|
||||
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 codes_found(rounds: list[Round], effects: Effects) -> dict[Round, Code]:
|
||||
"""The code each round reviewed, as code_of finds it; stderr names each round left out, and why."""
|
||||
codes = {}
|
||||
for found in rounds:
|
||||
if isinstance(code := code_of(found, effects), Failure):
|
||||
print(f"{found.root} {found.at} is left out: {code.reason}", file=sys.stderr, flush=True)
|
||||
else:
|
||||
codes[found] = code
|
||||
return codes
|
||||
|
||||
|
||||
def 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 folder rounds.reviewed_path guesses from the prompt, 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 shows every rung the same wrong code: the project's rung finds fewer of that round's archived findings, which lowers the bar, and the rungs below find fewer too.
|
||||
"""
|
||||
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")
|
||||
ref = default_ref(cwd=found.root, guarded=True, run=effects.git)
|
||||
if isinstance(ref, Failure):
|
||||
return ref
|
||||
default = ref.removeprefix("origin/")
|
||||
log = effects.git("log", "--format=%H %at", f"refs/remotes/origin/{default}", cwd=found.root)
|
||||
main_line = effects.git("log", "--first-parent", "--format=%H %at", f"refs/remotes/origin/{default}", cwd=found.root)
|
||||
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_replayed(found: Round, code: Code, rung: Rung, project: Rung, home: pathlib.Path, effects: Effects, bare: bool) -> set[int] | Failure | Limited:
|
||||
"""The indexes of the round's findings that its replay on rung reports, as claude on the project's rung matches them, or the Failure of the review or the match; where bare, the replay runs without CLAUDE.md, as `launch` says."""
|
||||
reviewed: str | Failure | Limited = first_reply(lambda: review(found, code, rung, home, effects, bare))
|
||||
if isinstance(reviewed, (Failure, Limited)):
|
||||
return reviewed
|
||||
return first_reply(lambda: match(found.findings, reviewed, found.root, project, effects))
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Copies:
|
||||
"""The throwaway copies a replay hands its reviewer: clone, of the project's checkout, and reports, of the chunk's review folder."""
|
||||
clone: str
|
||||
reports: str
|
||||
|
||||
|
||||
# The shell makes and removes the clone itself, and is tested on a temporary home as judge-replay's is.
|
||||
def review(found: Round, code: Code, rung: Rung, home: pathlib.Path, effects: Effects, bare: bool) -> str | Failure | Limited:
|
||||
try:
|
||||
(home / REPORTS).mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
with tempfile.TemporaryDirectory(prefix="review-replay-", ignore_cleanup_errors=True) as clone, tempfile.TemporaryDirectory(prefix="review-replay-", dir=home / REPORTS, ignore_cleanup_errors=True) as reports:
|
||||
return reviewed_in(found, code, rung, Copies(clone, reports), home, effects, bare)
|
||||
except OSError as failure:
|
||||
return Failure(f"could not prepare the replay: {failure}")
|
||||
|
||||
|
||||
def reviewed_in(found: Round, code: Code, rung: Rung, copies: Copies, home: pathlib.Path, effects: Effects, bare: bool) -> str | Failure | Limited:
|
||||
"""The report of found's reviewer on rung, replayed on code cloned into copies.clone, with its review folder copied into copies.reports; without CLAUDE.md where bare."""
|
||||
folder = pathlib.Path(review_folder(str(home), code.path))
|
||||
copy_reports(found, folder, copies.reports)
|
||||
prompt = redirected(found.prompt, home, folder, code.path, copies)
|
||||
if isinstance(prompt, Failure):
|
||||
return prompt
|
||||
if lost := lost_inputs(prompt, copies.reports, lambda name: (pathlib.Path(copies.reports) / name).exists()):
|
||||
return Failure(f"the prompt names {', '.join(lost)}, which the review folder did not hold from the chunk's start until the round's")
|
||||
if isinstance(cloned := clone_reviewed(found, code, copies.clone, effects), Failure):
|
||||
return cloned
|
||||
launched = launch(found.reviewer, rung, prompt, copies.clone, home, bare)
|
||||
if isinstance(launched, Failure):
|
||||
return launched
|
||||
reply = claude_reply(effects.claude, launched[0], copies.clone, launched[1], "claude")
|
||||
if isinstance(reply, Failure | Limited):
|
||||
return reply
|
||||
return reply["result"] if isinstance(reply.get("result"), str) else Failure("the reviewer replied with no report")
|
||||
|
||||
|
||||
def launch(reviewer: str, rung: Rung, prompt: str, clone: str, home: pathlib.Path, bare: bool) -> tuple[list[str], str] | Failure:
|
||||
"""claude's arguments and prompt for reviewer on rung. Where bare, it starts without CLAUDE.md, and the prompt holds what the SubagentStart hook and the header's last line hand such a reviewer."""
|
||||
args = ["--agent", reviewer, *rung.flags()]
|
||||
if not bare:
|
||||
return args, prompt
|
||||
context = reviewer_context(home)
|
||||
if isinstance(context, Failure):
|
||||
return context
|
||||
return [*args, *NO_CLAUDE_MD], "\n".join([f"{context}\n\n{prompt}", *([principles] if (principles := principles_line(clone)) else [])])
|
||||
|
||||
|
||||
def copy_reports(found: Round, folder: pathlib.Path, reports: str) -> None:
|
||||
"""Copies into reports each report written to folder after found's chunk began and before its round did."""
|
||||
# The round's own report, any later one, and one from an earlier attempt at the item in the same worktree would each hand the reviewer the findings it is to find.
|
||||
for written in folder.iterdir() if folder.is_dir() else ():
|
||||
if written.is_file() and found.began <= written.stat().st_mtime < found.seconds:
|
||||
shutil.copy2(written, reports)
|
||||
|
||||
|
||||
def redirected(prompt: str, home: pathlib.Path, folder: pathlib.Path, worktree: str, copies: Copies) -> str | Failure:
|
||||
"""prompt naming copies.reports in place of the review folder, in either spelling, and copies.clone in place of the worktree; a Failure where it still names the review folder."""
|
||||
# Replace the folder's path first: outside home it contains the worktree's path, which replacing the worktree's would otherwise turn into the clone's.
|
||||
prompt = prompt.replace(str(folder), copies.reports).replace(f"~/{folder.relative_to(home)}", copies.reports).replace(worktree, copies.clone)
|
||||
# A spelling the rewrite misses, such as $HOME/, would leave the reviewer the live folder and the findings in it.
|
||||
if REPORTS in prompt.replace(copies.reports, ""):
|
||||
return Failure("the prompt names the review folder in a spelling the replay does not redirect")
|
||||
return prompt
|
||||
|
||||
|
||||
def clone_reviewed(found: Round, code: Code, clone: str, effects: Effects) -> Failure | None:
|
||||
"""Clones found's checkout into clone, on the commit its reviewer read, with the default branch where it stood as the chunk began."""
|
||||
for command in (
|
||||
("clone", "--quiet", "--shared", "--no-checkout", found.root, clone),
|
||||
("-C", clone, "update-ref", f"refs/remotes/origin/{code.default}", code.base),
|
||||
("-C", clone, "update-ref", f"refs/heads/{code.default}", code.base),
|
||||
("-C", clone, "checkout", "--quiet", *(("-B", found.branch) if found.branch and found.branch != code.default else ("--detach",)), code.reviewed),
|
||||
):
|
||||
if isinstance(ran := effects.git(*command, cwd=found.root), Failure):
|
||||
return ran
|
||||
return None
|
||||
|
||||
|
||||
def match(findings: tuple[str, ...], replay_report: str, root: str, rung: Rung, effects: Effects) -> set[int] | Failure | Limited:
|
||||
numbered = "\n\n".join(f"{n}. {finding}" for n, finding in enumerate(findings, 1))
|
||||
prompt = (
|
||||
"A code reviewer reported the numbered findings below. Another reviewer then reviewed the same change; its report follows them. "
|
||||
"List the number of each finding that the other report also raises as 🔴 or 🟡: the same defect, at the same place or from the same cause, however it is worded. "
|
||||
"A finding it raises only as 🟢 or ❓, or not at all, is not listed.\n\n"
|
||||
f"The findings:\n{numbered}\n\nThe other report:\n{replay_report}"
|
||||
)
|
||||
args = ["--json-schema", json.dumps(MATCH_SCHEMA), *rung.flags(), "--tools", ""]
|
||||
reply = claude_reply(effects.claude, args, root, prompt, "claude")
|
||||
if isinstance(reply, Failure | Limited):
|
||||
return reply
|
||||
output = structured_output(reply)
|
||||
numbers = output.get("found") if isinstance(output, dict) else None
|
||||
if not isinstance(numbers, list) or not all(isinstance(n, int) for n in numbers):
|
||||
return Failure(f"the match replied: {json.dumps(reply)}")
|
||||
return {n - 1 for n in numbers if 1 <= n <= len(findings)}
|
||||
+41
-18
@@ -1,13 +1,16 @@
|
||||
"""Which archived rounds of a review pass to replay, the code each reviewed, and the report: docs/decisions.md → `routing: a review pass runs below the project's rung only on a rung that a replay of its rounds shows finding every 🔴 and 🟡 the project's rung finds`."""
|
||||
"""Which archived rounds of a review pass to replay, and the code each reviewed: docs/decisions.md → `routing: a review pass runs below the project's rung only on a rung whose replay of its rounds finds a share of their 🔴 and 🟡 findings no more than a margin below the project's rung's own replay`."""
|
||||
import dataclasses
|
||||
import datetime
|
||||
import json
|
||||
import pathlib
|
||||
import re
|
||||
import typing
|
||||
|
||||
from claude_code.entries import AssistantTurn, Entry, Text, UserText
|
||||
from rung_replay.search import Replay
|
||||
from model_routing.ladder import Rung
|
||||
from claude_code.entries import AssistantTurn, Entry, parse_entry, Text, UserText
|
||||
from transcript_archive.project_key import checkout_of
|
||||
from failure import Failure
|
||||
from claude_code.transcript import first_timestamped_line, read_transcript
|
||||
from rung_replay.command import projects_on
|
||||
|
||||
# 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*(?:🔴|🟡)")
|
||||
@@ -34,6 +37,12 @@ class Round:
|
||||
return stamp_seconds(self.at)
|
||||
|
||||
|
||||
def is_red(finding: str) -> bool:
|
||||
"""Whether finding, which opens with a line FINDING matches, is raised as 🔴: by the mark it opens with, whatever marks its text names."""
|
||||
mark = FINDING.match(finding)
|
||||
return mark is not None and mark[0].endswith("🔴")
|
||||
|
||||
|
||||
def round_from(reviewer: str, root: str, began: float, entries: list[Entry]) -> Round | None:
|
||||
"""The round a reviewer's transcript holds: its first entry's prompt, and its last text. None without a 🔴 or 🟡 finding to hold a rung to."""
|
||||
reports = [part.text for entry in entries if isinstance(entry, AssistantTurn) for part in entry.parts if isinstance(part, Text) and part.text]
|
||||
@@ -102,17 +111,31 @@ def sample(rounds: list[Round], latest: int) -> list[Round]:
|
||||
return sorted(rounds, key=lambda found: (found.seconds, found.root))[-latest:]
|
||||
|
||||
|
||||
def report(reviewed: str, model: str, reference: Rung, rounds: list[Round], replay: Replay[Round, int, set[int]]) -> str:
|
||||
total = sum(len(found_round.findings) for found_round in rounds)
|
||||
lines = [
|
||||
f"Replayed {len(rounds)} {reviewed} rounds of {model} projects, holding {total} 🔴 and 🟡 findings.",
|
||||
f"The reference reviewer, {reference}, found {sum(len(found) for found in replay.on_reference)} of them.",
|
||||
]
|
||||
for tried in replay.tried:
|
||||
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)
|
||||
def archived_rounds(reviewer: str, model: str, root: pathlib.Path, home: pathlib.Path) -> list[Round] | Failure:
|
||||
projects = projects_on(model, home)
|
||||
if isinstance(projects, Failure):
|
||||
return projects
|
||||
found = []
|
||||
try:
|
||||
for key in projects:
|
||||
for chunk in sorted(path for path in (root / key).glob("*") if path.is_dir()):
|
||||
found += chunk_rounds(reviewer, checkout_of(key, home), chunk)
|
||||
except (OSError, UnicodeDecodeError, ValueError) as failure:
|
||||
return Failure(f"could not read the archive {root}: {failure}")
|
||||
return found
|
||||
|
||||
|
||||
def chunk_rounds(reviewer: str, checkout: str, chunk: pathlib.Path) -> list[Round]:
|
||||
copies = sorted(chunk.glob("*.jsonl"))
|
||||
began = parse_entry(first_timestamped_line(copies[0].read_bytes())) if copies else None
|
||||
if not began or not began.timestamp:
|
||||
return []
|
||||
found = []
|
||||
for meta in sorted(chunk.glob("session/*/subagents/*.meta.json")):
|
||||
described = json.loads(meta.read_text(encoding="utf-8"))
|
||||
if not isinstance(described, dict) or described.get("agentType") != reviewer:
|
||||
continue
|
||||
entries = read_transcript(str(meta.with_name(meta.name.removesuffix(".meta.json") + ".jsonl")))
|
||||
if not isinstance(entries, Failure) and (one := round_from(reviewer, checkout, stamp_seconds(began.timestamp), entries)):
|
||||
found.append(one)
|
||||
return found
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
import pathlib
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from review_replay.recall import candidates, needed, Recall, recall_report, tried
|
||||
from review_replay.rounds import is_red, Round
|
||||
from model_routing.ladder import Rung
|
||||
|
||||
REFERENCE = Rung("claude-opus-5-5", "medium")
|
||||
LOW = Rung("claude-opus-5-5", "low")
|
||||
SONNET = Rung("claude-sonnet-5-5", "high")
|
||||
|
||||
|
||||
def a_round(at, findings):
|
||||
return Round("prose-reviewer", "/code/p", "x", f"2026-10-14T10:00:0{at}Z", 0, "Review it.", tuple(findings))
|
||||
|
||||
|
||||
# Ten findings over two rounds; the project's rung found 8 and then 6, so its share is 70%, the bar 60% and a rung needs 6. Both found the first round's 🔴, and only the first found the second's.
|
||||
ROUNDS = [a_round(1, ("🔴 a", "🟡 b", "🟡 c", "🟡 d", "🟡 e")), a_round(2, ("🔴 f\nmore", "🟡 g", "🟡 h", "🟡 i", "🟡 j"))]
|
||||
FIRST = [{0, 1, 2, 3}, {0, 1, 2, 3}]
|
||||
SECOND = [{0, 1, 2}, {1, 2, 3}]
|
||||
# The project's rung found 1 and then 1 of the 10, so the bar is zero.
|
||||
TENTH = ([{0}, set()], [{0}, set()])
|
||||
|
||||
|
||||
class Candidates(unittest.TestCase):
|
||||
def test_tries_the_project_models_lower_efforts_first_then_the_ladder_below_it(self):
|
||||
self.assertEqual(candidates(REFERENCE), [LOW, SONNET])
|
||||
|
||||
def test_tries_each_ladder_rung_below_highest_first(self):
|
||||
self.assertEqual(candidates(Rung("claude-fable-5-2", "low")), [REFERENCE, SONNET])
|
||||
|
||||
def test_tries_each_lower_effort_of_the_ladders_lowest_rung(self):
|
||||
self.assertEqual(candidates(SONNET), [Rung("claude-sonnet-5-5", "medium"), Rung("claude-sonnet-5-5", "low")])
|
||||
|
||||
|
||||
class Tried(unittest.TestCase):
|
||||
def test_qualifies_a_rung_no_more_than_the_margin_below_the_project_rungs_share_that_misses_no_red_found_both_times(self):
|
||||
found = tried(LOW, ROUNDS, (FIRST, SECOND), [{0, 1, 2}, {0, 1, 2}])
|
||||
self.assertEqual((found.found, found.missed_red, found.qualifies), (6, [], True))
|
||||
|
||||
def test_fails_a_rung_below_the_bar(self):
|
||||
found = tried(LOW, ROUNDS, (FIRST, SECOND), [{0, 1}, {0, 3}])
|
||||
self.assertEqual((found.found, found.missed_red, found.qualifies), (4, [], False))
|
||||
|
||||
def test_fails_a_rung_that_misses_a_red_found_both_times_and_only_such_a_red(self):
|
||||
above_the_bar = [{1, 2, 3, 4}, {0, 1, 2, 3}]
|
||||
found = tried(LOW, ROUNDS, (FIRST, SECOND), above_the_bar)
|
||||
self.assertEqual((found.found, found.missed_red, found.qualifies), (8, [(ROUNDS[0], 0)], False))
|
||||
# The first round's 🔴 is found both times; a yellow found both times, such as its b, may be missed.
|
||||
self.assertTrue(tried(LOW, ROUNDS, (FIRST, SECOND), [{0, 2, 3, 4}, {0, 2, 3, 4}]).qualifies)
|
||||
# The second round's 🔴, which only the first replay found, may be missed too.
|
||||
self.assertTrue(tried(LOW, ROUNDS, (FIRST, SECOND), [{0, 1, 2, 3}, {1, 2, 3}]).qualifies)
|
||||
|
||||
def test_fails_every_rung_where_the_bar_is_zero_or_below(self):
|
||||
self.assertFalse(tried(LOW, ROUNDS, ([set(), set()], [set(), set()]), [{0}, {0}]).qualifies)
|
||||
self.assertFalse(tried(LOW, ROUNDS, TENTH, [{0}, {0}]).qualifies)
|
||||
|
||||
def test_rounds_the_findings_a_rung_needs_up(self):
|
||||
# 33 findings, of which the project's rung found 24 and then 23: the bar is 61.2%, which 20 findings, 60.6%, don't reach.
|
||||
rounds = [a_round(1, ["🟡 a"] * 33)]
|
||||
reference = ([set(range(24))], [set(range(23))])
|
||||
self.assertEqual(needed(rounds, reference), 21)
|
||||
self.assertFalse(tried(LOW, rounds, reference, [set(range(20))]).qualifies)
|
||||
self.assertTrue(tried(LOW, rounds, reference, [set(range(21))]).qualifies)
|
||||
|
||||
def test_lets_a_rung_miss_a_yellow_that_mentions_a_red(self):
|
||||
rounds = [a_round(1, ("### 🟡 `SKILL.md:80`: the rule says a 🔴 in round 2 escalates", "🟡 b"))]
|
||||
self.assertFalse(is_red(rounds[0].findings[0]))
|
||||
self.assertTrue(is_red("### 1. **🔴 a\nwhich is no 🟡"))
|
||||
found = tried(LOW, rounds, ([{0, 1}], [{0, 1}]), [{1}])
|
||||
self.assertEqual((found.missed_red, found.qualifies), ([], False))
|
||||
self.assertEqual(tried(LOW, rounds, ([{0, 1}], [{0}]), [{1}]).missed_red, [])
|
||||
|
||||
|
||||
class RecallReport(unittest.TestCase):
|
||||
# Eight rounds, enough to try a rung.
|
||||
EIGHT = (ROUNDS * 4, (FIRST * 4, SECOND * 4))
|
||||
|
||||
def test_states_the_bar_each_rung_tried_each_red_it_missed_and_the_lowest_that_qualifies(self):
|
||||
rounds, reference = self.EIGHT
|
||||
low = tried(LOW, rounds, reference, [{0, 1, 2}, {0, 1, 2}] * 4)
|
||||
sonnet = tried(SONNET, rounds, reference, [{1, 2, 3, 4}, {0}] * 4)
|
||||
lines = recall_report("prose", REFERENCE, Recall(rounds, reference, 1, [low, sonnet], LOW)).splitlines()
|
||||
self.assertEqual(lines, [
|
||||
"Replayed 8 prose rounds of claude-opus-5-5 projects, which hold 40 🔴 and 🟡 findings, twice on the project's rung, claude-opus-5-5 at medium effort.",
|
||||
"Left out 1 more, which a replay on the project's rung failed on; stderr says why.",
|
||||
"The project's rung found 32 and then 24 of the 40, 70% on average, so a rung qualifies finding 24 or more of them, missing no 🔴 that both of its replays found.",
|
||||
"claude-opus-5-5 at low effort found 24, 60%, and missed no such 🔴: it qualifies.",
|
||||
"claude-sonnet-5-5 at high effort found 20, 50%, and missed 4 such 🔴: it doesn't qualify.",
|
||||
*[" /code/p 2026-10-14T10:00:01Z: 🔴 a"] * 4,
|
||||
"Lowest rung that qualifies: claude-opus-5-5 at low effort",
|
||||
])
|
||||
|
||||
def test_says_why_no_rung_was_tried(self):
|
||||
few = recall_report("prose", REFERENCE, Recall(ROUNDS, (FIRST, SECOND), 0, [], None)).splitlines()
|
||||
self.assertEqual(few[1:], ["No rung tried: fewer than 8 rounds were replayed on the project's rung without a failure."])
|
||||
rounds, _ = self.EIGHT
|
||||
for reference in (([set()] * 8, [set()] * 8), (TENTH[0] * 4, TENTH[1] * 4)):
|
||||
too_few = recall_report("prose", REFERENCE, Recall(rounds, reference, 0, [], None)).splitlines()
|
||||
self.assertEqual(too_few[1:], ["No rung tried: the project's rung found too few of them to hold a rung to."])
|
||||
|
||||
def test_names_no_rung_where_none_qualifies(self):
|
||||
rounds, reference = self.EIGHT
|
||||
low = tried(LOW, rounds, reference, [{0}, {0}] * 4)
|
||||
lines = recall_report("prose", REFERENCE, Recall(rounds, reference, 0, [low], None)).splitlines()
|
||||
self.assertEqual(lines[-2:], ["claude-opus-5-5 at low effort found 8, 20%, and missed no such 🔴: it doesn't qualify.", "Lowest rung that qualifies: none below the project's rung"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -14,19 +14,20 @@ import unittest.mock
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from review_replay.rounds import authored_by, lost_inputs, recorded_findings, report, reviewed_path, Round, round_from, sample, stamp_seconds
|
||||
from review_replay.rounds import authored_by, lost_inputs, recorded_findings, reviewed_path, Round, round_from, sample, stamp_seconds
|
||||
from loop_effects.effects import Effects, system_effects
|
||||
from claude_code.entries import entry_from
|
||||
from failure import Failure
|
||||
from review_replay import main
|
||||
from rung_replay.search import Miss, Replay, Tried
|
||||
from review_replay import main, recall, replay
|
||||
from review_rules.reviewer_context import reviewer_context
|
||||
from review_rules.review_passes import REVIEWERS
|
||||
from model_routing.ladder import Rung
|
||||
from rung_replay import search
|
||||
|
||||
TOOL = pathlib.Path(__file__).resolve().parents[1] / "review-replay"
|
||||
REFERENCE = Rung("claude-opus-5-5", "medium")
|
||||
LOW = Rung("claude-opus-5-5", "low")
|
||||
MIDDLE = Rung("claude-sonnet-5-5", "high")
|
||||
CHEAP = Rung("claude-haiku-5-5", "max")
|
||||
|
||||
|
||||
def entry(kind, text, **fields):
|
||||
@@ -114,20 +115,26 @@ class Sample(unittest.TestCase):
|
||||
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("stability", "claude-opus-5-5", REFERENCE, rounds, Replay([{0, 1}, set()], [Tried(MIDDLE, []), Tried(CHEAP, [Miss(rounds[0], 0, {1})])], MIDDLE)).splitlines()
|
||||
self.assertEqual(lines, [
|
||||
"Replayed 2 stability rounds of claude-opus-5-5 projects, holding 3 🔴 and 🟡 findings.",
|
||||
"The reference reviewer, claude-opus-5-5 at medium effort, found 2 of them.",
|
||||
"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("stability", "claude-opus-5-5", REFERENCE, rounds, Replay([{0, 1}, {0}], [Tried(MIDDLE, [Miss(rounds[1], 0, set())])], None)).splitlines()[-1], "Lowest rung that finds every finding the reference reviewer finds: none below the project's rung")
|
||||
self.assertEqual(report("stability", "claude-opus-5-5", REFERENCE, rounds, Replay([set(), set()], [], None)).splitlines()[-1], "No rung tried: the reference reviewer found no finding to hold one to.")
|
||||
class Launch(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.home = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory()))
|
||||
(self.home / ".claude").mkdir()
|
||||
(self.home / ".claude" / "CLAUDE.md").write_text("## Shared goal\n\nHealth.\n\n## Prose\n\nShort.\n\n## Vocabulary\n\nWords.\n")
|
||||
self.clone = self.home / "clone"
|
||||
self.clone.mkdir()
|
||||
|
||||
def test_runs_the_reviewer_as_archived_with_claude_md(self):
|
||||
self.assertEqual(replay.launch("prose-reviewer", REFERENCE, "Review it.", str(self.clone), self.home, False), (["--agent", "prose-reviewer", *REFERENCE.flags()], "Review it."))
|
||||
|
||||
def test_drops_claude_md_and_hands_the_reviewer_what_the_hook_and_the_header_would(self):
|
||||
(self.clone / "AGENTS.md").write_text("")
|
||||
args, prompt = replay.launch("prose-reviewer", REFERENCE, "Review it.", str(self.clone), self.home, True)
|
||||
self.assertEqual(args, ["--agent", "prose-reviewer", *REFERENCE.flags(), "--settings", json.dumps({"env": {"CLAUDE_CODE_DISABLE_CLAUDE_MDS": "1"}})])
|
||||
self.assertEqual(prompt, f"{reviewer_context(self.home)}\n\nReview it.\nPrinciples: read {self.clone}/AGENTS.md first, for the project principles and the decision titles.")
|
||||
|
||||
def test_fails_without_the_sections_to_hand_over(self):
|
||||
(self.home / ".claude" / "CLAUDE.md").write_text("")
|
||||
self.assertIsInstance(replay.launch("prose-reviewer", REFERENCE, "Review it.", str(self.clone), self.home, True), Failure)
|
||||
|
||||
|
||||
class Match(unittest.TestCase):
|
||||
@@ -138,14 +145,14 @@ class Match(unittest.TestCase):
|
||||
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))
|
||||
return replay.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(json.loads(args[args.index("--json-schema") + 1]), replay.MATCH_SCHEMA)
|
||||
self.assertEqual(args[args.index("--tools") + 1], "")
|
||||
self.assertEqual(args[args.index("--model"):args.index("--model") + 4], REFERENCE.flags())
|
||||
|
||||
@@ -185,6 +192,9 @@ class Main(unittest.TestCase):
|
||||
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.home / ".claude" / "CLAUDE.md").write_text("## Shared goal\n\nHealth.\n\n## Prose\n\nShort.\n\n## Vocabulary\n\nWords.\n")
|
||||
# The fixture holds one round.
|
||||
self.enterContext(unittest.mock.patch.object(recall, "ENOUGH_ROUNDS", 1))
|
||||
self.reviews = []
|
||||
self.agents = set()
|
||||
self.matched_in = []
|
||||
@@ -230,24 +240,80 @@ class Main(unittest.TestCase):
|
||||
result = result if "api_error_status" in result else {"type": "result", "structured_output": {"found": [n + 1 for n in result["found"]]}}
|
||||
return subprocess.CompletedProcess(args, 0, json.dumps(result), "")
|
||||
|
||||
effects = Effects(alive=unused, claude=claude, claude_on_terminal=unused, discard_typed=unused, execv=unused, git=system_effects().git, input=unused, input_or=unused, local_time=unused, memory=unused, new_id=unused, now=unused, on_terminal=unused, pid=unused, python=unused, sleep=unused, stream_claude=unused)
|
||||
effects = Effects(alive=unused, claude=claude, claude_on_terminal=unused, discard_typed=unused, dm=unused, execv=unused, git=system_effects().git, input=unused, input_or=unused, local_time=unused, memory=unused, new_id=unused, now=unused, on_terminal=unused, pid=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(["stability", "claude-opus-5-5"], lambda rung: {"found": [0] if rung == MIDDLE else [0, 1]})
|
||||
def test_without_claude_md_replays_each_round_three_times_with_it_and_once_without_on_the_project_rung(self):
|
||||
finds = iter(([0, 1], [0], [0, 1], [1]))
|
||||
code, out, err = self.run_main(["stability", "claude-opus-5-5", "--omit-claude-md"], lambda rung: {"found": next(finds)})
|
||||
self.assertEqual(code, 0, err)
|
||||
self.assertEqual([rung for rung, *_ in self.reviews], [REFERENCE, MIDDLE])
|
||||
self.assertEqual([rung for rung, *_ in self.reviews], [REFERENCE] * 4)
|
||||
context = reviewer_context(self.home)
|
||||
self.assertEqual([prompt.startswith(context) for *_, prompt, _ in self.reviews], [False, False, False, True])
|
||||
self.assertEqual(out, (
|
||||
f"Replayed 1 stability rounds of claude-opus-5-5 projects, which hold 2 🔴 and 🟡 findings, four times on {REFERENCE}: three with CLAUDE.md, one without.\n"
|
||||
"With CLAUDE.md the three replays found 2, 1 and 2 of them, and missed 0, 1 and 0 of the findings that both of the other two found.\n"
|
||||
"Without CLAUDE.md it found 1 of them, and missed 1 of the 1 findings that both of the first two found:\n"
|
||||
f" {self.checkout} 2026-10-14T10:00:00Z: 🔴 a.txt:1 wrong\n"
|
||||
"It passes: 1 missed is no more than the most a replay with CLAUDE.md missed, 1.\n"
|
||||
))
|
||||
with_them = f"replaying 1 stability rounds with the instruction files on {REFERENCE}\n"
|
||||
self.assertEqual(err, with_them * 3 + f"replaying 1 stability rounds without the instruction files on {REFERENCE}\n")
|
||||
|
||||
def test_without_claude_md_fails_where_it_missed_more_than_every_replay_with_it(self):
|
||||
finds = iter(([0, 1], [0, 1], [0, 1], []))
|
||||
_, out, _ = self.run_main(["stability", "claude-opus-5-5", "--omit-claude-md"], lambda rung: {"found": next(finds)})
|
||||
self.assertEqual(out.splitlines()[-1], "It fails: 2 missed is more than the most a replay with CLAUDE.md missed, 0.")
|
||||
|
||||
def test_without_claude_md_says_so_where_the_reviewer_missed_nothing(self):
|
||||
code, out, err = self.run_main(["stability", "claude-opus-5-5", "--omit-claude-md"], lambda rung: {"found": [0]})
|
||||
self.assertEqual((code, out.splitlines()[-2:]), (0, ["Without CLAUDE.md it found 1 of them, and missed 0 of the 1 findings that both of the first two found.", "It passes: 0 missed is no more than the most a replay with CLAUDE.md missed, 0."]))
|
||||
|
||||
def test_without_claude_md_says_there_is_no_evidence_where_the_first_two_replays_share_no_finding(self):
|
||||
finds = iter(([0], [1], [1], [1]))
|
||||
_, out, _ = self.run_main(["stability", "claude-opus-5-5", "--omit-claude-md"], lambda rung: {"found": next(finds)})
|
||||
self.assertEqual(out.splitlines()[-1], "Without CLAUDE.md it found 1 of them. No evidence: the first two replays with CLAUDE.md found none in common, so there is no finding to hold it to.")
|
||||
|
||||
def test_without_claude_md_leaves_out_a_round_that_a_replay_failed_on(self):
|
||||
failing = {}
|
||||
|
||||
def review(rung):
|
||||
# claude is tried three times running, so the first replay fails only where all three tries do.
|
||||
failing["tries"] = failing.get("tries", 0) + 1
|
||||
return [] if failing["tries"] <= 3 else {"type": "result", "result": f"review on {rung.model} {rung.effort}"}
|
||||
|
||||
code, out, err = self.run_main(["stability", "claude-opus-5-5", "--omit-claude-md"], lambda rung: {"found": [0, 1]}, review=review)
|
||||
self.assertEqual(code, 0, err)
|
||||
self.assertEqual(out, (
|
||||
f"Replayed 0 stability rounds of claude-opus-5-5 projects, which hold 0 🔴 and 🟡 findings, four times on {REFERENCE}: three with CLAUDE.md, one without.\n"
|
||||
"Left out 1 more, which a replay failed on; stderr says why.\n"
|
||||
"With CLAUDE.md the three replays found 0, 0 and 0 of them, and missed 0, 0 and 0 of the findings that both of the other two found.\n"
|
||||
"Without CLAUDE.md it found 0 of them. No evidence: the first two replays with CLAUDE.md found none in common, so there is no finding to hold it to.\n"
|
||||
))
|
||||
self.assertIn(f" {self.checkout} 2026-10-14T10:00:00Z with the instruction files failed, so the round is left out: claude printed no json reply", err)
|
||||
self.assertNotIn("without the instruction files failed", err)
|
||||
|
||||
def test_without_claude_md_stops_at_a_usage_limit(self):
|
||||
code, out, err = self.run_main(["stability", "claude-opus-5-5", "--omit-claude-md"], lambda rung: {"type": "result", "api_error_status": 429, "result": "You've hit your limit"})
|
||||
self.assertEqual((code, out), (1, ""))
|
||||
self.assertIn("review-replay: claude hit a usage limit: You've hit your limit", err)
|
||||
self.assertEqual(len(self.reviews), 1)
|
||||
|
||||
def test_replays_the_models_rounds_on_the_commit_reviewed_from_the_project_rung_down(self):
|
||||
code, out, err = self.run_main(["stability", "claude-opus-5-5"], lambda rung: {"found": [1] if rung == LOW else [0, 1]})
|
||||
self.assertEqual(code, 0, err)
|
||||
self.assertEqual([rung for rung, *_ in self.reviews], [REFERENCE, REFERENCE, LOW])
|
||||
_, 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: none below the project's rung\n"), out)
|
||||
self.assertIn("The project's rung found 2 and then 2 of the 2, 100% on average, so a rung qualifies finding 2 or more of them", out)
|
||||
self.assertIn(f"claude-opus-5-5 at low effort found 1, 50%, and missed 1 such 🔴: it doesn't qualify.\n {self.checkout} 2026-10-14T10:00:00Z: 🔴 a.txt:1 wrong\n", out)
|
||||
self.assertTrue(out.endswith("qualifies: none below the project's rung\n"), out)
|
||||
self.assertEqual(set(self.matched_in), {str(self.checkout)})
|
||||
self.assertTrue(out.startswith("Replayed 1 stability rounds of claude-opus-5-5 projects,"), out)
|
||||
|
||||
@@ -260,8 +326,16 @@ class Main(unittest.TestCase):
|
||||
def test_tries_each_rung_down_to_the_ladders_lowest_below_the_lowest_a_worker_routes_to(self):
|
||||
code, out, err = self.run_main(["prose", "claude-opus-5-5"], lambda rung: {"found": [0, 1]})
|
||||
self.assertEqual(code, 0, err)
|
||||
self.assertEqual([rung for rung, *_ in self.reviews], [REFERENCE, MIDDLE])
|
||||
self.assertTrue(out.endswith("finds: claude-sonnet-5-5 at high effort\n"), out)
|
||||
self.assertEqual([rung for rung, *_ in self.reviews], [REFERENCE, REFERENCE, LOW, MIDDLE])
|
||||
self.assertTrue(out.endswith("qualifies: claude-sonnet-5-5 at high effort\n"), out)
|
||||
|
||||
def test_counts_a_failed_replay_on_a_lower_rung_as_finding_nothing(self):
|
||||
code, out, err = self.run_main(["prose", "claude-opus-5-5"], lambda rung: {"found": [0, 1]}, review=lambda rung: {"type": "result"} if rung == LOW else {"type": "result", "result": f"review on {rung.model} {rung.effort}"})
|
||||
self.assertEqual(code, 0, err)
|
||||
self.assertIn(f"replaying 1 prose rounds on {REFERENCE}\n", err)
|
||||
self.assertIn(f"replaying 1 prose rounds on {LOW}\n", err)
|
||||
self.assertIn(f"on {LOW} failed: the reviewer replied with no report", err)
|
||||
self.assertIn("claude-opus-5-5 at low effort found 0, 0%, and missed 1 such 🔴: it doesn't qualify.", out)
|
||||
|
||||
def review_folder_with_round_1(self):
|
||||
"""The chunk's review folder, holding round 1's report from before the replayed round began at 10:00, that round's own and a later pass's reports, written after, and an earlier attempt's report, from before the chunk began at 09:15."""
|
||||
@@ -314,8 +388,9 @@ class Main(unittest.TestCase):
|
||||
code, out, err = self.run_main(["stability", "claude-opus-5-5"], unused)
|
||||
self.assertEqual(code, 0, err)
|
||||
self.assertEqual(self.reviews, [])
|
||||
self.assertIn(f"on {REFERENCE} found nothing: the prompt names the review folder in a spelling the replay does not redirect", err)
|
||||
self.assertTrue(out.endswith("No rung tried: the reference reviewer found no finding to hold one to.\n"))
|
||||
self.assertIn(f"on {REFERENCE} failed: the prompt names the review folder in a spelling the replay does not redirect", err)
|
||||
self.assertIn("Left out 1 more, which a replay on the project's rung failed on", out)
|
||||
self.assertTrue(out.endswith("No rung tried: fewer than 1 rounds were replayed on the project's rung without a failure.\n"), out)
|
||||
|
||||
def test_replays_a_round_whose_prompt_names_an_input_written_before_it_began_naming_the_copy(self):
|
||||
folder = self.review_folder_with_round_1()
|
||||
@@ -334,9 +409,9 @@ class Main(unittest.TestCase):
|
||||
code, out, err = self.run_main(["stability", "claude-opus-5-5"], unused)
|
||||
self.assertEqual(code, 0, err)
|
||||
self.assertEqual(self.reviews, [])
|
||||
self.assertIn(f"on {REFERENCE} found nothing: the prompt names branch.diff, which the review folder did not hold from the chunk's start until the round's", err)
|
||||
self.assertIn(f"on {REFERENCE} failed: the prompt names branch.diff, which the review folder did not hold from the chunk's start until the round's", err)
|
||||
|
||||
def test_finds_nothing_and_leaves_no_folder_behind_when_it_cannot_copy_the_reports(self):
|
||||
def test_fails_the_replay_and_leaves_no_folder_behind_when_it_cannot_copy_the_reports(self):
|
||||
folder = self.review_folder_with_round_1()
|
||||
(folder / "stability-round-1.md").chmod(0)
|
||||
self.set_prompt(f"Review branch x in {self.home}/code/proj-x. Write your report to ~/.local/state/larv-review/code/proj-x/stability-round-2.md.")
|
||||
@@ -345,7 +420,7 @@ class Main(unittest.TestCase):
|
||||
code, _, err = self.run_main(["stability", "claude-opus-5-5"], unused)
|
||||
self.assertEqual(code, 0, err)
|
||||
self.assertEqual(self.reviews, [])
|
||||
self.assertIn(f"on {REFERENCE} found nothing: could not prepare the replay: ", err)
|
||||
self.assertIn(f"on {REFERENCE} failed: could not prepare the replay: ", err)
|
||||
self.assertEqual(list(scratch.iterdir()), [], "the clone is removed")
|
||||
self.assertEqual([path.name for path in folder.parent.parent.iterdir()], ["code"], "the copy is removed")
|
||||
|
||||
@@ -355,6 +430,24 @@ class Main(unittest.TestCase):
|
||||
self.assertEqual(code, 0, err)
|
||||
self.assertTrue(out.startswith("Replayed 2 stability rounds"), out)
|
||||
|
||||
def test_leaves_out_a_round_that_either_replay_on_the_project_rung_failed_on(self):
|
||||
self.write_chunk("proj", "c2", "2026-10-14T10:30:00Z")
|
||||
self.enterContext(unittest.mock.patch.object(search, "AT_ONCE", 1))
|
||||
# One round at a time, three tries on a round reply with no report: the first replay's on its first round, then the second replay's on its first, after the first replay's two reviews. Every other review replies.
|
||||
for failing in (range(3), range(2, 5)):
|
||||
with self.subTest(failing=failing):
|
||||
calls = iter(range(100))
|
||||
code, out, err = self.run_main(["prose", "claude-opus-5-5"], lambda rung: {"found": [0, 1]}, review=lambda rung: {"type": "result"} if next(calls) in failing else {"type": "result", "result": f"review on {rung.model} {rung.effort}"})
|
||||
self.assertEqual(code, 0, err)
|
||||
self.assertTrue(out.startswith("Replayed 1 prose rounds"), out)
|
||||
self.assertIn("Left out 1 more", out)
|
||||
|
||||
def test_tries_no_lower_rung_where_the_project_rung_found_nothing(self):
|
||||
code, out, err = self.run_main(["prose", "claude-opus-5-5"], lambda rung: {"found": []})
|
||||
self.assertEqual(code, 0, err)
|
||||
self.assertEqual([rung for rung, *_ in self.reviews], [REFERENCE, REFERENCE])
|
||||
self.assertTrue(out.endswith("No rung tried: the project's rung found too few of them to hold a rung to.\n"), 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(["stability", "claude-opus-5-5"], lambda rung: {"found": [0]})[0], 0)
|
||||
@@ -372,12 +465,14 @@ class Main(unittest.TestCase):
|
||||
self.assertEqual(self.run_main(["stability", "claude-opus-5-5"], lambda rung: {"found": [0]})[0], 0)
|
||||
self.assertEqual(self.reviews[0][1:4], ("s\n", "x\n", "0\n"))
|
||||
|
||||
def test_finds_nothing_in_a_round_whose_review_has_no_report(self):
|
||||
def test_leaves_out_a_round_whose_review_on_the_project_rung_has_no_report(self):
|
||||
code, out, err = self.run_main(["stability", "claude-opus-5-5"], unused, review=lambda rung: {"type": "result"})
|
||||
self.assertEqual(code, 0, err)
|
||||
self.assertEqual([rung for rung, *_ in self.reviews], [REFERENCE] * 3)
|
||||
self.assertIn(f" {self.checkout} 2026-10-14T10:00:00Z on {REFERENCE} found nothing: the reviewer replied with no report", err)
|
||||
self.assertTrue(out.endswith("No rung tried: the reference reviewer found no finding to hold one to.\n"))
|
||||
# Each of the two replays tries claude three times.
|
||||
self.assertEqual([rung for rung, *_ in self.reviews], [REFERENCE] * 6)
|
||||
self.assertIn(f" {self.checkout} 2026-10-14T10:00:00Z on {REFERENCE} failed: the reviewer replied with no report", err)
|
||||
self.assertIn("Left out 1 more, which a replay on the project's rung failed on", out)
|
||||
self.assertTrue(out.endswith("No rung tried: fewer than 1 rounds were replayed on the project's rung without a failure.\n"), out)
|
||||
|
||||
def assert_no_round(self):
|
||||
code, _, err = self.run_main(["stability", "claude-opus-5-5"], unused)
|
||||
@@ -403,7 +498,7 @@ class Main(unittest.TestCase):
|
||||
|
||||
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: ")
|
||||
self.assert_left_out("origin records no default branch")
|
||||
|
||||
def test_leaves_out_a_round_whose_checkout_is_gone(self):
|
||||
shutil.rmtree(self.checkout)
|
||||
@@ -417,7 +512,7 @@ class Main(unittest.TestCase):
|
||||
def test_exits_1_on_a_usage_limit_bad_arguments_or_no_round_to_replay(self):
|
||||
code, _, err = self.run_main(["stability", "claude-opus-5-5"], lambda rung: {"type": "result", "api_error_status": 429, "result": "You've hit your limit"})
|
||||
self.assertEqual(code, 1)
|
||||
self.assertIn("usage limit: You've hit your limit", err)
|
||||
self.assertIn("review-replay: claude hit a usage limit: You've hit your limit", err)
|
||||
for argv in ([], ["claude-opus-5-5"], ["full scan", "claude-opus-5-5"], ["stability", "off-ladder"], ["stability", "claude-opus-5-5", "x"]):
|
||||
with self.subTest(argv=argv):
|
||||
self.assertEqual(self.run_main(argv, unused)[0], 1)
|
||||
@@ -427,7 +522,7 @@ class Main(unittest.TestCase):
|
||||
|
||||
def test_prints_the_help(self):
|
||||
code, out, _ = self.run_main(["-h"], unused)
|
||||
self.assertEqual((code, out.splitlines()[2]), (0, "usage: review-replay <pass> <model>"))
|
||||
self.assertEqual((code, out.splitlines()[2]), (0, "usage: review-replay <pass> <model> [--omit-claude-md]"))
|
||||
self.assertIn(f"{', '.join(list(REVIEWERS)[:-1])} or {list(REVIEWERS)[-1]}.", " ".join(out.split()))
|
||||
|
||||
def test_the_launcher_prints_the_help(self):
|
||||
|
||||
@@ -9,7 +9,7 @@ from records.utc_stamp import utc
|
||||
ARCHITECT = "Inherited architect"
|
||||
DECIDED_BY = "decided by"
|
||||
DIMENSIONS = ("Navigation", "Locality", "Shape", "Self-sufficiency", "Overall")
|
||||
# The comprehension floor, which every dimension and the overall should reach; docs/decisions.md → "comprehension floor" says it blocks nothing.
|
||||
# The comprehension floor, which every dimension and the overall should reach; docs/decisions.md → "comprehension floor" says it doesn't block anything.
|
||||
FLOOR = decimal.Decimal("7.0")
|
||||
HARDEST_FIRST = "hardest first"
|
||||
HEADING = re.compile(r"^([^,]+), (.+) at ([0-9a-f]{7,40})(?:, against ([0-9a-f]{7,40}))?$")
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
"""What a reviewer under agents/ is handed in place of the instruction files: `omitClaudeMd` starts it without them, and most of `~/.claude/CLAUDE.md` is the worker's. docs/decisions.md → `agents/: a reviewer starts without CLAUDE.md only where a replay of its pass missed no more findings than the most an unchanged replay missed` says why, and which reviewers."""
|
||||
import json
|
||||
import pathlib
|
||||
import re
|
||||
|
||||
from failure import Failure
|
||||
from review_rules.review_passes import REVIEWERS
|
||||
from records.markdown_text import section
|
||||
|
||||
# The sections of ~/.claude/CLAUDE.md a reviewer needs, in the file's order: the code-health goal the agents cite, the bar its own prose meets, and the words its reports use.
|
||||
SECTIONS = ("Shared goal", "Prose", "Vocabulary")
|
||||
|
||||
|
||||
def reviewer_context(home: pathlib.Path) -> str | Failure:
|
||||
"""SECTIONS of the CLAUDE.md under home, as a reviewer is told them; a Failure where the file or a section is missing."""
|
||||
path = home / ".claude" / "CLAUDE.md"
|
||||
try:
|
||||
text = path.read_text(encoding="utf-8")
|
||||
except (OSError, UnicodeDecodeError) as failure:
|
||||
return Failure(f"could not read {path}: {failure}")
|
||||
found = {name: section(text, re.escape(name)) for name in SECTIONS}
|
||||
if missing := [name for name, lines in found.items() if lines is None]:
|
||||
return Failure(f"{path} holds no section {', '.join(missing)}")
|
||||
return "\n\n".join(["You start without `~/.claude/CLAUDE.md`. These sections of it hold for you:", *("\n".join([f"## {name}", *lines]).strip() for name, lines in found.items() if lines is not None)])
|
||||
|
||||
|
||||
def starts_bare(agent: str, home: pathlib.Path) -> bool:
|
||||
"""Whether agent is a reviewer whose definition under home starts it without the instruction files."""
|
||||
if agent not in REVIEWERS.values():
|
||||
return False
|
||||
try:
|
||||
text = (home / ".claude" / "agents" / f"{agent}.md").read_text(encoding="utf-8")
|
||||
except (OSError, UnicodeDecodeError):
|
||||
return False
|
||||
frontmatter = text.split("---\n")[1] if text.startswith("---\n") else ""
|
||||
return "omitClaudeMd: true" in frontmatter.splitlines()
|
||||
|
||||
|
||||
def hook_reply(given: str, home: pathlib.Path) -> str:
|
||||
"""What the SubagentStart hook prints for its input given: the context for a reviewer that starts without the instruction files, and no text for any other agent."""
|
||||
try:
|
||||
read = json.loads(given)
|
||||
except ValueError:
|
||||
return ""
|
||||
if not isinstance(read, dict) or not isinstance(agent := read.get("agent_type"), str) or not starts_bare(agent, home):
|
||||
return ""
|
||||
context = reviewer_context(home)
|
||||
if isinstance(context, Failure):
|
||||
# Claude Code starts the subagent whatever a SubagentStart hook exits with, and shows its stderr to no headless run, so the reviewer's report is where the worker can see the failure.
|
||||
context = f"You start without `~/.claude/CLAUDE.md`, and the hook that hands you three of its sections failed: {context.reason}. Open your report by saying so."
|
||||
return json.dumps({"hookSpecificOutput": {"hookEventName": "SubagentStart", "additionalContext": context}})
|
||||
|
||||
|
||||
def principles_line(worktree: str) -> str | None:
|
||||
"""The line of a reviewer's header that names where the project in worktree keeps its principles and decision titles, or None where it keeps neither file."""
|
||||
what = "for the project principles and the decision titles"
|
||||
if (pathlib.Path(worktree) / "AGENTS.md").is_file():
|
||||
return f"Principles: read {worktree}/AGENTS.md first, {what}."
|
||||
if (pathlib.Path(worktree) / "docs" / "decisions.md").is_file():
|
||||
return f"Principles: read {worktree}/docs/decisions.md first, up to `# Decisions`, {what}."
|
||||
return None
|
||||
@@ -0,0 +1,104 @@
|
||||
import json
|
||||
import pathlib
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from failure import Failure
|
||||
from review_rules.reviewer_context import hook_reply, principles_line, reviewer_context, SECTIONS, starts_bare
|
||||
from review_rules.review_passes import REVIEWERS
|
||||
|
||||
REPO = pathlib.Path(__file__).resolve().parents[2]
|
||||
CLAUDE_MD = "# Global\n\n## Working loop\n\nThe worker's.\n\n## Shared goal\n\nCode health.\n\n## Prose\n\nWrite short.\n\n## Git\n\nOne line.\n\n## Vocabulary\n\n- **chunk** — a unit.\n"
|
||||
|
||||
|
||||
class ReviewerContext(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.home = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory()))
|
||||
(self.home / ".claude").mkdir()
|
||||
(self.home / ".claude" / "CLAUDE.md").write_text(CLAUDE_MD)
|
||||
(self.home / ".claude" / "agents").mkdir()
|
||||
for agent in REVIEWERS.values():
|
||||
(self.home / ".claude" / "agents" / f"{agent}.md").write_text(f"---\nname: {agent}\nomitClaudeMd: true\n---\n\nReview.\n")
|
||||
|
||||
def test_holds_the_shared_goal_prose_and_vocabulary_sections_and_none_of_the_workers(self):
|
||||
self.assertEqual(reviewer_context(self.home), "You start without `~/.claude/CLAUDE.md`. These sections of it hold for you:\n\n## Shared goal\n\nCode health.\n\n## Prose\n\nWrite short.\n\n## Vocabulary\n\n- **chunk** — a unit.")
|
||||
|
||||
def test_a_heading_inside_a_code_fence_does_not_end_a_section(self):
|
||||
(self.home / ".claude" / "CLAUDE.md").write_text("## Shared goal\n\n```\n## Not a heading\n```\n\nstill the goal\n\n## Prose\n\np\n\n## Vocabulary\n\nv\n")
|
||||
self.assertIn("## Shared goal\n\n```\n## Not a heading\n```\n\nstill the goal\n\n## Prose", reviewer_context(self.home))
|
||||
|
||||
def test_fails_on_a_missing_section_or_file(self):
|
||||
(self.home / ".claude" / "CLAUDE.md").write_text("## Prose\n\nWrite short.\n")
|
||||
self.assertEqual(reviewer_context(self.home), Failure(f"{self.home / '.claude' / 'CLAUDE.md'} holds no section Shared goal, Vocabulary"))
|
||||
(self.home / ".claude" / "CLAUDE.md").unlink()
|
||||
path = self.home / ".claude" / "CLAUDE.md"
|
||||
self.assertIn(f"could not read {path}: ", reviewer_context(self.home).reason)
|
||||
|
||||
def test_the_repos_claude_md_holds_each_section(self):
|
||||
headings = [line[3:] for line in (REPO / "CLAUDE.md").read_text().splitlines() if line.startswith("## ")]
|
||||
self.assertEqual([name for name in SECTIONS if name not in headings], [])
|
||||
|
||||
def test_the_hook_hands_a_reviewer_the_context_and_any_other_agent_nothing(self):
|
||||
for agent in REVIEWERS.values():
|
||||
with self.subTest(agent=agent):
|
||||
reply = hook_reply(json.dumps({"hook_event_name": "SubagentStart", "agent_type": agent}), self.home)
|
||||
self.assertEqual(json.loads(reply), {"hookSpecificOutput": {"hookEventName": "SubagentStart", "additionalContext": reviewer_context(self.home)}})
|
||||
for given in (json.dumps({"agent_type": "Explore"}), json.dumps({}), json.dumps([]), "no json"):
|
||||
with self.subTest(given=given):
|
||||
self.assertEqual(hook_reply(given, self.home), "")
|
||||
|
||||
def test_the_hook_hands_nothing_to_a_reviewer_whose_definition_keeps_the_instruction_files(self):
|
||||
given = json.dumps({"agent_type": "prose-reviewer"})
|
||||
for kept in ("---\nname: prose-reviewer\n---\n\nomitClaudeMd: true\n", "---\nname: prose-reviewer\nomitClaudeMd: false\n---\n", "omitClaudeMd: true\n", b"\xff"):
|
||||
with self.subTest(kept=kept):
|
||||
path = self.home / ".claude" / "agents" / "prose-reviewer.md"
|
||||
path.write_bytes(kept) if isinstance(kept, bytes) else path.write_text(kept)
|
||||
self.assertEqual(hook_reply(given, self.home), "")
|
||||
(self.home / ".claude" / "agents" / "prose-reviewer.md").unlink()
|
||||
self.assertEqual(hook_reply(given, self.home), "")
|
||||
self.assertTrue(starts_bare("stability-reviewer", self.home))
|
||||
(self.home / ".claude" / "agents" / "Explore.md").write_text("---\nomitClaudeMd: true\n---\n")
|
||||
self.assertFalse(starts_bare("Explore", self.home))
|
||||
|
||||
def test_the_hook_tells_a_reviewer_to_report_that_a_section_is_missing(self):
|
||||
path = self.home / ".claude" / "CLAUDE.md"
|
||||
path.write_text("## Prose\n\nWrite short.\n")
|
||||
reply = json.loads(hook_reply(json.dumps({"agent_type": "prose-reviewer"}), self.home))
|
||||
self.assertEqual(reply["hookSpecificOutput"]["additionalContext"], f"You start without `~/.claude/CLAUDE.md`, and the hook that hands you three of its sections failed: {path} holds no section Shared goal, Vocabulary. Open your report by saying so.")
|
||||
|
||||
|
||||
class PrinciplesLine(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.worktree = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory()))
|
||||
|
||||
def test_names_agents_md_where_the_project_keeps_one(self):
|
||||
(self.worktree / "AGENTS.md").write_text("")
|
||||
(self.worktree / "docs").mkdir()
|
||||
(self.worktree / "docs" / "decisions.md").write_text("")
|
||||
self.assertEqual(principles_line(str(self.worktree)), f"Principles: read {self.worktree}/AGENTS.md first, for the project principles and the decision titles.")
|
||||
|
||||
def test_names_the_head_of_the_decision_log_where_the_project_keeps_no_agents_md(self):
|
||||
(self.worktree / "docs").mkdir()
|
||||
(self.worktree / "docs" / "decisions.md").write_text("")
|
||||
self.assertEqual(principles_line(str(self.worktree)), f"Principles: read {self.worktree}/docs/decisions.md first, up to `# Decisions`, for the project principles and the decision titles.")
|
||||
|
||||
def test_names_nothing_where_the_project_keeps_neither(self):
|
||||
self.assertIsNone(principles_line(str(self.worktree)))
|
||||
|
||||
|
||||
class Reviewers(unittest.TestCase):
|
||||
def test_only_the_reviewers_whose_pass_met_the_replay_gate_start_without_claude_md(self):
|
||||
# docs/decisions.md → `agents/: a reviewer starts without CLAUDE.md only where a replay of its pass missed no more findings than the most an unchanged replay missed` holds each pass's result; override-reviewer has no archived round to replay.
|
||||
bare = [path.stem for path in sorted((REPO / "agents").glob("*.md")) if "omitClaudeMd: true" in path.read_text().split("---\n")[1].splitlines()]
|
||||
self.assertEqual(bare, ["principles-auditor", "product-owner-reviewer", "prose-reviewer", "stability-reviewer", "systems-architect"])
|
||||
|
||||
def test_settings_run_the_hook_as_each_subagent_starts(self):
|
||||
hooks = json.loads((REPO / "settings.json").read_text())["hooks"]["SubagentStart"]
|
||||
self.assertEqual(hooks, [{"hooks": [{"command": "~/.claude/bin/larv-review reviewer-context", "timeout": 30, "type": "command"}]}])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -110,7 +110,7 @@ def entries(path: pathlib.Path) -> list[Entry]:
|
||||
|
||||
|
||||
def subagent(transcript: pathlib.Path) -> Subagent:
|
||||
"""The subagent, named by the .meta.json Claude Code writes beside its transcript: {"agentType": "Explore", "toolUseId": "toolu_01…", ...}. A meta missing or unreadable names nothing."""
|
||||
"""The subagent, named by the .meta.json Claude Code writes beside its transcript: {"agentType": "Explore", "toolUseId": "toolu_01…", ...}. A meta missing or unreadable doesn't name anything."""
|
||||
path = transcript.with_name(transcript.name.removesuffix(".jsonl") + ".meta.json")
|
||||
try:
|
||||
meta = json.loads(path.read_text(encoding="utf-8"))
|
||||
|
||||
@@ -3,8 +3,8 @@ import collections
|
||||
import dataclasses
|
||||
import typing
|
||||
|
||||
from claude_code.entries import AssistantTurn, CostState, Entry, ToolCall
|
||||
from routing_figures.prices import listed
|
||||
from claude_code.entries import messages as claude_messages, CostState, Entry, ToolCall
|
||||
from model_routing.prices import listed
|
||||
|
||||
DIMENSIONS = ("project", "subagent type", "rung", "tool")
|
||||
# Each of DIMENSIONS to its labels' dollars.
|
||||
@@ -33,17 +33,12 @@ class Spent(typing.NamedTuple):
|
||||
|
||||
def messages(entries: list[Entry]) -> list[Message]:
|
||||
"""The assistant messages, counted once each, each with the tools whose results it took in, or `prompt` where it took none in."""
|
||||
# A message's usage is the same in each of its entries (none of 1,681 multi-entry messages in the archive of 2026-10-28 differed), so the first is kept, where reading_cost's tokens_in keeps the last.
|
||||
kept: dict[str, tuple[AssistantTurn, list[str]]] = {}
|
||||
for entry in entries:
|
||||
if isinstance(entry, AssistantTurn):
|
||||
found = kept.setdefault(entry.message_id or entry.uuid, (entry, []))
|
||||
found[1].extend(part.name for part in entry.parts if isinstance(part, ToolCall))
|
||||
counted = []
|
||||
before = [PROMPT]
|
||||
for turn, called in kept.values():
|
||||
for turns in claude_messages(entries):
|
||||
turn = turns[0]
|
||||
counted.append(Message(turn.timestamp, before, turn.model, listed(turn.model, turn.usage)))
|
||||
before = called or [PROMPT]
|
||||
before = [part.name for each in turns for part in each.parts if isinstance(part, ToolCall)] or [PROMPT]
|
||||
return counted
|
||||
|
||||
|
||||
|
||||
@@ -1,44 +0,0 @@
|
||||
"""What a message costs at list prices: the weights that split a chunk's recorded cost between its messages."""
|
||||
import dataclasses
|
||||
|
||||
from claude_code.entries import usage_count
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Price:
|
||||
"""Dollars per million tokens. A cache write costs 1.25 times the input for a five-minute cache and 2 times for an hour's, as Opus 5.5's $5 and $8 show."""
|
||||
input: float
|
||||
read: float
|
||||
output: float
|
||||
|
||||
@property
|
||||
def write_5m(self) -> float:
|
||||
return self.input * 1.25
|
||||
|
||||
@property
|
||||
def write_1h(self) -> float:
|
||||
return self.input * 2
|
||||
|
||||
|
||||
# Anthropic's list prices as the claude-api skill lists them (cached 2026-10-06), with Opus 5.5's cache prices from `docs/decisions.md` → `loop-claude: the worker's claude compacts…`. Haiku 5.5's cache read is assumed at a tenth of its input, and its dearer prompts above 200k tokens are left out. Where a chunk records its cost, only the proportions between one model's messages matter, so these may be a little off.
|
||||
PRICES = {
|
||||
"claude-fable-5-1": Price(10, 0.25, 50),
|
||||
"claude-haiku-5-5": Price(0.1, 0.01, 0.5),
|
||||
"claude-opus-5-5": Price(4, 0.2, 20),
|
||||
"claude-sonnet-5-5": Price(2, 0.2, 10),
|
||||
}
|
||||
|
||||
|
||||
# {"input_tokens": 2, "cache_creation": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 25919}, "cache_read_input_tokens": 10365, "output_tokens": 193, ...}
|
||||
def listed(model: str, usage: object) -> float:
|
||||
"""The cost of one message's usage at the model's list price; 0 for a model without one."""
|
||||
price = PRICES.get(model)
|
||||
if not price or not isinstance(usage, dict):
|
||||
return 0.0
|
||||
written = usage.get("cache_creation")
|
||||
# A write without the split by lifetime counts as a five-minute one.
|
||||
five, hour = (usage_count(written, "ephemeral_5m_input_tokens"), usage_count(written, "ephemeral_1h_input_tokens")) if isinstance(written, dict) else (usage_count(usage, "cache_creation_input_tokens"), 0)
|
||||
return (
|
||||
usage_count(usage, "input_tokens") * price.input + five * price.write_5m + hour * price.write_1h
|
||||
+ usage_count(usage, "cache_read_input_tokens") * price.read + usage_count(usage, "output_tokens") * price.output
|
||||
) / 1_000_000
|
||||
@@ -30,12 +30,12 @@ from routing_figures.render import render
|
||||
from model_routing.route import Route
|
||||
|
||||
LOW = Rung("claude-opus-5-5", "medium")
|
||||
HIGH = Rung("claude-opus-5-5", "high")
|
||||
HIGH = Rung("claude-fable-5-2", "low")
|
||||
LOW_ROUTE = Route(LOW, 7, 3, 4).worker_line()
|
||||
|
||||
|
||||
def message(id_, at, *parts, model="claude-opus-5-5", usage=None):
|
||||
"""Costs $2 on Opus 5.5, whose output is $20 per million tokens, and $1 on Sonnet 5.5, whose output is $10."""
|
||||
"""Writes 100k output tokens: $2 on Opus 5.5, $1 on Sonnet 5.5 and $4 on Fable 5.2, at $20, $10 and $40 per million."""
|
||||
return {"type": "assistant", "timestamp": at, "cwd": "/c", "message": {"id": id_, "model": model, "content": list(parts), "usage": usage or {"output_tokens": 100_000}}}
|
||||
|
||||
|
||||
@@ -164,10 +164,10 @@ class Measured(unittest.TestCase):
|
||||
message("m2", "2026-10-14T10:30:00Z", call("Agent", "a1", subagent_type="Explore", model="sonnet")),
|
||||
message("m3", "2026-10-14T10:31:00Z", call("Agent", "a2", subagent_type="Explore")),
|
||||
]
|
||||
subagents = [subagent_of("Explore", "a1", [result("r", "x")]), subagent_of("Explore", "a2", [message("s2", "2026-10-14T10:31:01Z", model="claude-opus-5-5")])]
|
||||
subagents = [subagent_of("Explore", "a1", [result("r", "x")]), subagent_of("Explore", "a2", [message("s2", "2026-10-14T10:31:01Z", model="claude-fable-5-2")])]
|
||||
found = chunk_figures(chunk_of("log", [kept], worker, subagents), "/h")
|
||||
self.assertEqual(found.delegated, {"sonnet at high effort": 1, str(HIGH): 1})
|
||||
self.assertEqual(found.dollars["rung"], {str(LOW): 2.0, str(HIGH): 6.0})
|
||||
self.assertEqual(found.delegated, {"sonnet at low effort": 1, str(HIGH): 1})
|
||||
self.assertEqual(found.dollars["rung"], {str(LOW): 2.0, str(HIGH): 8.0})
|
||||
|
||||
def test_names_a_subagent_by_its_meta_or_else_its_call_or_else_unknown(self):
|
||||
worker = [message("m1", "2026-10-14T10:00:00Z", call("Agent", "a1", subagent_type="Explore"), call("Agent", "a2", subagent_type="Plan"))]
|
||||
|
||||
@@ -102,7 +102,7 @@ def answer(checked: Checked, what: str, now: float) -> int:
|
||||
if checked.blocked:
|
||||
return 2
|
||||
logs = [(breach, reason, log_path(breach.directory)) for breach, reason in checked.overridden]
|
||||
# Resolve every log before writing any, so a call that ends blocked has logged nothing.
|
||||
# Resolve every log before writing any, so a call that ends blocked hasn't logged anything.
|
||||
unloggable = [f"{breach.rule}: {log.reason}" for breach, _, log in logs if isinstance(log, Failure)]
|
||||
if not unloggable:
|
||||
for breach, reason, log in logs:
|
||||
|
||||
@@ -55,7 +55,7 @@ RULES: dict[RuleName, Rule] = {
|
||||
),
|
||||
# A reviewer only reports, so no marker waives it.
|
||||
"reviewer-report": Rule(
|
||||
f"a reviewer writes nothing but its report, with Write, into a file under ~/{REPORTS}/",
|
||||
f"a reviewer writes only its report, with Write, into a file under ~/{REPORTS}/",
|
||||
"a Write, Edit or MultiEdit call from inside an agent under agents/",
|
||||
overridable=False,
|
||||
),
|
||||
|
||||
@@ -216,8 +216,8 @@ class OverrideLog(unittest.TestCase):
|
||||
class ReviewerRung(unittest.TestCase):
|
||||
# A worker routed to Sonnet 5.5 at high, on a project whose rung is Opus 5.5 at medium, with its reviewers on the project's rung.
|
||||
ENVIRON = {"LOOP_CLAUDE_PROJECT_RUNG": "claude-opus-5-5 at medium effort", "LOOP_CLAUDE_WORKER_RUNG": "claude-sonnet-5-5 at high effort", "LOOP_CLAUDE_ESCAPE_AND_IMPACT": "4"}
|
||||
# The same project, with a worker, and so its reviewers, routed above it to Fable 5.1 at max.
|
||||
ABOVE = {"LOOP_CLAUDE_PROJECT_RUNG": "claude-opus-5-5 at medium effort", "LOOP_CLAUDE_WORKER_RUNG": "claude-fable-5-1 at max effort", "LOOP_CLAUDE_ESCAPE_AND_IMPACT": "4"}
|
||||
# The same project, with a worker, and so its reviewers, routed above it to Fable 5.2 at max.
|
||||
ABOVE = {"LOOP_CLAUDE_PROJECT_RUNG": "claude-opus-5-5 at medium effort", "LOOP_CLAUDE_WORKER_RUNG": "claude-fable-5-2 at max effort", "LOOP_CLAUDE_ESCAPE_AND_IMPACT": "4"}
|
||||
|
||||
def refused(self, given: dict, environ: dict[str, str] = ENVIRON) -> list[str]:
|
||||
return rules(reviewer_breaches(Call("Agent", given, "/r"), environ))
|
||||
@@ -260,7 +260,7 @@ class ReviewerRung(unittest.TestCase):
|
||||
|
||||
def test_a_reviewer_on_the_project_rung_or_a_rerun_above_it_passes(self):
|
||||
self.assertEqual(self.refused({"subagent_type": "prose-reviewer", "model": "opus", "effort": "medium"}), [])
|
||||
self.assertEqual(self.refused({"subagent_type": "prose-reviewer", "model": "opus", "effort": "high"}), [])
|
||||
self.assertEqual(self.refused({"subagent_type": "prose-reviewer", "model": "fable", "effort": "low"}), [])
|
||||
|
||||
def test_an_agent_calls_prompt_is_the_text_scanned_for_a_marker(self):
|
||||
call = Call("Agent", {"subagent_type": "prose-reviewer", "prompt": "Review. # rule-override reviewer-rung: trust me"}, "/r")
|
||||
@@ -860,9 +860,9 @@ class Hook(unittest.TestCase):
|
||||
for rule in ["action-pin", "commit-one-line", "docker-run-memory", "ignorefile-sorted", "image-pin", "no-ai-attribution", "repeat-read", "reviewer-report", "reviewer-rung", "round-cap", "round-title-counts", "run-heavy", "todo-rank-check"]:
|
||||
with self.subTest(rule):
|
||||
self.assertIn(f" {rule}\n The rule: ", helped)
|
||||
self.assertIn("reviewer-report\n The rule: a reviewer writes nothing but its report", helped)
|
||||
self.assertIn("reviewer-report\n The rule: a reviewer writes only its report", helped)
|
||||
self.assertRegex(helped, r" reviewer-report\n( .*\n){2} Takes no override\.\n")
|
||||
self.assertRegex(helped, r" image-pin\n( .*\n){2} \S", "a rule a marker waives says nothing of overrides")
|
||||
self.assertRegex(helped, r" image-pin\n( .*\n){2} \S", "a rule a marker waives doesn't say anything of overrides")
|
||||
|
||||
|
||||
class TodoRankCheck(unittest.TestCase):
|
||||
@@ -900,7 +900,7 @@ class TodoRankCheck(unittest.TestCase):
|
||||
|
||||
def test_its_own_rank_todo_failing_silently_names_the_script_and_exit(self):
|
||||
checkout = self.changed_plan(f"{self.folder}/clone", "import sys\nsys.exit(3)\n")
|
||||
self.assertEqual(self.details(checkout), [f"{checkout}/bin/rank_todo.py --check failed with exit 3 and printed nothing"])
|
||||
self.assertEqual(self.details(checkout), [f"{checkout}/bin/rank_todo.py --check failed with exit 3 and printed no output"])
|
||||
|
||||
def test_its_own_rank_todo_running_past_the_limit_is_named(self):
|
||||
checkout = self.changed_plan(f"{self.folder}/clone", "import signal\nsignal.pause()\n")
|
||||
|
||||
@@ -36,7 +36,7 @@ def check_failures(top: str, todo: pathlib.Path, own: pathlib.Path) -> list[str]
|
||||
return [f"{script} --check could not run: {failure}"]
|
||||
if ran.returncode == 0:
|
||||
return []
|
||||
return ran.stderr.splitlines() or [f"{script} --check failed with exit {ran.returncode} and printed nothing"]
|
||||
return ran.stderr.splitlines() or [f"{script} --check failed with exit {ran.returncode} and printed no output"]
|
||||
|
||||
|
||||
def same_repo(top: str, own: pathlib.Path) -> bool:
|
||||
|
||||
Executable
+9
@@ -0,0 +1,9 @@
|
||||
#!/usr/bin/env python3
|
||||
import pathlib
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
|
||||
|
||||
from run_tests import main
|
||||
|
||||
sys.exit(main.main(sys.argv[1:]))
|
||||
@@ -61,7 +61,7 @@ def main(argv: list[str], env: typing.Mapping[str, str], cpus: int | None, memor
|
||||
|
||||
|
||||
def capping(memory: Memory | None, slots: int, env: typing.Mapping[str, str]) -> dict[str, str]:
|
||||
"""What the command's environment needs for its docker to cap each container it makes at the slot's share of memory; nothing where the memory is unknown, as off Linux, or where PATH finds no docker to cap."""
|
||||
"""What the command's environment needs for its docker to cap each container it makes at the slot's share of memory; none where the memory is unknown, as off Linux, or where PATH finds no docker to cap."""
|
||||
path = env.get("PATH", "")
|
||||
if memory is None or shutil.which("docker", path=without_path_entry(path)) is None:
|
||||
return {}
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
"""Run this repo's test suite as README.md → Test says, and print only what a reader needs from it.
|
||||
|
||||
usage: run-tests [<pytest args>...]
|
||||
|
||||
It runs pytest, pinned with pytest-xdist in one worker per CPU of a heavy slot through uvx, on the arguments given,
|
||||
adding the repo's bin/ folder where none of them names a path that exists. It saves the whole
|
||||
output to a new file. It prints each failing test's name, its first error lines and where it
|
||||
failed, then pytest's short test summary and summary line, then `Full log: <path>`. Where pytest
|
||||
printed no summary line, it prints the log's last lines in their place.
|
||||
|
||||
Exit 0 where every test passed, 1 otherwise, or where pytest cannot start, saying why.
|
||||
"""
|
||||
import os
|
||||
import pathlib
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
from machine_load.slots import CPUS_PER_SLOT
|
||||
|
||||
BIN = pathlib.Path(__file__).resolve().parents[1]
|
||||
# ci.sh runs this command, so its pins live here; README.md → Test's mutation command repeats the pytest pin, so change both. The workers fill one heavy slot, since run-heavy grants one.
|
||||
PYTEST = ["uvx", "--python", shutil.which("python3") or sys.executable, "--with", "pytest-xdist==3.8.0", "pytest==9.2.0", "-n", str(CPUS_PER_SLOT)]
|
||||
SECTION = re.compile(r"^=+ (.+) =+$")
|
||||
TEST_HEADER = re.compile(r"^_+ .+ _+$")
|
||||
# A traceback's last line, such as `bin/x/test_x.py:12: AssertionError`.
|
||||
LOCATION = re.compile(r"^\S+:\d+: \S")
|
||||
# pytest's last line, such as `==== 2 failed, 1 passed in 0.31s ====`, or without the rules under -q.
|
||||
SUMMARY_LINE = re.compile(r"^(=+ )?(no tests ran|\d+ \w+).* in [\d.]+s\b.*$")
|
||||
ERROR_LINES = 10
|
||||
LOG_TAIL = 20
|
||||
|
||||
|
||||
def pytest_args(argv: list[str]) -> list[str]:
|
||||
"""argv, with bin/ added where no argument names a path, so `run-tests -k name` still runs the suite."""
|
||||
if any(os.path.exists(arg.split("::")[0]) for arg in argv):
|
||||
return argv
|
||||
return [*argv, str(BIN)]
|
||||
|
||||
|
||||
def report(log: str) -> list[str]:
|
||||
"""What to print of pytest's output: each failing test's header, error lines and location, then the short test summary and the summary line; [] where pytest printed no summary line.
|
||||
|
||||
The error lines come from the FAILURES and ERRORS sections, since pytest-xdist leaves them out of the short summary's lines."""
|
||||
lines = log.splitlines()
|
||||
ends = [index for index, line in enumerate(lines) if SUMMARY_LINE.match(line)]
|
||||
if not ends:
|
||||
return []
|
||||
printed: list[str] = []
|
||||
section = ""
|
||||
errors = 0
|
||||
for line in lines[:ends[-1]]:
|
||||
heading = SECTION.match(line)
|
||||
if heading:
|
||||
section = heading.group(1)
|
||||
elif section in ("FAILURES", "ERRORS"):
|
||||
if TEST_HEADER.match(line):
|
||||
errors = 0
|
||||
printed.append(line)
|
||||
elif line.startswith("E "):
|
||||
errors += 1
|
||||
if errors <= ERROR_LINES:
|
||||
printed.append(line)
|
||||
elif LOCATION.match(line):
|
||||
if errors > ERROR_LINES:
|
||||
printed.append(f"E … {errors - ERROR_LINES} more lines in the log")
|
||||
printed.append(line)
|
||||
elif section == "short test summary info":
|
||||
printed.append(line)
|
||||
return [*printed, lines[ends[-1]]]
|
||||
|
||||
|
||||
def run(argv: list[str], pytest: list[str] = PYTEST, cwd: str | None = None) -> int:
|
||||
descriptor, log_path = tempfile.mkstemp(prefix="run-tests-", suffix=".log")
|
||||
with os.fdopen(descriptor, "w") as log:
|
||||
try:
|
||||
code = subprocess.run([*pytest, *pytest_args(argv)], stdout=log, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL, cwd=cwd).returncode
|
||||
except OSError as error:
|
||||
os.unlink(log_path)
|
||||
print(f"run-tests: cannot start {pytest[0]}: {error.strerror}", file=sys.stderr)
|
||||
return 1
|
||||
output = pathlib.Path(log_path).read_text(errors="replace")
|
||||
lines = report(output)
|
||||
if lines:
|
||||
print("\n".join(lines))
|
||||
else:
|
||||
print("run-tests: pytest printed no summary line; the log ends:")
|
||||
print("\n".join(output.splitlines()[-LOG_TAIL:]))
|
||||
print(f"Full log: {log_path}")
|
||||
return 0 if code == 0 else 1
|
||||
|
||||
|
||||
def main(argv: list[str]) -> int:
|
||||
if argv[:1] in (["-h"], ["--help"]):
|
||||
print(__doc__.strip())
|
||||
return 0
|
||||
return run(argv)
|
||||
@@ -0,0 +1,169 @@
|
||||
import contextlib
|
||||
import importlib.util
|
||||
import io
|
||||
from unittest import mock
|
||||
import os
|
||||
import pathlib
|
||||
import re
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from run_tests import main
|
||||
|
||||
BIN = pathlib.Path(__file__).resolve().parents[1]
|
||||
# The suite runs under pytest, and `python3 -m unittest` may run it where pytest is not installed.
|
||||
HAS_PYTEST = importlib.util.find_spec("pytest") is not None
|
||||
HAS_XDIST = importlib.util.find_spec("xdist") is not None
|
||||
PYTEST_HERE = [sys.executable, "-m", "pytest", "-p", "no:cacheprovider"]
|
||||
|
||||
|
||||
class PytestArgs(unittest.TestCase):
|
||||
def test_runs_bin_when_no_argument_names_a_path(self):
|
||||
self.assertEqual(main.pytest_args([]), [str(BIN)])
|
||||
self.assertEqual(main.pytest_args(["-k", "no_such_path_here"]), ["-k", "no_such_path_here", str(BIN)])
|
||||
|
||||
def test_passes_a_given_path_on_alone(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
test_file = pathlib.Path(folder, "test_x.py")
|
||||
test_file.write_text("")
|
||||
self.assertEqual(main.pytest_args([str(test_file)]), [str(test_file)])
|
||||
self.assertEqual(main.pytest_args(["-x", f"{test_file}::T::test_a"]), ["-x", f"{test_file}::T::test_a"])
|
||||
|
||||
|
||||
def errors(count: int) -> str:
|
||||
return "".join(f"E line {n}\n" for n in range(count))
|
||||
|
||||
|
||||
class Report(unittest.TestCase):
|
||||
def test_prints_each_failure_and_error_with_its_errors_then_the_summary(self):
|
||||
log = (
|
||||
"===== test session starts =====\nE not in a section\n"
|
||||
f"===== FAILURES =====\n_____ test_a _____\n\n def test_a():\n{errors(main.ERROR_LINES)}a.py:2: AssertionError\n"
|
||||
f"===== ERRORS =====\n_____ ERROR at setup of test_b _____\n{errors(main.ERROR_LINES + 3)}b.py:4: ValueError\n"
|
||||
"===== short test summary info =====\nFAILED a.py::test_a\nERROR b.py::test_b\n===== 1 failed, 1 error in 0.10s =====\n"
|
||||
)
|
||||
self.assertEqual(main.report(log), [
|
||||
"_____ test_a _____", *errors(main.ERROR_LINES).splitlines(), "a.py:2: AssertionError",
|
||||
"_____ ERROR at setup of test_b _____", *errors(main.ERROR_LINES).splitlines(), "E … 3 more lines in the log", "b.py:4: ValueError",
|
||||
"FAILED a.py::test_a", "ERROR b.py::test_b", "===== 1 failed, 1 error in 0.10s =====",
|
||||
])
|
||||
|
||||
def test_prints_nothing_where_pytest_printed_no_summary_line(self):
|
||||
self.assertEqual(main.report("usage: pytest\nerror: unrecognized arguments\n"), [])
|
||||
|
||||
|
||||
class Main(unittest.TestCase):
|
||||
def test_prints_the_help_for_h_or_help_first_and_runs_anything_else(self):
|
||||
for argv in (["-h"], ["--help"], ["--help", "bin/x"]):
|
||||
with self.subTest(argv=argv):
|
||||
out = io.StringIO()
|
||||
with contextlib.redirect_stdout(out), mock.patch.object(main, "run") as run:
|
||||
self.assertEqual(main.main(argv), 0)
|
||||
self.assertEqual(out.getvalue(), main.__doc__.strip() + "\n")
|
||||
run.assert_not_called()
|
||||
with mock.patch.object(main, "run", return_value=1) as run:
|
||||
self.assertEqual(main.main(["bin/x", "-h"]), 1)
|
||||
run.assert_called_once_with(["bin/x", "-h"])
|
||||
|
||||
|
||||
class RunWithAStandIn(unittest.TestCase):
|
||||
"""run with a stand-in for pytest: a Python script given the arguments run passes on."""
|
||||
|
||||
def run_script(self, script: str, cwd: str | None = None) -> tuple[int, str, str]:
|
||||
out, err = io.StringIO(), io.StringIO()
|
||||
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
|
||||
code = main.run(["-x"], [sys.executable, "-c", script], cwd)
|
||||
lines = out.getvalue().splitlines()
|
||||
if lines and lines[-1].startswith("Full log: "):
|
||||
self.addCleanup(os.unlink, lines[-1].removeprefix("Full log: "))
|
||||
return code, out.getvalue(), err.getvalue()
|
||||
|
||||
def test_saves_the_log_as_run_tests_star_log_in_the_temp_folder_which_ci_sh_prints(self):
|
||||
code, out, _ = self.run_script("print('== 1 passed in 0.1s ==')")
|
||||
self.assertEqual(code, 0)
|
||||
log = pathlib.Path(out.splitlines()[-1].removeprefix("Full log: "))
|
||||
self.assertEqual(log.parent, pathlib.Path(tempfile.gettempdir()))
|
||||
self.assertRegex(log.name, r"^run-tests-.+\.log$")
|
||||
|
||||
def test_runs_in_the_folder_given_and_shows_the_last_lines_of_a_log_without_a_summary(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
script = "import os, sys; sys.stdout.buffer.write(b'bad \\xff byte\\n'); print('\\n'.join(map(str, range(30)))); print(os.getcwd())"
|
||||
code, out, _ = self.run_script(script, folder)
|
||||
self.assertEqual(code, 0)
|
||||
tail = [str(n) for n in range(30 - main.LOG_TAIL + 1, 30)] + [os.path.realpath(folder)]
|
||||
self.assertEqual(out.splitlines()[:-1], ["run-tests: pytest printed no summary line; the log ends:", *tail])
|
||||
|
||||
def test_reads_a_log_that_is_not_utf_8(self):
|
||||
code, out, _ = self.run_script("import sys; sys.stdout.buffer.write(b'\\xff\\n== 1 failed in 0.1s ==\\n'); sys.exit(1)")
|
||||
self.assertEqual(code, 1)
|
||||
self.assertIn("== 1 failed in 0.1s ==", out)
|
||||
|
||||
def test_says_on_stderr_that_a_command_cannot_start(self):
|
||||
out, err = io.StringIO(), io.StringIO()
|
||||
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
|
||||
code = main.run([], ["/no/such/uvx"])
|
||||
self.assertEqual((code, out.getvalue()), (1, ""))
|
||||
self.assertEqual(err.getvalue(), "run-tests: cannot start /no/such/uvx: No such file or directory\n")
|
||||
|
||||
|
||||
@unittest.skipUnless(HAS_PYTEST, "needs pytest importable")
|
||||
class Run(unittest.TestCase):
|
||||
def run_in(self, folder: str, pytest: list[str], *args: str) -> tuple[int, str]:
|
||||
out = io.StringIO()
|
||||
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(out):
|
||||
code = main.run(list(args), pytest, folder)
|
||||
return code, out.getvalue()
|
||||
|
||||
def log_named(self, output: str) -> pathlib.Path:
|
||||
last = output.rstrip("\n").splitlines()[-1]
|
||||
self.assertTrue(last.startswith("Full log: "), output)
|
||||
path = pathlib.Path(last.removeprefix("Full log: "))
|
||||
self.addCleanup(path.unlink, missing_ok=True)
|
||||
return path
|
||||
|
||||
def test_a_passing_run_prints_the_summary_line_and_the_log_path(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
pathlib.Path(folder, "test_ok.py").write_text("def test_ok():\n\tprint('noise from a passing test')\n")
|
||||
code, output = self.run_in(folder, PYTEST_HERE, "-s", folder)
|
||||
self.assertEqual(code, 0)
|
||||
lines = output.rstrip("\n").splitlines()
|
||||
self.assertEqual(len(lines), 2, output)
|
||||
self.assertRegex(lines[0], r"^=+ 1 passed in .* =+$")
|
||||
self.assertIn("noise from a passing test", self.log_named(output).read_text())
|
||||
|
||||
def test_a_failing_run_prints_each_failing_test_with_its_error(self):
|
||||
# pytest-xdist drops the error from the short summary's lines, so the run takes it from the FAILURES section.
|
||||
workers = ["-n", "2"] if HAS_XDIST else []
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
pathlib.Path(folder, "test_bad.py").write_text("def test_ok():\n\tpass\n\ndef test_bad():\n\tassert 1 == 2, 'one is not two'\n\ndef test_long():\n\traise ValueError('\\n'.join(map(str, range(30))))\n")
|
||||
code, output = self.run_in(folder, PYTEST_HERE, *workers, folder)
|
||||
self.assertEqual(code, 1)
|
||||
self.assertRegex(output, r"(?m)^_+ test_bad _+\nE +AssertionError: one is not two\n(E .*\n)*.*test_bad\.py:5: AssertionError$")
|
||||
self.assertRegex(output, r"(?m)^FAILED .*test_bad\.py::test_bad\b")
|
||||
self.assertRegex(output, r"(?m)^E +… \d+ more lines in the log$")
|
||||
self.assertEqual(len(re.findall(r"(?m)^E ", output)), 2 + main.ERROR_LINES + 1)
|
||||
self.assertRegex(output, r"=+ 2 failed, 1 passed in .* =+\n")
|
||||
self.assertNotIn("def test_bad", output)
|
||||
self.assertIn("def test_bad", self.log_named(output).read_text())
|
||||
|
||||
def test_a_run_that_cannot_start_says_so(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
code, output = self.run_in(folder, [os.path.join(folder, "no-such-uvx")])
|
||||
self.assertEqual(code, 1)
|
||||
self.assertIn("run-tests: cannot start", output)
|
||||
self.assertNotIn("Full log: ", output)
|
||||
|
||||
def test_a_run_that_prints_no_summary_line_shows_the_logs_last_lines(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
code, output = self.run_in(folder, PYTEST_HERE, "--no-such-option", folder)
|
||||
self.assertEqual(code, 1)
|
||||
self.assertIn("run-tests: pytest printed no summary line; the log ends:", output)
|
||||
self.assertIn("--no-such-option", output)
|
||||
self.log_named(output)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
+42
-16
@@ -1,4 +1,4 @@
|
||||
"""The rung search judge-replay and review-replay share: replay archived cases on a reference rung, then hold each candidate rung to what the reference reproduced."""
|
||||
"""Replay archived cases on a rung, as judge-replay and review-replay both do; and judge-replay's rung search, which holds each candidate rung to what a reference rung reproduced."""
|
||||
import concurrent.futures
|
||||
import dataclasses
|
||||
import sys
|
||||
@@ -35,10 +35,11 @@ class Tried(typing.Generic[Case, Aim, Answer]):
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Replay(typing.Generic[Case, Aim, Answer]):
|
||||
"""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 holds the reference's reply on each case; tried, each candidate tried, highest first; lowest, the lowest candidate that, like each candidate above it, didn't miss anything, or None; climbed, each climb tried, in the order given."""
|
||||
on_reference: list[Answer]
|
||||
tried: list[Tried[Case, Aim, Answer]]
|
||||
lowest: Rung | None
|
||||
climbed: list[Tried[Case, Aim, Answer]] = dataclasses.field(default_factory=list)
|
||||
|
||||
|
||||
def replayed(
|
||||
@@ -48,31 +49,56 @@ def replayed(
|
||||
replay_one: typing.Callable[[Case, Rung], Answer | Limited],
|
||||
reproduced: typing.Callable[[Case, Answer], list[Aim]],
|
||||
what: str,
|
||||
climbs: typing.Sequence[Rung] = (),
|
||||
) -> Replay[Case, Aim, Answer] | 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.
|
||||
"""Replays the cases on the reference rung, then on each climb and each candidate, on the cases where the reference reproduced anything.
|
||||
|
||||
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.
|
||||
A climb is a rung above the candidates, such as one a chunk's E + I raises a review to. The rungs a route picks there don't follow from one another, so each climb is tried whatever another misses.
|
||||
|
||||
The candidates are tried highest first, until one misses an item the reference reproduced. Going down, every candidate at or above the one named was tried and didn't miss anything, 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))]
|
||||
# Without anything to hold a rung to, no rung would miss anything.
|
||||
if not held:
|
||||
return Replay(on_reference, [], None)
|
||||
climbed: list[Tried[Case, Aim, Answer]] = []
|
||||
for rung in climbs:
|
||||
climb = tried_on(held, rung, replay_one, reproduced, what)
|
||||
if isinstance(climb, Limited):
|
||||
return climb
|
||||
climbed.append(climb)
|
||||
tried: list[Tried[Case, Aim, Answer]] = []
|
||||
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, Aim, Answer]] = []
|
||||
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:
|
||||
for rung in candidates:
|
||||
candidate = tried_on(held, rung, replay_one, reproduced, what)
|
||||
if isinstance(candidate, Limited):
|
||||
return candidate
|
||||
tried.append(candidate)
|
||||
if candidate.missed:
|
||||
break
|
||||
lowest = rung
|
||||
return Replay(on_reference, tried, lowest)
|
||||
return Replay(on_reference, tried, lowest, climbed)
|
||||
|
||||
|
||||
def tried_on(
|
||||
held: list[tuple[Case, list[Aim]]],
|
||||
rung: Rung,
|
||||
replay_one: typing.Callable[[Case, Rung], Answer | Limited],
|
||||
reproduced: typing.Callable[[Case, Answer], list[Aim]],
|
||||
what: str,
|
||||
) -> Tried[Case, Aim, Answer] | Limited:
|
||||
"""rung and each item, of those the reference reproduced in the held cases, that its replies missed."""
|
||||
replies = replayed_on([case for case, _ in held], rung, replay_one, what)
|
||||
if isinstance(replies, Limited):
|
||||
return replies
|
||||
misses: list[Miss[Case, Aim, Answer]] = []
|
||||
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]
|
||||
return Tried(rung, misses)
|
||||
|
||||
|
||||
def replayed_on(cases: list[Case], rung: Rung, replay_one: typing.Callable[[Case, Rung], Answer | Limited], what: str) -> list[Answer] | Limited:
|
||||
|
||||
@@ -18,7 +18,7 @@ CHEAP = Rung("claude-haiku-5-5", "max")
|
||||
LOWER = Rung("claude-haiku-5-5", "xhigh")
|
||||
|
||||
|
||||
def search(cases, candidates, replies):
|
||||
def search(cases, candidates, replies, climbs=()):
|
||||
"""replayed on cases named by strings, where replies[rung][case] is the set of items a rung reproduces in the case."""
|
||||
asked = []
|
||||
|
||||
@@ -28,7 +28,7 @@ def search(cases, candidates, replies):
|
||||
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
|
||||
return replayed(cases, REFERENCE, candidates, replay_one, lambda _, reply: sorted(reply), "cases", climbs), asked
|
||||
|
||||
|
||||
class Replayed(unittest.TestCase):
|
||||
@@ -46,8 +46,17 @@ class Replayed(unittest.TestCase):
|
||||
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_holds_each_climb_to_what_the_reference_reproduced_whatever_another_climb_misses(self):
|
||||
high, higher = Rung("claude-fable-5-2", "low"), Rung("claude-fable-5-2", "high")
|
||||
replies = {REFERENCE: {"a": {0}, "b": set()}, high: {"a": set()}, higher: {"a": {0}}, MIDDLE: {"a": {0}}}
|
||||
replay, asked = search(["a", "b"], [MIDDLE], replies, [high, higher])
|
||||
self.assertEqual(replay, Replay([{0}, set()], [Tried(MIDDLE, [])], MIDDLE, [Tried(high, [Miss("a", 0, set())]), Tried(higher, [])]))
|
||||
self.assertNotIn(("b", high), asked)
|
||||
self.assertEqual(search(["a"], [MIDDLE], {REFERENCE: {"a": set()}}, [high]), (Replay([set()], [], None, []), [("a", REFERENCE)]))
|
||||
|
||||
def test_stops_at_a_usage_limit(self):
|
||||
limit = Limited(None, "limit")
|
||||
self.assertEqual(search(["a"], [MIDDLE], {REFERENCE: {"a": {0}}, MIDDLE: {"a": {0}}, CHEAP: limit}, [CHEAP])[0], limit)
|
||||
self.assertEqual(search(["a"], [MIDDLE], {REFERENCE: limit})[0], limit)
|
||||
self.assertEqual(search(["a"], [MIDDLE, CHEAP], {REFERENCE: {"a": {0}}, MIDDLE: limit})[0], limit)
|
||||
|
||||
@@ -64,7 +73,7 @@ class FirstReply(unittest.TestCase):
|
||||
|
||||
class DownFrom(unittest.TestCase):
|
||||
def test_runs_from_the_projects_rung_down_to_the_floor_highest_first(self):
|
||||
self.assertEqual(down_from(Rung("claude-opus-5-5", "high"), MIDDLE), [Rung("claude-opus-5-5", "high"), REFERENCE, MIDDLE])
|
||||
self.assertEqual(down_from(Rung("claude-fable-5-2", "low"), MIDDLE), [Rung("claude-fable-5-2", "low"), REFERENCE, MIDDLE])
|
||||
self.assertEqual(down_from(REFERENCE, MIDDLE), [REFERENCE, MIDDLE])
|
||||
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user