Compare commits
69 Commits
item-373
...
patch-0.10.1
| Author | SHA1 | Date | |
|---|---|---|---|
| bf1897b1a0 | |||
| 34468c20d7 | |||
| bedd304479 | |||
| daaa61b607 | |||
| 3422a39b6f | |||
| d2133c410f | |||
| a62992d877 | |||
| 2ecec90ec5 | |||
| 46135acab6 | |||
| 8d58dec886 | |||
| c5acadf8d3 | |||
| 0a20b6d4f6 | |||
| 58b098b89d | |||
| 564b022c93 | |||
| e8ef498977 | |||
| 4abefba032 | |||
| e8988b5192 | |||
| 4854ea0624 | |||
| d9c4e71f8d | |||
| 39163df349 | |||
| 1715c58548 | |||
| cbf007f68c | |||
| 510df4b31d | |||
| f830d764cd | |||
| e71170a2d6 | |||
| 3f2046f4be | |||
| 54ab1e4c69 | |||
| d07d108943 | |||
| e44d5bef50 | |||
| b057cc0deb | |||
| aa55d01564 | |||
| b60d921427 | |||
| 9b56738935 | |||
| 2b5e4998cc | |||
| cab71cc03e | |||
| d432fa207f | |||
| a976ef611d | |||
| 39e4e5d4f8 | |||
| 2e6f6d91cf | |||
| b405c81d10 | |||
| da5eb0d203 | |||
| 1f963024c8 | |||
| dfa2989e8b | |||
| 854a8cccda | |||
| cce83286d3 | |||
| ac71228969 | |||
| dd9da17240 | |||
| addfead4c7 | |||
| e3875d2b05 | |||
| 6326edcd5b | |||
| e78725db51 | |||
| 60bc76c876 | |||
| 7f5c3fcbbc | |||
| 6687c913e2 | |||
| a194747012 | |||
| 73f7cf1a62 | |||
| a9c15b79a0 | |||
| 155f1e873c | |||
| 0aa89d283e | |||
| 669a2833c5 | |||
| fe31d6eae5 | |||
| 35f1f5e70f | |||
| af8e7ad3d1 | |||
| 2a7018dc43 | |||
| a0945b6dae | |||
| 800f7b3031 | |||
| 8e79cb7dc8 | |||
| 6804b9496e | |||
| 50d34ce804 |
@@ -74,6 +74,7 @@
|
||||
!bin/metric_bench/*.py
|
||||
!bin/model_routing/
|
||||
!bin/model_routing/*.py
|
||||
!bin/model_routing/routing-ladder.json
|
||||
!bin/mutate-changes
|
||||
!bin/mutate_changes/
|
||||
!bin/mutate_changes/*.py
|
||||
|
||||
+10
-1
@@ -2,6 +2,11 @@
|
||||
|
||||
## Unreleased
|
||||
|
||||
- Two loop-claude runs in one project now work side by side, each on its own chunk. Each loop holds a slot of the project, a locked file under `~/.local/state/loop-claude/<key>/`, and names its session after it: the first loop's session keeps its name, `A <key> loop-claude`, and the second's is `A <key> loop-claude 2`. A rerun resumes a chunk left open first. A commit in the config's folder now takes only the file it changed, as `git commit -m <title> -- <file>`.
|
||||
- `todo-item finish` finishes an item of a plan kept in a Jira epic: it moves the item's issue by the workflow transition, and to the status, that the config's new optional settings `jira-finish-transition` and `jira-finish-status` name, both as Jira shows them. It refuses a transition that leads to another status, or to one Jira doesn't count as done, and fails where the config sets neither.
|
||||
- Reviewers and loop-claude's judge read the review standards from the folder a project's config sets as `standards`, in place of `~/.claude/skills/larv-review/standards/`. The setting is required. To upgrade, add `standards = "~/.claude/skills/larv-review/standards"` to every config under `~/.claude-projects/` right after `deploy-release` moves `~/.claude` to this release, and not before.
|
||||
- A project's config may keep each of its five records on a Confluence Cloud page: set, for example, `decisions = "confluence:https://<site>/wiki/spaces/<space>/pages/<page ID>"`, with the credentials in the config's `env-file`. `decisions` and `comprehension-history` may name a page only where `plan` names a Jira epic. The loop reads and writes the page as markdown, so a save replaces a mention or a macro on it with plain text. It never overwrites a teammate's edit: where someone saved the page since the loop read it, `project-record save` refuses and the loop asks you.
|
||||
- `todo-item add` files an item into a plan kept in a Jira epic: a Task under the epic, under the project's Fix Version for the release, labelled `security` for a security finding and linked to each item that blocks it. Editing an issue still happens in Jira.
|
||||
- An item of the next release may predict the files and parts it will touch, under a `Touches:` line in its detail. `chunk-preflight` then names the items that may start chunks at once, and the new `touch-predictions record` keeps each prediction beside what the merged chunk touched, in the record a project's config places with `touch-predictions`.
|
||||
- CLAUDE.md and the todo-items rule define the plan as a todo.md or a Jira epic, and say plan where todo.md was false for a Jira plan.
|
||||
- Reviewers without a shell read the plan from a listing that larv-review writes into the review folder, whichever store holds it.
|
||||
@@ -18,11 +23,15 @@
|
||||
- The technical principles ask for code in files and folders before `// --- name ---` banner comments. They also ask for an entry point a newcomer finds at once: the root holds it, the README and the files a tool reads only from there.
|
||||
- In a client project, the loop reads the team's own `CLAUDE.md` and `AGENTS.md` and proposes each change that aligns them with this setup in a pull request of its own. Where the team declines or doesn't answer, the loop follows the team's rule unless it breaks a project goal, and records the conflict as a decision in the `decisions` record.
|
||||
- The new `project-record open <record>` prints the file in which an agent reads and edits one of a project's five records (`decisions`, `score-anchors`, `comprehension-history`, `reading-cost` and `changelog`), and `project-record save <record>` stores the edit. Every tool now reads and writes a record the same one way, so that a later release can keep a record outside files. No config needs a change.
|
||||
- `loop-inbox` is gone. loop-claude now asks its questions only on its own terminal. A line typed there answers a question, and `/talk` opens the worker's session. The DM still tells you a loop waits. To upgrade, quit any `loop-inbox` still open and remove your `~/.local/bin/loop-inbox` link. Once every loop started before the upgrade has reloaded or ended, remove the folder `~/.local/state/loop-claude/`, which nothing reads any more.
|
||||
- `loop-inbox` is gone. loop-claude now asks its questions only on its own terminal. A line typed there answers a question, and `/talk` opens the worker's session. The DM still tells you a loop waits. To upgrade, quit any `loop-inbox` still open and remove your `~/.local/bin/loop-inbox` link.
|
||||
- rule-hook refuses a Read or a Grep of `~/.claude/.env` or of the `env-file` any project's config names, and a Bash command that names either or searches a folder holding either with `ag`, `grep -r` or `rg`, unless the tool skips the file as hidden or ignored, so that a worker doesn't put a credential in its transcript in passing. A command that hides the path, such as behind a glob or a variable, still goes through.
|
||||
- A project's config names the service for loop-claude's DMs: `notifier = "mattermost"` or `"slack"`, with the bot's token and the recipient in the `env-file`. To upgrade, move the Mattermost keys from `~/.claude/.env` into a file outside the checkout and the config's folder, such as `~/.claude-projects/<key>.env`, name it as `env-file` and add `notifier = "mattermost"`. A project with no `notifier` gets no DM, and `~/.claude/.env` is no longer read. A failure names each missing key and holds no token.
|
||||
- `mattermost-dm` is now `notify`, which sends through the project's `notifier`; `notify --help` names the keys.
|
||||
|
||||
## 0.10.1
|
||||
|
||||
- The routing ladder is now a file, `bin/model_routing/routing-ladder.json`, and a project may run on a ladder of its own: a `routing-ladder.json` in its config's folder, `~/.claude-projects/<key>/`, replaces the shipped ladder whole for that project, and loop-claude says so as each cycle starts. loop-claude, `subagent-rung` and rule-hook read the project's ladder; the routing figures, `judge-replay` and `review-replay` read the shipped one. `subagent-rung` now reads the config of the checkout it runs in, and exits 1 where that config or the ladder holds a fault; loop-claude stops on a faulty ladder as it does on a faulty config. `loop-claude --help` shows the file's shape, and README → Install → "Set up a project" says when to write one.
|
||||
|
||||
## 0.10.0
|
||||
|
||||
- The loop commits each change it makes to a file in the config's folder, such as a plan kept there, in that folder's git repo, titled as it titles its commits in the checkout. rule-hook ranks the plan on such a commit; before, it refused the commit.
|
||||
|
||||
@@ -2,11 +2,11 @@
|
||||
|
||||
## Working loop
|
||||
|
||||
How work proceeds in any repo, unless the repo's `AGENTS.md` says otherwise. The *next release* is the earliest one not yet cut. A rule names a project's files by their usual paths: `todo.md`, `AGENTS.md`, `CHANGELOG.md` and the files under `docs/`. Each is where the project's config puts it, which `~/.claude/bin/project-config` prints and `chunk-preflight`'s facts quote. Where the config names a Jira epic as the plan, the plan is the epic's open child issues, which no tool writes yet. Read and edit a project record in the file `~/.claude/bin/project-record open <record>` prints, and run `project-record save <record>` after each edit. Other words, such as *chunk*, are defined under "Vocabulary" at the end of this file.
|
||||
How work proceeds in any repo, unless the repo's `AGENTS.md` says otherwise. The *next release* is the earliest one not yet cut. A rule names a project's files by their usual paths: `todo.md`, `AGENTS.md`, `CHANGELOG.md` and the files under `docs/`. Each is where the project's config puts it, which `~/.claude/bin/project-config` prints and `chunk-preflight`'s facts quote. Where the config names a Jira epic as the plan, the plan is the epic's open child issues. Read and edit a project record in the file `~/.claude/bin/project-record open <record>` prints, and run `project-record save <record>` after each edit. Other words, such as *chunk*, are defined under "Vocabulary" at the end of this file.
|
||||
|
||||
- **Until the goals file has a `## Goals` and an `## Audience` section, writing them is the only work.** Not even planning. In a README both are public: an outside reader judges a project by where it is heading and who it is for. Goals or an audience written anywhere else, such as `AGENTS.md` or `docs/`, do not count; the one exception is code health, which "Shared goal" below states for every project.
|
||||
- **Keep a plan in `todo.md` as one scored table, in the shape whose example `~/.claude/bin/rank_todo.py --help` shows**: every item names the release that ships it. Until `todo.md` has that shape, reshaping it is the only work, and the human approves it.
|
||||
- **Read and change the plan's items only with `~/.claude/bin/todo-item`**, which lists, shows, files, edits, moves and finishes them; `todo-item --help` says how. It reads a plan in Jira as it does a file, and writes only a file for now. Two open the file itself: whoever plans a release, to compare Scores across releases, which `todo-item list` doesn't print; and whoever edits `## Scoring` or `## Renamed`, or reshapes an old table.
|
||||
- **Read and change the plan's items only with `~/.claude/bin/todo-item`**, which lists, shows, files, edits, moves and finishes them; `todo-item --help` says how. It reads a plan in Jira as it does a file, and there it files and finishes an item but doesn't edit or move one yet. Two open the file itself: whoever plans a release, to compare Scores across releases, which `todo-item list` doesn't print; and whoever edits `## Scoring` or `## Renamed`, or reshapes an old table.
|
||||
- **When the next release has no items and no work has landed towards it, plan it as this chunk.** Move the highest-scoring items of later releases into it, and get the human's approval of that set before writing any code.
|
||||
- **When the next release has no items left and work has landed towards it, its release review is the chunk** (`larv-review` §3 → "Release review"). **Once that has merged and the release holds no item, the release is finished: stop.** Report what it holds and that it is ready to cut. Under `/loop`, this ends the loop. Until the human cuts it, only a security fix, or an item its release review filed, lands, into that release; never start a later release's items or plan a new one.
|
||||
- **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.
|
||||
@@ -46,7 +46,7 @@ Write the thing, not an introduction to it. State what holds and stop; name a re
|
||||
|
||||
Write negations as people say them: after a verb, or after its preposition, write `doesn't <verb> anything` or `anyone`, never `<verb> nothing` or `no one`. BANNED: `stops nothing`, `depends on no one`, `so answering in time costs nothing`. GOOD: `doesn't stop anything`, `doesn't depend on anyone`, `so answering in time doesn't cost anything`.
|
||||
|
||||
Reviewers hold prose to the full rules, with examples: `~/.claude/skills/larv-review/standards/prose.md`.
|
||||
Reviewers hold prose to the full rules, with examples: `prose.md` in the project's review standards, which "Topic rules" below defines.
|
||||
|
||||
## Public API specs
|
||||
- Text in public API specs (OpenAPI `description`/`title` fields, in a spec file or in code, and the generated api-docs) is read by external consumers. Never leak internal references: no ticket IDs, internal URLs, repo/system code-names, "see ticket X". Describe behaviour in consumer terms. GOOD: `Deprecated alias for paymentAccountId`. BANNED: `…will be removed (ABC-123)`.
|
||||
@@ -60,7 +60,7 @@ Claude Code loads a rule file when a session writes a file its `paths:` frontmat
|
||||
- Goals and audience: `~/.claude/rules/goals-and-audience.md`.
|
||||
- Plan items, their scores and Exempt reasons: `~/.claude/rules/todo-items.md`. Read it before you file, score, edit or move an item: a session that runs `todo-item` never opens `todo.md` itself, so the rule doesn't load.
|
||||
|
||||
The rules only reviewers apply, for quality, comments, READMEs and prose, live in `~/.claude/skills/larv-review/standards/`.
|
||||
The rules only reviewers apply, for quality, comments, READMEs and prose, are the project's review standards: the folder its config sets as `standards`, which `~/.claude/bin/project-config standards` prints.
|
||||
|
||||
## Working with the codebase
|
||||
- Always start a new git worktree when doing something in a codebase, and clean it up when done. Unless told otherwise, branch it off a freshly-updated default branch (`git fetch origin`, then base on `origin/main`), not whatever happens to be checked out.
|
||||
@@ -78,7 +78,7 @@ The rules only reviewers apply, for quality, comments, READMEs and prose, live i
|
||||
1. A re-score of the item's L, made on the project's rung or above, picks a rung above yours.
|
||||
2. The same failing test or finding survives two fix attempts.
|
||||
3. A pass reports a 🔴 in round 2.
|
||||
4. A review rules the work below standard: systems-architect's BLOCK, a finding against larv-review's `standards/quality.md`, or a vote `record-ruling` counts as worse, in the report that stands after any relaunch one rung up (`larv-review` §3 → "Rung up"). It doesn't fire where the fix changes only prose (`larv-review` §3 says what is prose): fix that on your own rung.
|
||||
4. A review rules the work below standard: systems-architect's BLOCK, a finding against the review standards' `quality.md`, or a vote `record-ruling` counts as worse, in the report that stands after any relaunch one rung up (`larv-review` §3 → "Rung up"). It doesn't fire where the fix changes only prose (`larv-review` §3 says what is prose): fix that on your own rung.
|
||||
|
||||
When one fires, hand the hard part, edits included, to a subagent on the rung loop-claude's prompt names, one above yours. Open the subagent's prompt with the marker loop-claude's prompt gives, then the trigger's evidence. Each later subagent on that task runs on that rung or higher, and each further escalation trigger moves the task one rung higher, up to the highest rung loop-claude's prompt names. Ask the human before going higher. Where loop-claude's prompt names no escalation, as on the ladder's top rung or off it, keep the task in your own thread.
|
||||
- Give a subagent only the access its job needs, and state the limits in its prompt. One that only reads, such as a prose review, gets no shell and no edits. A reviewer under `~/.claude/agents/` writes only its report, under `~/.local/state/larv-review/`, and rule-hook refuses it every other Write, every Edit and every MultiEdit. One that probes a build tags the image as throwaway and removes it afterwards, writes only to a folder it makes under the chunk's review folder (`~/.claude/bin/larv-review review-folder` prints it), and removes no image or file it did not create.
|
||||
@@ -97,7 +97,7 @@ The rules only reviewers apply, for quality, comments, READMEs and prose, live i
|
||||
- PR summary: short and concise. No test plan (it lives in the ticket), no link to the ticket (it's in the title).
|
||||
- Branch for a ticket: exactly the ticket ID, nothing more. `ABC-123`, never `ABC-123-some-description`.
|
||||
- Branch for a plan item without a ticket: `item-<ID>`, in the worktree `<checkout>-item-<ID>` beside the checkout, as `chunk-preflight` makes them. Under a `branch` template, `chunk-preflight` names both by the template.
|
||||
- Where the project's config keeps a file in the config's folder, `~/.claude-projects/<key>/`, such as the plan or a record, commit each change you make to that file in the folder's own git repo, on its only branch. Title that commit as you would title the change in the checkout: where a commit in the checkout goes with it, give it the same title.
|
||||
- Where the project's config keeps a file in the config's folder, `~/.claude-projects/<key>/`, such as the plan or a record, commit each change you make to that file in the folder's own git repo, on its only branch. Two chunks may commit there at once, so commit only that file: `git commit -m <title> -- <file>`, after `git add <file>` where it is new. Where git finds `index.lock` held, the other chunk is committing: try again. Title that commit as you would title the change in the checkout: where a commit in the checkout goes with it, give it the same title.
|
||||
- Use `gh` on GitHub remotes and `tea` on Gitea remotes (e.g. `gitea.larvit.se`) — same command shape: `tea pr list|create`, `tea issue`, `tea release`, `tea api`. Everything in this section applies to both.
|
||||
- On GitHub and Gitea, open a chunk's pull request as a draft, mark it ready and merge it with `~/.claude/bin/chunk-pr`, which picks `gh` or `tea` from the remote; `chunk-pr --help` says how. Once it has merged, run `chunk-pr clean` in the chunk's worktree: it removes the worktree and the branch and fast-forwards the main checkout.
|
||||
|
||||
@@ -130,7 +130,7 @@ Claude Code reads this section by its heading when it compacts a conversation. K
|
||||
- **goals file** — the file holding a project's `## Goals` and `## Audience`: the one its config names as `goals-and-audience`. Read it in the file `~/.claude/bin/project-record open goals-and-audience` prints. It is `README.md`, unless a client's project keeps it in the config's folder, or in a Jira epic's description, which the loop only reads.
|
||||
- **interrupt** — `loop-claude` asking the human, on its terminal, for a decision that is theirs. They type a one-line answer there, or `/talk` to open the worker's session there with `claude --resume`. A release ready to cut opens that session at once. A routing call opens claude on that terminal too, in `~/code/claude-config`, the checkout where this setup is developed.
|
||||
- **judge** — the headless claude that reads a worker's transcript each cycle and decides whether to interrupt and whether the chunk is finished.
|
||||
- **judge's records** — the files the judge reads beside the premises: the project's `AGENTS.md` and `docs/decisions.md`, then the human's `~/.claude/CLAUDE.md` and the `.md` files in `~/.claude/rules/` and `~/.claude/skills/larv-review/standards/`.
|
||||
- **judge's records** — the files the judge reads beside the premises: the project's `AGENTS.md` and `docs/decisions.md`, then the human's `~/.claude/CLAUDE.md` and the `.md` files in `~/.claude/rules/`, then those in the project's review standards.
|
||||
- **paired ruling** — the seats vote whether the project reads better, the same or worse at the branch's head than at the base, the commit `larv-review ruling-base` prints; `larv-review --help` says how the votes make the ruling.
|
||||
- **pass** — one kind of review a chunk may take, run in rounds by its reviewers until clean; `larv-review` §3 lists them.
|
||||
- **place** — the smallest addressable unit, such as a function or a section heading, that a seat names with its `path:line` when it judges how hard the project is to read there.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Claude Code configuration
|
||||
|
||||
My personal `~/.claude`, version controlled: `CLAUDE.md` and `rules/` for instructions, the words under `CLAUDE.md` → "Vocabulary"; `.claude/rules/` for the rules that load in this repo alone; `agents/` and `skills/`; `principles/` and `skills/larv-review/standards/` for what the reviewer agents hold projects to; `docs/` for decisions and the comprehension history; `settings.json` for the harness and `.claude/settings.json` for the harness inside this repo; `CHANGELOG.md` and `todo.md`; the tools in `bin/`; `workflow-bench/`, the scripts and prompts of the 2026-09-30 bench of larv-review and of the 2026-11-12 bench of the advisor tool; `reviewer-merge-trials/`, the 2026-11-09 trials of merging reviewers, with their method, results and scripts; `judge-field-trials/`, the 2026-11-11 trials of which facts code could read in place of loop-claude's judge, with their results and scripts; `stability-skip-count/`, the 2026-11-12 count of archived stability rounds, with its script, from which larv-review took when to skip a stability round 2; and `presentation/`, a page that explains this setup to newcomers, with the script that prints it to PDF.
|
||||
My personal `~/.claude`, version controlled: `CLAUDE.md` and `rules/` for instructions, the words under `CLAUDE.md` → "Vocabulary"; `.claude/rules/` for the rules that load in this repo alone; `agents/` and `skills/`; `principles/` and `skills/larv-review/standards/` for what the reviewer agents hold projects to, which a project's config names as `principles` and `standards`; `docs/` for decisions and the comprehension history; `settings.json` for the harness and `.claude/settings.json` for the harness inside this repo; `CHANGELOG.md` and `todo.md`; the tools in `bin/`, with the routing ladder they ship, `bin/model_routing/routing-ladder.json`; `workflow-bench/`, the scripts and prompts of the 2026-09-30 bench of larv-review and of the 2026-11-12 bench of the advisor tool; `reviewer-merge-trials/`, the 2026-11-09 trials of merging reviewers, with their method, results and scripts; `judge-field-trials/`, the 2026-11-11 trials of which facts code could read in place of loop-claude's judge, with their results and scripts; `stability-skip-count/`, the 2026-11-12 count of archived stability rounds, with its script, from which larv-review took when to skip a stability round 2; and `presentation/`, a page that explains this setup to newcomers, with the script that prints it to PDF.
|
||||
|
||||
## Goals
|
||||
|
||||
@@ -79,7 +79,7 @@ To get loop-claude's questions and stops as DMs from a bot, write the bot's toke
|
||||
|
||||
Each project the loop runs in has a folder, `~/.claude-projects/<key>/`, where `<key>` is the project's name, and a config in it, `config.toml`. The folder is a git repo of its own, so the config has a history and a client's files never enter this repo. The loop commits each change it makes to a file there, such as the plan, in that repo, titled as its commits in the checkout. A project is a whole git checkout, never a subfolder of one.
|
||||
|
||||
The config names the project's main checkout and the path of every file the loop keeps for it. No path setting has a default: `project-config` fails and names each setting a config leaves out. A path is `checkout:<path>` inside the checkout, `folder:<path>` inside the config's folder, or one that starts with `/` or `~/`. Every tool reads and writes each file at the path its setting gives, and `chunk-preflight` and `todo-item` print those paths for the agents. Five of the settings name the project's records: `decisions`, `score-anchors`, `comprehension-history`, `reading-cost` and `changelog`. Keep each file's name, such as `todo.md`: the rules for a file load by its name. A project of your own keeps every file but the principles in its checkout:
|
||||
The config names the project's main checkout and the path of every file the loop keeps for it. No path setting has a default: `project-config` fails and names each setting a config leaves out. A path is `checkout:<path>` inside the checkout, `folder:<path>` inside the config's folder, or one that starts with `/` or `~/`. Every tool reads and writes each file at the path its setting gives, and `chunk-preflight` and `todo-item` print those paths for the agents. Five of the settings name the project's records: `decisions`, `score-anchors`, `comprehension-history`, `reading-cost` and `changelog`. Keep each file's name, such as `todo.md`: the rules for a file load by its name. A project of your own keeps every file but the principles and the review standards in its checkout:
|
||||
|
||||
```toml
|
||||
checkout = "~/code/log"
|
||||
@@ -92,8 +92,11 @@ reading-cost = "checkout:docs/reading-cost.md"
|
||||
changelog = "checkout:CHANGELOG.md"
|
||||
goals-and-audience = "checkout:README.md"
|
||||
principles = "~/.claude/principles"
|
||||
standards = "~/.claude/skills/larv-review/standards"
|
||||
```
|
||||
|
||||
`principles` and `standards` name the folders the reviewers hold the project to: the technical principles and the review standards. Both ship with this setup, at the paths above. A folder of your own replaces the shipped one. A standards folder must hold `quality.md`, `prose.md`, `comments.md` and `readme.md`, since the reviewers and the rules name those files.
|
||||
|
||||
A project may also set `env-file`, the file of `KEY=value` credentials its tools read, such as `env-file = "~/.claude-projects/log.env"`. It is a path that starts with `/` or `~/`, outside the checkout and the config's folder, so that no git remote receives it. A tool that needs a key fails and names each one the file lacks. No failure message, prompt, log line or archived loop output holds a token from the file. rule-hook refuses a Read or a Grep of the file and a Bash command that names it or searches a folder holding it with `ag`, `grep -r` or `rg`, unless the tool skips the file as hidden or ignored, so a worker doesn't read it in passing; `rule-hook --help` says which calls it checks. A project without the setting has no credentials, and never reads another project's. `project-config env-file` prints the path.
|
||||
|
||||
A project may also set `touch-predictions`, a path spelt as `changelog`'s is, such as `touch-predictions = "checkout:docs/touch-predictions.md"`. `touch-predictions record` appends each chunk's predicted files and parts there, beside those it touched. A project that leaves it out keeps no such record.
|
||||
@@ -117,7 +120,7 @@ A client that plans in Jira Cloud names an epic as its project's plan: `plan = "
|
||||
- A blocker is an "is blocked by" link to another open child.
|
||||
- The scores are the issue property `plan-item`, a JSON object such as `{"L": 2, "E": 2, "I": 3, "S": 3, "Moves": "1.6 by 4", "Exempt": ""}`. An issue without it reads as an item nobody scored yet.
|
||||
|
||||
A read fails, naming the issue, where a child is in another Jira project or names no such Fix Version. The config's `env-file` must hold `ATLASSIAN_EMAIL` and `ATLASSIAN_API_TOKEN`, an API token of that Atlassian account, and only its owner may read that file: `chmod 600` it. The loop only reads such a plan so far. `todo-item add`, `edit`, `move` and `finish` fail, so file, edit and finish its issues in Jira. `rank_todo.py` doesn't rank it, since Jira's backlog does. The four things not supported for a plan outside the checkout, above, are not supported for a plan in Jira either.
|
||||
A read fails, naming the issue, where a child is in another Jira project or names no such Fix Version. The config's `env-file` must hold `ATLASSIAN_EMAIL` and `ATLASSIAN_API_TOKEN`, an API token of that Atlassian account, and only its owner may read that file: `chmod 600` it. The loop reads such a plan and files items into it, each as a Task under the epic, and doesn't edit an issue yet. `todo-item edit` and `move` fail, so edit its issues in Jira. For `todo-item finish`, the config names the workflow transition that finishes an item and the status it leads to, both as Jira shows them: `jira-finish-transition = "Mark as done"` and `jira-finish-status = "Done"`. Finish then moves the item's issue by that transition. It refuses a transition that leads to another status, or to one Jira doesn't count as done, and fails where the config sets neither. `todo-item add` needs the item's release among the Jira project's Fix Versions, named as `1.2.0` or `v1.2.0`. `rank_todo.py` doesn't rank it, since Jira's backlog does. The four things not supported for a plan outside the checkout, above, are not supported for a plan in Jira either.
|
||||
|
||||
A client that keeps its goals and audience in an epic's description names that epic as the goals file: `goals-and-audience = "jira:https://acme.atlassian.net/browse/ABC-12"`, which may be the plan's own epic. Such a config keeps its plan in Jira too, and reads both with the same `env-file`. The description needs `## Goals` and `## Audience` as headings, level-2 headings in Jira's editor. The loop only reads the description, so edit it in Jira; `project-record open goals-and-audience` prints a file holding its text. Whoever may edit that description sets the premises every worker and judge follows, so keep its edit rights to the people who own the project's goals.
|
||||
|
||||
@@ -133,6 +136,8 @@ cd ~/code/acme-billing && ~/.claude/bin/project-config
|
||||
|
||||
The last line prints each setting's path once the config is complete.
|
||||
|
||||
A project runs on the routing ladder this setup ships, `bin/model_routing/routing-ladder.json`: the rungs, least competent first, each a model at an effort, that loop-claude routes workers, subagents and reviews to. To run one project on other rungs, as when an outage or a client's account leaves it fewer models, copy that file to `~/.claude-projects/<key>/routing-ladder.json` and cut or change its rungs. Keep one model for each family, such as opus: Claude Code launches a subagent by its family's name. The project's file replaces the shipped ladder whole. loop-claude reads it as each cycle starts, and `subagent-rung` and rule-hook each time they run. The loop never commits it, so commit it in the folder's repo yourself only where it should last. Set the project's models to ones its ladder holds, for example with `LOOP_CLAUDE_WORKER_MODEL` and `LOOP_CLAUDE_JUDGE_MODEL`. A model off the ladder is not routed: every worker runs on that model, at the effort Claude Code's `settings.json` gives. Each cycle of a project on a ladder of its own says so on stderr, naming the file, and says where the worker's model is off it. `loop-claude --help` shows the file's shape.
|
||||
|
||||
## Update
|
||||
|
||||
Move `~/.claude` to the newest release:
|
||||
@@ -180,7 +185,7 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a
|
||||
- `score-outcomes [L E I S]` shows what each finished item's chunk measured beside the scores the item was guessed at, to score a new item by. Per chunk it also shows code health's two counter-signals, misread findings and later fixes, and how many of the human's answers reversed a worker's choice; `score-outcomes --help` states the report.
|
||||
- `settings_filter.py` is git's clean filter for `settings.json`: it drops `"model"` and sorts the keys. `.gitattributes` sets the filter `settings` on `settings.json`, and Install's `git config` line makes this script that filter.
|
||||
- `statusline.py` renders Claude Code's status line; `settings.json` → `statusLine` runs it.
|
||||
- `subagent-rung [--plan] <model> <L>` prints the Agent tool's model and effort for a subagent's task, picked by its L from the project's model, and with `--plan` never below the project's rung; `subagent-rung --help` states the rule.
|
||||
- `subagent-rung [--plan] <model> <L>` prints the Agent tool's model and effort for a subagent's task, picked by its L from the project's model on the project's routing ladder, and with `--plan` never below the project's rung; `subagent-rung --help` states the rule.
|
||||
- `todo-item` reads and changes a project's plan, whatever holds it: `list` prints the items in the plan's order and `show <ID>` one item's row and detail; `add …` files an item under the next free ID, `edit <ID> …` sets an item's cells or detail, and `move <ID> --release <version>` sets an item's release; `finish <ID>` removes a finished item and adds the bullet passed with `--changelog` to `CHANGELOG.md`. Each change ranks a markdown plan. `todo-item --help` states the flags.
|
||||
- `touch-predictions record <ID>...` appends what a chunk's items were predicted to touch, under `Touches:` in their details, beside the files and parts its branch touched, to the record the config names as `touch-predictions`; `touch-predictions --help` shows the spelling and how a part is named. `chunk-preflight` reads the same predictions to name the items that may start chunks at once.
|
||||
- `wait-for <file> [<pattern>] [--timeout <seconds>]` waits until a file a background job writes holds a line matching the pattern, and prints it.
|
||||
@@ -198,14 +203,14 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a
|
||||
- `loop_effects/` holds `Effects`: the processes, terminal, clock and git a tool reaches, injected so its tests can script them. loop-claude, both replay tools and `reviewer-merge-trials`' driver use it.
|
||||
- `loop_state/` holds where loop-claude keeps its files (`paths.py`), which `rung_replay` reads too.
|
||||
- `machine_load/` takes the machine's heavy slots, its shared lock files, for `run_heavy` and `adf_codec`, and reads the memory share that loop-claude waits for. It also gives `mutate_changes` a slot's CPU count.
|
||||
- `model_routing/` holds the routing ladder, which loop-claude, `rule_hook`, both replay tools and `subagent-rung` read, and the list prices, which `routing_figures` and `transcript_archive` read.
|
||||
- `model_routing/` holds the shipped routing ladder (`routing-ladder.json`) and its steps (`ladder.py`), and reads a ladder from that file or a project's own (`ladder_file.py`), for loop-claude, `rule_hook`, both replay tools and `subagent-rung`. It finds a project's config folder through `project_config`. It also holds the list prices, which `routing_figures` and `transcript_archive` read.
|
||||
- `notifier/` sends the human a DM through the notifier a project's config names, for `notify` and for loop-claude through `loop_effects`; `mattermost_dm/` and `slack_dm/` are its two backends.
|
||||
- `plan_store/` reads and writes a project's plan through the store the project's config names (`stores.py`), with the markdown file's edits in `markdown_edits.py`. `contract.py` holds the tests every backend that writes must pass, which `jira_epic.py` doesn't yet, and `fakes.py` a plan in memory.
|
||||
- `rank_todo.py`, `settings_filter.py` and `statusline.py` are tools of one file each, tested beside them.
|
||||
- `record_store/` reads and writes a project's records, each through the store the project's config names (`stores.py`). `contract.py` holds the tests every backend must pass, and `fakes.py` a store in memory that the tests of other tools use.
|
||||
- `record_store/` reads and writes a project's records, each through the store the project's config names (`stores.py`): a markdown file, a Confluence Cloud page (`confluence_page.py`), or, for the goals, a Jira epic's description (`jira_description.py`). `contract.py` holds the tests every backend must pass, and `fakes.py` a store in memory that the tests of other tools use.
|
||||
- `release_plan/` 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`). `goals_file.py` reads the goals file's sections, goals and goal weights, for the ranking and for `loop_claude`'s premises, and `citations.py` holds `todo.md` and `docs/decisions.md` to each other. `plan_file.py` ranks, checks and writes a `todo.md`, for `larv_review`, `rank_todo.py` and `rule_hook`.
|
||||
- `repo_checks/` tests the repo itself.
|
||||
- `rest_client/` sends a JSON request to a REST API and reads its credentials from an env file, for `mattermost_dm`, `slack_dm` and `plan_store`.
|
||||
- `rest_client/` sends a JSON request to a REST API and reads its credentials from an env file, for `mattermost_dm`, `slack_dm`, `plan_store` and `record_store`.
|
||||
- `review_rules/` holds the larv-review rules that several tools apply: its passes, its review folder, its round commit titles and the comprehension history's format.
|
||||
- `routing_figures/` measures loop-claude's archive, and each of its projects' default branches, for loop-claude's routing calls.
|
||||
- `rung_replay/` holds what `judge_replay` and `review_replay` share: the parallel replay runner, the argument reader, the candidate rungs and the exits, and `judge_replay`'s rung search. It reads `loop_claude`'s retry count and models file, and finds that file through `loop_state`'s paths.
|
||||
|
||||
@@ -9,13 +9,13 @@ You read the prose as someone who did not write it: you see only what it says, n
|
||||
|
||||
The bar, read each time, since it changes:
|
||||
|
||||
- every file under `~/.claude/skills/larv-review/standards/`, of `quality.md` only "A false claim is a bug";
|
||||
- every file in the folder your prompt's `Review standards:` line names, of `quality.md` only "A false claim is a bug";
|
||||
- `~/.claude/CLAUDE.md` → "Public API specs";
|
||||
- each file under `~/.claude/rules/` whose `paths:` frontmatter matches a file the diff changes.
|
||||
|
||||
Verdict, severities and rounds: ~/.claude/skills/larv-review/review-findings.md.
|
||||
|
||||
Your prompt's `Prose language:` line names the language the project's config sets. Apply every check below to prose in that language, by that language's grammar and idiom. The bar's examples are English: find the same fault in the other language, never the same English words. Prose in another language is a finding, except what `standards/prose.md` says stays English. Write your report in English.
|
||||
Your prompt's `Prose language:` line names the language the project's config sets. Apply every check below to prose in that language, by that language's grammar and idiom. The bar's examples are English: find the same fault in the other language, never the same English words. Prose in another language is a finding, except what `prose.md` in the review standards says stays English. Write your report in English.
|
||||
|
||||
## Checks, in priority order
|
||||
|
||||
@@ -23,7 +23,7 @@ Run them in this order. A fix for a later check never breaks an earlier one.
|
||||
|
||||
1. **Easy to understand.** Read each sentence once, cold. A sentence you had to reread, a term used before it is explained, or an "it" or "them" that could point at two things is a finding. Fix: **Rewrite**, giving the plain sentence.
|
||||
2. **Most important first.** Name the document's reader and what they want to know first. Check that the sections run in that order, then the paragraphs within each section, then the items within each list. If not, fix: **Reorder**, naming the new order. A section so long that a reader has to search it gets sub-headings or an index. Fix: **Split**.
|
||||
3. **Default to delete.** A line the reader does not need fails. Fix: **Delete** what the code, a type, a test name, the README or another rule already says. Fix: **Move** a choice made in one place to a comment there, one made in more places to `docs/decisions.md` with its title in `AGENTS.md` unless a project principle there covers it, and a goal to the README. A pointer standing where a definition belongs (`~/.claude/skills/larv-review/standards/comments.md` → "Links and pointers", "A pointer is not a definition") gets the fix **Move back**: inline the definition, and leave the reasoning where it is.
|
||||
3. **Default to delete.** A line the reader does not need fails. Fix: **Delete** what the code, a type, a test name, the README or another rule already says. Fix: **Move** a choice made in one place to a comment there, one made in more places to `docs/decisions.md` with its title in `AGENTS.md` unless a project principle there covers it, and a goal to the README. A pointer standing where a definition belongs (the review standards' `comments.md` → "Links and pointers", "A pointer is not a definition") gets the fix **Move back**: inline the definition, and leave the reasoning where it is.
|
||||
4. **Short.** Words that do not clearly help 1–3 fail. Fix: **Cut**.
|
||||
|
||||
Also report a list whose order carries no meaning and is not sorted (the technical principles' "Deterministic order", in the folder your prompt's `Technical principles:` line names; without one, open your report by saying so), a sentence contradicting another, a claim the code shows false, and a word used against `CLAUDE.md` → "Vocabulary".
|
||||
|
||||
@@ -11,7 +11,7 @@ You are an elite stability-focused code reviewer with deep expertise in defensiv
|
||||
## First Steps
|
||||
|
||||
1. **Scope the change.** You review every PR; a fresh invocation has no prior context, so determine the diff yourself. Diff the PR branch against its base (`gh pr diff`, or `git merge-base <base> HEAD` then `git diff`), and review the changed lines **plus enough surrounding code and callers** to judge correctness — read the whole changed file when practical; a diff alone hides whether a caller breaks. Read the PR description and, when the project uses an issue tracker (project-specific — check its docs) and the change references a ticket, that ticket: the diff is judged against its stated intent, and a scope mismatch in either direction is a finding — claimed-but-unimplemented, and implemented-but-unasked (#2).
|
||||
2. **Read every file in the folder your prompt's `Technical principles:` line names**, and `~/.claude/skills/larv-review/standards/quality.md`. These are mandatory guidelines; all code MUST comply with each that applies. A file's `Applies to` line says what it covers; one without the line covers every change. Re-read each time — they change. Flag violations prominently. Where your prompt has no such line, without one, open your report by saying so.
|
||||
2. **Read every file in the folder your prompt's `Technical principles:` line names**, and `quality.md` in the folder your prompt's `Review standards:` line names. These are mandatory guidelines; all code MUST comply with each that applies. A file's `Applies to` line says what it covers; one without the line covers every change. Re-read each time — they change. Flag violations prominently. Where your prompt lacks either line, open your report by saying so.
|
||||
3. **Read README.md, AGENTS.md and `docs/decisions.md`** in the current project for project-specific conventions, build instructions, tooling, and the accepted trade-offs a reviewer should honor rather than re-flag. Note the documented test, lint, and static-analysis commands — you run them unless your prompt hands you a passing run on the head (step 4).
|
||||
4. **Verify, don't just read.** Where your prompt hands you the commit on which the worker's run of the test suite and static analysis last passed, and it is the head, don't run them again, and say so in Coverage & Verification. Otherwise run the test suite and static analysis/linters through the project's container tooling, unless `~/.claude/bin/project-config tooling-on-host` prints true or a decision puts them on the host; tear down test containers afterwards. Run the full suite under `~/.claude/bin/run-heavy`. Run it in the background or with the Bash tool's longest timeout: that timeout includes the wait for a slot. A full-suite run catches broken callers that diff-reading misses. When a suspected bug is cheap to confirm, reproduce it — a scratch script, a targeted test run — before reporting it. Make scratch work with Bash, since Write is for your report alone. Put it in a directory you create for this run, and delete it when done; don't delete anything else, since a directory the prompt names may hold other agents' files. Leave the working tree exactly as you found it. Anything you could not run goes in Coverage & Verification, never silently skipped.
|
||||
5. **Judge the surviving mutants.** Your prompt hands you what the project's mutation command printed on the change, with the commit it ran on: the mutants of changed lines that no test kills, or the message of a run that failed. Ignore a surviving mutant that leaves behaviour unchanged, or changes only message or log text no caller or user depends on. Report one 🟡 per test to add or strengthen, naming the surviving mutants it would catch. Where the prompt doesn't hand you any output, or names a commit other than the head, run the command yourself in the change's checkout, through run-heavy as in step 4: the one the project's README documents, else `~/.claude/bin/run-heavy ~/.claude/bin/mutate-changes --prefix '<how the project runs its tools>'`. `~/.claude/bin/mutate-changes --help` says which tool it runs for each language, how to set `--jobs`, and what it prints. Mutation-test the changed code that no run mutated, in a language mutate-changes doesn't cover or where a run failed, with a widely deployed mutation tool limited to the changed lines, else with mutants you make by hand. Report the wall time and mutant count in Coverage & Verification, or why nothing was mutated.
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
usage: judge-replay <model>
|
||||
|
||||
<model> is a project model on the routing ladder, such as claude-opus-5-5. The tool replays the
|
||||
<model> is a project model on the routing ladder this setup ships, such as claude-opus-5-5. The tool replays the
|
||||
verdicts archived for the projects that ~/.claude/loop-claude-models.json runs on it: the latest
|
||||
15 of each kind, finished, unfinished, interrupt and quoted answer. Each transcript copy in the
|
||||
archive is what the judge read for the verdict beside it, so the replay hands the judge that copy,
|
||||
@@ -41,8 +41,9 @@ from transcript_archive.project_key import checkout_of
|
||||
from loop_effects.effects import Effects
|
||||
from failure import Failure
|
||||
from rung_replay.search import first_reply, replayed
|
||||
from model_routing.ladder import Ladder, REVIEW_STEPS, Rung
|
||||
from claude_code.reply import Limited
|
||||
from model_routing.ladder import lowest_worker_rung, position, project_rung, review_floor, REVIEW_STEPS, Rung
|
||||
from model_routing.ladder_file import read_ladder, SHIPPED
|
||||
from loop_claude.project.premises import read_premises
|
||||
from loop_claude.project.records import read_records
|
||||
from claude_code.transcript import read_transcript
|
||||
@@ -56,7 +57,11 @@ REFERENCE_EFFORT = "xhigh"
|
||||
|
||||
|
||||
def main(argv: list[str], env: typing.Mapping[str, str], home: pathlib.Path, effects: Effects) -> int:
|
||||
project = arguments_or_exit(TOOL, argv, __doc__, USAGE, model_argument)
|
||||
# The shipped ladder, not a project's: the replay spans every project on the model.
|
||||
ladder = read_ladder(SHIPPED)
|
||||
if isinstance(ladder, Failure):
|
||||
return failed(TOOL, ladder.reason)
|
||||
project = arguments_or_exit(TOOL, argv, __doc__, USAGE, lambda argv: model_argument(ladder, argv))
|
||||
if isinstance(project, int):
|
||||
return project
|
||||
cases = archived_cases(project.model, archive_root(home, env), home)
|
||||
@@ -67,21 +72,21 @@ def main(argv: list[str], env: typing.Mapping[str, str], home: pathlib.Path, eff
|
||||
cases = sample(cases, PER_KIND)
|
||||
reference = Rung(project.model, REFERENCE_EFFORT)
|
||||
# The candidates stop at the lowest rung a worker routes to: no route uses a rung below it for the judge.
|
||||
replay = replayed(cases, reference, down_from(project, lowest_worker_rung(project)), lambda found, rung: rule(found, rung, home, effects), reproduced, "verdicts", climbs(project, reference))
|
||||
replay = replayed(cases, reference, down_from(ladder, project, ladder.lowest_worker_rung(project)), lambda found, rung: rule(found, rung, home, effects), reproduced, "verdicts", climbs(ladder, project, reference))
|
||||
if isinstance(replay, Limited):
|
||||
return limited_exit(TOOL, replay)
|
||||
print(report(project.model, reference, cases, replay))
|
||||
return 0
|
||||
|
||||
|
||||
def model_argument(argv: list[str]) -> Rung | None:
|
||||
"""The project's rung of the one model argv names; None for any other argv."""
|
||||
return project_rung(argv[0]) if len(argv) == 1 else None
|
||||
def model_argument(ladder: Ladder, argv: list[str]) -> Rung | None:
|
||||
"""The project's rung on ladder of the one model argv names; None for any other argv."""
|
||||
return ladder.project_rung(argv[0]) if len(argv) == 1 else None
|
||||
|
||||
|
||||
def climbs(project: Rung, reference: Rung) -> list[Rung]:
|
||||
def climbs(ladder: Ladder, project: Rung, reference: Rung) -> list[Rung]:
|
||||
"""The rungs above the project's rung that an E + I raises a review to, except the reference's, lowest first."""
|
||||
return sorted({review_floor(project, score) for score in REVIEW_STEPS} - {project, reference}, key=position)
|
||||
return sorted({ladder.review_floor(project, score) for score in REVIEW_STEPS} - {project, reference}, key=ladder.position)
|
||||
|
||||
|
||||
def archived_cases(model: str, root: pathlib.Path, home: pathlib.Path) -> list[Case] | Failure:
|
||||
|
||||
@@ -130,17 +130,17 @@ 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, the folder of technical principles the project's config sets, the goals
|
||||
and the plan and, for architecture and stability, the places. For a reviewer whose
|
||||
report, the branch diff, the folders of technical principles and review standards the project's
|
||||
config sets, the goals and the plan 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, writes what
|
||||
places prints into places.md, and lists the plan's items into
|
||||
plan.md, whatever store holds the plan; 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, when `project-config` fails in the checkout, when the
|
||||
principles folder it names is not a folder with a file in it, or, with --rerun, when the report that
|
||||
asked is missing.
|
||||
it. It exits 1 when the pass takes no more rounds, when `project-config` fails in the checkout, when
|
||||
the principles or standards folder is not a folder with a file in it, 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,
|
||||
|
||||
@@ -34,6 +34,7 @@ class Launch:
|
||||
folder: pathlib.Path
|
||||
diff: pathlib.Path
|
||||
principles: pathlib.Path
|
||||
standards: pathlib.Path
|
||||
goals: pathlib.Path
|
||||
# The plan's listing, for a reviewer that reads files, whatever store holds the plan.
|
||||
plan: pathlib.Path
|
||||
@@ -59,6 +60,7 @@ class Launch:
|
||||
f"Report: write it to {report}.",
|
||||
f"Diff: {self.diff}",
|
||||
f"Technical principles: {self.principles}",
|
||||
f"Review standards: {self.standards}",
|
||||
f"Goals and audience: {self.goals}",
|
||||
f"Plan: {self.plan}",
|
||||
f"Prose language: {self.language}.",
|
||||
@@ -97,10 +99,11 @@ def reviewer_header(default: str, pass_: str, rerun: bool, home: pathlib.Path) -
|
||||
config = located(None, home)
|
||||
if isinstance(config, Failure):
|
||||
return config
|
||||
principles = config.paths["principles"]
|
||||
# A typo in the config would otherwise hand every reviewer an empty folder, and the review would run with no principles.
|
||||
if not principles.is_dir() or not any(principles.iterdir()):
|
||||
return Failure(f"{principles} is not a folder with a file in it; {config.folder / 'config.toml'} sets it as `principles`")
|
||||
principles, standards = config.paths["principles"], config.paths["standards"]
|
||||
# A typo in the config would otherwise hand every reviewer an empty folder, and the review would run with no principles or standards.
|
||||
empty = next((setting for setting in ("principles", "standards") if not config.paths[setting].is_dir() or not any(config.paths[setting].iterdir())), None)
|
||||
if empty is not None:
|
||||
return Failure(f"{config.paths[empty]} is not a folder with a file in it; {config.folder / 'config.toml'} sets it as `{empty}`")
|
||||
decisions = local_file(store(config, "decisions"), folder / "decisions.md")
|
||||
if isinstance(decisions, Failure):
|
||||
return decisions
|
||||
@@ -108,7 +111,7 @@ def reviewer_header(default: str, pass_: str, rerun: bool, home: pathlib.Path) -
|
||||
goals = local_file(goals_store(config), folder / "goals.md")
|
||||
if isinstance(goals, Failure):
|
||||
return goals
|
||||
launch = Launch(pass_, round_, rerun, pull_named(worktree, branch), worktree, branch, base, default, folder, folder / f"branch-{head}.diff", principles, goals, folder / "plan.md", starts_bare(next((agent for name, agent in REVIEWERS.items() if name == pass_), ""), home), config.paths["working-rules"], decisions, config.language)
|
||||
launch = Launch(pass_, round_, rerun, pull_named(worktree, branch), worktree, branch, base, default, folder, folder / f"branch-{head}.diff", principles, standards, goals, folder / "plan.md", starts_bare(next((agent for name, agent in REVIEWERS.items() if name == pass_), ""), home), config.paths["working-rules"], decisions, config.language)
|
||||
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, home, plan_listing(plan_store(config)))
|
||||
|
||||
@@ -182,6 +182,14 @@ class History(unittest.TestCase):
|
||||
votes = {"Mid A": ["better", "worse", "same", "same", "better"]}
|
||||
self.assertEqual(ruling_entry("2026-10-09T09:47:25Z, PR #232 at 324d650, against 12d6d75", [seat], votes, votes, "same"), "\n".join(sample) + "\n")
|
||||
|
||||
def test_reads_tables_whose_separators_hold_spaces_as_adf_codec_writes_them(self):
|
||||
scoring = ScoringRun([Seat("Junior A", "", [])], {"Junior A": ["7", "6.5", "7", "7", "7"]}, [decimal.Decimal(mean) for mean in ("7.00", "6.50", "7.00", "7.00", "7.00")])
|
||||
history = appended("", scoring_entry("2026-10-08T12:00:00Z, PR #1 at aaaaaaa", scoring))
|
||||
spaced = "\n".join("| " + " | ".join(["---"] * line.count("---")) + " |" if line.startswith("|-") else line for line in history.splitlines())
|
||||
self.assertNotEqual(spaced, history)
|
||||
self.assertEqual(entries(spaced)[0].score_rows, entries(history)[0].score_rows)
|
||||
self.assertIn("Mean", entries(spaced)[0].score_rows)
|
||||
|
||||
def test_reads_back_what_it_writes(self):
|
||||
seats = [Seat("Mid A", said("better", "worse"), ["`bin/a.py:3` `f`: hard, with `:9` `g`"]), Seat("Inherited architect", said("worse", "worse"), [])]
|
||||
written = {"Mid A": ["same", "worse", "same", "same", "better"], "Inherited architect": ["same", "worse", "same", "same", "worse"]}
|
||||
@@ -475,6 +483,7 @@ reading-cost = "checkout:docs/reading-cost.md"
|
||||
changelog = "checkout:CHANGELOG.md"
|
||||
goals-and-audience = "checkout:README.md"
|
||||
principles = "~/principles"
|
||||
standards = "~/standards"
|
||||
"""
|
||||
|
||||
|
||||
@@ -497,6 +506,8 @@ class LarvReviewTool(unittest.TestCase):
|
||||
self.config.write_text(PROJECT_CONFIG)
|
||||
(root / "principles").mkdir()
|
||||
(root / "principles" / "technical-principles.md").write_text("# Principles\n")
|
||||
(root / "standards").mkdir()
|
||||
(root / "standards" / "quality.md").write_text("# Quality\n")
|
||||
|
||||
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
|
||||
@@ -1120,6 +1131,7 @@ class LarvReviewTool(unittest.TestCase):
|
||||
f"Report: write it to {folder}/stability-round-1.md.\n"
|
||||
f"Diff: {folder}/branch-{short}.diff\n"
|
||||
f"Technical principles: {self.checkout.parent}/principles\n"
|
||||
f"Review standards: {self.checkout.parent}/standards\n"
|
||||
f"Goals and audience: {self.checkout}/README.md\n"
|
||||
f"Plan: {folder}/plan.md\n"
|
||||
"Prose language: English.\n"
|
||||
@@ -1212,6 +1224,9 @@ class LarvReviewTool(unittest.TestCase):
|
||||
def test_reviewer_header_names_the_principles_folder_the_projects_config_sets(self):
|
||||
self.assertEqual(self.header_line("Technical principles:", "prose"), f"Technical principles: {self.checkout.parent}/principles")
|
||||
|
||||
def test_reviewer_header_names_the_review_standards_folder_the_projects_config_sets(self):
|
||||
self.assertEqual(self.header_line("Review standards:", "prose"), f"Review standards: {self.checkout.parent}/standards")
|
||||
|
||||
def test_reviewer_header_names_the_language_and_counts_rounds_through_the_commit_title_the_projects_config_sets(self):
|
||||
self.config.write_text(PROJECT_CONFIG + 'language = "Swedish"\ncommit-title = "PAY-{id} - {summary}"\n')
|
||||
self.commit("PAY-7 - Answer prose round 1: 0 🔴, 1 🟡 (0 misread); a")
|
||||
@@ -1240,11 +1255,13 @@ class LarvReviewTool(unittest.TestCase):
|
||||
self.assertEqual((ran.returncode, ran.stdout), (1, ""))
|
||||
self.assertIn("cannot read the epic ABC-12", ran.stderr)
|
||||
|
||||
def test_reviewer_header_fails_with_the_configs_message_where_it_sets_no_principles_folder(self):
|
||||
self.config.write_text(PROJECT_CONFIG.replace('principles = "~/principles"\n', ""))
|
||||
ran = self.run_tool("reviewer-header", "prose")
|
||||
self.assertEqual((ran.returncode, ran.stdout), (1, ""))
|
||||
self.assertIn("`principles` is missing", ran.stderr)
|
||||
def test_reviewer_header_fails_with_the_configs_message_where_it_sets_no_principles_or_standards_folder(self):
|
||||
for setting in ("principles", "standards"):
|
||||
with self.subTest(setting=setting):
|
||||
self.config.write_text(PROJECT_CONFIG.replace(f'{setting} = "~/{setting}"\n', ""))
|
||||
ran = self.run_tool("reviewer-header", "prose")
|
||||
self.assertEqual((ran.returncode, ran.stdout), (1, ""))
|
||||
self.assertIn(f"`{setting}` is missing", ran.stderr)
|
||||
|
||||
def test_reviewer_header_fails_where_no_config_names_the_checkout(self):
|
||||
self.config.unlink()
|
||||
@@ -1252,15 +1269,19 @@ class LarvReviewTool(unittest.TestCase):
|
||||
self.assertEqual((ran.returncode, ran.stdout), (1, ""))
|
||||
self.assertIn(f"no config names the checkout {self.checkout}", ran.stderr)
|
||||
|
||||
def test_reviewer_header_fails_where_the_principles_folder_is_missing_or_empty(self):
|
||||
folder = self.checkout.parent / "principles"
|
||||
(folder / "technical-principles.md").unlink()
|
||||
empty = self.run_tool("reviewer-header", "prose")
|
||||
folder.rmdir()
|
||||
missing = self.run_tool("reviewer-header", "prose")
|
||||
for ran in (empty, missing):
|
||||
self.assertEqual((ran.returncode, ran.stdout), (1, ""))
|
||||
self.assertIn(f"{folder} is not a folder with a file in it; {self.config} sets it as `principles`", ran.stderr)
|
||||
def test_reviewer_header_fails_where_the_principles_or_standards_folder_is_missing_or_empty(self):
|
||||
for setting, file in (("principles", "technical-principles.md"), ("standards", "quality.md")):
|
||||
with self.subTest(setting=setting):
|
||||
folder = self.checkout.parent / setting
|
||||
(folder / file).unlink()
|
||||
empty = self.run_tool("reviewer-header", "prose")
|
||||
folder.rmdir()
|
||||
missing = self.run_tool("reviewer-header", "prose")
|
||||
folder.mkdir()
|
||||
(folder / file).write_text("# Restored\n")
|
||||
for ran in (empty, missing):
|
||||
self.assertEqual((ran.returncode, ran.stdout), (1, ""))
|
||||
self.assertIn(f"{folder} is not a folder with a file in it; {self.config} sets it as `{setting}`", ran.stderr)
|
||||
|
||||
def test_reviewer_header_gives_the_architect_the_places(self):
|
||||
folder = self.checkout.parent / ".local" / "state" / "larv-review" / "proj"
|
||||
|
||||
@@ -57,7 +57,7 @@ FINISHED_RULES = (
|
||||
"finished=true when the chunk is complete: merged, or nothing remains that the worker could do on "
|
||||
f"its own. Even then, it is finished only once {ANSWERS_RECORDED}.\n\n"
|
||||
"An answer counts as recorded where the premises or the records above already hold it, the human's rules "
|
||||
"(~/.claude/CLAUDE.md, ~/.claude/rules/, ~/.claude/skills/larv-review/standards/) included. "
|
||||
"(~/.claude/CLAUDE.md, ~/.claude/rules/, the project's review standards, each headed by its path) included. "
|
||||
f"It also counts where the transcript shows the worker writing it into {ANSWER_DESTINATIONS}, "
|
||||
"but not into one of the human's rules.\n\n"
|
||||
"finished=false when work remains that a further run can "
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
"""What loop-claude says to the worker each cycle. model_routing.review_choice chooses where the reviews run. review_launches and reruns put that choice into sentences, and escalation says where escalated subagents run; rung_sentences returns the sentences of all three. In a chunk's first prompt, routed_by places them after its routing sentences where an item routed the chunk, and fresh places them alone otherwise. rungs_held repeats them at the end of a prompt after a step-up or an unfinished verdict."""
|
||||
from model_routing.review_choice import chosen, ReviewChoice
|
||||
from loop_claude.cycle.chunk_items import CHUNK_ITEMS
|
||||
from model_routing.ladder import climbed, LADDER, position, Rung
|
||||
from model_routing.route import ESCALATION_MARKER, Route
|
||||
from loop_claude.routing import escalation_rungs
|
||||
from loop_claude.project.records import HUMAN_RULE_NAMES, RECORD_FILES
|
||||
from review_rules.review_passes import INSTRUCTION_FILES, INSTRUCTION_FOLDERS
|
||||
from model_routing.ladder import Ladder, Rung
|
||||
from text_files.markdown_text import listed, quoted
|
||||
from claude_code.transcript import Typed
|
||||
|
||||
@@ -29,17 +29,17 @@ NAME_THE_ITEMS = f"Name every todo.md item this chunk takes on one line, as in `
|
||||
AFTER_CODE_HEALTH = 'which rank after code health (~/.claude/CLAUDE.md → "Shared goal") unless the goals file voids it'
|
||||
|
||||
|
||||
def fresh(task: str, premises: str, route: Route, project: Rung | None, facts: str) -> str:
|
||||
def fresh(task: str, premises: str, route: Route, ladder: Ladder, project: Rung | None, facts: str) -> str:
|
||||
"""A chunk's first prompt; facts is preflight_facts' or preflight_failed's text."""
|
||||
routed = f"{routed_by(route, project)} {recount(route)}" if route.item else " ".join(rung_sentences(route, project))
|
||||
routed = f"{routed_by(route, ladder, project)} {recount(route)}" if route.item else " ".join(rung_sentences(route, ladder, project))
|
||||
opening = f"{routed}\n\n" if routed else ""
|
||||
return f"{task}\n\nContinue any open draft PR or worktree for the chunk before creating a new one. {READING_RULE} {NAME_THE_ITEMS}\n\n{opening}{facts}\n\nThe chunk's todo.md items, or else the task above, set its scope. The goals below, {AFTER_CODE_HEALTH}, choose between ways to deliver that scope, and never widen it.\n\nFrom the goals file, {premises}"
|
||||
|
||||
|
||||
def routed_by(route: Route, project: Rung | None) -> str:
|
||||
def routed_by(route: Route, ladder: Ladder, project: Rung | None) -> str:
|
||||
return " ".join((
|
||||
f"loop-claude runs you on {route.rung}, routed by item {route.item}'s L of {route.likelihood}.",
|
||||
*rung_sentences(route, project),
|
||||
*rung_sentences(route, ladder, project),
|
||||
))
|
||||
|
||||
|
||||
@@ -58,12 +58,12 @@ def preflight_failed(reason: str) -> str:
|
||||
return f"loop-claude could not run `~/.claude/bin/chunk-preflight`, so find the chunk's facts yourself. Why it could not run: {reason}"
|
||||
|
||||
|
||||
def review_launches(route: Route, project: Rung | None) -> list[str]:
|
||||
def review_launches(route: Route, ladder: Ladder, project: Rung | None) -> list[str]:
|
||||
"""The sentences naming where to launch reviews, in this order, each from the function that says when it applies; none off the ladder."""
|
||||
if project is None:
|
||||
return []
|
||||
choice = chosen(project, route)
|
||||
return [*shared_launches(choice, route, project), *scan_launch(choice, route), *planning_launch(route, project), *taken_in_launches(choice), *markdown_launch(choice)]
|
||||
choice = chosen(ladder, project, route)
|
||||
return [*shared_launches(choice, route, project), *scan_launch(choice, route), *planning_launch(route, ladder, project), *taken_in_launches(choice), *markdown_launch(choice)]
|
||||
|
||||
|
||||
def scan_launch(choice: ReviewChoice, route: Route) -> list[str]:
|
||||
@@ -71,9 +71,9 @@ def scan_launch(choice: ReviewChoice, route: Route) -> list[str]:
|
||||
return ["Run a full scan only from such a subagent, since the scan's agents run on the model that starts them."] if choice.security != route.rung else []
|
||||
|
||||
|
||||
def planning_launch(route: Route, project: Rung) -> list[str]:
|
||||
def planning_launch(route: Route, ladder: Ladder, project: Rung) -> list[str]:
|
||||
"""Where the worker runs below the project's rung, the sentence naming where to launch a subagent that files or scores todo.md items. On an Opus 5.5 project: `Your rung is below the project's: launch each subagent that files or scores todo.md items on the rung `~/.claude/bin/subagent-rung --plan claude-opus-5-5 <L>` prints.`"""
|
||||
return [f"Your rung is below the project's: launch each subagent that files or scores todo.md items on the rung `~/.claude/bin/subagent-rung --plan {project.model} <L>` prints."] if position(route.rung) < position(project) else []
|
||||
return [f"Your rung is below the project's: launch each subagent that files or scores todo.md items on the rung `~/.claude/bin/subagent-rung --plan {project.model} <L>` prints."] if ladder.position(route.rung) < ladder.position(project) else []
|
||||
|
||||
|
||||
def markdown_launch(choice: ReviewChoice) -> list[str]:
|
||||
@@ -118,19 +118,19 @@ def rung_named(rung: Rung, route: Route, project: Rung) -> str:
|
||||
return f"the rung item {route.item}'s E + I of {route.escape_and_impact} picks"
|
||||
|
||||
|
||||
def escalation(route: Route, project: Rung | None) -> list[str]:
|
||||
def escalation(route: Route, ladder: Ladder, project: Rung | None) -> list[str]:
|
||||
"""The prompt's escalation sentences, the marker's among them. None off the ladder or on its top rung. Where escalation_rungs opens none, the worker escalates only with the human's yes.
|
||||
Else they name the rungs escalation_rungs opens to a subagent, and offer to resume the worker one rung up for the rest of the chunk, up to the highest of those rungs.
|
||||
|
||||
For a worker one rung above the project's, routed by item 3 of L 4, they read: `When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `<rung>`, one rung above yours, and on each further trigger one rung higher, up to `<rung>`; above that, ask the human first.`, `Open the subagent's prompt with `Escalation trigger <n>:`, n the trigger's number.` and `Where the hard part is the rest of the chunk, end your run instead, asking loop-claude for a higher rung and naming a trigger that fired since your last step-up, if any: once the judge finds it in your transcript, the next cycle resumes you one rung up, up to `<rung>`.`
|
||||
"""
|
||||
if project is None or route.rung not in LADDER[:-1]:
|
||||
if project is None or route.rung not in ladder.rungs[:-1]:
|
||||
return []
|
||||
marked = f"Open the subagent's prompt with `{ESCALATION_MARKER} <n>:`, n the trigger's number."
|
||||
rungs = [f"`{rung.agent_args()}`" for rung in escalation_rungs(project, route)]
|
||||
rungs = [f"`{rung.agent_args()}`" for rung in escalation_rungs(ladder, project, route)]
|
||||
if not rungs:
|
||||
return [
|
||||
f"An escalation trigger in `~/.claude/CLAUDE.md` lets you hand the hard part of a task to a subagent with the Agent tool set to `{climbed(route.rung, 1).agent_args()}`, one rung above yours, only once the human agrees; loop-claude will not resume you higher for a trigger either, so ask the human for that yes.",
|
||||
f"An escalation trigger in `~/.claude/CLAUDE.md` lets you hand the hard part of a task to a subagent with the Agent tool set to `{ladder.climbed(route.rung, 1).agent_args()}`, one rung above yours, only once the human agrees; loop-claude will not resume you higher for a trigger either, so ask the human for that yes.",
|
||||
marked,
|
||||
]
|
||||
further = f", and on each further trigger one rung higher, up to {rungs[-1]}" if len(rungs) > 1 else ""
|
||||
@@ -141,16 +141,16 @@ def escalation(route: Route, project: Rung | None) -> list[str]:
|
||||
]
|
||||
|
||||
|
||||
def reruns(route: Route, project: Rung | None) -> list[str]:
|
||||
def reruns(route: Route, ladder: Ladder, project: Rung | None) -> list[str]:
|
||||
"""The sentence naming the rung one above a reviewer's and the one above a seat's, on which each reruns when it asks, leaving out either that is already on the top rung. None off the ladder.
|
||||
|
||||
For a worker one rung below the project's, routed by an item of E + I 4, it reads: `A reviewer or comprehension seat that asks for a rerun one rung up reruns with the Agent tool set to `<rung>`.`
|
||||
"""
|
||||
if project is None or route.rung not in LADDER:
|
||||
if project is None or route.rung not in ladder.rungs:
|
||||
return []
|
||||
choice = chosen(project, route)
|
||||
choice = chosen(ladder, project, route)
|
||||
launched = (("reviewer", choice.reviewers), ("comprehension seat", choice.seat))
|
||||
rerun = {name: climbed(rung, 1) for name, rung in launched if rung != LADDER[-1]}
|
||||
rerun = {name: ladder.climbed(rung, 1) for name, rung in launched if rung != ladder.rungs[-1]}
|
||||
if not rerun:
|
||||
return []
|
||||
if len(set(rerun.values())) == 1:
|
||||
@@ -158,31 +158,31 @@ def reruns(route: Route, project: Rung | None) -> list[str]:
|
||||
return [f"A reviewer that asks for a rerun one rung up reruns with the Agent tool set to `{rerun['reviewer'].agent_args()}`, and a comprehension seat with `{rerun['comprehension seat'].agent_args()}`."]
|
||||
|
||||
|
||||
def resumed(unfinished_evidence: str, route: Route, project: Rung | None) -> str:
|
||||
def resumed(unfinished_evidence: str, route: Route, ladder: Ladder, project: Rung | None) -> str:
|
||||
"""Names the worker's rung, so it learns whether its request for a higher rung went through, and the project's again, since a step-up between cycles may have taken the worker above it."""
|
||||
on = f" loop-claude runs you on {route.rung}." if project else ""
|
||||
ruled = f" A judge ruled the chunk unfinished, quoting this passage of your transcript as the work remaining:\n\n{quoted(unfinished_evidence)}\n\n" if unfinished_evidence else " "
|
||||
return f"Continue the task; the previous run ended before the chunk was finished.{ruled}The chunk is finished once it is merged, or nothing remains that you could do on your own. Even then, it is finished only once {ANSWERS_RECORDED}. {NAME_THE_ITEMS}{on}{rungs_held(route, project)}"
|
||||
return f"Continue the task; the previous run ended before the chunk was finished.{ruled}The chunk is finished once it is merged, or nothing remains that you could do on your own. Even then, it is finished only once {ANSWERS_RECORDED}. {NAME_THE_ITEMS}{on}{rungs_held(route, ladder, project)}"
|
||||
|
||||
|
||||
def rung_sentences(route: Route, project: Rung | None) -> list[str]:
|
||||
def rung_sentences(route: Route, ladder: Ladder, project: Rung | None) -> list[str]:
|
||||
"""The sentences that depend on the worker's rung: where its reviews run and rerun, and where its escalated subagents run."""
|
||||
return [*review_launches(route, project), *escalation(route, project), *reruns(route, project)]
|
||||
return [*review_launches(route, ladder, project), *escalation(route, ladder, project), *reruns(route, ladder, project)]
|
||||
|
||||
|
||||
def rungs_held(route: Route, project: Rung | None) -> str:
|
||||
def rungs_held(route: Route, ladder: Ladder, project: Rung | None) -> str:
|
||||
"""rung_sentences, each after a space, to follow the sentence a prompt ends on."""
|
||||
return "".join(f" {sentence}" for sentence in rung_sentences(route, project))
|
||||
return "".join(f" {sentence}" for sentence in rung_sentences(route, ladder, project))
|
||||
|
||||
|
||||
def answered(question: str, answer: str, route: Route, project: Rung | None, stepped: bool) -> str:
|
||||
def answered(question: str, answer: str, route: Route, ladder: Ladder, project: Rung | None, stepped: bool) -> str:
|
||||
"""stepped is whether the answer's ruling stepped the worker up."""
|
||||
return f"Your question: {question}\n\n{QUOTE_SOURCES} answers it:\n\n{answer}\n\nContinue the task.{stepped_to(route, project, stepped)}"
|
||||
return f"Your question: {question}\n\n{QUOTE_SOURCES} answers it:\n\n{answer}\n\nContinue the task.{stepped_to(route, ladder, project, stepped)}"
|
||||
|
||||
|
||||
def typed(question: str, answer: str, route: Route, project: Rung | None, stepped: bool) -> str:
|
||||
def typed(question: str, answer: str, route: Route, ladder: Ladder, project: Rung | None, stepped: bool) -> str:
|
||||
"""The prompt that resumes the worker with the human's answer to an interrupt. answer is one line, as the terminal reads it."""
|
||||
return f"{TYPED_HERE}\n{answer}\n\nYour question was: {question}\n\nContinue the task. The chunk is finished only once {ANSWERS_RECORDED}.{stepped_to(route, project, stepped)}"
|
||||
return f"{TYPED_HERE}\n{answer}\n\nYour question was: {question}\n\nContinue the task. The chunk is finished only once {ANSWERS_RECORDED}.{stepped_to(route, ladder, project, stepped)}"
|
||||
|
||||
|
||||
# Opens typed's prompt, with the answer on the line after it, so typed_answer finds the answer at the prompt's start, whatever the question holds.
|
||||
@@ -198,9 +198,9 @@ def typed_answer(prompt: str) -> Typed | None:
|
||||
return Typed(rest, answer)
|
||||
|
||||
|
||||
def stepped_to(route: Route, project: Rung | None, stepped: bool) -> str:
|
||||
def stepped_to(route: Route, ladder: Ladder, project: Rung | None, stepped: bool) -> str:
|
||||
"""The sentences naming the worker's new rung, as resumed has them, where the ruling that brought the answer stepped the worker up; empty otherwise."""
|
||||
return f" Your request for a higher rung went through: loop-claude runs you on {route.rung}. The escalation triggers that fired before this step are spent.{rungs_held(route, project)}" if stepped else ""
|
||||
return f" Your request for a higher rung went through: loop-claude runs you on {route.rung}. The escalation triggers that fired before this step are spent.{rungs_held(route, ladder, project)}" if stepped else ""
|
||||
|
||||
|
||||
def past_the_cap(question: str, answer: str, cap: int) -> str:
|
||||
|
||||
@@ -14,6 +14,7 @@ from failure import Failure
|
||||
from loop_claude.verdicts import Finished, Interrupt, Judged, QuotedAnswer, Unfinished, Verdict
|
||||
from loop_claude.cycle.interrupt import interrupt, Talked, WorkerSession
|
||||
from loop_claude.routing import judge_rung, next_route, step_up, StepUp
|
||||
from model_routing.ladder import Ladder, Rung
|
||||
from transcript_archive.read import last_spent
|
||||
from transcript_archive import outcomes
|
||||
from plan_store.stores import Plan
|
||||
@@ -21,7 +22,6 @@ from loop_claude.cycle import prompts
|
||||
from claude_code.transcript import read_transcript
|
||||
from loop_claude.cycle.retry import retried
|
||||
from model_routing.route import Route
|
||||
from model_routing.ladder import Rung
|
||||
from loop_claude.cycle import spend
|
||||
from loop_claude.stop import Stop
|
||||
from model_routing import worker_rungs
|
||||
@@ -39,6 +39,8 @@ class Cycle:
|
||||
# What chunk-preflight found, or why it could not run, for a fresh worker's prompt; empty when the session was open as the cycle began.
|
||||
facts: str
|
||||
judge_model: str
|
||||
# The project's routing ladder, as model_routing/ladder_file.py read it when the cycle started.
|
||||
ladder: Ladder
|
||||
premises: str
|
||||
# The project's rung; None for a model off the ladder.
|
||||
project: Rung | None
|
||||
@@ -79,7 +81,7 @@ def run_cycle(cycle: Cycle) -> Stop | Concluded:
|
||||
|
||||
def ruling_step_up(cycle: Cycle, verdict: Verdict) -> StepUp | None:
|
||||
"""The step-up an interrupt's or a quoted answer's escalation makes, so the work after the answer runs on the stepped route; None where the route holds. A finished or unfinished verdict steps the route only as the loop starts the next cycle."""
|
||||
return step_up(cycle.route, next_route(cycle.project, cycle.route, verdict)) if isinstance(verdict, Interrupt | QuotedAnswer) else None
|
||||
return step_up(cycle.route, next_route(cycle.ladder, cycle.project, cycle.route, verdict)) if isinstance(verdict, Interrupt | QuotedAnswer) else None
|
||||
|
||||
|
||||
def stopped(cycle: Cycle, stop: Stop, why: str) -> Stop:
|
||||
@@ -100,7 +102,7 @@ def archived(project_archive: pathlib.Path, transcript_path: str, task: str, out
|
||||
|
||||
def judge_of(cycle: Cycle) -> Rung:
|
||||
"""The judge's rung, which the archive names beside each verdict."""
|
||||
return judge_rung(cycle.judge_model)
|
||||
return judge_rung(cycle.ladder, cycle.judge_model)
|
||||
|
||||
|
||||
def step(cycle: Cycle, state: Active) -> Event | Stop:
|
||||
@@ -138,12 +140,12 @@ def worker_session(cycle: Cycle, transcript_path: str) -> WorkerSession:
|
||||
|
||||
def worker_start(cycle: Cycle, answered: QuotedAnswer | TypedAnswer | None, stepped: bool) -> list[str]:
|
||||
if isinstance(answered, QuotedAnswer):
|
||||
return worker_args(cycle.session, cycle.route.rung, prompts.answered(answered.question, answered.answer, cycle.route, cycle.project, stepped), resume=True)
|
||||
return worker_args(cycle.session, cycle.route.rung, prompts.answered(answered.question, answered.answer, cycle.route, cycle.ladder, cycle.project, stepped), resume=True)
|
||||
if isinstance(answered, TypedAnswer):
|
||||
return worker_args(cycle.session, cycle.route.rung, prompts.typed(answered.question, answered.answer, cycle.route, cycle.project, stepped), resume=True)
|
||||
return worker_args(cycle.session, cycle.route.rung, prompts.typed(answered.question, answered.answer, cycle.route, cycle.ladder, cycle.project, stepped), resume=True)
|
||||
if session_open(cycle.session):
|
||||
return worker_args(cycle.session, cycle.route.rung, prompts.resumed(cycle.unfinished_evidence, cycle.route, cycle.project), resume=True)
|
||||
return worker_args(cycle.session, cycle.route.rung, prompts.fresh(cycle.task, cycle.premises, cycle.route, cycle.project, cycle.facts), resume=False)
|
||||
return worker_args(cycle.session, cycle.route.rung, prompts.resumed(cycle.unfinished_evidence, cycle.route, cycle.ladder, cycle.project), resume=True)
|
||||
return worker_args(cycle.session, cycle.route.rung, prompts.fresh(cycle.task, cycle.premises, cycle.route, cycle.ladder, cycle.project, cycle.facts), resume=False)
|
||||
|
||||
|
||||
def rule(cycle: Cycle, transcript_path: str, quoted_answers: int) -> Ruled | Stop:
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
"""The slot a loop holds in its project, so that loops of one project, each on its own chunk, run side by side, each in a session named after its slot."""
|
||||
import dataclasses
|
||||
import os
|
||||
import pathlib
|
||||
|
||||
from failure import Failure
|
||||
from machine_load.slots import first_free_slot
|
||||
from loop_claude.loop.reload import LoopRun
|
||||
from loop_state.paths import Paths
|
||||
from transcript_archive.project_key import project_key
|
||||
from claude_code.session import Session, session_named, session_open
|
||||
|
||||
# Under the home folder, a folder per project key holds a file per slot, which a running loop keeps locked with flock.
|
||||
SLOTS = ".local/state/loop-claude"
|
||||
# A bound no project reaches. Once todo.md item 375 lands, the project's config sets how many loops run at once.
|
||||
MOST = 64
|
||||
|
||||
|
||||
def held_slot(home: pathlib.Path, key: str, claude_code_transcripts: pathlib.Path) -> int | Failure:
|
||||
"""The slot this loop takes, or why it could take none: the lowest free slot whose session is open, so that a rerun resumes a chunk left open, or else the lowest free slot. The loop holds it until it exits; a reload's exec keeps the lock."""
|
||||
folder = home / SLOTS / key
|
||||
order = sorted(range(MOST), key=lambda slot: not session_open(session_named(session_name(key, slot), claude_code_transcripts)))
|
||||
try:
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
taken = first_free_slot(folder, order)
|
||||
except OSError as failure:
|
||||
return Failure(f"cannot take a slot in {folder}: {failure.strerror}")
|
||||
if taken is None:
|
||||
return Failure(f"{MOST} loops of this project are running already; `fuser {folder}/slot-*` names them")
|
||||
slot, fd = taken
|
||||
os.set_inheritable(fd, True)
|
||||
return slot
|
||||
|
||||
|
||||
def session_name(key: str, slot: int) -> str:
|
||||
""""A " is the human's cue in the session picker that the session is the loop's. Slot 0 keeps the name every loop had before slots, so a chunk left open before slots resumes in it."""
|
||||
return f"A {key} loop-claude" if slot == 0 else f"A {key} loop-claude {slot + 1}"
|
||||
|
||||
|
||||
def slotted(loop_run: LoopRun, paths: Paths) -> tuple[LoopRun, Session] | Failure:
|
||||
"""loop_run holding its slot, and the worker's session, named after the slot. A reloaded script keeps the slot it is handed."""
|
||||
key = project_key(loop_run.root, paths.home)
|
||||
slot = held_slot(paths.home, key, paths.claude_code_transcripts) if loop_run.slot is None else loop_run.slot
|
||||
if isinstance(slot, Failure):
|
||||
return slot
|
||||
return dataclasses.replace(loop_run, slot=slot), session_named(session_name(key, slot), paths.claude_code_transcripts)
|
||||
@@ -9,12 +9,12 @@ from failure import Failure
|
||||
from loop_claude.routing import first_route, kept, routed_item
|
||||
from plan_store.stores import held_at, Plan, store as plan_store
|
||||
from release_plan.todo_table import Item
|
||||
from model_routing.ladder import Ladder, Rung
|
||||
from transcript_archive.read import latest_worker
|
||||
from project_config.main import located
|
||||
from loop_claude.loop.this_loop import Loop
|
||||
from loop_claude.cycle import prompts
|
||||
from model_routing.route import Route, route_from
|
||||
from model_routing.ladder import Rung
|
||||
from claude_code.session import session_open, transcript_file
|
||||
|
||||
# Seconds routing waits for origin to name its default branch, asked only where the checkout records none; past them, the chunk runs on the project's rung.
|
||||
@@ -34,15 +34,15 @@ def fetched_todo(loop: Loop) -> Plan | Failure:
|
||||
return todo
|
||||
|
||||
|
||||
def routed(route: Route | None, project: Rung | None, model: str, archived: typing.Callable[[], Route | None], item: typing.Callable[[], Item | None]) -> Route:
|
||||
"""The route the cycle runs on. project is the project's rung, and model the project's model.
|
||||
def routed(route: Route | None, ladder: Ladder, project: Rung | None, model: str, archived: typing.Callable[[], Route | None], item: typing.Callable[[], Item | None]) -> Route:
|
||||
"""The route the cycle runs on. project is the project's rung on ladder, and model the project's model.
|
||||
|
||||
Where project is None, the model is off the ladder, and the worker runs on it. Otherwise the chunk keeps route, or on a rerun the route its archive last names, as routing.kept allows. Else the plan item routes the chunk afresh.
|
||||
"""
|
||||
if project is None:
|
||||
return Route(Rung(model))
|
||||
route = route or archived()
|
||||
return route if route and kept(route, project) else first_route(project, item())
|
||||
return route if route and kept(route, ladder, project) else first_route(ladder, project, item())
|
||||
|
||||
|
||||
def archived_route(archive_folder: pathlib.Path, loop: Loop) -> Route | None:
|
||||
|
||||
@@ -4,20 +4,20 @@ import pathlib
|
||||
|
||||
from loop_claude.cycle.run import archived_step, archived_stop, Concluded
|
||||
from loop_claude.verdicts import Finished
|
||||
from model_routing.ladder import Ladder, Rung
|
||||
from loop_claude.loop.this_loop import Loop
|
||||
from loop_claude.loop.reload import LoopRun
|
||||
from loop_claude.stop import needs_human, Stop
|
||||
from loop_claude.routing import next_route, step_up
|
||||
from model_routing.ladder import Rung
|
||||
from claude_code.session import transcript_file
|
||||
|
||||
# How many unfinished verdicts running end the loop, so a worker and a judge that disagree about a chunk cannot cycle unattended without end. A policy number, not derived from the routing steps: well above the two unfinished verdicts running that archived chunks have reached at most, and low enough that a stuck pair is stopped after six cycles. It counts every unfinished verdict, including those of cycles where the human answered an interrupt: a rerun is cheap, and a chunk that needs that many answers is worth a look. The human confirmed both the number and what it counts.
|
||||
UNFINISHED_LIMIT = 6
|
||||
|
||||
|
||||
def closed_cycle(loop_run: LoopRun, project: Rung | None, concluded: Concluded, archive_folder: pathlib.Path, loop: Loop) -> LoopRun | Stop:
|
||||
def closed_cycle(loop_run: LoopRun, ladder: Ladder, project: Rung | None, concluded: Concluded, archive_folder: pathlib.Path, loop: Loop) -> LoopRun | Stop:
|
||||
"""The loop run after a cycle concluded, with the step-up archived; the stop that needs the human, archived, once the chunk has had UNFINISHED_LIMIT unfinished verdicts running."""
|
||||
after = after_verdict(loop_run, project, concluded)
|
||||
after = after_verdict(loop_run, ladder, project, concluded)
|
||||
# A finished chunk drops its route, so it has no step-up, and its run of unfinished verdicts restarts.
|
||||
if after.route is None:
|
||||
return after
|
||||
@@ -38,10 +38,10 @@ def reached_limit(loop_run: LoopRun) -> Stop | None:
|
||||
return needs_human("go on with the chunk", f"the judge ruled it unfinished {loop_run.unfinished_run} cycles running; finish the chunk yourself, or rerun loop-claude to give it {UNFINISHED_LIMIT} more cycles")
|
||||
|
||||
|
||||
def after_verdict(loop_run: LoopRun, project: Rung | None, concluded: Concluded) -> LoopRun:
|
||||
def after_verdict(loop_run: LoopRun, ladder: Ladder, project: Rung | None, concluded: Concluded) -> LoopRun:
|
||||
"""The loop run the next cycle starts from. A finished chunk drops its route and its run of unfinished verdicts. An unfinished one takes the route routing.next_route makes of the route its cycle ended on, which an interrupt's or a quoted answer's escalation may have raised, and the evidence the judge gave for the verdict; and counts the verdict."""
|
||||
verdict = concluded.verdict
|
||||
if isinstance(verdict, Finished):
|
||||
return dataclasses.replace(loop_run, route=None, unfinished_evidence="", unfinished_run=0)
|
||||
route = next_route(project, concluded.route, verdict)
|
||||
route = next_route(ladder, project, concluded.route, verdict)
|
||||
return dataclasses.replace(loop_run, route=route, unfinished_evidence=verdict.evidence, unfinished_run=loop_run.unfinished_run + 1)
|
||||
|
||||
@@ -17,10 +17,10 @@ from loop_claude.loop.usage import HELP
|
||||
from loop_claude.loop.this_loop import Loop
|
||||
from loop_state.paths import Paths
|
||||
from transcript_archive.project_key import project_key
|
||||
from model_routing.ladder import project_rung
|
||||
from model_routing.ladder_file import project_ladder_file, read_ladder, SHIPPED
|
||||
from loop_claude.project.premises import read_premises
|
||||
from loop_claude.project.records import read_records
|
||||
from claude_code.session import session_named
|
||||
from loop_claude.loop.chunk_slot import slotted
|
||||
from loop_claude.stop import Stop
|
||||
from loop_claude.direct_message import tell
|
||||
|
||||
@@ -46,8 +46,10 @@ def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launc
|
||||
if isinstance(loop_run, Stop):
|
||||
return loop_run
|
||||
baseline = fingerprint(launcher)
|
||||
# "A " is the human's cue in the session picker that the session is the loop's.
|
||||
session = session_named(f"A {project_key(loop_run.root, paths.home)} loop-claude", paths.claude_code_transcripts)
|
||||
held = slotted(loop_run, paths)
|
||||
if isinstance(held, Failure):
|
||||
return Stop(1, held.reason)
|
||||
loop_run, session = held
|
||||
loop = Loop(root=loop_run.root, session=session, paths=paths, env=env, launcher=launcher, effects=effects)
|
||||
while True:
|
||||
if stop := exec_if_edited(loop, baseline, loop_run):
|
||||
@@ -59,7 +61,7 @@ def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launc
|
||||
concluded = run_cycle(cycle)
|
||||
if isinstance(concluded, Stop):
|
||||
return concluded
|
||||
closed = closed_cycle(loop_run, cycle.project, concluded, cycle.project_archive, loop)
|
||||
closed = closed_cycle(loop_run, cycle.ladder, cycle.project, concluded, cycle.project_archive, loop)
|
||||
if isinstance(closed, Stop):
|
||||
return closed
|
||||
loop_run = closed
|
||||
@@ -69,7 +71,7 @@ def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launc
|
||||
|
||||
|
||||
def next_cycle(loop_run: LoopRun, loop: Loop) -> Cycle | Stop:
|
||||
"""The cycle loop_run runs next, from the premises, the records and the project's models read afresh, and the route the chunk runs on; the stop where one of them cannot be read."""
|
||||
"""The cycle loop_run runs next, from the premises, the records, the project's models and its routing ladder read afresh, and the route the chunk runs on; the stop where one of them cannot be read."""
|
||||
premises = read_premises(loop.root, loop.paths.home)
|
||||
if isinstance(premises, Failure):
|
||||
return Stop(1, premises.reason)
|
||||
@@ -79,14 +81,28 @@ def next_cycle(loop_run: LoopRun, loop: Loop) -> Cycle | Stop:
|
||||
models = get_or_ask_models(project_key(loop.root, loop.paths.home), loop.paths, loop.env, loop.effects)
|
||||
if isinstance(models, Stop):
|
||||
return models
|
||||
ladder_file = project_ladder_file(loop.root, loop.paths.home)
|
||||
if isinstance(ladder_file, Failure):
|
||||
return Stop(1, ladder_file.reason)
|
||||
ladder = read_ladder(ladder_file)
|
||||
if isinstance(ladder, Failure):
|
||||
return Stop(1, ladder.reason)
|
||||
archive_folder = project_archive(loop.root, loop.paths.home, loop.env)
|
||||
# After the reads above, so a loop that stops on one makes no worktree.
|
||||
facts, item = chunk_start(loop)
|
||||
project = project_rung(models.worker)
|
||||
route = routed(loop_run.route, project, models.worker, lambda: archived_route(archive_folder, loop), item)
|
||||
project = ladder.project_rung(models.worker)
|
||||
route = routed(loop_run.route, ladder, project, models.worker, lambda: archived_route(archive_folder, loop), item)
|
||||
say(f"\n=== cycle {loop_run.cycle_number}, worker on {route.rung} ===", loop.effects, stdout=True)
|
||||
if ladder_file != SHIPPED:
|
||||
say(own_ladder(ladder_file, models.worker, project is None), loop.effects)
|
||||
todo = fetched_todo(loop)
|
||||
return Cycle(config=setup_version(loop.paths.claude_dir, loop.effects.git), effects=loop.effects, facts=facts, judge_model=models.judge, premises=premises, project=project, project_archive=archive_folder, records=records, root=loop.root, route=route, session=loop.session, task=loop_run.task, todo=todo, unfinished_evidence=loop_run.unfinished_evidence)
|
||||
return Cycle(config=setup_version(loop.paths.claude_dir, loop.effects.git), effects=loop.effects, facts=facts, judge_model=models.judge, ladder=ladder, premises=premises, project=project, project_archive=archive_folder, records=records, root=loop.root, route=route, session=loop.session, task=loop_run.task, todo=todo, unfinished_evidence=loop_run.unfinished_evidence)
|
||||
|
||||
|
||||
def own_ladder(file: pathlib.Path, model: str, unrouted: bool) -> str:
|
||||
"""What a cycle says of a project that runs on a ladder of its own, so that a file left in place after its reason passed doesn't go unseen, nor one that leaves out the project's model, whose work the ladder then doesn't route."""
|
||||
routes = f" {model} is not on it, so the worker runs on {model} unrouted; LOOP_CLAUDE_WORKER_MODEL and LOOP_CLAUDE_JUDGE_MODEL name other models for a run." if unrouted else ""
|
||||
return f"routing on the project's own ladder, {file}.{routes}"
|
||||
|
||||
|
||||
def loop_run_from(argv: list[str], cwd: pathlib.Path, effects: Effects) -> LoopRun | Stop:
|
||||
|
||||
@@ -25,6 +25,8 @@ class LoopRun:
|
||||
route: Route | None = None
|
||||
# How many unfinished verdicts the chunk has had running; a finished chunk and a rerun each set it to 0. It stays apart from route and unfinished_evidence, though all three change together at each verdict: merging or renaming a field stops a running loop at its next reload.
|
||||
unfinished_run: int = 0
|
||||
# The project's slot this loop holds (chunk_slot.py); None until it takes one. A loop started before slots reloads with None, and so takes a slot then.
|
||||
slot: int | None = None
|
||||
|
||||
|
||||
class Unreadable(Exception):
|
||||
@@ -75,7 +77,7 @@ def decoded_route(value: object) -> Route | None:
|
||||
|
||||
|
||||
# One decoder per field of LoopRun, which a test holds to the dataclass's fields: a field missing here stops a loop at the reload after it joined.
|
||||
LOOP_RUN_FIELDS = {"cycle_number": exactly(int), "root": exactly(str), "task": exactly(str), "unfinished_evidence": exactly(str), "route": decoded_route, "unfinished_run": exactly(int)}
|
||||
LOOP_RUN_FIELDS = {"cycle_number": exactly(int), "root": exactly(str), "task": exactly(str), "unfinished_evidence": exactly(str), "route": decoded_route, "unfinished_run": exactly(int), "slot": lambda value: None if value is None else exactly(int)(value)}
|
||||
|
||||
|
||||
def fingerprint(launcher: pathlib.Path) -> str:
|
||||
|
||||
@@ -8,6 +8,7 @@ from loop_effects.effects import Effects, say
|
||||
from failure import Failure
|
||||
from loop_claude.loop.this_loop import Loop
|
||||
from loop_state.paths import Paths
|
||||
from model_routing.ladder_file import read_ladder, SHIPPED
|
||||
from routing_figures.render import render
|
||||
from model_routing.ladder import Rung
|
||||
from routing_figures import state
|
||||
@@ -41,9 +42,13 @@ def new_calls(root: pathlib.Path, paths: Paths, effects: Effects) -> list[Call]
|
||||
measured = archive.measure_archive(root, str(paths.home), raised.since, effects.git)
|
||||
if isinstance(measured, Failure):
|
||||
return measured
|
||||
# The shipped ladder, not the project's: the figures span every project.
|
||||
ladder = read_ladder(SHIPPED)
|
||||
if isinstance(ladder, Failure):
|
||||
return ladder
|
||||
figures = totals(measured.chunks, measured.skipped, measured.unread)
|
||||
found = calls(figures)
|
||||
if unwritten := archive.write_figures(root, render(figures, found, utc(effects.now()), cycle, raised.since)) or state.mark_measured(root, cycle):
|
||||
found = calls(ladder, figures)
|
||||
if unwritten := archive.write_figures(root, render(ladder, figures, found, utc(effects.now()), cycle, raised.since)) or state.mark_measured(root, cycle):
|
||||
return unwritten
|
||||
return [call for call in found if call not in raised.calls]
|
||||
|
||||
|
||||
@@ -10,20 +10,20 @@ first worker prompt also quotes the premises. They, with code health (~/.claude/
|
||||
"Shared goal") ranked first unless the goals file voids it, choose between ways to deliver the
|
||||
chunk's todo.md items, or else the task, and never widen them. A judge then reads the transcript's
|
||||
end, the premises, and the records: the project's AGENTS.md and docs/decisions.md, and the human's
|
||||
~/.claude/CLAUDE.md, ~/.claude/rules/*.md and ~/.claude/skills/larv-review/standards/*.md, where
|
||||
they exist. It rules whether the chunk, the work of one PR, is finished. A chunk stays unfinished
|
||||
until each answer the human typed in it that a later chunk could need is recorded: the premises or
|
||||
the records hold it, or the transcript shows the worker writing it into the premises, AGENTS.md,
|
||||
docs/decisions.md, todo.md or a code comment. A choice the worker made that the premises or the
|
||||
records settle is not asked about. When the worker asks a question they answer, the judge quotes the
|
||||
answer, loop-claude prints it, and the worker resumes with it. A quote they do not hold word for
|
||||
word is dropped, and the question goes to the human. So does a question asked again after its
|
||||
answer. A question the human answered earlier in the chunk goes back to the worker with that answer,
|
||||
unless the question quotes the words of the answer that leave it open. The fourth question they
|
||||
answer in one cycle goes to the human too, with the quote. An unfinished chunk resumes its session
|
||||
next cycle, and the worker is shown the passage the judge quoted as the work remaining. The next
|
||||
chunk starts a fresh session. Cycles continue until an exit below or Ctrl-C. Words:
|
||||
~/.claude/CLAUDE.md → "Vocabulary".
|
||||
~/.claude/CLAUDE.md and ~/.claude/rules/*.md, then the .md files in the folder of review standards
|
||||
the project's config sets, where they exist. It rules whether the chunk, the work of one PR, is
|
||||
finished. A chunk stays unfinished until each answer the human typed in it that a later chunk could
|
||||
need is recorded: the premises or the records hold it, or the transcript shows the worker writing it
|
||||
into the premises, AGENTS.md, docs/decisions.md, todo.md or a code comment. A choice the worker made
|
||||
that the premises or the records settle is not asked about. When the worker asks a question they
|
||||
answer, the judge quotes the answer, loop-claude prints it, and the worker resumes with it. A quote
|
||||
they do not hold word for word is dropped, and the question goes to the human. So does a question
|
||||
asked again after its answer. A question the human answered earlier in the chunk goes back to the
|
||||
worker with that answer, unless the question quotes the words of the answer that leave it open. The
|
||||
fourth question they answer in one cycle goes to the human too, with the quote. An unfinished chunk
|
||||
resumes its session next cycle, and the worker is shown the passage the judge quoted as the work
|
||||
remaining. The next chunk starts a fresh session. Cycles continue until an exit below or Ctrl-C.
|
||||
Words: ~/.claude/CLAUDE.md → "Vocabulary".
|
||||
|
||||
A question only the human can answer is an interrupt (bin/loop_claude/cycle/interrupt.py).
|
||||
loop-claude prints the question on its terminal, where the human answers it:
|
||||
@@ -43,8 +43,12 @@ what it prints in the first prompt (prompts.preflight_facts in bin/loop_claude/c
|
||||
chunk-preflight --help says what it finds and makes. A preflight that fails, or is still running
|
||||
after 600 s and is stopped, leaves the worker to find the facts itself.
|
||||
|
||||
Each project has one session, named "A <key> loop-claude", where <key> is the checkout's path
|
||||
relative to ~/code, or to / outside it. The session is deleted when its chunk finishes. At every
|
||||
Loops of one project run side by side, each on one chunk at a time. Each holds a slot of the
|
||||
project, the file slot-<n> under ~/.local/state/loop-claude/<key>/, locked while the loop runs.
|
||||
<key> is the checkout's path relative to ~/code, or to / outside it. A loop takes the lowest free
|
||||
slot whose session is open, so a rerun resumes a chunk left open, or else the lowest free slot.
|
||||
slot-0's session is named "A <key> loop-claude", and slot-<n>'s "A <key> loop-claude <n+1>".
|
||||
The session is deleted when its chunk finishes. At every
|
||||
interrupt, and as every cycle ends, Ctrl-C and a failure included, the session's transcript is
|
||||
copied into a folder per chunk under $LOOP_CLAUDE_TRANSCRIPTS/<key> (default root
|
||||
~/.claude/loop-claude-transcripts), named by its hash, with an outcomes file beside it: the task,
|
||||
@@ -65,8 +69,9 @@ entry, as on its first run, is asked for one on the terminal. LOOP_CLAUDE_JUDGE_
|
||||
the model for the judge, LOOP_CLAUDE_WORKER_MODEL for the worker and the session /talk opens; with
|
||||
both set, nothing is asked.
|
||||
|
||||
Where the project's model is on the routing ladder (bin/model_routing/ladder.py), the worker and the
|
||||
session /talk opens run on the rung that the chunk's todo.md item picks, and the judge of some
|
||||
The routing ladder is a list of rungs, least competent first, each a model at an effort. Where the
|
||||
project's model is on it, the worker and the session /talk opens run on
|
||||
the rung that the chunk's todo.md item picks, and the judge of some
|
||||
models on another; a chunk no item routes runs on the project's model. The worker's prompts name the
|
||||
rungs it launches its reviews on. The worker's rung steps up as a chunk stays unfinished, when the
|
||||
worker names on its `Chunk items:` line an item that picks a higher rung, or when the judge finds
|
||||
@@ -79,6 +84,22 @@ bin/model_routing/route.py); a rerun resumes an open chunk on the latest route n
|
||||
todo.md or an archive that cannot be read or parsed is said on stderr, and the chunk is routed
|
||||
without it.
|
||||
|
||||
The ladder is a JSON file, each rung a model's full name and an effort of low, medium, high, xhigh
|
||||
or max:
|
||||
|
||||
[
|
||||
{"model": "claude-opus-5-5", "effort": "medium"},
|
||||
{"model": "claude-fable-5-2", "effort": "low"}
|
||||
]
|
||||
|
||||
It holds one model of each family, such as opus, since the Agent tool launches a subagent or a
|
||||
review by its family's name. This setup ships one, bin/model_routing/routing-ladder.json. A project
|
||||
that keeps a routing-ladder.json in its config's folder, ~/.claude-projects/<key>/, runs on that
|
||||
ladder instead, whole: write there every rung the project may run on. loop-claude reads the
|
||||
project's ladder as each cycle starts, says on stderr where the project runs on its own, and never
|
||||
commits the file. subagent-rung and rule-hook read the same ladder; the routing figures,
|
||||
judge-replay and review-replay, which span every project, read the shipped one.
|
||||
|
||||
Once 20 cycles have closed across all projects in the archive since the last measurement, the next
|
||||
loop to close one measures every finished chunk there, with no model run, and writes
|
||||
routing-figures.md at the archive's root (bin/routing_figures/). Each call the figures make for a
|
||||
@@ -95,10 +116,12 @@ loop-claude --help succeeds: the loop reloads into the edited script.
|
||||
Exit 1, saying why, when:
|
||||
- no task is given
|
||||
- git cannot start or finds no checkout
|
||||
- its slot in the project cannot be taken
|
||||
- the goals file, or AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/*.md or
|
||||
~/.claude/skills/larv-review/standards/*.md where they exist, cannot be read or is not UTF-8
|
||||
the project's review standards where they exist, cannot be read or is not UTF-8
|
||||
- no config names the checkout, its config cannot be read, or the goals file holds no premises
|
||||
- the models file cannot be read or written
|
||||
- the project's routing ladder cannot be read or holds a fault
|
||||
- claude leaves no transcript
|
||||
- a transcript cannot be read or archived
|
||||
- a finished chunk's session cannot be deleted
|
||||
@@ -123,4 +146,4 @@ Exit 2, when the human is needed to go on:
|
||||
- the claude opened for /talk, 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."""
|
||||
Rerunning resumes an open session that no running loop holds, the lowest one first."""
|
||||
|
||||
@@ -9,26 +9,27 @@ from record_store.stores import store
|
||||
RECORD_FILES = ("AGENTS.md", "docs/decisions.md")
|
||||
# The setting in the project's config that places each of RECORD_FILES.
|
||||
RECORD_SETTINGS = ("working-rules", "decisions")
|
||||
# The human's rules for every project, under ~/.claude: CLAUDE.md, then each .md file in these folders, which a repo check keeps present.
|
||||
# The human's rules, in the order the judge reads them: ~/.claude/CLAUDE.md, each .md file in ~/.claude/rules/,
|
||||
# then each .md file in the review standards folder the project's config sets.
|
||||
HUMAN_RULES_FILE = "CLAUDE.md"
|
||||
HUMAN_RULE_DIRS = ("rules", "skills/larv-review/standards")
|
||||
HUMAN_RULE_NAMES = (f"~/.claude/{HUMAN_RULES_FILE}", *(f"~/.claude/{folder}/" for folder in HUMAN_RULE_DIRS))
|
||||
HUMAN_RULE_DIR = "rules"
|
||||
HUMAN_RULE_NAMES = (f"~/.claude/{HUMAN_RULES_FILE}", f"~/.claude/{HUMAN_RULE_DIR}/", "the project's review standards")
|
||||
|
||||
|
||||
CONSEQUENCE = "the judge cannot read the records"
|
||||
|
||||
|
||||
def read_records(root: str, home: pathlib.Path, claude_dir: pathlib.Path) -> str | Failure:
|
||||
"""The project's `AGENTS.md` and decision log, then the human's rules for every project, CLAUDE.md first, each headed by its name; one that does not exist, or is empty, is left out.
|
||||
"""The project's `AGENTS.md` and decision log, then the human's rules, CLAUDE.md first, each headed by its name; one that does not exist, or is empty, is left out.
|
||||
|
||||
`AGENTS.md` is read where the config under home of root's project puts it, and the decision log from the store that config names. Each is headed by its name in RECORD_FILES wherever it is kept."""
|
||||
config = located(root, home)
|
||||
if isinstance(config, Failure):
|
||||
return Failure(f"{config.reason} - {CONSEQUENCE}.")
|
||||
rules = [claude_dir / HUMAN_RULES_FILE] + [rule for folder in HUMAN_RULE_DIRS for rule in sorted((claude_dir / folder).glob("*.md"))]
|
||||
rules = [claude_dir / HUMAN_RULES_FILE, *sorted((claude_dir / HUMAN_RULE_DIR).glob("*.md")), *sorted(config.paths["standards"].glob("*.md"))]
|
||||
decisions = store(config, RECORD_SETTINGS[1]).read()
|
||||
texts = [(RECORD_FILES[0], file_text(config.paths[RECORD_SETTINGS[0]])), (RECORD_FILES[1], Failure(f"{decisions.reason} - {CONSEQUENCE}.") if isinstance(decisions, Failure) else decisions)]
|
||||
texts += [(f"~/.claude/{rule.relative_to(claude_dir)}", file_text(rule)) for rule in rules]
|
||||
texts += [(named(rule, home, claude_dir), file_text(rule)) for rule in rules]
|
||||
records = []
|
||||
for heading, text in texts:
|
||||
if isinstance(text, Failure):
|
||||
@@ -41,3 +42,10 @@ def read_records(root: str, home: pathlib.Path, claude_dir: pathlib.Path) -> str
|
||||
def file_text(path: pathlib.Path) -> str | Failure:
|
||||
"""path's text, empty where no such file exists."""
|
||||
return read_utf8(str(path.parent), path.name, CONSEQUENCE) if path.exists() else ""
|
||||
|
||||
|
||||
def named(rule: pathlib.Path, home: pathlib.Path, claude_dir: pathlib.Path) -> str:
|
||||
"""rule's path as the human writes it: under ~/.claude, or ~/ for the rest of home, or else in full."""
|
||||
if rule.is_relative_to(claude_dir):
|
||||
return f"~/.claude/{rule.relative_to(claude_dir)}"
|
||||
return f"~/{rule.relative_to(home)}" if rule.is_relative_to(home) else str(rule)
|
||||
|
||||
+34
-34
@@ -30,11 +30,11 @@ Each verdict then moves the rung by one rule, and the rung never falls. The rung
|
||||
import dataclasses
|
||||
|
||||
from release_plan.release_standing import chunk_item, LastCut, Next
|
||||
from model_routing.ladder import climbed, highest, LADDER, position, project_rung, Rung, stepped_up, worker_rung
|
||||
from loop_claude import escalation_mark
|
||||
from failure import Failure
|
||||
from loop_claude.verdicts import Interrupt, QuotedAnswer, Unfinished
|
||||
from release_plan.todo_table import Item, NoItemsTable
|
||||
from model_routing.ladder import Ladder, Rung
|
||||
from plan_store.stores import Plan
|
||||
from model_routing.route import Route
|
||||
|
||||
@@ -56,42 +56,42 @@ def routed_item(plan: Plan | Failure, cut: LastCut) -> Item | Failure | None:
|
||||
return takes if takes and takes.likelihood and takes.escape_and_impact else None
|
||||
|
||||
|
||||
def first_route(project: Rung, item: Item | None) -> Route:
|
||||
"""The route a chunk starts on: the rung its item's L picks from the project's rung, or the project's rung without an item."""
|
||||
def first_route(ladder: Ladder, project: Rung, item: Item | None) -> Route:
|
||||
"""The route a chunk starts on: the rung its item's L picks on ladder from the project's rung, or the project's rung without an item."""
|
||||
if item is None:
|
||||
return Route(project)
|
||||
return Route(worker_rung(project, item.likelihood), item.id, item.likelihood, item.escape_and_impact)
|
||||
return Route(ladder.worker_rung(project, item.likelihood), item.id, item.likelihood, item.escape_and_impact)
|
||||
|
||||
|
||||
def kept(route: Route, project: Rung) -> bool:
|
||||
def kept(route: Route, ladder: Ladder, project: Rung) -> bool:
|
||||
"""Whether a chunk keeps route: its rung is on the ladder and at or above item_rung."""
|
||||
return floor_rung(project, route) == route.rung
|
||||
return floor_rung(ladder, project, route) == route.rung
|
||||
|
||||
|
||||
def item_rung(project: Rung, route: Route) -> Rung:
|
||||
def item_rung(ladder: Ladder, project: Rung, route: Route) -> Rung:
|
||||
"""The rung the route's item's L picks from the project's rung, or the project's rung itself when no item routed it. The worker may run on a rung below the project's."""
|
||||
return worker_rung(project, route.likelihood) if route.item else project
|
||||
return ladder.worker_rung(project, route.likelihood) if route.item else project
|
||||
|
||||
|
||||
def floor_rung(project: Rung, route: Route, likelihood_taken_in: int = 0) -> Rung:
|
||||
def floor_rung(ladder: Ladder, project: Rung, route: Route, likelihood_taken_in: int = 0) -> Rung:
|
||||
"""The lowest rung the worker may run on: the route's own, raised to item_rung where it is lower or off the ladder, and to the rung likelihood_taken_in picks from project. likelihood_taken_in is the highest L the worker took into the chunk, 0 for none."""
|
||||
floor = highest(route.rung, item_rung(project, route))
|
||||
return highest(floor, worker_rung(project, likelihood_taken_in)) if likelihood_taken_in else floor
|
||||
floor = ladder.highest(route.rung, item_rung(ladder, project, route))
|
||||
return ladder.highest(floor, ladder.worker_rung(project, likelihood_taken_in)) if likelihood_taken_in else floor
|
||||
|
||||
|
||||
def escalation_rungs(project: Rung, route: Route) -> tuple[Rung, ...]:
|
||||
def escalation_rungs(ladder: Ladder, project: Rung, route: Route) -> tuple[Rung, ...]:
|
||||
"""The rungs an escalation trigger opens to the worker, least competent first: from one above its own up to escalation_cap; none off the ladder."""
|
||||
if route.rung not in LADDER:
|
||||
if route.rung not in ladder.rungs:
|
||||
return ()
|
||||
return LADDER[position(route.rung) + 1:position(escalation_cap(project, route)) + 1]
|
||||
return ladder.rungs[ladder.position(route.rung) + 1:ladder.position(escalation_cap(ladder, project, route)) + 1]
|
||||
|
||||
|
||||
def escalation_cap(project: Rung, route: Route) -> Rung:
|
||||
def escalation_cap(ladder: Ladder, project: Rung, route: Route) -> Rung:
|
||||
"""The highest rung an escalation trigger takes the worker or a task to without the human's yes: docs/decisions.md → `routing: a worker hands a task one rung up`.
|
||||
|
||||
It counts from item_rung, the rung the chunk started on, so a step-up between cycles narrows what the worker may climb without a yes, and never widens it.
|
||||
"""
|
||||
return climbed(item_rung(project, route), ESCALATION_CAP)
|
||||
return ladder.climbed(item_rung(ladder, project, route), ESCALATION_CAP)
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
@@ -101,31 +101,31 @@ class StepUp:
|
||||
after: Route
|
||||
|
||||
|
||||
def next_route(project: Rung | None, route: Route, verdict: Unfinished | Interrupt | QuotedAnswer) -> Route:
|
||||
def next_route(ladder: Ladder, project: Rung | None, route: Route, verdict: Unfinished | Interrupt | QuotedAnswer) -> Route:
|
||||
"""The route the worker runs on after the judge's verdict. Off the ladder, project is None, and the route holds. The rung never falls."""
|
||||
if project is None:
|
||||
return route
|
||||
if isinstance(verdict, Unfinished):
|
||||
return unfinished_route(project, route, verdict)
|
||||
return escalated_route(project, route, verdict)
|
||||
return unfinished_route(ladder, project, route, verdict)
|
||||
return escalated_route(ladder, project, route, verdict)
|
||||
|
||||
|
||||
def unfinished_route(project: Rung, route: Route, verdict: Unfinished) -> Route:
|
||||
def unfinished_route(ladder: Ladder, project: Rung, route: Route, verdict: Unfinished) -> Route:
|
||||
"""The route after an unfinished verdict. The rung rises to floor_rung, which the verdict's highest L taken in may raise.
|
||||
|
||||
The verdict counts towards UNFINISHED_PER_STEP. Where steps says so, the rung steps once from the floor, and the mark moves only where the verdict escalates. Last, the route takes in the verdict's highest E + I, as Route.taking_in does.
|
||||
"""
|
||||
mark = escalation_mark.moved_to(verdict)
|
||||
floor = floor_rung(project, route, verdict.taken_in.highest_likelihood)
|
||||
floor = floor_rung(ladder, project, route, verdict.taken_in.highest_likelihood)
|
||||
counted = route.unfinished + 1
|
||||
if steps(counted, mark is not None and below_cap(project, route, floor)):
|
||||
after = one_rung_up(route, floor, route.escalated_at if mark is None else mark)
|
||||
if steps(counted, mark is not None and below_cap(ladder, project, route, floor)):
|
||||
after = one_rung_up(ladder, route, floor, route.escalated_at if mark is None else mark)
|
||||
else:
|
||||
after = dataclasses.replace(route, rung=floor, unfinished=counted)
|
||||
return after.taking_in(verdict.taken_in.highest_escape_and_impact)
|
||||
|
||||
|
||||
def escalated_route(project: Rung, route: Route, verdict: Interrupt | QuotedAnswer) -> Route:
|
||||
def escalated_route(ladder: Ladder, project: Rung, route: Route, verdict: Interrupt | QuotedAnswer) -> Route:
|
||||
"""The route after an interrupt or a quoted answer. Without an escalation it holds, since neither is an unfinished verdict.
|
||||
|
||||
With one, the rung rises to floor_rung, which the verdict's highest L taken in may raise. Where floor_rung lies below escalation_cap, the rung steps one up from it and the mark moves, as loop_claude/escalation_mark.py says; at the cap the rung stays on floor_rung and the mark holds.
|
||||
@@ -133,8 +133,8 @@ def escalated_route(project: Rung, route: Route, verdict: Interrupt | QuotedAnsw
|
||||
mark = escalation_mark.moved_to(verdict)
|
||||
if mark is None:
|
||||
return route
|
||||
floor = floor_rung(project, route, verdict.taken_in.highest_likelihood)
|
||||
return one_rung_up(route, floor, mark) if below_cap(project, route, floor) else dataclasses.replace(route, rung=floor)
|
||||
floor = floor_rung(ladder, project, route, verdict.taken_in.highest_likelihood)
|
||||
return one_rung_up(ladder, route, floor, mark) if below_cap(ladder, project, route, floor) else dataclasses.replace(route, rung=floor)
|
||||
|
||||
|
||||
def steps(counted: int, escalates: bool) -> bool:
|
||||
@@ -142,9 +142,9 @@ def steps(counted: int, escalates: bool) -> bool:
|
||||
return counted >= UNFINISHED_PER_STEP or escalates
|
||||
|
||||
|
||||
def below_cap(project: Rung, route: Route, floor: Rung) -> bool:
|
||||
def below_cap(ladder: Ladder, project: Rung, route: Route, floor: Rung) -> bool:
|
||||
"""Whether an escalation from floor may step the rung: floor lies below escalation_cap."""
|
||||
return position(floor) < position(escalation_cap(project, route))
|
||||
return ladder.position(floor) < ladder.position(escalation_cap(ladder, project, route))
|
||||
|
||||
|
||||
def step_up(before: Route, after: Route) -> StepUp | None:
|
||||
@@ -152,13 +152,13 @@ def step_up(before: Route, after: Route) -> StepUp | None:
|
||||
return StepUp(before, after) if after.worker_line() != before.worker_line() else None
|
||||
|
||||
|
||||
def one_rung_up(route: Route, rung: Rung, escalated_at: int) -> Route:
|
||||
def one_rung_up(ladder: Ladder, route: Route, rung: Rung, escalated_at: int) -> Route:
|
||||
"""The route one rung above rung, with the count of unfinished verdicts restarted and the mark at escalated_at."""
|
||||
return dataclasses.replace(route, rung=stepped_up(rung), unfinished=0, escalated_at=escalated_at)
|
||||
return dataclasses.replace(route, rung=ladder.stepped_up(rung), unfinished=0, escalated_at=escalated_at)
|
||||
|
||||
|
||||
def judge_rung(judge_model: str) -> Rung:
|
||||
"""The highest of the judge model's own rungs: docs/decisions.md → `routing: on a model judge-replay covered`. A model off the ladder, or not in JUDGE_REPLAYED, gets no effort flag, so claude runs it at the effort its settings give."""
|
||||
if project_rung(judge_model) is None or judge_model not in JUDGE_REPLAYED:
|
||||
def judge_rung(ladder: Ladder, judge_model: str) -> Rung:
|
||||
"""The highest of the judge model's own rungs on ladder: docs/decisions.md → `routing: on a model judge-replay covered`. A model off the ladder, or not in JUDGE_REPLAYED, gets no effort flag, so claude runs it at the effort its settings give."""
|
||||
if ladder.project_rung(judge_model) is None or judge_model not in JUDGE_REPLAYED:
|
||||
return Rung(judge_model)
|
||||
return highest(*(rung for rung in LADDER if rung.model == judge_model))
|
||||
return ladder.highest(*(rung for rung in ladder.rungs if rung.model == judge_model))
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import dataclasses
|
||||
import datetime
|
||||
import fcntl
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
@@ -467,6 +468,38 @@ class Cycles(unittest.TestCase):
|
||||
self.assertIn('<UTC> Verdict: unfinished\n\nEvidence:\n> three\n\nConfig: <config>\nJudge: judge-model\nWorker: {"model": "claude-opus-5-5", "effort": "medium", "item": 4, "likelihood": 2, "escape_and_impact": 3}\n\n<UTC> Stepped up\n\nWorker: {"model": "claude-fable-5-2", "effort": "low", "item": 4, "likelihood": 2, "escape_and_impact": 3}\n', outcomes)
|
||||
self.assertIn('<UTC> Verdict: finished\n\nEvidence:\n> four\n\nConfig: <config>\nJudge: judge-model\nWorker: {"model": "claude-fable-5-2", "effort": "low", "item": 4, "likelihood": 2, "escape_and_impact": 3}\n', outcomes)
|
||||
|
||||
def test_routes_on_the_ladder_the_projects_config_folder_holds_in_place_of_the_shipped_one(self):
|
||||
checkout = Checkout(self)
|
||||
checkout.env["LOOP_CLAUDE_WORKER_MODEL"] = "claude-fable-5-2"
|
||||
ladder = checkout.home / ".claude-projects" / "proj" / "routing-ladder.json"
|
||||
ladder.write_text('[{"model": "claude-fable-5-2", "effort": "low"}, {"model": "claude-fable-5-2", "effort": "max"}]')
|
||||
checkout.commit_plan(CHEAP)
|
||||
run = checkout.run([worker(), judge(), worker(), judge(), worker()])
|
||||
self.assertEqual(run.code, 130)
|
||||
# Item 4's L of 2 steps one rung down, to Opus 5.5 on the shipped ladder; the project's ladder holds no rung below the project's rung, and one above it, which the second unfinished verdict steps to.
|
||||
self.assertEqual([(argument(call, "--model"), argument(call, "--effort")) for call in run.calls if call["role"] == "worker"], [("claude-fable-5-2", "low"), ("claude-fable-5-2", "low"), ("claude-fable-5-2", "max")])
|
||||
self.assertEqual(run.stderr.count(f"routing on the project's own ladder, {ladder}.\n"), 3, "each cycle says so")
|
||||
|
||||
def test_says_where_the_projects_own_ladder_leaves_out_the_workers_model_and_says_nothing_on_the_shipped_one(self):
|
||||
checkout = Checkout(self)
|
||||
self.assertNotIn("own ladder", checkout.run([worker()]).stderr)
|
||||
ladder = checkout.home / ".claude-projects" / "proj" / "routing-ladder.json"
|
||||
ladder.write_text('[{"model": "claude-fable-5-2", "effort": "low"}]')
|
||||
run = checkout.run([worker()])
|
||||
self.assertIn(f"routing on the project's own ladder, {ladder}. worker-model is not on it, so the worker runs on worker-model unrouted; LOOP_CLAUDE_WORKER_MODEL and LOOP_CLAUDE_JUDGE_MODEL name other models for a run.\n", run.stderr)
|
||||
self.assertEqual((argument(run.calls[0], "--model"), argument(run.calls[0], "--effort")), ("worker-model", None))
|
||||
|
||||
def test_reads_the_projects_ladder_afresh_each_cycle_and_exits_1_once_it_holds_a_fault(self):
|
||||
checkout = Checkout(self)
|
||||
checkout.env["LOOP_CLAUDE_WORKER_MODEL"] = "claude-fable-5-2"
|
||||
ladder = checkout.home / ".claude-projects" / "proj" / "routing-ladder.json"
|
||||
ladder.write_text('[{"model": "claude-fable-5-2", "effort": "high"}]')
|
||||
checkout.env["FAKE_CLAUDE_EDIT"] = str(ladder.parent)
|
||||
run = checkout.run([worker(replace=["routing-ladder.json", '"high"}', '"high"},']), judge()])
|
||||
self.assertEqual((run.code, run.roles()), (1, ["worker", "judge"]))
|
||||
self.assertEqual((argument(run.calls[0], "--model"), argument(run.calls[0], "--effort")), ("claude-fable-5-2", "high"))
|
||||
self.assertIn(f"cannot read the routing ladder {ladder}: ", run.stderr)
|
||||
|
||||
def test_routes_on_and_states_the_same_item_from_the_fetched_default_branch_whatever_the_checkout_holds(self):
|
||||
checkout = Checkout(self)
|
||||
checkout.env["LOOP_CLAUDE_WORKER_MODEL"] = "claude-opus-5-5"
|
||||
@@ -575,6 +608,27 @@ class Cycles(unittest.TestCase):
|
||||
self.assertIsNotNone(argument(run.calls[0], "--resume"))
|
||||
self.assertEqual((argument(run.calls[0], "--model"), argument(run.calls[0], "--effort")), ("claude-fable-5-2", "medium"))
|
||||
|
||||
def test_a_second_loop_in_the_project_runs_its_own_session_and_leaves_the_first_loops_open_chunk_alone(self):
|
||||
checkout = Checkout(self)
|
||||
first = checkout.run([worker(say="first chunk"), judge(evidence="first chunk")])
|
||||
session = argument(first.calls[0], "--session-id")
|
||||
transcript = checkout.transcripts()[0]
|
||||
kept, archived = transcript.read_bytes(), checkout.archived()
|
||||
slot = checkout.home / ".local" / "state" / "loop-claude" / "proj" / "slot-0"
|
||||
slot.parent.mkdir(parents=True, exist_ok=True)
|
||||
# The test holds the first loop's slot, as the first loop does while it runs.
|
||||
with open(slot, "a") as running:
|
||||
fcntl.flock(running, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
second = checkout.run([worker(say="second chunk"), judge(evidence="second chunk")])
|
||||
self.assertEqual(argument(second.calls[0], "--name"), "A proj loop-claude 2")
|
||||
self.assertNotIn(session, [argument(call, "--session-id") or argument(call, "--resume") for call in second.calls if call["role"] == "worker"])
|
||||
self.assertNotIn("first chunk", second.calls[1]["stdin"])
|
||||
self.assertEqual(transcript.read_bytes(), kept)
|
||||
self.assertLessEqual(archived.items(), checkout.archived().items())
|
||||
self.assertEqual(len(checkout.archived()), len(archived) + 1)
|
||||
rerun = checkout.run([worker()])
|
||||
self.assertEqual(argument(rerun.calls[0], "--resume"), session)
|
||||
|
||||
def test_exits_1_when_the_transcript_cannot_be_archived_and_resumes_on_the_next_run(self):
|
||||
checkout = Checkout(self)
|
||||
checkout.archive().parent.mkdir(parents=True)
|
||||
@@ -917,7 +971,7 @@ class Reload(unittest.TestCase):
|
||||
self.assertEqual(run.roles(), ["worker", "judge"] * 5)
|
||||
self.assertIn("keeping the running script", run.stderr)
|
||||
reloads = [json.loads(argv[1]) for argv in run.starts if argv[:1] == ["--reloaded"]]
|
||||
self.assertEqual(reloads, [{"cycle_number": cycle, "root": str(checkout.root), "task": TASK, "unfinished_evidence": "working", "route": OFF_LADDER_ROUTE, "unfinished_run": cycle} for cycle in (2, 3, 4)])
|
||||
self.assertEqual(reloads, [{"cycle_number": cycle, "root": str(checkout.root), "task": TASK, "unfinished_evidence": "working", "route": OFF_LADDER_ROUTE, "unfinished_run": cycle, "slot": 0} for cycle in (2, 3, 4)])
|
||||
self.assertIn("=== cycle 5,", run.stdout)
|
||||
|
||||
outside = checkout.temp / "outside"
|
||||
|
||||
+197
-118
@@ -21,7 +21,7 @@ from routing_figures import archive, state
|
||||
from routing_figures.calls import Call
|
||||
from loop_claude.project import checkout, model_choice, records
|
||||
from loop_claude.cycle import chunk_items
|
||||
from loop_claude.loop import chunk_start, close
|
||||
from loop_claude.loop import chunk_slot, chunk_start, close
|
||||
from project_config.test_project_config import configured
|
||||
from release_plan.release_standing import DefaultPlan, LastCut, UNSEEN_RELEASES
|
||||
from loop_effects.effects import Effects, PYTHON_TIMEOUT
|
||||
@@ -30,7 +30,6 @@ from failure import Failure
|
||||
from loop_claude.verdicts import Finished, Interrupt, Judged, QuotedAnswer, TakenIn, Unfinished
|
||||
from git_cli.git_repo import git
|
||||
from loop_claude.cycle import interrupt, judge, prompts, retry, run, spend, states, worker
|
||||
from model_routing.ladder import LADDER, Rung
|
||||
from claude_code.reply import Limited
|
||||
from loop_claude.loop import main, reload, routing_check, this_loop, usage
|
||||
from machine_load import memory
|
||||
@@ -38,14 +37,17 @@ from transcript_archive import outcomes, write
|
||||
from loop_state import paths
|
||||
from plan_store.stores import plan_of
|
||||
from transcript_archive.location import project_archive
|
||||
from model_routing.ladder_file import read_ladder, SHIPPED
|
||||
from model_routing.route import Route, route_from, WorkerLine
|
||||
from loop_claude import routing
|
||||
from model_routing.ladder import Rung
|
||||
from loop_claude.stop import Stop
|
||||
from claude_code.tokens import Tokens, tokens_of
|
||||
from text_files.utc_stamp import utc
|
||||
from loop_claude.cycle.judge import verdict_from
|
||||
|
||||
# How the archive records a worker that runs off the ladder.
|
||||
LADDER = read_ladder(SHIPPED)
|
||||
OFF_LADDER = '{"model": "worker-model"}'
|
||||
# The claude-config release and commit each cycle the tests run is under.
|
||||
CONFIG = "v0.8.0 (abc123)"
|
||||
@@ -250,7 +252,7 @@ class Transitions(unittest.TestCase):
|
||||
class QuestionFor(unittest.TestCase):
|
||||
def test_puts_an_interrupts_question_as_asked_and_a_quoted_answer_past_the_cap_with_its_quote(self):
|
||||
self.assertEqual(run.question_for(Interrupt("e", "Which one?")), "Which one?")
|
||||
self.assertEqual(run.question_for(QuotedAnswer("e", "Which one?", "A.")), "Which one?\n\nthe goals file's Goals and Audience, AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/ or ~/.claude/skills/larv-review/standards/ says:\nA.\n\nThose files have answered 3 questions this cycle, the most allowed, so this one comes to you.")
|
||||
self.assertEqual(run.question_for(QuotedAnswer("e", "Which one?", "A.")), "Which one?\n\nthe goals file's Goals and Audience, AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/ or the project's review standards says:\nA.\n\nThose files have answered 3 questions this cycle, the most allowed, so this one comes to you.")
|
||||
|
||||
|
||||
class Cycles(unittest.TestCase):
|
||||
@@ -263,7 +265,7 @@ class Cycles(unittest.TestCase):
|
||||
self.archive = project_archive(str(self.home / "code" / "proj"), self.home, {})
|
||||
|
||||
def cycle(self, fake, records="", unfinished_evidence="", facts="- A preflight fact."):
|
||||
return run.Cycle(config=CONFIG, effects=fake.effects(), facts=facts, judge_model="judge-model", premises="## Goals", project=None, project_archive=self.archive, records=records, root=str(self.home), route=Route(Rung("worker-model")), session=self.session, task="Do it.", todo=plan_of(""), unfinished_evidence=unfinished_evidence)
|
||||
return run.Cycle(config=CONFIG, effects=fake.effects(), facts=facts, judge_model="judge-model", ladder=LADDER, premises="## Goals", project=None, project_archive=self.archive, records=records, root=str(self.home), route=Route(Rung("worker-model")), session=self.session, task="Do it.", todo=plan_of(""), unfinished_evidence=unfinished_evidence)
|
||||
|
||||
def archived_outcomes(self):
|
||||
return sorted(path.read_text() for path in self.archive.glob("*/*.outcomes.md"))
|
||||
@@ -491,12 +493,12 @@ Spent since 2026-09-21T14:13:20Z, in tokens of input, cache write 5m, cache writ
|
||||
with contextlib.redirect_stderr(io.StringIO()) as said, contextlib.redirect_stdout(io.StringIO()) as printed:
|
||||
self.assertEqual(run.run_cycle(self.cycle(fake, records="From AGENTS.md:\nUse A.")), Stop(2, "the human is needed to answer the question above, but nothing was typed"))
|
||||
resumed = fake.made("stream_claude")[1]
|
||||
self.assertEqual(resumed[resumed.index("-p") + 1], "Your question: Which one?\n\nthe goals file's Goals and Audience, AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/ or ~/.claude/skills/larv-review/standards/ answers it:\n\nUse *A*.\n\nContinue the task.")
|
||||
self.assertEqual(resumed[resumed.index("-p") + 1], "Your question: Which one?\n\nthe goals file's Goals and Audience, AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/ or the project's review standards answers it:\n\nUse *A*.\n\nContinue the task.")
|
||||
self.assertEqual(len(fake.made("stream_claude")), 4)
|
||||
self.assertEqual(printed.getvalue().count("=== the goals file'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\nthe goals file'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\nthe goals file'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\nthe goals file'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])
|
||||
self.assertEqual(printed.getvalue().count("=== the goals file's Goals and Audience, AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/ or the project's review standards answered: Which one? ===\nUse *A*."), 3)
|
||||
self.assertIn("Which one?\n\nthe goals file's Goals and Audience, AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/ or the project's 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\nthe goals file's Goals and Audience, AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/ or the project's 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\nthe goals file's Goals and Audience, AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/ or the project's 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")])
|
||||
@@ -506,7 +508,7 @@ Spent since 2026-09-21T14:13:20Z, in tokens of input, cache write 5m, cache writ
|
||||
self.assertEqual(concluded.route, Route(Routing.OPUS, 179, 2, 5, escalated_at=3))
|
||||
first, resumed = fake.made("stream_claude")
|
||||
self.assertEqual([args[args.index("--effort") + 1] for args in (first, resumed)], ["high", "medium"])
|
||||
self.assertTrue(resumed[resumed.index("-p") + 1].endswith(f"Continue the task. Your request for a higher rung went through: loop-claude runs you on {Routing.OPUS}. The escalation triggers that fired before this step are spent.{prompts.rungs_held(concluded.route, Routing.OPUS)}"))
|
||||
self.assertTrue(resumed[resumed.index("-p") + 1].endswith(f"Continue the task. Your request for a higher rung went through: loop-claude runs you on {Routing.OPUS}. The escalation triggers that fired before this step are spent.{prompts.rungs_held(concluded.route, LADDER, Routing.OPUS)}"))
|
||||
self.assertNotIn("went through", first[first.index("-p") + 1])
|
||||
answered = f"Verdict: quoted answer\n\nWhich one?\n\n{prompts.QUOTE_SOURCES} says:\n> Use A.\n\nEvidence:\n> working\n\nEscalation:\n> working\n\nConfig: {CONFIG}\nJudge: judge-model\nWorker: {SONNET_179}\n"
|
||||
stepped = f"Stepped up\n\nWorker: {OPUS_179_AT_3}\n"
|
||||
@@ -996,53 +998,53 @@ class Routing(unittest.TestCase):
|
||||
self.assertEqual(routed_item(todo.replace(first, "") + first, NO_CUT).id, 3)
|
||||
|
||||
def test_starts_a_chunk_on_the_rung_its_items_l_picks_below_the_projects_too(self):
|
||||
self.assertEqual(routing.first_route(self.OPUS, routed_item(TODO, NO_CUT)), Route(self.ONE_UP, 3, 4, 5))
|
||||
self.assertEqual(routing.first_route(LADDER, self.OPUS, routed_item(TODO, NO_CUT)), Route(self.ONE_UP, 3, 4, 5))
|
||||
cheap = routed_item(TODO.replace("| 4 | 2 | 3 |", "| 1 | 2 | 3 |"), NO_CUT)
|
||||
self.assertEqual(routing.first_route(self.OPUS, cheap), Route(Rung("claude-sonnet-5-5", "high"), 3, 1, 5))
|
||||
self.assertEqual(routing.first_route(self.OPUS, None), Route(self.OPUS))
|
||||
self.assertEqual(routing.first_route(LADDER, self.OPUS, cheap), Route(Rung("claude-sonnet-5-5", "high"), 3, 1, 5))
|
||||
self.assertEqual(routing.first_route(LADDER, self.OPUS, None), Route(self.OPUS))
|
||||
|
||||
def test_steps_up_a_rung_after_every_second_unfinished_verdict(self):
|
||||
once = routing.next_route(self.OPUS, Route(self.OPUS, 3, 3, 4), unfinished())
|
||||
once = routing.next_route(LADDER, self.OPUS, Route(self.OPUS, 3, 3, 4), unfinished())
|
||||
self.assertEqual(once, Route(self.OPUS, 3, 3, 4, unfinished=1))
|
||||
self.assertEqual(routing.next_route(self.OPUS, once, unfinished()), Route(self.ONE_UP, 3, 3, 4))
|
||||
self.assertEqual(routing.next_route(self.OPUS, Route(LADDER[-1], unfinished=1), unfinished()).rung, LADDER[-1])
|
||||
self.assertEqual(routing.next_route(LADDER, self.OPUS, once, unfinished()), Route(self.ONE_UP, 3, 3, 4))
|
||||
self.assertEqual(routing.next_route(LADDER, self.OPUS, Route(LADDER.rungs[-1], unfinished=1), unfinished()).rung, LADDER.rungs[-1])
|
||||
|
||||
def test_steps_up_to_the_rung_a_taken_in_items_l_picks_and_never_down(self):
|
||||
self.assertEqual(routing.next_route(self.OPUS, Route(self.OPUS), unfinished(4)).rung, self.ONE_UP)
|
||||
self.assertEqual(routing.next_route(self.OPUS, Route(self.TWO_UP), unfinished(4)).rung, self.TWO_UP)
|
||||
self.assertEqual(routing.next_route(self.OPUS, Route(self.OPUS, unfinished=1), unfinished(4)).rung, self.TWO_UP)
|
||||
self.assertEqual(routing.next_route(LADDER, self.OPUS, Route(self.OPUS), unfinished(4)).rung, self.ONE_UP)
|
||||
self.assertEqual(routing.next_route(LADDER, self.OPUS, Route(self.TWO_UP), unfinished(4)).rung, self.TWO_UP)
|
||||
self.assertEqual(routing.next_route(LADDER, self.OPUS, Route(self.OPUS, unfinished=1), unfinished(4)).rung, self.TWO_UP)
|
||||
|
||||
def test_steps_up_from_a_rung_below_the_projects_one_rung_at_a_time(self):
|
||||
low = Route(self.SONNET, 3, 1, 3, unfinished=1)
|
||||
self.assertEqual(routing.next_route(self.OPUS, low, unfinished()).rung, self.OPUS)
|
||||
self.assertEqual(routing.next_route(self.OPUS, Route(low.rung, 3, 1, 3), unfinished()).rung, low.rung)
|
||||
self.assertEqual(routing.next_route(self.OPUS, Route(low.rung, 3, 1, 3), unfinished(3)).rung, self.OPUS)
|
||||
self.assertEqual(routing.next_route(LADDER, self.OPUS, low, unfinished()).rung, self.OPUS)
|
||||
self.assertEqual(routing.next_route(LADDER, self.OPUS, Route(low.rung, 3, 1, 3), unfinished()).rung, low.rung)
|
||||
self.assertEqual(routing.next_route(LADDER, self.OPUS, Route(low.rung, 3, 1, 3), unfinished(3)).rung, self.OPUS)
|
||||
|
||||
def test_steps_up_a_rung_on_an_escalation_the_judge_found_up_to_two_above_the_items_rung_marking_the_transcript_entries_it_read(self):
|
||||
self.assertEqual(routing.next_route(self.OPUS, Route(self.ONE_UP, 3, 4, 5), unfinished(escalated_at=7)), Route(self.TWO_UP, 3, 4, 5, escalated_at=7))
|
||||
self.assertEqual(routing.next_route(self.OPUS, Route(self.TWO_UP, 3, 4, 5, escalated_at=7), unfinished(escalated_at=9)), Route(self.THREE_UP, 3, 4, 5, escalated_at=9))
|
||||
self.assertEqual(routing.next_route(self.OPUS, Route(self.THREE_UP, 3, 4, 5, escalated_at=9), unfinished(escalated_at=12)), Route(self.THREE_UP, 3, 4, 5, unfinished=1, escalated_at=9))
|
||||
self.assertEqual(routing.next_route(self.OPUS, Route(self.ONE_UP, 3, 4, 5, unfinished=1), unfinished(escalated_at=7)), Route(self.TWO_UP, 3, 4, 5, escalated_at=7))
|
||||
self.assertEqual(routing.next_route(self.OPUS, Route(self.TWO_UP), unfinished(escalated_at=7)), Route(self.TWO_UP, unfinished=1))
|
||||
self.assertEqual(routing.next_route(self.OPUS, Route(self.SONNET, 3, 2, 4), unfinished(4, escalated_at=7)), Route(self.ONE_UP, 3, 2, 4, unfinished=1))
|
||||
self.assertEqual(routing.next_route(LADDER, self.OPUS, Route(self.ONE_UP, 3, 4, 5), unfinished(escalated_at=7)), Route(self.TWO_UP, 3, 4, 5, escalated_at=7))
|
||||
self.assertEqual(routing.next_route(LADDER, self.OPUS, Route(self.TWO_UP, 3, 4, 5, escalated_at=7), unfinished(escalated_at=9)), Route(self.THREE_UP, 3, 4, 5, escalated_at=9))
|
||||
self.assertEqual(routing.next_route(LADDER, self.OPUS, Route(self.THREE_UP, 3, 4, 5, escalated_at=9), unfinished(escalated_at=12)), Route(self.THREE_UP, 3, 4, 5, unfinished=1, escalated_at=9))
|
||||
self.assertEqual(routing.next_route(LADDER, self.OPUS, Route(self.ONE_UP, 3, 4, 5, unfinished=1), unfinished(escalated_at=7)), Route(self.TWO_UP, 3, 4, 5, escalated_at=7))
|
||||
self.assertEqual(routing.next_route(LADDER, self.OPUS, Route(self.TWO_UP), unfinished(escalated_at=7)), Route(self.TWO_UP, unfinished=1))
|
||||
self.assertEqual(routing.next_route(LADDER, self.OPUS, Route(self.SONNET, 3, 2, 4), unfinished(4, escalated_at=7)), Route(self.ONE_UP, 3, 2, 4, unfinished=1))
|
||||
|
||||
def test_keeps_the_mark_through_a_step_no_escalation_took(self):
|
||||
self.assertEqual(routing.next_route(self.OPUS, Route(self.OPUS, 3, 3, 4, unfinished=1, escalated_at=5), unfinished()), Route(self.ONE_UP, 3, 3, 4, escalated_at=5))
|
||||
self.assertEqual(routing.next_route(LADDER, self.OPUS, Route(self.OPUS, 3, 3, 4, unfinished=1, escalated_at=5), unfinished()), Route(self.ONE_UP, 3, 3, 4, escalated_at=5))
|
||||
|
||||
def test_steps_up_a_rung_as_the_judge_interrupts_up_to_two_above_the_items_rung_without_counting_an_unfinished_verdict(self):
|
||||
self.assertEqual(routing.next_route(self.OPUS, Route(self.ONE_UP, 3, 4, 5, unfinished=1), interrupted(escalated_at=7)), Route(self.TWO_UP, 3, 4, 5, escalated_at=7))
|
||||
self.assertEqual(routing.next_route(self.OPUS, Route(self.TWO_UP, 3, 4, 5, escalated_at=7), interrupted(escalated_at=9)), Route(self.THREE_UP, 3, 4, 5, escalated_at=9))
|
||||
self.assertEqual(routing.next_route(self.OPUS, Route(self.THREE_UP, 3, 4, 5, unfinished=1, escalated_at=9), interrupted(escalated_at=12)), Route(self.THREE_UP, 3, 4, 5, unfinished=1, escalated_at=9))
|
||||
self.assertEqual(routing.next_route(self.OPUS, Route(self.SONNET, 3, 2, 4), interrupted(escalated_at=7)), Route(self.OPUS, 3, 2, 4, escalated_at=7))
|
||||
self.assertEqual(routing.next_route(self.OPUS, Route(self.ONE_UP, 3, 4, 5, unfinished=1, escalated_at=2), interrupted(4)), Route(self.ONE_UP, 3, 4, 5, unfinished=1, escalated_at=2))
|
||||
self.assertEqual(routing.next_route(LADDER, self.OPUS, Route(self.ONE_UP, 3, 4, 5, unfinished=1), interrupted(escalated_at=7)), Route(self.TWO_UP, 3, 4, 5, escalated_at=7))
|
||||
self.assertEqual(routing.next_route(LADDER, self.OPUS, Route(self.TWO_UP, 3, 4, 5, escalated_at=7), interrupted(escalated_at=9)), Route(self.THREE_UP, 3, 4, 5, escalated_at=9))
|
||||
self.assertEqual(routing.next_route(LADDER, self.OPUS, Route(self.THREE_UP, 3, 4, 5, unfinished=1, escalated_at=9), interrupted(escalated_at=12)), Route(self.THREE_UP, 3, 4, 5, unfinished=1, escalated_at=9))
|
||||
self.assertEqual(routing.next_route(LADDER, self.OPUS, Route(self.SONNET, 3, 2, 4), interrupted(escalated_at=7)), Route(self.OPUS, 3, 2, 4, escalated_at=7))
|
||||
self.assertEqual(routing.next_route(LADDER, self.OPUS, Route(self.ONE_UP, 3, 4, 5, unfinished=1, escalated_at=2), interrupted(4)), Route(self.ONE_UP, 3, 4, 5, unfinished=1, escalated_at=2))
|
||||
|
||||
def test_raises_the_worker_to_a_taken_in_items_rung_above_the_escalation_cap_without_a_step_as_the_judge_interrupts(self):
|
||||
self.assertEqual(routing.next_route(self.OPUS, Route(self.OPUS, 3, 1, 3, escalated_at=2), interrupted(4, escalated_at=7)), Route(self.ONE_UP, 3, 1, 3, escalated_at=2))
|
||||
self.assertEqual(routing.next_route(LADDER, self.OPUS, Route(self.OPUS, 3, 1, 3, escalated_at=2), interrupted(4, escalated_at=7)), Route(self.ONE_UP, 3, 1, 3, escalated_at=2))
|
||||
|
||||
def test_steps_up_from_the_rung_a_taken_in_item_picks_as_the_judge_interrupts(self):
|
||||
self.assertEqual(routing.next_route(self.OPUS, Route(self.OPUS, 3, 3, 4), interrupted(4, escalated_at=7)), Route(self.TWO_UP, 3, 3, 4, escalated_at=7))
|
||||
self.assertEqual(routing.next_route(self.OPUS, Route(self.TWO_UP, 3, 4, 5), interrupted(4, escalated_at=7)), Route(self.THREE_UP, 3, 4, 5, escalated_at=7))
|
||||
self.assertEqual(routing.next_route(self.OPUS, Route(self.THREE_UP, 3, 4, 5, unfinished=1), interrupted(4, escalated_at=7)), Route(self.THREE_UP, 3, 4, 5, unfinished=1))
|
||||
self.assertEqual(routing.next_route(LADDER, self.OPUS, Route(self.OPUS, 3, 3, 4), interrupted(4, escalated_at=7)), Route(self.TWO_UP, 3, 3, 4, escalated_at=7))
|
||||
self.assertEqual(routing.next_route(LADDER, self.OPUS, Route(self.TWO_UP, 3, 4, 5), interrupted(4, escalated_at=7)), Route(self.THREE_UP, 3, 4, 5, escalated_at=7))
|
||||
self.assertEqual(routing.next_route(LADDER, self.OPUS, Route(self.THREE_UP, 3, 4, 5, unfinished=1), interrupted(4, escalated_at=7)), Route(self.THREE_UP, 3, 4, 5, unfinished=1))
|
||||
|
||||
def test_keeps_an_e_plus_i_taken_in_only_where_it_picks_a_higher_review_rung(self):
|
||||
taken = Route(self.OPUS, 3, 3, 4).taking_in(6)
|
||||
@@ -1057,14 +1059,14 @@ class Routing(unittest.TestCase):
|
||||
self.assertEqual(Route(self.OPUS).taking_in(0), Route(self.OPUS))
|
||||
|
||||
def test_a_rung_an_edit_took_off_the_ladder_counts_as_the_projects(self):
|
||||
self.assertEqual(routing.next_route(self.OPUS, Route(Rung("claude-opus-5-5", "low")), unfinished()).rung, self.OPUS)
|
||||
self.assertEqual(routing.next_route(self.OPUS, Route(Rung("claude-opus-5-5", "low")), unfinished(2)).rung, self.OPUS)
|
||||
self.assertEqual(routing.next_route(LADDER, self.OPUS, Route(Rung("claude-opus-5-5", "low")), unfinished()).rung, self.OPUS)
|
||||
self.assertEqual(routing.next_route(LADDER, self.OPUS, Route(Rung("claude-opus-5-5", "low")), unfinished(2)).rung, self.OPUS)
|
||||
|
||||
def test_runs_the_judge_of_a_replayed_model_on_its_models_highest_rung(self):
|
||||
self.assertEqual(routing.judge_rung("claude-opus-5-5"), self.THREE_UP)
|
||||
self.assertEqual(routing.judge_rung(LADDER, "claude-opus-5-5"), self.THREE_UP)
|
||||
# A model off the ladder, or not replayed, gets no effort flag.
|
||||
self.assertEqual(routing.judge_rung("judge-model"), Rung("judge-model"))
|
||||
self.assertEqual(routing.judge_rung("claude-sonnet-5-5"), Rung("claude-sonnet-5-5"))
|
||||
self.assertEqual(routing.judge_rung(LADDER, "judge-model"), Rung("judge-model"))
|
||||
self.assertEqual(routing.judge_rung(LADDER, "claude-sonnet-5-5"), Rung("claude-sonnet-5-5"))
|
||||
|
||||
def test_refuses_a_route_whose_item_has_levels_off_their_scales_or_levels_without_an_item(self):
|
||||
for item, likelihood, escape_and_impact in ((3, 0, 5), (3, 5, 5), (3, 4, 1), (3, 4, 9), (0, 4, 5), (0, 4, 0), (0, 0, 5)):
|
||||
@@ -1109,14 +1111,14 @@ class Routing(unittest.TestCase):
|
||||
archived = Route(self.TWO_UP, 3, 4, 5)
|
||||
def never():
|
||||
raise AssertionError("not asked")
|
||||
self.assertEqual(chunk_start.routed(archived, None, "worker-model", never, never), Route(Rung("worker-model")))
|
||||
self.assertEqual(chunk_start.routed(archived, self.OPUS, "claude-opus-5-5", never, never), archived)
|
||||
self.assertEqual(chunk_start.routed(None, self.OPUS, "claude-opus-5-5", lambda: archived, never), archived)
|
||||
self.assertEqual(chunk_start.routed(None, self.OPUS, "claude-opus-5-5", lambda: None, lambda: item), Route(self.ONE_UP, 3, 4, 5))
|
||||
self.assertEqual(chunk_start.routed(Route(self.SONNET), self.OPUS, "claude-opus-5-5", never, lambda: None), Route(self.OPUS))
|
||||
self.assertEqual(chunk_start.routed(archived, LADDER, None, "worker-model", never, never), Route(Rung("worker-model")))
|
||||
self.assertEqual(chunk_start.routed(archived, LADDER, self.OPUS, "claude-opus-5-5", never, never), archived)
|
||||
self.assertEqual(chunk_start.routed(None, LADDER, self.OPUS, "claude-opus-5-5", lambda: archived, never), archived)
|
||||
self.assertEqual(chunk_start.routed(None, LADDER, self.OPUS, "claude-opus-5-5", lambda: None, lambda: item), Route(self.ONE_UP, 3, 4, 5))
|
||||
self.assertEqual(chunk_start.routed(Route(self.SONNET), LADDER, self.OPUS, "claude-opus-5-5", never, lambda: None), Route(self.OPUS))
|
||||
cheap = Route(self.SONNET, 4, 2, 3)
|
||||
self.assertEqual(chunk_start.routed(cheap, self.OPUS, "claude-opus-5-5", never, never), cheap)
|
||||
self.assertEqual(chunk_start.routed(Route(Rung("claude-haiku-5-5", "max"), 4, 2, 3), self.OPUS, "claude-opus-5-5", never, lambda: None), Route(self.OPUS))
|
||||
self.assertEqual(chunk_start.routed(cheap, LADDER, self.OPUS, "claude-opus-5-5", never, never), cheap)
|
||||
self.assertEqual(chunk_start.routed(Route(Rung("claude-haiku-5-5", "max"), 4, 2, 3), LADDER, self.OPUS, "claude-opus-5-5", never, lambda: None), Route(self.OPUS))
|
||||
|
||||
|
||||
class RouteSources(unittest.TestCase):
|
||||
@@ -1206,29 +1208,86 @@ class RouteSources(unittest.TestCase):
|
||||
self.assertTrue(stderr.getvalue().startswith(f"{STAMP} routing the chunk afresh: could not read the archive"), stderr.getvalue())
|
||||
|
||||
|
||||
class ChunkSlots(unittest.TestCase):
|
||||
def setUp(self):
|
||||
temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(temp.cleanup)
|
||||
self.home = pathlib.Path(temp.name)
|
||||
self.paths = paths.paths_from(self.home)
|
||||
self.addCleanup(self.release)
|
||||
|
||||
def held(self):
|
||||
"""This process's open files on a slot, each with whether an exec keeps it."""
|
||||
folder = self.home / chunk_slot.SLOTS
|
||||
found = {}
|
||||
for fd in os.listdir("/proc/self/fd"):
|
||||
with contextlib.suppress(OSError):
|
||||
if pathlib.Path(os.readlink(f"/proc/self/fd/{fd}")).is_relative_to(folder):
|
||||
found[os.readlink(f"/proc/self/fd/{fd}")] = os.get_inheritable(int(fd))
|
||||
return found
|
||||
|
||||
def release(self):
|
||||
folder = str(self.home / chunk_slot.SLOTS)
|
||||
for fd in os.listdir("/proc/self/fd"):
|
||||
with contextlib.suppress(OSError):
|
||||
if os.readlink(f"/proc/self/fd/{fd}").startswith(folder):
|
||||
os.close(int(fd))
|
||||
|
||||
def test_each_loop_takes_the_lowest_free_slot_and_names_its_session_after_it(self):
|
||||
loop_run = main.LoopRun(cycle_number=0, root=str(self.home / "code" / "proj"), task="do it", unfinished_evidence="")
|
||||
first, second = chunk_slot.slotted(loop_run, self.paths), chunk_slot.slotted(loop_run, self.paths)
|
||||
self.assertEqual((first[0], first[1].name), (dataclasses.replace(loop_run, slot=0), "A proj loop-claude"))
|
||||
self.assertEqual((second[0].slot, second[1].name), (1, "A proj loop-claude 2"))
|
||||
self.assertEqual(second[1], session.session_named("A proj loop-claude 2", self.paths.claude_code_transcripts))
|
||||
folder = self.home / ".local" / "state" / "loop-claude" / "proj"
|
||||
self.assertEqual(self.held(), {str(folder / "slot-0"): True, str(folder / "slot-1"): True})
|
||||
|
||||
def test_a_rerun_takes_the_lowest_free_slot_whose_session_is_open_before_a_lower_closed_one(self):
|
||||
loop_run = main.LoopRun(cycle_number=0, root=str(self.home / "code" / "proj"), task="do it", unfinished_evidence="")
|
||||
for name in ("A proj loop-claude 3", "A proj loop-claude 4"):
|
||||
transcript = self.paths.claude_code_transcripts / "-home-proj" / f"{session.session_named(name, self.paths.claude_code_transcripts).id}.jsonl"
|
||||
transcript.parent.mkdir(parents=True, exist_ok=True)
|
||||
transcript.write_text("")
|
||||
self.assertEqual([chunk_slot.slotted(loop_run, self.paths)[0].slot for _ in range(4)], [2, 3, 0, 1])
|
||||
|
||||
def test_a_reload_keeps_the_slot_it_is_handed_and_takes_no_other(self):
|
||||
loop_run = main.LoopRun(cycle_number=3, root="/srv/proj", task="do it", unfinished_evidence="", slot=2)
|
||||
self.assertEqual(chunk_slot.slotted(loop_run, self.paths), (loop_run, session.session_named("A srv/proj loop-claude 3", self.paths.claude_code_transcripts)))
|
||||
self.assertEqual(self.held(), {})
|
||||
|
||||
def test_says_why_it_takes_no_slot(self):
|
||||
loop_run = main.LoopRun(cycle_number=0, root="/srv/proj", task="do it", unfinished_evidence="")
|
||||
with unittest.mock.patch.object(chunk_slot, "MOST", 1):
|
||||
chunk_slot.slotted(loop_run, self.paths)
|
||||
self.assertEqual(chunk_slot.slotted(loop_run, self.paths), Failure(f"1 loops of this project are running already; `fuser {self.home}/.local/state/loop-claude/srv/proj/slot-*` names them"))
|
||||
(self.home / ".local" / "state" / "loop-claude").mkdir(parents=True, exist_ok=True)
|
||||
(self.home / ".local" / "state" / "loop-claude" / "other").write_text("")
|
||||
self.assertEqual(chunk_slot.slotted(dataclasses.replace(loop_run, root="/other"), self.paths), Failure(f"cannot take a slot in {self.home}/.local/state/loop-claude/other: File exists"))
|
||||
|
||||
|
||||
class Steps(unittest.TestCase):
|
||||
OPUS = Rung("claude-opus-5-5", "medium")
|
||||
|
||||
def test_a_finished_verdict_clears_the_route_and_the_evidence(self):
|
||||
run_with = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="old", route=Route(self.OPUS))
|
||||
self.assertEqual(close.after_verdict(run_with, self.OPUS, run.Concluded(Finished("x"), run_with.route)), dataclasses.replace(run_with, route=None, unfinished_evidence=""))
|
||||
self.assertEqual(close.after_verdict(dataclasses.replace(run_with, unfinished_run=3), self.OPUS, run.Concluded(Finished("x"), run_with.route)).unfinished_run, 0)
|
||||
self.assertEqual(close.after_verdict(run_with, self.OPUS, run.Concluded(Unfinished("new", taken_in=TakenIn(highest_likelihood=4)), run_with.route)), dataclasses.replace(run_with, route=Route(Rung("claude-fable-5-2", "low"), unfinished=1), unfinished_evidence="new", unfinished_run=1))
|
||||
self.assertEqual(close.after_verdict(run_with, LADDER, self.OPUS, run.Concluded(Finished("x"), run_with.route)), dataclasses.replace(run_with, route=None, unfinished_evidence=""))
|
||||
self.assertEqual(close.after_verdict(dataclasses.replace(run_with, unfinished_run=3), LADDER, self.OPUS, run.Concluded(Finished("x"), run_with.route)).unfinished_run, 0)
|
||||
self.assertEqual(close.after_verdict(run_with, LADDER, self.OPUS, run.Concluded(Unfinished("new", taken_in=TakenIn(highest_likelihood=4)), run_with.route)), dataclasses.replace(run_with, route=Route(Rung("claude-fable-5-2", "low"), unfinished=1), unfinished_evidence="new", unfinished_run=1))
|
||||
|
||||
def test_steps_from_the_route_its_cycle_ended_on_which_a_ruling_may_have_raised(self):
|
||||
run_with = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="", route=Route(self.OPUS, 3, 3, 4))
|
||||
raised = Route(Rung("claude-fable-5-2", "low"), 3, 3, 4, escalated_at=5)
|
||||
self.assertEqual(close.after_verdict(run_with, self.OPUS, run.Concluded(Unfinished("new"), raised)).route, dataclasses.replace(raised, unfinished=1))
|
||||
self.assertEqual(close.after_verdict(run_with, LADDER, self.OPUS, run.Concluded(Unfinished("new"), raised)).route, dataclasses.replace(raised, unfinished=1))
|
||||
|
||||
def test_keeps_the_route_its_cycle_ended_on_off_the_ladder(self):
|
||||
off_ladder = Route(Rung("worker-model"))
|
||||
run_with = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="")
|
||||
self.assertEqual(close.after_verdict(run_with, None, run.Concluded(Unfinished("new", "round 2: 🔴", TakenIn(highest_likelihood=4), entries_read=9), off_ladder)).route, off_ladder)
|
||||
self.assertEqual(close.after_verdict(run_with, LADDER, None, run.Concluded(Unfinished("new", "round 2: 🔴", TakenIn(highest_likelihood=4), entries_read=9), off_ladder)).route, off_ladder)
|
||||
|
||||
def test_an_unfinished_verdicts_escalation_marks_the_transcript_entries_the_judge_read(self):
|
||||
run_with = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="", route=Route(self.OPUS, 3, 3, 4, escalated_at=2))
|
||||
self.assertEqual(close.after_verdict(run_with, self.OPUS, run.Concluded(Unfinished("new", "round 2: 🔴", entries_read=9), run_with.route)).route, Route(Rung("claude-fable-5-2", "low"), 3, 3, 4, escalated_at=9))
|
||||
self.assertEqual(close.after_verdict(run_with, self.OPUS, run.Concluded(Unfinished("new", entries_read=9), run_with.route)).route, Route(self.OPUS, 3, 3, 4, unfinished=1, escalated_at=2))
|
||||
self.assertEqual(close.after_verdict(run_with, LADDER, self.OPUS, run.Concluded(Unfinished("new", "round 2: 🔴", entries_read=9), run_with.route)).route, Route(Rung("claude-fable-5-2", "low"), 3, 3, 4, escalated_at=9))
|
||||
self.assertEqual(close.after_verdict(run_with, LADDER, self.OPUS, run.Concluded(Unfinished("new", entries_read=9), run_with.route)).route, Route(self.OPUS, 3, 3, 4, unfinished=1, escalated_at=2))
|
||||
|
||||
def test_archives_a_step_up_as_it_happens_so_a_rerun_resumes_on_it(self):
|
||||
with tempfile.TemporaryDirectory() as home:
|
||||
@@ -1240,14 +1299,14 @@ class Steps(unittest.TestCase):
|
||||
before = Route(self.OPUS, 3, 3, 4)
|
||||
with contextlib.redirect_stderr(io.StringIO()):
|
||||
self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.unfinished(before.worker_line(), "working", "j", ""), NOW))
|
||||
after = close.closed_cycle(main.LoopRun(cycle_number=1, root="/r", task="Do it.", unfinished_evidence=""), self.OPUS, run.Concluded(Unfinished("working", taken_in=TakenIn(highest_likelihood=4)), before), archive, a_loop(FakeEffects().effects(), session=opened))
|
||||
after = close.closed_cycle(main.LoopRun(cycle_number=1, root="/r", task="Do it.", unfinished_evidence=""), LADDER, self.OPUS, run.Concluded(Unfinished("working", taken_in=TakenIn(highest_likelihood=4)), before), archive, a_loop(FakeEffects().effects(), session=opened))
|
||||
self.assertEqual(chunk_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened)), Route(Rung("claude-fable-5-2", "low"), 3, 3, 4))
|
||||
with contextlib.redirect_stderr(io.StringIO()):
|
||||
close.closed_cycle(after, self.OPUS, run.Concluded(Finished("done"), after.route), archive, a_loop(FakeEffects().effects(), session=opened))
|
||||
close.closed_cycle(after, LADDER, self.OPUS, run.Concluded(Finished("done"), after.route), archive, a_loop(FakeEffects().effects(), session=opened))
|
||||
self.assertEqual(chunk_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened)), Route(Rung("claude-fable-5-2", "low"), 3, 3, 4))
|
||||
blocked = pathlib.Path(home, "blocked")
|
||||
blocked.write_text("")
|
||||
stop = close.closed_cycle(main.LoopRun(cycle_number=1, root="/r", task="Do it.", unfinished_evidence=""), self.OPUS, run.Concluded(Unfinished("working", taken_in=TakenIn(highest_likelihood=4)), before), blocked, a_loop(FakeEffects().effects(), session=opened))
|
||||
stop = close.closed_cycle(main.LoopRun(cycle_number=1, root="/r", task="Do it.", unfinished_evidence=""), LADDER, self.OPUS, run.Concluded(Unfinished("working", taken_in=TakenIn(highest_likelihood=4)), before), blocked, a_loop(FakeEffects().effects(), session=opened))
|
||||
self.assertEqual((stop.code, stop.reason.split(":")[0]), (1, "could not archive the transcript"))
|
||||
|
||||
def test_names_no_step_up_where_only_the_count_of_unfinished_verdicts_changed(self):
|
||||
@@ -1265,7 +1324,7 @@ class Steps(unittest.TestCase):
|
||||
before = Route(self.OPUS, 3, 3, 4)
|
||||
with contextlib.redirect_stderr(io.StringIO()):
|
||||
self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.unfinished(before.worker_line(), "working", "j", ""), NOW))
|
||||
close.closed_cycle(main.LoopRun(cycle_number=1, root="/r", task="Do it.", unfinished_evidence=""), self.OPUS, run.Concluded(Unfinished("working", taken_in=TakenIn(highest_escape_and_impact=6)), before), archive, a_loop(FakeEffects().effects(), session=opened))
|
||||
close.closed_cycle(main.LoopRun(cycle_number=1, root="/r", task="Do it.", unfinished_evidence=""), LADDER, self.OPUS, run.Concluded(Unfinished("working", taken_in=TakenIn(highest_escape_and_impact=6)), before), archive, a_loop(FakeEffects().effects(), session=opened))
|
||||
self.assertEqual(chunk_start.archived_route(archive, a_loop(FakeEffects().effects(), session=opened)), Route(self.OPUS, 3, 3, 4, escape_and_impact_taken_in=6))
|
||||
|
||||
|
||||
@@ -1305,13 +1364,13 @@ class TypedAnswers(unittest.TestCase):
|
||||
def test_splits_the_prompt_handing_over_the_answer_into_the_answer_on_the_line_after_its_marker_and_the_rest_and_no_other_prompt(self):
|
||||
route = Route(Rung("worker-model"))
|
||||
marked = "The human answered your question at loop-claude's terminal:\nB"
|
||||
typed = prompts.typed_answer(prompts.typed("Which one?", "Use B.", route, None, False))
|
||||
typed = prompts.typed_answer(prompts.typed("Which one?", "Use B.", route, LADDER, None, False))
|
||||
self.assertEqual(typed.answer, "Use B.")
|
||||
self.assertTrue(typed.loop_words.startswith("Your question was: Which one?\n\nContinue the task."))
|
||||
self.assertEqual(prompts.typed_answer(prompts.typed(f"Which one?\n{marked}", "Use B.", route, None, False)).answer, "Use B.")
|
||||
self.assertEqual(prompts.typed_answer(prompts.typed("Which one?", "Use B.", Route(Routing.SONNET, 179, 2, 5), Routing.OPUS, True)).answer, "Use B.")
|
||||
self.assertIsNone(prompts.typed_answer(prompts.answered("Which one?", marked, route, None, False)))
|
||||
self.assertIsNone(prompts.typed_answer(prompts.resumed(marked, route, None)))
|
||||
self.assertEqual(prompts.typed_answer(prompts.typed(f"Which one?\n{marked}", "Use B.", route, LADDER, None, False)).answer, "Use B.")
|
||||
self.assertEqual(prompts.typed_answer(prompts.typed("Which one?", "Use B.", Route(Routing.SONNET, 179, 2, 5), LADDER, Routing.OPUS, True)).answer, "Use B.")
|
||||
self.assertIsNone(prompts.typed_answer(prompts.answered("Which one?", marked, route, LADDER, None, False)))
|
||||
self.assertIsNone(prompts.typed_answer(prompts.resumed(marked, route, LADDER, None)))
|
||||
|
||||
|
||||
class WorkerArgs(unittest.TestCase):
|
||||
@@ -1322,24 +1381,24 @@ class WorkerArgs(unittest.TestCase):
|
||||
FACTS = "- A preflight fact."
|
||||
|
||||
def test_names_the_route_in_a_fresh_prompt_only_where_an_item_routed_it(self):
|
||||
routed = prompts.fresh("Do it.", "## Goals", Route(Rung("m", "high"), 3, 4, 5), None, self.FACTS)
|
||||
routed = prompts.fresh("Do it.", "## Goals", Route(Rung("m", "high"), 3, 4, 5), LADDER, None, self.FACTS)
|
||||
self.assertIn(f"Continue any open draft PR or worktree for the chunk before creating a new one. {prompts.READING_RULE} {prompts.NAME_THE_ITEMS}\n\nloop-claude runs you on m at high effort, routed by item 3's L of 4.", routed)
|
||||
unrouted = prompts.fresh("Do it.", "## Goals", Route(Rung("m")), None, self.FACTS)
|
||||
unrouted = prompts.fresh("Do it.", "## Goals", Route(Rung("m")), LADDER, None, self.FACTS)
|
||||
self.assertIn(f"before creating a new one. {prompts.READING_RULE} {prompts.NAME_THE_ITEMS}\n\n{self.FACTS}\n\nThe chunk's", unrouted)
|
||||
self.assertNotIn("loop-claude runs you on", unrouted)
|
||||
|
||||
def test_has_the_routed_worker_count_its_items_size_again_and_puts_the_facts_before_the_scope(self):
|
||||
routed = prompts.fresh("Do it.", "## Goals", Route(Rung("m", "high"), 3, 4, 5), None, self.FACTS)
|
||||
routed = prompts.fresh("Do it.", "## Goals", Route(Rung("m", "high"), 3, 4, 5), LADDER, None, self.FACTS)
|
||||
self.assertIn("item 3's size again", routed)
|
||||
self.assertIn("escalation trigger 1", routed)
|
||||
self.assertIn(f"\n\n{self.FACTS}\n\nThe chunk's", routed)
|
||||
self.assertNotIn("size again", prompts.fresh("Do it.", "## Goals", Route(Rung("m")), None, self.FACTS))
|
||||
self.assertNotIn("size again", prompts.fresh("Do it.", "## Goals", Route(Rung("m")), LADDER, None, self.FACTS))
|
||||
|
||||
def test_gives_each_fresh_worker_the_reading_rule_once(self):
|
||||
rule = "never read more than 80 lines of a file at once, nor take a tool output over 3,000 characters into your context"
|
||||
for route in (Route(Rung("m", "high"), 3, 4, 5), Route(Rung("m"))):
|
||||
with self.subTest(route=route):
|
||||
self.assertEqual(prompts.fresh("Do it.", "## Goals", route, None, self.FACTS).count(rule), 1)
|
||||
self.assertEqual(prompts.fresh("Do it.", "## Goals", route, LADDER, None, self.FACTS).count(rule), 1)
|
||||
|
||||
def test_quotes_what_the_preflight_printed_or_has_the_worker_find_the_facts_itself(self):
|
||||
self.assertIn("\n\n- A fact.", prompts.preflight_facts("- A fact."))
|
||||
@@ -1350,93 +1409,95 @@ class WorkerArgs(unittest.TestCase):
|
||||
def test_has_each_fresh_worker_continue_an_open_draft_pr_or_worktree_once_whatever_the_preflight_found(self):
|
||||
for facts in (prompts.preflight_facts("- A fact."), prompts.preflight_failed("git could not start")):
|
||||
with self.subTest(facts=facts):
|
||||
self.assertEqual(prompts.fresh("Do it.", "## Goals", Route(Rung("m")), None, facts).count("Continue any open draft PR or worktree"), 1)
|
||||
self.assertEqual(prompts.fresh("Do it.", "## Goals", Route(Rung("m")), LADDER, None, facts).count("Continue any open draft PR or worktree"), 1)
|
||||
|
||||
def test_keeps_every_review_on_the_projects_rung_while_the_worker_runs_below_it(self):
|
||||
opus = Rung("claude-opus-5-5", "medium")
|
||||
below = prompts.fresh("Do it.", "## Goals", Route(Rung("claude-sonnet-5-5", "high"), 3, 2, 4), opus, self.FACTS)
|
||||
below = prompts.fresh("Do it.", "## Goals", Route(Rung("claude-sonnet-5-5", "high"), 3, 2, 4), LADDER, opus, self.FACTS)
|
||||
self.assertIn(f"item 3's L of 2. Launch each reviewer, each comprehension seat and the security pass's subagent with the Agent tool set to model opus, effort medium, the project's rung.{self.SCAN} Your rung is below the project's: launch each subagent that files or scores todo.md items on the rung `~/.claude/bin/subagent-rung --plan claude-opus-5-5 <L>` prints. Where an item you take into the chunk has an E + I of 5 or more, launch each reviewer with the Agent tool set to `model fable, effort low` from 5, `model fable, effort medium` from 6, `model opus, effort xhigh` from 7 and `model fable, effort high` from 8. When an escalation trigger", below)
|
||||
self.assertNotIn("Launch each", prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 4), opus, self.FACTS))
|
||||
self.assertNotIn("Launch each", prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 4), LADDER, opus, self.FACTS))
|
||||
|
||||
def test_launches_reviewers_on_the_rung_the_items_e_plus_i_picks_above_the_workers(self):
|
||||
opus = Rung("claude-opus-5-5", "medium")
|
||||
level = prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 6), opus, self.FACTS)
|
||||
level = prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 6), LADDER, opus, self.FACTS)
|
||||
self.assertIn(f"item 3's L of 3. Launch each reviewer with the Agent tool set to model fable, effort medium, the rung item 3's E + I of 6 picks. Where an item you take into the chunk has an E + I of 7 or more, launch each reviewer with the Agent tool set to `model opus, effort xhigh` from 7 and `model fable, effort high` from 8.{self.MARKDOWN} When an escalation trigger", level)
|
||||
below = prompts.fresh("Do it.", "## Goals", Route(Rung("claude-sonnet-5-5", "high"), 3, 2, 5), opus, self.FACTS)
|
||||
below = prompts.fresh("Do it.", "## Goals", Route(Rung("claude-sonnet-5-5", "high"), 3, 2, 5), LADDER, opus, self.FACTS)
|
||||
self.assertIn(f"item 3's L of 2. Launch each reviewer with the Agent tool set to model fable, effort low, the rung item 3's E + I of 5 picks.{self.SEATS}{self.SCAN} Your rung is below the project's:", below)
|
||||
self.assertNotIn("Launch each reviewer", prompts.resumed("", Route(Rung("claude-fable-5-2", "medium"), 3, 4, 6), opus))
|
||||
self.assertNotIn("Launch each reviewer", prompts.resumed("", Route(Rung("claude-fable-5-2", "medium"), 3, 4, 6), LADDER, opus))
|
||||
|
||||
def test_names_the_reviewers_rung_each_higher_e_plus_i_an_item_taken_in_picks(self):
|
||||
opus = Rung("claude-opus-5-5", "medium")
|
||||
taking_in = " Where an item you take into the chunk has an E + I of 5 or more, launch each reviewer with the Agent tool set to `model fable, effort low` from 5, `model fable, effort medium` from 6, `model opus, effort xhigh` from 7 and `model fable, effort high` from 8."
|
||||
self.assertIn(f"item 3's L of 3.{taking_in} When an escalation trigger", prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 4), opus, self.FACTS))
|
||||
self.assertIn(" Where an item you take into the chunk has an E + I of 7 or more, launch each reviewer with the Agent tool set to `model opus, effort xhigh` from 7 and `model fable, effort high` from 8.", prompts.resumed("", Route(opus, 3, 3, 6), opus))
|
||||
self.assertIn(" Where an item you take into the chunk has an E + I of 7 or more, launch each reviewer with the Agent tool set to `model opus, effort xhigh` from 7 and `model fable, effort high` from 8.", prompts.resumed("", Route(Rung("claude-fable-5-2", "medium"), 3, 4, 4), opus))
|
||||
self.assertNotIn("Where an item you take into", prompts.resumed("", Route(opus, 3, 3, 8), opus))
|
||||
self.assertNotIn("Where an item you take into", prompts.resumed("", Route(Rung("m")), None))
|
||||
self.assertIn(f"item 3's L of 3.{taking_in} When an escalation trigger", prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 4), LADDER, opus, self.FACTS))
|
||||
self.assertIn(" Where an item you take into the chunk has an E + I of 7 or more, launch each reviewer with the Agent tool set to `model opus, effort xhigh` from 7 and `model fable, effort high` from 8.", prompts.resumed("", Route(opus, 3, 3, 6), LADDER, opus))
|
||||
self.assertIn(" Where an item you take into the chunk has an E + I of 7 or more, launch each reviewer with the Agent tool set to `model opus, effort xhigh` from 7 and `model fable, effort high` from 8.", prompts.resumed("", Route(Rung("claude-fable-5-2", "medium"), 3, 4, 4), LADDER, opus))
|
||||
self.assertNotIn("Where an item you take into", prompts.resumed("", Route(opus, 3, 3, 8), LADDER, opus))
|
||||
self.assertNotIn("Where an item you take into", prompts.resumed("", Route(Rung("m")), LADDER, None))
|
||||
|
||||
def test_launches_reviewers_on_the_rung_the_highest_e_plus_i_taken_in_picks(self):
|
||||
opus = Rung("claude-opus-5-5", "medium")
|
||||
self.assertIn(f"loop-claude runs you on claude-opus-5-5 at medium effort. Launch each reviewer with the Agent tool set to model opus, effort xhigh, the rung picked by an item of E + I 7 taken into the chunk. Where an item you take into the chunk has an E + I of 8 or more, launch each reviewer with the Agent tool set to `model fable, effort high` from 8.{self.MARKDOWN} When an escalation trigger", prompts.resumed("", Route(opus, 3, 3, 5, escape_and_impact_taken_in=7), opus))
|
||||
self.assertIn(" Launch each reviewer with the Agent tool set to model fable, effort low, the rung picked by an item of E + I 5 taken into the chunk.", prompts.resumed("", Route(opus, escape_and_impact_taken_in=5), opus))
|
||||
self.assertIn(f"loop-claude runs you on claude-opus-5-5 at medium effort. Launch each reviewer with the Agent tool set to model opus, effort xhigh, the rung picked by an item of E + I 7 taken into the chunk. Where an item you take into the chunk has an E + I of 8 or more, launch each reviewer with the Agent tool set to `model fable, effort high` from 8.{self.MARKDOWN} When an escalation trigger", prompts.resumed("", Route(opus, 3, 3, 5, escape_and_impact_taken_in=7), LADDER, opus))
|
||||
self.assertIn(" Launch each reviewer with the Agent tool set to model fable, effort low, the rung picked by an item of E + I 5 taken into the chunk.", prompts.resumed("", Route(opus, escape_and_impact_taken_in=5), LADDER, opus))
|
||||
|
||||
def test_keeps_seats_and_the_security_pass_on_the_projects_rung_while_the_worker_runs_above_it(self):
|
||||
opus = Rung("claude-opus-5-5", "medium")
|
||||
above = prompts.fresh("Do it.", "## Goals", Route(Rung("claude-fable-5-2", "low"), 3, 4, 4), opus, self.FACTS)
|
||||
stepped_up = prompts.resumed("", Route(Rung("claude-fable-5-2", "low"), 3, 3, 4), opus)
|
||||
above = prompts.fresh("Do it.", "## Goals", Route(Rung("claude-fable-5-2", "low"), 3, 4, 4), LADDER, opus, self.FACTS)
|
||||
stepped_up = prompts.resumed("", Route(Rung("claude-fable-5-2", "low"), 3, 3, 4), LADDER, opus)
|
||||
self.assertIn(f"{prompts.ANSWERS_RECORDED}. {prompts.NAME_THE_ITEMS} loop-claude runs you on claude-fable-5-2 at low effort.{self.SEATS}{self.SCAN} Where an item you take into the chunk has an E + I of 6 or more, launch each reviewer with the Agent tool set to `model fable, effort medium` from 6, `model opus, effort xhigh` from 7 and `model fable, effort high` from 8.{self.MARKDOWN} When an escalation trigger", stepped_up)
|
||||
self.assertNotIn("the project's", prompts.resumed("", Route(opus, 3, 3, 4), opus))
|
||||
self.assertNotIn("runs you on", prompts.resumed("", Route(Rung("m")), None))
|
||||
self.assertNotIn("the project's", prompts.resumed("", Route(opus, 3, 3, 4), LADDER, opus))
|
||||
self.assertNotIn("runs you on", prompts.resumed("", Route(Rung("m")), LADDER, None))
|
||||
self.assertIn(f"item 3's L of 4.{self.SEATS}{self.SCAN} Where an item you take into the chunk has an E + I of 6 or more, launch each reviewer with the Agent tool set to `model fable, effort medium` from 6, `model opus, effort xhigh` from 7 and `model fable, effort high` from 8.{self.MARKDOWN} When an escalation trigger", above)
|
||||
|
||||
def test_names_the_rungs_an_escalation_trigger_lets_the_worker_hand_a_task_to_at_most_two_above_its_items(self):
|
||||
opus = Rung("claude-opus-5-5", "medium")
|
||||
fresh = prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 4), opus, self.FACTS)
|
||||
fresh = prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 4), LADDER, opus, self.FACTS)
|
||||
self.assertIn("item 3's L of 3. Where an item you take into the chunk has an E + I of 5 or more, launch each reviewer with the Agent tool set to `model fable, effort low` from 5, `model fable, effort medium` from 6, `model opus, effort xhigh` from 7 and `model fable, effort high` from 8. When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `model fable, effort low`, one rung above yours, and on each further trigger one rung higher, up to `model fable, effort medium`; above that, ask the human first. Open the subagent's prompt with `Escalation trigger <n>:`, n the trigger's number.", fresh)
|
||||
self.assertIn(" When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `model fable, effort medium`, one rung above yours; above that, ask the human first. Open the subagent's prompt with `Escalation trigger <n>:`, n the trigger's number.", prompts.resumed("", Route(Rung("claude-fable-5-2", "low"), 3, 3, 4), opus))
|
||||
self.assertIn(" An escalation trigger in `~/.claude/CLAUDE.md` lets you hand the hard part of a task to a subagent with the Agent tool set to `model opus, effort xhigh`, one rung above yours, only once the human agrees; loop-claude will not resume you higher for a trigger either, so ask the human for that yes. Open the subagent's prompt with `Escalation trigger <n>:`, n the trigger's number.", prompts.resumed("", Route(Rung("claude-fable-5-2", "medium"), 3, 3, 4), opus))
|
||||
self.assertNotIn("escalation", prompts.resumed("", Route(Rung("claude-fable-5-2", "max"), 3, 4, 8), opus))
|
||||
self.assertIn("only once the human agrees", prompts.resumed("", Route(Rung("claude-opus-5-5", "xhigh"), 3, 4, 5), opus))
|
||||
self.assertIn("hand the hard part of the task to a subagent with the Agent tool set to `model opus, effort xhigh`, one rung above yours;", prompts.resumed("", Route(Rung("claude-fable-5-2", "medium"), 3, 4, 5), opus))
|
||||
self.assertNotIn("escalation", prompts.resumed("", Route(Rung("m")), None))
|
||||
self.assertNotIn("escalation", prompts.resumed("", Route(Rung("claude-opus-5-5", "low"), 3, 3, 4), opus))
|
||||
self.assertIn(f"{prompts.READING_RULE} {prompts.NAME_THE_ITEMS}\n\nWhere an item you take into the chunk has an E + I of 5 or more, launch each reviewer with the Agent tool set to `model fable, effort low` from 5, `model fable, effort medium` from 6, `model opus, effort xhigh` from 7 and `model fable, effort high` from 8. When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `model fable, effort low`, one rung above yours, and on each further trigger one rung higher, up to `model fable, effort medium`; above that, ask the human first. Open the subagent's prompt with `Escalation trigger <n>:`, n the trigger's number. Where the hard part is the rest of the chunk, end your run instead, asking loop-claude for a higher rung and naming a trigger that fired since your last step-up, if any: once the judge finds it in your transcript, the next cycle resumes you one rung up, up to `model fable, effort medium`. A reviewer", prompts.fresh("Do it.", "## Goals", Route(opus), opus, self.FACTS))
|
||||
self.assertIn(" When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `model fable, effort medium`, one rung above yours; above that, ask the human first. Open the subagent's prompt with `Escalation trigger <n>:`, n the trigger's number.", prompts.resumed("", Route(Rung("claude-fable-5-2", "low"), 3, 3, 4), LADDER, opus))
|
||||
self.assertIn(" An escalation trigger in `~/.claude/CLAUDE.md` lets you hand the hard part of a task to a subagent with the Agent tool set to `model opus, effort xhigh`, one rung above yours, only once the human agrees; loop-claude will not resume you higher for a trigger either, so ask the human for that yes. Open the subagent's prompt with `Escalation trigger <n>:`, n the trigger's number.", prompts.resumed("", Route(Rung("claude-fable-5-2", "medium"), 3, 3, 4), LADDER, opus))
|
||||
self.assertNotIn("escalation", prompts.resumed("", Route(Rung("claude-fable-5-2", "max"), 3, 4, 8), LADDER, opus))
|
||||
self.assertIn("only once the human agrees", prompts.resumed("", Route(Rung("claude-opus-5-5", "xhigh"), 3, 4, 5), LADDER, opus))
|
||||
self.assertIn("only once the human agrees", prompts.resumed("", Route(Rung("claude-fable-5-2", "high"), 3, 4, 5), LADDER, opus), "one rung below the top still names the rung above")
|
||||
self.assertNotIn("rerun", prompts.resumed("", Route(Rung("claude-opus-5-5", "low"), 3, 3, 4), LADDER, opus), "a worker off the ladder is told no rerun rung")
|
||||
self.assertIn("hand the hard part of the task to a subagent with the Agent tool set to `model opus, effort xhigh`, one rung above yours;", prompts.resumed("", Route(Rung("claude-fable-5-2", "medium"), 3, 4, 5), LADDER, opus))
|
||||
self.assertNotIn("escalation", prompts.resumed("", Route(Rung("m")), LADDER, None))
|
||||
self.assertNotIn("escalation", prompts.resumed("", Route(Rung("claude-opus-5-5", "low"), 3, 3, 4), LADDER, opus))
|
||||
self.assertIn(f"{prompts.READING_RULE} {prompts.NAME_THE_ITEMS}\n\nWhere an item you take into the chunk has an E + I of 5 or more, launch each reviewer with the Agent tool set to `model fable, effort low` from 5, `model fable, effort medium` from 6, `model opus, effort xhigh` from 7 and `model fable, effort high` from 8. When an escalation trigger in `~/.claude/CLAUDE.md` fires, hand the hard part of the task to a subagent with the Agent tool set to `model fable, effort low`, one rung above yours, and on each further trigger one rung higher, up to `model fable, effort medium`; above that, ask the human first. Open the subagent's prompt with `Escalation trigger <n>:`, n the trigger's number. Where the hard part is the rest of the chunk, end your run instead, asking loop-claude for a higher rung and naming a trigger that fired since your last step-up, if any: once the judge finds it in your transcript, the next cycle resumes you one rung up, up to `model fable, effort medium`. A reviewer", prompts.fresh("Do it.", "## Goals", Route(opus), LADDER, opus, self.FACTS))
|
||||
|
||||
def test_offers_the_worker_a_higher_rung_for_the_rest_of_the_chunk_up_to_the_escalation_cap(self):
|
||||
opus = Rung("claude-opus-5-5", "medium")
|
||||
offer = " Where the hard part is the rest of the chunk, end your run instead, asking loop-claude for a higher rung and naming a trigger that fired since your last step-up, if any: once the judge finds it in your transcript, the next cycle resumes you one rung up, up to `model fable, effort medium`."
|
||||
self.assertIn(f"`Escalation trigger <n>:`, n the trigger's number.{offer}", prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 4), opus, self.FACTS))
|
||||
self.assertIn(f"`Escalation trigger <n>:`, n the trigger's number.{offer}", prompts.resumed("", Route(Rung("claude-fable-5-2", "low"), 3, 3, 4), opus))
|
||||
self.assertNotIn("Where the hard part", prompts.resumed("", Route(Rung("claude-fable-5-2", "medium"), 3, 3, 4), opus))
|
||||
self.assertIn(f"`Escalation trigger <n>:`, n the trigger's number.{offer}", prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 4), LADDER, opus, self.FACTS))
|
||||
self.assertIn(f"`Escalation trigger <n>:`, n the trigger's number.{offer}", prompts.resumed("", Route(Rung("claude-fable-5-2", "low"), 3, 3, 4), LADDER, opus))
|
||||
self.assertNotIn("Where the hard part", prompts.resumed("", Route(Rung("claude-fable-5-2", "medium"), 3, 3, 4), LADDER, opus))
|
||||
|
||||
def test_lets_a_markdown_only_branch_review_on_the_projects_rung_where_the_reviewers_run_above_it(self):
|
||||
opus = Rung("claude-opus-5-5", "medium")
|
||||
markdown = " Where your branch changes only Markdown, none of it `CLAUDE.md`, `AGENTS.md`, `workflow-bench/*-prompt.md` or under `agents/`, `principles/`, `rules/` or `skills/`, launch each reviewer on the project's rung instead, with the Agent tool set to model opus, effort medium."
|
||||
self.assertIn(markdown, prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 7), opus, self.FACTS))
|
||||
self.assertIn(markdown, prompts.resumed("", Route(Rung("claude-fable-5-2", "low"), 3, 4, 4), opus))
|
||||
self.assertNotIn("only Markdown", prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 4), opus, self.FACTS))
|
||||
self.assertIn(markdown, prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 7), LADDER, opus, self.FACTS))
|
||||
self.assertIn(markdown, prompts.resumed("", Route(Rung("claude-fable-5-2", "low"), 3, 4, 4), LADDER, opus))
|
||||
self.assertNotIn("only Markdown", prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 4), LADDER, opus, self.FACTS))
|
||||
|
||||
def test_names_the_rung_a_reviewer_or_seat_reruns_on_one_above_its_own(self):
|
||||
opus = Rung("claude-opus-5-5", "medium")
|
||||
both = " A reviewer or comprehension seat that asks for a rerun one rung up reruns with the Agent tool set to `model fable, effort low`."
|
||||
self.assertTrue(prompts.resumed("", Route(opus, 3, 3, 4), opus).endswith(both))
|
||||
self.assertTrue(prompts.resumed("", Route(Rung("claude-sonnet-5-5", "high"), 3, 2, 4), opus).endswith(both))
|
||||
self.assertTrue(prompts.fresh("Do it.", "## Goals", Route(opus), opus, self.FACTS).split(f"\n\n{self.FACTS}")[0].endswith(both))
|
||||
self.assertTrue(prompts.resumed("", Route(Rung("claude-fable-5-2", "low"), 3, 4, 4), opus).endswith(" A reviewer that asks for a rerun one rung up reruns with the Agent tool set to `model fable, effort medium`, and a comprehension seat with `model fable, effort low`."))
|
||||
self.assertTrue(prompts.resumed("", Route(opus, 3, 3, 7), opus).endswith(" A reviewer that asks for a rerun one rung up reruns with the Agent tool set to `model fable, effort high`, and a comprehension seat with `model fable, effort low`."))
|
||||
self.assertTrue(prompts.resumed("", Route(Rung("claude-fable-5-2", "max"), 3, 4, 8), opus).endswith(" A comprehension seat that asks for a rerun one rung up reruns with the Agent tool set to `model fable, effort low`."))
|
||||
self.assertNotIn("rerun", prompts.resumed("", Route(Rung("m")), None))
|
||||
self.assertNotIn("rerun", prompts.fresh("Do it.", "## Goals", Route(Rung("m", "high"), 3, 4, 5), None, self.FACTS))
|
||||
self.assertIn(f"{both} After your first read", prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 4), opus, self.FACTS))
|
||||
self.assertTrue(prompts.resumed("", Route(opus, 3, 3, 4), LADDER, opus).endswith(both))
|
||||
self.assertTrue(prompts.resumed("", Route(Rung("claude-sonnet-5-5", "high"), 3, 2, 4), LADDER, opus).endswith(both))
|
||||
self.assertTrue(prompts.fresh("Do it.", "## Goals", Route(opus), LADDER, opus, self.FACTS).split(f"\n\n{self.FACTS}")[0].endswith(both))
|
||||
self.assertTrue(prompts.resumed("", Route(Rung("claude-fable-5-2", "low"), 3, 4, 4), LADDER, opus).endswith(" A reviewer that asks for a rerun one rung up reruns with the Agent tool set to `model fable, effort medium`, and a comprehension seat with `model fable, effort low`."))
|
||||
self.assertTrue(prompts.resumed("", Route(opus, 3, 3, 7), LADDER, opus).endswith(" A reviewer that asks for a rerun one rung up reruns with the Agent tool set to `model fable, effort high`, and a comprehension seat with `model fable, effort low`."))
|
||||
self.assertTrue(prompts.resumed("", Route(Rung("claude-fable-5-2", "max"), 3, 4, 8), LADDER, opus).endswith(" A comprehension seat that asks for a rerun one rung up reruns with the Agent tool set to `model fable, effort low`."))
|
||||
self.assertNotIn("rerun", prompts.resumed("", Route(Rung("m")), LADDER, None))
|
||||
self.assertNotIn("rerun", prompts.fresh("Do it.", "## Goals", Route(Rung("m", "high"), 3, 4, 5), LADDER, None, self.FACTS))
|
||||
self.assertIn(f"{both} After your first read", prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 4), LADDER, opus, self.FACTS))
|
||||
fable = Rung("claude-fable-5-2", "max")
|
||||
self.assertNotIn("rerun", prompts.resumed("", Route(fable), fable))
|
||||
self.assertNotIn("rerun", prompts.resumed("", Route(fable), LADDER, fable))
|
||||
|
||||
def test_opens_a_fresh_session_by_name_and_resumes_an_open_one(self):
|
||||
opened = session.session_named("A proj loop-claude", pathlib.Path("/h/.claude/projects"))
|
||||
fresh = worker.worker_args(opened, Rung("m"), prompts.fresh("Do it.", "## Goals\n1. g\n\n## Audience\nme", Route(Rung("m")), None, self.FACTS), resume=False)
|
||||
fresh = worker.worker_args(opened, Rung("m"), prompts.fresh("Do it.", "## Goals\n1. g\n\n## Audience\nme", Route(Rung("m")), LADDER, None, self.FACTS), resume=False)
|
||||
self.assertEqual(fresh[fresh.index("--session-id") + 1], str(opened.id))
|
||||
self.assertEqual(fresh[fresh.index("--name") + 1], "A proj loop-claude")
|
||||
resumed = worker.worker_args(opened, Rung("m"), prompts.resumed("", Route(Rung("m")), None), resume=True)
|
||||
resumed = worker.worker_args(opened, Rung("m"), prompts.resumed("", Route(Rung("m")), LADDER, None), resume=True)
|
||||
self.assertEqual(resumed[resumed.index("--resume") + 1], str(opened.id))
|
||||
self.assertNotIn("--session-id", resumed)
|
||||
self.assertTrue(resumed[resumed.index("-p") + 1].startswith("Continue the task; the previous run ended before the chunk was finished. The chunk is finished once"))
|
||||
@@ -1469,6 +1530,14 @@ class Records(unittest.TestCase):
|
||||
pathlib.Path(claude_md.parent, "skills", "larv-review", "standards").mkdir(parents=True)
|
||||
pathlib.Path(claude_md.parent, "skills", "larv-review", "standards", "comments.md").write_text("# Comments\n")
|
||||
self.assertTrue(records.read_records(root, claude_md.parents[1], claude_md.parent).endswith("From ~/.claude/CLAUDE.md:\n# Global\n\nFrom ~/.claude/rules/goals-and-audience.md:\n# Goals\n\nFrom ~/.claude/rules/todo-items.md:\n# Todo\n\nFrom ~/.claude/skills/larv-review/standards/comments.md:\n# Comments"))
|
||||
config.write_text(config.read_text().replace('"~/.claude/skills/larv-review/standards"', '"~/review-standards"'))
|
||||
pathlib.Path(claude_md.parents[1], "review-standards").mkdir()
|
||||
pathlib.Path(claude_md.parents[1], "review-standards", "quality.md").write_text("# Ours\n")
|
||||
self.assertTrue(records.read_records(root, claude_md.parents[1], claude_md.parent).endswith("From ~/.claude/rules/todo-items.md:\n# Todo\n\nFrom ~/review-standards/quality.md:\n# Ours"), "the config's standards folder replaces the default")
|
||||
config.write_text(config.read_text().replace('"~/review-standards"', f'"{root}/standards"'))
|
||||
pathlib.Path(root, "standards").mkdir()
|
||||
pathlib.Path(root, "standards", "quality.md").write_text("# Elsewhere\n")
|
||||
self.assertTrue(records.read_records(root, claude_md.parents[1], claude_md.parent).endswith(f"From {root}/standards/quality.md:\n# Elsewhere"), "a folder outside home is named in full")
|
||||
|
||||
config.write_text(config.read_text().replace('"checkout:AGENTS.md"', '"folder:AGENTS.md"').replace('"checkout:docs/decisions.md"', '"folder:log/decisions.md"'))
|
||||
self.assertTrue(records.read_records(root, claude_md.parents[1], claude_md.parent).startswith("From ~/.claude/CLAUDE.md:\n# Global"), "the checkout's AGENTS.md and docs/decisions.md are its owners'")
|
||||
@@ -1535,7 +1604,7 @@ class JudgePrompt(unittest.TestCase):
|
||||
self.assertEqual(judge.quotes_checked(Unfinished("e", "new", entries_read=3), grounds), Unfinished("e", "new", entries_read=3))
|
||||
|
||||
def test_shows_a_typed_answer_before_the_step_up_as_the_humans(self):
|
||||
typed = prompts.typed("Which one?", "Use B.", Route(Rung("worker-model")), None, False)
|
||||
typed = prompts.typed("Which one?", "Use B.", Route(Rung("worker-model")), LADDER, None, False)
|
||||
entries = [{**human(typed), "promptSource": "sdk"}, assistant({"type": "text", "text": "round 3: 🔴"})]
|
||||
_, grounds = judge.judge_prompt(judge.Brief("Do it.", "## Goals", "", kinds(*entries), 1))
|
||||
self.assertIn("\n\n[human] Use B.\n\n[step] ", grounds.shown)
|
||||
@@ -1675,7 +1744,7 @@ class ChunkItems(unittest.TestCase):
|
||||
self.assertEqual(chunk_items.named([said(example)]), (297, 298))
|
||||
|
||||
def test_every_prompt_that_starts_or_resumes_a_chunk_asks_for_the_line(self):
|
||||
self.assertIn("on one line, as in `Chunk items: ", prompts.resumed("", Route(Rung("m")), None))
|
||||
self.assertIn("on one line, as in `Chunk items: ", prompts.resumed("", Route(Rung("m")), LADDER, None))
|
||||
|
||||
def test_reads_only_a_line_the_worker_opens_with_the_label_in_its_own_text(self):
|
||||
prompt = entries.LoopPrompt(text="Chunk items: 297 (L 3, E + I 5)")
|
||||
@@ -1921,11 +1990,18 @@ class HelpLimits(unittest.TestCase):
|
||||
self.assertIn(f"rerun to give it {close.UNFINISHED_LIMIT} more", said)
|
||||
|
||||
|
||||
class OwnLadder(unittest.TestCase):
|
||||
def test_a_cycle_on_a_projects_own_ladder_names_its_file_and_says_where_the_workers_model_is_off_it(self):
|
||||
file = pathlib.Path("/h/.claude-projects/acme/routing-ladder.json")
|
||||
self.assertEqual(main.own_ladder(file, "claude-fable-5-2", False), f"routing on the project's own ladder, {file}.")
|
||||
self.assertEqual(main.own_ladder(file, "claude-opus-5-5", True), f"routing on the project's own ladder, {file}. claude-opus-5-5 is not on it, so the worker runs on claude-opus-5-5 unrouted; LOOP_CLAUDE_WORKER_MODEL and LOOP_CLAUDE_JUDGE_MODEL name other models for a run.")
|
||||
|
||||
|
||||
class ExitContract(unittest.TestCase):
|
||||
def test_every_exit_1_stop_has_its_clause_in_help(self):
|
||||
read, git, premises_ = "a transcript cannot be read or archived", "git cannot start or finds no checkout", "no config names the checkout, its config cannot be read, or the goals file holds no premises"
|
||||
models_ = "the models file cannot be read or written"
|
||||
names = (*records.RECORD_FILES, records.HUMAN_RULE_NAMES[0], *(f"{folder}*.md" for folder in records.HUMAN_RULE_NAMES[1:]))
|
||||
names = (*records.RECORD_FILES, records.HUMAN_RULE_NAMES[0], f"{records.HUMAN_RULE_NAMES[1]}*.md", records.HUMAN_RULE_NAMES[2])
|
||||
unreadable = f"the goals file, or {', '.join(names[:-1])} or {names[-1]} where they exist, cannot be read or is not UTF-8"
|
||||
# Every Stop whose code is not a literal 0, 2 or 130, in source order: path, function, code, start of reason, its --help clause.
|
||||
clauses = [
|
||||
@@ -1943,8 +2019,11 @@ class ExitContract(unittest.TestCase):
|
||||
("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),
|
||||
("loop/main.py", "run_loop", "1", "held.reason", "its slot in the project cannot be taken"),
|
||||
("loop/main.py", "next_cycle", "1", "premises.reason", premises_),
|
||||
("loop/main.py", "next_cycle", "1", "records.reason", unreadable),
|
||||
("loop/main.py", "next_cycle", "1", "ladder_file.reason", premises_),
|
||||
("loop/main.py", "next_cycle", "1", "ladder.reason", "the project's routing ladder cannot be read or holds a fault"),
|
||||
("loop/main.py", "loop_run_from", "0 if task else 1", "HELP", "no task is given"),
|
||||
("loop/main.py", "loop_run_from", "1", 'f"the edited loop-claude cannot read the state', "a reload cannot read the state the running script handed it"),
|
||||
("loop/reload.py", "exec_if_edited", "1", "f'could not reload loop-claude:", "python cannot start for a reload"),
|
||||
|
||||
@@ -27,8 +27,13 @@ def slot_folder(env: typing.Mapping[str, str], home: pathlib.Path) -> pathlib.Pa
|
||||
|
||||
|
||||
def taken_slot(folder: pathlib.Path, slots: int) -> tuple[int, int] | None:
|
||||
"""The number and open file of a slot this call locked; None while every slot is held. Raises OSError where a slot file cannot be opened or locked."""
|
||||
for slot in range(slots):
|
||||
"""The number and open file of the lowest slot this call locked; None while every slot is held. Raises OSError where a slot file cannot be opened or locked."""
|
||||
return first_free_slot(folder, range(slots))
|
||||
|
||||
|
||||
def first_free_slot(folder: pathlib.Path, order: typing.Iterable[int]) -> tuple[int, int] | None:
|
||||
"""The number and open file of the first slot in order that this call locked; None while every slot in order is held. Raises OSError where a slot file cannot be opened or locked."""
|
||||
for slot in order:
|
||||
fd = os.open(folder / f"slot-{slot}", os.O_RDWR | os.O_CREAT, 0o644)
|
||||
try:
|
||||
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
|
||||
@@ -54,7 +54,7 @@ def id_of(answer: object, request: str) -> str | Failure:
|
||||
|
||||
|
||||
def http_json(method: str, url: str, token: str, body: object) -> object:
|
||||
"""The JSON that url answers to the bot's request, or a Failure saying why there is none."""
|
||||
"""The JSON that url answers to the bot's request, None where the answer has no body, or a Failure saying why there is none."""
|
||||
return json_request.http_json(method, url, f"Bearer {token}", body, TIMEOUT, error_message)
|
||||
|
||||
|
||||
|
||||
+48
-62
@@ -1,4 +1,4 @@
|
||||
"""The routing ladder, and the rungs a task's L and E + I pick from the project's rung: docs/decisions.md → `routing:`."""
|
||||
"""A routing ladder, and the rungs a task's L and E + I pick on it from the project's rung: docs/decisions.md → `routing:`."""
|
||||
import dataclasses
|
||||
import re
|
||||
import typing
|
||||
@@ -7,6 +7,8 @@ from review_rules.review_passes import ReviewedPass
|
||||
|
||||
# How Rung.__str__ spells a rung that names an effort, and Rung.parse reads it back.
|
||||
WORDING = re.compile(r"(?P<model>\S+) at (?P<effort>\S+) effort")
|
||||
# Lowest first, as Claude Code's --effort takes them.
|
||||
EFFORTS = ("low", "medium", "high", "xhigh", "max")
|
||||
# What a review launch reviews: such a pass, a comprehension seat or the security pass.
|
||||
ReviewKind = ReviewedPass | typing.Literal["seat", "security"]
|
||||
|
||||
@@ -28,14 +30,6 @@ class Rung:
|
||||
"""The rung in the Agent tool's words. The tool takes a family name, such as opus, and runs that family's latest model, which is the model each rung names."""
|
||||
return f"model {self.family()}, effort {self.effort}"
|
||||
|
||||
@staticmethod
|
||||
def from_agent(model: str, effort: str) -> "Rung":
|
||||
"""The rung the Agent tool's model and effort name: a family such as opus is its ladder model, at the effort given or else its cheapest. A family off the ladder, or an effort off it, gives a rung that is not on LADDER."""
|
||||
family = next((rung for rung in LADDER if rung.family() == model), None)
|
||||
if family is None:
|
||||
return Rung(model, effort)
|
||||
return Rung(family.model, effort) if effort else family
|
||||
|
||||
# loop-claude hands a rung to rule-hook in environment variables in this spelling, so parse must keep reading it.
|
||||
def __str__(self) -> str:
|
||||
return f"{self.model} at {self.effort} effort" if self.effort else self.model
|
||||
@@ -47,76 +41,68 @@ class Rung:
|
||||
return Rung(found["model"], found["effort"]) if found else None
|
||||
|
||||
|
||||
# Least competent first.
|
||||
LADDER = (
|
||||
Rung("claude-sonnet-5-5", "high"),
|
||||
Rung("claude-opus-5-5", "medium"),
|
||||
Rung("claude-fable-5-2", "low"),
|
||||
Rung("claude-fable-5-2", "medium"),
|
||||
Rung("claude-opus-5-5", "xhigh"),
|
||||
Rung("claude-fable-5-2", "high"),
|
||||
Rung("claude-fable-5-2", "max"),
|
||||
)
|
||||
# The rungs a task's L steps its worker from the project's rung.
|
||||
WORKER_STEPS = {1: -1, 2: -1, 3: 0, 4: 1}
|
||||
# The rungs a task's E + I steps a review up from the project's rung; an E + I under 5 steps none.
|
||||
REVIEW_STEPS = {5: 1, 6: 2, 7: 3, 8: 4}
|
||||
|
||||
|
||||
def project_rung(model: str) -> Rung | None:
|
||||
"""The model's cheapest rung, which for Opus 5.5 is its default effort; None for a model off the ladder."""
|
||||
return next((rung for rung in LADDER if rung.model == model), None)
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Ladder:
|
||||
"""A project's rungs, least competent first. model_routing/ladder_file.py reads one, and refuses a file that holds no rung, one rung twice, since a rung's position sets every step, or two models of one family, since from_agent reads a family as one model."""
|
||||
rungs: tuple[Rung, ...]
|
||||
|
||||
def from_agent(self, model: str, effort: str) -> Rung:
|
||||
"""The rung the Agent tool's model and effort name: a family such as opus is its ladder model, at the effort given or else its cheapest. A family off the ladder, or an effort off it, gives a rung that is not on the ladder."""
|
||||
family = next((rung for rung in self.rungs if rung.family() == model), None)
|
||||
if family is None:
|
||||
return Rung(model, effort)
|
||||
return Rung(family.model, effort) if effort else family
|
||||
|
||||
def worker_rung(project: Rung, likelihood: int) -> Rung:
|
||||
"""The rung a task's L picks for its worker, counted from the project's rung, stopping at either end of the ladder."""
|
||||
return climbed(project, WORKER_STEPS[likelihood])
|
||||
def project_rung(self, model: str) -> Rung | None:
|
||||
"""The model's cheapest rung, which for Opus 5.5 is its default effort; None for a model off the ladder."""
|
||||
return next((rung for rung in self.rungs if rung.model == model), None)
|
||||
|
||||
def worker_rung(self, project: Rung, likelihood: int) -> Rung:
|
||||
"""The rung a task's L picks for its worker, counted from the project's rung, stopping at either end of the ladder."""
|
||||
return self.climbed(project, WORKER_STEPS[likelihood])
|
||||
|
||||
def lowest_worker_rung(project: Rung) -> Rung:
|
||||
"""The lowest rung any L routes a worker to, counted from the project's rung."""
|
||||
return climbed(project, min(WORKER_STEPS.values()))
|
||||
def lowest_worker_rung(self, project: Rung) -> Rung:
|
||||
"""The lowest rung any L routes a worker to, counted from the project's rung."""
|
||||
return self.climbed(project, min(WORKER_STEPS.values()))
|
||||
|
||||
def planning_rung(self, project: Rung, likelihood: int) -> Rung:
|
||||
"""The rung of a task that files or scores todo.md items: the one its L picks, never below the project's rung."""
|
||||
return self.highest(project, self.worker_rung(project, likelihood))
|
||||
|
||||
def planning_rung(project: Rung, likelihood: int) -> Rung:
|
||||
"""The rung of a task that files or scores todo.md items: the one its L picks, never below the project's rung."""
|
||||
return highest(project, worker_rung(project, likelihood))
|
||||
def review_floor(self, project: Rung, escape_and_impact: int) -> Rung:
|
||||
"""The rung a task's E + I picks for a review, counted up from the project's rung. An E + I of 0, for no task, picks the project's rung."""
|
||||
return self.climbed(project, REVIEW_STEPS.get(escape_and_impact, 0))
|
||||
|
||||
def stepped_up(self, rung: Rung) -> Rung:
|
||||
"""The rung above, or the top one; a rung off the ladder steps to the bottom one."""
|
||||
return self.climbed(rung, 1)
|
||||
|
||||
def review_floor(project: Rung, escape_and_impact: int) -> Rung:
|
||||
"""The rung a task's E + I picks for a review, counted up from the project's rung. An E + I of 0, for no task, picks the project's rung."""
|
||||
return climbed(project, REVIEW_STEPS.get(escape_and_impact, 0))
|
||||
def review_rung(self, project: Rung, worker: Rung, escape_and_impact: int, kind: ReviewKind, markdown_only: bool = False) -> Rung:
|
||||
"""The rung a review of this kind runs on in a chunk whose worker runs on worker and whose item has that E + I; markdown_only where the branch changes only Markdown no agent follows.
|
||||
|
||||
A pass's reviewer runs on reviewers_rung; no replay has qualified a lower rung for any pass, docs/decisions.md → `routing: a review pass runs below the project's rung only on a rung whose replay of its rounds finds a share of their 🔴 and 🟡 findings no more than a margin below the project's rung's own replay`. A seat and the security pass run on the project's rung, so the seats score every chunk on one rung, and the security pass spends no more than the project chose.
|
||||
"""
|
||||
return project if kind in ("seat", "security") else self.reviewers_rung(project, worker, escape_and_impact, markdown_only)
|
||||
|
||||
def stepped_up(rung: Rung) -> Rung:
|
||||
"""The rung above, or the top one; a rung off the ladder steps to the bottom one."""
|
||||
return climbed(rung, 1)
|
||||
def reviewers_rung(self, project: Rung, worker: Rung, escape_and_impact: int, markdown_only: bool = False) -> Rung:
|
||||
"""The rung of each pass's reviewer: the higher of the worker's rung and review_floor's, which is never below the project's.
|
||||
|
||||
markdown_only means the branch changes only Markdown no agent follows. Such a branch holds no code or config for a higher rung to catch a defect in, so its reviewer runs on the project's rung: skills/larv-review/SKILL.md → "Markdown only".
|
||||
"""
|
||||
return project if markdown_only else self.highest(worker, self.review_floor(project, escape_and_impact))
|
||||
|
||||
def review_rung(project: Rung, worker: Rung, escape_and_impact: int, kind: ReviewKind, markdown_only: bool = False) -> Rung:
|
||||
"""The rung a review of this kind runs on in a chunk whose worker runs on worker and whose item has that E + I; markdown_only where the branch changes only Markdown no agent follows.
|
||||
def highest(self, *rungs: Rung) -> Rung:
|
||||
"""The most competent of the rungs; one off the ladder ranks below every rung on it."""
|
||||
return max(rungs, key=self.position)
|
||||
|
||||
A pass's reviewer runs on reviewers_rung; no replay has qualified a lower rung for any pass, docs/decisions.md → `routing: a review pass runs below the project's rung only on a rung whose replay of its rounds finds a share of their 🔴 and 🟡 findings no more than a margin below the project's rung's own replay`. A seat and the security pass run on the project's rung, so the seats score every chunk on one rung, and the security pass spends no more than the project chose.
|
||||
"""
|
||||
return project if kind in ("seat", "security") else reviewers_rung(project, worker, escape_and_impact, markdown_only)
|
||||
def climbed(self, rung: Rung, by: int) -> Rung:
|
||||
return self.rungs[max(0, min(len(self.rungs) - 1, self.position(rung) + by))]
|
||||
|
||||
|
||||
def reviewers_rung(project: Rung, worker: Rung, escape_and_impact: int, markdown_only: bool = False) -> Rung:
|
||||
"""The rung of each pass's reviewer: the higher of the worker's rung and review_floor's, which is never below the project's.
|
||||
|
||||
markdown_only means the branch changes only Markdown no agent follows. Such a branch holds no code or config for a higher rung to catch a defect in, so its reviewer runs on the project's rung: skills/larv-review/SKILL.md → "Markdown only".
|
||||
"""
|
||||
return project if markdown_only else highest(worker, review_floor(project, escape_and_impact))
|
||||
|
||||
|
||||
def highest(*rungs: Rung) -> Rung:
|
||||
"""The most competent of the rungs; one off the ladder ranks below every rung on it."""
|
||||
return max(rungs, key=position)
|
||||
|
||||
|
||||
def climbed(rung: Rung, by: int) -> Rung:
|
||||
return LADDER[max(0, min(len(LADDER) - 1, position(rung) + by))]
|
||||
|
||||
|
||||
def position(rung: Rung) -> int:
|
||||
return LADDER.index(rung) if rung in LADDER else -1
|
||||
def position(self, rung: Rung) -> int:
|
||||
return self.rungs.index(rung) if rung in self.rungs else -1
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
"""Read a routing ladder from its JSON file: the one this setup ships, or a project's own, kept in its config's folder. docs/decisions.md → `routing: one ladder of (model, effort) rungs`."""
|
||||
import json
|
||||
import pathlib
|
||||
import re
|
||||
|
||||
from model_routing.ladder import EFFORTS, Ladder, Rung
|
||||
from failure import Failure
|
||||
from project_config.main import located
|
||||
from project_config.settings import Unnamed
|
||||
|
||||
# The file's name in both places. Three readers, seated as the human who writes an override in a hurry, picked a bare list of objects over a list of strings, a list of pairs and a list under a key. Two of them picked one name for both files: an override is then a copy of the shipped file with rungs cut.
|
||||
NAME = "routing-ladder.json"
|
||||
# The ladder this setup ships, beside this module, so a copy of bin/ carries it: mutate-changes and the tests of a reload each run the tools from such a copy.
|
||||
SHIPPED = pathlib.Path(__file__).resolve().with_name(NAME)
|
||||
# A model as Rung.family reads it: the Agent tool's family name follows the first hyphen.
|
||||
MODEL = re.compile(r"[^\s-]+(-[^\s-]+)+")
|
||||
SHAPE = f'a JSON list of rungs, least competent first, each as {{"model": "claude-opus-5-5", "effort": "medium"}}: a model\'s full name, one model for each family such as opus, and an effort of {", ".join(EFFORTS[:-1])} or {EFFORTS[-1]}'
|
||||
|
||||
|
||||
def project_ladder_file(directory: str | None, home: pathlib.Path, shipped: pathlib.Path = SHIPPED) -> pathlib.Path | Failure:
|
||||
"""The file that holds the ladder of the project whose checkout holds directory, else the current directory: the file NAME in its config's folder under home, or shipped where that folder holds none. Also shipped where no config names a checkout there, or git fails there. A Failure where the project's config is faulty or cannot be read, since its folder may hold the ladder."""
|
||||
config = located(directory, home)
|
||||
if isinstance(config, Unnamed):
|
||||
return shipped
|
||||
if isinstance(config, Failure):
|
||||
return config
|
||||
own = config.folder / NAME
|
||||
return own if own.exists() else shipped
|
||||
|
||||
|
||||
def project_ladder(directory: str | None, home: pathlib.Path, shipped: pathlib.Path = SHIPPED) -> Ladder | Failure:
|
||||
"""The ladder project_ladder_file's file holds. A Failure where that file holds a fault too: the shipped ladder never stands in for a project's own, since work routed on it could run on a model the project cannot reach."""
|
||||
file = project_ladder_file(directory, home, shipped)
|
||||
return file if isinstance(file, Failure) else read_ladder(file)
|
||||
|
||||
|
||||
def read_ladder(file: pathlib.Path) -> Ladder | Failure:
|
||||
"""The ladder a file holds; a Failure naming the file and its fault where it holds none."""
|
||||
try:
|
||||
held = json.loads(file.read_text(encoding="utf-8"))
|
||||
except (OSError, UnicodeDecodeError, ValueError) as failure:
|
||||
# An OSError's own text names the file again.
|
||||
return Failure(f"cannot read the routing ladder {file}: {failure.strerror if isinstance(failure, OSError) else failure}. The routing ladder is {SHAPE}")
|
||||
faults = faults_of(held)
|
||||
if faults:
|
||||
return Failure(f"{file}: {'; '.join(faults)}. The routing ladder is {SHAPE}")
|
||||
return Ladder(tuple(Rung(rung["model"], rung["effort"]) for rung in held))
|
||||
|
||||
|
||||
def faults_of(held: object) -> list[str]:
|
||||
"""What keeps held from being a ladder: it is no list or an empty one, or else each rung, by its number from 1, that is misspelt, repeats one above it, or names a second model of a family."""
|
||||
if not isinstance(held, list) or not held:
|
||||
return ["it holds no list of rungs"]
|
||||
faults = []
|
||||
# The first rung of each family, by number: the Agent tool launches by family name, which Ladder.from_agent reads back as that family's one model.
|
||||
families: dict[str, tuple[int, str]] = {}
|
||||
for number, rung in enumerate(held, 1):
|
||||
if not well_formed(rung):
|
||||
faults.append(f"rung {number} is {json.dumps(rung)}")
|
||||
continue
|
||||
family = Rung(rung["model"]).family()
|
||||
first, model = families.setdefault(family, (number, rung["model"]))
|
||||
if rung in held[:number - 1]:
|
||||
faults.append(f"rung {number} repeats rung {held.index(rung) + 1}")
|
||||
elif model != rung["model"]:
|
||||
faults.append(f"rung {number} names a second model of the family {family}, after rung {first}")
|
||||
return faults
|
||||
|
||||
|
||||
def well_formed(rung: object) -> bool:
|
||||
return isinstance(rung, dict) and rung.keys() == {"model", "effort"} and isinstance(rung["model"], str) and bool(MODEL.fullmatch(rung["model"])) and rung["effort"] in EFFORTS
|
||||
@@ -2,7 +2,7 @@
|
||||
import dataclasses
|
||||
|
||||
from model_routing.route import HIGHEST_ESCAPE_AND_IMPACT, Route
|
||||
from model_routing.ladder import review_rung, reviewers_rung, Rung
|
||||
from model_routing.ladder import Ladder, Rung
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
@@ -17,12 +17,12 @@ class ReviewChoice:
|
||||
higher: dict[Rung, int]
|
||||
|
||||
|
||||
def chosen(project: Rung, route: Route) -> ReviewChoice:
|
||||
"""The rung each kind of review runs on for a chunk whose route is route, on a project whose rung is project."""
|
||||
reviewers = reviewers_rung(project, route.rung, route.reviewed_on())
|
||||
def chosen(ladder: Ladder, project: Rung, route: Route) -> ReviewChoice:
|
||||
"""The rung each kind of review runs on for a chunk whose route is route, on a project whose rung on ladder is project."""
|
||||
reviewers = ladder.reviewers_rung(project, route.rung, route.reviewed_on())
|
||||
higher: dict[Rung, int] = {}
|
||||
for escape_and_impact in range(route.reviewed_on() + 1, HIGHEST_ESCAPE_AND_IMPACT + 1):
|
||||
if (rung := reviewers_rung(project, route.rung, escape_and_impact)) != reviewers:
|
||||
if (rung := ladder.reviewers_rung(project, route.rung, escape_and_impact)) != reviewers:
|
||||
higher.setdefault(rung, escape_and_impact)
|
||||
markdown_only = reviewers_rung(project, route.rung, route.reviewed_on(), markdown_only=True)
|
||||
return ReviewChoice(reviewers, markdown_only, review_rung(project, route.rung, route.reviewed_on(), "seat"), review_rung(project, route.rung, route.reviewed_on(), "security"), higher)
|
||||
markdown_only = ladder.reviewers_rung(project, route.rung, route.reviewed_on(), markdown_only=True)
|
||||
return ReviewChoice(reviewers, markdown_only, ladder.review_rung(project, route.rung, route.reviewed_on(), "seat"), ladder.review_rung(project, route.rung, route.reviewed_on(), "security"), higher)
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
[
|
||||
{"model": "claude-sonnet-5-5", "effort": "high"},
|
||||
{"model": "claude-opus-5-5", "effort": "medium"},
|
||||
{"model": "claude-fable-5-2", "effort": "low"},
|
||||
{"model": "claude-fable-5-2", "effort": "medium"},
|
||||
{"model": "claude-opus-5-5", "effort": "xhigh"},
|
||||
{"model": "claude-fable-5-2", "effort": "high"},
|
||||
{"model": "claude-fable-5-2", "effort": "max"}
|
||||
]
|
||||
@@ -4,58 +4,58 @@ import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from model_routing.ladder import highest, LADDER, lowest_worker_rung, planning_rung, project_rung, review_floor, review_rung, Rung, stepped_up, worker_rung, WORKER_STEPS
|
||||
from release_plan.todo_table import LEVELS
|
||||
from model_routing.ladder_file import read_ladder, SHIPPED
|
||||
from review_rules.review_passes import REVIEWERS
|
||||
from model_routing.ladder import Rung, WORKER_STEPS
|
||||
|
||||
# The ladder this setup ships, whose rungs the tests below name.
|
||||
LADDER = read_ladder(SHIPPED)
|
||||
OPUS = Rung("claude-opus-5-5", "medium")
|
||||
FABLE_LOW = Rung("claude-fable-5-2", "low")
|
||||
|
||||
|
||||
class Ladder(unittest.TestCase):
|
||||
def test_holds_each_rung_once_since_a_rung_s_position_sets_every_step(self):
|
||||
self.assertEqual(len(set(LADDER)), len(LADDER))
|
||||
|
||||
def test_puts_a_project_on_its_models_cheapest_rung_and_none_off_the_ladder(self):
|
||||
self.assertEqual(project_rung("claude-opus-5-5"), OPUS)
|
||||
self.assertEqual(project_rung("claude-sonnet-5-5"), Rung("claude-sonnet-5-5", "high"))
|
||||
self.assertEqual(project_rung("claude-fable-5-2"), FABLE_LOW)
|
||||
self.assertIsNone(project_rung("claude-opus-5"))
|
||||
self.assertIsNone(project_rung("opus"))
|
||||
self.assertEqual(LADDER.project_rung("claude-opus-5-5"), OPUS)
|
||||
self.assertEqual(LADDER.project_rung("claude-sonnet-5-5"), Rung("claude-sonnet-5-5", "high"))
|
||||
self.assertEqual(LADDER.project_rung("claude-fable-5-2"), FABLE_LOW)
|
||||
self.assertIsNone(LADDER.project_rung("claude-opus-5"))
|
||||
self.assertIsNone(LADDER.project_rung("opus"))
|
||||
|
||||
def test_steps_a_workers_rung_by_its_l_from_the_projects_rung(self):
|
||||
position = LADDER.index(OPUS)
|
||||
self.assertEqual([LADDER.index(worker_rung(OPUS, likelihood)) - position for likelihood in range(1, 5)], [-1, -1, 0, 1])
|
||||
position = LADDER.rungs.index(OPUS)
|
||||
self.assertEqual([LADDER.rungs.index(LADDER.worker_rung(OPUS, likelihood)) - position for likelihood in range(1, 5)], [-1, -1, 0, 1])
|
||||
|
||||
def test_steps_a_review_up_by_its_e_plus_i_from_the_projects_rung_and_never_down(self):
|
||||
position = LADDER.index(OPUS)
|
||||
self.assertEqual([LADDER.index(review_floor(OPUS, total)) - position for total in range(2, 9)], [0, 0, 0, 1, 2, 3, 4])
|
||||
self.assertEqual(review_floor(OPUS, 0), OPUS)
|
||||
position = LADDER.rungs.index(OPUS)
|
||||
self.assertEqual([LADDER.rungs.index(LADDER.review_floor(OPUS, total)) - position for total in range(2, 9)], [0, 0, 0, 1, 2, 3, 4])
|
||||
self.assertEqual(LADDER.review_floor(OPUS, 0), OPUS)
|
||||
|
||||
def test_a_step_past_either_end_stops_there(self):
|
||||
self.assertEqual(worker_rung(OPUS, 1), Rung("claude-sonnet-5-5", "high"))
|
||||
self.assertEqual(worker_rung(LADDER[0], 1), LADDER[0])
|
||||
self.assertEqual(review_floor(Rung("claude-opus-5-5", "xhigh"), 8), LADDER[-1])
|
||||
self.assertEqual(stepped_up(LADDER[-1]), LADDER[-1])
|
||||
self.assertEqual(stepped_up(OPUS), FABLE_LOW)
|
||||
self.assertEqual(LADDER.worker_rung(OPUS, 1), Rung("claude-sonnet-5-5", "high"))
|
||||
self.assertEqual(LADDER.worker_rung(LADDER.rungs[0], 1), LADDER.rungs[0])
|
||||
self.assertEqual(LADDER.review_floor(Rung("claude-opus-5-5", "xhigh"), 8), LADDER.rungs[-1])
|
||||
self.assertEqual(LADDER.stepped_up(LADDER.rungs[-1]), LADDER.rungs[-1])
|
||||
self.assertEqual(LADDER.stepped_up(OPUS), FABLE_LOW)
|
||||
|
||||
def test_steps_a_worker_for_every_level_on_ls_scale(self):
|
||||
self.assertEqual(set(WORKER_STEPS), set(range(1, LEVELS["L"] + 1)))
|
||||
|
||||
def test_names_the_lowest_rung_any_l_routes_a_worker_to(self):
|
||||
self.assertEqual(lowest_worker_rung(OPUS), Rung("claude-sonnet-5-5", "high"))
|
||||
self.assertEqual(LADDER.lowest_worker_rung(OPUS), Rung("claude-sonnet-5-5", "high"))
|
||||
|
||||
def test_plans_on_the_rung_l_picks_but_never_below_the_projects(self):
|
||||
self.assertEqual(planning_rung(OPUS, 1), OPUS)
|
||||
self.assertEqual(planning_rung(OPUS, 4), FABLE_LOW)
|
||||
self.assertEqual(LADDER.planning_rung(OPUS, 1), OPUS)
|
||||
self.assertEqual(LADDER.planning_rung(OPUS, 4), FABLE_LOW)
|
||||
|
||||
def test_names_each_rung_by_a_family_the_agent_tool_takes(self):
|
||||
self.assertEqual({rung.agent_args().split(",")[0] for rung in LADDER}, {"model sonnet", "model opus", "model fable"})
|
||||
self.assertEqual({rung.agent_args().split(",")[0] for rung in LADDER.rungs}, {"model sonnet", "model opus", "model fable"})
|
||||
|
||||
def test_ranks_a_rung_off_the_ladder_below_every_rung_on_it(self):
|
||||
self.assertEqual(highest(OPUS, LADDER[-1], LADDER[0]), LADDER[-1])
|
||||
self.assertEqual(highest(Rung("claude-opus-5-5", "low"), LADDER[0]), LADDER[0])
|
||||
self.assertEqual(stepped_up(Rung("claude-opus-5-5", "low")), LADDER[0])
|
||||
self.assertEqual(LADDER.highest(OPUS, LADDER.rungs[-1], LADDER.rungs[0]), LADDER.rungs[-1])
|
||||
self.assertEqual(LADDER.highest(Rung("claude-opus-5-5", "low"), LADDER.rungs[0]), LADDER.rungs[0])
|
||||
self.assertEqual(LADDER.stepped_up(Rung("claude-opus-5-5", "low")), LADDER.rungs[0])
|
||||
|
||||
def test_passes_the_effort_only_where_the_rung_names_one(self):
|
||||
self.assertEqual(Rung("claude-opus-5-5", "high").flags(), ["--model", "claude-opus-5-5", "--effort", "high"])
|
||||
@@ -64,7 +64,7 @@ class Ladder(unittest.TestCase):
|
||||
self.assertEqual(str(Rung("worker-model")), "worker-model")
|
||||
|
||||
def test_parses_what_str_wrote_for_each_rung_on_the_ladder(self):
|
||||
for rung in LADDER:
|
||||
for rung in LADDER.rungs:
|
||||
with self.subTest(rung=rung):
|
||||
self.assertEqual(Rung.parse(str(rung)), rung)
|
||||
|
||||
@@ -77,31 +77,32 @@ class Ladder(unittest.TestCase):
|
||||
self.assertIsNone(Rung.parse(text))
|
||||
|
||||
def test_reads_the_agent_tools_words_back_as_a_rung(self):
|
||||
for rung in LADDER:
|
||||
for rung in LADDER.rungs:
|
||||
with self.subTest(rung=rung):
|
||||
model, effort = (part.split(" ")[1] for part in rung.agent_args().split(", "))
|
||||
self.assertEqual(Rung.from_agent(model, effort), rung)
|
||||
self.assertEqual(LADDER.from_agent(model, effort), rung)
|
||||
|
||||
def test_reads_a_family_named_without_an_effort_as_its_cheapest_rung(self):
|
||||
self.assertEqual(Rung.from_agent("opus", ""), OPUS)
|
||||
self.assertEqual(Rung.from_agent("sonnet", ""), Rung("claude-sonnet-5-5", "high"))
|
||||
self.assertEqual(LADDER.from_agent("opus", ""), OPUS)
|
||||
self.assertEqual(LADDER.from_agent("sonnet", ""), Rung("claude-sonnet-5-5", "high"))
|
||||
|
||||
def test_reads_an_unknown_family_or_an_effort_off_the_ladder_as_a_rung_off_it(self):
|
||||
for model, effort in (("gpt", "high"), ("gpt", ""), ("opus", "low"), ("opus", "high"), ("haiku", "bogus")):
|
||||
with self.subTest(model=model, effort=effort):
|
||||
self.assertNotIn(Rung.from_agent(model, effort), LADDER)
|
||||
self.assertEqual(Rung.from_agent("opus", "low"), Rung("claude-opus-5-5", "low"))
|
||||
self.assertNotIn(LADDER.from_agent(model, effort), LADDER.rungs)
|
||||
self.assertEqual(LADDER.from_agent("opus", "low"), Rung("claude-opus-5-5", "low"))
|
||||
self.assertEqual(LADDER.from_agent("gpt", "high"), Rung("gpt", "high"))
|
||||
|
||||
def test_puts_reviewers_on_the_highest_of_the_projects_rung_the_workers_and_the_one_e_plus_i_picks(self):
|
||||
sonnet, fable = LADDER[0], LADDER[-1]
|
||||
self.assertEqual(review_rung(OPUS, sonnet, 4, "stability"), OPUS)
|
||||
self.assertEqual(review_rung(OPUS, sonnet, 5, "stability"), FABLE_LOW)
|
||||
self.assertEqual(review_rung(OPUS, fable, 5, "stability"), fable)
|
||||
self.assertEqual(review_rung(OPUS, FABLE_LOW, 7, "stability"), Rung("claude-opus-5-5", "xhigh"))
|
||||
sonnet, fable = LADDER.rungs[0], LADDER.rungs[-1]
|
||||
self.assertEqual(LADDER.review_rung(OPUS, sonnet, 4, "stability"), OPUS)
|
||||
self.assertEqual(LADDER.review_rung(OPUS, sonnet, 5, "stability"), FABLE_LOW)
|
||||
self.assertEqual(LADDER.review_rung(OPUS, fable, 5, "stability"), fable)
|
||||
self.assertEqual(LADDER.review_rung(OPUS, FABLE_LOW, 7, "stability"), Rung("claude-opus-5-5", "xhigh"))
|
||||
|
||||
def test_keeps_the_seats_and_the_security_pass_on_the_projects_rung_whatever_the_worker_or_e_plus_i(self):
|
||||
self.assertEqual([review_rung(OPUS, LADDER[-1], 8, kind) for kind in (*REVIEWERS, "seat", "security")], [LADDER[-1]] * len(REVIEWERS) + [OPUS, OPUS])
|
||||
self.assertEqual([LADDER.review_rung(OPUS, LADDER.rungs[-1], 8, kind) for kind in (*REVIEWERS, "seat", "security")], [LADDER.rungs[-1]] * len(REVIEWERS) + [OPUS, OPUS])
|
||||
|
||||
def test_puts_every_review_of_a_branch_changing_only_markdown_no_agent_follows_on_the_projects_rung(self):
|
||||
self.assertEqual([review_rung(OPUS, LADDER[-1], 8, kind, markdown_only=True) for kind in (*REVIEWERS, "seat", "security")], [OPUS] * (len(REVIEWERS) + 2))
|
||||
self.assertEqual(review_rung(OPUS, LADDER[0], 4, "stability", markdown_only=True), OPUS)
|
||||
self.assertEqual([LADDER.review_rung(OPUS, LADDER.rungs[-1], 8, kind, markdown_only=True) for kind in (*REVIEWERS, "seat", "security")], [OPUS] * (len(REVIEWERS) + 2))
|
||||
self.assertEqual(LADDER.review_rung(OPUS, LADDER.rungs[0], 4, "stability", markdown_only=True), OPUS)
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
import pathlib
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from failure import Failure
|
||||
from test_env import isolated_env
|
||||
from model_routing.ladder import Ladder, Rung
|
||||
from model_routing.ladder_file import NAME, project_ladder, project_ladder_file, read_ladder, SHIPPED
|
||||
from project_config.test_project_config import write_config
|
||||
|
||||
FABLE_ONLY = '[\n\t{"model": "claude-fable-5-2", "effort": "low"},\n\t{"model": "claude-fable-5-2", "effort": "max"}\n]\n'
|
||||
FABLE_LADDER = Ladder((Rung("claude-fable-5-2", "low"), Rung("claude-fable-5-2", "max")))
|
||||
OPUS = '{"model": "claude-opus-5-5", "effort": "medium"}'
|
||||
|
||||
|
||||
class LadderCase(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
made = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(made.cleanup)
|
||||
self.home = pathlib.Path(made.name).resolve()
|
||||
self.shipped = self.home / "shipped.json"
|
||||
self.shipped.write_text(f"[{OPUS}]", encoding="utf-8")
|
||||
|
||||
def checkout(self, name: str = "acme") -> pathlib.Path:
|
||||
"""A git checkout under the home, holding one commit, that no config names yet."""
|
||||
checkout = self.home / "code" / name
|
||||
checkout.mkdir(parents=True)
|
||||
self.git(checkout, "init", "--quiet", "-b", "main")
|
||||
self.git(checkout, "commit", "--quiet", "--allow-empty", "-m", "base")
|
||||
return checkout
|
||||
|
||||
def git(self, cwd: pathlib.Path, *args: str) -> None:
|
||||
subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@example.com", *args], capture_output=True, check=True, cwd=cwd, env=isolated_env())
|
||||
|
||||
|
||||
class ReadLadder(LadderCase):
|
||||
def reason(self, text: str) -> str:
|
||||
file = self.home / NAME
|
||||
file.write_text(text, encoding="utf-8")
|
||||
read = read_ladder(file)
|
||||
assert isinstance(read, Failure), read
|
||||
return read.reason
|
||||
|
||||
def test_the_ladder_this_setup_ships_reads_as_a_ladder(self):
|
||||
self.assertIsInstance(read_ladder(SHIPPED), Ladder)
|
||||
|
||||
def test_reads_the_rungs_in_the_files_order(self):
|
||||
file = self.home / NAME
|
||||
file.write_text(FABLE_ONLY, encoding="utf-8")
|
||||
self.assertEqual(read_ladder(file), FABLE_LADDER)
|
||||
|
||||
def test_a_file_that_is_missing_or_no_json_fails_naming_the_file_and_the_shape(self):
|
||||
file = self.home / NAME
|
||||
missing = read_ladder(file)
|
||||
self.assertIsInstance(missing, Failure)
|
||||
self.assertTrue(missing.reason.startswith(f"cannot read the routing ladder {file}: No such file or directory. The routing ladder is a JSON list of rungs"), missing.reason)
|
||||
# The comma a reader leaves after the last rung when dropping one.
|
||||
trailing = self.reason(f"[\n\t{OPUS},\n]\n")
|
||||
self.assertIn(f"cannot read the routing ladder {file}: ", trailing)
|
||||
self.assertIn("line 2", trailing)
|
||||
self.assertTrue(trailing.endswith('. The routing ladder is a JSON list of rungs, least competent first, each as {"model": "claude-opus-5-5", "effort": "medium"}: a model\'s full name, one model for each family such as opus, and an effort of low, medium, high, xhigh or max'), trailing)
|
||||
file.write_bytes(b"\xff")
|
||||
self.assertIn(f"cannot read the routing ladder {file}: ", read_ladder(file).reason)
|
||||
|
||||
def test_a_file_holding_anything_but_a_list_of_rungs_fails(self):
|
||||
for text in (OPUS, "[]", '"claude-opus-5-5 at medium effort"', "null"):
|
||||
with self.subTest(text=text):
|
||||
self.assertEqual(self.reason(text).split(". ")[0], f"{self.home / NAME}: it holds no list of rungs")
|
||||
|
||||
def test_names_each_misspelt_rung_by_its_number(self):
|
||||
misspelt = {
|
||||
"an effort off the scale": '{"model": "claude-opus-5-5", "effort": "ultra"}',
|
||||
"no effort": '{"model": "claude-opus-5-5"}',
|
||||
"an empty effort": '{"model": "claude-opus-5-5", "effort": ""}',
|
||||
"a key too many": '{"model": "claude-opus-5-5", "effort": "low", "note": "x"}',
|
||||
"a model that names no family": '{"model": "opus", "effort": "low"}',
|
||||
"a model with a space": '{"model": "claude-opus 5-5", "effort": "low"}',
|
||||
"a model that is no text": '{"model": 5, "effort": "low"}',
|
||||
"a pair": '["claude-opus-5-5", "low"]',
|
||||
"the rung as a tool prints it": '"claude-opus-5-5 at low effort"',
|
||||
}
|
||||
for what, rung in misspelt.items():
|
||||
with self.subTest(what):
|
||||
self.assertEqual(self.reason(f"[{OPUS}, {rung}]").split(". ")[0], f"{self.home / NAME}: rung 2 is {rung}")
|
||||
self.assertIn("rung 1 is 1; rung 3 is 3. The routing ladder is a JSON list of rungs, least competent first", self.reason(f"[1, {OPUS}, 3]"))
|
||||
|
||||
def test_a_rung_held_twice_fails_naming_both_since_a_rungs_position_sets_every_step(self):
|
||||
low = '{"model": "claude-opus-5-5", "effort": "low"}'
|
||||
self.assertEqual(self.reason(f"[{low}, {OPUS}, {low}]").split(". ")[0], f"{self.home / NAME}: rung 3 repeats rung 1")
|
||||
|
||||
def test_a_second_model_of_one_family_fails_naming_the_familys_first_rung_since_a_subagent_launches_by_family(self):
|
||||
older, newer = '{"model": "claude-fable-5-1", "effort": "max"}', '{"model": "claude-fable-5-2", "effort": "low"}'
|
||||
self.assertEqual(self.reason(f"[{OPUS}, {older}, {newer}]").split(". ")[0], f"{self.home / NAME}: rung 3 names a second model of the family fable, after rung 2")
|
||||
both = self.reason(f'[{older}, {newer}, {{"model": "claude-fable-5-2", "effort": "high"}}]').split(". ")[0]
|
||||
self.assertEqual(both, f"{self.home / NAME}: rung 2 names a second model of the family fable, after rung 1; rung 3 names a second model of the family fable, after rung 1")
|
||||
file = self.home / NAME
|
||||
file.write_text(f'[{OPUS}, {newer}, {{"model": "claude-opus-5-5", "effort": "xhigh"}}, {{"model": "claude-fable-5-2", "effort": "max"}}]', encoding="utf-8")
|
||||
self.assertIsInstance(read_ladder(file), Ladder, "one model at several efforts, between another family's rungs, is no fault")
|
||||
|
||||
|
||||
class ProjectLadder(LadderCase):
|
||||
def test_a_project_runs_on_the_ladder_its_configs_folder_holds_from_a_worktree_too(self):
|
||||
checkout = self.checkout()
|
||||
(write_config(self.home, checkout) / NAME).write_text(FABLE_ONLY, encoding="utf-8")
|
||||
self.assertEqual(project_ladder(str(checkout), self.home, self.shipped), FABLE_LADDER)
|
||||
worktree = self.home / "code" / "acme-item-7"
|
||||
self.git(checkout, "worktree", "add", "--quiet", str(worktree), "-b", "item-7")
|
||||
self.assertEqual(project_ladder(str(worktree), self.home, self.shipped), FABLE_LADDER)
|
||||
|
||||
def test_names_the_file_it_reads_the_projects_own_or_else_the_shipped_one(self):
|
||||
checkout = self.checkout()
|
||||
folder = write_config(self.home, checkout)
|
||||
self.assertEqual(project_ladder_file(str(checkout), self.home, self.shipped), self.shipped)
|
||||
(folder / NAME).write_text(FABLE_ONLY, encoding="utf-8")
|
||||
self.assertEqual(project_ladder_file(str(checkout), self.home, self.shipped), folder / NAME)
|
||||
self.assertEqual(project_ladder_file(str(self.home), self.home), SHIPPED, "outside a checkout, the ladder this setup ships")
|
||||
|
||||
def test_another_projects_ladder_is_not_read(self):
|
||||
checkout, other = self.checkout(), self.checkout("other")
|
||||
write_config(self.home, checkout)
|
||||
(write_config(self.home, other) / NAME).write_text(FABLE_ONLY, encoding="utf-8")
|
||||
self.assertEqual(project_ladder(str(checkout), self.home, self.shipped), Ladder((Rung("claude-opus-5-5", "medium"),)))
|
||||
|
||||
def test_a_checkout_no_config_names_and_a_folder_outside_any_checkout_run_on_the_shipped_ladder(self):
|
||||
shipped = Ladder((Rung("claude-opus-5-5", "medium"),))
|
||||
self.assertEqual(project_ladder(str(self.checkout()), self.home, self.shipped), shipped)
|
||||
self.assertEqual(project_ladder(str(self.home), self.home, self.shipped), shipped)
|
||||
|
||||
def test_a_faulty_ladder_of_the_projects_own_fails_and_the_shipped_one_does_not_stand_in(self):
|
||||
checkout = self.checkout()
|
||||
own = write_config(self.home, checkout) / NAME
|
||||
own.write_text("[]", encoding="utf-8")
|
||||
self.assertEqual(project_ladder(str(checkout), self.home, self.shipped).reason.split(". ")[0], f"{own}: it holds no list of rungs")
|
||||
|
||||
def test_a_faulty_config_fails_since_its_folder_may_hold_the_ladder(self):
|
||||
checkout = self.checkout()
|
||||
config = write_config(self.home, checkout) / "config.toml"
|
||||
config.write_text(config.read_text(encoding="utf-8") + 'readme = "checkout:README.md"\n', encoding="utf-8")
|
||||
self.assertIn("`readme` is not a setting", project_ladder(str(checkout), self.home, self.shipped).reason)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -4,13 +4,13 @@ import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from model_routing.ladder import LADDER
|
||||
from model_routing.prices import PRICES
|
||||
from model_routing.ladder_file import read_ladder, SHIPPED
|
||||
|
||||
|
||||
class Prices(unittest.TestCase):
|
||||
def test_every_model_on_the_ladder_has_a_price_since_a_model_without_one_is_left_out_of_every_figure(self):
|
||||
self.assertEqual(sorted({rung.model for rung in LADDER} - set(PRICES)), [])
|
||||
self.assertEqual(sorted({rung.model for rung in read_ladder(SHIPPED).rungs} - set(PRICES)), [])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -1,17 +1,19 @@
|
||||
import unittest
|
||||
|
||||
from model_routing.review_choice import chosen
|
||||
from model_routing.ladder_file import read_ladder, SHIPPED
|
||||
from model_routing.route import Route
|
||||
from model_routing.ladder import Rung
|
||||
|
||||
LADDER = read_ladder(SHIPPED)
|
||||
OPUS = Rung("claude-opus-5-5", "medium")
|
||||
FABLE = Rung("claude-fable-5-2", "max")
|
||||
|
||||
|
||||
class Chosen(unittest.TestCase):
|
||||
def test_names_no_higher_rung_on_the_top_one(self):
|
||||
self.assertEqual(chosen(OPUS, Route(FABLE, 3, 4, 5)).higher, {})
|
||||
self.assertEqual(chosen(LADDER, OPUS, Route(FABLE, 3, 4, 5)).higher, {})
|
||||
|
||||
def test_reviews_a_branch_changing_only_markdown_on_the_projects_rung_and_the_seats_and_security_pass_there_always(self):
|
||||
choice = chosen(OPUS, Route(FABLE, 3, 4, 5))
|
||||
choice = chosen(LADDER, OPUS, Route(FABLE, 3, 4, 5))
|
||||
self.assertEqual((choice.reviewers, choice.markdown_only, choice.seat, choice.security), (FABLE, OPUS, OPUS, OPUS))
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
import unittest
|
||||
|
||||
from model_routing.worker_rungs import environment, handed
|
||||
from model_routing.worker_rungs import environment, handed, hands_rungs
|
||||
from model_routing.ladder import Ladder, Rung
|
||||
from model_routing.ladder_file import read_ladder, SHIPPED
|
||||
from model_routing.route import Route
|
||||
from model_routing.ladder import Rung
|
||||
|
||||
|
||||
LADDER = read_ladder(SHIPPED)
|
||||
|
||||
|
||||
class Environment(unittest.TestCase):
|
||||
@@ -18,13 +22,23 @@ class Environment(unittest.TestCase):
|
||||
self.assertEqual(environment(None, Route(self.WORKER)), {"LOOP_CLAUDE_PROJECT_RUNG": "", "LOOP_CLAUDE_WORKER_RUNG": "claude-sonnet-5-5 at high effort", "LOOP_CLAUDE_ESCAPE_AND_IMPACT": "0"})
|
||||
|
||||
def test_handed_reads_back_what_environment_named(self):
|
||||
self.assertEqual(handed(environment(self.PROJECT, Route(self.WORKER, 3, 1, 5))), (self.PROJECT, self.WORKER, 5))
|
||||
self.assertEqual(handed(environment(None, Route(self.WORKER))), (None, self.WORKER, 0))
|
||||
self.assertEqual(handed(environment(self.PROJECT, Route(self.WORKER, 3, 1, 5)), LADDER), (self.PROJECT, self.WORKER, 5))
|
||||
self.assertEqual(handed(environment(None, Route(self.WORKER)), LADDER), (None, self.WORKER, 0))
|
||||
|
||||
def test_a_rung_off_the_ladder_given_reads_as_none(self):
|
||||
fable_only = Ladder((Rung("claude-fable-5-2", "low"),))
|
||||
self.assertEqual(handed(environment(self.PROJECT, Route(Rung("claude-fable-5-2", "low"))), fable_only), (None, Rung("claude-fable-5-2", "low"), 0))
|
||||
|
||||
def test_tells_whether_both_rungs_are_named_before_any_ladder_is_read(self):
|
||||
self.assertTrue(hands_rungs(environment(self.PROJECT, Route(self.WORKER))))
|
||||
self.assertFalse(hands_rungs(environment(None, Route(self.WORKER))))
|
||||
self.assertFalse(hands_rungs({"LOOP_CLAUDE_PROJECT_RUNG": "claude-opus-5-5 at medium effort"}))
|
||||
self.assertFalse(hands_rungs({}))
|
||||
|
||||
def test_a_missing_or_unknown_rung_reads_as_none_and_a_missing_or_unknown_e_plus_i_as_0(self):
|
||||
self.assertEqual(handed({}), (None, None, 0))
|
||||
self.assertEqual(handed({"LOOP_CLAUDE_WORKER_RUNG": "claude-haiku-5-5 bogus"}), (None, None, 0))
|
||||
self.assertEqual(handed({"LOOP_CLAUDE_WORKER_RUNG": "claude-haiku-5-5 at bogus effort"}), (None, None, 0))
|
||||
self.assertEqual(handed({}, LADDER), (None, None, 0))
|
||||
self.assertEqual(handed({"LOOP_CLAUDE_WORKER_RUNG": "claude-haiku-5-5 bogus"}, LADDER), (None, None, 0))
|
||||
self.assertEqual(handed({"LOOP_CLAUDE_WORKER_RUNG": "claude-haiku-5-5 at bogus effort"}, LADDER), (None, None, 0))
|
||||
for bogus in ("", "five", "-1", "5.0", "²"):
|
||||
with self.subTest(bogus=bogus):
|
||||
self.assertEqual(handed({"LOOP_CLAUDE_ESCAPE_AND_IMPACT": bogus})[2], 0)
|
||||
self.assertEqual(handed({"LOOP_CLAUDE_ESCAPE_AND_IMPACT": bogus}, LADDER)[2], 0)
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
loop-claude sets these variables for its worker and for the claude an interrupt resumes; a human's shell does not, and rule-hook then checks no review launch."""
|
||||
import typing
|
||||
|
||||
from model_routing.ladder import LADDER, Rung
|
||||
from model_routing.ladder import Ladder, Rung
|
||||
from model_routing.route import Route
|
||||
|
||||
PROJECT_RUNG = "LOOP_CLAUDE_PROJECT_RUNG"
|
||||
@@ -17,12 +17,17 @@ def environment(project: Rung | None, route: Route) -> dict[str, str]:
|
||||
return {PROJECT_RUNG: str(project) if project else "", WORKER_RUNG: str(route.rung), ESCAPE_AND_IMPACT: str(route.reviewed_on())}
|
||||
|
||||
|
||||
def handed(environ: typing.Mapping[str, str]) -> tuple[Rung | None, Rung | None, int]:
|
||||
"""The project's and the worker's rungs, each None when unset or not on the ladder, and the reviews' E + I, 0 when unset or not a whole number. An older loop-claude hands no E + I, and 0 steps no review up."""
|
||||
def hands_rungs(environ: typing.Mapping[str, str]) -> bool:
|
||||
"""Whether the environment names a project's and a worker's rung, as loop-claude sets them for a project on its ladder. Where it names neither, no review launch is checked, so the caller skips reading the project's ladder."""
|
||||
return bool(environ.get(PROJECT_RUNG) and environ.get(WORKER_RUNG))
|
||||
|
||||
|
||||
def handed(environ: typing.Mapping[str, str], ladder: Ladder) -> tuple[Rung | None, Rung | None, int]:
|
||||
"""The project's and the worker's rungs, each None when unset or not on ladder, and the reviews' E + I, 0 when unset or not a whole number. ladder is the project's. An older loop-claude hands no E + I, and 0 steps no review up."""
|
||||
escape_and_impact = environ.get(ESCAPE_AND_IMPACT, "")
|
||||
return on_the_ladder(environ.get(PROJECT_RUNG)), on_the_ladder(environ.get(WORKER_RUNG)), int(escape_and_impact) if escape_and_impact.isdecimal() else 0
|
||||
return on_the_ladder(environ.get(PROJECT_RUNG), ladder), on_the_ladder(environ.get(WORKER_RUNG), ladder), int(escape_and_impact) if escape_and_impact.isdecimal() else 0
|
||||
|
||||
|
||||
def on_the_ladder(value: str | None) -> Rung | None:
|
||||
def on_the_ladder(value: str | None, ladder: Ladder) -> Rung | None:
|
||||
rung = Rung.parse(value or "")
|
||||
return rung if rung in LADDER else None
|
||||
return rung if rung in ladder.rungs else None
|
||||
|
||||
+178
-15
@@ -1,22 +1,22 @@
|
||||
"""A plan kept as the child issues of one Jira Cloud epic, read over Jira's REST API.
|
||||
"""A plan kept as the child issues of one Jira Cloud epic, read, filed into and finished over Jira's REST API.
|
||||
|
||||
An item is an open child issue. Its ID is the issue's number, so every child must be in the epic's own Jira project: ABC-34 is item 34 of the plan under ABC-12. The summary is the tagline, the description the detail, the earliest Fix Version the release, and an "is blocked by" link a blocker. L, E, I, S, Moves and Exempt sit in one issue property, PROPERTY, which needs no Jira admin to set up; an issue a teammate filed holds none, and reads as an item without scores.
|
||||
|
||||
The store only reads so far: every write is a Failure."""
|
||||
`add` files an item as a new child issue, marked with FILED_BY, and `finish` moves an item's issue to a done status. edit is a Failure until todo.md's item 382."""
|
||||
import base64
|
||||
import dataclasses
|
||||
import pathlib
|
||||
import re
|
||||
import typing
|
||||
|
||||
from adf_codec.convert import adfs_to_markdown, Refused
|
||||
from plan_store.markdown_edits import bold_cell
|
||||
from project_config.settings import Epic
|
||||
from release_plan.todo_table import EXEMPTIONS, is_exempt, Item, MOVES, parse_moves, parse_scores, SHAPE
|
||||
from adf_codec.convert import adfs_to_markdown, markdown_to_adf, Refused
|
||||
from release_plan.todo_table import BLOCKED_BY, EXEMPTIONS, is_exempt, Item, MOVES, parse_ids, parse_moves, parse_scores, SHAPE
|
||||
from plan_store.markdown_edits import bold_cell, plain, unfit_text
|
||||
from plan_store.stores import cells, Plan, Written
|
||||
from project_config.settings import Epic, Finish, JIRA_FINISH_STATUS, JIRA_FINISH_TRANSITION
|
||||
from failure import Failure
|
||||
from rest_client import json_request
|
||||
from release_plan.release import parsed, Release, tagged
|
||||
from plan_store.stores import Plan, Written
|
||||
from rest_client.env_file import read_env
|
||||
|
||||
# One pair of keys for Jira and Confluence: one Atlassian account's API token opens both.
|
||||
@@ -29,11 +29,25 @@ TIMEOUT = 30
|
||||
PAGE = 100
|
||||
# The pages one read asks for at most, so an answer that never names a last page ends the read.
|
||||
MAX_PAGES = 100
|
||||
READ_ONLY = "a plan in Jira is only read so far: file, edit and finish its issues in Jira"
|
||||
READ_ONLY = "the loop doesn't edit an issue of a plan in Jira yet: edit it in Jira"
|
||||
# The key in PROPERTY's value that marks an issue the loop filed, and its value. The loop never edits the summary or description of an issue without it, which a person filed.
|
||||
FILED_BY = ("Filed by", "loop")
|
||||
# The issue type of an issue the loop files, which Jira Software's project templates all have; a project without it refuses the issue, saying so.
|
||||
ISSUE_TYPE = "Task"
|
||||
# The name of the link type whose inward side reads "is blocked by", as Jira Cloud ships it.
|
||||
BLOCKS = "Blocks"
|
||||
SECURITY = "security"
|
||||
# The key of the status category Jira Cloud gives every done status.
|
||||
DONE = "done"
|
||||
# What a failed create ends with: a request Jira never answered, or answered brokenly, may still have filed the issue.
|
||||
PERHAPS_FILED = "unless Jira refused the request, the issue may exist: look under {epic} before filing the item again"
|
||||
# What a failed move ends with, for the same reason.
|
||||
PERHAPS_MOVED = "unless Jira refused the request, the issue may have moved: look at {key} before finishing the item again"
|
||||
|
||||
# Sends a request with the Authorization header given, the body as JSON where there is one, and returns the JSON answer, or a Failure saying why there is none.
|
||||
# Sends a request with the Authorization header given, the body as JSON where there is one, and returns the JSON answer, None where the answer has no body, or a Failure saying why there is none.
|
||||
Http = typing.Callable[[str, str, str, object], object]
|
||||
ToMarkdown = typing.Callable[[list[dict[str, typing.Any]]], list[str] | Refused | Failure]
|
||||
ToAdf = typing.Callable[[str], dict[str, typing.Any] | Failure]
|
||||
|
||||
|
||||
def http_json(method: str, url: str, authorization: str, body: object) -> object:
|
||||
@@ -68,11 +82,14 @@ class Issue:
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class JiraPlan:
|
||||
"""The plan under epic, read with the credentials env_file holds."""
|
||||
"""The plan under epic, read and written with the credentials env_file holds."""
|
||||
epic: Epic
|
||||
env_file: pathlib.Path
|
||||
http: Http = http_json
|
||||
to_markdown: ToMarkdown = adfs_to_markdown
|
||||
to_adf: ToAdf = markdown_to_adf
|
||||
# How a finished item moves; None where the config doesn't say, and then `finish` is a Failure.
|
||||
finish_by: Finish | None = None
|
||||
|
||||
@property
|
||||
def label(self) -> str:
|
||||
@@ -93,13 +110,159 @@ class JiraPlan:
|
||||
return next((issue for issue in issues if isinstance(issue, Failure)), None) or plan_of([issue for issue in issues if isinstance(issue, Issue)], self.epic, self.to_markdown)
|
||||
|
||||
def add(self, fields: dict[str, str], detail: str) -> Written | Failure:
|
||||
return Failure(READ_ONLY)
|
||||
"""Files the item as a child issue, which Jira ranks last in the backlog. No bar applies and the goals file isn't read, since a plan in Jira has no place for a formula or a bar yet (todo.md's item 384).
|
||||
|
||||
Jira takes the links after the issue. A link it refuses leaves the issue filed, so the write counts as landed, and a note names each link to make by hand."""
|
||||
filing = filing_of(fields, detail, self.epic)
|
||||
if isinstance(filing, Failure):
|
||||
return filing
|
||||
authorization = basic_auth(self.env_file)
|
||||
if isinstance(authorization, Failure):
|
||||
return authorization
|
||||
issue_fields = filing.fields
|
||||
if detail.strip():
|
||||
description = self.to_adf(detail)
|
||||
if isinstance(description, Failure):
|
||||
return Failure(f"cannot convert the item's detail to a Jira description: {description.reason}")
|
||||
issue_fields = issue_fields | {"description": description}
|
||||
version = self.fix_version(filing.release, authorization)
|
||||
if isinstance(version, Failure):
|
||||
return version
|
||||
if filing.blockers and (missing := self.missing_blocker(filing.blockers, authorization)):
|
||||
return missing
|
||||
created = self.http("POST", f"{self.epic.site}/rest/api/3/issue", authorization, {"fields": issue_fields | {"fixVersions": [{"name": version}]}, "properties": [{"key": PROPERTY, "value": filing.scores}]})
|
||||
if isinstance(created, Failure):
|
||||
return Failure(f"cannot file the item under {self.epic.key}: {created.reason}; {PERHAPS_FILED.format(epic=self.epic.key)}")
|
||||
key = created.get("key") if isinstance(created, dict) else None
|
||||
if not isinstance(key, str) or not ISSUE_KEY.fullmatch(key) or project_of(key) != project_of(self.epic.key):
|
||||
return Failure(f"Jira answered the new issue without an issue key in {project_of(self.epic.key)}; {PERHAPS_FILED.format(epic=self.epic.key)}")
|
||||
notes = []
|
||||
for blocker in filing.blockers:
|
||||
# Jira names the two ends by the link type's sides: the inward issue blocks the outward one, which then reads "is blocked by" it.
|
||||
linked = self.http("POST", f"{self.epic.site}/rest/api/3/issueLink", authorization, {"type": {"name": BLOCKS}, "inwardIssue": {"key": blocker}, "outwardIssue": {"key": key}})
|
||||
if isinstance(linked, Failure):
|
||||
notes.append(f"filed {key}, but cannot link it as blocked by {blocker}: {linked.reason}; link it in Jira")
|
||||
return Written(number(key), tuple(notes))
|
||||
|
||||
def fix_version(self, release: str, authorization: str) -> str | Failure:
|
||||
"""The name of the Jira project's Fix Version for release, which a project may spell with a leading v, as `earliest_release` reads it."""
|
||||
project = project_of(self.epic.key)
|
||||
versions = self.http("GET", f"{self.epic.site}/rest/api/3/project/{project}/versions", authorization, None)
|
||||
if isinstance(versions, Failure):
|
||||
return Failure(f"cannot read {project}'s Fix Versions: {versions.reason}")
|
||||
names = {name for version in versions if isinstance(version, dict) and isinstance(name := version.get("name"), str)} if isinstance(versions, list) else set()
|
||||
return next((name for name in (release, f"v{release}") if name in names), None) or Failure(f"the Jira project {project} has no Fix Version {release} or v{release}; create it in Jira, or file the item under a release it has")
|
||||
|
||||
def missing_blocker(self, blockers: tuple[str, ...], authorization: str) -> Failure | None:
|
||||
"""A Failure naming the first of blockers that is no open child of the epic. `item` reads only an open child as a blocker, so a link to any other issue would be lost on the next read."""
|
||||
answered = children(self.epic, authorization, self.http)
|
||||
if isinstance(answered, Failure):
|
||||
return answered
|
||||
held = {raw.get("key") for raw in answered if isinstance(raw, dict)}
|
||||
return next((Failure(f"{self.label} holds no item {number(blocker)} to be blocked by") for blocker in blockers if blocker not in held), None)
|
||||
|
||||
def edit(self, id_: int, fields: dict[str, str], detail: str | None) -> Written | Failure:
|
||||
return Failure(READ_ONLY)
|
||||
|
||||
def finish(self, id_: int) -> Written | Failure:
|
||||
return Failure(READ_ONLY)
|
||||
"""Moves item id_'s issue by the transition that the config names, to the status it names. Any open child of the epic may move, whoever filed it."""
|
||||
if self.finish_by is None:
|
||||
return Failure(f"the config names no transition to finish an item by: set `{JIRA_FINISH_TRANSITION}` and `{JIRA_FINISH_STATUS}`, as `project-config --help` shows")
|
||||
authorization = basic_auth(self.env_file)
|
||||
if isinstance(authorization, Failure):
|
||||
return authorization
|
||||
answered = children(self.epic, authorization, self.http)
|
||||
if isinstance(answered, Failure):
|
||||
return answered
|
||||
key = f"{project_of(self.epic.key)}-{id_}"
|
||||
if not any(isinstance(raw, dict) and raw.get("key") == key for raw in answered):
|
||||
return Failure(f"{self.label} holds no item {id_}")
|
||||
url = f"{self.epic.site}/rest/api/3/issue/{key}/transitions"
|
||||
offered = self.http("GET", url, authorization, None)
|
||||
if isinstance(offered, Failure):
|
||||
return Failure(f"cannot read {key}'s transitions: {offered.reason}")
|
||||
transition = transition_of(offered, key, self.finish_by)
|
||||
if isinstance(transition, Failure):
|
||||
return transition
|
||||
moved = self.http("POST", url, authorization, {"transition": {"id": transition}})
|
||||
return Failure(f"cannot move {key} by {self.finish_by.transition!r}: {moved.reason}; {PERHAPS_MOVED.format(key=key)}") if isinstance(moved, Failure) else Written(id_)
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Filing:
|
||||
"""An item checked and ready to file."""
|
||||
# The new issue's fields, without its description and its Fix Version.
|
||||
fields: dict[str, typing.Any]
|
||||
release: str
|
||||
# PROPERTY's value.
|
||||
scores: dict[str, typing.Any]
|
||||
# The key of each issue the item is blocked by.
|
||||
blockers: tuple[str, ...]
|
||||
|
||||
|
||||
def filing_of(fields: dict[str, str], detail: str, epic: Epic) -> Filing | Failure:
|
||||
"""The issue to file for an item with these fields under epic, or why a field cannot be filed."""
|
||||
named = cells(fields)
|
||||
summary = plain(named.get("Item", "")).strip()
|
||||
if not summary:
|
||||
return Failure("the item has no tagline")
|
||||
if unfit := unfit_text(summary, detail):
|
||||
return unfit
|
||||
release = named.get("Release", "")
|
||||
if parsed(release) is None:
|
||||
return Failure(f"the item's Release {release!r} is not a version such as 1.2.0")
|
||||
# Named so the shared messages read "item to file's L": they open with "item" and an ID, which this item has none of yet.
|
||||
levels = parse_scores("to file", named, SHAPE.score_columns)
|
||||
if isinstance(levels, Failure):
|
||||
return levels
|
||||
moves, exempt = named.get(MOVES, ""), named.get("Exempt", "")
|
||||
if isinstance(unfit_moves := parse_moves("to file", moves), Failure):
|
||||
return unfit_moves
|
||||
if not is_exempt(exempt):
|
||||
return Failure(f"the item's Exempt {exempt!r} is not empty or one of {', '.join(EXEMPTIONS[1:])}")
|
||||
blockers = parse_ids(named.get(BLOCKED_BY, ""))
|
||||
if blockers is None:
|
||||
return Failure(f"the item's {BLOCKED_BY} {named[BLOCKED_BY]!r} is not empty or IDs separated by \", \"")
|
||||
project = project_of(epic.key)
|
||||
issue_fields: dict[str, typing.Any] = {"project": {"key": project}, "parent": {"key": epic.key}, "issuetype": {"name": ISSUE_TYPE}, "summary": summary}
|
||||
if exempt == SECURITY:
|
||||
issue_fields["labels"] = [SECURITY]
|
||||
value = levels | {MOVES: moves, "Exempt": exempt, FILED_BY[0]: FILED_BY[1]}
|
||||
return Filing(issue_fields, release, value, tuple(f"{project}-{blocker}" for blocker in blockers))
|
||||
|
||||
|
||||
def offer_of(raw: object) -> tuple[str, str, str, str] | None:
|
||||
"""One transition Jira offers, as its ID, its name, the name of the status it leads to and the key of that status's category; None where raw holds no such transition."""
|
||||
to = raw.get("to") if isinstance(raw, dict) else None
|
||||
category = to.get("statusCategory") if isinstance(to, dict) else None
|
||||
if not isinstance(raw, dict) or not isinstance(to, dict) or not isinstance(category, dict):
|
||||
return None
|
||||
id_, name, status, key = raw.get("id"), raw.get("name"), to.get("name"), category.get("key")
|
||||
return (id_, name, status, key) if isinstance(id_, str) and isinstance(name, str) and isinstance(status, str) and isinstance(key, str) else None
|
||||
|
||||
|
||||
def transition_of(offered: object, key: str, finish: Finish) -> str | Failure:
|
||||
"""The ID of the transition finish names, among those Jira offered for the issue named key, which are the ones its present status has; or why none of them finishes the item."""
|
||||
raw = offered.get("transitions") if isinstance(offered, dict) else None
|
||||
found = [offer for each in raw if (offer := offer_of(each))] if isinstance(raw, list) else []
|
||||
if not isinstance(raw, list) or len(found) != len(raw):
|
||||
return Failure(f"Jira answered {key}'s transitions in a shape other than the one it documents")
|
||||
named = [each for each in found if each[1] == finish.transition]
|
||||
if not named:
|
||||
others = " and ".join(f"{name!r} to {status!r}" for _, name, status, _ in found)
|
||||
return Failure(f"{key} has no transition {finish.transition!r} from its status, " + (f"only {others}: move the issue in Jira to a status that has it, or name in `{JIRA_FINISH_TRANSITION}` one that leads to a done status" if found else "nor any other the account may make"))
|
||||
id_, _, status, category = next((each for each in named if each[2] == finish.status), named[0])
|
||||
if status != finish.status:
|
||||
return Failure(f"{key}'s transition {finish.transition!r} leads to the status {status!r}, not to {finish.status!r}, which `{JIRA_FINISH_STATUS}` names")
|
||||
# `children` reads an issue as finished by its status's category, so a move to any other category would leave the item in the plan.
|
||||
if category != DONE:
|
||||
return Failure(f"{key}'s transition {finish.transition!r} leads to the status {status!r}, which Jira doesn't count as done, so the item would stay in the plan: name a transition to a done status")
|
||||
return id_
|
||||
|
||||
|
||||
def project_of(key: str) -> str:
|
||||
"""The key of the Jira project an issue key lies in."""
|
||||
return key.rpartition("-")[0]
|
||||
|
||||
|
||||
def basic_auth(env_file: pathlib.Path) -> str | Failure:
|
||||
@@ -154,8 +317,8 @@ def issue_of(raw: object) -> Issue | Failure:
|
||||
|
||||
def plan_of(issues: list[Issue], epic: Epic, to_markdown: ToMarkdown) -> Plan | Failure:
|
||||
"""The plan the issues hold, in their order."""
|
||||
project = epic.key.rpartition("-")[0]
|
||||
if strangers := [issue.key for issue in issues if issue.key.rpartition("-")[0] != project]:
|
||||
project = project_of(epic.key)
|
||||
if strangers := [issue.key for issue in issues if project_of(issue.key) != project]:
|
||||
return Failure(f"{strangers[0]} is a child of {epic.key} in another Jira project, and an item's ID is its number in {project}; move it into {project} or out of the epic")
|
||||
ids = {issue.number for issue in issues}
|
||||
items = [item(issue, project, ids) for issue in issues]
|
||||
@@ -192,7 +355,7 @@ def item(issue: Issue, project: str, ids: set[int]) -> Item | Failure:
|
||||
scored = scores(issue.key, issue.scores)
|
||||
if isinstance(scored, Failure):
|
||||
return scored
|
||||
blockers = {number(key) for key in issue.blockers if key.rpartition("-")[0] == project}
|
||||
blockers = {number(key) for key in issue.blockers if project_of(key) == project}
|
||||
return Item(issue.number, release, scored[2], bold_cell(issue.summary), scored[0], scored[1], tuple(sorted(blockers & ids)), "")
|
||||
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"""The one way a tool reads or writes a project's plan: through the store its config names.
|
||||
|
||||
The config's `plan` setting names the backend. A path names a markdown file, todo.md. `jira:` and an epic's address name a Jira epic, whose open child issues `jira_epic` reads and nothing writes yet. An agent reads and changes the plan with `todo-item`, which works through the same store.
|
||||
The config's `plan` setting names the backend. A path names a markdown file, todo.md. `jira:` and an epic's address name a Jira epic, whose open child issues are the plan: `jira_epic` reads them, and files an item as a new child issue. An agent reads and changes the plan with `todo-item`, which works through the same store.
|
||||
|
||||
A tool that reads what a past commit held, such as `score-outcomes`, still parses that commit's todo.md itself, with `release_plan.todo_table`: only the markdown backend has commits, and todo.md's items 365, 366 and 368 port those tools to the other backends."""
|
||||
import dataclasses
|
||||
@@ -47,7 +47,7 @@ class Written:
|
||||
|
||||
|
||||
class PlanStore(typing.Protocol):
|
||||
"""A project's plan. plan_store.contract holds every backend that writes to the same behaviour; `jira_epic` only reads until todo.md's item 352. A write that fails leaves the plan as it was."""
|
||||
"""A project's plan. plan_store.contract holds every backend that writes to the same behaviour; `jira_epic` reads, files and finishes, and fails an edit until todo.md's item 382. A write that fails leaves the plan as it was, except where its Failure says the tracker may have taken the write all the same, as when Jira's answer to a new issue or to a move is lost."""
|
||||
|
||||
@property
|
||||
def label(self) -> str:
|
||||
@@ -157,7 +157,7 @@ def store(config: ProjectConfig) -> PlanStore:
|
||||
from plan_store.jira_epic import JiraPlan
|
||||
# load refuses a config that names an epic and no env-file.
|
||||
assert config.env_file is not None
|
||||
return JiraPlan(config.epic, config.env_file)
|
||||
return JiraPlan(config.epic, config.env_file, finish_by=config.jira_finish)
|
||||
|
||||
|
||||
def file_plan(config: ProjectConfig, path: pathlib.Path | None = None) -> FilePlan:
|
||||
|
||||
@@ -7,10 +7,11 @@ import unittest.mock
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from project_config.settings import Epic
|
||||
from project_config.settings import Epic, Finish
|
||||
from release_plan.todo_table import EXEMPTIONS
|
||||
from failure import Failure
|
||||
from plan_store import jira_epic
|
||||
from plan_store.stores import Plan
|
||||
from plan_store.stores import Plan, Written
|
||||
from adf_codec.convert import Refused
|
||||
from release_plan.release import release_of
|
||||
|
||||
@@ -209,17 +210,253 @@ class JiraPlan(unittest.TestCase):
|
||||
self.pages = [{"issues": [issue("OTHER-5")]}]
|
||||
self.assertNotIn("s3cret", self.store().read().reason) # type: ignore[union-attr]
|
||||
|
||||
def test_every_write_fails_since_the_store_only_reads(self):
|
||||
store = self.store()
|
||||
for written in (store.add({}, ""), store.edit(34, {"L": "2"}, None), store.finish(34)):
|
||||
with self.subTest(written=written):
|
||||
self.assertEqual(written, Failure("a plan in Jira is only read so far: file, edit and finish its issues in Jira"))
|
||||
def test_edit_fails_since_the_store_does_not_edit_yet(self):
|
||||
self.assertEqual(self.store().edit(34, {"L": "2"}, None), Failure("the loop doesn't edit an issue of a plan in Jira yet: edit it in Jira"))
|
||||
self.assertEqual(self.calls + self.epic_calls, [])
|
||||
|
||||
def test_names_itself_by_the_configs_spelling_and_no_commit_holds_it(self):
|
||||
self.assertEqual((self.store().label, self.store().tracked), ("jira:https://acme.atlassian.net/browse/ABC-12", None))
|
||||
|
||||
|
||||
ISSUES = "https://acme.atlassian.net/rest/api/3/issue"
|
||||
LINKS = "https://acme.atlassian.net/rest/api/3/issueLink"
|
||||
VERSIONS = "https://acme.atlassian.net/rest/api/3/project/ABC/versions"
|
||||
PERHAPS_FILED = "unless Jira refused the request, the issue may exist: look under ABC-12 before filing the item again"
|
||||
FIELDS = {"Release": "0.1.0", "Tagline": "Count the runs.", "L": "1", "E": "2", "I": "3", "S": "1", "Moves": "1 by 9"}
|
||||
PROPERTY = {"L": 1, "E": 2, "I": 3, "S": 1, "Moves": "1 by 9", "Exempt": "", "Filed by": "loop"}
|
||||
|
||||
|
||||
class Filing(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.env = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory())) / "acme.env"
|
||||
self.env.write_text("ATLASSIAN_EMAIL=me@example.com\nATLASSIAN_API_TOKEN=s3cret\n")
|
||||
self.env.chmod(0o600)
|
||||
self.calls: list[tuple[str, str, object]] = []
|
||||
self.open: list[dict[str, object]] = []
|
||||
self.created: object = {"id": "10040", "key": "ABC-40"}
|
||||
self.linked: object = None
|
||||
self.versions: object = [{"name": "0.1.0"}, {"name": "v0.2.0"}, "odd", {"name": ["0.1.0"]}, {"name": {"en": "0.1.0"}}]
|
||||
|
||||
def http(self, method: str, url: str, authorization: str, body: object) -> object:
|
||||
"""Stands in for Jira: answers the epic, self.versions for the project's Fix Versions, self.open to the search, self.created to a new issue and self.linked to a new link."""
|
||||
self.calls.append((method, url, body))
|
||||
assert authorization == AUTHORIZATION
|
||||
return {SEARCH: {"issues": self.open}, ISSUES: self.created, LINKS: self.linked, VERSIONS: self.versions}.get(url, {"key": "ABC-12"})
|
||||
|
||||
def to_adf(self, markdown: str) -> dict[str, object] | Failure:
|
||||
return adf(markdown)
|
||||
|
||||
def add(self, fields: dict[str, str] = FIELDS, detail: str = ""):
|
||||
return jira_epic.JiraPlan(EPIC, self.env, self.http, text_of, self.to_adf).add(fields, detail)
|
||||
|
||||
def sent(self, url: str) -> list[object]:
|
||||
return [body for _, sent_to, body in self.calls if sent_to == url]
|
||||
|
||||
def test_files_the_item_as_a_task_under_the_epic_marked_as_the_loops(self):
|
||||
self.assertEqual(self.add(), Written(40))
|
||||
self.assertEqual(self.calls, [("GET", VERSIONS, None), ("POST", ISSUES, {
|
||||
"fields": {"project": {"key": "ABC"}, "parent": {"key": "ABC-12"}, "issuetype": {"name": "Task"}, "summary": "Count the runs.", "fixVersions": [{"name": "0.1.0"}]},
|
||||
"properties": [{"key": "plan-item", "value": PROPERTY}],
|
||||
})])
|
||||
|
||||
def test_a_bold_tagline_is_filed_plain(self):
|
||||
self.add(FIELDS | {"Tagline": "**Count the runs.**"})
|
||||
self.assertEqual(self.sent(ISSUES)[0]["fields"]["summary"], "Count the runs.") # type: ignore[index]
|
||||
|
||||
def test_the_detail_is_the_description_as_adf(self):
|
||||
self.add(detail="Why it counts.")
|
||||
self.assertEqual(self.sent(ISSUES)[0]["fields"]["description"], adf("Why it counts.")) # type: ignore[index]
|
||||
|
||||
def test_a_security_finding_is_labelled_security(self):
|
||||
self.add(FIELDS | {"Exempt": "security"})
|
||||
sent, = self.sent(ISSUES)
|
||||
self.assertEqual((sent["fields"]["labels"], sent["properties"][0]["value"]["Exempt"]), (["security"], "security")) # type: ignore[index]
|
||||
|
||||
def test_no_other_item_is_labelled(self):
|
||||
self.add(FIELDS | {"Exempt": "owner"})
|
||||
self.assertNotIn("labels", self.sent(ISSUES)[0]["fields"]) # type: ignore[index]
|
||||
|
||||
def test_links_the_issue_as_blocked_by_each_blocker_once_filed(self):
|
||||
self.open = [issue("ABC-34"), issue("ABC-35")]
|
||||
self.assertEqual(self.add(FIELDS | {"Blocked by": "34, 35"}), Written(40))
|
||||
self.assertEqual([(method, url) for method, url, _ in self.calls][-3:], [("POST", ISSUES), ("POST", LINKS), ("POST", LINKS)])
|
||||
self.assertEqual(self.sent(LINKS), [{"type": {"name": "Blocks"}, "inwardIssue": {"key": f"ABC-{blocker}"}, "outwardIssue": {"key": "ABC-40"}} for blocker in (34, 35)])
|
||||
|
||||
def test_a_blocker_that_is_no_open_child_fails_before_anything_is_filed(self):
|
||||
self.open = [issue("ABC-34")]
|
||||
self.assertEqual(self.add(FIELDS | {"Blocked by": "34, 36"}), Failure("jira:https://acme.atlassian.net/browse/ABC-12 holds no item 36 to be blocked by"))
|
||||
self.assertEqual(self.sent(ISSUES), [])
|
||||
|
||||
def test_a_field_out_of_format_fails_before_any_request(self):
|
||||
cases = ({"L": "9"}, {"Release": "soon"}, {"Release": ""}, {"Moves": "much"}, {"Exempt": "whim"}, {"Blocked by": "ABC-34"}, {"Tagline": "Count\nthe runs."}, {"Tagline": " "})
|
||||
for change in cases:
|
||||
with self.subTest(change=change):
|
||||
self.assertIsInstance(self.add(FIELDS | change), Failure)
|
||||
self.assertEqual(self.calls, [])
|
||||
|
||||
def test_each_field_out_of_format_fails_saying_how(self):
|
||||
cases = (
|
||||
({"Tagline": "** **"}, "the item has no tagline"),
|
||||
({"L": "9"}, "item to file's L '9' is not a whole number from 1 to 4"),
|
||||
({"Exempt": "whim"}, f"the item's Exempt 'whim' is not empty or one of {', '.join(EXEMPTIONS[1:])}"),
|
||||
({"Blocked by": "ABC-34"}, "the item's Blocked by 'ABC-34' is not empty or IDs separated by \", \""),
|
||||
)
|
||||
for change, reason in cases:
|
||||
with self.subTest(change=change):
|
||||
self.assertEqual(self.add(FIELDS | change), Failure(reason))
|
||||
self.assertEqual(self.add({name: value for name, value in FIELDS.items() if name != "Tagline"}), Failure("the item has no tagline"))
|
||||
|
||||
def test_an_item_without_moves_files_with_none(self):
|
||||
self.assertEqual(self.add({name: value for name, value in FIELDS.items() if name != "Moves"}), Written(40))
|
||||
self.assertEqual(self.sent(ISSUES)[0]["properties"][0]["value"]["Moves"], "") # type: ignore[index]
|
||||
|
||||
def test_a_field_the_plan_does_not_have_is_a_programming_error(self):
|
||||
with self.assertRaises(ValueError):
|
||||
self.add(FIELDS | {"Colour": "red"})
|
||||
|
||||
def test_an_item_without_a_release_fails_naming_the_field(self):
|
||||
self.assertEqual(self.add({name: value for name, value in FIELDS.items() if name != "Release"}), Failure("the item's Release '' is not a version such as 1.2.0"))
|
||||
|
||||
def test_a_detail_that_does_not_convert_fails_before_any_request(self):
|
||||
self.to_adf = lambda markdown: Failure("docker is not running") # type: ignore[method-assign]
|
||||
self.assertEqual(self.add(detail="Why."), Failure("cannot convert the item's detail to a Jira description: docker is not running"))
|
||||
self.assertEqual(self.calls, [])
|
||||
|
||||
def test_an_item_jira_refuses_fails_with_jiras_reason(self):
|
||||
self.created = Failure("POST /rest/api/3/issue answered 400: Version name '0.1.0' is not valid")
|
||||
self.assertEqual(self.add(), Failure(f"cannot file the item under ABC-12: POST /rest/api/3/issue answered 400: Version name '0.1.0' is not valid; {PERHAPS_FILED}"))
|
||||
|
||||
def test_an_answer_that_names_no_issue_of_the_epics_project_fails(self):
|
||||
for answer in ({}, {"key": 7}, {"key": "OTHER-5"}, ["ABC-40"]):
|
||||
with self.subTest(answer=answer):
|
||||
self.created = answer
|
||||
self.assertEqual(self.add(), Failure(f"Jira answered the new issue without an issue key in ABC; {PERHAPS_FILED}"))
|
||||
|
||||
def test_a_link_jira_refuses_leaves_the_item_filed_with_a_note_and_the_other_links_made(self):
|
||||
refusal = "POST /rest/api/3/issueLink answered 404: No issue link type with name 'Blocks' found."
|
||||
self.open, self.linked = [issue("ABC-34"), issue("ABC-35")], Failure(refusal)
|
||||
self.assertEqual(self.add(FIELDS | {"Blocked by": "34, 35"}), Written(40, tuple(f"filed ABC-40, but cannot link it as blocked by ABC-{blocker}: {refusal}; link it in Jira" for blocker in (34, 35))))
|
||||
self.assertEqual(len(self.sent(LINKS)), 2)
|
||||
|
||||
def test_files_under_the_fix_version_as_the_project_spells_it(self):
|
||||
self.assertEqual(self.add(FIELDS | {"Release": "0.2.0"}), Written(40))
|
||||
self.assertEqual(self.sent(ISSUES)[0]["fields"]["fixVersions"], [{"name": "v0.2.0"}]) # type: ignore[index]
|
||||
|
||||
def test_a_release_the_project_has_no_fix_version_for_fails_before_anything_is_filed(self):
|
||||
for versions in ([{"name": "0.1.0"}], {"name": "0.3.0"}, [], 7):
|
||||
with self.subTest(versions=versions):
|
||||
self.versions = versions
|
||||
self.assertEqual(self.add(FIELDS | {"Release": "0.3.0"}), Failure("the Jira project ABC has no Fix Version 0.3.0 or v0.3.0; create it in Jira, or file the item under a release it has"))
|
||||
self.assertEqual(self.sent(ISSUES), [])
|
||||
|
||||
def test_fix_versions_that_cannot_be_read_fail_before_anything_is_filed(self):
|
||||
self.versions = Failure("GET /rest/api/3/project/ABC/versions answered 403: Forbidden")
|
||||
self.assertEqual(self.add(), Failure("cannot read ABC's Fix Versions: GET /rest/api/3/project/ABC/versions answered 403: Forbidden"))
|
||||
self.assertEqual(self.sent(ISSUES), [])
|
||||
|
||||
def test_what_it_files_reads_back_as_the_item(self):
|
||||
self.add(FIELDS | {"Exempt": "owner"}, "Why it counts.")
|
||||
sent, = self.sent(ISSUES)
|
||||
raw = {"key": "ABC-40", "fields": sent["fields"] | {"issuelinks": []}, "properties": {entry["key"]: entry["value"] for entry in sent["properties"]}} # type: ignore[index, operator, union-attr]
|
||||
filed = jira_epic.issue_of(raw)
|
||||
assert isinstance(filed, jira_epic.Issue), filed
|
||||
plan = jira_epic.plan_of([filed], EPIC, lambda documents: [text_of(document) for document in documents])
|
||||
assert isinstance(plan, Plan), plan
|
||||
item, = plan.items
|
||||
self.assertEqual((item.id, item.release, item.exempt, item.tagline, item.moves, item.detail), (40, release_of("0.1.0"), "owner", "**Count the runs.**", (("1", 9),), "Why it counts."))
|
||||
self.assertEqual({name: item.scores[name] for name in "LEIS"}, {"L": 1, "E": 2, "I": 3, "S": 1})
|
||||
|
||||
def test_a_missing_env_file_fails_before_any_request(self):
|
||||
self.env.unlink()
|
||||
self.assertIsInstance(self.add(), Failure)
|
||||
self.assertEqual(self.calls, [])
|
||||
|
||||
|
||||
TRANSITIONS = "https://acme.atlassian.net/rest/api/3/issue/ABC-34/transitions"
|
||||
|
||||
|
||||
def transition(id_: str, name: str, status: str, category: str = "done") -> dict[str, object]:
|
||||
return {"id": id_, "name": name, "to": {"name": status, "statusCategory": {"key": category}}}
|
||||
|
||||
|
||||
class Finishing(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.env = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory())) / "acme.env"
|
||||
self.env.write_text("ATLASSIAN_EMAIL=me@example.com\nATLASSIAN_API_TOKEN=s3cret\n")
|
||||
self.env.chmod(0o600)
|
||||
self.calls: list[tuple[str, str, object]] = []
|
||||
self.open = [issue("ABC-34"), issue("ABC-35")]
|
||||
self.transitions: object = {"transitions": [transition("11", "Start", "In Progress", "indeterminate"), transition("31", "Mark as done", "Done")]}
|
||||
self.moved: object = None
|
||||
|
||||
def http(self, method: str, url: str, authorization: str, body: object) -> object:
|
||||
"""Stands in for Jira: answers the epic, self.open to the search, self.transitions for ABC-34's transitions and self.moved to a transition of it."""
|
||||
self.calls.append((method, url, body))
|
||||
assert authorization == AUTHORIZATION
|
||||
if url == TRANSITIONS:
|
||||
return self.transitions if method == "GET" else self.moved
|
||||
return {SEARCH: {"issues": self.open}}.get(url, {"key": "ABC-12"})
|
||||
|
||||
def finish(self, id_: int = 34, by: Finish | None = Finish("Mark as done", "Done")):
|
||||
return jira_epic.JiraPlan(EPIC, self.env, self.http, text_of, finish_by=by).finish(id_)
|
||||
|
||||
def posts(self) -> list[tuple[str, str, object]]:
|
||||
return [call for call in self.calls if call[0] == "POST" and call[1] != SEARCH]
|
||||
|
||||
def test_moves_the_issue_by_the_transition_the_config_names(self):
|
||||
self.assertEqual(self.finish(), Written(34))
|
||||
self.assertEqual(self.posts(), [("POST", TRANSITIONS, {"transition": {"id": "31"}})])
|
||||
|
||||
def test_a_config_that_names_no_transition_fails_before_any_request(self):
|
||||
self.assertEqual(self.finish(by=None), Failure("the config names no transition to finish an item by: set `jira-finish-transition` and `jira-finish-status`, as `project-config --help` shows"))
|
||||
self.assertEqual(self.calls, [])
|
||||
|
||||
def test_an_issue_that_is_no_open_child_of_the_epic_is_not_moved(self):
|
||||
self.assertEqual(self.finish(36), Failure("jira:https://acme.atlassian.net/browse/ABC-12 holds no item 36"))
|
||||
self.assertEqual(self.posts(), [])
|
||||
|
||||
def test_a_transition_the_issue_does_not_have_fails_naming_those_it_has(self):
|
||||
self.assertEqual(self.finish(by=Finish("Close", "Done")), Failure("ABC-34 has no transition 'Close' from its status, only 'Start' to 'In Progress' and 'Mark as done' to 'Done': move the issue in Jira to a status that has it, or name in `jira-finish-transition` one that leads to a done status"))
|
||||
self.assertEqual(self.posts(), [])
|
||||
|
||||
def test_a_transition_that_leads_to_another_status_fails(self):
|
||||
self.assertEqual(self.finish(by=Finish("Mark as done", "Closed")), Failure("ABC-34's transition 'Mark as done' leads to the status 'Done', not to 'Closed', which `jira-finish-status` names"))
|
||||
self.assertEqual(self.posts(), [])
|
||||
|
||||
def test_two_transitions_share_the_name_and_the_one_to_the_status_is_made(self):
|
||||
self.transitions = {"transitions": [transition("30", "Close", "Rejected"), transition("31", "Close", "Done")]}
|
||||
self.assertEqual(self.finish(by=Finish("Close", "Done")), Written(34))
|
||||
self.assertEqual(self.posts(), [("POST", TRANSITIONS, {"transition": {"id": "31"}})])
|
||||
|
||||
def test_a_status_jira_does_not_count_as_done_fails_since_the_item_would_stay_in_the_plan(self):
|
||||
self.assertEqual(self.finish(by=Finish("Start", "In Progress")), Failure("ABC-34's transition 'Start' leads to the status 'In Progress', which Jira doesn't count as done, so the item would stay in the plan: name a transition to a done status"))
|
||||
self.assertEqual(self.posts(), [])
|
||||
|
||||
def test_an_issue_with_no_transition_fails_saying_so(self):
|
||||
self.transitions = {"transitions": []}
|
||||
self.assertEqual(self.finish(), Failure("ABC-34 has no transition 'Mark as done' from its status, nor any other the account may make"))
|
||||
|
||||
def test_transitions_that_cannot_be_read_fail(self):
|
||||
self.transitions = Failure("HTTP 403")
|
||||
self.assertEqual(self.finish(), Failure("cannot read ABC-34's transitions: HTTP 403"))
|
||||
|
||||
def test_transitions_in_another_shape_fail(self):
|
||||
odd = [transition(31, "Mark as done", "Done"), transition("31", None, "Done"), transition("31", "Mark as done", ["Done"]), transition("31", "Mark as done", "Done", 4), {"id": "31", "name": "Mark as done", "to": "Done"}, {"id": "31", "name": "Mark as done", "to": {"name": "Done"}}, "odd"] # type: ignore[arg-type]
|
||||
for answered in ([], {"transitions": "none"}, *({"transitions": [each]} for each in odd)):
|
||||
with self.subTest(answered=answered):
|
||||
self.transitions = answered
|
||||
self.assertEqual(self.finish(), Failure("Jira answered ABC-34's transitions in a shape other than the one it documents"))
|
||||
|
||||
def test_a_move_jira_refuses_fails_with_jiras_reason(self):
|
||||
self.moved = Failure("HTTP 400: Resolution is required")
|
||||
self.assertEqual(self.finish(), Failure("cannot move ABC-34 by 'Mark as done': HTTP 400: Resolution is required; unless Jira refused the request, the issue may have moved: look at ABC-34 before finishing the item again"))
|
||||
|
||||
def test_a_missing_env_file_fails_before_any_request(self):
|
||||
self.env.unlink()
|
||||
self.assertIsInstance(self.finish(), Failure)
|
||||
self.assertEqual(self.calls, [])
|
||||
|
||||
|
||||
class Requests(unittest.TestCase):
|
||||
def test_sends_each_request_through_the_shared_client_with_jiras_error_messages(self):
|
||||
with unittest.mock.patch.object(jira_epic.json_request, "http_json", return_value={"issues": []}) as sent:
|
||||
|
||||
@@ -8,7 +8,7 @@ import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from project_config.settings import DEFAULT_FLOOR, Epic, ProjectConfig, SETTINGS
|
||||
from project_config.settings import DEFAULT_FLOOR, Epic, Finish, ProjectConfig, SETTINGS
|
||||
from failure import Failure
|
||||
from record_store.stores import FileStore
|
||||
from plan_store.contract import FIRST, MOVES, PlanStoreContract, SECOND
|
||||
@@ -210,6 +210,11 @@ class Store(unittest.TestCase):
|
||||
picked = stores.store(self.config(epic=epic, env_file=pathlib.Path("/secrets/acme.env")))
|
||||
self.assertEqual(picked, JiraPlan(epic, pathlib.Path("/secrets/acme.env"), picked.http))
|
||||
|
||||
def test_an_epic_finishes_an_item_as_the_config_says(self):
|
||||
finish = Finish("Mark as done", "Done")
|
||||
picked = stores.store(self.config(epic=Epic("https://acme.atlassian.net", "ABC-12"), env_file=pathlib.Path("/secrets/acme.env"), jira_finish=finish))
|
||||
self.assertEqual(picked.finish_by, finish)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@@ -20,25 +20,50 @@ starts with / or ~/. In a worktree, a "checkout:" path is the worktree's own fil
|
||||
changelog = "checkout:CHANGELOG.md"
|
||||
goals-and-audience = "folder:goals.md"
|
||||
principles = "folder:principles"
|
||||
standards = "~/.claude/skills/larv-review/standards"
|
||||
|
||||
`principles` and `standards` name the folders the reviewers hold the project to: the technical
|
||||
principles and the review standards. A standards folder must hold quality.md, prose.md, comments.md
|
||||
and readme.md, since the reviewers and the rules name those files.
|
||||
|
||||
`plan` may name a Jira Cloud epic in place of a path, as "jira:" and the epic's address:
|
||||
"jira:https://acme.atlassian.net/browse/ABC-12". The plan is then the epic's open child issues, in
|
||||
Jira's backlog order, and `project-config plan` prints the setting as the config spells it. Such a
|
||||
config must set `env-file`, and that file must hold ATLASSIAN_EMAIL and ATLASSIAN_API_TOKEN.
|
||||
|
||||
`jira-finish-transition` and `jira-finish-status` are optional settings, set together and only
|
||||
beside such a plan, since each Jira workflow differs. `todo-item finish` moves an item's issue by
|
||||
the workflow transition the first names. That transition must lead to the status the second names,
|
||||
which must be one Jira counts as done. Write both names as Jira shows them:
|
||||
|
||||
jira-finish-transition = "Mark as done"
|
||||
jira-finish-status = "Done"
|
||||
|
||||
Where the config leaves them out, `todo-item finish` fails in a Jira plan. Each is printed with the others only where it is set.
|
||||
|
||||
`goals-and-audience` may name a Jira Cloud epic the same way, where `plan` names one too. The
|
||||
epic's description is then the goals file, with ## Goals and ## Audience as headings, and
|
||||
`project-config goals-and-audience` prints the setting as the config spells it. The description is
|
||||
only read: edit it in Jira.
|
||||
|
||||
Each record, `decisions`, `score-anchors`, `comprehension-history`, `reading-cost` and `changelog`,
|
||||
may name a Confluence Cloud page in place of a path, as "confluence:" and the page's address, with or
|
||||
without the title at its end: "confluence:https://acme.atlassian.net/wiki/spaces/ENG/pages/2293761".
|
||||
The record is then that page's text, which `project-record` reads and writes as markdown, and
|
||||
`project-config <record>` prints the setting as the config spells it. A mention or a macro on the
|
||||
page reads as plain text, and a save writes that text in its place. Such a config must set
|
||||
`env-file`, holding ATLASSIAN_EMAIL and ATLASSIAN_API_TOKEN, as for a Jira epic.
|
||||
`decisions` and `comprehension-history` may name a page only where `plan` names a Jira epic, since
|
||||
rule-hook ranks a plan kept as a file before tool calls, and a read from Confluence mustn't hold it up.
|
||||
|
||||
`env-file` is an optional setting: the file of KEY=value credentials the project's tools read,
|
||||
a path that starts with / or ~/ and lies outside the checkout and the config's folder, such as
|
||||
"~/.claude-projects/acme-billing.env". Where it is left out, the project has no credentials file, and
|
||||
a tool that needs one fails naming the setting. It is printed with the others only where it is set.
|
||||
|
||||
`touch-predictions` is an optional setting, a path spelt as `changelog`'s is: the record where
|
||||
`touch-predictions record` appends what each chunk was predicted to touch beside what it touched. Left
|
||||
out, the project keeps no such record. It is printed with the others only where it is set.
|
||||
`touch-predictions` is an optional setting, a path spelt as the others are, never a page: the record
|
||||
where `touch-predictions record` appends what each chunk was predicted to touch beside what it touched.
|
||||
Left out, the project keeps no such record. It is printed with the others only where it is set.
|
||||
|
||||
`notifier` is an optional setting, "mattermost" or "slack": the service that sends loop-claude's DMs and
|
||||
`notify`'s messages to the human. Setting it requires `env-file`, which holds that service's keys;
|
||||
@@ -95,13 +120,14 @@ and its commits and pull request are titled "ABC-123 - …".
|
||||
Exit 1, naming each fault on stderr, where no config names the checkout, or its config leaves out a
|
||||
setting, names an unknown one, misspells a path, a language or a template, sets `wait-for-approval` or
|
||||
`tooling-on-host` to anything but true or false, sets `notifier` to anything but mattermost or slack or
|
||||
without `env-file`, or sets `readability-floor` to anything but a number
|
||||
from 1 to 10, and where `env-file`, `notifier` or `touch-predictions` is asked for and not set. No path setting has a default.
|
||||
without `env-file`, sets `jira-finish-transition` or `jira-finish-status` to anything but a name, without the other or
|
||||
without a `plan` in Jira, or sets `readability-floor` to anything but a number
|
||||
from 1 to 10, and where `env-file`, `jira-finish-transition`, `jira-finish-status`, `notifier` or `touch-predictions` is asked for and not set. No path setting has a default.
|
||||
"""
|
||||
import pathlib
|
||||
import sys
|
||||
|
||||
from project_config.settings import CONFIG, DEFAULT_FLOOR, ENV_FILE, load, NOTIFIER, OPTIONAL, ProjectConfig, READABILITY_FLOOR, SETTINGS, TOOLING_ON_HOST, Unnamed, WAIT_FOR_APPROVAL
|
||||
from project_config.settings import CONFIG, DEFAULT_FLOOR, ENV_FILE, JIRA_FINISH_STATUS, JIRA_FINISH_TRANSITION, load, NOTIFIER, OPTIONAL, ProjectConfig, READABILITY_FLOOR, SETTINGS, TOOLING_ON_HOST, Unnamed, WAIT_FOR_APPROVAL
|
||||
from failure import Failure
|
||||
from git_cli.git_repo import git, Git
|
||||
from project_config import templates
|
||||
@@ -128,7 +154,7 @@ def main(argv: list[str]) -> int:
|
||||
if argv and argv[0] in config.texts:
|
||||
print(config.texts[argv[0]])
|
||||
return 0
|
||||
paths = {**config.places, **({ENV_FILE: str(config.env_file)} if config.env_file else {}), **({NOTIFIER: config.notifier} if config.notifier else {})}
|
||||
paths = {**config.places, **({ENV_FILE: str(config.env_file)} if config.env_file else {}), **({NOTIFIER: config.notifier} if config.notifier else {}), **({JIRA_FINISH_TRANSITION: config.jira_finish.transition, JIRA_FINISH_STATUS: config.jira_finish.status} if config.jira_finish else {})}
|
||||
if argv and argv[0] not in paths:
|
||||
print(f"{config.folder / CONFIG} sets no `{argv[0]}`", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
@@ -15,7 +15,7 @@ from project_config import templates
|
||||
PROJECTS = ".claude-projects"
|
||||
CONFIG = "config.toml"
|
||||
# Every path a project sets, by its role. Three readers, seated as the human who writes the config, picked the spelling from four candidates. They picked role names over file names, which a client's project doesn't share.
|
||||
SETTINGS = ("plan", "working-rules", "decisions", "score-anchors", "comprehension-history", "reading-cost", "changelog", "goals-and-audience", "principles")
|
||||
SETTINGS = ("plan", "working-rules", "decisions", "score-anchors", "comprehension-history", "reading-cost", "changelog", "goals-and-audience", "principles", "standards")
|
||||
# They also picked a prefix over bare relative paths: each line says its own place, and a relative path with no prefix fails instead of landing somewhere by default.
|
||||
SPELLING = '"checkout:<path>" for a path in the checkout, "folder:<path>" for one in the config\'s folder, or a path that starts with / or ~/'
|
||||
# A path setting a project may leave out: the file of KEY=value credentials its tools read. It has no default either: a project without it asks for no credentials, and never reads another project's.
|
||||
@@ -39,21 +39,26 @@ PULL_REQUEST_TITLE = "pull-request-title"
|
||||
BRANCH = "branch"
|
||||
# An optional path setting: main's help says what it places.
|
||||
TOUCH_PREDICTIONS = "touch-predictions"
|
||||
OPTIONAL = (BRANCH, COMMIT_TITLE, ENV_FILE, LANGUAGE, NOTIFIER, PULL_REQUEST_TITLE, READABILITY_FLOOR, TOOLING_ON_HOST, TOUCH_PREDICTIONS, WAIT_FOR_APPROVAL)
|
||||
# Two optional settings, each a name, set together and only where `plan` names a Jira epic: the name of the workflow transition that finishes an item, and of the status it must lead to. Three readers, seated as the human who writes a client's config, picked the spelling from four candidates: two flat keys, as the other settings are, with a prefix that says what they apply to.
|
||||
JIRA_FINISH_TRANSITION = "jira-finish-transition"
|
||||
JIRA_FINISH_STATUS = "jira-finish-status"
|
||||
JIRA_FINISH = (JIRA_FINISH_TRANSITION, JIRA_FINISH_STATUS)
|
||||
OPTIONAL = (BRANCH, COMMIT_TITLE, ENV_FILE, JIRA_FINISH_STATUS, JIRA_FINISH_TRANSITION, LANGUAGE, NOTIFIER, PULL_REQUEST_TITLE, READABILITY_FLOOR, TOOLING_ON_HOST, TOUCH_PREDICTIONS, WAIT_FOR_APPROVAL)
|
||||
# What opens a setting that names a Jira Cloud epic in place of a path: `jira:`, then the epic's address as the browser shows it. The settings below may name an epic; each reads its own part of it.
|
||||
JIRA = "jira:"
|
||||
EPIC_SPELLINGS = {
|
||||
"goals-and-audience": '"jira:https://<site>/browse/<epic\'s key>" for goals and audience kept in a Jira Cloud epic\'s description',
|
||||
"plan": '"jira:https://<site>/browse/<epic\'s key>" for a plan kept as a Jira Cloud epic\'s child issues',
|
||||
}
|
||||
# The settings that each name a record, a document a project keeps beside its plan. Each may name a Confluence Cloud page in place of a path: `confluence:`, then the page's address as the browser shows it, whose last part, the title, may be left out.
|
||||
RECORDS = ("decisions", "score-anchors", "comprehension-history", "reading-cost", "changelog")
|
||||
CONFLUENCE = "confluence:"
|
||||
# The records that ranking a plan reads.
|
||||
RANKED = ("decisions", "comprehension-history")
|
||||
PAGE_SPELLING = '"confluence:https://<site>/wiki/spaces/<space>/pages/<page ID>" for a record kept on a Confluence Cloud page'
|
||||
OUTSIDE = "a path that starts with / or ~/ and lies outside the checkout and the config's folder, so that no git remote receives the credentials"
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Unnamed(Failure):
|
||||
"""No config names a checkout here: none names the one asked for, or git finds no checkout. A reader of titles takes them bare there, as in a third party's clone; a config that is faulty or cannot be read is a plain Failure."""
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Epic:
|
||||
"""A Jira Cloud epic: site is its site's address, such as https://acme.atlassian.net, and key its issue key, such as ABC-12."""
|
||||
@@ -66,9 +71,29 @@ class Epic:
|
||||
return f"{JIRA}{self.site}/browse/{self.key}"
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Finish:
|
||||
"""How a finished item of a Jira plan moves: by the workflow transition named transition, which must lead to the status named status."""
|
||||
transition: str
|
||||
status: str
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Page:
|
||||
"""A Confluence Cloud page: site is its site's address, such as https://acme.atlassian.net, page_id its number, and spelling the setting's value as the config writes it."""
|
||||
site: str
|
||||
page_id: str
|
||||
spelling: str
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Unnamed(Failure):
|
||||
"""No config names a checkout here: none names the one asked for, or git fails there, as outside a checkout. A config that is faulty or cannot be read is a plain Failure."""
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class ProjectConfig:
|
||||
"""folder is `~/.claude-projects/<key>`, top is the worktree that asked, and paths holds each of SETTINGS as an absolute path, except `plan` and `goals-and-audience` where they are kept in Jira."""
|
||||
"""folder is `~/.claude-projects/<key>`, top is the worktree that asked, and paths holds each of SETTINGS as an absolute path, except three kinds that pages or epics hold instead: `plan` and `goals-and-audience` where they are kept in Jira, and a record kept on a Confluence page."""
|
||||
key: str
|
||||
folder: pathlib.Path
|
||||
top: pathlib.Path
|
||||
@@ -88,6 +113,10 @@ class ProjectConfig:
|
||||
goals_epic: Epic | None = None
|
||||
# The config's `notifier`, or None where it names none.
|
||||
notifier: Notifier | None = None
|
||||
# The config's `jira-finish-transition` and `jira-finish-status`, or None where it sets neither.
|
||||
jira_finish: Finish | None = None
|
||||
# The Confluence page of each record the config keeps on one, by the record's setting.
|
||||
pages: dict[str, Page] = dataclasses.field(default_factory=dict)
|
||||
|
||||
@property
|
||||
def plan_file(self) -> pathlib.Path | None:
|
||||
@@ -101,9 +130,9 @@ class ProjectConfig:
|
||||
|
||||
@property
|
||||
def places(self) -> dict[str, str]:
|
||||
"""Where each of SETTINGS is kept, in SETTINGS' order, then TOUCH_PREDICTIONS where the config sets it: a path, or the epic as the config spells it."""
|
||||
epics = {"plan": self.epic, "goals-and-audience": self.goals_epic}
|
||||
return {name: epic.spelling if (epic := epics.get(name)) else str(self.paths[name]) for name in (*SETTINGS, TOUCH_PREDICTIONS) if epics.get(name) or name in self.paths}
|
||||
"""Where each of SETTINGS is kept, in SETTINGS' order, then TOUCH_PREDICTIONS where the config sets it: a path, or the epic or page as the config spells it."""
|
||||
spelt = {name: kept.spelling for name, kept in {"plan": self.epic, "goals-and-audience": self.goals_epic, **self.pages}.items() if kept}
|
||||
return {name: spelt[name] if name in spelt else str(self.paths[name]) for name in (*SETTINGS, TOUCH_PREDICTIONS) if name in spelt or name in self.paths}
|
||||
|
||||
@property
|
||||
def texts(self) -> dict[str, str]:
|
||||
@@ -142,24 +171,32 @@ def load(top: pathlib.Path, main: pathlib.Path, home: pathlib.Path) -> ProjectCo
|
||||
file, values = named[0]
|
||||
paths = {name: placed(values[name], top, file.parent, home) for name in (*SETTINGS, TOUCH_PREDICTIONS) if name in values}
|
||||
epics = {name: epic_of(values.get(name)) for name in EPIC_SPELLINGS}
|
||||
pages = {name: page for name in RECORDS if (page := page_of(values.get(name)))}
|
||||
env_file = anywhere(values.get(ENV_FILE), home)
|
||||
misplaced = ENV_FILE in values and (env_file is None or lies_in(env_file, top, main, file.parent))
|
||||
notifier = next((name for name in NOTIFIERS if name == values.get(NOTIFIER)), None)
|
||||
waits = values.get(WAIT_FOR_APPROVAL, False)
|
||||
on_host = values.get(TOOLING_ON_HOST, False)
|
||||
floor = floor_of(values[READABILITY_FLOOR]) if READABILITY_FLOOR in values else DEFAULT_FLOOR
|
||||
finish = [name for setting in JIRA_FINISH if (name := name_of(values.get(setting)))]
|
||||
checks = {LANGUAGE: language_fault, COMMIT_TITLE: templates.title_fault, PULL_REQUEST_TITLE: templates.title_fault, BRANCH: templates.branch_fault}
|
||||
faults = [
|
||||
*(f"`{name}` is missing" for name in SETTINGS if name not in values),
|
||||
*(f"`{name}` is not a setting" for name in values if name not in (*SETTINGS, *OPTIONAL)),
|
||||
*(f"`{name}` is {values[name]!r}, not {SPELLING}" for name, path in paths.items() if path is None and name not in EPIC_SPELLINGS),
|
||||
*(f"`{name}` is {values[name]!r}, not {SPELLING}" for name, path in paths.items() if path is None and name not in (*EPIC_SPELLINGS, *RECORDS)),
|
||||
*(f"`{name}` is {values[name]!r}, not {SPELLING}, or {EPIC_SPELLINGS[name]}" for name in EPIC_SPELLINGS if name in values and paths[name] is None and epics[name] is None),
|
||||
*(f"`{name}` is {values[name]!r}, not {SPELLING}, or {PAGE_SPELLING}" for name in RECORDS if name in values and paths[name] is None and name not in pages),
|
||||
*(f"`{name}` names a Jira epic, so `{ENV_FILE}` must name the file that holds its credentials" for name, epic in epics.items() if epic and ENV_FILE not in values),
|
||||
# rule-hook ranks a plan kept as a file before tool calls, inside the hook's time limit, which a read from Jira mustn't hold up.
|
||||
*(f"`{name}` names a Confluence page, so `{ENV_FILE}` must name the file that holds its credentials" for name in pages if ENV_FILE not in values),
|
||||
# rule-hook ranks a plan kept as a file before tool calls, inside the hook's time limit, which a read from Jira or Confluence mustn't hold up.
|
||||
*(["`goals-and-audience` names a Jira epic, so `plan` must name one too"] if epics["goals-and-audience"] and not epics["plan"] else []),
|
||||
*(f"`{name}` names a Confluence page, so `plan` must name a Jira epic" for name in RANKED if name in pages and not epics["plan"]),
|
||||
*([f"`{ENV_FILE}` is {values[ENV_FILE]!r}, not {OUTSIDE}"] if misplaced else []),
|
||||
*([f"`{NOTIFIER}` is {values[NOTIFIER]!r}, not {' or '.join(NOTIFIERS)}"] if NOTIFIER in values and values[NOTIFIER] not in NOTIFIERS else []),
|
||||
*([f"`{NOTIFIER}` names a notifier, so `{ENV_FILE}` must name the file that holds its credentials"] if NOTIFIER in values and ENV_FILE not in values else []),
|
||||
*(f"`{name}` is {values[name]!r}, not the name Jira shows, such as \"{example}\"" for name, example in zip(JIRA_FINISH, ("Mark as done", "Done")) if name in values and not name_of(values[name])),
|
||||
*(f"`{name}` is set, so `{other}` must be too" for name, other in (JIRA_FINISH, JIRA_FINISH[::-1]) if name in values and other not in values),
|
||||
*(f"`{name}` is set, so `plan` must name a Jira epic" for name in JIRA_FINISH if name in values and not epics["plan"]),
|
||||
*(f"`{name}` is {value!r}, not true or false" for name, value in ((WAIT_FOR_APPROVAL, waits), (TOOLING_ON_HOST, on_host)) if not isinstance(value, bool)),
|
||||
*([f"`{READABILITY_FLOOR}` is {values[READABILITY_FLOOR]!r}, not a number from 1 to 10; write a bare number, such as `{READABILITY_FLOOR} = 7.0`"] if floor is None else []),
|
||||
*(f"`{name}` is {values[name]!r}, {fault}" for name, check in checks.items() if name in values and (fault := check(values[name]))),
|
||||
@@ -168,7 +205,12 @@ def load(top: pathlib.Path, main: pathlib.Path, home: pathlib.Path) -> ProjectCo
|
||||
return Failure(f"{file}: {'; '.join(faults)}. The settings are {', '.join(SETTINGS)}, and optionally {', '.join(OPTIONAL[:-1])} and {OPTIONAL[-1]}.")
|
||||
# faults names a floor the config misspells.
|
||||
assert floor is not None
|
||||
return ProjectConfig(file.parent.name, file.parent, top, {name: path for name, path in paths.items() if path}, env_file, waits is True, on_host is True, floor, **{name.replace("-", "_"): str(values[name]) for name in checks if name in values}, epic=epics["plan"], goals_epic=epics["goals-and-audience"], notifier=notifier)
|
||||
return ProjectConfig(file.parent.name, file.parent, top, {name: path for name, path in paths.items() if path}, env_file, waits is True, on_host is True, floor, **{name.replace("-", "_"): str(values[name]) for name in checks if name in values}, epic=epics["plan"], goals_epic=epics["goals-and-audience"], notifier=notifier, jira_finish=Finish(*finish) if finish else None, pages=pages)
|
||||
|
||||
|
||||
def name_of(value: object) -> str | None:
|
||||
"""The name value holds, of a Jira transition or status; None where it holds none."""
|
||||
return value if isinstance(value, str) and value.strip() else None
|
||||
|
||||
|
||||
def epic_of(value: object) -> Epic | None:
|
||||
@@ -177,6 +219,12 @@ def epic_of(value: object) -> Epic | None:
|
||||
return Epic(spelt.group(1), spelt.group(2)) if spelt else None
|
||||
|
||||
|
||||
def page_of(value: object) -> Page | None:
|
||||
"""The page a setting's value spells; None where it spells none. Only https, as for an epic."""
|
||||
spelt = isinstance(value, str) and re.fullmatch(rf"{CONFLUENCE}(https://[A-Za-z0-9.-]+(?::[0-9]+)?)/wiki/spaces/[^/?#]+/pages/([0-9]+)(?:/[^/?#]*)?", value)
|
||||
return Page(spelt.group(1), spelt.group(2), spelt.string) if spelt else None
|
||||
|
||||
|
||||
def floor_of(value: object) -> decimal.Decimal | None:
|
||||
"""The floor value spells, an integer or a float from 1 to 10; None where it spells none. Not a string, nor a boolean, which Python counts as an integer, nor TOML's nan or inf."""
|
||||
# An integer too large for a float makes math.isfinite raise, so only a float is checked.
|
||||
|
||||
@@ -9,10 +9,10 @@ import unittest.mock
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from project_config.settings import env_files, Epic, held, load, NOTIFIERS, OUTSIDE, ProjectConfig, SETTINGS, Unnamed
|
||||
from project_config.settings import env_files, Epic, Finish, held, load, NOTIFIERS, OUTSIDE, Page, ProjectConfig, SETTINGS, Unnamed
|
||||
from failure import Failure
|
||||
from test_env import isolated_env
|
||||
from project_config.main import title_templates
|
||||
from project_config.main import located, title_templates
|
||||
from project_config.templates import Titles
|
||||
|
||||
TOOL = pathlib.Path(__file__).resolve().parents[1] / "project-config"
|
||||
@@ -27,10 +27,12 @@ reading-cost = "folder:docs/reading-cost.md"
|
||||
changelog = "checkout:CHANGELOG.md"
|
||||
goals-and-audience = "folder:goals.md"
|
||||
principles = "~/.claude/principles"
|
||||
standards = "~/.claude/skills/larv-review/standards"
|
||||
"""
|
||||
|
||||
JIRA_PLAN = "jira:https://acme.atlassian.net/browse/ABC-12"
|
||||
JIRA_CLIENT = CLIENT.replace("folder:todo.md", JIRA_PLAN) + 'env-file = "~/acme.env"\n'
|
||||
DECISIONS_PAGE = "confluence:https://acme.atlassian.net/wiki/spaces/ENG/pages/2293761/Decisions"
|
||||
|
||||
|
||||
def write_config(home: pathlib.Path, checkout: pathlib.Path, goals: str = "checkout:README.md") -> pathlib.Path:
|
||||
@@ -85,6 +87,7 @@ class LoadTest(ConfigCase):
|
||||
self.assertEqual(found.paths["decisions"], folder / "docs" / "decisions.md")
|
||||
self.assertEqual(found.paths["changelog"], self.checkout / "CHANGELOG.md")
|
||||
self.assertEqual(found.paths["principles"], self.home / ".claude" / "principles")
|
||||
self.assertEqual(found.paths["standards"], self.home / ".claude" / "skills" / "larv-review" / "standards")
|
||||
self.assertEqual(tuple(found.paths), SETTINGS)
|
||||
|
||||
def test_a_plan_spelt_as_a_jira_epic_is_no_path(self) -> None:
|
||||
@@ -153,6 +156,53 @@ class LoadTest(ConfigCase):
|
||||
self.assertIn("jira:https://<site>/browse/<epic's key>", reason)
|
||||
self.assertIn("description", reason)
|
||||
|
||||
def test_a_record_spelt_as_a_confluence_page_is_no_path_and_prints_as_written(self) -> None:
|
||||
self.write("acme", JIRA_CLIENT.replace("folder:docs/decisions.md", DECISIONS_PAGE))
|
||||
found = load(self.checkout, self.checkout, self.home)
|
||||
assert isinstance(found, ProjectConfig), found
|
||||
self.assertEqual(found.pages, {"decisions": Page("https://acme.atlassian.net", "2293761", DECISIONS_PAGE)})
|
||||
self.assertEqual(found.places["decisions"], DECISIONS_PAGE)
|
||||
self.assertEqual(tuple(found.places), SETTINGS)
|
||||
self.assertNotIn("decisions", found.paths)
|
||||
self.assertIsNone(found.tracked("decisions"))
|
||||
|
||||
def test_a_confluence_page_may_leave_out_its_title(self) -> None:
|
||||
for spelled in ("confluence:https://acme.atlassian.net/wiki/spaces/ENG/pages/2293761", "confluence:https://acme.atlassian.net/wiki/spaces/~5b1e/pages/2293761/R%C3%A5d+och+beslut"):
|
||||
with self.subTest(spelled):
|
||||
for config in (self.home / ".claude-projects").glob("*/config.toml"):
|
||||
config.unlink()
|
||||
config.parent.rmdir()
|
||||
self.write("acme", CLIENT.replace("checkout:CHANGELOG.md", spelled) + 'env-file = "~/acme.env"\n')
|
||||
found = load(self.checkout, self.checkout, self.home)
|
||||
assert isinstance(found, ProjectConfig), found
|
||||
self.assertEqual(found.pages["changelog"].page_id, "2293761")
|
||||
|
||||
def test_a_confluence_record_needs_an_env_file(self) -> None:
|
||||
self.write("acme", CLIENT.replace("folder:docs/decisions.md", DECISIONS_PAGE))
|
||||
self.assertIn("`decisions` names a Confluence page, so `env-file` must name the file that holds its credentials", self.failure())
|
||||
|
||||
def test_a_record_that_ranking_reads_names_a_page_only_beside_a_plan_in_jira(self) -> None:
|
||||
self.write("acme", CLIENT.replace("folder:docs/decisions.md", DECISIONS_PAGE).replace("folder:docs/comprehension-history.md", DECISIONS_PAGE) + 'env-file = "~/acme.env"\n')
|
||||
reason = self.failure()
|
||||
self.assertIn("`decisions` names a Confluence page, so `plan` must name a Jira epic", reason)
|
||||
self.assertIn("`comprehension-history` names a Confluence page, so `plan` must name a Jira epic", reason)
|
||||
|
||||
def test_a_record_that_spells_no_path_and_no_page_names_both_spellings(self) -> None:
|
||||
for count, spelled in enumerate(("confluence:http://acme.atlassian.net/wiki/spaces/ENG/pages/2293761", "confluence:https://acme.atlassian.net/wiki/spaces/ENG/pages/Decisions", "confluence:https://acme.atlassian.net@evil.example/wiki/spaces/ENG/pages/2293761", "confluence:2293761", "https://acme.atlassian.net/wiki/spaces/ENG/pages/2293761")):
|
||||
with self.subTest(spelled):
|
||||
self.write(f"acme-{count}", CLIENT.replace("folder:docs/decisions.md", spelled) + 'env-file = "~/acme.env"\n')
|
||||
reason = self.failure()
|
||||
self.assertIn(f"`decisions` is {spelled!r}, not ", reason)
|
||||
self.assertIn("confluence:https://<site>/wiki/spaces/<space>/pages/<page ID>", reason)
|
||||
for config in (self.home / ".claude-projects").glob("*/config.toml"):
|
||||
config.unlink()
|
||||
|
||||
def test_only_a_record_may_name_a_confluence_page(self) -> None:
|
||||
self.write("acme", CLIENT.replace('"folder:AGENTS.md"', '"' + DECISIONS_PAGE + '"') + 'env-file = "~/acme.env"\n')
|
||||
reason = self.failure()
|
||||
self.assertIn("`working-rules` is", reason)
|
||||
self.assertNotIn("confluence:https://<site>", reason)
|
||||
|
||||
def test_a_worktree_finds_the_main_checkouts_config_and_reads_its_own_files(self) -> None:
|
||||
self.write("acme", CLIENT)
|
||||
worktree = self.home / "code" / "acme-billing-item-3"
|
||||
@@ -191,11 +241,16 @@ class LoadTest(ConfigCase):
|
||||
self.assertIn(str(self.checkout), reason)
|
||||
self.assertIn("~/.claude-projects/<key>/config.toml", reason)
|
||||
|
||||
def test_a_folder_that_is_no_checkout_fails_as_unnamed_with_gits_reason(self) -> None:
|
||||
outside = located(str(self.checkout), self.home)
|
||||
self.assertIsInstance(outside, Unnamed)
|
||||
self.assertIn("not a git repository", outside.reason)
|
||||
|
||||
def test_every_missing_setting_is_named(self) -> None:
|
||||
kept = "".join(line + "\n" for line in CLIENT.splitlines() if not line.startswith(("plan", "changelog", "principles")))
|
||||
kept = "".join(line + "\n" for line in CLIENT.splitlines() if not line.startswith(("plan", "changelog", "principles", "standards")))
|
||||
self.write("acme", kept)
|
||||
reason = self.failure()
|
||||
for name in ("plan", "changelog", "principles"):
|
||||
for name in ("plan", "changelog", "principles", "standards"):
|
||||
with self.subTest(name=name):
|
||||
self.assertIn(f"`{name}` is missing", reason)
|
||||
self.assertNotIn("`decisions` is", reason)
|
||||
@@ -245,6 +300,26 @@ class LoadTest(ConfigCase):
|
||||
assert isinstance(named, ProjectConfig), named
|
||||
self.assertEqual(named.notifier, name)
|
||||
|
||||
def test_a_jira_plan_may_name_the_transition_and_status_that_finish_an_item(self) -> None:
|
||||
self.write("acme", JIRA_CLIENT)
|
||||
left_out = load(self.checkout, self.checkout, self.home)
|
||||
assert isinstance(left_out, ProjectConfig), left_out
|
||||
self.assertIsNone(left_out.jira_finish)
|
||||
(self.home / ".claude-projects" / "acme" / "config.toml").write_text(JIRA_CLIENT + 'jira-finish-transition = "Mark as done"\njira-finish-status = "Done"\n')
|
||||
named = load(self.checkout, self.checkout, self.home)
|
||||
assert isinstance(named, ProjectConfig), named
|
||||
self.assertEqual(named.jira_finish, Finish("Mark as done", "Done"))
|
||||
|
||||
def test_a_finish_setting_alone_misspelt_or_beside_a_plan_in_a_file_fails_naming_it(self) -> None:
|
||||
self.write("acme", JIRA_CLIENT + 'jira-finish-status = "Done"\n')
|
||||
self.assertIn("`jira-finish-status` is set, so `jira-finish-transition` must be too", self.failure())
|
||||
(self.home / ".claude-projects" / "acme" / "config.toml").write_text(JIRA_CLIENT + 'jira-finish-transition = "Mark as done"\n')
|
||||
self.assertIn("`jira-finish-transition` is set, so `jira-finish-status` must be too", self.failure())
|
||||
(self.home / ".claude-projects" / "acme" / "config.toml").write_text(JIRA_CLIENT + 'jira-finish-transition = 31\njira-finish-status = " "\n')
|
||||
self.assertIn("`jira-finish-transition` is 31, not the name Jira shows, such as \"Mark as done\"; `jira-finish-status` is ' ', not the name Jira shows, such as \"Done\"", self.failure())
|
||||
(self.home / ".claude-projects" / "acme" / "config.toml").write_text(CLIENT + 'jira-finish-transition = "Mark as done"\njira-finish-status = "Done"\n')
|
||||
self.assertIn("`jira-finish-transition` is set, so `plan` must name a Jira epic; `jira-finish-status` is set, so `plan` must name a Jira epic", self.failure())
|
||||
|
||||
def test_a_notifier_that_is_unknown_or_has_no_env_file_fails_naming_it(self) -> None:
|
||||
self.write("acme", CLIENT + 'env-file = "~/acme.env"\nnotifier = "teams"\n')
|
||||
self.assertIn("`notifier` is 'teams', not mattermost or slack", self.failure())
|
||||
@@ -287,7 +362,7 @@ class LoadTest(ConfigCase):
|
||||
(folder / "config.toml").write_text(CLIENT + 'touch-predictions = "folder:docs/touch-predictions.md"\n', encoding="utf-8")
|
||||
found = load(self.checkout, self.checkout, self.home)
|
||||
assert isinstance(found, ProjectConfig)
|
||||
self.assertEqual(list(found.places)[-2:], ["principles", "touch-predictions"])
|
||||
self.assertEqual(list(found.places)[-2:], ["standards", "touch-predictions"])
|
||||
self.assertEqual(found.paths["touch-predictions"], folder / "docs/touch-predictions.md")
|
||||
self.assertIsNone(found.tracked("touch-predictions"))
|
||||
(folder / "config.toml").write_text(CLIENT + 'touch-predictions = "docs/touch-predictions.md"\n', encoding="utf-8")
|
||||
@@ -387,7 +462,7 @@ class LoadTest(ConfigCase):
|
||||
|
||||
def test_the_failure_for_a_misplaced_env_file_and_a_missing_setting_names_both_and_lists_every_setting(self) -> None:
|
||||
folder = self.write("acme", "".join(line + "\n" for line in CLIENT.splitlines() if not line.startswith("plan")) + 'env-file = "checkout:.env"\n')
|
||||
self.assertEqual(self.failure(), f"{folder / 'config.toml'}: `plan` is missing; `env-file` is 'checkout:.env', not {OUTSIDE}. The settings are {', '.join(SETTINGS)}, and optionally branch, commit-title, env-file, language, notifier, pull-request-title, readability-floor, tooling-on-host, touch-predictions and wait-for-approval.")
|
||||
self.assertEqual(self.failure(), f"{folder / 'config.toml'}: `plan` is missing; `env-file` is 'checkout:.env', not {OUTSIDE}. The settings are {', '.join(SETTINGS)}, and optionally branch, commit-title, env-file, jira-finish-status, jira-finish-transition, language, notifier, pull-request-title, readability-floor, tooling-on-host, touch-predictions and wait-for-approval.")
|
||||
|
||||
def test_two_configs_naming_one_checkout_fail_naming_both(self) -> None:
|
||||
self.write("acme", CLIENT)
|
||||
@@ -506,6 +581,17 @@ class ToolTest(ConfigCase):
|
||||
self.assertEqual(self.run_tool("notifier").stdout, "slack\n")
|
||||
self.assertEqual(self.run_tool().stdout.splitlines()[-1], "notifier: slack")
|
||||
|
||||
def test_prints_how_a_jira_item_finishes_where_the_config_says_and_fails_asking_for_it_where_it_does_not(self) -> None:
|
||||
folder = self.write("acme", JIRA_CLIENT)
|
||||
for name in ("jira-finish-transition", "jira-finish-status"):
|
||||
unset = self.run_tool(name)
|
||||
self.assertEqual((unset.returncode, unset.stdout, unset.stderr), (1, "", f"{folder / 'config.toml'} sets no `{name}`\n"))
|
||||
self.assertNotIn("jira-finish", self.run_tool().stdout)
|
||||
(folder / "config.toml").write_text(JIRA_CLIENT + 'jira-finish-transition = "Mark as done"\njira-finish-status = "Done"\n')
|
||||
self.assertEqual(self.run_tool("jira-finish-transition").stdout, "Mark as done\n")
|
||||
self.assertEqual(self.run_tool("jira-finish-status").stdout, "Done\n")
|
||||
self.assertEqual(self.run_tool().stdout.splitlines()[-2:], ["jira-finish-transition: Mark as done", "jira-finish-status: Done"])
|
||||
|
||||
def test_prints_true_or_false_for_wait_for_approval_and_lists_it_only_where_the_config_sets_it(self) -> None:
|
||||
folder = self.write("acme", CLIENT)
|
||||
left_out = self.run_tool("wait-for-approval")
|
||||
|
||||
@@ -15,9 +15,13 @@ stands, so open it again before each edit. A record that doesn't exist yet has n
|
||||
create it there.
|
||||
|
||||
save stores the file's text in the record, and prints one line saying so. Where the record is kept
|
||||
as a file there is nothing left to store, and it says that. Run it after every edit, so the same
|
||||
as a file, there is nothing left to store, and save says so. Run it after every edit, so the same
|
||||
steps work wherever a project keeps the record.
|
||||
|
||||
For a record kept on a Confluence page, save refuses where someone saved the page after open read
|
||||
it, and the human decides what follows. The copy keeps the unsaved edit until open runs again and
|
||||
writes the copy afresh.
|
||||
|
||||
Exit 2 on bad arguments, and 1, saying why, on any other failure.
|
||||
"""
|
||||
import pathlib
|
||||
@@ -26,6 +30,7 @@ import sys
|
||||
from failure import Failure
|
||||
from record_store.stores import FileStore, goals_store, local_file, RECORDS, RecordStore, store, stored
|
||||
from project_config.main import located
|
||||
from project_config.settings import ProjectConfig
|
||||
|
||||
# Not git's verbs, such as checkout and commit: those read as acting on the repo.
|
||||
COMMANDS = ("open", "save")
|
||||
@@ -44,7 +49,7 @@ def main(argv: list[str]) -> int:
|
||||
return 2
|
||||
home = pathlib.Path.home()
|
||||
config = located(None, home)
|
||||
done = config if isinstance(config, Failure) else act(argv[0], goals_store(config) if argv[1] == GOALS else store(config, argv[1]), home / COPIES / config.key / f"{argv[1]}.md")
|
||||
done = config if isinstance(config, Failure) else act(argv[0], *opened(config, argv[1], home))
|
||||
if isinstance(done, Failure):
|
||||
print(f"project-record: {done.reason}", file=sys.stderr)
|
||||
return 1
|
||||
@@ -52,6 +57,12 @@ def main(argv: list[str]) -> int:
|
||||
return 0
|
||||
|
||||
|
||||
def opened(config: ProjectConfig, name: str, home: pathlib.Path) -> tuple[RecordStore, pathlib.Path]:
|
||||
"""The store of the record called name, and the copy it gets where it isn't kept as a file. A store that keeps the version it read, for a later save, keeps it beside the copy."""
|
||||
copy = home / COPIES / config.key / f"{name}.md"
|
||||
return (goals_store(config) if name == GOALS else store(config, name, copy.with_suffix(".version"))), copy
|
||||
|
||||
|
||||
def act(command: str, record: RecordStore, copy: pathlib.Path) -> str | Failure:
|
||||
"""What command, one of COMMANDS, prints for record. copy is where a record kept outside files gets its file."""
|
||||
if command == "open":
|
||||
|
||||
@@ -8,13 +8,30 @@ import unittest
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from project_config.test_project_config import configured
|
||||
from record_store.confluence_page import ConfluencePage
|
||||
from failure import Failure
|
||||
from project_record import main
|
||||
from record_store.fakes import MemoryStore
|
||||
from project_config.settings import Page, ProjectConfig
|
||||
|
||||
TOOL = pathlib.Path(__file__).resolve().parents[1] / "project-record"
|
||||
|
||||
|
||||
class Opened(unittest.TestCase):
|
||||
def test_a_record_on_a_confluence_page_keeps_the_version_it_read_beside_its_copy(self):
|
||||
page = Page("https://acme.atlassian.net", "2293761", "confluence:https://acme.atlassian.net/wiki/spaces/ENG/pages/2293761")
|
||||
config = ProjectConfig("acme", pathlib.Path("/home/me/.claude-projects/acme"), pathlib.Path("/code/acme"), {}, pathlib.Path("/home/me/acme.env"), pages={"decisions": page})
|
||||
record, copy = main.opened(config, "decisions", pathlib.Path("/home/me"))
|
||||
self.assertEqual(copy, pathlib.Path("/home/me/.local/state/project-record/acme/decisions.md"))
|
||||
assert isinstance(record, ConfluencePage), record
|
||||
self.assertEqual(record.kept, pathlib.Path("/home/me/.local/state/project-record/acme/decisions.version"))
|
||||
|
||||
def test_the_goals_file_opens_through_the_goals_store(self):
|
||||
config = ProjectConfig("acme", pathlib.Path("/home/me/.claude-projects/acme"), pathlib.Path("/code/acme"), {"goals-and-audience": pathlib.Path("/code/acme/README.md")})
|
||||
record, copy = main.opened(config, "goals-and-audience", pathlib.Path("/home/me"))
|
||||
self.assertEqual((record.label, copy), ("/code/acme/README.md", pathlib.Path("/home/me/.local/state/project-record/acme/goals-and-audience.md")))
|
||||
|
||||
|
||||
class Act(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.copy = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory()), "acme", "decisions.md")
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
"""A record kept on one Confluence Cloud page, read and written as markdown over Confluence's REST API version 2, with the credentials of the config's env-file, and converted by the adf-codec shim.
|
||||
|
||||
A write never overwrites a teammate's edit: it sends the version it read, and Confluence refuses it where someone saved the page since. The human then decides (lilleman, 2026-11-12)."""
|
||||
import dataclasses
|
||||
import json
|
||||
import pathlib
|
||||
import typing
|
||||
|
||||
from adf_codec.convert import adfs_to_markdown, markdown_to_adf, Refused
|
||||
from plan_store.jira_epic import basic_auth, Http, TIMEOUT, ToAdf, ToMarkdown
|
||||
from rest_client.json_request import ErrorAnswer
|
||||
from failure import Failure
|
||||
from rest_client import json_request
|
||||
from project_config.settings import Page
|
||||
from text_files.file_writes import replace_file
|
||||
|
||||
# What Confluence answers to a write whose version isn't the one after the version it holds.
|
||||
CONFLICT = 409
|
||||
SHAPE = "not in the shape Confluence Cloud's REST API version 2 documents"
|
||||
|
||||
|
||||
def http_json(method: str, url: str, authorization: str, body: object) -> object:
|
||||
return json_request.http_json(method, url, authorization, body, TIMEOUT, error_message)
|
||||
|
||||
|
||||
def error_message(answer: object) -> str:
|
||||
"""Confluence's messages in the JSON of an error answer; empty where it holds none."""
|
||||
errors = answer.get("errors") if isinstance(answer, dict) else None
|
||||
found = [error.get("title") for error in errors if isinstance(error, dict)] if isinstance(errors, list) else [answer.get("message")] if isinstance(answer, dict) else []
|
||||
return "; ".join(text for text in found if isinstance(text, str))
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Seen:
|
||||
"""The page's version number and title as the store last read or wrote them. A write needs both."""
|
||||
version: int
|
||||
title: str
|
||||
|
||||
|
||||
@dataclasses.dataclass
|
||||
class ConfluencePage:
|
||||
"""The text of page as markdown, read and written with the credentials env_file holds.
|
||||
|
||||
kept is a file that keeps the version the store read for a later process, such as `project-record save` after `project-record open`; None keeps it only in memory."""
|
||||
page: Page
|
||||
env_file: pathlib.Path
|
||||
kept: pathlib.Path | None = None
|
||||
http: Http = http_json
|
||||
to_markdown: ToMarkdown = adfs_to_markdown
|
||||
to_adf: ToAdf = markdown_to_adf
|
||||
seen: Seen | None = None
|
||||
|
||||
@property
|
||||
def label(self) -> str:
|
||||
return self.page.spelling
|
||||
|
||||
@property
|
||||
def tracked(self) -> str | None:
|
||||
return None
|
||||
|
||||
@property
|
||||
def url(self) -> str:
|
||||
return f"{self.page.site}/wiki/api/v2/pages/{self.page.page_id}"
|
||||
|
||||
def read(self) -> str | Failure:
|
||||
"""The page's text as markdown; empty where the page is."""
|
||||
answer = self.fetched("?body-format=atlas_doc_format")
|
||||
if isinstance(answer, Failure):
|
||||
return answer
|
||||
seen, held = answer
|
||||
if not isinstance(held, str):
|
||||
return Failure(f"{self.label} is {SHAPE}: it holds no body in atlas_doc_format")
|
||||
text = self.converted(held)
|
||||
if isinstance(text, Failure):
|
||||
return text
|
||||
# Kept only once the text is in hand: a version kept for a read that failed would let a later write overwrite the save it saw.
|
||||
unkept = self.keep(seen)
|
||||
return unkept or text
|
||||
|
||||
def converted(self, held: str) -> str | Failure:
|
||||
"""The markdown of the body held, the JSON of an ADF document; empty where held is."""
|
||||
if not held:
|
||||
return ""
|
||||
try:
|
||||
document = json.loads(held)
|
||||
except ValueError:
|
||||
return Failure(f"{self.label} holds a body that is not JSON")
|
||||
texts = self.to_markdown([document])
|
||||
if isinstance(texts, Refused):
|
||||
return Failure(f"{self.label}: {texts.failure.reason}")
|
||||
if isinstance(texts, Failure):
|
||||
return Failure(f"cannot convert {self.label} to markdown: {texts.reason}")
|
||||
return texts[0]
|
||||
|
||||
def write(self, text: str) -> Failure | None:
|
||||
"""Replaces the page's text with text, as the version after the one the store read. Where the store hasn't read the page, it replaces the page as it stands."""
|
||||
seen = self.seen or self.recalled()
|
||||
if seen is None:
|
||||
fetched = self.fetched("")
|
||||
if isinstance(fetched, Failure):
|
||||
return fetched
|
||||
seen = fetched[0]
|
||||
if isinstance(seen, Failure):
|
||||
return seen
|
||||
document = self.to_adf(text)
|
||||
if isinstance(document, Failure):
|
||||
return Failure(f"cannot convert the text for {self.label} to ADF: {document.reason}")
|
||||
authorization = basic_auth(self.env_file)
|
||||
if isinstance(authorization, Failure):
|
||||
return authorization
|
||||
body = {"id": self.page.page_id, "status": "current", "title": seen.title, "body": {"representation": "atlas_doc_format", "value": json.dumps(document)}, "version": {"number": seen.version + 1}}
|
||||
answer = self.http("PUT", self.url, authorization, body)
|
||||
if isinstance(answer, ErrorAnswer) and answer.status == CONFLICT:
|
||||
return Failure(f"someone saved {self.label} since the loop read version {seen.version} of it, so the loop didn't write it: never overwrite their edit, but ask the human what to do ({answer.reason})")
|
||||
if isinstance(answer, Failure):
|
||||
return Failure(f"cannot write {self.label}: {answer.reason}")
|
||||
return self.keep(Seen(seen.version + 1, seen.title))
|
||||
|
||||
def fetched(self, query: str) -> tuple[Seen, object] | Failure:
|
||||
"""The page's version and title, and the value of its body in atlas_doc_format where query asks for it; None where it doesn't."""
|
||||
authorization = basic_auth(self.env_file)
|
||||
if isinstance(authorization, Failure):
|
||||
return authorization
|
||||
answer = self.http("GET", self.url + query, authorization, None)
|
||||
if isinstance(answer, Failure):
|
||||
return Failure(f"cannot read {self.label}: {answer.reason}")
|
||||
page = answer if isinstance(answer, dict) else {}
|
||||
version, title = page.get("version"), page.get("title")
|
||||
number = version.get("number") if isinstance(version, dict) else None
|
||||
if not isinstance(number, int) or not isinstance(title, str):
|
||||
return Failure(f"{self.label} is {SHAPE}: its version number or title is missing")
|
||||
body = page.get("body")
|
||||
adf = body.get("atlas_doc_format") if isinstance(body, dict) else None
|
||||
return Seen(number, title), adf.get("value") if isinstance(adf, dict) else None
|
||||
|
||||
def keep(self, seen: Seen) -> Failure | None:
|
||||
self.seen = seen
|
||||
if self.kept is None:
|
||||
return None
|
||||
try:
|
||||
self.kept.parent.mkdir(parents=True, exist_ok=True)
|
||||
except OSError as failure:
|
||||
return Failure(f"cannot write {self.kept}: {failure.strerror}")
|
||||
unwritten = replace_file(self.kept, json.dumps(dataclasses.asdict(seen)).encode())
|
||||
return Failure(f"cannot write {self.kept}: {unwritten.reason}") if unwritten else None
|
||||
|
||||
def recalled(self) -> Seen | Failure | None:
|
||||
"""The version and title the file kept holds; None where kept is None or names no file."""
|
||||
if self.kept is None:
|
||||
return None
|
||||
try:
|
||||
held: typing.Any = json.loads(self.kept.read_text(encoding="utf-8"))
|
||||
return Seen(int(held["version"]), str(held["title"]))
|
||||
except FileNotFoundError:
|
||||
return None
|
||||
except (OSError, ValueError, KeyError, TypeError) as failure:
|
||||
return Failure(f"cannot read the version of {self.label} that {self.kept} keeps: {failure}")
|
||||
@@ -1,18 +1,15 @@
|
||||
"""The one way a tool reads or writes a project's records: through the store its config names for each.
|
||||
|
||||
Each record has its own setting in the config, so a project may keep one record in its wiki and another as a file. The setting's value names the backend. A path names a markdown file, the only backend of a record so far; the goals file may also be a Jira epic's description, which `goals_store` picks."""
|
||||
Each record has its own setting in the config, so a project may keep one record in its wiki and another as a file. The setting's value names the backend. A path names a markdown file, and `confluence:` a Confluence Cloud page; the goals file may also be a Jira epic's description, which `goals_store` picks."""
|
||||
import dataclasses
|
||||
import pathlib
|
||||
import typing
|
||||
|
||||
from failure import Failure
|
||||
from git_cli.git_repo import file_at, git, Git
|
||||
from project_config.settings import ProjectConfig, TOUCH_PREDICTIONS
|
||||
from project_config.settings import ProjectConfig, RECORDS, TOUCH_PREDICTIONS
|
||||
from text_files.file_writes import replace_file
|
||||
|
||||
# The settings in a project's config that each name a record.
|
||||
RECORDS = ("decisions", "score-anchors", "comprehension-history", "reading-cost", "changelog")
|
||||
|
||||
|
||||
class RecordStore(typing.Protocol):
|
||||
"""One record, as text. record_store.contract holds every backend to the same behaviour."""
|
||||
@@ -61,11 +58,17 @@ class FileStore:
|
||||
return Failure(f"cannot write {self.path}: {unwritten.reason}") if unwritten else None
|
||||
|
||||
|
||||
def store(config: ProjectConfig, record: str) -> RecordStore:
|
||||
"""The store config names for record, one of RECORDS."""
|
||||
def store(config: ProjectConfig, record: str, kept: pathlib.Path | None = None) -> RecordStore:
|
||||
"""The store config names for record, one of RECORDS. A record on a Confluence page keeps the version it read in the file the parameter kept names, for a later process that writes it; where kept is None, the store keeps the version only in memory."""
|
||||
if record not in RECORDS:
|
||||
raise ValueError(f"{record} is not a record; the records are {', '.join(RECORDS)}")
|
||||
return FileStore(config.paths[record], config.tracked(record))
|
||||
if record not in config.pages:
|
||||
return FileStore(config.paths[record], config.tracked(record))
|
||||
# Imported here, as in goals_store.
|
||||
from record_store.confluence_page import ConfluencePage
|
||||
# load refuses a config that names a page and no env-file.
|
||||
assert config.env_file is not None
|
||||
return ConfluencePage(config.pages[record], config.env_file, kept)
|
||||
|
||||
|
||||
def touch_predictions_store(config: ProjectConfig) -> RecordStore | None:
|
||||
|
||||
@@ -0,0 +1,202 @@
|
||||
import base64
|
||||
import json
|
||||
import pathlib
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from record_store.confluence_page import ConfluencePage, error_message
|
||||
from rest_client.json_request import ErrorAnswer
|
||||
from failure import Failure
|
||||
from project_config.settings import Page
|
||||
from record_store.contract import RecordStoreContract
|
||||
from adf_codec.convert import Refused
|
||||
|
||||
PAGE = Page("https://acme.atlassian.net", "2293761", "confluence:https://acme.atlassian.net/wiki/spaces/ENG/pages/2293761")
|
||||
URL = "https://acme.atlassian.net/wiki/api/v2/pages/2293761"
|
||||
AUTHORIZATION = "Basic " + base64.b64encode(b"me@example.com:s3cret").decode()
|
||||
|
||||
|
||||
class FakeConfluence:
|
||||
"""One page as Confluence Cloud's REST API version 2 serves it, refusing with 409 a write whose version isn't the current one plus one."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.title = "Decisions"
|
||||
self.version = 1
|
||||
self.value = ""
|
||||
self.calls: list[tuple[str, str, str, object]] = []
|
||||
|
||||
def http(self, method: str, url: str, authorization: str, body: object) -> object:
|
||||
self.calls.append((method, url, authorization, body))
|
||||
if method == "GET":
|
||||
return {"id": PAGE.page_id, "title": self.title, "version": {"number": self.version}, "body": {"atlas_doc_format": {"representation": "atlas_doc_format", "value": self.value}}}
|
||||
assert isinstance(body, dict)
|
||||
if body["version"]["number"] != self.version + 1:
|
||||
return ErrorAnswer(f"PUT /wiki/api/v2/pages/{PAGE.page_id} answered 409: Version must be incremented on update. Current version is: {self.version}", 409)
|
||||
self.title, self.version, self.value = body["title"], body["version"]["number"], body["body"]["value"]
|
||||
return {"id": PAGE.page_id, "version": {"number": self.version}}
|
||||
|
||||
def teammate_saves(self, text: str) -> None:
|
||||
self.version += 1
|
||||
self.value = json.dumps(to_adf(text))
|
||||
|
||||
|
||||
def to_adf(text: str) -> dict[str, object]:
|
||||
return {"type": "doc", "version": 1, "content": [{"type": "paragraph", "content": [{"type": "text", "text": text}]}]}
|
||||
|
||||
|
||||
def to_markdown(documents: list[dict[str, object]]) -> list[str]:
|
||||
return [document["content"][0]["content"][0]["text"] for document in documents] # type: ignore[index]
|
||||
|
||||
|
||||
class ConfluenceCase(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
folder = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory()))
|
||||
self.env = folder / "acme.env"
|
||||
self.env.write_text("ATLASSIAN_EMAIL=me@example.com\nATLASSIAN_API_TOKEN=s3cret\n")
|
||||
self.env.chmod(0o600)
|
||||
self.kept = folder / "state" / "acme" / "decisions.version"
|
||||
self.confluence = FakeConfluence()
|
||||
|
||||
def new_store(self, kept: pathlib.Path | None = None) -> ConfluencePage:
|
||||
return ConfluencePage(PAGE, self.env, kept, self.confluence.http, to_markdown, to_adf)
|
||||
|
||||
|
||||
class ConfluencePageContract(ConfluenceCase, RecordStoreContract):
|
||||
pass
|
||||
|
||||
|
||||
class ConfluencePageTest(ConfluenceCase):
|
||||
def test_reads_the_pages_document_as_markdown(self) -> None:
|
||||
self.confluence.teammate_saves("# Decisions\n")
|
||||
self.assertEqual(self.new_store().read(), "# Decisions\n")
|
||||
self.assertEqual(self.confluence.calls, [("GET", f"{URL}?body-format=atlas_doc_format", AUTHORIZATION, None)])
|
||||
|
||||
def test_writes_markdown_as_the_version_it_read_plus_one(self) -> None:
|
||||
self.confluence.version = 7
|
||||
store = self.new_store()
|
||||
store.read()
|
||||
self.assertIsNone(store.write("- a decision\n"))
|
||||
self.assertEqual(self.confluence.calls[-1], ("PUT", URL, AUTHORIZATION, {"id": PAGE.page_id, "status": "current", "title": "Decisions", "body": {"representation": "atlas_doc_format", "value": json.dumps(to_adf("- a decision\n"))}, "version": {"number": 8}}))
|
||||
|
||||
def test_refuses_to_overwrite_a_teammates_save_since_its_read_and_says_to_ask_the_human(self) -> None:
|
||||
store = self.new_store()
|
||||
store.read()
|
||||
self.confluence.teammate_saves("their edit\n")
|
||||
written = store.write("my edit\n")
|
||||
assert isinstance(written, Failure), written
|
||||
self.assertIn("someone saved", written.reason)
|
||||
self.assertIn("ask the human", written.reason)
|
||||
self.assertIn(PAGE.spelling, written.reason)
|
||||
self.assertEqual(self.new_store().read(), "their edit\n")
|
||||
|
||||
def test_keeps_the_version_it_read_in_its_file_for_a_later_process(self) -> None:
|
||||
self.new_store(self.kept).read()
|
||||
self.confluence.teammate_saves("their edit\n")
|
||||
written = self.new_store(self.kept).write("my edit\n")
|
||||
assert isinstance(written, Failure), written
|
||||
self.assertIn("someone saved", written.reason)
|
||||
|
||||
def test_a_read_that_fails_keeps_the_version_an_earlier_read_kept(self) -> None:
|
||||
self.new_store(self.kept).read()
|
||||
self.confluence.teammate_saves("their edit\n")
|
||||
failing = ConfluencePage(PAGE, self.env, self.kept, self.confluence.http, lambda _: Refused(0, Failure("adf-codec refused the input")), to_adf)
|
||||
self.assertIsInstance(failing.read(), Failure)
|
||||
self.confluence.value = "{not json"
|
||||
self.assertIsInstance(self.new_store(self.kept).read(), Failure)
|
||||
written = self.new_store(self.kept).write("my edit\n")
|
||||
assert isinstance(written, Failure), written
|
||||
self.assertIn("someone saved", written.reason)
|
||||
self.assertEqual(self.confluence.version, 2)
|
||||
|
||||
def test_a_later_process_writes_with_the_version_an_earlier_one_read_or_wrote(self) -> None:
|
||||
self.new_store(self.kept).read()
|
||||
self.assertIsNone(self.new_store(self.kept).write("first\n"))
|
||||
self.assertIsNone(self.new_store(self.kept).write("second\n"))
|
||||
self.assertEqual(self.new_store().read(), "second\n")
|
||||
self.assertEqual(self.confluence.title, "Decisions")
|
||||
|
||||
def test_a_write_with_no_read_replaces_the_page_as_it_stands(self) -> None:
|
||||
self.confluence.teammate_saves("earlier\n")
|
||||
self.assertIsNone(self.new_store().write("replaced\n"))
|
||||
self.assertEqual(self.confluence.calls[0], ("GET", URL, AUTHORIZATION, None))
|
||||
self.assertEqual(self.new_store().read(), "replaced\n")
|
||||
|
||||
def test_fails_on_an_answer_not_shaped_as_a_page(self) -> None:
|
||||
for answer in ({}, {"title": "Decisions", "version": {}, "body": {"atlas_doc_format": {"value": ""}}}, {"version": {"number": 3}, "body": {"atlas_doc_format": {"value": ""}}}, ["not", "a", "page"]):
|
||||
with self.subTest(answer):
|
||||
store = ConfluencePage(PAGE, self.env, None, lambda *_: answer, to_markdown, to_adf)
|
||||
read = store.read()
|
||||
assert isinstance(read, Failure), read
|
||||
self.assertIn("not in the shape Confluence Cloud's REST API version 2 documents", read.reason)
|
||||
|
||||
def test_fails_on_a_page_without_a_body_in_adf(self) -> None:
|
||||
for body in ({}, "text", {"atlas_doc_format": "text"}, {"atlas_doc_format": {"value": 3}}):
|
||||
with self.subTest(body):
|
||||
answer = {"title": "Decisions", "version": {"number": 3}, "body": body}
|
||||
store = ConfluencePage(PAGE, self.env, None, lambda *_: answer, to_markdown, to_adf)
|
||||
self.assertEqual(store.read(), Failure(f"{PAGE.spelling} is not in the shape Confluence Cloud's REST API version 2 documents: it holds no body in atlas_doc_format"))
|
||||
|
||||
def test_fails_on_a_body_that_is_not_json(self) -> None:
|
||||
self.confluence.value = "{not json"
|
||||
self.assertEqual(self.new_store().read(), Failure(f"{PAGE.spelling} holds a body that is not JSON"))
|
||||
|
||||
def test_fails_naming_the_page_where_the_text_cannot_be_converted(self) -> None:
|
||||
self.confluence.teammate_saves("text\n")
|
||||
store = ConfluencePage(PAGE, self.env, None, self.confluence.http, lambda _: Failure("the shim is down"), lambda _: Failure("the shim is down"))
|
||||
self.assertEqual(store.read(), Failure(f"cannot convert {PAGE.spelling} to markdown: the shim is down"))
|
||||
self.assertEqual(store.write("text\n"), Failure(f"cannot convert the text for {PAGE.spelling} to ADF: the shim is down"))
|
||||
|
||||
def test_fails_naming_the_page_where_adf_codec_refuses_its_document(self) -> None:
|
||||
self.confluence.teammate_saves("text\n")
|
||||
store = ConfluencePage(PAGE, self.env, None, self.confluence.http, lambda _: Refused(0, Failure("adf-codec refused the input")), to_adf)
|
||||
self.assertEqual(store.read(), Failure(f"{PAGE.spelling}: adf-codec refused the input"))
|
||||
|
||||
def test_fails_where_the_folder_of_its_file_cannot_be_made(self) -> None:
|
||||
self.kept.parent.parent.mkdir(parents=True)
|
||||
self.kept.parent.write_text("a file, not a folder")
|
||||
read = self.new_store(self.kept).read()
|
||||
assert isinstance(read, Failure), read
|
||||
self.assertTrue(read.reason.startswith(f"cannot write {self.kept}: "), read.reason)
|
||||
|
||||
def test_a_write_confluence_refuses_otherwise_fails_naming_the_page_and_not_a_teammate(self) -> None:
|
||||
answers = iter([{"title": "Decisions", "version": {"number": 3}}, ErrorAnswer("PUT /wiki/api/v2/pages/2293761 answered 403: Forbidden", 403)])
|
||||
store = ConfluencePage(PAGE, self.env, None, lambda *_: next(answers), to_markdown, to_adf)
|
||||
self.assertEqual(store.write("text\n"), Failure(f"cannot write {PAGE.spelling}: PUT /wiki/api/v2/pages/2293761 answered 403: Forbidden"))
|
||||
|
||||
def test_fails_where_its_file_cannot_keep_the_version(self) -> None:
|
||||
self.kept.mkdir(parents=True)
|
||||
read = self.new_store(self.kept).read()
|
||||
assert isinstance(read, Failure), read
|
||||
self.assertTrue(read.reason.startswith(f"cannot write {self.kept}: "), read.reason)
|
||||
|
||||
def test_fails_on_a_kept_version_it_cannot_read_and_writes_nothing(self) -> None:
|
||||
self.kept.parent.mkdir(parents=True)
|
||||
self.kept.write_text("{}")
|
||||
written = self.new_store(self.kept).write("text\n")
|
||||
assert isinstance(written, Failure), written
|
||||
self.assertTrue(written.reason.startswith(f"cannot read the version of {PAGE.spelling} that {self.kept} keeps: "), written.reason)
|
||||
self.assertEqual(self.confluence.calls, [])
|
||||
|
||||
def test_reads_confluences_messages_from_an_error_answer(self) -> None:
|
||||
self.assertEqual(error_message({"errors": [{"status": 409, "title": "Version must be incremented"}, {"title": "and more"}, "odd"]}), "Version must be incremented; and more")
|
||||
self.assertEqual(error_message({"message": "Not Found"}), "Not Found")
|
||||
self.assertEqual(error_message({"errors": "odd"}), "")
|
||||
self.assertEqual(error_message(["odd"]), "")
|
||||
|
||||
def test_fails_naming_the_page_when_confluence_answers_an_error(self) -> None:
|
||||
store = ConfluencePage(PAGE, self.env, None, lambda *_: ErrorAnswer("GET /wiki/api/v2/pages/2293761 answered 404: Not Found", 404), to_markdown, to_adf)
|
||||
self.assertEqual(store.read(), Failure(f"cannot read {PAGE.spelling}: GET /wiki/api/v2/pages/2293761 answered 404: Not Found"))
|
||||
|
||||
def test_fails_without_credentials_before_any_request(self) -> None:
|
||||
self.env.unlink()
|
||||
read = self.new_store().read()
|
||||
assert isinstance(read, Failure), read
|
||||
self.assertIn("does not exist", read.reason)
|
||||
self.assertEqual(self.confluence.calls, [])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -6,7 +6,8 @@ import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from project_config.settings import Epic, ProjectConfig
|
||||
from record_store.confluence_page import ConfluencePage
|
||||
from project_config.settings import Epic, Page, ProjectConfig
|
||||
from record_store.jira_description import EpicDescription
|
||||
from failure import Failure
|
||||
from record_store.fakes import MemoryStore
|
||||
@@ -171,6 +172,12 @@ class Store(unittest.TestCase):
|
||||
stores.store(self.config(pathlib.Path("/code/acme"), pathlib.Path("/home/me/.claude-projects/acme")), "plan")
|
||||
self.assertEqual(str(refused.exception), "plan is not a record; the records are decisions, score-anchors, comprehension-history, reading-cost, changelog")
|
||||
|
||||
def test_a_record_on_a_confluence_page_is_that_page_keeping_its_version_where_asked(self):
|
||||
page = Page("https://acme.atlassian.net", "2293761", "confluence:https://acme.atlassian.net/wiki/spaces/ENG/pages/2293761")
|
||||
config = ProjectConfig("acme", pathlib.Path("/home/me/.claude-projects/acme"), pathlib.Path("/code/acme"), {}, pathlib.Path("/home/me/acme.env"), pages={"decisions": page})
|
||||
kept = pathlib.Path("/home/me/decisions.version")
|
||||
self.assertEqual(stores.store(config, "decisions", kept), ConfluencePage(page, pathlib.Path("/home/me/acme.env"), kept))
|
||||
|
||||
|
||||
class GoalsStore(unittest.TestCase):
|
||||
def test_goals_kept_as_a_file_are_that_file(self):
|
||||
|
||||
@@ -6,11 +6,18 @@ import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from loop_claude.project.records import HUMAN_RULE_DIRS
|
||||
from loop_claude.project.records import HUMAN_RULE_DIR
|
||||
from repo_checks import ROOT
|
||||
|
||||
RULE_PATH = rf"(?:{'|'.join(map(re.escape, HUMAN_RULE_DIRS))})/[\w-]+\.md"
|
||||
CITATION = re.compile(rf'`?(?:~/\.claude/)?(CLAUDE\.md|{RULE_PATH})`? → ("[^"]+"(?:,? (?:and )?"[^"]+")*)')
|
||||
# The review standards this repo ships. A project's config may name another folder as `standards`.
|
||||
STANDARDS = "skills/larv-review/standards"
|
||||
# The folders whose files a citation may name by path. The judge reads both.
|
||||
RULE_DIRS = (HUMAN_RULE_DIR, STANDARDS)
|
||||
RULE_PATH = rf"(?:{'|'.join(map(re.escape, RULE_DIRS))})/[\w-]+\.md"
|
||||
NAMES = r'("[^"]+"(?:,? (?:and )?"[^"]+")*)'
|
||||
CITATION = re.compile(rf'`?(?:~/\.claude/)?(CLAUDE\.md|{RULE_PATH})`? → {NAMES}')
|
||||
# A citation of a file in whichever folder the project's config names as `standards`, checked against the folder this repo ships.
|
||||
STANDARD_CITATION = re.compile(rf"the review standards' `([\w-]+\.md)` → {NAMES}")
|
||||
HEADING = re.compile(r"^#+ (.+?)(?: \(.*\))?$", re.MULTILINE)
|
||||
LEAD = re.compile(r"^(?:- )?\*\*(.+?)(?:\*\*|[:.](?=\*\*| )| —)", re.MULTILINE)
|
||||
DECISION_CITATION = re.compile(r"`?docs/decisions\.md`? → `([^`]+)`")
|
||||
@@ -27,6 +34,7 @@ class Citations(unittest.TestCase):
|
||||
texts = [(path, (ROOT / path).read_text()) for path in filter(None, tracked)]
|
||||
self.assertEqual([f"{path}: {stray}" for path, text in texts for stray in STRAY.findall(text)], [], 'spell a citation `CLAUDE.md` → "Vocabulary"')
|
||||
cited = [(path, file, NAME.findall(run)) for path, text in texts for file, run in CITATION.findall(text)]
|
||||
cited += [(path, f"{STANDARDS}/{file}", NAME.findall(run)) for path, text in texts for file, run in STANDARD_CITATION.findall(text)]
|
||||
self.assertTrue(cited)
|
||||
unresolved = []
|
||||
for path, file, names in cited:
|
||||
@@ -47,8 +55,8 @@ class Citations(unittest.TestCase):
|
||||
topic_rules = (ROOT / "CLAUDE.md").read_text().split("## Topic rules\n")[1].split("\n## ")[0]
|
||||
self.assertEqual(sorted(set(RULE_FILE.findall(topic_rules))), sorted(f"rules/{rule.name}" for rule in (ROOT / "rules").glob("*.md")))
|
||||
|
||||
def test_every_folder_the_judge_reads_rules_from_exists(self):
|
||||
self.assertEqual([folder for folder in HUMAN_RULE_DIRS if not (ROOT / folder).is_dir()], [])
|
||||
def test_the_rules_folder_and_the_review_standards_this_repo_ships_exist(self):
|
||||
self.assertEqual([folder for folder in RULE_DIRS if not (ROOT / folder).is_dir()], [])
|
||||
|
||||
def test_every_decision_title_the_log_lists_at_its_head_is_a_title_in_it(self):
|
||||
log = (ROOT / "docs/decisions.md").read_text()
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
"""Sends one request to a REST API that speaks JSON, with a credential that no redirect may carry elsewhere."""
|
||||
import dataclasses
|
||||
import http.client
|
||||
import json
|
||||
import typing
|
||||
@@ -12,6 +13,12 @@ from failure import Failure
|
||||
MessageOf = typing.Callable[[object], str]
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class ErrorAnswer(Failure):
|
||||
"""The API answered an HTTP error, whose code is status, such as 409 for a conflict."""
|
||||
status: int
|
||||
|
||||
|
||||
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
||||
"""Refuses every redirect, which a REST API doesn't send: urllib would resend the credential to the new location, even one off https."""
|
||||
|
||||
@@ -19,14 +26,14 @@ class NoRedirect(urllib.request.HTTPRedirectHandler):
|
||||
return None
|
||||
|
||||
|
||||
# Sends a request: method, url, token and the body as JSON where there is one. It returns the JSON answer, or a Failure saying why there is none.
|
||||
# Sends a request: method, url, token and the body as JSON where there is one. It returns the JSON answer, None where the answer has no body, or a Failure saying why there is none.
|
||||
Http = typing.Callable[[str, str, str, object], object]
|
||||
|
||||
OPENER = urllib.request.build_opener(NoRedirect)
|
||||
|
||||
|
||||
def http_json(method: str, url: str, authorization: str, body: object, seconds: int, message_of: MessageOf) -> object:
|
||||
"""The JSON that url answers to a request with the Authorization header given, and body as JSON where there is one. A Failure names the server where it cannot be reached, and the request where it answers an error, breaks HTTP or answers something other than JSON. Each connect and each read may wait that many seconds."""
|
||||
"""The JSON that url answers to a request with the Authorization header given, and body as JSON where there is one; None where it answers a success without a body, as Jira does to a new issue link. A Failure names the server where it cannot be reached, and the request where it answers an error, breaks HTTP or answers something other than JSON. Each connect and each read may wait that many seconds."""
|
||||
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": authorization, "Content-Type": "application/json", "Accept": "application/json"}, method=method)
|
||||
@@ -35,12 +42,14 @@ def http_json(method: str, url: str, authorization: str, body: object, seconds:
|
||||
raw = response.read()
|
||||
except urllib.error.HTTPError as failure:
|
||||
with failure:
|
||||
return Failure(f"{request_name} answered {failure.code}: {error_message(failure, message_of) or failure.reason}")
|
||||
return ErrorAnswer(f"{request_name} answered {failure.code}: {error_message(failure, message_of) or failure.reason}", failure.code)
|
||||
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)}")
|
||||
if not raw.strip():
|
||||
return None
|
||||
try:
|
||||
return json.loads(raw)
|
||||
except ValueError:
|
||||
|
||||
@@ -8,6 +8,7 @@ import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from rest_client.json_request import ErrorAnswer
|
||||
from failure import Failure
|
||||
from rest_client import json_request
|
||||
|
||||
@@ -66,13 +67,19 @@ class HttpJson(unittest.TestCase):
|
||||
[(method, path, headers, body)] = self.server.got # type: ignore[attr-defined]
|
||||
self.assertEqual((method, path, headers["Authorization"], headers["Content-Type"], headers["Accept"], json.loads(body)), ("POST", "/api/v4/posts", "Bearer secret-token", "application/json", "application/json", {"message": "hi"}))
|
||||
|
||||
def test_reads_an_answer_without_a_body_as_none(self):
|
||||
for body in (b"", b"\n"):
|
||||
with self.subTest(body=body):
|
||||
base = self.serve((201, body))
|
||||
self.assertIsNone(send("POST", f"{base}/rest/api/3/issueLink", "t", {"type": {"name": "Blocks"}}))
|
||||
|
||||
def test_names_the_request_the_status_and_the_apis_message_on_an_error(self):
|
||||
base = self.serve((401, b'{"message": "Invalid or expired session, please login again."}'))
|
||||
self.assertEqual(send("GET", f"{base}/api/v4/users/me", "bad", None), Failure("GET /api/v4/users/me answered 401: Invalid or expired session, please login again."))
|
||||
self.assertEqual(send("GET", f"{base}/api/v4/users/me", "bad", None), ErrorAnswer("GET /api/v4/users/me answered 401: Invalid or expired session, please login again.", 401))
|
||||
|
||||
def test_follows_no_redirect_so_the_token_goes_only_to_the_server_named(self):
|
||||
base = self.serve((302, b"{}"))
|
||||
self.assertEqual(send("GET", f"{base}/api/v4/users/me", "t", None), Failure("GET /api/v4/users/me answered 302: Found"))
|
||||
self.assertEqual(send("GET", f"{base}/api/v4/users/me", "t", None), ErrorAnswer("GET /api/v4/users/me answered 302: Found", 302))
|
||||
self.assertEqual(len(self.server.got), 1) # type: ignore[attr-defined]
|
||||
|
||||
def test_sends_no_body_with_a_get(self):
|
||||
@@ -90,7 +97,7 @@ class HttpJson(unittest.TestCase):
|
||||
|
||||
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(send("GET", f"{base}/api/v4/users/me", "t", None), Failure("GET /api/v4/users/me answered 500: Internal Server Error"))
|
||||
self.assertEqual(send("GET", f"{base}/api/v4/users/me", "t", None), ErrorAnswer("GET /api/v4/users/me answered 500: Internal Server Error", 500))
|
||||
|
||||
def test_gives_up_on_a_server_that_never_answers_after_the_timeout(self):
|
||||
silent = socket.socket()
|
||||
@@ -120,7 +127,7 @@ class HttpJson(unittest.TestCase):
|
||||
|
||||
def test_an_error_whose_body_is_not_json_names_the_status_alone(self):
|
||||
base = self.serve((403, b"<html>"))
|
||||
self.assertEqual(send("GET", f"{base}/api/v4/users/me", "t", None), Failure("GET /api/v4/users/me answered 403: Forbidden"))
|
||||
self.assertEqual(send("GET", f"{base}/api/v4/users/me", "t", None), ErrorAnswer("GET /api/v4/users/me answered 403: Forbidden", 403))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
usage: review-replay <pass> <model> [--omit-claude-md]
|
||||
|
||||
<pass> is one of architecture, principles, overrides, stability, product-owner or prose.
|
||||
<model> is a project model on the routing ladder, such as claude-opus-5-5. The tool replays the
|
||||
<model> is a project model on the routing ladder this setup ships, such as claude-opus-5-5. The tool replays the
|
||||
latest 10 archived rounds of the pass whose report holds a 🔴 or 🟡 finding, from the projects
|
||||
that ~/.claude/loop-claude-models.json runs on the model. It replays each round on the code it
|
||||
reviewed: in a throwaway clone of the project's checkout, at the newest commit of origin/HEAD
|
||||
@@ -61,8 +61,9 @@ from review_replay.replay import codes_found, findings_replayed
|
||||
from review_replay.omit_comparison import compared
|
||||
from loop_effects.effects import Effects
|
||||
from failure import Failure
|
||||
from model_routing.ladder import Ladder, Rung
|
||||
from claude_code.reply import Limited
|
||||
from model_routing.ladder import project_rung, Rung
|
||||
from model_routing.ladder_file import read_ladder, SHIPPED
|
||||
from review_replay.recall import recall_report, recalled
|
||||
from review_rules.review_passes import ReviewedPass, REVIEWERS
|
||||
|
||||
@@ -73,7 +74,11 @@ LATEST = 10
|
||||
|
||||
|
||||
def main(argv: list[str], env: typing.Mapping[str, str], home: pathlib.Path, effects: Effects) -> int:
|
||||
read = arguments_or_exit(TOOL, argv, __doc__, USAGE, pass_and_model)
|
||||
# The shipped ladder, not a project's: the replay spans every project on the model.
|
||||
ladder = read_ladder(SHIPPED)
|
||||
if isinstance(ladder, Failure):
|
||||
return failed(TOOL, ladder.reason)
|
||||
read = arguments_or_exit(TOOL, argv, __doc__, USAGE, lambda argv: pass_and_model(ladder, argv))
|
||||
if isinstance(read, int):
|
||||
return read
|
||||
reviewed, project, without = read
|
||||
@@ -97,17 +102,17 @@ def main(argv: list[str], env: typing.Mapping[str, str], home: pathlib.Path, eff
|
||||
print(f" {found.root} {found.at} on {rung} failed: {matched.reason}", file=sys.stderr, flush=True)
|
||||
return matched
|
||||
|
||||
recall = recalled(chosen, project, replay_one, f"{reviewed} rounds")
|
||||
recall = recalled(chosen, ladder, project, replay_one, f"{reviewed} rounds")
|
||||
if isinstance(recall, Limited):
|
||||
return limited_exit(TOOL, recall)
|
||||
print(recall_report(reviewed, project, recall))
|
||||
return 0
|
||||
|
||||
|
||||
def pass_and_model(argv: list[str]) -> tuple[ReviewedPass, Rung, bool] | None:
|
||||
"""The pass, the project's rung of the model, and whether OMIT follows, as argv names them in `<pass> <model> [--omit-claude-md]`; None for any other argv."""
|
||||
def pass_and_model(ladder: Ladder, argv: list[str]) -> tuple[ReviewedPass, Rung, bool] | None:
|
||||
"""The pass, the project's rung on ladder of the model, and whether OMIT follows, as argv names them in `<pass> <model> [--omit-claude-md]`; None for any other argv."""
|
||||
if argv[2:] not in ([], [OMIT]) or len(argv) < 2:
|
||||
return None
|
||||
reviewed = next((kind for kind in REVIEWERS if kind == argv[0]), None)
|
||||
project = project_rung(argv[1])
|
||||
project = ladder.project_rung(argv[1])
|
||||
return (reviewed, project, argv[2:] == [OMIT]) if reviewed and project else None
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
"""The bar review-replay holds a rung to, and its report: docs/decisions.md → `routing: a review pass runs below the project's rung only on a rung whose replay of its rounds finds a share of their 🔴 and 🟡 findings no more than a margin below the project's rung's own replay`."""
|
||||
import dataclasses
|
||||
from rung_replay.command import down_from
|
||||
from model_routing.ladder import EFFORTS, Ladder, Rung
|
||||
from failure import Failure
|
||||
from fractions import Fraction
|
||||
from review_replay.rounds import is_red, Round
|
||||
from model_routing.ladder import LADDER, Rung
|
||||
from claude_code.reply import Limited
|
||||
import math
|
||||
from rung_replay.search import replayed_on
|
||||
@@ -14,8 +14,6 @@ import typing
|
||||
MARGIN = Fraction(1, 10)
|
||||
# The fewest rounds a rung is tried on: 8 of the 10 the tool samples, so up to two may fail on the project's rung.
|
||||
ENOUGH_ROUNDS = 8
|
||||
# Lowest first, as Claude Code's --effort takes them.
|
||||
EFFORTS = ("low", "medium", "high", "xhigh", "max")
|
||||
# The two replays on the project's rung. Each lists, round by round, the indexes of the findings it found.
|
||||
Reference = tuple[list[set[int]], list[set[int]]]
|
||||
|
||||
@@ -39,10 +37,10 @@ class Recall:
|
||||
lowest: Rung | None
|
||||
|
||||
|
||||
def candidates(project: Rung) -> list[Rung]:
|
||||
def candidates(ladder: Ladder, project: Rung) -> list[Rung]:
|
||||
"""The rungs tried below the project's, highest first: its model at each lower effort, which the ladder leaves out, then each ladder rung below it, down to the ladder's lowest. That reaches below the lowest a worker routes to, since a pass may run below the worker's rung."""
|
||||
lower_efforts = [Rung(project.model, effort) for effort in reversed(EFFORTS[:EFFORTS.index(project.effort)])]
|
||||
return lower_efforts + down_from(project, LADDER[0])[1:]
|
||||
return lower_efforts + down_from(ladder, project, ladder.rungs[0])[1:]
|
||||
|
||||
|
||||
def enough(rounds: list[Round]) -> bool:
|
||||
@@ -97,7 +95,7 @@ def percent(fraction: Fraction) -> str:
|
||||
return f"{float(fraction):.0%}"
|
||||
|
||||
|
||||
def recalled(chosen: list[Round], project: Rung, replay_one: typing.Callable[[Round, Rung], set[int] | Failure | Limited], what: str) -> Recall | Limited:
|
||||
def recalled(chosen: list[Round], ladder: Ladder, project: Rung, replay_one: typing.Callable[[Round, Rung], set[int] | Failure | Limited], what: str) -> Recall | Limited:
|
||||
"""Replays chosen twice on the project's rung, then each candidate, highest first, on the rounds neither of those failed on, until one doesn't qualify."""
|
||||
runs: list[list[set[int] | Failure]] = []
|
||||
for _ in range(2):
|
||||
@@ -114,7 +112,7 @@ def recalled(chosen: list[Round], project: Rung, replay_one: typing.Callable[[Ro
|
||||
reference[1].append(second)
|
||||
recalls: list[RungRecall] = []
|
||||
lowest = None
|
||||
for rung in candidates(project) if enough(rounds) and needed(rounds, reference) > 0 else []:
|
||||
for rung in candidates(ladder, project) if enough(rounds) and needed(rounds, reference) > 0 else []:
|
||||
on_rung: list[set[int] | Failure] | Limited = replayed_on(rounds, rung, replay_one, what)
|
||||
if isinstance(on_rung, Limited):
|
||||
return on_rung
|
||||
|
||||
@@ -1,13 +1,17 @@
|
||||
import contextlib
|
||||
import io
|
||||
import pathlib
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from review_replay.recall import candidates, needed, Recall, recall_report, tried
|
||||
from review_replay.recall import candidates, needed, Recall, recall_report, recalled, tried
|
||||
from review_replay.rounds import is_red, Round
|
||||
from model_routing.ladder_file import read_ladder, SHIPPED
|
||||
from model_routing.ladder import Rung
|
||||
|
||||
LADDER = read_ladder(SHIPPED)
|
||||
REFERENCE = Rung("claude-opus-5-5", "medium")
|
||||
LOW = Rung("claude-opus-5-5", "low")
|
||||
SONNET = Rung("claude-sonnet-5-5", "high")
|
||||
@@ -27,13 +31,22 @@ TENTH = ([{0}, set()], [{0}, set()])
|
||||
|
||||
class Candidates(unittest.TestCase):
|
||||
def test_tries_the_project_models_lower_efforts_first_then_the_ladder_below_it(self):
|
||||
self.assertEqual(candidates(REFERENCE), [LOW, SONNET])
|
||||
self.assertEqual(candidates(LADDER, REFERENCE), [LOW, SONNET])
|
||||
|
||||
def test_tries_each_ladder_rung_below_highest_first(self):
|
||||
self.assertEqual(candidates(Rung("claude-fable-5-2", "low")), [REFERENCE, SONNET])
|
||||
self.assertEqual(candidates(LADDER, Rung("claude-fable-5-2", "low")), [REFERENCE, SONNET])
|
||||
|
||||
def test_tries_each_lower_effort_of_the_ladders_lowest_rung(self):
|
||||
self.assertEqual(candidates(SONNET), [Rung("claude-sonnet-5-5", "medium"), Rung("claude-sonnet-5-5", "low")])
|
||||
self.assertEqual(candidates(LADDER, SONNET), [Rung("claude-sonnet-5-5", "medium"), Rung("claude-sonnet-5-5", "low")])
|
||||
|
||||
|
||||
class Recalled(unittest.TestCase):
|
||||
def test_tries_the_rungs_below_where_the_project_rung_needs_one_finding(self):
|
||||
# Eight findings, of which both replays on the project's rung find one: a share of an eighth, a tenth under which leaves one finding needed.
|
||||
rounds = [a_round(at, ("🟡 a",)) for at in range(8)]
|
||||
with contextlib.redirect_stderr(io.StringIO()):
|
||||
recall = recalled(rounds, LADDER, REFERENCE, lambda one, rung: {0} if one == rounds[0] else set(), "prose rounds")
|
||||
self.assertEqual(([one.rung for one in recall.tried], recall.lowest), ([LOW, SONNET], SONNET))
|
||||
|
||||
|
||||
class Tried(unittest.TestCase):
|
||||
|
||||
@@ -214,7 +214,8 @@ def worse_dimensions(votes: list[str]) -> set[str]:
|
||||
def table_rows(body: str) -> list[dict[str, list[str]]]:
|
||||
"""Each table's rows after its header and separator, the cells after the first keyed by the first cell. Tables may touch, so a table starts at the row above a separator."""
|
||||
lines = [line for line in body.splitlines() if line.startswith("|")]
|
||||
separators = [index for index, line in enumerate(lines) if line.startswith("|-")]
|
||||
# entry_text writes a separator as `|---|`, and adf-codec, for a history kept on a Confluence page, as `| --- |`.
|
||||
separators = [index for index, line in enumerate(lines) if re.fullmatch(r"\|( *-+ *\|)+ *", line)]
|
||||
ends = [*(index - 1 for index in separators[1:]), len(lines)]
|
||||
return [dict(row_cells(line) for line in lines[separator + 1:end]) for separator, end in zip(separators, ends)]
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ import typing
|
||||
|
||||
from routing_figures.chunk import ChunkFigures, Reports
|
||||
from routing_figures.dollars import DIMENSIONS, Dollars
|
||||
from model_routing.ladder import position, Rung
|
||||
from model_routing.ladder import Ladder, Rung
|
||||
|
||||
# A rung or a subagent type is compared only once this many of its chunks or subagents are measured, so a single odd chunk calls for no change.
|
||||
MEASURED_AT_LEAST = 5
|
||||
@@ -73,9 +73,9 @@ class Call:
|
||||
return SENTENCES[self.kind].format(*self.subjects)
|
||||
|
||||
|
||||
def calls(figures: Figures) -> list[Call]:
|
||||
"""Each routing change the figures call for."""
|
||||
compared = sorted((rung for rung, chunks in figures.routed.items() if len(chunks) >= MEASURED_AT_LEAST and position(rung) >= 0), key=position)
|
||||
def calls(ladder: Ladder, figures: Figures) -> list[Call]:
|
||||
"""Each routing change the figures call for, comparing the rungs on ladder."""
|
||||
compared = sorted((rung for rung, chunks in figures.routed.items() if len(chunks) >= MEASURED_AT_LEAST and ladder.position(rung) >= 0), key=ladder.position)
|
||||
found = []
|
||||
for lower, upper in zip(compared, compared[1:]):
|
||||
measures: tuple[tuple[Kind, typing.Callable[[ChunkFigures], int]], ...] = (("rounds", lambda chunk: chunk.rounds_past_first), ("unfinished", lambda chunk: chunk.unfinished))
|
||||
|
||||
@@ -6,11 +6,11 @@ import typing
|
||||
from routing_figures.calls import Call, Figures, mean, summed
|
||||
from routing_figures.chunk import ChunkFigures
|
||||
from routing_figures.dollars import DIMENSIONS
|
||||
from model_routing.ladder import position
|
||||
from model_routing.ladder import Ladder
|
||||
|
||||
|
||||
def render(figures: Figures, found: list[Call], at: str, cycle: int, since: str) -> str:
|
||||
"""The figures as markdown, for the human to read. since is the latest reset's stamp, empty for none."""
|
||||
def render(ladder: Ladder, figures: Figures, found: list[Call], at: str, cycle: int, since: str) -> str:
|
||||
"""The figures as markdown, for the human to read. ladder orders the rungs, and since is the latest reset's stamp, empty for none."""
|
||||
sections = [
|
||||
"# Routing figures",
|
||||
f"Measured {at}, at cycle {cycle} across loop-claude's archive, from {figures.chunks} finished chunk{'' if figures.chunks == 1 else 's'}{f' that finished after the reset of {since}' if since else ''}. {basis(figures)}",
|
||||
@@ -19,7 +19,7 @@ def render(figures: Figures, found: list[Call], at: str, cycle: int, since: str)
|
||||
*[part for dimension in DIMENSIONS for part in (f"## Dollars by {dimension}", dollars_table(figures, dimension))],
|
||||
"## Routed chunks by the rung they started on",
|
||||
fixes_basis(figures),
|
||||
routed_table(figures),
|
||||
routed_table(ladder, figures),
|
||||
"## Escalations by trigger across every chunk, routed or not",
|
||||
f"{triggers(figures.escalated) or 'None'}.",
|
||||
"## Subagent reports against the tool results they read, in characters",
|
||||
@@ -35,8 +35,8 @@ def dollars_table(figures: Figures, dimension: str) -> str:
|
||||
return table((dimension.capitalize(), "Dollars"), [(label, money(dollars)) for label, dollars in sorted(figures.dollars[dimension].items(), key=lambda spent: -spent[1])])
|
||||
|
||||
|
||||
def routed_table(figures: Figures) -> str:
|
||||
"""One row per rung the routed chunks started on, from the bottom of the ladder up."""
|
||||
def routed_table(ladder: Ladder, figures: Figures) -> str:
|
||||
"""One row per rung the routed chunks started on, from the bottom of the ladder up, after the rungs off it."""
|
||||
return table(("Rung", "Chunks", "Review rounds past each pass's first, mean", "Unfinished verdicts, mean", "Later fixes, mean", "Subagent rungs", "Escalations by trigger"), [
|
||||
(
|
||||
str(rung),
|
||||
@@ -47,7 +47,7 @@ def routed_table(figures: Figures) -> str:
|
||||
subagent_rungs(chunks),
|
||||
triggers(summed(chunks, lambda chunk: chunk.escalated)),
|
||||
)
|
||||
for rung, chunks in sorted(figures.routed.items(), key=lambda routed: position(routed[0]))
|
||||
for rung, chunks in sorted(figures.routed.items(), key=lambda routed: ladder.position(routed[0]))
|
||||
])
|
||||
|
||||
|
||||
|
||||
@@ -26,11 +26,13 @@ from failure import Failure
|
||||
from git_cli import git_repo
|
||||
from test_env import isolated_env
|
||||
from release_plan.todo_table import Item
|
||||
from model_routing.ladder import LADDER, Rung
|
||||
from transcript_archive import outcomes, write
|
||||
from model_routing.ladder_file import read_ladder, SHIPPED
|
||||
from routing_figures.render import render
|
||||
from model_routing.route import Route
|
||||
from model_routing.ladder import Rung
|
||||
|
||||
LADDER = read_ladder(SHIPPED)
|
||||
LOW = Rung("claude-opus-5-5", "medium")
|
||||
HIGH = Rung("claude-fable-5-2", "low")
|
||||
LOW_ROUTE = Route(LOW, 7, 3, 4).worker_line()
|
||||
@@ -246,30 +248,30 @@ class Measured(unittest.TestCase):
|
||||
class Calls(unittest.TestCase):
|
||||
def test_calls_when_chunks_on_a_rung_took_more_rounds_or_unfinished_verdicts_than_the_rung_above(self):
|
||||
chunks = [figures(LOW, rounds=2)] * 5 + [figures(HIGH, unfinished=1)] * 5
|
||||
self.assertEqual(calls(totals(chunks)), [Call("rounds", (str(LOW), str(HIGH)))])
|
||||
self.assertEqual(calls(totals(chunks))[0].sentence(), f"Chunks routed onto {LOW} took more review rounds past each pass's first than chunks routed onto {HIGH}.")
|
||||
[unfinished] = calls(totals([figures(LOW, unfinished=1)] * 5 + [figures(HIGH)] * 5))
|
||||
self.assertEqual(calls(LADDER, totals(chunks)), [Call("rounds", (str(LOW), str(HIGH)))])
|
||||
self.assertEqual(calls(LADDER, totals(chunks))[0].sentence(), f"Chunks routed onto {LOW} took more review rounds past each pass's first than chunks routed onto {HIGH}.")
|
||||
[unfinished] = calls(LADDER, totals([figures(LOW, unfinished=1)] * 5 + [figures(HIGH)] * 5))
|
||||
self.assertEqual(unfinished, Call("unfinished", (str(LOW), str(HIGH))))
|
||||
self.assertEqual(unfinished.sentence(), f"Chunks routed onto {LOW} took more unfinished verdicts than chunks routed onto {HIGH}.")
|
||||
|
||||
def test_compares_the_bottom_rungs_and_calls_nothing_on_a_tie(self):
|
||||
self.assertEqual(calls(totals([figures(LADDER[0], rounds=1)] * 5 + [figures(LADDER[1])] * 5)), [Call("rounds", (str(LADDER[0]), str(LADDER[1])))])
|
||||
self.assertEqual(calls(totals([figures(LOW, rounds=1)] * 5 + [figures(HIGH, rounds=1)] * 5)), [])
|
||||
self.assertEqual(calls(totals([figures(reports={"Explore": Reports(1, 20, 20)})] * 5)), [])
|
||||
self.assertEqual(calls(LADDER, totals([figures(LADDER.rungs[0], rounds=1)] * 5 + [figures(LADDER.rungs[1])] * 5)), [Call("rounds", (str(LADDER.rungs[0]), str(LADDER.rungs[1])))])
|
||||
self.assertEqual(calls(LADDER, totals([figures(LOW, rounds=1)] * 5 + [figures(HIGH, rounds=1)] * 5)), [])
|
||||
self.assertEqual(calls(LADDER, totals([figures(reports={"Explore": Reports(1, 20, 20)})] * 5)), [])
|
||||
|
||||
def test_compares_only_rungs_with_five_chunks_each(self):
|
||||
self.assertEqual(calls(totals([figures(LOW, rounds=2)] * 5 + [figures(HIGH)] * 4)), [])
|
||||
self.assertEqual(calls(LADDER, totals([figures(LOW, rounds=2)] * 5 + [figures(HIGH)] * 4)), [])
|
||||
|
||||
def test_calls_when_a_subagent_types_reports_outgrow_the_searches_they_ran(self):
|
||||
[call] = calls(totals([figures(reports={"Explore": Reports(1, 30, 20)})] * 5))
|
||||
[call] = calls(LADDER, totals([figures(reports={"Explore": Reports(1, 30, 20)})] * 5))
|
||||
self.assertEqual(call, Call("reports", ("Explore",)))
|
||||
self.assertEqual(call.sentence(), "Explore subagents' reports took more of the worker's context than their searches would have.")
|
||||
self.assertEqual(calls(totals([figures(reports={"Explore": Reports(1, 30, 20)})] * 4)), [])
|
||||
self.assertEqual(calls(totals([figures(reports={"Explore": Reports(1, 20, 30)})] * 5)), [])
|
||||
self.assertEqual(calls(LADDER, totals([figures(reports={"Explore": Reports(1, 30, 20)})] * 4)), [])
|
||||
self.assertEqual(calls(LADDER, totals([figures(reports={"Explore": Reports(1, 20, 30)})] * 5)), [])
|
||||
|
||||
def test_renders_each_dimension_largest_first_and_the_calls(self):
|
||||
chunk = ChunkFigures({"project": collections.Counter({"a": 2.5, "b": 1234.5})}, LOW, 1, 0, collections.Counter({str(HIGH): 2}), {"Explore": Reports(2, 3, 4)}, collections.Counter(), 0.0)
|
||||
text = render(totals([chunk]), [Call("reports", ("Explore",))], "2026-10-15T00:00:00Z", 40, "")
|
||||
text = render(LADDER, totals([chunk]), [Call("reports", ("Explore",))], "2026-10-15T00:00:00Z", 40, "")
|
||||
self.assertIn("Measured 2026-10-15T00:00:00Z, at cycle 40 across loop-claude's archive, from 1 finished chunk.", text)
|
||||
self.assertIn("## Calls for a routing change\n\n- Explore subagents' reports took more of the worker's context than their searches would have.\n", text)
|
||||
self.assertIn("## Dollars by project", text)
|
||||
@@ -278,32 +280,32 @@ class Calls(unittest.TestCase):
|
||||
self.assertIn("The judge's cost counts from the verdicts and rejections that record it, so a chunk archived before they did, and a judge run that failed, add none.", text)
|
||||
self.assertNotIn("left out", text)
|
||||
self.assertNotIn("no transcript", text)
|
||||
self.assertIn("The archive holds no subagent transcript for 2 of the chunks' Agent calls.", render(totals([dataclasses.replace(chunk, lacking=1)] * 2), [], "2026-10-15T00:00:00Z", 40, ""))
|
||||
self.assertIn("$0.50 of the recorded cost is left out", render(totals([ChunkFigures({}, LOW, 0, 0, collections.Counter(), {}, collections.Counter(), 0.5), chunk]), [], "2026-10-15T00:00:00Z", 40, ""))
|
||||
self.assertIn("The archive holds no subagent transcript for 2 of the chunks' Agent calls.", render(LADDER, totals([dataclasses.replace(chunk, lacking=1)] * 2), [], "2026-10-15T00:00:00Z", 40, ""))
|
||||
self.assertIn("$0.50 of the recorded cost is left out", render(LADDER, totals([ChunkFigures({}, LOW, 0, 0, collections.Counter(), {}, collections.Counter(), 0.5), chunk]), [], "2026-10-15T00:00:00Z", 40, ""))
|
||||
self.assertIn(f"| {LOW} | 1 | 1.0 | 0.0 | unknown | {HIGH} 2 | |", text)
|
||||
two = ChunkFigures({}, HIGH, 0, 1, collections.Counter({str(HIGH): 2, str(LOW): 1}), {}, collections.Counter(), 0.0)
|
||||
self.assertIn(f"| {LOW} | 1 | 1.0 | 0.0 | unknown | {HIGH} 2 | |\n| {HIGH} | 1 | 0.0 | 1.0 | unknown | {HIGH} 2, {LOW} 1 | |", render(totals([two, chunk]), [], "2026-10-15T00:00:00Z", 40, ""))
|
||||
self.assertIn(f"| {LOW} | 1 | 1.0 | 0.0 | unknown | {HIGH} 2 | |\n| {HIGH} | 1 | 0.0 | 1.0 | unknown | {HIGH} 2, {LOW} 1 | |", render(LADDER, totals([two, chunk]), [], "2026-10-15T00:00:00Z", 40, ""))
|
||||
self.assertIn("| Explore | 2 | 3 | 4 |", text)
|
||||
escalated = render(totals([figures(escalated={2: 2}), figures(escalated={2: 1, 10: 1}), figures(start=None, escalated={3: 1})]), [], "2026-10-15T00:00:00Z", 40, "")
|
||||
escalated = render(LADDER, totals([figures(escalated={2: 2}), figures(escalated={2: 1, 10: 1}), figures(start=None, escalated={3: 1})]), [], "2026-10-15T00:00:00Z", 40, "")
|
||||
self.assertIn(f"| {LOW} | 2 | 0.0 | 0.0 | unknown | | trigger 2: 3, trigger 10: 1 |", escalated)
|
||||
self.assertIn("## Escalations by trigger across every chunk, routed or not\n\ntrigger 2: 3, trigger 3: 1, trigger 10: 1.\n", escalated)
|
||||
self.assertIn("## Escalations by trigger across every chunk, routed or not\n\nNone.\n", text)
|
||||
self.assertIn("## Calls for a routing change\n\nNone.\n", render(totals([]), [], "2026-10-15T00:00:00Z", 20, ""))
|
||||
self.assertIn("from 0 finished chunks that finished after the reset of 2026-10-14T00:00:00Z.", render(totals([]), [], "2026-10-15T00:00:00Z", 20, "2026-10-14T00:00:00Z"))
|
||||
self.assertIn("## Calls for a routing change\n\nNone.\n", render(LADDER, totals([]), [], "2026-10-15T00:00:00Z", 20, ""))
|
||||
self.assertIn("from 0 finished chunks that finished after the reset of 2026-10-14T00:00:00Z.", render(LADDER, totals([]), [], "2026-10-15T00:00:00Z", 20, "2026-10-14T00:00:00Z"))
|
||||
|
||||
def test_renders_the_mean_later_fixes_of_the_matched_chunks_and_how_many_they_are(self):
|
||||
text = render(totals([*MATCHED, figures()]), [], "2026-10-15T00:00:00Z", 40, "")
|
||||
text = render(LADDER, totals([*MATCHED, figures()]), [], "2026-10-15T00:00:00Z", 40, "")
|
||||
self.assertIn(f"| {LOW} | 4 | 0.0 | 0.0 | 1.0 (3 known) | | |", text)
|
||||
self.assertIn("## Routed chunks by the rung they started on\n\nA routed chunk's later fixes are", text)
|
||||
self.assertNotIn("later fixes", text.split("## Calls for a routing change")[0])
|
||||
|
||||
def test_counts_the_routed_chunks_whose_later_fixes_are_unknown(self):
|
||||
self.assertIn("The later fixes of 2 of the routed chunks are unknown", render(totals([*MATCHED, figures(), figures(), figures(start=None)]), [], "2026-10-15T00:00:00Z", 40, ""))
|
||||
self.assertNotIn("are unknown", render(totals(MATCHED), [], "2026-10-15T00:00:00Z", 40, ""))
|
||||
self.assertIn("The later fixes of 2 of the routed chunks are unknown", render(LADDER, totals([*MATCHED, figures(), figures(), figures(start=None)]), [], "2026-10-15T00:00:00Z", 40, ""))
|
||||
self.assertNotIn("are unknown", render(LADDER, totals(MATCHED), [], "2026-10-15T00:00:00Z", 40, ""))
|
||||
|
||||
def test_names_each_default_branch_unread(self):
|
||||
self.assertIn("## Default branches unread\n\n- log: no main branch\n", render(totals(MATCHED, unread=("log: no main branch",)), [], "2026-10-15T00:00:00Z", 40, ""))
|
||||
self.assertNotIn("branches unread", render(totals(MATCHED), [], "2026-10-15T00:00:00Z", 40, ""))
|
||||
self.assertIn("## Default branches unread\n\n- log: no main branch\n", render(LADDER, totals(MATCHED, unread=("log: no main branch",)), [], "2026-10-15T00:00:00Z", 40, ""))
|
||||
self.assertNotIn("branches unread", render(LADDER, totals(MATCHED), [], "2026-10-15T00:00:00Z", 40, ""))
|
||||
|
||||
def test_measures_once_the_count_runs_20_past_the_last_measurement(self):
|
||||
self.assertEqual([due(cycle, 20) for cycle in (39, 40, 41)], [False, True, True])
|
||||
@@ -463,7 +465,7 @@ class Archive(unittest.TestCase):
|
||||
(self.root / "broken" / "c3" / "copy.outcomes.md").write_bytes(b"\xff")
|
||||
found = archive.measure_archive(self.root, "/h", "", no_checkout)
|
||||
self.assertEqual((len(found.chunks), found.skipped), (1, ("broken", "log/c1")))
|
||||
self.assertIn("## Chunks skipped, unreadable\n\n- log/c1\n", render(totals([], ("log/c1",)), [], "2026-10-15T00:00:00Z", 20, ""))
|
||||
self.assertIn("## Chunks skipped, unreadable\n\n- log/c1\n", render(LADDER, totals([], ("log/c1",)), [], "2026-10-15T00:00:00Z", 20, ""))
|
||||
|
||||
def test_keeps_the_cycle_it_measured_at_and_reads_it_back(self):
|
||||
self.assertEqual(state.read_state(self.root), state.State(0, ()))
|
||||
|
||||
@@ -88,9 +88,9 @@ def main(argv: list[str], stdin: str) -> int:
|
||||
def breaches_of(call: Call, home: str, environ: typing.Mapping[str, str]) -> tuple[str, str, list[Breach]] | None:
|
||||
"""The text that may carry an override, what the log names the call by, and its breaches; None for a call no rule checks."""
|
||||
if call.tool == "Agent":
|
||||
return text(call.given, "prompt"), text(call.given, "subagent_type"), reviewer_breaches(call, environ)
|
||||
return text(call.given, "prompt"), text(call.given, "subagent_type"), reviewer_breaches(call, environ, home)
|
||||
if call.tool == "Skill":
|
||||
return text(call.given, "args"), text(call.given, "skill"), skill_breaches(call, environ)
|
||||
return text(call.given, "args"), text(call.given, "skill"), skill_breaches(call, environ, home)
|
||||
if call.tool == "Bash":
|
||||
command = text(call.given, "command")
|
||||
return command, command.split("\n", 1)[0], bash_breaches(command, call.cwd, home) + read_breaches(call, home) + env_file_breaches(call, home)
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
"""Refuse an Agent or Skill call that launches a review below the rung it needs, worked out from the rungs and the E + I loop-claude hands its worker: docs/decisions.md → `routing:`."""
|
||||
"""Refuse an Agent or Skill call that launches a review below the rung it needs, worked out on the project's ladder from the rungs and the E + I loop-claude hands its worker: docs/decisions.md → `routing:`."""
|
||||
import pathlib
|
||||
import typing
|
||||
|
||||
from rule_hook.rules import Breach
|
||||
@@ -6,8 +7,9 @@ from rule_hook.call import Call, text
|
||||
from failure import Failure
|
||||
from git_cli import git_repo
|
||||
from rule_hook.git import guarded_git
|
||||
from model_routing.worker_rungs import handed
|
||||
from model_routing.ladder import position, review_rung, ReviewKind, Rung
|
||||
from model_routing.worker_rungs import handed, hands_rungs
|
||||
from model_routing.ladder import Ladder, ReviewKind, Rung
|
||||
from model_routing.ladder_file import project_ladder
|
||||
from review_rules.review_passes import prose, REVIEWERS
|
||||
from claude_code.transcript import read_transcript
|
||||
from claude_code.entries import UserText
|
||||
@@ -23,29 +25,44 @@ SUBJECTS: dict[ReviewKind, str] = {"seat": "a comprehension seat", "security": "
|
||||
SECURITY_SKILLS = {"claude-security", "security-review"}
|
||||
|
||||
|
||||
def reviewer_breaches(call: Call, environ: typing.Mapping[str, str]) -> list[Breach]:
|
||||
def reviewer_breaches(call: Call, environ: typing.Mapping[str, str], home: str) -> list[Breach]:
|
||||
"""The breach of an Agent call that launches a review below its rung; none where loop-claude handed no rungs."""
|
||||
project, worker, escape_and_impact = handed(environ)
|
||||
kind = review_kind(call.given)
|
||||
if kind is None or project is None or worker is None:
|
||||
if kind is None or not hands_rungs(environ):
|
||||
return []
|
||||
required = review_rung(project, worker, escape_and_impact, kind, markdown_only(call.cwd))
|
||||
named = named_rung(call.given, worker)
|
||||
if position(named) >= position(required):
|
||||
ladder = project_ladder(call.cwd, pathlib.Path(home))
|
||||
if isinstance(ladder, Failure):
|
||||
return [unread(ladder, call.cwd)]
|
||||
project, worker, escape_and_impact = handed(environ, ladder)
|
||||
if project is None or worker is None:
|
||||
return []
|
||||
required = ladder.review_rung(project, worker, escape_and_impact, kind, markdown_only(call.cwd))
|
||||
named = named_rung(call.given, worker, ladder)
|
||||
if ladder.position(named) >= ladder.position(required):
|
||||
return []
|
||||
subject = SUBJECTS.get(kind) or text(call.given, "subagent_type")
|
||||
return [Breach("reviewer-rung", f"{subject} would run on {named}, below {required}: launch it with {required.agent_args()}", call.cwd)]
|
||||
|
||||
|
||||
def skill_breaches(call: Call, environ: typing.Mapping[str, str]) -> list[Breach]:
|
||||
def unread(ladder: Failure, cwd: str) -> Breach:
|
||||
"""The breach of a review launched where loop-claude handed rungs and the project's ladder cannot be read, so nothing tells which rung the review needs."""
|
||||
return Breach("reviewer-rung", f"the rung this review needs cannot be worked out: {ladder.reason}", cwd)
|
||||
|
||||
|
||||
def skill_breaches(call: Call, environ: typing.Mapping[str, str], home: str) -> list[Breach]:
|
||||
"""The breach of a Skill call that runs the security pass below the project's rung; none where loop-claude handed no rungs.
|
||||
|
||||
The skill runs on its caller's rung. A subagent launched as the security pass was held to the project's rung by reviewer_breaches. The worker's own rung is known, so its call is refused only below the project's rung. Any other subagent's rung is unknown, so its call is refused."""
|
||||
project, worker, _ = handed(environ)
|
||||
skill = text(call.given, "skill").lstrip("/").rsplit(":", 1)[-1]
|
||||
if skill not in SECURITY_SKILLS or project is None or worker is None or opening_prompt(call.transcript).startswith(SECURITY_OPENER):
|
||||
if skill not in SECURITY_SKILLS or not hands_rungs(environ) or opening_prompt(call.transcript).startswith(SECURITY_OPENER):
|
||||
return []
|
||||
if not call.subagent and position(worker) >= position(project):
|
||||
ladder = project_ladder(call.cwd, pathlib.Path(home))
|
||||
if isinstance(ladder, Failure):
|
||||
return [unread(ladder, call.cwd)]
|
||||
project, worker, _ = handed(environ, ladder)
|
||||
if project is None or worker is None:
|
||||
return []
|
||||
if not call.subagent and ladder.position(worker) >= ladder.position(project):
|
||||
return []
|
||||
runs_on = "on a rung rule-hook cannot see" if call.subagent else f"in this context on {worker}, below {project}"
|
||||
return [Breach("reviewer-rung", f"{skill} would run {runs_on}: invoke it from a subagent launched with {project.agent_args()}, its prompt opening with `{SECURITY_OPENER}`", call.cwd)]
|
||||
@@ -70,12 +87,12 @@ def review_kind(given: dict[str, typing.Any]) -> ReviewKind | None:
|
||||
return None
|
||||
|
||||
|
||||
def named_rung(given: dict[str, typing.Any], worker: Rung) -> Rung:
|
||||
"""The rung an Agent call's model and effort name. A call naming no model runs on the worker's model, at the effort it names or else the worker's; one naming a model but no effort runs on that model's cheapest rung."""
|
||||
def named_rung(given: dict[str, typing.Any], worker: Rung, ladder: Ladder) -> Rung:
|
||||
"""The rung an Agent call's model and effort name. A call naming no model runs on the worker's model, at the effort it names or else the worker's; one naming a model but no effort runs on that model's cheapest rung on ladder."""
|
||||
model, effort = text(given, "model"), text(given, "effort")
|
||||
if not model:
|
||||
return Rung(worker.model, effort or worker.effort)
|
||||
return Rung.from_agent(model, effort)
|
||||
return ladder.from_agent(model, effort)
|
||||
|
||||
|
||||
def markdown_only(directory: str) -> bool:
|
||||
|
||||
@@ -72,7 +72,7 @@ RULES: dict[RuleName, Rule] = {
|
||||
),
|
||||
# A rung is not a judgment call, and the refusal names the arguments to pass, so no marker waives it.
|
||||
"reviewer-rung": Rule(
|
||||
"a reviewer, a comprehension seat or the security pass runs on the rung loop-claude names for it: for a seat or the security pass the project's rung, and for a reviewer the highest of the project's rung, the worker's and the one the chunk's item's E + I picks, or the project's rung where the branch changes only Markdown no agent follows, so a worker below the project's rung cannot hand a review to its own cheaper model",
|
||||
"a reviewer, a comprehension seat or the security pass runs on the rung loop-claude names for it: for a seat or the security pass the project's rung, and for a reviewer the highest of the project's rung, the worker's and the one the chunk's item's E + I picks, or the project's rung where the branch changes only Markdown no agent follows, so a worker below the project's rung cannot hand a review to its own cheaper model. The rungs rank as on the project's routing ladder, and the review is refused while that ladder cannot be read",
|
||||
"an Agent call, in a claude loop-claude started, whose subagent type is an agent under agents/, or whose prompt opens with seat-prompts.md's opening sentence or the one larv-review's Security section sets; and a `security-review` or `claude-security` Skill call in such a claude, which runs on its caller's rung, unless the caller is a subagent whose prompt opens with that sentence",
|
||||
overridable=False,
|
||||
),
|
||||
|
||||
@@ -236,6 +236,10 @@ class OverrideLog(unittest.TestCase):
|
||||
self.assertEqual(this_chunks(LogLine("t", branch, commit, "image-pin", "r", "w"), {"base", "c1"}, "chunk", on_default), expected)
|
||||
|
||||
|
||||
# A home that holds no project config, so a review launched there is checked on the ladder this setup ships.
|
||||
HOME = "/h"
|
||||
|
||||
|
||||
class ReviewerRung(unittest.TestCase):
|
||||
# A worker routed to Sonnet 5.5 at high, on a project whose rung is Opus 5.5 at medium, with its reviewers on the project's rung.
|
||||
ENVIRON = {"LOOP_CLAUDE_PROJECT_RUNG": "claude-opus-5-5 at medium effort", "LOOP_CLAUDE_WORKER_RUNG": "claude-sonnet-5-5 at high effort", "LOOP_CLAUDE_ESCAPE_AND_IMPACT": "4"}
|
||||
@@ -243,7 +247,7 @@ class ReviewerRung(unittest.TestCase):
|
||||
ABOVE = {"LOOP_CLAUDE_PROJECT_RUNG": "claude-opus-5-5 at medium effort", "LOOP_CLAUDE_WORKER_RUNG": "claude-fable-5-2 at max effort", "LOOP_CLAUDE_ESCAPE_AND_IMPACT": "4"}
|
||||
|
||||
def refused(self, given: dict, environ: dict[str, str] = ENVIRON) -> list[str]:
|
||||
return rules(reviewer_breaches(Call("Agent", given, "/r"), environ))
|
||||
return rules(reviewer_breaches(Call("Agent", given, "/r"), environ, HOME))
|
||||
|
||||
def test_a_branch_changing_only_markdown_reviews_on_the_projects_rung_whatever_the_e_plus_i(self):
|
||||
repo = tempfile.mkdtemp()
|
||||
@@ -258,24 +262,24 @@ class ReviewerRung(unittest.TestCase):
|
||||
git(repo, "commit", "-q", "-m", "prose")
|
||||
high = self.ENVIRON | {"LOOP_CLAUDE_ESCAPE_AND_IMPACT": "7"}
|
||||
on_project = {"subagent_type": "stability-reviewer", "model": "opus", "effort": "medium"}
|
||||
self.assertEqual(rules(reviewer_breaches(Call("Agent", on_project, repo), high)), [])
|
||||
self.assertEqual(rules(reviewer_breaches(Call("Agent", {**on_project, "model": "sonnet", "effort": "high"}, repo), high)), ["reviewer-rung"])
|
||||
self.assertEqual(rules(reviewer_breaches(Call("Agent", on_project, repo), self.ABOVE)), [], "a worker that climbed doesn't lift a Markdown-only review either")
|
||||
self.assertEqual(rules(reviewer_breaches(Call("Agent", on_project, repo), high, HOME)), [])
|
||||
self.assertEqual(rules(reviewer_breaches(Call("Agent", {**on_project, "model": "sonnet", "effort": "high"}, repo), high, HOME)), ["reviewer-rung"])
|
||||
self.assertEqual(rules(reviewer_breaches(Call("Agent", on_project, repo), self.ABOVE, HOME)), [], "a worker that climbed doesn't lift a Markdown-only review either")
|
||||
for instructions in ("CLAUDE.md", "AGENTS.md", "skills/review/SKILL.md", "agents/reviewer.md", "rules/todo.md", "principles/tests.md", "workflow-bench/run-prompt.md"):
|
||||
with self.subTest(instructions=instructions):
|
||||
path = pathlib.Path(repo, instructions)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text("Do this.\n")
|
||||
self.assertEqual(rules(reviewer_breaches(Call("Agent", on_project, repo), high)), ["reviewer-rung"], "Markdown an agent follows is config")
|
||||
self.assertEqual(rules(reviewer_breaches(Call("Agent", on_project, repo), high, HOME)), ["reviewer-rung"], "Markdown an agent follows is config")
|
||||
path.unlink()
|
||||
pathlib.Path(repo, "gate.yml").write_text("on: push\n")
|
||||
self.assertEqual(rules(reviewer_breaches(Call("Agent", on_project, repo), high)), ["reviewer-rung"], "an uncommitted change to another file counts")
|
||||
self.assertEqual(rules(reviewer_breaches(Call("Agent", on_project, repo), high, HOME)), ["reviewer-rung"], "an uncommitted change to another file counts")
|
||||
git(repo, "add", ".")
|
||||
git(repo, "commit", "-q", "-m", "config")
|
||||
self.assertEqual(rules(reviewer_breaches(Call("Agent", on_project, repo), high)), ["reviewer-rung"])
|
||||
self.assertEqual(rules(reviewer_breaches(Call("Agent", on_project, repo), high, HOME)), ["reviewer-rung"])
|
||||
|
||||
def test_a_reviewer_below_the_project_rung_is_refused_naming_the_arguments_to_pass(self):
|
||||
breaches = reviewer_breaches(Call("Agent", {"subagent_type": "stability-reviewer", "model": "sonnet", "effort": "high", "prompt": "Review."}, "/r"), self.ENVIRON)
|
||||
breaches = reviewer_breaches(Call("Agent", {"subagent_type": "stability-reviewer", "model": "sonnet", "effort": "high", "prompt": "Review."}, "/r"), self.ENVIRON, HOME)
|
||||
self.assertEqual(rules(breaches), ["reviewer-rung"])
|
||||
self.assertIn("stability-reviewer", breaches[0].detail)
|
||||
self.assertIn("claude-sonnet-5-5 at high effort", breaches[0].detail)
|
||||
@@ -332,13 +336,69 @@ class ReviewerRung(unittest.TestCase):
|
||||
def test_a_claude_loop_claude_did_not_start_is_not_checked(self):
|
||||
self.assertEqual(self.refused({"subagent_type": "stability-reviewer", "model": "haiku", "effort": "low"}, {}), [])
|
||||
|
||||
def project(self, ladder: str) -> tuple[str, str]:
|
||||
"""A checkout whose config's folder holds ladder as its routing ladder, and its home."""
|
||||
home = pathlib.Path(tempfile.mkdtemp()).resolve()
|
||||
self.addCleanup(subprocess.run, ["rm", "-rf", str(home)])
|
||||
checkout = home / "code" / "acme"
|
||||
checkout.mkdir(parents=True)
|
||||
(configured(self, checkout, home=home) / "routing-ladder.json").write_text(ladder)
|
||||
return str(checkout), str(home)
|
||||
|
||||
# A project that runs on Fable 5.2 at low and at high alone, with a worker on its rung and an E + I of 5, which picks the rung one up.
|
||||
TWO_RUNGS = '[{"model": "claude-fable-5-2", "effort": "low"}, {"model": "claude-fable-5-2", "effort": "high"}]'
|
||||
ON_TWO_RUNGS = {"LOOP_CLAUDE_PROJECT_RUNG": "claude-fable-5-2 at low effort", "LOOP_CLAUDE_WORKER_RUNG": "claude-fable-5-2 at low effort", "LOOP_CLAUDE_ESCAPE_AND_IMPACT": "5"}
|
||||
|
||||
def test_a_review_is_held_to_the_rung_picked_on_the_projects_own_ladder(self):
|
||||
checkout, home = self.project(self.TWO_RUNGS)
|
||||
reviewer = {"subagent_type": "stability-reviewer", "model": "fable"}
|
||||
self.assertEqual(rules(reviewer_breaches(Call("Agent", {**reviewer, "effort": "high"}, checkout), self.ON_TWO_RUNGS, home)), [])
|
||||
# One up from Fable 5.2 at low is its medium effort on the shipped ladder, and its high effort on the project's, which holds no medium.
|
||||
breaches = reviewer_breaches(Call("Agent", {**reviewer, "effort": "medium"}, checkout), self.ON_TWO_RUNGS, home)
|
||||
self.assertEqual([breach.detail for breach in breaches], ["stability-reviewer would run on claude-fable-5-2 at medium effort, below claude-fable-5-2 at high effort: launch it with model fable, effort high"])
|
||||
self.assertEqual(rules(reviewer_breaches(Call("Agent", {**reviewer, "effort": "medium"}, "/r"), self.ON_TWO_RUNGS, HOME)), [])
|
||||
self.assertEqual(rules(breaches_of(Call("Agent", {**reviewer, "effort": "medium"}, checkout), home, self.ON_TWO_RUNGS)[2]), ["reviewer-rung"], "the hook reads the ladder under the home it is given")
|
||||
|
||||
def test_a_rung_loop_claude_handed_that_the_projects_ladder_does_not_hold_is_not_checked(self):
|
||||
# As when the ladder's file changed after loop-claude started the worker: the next cycle routes on the new ladder.
|
||||
checkout, home = self.project(self.TWO_RUNGS)
|
||||
reviewer = Call("Agent", {"subagent_type": "stability-reviewer", "model": "haiku", "effort": "low"}, checkout)
|
||||
for name in ("LOOP_CLAUDE_PROJECT_RUNG", "LOOP_CLAUDE_WORKER_RUNG"):
|
||||
with self.subTest(name=name):
|
||||
environ = self.ON_TWO_RUNGS | {name: "claude-opus-5-5 at medium effort"}
|
||||
self.assertEqual(reviewer_breaches(reviewer, environ, home), [])
|
||||
self.assertEqual(skill_breaches(Call("Skill", {"skill": "security-review"}, checkout), environ, home), [])
|
||||
|
||||
def test_a_security_skill_is_held_to_the_projects_rung_on_the_projects_own_ladder(self):
|
||||
checkout, home = self.project('[{"model": "claude-fable-5-2", "effort": "high"}, {"model": "claude-fable-5-2", "effort": "low"}]')
|
||||
# On this ladder the worker's low effort ranks above the project's high one; on the shipped ladder it ranks below.
|
||||
environ = {"LOOP_CLAUDE_PROJECT_RUNG": "claude-fable-5-2 at high effort", "LOOP_CLAUDE_WORKER_RUNG": "claude-fable-5-2 at low effort"}
|
||||
self.assertEqual(skill_breaches(Call("Skill", {"skill": "security-review"}, checkout), environ, home), [])
|
||||
self.assertEqual(rules(skill_breaches(Call("Skill", {"skill": "security-review"}, "/r"), environ, HOME)), ["reviewer-rung"])
|
||||
self.assertEqual(rules(breaches_of(Call("Skill", {"skill": "security-review"}, "/r"), home, environ)[2]), ["reviewer-rung"])
|
||||
self.assertEqual(breaches_of(Call("Skill", {"skill": "security-review"}, checkout), home, environ)[2], [])
|
||||
on_the_projects = environ | {"LOOP_CLAUDE_WORKER_RUNG": "claude-fable-5-2 at high effort"}
|
||||
self.assertEqual(skill_breaches(Call("Skill", {"skill": "security-review"}, checkout), on_the_projects, home), [], "a worker on the project's rung runs the skill itself")
|
||||
|
||||
def test_a_review_is_refused_where_the_projects_ladder_cannot_be_read_and_loop_claude_handed_rungs(self):
|
||||
checkout, home = self.project("[]")
|
||||
own = pathlib.Path(home, ".claude-projects", "acme", "routing-ladder.json")
|
||||
reviewer = Call("Agent", {"subagent_type": "stability-reviewer", "model": "fable", "effort": "max"}, checkout)
|
||||
for breaches in (reviewer_breaches(reviewer, self.ON_TWO_RUNGS, home), skill_breaches(Call("Skill", {"skill": "security-review"}, checkout), self.ON_TWO_RUNGS, home)):
|
||||
self.assertEqual(rules(breaches), ["reviewer-rung"])
|
||||
self.assertTrue(breaches[0].detail.startswith(f"the rung this review needs cannot be worked out: {own}: it holds no list of rungs. "), breaches[0].detail)
|
||||
self.assertEqual(breaches[0].directory, checkout)
|
||||
self.assertEqual(reviewer_breaches(reviewer, {}, home), [], "a claude loop-claude did not start is not checked")
|
||||
self.assertEqual(reviewer_breaches(Call("Agent", {"subagent_type": "Explore"}, checkout), self.ON_TWO_RUNGS, home), [], "nor is a subagent that reviews nothing")
|
||||
self.assertEqual(skill_breaches(Call("Skill", {"skill": "simplify"}, checkout), self.ON_TWO_RUNGS, home), [])
|
||||
|
||||
def skill_refused(self, given: dict, environ: dict[str, str] = ENVIRON, subagent_prompt: str | list | None = None) -> list[Breach]:
|
||||
transcript = ""
|
||||
if subagent_prompt is not None:
|
||||
transcript = os.path.join(tempfile.mkdtemp(), "agent-a1.jsonl")
|
||||
self.addCleanup(subprocess.run, ["rm", "-rf", os.path.dirname(transcript)])
|
||||
pathlib.Path(transcript).write_text(json.dumps({"type": "user", "message": {"role": "user", "content": subagent_prompt}}) + "\n")
|
||||
return skill_breaches(Call("Skill", given, "/r", "general-purpose" if subagent_prompt is not None else "", transcript, subagent_prompt is not None), environ)
|
||||
return skill_breaches(Call("Skill", given, "/r", "general-purpose" if subagent_prompt is not None else "", transcript, subagent_prompt is not None), environ, HOME)
|
||||
|
||||
def test_a_security_skill_from_the_sessions_own_agent_is_refused_below_the_projects_rung(self):
|
||||
for skill in ("/security-review", "claude-security", "claude-security:claude-security", "security-review"):
|
||||
@@ -358,7 +418,7 @@ class ReviewerRung(unittest.TestCase):
|
||||
with self.subTest(prompt=prompt):
|
||||
self.assertEqual(rules(self.skill_refused({"skill": "security-review"}, self.ENVIRON, prompt)), [])
|
||||
self.assertEqual(rules(self.skill_refused({"skill": "security-review"}, self.ABOVE, "Invoke /security-review.")), ["reviewer-rung"], "a subagent's rung is unknown, whatever the worker's")
|
||||
unreadable = skill_breaches(Call("Skill", {"skill": "security-review"}, "/r", "general-purpose", "/nonexistent/agent-a1.jsonl", True), self.ENVIRON)
|
||||
unreadable = skill_breaches(Call("Skill", {"skill": "security-review"}, "/r", "general-purpose", "/nonexistent/agent-a1.jsonl", True), self.ENVIRON, HOME)
|
||||
self.assertEqual(rules(unreadable), ["reviewer-rung"])
|
||||
|
||||
def test_any_other_skill_or_a_claude_loop_claude_did_not_start_is_not_checked(self):
|
||||
|
||||
@@ -4,7 +4,7 @@ import sys
|
||||
import typing
|
||||
|
||||
from failure import Failure
|
||||
from model_routing.ladder import LADDER, position, Rung
|
||||
from model_routing.ladder import Ladder, Rung
|
||||
from claude_code.reply import Limited
|
||||
from loop_state.paths import paths_from
|
||||
from loop_claude.project.model_choice import read_models_file
|
||||
@@ -32,9 +32,9 @@ def projects_on(model: str, home: pathlib.Path) -> list[str] | Failure:
|
||||
return sorted(key for key, on in models.items() if on == model)
|
||||
|
||||
|
||||
def down_from(top: Rung, floor: Rung) -> list[Rung]:
|
||||
"""top, the project's rung, and each rung below it, highest first, down to floor."""
|
||||
return list(LADDER[position(floor):position(top) + 1])[::-1]
|
||||
def down_from(ladder: Ladder, top: Rung, floor: Rung) -> list[Rung]:
|
||||
"""top, the project's rung, and each rung below it on ladder, highest first, down to floor."""
|
||||
return list(ladder.rungs[ladder.position(floor):ladder.position(top) + 1])[::-1]
|
||||
|
||||
|
||||
def limited_exit(tool: str, limited: Limited) -> int:
|
||||
|
||||
@@ -10,8 +10,10 @@ from rung_replay.command import down_from
|
||||
from failure import Failure
|
||||
from rung_replay.search import first_reply, Miss, Replay, replayed, Tried
|
||||
from claude_code.reply import Limited
|
||||
from model_routing.ladder_file import read_ladder, SHIPPED
|
||||
from model_routing.ladder import Rung
|
||||
|
||||
LADDER = read_ladder(SHIPPED)
|
||||
REFERENCE = Rung("claude-opus-5-5", "medium")
|
||||
MIDDLE = Rung("claude-sonnet-5-5", "high")
|
||||
CHEAP = Rung("claude-haiku-5-5", "max")
|
||||
@@ -73,8 +75,8 @@ class FirstReply(unittest.TestCase):
|
||||
|
||||
class DownFrom(unittest.TestCase):
|
||||
def test_runs_from_the_projects_rung_down_to_the_floor_highest_first(self):
|
||||
self.assertEqual(down_from(Rung("claude-fable-5-2", "low"), MIDDLE), [Rung("claude-fable-5-2", "low"), REFERENCE, MIDDLE])
|
||||
self.assertEqual(down_from(REFERENCE, MIDDLE), [REFERENCE, MIDDLE])
|
||||
self.assertEqual(down_from(LADDER, Rung("claude-fable-5-2", "low"), MIDDLE), [Rung("claude-fable-5-2", "low"), REFERENCE, MIDDLE])
|
||||
self.assertEqual(down_from(LADDER, REFERENCE, MIDDLE), [REFERENCE, MIDDLE])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
+1
-1
@@ -42,7 +42,7 @@ def send(config: Config, message: str, http: Http) -> Failure | None:
|
||||
|
||||
|
||||
def http_json(method: str, url: str, token: str, body: object) -> object:
|
||||
"""The JSON that url answers to the bot's request, or a Failure saying why there is none."""
|
||||
"""The JSON that url answers to the bot's request, None where the answer has no body, or a Failure saying why there is none."""
|
||||
return json_request.http_json(method, url, f"Bearer {token}", body, TIMEOUT, error_message)
|
||||
|
||||
|
||||
|
||||
+1
-1
@@ -6,4 +6,4 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
|
||||
|
||||
from subagent_rung import main
|
||||
|
||||
sys.exit(main.main(sys.argv[1:]))
|
||||
sys.exit(main.main(sys.argv[1:], pathlib.Path.home()))
|
||||
|
||||
+24
-11
@@ -7,29 +7,37 @@ a defect, a level from 1 to 4 scored as for a todo.md item. It prints the rung t
|
||||
the model's cheapest rung, the project's rung, in the Agent tool's words, such as `model sonnet,
|
||||
effort high`. --plan, for a task that files or scores todo.md items, prints the project's rung where
|
||||
that L picks a lower one, as ~/.claude/rules/todo-items.md lets only the project's rung or above
|
||||
plan. For a model off the routing ladder, the tool doesn't print anything on stdout, says so on stderr and
|
||||
exits 0; launch the subagent with no model or effort.
|
||||
plan. For a model off the routing ladder, the tool doesn't print anything on stdout, says so on stderr,
|
||||
naming the ladder's file, and exits 0; launch the subagent with no model or effort.
|
||||
|
||||
Exit 1, saying why, on bad arguments.
|
||||
It reads the routing ladder of the project whose checkout it runs in: routing-ladder.json in the
|
||||
folder of the project's config, ~/.claude-projects/<key>/, or else the one this setup ships, as in
|
||||
a checkout no config names. loop-claude --help shows the file's shape.
|
||||
|
||||
Exit 1, saying why, on bad arguments, or where the project's config or its routing ladder is faulty
|
||||
or cannot be read.
|
||||
"""
|
||||
import pathlib
|
||||
import re
|
||||
import sys
|
||||
|
||||
from failure import Failure
|
||||
from model_routing.ladder import Ladder
|
||||
from release_plan.todo_table import LEVELS
|
||||
from model_routing.ladder import planning_rung, project_rung, worker_rung
|
||||
from model_routing.ladder_file import project_ladder_file, read_ladder
|
||||
|
||||
USAGE = f"usage: subagent-rung [--plan] <model> <L>, L a level from 1 to {LEVELS['L']}"
|
||||
|
||||
|
||||
def agent_args(model: str, likelihood: int, planning: bool = False) -> str | None:
|
||||
"""The Agent tool's model and effort for the rung likelihood picks from model's cheapest rung, never below it when planning; None for a model off the ladder."""
|
||||
project = project_rung(model)
|
||||
def agent_args(ladder: Ladder, model: str, likelihood: int, planning: bool = False) -> str | None:
|
||||
"""The Agent tool's model and effort for the rung likelihood picks on ladder from model's cheapest rung, never below it when planning; None for a model off the ladder."""
|
||||
project = ladder.project_rung(model)
|
||||
if project is None:
|
||||
return None
|
||||
return (planning_rung if planning else worker_rung)(project, likelihood).agent_args()
|
||||
return (ladder.planning_rung if planning else ladder.worker_rung)(project, likelihood).agent_args()
|
||||
|
||||
|
||||
def main(argv: list[str]) -> int:
|
||||
def main(argv: list[str], home: pathlib.Path) -> int:
|
||||
if argv[:1] in (["-h"], ["--help"]):
|
||||
print(__doc__.strip())
|
||||
return 0
|
||||
@@ -39,9 +47,14 @@ def main(argv: list[str]) -> int:
|
||||
print(f"subagent-rung: cannot read the arguments{' ' + ' '.join(argv) if argv else ''}; {USAGE}", file=sys.stderr)
|
||||
return 1
|
||||
model, likelihood = operands
|
||||
args = agent_args(model, int(likelihood), planning)
|
||||
file = project_ladder_file(None, home)
|
||||
ladder = file if isinstance(file, Failure) else read_ladder(file)
|
||||
if isinstance(ladder, Failure):
|
||||
print(f"subagent-rung: {ladder.reason}", file=sys.stderr)
|
||||
return 1
|
||||
args = agent_args(ladder, model, int(likelihood), planning)
|
||||
if args is None:
|
||||
print(f"subagent-rung: {model} is not on the routing ladder; pass the Agent tool no model or effort", file=sys.stderr)
|
||||
print(f"subagent-rung: {model} is not on the routing ladder {file}; pass the Agent tool no model or effort", file=sys.stderr)
|
||||
else:
|
||||
print(args)
|
||||
return 0
|
||||
|
||||
@@ -1,33 +1,67 @@
|
||||
import pathlib
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from test_env import isolated_env
|
||||
from subagent_rung import main
|
||||
from model_routing.ladder_file import read_ladder, SHIPPED
|
||||
from project_config.test_project_config import write_config
|
||||
|
||||
LADDER = read_ladder(SHIPPED)
|
||||
TOOL = pathlib.Path(__file__).resolve().parents[1] / "subagent-rung"
|
||||
|
||||
|
||||
class SubagentRung(unittest.TestCase):
|
||||
def run_tool(self, *args: str) -> subprocess.CompletedProcess[str]:
|
||||
return subprocess.run([sys.executable, str(TOOL), *args], capture_output=True, text=True)
|
||||
def setUp(self) -> None:
|
||||
made = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(made.cleanup)
|
||||
# A home with no project config, so the tool reads the ladder this setup ships, whatever the host's own projects hold.
|
||||
self.home = pathlib.Path(made.name).resolve()
|
||||
|
||||
def run_tool(self, *args: str, cwd: pathlib.Path | None = None) -> subprocess.CompletedProcess[str]:
|
||||
return subprocess.run([sys.executable, str(TOOL), *args], capture_output=True, cwd=cwd or self.home, env={**isolated_env(), "HOME": str(self.home)}, text=True)
|
||||
|
||||
def project(self, ladder: str) -> pathlib.Path:
|
||||
"""A checkout under the home whose config's folder holds ladder as its routing ladder."""
|
||||
checkout = self.home / "code" / "acme"
|
||||
checkout.mkdir(parents=True)
|
||||
subprocess.run(["git", "init", "--quiet", str(checkout)], check=True, env=isolated_env())
|
||||
(write_config(self.home, checkout) / "routing-ladder.json").write_text(ladder)
|
||||
return checkout
|
||||
|
||||
def test_picks_the_rung_on_the_ladder_of_the_project_it_runs_in(self):
|
||||
checkout = self.project('[{"model": "claude-fable-5-2", "effort": "low"}, {"model": "claude-fable-5-2", "effort": "max"}]')
|
||||
(checkout / "nested").mkdir()
|
||||
# On the shipped ladder an L of 1 steps Fable 5.2 down to Opus 5.5, and an L of 4 up to its medium effort.
|
||||
self.assertEqual([self.run_tool("claude-fable-5-2", level, cwd=checkout / "nested").stdout for level in ("1", "4")], ["model fable, effort low\n", "model fable, effort max\n"])
|
||||
off = self.run_tool("claude-opus-5-5", "3", cwd=checkout)
|
||||
own = self.home / ".claude-projects" / "acme" / "routing-ladder.json"
|
||||
self.assertEqual((off.returncode, off.stdout, off.stderr), (0, "", f"subagent-rung: claude-opus-5-5 is not on the routing ladder {own}; pass the Agent tool no model or effort\n"))
|
||||
|
||||
def test_exits_1_naming_the_file_where_the_projects_ladder_holds_a_fault(self):
|
||||
checkout = self.project('[{"model": "claude-fable-5-2", "effort": "low"},]')
|
||||
refused = self.run_tool("claude-fable-5-2", "3", cwd=checkout)
|
||||
self.assertEqual((refused.returncode, refused.stdout), (1, ""))
|
||||
self.assertTrue(refused.stderr.startswith(f"subagent-rung: cannot read the routing ladder {self.home / '.claude-projects' / 'acme' / 'routing-ladder.json'}: "), refused.stderr)
|
||||
|
||||
def test_prints_the_agent_tools_model_and_effort_for_the_rung_an_l_picks(self):
|
||||
self.assertEqual(main.agent_args("claude-opus-5-5", 3), "model opus, effort medium")
|
||||
self.assertEqual(main.agent_args("claude-opus-5-5", 2), "model sonnet, effort high")
|
||||
self.assertEqual(main.agent_args("claude-opus-5-5", 4), "model fable, effort low")
|
||||
self.assertEqual(main.agent_args("claude-sonnet-5-5", 1), "model sonnet, effort high")
|
||||
self.assertIsNone(main.agent_args("claude-haiku-5-5", 1))
|
||||
self.assertEqual(main.agent_args(LADDER, "claude-opus-5-5", 3), "model opus, effort medium")
|
||||
self.assertEqual(main.agent_args(LADDER, "claude-opus-5-5", 2), "model sonnet, effort high")
|
||||
self.assertEqual(main.agent_args(LADDER, "claude-opus-5-5", 4), "model fable, effort low")
|
||||
self.assertEqual(main.agent_args(LADDER, "claude-sonnet-5-5", 1), "model sonnet, effort high")
|
||||
self.assertIsNone(main.agent_args(LADDER, "claude-haiku-5-5", 1))
|
||||
|
||||
def test_a_planning_task_never_runs_below_the_projects_rung(self):
|
||||
self.assertEqual(main.agent_args("claude-opus-5-5", 1, planning=True), "model opus, effort medium")
|
||||
self.assertEqual(main.agent_args("claude-opus-5-5", 4, planning=True), "model fable, effort low")
|
||||
self.assertEqual(main.agent_args(LADDER, "claude-opus-5-5", 1, planning=True), "model opus, effort medium")
|
||||
self.assertEqual(main.agent_args(LADDER, "claude-opus-5-5", 4, planning=True), "model fable, effort low")
|
||||
self.assertEqual(self.run_tool("--plan", "claude-opus-5-5", "2").stdout, "model opus, effort medium\n")
|
||||
|
||||
def test_picks_nothing_for_a_model_off_the_ladder(self):
|
||||
self.assertIsNone(main.agent_args("claude-opus-5", 3))
|
||||
self.assertIsNone(main.agent_args(LADDER, "claude-opus-5", 3))
|
||||
|
||||
def test_refuses_an_l_outside_1_to_4_or_a_wrong_count_of_arguments(self):
|
||||
for argv in (["claude-opus-5-5", "0"], ["claude-opus-5-5", "01"], ["claude-opus-5-5", "5"], ["claude-opus-5-5", "x"], ["claude-opus-5-5"], ["3", "claude-opus-5-5"], ["claude-opus-5-5", "3", "--plan"], ["--planning", "claude-opus-5-5", "3"]):
|
||||
@@ -43,7 +77,7 @@ class SubagentRung(unittest.TestCase):
|
||||
def test_the_launcher_prints_nothing_and_says_why_and_exits_0_off_the_ladder(self):
|
||||
off = self.run_tool("claude-opus-5", "4")
|
||||
self.assertEqual((off.returncode, off.stdout), (0, ""))
|
||||
self.assertEqual(off.stderr, "subagent-rung: claude-opus-5 is not on the routing ladder; pass the Agent tool no model or effort\n")
|
||||
self.assertEqual(off.stderr, f"subagent-rung: claude-opus-5 is not on the routing ladder {SHIPPED}; pass the Agent tool no model or effort\n")
|
||||
|
||||
def test_the_launcher_accepts_an_l_of_1(self):
|
||||
self.assertEqual(self.run_tool("claude-opus-5-5", "1").stdout, "model sonnet, effort high\n")
|
||||
|
||||
+16
-3
@@ -10,8 +10,8 @@ usage: todo-item list [--release <version>]
|
||||
todo-item finish <ID> [--changelog <bullet> | --no-changelog]
|
||||
|
||||
Run inside a checkout. Every command works on the plan the project's config names, which
|
||||
`project-config plan` prints: a markdown file, todo.md, or a Jira epic. A plan in a Jira epic is
|
||||
only read so far: list and show work, and add, edit, move and finish fail. Each command that changes
|
||||
`project-config plan` prints: a markdown file, todo.md, or a Jira epic. In a Jira epic, list,
|
||||
show, add and finish work, and edit and move fail so far. Each command that changes
|
||||
a todo.md ranks it as rank_todo.py does, and so reads the goals file, docs/decisions.md and the
|
||||
comprehension history, each where the config puts it.
|
||||
The cells take the format rank_todo.py --help states; the letter flags take upper case too, as --L.
|
||||
@@ -28,6 +28,11 @@ list and show read only the plan, and print no Score: an item's place in list's
|
||||
add files the item under the next free ID, with the tagline in bold, and the detail it reads from
|
||||
stdin, if any. The detail may hold no ## or ### heading.
|
||||
It prints `Filed item <ID> in <plan>.` It doesn't write anything where ranking fails or scores the item under the bar.
|
||||
In a Jira epic, add files a Task under the epic, last in the backlog, and <ID> is the new issue's
|
||||
number. The release must be one of the Jira project's Fix Versions, named as 1.2.0 or v1.2.0 there,
|
||||
and --exempt security also labels the issue `security`. No bar applies there yet. Where Jira files
|
||||
the issue and then refuses a --blocked-by link, add still prints `Filed item <ID> …`, and says on
|
||||
stderr which link to make in Jira.
|
||||
|
||||
edit sets the cells whose flag is given and leaves the rest; an empty value, as in --blocked-by "",
|
||||
empties the cell. --detail replaces the detail with the text on stdin, and --clear-detail removes it.
|
||||
@@ -43,9 +48,17 @@ file, where missing. It refuses where that section holds ### subsections: add th
|
||||
Where CHANGELOG.md holds text, finish needs --changelog or --no-changelog, so no bullet is left out by
|
||||
mistake. It prints `Finished item <ID> in <plan>.` It doesn't write anything while docs/decisions.md cites the item.
|
||||
finish <ID> --no-changelog also drops an item no chunk built.
|
||||
In a Jira epic, finish doesn't remove anything: it moves the item's issue by the transition, and to
|
||||
the status, that the config's `jira-finish-transition` and `jira-finish-status` name, as
|
||||
`project-config --help` shows. The --changelog rules hold there too, and docs/decisions.md isn't checked.
|
||||
It fails, moving no issue, where the config sets neither, where the issue has no such transition
|
||||
from its present status, or where the transition leads to another status or to one Jira doesn't
|
||||
count as done. An issue that no chunk built is dropped in Jira, not with finish, which would mark it done.
|
||||
|
||||
Exit 2 on bad arguments, and 1, saying why, on any other failure. A message opening `not filed:`,
|
||||
`not edited:`, `not moved:` or `not finished:` means it didn't write anything.
|
||||
`not edited:`, `not moved:` or `not finished:` means it didn't write anything. The one exception is an add to, or a
|
||||
finish in, a Jira epic that Jira didn't answer or answered brokenly: the message then says the issue
|
||||
may exist, or may have moved.
|
||||
"""
|
||||
import argparse
|
||||
import pathlib
|
||||
|
||||
+33
-11
@@ -17,9 +17,10 @@ Each project principle states one rule that the decisions below apply; their ent
|
||||
- bin/: the tools support only the latest stable Python, and the tests, written in plain unittest, run on it in four pytest-xdist workers
|
||||
- deploy: this repo keeps no `AGENTS.md`, since `~/.claude` is its checkout; its principles and decision titles head `docs/decisions.md`, its working rules follow them there, and its `.claude/settings.json` excludes every `.claude/CLAUDE.md`, so a session in the clone loads only the clone's `CLAUDE.md`
|
||||
- loop-claude: each verdict records the claude-config release and commit that ran it, the raw tokens each thread spent by model and kind since the previous outcome that recorded a spend, and the human's typed answer the judge quotes as reversing a choice the worker took on its own recommendation
|
||||
- loop-claude: one session per project, its id derived from the checkout's path relative to `~/code`, or to `/` outside it
|
||||
- loop-claude: one session per running loop of a project, named after the slot the loop holds, its id derived from that name; a chunk's commit in the config's folder takes only the file it changed
|
||||
- machine load: a heavy command waits for one of the machine's heavy slots, one for every 4 CPUs, which every session shares, and loop-claude starts a worker only while at least a quarter of the machine's memory is available
|
||||
- principles: about seven things per level, four or five where they act on each other, more where a reader finds them by name; crossing a limit asks for a grouping or a recorded reason
|
||||
- project config: a record may name a Confluence Cloud page as `confluence:` and its address, the loop reads and writes it as markdown, and a write never overwrites a save made since the loop's read
|
||||
- project config: a tool that reads a file's commits says where it does not support that file, and the work goes on
|
||||
- project config: `language` names the prose's language by its English name, and `commit-title`, `pull-request-title` and `branch` are brace templates over `{id}` and `{summary}`
|
||||
- project config: `plan` may name a Jira Cloud epic as `jira:` and its address, the plan is its open child issues in backlog order, and an issue's number is the item's ID
|
||||
@@ -42,7 +43,7 @@ Each project principle states one rule that the decisions below apply; their ent
|
||||
- todo.md: one table of items, scored by the formula it states, held to its bar and ranked by `bin/rank_todo.py`, which ranks each blocker above the items it blocks; each achieve goal weighs by its position, code health first and four times as heavy while the comprehension panel's overall is under the project's readability floor or unmeasured, then the goals file's goals, and a maintain goal weighs 0.5 per point of the confidence an item's test, gate leg or probe adds to it; the table's order is the plan's only order
|
||||
- todo.md: only a session or subagent on the project's rung or above scores or reshapes the plan; one below it drafts new items and changes to filed ones for a subagent at or above that rung to apply and score, and removes finished ones
|
||||
- todo.md: tools and agents read and change the plan as it stands only through `bin/plan_store` and `todo-item`; a tool that reads what a past commit held, ranks the file or checks its rank still parses `todo.md`
|
||||
- worker: a chunk's worker writes the simplest change that solves its item, test first wherever a test can check the change, and reads a technical principle only where the item, a finding or its own record names it; larv-review's reviewers hold the change to the principles and to the standards in `skills/larv-review/standards/`
|
||||
- worker: a chunk's worker writes the simplest change that solves its item, test first wherever a test can check the change, and reads a technical principle only where the item, a finding or its own record names it; larv-review's reviewers hold the change to the principles and to the project's review standards
|
||||
- workflow-bench/: the remote may show the bench cases' names and commit SHAs
|
||||
|
||||
# Working rules
|
||||
@@ -119,9 +120,9 @@ Valid while `~/.claude` is a checkout of this repo.
|
||||
|
||||
2026-10-03, lilleman. Serves goals 1.2 and 1.4. When the README's premises or those files answer the worker's question, the judge quotes the answer verbatim and the worker resumes with it, so an answer recorded there is not asked again. The judge then sees the quote as a `[loop]` line. The worker asking it again shows the quote did not settle it, and the judge sends it to the human. A backstop of three quoted answers per cycle bounds what the judge misses, such as a reworded repeat or a worker asking without end, so the worker cannot loop unattended: the fourth question that the README's premises or those files answer in one cycle goes to the human with the judge's quote. An interrupt does not reset the count, so every later question they answer in that cycle also goes to the human. Valid while the worker writes records only in a worktree, as `CLAUDE.md` → "Working with the codebase" has it, so the records the judge reads from the checkout root are merged ones.
|
||||
|
||||
2026-10-03, lilleman. Serves goal 1.2. The judge reads `~/.claude/CLAUDE.md`, each file under `~/.claude/rules/` and each file under `~/.claude/skills/larv-review/standards/` whole. The worker follows them, so a question they answer should not reach the human. Reading whole is safe, because the judge may quote only words that appear in them, and a list of sections would need keeping current.
|
||||
2026-10-03, lilleman. Serves goal 1.2. The judge reads `~/.claude/CLAUDE.md`, each file under `~/.claude/rules/` and each file in the project's review standards, the folder its config sets as `standards`, whole. The worker follows them, so a question they answer should not reach the human. Reading whole is safe, because the judge may quote only words that appear in them, and a list of sections would need keeping current.
|
||||
|
||||
2026-10-03, lilleman. Serves goal 1.2. The judge rules a chunk finished only once every answer the human typed in it is recorded. A finished chunk's session is deleted, and its answers with it, so an answer recorded nowhere would be asked again in a later chunk. Claude settled two choices lilleman's ruling left open. First, an answer counts as recorded where the files the judge reads hold it, `~/.claude/CLAUDE.md` included, or where the transcript shows the worker writing it into `README.md`'s premises, `AGENTS.md`, `docs/decisions.md`, `todo.md` or a code comment. A worker's write to `~/.claude/CLAUDE.md`, `~/.claude/rules/` or `~/.claude/skills/larv-review/standards/` does not count: the judge reads the live `~/.claude`, which holds the write only once it merges and the checkout is pulled. The judge cannot read a code comment or `todo.md`. Yet `CLAUDE.md` → "Working loop", "Ask, don't guess" puts a standing choice made in one place in a comment there. And the human's approval of a release's items, which "Working loop" requires, is the set of rows `todo.md` names for that release. The judge also reads the records once a cycle from the main checkout. That checkout may not yet hold an answer the worker wrote and merged. A judge that refused any of these would hold the chunk open every cycle. Second, only an answer a later chunk could need must be recorded, so an approval such as "merge it" doesn't hold anything open. The worker's resume prompt states the rule, so a worker whose chunk is held open knows it.
|
||||
2026-10-03, lilleman. Serves goal 1.2. The judge rules a chunk finished only once every answer the human typed in it is recorded. A finished chunk's session is deleted, and its answers with it, so an answer recorded nowhere would be asked again in a later chunk. Claude settled two choices lilleman's ruling left open. First, an answer counts as recorded where the files the judge reads hold it, `~/.claude/CLAUDE.md` included, or where the transcript shows the worker writing it into `README.md`'s premises, `AGENTS.md`, `docs/decisions.md`, `todo.md` or a code comment. A worker's write to `~/.claude/CLAUDE.md`, `~/.claude/rules/` or the project's review standards does not count: the judge reads those files where they are kept, not in the chunk's worktree, so they hold the write only once it merges and reaches there. The judge cannot read a code comment or `todo.md`. Yet `CLAUDE.md` → "Working loop", "Ask, don't guess" puts a standing choice made in one place in a comment there. And the human's approval of a release's items, which "Working loop" requires, is the set of rows `todo.md` names for that release. The judge also reads the records once a cycle from the main checkout. That checkout may not yet hold an answer the worker wrote and merged. A judge that refused any of these would hold the chunk open every cycle. Second, only an answer a later chunk could need must be recorded, so an approval such as "merge it" doesn't hold anything open. The worker's resume prompt states the rule, so a worker whose chunk is held open knows it.
|
||||
|
||||
2026-10-17, lilleman, todo item 168. The human answers an interrupt on loop-claude's terminal, and the worker resumes headless with the answer in a `-p` prompt. The judge reads that answer as a `[human]` line, not a `[loop]` one, so it holds the chunk open until the answer is recorded, as it does for an answer typed in claude.
|
||||
|
||||
@@ -141,9 +142,17 @@ Valid while `~/.claude` is a checkout of this repo.
|
||||
|
||||
2026-09-30, lilleman. Applies "Always grant explicit access to data": the sandbox `loop-claude` runs in is where access is granted, so the worker and the claude an interrupt opens run with `bypassPermissions`. The worker may read `~/.claude/.credentials.json`: it holds Claude Code's own credentials, which claude reads to run anyway. Its one seam to production is the forge: what it pushes or merges can publish through CI. Valid while `loop-claude` runs only in the sandbox README → Install names.
|
||||
|
||||
## loop-claude: one session per project, its id derived from the checkout's path relative to `~/code`, or to `/` outside it
|
||||
## loop-claude: one session per running loop of a project, named after the slot the loop holds, its id derived from that name; a chunk's commit in the config's folder takes only the file it changed
|
||||
|
||||
2026-09-21, lilleman; revised 2026-09-30 by lilleman. Serves goal 1. One fixed id per project keeps the session picker at one entry per project and makes any transcript under that id loop-claude's own to delete. A checkout outside `~/code` mirroring a path inside it shares that id, and a second loop on it is not refused. Once `todo.md` item 5 lands, the id comes from the full path, so no two checkouts share one, and `loop-claude` refuses to start while another session on that id is active. Moving the checkout orphans its open sessions, archive folder and models entry: sessions stay in the picker until the human deletes them, migration code not being worth a one-human audience. Valid while claude takes `--session-id` and resumes by it.
|
||||
2026-09-21, lilleman; revised 2026-09-30 by lilleman. Serves goal 1. Ids derived from names keep the session picker at one entry per running loop and make any transcript under those ids loop-claude's own to delete. A checkout outside `~/code` mirroring a path inside it shares that id, and a second loop on it is not refused. Once `todo.md` item 5 lands, the id comes from the full path, so no two checkouts share one, and `loop-claude` refuses to start while another session on that id is active. Moving the checkout orphans its open sessions, archive folder and models entry: sessions stay in the picker until the human deletes them, migration code not being worth a one-human audience.
|
||||
|
||||
2026-11-15, lilleman's call of 2026-11-13 in item 372, which split item 361: loops of one project, each on its own chunk, run side by side without touching each other's state. The worker's choices, for what the call left open:
|
||||
|
||||
- **A slot, not the chunk, names the session.** A loop names its session before it knows its chunk, since a rerun resumes the open session in place of running `chunk-preflight`. So each loop holds a slot, a file it keeps locked with flock under `~/.local/state/loop-claude/<key>/` (`bin/loop_claude/loop/chunk_slot.py`): the lowest free slot whose session is open, so a rerun resumes a chunk left open, or else the lowest free slot. A session lives one chunk, so one slot holds one chunk at a time. Slot 0 keeps the name every loop had before slots, so a chunk left open before slots still resumes. A reload's exec keeps the lock and hands on the slot.
|
||||
- **The archive and the route needed no change.** The archive keys each chunk by its own transcript's first line, and a rerun's route comes from the latest verdict on that transcript, so both follow the session. The routing figures are measured across all projects, under their own lock.
|
||||
- **git's own lock serializes the config folder's commits, in place of the file lock the item asked for.** `git commit` holds `.git/index.lock`, so of two commits at once the second fails, and the worker tries again. A wrapper lock would only make it wait, and a command spelled `flock … git commit` would pass rule-hook unchecked, since it reads only a command that starts with `git`. What two chunks could still break is one committing the file the other staged, so each commits only its own file, as `git commit -m <title> -- <file>` (`CLAUDE.md` → "Git, commits, and PRs").
|
||||
|
||||
Valid while claude takes `--session-id` and resumes by it, and a loop names its session before it knows its chunk.
|
||||
|
||||
## loop-claude: the archive keeps the raw transcript, and a failed archive stops the loop
|
||||
|
||||
@@ -268,6 +277,16 @@ Valid while the later fixes per finished chunk, which `score-outcomes` and the r
|
||||
|
||||
2026-10-04, lilleman. Serves goal 1.4. In a restructure, each step's scoring run measures code the next step deletes. It costs a run and, below the floor, blocks the step, yet doesn't say anything about what the restructure buys. The scoring run after the last step measures that. 2026-10-08: the paired ruling replaced the scoring run in most chunks, and the suspension covers it too; the ruling after the last step compares with the commit measured before the first step. 2026-10-13, lilleman: the comprehension check doesn't block anything now, so a suspension saves only the runs. Valid while such a decision names its items and the plan item that ends it.
|
||||
|
||||
## project config: a record may name a Confluence Cloud page as `confluence:` and its address, the loop reads and writes it as markdown, and a write never overwrites a save made since the loop's read
|
||||
|
||||
2026-11-15, larv-review, on lilleman's calls of 2026-11-12. Serves goal 1.6: a client's team keeps its records in its own wiki. Valid while one record fits one page, and while one session per project opens a record's copy, which todo.md's item 375 ends.
|
||||
|
||||
- **A bench of readers picked the spelling.** Three fresh readers, seated as the person who writes a client's `config.toml`, each picked `decisions = "confluence:https://<site>/wiki/spaces/<space>/pages/<page ID>"`, pasted from the browser with or without the title at its end, over the bare address, a page ID beside a `confluence-site` key, and a table. Each named the match with `jira:`. Any of the five records may name a page; the goals file, the plan, the working rules and the principles may not.
|
||||
- **`decisions` and `comprehension-history` may name a page only where `plan` names a Jira epic.** rule-hook ranks a plan kept as a file before tool calls, inside its 30-second limit, and ranking reads those two records. A Confluence read and two adf-codec container runs would hold up every guarded tool call, and fail it while Confluence is down. `load` refuses goals in Jira beside a plan in a file for the same reason.
|
||||
- **A write sends the version number the store read, plus one, and Confluence refuses it with 409 where someone saved the page since.** The store then fails, saying to ask the human, and doesn't write the page; the loop never overwrites a teammate's edit on its own (lilleman, 2026-11-12). A write with no read before it replaces the page as it stands, as the record contract asks.
|
||||
- **`project-record` keeps the version `open` read in a file beside its copy**, `~/.local/state/project-record/<key>/<record>.version`, since `save` runs in a later process. The store keeps the version itself, so `write` still takes only the text. Every other tool reads and writes a record in one process, and its store keeps the version in memory, so a read by another tool, such as larv-review's, never moves the version an edit in `project-record` rests on.
|
||||
- **The page holds ADF, which adf-codec converts both ways**, so a teammate reads the record as Confluence renders it. Where adf-codec cannot convert the markdown, the write fails with adf-codec's error. A node markdown cannot hold reads as text: a mention as its name, a macro as `_(<macro> not included)_`. So the next write replaces it with that text, and a record page should hold only what markdown can.
|
||||
|
||||
## project config: a tool that reads a file's commits says where it does not support that file, and the work goes on
|
||||
|
||||
2026-11-13, larv-review. Serves goal 1.6: a client's plan and records live in the config's folder, and the loop still runs there. A file the config puts outside the checkout has no commit in the project's history, so a tool that needs the file's commits cannot do its job for it. No such tool blocks the loop or a merge, and each says what it leaves undone:
|
||||
@@ -302,7 +321,8 @@ Messages keep each file's usual name, such as `todo.md`, as its label, since the
|
||||
- **An item's ID stays a whole number: the issue's number in the epic's Jira project.** About 30 modules read an ID as an int, and the `branch` and title templates already spell a ticket's name, as `ABC-{id}`. So the store refuses a child issue from another Jira project, and counts a blocker only among the plan's own items (`bin/plan_store/jira_epic.py`).
|
||||
- **The scores sit in one issue property, `plan-item`**, which needs no Jira admin (lilleman, 2026-11-12). An issue without it reads as an item nobody scored.
|
||||
- **The release is the earliest Fix Version named as a semver version**, and an issue with none fails the read, naming it, until todo.md's item 359 ties releases to something else.
|
||||
- **The store only reads**, until todo.md's item 352 writes. `rank_todo.py` refuses to rank a plan in Jira, and its `--check` passes, since Jira's backlog ranks it; rule-hook's rank check skips it. Each read first asks Jira for the epic itself, since a search under an epic the account cannot see answers no issues, as a finished plan does.
|
||||
- **The loop files an item as a Task under the epic, and marks it as its own** (lilleman's calls of 2026-11-12). `"Filed by": "loop"` in the `plan-item` property tells such an issue from one a person filed, whose summary and description the loop never edits. Task is an issue type every Jira Software project template has; a project without it refuses the issue, saying so. The issue takes the project's Fix Version named as the release, with a leading v or without, and the store refuses an item whose release the project has no Fix Version for, before it files anything. A security finding also gets the label `security`, and its text never holds a secret's value. Jira ranks the new issue last, and no bar or goals check applies, until todo.md's item 384 says where a plan in Jira states its formula. Jira takes a blocker's link only after the issue exists, so the store first checks that each blocker is an open child. A link Jira still refuses leaves the issue filed: the write counts as landed, with a note naming the link to make by hand. A failed create says the issue may exist all the same, since a lost answer doesn't tell.
|
||||
- **The store reads, files and finishes, and doesn't edit an issue** until todo.md's item 382. It finishes an item with the transition that the config's `jira-finish-transition` names, which must lead to the status `jira-finish-status` names, since each Jira workflow differs (lilleman's call, 2026-11-12); any open child of the epic may move. It refuses a status outside Jira's done status category: the read counts an issue as finished only in that category, so the item would stay in the plan. Where the issue's present status has no direct transition to the status `jira-finish-status` names, `todo-item finish` fails and a person moves the issue in Jira: the store never walks an issue through other statuses to reach it. lilleman answered on 2026-11-15: "If it is possible to move it to done without a transisiont, that should happen. If not, fail." The implementer read "without a transition" as "without a transition in between". `rank_todo.py` refuses to rank a plan in Jira, and its `--check` passes, since Jira's backlog ranks it; rule-hook's rank check skips it. Each read first asks Jira for the epic itself, since a search under an epic the account cannot see answers no issues, as a finished plan does.
|
||||
|
||||
## project config: `tooling-on-host = true` lets a project with no container setup run its language runtime, package manager, tests and task runner on the host
|
||||
|
||||
@@ -316,7 +336,7 @@ Messages keep each file's usual name, such as `todo.md`, as its label, since the
|
||||
|
||||
2026-10-15, lilleman asked for it through todo item 144, implemented by claude. Serves goal 1.1: a cheap reviewer that finds the work below standard can have a more capable one check that ruling, and work below standard gets a more capable rung to fix it, unless the fix changes only prose.
|
||||
|
||||
The work is below standard where systems-architect returns BLOCK, a reviewer reports a finding against larv-review's `standards/quality.md`, or `record-ruling` counts a comprehension seat's vote in a paired ruling as worse. That reviewer or seat may ask, and the worker then relaunches it on the rung loop-claude's prompt names, one above the rung it ran on. `bin/loop_claude/cycle/prompts.py`'s `reruns` names it: the seats run on the project's rung, and the reviewers on the highest of the worker's rung and the one their item's E + I picks. Off the ladder, or for a reviewer or seat already on the top rung, the prompt names none, and its report stands.
|
||||
The work is below standard where systems-architect returns BLOCK, a reviewer reports a finding against the review standards' `quality.md`, or `record-ruling` counts a comprehension seat's vote in a paired ruling as worse. That reviewer or seat may ask, and the worker then relaunches it on the rung loop-claude's prompt names, one above the rung it ran on. `bin/loop_claude/cycle/prompts.py`'s `reruns` names it: the seats run on the project's rung, and the reviewers on the highest of the worker's rung and the one their item's E + I picks. Off the ladder, or for a reviewer or seat already on the top rung, the prompt names none, and its report stands.
|
||||
|
||||
A reviewer's relaunch gets the report that asked and confirms or dismisses each of its findings with a reason, so no finding goes unanswered; a seat's relaunch reads afresh, since a seat reports no findings. The relaunch's report stands in place of the one that asked, in the same round, so it adds no round, and a relaunch cannot ask again. So the round cap still bounds a pass, and one round launches a reviewer at most twice. The ruling that stands is the fourth escalation trigger in `CLAUDE.md`, except where the fix changes only prose: the worker fixes that on its own rung. lilleman ruled that on 2026-11-08 through todo item 276, after PR #432's two quality findings were false claims, one in a docstring and one in a sentence of this file. lilleman also ruled that no ruling raises the judge's rung, which `routing: on a model judge-replay covered` sets.
|
||||
|
||||
@@ -531,9 +551,9 @@ On 2026-11-12, `bin/judge-replay claude-opus-5-5` replayed 60 verdicts, 15 of ea
|
||||
|
||||
Valid while the archived verdicts show what a judge should return, and until a new model joins the ladder: replay then.
|
||||
|
||||
## routing: one ladder of (model, effort) rungs, ordered by the Artificial Analysis Intelligence Index; a task's L picks its worker's rung and its E + I its reviewers', by fixed steps counted from the cheapest rung of the project's model
|
||||
## routing: one ladder of (model, effort) rungs, ordered by the Artificial Analysis Intelligence Index, shipped as `bin/model_routing/routing-ladder.json`, which a project may replace with a file of that name in its config's folder; a task's L picks its worker's rung and its E + I its reviewers', by fixed steps counted from the cheapest rung of the project's model
|
||||
|
||||
2026-10-14, lilleman. Serves goal 1.4, and goal 1.3: one ladder, the same in every project, read by loop-claude and by the worker through `bin/subagent-rung`. The judge's rung is set by `routing: on a model judge-replay covered`. `bin/model_routing/ladder.py` holds the rungs and the steps.
|
||||
2026-10-14, lilleman. Serves goal 1.4, and goal 1.3: one shipped ladder and one set of steps for every project, read by loop-claude and by the worker through `bin/subagent-rung`; a project runs on other rungs only through a ladder file of its own (2026-11-15 note). The judge's rung is set by `routing: on a model judge-replay covered`. `bin/model_routing/routing-ladder.json` holds the rungs and `ladder.py` beside it the steps.
|
||||
|
||||
The rungs, least competent first: Sonnet 5.5 at high; Opus 5.5 at medium; Fable 5.2 at low and medium; Opus 5.5 at xhigh; Fable 5.2 at high and max. The 2026-11-11 note below put them so. Before it they were Sonnet 5.5 at high; Opus 5.5 at medium, high, xhigh and max; Fable 5.1 at max, after the 2026-10-29 note took Haiku 5.5 off. They first were: Haiku 5.5 at low, medium, high, xhigh and max; Sonnet 5.5 at high; Opus 5.5 at medium, high, xhigh and max; Fable 5.1 at max. The order and the cut come from the Artificial Analysis Intelligence Index (https://artificialanalysis.ai/leaderboards/models), which scores each model at each effort and gives a cost per task. A rung stays only where no cheaper rung scores as high, so a step up always buys more score (goal 1.4). The first cut, from the index read 2026-10-14, dropped Sonnet 5.5 at low, medium, xhigh and max, Opus 5.5 at low, and every Fable 5.1 rung, and every tie in the index fell among the dropped rungs. lilleman put Fable 5.1 at max back on top: the index scored it under Opus 5.5 at high, but Anthropic's model catalog names Fable the most capable model, and for the hardest tasks lilleman wants the highest quality at any price. Fable 5.2 at max tops the index outright, so that exception has ended.
|
||||
|
||||
@@ -553,6 +573,8 @@ A project's rung is its model's cheapest rung, which for Opus 5.5 is its default
|
||||
|
||||
2026-11-14, lilleman ruled that L 3 is to step one rung up and L 4 two up, in every project and for delegated subagents. The steps stated above, L 3 none and L 4 one up, hold until `bin/model_routing/ladder.py` changes. Then, on an Opus 5.5 project, an L 3 worker or subagent runs on Fable 5.2 at low, and an escalation stops without lilleman's yes at Opus 5.5 at xhigh. An L 4 one runs on Fable 5.2 at medium, and stops at Fable 5.2 at high. The ruling settles the two calls of the routing figures measured at 2026-11-14T00:59:50Z, which were not yet in `routing-calls-raised.md`; the chunk that settles them cites their stamp there. The figures came from 276 chunks finished since the 2026-10-29 reset. Chunks started on Opus 5.5 at medium, 79 of them, took a mean 0.8 review rounds past each pass's first, 0.3 unfinished verdicts and 0.2 later fixes. Chunks started on Fable 5.2 at low, 5 of them, took 0.4, 0.0 and 0.0. On an Opus 5.5 project only L 4 items start on Fable 5.2 at low, so it did better on harder items. Two things weaken the evidence: 5 chunks is the fewest a call allows, and the Opus 5.5 figures include chunks from before Fable 5.2 joined the ladder. On the 2026-11-11 index, an L 3 task's cost rises about 1.3 times, from $2.45 to $3.10, for fewer rounds and fewer unfinished verdicts (goal 1.4). The chunks started on Sonnet 5.5 at high, 164 of the 276, don't move.
|
||||
|
||||
2026-11-15, lilleman asked for the ladder as a file that a project can replace, on a day when an outage left only Fable 5.2 answering: the rungs were a constant in `bin/model_routing/ladder.py`, so no project could leave Sonnet 5.5 and Opus 5.5 without a release. The shipped ladder is `bin/model_routing/routing-ladder.json`, a JSON list of rungs, least competent first. A project that keeps a `routing-ladder.json` in its config's folder, `~/.claude-projects/<key>/`, runs on that ladder whole, and the steps count on it as on the shipped one. Every project still runs the same routing rules and steps, so the workflow of goal 1.3 holds; the ladder joins what a project's config folder may supply, which that goal's list does not name yet. lilleman chose a file per project over one per machine, so a single project can differ. A ladder holds one model of each family, since the Agent tool launches a subagent or a review by its family's name. The project's file is lilleman's to write, as any change to the ladder is, and the loop never commits it. loop-claude reads the project's ladder as each cycle starts; `subagent-rung` and rule-hook's `reviewer-rung` read it each time they run, from the checkout they run in. A ladder file that holds a fault stops each of them, since work routed on the shipped ladder in its place could run on a model the project cannot reach. The routing figures, `judge-replay` and `review-replay` span every project, so they read the shipped ladder: a rung only a project's own ladder holds is left out of the figures' calls, and no replay qualifies it. lilleman shipped the change as 0.10.1, a patch cut from the tag v0.10.0, on the day of the outage: it adds a file format and an exit 1 to `subagent-rung`, which the technical principles' semantic versioning gives a minor, and lilleman asked for the patch "even if that breaks semver", so that the release in use could run again without taking the unreleased work on `main`.
|
||||
|
||||
Valid while the index ranks these models, and while no newer model joins the catalog.
|
||||
|
||||
## routing: the worker changes rung only as a chunk starts, after every second unfinished verdict, when it names a chunk item that picks a higher rung, or when it cites an escalation trigger the judge finds
|
||||
@@ -720,7 +742,7 @@ Four choices the item left open:
|
||||
|
||||
`rules/todo-items.md` loads when a session itself reads or writes a `todo.md`, which a session that runs `todo-item` never does, so `CLAUDE.md` → "Topic rules" asks for it before an item is filed, scored, edited or moved. A reviewer without a shell reads the plan from the listing `larv-review reviewer-header` writes, which the header's `Plan:` line names. Valid while `todo-item` is the only command that changes a plan's items.
|
||||
|
||||
## worker: a chunk's worker writes the simplest change that solves its item, test first wherever a test can check the change, and reads a technical principle only where the item, a finding or its own record names it; larv-review's reviewers hold the change to the principles and to the standards in `skills/larv-review/standards/`
|
||||
## worker: a chunk's worker writes the simplest change that solves its item, test first wherever a test can check the change, and reads a technical principle only where the item, a finding or its own record names it; larv-review's reviewers hold the change to the principles and to the project's review standards
|
||||
|
||||
2026-10-13, lilleman through todo item 104, implemented by claude. Serves goals 1.4 and 1.5. Like red, green, refactor: the worker makes the item work, and the review passes raise it to the bar. A loop-claude worker loaded `CLAUDE.md` and every file under `rules/`, 4,247 words, and `CLAUDE.md` told it to read `technical-principles.md` too, 2,426 words more. The reviewers read the principles anyway, and a finding against one names it.
|
||||
|
||||
|
||||
@@ -2169,3 +2169,83 @@ Read most (opens and searches):
|
||||
- `agents/principles-auditor.md` 2
|
||||
- `bin/larv_review/main.py` 2
|
||||
- `bin/larv_review/plan.py` 2
|
||||
|
||||
## Reading cost, chunk b3bdb6c3ea26, finished 2026-11-15T02:08:49Z
|
||||
|
||||
103160 new input tokens before the first commit.
|
||||
|
||||
Read most (opens and searches):
|
||||
|
||||
- `rules/todo-items.md` 3
|
||||
- `todo.md` 2
|
||||
- `bin/chunk_preflight/choices.py` 1
|
||||
- `bin/chunk_preflight/facts.py` 1
|
||||
- `bin/chunk_preflight/gathered.py` 1
|
||||
- `bin/chunk_preflight/main.py` 1
|
||||
- `bin/release_plan/release_standing.py` 1
|
||||
- `docs/decisions.md` 1
|
||||
- `docs/score-anchors.md` 1
|
||||
|
||||
## Reading cost, chunk 6cc45aabfc70, finished 2026-11-15T10:19:26Z
|
||||
|
||||
81857 new input tokens before the first commit.
|
||||
|
||||
Read most (opens and searches):
|
||||
|
||||
- `docs/score-anchors.md` 3
|
||||
- `bin/plan_store/jira_epic.py` 2
|
||||
- `bin/plan_store/stores.py` 2
|
||||
- `rules/todo-items.md` 2
|
||||
- `bin/adf_codec/convert.py` 1
|
||||
- `bin/plan_store/contract.py` 1
|
||||
|
||||
## Reading cost, chunk e42be6f8dd66, finished 2026-11-15T11:13:36Z
|
||||
|
||||
175773 new input tokens before the first commit.
|
||||
|
||||
Read most (opens and searches):
|
||||
|
||||
- `bin/project_config/test_project_config.py` 5
|
||||
- `bin/record_store/test_stores.py` 5
|
||||
- `bin/project_config/settings.py` 4
|
||||
- `bin/rest_client/test_json_request.py` 4
|
||||
- `README.md` 3
|
||||
- `bin/plan_store/jira_epic.py` 3
|
||||
- `bin/project_config/main.py` 3
|
||||
- `bin/project_record/main.py` 3
|
||||
- `docs/decisions.md` 3
|
||||
- `bin/adf_codec/convert.py` 2
|
||||
|
||||
## Reading cost, chunk 85cc03e9b3e9, finished 2026-11-15T11:46:29Z
|
||||
|
||||
195738 new input tokens before the first commit.
|
||||
|
||||
Read most (opens and searches):
|
||||
|
||||
- `bin/project_config/test_project_config.py` 8
|
||||
- `bin/loop_claude/test_loop_claude.py` 7
|
||||
- `bin/loop_claude/loop/usage.py` 6
|
||||
- `README.md` 5
|
||||
- `docs/decisions.md` 5
|
||||
- `bin/larv_review/test_larv_review.py` 4
|
||||
- `CLAUDE.md` 3
|
||||
- `bin/loop_claude/project/records.py` 3
|
||||
- `bin/project_config/main.py` 3
|
||||
- `bin/project_config/settings.py` 3
|
||||
|
||||
## Reading cost, chunk 09532b58c32b, finished 2026-11-15T13:01:57Z
|
||||
|
||||
152048 new input tokens before the first commit.
|
||||
|
||||
Read most (opens and searches):
|
||||
|
||||
- `README.md` 5
|
||||
- `bin/project_config/settings.py` 5
|
||||
- `bin/plan_store/jira_epic.py` 4
|
||||
- `bin/project_config/main.py` 4
|
||||
- `bin/todo_item/main.py` 4
|
||||
- `bin/plan_store/test_jira_epic.py` 3
|
||||
- `bin/project_config/test_project_config.py` 3
|
||||
- `bin/plan_store/stores.py` 2
|
||||
- `docs/decisions.md` 2
|
||||
- `CHANGELOG.md` 1
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@ paths:
|
||||
|
||||
# Todo items (`todo.md`)
|
||||
|
||||
- **A plan is mandatory in every project, and a plan kept as `todo.md` has the shape `rank_todo.py --help` shows**, which `~/.claude/bin/rank_todo.py` checks and ranks; its `--help` shows a valid file. A plan in a Jira epic is read from the epic's open child issues, and `todo-item` can't write one yet. Below, `todo.md` means a plan kept as a file, and "the plan" either kind. `## Scoring` holds the formula and the bar; `## Items` is one table of every item; `## Details` holds each item's detail under its ID. `## Renamed` marks each renamed release with a line such as `- 0.2.1 renamed to 0.3.0`; `rank_todo.py --help` says what a mark does. Cite an item by its ID. The formula and bar are the project's own to tune.
|
||||
- **A plan is mandatory in every project, and a plan kept as `todo.md` has the shape `rank_todo.py --help` shows**, which `~/.claude/bin/rank_todo.py` checks and ranks; its `--help` shows a valid file. A plan in a Jira epic is read from the epic's open child issues. `todo-item add` files an item there as a new child issue, and `todo-item finish` moves an item's issue to done, and `todo-item` can't edit or move an issue yet. Below, `todo.md` means a plan kept as a file, and "the plan" either kind. `## Scoring` holds the formula and the bar; `## Items` is one table of every item; `## Details` holds each item's detail under its ID. `## Renamed` marks each renamed release with a line such as `- 0.2.1 renamed to 0.3.0`; `rank_todo.py --help` says what a mark does. Cite an item by its ID. The formula and bar are the project's own to tune.
|
||||
- **File an item with `~/.claude/bin/todo-item add`, and change one with `todo-item edit` or `todo-item move`.** `add` and `edit --detail` read the item's detail from stdin, and all three commands rank the plan; `todo-item --help` shows the flags. `todo-item finish <ID> --no-changelog` drops an item no chunk built. Edit `todo.md` itself only for what `todo-item` has no command for: `## Scoring`, `## Renamed`, and reshaping an old table.
|
||||
- **Order items only by score and the Blocked by column.** An item's Blocked by cell lists the IDs of the items that must be done before it starts, such as `12, 14`; `rank_todo.py --help` says how it ranks them. No text in `todo.md` outside the table orders items: where an item must go first, score it so, and say why in its detail.
|
||||
- **Plan only on the project's rung or above.** loop-claude's prompt tells you when you run below it. Below it, never score or re-score an item, move it between releases, split a milestone into items, delete an item under the bar, rewrite a filed item's tagline or detail, or choose or replace an item in `docs/score-anchors.md`. Draft each new item, each change to a filed item, and each change to the anchors, instead. Before your next commit, launch one subagent to apply the drafts, score them and set their release. Launch it on the rung `CLAUDE.md`'s delegation rule gives a subagent that files or scores items. Keep the scores and releases it writes. For a security finding, launch it at once. Any rung may remove a finished item's row and detail, and score a delegated task's L. A subagent launched for another task leaves the plan alone.
|
||||
|
||||
@@ -9,7 +9,7 @@ You orchestrate, fix, and ship; reviewers only report. Run every reviewer in the
|
||||
|
||||
**Forge-neutral.** Five PR operations recur below: read a PR's diff, open a draft PR, read check status, mark ready, merge. On GitHub and Gitea, `~/.claude/bin/chunk-pr` opens the draft PR, marks it ready and merges it. Read the diff and the checks with the forge's own CLI, `gh` or `tea` per `~/.claude/CLAUDE.md` → "Git, commits, and PRs". On any other forge, achieve all five through its CLI or API — discover how rather than assuming. A forge without a native draft state gets the closest equivalent (a `WIP:`/`Draft:` title prefix); note any approximation in the summary.
|
||||
|
||||
The bar a chunk is reviewed to: ~/.claude/skills/larv-review/standards/quality.md. Words: `~/.claude/CLAUDE.md` → "Vocabulary". What a reviewer reports: ~/.claude/skills/larv-review/review-findings.md; how you resolve it: §3 → "Findings".
|
||||
The bar a chunk is reviewed to: `quality.md` in the project's review standards, the folder `~/.claude/bin/project-config standards` prints. Words: `~/.claude/CLAUDE.md` → "Vocabulary". What a reviewer reports: ~/.claude/skills/larv-review/review-findings.md; how you resolve it: §3 → "Findings".
|
||||
|
||||
**An ask** holds only what it asks about; the rest runs on while it waits. No user reachable (a headless run) → finish the rest, then leave the PR unmerged with the question and your recommendation in the summary, unless the ask's rule names another branch.
|
||||
|
||||
@@ -65,7 +65,7 @@ Give a reviewer without Bash `git ls-files`'s output in its prompt, since some h
|
||||
|
||||
`~/.claude/bin/larv-review` holds this section's mechanical rules: the chunk's review folder, the round count, the paired ruling's base and vote count, the scoring run's trigger; the history's format, its latest places and its count of how often seats agree; and the header of each reviewer's prompt. Run it in the chunk's worktree; `~/.claude/bin/larv-review --help` states each rule. On exit 1, repair what its message names and run it again; when you cannot, ask the user.
|
||||
|
||||
**Reports.** Run `~/.claude/bin/larv-review reviewer-header <pass>` in the chunk's worktree, and open each prompt to an agent under `~/.claude/agents/` with what it prints; then say in a few lines what the change does and which files it touches. The command makes the chunk's review folder and writes the branch diff and the plan's listing into it. The header names that diff, the reviewer's full report, `<pass>-round-<n>.md`, in the folder, the folder of technical principles the project's config sets, the listing, and for architecture and stability the places too. For a reviewer whose definition starts it without `CLAUDE.md`, the header's last line names the file that holds the project principles and decision titles, which the reviewer reads first. For a relaunch one rung up, add `--rerun`: the report becomes `<pass>-round-<n>-rerun.md`, and the header names the report that asked. Before you answer a 🔴 or 🟡, read its entry: Grep the report for the finding's place, with the lines after it, rather than Read the whole report. rule-hook refuses a reviewer's Edit and MultiEdit, and any Write outside `~/.local/state/larv-review/`. Keep the folder after the merge: `review-replay` replays a round from the reports its prompt names.
|
||||
**Reports.** Run `~/.claude/bin/larv-review reviewer-header <pass>` in the chunk's worktree, and open each prompt to an agent under `~/.claude/agents/` with what it prints; then say in a few lines what the change does and which files it touches. The command makes the chunk's review folder and writes the branch diff and the plan's listing into it. The header names that diff, the reviewer's full report, `<pass>-round-<n>.md`, in the folder, the folders of technical principles and review standards the project's config sets, the listing, and for architecture and stability the places too. For a reviewer whose definition starts it without `CLAUDE.md`, the header's last line names the file that holds the project principles and decision titles, which the reviewer reads first. For a relaunch one rung up, add `--rerun`: the report becomes `<pass>-round-<n>-rerun.md`, and the header names the report that asked. Before you answer a 🔴 or 🟡, read its entry: Grep the report for the finding's place, with the lines after it, rather than Read the whole report. rule-hook refuses a reviewer's Edit and MultiEdit, and any Write outside `~/.local/state/larv-review/`. Keep the folder after the merge: `review-replay` replays a round from the reports its prompt names.
|
||||
|
||||
**Precedent, then ask** — for the full scan:
|
||||
|
||||
@@ -104,7 +104,7 @@ A fix meets every row it fits. Prose has no row, so a comment or doc edit inside
|
||||
|
||||
**What a round reviews.** An agent under `~/.claude/agents/` reviews the branch in round 1. From round 2 it reviews only the answers to its last round's findings, and each fix from another pass that re-entered its pass. Prompt it with the path of its last round's report and each finding's answer: the fix's diff, or the reason it was dismissed. Give it each other pass's fix as `git diff <the commit before that fix> <the fix's commit>`, since the fixes may be unpushed, with the finding it answered. It reports only an answer that is plainly wrong or worse than the change it answered, so its pass converges in its second round. Other reviewers review the branch as their tool does.
|
||||
|
||||
**Rung up.** A reviewer rules the work below standard when its report holds systems-architect's BLOCK or a finding against `standards/quality.md`. A comprehension seat does when `record-ruling` counts one of its votes as worse.
|
||||
**Rung up.** A reviewer rules the work below standard when its report holds systems-architect's BLOCK or a finding against the review standards' `quality.md`. A comprehension seat does when `record-ruling` counts one of its votes as worse.
|
||||
|
||||
- **Ask.** Such a reviewer or seat may end its report asking for a rerun one rung up. Relaunch it only on the rung loop-claude's prompt names for it; where the prompt names none, the report stands.
|
||||
- **Relaunch.** Relaunch a reviewer on that rung with the same prompt, except for its header, made with `--rerun` per "Reports"; its report stands in place of the report that asked, in the same round. Relaunch a seat with the same prompt alone; its line replaces the one that asked in the votes file, before `record-ruling` runs. A relaunch cannot ask again.
|
||||
@@ -115,7 +115,7 @@ A fix meets every row it fits. Prose has no row, so a comment or doc edit inside
|
||||
- **Outside the chunk.** A finding outside the chunk's change, whatever its pass or severity, is scored and filed in `todo.md` per `~/.claude/rules/todo-items.md`. A 🔴 is marked `defect`. A 🟡 against a file in the config's principles folder is marked `principle`, its detail naming the principle, where no other reason fits. One under the bar and not exempt is named in the summary with its score. A verified security HIGH is handled per "Security". In the release review the whole project is the chunk's change, so nothing lies outside it; "Release review" → "Findings" says which of its findings are filed.
|
||||
- **Goal or decision.** A fix that would change a goal, or a `docs/decisions.md` entry the repo held before the chunk began, is asked; no user reachable → filed, marked `question`, the goal or decision left as is.
|
||||
- **New decision.** Each decision a fix or an answer records in `docs/decisions.md` is checked against the project principles per `~/.claude/rules/decisions.md` → "Decisions: one home, each linked to a goal or a technical principle", "Check each new decision against the project's principles", before the commit that records it.
|
||||
- **🔴.** A 🔴 is fixed, or shown factually wrong, and what disproved it recorded per `~/.claude/skills/larv-review/standards/comments.md` → "Where a choice goes": in a comment at the code the finding concerns, or in `docs/decisions.md` when it concerns more than one place. Never declined.
|
||||
- **🔴.** A 🔴 is fixed, or shown factually wrong, and what disproved it recorded per the review standards' `comments.md` → "Where a choice goes": in a comment at the code the finding concerns, or in `docs/decisions.md` when it concerns more than one place. Never declined.
|
||||
- **🟡.** A 🟡 is fixed, shown factually wrong like a 🔴, or declined. Decline one only where the reason is sound, consistent with the goals and the technical principles, and confidence is very high; the decline and its reason are recorded the same way. A reason neither speaks to is a gap in the goals: fix the finding, or ask per `~/.claude/CLAUDE.md` → "Working loop", "Ask, don't guess"; no user reachable → fix. Never drop one silently, and never decline one for convenience or the size of the fix.
|
||||
- **🟢 and ❓.** A 🟢 or ❓ is fixed, answered, declined in the summary with its reason, or filed. Answer one where the code, a test, a goal or a decision the repo held before the chunk began settles it, and quote what in the summary. A ❓ only the user can answer is asked; no user reachable → filed, marked `question`.
|
||||
- **🔀.** A 🔀 runs the named reviewer's pass once the current pass is done.
|
||||
|
||||
@@ -12,7 +12,7 @@ A reviewer reads and reports; it doesn't edit anything. It writes no file but it
|
||||
- ❓ **question** for the author: a finding you could not confirm goes here, not above.
|
||||
- 🔀 **escalation** — names the reviewer whose concern it is (`product-owner-reviewer`, `systems-architect` or `/security-review`) and why, in one line.
|
||||
|
||||
A finding against a technical principle names it and the file in the config's principles folder it lives in. A finding against `~/.claude/skills/larv-review/standards/quality.md` names that file and the rule it breaks.
|
||||
A finding against a technical principle names it and the file in the config's principles folder it lives in. A finding against `quality.md`, in the folder your prompt's `Review standards:` line names, names that file and the rule it breaks.
|
||||
|
||||
## Misread
|
||||
|
||||
@@ -28,14 +28,14 @@ A review's first line, derived from the findings:
|
||||
|
||||
## Rung up
|
||||
|
||||
Where your report holds a finding against `~/.claude/skills/larv-review/standards/quality.md`, or you are systems-architect and return BLOCK, you may end it with the line `Rerun one rung up` when you want a more capable reviewer to check that ruling.
|
||||
Where your report holds a finding against `quality.md`, or you are systems-architect and return BLOCK, you may end it with the line `Rerun one rung up` when you want a more capable reviewer to check that ruling.
|
||||
|
||||
## Report
|
||||
|
||||
Write your full report with the Write tool to the file your prompt names. The file is the worker's input, which it searches for each finding's entry, so write it even where your harness says to return findings directly. It holds the verdict, then every finding with its place, its evidence and its fix, as your agent file shapes them. Then return only:
|
||||
|
||||
- the verdict line
|
||||
- one line per finding, in this order: its severity mark, `[misread]` where you marked the finding so, its place, and what is wrong, in one sentence. Where the finding breaks `standards/quality.md` or a file in the config's principles folder, end the line with that file's name. For a 🔀, end it with the reviewer it names. Example: ``🟡 `bin/example.py:42` `parse`: an empty line raises IndexError (technical-principles.md)``
|
||||
- one line per finding, in this order: its severity mark, `[misread]` where you marked the finding so, its place, and what is wrong, in one sentence. Where the finding breaks the review standards' `quality.md` or a file in the config's principles folder, end the line with that file's name. For a 🔀, end it with the reviewer it names. Example: ``🟡 `bin/example.py:42` `parse`: an empty line raises IndexError (technical-principles.md)``
|
||||
- for stability-reviewer, whether the tests passed, and at which commit
|
||||
- `Rerun one rung up`, where your report ends with it
|
||||
- the report's path
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
**A README covers what a reader needs *before* opening the code**: how it meets its goals, and how to build, test, run, and deploy it. It does **not** narrate an individual symbol, file, or test case — whoever wants to know what a test asserts opens the test, where the answer is exact and cannot drift.
|
||||
|
||||
**Refresh `README.md` only to keep it true.** A change that alters a build/test/run/deploy step, a required env var, or a prerequisite makes the README a false claim by omission, fixed per `~/.claude/skills/larv-review/standards/quality.md` → "A false claim is a bug". Otherwise most changes need no README edit at all. GOOD: `run-tests.sh` gained a required `--profile` flag → update the documented command. BANNED: the change added a test case → add a paragraph describing it.
|
||||
**Refresh `README.md` only to keep it true.** A change that alters a build/test/run/deploy step, a required env var, or a prerequisite makes the README a false claim by omission, fixed per the review standards' `quality.md` → "A false claim is a bug". Otherwise most changes need no README edit at all. GOOD: `run-tests.sh` gained a required `--profile` flag → update the documented command. BANNED: the change added a test case → add a paragraph describing it.
|
||||
|
||||
## Package README (what someone finds on npm or GitHub)
|
||||
- The public API is the contract, so the README documents it: options, results, events, everything exported. The rule against narrating a file or test case still holds.
|
||||
|
||||
@@ -6,19 +6,18 @@
|
||||
|
||||
`Bar = 0.1`
|
||||
|
||||
`Next ID = 382`
|
||||
`Next ID = 389`
|
||||
|
||||
## Items
|
||||
|
||||
| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |
|
||||
|---|---|---|---|---|---|---|---|---|---|---|---|
|
||||
| 352 | 0.11.0 | | | **Write a project's plan to its Jira epic: file items as child issues, edit those the loop filed, score unscored issues with a comment, and move a finished item to the status its config names.** | 3 | 2 | 3 | 6 | 5 | 1.6 by 6 | 1.2 |
|
||||
| 355 | 0.11.0 | | | **Store a record on the Confluence Cloud page its config names, as markdown converted through the adf-codec shim, and interrupt the human when a teammate saved the page since the loop read it.** | 3 | 2 | 3 | 6 | 5 | 1.6 by 6 | 1.2 |
|
||||
| 356 | 0.11.0 | | | **Hand reviewers the review standards from the folder a project's config names, in place of `~/.claude/skills/larv-review/standards/`.** | 2 | 2 | 3 | 5 | 2 | 1.6 by 3 | 1.1 |
|
||||
| 372 | 0.11.0 | | | **Key loop-claude's session, archive, routing state and config-folder commits per chunk, so two chunks of one project run side by side without touching each other's state.** | 3 | 2 | 3 | 6 | 6 | 1.5 by 3 | 0.4 |
|
||||
| 374 | 0.11.0 | 372 | decision | **Merge open chunks one at a time: rebase, finish the item in todo.md and CHANGELOG.md, rerun the gate and the paired ruling, and keep a chunk waiting for approval in the queue without blocking the next.** | 4 | 2 | 3 | 7 | 6 | 1.5 by 4, 1.6 by 3 | 1.0 |
|
||||
| 374 | 0.11.0 | | decision | **Merge open chunks one at a time: rebase, finish the item in todo.md and CHANGELOG.md, rerun the gate and the paired ruling, and keep a chunk waiting for approval in the queue without blocking the next.** | 4 | 2 | 3 | 7 | 6 | 1.5 by 4, 1.6 by 3 | 1.0 |
|
||||
| 386 | 0.11.0 | | | **Key project-record's copies per worktree, so two chunks of one project editing the same record kept outside a file don't overwrite each other's unsaved edit.** | 2 | 2 | 2 | 4 | 2 | 1.1 by 2 | 0.8 |
|
||||
| 359 | 0.11.0 | | | **Tie a project's releases to what its config names: semver tags, Jira Fix Versions, sprints, or none.** | 3 | 2 | 3 | 6 | 4 | 1.6 by 3 | 0.8 |
|
||||
| 375 | 0.11.0 | 372, 374 | decision | **Run up to the project's configured number of chunks at once, each in its own window of one tmux session named for the project, mark a window whose chunk waits for the human, and refuse to start without tmux at the needed version.** | 4 | 2 | 3 | 7 | 7 | 1.5 by 7 | 0.6 |
|
||||
| 382 | 0.11.0 | | | **Edit a Jira issue the loop filed, and score an unscored issue a teammate filed with a comment saying why.** | 4 | 2 | 3 | 7 | 4 | 1.6 by 3 | 0.8 |
|
||||
| 384 | 0.11.0 | | | **Rank an issue the loop files in Jira by its score among the issues the loop filed, a security finding first.** | 3 | 2 | 2 | 5 | 3 | 1.6 by 2 | 0.7 |
|
||||
| 375 | 0.11.0 | 374 | decision | **Run up to the project's configured number of chunks at once, each in its own window of one tmux session named for the project, mark a window whose chunk waits for the human, and refuse to start without tmux at the needed version.** | 4 | 2 | 3 | 7 | 7 | 1.5 by 7 | 0.6 |
|
||||
| 319 | 0.12.0 | | | **Start a fresh session with a brief of the chunk when a rung step changes the worker's model, in place of resuming the old session.** | 3 | 2 | 3 | 6 | 4 | 1.1 by 2, 1.4 by 2 | 1.2 |
|
||||
| 309 | 0.12.0 | | | **Run a scoring run's second pass on one head with two seats in place of four, once `larv-review agreement` shows the seats agree with each other more than a run agrees with its rerun.** | 2 | 2 | 2 | 4 | 2 | 1.4 by 3 | 1.2 |
|
||||
| 299 | 0.12.0 | | | **Replay the archived judge verdicts through code rules and a classifier trained locally on the archive, and file an item for each verdict kind one of them decides with no missed interrupt.** | 2 | 2 | 2 | 4 | 3 | 1.4 by 3 | 1.0 |
|
||||
@@ -31,14 +30,15 @@
|
||||
| 331 | 0.12.0 | | | **Reword four decisions to expire when the rungs their replays tested change, not whenever a model joins the ladder.** | 1 | 1 | 1 | 1 | 2 | 1.4 by 2 | 0.8 |
|
||||
| 381 | 0.12.0 | | | **Read a `Touches:` list from a plan kept in Jira as from one in todo.md, with a test that converts a description through `adf_codec`.** | 1 | 2 | 1 | 2 | 2 | 1.5 by 2 | 0.7 |
|
||||
| 327 | 0.12.0 | | | **Have `larv-review` print a round commit's title prefix, counted from the round's report, and have rule-hook refuse a round title whose counts differ from it.** | 3 | 2 | 3 | 6 | 4 | 1.1 by 1, 1.4 by 1 | 0.6 |
|
||||
| 365 | 0.13.0 | 352 | | **Have `score-outcomes` read the finished and dropped items of a plan outside the checkout, from the project repo's history or from Jira's issue changelogs.** | 3 | 2 | 2 | 5 | 4 | 1.6 by 2, 1.1 by 2 | 1.2 |
|
||||
| 368 | 0.13.0 | 352 | | **Call a release review due, call a release ready to cut, and tell whether a chunk owes a scoring run, for a plan outside the checkout, from the project repo's history or from Jira.** | 3 | 2 | 2 | 5 | 4 | 1.6 by 2, 1.1 by 2 | 1.2 |
|
||||
| 366 | 0.13.0 | 352 | | **Count the chunks of a project whose plan sits outside the checkout in the routing figures, from the project repo's history or from Jira.** | 3 | 2 | 2 | 5 | 4 | 1.6 by 2, 1.4 by 2 | 1.1 |
|
||||
| 367 | 0.13.0 | 352 | | **Check that every write to a Jira plan leaves it ranked, as rule-hook's `todo-rank-check` checks `todo.md` today.** | 2 | 2 | 3 | 5 | 3 | 1.6 by 2 | 0.7 |
|
||||
| 365 | 0.13.0 | 382 | | **Have `score-outcomes` read the finished and dropped items of a plan outside the checkout, from the project repo's history or from Jira's issue changelogs.** | 3 | 2 | 2 | 5 | 4 | 1.6 by 2, 1.1 by 2 | 1.2 |
|
||||
| 368 | 0.13.0 | 382 | | **Call a release review due, call a release ready to cut, and tell whether a chunk owes a scoring run, for a plan outside the checkout, from the project repo's history or from Jira.** | 3 | 2 | 2 | 5 | 4 | 1.6 by 2, 1.1 by 2 | 1.2 |
|
||||
| 366 | 0.13.0 | 382 | | **Count the chunks of a project whose plan sits outside the checkout in the routing figures, from the project repo's history or from Jira.** | 3 | 2 | 2 | 5 | 4 | 1.6 by 2, 1.4 by 2 | 1.1 |
|
||||
| 367 | 0.13.0 | 382, 384 | | **Check that every write to a Jira plan leaves it ranked, as rule-hook's `todo-rank-check` checks `todo.md` today.** | 2 | 2 | 3 | 5 | 3 | 1.6 by 2 | 0.7 |
|
||||
| 303 | 0.14.0 | | defect | **Archive each judge run's prompt and json reply beside the verdict it gave, so judge cost, replays and backups cover the judge as they cover the worker.** | 2 | 2 | 3 | 5 | 3 | 1.4 by 3, 3 by 2 | 4.2 |
|
||||
| 306 | 0.14.0 | | | **Set a strategy that keeps loop-claude's archive and larv-review's review folders backed up and small over the years, compressing older entries without losing any.** | 3 | 2 | 4 | 7 | 5 | 3 by 5 | 3.9 |
|
||||
| 304 | 0.14.0 | 303 | defect | **Archive each review-replay and judge-replay run's transcript beside its result, so a replay that decided a rung can be checked and re-priced later.** | 2 | 2 | 2 | 4 | 3 | 1.4 by 2, 3 by 2 | 3.8 |
|
||||
| 287 | 0.14.0 | | | **Move the forge helpers `Forge`, `forge_of`, `runner`, `open_pull`, `merged_pull`, `pull_at`, `gitea`, `checks_passed` and `required_checks` into one module that `chunk_preflight`, `chunk_pr`, `deploy_release` and `larv_review` all import from, so no tool imports another tool's internals for them.** | 3 | 1 | 3 | 5 | 5 | code health by 3 | 2.9 |
|
||||
| 387 | 0.14.0 | | | **Bind a project's rung to its ladder in one value, so the routing functions and `Cycle` take one argument for both.** | 3 | 1 | 3 | 5 | 5 | code health by 3 | 2.9 |
|
||||
| 338 | 0.14.0 | | owner | **Script each step that 0.9.0's chunks repeated by hand and a program can compute, filing one item per step, and file this audit again for the next release.** | 1 | 2 | 1 | 2 | 2 | 1.4 by 3, 1.5 by 3 | 2.3 |
|
||||
| 288 | 0.14.0 | | | **Point the two reading-cost decisions at code health and goal 1.4's counter-signal, in place of the goal 1.1 they cite.** | 1 | 2 | 1 | 2 | 1 | code health by 1, 1.4 by 1 | 2.2 |
|
||||
| 77 | 0.14.0 | | | **Teach `bin/metric-bench` Go and TypeScript, rerun it once two projects' comprehension histories name places, and bring into review only a metric that tracks the panel.** | 4 | 2 | 1 | 5 | 6 | 1.1 by 7, 1.4 by 7 | 2.1 |
|
||||
@@ -60,6 +60,7 @@
|
||||
| 5 | 0.14.0 | | decision | **Key a project on its checkout's full path, and refuse to start while another session uses that key.** | 4 | 2 | 3 | 7 | 5 | 1.1 by 6 | 1.4 |
|
||||
| 291 | 0.14.0 | | owner | **Let `principles/technical-principles.md` → "Sane defaults" allow a library whose README goals ask that it work with no config to default the clock and randomness in its public constructor, where a documented option overrides each.** | 1 | 2 | 3 | 4 | 1 | 1.2 by 3 | 1.3 |
|
||||
| 156 | 0.14.0 | | decision | **Drop `rank_todo.py`'s ranking of an old-shape table once no project under `~/code` holds one.** | 2 | 1 | 3 | 4 | 4 | 1.1 by 4 | 1.2 |
|
||||
| 388 | 0.14.0 | | | **Refuse an agent's Write or Edit of a routing ladder file in rule-hook, since a change to the ladder is the human's.** | 1 | 1 | 3 | 3 | 2 | 1.2 by 3 | 1.2 |
|
||||
| 260 | 0.14.0 | | decision | **Compare the first 20 chunks whose worker got the reading rule with the 20 before them, on review rounds past each pass's first, unfinished verdicts, 🔴, 🟡 and misread findings, dollars and hours per chunk, and drop the rule where any rose.** | 1 | 2 | 1 | 2 | 2 | 1.4 by 3 | 1.2 |
|
||||
| 51 | 0.14.0 | | principle | **Hand loop-claude's terminal output to an injected effect, so no storage or retry function prints.** | 2 | 1 | 3 | 4 | 5 | 1.1 by 5 | 1.1 |
|
||||
| 201 | 0.14.0 | | owner | **Save the human's tmux setups and restore them after a reboot, so work is up and running again quickly.** | 3 | 2 | 1 | 4 | 4 | 1.5 by 4 | 1.1 |
|
||||
@@ -78,26 +79,6 @@
|
||||
|
||||
## Details
|
||||
|
||||
### 352. Write a project's plan to its Jira epic: file items as child issues, edit those the loop filed, score unscored issues with a comment, and move a finished item to the status its config names.
|
||||
|
||||
lilleman's calls, 2026-11-12. Without asking, the loop may create child issues in the epic, edit the summary, description and scores of issues it created, and comment on and transition any issue in the epic. It never edits the summary or description of an issue a person filed. An issue a teammate files without scores gets scored like any item, with a short comment saying it was scored and why; its scope stays as written. A finished item moves by the transition and to the status the config names, since each Jira workflow differs. An issue the loop files goes into Jira rank by its score among the issues the loop filed. A security finding is filed in the epic like any item, labelled `security` and ranked first, never with a secret's value. R is above 5, so this item ships alone.
|
||||
|
||||
### 355. Store a record on the Confluence Cloud page its config names, as markdown converted through the adf-codec shim, and interrupt the human when a teammate saved the page since the loop read it.
|
||||
|
||||
lilleman's calls, 2026-11-12: one page per record, whose ID the config names. The loop reads the page's ADF as portable markdown and writes markdown back through adf-codec. It writes with the version number it read; where Confluence reports a newer version, the loop asks the human, and never overwrites a teammate's edit on its own. Auth: email plus API token from the project's env file. The page is one more `RecordStore` in `bin/record_store/stores.py`, held to `contract.py`. `store` picks it by the setting's value. `project-config` and `chunk-preflight` print each record's setting as a path, so make both print a page's setting as it is written. `write` takes only the text, so the store itself keeps the version it read.
|
||||
|
||||
### 356. Hand reviewers the review standards from the folder a project's config names, in place of `~/.claude/skills/larv-review/standards/`.
|
||||
|
||||
lilleman's call, 2026-11-12: the folder replaces the default, as item 347's principles folder does. Readers: the reviewers under `agents/`, the judge's records, larv-review, and the repo check that keeps the standards present.
|
||||
|
||||
### 372. Key loop-claude's session, archive, routing state and config-folder commits per chunk, so two chunks of one project run side by side without touching each other's state.
|
||||
|
||||
lilleman's call, 2026-11-13, splitting item 361. Items 373 to 375 run several chunks of one project at once. Today a project has one session and one chunk at a time. This item makes two loop-claudes in one project, each on its own chunk, safe to run side by side. It doesn't yet start them; item 375 does that.
|
||||
|
||||
Key per chunk, not per project: the worker's session, which `session_named` names after the project, the archive keys and routing's state. Serialize item 345's commits to the config's folder, `~/.claude-projects/<key>/`, with a file lock, since two chunks may commit there at once. Leave `todo.md`'s and `CHANGELOG.md`'s edits to item 374, which moves them to merge time. A test runs two loops in one project and checks that neither reads or overwrites the other's state.
|
||||
|
||||
`bin/loop_claude/cycle/run.py:154` `rule` and `run.py:94` `archived` are places the comprehension seats found hard: the archive helpers sit in the cycle runner, and `rule` archives twice in an order only the code states. Make them easier to read where the archive keys change.
|
||||
|
||||
### 374. Merge open chunks one at a time: rebase, finish the item in todo.md and CHANGELOG.md, rerun the gate and the paired ruling, and keep a chunk waiting for approval in the queue without blocking the next.
|
||||
|
||||
lilleman's call, 2026-11-13, splitting item 361, which also asked that a chunk keep waiting for a human approval while others run. With several chunks open, `chunk-pr merge` merges one pull request at a time. For each it rebases the branch onto the default branch, then writes the item's `todo-item finish` and its changelog bullet, then reruns the gate, then merges. Moving those edits to merge time keeps `todo.md` and `CHANGELOG.md` out of every chunk's conflicts.
|
||||
@@ -106,10 +87,46 @@ Where the rebase conflicts, the chunk's worker resolves it, and only the review
|
||||
|
||||
`bin/chunk_preflight/choices.py:80` `forge_of` is a place the comprehension seats found hard: forge code split across tools. Where this item touches it, build on item 287's forge module if that has shipped.
|
||||
|
||||
### 386. Key project-record's copies per worktree, so two chunks of one project editing the same record kept outside a file don't overwrite each other's unsaved edit.
|
||||
|
||||
Found in item 372's chunk. `project-record open` writes a record kept on a Confluence page to a copy under `~/.local/state/project-record/<key>/`, keyed by the project alone (`bin/project_record/main.py`, `COPIES`). Two chunks of one project, running side by side as item 375 will run them, share that copy: the second `open` rewrites it, and the first chunk's unsaved edit is lost. Key the copy by the worktree as well as the project.
|
||||
|
||||
Touches:
|
||||
- `bin/project_record/main.py`: `(module)` (small)
|
||||
- `bin/project_record/test_project_record.py`
|
||||
|
||||
### 359. Tie a project's releases to what its config names: semver tags, Jira Fix Versions, sprints, or none.
|
||||
|
||||
lilleman's call, 2026-11-12: what a release is differs per client. With none, items name no release, and the architecture and principles passes the release review runs need another trigger, which this item settles and records. Readers: `rank_todo.py`'s release order, chunk-preflight's next release, loop-claude's "release ready to cut", larv-review's release review, `CLAUDE.md` → "Working loop". Cutting a release stays the human's.
|
||||
|
||||
### 382. Edit a Jira issue the loop filed, and score an unscored issue a teammate filed with a comment saying why.
|
||||
|
||||
Split from item 352 on 2026-11-15; lilleman's calls, 2026-11-12. The loop edits the summary, description and scores of issues it created, which the `Filed by` mark in the `plan-item` property tells apart, and never the summary or description of an issue a person filed. An issue a teammate files without scores gets scored like any item, with a short comment saying it was scored and why; its scope stays as written. The comment reaches the client's team, so it is in the project's `language`, and its reason comes from whoever scores: `PlanStore.edit` and `todo-item edit` gain a way to pass it, whose spelling a bench of readers picks. Say in `docs/decisions.md` whether the loop may re-score or move a person's issue that already holds scores; the calls name neither.
|
||||
|
||||
Touches:
|
||||
- `bin/plan_store/jira_epic.py`: `JiraPlan.edit`
|
||||
- `bin/plan_store/test_jira_epic.py`: new tests of `edit`
|
||||
- `bin/plan_store/stores.py`: `PlanStore.edit`, `FilePlan.edit`
|
||||
- `bin/todo_item/main.py`: the help, `edit`'s flags
|
||||
|
||||
### 384. Rank an issue the loop files in Jira by its score among the issues the loop filed, a security finding first.
|
||||
|
||||
Split from item 352 on 2026-11-15; lilleman's call, 2026-11-12: an issue the loop files goes into Jira rank by its score among the issues the loop filed, and a security finding ranks first. The team's own rank of every other issue stays as it is.
|
||||
|
||||
lilleman's answer, 2026-11-15: a plan in Jira states its score formula and its bar as two settings in the project's `config.toml`. They hold what a `todo.md` states under `## Scoring`: a formula such as `100 * V / (2**S + 8)`, and a bar such as `1`. A bench of readers, seated as the person who writes a client's `config.toml`, picks the two settings' spelling. A config that names an epic as its plan and leaves them out fails to load, saying which to add, since no path setting has a default either.
|
||||
|
||||
With the two settings, `JiraPlan.add` scores the new item as `bin/release_plan/ranking.py` scores a row of `todo.md`: it reads the goals file, the decision log and the comprehension history for the weights. It refuses an item under the bar that isn't exempt, and checks that Moves names goals the goals file holds. Then it asks Jira to rank the new issue just before the first issue the loop filed that scores lower. A security finding goes before the first issue the loop filed that isn't one.
|
||||
|
||||
Touches:
|
||||
- `bin/plan_store/jira_epic.py`: `JiraPlan`, `JiraPlan.add`, `Issue`, and a new function that places the issue
|
||||
- `bin/plan_store/stores.py`: `store`
|
||||
- `bin/plan_store/test_jira_epic.py`: new tests of the bar and the rank
|
||||
- `bin/project_config/main.py`: the help
|
||||
- `bin/project_config/settings.py`: `OPTIONAL`, `ProjectConfig`, `load`
|
||||
- `bin/release_plan/ranking.py`: `read_scoring`, so a formula and a bar from the config score an item
|
||||
- `bin/todo_item/main.py`: the help's lines on `add` in a Jira epic
|
||||
- `docs/decisions.md`: "project config: `plan` may name a Jira Cloud epic …"
|
||||
|
||||
### 375. Run up to the project's configured number of chunks at once, each in its own window of one tmux session named for the project, mark a window whose chunk waits for the human, and refuse to start without tmux at the needed version.
|
||||
|
||||
lilleman's call, 2026-11-13, splitting item 361. lilleman knows tmux and prefers it. loop-claude runs each chunk in its own window of one tmux session named for the project, such as session `loop-claude-config` with windows `item-372` and `item-373`. It runs up to the number of chunks the project's config allows at once, with 1 as the default, and starts the next chunk item 373's pass allows as each one merges. It uses tmux even at 1, so every project runs the same workflow (goal 1.3). Each window holds a loop-claude for its one chunk, so the interrupt and `/talk` work there as on any terminal. When a chunk waits for the human, loop-claude marks its window, renaming it to end in ` ?` and ringing the bell so tmux's status bar shows it, and clears the mark once it is answered. The DM each interrupt sends names the session and window to answer in, such as `loop-claude-config:item-372`, so the human goes straight to it.
|
||||
@@ -250,6 +267,12 @@ Both comprehension seats of PR #453's paired ruling (2026-11-09) named this web
|
||||
|
||||
Put the seven helpers in a folder named by what it holds, such as `bin/forge/`, and import them from there. Keep each helper's behaviour and its tests. `chunk_preflight/choices.py` keeps `pulls_command`, which is preflight's own. Check `docs/decisions.md` for a mention of where a helper lives, and update it.
|
||||
|
||||
### 387. Bind a project's rung to its ladder in one value, so the routing functions and `Cycle` take one argument for both.
|
||||
|
||||
Filed by PR #553, which made the routing ladder a file a project may replace. Its stability round 1 found two places the comprehension seats name as hard, touched and no easier to read: `bin/loop_claude/routing.py` `unfinished_route` took `ladder` as a fourth parameter, and `Cycle` in `bin/loop_claude/cycle/run.py` gained the field `ladder`. The patch threaded the ladder as an argument, since a wider change did not fit a patch cut during an outage.
|
||||
|
||||
12 functions in `routing.py` take `ladder` only to pass it on beside `project`, and 6 of `Ladder`'s methods in `bin/model_routing/ladder.py` take `project` first. One value that holds the project's rung with the ladder it stands on removes the extra argument from each, and gives `Cycle` back the field count it had. Make `unfinished_route` and `Cycle` easier to read while there: both are places the seats found hard.
|
||||
|
||||
### 338. Script each step that 0.9.0's chunks repeated by hand and a program can compute, filing one item per step, and file this audit again for the next release.
|
||||
|
||||
lilleman asked, on 2026-10-16, for a standing audit each release, so the loop keeps moving work a program does as well from the model to scripts (goals 1.4 and 1.5). This audit reads the archived transcripts of the chunks that shipped release 0.9.0 for every step that chunks repeated by hand, before, during or after review. It keeps the steps whose answer a program computes the same way each time, such as a lookup, a check, a prompt assembled for a reviewer, a cleanup. File one item per such step, with the time and tokens it cost, into the next release with items left. Leave a step that needs judgement with the model. Run `command-patterns 0.9.0` first; its table names the patterns, and `read_threads` and `calls` in `bin/command_patterns/tally.py` open the calls of one pattern, or `command-patterns 0.9.0 --calls <file>` dumps them all as JSON lines. The 0.7.0 audit found that most steps its chunks repeated were already scripted by that release's own tools, so a step a shipped item already covers is not filed.
|
||||
@@ -406,6 +429,12 @@ The key names the project's session, archive folder and models entry. `project_k
|
||||
|
||||
While `rank_todo.py` ranks two shapes, projects follow two sets of scoring rules, against goal 1.3. Once every project has reshaped, drop `OLD_SHAPE`'s weighing from `bin/release_plan/ranking.py`, `RESHAPE`, and the old shape's lines in `rank_todo.py --help` and `rules/todo-items.md`. Keep `todo_table` reading old tables: `score_outcomes` reads every past merge's `todo.md`. PR #283's paired ruling found the old-shape path made `ranking.py`'s `score`, `Scoring.weights`, `unknown_columns` and `todo_table.py`'s `Moves` harder to read; leave each easier, with one shape and moves that are always moves, and the Moves cell's rules in one place. Release 0.3.0's seats named `ranking.py`'s `score`, `weigh` and `rank` and `todo_table.py`'s `OLD_SHAPE` for the same fork: "every rule exists twice for the old table shape" (Mid A). Make `weigh` and `rank` easier to read too.
|
||||
|
||||
### 388. Refuse an agent's Write or Edit of a routing ladder file in rule-hook, since a change to the ladder is the human's.
|
||||
|
||||
Filed by PR #553, which made the routing ladder a file: `bin/model_routing/routing-ladder.json`, and a project's own `routing-ladder.json` in its config's folder. `CLAUDE.md` → "Working loop", "Ask, don't guess" reserves a change to the routing ladder for the human, and until PR #553 the ladder was code, which only a reviewed chunk changed. A worker can now write its project's file, and with it choose the rungs its own later cycles and reviews run on. The security pass of PR #553 noted that a ladder changed mid-cycle also makes rule-hook's `reviewer-rung` skip its check, since the rungs loop-claude handed are then off the ladder.
|
||||
|
||||
Project principle 4 asks that a rule a program can check is enforced by a program. Refuse a Write, an Edit and a MultiEdit of a file named `routing-ladder.json` under `~/.claude-projects/`, with no override, and say that the ladder is the human's to change. The shipped file stays editable in the setup's own checkout, where a chunk's review covers it.
|
||||
|
||||
### 260. Compare the first 20 chunks whose worker got the reading rule with the 20 before them, on review rounds past each pass's first, unfinished verdicts, 🔴, 🟡 and misread findings, dollars and hours per chunk, and drop the rule where any rose.
|
||||
|
||||
Start once 20 chunks have run under the rule. The rule is `READING_RULE` in `bin/loop_claude/cycle/prompts.py`, which every fresh worker prompt holds; `git log --first-parent -S READING_RULE` on the default branch finds the merge that added it. A chunk got it when its first worker started after that merge. Measure as `docs/decisions.md` → `loop-claude: the worker's claude compacts its context before it fills a 200k window…` measured the window: rounds past each pass's first and the 🔴, 🟡 and misread counts from the round commit titles, unfinished verdicts from the outcomes files, hours from the worker's first message to its last, and dollars from the chunk's `cost-state` entry. Compare means, since the decision weighs the rule by all spend.
|
||||
|
||||
Reference in New Issue
Block a user