Compare commits
121 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| d01d0d421e | |||
| a921b08207 | |||
| e2c4e94cb2 | |||
| 251b0e8f02 | |||
| 55235a07d8 | |||
| 96e1b364f1 | |||
| 30b0e9e0a7 | |||
| 255d5f7bb1 | |||
| 986697ab52 | |||
| fa9d487afd | |||
| fbd1b5e99d | |||
| f3eaf19f62 | |||
| 4e02971bfe | |||
| 3fd7e15255 | |||
| 2de1e7e74e | |||
| eecb0387ca | |||
| 7fc64d860a | |||
| 00c1dd2480 | |||
| f768ef3272 | |||
| cf1180734c | |||
| 727ed70ecb | |||
| 9d9c5a3352 | |||
| 2db4759c2a | |||
| 9d685c52b3 | |||
| c56b3166a0 | |||
| b6a53ef98b | |||
| c46a117088 | |||
| 121aba05ea | |||
| eb5a63edd2 | |||
| 2707cfc04e | |||
| 53a54e50dd | |||
| 2e9d9dd714 | |||
| 0681e9be17 | |||
| 2fdc75d035 | |||
| bad76b07c8 | |||
| 9dd8441f3b | |||
| 1210f8cd68 | |||
| 0f0ba7fa43 | |||
| 37078cffa9 | |||
| 30129051ad | |||
| 58055f0fac | |||
| 55ad029df2 | |||
| b89ac805d3 | |||
| 8b649682dc | |||
| 4447e89e48 | |||
| 3c522160c9 | |||
| 39bf6e6d94 | |||
| 0339a515fc | |||
| 75c3c581ef | |||
| cca16e702a | |||
| 36d9ddb6f5 | |||
| dbc8cfe854 | |||
| fffba3d454 | |||
| 2695e9b530 | |||
| 4873ee9e74 | |||
| 70e3c0b9de | |||
| 93a4da0728 | |||
| bcb04e32d4 | |||
| 37fcedc5bf | |||
| e18555be3e | |||
| 2136413dd6 | |||
| e37518db29 | |||
| 9e0a6d4d7b | |||
| aff46cd64e | |||
| 0109f97cd7 | |||
| 85f3b74d4f | |||
| 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 |
@@ -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
|
||||
|
||||
+15
-2
@@ -2,7 +2,16 @@
|
||||
|
||||
## Unreleased
|
||||
|
||||
- `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 and finishing an issue still happen in Jira.
|
||||
- A config whose `plan` names a Jira epic must now set `jira-score-formula` and `jira-score-bar`, and fails to load without them. `todo-item add` scores the item by them, refuses one under the bar unless it is exempt, and ranks the new issue among the issues the loop filed: questions first, then security findings, then by score. A person's issues keep their rank.
|
||||
- `todo-item edit` and `move` work on a plan kept in a Jira epic. They change only an issue the loop filed, and never a link. Of an issue a person filed, `edit` sets only the scores, and posts the new `--comment` on the issue to tell the team why; a plan in a file takes the flag and keeps no comment.
|
||||
- A release someone else cut while it still held plan items no longer stops the loop: those items count as the next release's, `chunk-preflight` tells the worker to move them there, and `loop-claude` routes on them. Where the plan names no later release and `todo.md` named none since the cut, the loop still asks which release they belong to.
|
||||
- `project-record open` now writes the copy of a record kept outside a file under a folder of the worktree that ran it, `~/.local/state/project-record/<key>/<worktree>/`, so two chunks of one project no longer overwrite each other's unsaved edit. It also removes the folders of worktrees git no longer lists.
|
||||
- `chunk-pr merge` merges the chunks of one project on a machine one at a time, and `--finish <ID>` finishes each plan item in the chunk's turn, so `todo.md` and `CHANGELOG.md` no longer conflict between open chunks. A pull request that waits for an approval leaves the queue while it waits, and merge stops where a reviewer's comment waits for an answer.
|
||||
- `loop-claude` runs each chunk in its own window of one tmux session per project, `loop-<key>`, and needs tmux 3.2 or later. Up to the config's new optional `parallel-chunks` chunks run at once, 1 by default; a chunk starts beside the others only where its item's `Touches:` prediction overlaps none of theirs. `loop-claude <task>` starts the windows and attaches to the session, and as a chunk finishes, its loop starts the next. A window whose chunk waits for you ends its name in ` ?` and rings the bell, and the question's DM names the window. A stopped chunk keeps its window and its items until you run `loop-claude <task>` again. A chunk's claude session is named after its window, as `A <key> loop-claude item-372`. A commit in the config's folder now takes only the file it changed, as `git commit -m <title> -- <file>`. To upgrade, finish or stop every running loop-claude before `deploy-release` moves `~/.claude` to this release: a loop that reloads into it starts its project's windows afresh, and leaves its chunk's open claude session in the session picker.
|
||||
- `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.
|
||||
@@ -19,11 +28,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.
|
||||
|
||||
@@ -6,9 +6,10 @@ How work proceeds in any repo, unless the repo's `AGENTS.md` says otherwise. The
|
||||
|
||||
- **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 there it files an item but doesn't edit, move or finish 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.
|
||||
- **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. There it edits and moves only an issue the loop filed; of an issue a person filed it sets only the scores, with `--comment` telling the team why. Two open the file itself: whoever plans a release, to compare Scores across releases, which `todo-item list` doesn't print; and whoever edits `## Scoring` or `## Renamed`, or reshapes an old table.
|
||||
- **When the next release has no items and no work has landed towards it, plan it as this chunk.** Move the highest-scoring items of later releases into it, and get the human's approval of that set before writing any code.
|
||||
- **When the next release has no items left and work has landed towards it, its release review is the chunk** (`larv-review` §3 → "Release review"). **Once that has merged and the release holds no item, the release is finished: stop.** Report what it holds and that it is ready to cut. Under `/loop`, this ends the loop. Until the human cuts it, only a security fix, or an item its release review filed, lands, into that release; never start a later release's items or plan a new one.
|
||||
- **Where someone cut a release that still holds items, those items are the next release's.** Move them there as the chunk's first change and say so in its opening line; where `todo-item` cannot move an item, such as an issue a person filed in a Jira plan, ask the human in the chunk's summary to move it. Where the plan names no later release, ask the human which one they belong to.
|
||||
- **Open every chunk with one line:** the last version cut, how many changes are unreleased (the entries under `CHANGELOG.md` → `## Unreleased`, or else the commits since the last tag), and the release this chunk ships into. A repo that doesn't publish anything says so once.
|
||||
- **A client project's `CLAUDE.md` and `AGENTS.md` in its repo belong to its team.** Read both at the start of each chunk there. Propose each change that aligns them with this setup in a pull request of its own, never inside a chunk's; the one edit a chunk makes there is a decision's title in `AGENTS.md`. Until the team accepts a proposal, and after it declines or doesn't answer, follow the team's rule unless it breaks one of the project's goals. Record each such conflict as a decision in the `decisions` record, as `rules/decisions.md` asks: which rule you follow, why, and the open proposal's PR. Then nobody is asked twice.
|
||||
- **Read the goals file's `## Goals` and `## Audience` before starting a chunk, unless your prompt quotes them.** The chunk's items set its scope. The goals choose between ways to deliver those items, and never add to them.
|
||||
@@ -17,7 +18,7 @@ How work proceeds in any repo, unless the repo's `AGENTS.md` says otherwise. The
|
||||
- **Ask, don't guess.** Three choices are always the human's: a goal; a release, meaning the items planned into it and when it is cut; and a change to loop-claude's routing ladder, its rungs included. Any other rule that asks the human's approval reserves that choice too. Ask about a reserved choice. For any other choice, first check whether the goals already answer it. If they nearly do, propose a change to the goals and show how it answers this case: an answer settles one question, a goal settles every question like it. Otherwise take the option you would recommend, and record it with its reason: in the item's detail, or, where it governs later work, as the next sentence says. A recommendation you can give a reason for is not a guess. Ask only where you have no recommendation. Write every answer once, where it belongs, never only in chat: a goal in the goals file, a working rule in `AGENTS.md`, a standing choice in a comment at the one place it governs, or in `docs/decisions.md` once made in more than one place. When an answer holds a goal and a choice, write the goal in the goals file, and record as a choice only what the goal leaves open.
|
||||
- **Bench a syntax with the people who write it.** Before a new or changed spelling of something users read or write ships — markdown, HTML, a config key, a CLI flag — a panel of fresh-context readers, seated as those users from the goals file's `## Audience`, picks it.
|
||||
- **Implement the simplest change that solves the item, and ship it with `/larv-review`.** Whenever a test can check the change, write that test first and see it fail. Take its expected values from the item, never from the code. larv-review's reviewers hold the change to the technical principles, and a finding against one names it. Read a file in the principles folder the project's config sets (`~/.claude/bin/project-config principles` prints it) only when the item changes it, a finding or a record you write names it, or you decline a finding.
|
||||
- **Remove a finished item from the plan, and revise any decision that cites it.** If the repo publishes something others consume — a package, an image, an API — reword the item for them and move it to `CHANGELOG.md` under `## Unreleased`. A changelog is for the public, never for the next agent. Otherwise delete it; git history is the record. `~/.claude/bin/todo-item finish <ID>` removes the item with its detail, and adds the bullet you pass with `--changelog <bullet>`; it refuses while a decision cites the item.
|
||||
- **Remove a finished item from the plan, and revise any decision that cites it.** If the repo publishes something others consume — a package, an image, an API — reword the item for them and move it to `CHANGELOG.md` under `## Unreleased`. A changelog is for the public, never for the next agent. Otherwise delete it; git history is the record. `~/.claude/bin/todo-item finish <ID>` removes the item with its detail, and adds the bullet you pass with `--changelog <bullet>`; it refuses while a decision cites the item. A chunk finishes its items as it merges, through `chunk-pr merge --finish <ID>`, which takes the same flags (`larv-review` §5).
|
||||
- **Releases are the human's.** The version bump and the publishing credentials are theirs, whatever another rule says. Prepare everything else, so cutting a release is one decision.
|
||||
- **Open each plan item or ticket with a bold one-sentence tagline**, so the taglines alone say what a release holds. The tagline states the target state, checkable when done: an imperative verb plus what holds afterwards. A present-tense fact reads as the current state and doesn't say anything about what to do. Add "today X" only where the direction is otherwise ambiguous. GOOD: `**Accept undefined in MetadataValue and drop such keys on output.**` BANNED: `MetadataValue accepts undefined; such keys are dropped on output`.
|
||||
- **File a security finding the moment it is found.** A security finding — a leaked credential, secret or PII, an auth bypass, an injection — goes under the next release, marked `security`, naming the exposure and the path it reaches. `~/.claude/bin/rank_todo.py` ranks it first in its release, after only the open questions, which wait for me. Never among additive or nice-to-have items, never only in a chunk's summary, and never as a question about where it belongs: file it, say you did, and I will unmark it if I disagree. Fixing it inside an unrelated change is a separate call — say whether it is in the blast radius.
|
||||
@@ -46,7 +47,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 +61,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 +79,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 +98,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 +131,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.
|
||||
@@ -138,7 +139,7 @@ Claude Code reads this section by its heading when it compacts a conversation. K
|
||||
- **premises** — the goals and audience under `## Goals` and `## Audience` in the project's goals file, with code health ("Shared goal") first among the goals unless the goals file voids it.
|
||||
- **project's rung** — the cheapest rung on loop-claude's routing ladder of the project's model, which is the model loop-claude's prompt names as the project's, or else your own.
|
||||
- **project record** — one of five documents a project keeps beside its plan, each where its config names it: `decisions`, `score-anchors`, `comprehension-history`, `reading-cost` and `changelog`.
|
||||
- **release** — a semver version the human cuts.
|
||||
- **release** — a semver version the human cuts, or in a client's project someone on its team.
|
||||
- **release review** — a release's last chunk: the architecture and principles passes over the whole project, before the release is ready to cut; `larv-review` §3 → "Release review".
|
||||
- **reviewer** — a reporter of findings: an agent under `~/.claude/agents/`, `/security-review` or a forge's auto-reviewer.
|
||||
- **round cap** — the rounds one pass may take per chunk; `larv-review` §3 → "Round cap".
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -71,7 +71,7 @@ git config filter.settings.clean bin/settings_filter.py
|
||||
|
||||
Then pick a model with `/model`.
|
||||
|
||||
Link `loop-claude` onto `PATH`: `ln -s ~/.claude/bin/loop-claude ~/.local/bin/loop-claude`. Every claude it starts, the interactive ones included, skips every permission prompt.
|
||||
Link `loop-claude` onto `PATH`: `ln -s ~/.claude/bin/loop-claude ~/.local/bin/loop-claude`. Every claude it starts, the interactive ones included, skips every permission prompt. loop-claude runs each chunk in its own window of a tmux session per project, so it needs tmux 3.2 or later.
|
||||
|
||||
To get loop-claude's questions and stops as DMs from a bot, write the bot's token, your username or member ID and, for Mattermost, the server into `~/.claude-projects/<key>.env`, in the keys `~/.claude/bin/notify --help` names, run `chmod 600` on it, and add `env-file = "~/.claude-projects/<key>.env"` and `notifier = "mattermost"` (or `"slack"`) to the project's config, as Install → "Set up a project" describes.
|
||||
|
||||
@@ -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.
|
||||
@@ -102,13 +105,13 @@ A project may also set `notifier` to `"mattermost"` or `"slack"`, the service th
|
||||
|
||||
A project's config may set four more things, each optional, as `project-config --help` describes. `language` names the language its owners write in, where that isn't English: the worker writes the project's prose in it, and the prose reviewer judges the prose in it. `commit-title`, `pull-request-title` and `branch` are templates for a project that titles and names these in another way than `CLAUDE.md` → "Git, commits, and PRs" says. `chunk-preflight` names the branch and the worktree by the `branch` template. On a branch that fits it, rule-hook refuses a commit, and `chunk-pr` a pull request, whose title doesn't fit its template; on any other branch, such as a release review's, a title is the summary alone. A tool that reads a commit title, such as a round's `Answer <pass> round <n>:`, reads the template's `{summary}`: it tries `commit-title`, then `pull-request-title`, since a squash merge titles the commit as the pull request, then takes the title whole. While a project's config holds a fault, rule-hook refuses every commit there, and the tools that read its titles fail naming the fault.
|
||||
|
||||
A legacy project with no container setup sets `tooling-on-host = true`, so the loop runs its language runtime, package manager, tests and task runner directly on the host. One whose code the comprehension panel scores low may lower `readability-floor` from 7.0: under it, the ranking weighs code health 4 times as much, and a scoring run asks for a floor item.
|
||||
A legacy project with no container setup sets `tooling-on-host = true`, so the loop runs its language runtime, package manager, tests and task runner directly on the host. One whose code the comprehension panel scores low may lower `readability-floor` from 7.0: under it, the ranking weighs code health 4 times as much, and a scoring run asks for a floor item. To let more than one chunk run at once, set `parallel-chunks` to the most that may; left out, it is 1. Beside the plan's next item, only items whose `Touches:` predictions overlap none of the running chunks' items start.
|
||||
|
||||
A project whose pull requests need a human's approval sets `wait-for-approval = true` in its config. `chunk-pr merge` then waits, once the checks have passed, until GitHub reports the pull request approved as its branch protection requires, and merges it. It refuses on Gitea, where a reviewer requested changes and where the protection requires no review. It gives up after 90 minutes without an approval; run it again once the pull request is approved. Left out, the setting is false.
|
||||
A project whose pull requests need a human's approval sets `wait-for-approval = true` in its config. `chunk-pr merge` then waits, once the checks have passed, until GitHub reports the pull request approved as its branch protection requires, and merges it. It refuses on Gitea, where a reviewer requested changes and where the protection requires no review. While it waits, other chunks merge. It stops where a reviewer's comment waits for an answer, on an approved pull request too; answer it and run it again. It gives up after 90 minutes without an approval; run it again once the pull request is approved. Left out, the setting is false.
|
||||
|
||||
For a client's project, use one sandbox VM per client, so that one client's code, transcripts and credentials never share a machine with another's. What the client's repo should not hold lives in the config's folder, at paths written as `folder:<path>`, as `project-config --help` shows: the plan, the working rules in an `AGENTS.md` I write for the agents, the records, and the goals and audience, as `goals-and-audience = "folder:goals.md"`. Name that file `goals.md`, so the rules for goals and audience load when an agent writes it. A file outside the checkout has no commits in the checkout's history, so four things are not supported for it yet. `score-outcomes` and loop-claude's routing figures count a project's chunks only where `todo.md`, `docs/comprehension-history.md` and `docs/reading-cost.md` are at those paths in the checkout; otherwise each says so, and the loop goes on. For a plan or a comprehension history outside the checkout, `larv-review` says it cannot tell whether a scoring run is owed, and for such a history it cannot find a paired ruling's base. For a plan outside the checkout, chunk-preflight and loop-claude don't see a release whose last item has shipped, and say that its release review and its cut are yours to call. And rule-hook checks a plan outside the checkout on every call, not only when it changed.
|
||||
|
||||
A client that plans in Jira Cloud names an epic as its project's plan: `plan = "jira:https://acme.atlassian.net/browse/ABC-12"`, which is `jira:` and the epic's address as the browser shows it. The plan is then the epic's open child issues, in Jira's backlog order, which the team sets. An issue in a done status is a finished item. Each part of an item comes from one part of its issue:
|
||||
A client that plans in Jira Cloud names an epic as its project's plan: `plan = "jira:https://acme.atlassian.net/browse/ABC-12"`, which is `jira:` and the epic's address as the browser shows it. The plan is then the epic's open child issues, in Jira's backlog order, which the team sets, apart from the rank `todo-item add` gives an issue it files. An issue in a done status is a finished item. Each part of an item comes from one part of its issue:
|
||||
|
||||
- The ID is the issue's number, so every child must be in the epic's own Jira project.
|
||||
- The tagline is the summary.
|
||||
@@ -117,7 +120,11 @@ 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 reads such a plan and files items into it, each as a Task under the epic, and doesn't edit or finish an issue yet. `todo-item edit`, `move` and `finish` fail, so edit and finish its issues in Jira. `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 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. `todo-item add` needs the item's release among the Jira project's Fix Versions, named as `1.2.0` or `v1.2.0`. The config states the formula and the bar that a todo.md states under `## Scoring`, such as `jira-score-formula = "100 * V / (2**S + 8)"` and `jira-score-bar = 1`, and fails to load without them. `todo-item add` refuses an item that scores under the bar, unless it is exempt. It ranks the new issue among the issues the loop filed: questions first, then security findings, then by score. A person's issues keep the rank the team gave them, and `rank_todo.py` doesn't rank the plan.
|
||||
|
||||
`todo-item edit` and `move` change only an issue the loop filed. Of an issue a person filed, `edit` sets only the scores, and posts its `--comment` on the issue to tell the team why; the summary, description and Fix Version stay the team's to change in Jira, as do every issue's links. 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. 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 +140,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:
|
||||
@@ -159,13 +168,13 @@ It renames `## Unreleased` in `CHANGELOG.md` to the version and merges that thro
|
||||
|
||||
Install puts only `loop-claude` on `PATH`; call the others by their path, such as `~/.claude/bin/metric-bench`, from the project's checkout. Those under `~/.claude` are the release's; test a change to one from `~/code/claude-config/bin`.
|
||||
|
||||
- `chunk-pr open|sync|ready|merge|clean` opens a chunk's pull request as a draft, brings its branch level with origin's default branch, marks it ready and merges it once its checks pass, with `gh` on a GitHub origin and `tea` elsewhere; once it is merged, `clean` removes the chunk's worktree and branch and fast-forwards the main checkout. `chunk-pr --help` states the steps.
|
||||
- `chunk-pr open|sync|ready|merge|clean` opens a chunk's pull request as a draft, brings its branch level with origin's default branch, marks it ready and merges it once its checks pass, with `gh` on a GitHub origin and `tea` elsewhere. The chunks of one project merge one at a time: in its turn, `merge` brings the branch level again, finishes the plan items its `--finish` flags name, and waits for the checks; once the pull request is merged, `clean` removes the chunk's worktree and branch and fast-forwards the main checkout. `chunk-pr --help` states the steps.
|
||||
- `chunk-preflight` finds the mechanical facts a chunk starts from, and with `--worktree` makes its worktree; `loop-claude` runs it with `--worktree` before it routes each chunk, and `chunk-preflight --help` lists the facts.
|
||||
- `command-patterns [<version>] [--calls <file>]` prints a table of the shell command patterns a release's archived chunks ran, such as `tea pr create`, for an audit of the release, and with `--calls <file>` saves each call as a JSON line; `command-patterns --help` states the columns and the line's keys.
|
||||
- `deploy-release [--cut] [<checkout>]` moves `~/.claude`, or the checkout named, to the newest release, as Update says; with `--cut`, run in the development clone, it first cuts the next release, as Release says.
|
||||
- `judge-replay <model>` replays loop-claude's judge on archived verdicts of the projects run on the model, and prints what each rung a review climbs to misses, and the lowest rung below them that, like each candidate above it, returns them; `judge-replay --help` states the replay.
|
||||
- `larv-review <command>` holds larv-review's mechanical rules: the chunk's review folder, the paired ruling's base and vote count, each pass's round count, the scoring run's trigger and setup; the comprehension history's format, its latest places and its count of how often seats agree; and each reviewer's prompt header. `larv-review --help` states them. `settings.json` → `hooks` runs `larv-review reviewer-context` as each subagent starts. A reviewer under `agents/` whose frontmatter has `omitClaudeMd: true` starts without `CLAUDE.md`, and the command hands it that file's "Shared goal", "Prose" and "Vocabulary" sections.
|
||||
- `loop-claude <task>` runs a project's next chunk cycle after cycle; `loop-claude --help` states its contract.
|
||||
- `loop-claude <task>` runs a project's next chunks, each in its own tmux window, cycle after cycle; `loop-claude --help` states its contract.
|
||||
- `metric-bench [history]` benches cheap static metrics of a project's Python against the places its comprehension history names as hardest; `metric-bench --help` states the metrics and the scores.
|
||||
- `mutate-changes [--base <ref>] [--prefix <shell text>] [--jobs <n>]` mutation-tests the lines a branch changes and prints each mutant its tests don't kill; `mutate-changes --help` says which tool it runs for each language.
|
||||
- `notify [<message>]` sends a message, or else stdin, as a DM from the bot of the project's `notifier`, Mattermost or Slack, to the human; the project's `env-file` holds the bot's token, the recipient and, for Mattermost, the server, and `notify --help` names its keys. `loop-claude --help` says when loop-claude sends one.
|
||||
@@ -180,7 +189,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 +207,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.
|
||||
- `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, since it changes no link, 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.
|
||||
|
||||
+49
-17
@@ -9,7 +9,7 @@ from chunk_preflight.gathered import Forge
|
||||
from deploy_release.forge import Run
|
||||
|
||||
BIN = pathlib.Path(__file__).resolve().parents[1]
|
||||
# A human answers in hours, so merge polls once a minute and gives up after 90 minutes, which leaves room for the checks wait inside the 2 hours a background command may run, so that the give-up message prints.
|
||||
# A human answers in hours, so merge polls once a minute and gives up after 90 minutes. That leaves half an hour for the queue and the checks inside the 2 hours a background command may run; a run that needs more is killed before the give-up message prints, and its next run goes on from what it pushed.
|
||||
POLL_SECONDS = 60
|
||||
WAIT_SECONDS = 90 * 60
|
||||
|
||||
@@ -26,24 +26,56 @@ def awaited(forge: Forge, run: Run) -> bool | Failure:
|
||||
return answer.strip() == "true"
|
||||
|
||||
|
||||
# Each review thread, with whether it is resolved and who wrote its last comment, beside who opened the pull request. gh fills {owner} and {repo} from the checkout.
|
||||
THREADS = """query($owner: String!, $repo: String!, $number: Int!) { repository(owner: $owner, name: $repo) { pullRequest(number: $number) {
|
||||
author { login }
|
||||
reviewThreads(first: 100) { nodes { isResolved path comments(last: 1) { nodes { author { login } } } } }
|
||||
} } }"""
|
||||
|
||||
|
||||
def approval(number: str, run: Run) -> bool | Failure:
|
||||
"""Whether GitHub reports pull request number approved, as its branch protection asks, read once: False while it still wants a review. A Failure where a reviewer requested changes, or where the protection asks for no review."""
|
||||
viewed = run(["gh", "pr", "view", number, "--json", "reviewDecision"])
|
||||
try:
|
||||
decision = viewed if isinstance(viewed, Failure) else json.loads(viewed)["reviewDecision"]
|
||||
except (ValueError, KeyError, TypeError):
|
||||
return Failure(f"gh pr view printed no review decision: {str(viewed).strip()[:200]}")
|
||||
if isinstance(decision, Failure):
|
||||
return decision
|
||||
if decision == "CHANGES_REQUESTED":
|
||||
return Failure(f"a reviewer requested changes on pull request {number}")
|
||||
if not decision:
|
||||
return Failure("wait-for-approval is set, but the branch protection requires no review, so GitHub reports no decision; ask the human to require a review in the protection or to set wait-for-approval to false")
|
||||
if decision not in ("APPROVED", "REVIEW_REQUIRED"):
|
||||
return Failure(f"GitHub reports the review decision {decision!r} on pull request {number}, and chunk-pr doesn't know that decision")
|
||||
return decision == "APPROVED"
|
||||
|
||||
|
||||
def approved(number: str, run: Run, sleep: typing.Callable[[float], None] = time.sleep) -> Failure | None:
|
||||
"""None once GitHub reports pull request number approved, as its branch protection asks; a Failure where a reviewer requested changes, where the protection asks for no review, or where no approval came within WAIT_SECONDS."""
|
||||
"""None once GitHub reports pull request number approved; a Failure where `approval` fails, where a reviewer's comment waits for an answer, or where no approval came within WAIT_SECONDS."""
|
||||
for waited in range(0, WAIT_SECONDS + 1, POLL_SECONDS):
|
||||
viewed = run(["gh", "pr", "view", number, "--json", "reviewDecision"])
|
||||
try:
|
||||
decision = viewed if isinstance(viewed, Failure) else json.loads(viewed)["reviewDecision"]
|
||||
except (ValueError, KeyError, TypeError):
|
||||
return Failure(f"gh pr view printed no review decision: {str(viewed).strip()[:200]}")
|
||||
if isinstance(decision, Failure):
|
||||
return decision
|
||||
if decision == "APPROVED":
|
||||
return None
|
||||
if decision == "CHANGES_REQUESTED":
|
||||
return Failure(f"a reviewer requested changes on pull request {number}")
|
||||
if not decision:
|
||||
return Failure("wait-for-approval is set, but the branch protection requires no review, so GitHub reports no decision; ask the human to require a review in the protection or to set wait-for-approval to false")
|
||||
if decision != "REVIEW_REQUIRED":
|
||||
return Failure(f"GitHub reports the review decision {decision!r} on pull request {number}, and chunk-pr doesn't know that decision")
|
||||
read = approval(number, run)
|
||||
if read is True or isinstance(read, Failure):
|
||||
return None if read is True else read
|
||||
asked = unanswered(number, run)
|
||||
if asked is not None:
|
||||
return asked
|
||||
if waited < WAIT_SECONDS:
|
||||
sleep(POLL_SECONDS)
|
||||
return Failure(f"pull request {number} wasn't approved within {WAIT_SECONDS // 60} minutes; run chunk-pr merge again once it is")
|
||||
|
||||
|
||||
def unanswered(number: str, run: Run) -> Failure | None:
|
||||
"""A Failure naming the files where a reviewer's comment waits for an answer on pull request number: a review thread nobody resolved, whose last comment someone other than the pull request's author wrote. So a thread the worker answered, as that author, waits for the reviewer again. None where no thread waits."""
|
||||
read = run(["gh", "api", "graphql", "-f", f"query={THREADS}", "-F", "owner={owner}", "-F", "repo={repo}", "-F", f"number={number}"])
|
||||
try:
|
||||
pull = read if isinstance(read, Failure) else json.loads(read)["data"]["repository"]["pullRequest"]
|
||||
if isinstance(pull, Failure):
|
||||
return pull
|
||||
author = pull["author"]["login"]
|
||||
waiting = sorted({thread["path"] for thread in pull["reviewThreads"]["nodes"] if not thread["isResolved"] and any(comment["author"]["login"] != author for comment in thread["comments"]["nodes"])})
|
||||
except (ValueError, KeyError, TypeError):
|
||||
return Failure(f"gh api graphql printed no review threads: {str(read).strip()[:200]}")
|
||||
if not waiting:
|
||||
return None
|
||||
return Failure(f"a reviewer's comment on pull request {number} waits for an answer, in {', '.join(waiting)}; answer it in its thread, push any fix, and run chunk-pr merge again")
|
||||
|
||||
+235
-53
@@ -3,7 +3,7 @@
|
||||
usage: chunk-pr open <title> [<body>]
|
||||
chunk-pr sync
|
||||
chunk-pr ready [<title>]
|
||||
chunk-pr merge
|
||||
chunk-pr merge [--finish <ID> [--changelog <bullet> | --no-changelog]]...
|
||||
chunk-pr clean
|
||||
|
||||
Run it in the chunk's worktree, on the chunk's branch. ready and merge act on the branch's open
|
||||
@@ -25,22 +25,44 @@ ready marks the pull request ready for review. On Gitea a draft is a pull req
|
||||
starts with `WIP: `, so there it drops that prefix. Given <title>, one line, which it holds
|
||||
to the template as open does, it sets that
|
||||
as the pull request's title first; where that fails, the pull request stays a draft.
|
||||
merge waits for the pull request's checks, and those origin's default branch requires, to pass
|
||||
on the head, then merges the pull request, and only while its head is still the commit
|
||||
checked out, so a push after the gate is never merged. Where no check reports within a
|
||||
minute, it takes the pull request as having none. It refuses where a check fails, or, on
|
||||
Gitea, where the checks have not all passed within 30 minutes; on GitHub, gh watches them
|
||||
until they end. Run it in the background.
|
||||
It takes the first merge method the repository allows of: a merge commit, fast-forward
|
||||
only, a rebase followed by a merge commit, a rebase, a squash. GitHub offers only the
|
||||
merge commit, the rebase and the squash. It also refuses where `larv-review
|
||||
scoring-run-owed` exits 1, because the chunk owes a scoring run it has not recorded.
|
||||
merge merges the pull request in its turn: the chunks of one project on this machine take
|
||||
turns, one at a time. Run it in the background. In its turn it:
|
||||
1. fetches origin and merges its default branch into the branch, as sync does;
|
||||
2. finishes each plan item a --finish names with `todo-item finish`, passing on
|
||||
--changelog or --no-changelog, and commits what that changed in the plan and the
|
||||
changelog, so both change only at merge time, on top of every chunk merged before;
|
||||
3. pushes, also where step 2 failed after step 1 brought changes in;
|
||||
4. waits for the pull request's checks, and those origin's default branch requires, to
|
||||
pass on the head; where no check reports within a minute, it takes the pull request
|
||||
as having none;
|
||||
5. merges the pull request, only while its head is still the commit checked out, so a
|
||||
push after the gate is never merged. It takes the first merge method the repository
|
||||
allows of: a merge commit, fast-forward only, a rebase followed by a merge commit, a
|
||||
rebase, a squash. GitHub offers only the merge commit, the rebase and the squash.
|
||||
Its last line names each --finish item the plan did not hold when it began: an earlier
|
||||
run finished that item, or its ID is mistyped.
|
||||
Where the project's config sets `wait-for-approval = true` (`project-config --help`), it
|
||||
also waits, once the checks have passed, until GitHub reports the pull request approved
|
||||
as its branch protection requires. It refuses at once where a reviewer requested changes,
|
||||
where the protection requires no review, on Gitea, and where it cannot read the config.
|
||||
After 90 minutes without an approval it refuses too; run it again once the pull request
|
||||
is approved.
|
||||
merges only once GitHub reports the pull request approved as its branch protection
|
||||
requires. It waits for that outside its turn, so other chunks merge meanwhile, and takes
|
||||
a new turn once approved.
|
||||
It stops, without merging, and says what to do before running it again:
|
||||
- on a merge conflict in step 1, naming the conflicted files, with the merge in progress;
|
||||
- where `larv-review scoring-run-owed` exits 1 after step 3, because the chunk owes a
|
||||
scoring run it has not recorded;
|
||||
- where origin's default branch has moved since the branch last recorded a paired
|
||||
ruling, since that ruling read a head that no longer merges;
|
||||
- where a check fails, or, on Gitea, where the checks have not all passed within 30
|
||||
minutes; on GitHub, gh watches them until they end;
|
||||
- where other pull requests still hold the turn after 30 minutes, naming the last;
|
||||
- with `wait-for-approval`: where a reviewer requested changes, where the protection
|
||||
requires no review, on Gitea, where it cannot read the config, and after 90 minutes
|
||||
without an approval;
|
||||
- with `wait-for-approval`, approved or not: where a reviewer's comment waits for an
|
||||
answer, which is a review thread nobody resolved whose last comment is not the pull
|
||||
request author's. Answer it in its thread and push any fix.
|
||||
A run that waits for an approval takes two turns, so it can last the 90 minutes and,
|
||||
twice, the 30 minutes in the queue and the checks. One killed before that left the
|
||||
branch pushed, so run it again.
|
||||
clean acts once the forge reports the branch's pull request merged at the commit checked out,
|
||||
by any merge method. It fetches origin, fast-forwards the main checkout to origin's
|
||||
default branch, removes the chunk's worktree, then deletes the local branch; origin's
|
||||
@@ -51,7 +73,9 @@ clean acts once the forge reports the branch's pull request merged at the com
|
||||
|
||||
It prints what it did, exit 0, or why it failed, exit 1.
|
||||
"""
|
||||
import contextlib
|
||||
import dataclasses
|
||||
import fcntl
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
@@ -59,7 +83,7 @@ import sys
|
||||
import time
|
||||
import typing
|
||||
|
||||
from chunk_pr.approval import approved, awaited
|
||||
from chunk_pr.approval import approval, approved, awaited, unanswered
|
||||
from deploy_release.forge import checks_passed, gitea, merged_pull, open_pull, required_checks, Run, runner
|
||||
from failure import Failure
|
||||
from chunk_preflight.gathered import Forge
|
||||
@@ -69,7 +93,14 @@ from project_config import templates
|
||||
BIN = pathlib.Path(__file__).resolve().parents[1]
|
||||
# How long merge waits for a check to report before it takes a pull request without any as passed: CI queues its checks within seconds of a push, and merge may run right after one.
|
||||
NO_CHECKS_SECONDS = 60
|
||||
USAGE = "usage: chunk-pr open <title> [<body>] | chunk-pr sync | chunk-pr ready [<title>] | chunk-pr merge | chunk-pr clean"
|
||||
# The file, in the git folder that every worktree of the checkout shares, that a merge keeps locked with flock for its turn: so every chunk of the project on this machine queues on it.
|
||||
QUEUE = "chunk-pr-merge-queue"
|
||||
# A turn lasts as long as its checks, which chunk-pr waits half an hour for on Gitea, so a queue still held after that is reported, not waited out.
|
||||
QUEUE_SECONDS = 30 * 60
|
||||
QUEUE_POLL_SECONDS = 10
|
||||
# The line record-ruling writes into the comprehension history, as git's -G reads it.
|
||||
RULING = "^Ruling: "
|
||||
USAGE = "usage: chunk-pr open <title> [<body>] | chunk-pr sync | chunk-pr ready [<title>] | chunk-pr merge [--finish <ID> [--changelog <bullet> | --no-changelog]]... | chunk-pr clean"
|
||||
|
||||
# Each forge's merge methods in the order merge prefers them, as the repository setting that allows the method and the method's name in the forge's merge call. A merge commit and a fast-forward keep the branch's commits as they are; a rebase or a squash rewrites them.
|
||||
METHODS: dict[Forge, tuple[tuple[str, str], ...]] = {
|
||||
@@ -99,8 +130,9 @@ def step(argv: list[str], run: Run) -> str | Failure:
|
||||
return synced(run)
|
||||
case ["ready", *title] if len(title) <= 1 and not any(given.startswith("-") for given in title):
|
||||
return Failure("give a title of one line") if title and not one_line(title[0]) else (misfit(title[0], run) if title else None) or marked_ready(run, title[0] if title else None)
|
||||
case ["merge"]:
|
||||
return merged(run)
|
||||
case ["merge", *given]:
|
||||
finishes = finishes_of(given)
|
||||
return Failure(USAGE) if finishes is None else merged(run, finishes=finishes)
|
||||
case ["clean"]:
|
||||
return cleaned(run)
|
||||
return Failure(USAGE)
|
||||
@@ -195,23 +227,10 @@ def synced(run: Run) -> str | Failure:
|
||||
return base
|
||||
if branch == base:
|
||||
return Failure(f"{branch} is origin's default branch; sync the chunk's branch")
|
||||
fetched = run(["git", "fetch", "--quiet", "origin"])
|
||||
if isinstance(fetched, Failure):
|
||||
return fetched
|
||||
behind = answers(run, ["rev-list", "--count", f"HEAD..origin/{base}"], ["rev-parse", "--show-toplevel"])
|
||||
if isinstance(behind, Failure):
|
||||
return behind
|
||||
count, root = behind
|
||||
if count == "0":
|
||||
done = f"{branch} already holds origin/{base}."
|
||||
else:
|
||||
merged = run(["git", "merge", "--quiet", "--no-edit", f"origin/{base}"])
|
||||
if isinstance(merged, Failure):
|
||||
conflicted = answers(run, ["diff", "--name-only", "--diff-filter=U"])
|
||||
if isinstance(conflicted, Failure) or not conflicted[0]:
|
||||
return merged
|
||||
return Failure(f"merging origin/{base} into {branch} conflicts in {', '.join(conflicted[0].splitlines())}; the merge stays in progress: resolve them and commit")
|
||||
done = f"Merged origin/{base} into {branch}."
|
||||
level = levelled(run, branch, base)
|
||||
if isinstance(level, Failure):
|
||||
return level
|
||||
done = f"Merged origin/{base} into {branch}." if level else f"{branch} already holds origin/{base}."
|
||||
plan = run([str(BIN / "project-config"), "plan"])
|
||||
if isinstance(plan, Failure):
|
||||
return Failure(f"{done.removesuffix('.')}, but the plan to check cannot be found: {plan.reason}")
|
||||
@@ -224,6 +243,25 @@ def synced(run: Run) -> str | Failure:
|
||||
return f"{done}\nrank_todo.py --check todo.md passed."
|
||||
|
||||
|
||||
def levelled(run: Run, branch: str, base: str, resolve: str = "resolve them and commit") -> bool | Failure:
|
||||
"""Fetch origin and merge its base into branch, the one checked out: whether that brought anything in. On a conflict the merge stays in progress, and the Failure names the conflicted files and ends with resolve, the caller's words for what to do about them."""
|
||||
fetched = run(["git", "fetch", "--quiet", "origin"])
|
||||
if isinstance(fetched, Failure):
|
||||
return fetched
|
||||
behind = answers(run, ["rev-list", "--count", f"HEAD..origin/{base}"])
|
||||
if isinstance(behind, Failure):
|
||||
return behind
|
||||
if behind[0] == "0":
|
||||
return False
|
||||
merged = run(["git", "merge", "--quiet", "--no-edit", f"origin/{base}"])
|
||||
if isinstance(merged, Failure):
|
||||
conflicted = answers(run, ["diff", "--name-only", "--diff-filter=U"])
|
||||
if isinstance(conflicted, Failure) or not conflicted[0]:
|
||||
return merged
|
||||
return Failure(f"merging origin/{base} into {branch} conflicts in {', '.join(conflicted[0].splitlines())}; the merge stays in progress: {resolve}")
|
||||
return True
|
||||
|
||||
|
||||
def marked_ready(run: Run, title: str | None) -> str | Failure:
|
||||
found = pull(run)
|
||||
if isinstance(found, Failure):
|
||||
@@ -241,33 +279,177 @@ def marked_ready(run: Run, title: str | None) -> str | Failure:
|
||||
return f"Marked pull request #{number} ready, titled “{title}”." if title is not None else f"Marked pull request #{number} ready."
|
||||
|
||||
|
||||
def merged(run: Run, sleep: typing.Callable[[float], None] = time.sleep) -> str | Failure:
|
||||
def finishes_of(given: list[str]) -> list[list[str]] | None:
|
||||
"""`todo-item finish`'s arguments for each item that merge's flags name, in their order; None where the flags are malformed."""
|
||||
finishes, rest = [], given
|
||||
while rest:
|
||||
match rest:
|
||||
case ["--finish", item, "--changelog", bullet, *rest] if item.isdigit():
|
||||
finishes.append([item, "--changelog", bullet])
|
||||
case ["--finish", item, "--no-changelog", *rest] if item.isdigit():
|
||||
finishes.append([item, "--no-changelog"])
|
||||
case ["--finish", item, *rest] if item.isdigit():
|
||||
finishes.append([item])
|
||||
case _:
|
||||
return None
|
||||
return finishes
|
||||
|
||||
|
||||
def merged(run: Run, sleep: typing.Callable[[float], None] = time.sleep, finishes: typing.Sequence[list[str]] = ()) -> str | Failure:
|
||||
"""Merge the branch's pull request in the project's merge queue. Each pass of the loop is one turn in the queue; a pull request that still wants its approval leaves the queue while it waits, so the next chunk merges meanwhile, and takes a new turn once approved."""
|
||||
found = pull(run)
|
||||
if isinstance(found, Failure):
|
||||
return found
|
||||
forge, number, head = found
|
||||
forge, number, _ = found
|
||||
waits = awaited(forge, run)
|
||||
if isinstance(waits, Failure):
|
||||
return waits
|
||||
owed = run([str(BIN / "larv-review"), "scoring-run-owed"])
|
||||
if isinstance(owed, Failure):
|
||||
return owed
|
||||
method = merge_method(forge, run)
|
||||
if isinstance(method, Failure):
|
||||
return method
|
||||
base = default_branch(run)
|
||||
required = base if isinstance(base, Failure) else required_checks(forge, base, run)
|
||||
checked = required if isinstance(required, Failure) else checks_passed(forge, number, head, required, run, sleep, NO_CHECKS_SECONDS)
|
||||
if isinstance(checked, Failure):
|
||||
return checked
|
||||
approval = approved(number, run, sleep) if waits else None
|
||||
if isinstance(approval, Failure):
|
||||
return approval
|
||||
if forge == "gh":
|
||||
done = run(["gh", "pr", "merge", number, method, "--match-head-commit", head])
|
||||
else:
|
||||
done = gitea(run, f"repos/{{owner}}/{{repo}}/pulls/{number}/merge", f"Do={method}", f"head_commit_id={head}")
|
||||
return done if isinstance(done, Failure) else f"Merged pull request #{number} ({method.removeprefix('--')})."
|
||||
if isinstance(required, Failure):
|
||||
return required
|
||||
queue = answers(run, ["rev-parse", "--path-format=absolute", "--git-common-dir"])
|
||||
if isinstance(queue, Failure):
|
||||
return queue
|
||||
absent = unplanned(run, finishes)
|
||||
if isinstance(absent, Failure):
|
||||
return absent
|
||||
file = pathlib.Path(queue[0]) / QUEUE
|
||||
while True:
|
||||
try:
|
||||
with turn(file, number, sleep):
|
||||
head = levelled_and_finished(run, str(base), finishes)
|
||||
checked = head if isinstance(head, Failure) else checks_passed(forge, number, head, required, run, sleep, NO_CHECKS_SECONDS)
|
||||
if isinstance(checked, Failure):
|
||||
return checked
|
||||
ready = approval(number, run) if waits else True
|
||||
asked = unanswered(number, run) if waits and ready is True else None
|
||||
if isinstance(ready, Failure):
|
||||
return ready
|
||||
if asked is not None:
|
||||
return asked
|
||||
if ready and forge == "gh":
|
||||
done = run(["gh", "pr", "merge", number, method, "--match-head-commit", str(head)])
|
||||
elif ready:
|
||||
done = gitea(run, f"repos/{{owner}}/{{repo}}/pulls/{number}/merge", f"Do={method}", f"head_commit_id={head}")
|
||||
if ready:
|
||||
return done if isinstance(done, Failure) else f"Merged pull request #{number} ({method.removeprefix('--')}).{absent}"
|
||||
except Held as held:
|
||||
return Failure(f"the merge queue stayed held for {QUEUE_SECONDS // 60} minutes, last by pull request #{held.args[0] or '?'}, so this one took no turn; run chunk-pr merge again")
|
||||
except OSError as failure:
|
||||
return Failure(f"cannot take a turn in the merge queue, {file}: {failure.strerror}")
|
||||
waited = approved(number, run, sleep)
|
||||
if isinstance(waited, Failure):
|
||||
return waited
|
||||
|
||||
|
||||
def unplanned(run: Run, finishes: typing.Sequence[list[str]]) -> str | Failure:
|
||||
"""A sentence for merge's last line, naming each item of finishes the plan doesn't hold as merge begins: an earlier run finished it, or its ID is mistyped, and only the reader can tell which. Empty where the plan holds them all."""
|
||||
absent = []
|
||||
for finish in finishes:
|
||||
shown = run([str(BIN / "todo-item"), "show", finish[0]])
|
||||
if isinstance(shown, Failure) and f"holds no item {finish[0]}" not in shown.reason:
|
||||
return shown
|
||||
absent += [finish[0]] if isinstance(shown, Failure) else []
|
||||
return f" The plan held no item {', '.join(absent)} when merge began, so merge left the plan as it was there." if absent else ""
|
||||
|
||||
|
||||
class Held(Exception):
|
||||
"""Other merges kept the queue for QUEUE_SECONDS; the argument is the number of the pull request that held it last."""
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def turn(queue: pathlib.Path, number: str, sleep: typing.Callable[[float], None]) -> typing.Iterator[None]:
|
||||
"""Hold the project's merge queue as pull request number: wait until no other chunk-pr merge on this machine holds it, and free it on the way out, however that is. Raises Held where another one still holds it after QUEUE_SECONDS, and OSError where the file cannot be opened or locked."""
|
||||
fd = os.open(queue, os.O_RDWR | os.O_CREAT, 0o644)
|
||||
try:
|
||||
for waited in range(0, QUEUE_SECONDS + 1, QUEUE_POLL_SECONDS):
|
||||
try:
|
||||
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
break
|
||||
except BlockingIOError:
|
||||
if waited == QUEUE_SECONDS:
|
||||
raise Held(os.pread(fd, 20, 0).decode(errors="replace").strip()) from None
|
||||
sleep(QUEUE_POLL_SECONDS)
|
||||
os.ftruncate(fd, 0)
|
||||
os.pwrite(fd, number.encode(), 0)
|
||||
yield
|
||||
finally:
|
||||
os.close(fd)
|
||||
|
||||
|
||||
def levelled_and_finished(run: Run, base: str, finishes: typing.Sequence[list[str]]) -> str | Failure:
|
||||
"""What merge does to the branch inside its turn, before the checks: merge origin's base into it, finish the plan items, and push. The head to merge, or why the worker must act first. Whatever it committed is pushed before it fails, so the pull request's head stays the commit checked out."""
|
||||
found = checkout(run)
|
||||
if isinstance(found, Failure):
|
||||
return found
|
||||
_, branch, before = found
|
||||
moved = levelled(run, branch, base, "resolve them, commit, push, and run chunk-pr merge again")
|
||||
if isinstance(moved, Failure):
|
||||
return moved
|
||||
failed = next((failure for finish in finishes if (failure := finished(run, branch, finish))), None)
|
||||
head = answers(run, ["rev-parse", "HEAD"])
|
||||
if isinstance(head, Failure):
|
||||
return head
|
||||
pushed = run(["git", "push", "--quiet", "origin", branch]) if head[0] != before else ""
|
||||
if isinstance(pushed, Failure):
|
||||
return pushed
|
||||
# The scoring run is asked for only now: scoring-run-owed counts as shipped the items the committed plan no longer holds.
|
||||
owed = failed or run([str(BIN / "larv-review"), "scoring-run-owed"])
|
||||
if isinstance(owed, Failure):
|
||||
return owed
|
||||
return remeasure(run, base) or head[0]
|
||||
|
||||
|
||||
def finished(run: Run, branch: str, finish: list[str]) -> Failure | None:
|
||||
"""Finish one plan item with `todo-item finish` and commit what that changed. An item the plan no longer holds was finished by an earlier run of merge, which may have stopped before its commit: so the plan and the changelog are committed either way."""
|
||||
shown = run([str(BIN / "todo-item"), "show", finish[0]])
|
||||
if isinstance(shown, Failure) and f"holds no item {finish[0]}" not in shown.reason:
|
||||
return shown
|
||||
read = ["" if isinstance(shown, Failure) else run([str(BIN / "todo-item"), "finish", *finish]), run([str(BIN / "project-config"), "commit-title"]), run([str(BIN / "project-config"), "branch"]), run([str(BIN / "project-config"), "plan"]), run([str(BIN / "project-config"), "changelog"])]
|
||||
if failed := next((answer for answer in read if isinstance(answer, Failure)), None):
|
||||
return failed
|
||||
_, template, branch_template, *records = (str(answer).strip() for answer in read)
|
||||
summary = f"Finish item {finish[0]} in the plan"
|
||||
# A branch that doesn't fit the config's `branch` template has no ID for {id}, so its titles are the summary alone, as CLAUDE.md → "Git, commits, and PRs" says.
|
||||
title = template.replace(templates.ID, finish[0]).replace(templates.SUMMARY, summary) if templates.branch_fits(branch_template, branch) else summary
|
||||
return committed(run, title, [pathlib.Path(record) for record in records if pathlib.Path(record).is_file()])
|
||||
|
||||
|
||||
def committed(run: Run, title: str, files: list[pathlib.Path]) -> Failure | None:
|
||||
"""Commit what changed in files under title, each in the git repository that holds it, and only those files: a record the config keeps in its own folder is committed there, where another chunk may commit at the same time."""
|
||||
held: dict[str, list[str]] = {}
|
||||
for file in files:
|
||||
top = run(["git", "-C", str(file.parent), "rev-parse", "--show-toplevel"])
|
||||
if isinstance(top, Failure):
|
||||
return top
|
||||
held.setdefault(top.strip(), []).append(str(file))
|
||||
for top, paths in held.items():
|
||||
changed = run(["git", "-C", top, "status", "--porcelain", "--", *paths])
|
||||
steps = [changed] if isinstance(changed, Failure) or not changed.strip() else [run(["git", "-C", top, "add", "--", *paths]), run(["git", "-C", top, "commit", "--quiet", "-m", title, "--", *paths])]
|
||||
if failed := next((step for step in steps if isinstance(step, Failure)), None):
|
||||
return failed
|
||||
return None
|
||||
|
||||
|
||||
def remeasure(run: Run, base: str) -> Failure | None:
|
||||
"""A Failure where origin's base has moved since the branch last recorded a paired ruling: that ruling read a head that no longer merges. None where the branch recorded none, or the project keeps its history outside the checkout."""
|
||||
history = run([str(BIN / "project-config"), "comprehension-history"])
|
||||
if isinstance(history, Failure):
|
||||
return history
|
||||
top = answers(run, ["rev-parse", "--show-toplevel"])
|
||||
if isinstance(top, Failure) or not pathlib.Path(history.strip()).resolve().is_relative_to(top[0]):
|
||||
return top if isinstance(top, Failure) else None
|
||||
ruled = answers(run, ["log", "-1", "--format=%H", "-G", RULING, f"origin/{base}..HEAD", "--", history.strip()])
|
||||
if isinstance(ruled, Failure) or not ruled[0].strip():
|
||||
return ruled if isinstance(ruled, Failure) else None
|
||||
since = answers(run, ["rev-list", "--count", f"{ruled[0].strip()}..origin/{base}"])
|
||||
if isinstance(since, Failure) or since[0].strip() == "0":
|
||||
return since if isinstance(since, Failure) else None
|
||||
return Failure(f"origin/{base} moved after the branch recorded its paired ruling, and its changes are merged in and pushed; run the paired ruling again at the new head, record it, push, and run chunk-pr merge again")
|
||||
|
||||
|
||||
def merge_method(forge: Forge, run: Run) -> str | Failure:
|
||||
|
||||
+319
-22
@@ -1,5 +1,9 @@
|
||||
import contextlib
|
||||
import fcntl
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
@@ -7,10 +11,11 @@ import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from chunk_pr.main import cleaned, merged, step, USAGE
|
||||
from chunk_pr.main import cleaned, merged, QUEUE, step, turn, USAGE
|
||||
from failure import Failure
|
||||
from test_env import isolated_env
|
||||
from deploy_release.forge import Run
|
||||
from chunk_pr.approval import THREADS
|
||||
|
||||
TOOL = pathlib.Path(__file__).resolve().parents[1] / "chunk-pr"
|
||||
GITHUB = "git@github.com:me/project.git"
|
||||
@@ -29,6 +34,11 @@ TITLE = [str(pathlib.Path(__file__).resolve().parents[1] / "project-config"), "p
|
||||
BRANCH = [str(pathlib.Path(__file__).resolve().parents[1] / "project-config"), "branch"]
|
||||
WAITS = [str(pathlib.Path(__file__).resolve().parents[1] / "project-config"), "wait-for-approval"]
|
||||
GH_DECISION = ["gh", "pr", "view", "12", "--json", "reviewDecision"]
|
||||
GH_THREADS = ["gh", "api", "graphql", "-f", f"query={THREADS}", "-F", "owner={owner}", "-F", "repo={repo}", "-F", "number=12"]
|
||||
BEHIND = ["git", "rev-list", "--count", "HEAD..origin/main"]
|
||||
COMMON = ["git", "rev-parse", "--path-format=absolute", "--git-common-dir"]
|
||||
# The folder the fake checkouts name as their shared git folder, where merge keeps its queue's file.
|
||||
GIT_FOLDER = tempfile.TemporaryDirectory()
|
||||
|
||||
|
||||
class Checkout:
|
||||
@@ -45,6 +55,8 @@ class Checkout:
|
||||
self.decisions = ["APPROVED"]
|
||||
# Set, what GitHub prints instead of a decision's JSON.
|
||||
self.unreadable: str | Failure | None = None
|
||||
# The pull request's review threads, as GitHub's GraphQL API prints them; its author is `worker`.
|
||||
self.threads: list[dict[str, object]] = []
|
||||
self.ran: list[list[str]] = []
|
||||
self.answers: dict[tuple[str, ...], str | Failure] = {
|
||||
("git", "remote", "get-url", "origin"): f"{origin}\n",
|
||||
@@ -54,6 +66,9 @@ class Checkout:
|
||||
tuple(WAITS): "false\n",
|
||||
tuple(TITLE): "{summary}\n",
|
||||
tuple(BRANCH): "item-{id}\n",
|
||||
tuple(BEHIND): "0\n",
|
||||
tuple(COMMON): f"{GIT_FOLDER.name}\n",
|
||||
("git", "rev-parse", "--show-toplevel"): "/checkout\n",
|
||||
}
|
||||
|
||||
def __call__(self, command: list[str]) -> str | Failure:
|
||||
@@ -74,6 +89,8 @@ class Checkout:
|
||||
return self.unreadable
|
||||
if command == GH_DECISION:
|
||||
return json.dumps({"reviewDecision": self.decisions.pop(0) if len(self.decisions) > 1 else self.decisions[0]})
|
||||
if command == GH_THREADS:
|
||||
return json.dumps({"data": {"repository": {"pullRequest": {"author": {"login": "worker"}, "reviewThreads": {"nodes": self.threads}}}}})
|
||||
if command == TEA_BRANCH:
|
||||
return json.dumps({"enable_status_check": False})
|
||||
if command in (GH_SETTINGS, TEA_SETTINGS):
|
||||
@@ -82,7 +99,7 @@ class Checkout:
|
||||
|
||||
def acted(self) -> list[list[str]]:
|
||||
"""What it ran beyond reading the checkout, the pull requests and the repository's settings."""
|
||||
reads = [GH_LIST, GH_DECISION, TEA_LIST, GH_SETTINGS, TEA_SETTINGS, OWED, GH_CHECKS, TEA_BRANCH, TEA_STATUS]
|
||||
reads = [GH_LIST, GH_DECISION, TEA_LIST, GH_SETTINGS, TEA_SETTINGS, OWED, GH_CHECKS, TEA_BRANCH, TEA_STATUS, GH_THREADS]
|
||||
return [command for command in self.ran if tuple(command) not in self.answers and command not in reads]
|
||||
|
||||
|
||||
@@ -281,6 +298,11 @@ class Sync(unittest.TestCase):
|
||||
self.assertEqual(step(["sync"], checkout), Failure("git fetch --quiet: could not read from remote"))
|
||||
|
||||
|
||||
def changes(checkout: Checkout) -> list[list[str]]:
|
||||
"""What a merge ran, leaving out what it read, the project's config included, and the fetch each turn opens with."""
|
||||
return [command for command in checkout.acted() if command != FETCH and not command[0].endswith("/project-config")]
|
||||
|
||||
|
||||
class Merge(unittest.TestCase):
|
||||
def test_the_gate_passed_flag_it_no_longer_takes_is_refused_before_anything_runs(self):
|
||||
checkout = Checkout(GITHUB, open=True)
|
||||
@@ -302,7 +324,7 @@ class Merge(unittest.TestCase):
|
||||
checkout = Checkout(GITHUB, open=True)
|
||||
checkout.answers[tuple(GH_CHECKS)] = Failure("gh pr checks 12: CI / tests\tfail")
|
||||
self.assertEqual(step(["merge"], checkout), Failure("gh pr checks 12: CI / tests\tfail"))
|
||||
self.assertEqual(checkout.acted(), [])
|
||||
self.assertEqual(changes(checkout), [])
|
||||
|
||||
def test_github_waits_a_minute_for_checks_to_report_before_taking_none_as_passed(self):
|
||||
checkout = Checkout(GITHUB, open=True)
|
||||
@@ -335,13 +357,13 @@ class Merge(unittest.TestCase):
|
||||
def test_an_approved_pull_request_merges_after_the_checks_and_the_approval(self):
|
||||
checkout = self.requiring_approval()
|
||||
self.assertEqual(step(["merge"], checkout), "Merged pull request #12 (merge).")
|
||||
self.assertEqual(checkout.ran[-3:], [GH_CHECKS, GH_DECISION, ["gh", "pr", "merge", "12", "--merge", "--match-head-commit", HEAD]])
|
||||
self.assertEqual(checkout.ran[-4:], [GH_CHECKS, GH_DECISION, GH_THREADS, ["gh", "pr", "merge", "12", "--merge", "--match-head-commit", HEAD]])
|
||||
|
||||
def test_it_waits_a_minute_at_a_time_while_the_branch_protection_still_wants_a_review(self):
|
||||
checkout = self.requiring_approval(GITHUB, "REVIEW_REQUIRED", "REVIEW_REQUIRED", "APPROVED")
|
||||
slept: list[float] = []
|
||||
self.assertEqual(merged(checkout, slept.append), "Merged pull request #12 (merge).")
|
||||
self.assertEqual(slept, [60, 60])
|
||||
self.assertEqual(slept, [60])
|
||||
|
||||
def test_an_approval_that_never_comes_leaves_it_unmerged_after_90_minutes(self):
|
||||
checkout = self.requiring_approval(GITHUB, "REVIEW_REQUIRED")
|
||||
@@ -350,10 +372,10 @@ class Merge(unittest.TestCase):
|
||||
self.assertIsInstance(failed, Failure)
|
||||
self.assertIn("90 minutes", failed.reason)
|
||||
self.assertEqual(sum(slept), 90 * 60)
|
||||
self.assertEqual(checkout.acted(), [])
|
||||
self.assertEqual(changes(checkout), [])
|
||||
|
||||
def test_an_approval_that_comes_in_the_last_minute_still_merges(self):
|
||||
checkout = self.requiring_approval(GITHUB, *["REVIEW_REQUIRED"] * 90, "APPROVED")
|
||||
checkout = self.requiring_approval(GITHUB, *["REVIEW_REQUIRED"] * 91, "APPROVED")
|
||||
slept: list[float] = []
|
||||
self.assertEqual(merged(checkout, slept.append), "Merged pull request #12 (merge).")
|
||||
self.assertEqual(sum(slept), 90 * 60)
|
||||
@@ -364,7 +386,7 @@ class Merge(unittest.TestCase):
|
||||
checkout = self.requiring_approval()
|
||||
checkout.unreadable = answer
|
||||
self.assertIsInstance(step(["merge"], checkout), Failure)
|
||||
self.assertEqual(checkout.acted(), [])
|
||||
self.assertEqual(changes(checkout), [])
|
||||
|
||||
def test_requested_changes_leave_it_unmerged_without_waiting(self):
|
||||
checkout = self.requiring_approval(GITHUB, "CHANGES_REQUESTED")
|
||||
@@ -372,7 +394,7 @@ class Merge(unittest.TestCase):
|
||||
failed = merged(checkout, slept.append)
|
||||
self.assertIsInstance(failed, Failure)
|
||||
self.assertIn("requested changes", failed.reason)
|
||||
self.assertEqual((slept, checkout.acted()), ([], []))
|
||||
self.assertEqual((slept, changes(checkout)), ([], []))
|
||||
|
||||
def test_a_branch_protection_that_asks_for_no_review_leaves_it_unmerged_naming_the_setting(self):
|
||||
for decision in ("", None):
|
||||
@@ -381,14 +403,14 @@ class Merge(unittest.TestCase):
|
||||
failed = step(["merge"], checkout)
|
||||
self.assertIsInstance(failed, Failure)
|
||||
self.assertIn("requires no review", failed.reason)
|
||||
self.assertEqual(checkout.acted(), [])
|
||||
self.assertEqual(changes(checkout), [])
|
||||
|
||||
def test_gitea_with_wait_for_approval_leaves_it_unmerged_since_chunk_pr_reads_approvals_on_github_only(self):
|
||||
checkout = self.requiring_approval(GITEA)
|
||||
failed = step(["merge"], checkout)
|
||||
self.assertIsInstance(failed, Failure)
|
||||
self.assertIn("GitHub", failed.reason)
|
||||
self.assertEqual(checkout.acted(), [])
|
||||
self.assertEqual(changes(checkout), [])
|
||||
|
||||
def test_a_config_it_cannot_read_or_that_prints_neither_true_nor_false_leaves_it_unmerged(self):
|
||||
for answer in (Failure("no config names the checkout"), "maybe\n", ""):
|
||||
@@ -396,7 +418,7 @@ class Merge(unittest.TestCase):
|
||||
checkout = Checkout(GITHUB, open=True)
|
||||
checkout.answers[tuple(WAITS)] = answer
|
||||
self.assertIsInstance(step(["merge"], checkout), Failure)
|
||||
self.assertEqual(checkout.acted(), [])
|
||||
self.assertEqual(changes(checkout), [])
|
||||
|
||||
def protected(self, *reads: list[tuple[str, str]]) -> Checkout:
|
||||
"""A Gitea Checkout whose main requires a check matching CI / tests*, its status at HEAD holding each of reads in turn."""
|
||||
@@ -419,28 +441,28 @@ class Merge(unittest.TestCase):
|
||||
def test_a_failed_check_on_gitea_leaves_it_unmerged(self):
|
||||
checkout = self.protected([("CI / tests (pull_request)", "pending")], [("CI / tests (pull_request)", "failure")])
|
||||
self.assertIsInstance(merged(checkout, lambda _: None), Failure)
|
||||
self.assertEqual(checkout.acted(), [])
|
||||
self.assertEqual(changes(checkout), [])
|
||||
|
||||
def test_a_branch_protection_it_cannot_read_leaves_it_unmerged(self):
|
||||
checkout = Checkout(GITEA, open=True)
|
||||
checkout.answers[tuple(TEA_BRANCH)] = Failure("tea api: 500")
|
||||
self.assertEqual(merged(checkout, self.fail), Failure("tea api: 500"))
|
||||
self.assertNotIn(TEA_STATUS, checkout.ran)
|
||||
self.assertEqual(checkout.acted(), [])
|
||||
self.assertEqual(changes(checkout), [])
|
||||
|
||||
def test_an_unknown_default_branch_leaves_it_unmerged_reading_no_checks(self):
|
||||
checkout = Checkout(GITEA, open=True)
|
||||
checkout.answers[("git", "symbolic-ref", "--short", "refs/remotes/origin/HEAD")] = Failure("no such ref")
|
||||
self.assertEqual(merged(checkout, self.fail), Failure("origin records no default branch; set it with `git remote set-head origin --auto`: no such ref"))
|
||||
self.assertNotIn(TEA_STATUS, checkout.ran)
|
||||
self.assertEqual(checkout.acted(), [])
|
||||
self.assertEqual(changes(checkout), [])
|
||||
|
||||
def test_gitea_checks_that_never_pass_leave_it_unmerged(self):
|
||||
checkout = self.protected(*[[("CI / tests (pull_request)", "pending")]] * 1000)
|
||||
failed = merged(checkout, lambda _: None)
|
||||
self.assertIsInstance(failed, Failure)
|
||||
self.assertIn("gave up on pull request 12", failed.reason)
|
||||
self.assertEqual(checkout.acted(), [])
|
||||
self.assertEqual(changes(checkout), [])
|
||||
|
||||
def test_a_scoring_run_the_chunk_owes_and_has_not_recorded_refuses_the_merge(self):
|
||||
for origin in (GITHUB, GITEA):
|
||||
@@ -448,27 +470,27 @@ class Merge(unittest.TestCase):
|
||||
checkout = Checkout(origin, open=True)
|
||||
checkout.answers[tuple(OWED)] = Failure("larv-review scoring-run-owed: the chunk owes 2 scoring runs")
|
||||
self.assertEqual(step(["merge"], checkout), Failure("larv-review scoring-run-owed: the chunk owes 2 scoring runs"))
|
||||
self.assertEqual(checkout.acted(), [])
|
||||
self.assertEqual(changes(checkout), [])
|
||||
|
||||
def test_github_merges_with_a_merge_commit_pinned_to_the_head(self):
|
||||
checkout = Checkout(GITHUB, open=True, allowed=("squashMergeAllowed", "mergeCommitAllowed"))
|
||||
self.assertEqual(step(["merge"], checkout), "Merged pull request #12 (merge).")
|
||||
self.assertEqual(checkout.acted(), [["gh", "pr", "merge", "12", "--merge", "--match-head-commit", HEAD]])
|
||||
self.assertEqual(changes(checkout), [["gh", "pr", "merge", "12", "--merge", "--match-head-commit", HEAD]])
|
||||
|
||||
def test_github_without_merge_commits_rebases(self):
|
||||
checkout = Checkout(GITHUB, open=True, allowed=("squashMergeAllowed", "rebaseMergeAllowed"))
|
||||
step(["merge"], checkout)
|
||||
self.assertEqual(checkout.acted(), [["gh", "pr", "merge", "12", "--rebase", "--match-head-commit", HEAD]])
|
||||
self.assertEqual(changes(checkout), [["gh", "pr", "merge", "12", "--rebase", "--match-head-commit", HEAD]])
|
||||
|
||||
def test_gitea_merges_fast_forward_only_where_only_that_and_squash_are_allowed(self):
|
||||
checkout = Checkout(GITEA, open=True, allowed=("allow_squash_merge", "allow_fast_forward_only_merge"))
|
||||
self.assertEqual(step(["merge"], checkout), "Merged pull request #12 (fast-forward-only).")
|
||||
self.assertEqual(checkout.acted(), [["tea", "api", "--method", "POST", "--field", "Do=fast-forward-only", "--field", f"head_commit_id={HEAD}", "repos/{owner}/{repo}/pulls/12/merge"]])
|
||||
self.assertEqual(changes(checkout), [["tea", "api", "--method", "POST", "--field", "Do=fast-forward-only", "--field", f"head_commit_id={HEAD}", "repos/{owner}/{repo}/pulls/12/merge"]])
|
||||
|
||||
def test_a_repository_allowing_no_known_method_is_refused_unmerged(self):
|
||||
checkout = Checkout(GITEA, open=True, allowed=("allow_manual_merge",))
|
||||
self.assertIsInstance(step(["merge"], checkout), Failure)
|
||||
self.assertEqual(checkout.acted(), [])
|
||||
self.assertEqual(changes(checkout), [])
|
||||
|
||||
def test_a_forge_failure_is_returned(self):
|
||||
checkout = Checkout(GITHUB, open=True)
|
||||
@@ -484,7 +506,282 @@ class Merge(unittest.TestCase):
|
||||
checkout = Checkout(origin, open=True)
|
||||
checkout.answers[tuple(settings)] = Failure("settings: denied")
|
||||
self.assertEqual(step(["merge"], checkout), Failure("settings: denied"))
|
||||
self.assertEqual(checkout.acted(), [])
|
||||
self.assertEqual(changes(checkout), [])
|
||||
|
||||
|
||||
def queue_is_free() -> bool:
|
||||
"""Whether another merge could take its turn now."""
|
||||
fd = os.open(pathlib.Path(GIT_FOLDER.name) / QUEUE, os.O_RDWR | os.O_CREAT)
|
||||
try:
|
||||
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
except BlockingIOError:
|
||||
return False
|
||||
finally:
|
||||
os.close(fd)
|
||||
return True
|
||||
|
||||
|
||||
class MergeQueue(unittest.TestCase):
|
||||
PUSHED = ["git", "push", "--quiet", "origin", "item-7"]
|
||||
TODO_ITEM = str(pathlib.Path(__file__).resolve().parents[1] / "todo-item")
|
||||
CONFIG = str(pathlib.Path(__file__).resolve().parents[1] / "project-config")
|
||||
|
||||
def moved(self, checkout: Checkout) -> Checkout:
|
||||
"""checkout with origin's main two commits ahead of the branch, whose head is `decaf` once main is merged in."""
|
||||
checkout.answers[tuple(BEHIND)] = "2\n"
|
||||
run = checkout.__call__
|
||||
def merging(command: list[str]) -> str | Failure:
|
||||
answer = run(command)
|
||||
if command == MERGE and not isinstance(answer, Failure):
|
||||
checkout.answers[("git", "rev-parse", "HEAD")] = "decaf\n"
|
||||
return answer
|
||||
checkout.__call__ = merging # type: ignore[method-assign]
|
||||
return checkout
|
||||
|
||||
def with_plan(self, checkout: Checkout, held: bool = True) -> tuple[Checkout, str]:
|
||||
"""checkout in a project whose config names a todo.md and a CHANGELOG.md in one folder, which is returned, and titles commits `[{id}] {summary}`. The plan holds item 7 where held. A commit moves the head to `f00d`."""
|
||||
folder = tempfile.mkdtemp()
|
||||
self.addCleanup(shutil.rmtree, folder)
|
||||
for name in ("todo.md", "CHANGELOG.md"):
|
||||
(pathlib.Path(folder) / name).write_text("")
|
||||
checkout.answers.update({
|
||||
(self.TODO_ITEM, "show", "7"): "From todo.md:\n" if held else Failure("todo-item show 7: todo.md holds no item 7"),
|
||||
(self.CONFIG, "plan"): f"{folder}/todo.md\n",
|
||||
(self.CONFIG, "changelog"): f"{folder}/CHANGELOG.md\n",
|
||||
(self.CONFIG, "commit-title"): "[{id}] {summary}\n",
|
||||
("git", "-C", folder, "rev-parse", "--show-toplevel"): f"{folder}\n",
|
||||
("git", "-C", folder, "status", "--porcelain", "--", f"{folder}/todo.md", f"{folder}/CHANGELOG.md"): " M todo.md\n",
|
||||
})
|
||||
run = checkout.__call__
|
||||
def committing(command: list[str]) -> str | Failure:
|
||||
if command[3:4] == ["commit"]:
|
||||
checkout.answers[("git", "rev-parse", "HEAD")] = "f00d\n"
|
||||
return run(command)
|
||||
checkout.__call__ = committing # type: ignore[method-assign]
|
||||
return checkout, folder
|
||||
|
||||
@staticmethod
|
||||
def thread(path: str, last: str, resolved: bool = False) -> dict[str, object]:
|
||||
return {"isResolved": resolved, "path": path, "comments": {"nodes": [{"author": {"login": last}}]}}
|
||||
|
||||
def test_malformed_finish_flags_dont_run_anything(self):
|
||||
for flags in (["--finish"], ["--finish", "abc"], ["--changelog", "Bullet."], ["12"], ["--finish", "--no-changelog"], ["--finish", "7", "--changelog"], ["--finish", "7", "--no-changelog", "--changelog", "Bullet."]):
|
||||
with self.subTest(flags):
|
||||
checkout = Checkout(GITHUB, open=True)
|
||||
self.assertEqual(step(["merge", *flags], checkout), Failure(USAGE))
|
||||
self.assertEqual(checkout.ran, [])
|
||||
|
||||
def test_a_branch_behind_the_default_branch_merges_it_in_and_pushes_before_the_checks(self):
|
||||
checkout = self.moved(Checkout(GITHUB, open=True))
|
||||
self.assertEqual(merged(checkout.__call__), "Merged pull request #12 (merge).")
|
||||
self.assertEqual(changes(checkout), [MERGE, self.PUSHED, ["gh", "pr", "merge", "12", "--merge", "--match-head-commit", "decaf"]])
|
||||
self.assertLess(checkout.ran.index(self.PUSHED), checkout.ran.index(GH_CHECKS))
|
||||
|
||||
def test_a_conflict_with_the_default_branch_leaves_it_unmerged_naming_the_files_and_frees_the_queue(self):
|
||||
checkout = self.moved(Checkout(GITHUB, open=True))
|
||||
checkout.answers[tuple(MERGE)] = Failure("git merge --quiet: CONFLICT")
|
||||
checkout.answers[("git", "diff", "--name-only", "--diff-filter=U")] = "bin/tool.py\n"
|
||||
failed = merged(checkout.__call__)
|
||||
self.assertIsInstance(failed, Failure)
|
||||
self.assertIn("conflicts in bin/tool.py; the merge stays in progress: resolve them, commit, push, and run chunk-pr merge again", failed.reason)
|
||||
self.assertEqual((changes(checkout), MERGE in checkout.ran), ([], True))
|
||||
self.assertTrue(queue_is_free())
|
||||
|
||||
def test_a_finished_item_is_committed_under_the_configs_title_and_pushed_before_the_merge(self):
|
||||
checkout, folder = self.with_plan(Checkout(GITHUB, open=True))
|
||||
files = [f"{folder}/todo.md", f"{folder}/CHANGELOG.md"]
|
||||
self.assertEqual(merged(checkout.__call__, finishes=[["7", "--changelog", "Exports keep their order."]]), "Merged pull request #12 (merge).")
|
||||
self.assertEqual(changes(checkout)[:1], [[self.TODO_ITEM, "finish", "7", "--changelog", "Exports keep their order."]])
|
||||
self.assertEqual(changes(checkout)[-4:], [
|
||||
["git", "-C", folder, "add", "--", *files],
|
||||
["git", "-C", folder, "commit", "--quiet", "-m", "[7] Finish item 7 in the plan", "--", *files],
|
||||
self.PUSHED,
|
||||
["gh", "pr", "merge", "12", "--merge", "--match-head-commit", "f00d"],
|
||||
])
|
||||
|
||||
def test_the_flags_reach_todo_item_as_given(self):
|
||||
checkout, _ = self.with_plan(Checkout(GITHUB, open=True))
|
||||
checkout.answers.update({(self.TODO_ITEM, "show", "8"): "From todo.md:\n", (self.TODO_ITEM, "show", "9"): "From todo.md:\n"})
|
||||
self.assertEqual(step(["merge", "--finish", "7", "--no-changelog", "--finish", "8", "--finish", "9", "--changelog", "Exports keep their order."], checkout.__call__), "Merged pull request #12 (merge).")
|
||||
self.assertEqual([command[1:] for command in checkout.ran if command[:2] == [self.TODO_ITEM, "finish"]], [["finish", "7", "--no-changelog"], ["finish", "8"], ["finish", "9", "--changelog", "Exports keep their order."]])
|
||||
|
||||
def test_an_item_the_plan_no_longer_holds_is_named_on_the_last_line_and_what_an_earlier_run_left_uncommitted_is_committed(self):
|
||||
checkout, folder = self.with_plan(Checkout(GITHUB, open=True), held=False)
|
||||
self.assertEqual(merged(checkout.__call__, finishes=[["7"]]), "Merged pull request #12 (merge). The plan held no item 7 when merge began, so merge left the plan as it was there.")
|
||||
self.assertNotIn([self.TODO_ITEM, "finish", "7"], checkout.ran)
|
||||
self.assertEqual([command[3] for command in changes(checkout)[:-1]], ["add", "commit", "origin"])
|
||||
self.assertEqual(changes(checkout)[-1], ["gh", "pr", "merge", "12", "--merge", "--match-head-commit", "f00d"])
|
||||
|
||||
def test_each_item_the_plan_no_longer_holds_is_named(self):
|
||||
checkout, _ = self.with_plan(Checkout(GITHUB, open=True), held=False)
|
||||
checkout.answers[(self.TODO_ITEM, "show", "8")] = Failure("todo-item show 8: todo.md holds no item 8")
|
||||
self.assertIn("The plan held no item 7, 8 when merge began", str(merged(checkout.__call__, finishes=[["7"], ["8"]])))
|
||||
|
||||
def test_a_plan_that_turns_unreadable_inside_the_turn_leaves_it_unmerged(self):
|
||||
checkout, _ = self.with_plan(Checkout(GITHUB, open=True))
|
||||
run, shows = checkout.__call__, []
|
||||
def run_whose_second_show_fails(command: list[str]) -> str | Failure:
|
||||
shows.extend([command] if command[1:2] == ["show"] else [])
|
||||
return Failure("todo-item show 7: unreadable") if command[1:2] == ["show"] and len(shows) == 2 else run(command)
|
||||
self.assertEqual(merged(run_whose_second_show_fails, finishes=[["7"]]), Failure("todo-item show 7: unreadable"))
|
||||
self.assertNotIn([self.TODO_ITEM, "finish", "7"], checkout.ran)
|
||||
|
||||
def test_a_finish_that_changes_no_file_commits_and_pushes_nothing(self):
|
||||
for clean in ("status", "records"):
|
||||
with self.subTest(clean):
|
||||
checkout, folder = self.with_plan(Checkout(GITHUB, open=True))
|
||||
if clean == "status":
|
||||
checkout.answers[("git", "-C", folder, "status", "--porcelain", "--", f"{folder}/todo.md", f"{folder}/CHANGELOG.md")] = "\n"
|
||||
else:
|
||||
checkout.answers.update({(self.CONFIG, "plan"): "PAY-1\n", (self.CONFIG, "changelog"): f"{folder}/none.md\n"})
|
||||
self.assertEqual(merged(checkout.__call__, finishes=[["7", "--no-changelog"]]), "Merged pull request #12 (merge).")
|
||||
self.assertEqual(changes(checkout), [[self.TODO_ITEM, "finish", "7", "--no-changelog"], ["gh", "pr", "merge", "12", "--merge", "--match-head-commit", HEAD]])
|
||||
|
||||
def test_a_branch_outside_the_branch_template_titles_the_finish_with_the_summary_alone(self):
|
||||
checkout, folder = self.with_plan(Checkout(GITHUB, open=True))
|
||||
checkout.answers[tuple(BRANCH)] = "feature/PAY-{id}\n"
|
||||
merged(checkout.__call__, finishes=[["7"]])
|
||||
self.assertIn("Finish item 7 in the plan", [command[6] for command in checkout.ran if command[3:4] == ["commit"]])
|
||||
|
||||
def test_a_plan_it_cannot_read_or_an_item_it_cannot_finish_leaves_it_unmerged(self):
|
||||
for failing in ("show", "finish"):
|
||||
with self.subTest(failing):
|
||||
checkout, _ = self.with_plan(Checkout(GITHUB, open=True))
|
||||
checkout.answers[(self.TODO_ITEM, failing, "7")] = Failure(f"todo-item {failing} 7: no config names the checkout")
|
||||
self.assertEqual(merged(checkout.__call__, finishes=[["7"]]), Failure(f"todo-item {failing} 7: no config names the checkout"))
|
||||
self.assertNotIn(self.PUSHED, checkout.ran)
|
||||
|
||||
def test_a_step_of_the_turn_that_fails_leaves_it_unmerged_with_that_failure(self):
|
||||
_, folder = self.with_plan(Checkout(GITHUB, open=True))
|
||||
for failing in (FETCH, BEHIND, COMMON, self.PUSHED, ["git", "-C", "<plan>", "rev-parse", "--show-toplevel"], ["git", "-C", "<plan>", "add"], ["git", "-C", "<plan>", "commit"], [self.CONFIG, "comprehension-history"]):
|
||||
with self.subTest(failing):
|
||||
checkout, folder = self.with_plan(Checkout(GITHUB, open=True))
|
||||
run = checkout.__call__
|
||||
def failing_run(command: list[str]) -> str | Failure:
|
||||
asked = ["<plan>" if part == folder else part for part in command]
|
||||
return Failure("that step failed") if tuple(asked[:len(failing)]) == tuple(failing) else run(command)
|
||||
self.assertEqual(merged(failing_run, finishes=[["7"]]), Failure("that step failed"))
|
||||
self.assertNotIn("merge", [command[2] for command in checkout.ran if command[0] == "gh"])
|
||||
|
||||
def test_a_finish_that_fails_after_the_default_branch_was_merged_in_still_pushes_the_branch(self):
|
||||
checkout, _ = self.with_plan(self.moved(Checkout(GITHUB, open=True)))
|
||||
checkout.answers[(self.TODO_ITEM, "finish", "7")] = Failure("todo-item finish 7: a decision cites item 7")
|
||||
self.assertEqual(merged(checkout.__call__, finishes=[["7"]]), Failure("todo-item finish 7: a decision cites item 7"))
|
||||
self.assertEqual(changes(checkout), [MERGE, self.PUSHED])
|
||||
|
||||
def test_the_scoring_run_is_asked_for_once_the_finish_is_committed_and_one_owed_leaves_it_unmerged(self):
|
||||
checkout, _ = self.with_plan(Checkout(GITHUB, open=True))
|
||||
commit = lambda: next(index for index, command in enumerate(checkout.ran) if command[3:4] == ["commit"])
|
||||
self.assertEqual(merged(checkout.__call__, finishes=[["7"]]), "Merged pull request #12 (merge).")
|
||||
self.assertLess(commit(), checkout.ran.index(OWED))
|
||||
checkout, _ = self.with_plan(Checkout(GITHUB, open=True))
|
||||
checkout.answers[tuple(OWED)] = Failure("the chunk owes 1 scoring run")
|
||||
self.assertEqual(merged(checkout.__call__, finishes=[["7"]]), Failure("the chunk owes 1 scoring run"))
|
||||
self.assertEqual(changes(checkout)[-1], self.PUSHED)
|
||||
|
||||
def test_a_merge_holds_the_queue_through_the_checks_and_frees_it_while_it_waits_for_an_approval(self):
|
||||
checkout = Checkout(GITHUB, open=True)
|
||||
checkout.answers[tuple(WAITS)] = "true\n"
|
||||
checkout.decisions = ["REVIEW_REQUIRED", "REVIEW_REQUIRED", "APPROVED"]
|
||||
free: dict[str, bool] = {}
|
||||
def run(command: list[str]) -> str | Failure:
|
||||
if command == GH_CHECKS:
|
||||
free.setdefault("during the checks", queue_is_free())
|
||||
return checkout(command)
|
||||
self.assertEqual(merged(run, lambda seconds: free.setdefault("waiting for the approval", queue_is_free())), "Merged pull request #12 (merge).")
|
||||
self.assertEqual(free, {"during the checks": False, "waiting for the approval": True})
|
||||
self.assertEqual(checkout.ran.count(FETCH), 2)
|
||||
|
||||
def test_a_reviewers_comment_ends_the_wait_naming_its_file_until_the_author_answers_or_it_is_resolved(self):
|
||||
checkout = Checkout(GITHUB, open=True)
|
||||
checkout.answers[tuple(WAITS)] = "true\n"
|
||||
checkout.decisions = ["REVIEW_REQUIRED"]
|
||||
checkout.threads = [self.thread("bin/asked.py", "reviewer"), self.thread("bin/answered.py", "worker"), self.thread("bin/resolved.py", "reviewer", resolved=True)]
|
||||
slept: list[float] = []
|
||||
failed = merged(checkout, slept.append)
|
||||
self.assertIsInstance(failed, Failure)
|
||||
self.assertIn("waits for an answer, in bin/asked.py;", failed.reason)
|
||||
self.assertEqual((slept, changes(checkout)), ([], []))
|
||||
checkout.threads = checkout.threads[1:]
|
||||
checkout.decisions = ["REVIEW_REQUIRED", "REVIEW_REQUIRED", "APPROVED"]
|
||||
self.assertEqual(merged(checkout, slept.append), "Merged pull request #12 (merge).")
|
||||
|
||||
def test_an_approved_pull_request_with_a_comment_that_waits_for_an_answer_stays_unmerged(self):
|
||||
checkout = Checkout(GITHUB, open=True)
|
||||
checkout.answers[tuple(WAITS)] = "true\n"
|
||||
checkout.threads = [self.thread("bin/asked.py", "reviewer")]
|
||||
failed = merged(checkout)
|
||||
self.assertIsInstance(failed, Failure)
|
||||
self.assertIn("waits for an answer, in bin/asked.py;", failed.reason)
|
||||
self.assertEqual(changes(checkout), [])
|
||||
|
||||
def test_review_threads_it_cannot_read_leave_it_unmerged(self):
|
||||
for answer, reason in ((Failure("gh api graphql failed"), "gh api graphql failed"), ("not json", "gh api graphql printed no review threads: not json"), ("{}", "gh api graphql printed no review threads: {}")):
|
||||
with self.subTest(answer):
|
||||
checkout = Checkout(GITHUB, open=True)
|
||||
checkout.answers.update({tuple(WAITS): "true\n", tuple(GH_THREADS): answer})
|
||||
checkout.decisions = ["REVIEW_REQUIRED"]
|
||||
self.assertEqual(merged(checkout, lambda seconds: None), Failure(reason))
|
||||
self.assertEqual(changes(checkout), [])
|
||||
|
||||
def test_a_default_branch_that_moved_after_the_branchs_last_paired_ruling_stops_for_a_new_one(self):
|
||||
history = "/checkout/docs/comprehension-history.md"
|
||||
ruled = ["git", "log", "-1", "--format=%H", "-G", "^Ruling: ", "origin/main..HEAD", "--", history]
|
||||
since = ["git", "rev-list", "--count", "bead..origin/main"]
|
||||
for name, answers, stops in (
|
||||
("moved since the ruling", {tuple(ruled): "bead\n", tuple(since): "2\n"}, True),
|
||||
("ruled at this head", {tuple(ruled): "bead\n", tuple(since): "0\n"}, False),
|
||||
("no ruling", {tuple(ruled): "\n"}, False),
|
||||
):
|
||||
with self.subTest(name):
|
||||
checkout = Checkout(GITHUB, open=True)
|
||||
checkout.answers.update({(self.CONFIG, "comprehension-history"): f"{history}\n", **answers})
|
||||
done = merged(checkout.__call__)
|
||||
self.assertEqual(isinstance(done, Failure) and "run the paired ruling again" in done.reason, stops, done)
|
||||
self.assertEqual(changes(checkout), [] if stops else [["gh", "pr", "merge", "12", "--merge", "--match-head-commit", HEAD]])
|
||||
|
||||
def test_a_history_outside_the_checkout_or_one_git_cannot_read_never_stops_or_fails_the_merge_wrongly(self):
|
||||
ruled = ("git", "log", "-1", "--format=%H", "-G", "^Ruling: ", "origin/main..HEAD", "--", "/checkout/history.md")
|
||||
checkout = Checkout(GITHUB, open=True)
|
||||
checkout.answers[(self.CONFIG, "comprehension-history")] = "/elsewhere/history.md\n"
|
||||
self.assertEqual(merged(checkout.__call__), "Merged pull request #12 (merge).")
|
||||
self.assertNotIn("log", [command[1] for command in checkout.ran])
|
||||
for failing in (ruled, ("git", "rev-list", "--count", "bead..origin/main"), ("git", "rev-parse", "--show-toplevel")):
|
||||
with self.subTest(failing):
|
||||
checkout = Checkout(GITHUB, open=True)
|
||||
checkout.answers.update({(self.CONFIG, "comprehension-history"): "/checkout/history.md\n", ruled: "bead\n"})
|
||||
checkout.answers[failing] = Failure("git failed")
|
||||
self.assertEqual(merged(checkout.__call__), Failure("git failed"))
|
||||
|
||||
def test_a_turn_keeps_every_other_merge_out_until_it_ends_even_by_an_error(self):
|
||||
with self.assertRaises(ValueError):
|
||||
with turn(pathlib.Path(GIT_FOLDER.name) / QUEUE, "12", lambda seconds: None):
|
||||
self.assertFalse(queue_is_free())
|
||||
raise ValueError
|
||||
self.assertTrue(queue_is_free())
|
||||
|
||||
def test_a_queue_another_pull_request_holds_for_half_an_hour_leaves_it_unmerged_naming_the_holder(self):
|
||||
checkout = Checkout(GITHUB, open=True)
|
||||
slept: list[float] = []
|
||||
with turn(pathlib.Path(GIT_FOLDER.name) / QUEUE, "1234", lambda seconds: None):
|
||||
pass
|
||||
with turn(pathlib.Path(GIT_FOLDER.name) / QUEUE, "31", lambda seconds: None):
|
||||
failed = merged(checkout, slept.append)
|
||||
self.assertEqual(failed, Failure("the merge queue stayed held for 30 minutes, last by pull request #31, so this one took no turn; run chunk-pr merge again"))
|
||||
self.assertEqual((sum(slept), set(slept), changes(checkout)), (30 * 60, {10}, []))
|
||||
|
||||
def test_a_queue_freed_while_it_waits_gives_it_the_turn(self):
|
||||
checkout = Checkout(GITHUB, open=True)
|
||||
holder = contextlib.ExitStack()
|
||||
holder.enter_context(turn(pathlib.Path(GIT_FOLDER.name) / QUEUE, "31", lambda seconds: None))
|
||||
self.assertEqual(merged(checkout, lambda seconds: holder.close()), "Merged pull request #12 (merge).")
|
||||
|
||||
def test_a_queue_it_cannot_open_leaves_it_unmerged(self):
|
||||
checkout = Checkout(GITHUB, open=True)
|
||||
checkout.answers[tuple(COMMON)] = "/nonexistent/folder\n"
|
||||
self.assertEqual(merged(checkout), Failure("cannot take a turn in the merge queue, /nonexistent/folder/chunk-pr-merge-queue: No such file or directory"))
|
||||
self.assertEqual(checkout.acted(), [])
|
||||
|
||||
|
||||
|
||||
class Clean(unittest.TestCase):
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"""The pure choices the preflight's steps act on."""
|
||||
import pathlib
|
||||
|
||||
from release_plan.release_standing import chunk_item, Cut, dated_cut, LastCut, ReadyToCut, ReviewDue, Unknown, Unplanned
|
||||
from release_plan.release_standing import carried, chunk_item, Cut, dated_cut, LastCut, ReadyToCut, ReviewDue, Unknown, Unplanned
|
||||
from chunk_preflight.gathered import CarriedOver, Forge, NoItem, Plan
|
||||
from failure import Failure
|
||||
from chunk_preflight.gathered import Forge, NoItem, Plan
|
||||
from release_plan.todo_table import NoItemsTable
|
||||
from plan_store import stores as plan_stores
|
||||
from release_plan.release import version
|
||||
@@ -25,8 +25,8 @@ def plan_name(default: str, outside: str | None) -> str:
|
||||
return outside if outside else f"{default}'s todo.md"
|
||||
|
||||
|
||||
def planned(todo: plan_stores.Plan | Failure, cut: LastCut, default: str, branch: str, outside: str | None = None) -> Plan | NoItem:
|
||||
"""todo, which is the project's plan as its store read it and which plan_name names, with the item the next chunk takes first, release_standing.chunk_item's pick; else why there is none. branch is the project's `branch` template."""
|
||||
def planned(todo: plan_stores.Plan | Failure, cut: LastCut, default: str, branch: str, outside: str | None = None, item_id: int | None = None) -> Plan | NoItem:
|
||||
"""todo, which is the project's plan as its store read it and which plan_name names, with the item the next chunk takes first: the item of item_id where one is given, else release_standing.chunk_item's pick. Else why there is none. branch is the project's `branch` template."""
|
||||
where = plan_name(default, outside)
|
||||
if isinstance(todo, NoItemsTable):
|
||||
return NoItem(f"{where} holds no items table.")
|
||||
@@ -52,7 +52,15 @@ def planned(todo: plan_stores.Plan | Failure, cut: LastCut, default: str, branch
|
||||
first = pick.item
|
||||
if first is None:
|
||||
return NoItem(f"every item of release {version(pick.release)} in {where} waits." if pick.release is not None else f"{where}'s items table holds no item.")
|
||||
return Plan(found, first, f"{first.tagline}\n\n{first.detail}".strip(), branch)
|
||||
held = carried(found, cut)
|
||||
moved = [(was, now) for was, now in zip(found, held) if was.release != now.release]
|
||||
# Every carried item takes one release, the next.
|
||||
over = CarriedOver(moved[0][1].release, tuple(was.id for was, _ in moved)) if moved else None
|
||||
if item_id is not None:
|
||||
first = next((item for item in held if item.id == item_id), None)
|
||||
if first is None:
|
||||
return NoItem(f"{where} holds no item {item_id}, the one --item names; it may have shipped.")
|
||||
return Plan(held, first, f"{first.tagline}\n\n{first.detail}".strip(), branch, over, item_id is not None)
|
||||
|
||||
|
||||
def worktree_on(porcelain: str, branch: str) -> pathlib.Path | None:
|
||||
|
||||
@@ -45,7 +45,8 @@ def item_lines(plan: str, item: ItemFacts) -> list[str]:
|
||||
first = item.plan.first
|
||||
worktree = item.worktree.reason if isinstance(item.worktree, Failure) else f"{item.worktree.path}, {item.worktree.how}"
|
||||
return [
|
||||
f"- The earliest release in {plan}: {version(first.release)}. Its first item that does not wait: item {first.id}, {levels(first)}.",
|
||||
f"- The {'next release, after the last cut, that ' + plan + ' names' if item.plan.carried else 'earliest release in ' + plan}: {version(first.release)}. {'The item this chunk starts from, named with --item' if item.plan.named else 'Its first item that does not wait'}: item {first.id}, {levels(first)}.",
|
||||
*carried_lines(item.plan),
|
||||
f"- Worktree: {worktree}",
|
||||
f"- Open pull requests from {item.plan.branch}: {pulls_text(item.pulls, item.plan.branch)}",
|
||||
*bundled(item.plan),
|
||||
@@ -57,6 +58,15 @@ def item_lines(plan: str, item: ItemFacts) -> list[str]:
|
||||
]
|
||||
|
||||
|
||||
def carried_lines(plan: Plan) -> list[str]:
|
||||
"""What the worker does about the items of a release someone cut while it held them."""
|
||||
over = plan.carried
|
||||
if over is None:
|
||||
return []
|
||||
items, count, them = (f"Items {listed([str(id_) for id_ in over.ids], 'and')} are", "they count", "them") if len(over.ids) > 1 else (f"Item {over.ids[0]} is", "it counts", "it")
|
||||
return [f"- {items} filed under a release already cut, so {count} as release {version(over.into)}'s, the next. Move {them} there as this chunk's first change, with `~/.claude/bin/todo-item move`, and say so in the chunk's opening line. Where todo-item cannot move this plan's items, as in a Jira plan, leave {them} and ask the human, in the chunk's summary, to move {them}."]
|
||||
|
||||
|
||||
def joining_details(plan: Plan) -> list[str]:
|
||||
"""The detail of each of the first JOINING_DETAILS items that may join the chunk, in the table's order, and what the worker lacks: an item with no detail, or the items left out."""
|
||||
joining = bundle_candidates(plan.items, plan.first)
|
||||
|
||||
@@ -6,6 +6,7 @@ import typing
|
||||
from failure import Failure
|
||||
from release_plan.todo_table import Item
|
||||
from release_plan.release_standing import LastCut
|
||||
from release_plan.release import Release
|
||||
from project_config import templates
|
||||
|
||||
# The CLI that lists a forge's pull requests: gh for a github.com origin, tea for any other.
|
||||
@@ -20,6 +21,13 @@ class Ran:
|
||||
stderr: str
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class CarriedOver:
|
||||
"""The items, by ID in the plan's order, that the plan files under a release already cut, and that count as `into`'s, the next release: release_standing.carried."""
|
||||
into: Release
|
||||
ids: tuple[int, ...]
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Plan:
|
||||
"""The default branch's plan items, each with its detail, and `first`: the item the next chunk takes first."""
|
||||
@@ -28,6 +36,10 @@ class Plan:
|
||||
# first's tagline and detail.
|
||||
text: str
|
||||
branch_template: str
|
||||
# The items of a release already cut, which `items` and `first` hold as the next release's. None where every item's release is after the last cut.
|
||||
carried: CarriedOver | None = None
|
||||
# Whether --item named first, in place of the next release's first item that does not wait.
|
||||
named: bool = False
|
||||
|
||||
@property
|
||||
def branch(self) -> str:
|
||||
|
||||
+22
-16
@@ -1,6 +1,6 @@
|
||||
"""Find the mechanical facts a chunk starts from, so its worker starts from them; with --worktree, also make its worktree.
|
||||
|
||||
usage: chunk-preflight [--worktree]
|
||||
usage: chunk-preflight [--worktree] [--item <ID>]
|
||||
|
||||
Run it inside a project checkout. It fetches origin, when the checkout has that remote, and takes
|
||||
origin's default branch, or else the local main or master. Without --worktree, it still fetches,
|
||||
@@ -16,18 +16,21 @@ and prints that the release reviews and the cuts are the human's to call. It pri
|
||||
newest version CHANGELOG.md heads `## X.Y.Z - YYYY-MM-DD`; an undated heading doesn't count.
|
||||
Then how many entries the default branch's CHANGELOG.md holds under ## Unreleased, or else how
|
||||
many commits followed the cut: the tag, or the commit that added that heading;
|
||||
- the next release and its first item that does not wait, the item loop-claude routes on, with
|
||||
its L and E + I. An item waits while it is marked question, or while an item still in todo.md
|
||||
- the next release and its first item that does not wait, the item loop-claude routes on, with its L
|
||||
and E + I; with --item <ID>, the plan item of that ID instead, which loop-claude names in a window
|
||||
named for an item. An item waits while it is marked question, or while an item still in todo.md
|
||||
blocks it. Where the last cut is a version x.y.z, the next release is the earliest after x.y.z
|
||||
that todo.md has named at that cut or since, less a release its ## Renamed section marks
|
||||
renamed. Where nothing is cut, it is the earliest release todo.md has ever named, less those
|
||||
renamed, so a release whose items are all done still reads as next.
|
||||
that todo.md has named at that cut or since, less a release its ## Renamed section marks renamed.
|
||||
Where nothing is cut, it is the earliest release todo.md has ever named, less those renamed, so a
|
||||
release whose items are all done still reads as next.
|
||||
Where the next release holds no item, it says so, naming it where todo.md named it since the cut:
|
||||
its release review due where changes are unreleased (the ## Unreleased entries, or else the
|
||||
commits since the cut) and no commit titled `Release review of <release>` followed the tag,
|
||||
finished and ready to cut once one did, and else to be planned first. On a branch with no tag,
|
||||
such a commit counts only where its <release> is after the version under the dated heading.
|
||||
Where todo.md's earliest release is x.y.z or earlier, it says todo.md files items under a release
|
||||
Where todo.md files items under x.y.z or earlier, someone cut a release that still held them:
|
||||
they count as the next release, the earliest after x.y.z that todo.md names or has named
|
||||
since the cut, and a line says to move them there. Where there is no such release, it says todo.md files items under a release
|
||||
already cut;
|
||||
- with --worktree, the item's worktree: a sibling of the checkout named <checkout>-<branch>,
|
||||
each / of the branch a dash, on the branch the config's `branch` template names, which is
|
||||
@@ -63,7 +66,7 @@ running after {timeout} seconds, or after the seconds CHUNK_PREFLIGHT_TIMEOUT se
|
||||
stopped fetch reads origin as last fetched. With no item, it makes no worktree and runs none of
|
||||
those four tools, --worktree or not.
|
||||
|
||||
Exit 1, saying why, on any argument other than --worktree, -h or --help, on a
|
||||
Exit 1, saying why, on any argument other than --worktree, --item with an ID, -h or --help, on a
|
||||
CHUNK_PREFLIGHT_TIMEOUT that is no number of seconds above 0, when git cannot start or finds no
|
||||
checkout or no default branch, or when no config names the checkout or its config cannot be read.
|
||||
"""
|
||||
@@ -90,16 +93,19 @@ TIMEOUT = 60
|
||||
TIMEOUT_SETTING = "CHUNK_PREFLIGHT_TIMEOUT"
|
||||
# The flag that makes the item's worktree and runs TOOLS in it. Three readers seated as the README's audience picked it 2-1 over --start.
|
||||
WORKTREE = "--worktree"
|
||||
# The flag that names the chunk's item. Three readers seated as the README's audience picked it 3-0 over --for, --start and a bare ID.
|
||||
ITEM = "--item"
|
||||
|
||||
|
||||
def main(argv: list[str], env: typing.Mapping[str, str]) -> int:
|
||||
if argv in (["-h"], ["--help"]):
|
||||
print(__doc__.strip().format(timeout=TIMEOUT, JOINING_DETAILS=JOINING_DETAILS))
|
||||
return 0
|
||||
if argv not in ([], [WORKTREE]):
|
||||
print(f"unknown arguments {' '.join(argv)}; usage: chunk-preflight [{WORKTREE}]", file=sys.stderr)
|
||||
rest = [arg for arg in argv if arg != WORKTREE]
|
||||
if len(argv) - len(rest) > 1 or not (rest == [] or (len(rest) == 2 and rest[0] == ITEM and re.fullmatch(r"[0-9]+", rest[1], re.ASCII))):
|
||||
print(f"unknown arguments {' '.join(argv)}; usage: chunk-preflight [{WORKTREE}] [{ITEM} <ID>]", file=sys.stderr)
|
||||
return 1
|
||||
printed = run(env.get(TIMEOUT_SETTING), argv == [WORKTREE])
|
||||
printed = run(env.get(TIMEOUT_SETTING), WORKTREE in argv, int(rest[1]) if rest else None)
|
||||
if isinstance(printed, Failure):
|
||||
print(printed.reason, file=sys.stderr)
|
||||
return 1
|
||||
@@ -107,13 +113,13 @@ def main(argv: list[str], env: typing.Mapping[str, str]) -> int:
|
||||
return 0
|
||||
|
||||
|
||||
def run(setting: str | None, make: bool) -> list[str] | Failure:
|
||||
"""The preflight's lines, given the setting TIMEOUT_SETTING holds and whether to make the item's worktree; a Failure where the setting is no number of seconds above 0, or git finds no checkout or no default branch."""
|
||||
def run(setting: str | None, make: bool, item_id: int | None = None) -> list[str] | Failure:
|
||||
"""The preflight's lines, given the setting TIMEOUT_SETTING holds, whether to make the item's worktree, and the ID --item names; a Failure where the setting is no number of seconds above 0, or git finds no checkout or no default branch."""
|
||||
timeout = seconds(setting)
|
||||
if isinstance(timeout, Failure):
|
||||
return timeout
|
||||
root = top()
|
||||
return root if isinstance(root, Failure) else preflight(pathlib.Path(root), timeout, make)
|
||||
return root if isinstance(root, Failure) else preflight(pathlib.Path(root), timeout, make, item_id)
|
||||
|
||||
|
||||
def seconds(setting: str | None) -> float | Failure:
|
||||
@@ -125,7 +131,7 @@ def seconds(setting: str | None) -> float | Failure:
|
||||
return Failure(f"{TIMEOUT_SETTING}={setting!r} is no number of seconds above 0")
|
||||
|
||||
|
||||
def preflight(root: pathlib.Path, timeout: float, make: bool) -> list[str] | Failure:
|
||||
def preflight(root: pathlib.Path, timeout: float, make: bool, item_id: int | None) -> list[str] | Failure:
|
||||
"""Gathers the facts step by step, each step taking what the ones before it found, and renders them; a Failure where the checkout has no default branch."""
|
||||
default = default_branch(stale_ok=True, timeout=timeout)
|
||||
if isinstance(default, Failure):
|
||||
@@ -136,7 +142,7 @@ def preflight(root: pathlib.Path, timeout: float, make: bool) -> list[str] | Fai
|
||||
return config
|
||||
outside = None if config.tracked("plan") else config.plan_label
|
||||
held = project_plan(config, ref, str(root))
|
||||
plan = planned(held.todo, held.cut, ref, config.branch, outside)
|
||||
plan = planned(held.todo, held.cut, ref, config.branch, outside, item_id)
|
||||
item = plan if isinstance(plan, NoItem) else item_facts(root, ref, plan, timeout, make)
|
||||
# A `checkout:` path lands in the worktree the chunk works in.
|
||||
made = located(str(item.worktree.path), pathlib.Path.home()) if isinstance(item, ItemFacts) and isinstance(item.worktree, Worktree) else config
|
||||
|
||||
@@ -10,10 +10,10 @@ import unittest
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from project_config.templates import BRANCH
|
||||
from chunk_preflight.gathered import CarriedOver, Gathered, ItemFacts, NamedPath, NoItem, Ran, Worktree
|
||||
from chunk_preflight import choices
|
||||
from failure import Failure
|
||||
from chunk_preflight.choices import forge_of, worktree_add
|
||||
from chunk_preflight.gathered import Gathered, ItemFacts, NamedPath, NoItem, Ran, Worktree
|
||||
from test_env import isolated_env
|
||||
from release_plan.release_standing import LastCut, UNSEEN_RELEASES
|
||||
from chunk_preflight.main import line_count, ran, seconds, TIMEOUT
|
||||
@@ -54,6 +54,10 @@ Change `src/app.py`'s `run` and the files under `src`, not `gone.py`.
|
||||
SHIPPED = TODO.replace("| 3 | 0.2.0 | | | **Do the next thing.** | 2 | 2 | 3 | 5 | 3 | 1 by 9 | 56.2 |\n", "").replace("| 7 | 0.2.0 | 3 |", "| 7 | 0.2.0 | |").replace("### 3. Do the next thing.", "### 7. Do the thing after.")
|
||||
# The plan once release 0.2.0 has shipped all its items: only release 0.3.0's item 9 is left.
|
||||
LATER = TODO[:TODO.index("| 5 |")] + "| 9 | 0.3.0 | | | **Do a later thing.** | 1 | 1 | 1 | 1 | 1 | 1 by 9 | 90.0 |\n"
|
||||
# Item 9's row, the only one under release 0.3.0.
|
||||
NINTH = "| 9 | 0.3.0 | | | **Do a later thing.** | 1 | 1 | 1 | 1 | 1 | 1 by 9 | 90.0 |\n"
|
||||
# A plan whose release 0.2.0 holds item 3 alone, before release 0.3.0's item 9.
|
||||
SHIPPED_BUT_3 = TODO[:TODO.index("| 5 |")] + "| 3 | 0.2.0 | | | **Do the next thing.** | 2 | 2 | 3 | 5 | 3 | 1 by 9 | 56.2 |\n" + NINTH
|
||||
# An items table that holds no row.
|
||||
EMPTY = TODO[:TODO.index("| 5 |")]
|
||||
CHANGELOG = "# Changelog\n\n## Unreleased\n\n- One.\n - A nested line.\n- Two.\n\n## 0.1.0\n\n- Old.\n"
|
||||
@@ -315,6 +319,29 @@ class ChunkPreflightTool(unittest.TestCase):
|
||||
self.assertFalse((repo.temp / "proj-item-3").exists())
|
||||
self.assertNotIn("item-3", repo.git(repo.root, "branch", "--list"))
|
||||
|
||||
def test_item_names_the_item_the_chunk_starts_from_in_place_of_the_plans_next(self):
|
||||
repo = Repo(self)
|
||||
for args in (["--item", "7"], ["--worktree", "--item", "7"], ["--item", "7", "--worktree"]):
|
||||
with self.subTest(args):
|
||||
done = repo.preflight(*args)
|
||||
self.assertEqual((done.returncode, done.stderr), (0, ""))
|
||||
self.assertIn("0.2.0. The item this chunk starts from, named with --item: item 7, L 1, E + I 2.", done.stdout)
|
||||
self.assertNotIn("Its first item that does not wait", done.stdout)
|
||||
self.assertTrue((repo.temp / "proj-item-7").is_dir())
|
||||
self.assertFalse((repo.temp / "proj-item-3").exists())
|
||||
|
||||
def test_item_names_no_item_where_the_plan_no_longer_holds_it(self):
|
||||
done = Repo(self).preflight("--worktree", "--item", "4")
|
||||
self.assertEqual((done.returncode, done.stderr), (0, ""))
|
||||
self.assertIn("- No plan item: origin/main's todo.md holds no item 4, the one --item names; it may have shipped. No worktree was made.", done.stdout)
|
||||
|
||||
def test_exits_1_on_an_item_that_is_no_id(self):
|
||||
for args in (["--item"], ["--item", "x"], ["--item", "7", "8"]):
|
||||
with self.subTest(args):
|
||||
done = Repo(self).preflight(*args)
|
||||
self.assertEqual((done.returncode, done.stdout), (1, ""))
|
||||
self.assertIn(f"unknown arguments {' '.join(args)}; usage: chunk-preflight [--worktree] [--item <ID>]", done.stderr)
|
||||
|
||||
def test_exits_1_on_an_argument_other_than_worktree(self):
|
||||
done = Repo(self).preflight("--start")
|
||||
self.assertEqual(done.returncode, 1)
|
||||
@@ -387,6 +414,10 @@ class Render(unittest.TestCase):
|
||||
self.assertIn("item 7, L 1, E + I 2, S 1: **Do the thing after.**", said)
|
||||
self.assertNotIn("item 8,", said)
|
||||
|
||||
def test_says_the_item_was_named_with_item(self):
|
||||
said = rendered(item_facts(plan=planned(TODO, CUT, "origin/main", BRANCH, None, 7)))
|
||||
self.assertIn("origin/main's todo.md: 0.2.0. The item this chunk starts from, named with --item: item 7, L 1, E + I 2.", said)
|
||||
|
||||
def test_states_each_fact_once_with_the_paths_between_the_worktree_and_the_open_pull_requests(self):
|
||||
lines = render(gathered(item_facts()))
|
||||
self.assertEqual([line.partition(":")[0] for line in lines[:6]], ["- Last version cut", "- The earliest release in origin/main's todo.md", "- Worktree", "- The project's config puts its files and plan at", "- The project's config sets", "- Open pull requests from item-3"])
|
||||
@@ -527,6 +558,14 @@ class Plans(unittest.TestCase):
|
||||
self.assertIn("L 'x'", planned(TODO.replace("| 2 | 2 | 3 | 5 |", "| x | 2 | 3 | 5 |"), CUT, "origin/main", BRANCH).why)
|
||||
self.assertIn("## Details holds a fenced code block", planned(TODO + "```\n", CUT, "origin/main", BRANCH).why)
|
||||
|
||||
def test_takes_the_item_item_names_even_one_that_waits_or_says_it_left_the_plan(self):
|
||||
# Item 7 waits for item 3, which another chunk runs.
|
||||
named = planned(TODO, CUT, "origin/main", BRANCH, None, 7)
|
||||
self.assertEqual((named.first.id, named.first.tagline, named.named), (7, "**Do the thing after.**", True))
|
||||
self.assertTrue(named.text.startswith("**Do the thing after.**"), named.text)
|
||||
self.assertFalse(planned(TODO, CUT, "origin/main", BRANCH).named)
|
||||
self.assertEqual(planned(TODO, CUT, "origin/main", BRANCH, None, 4), NoItem("origin/main's todo.md holds no item 4, the one --item names; it may have shipped."))
|
||||
|
||||
def test_tells_a_plan_with_no_items_table_from_one_whose_table_holds_no_item(self):
|
||||
without = planned("", CUT, "origin/main", BRANCH).why
|
||||
self.assertIn("origin/main", without)
|
||||
@@ -576,8 +615,27 @@ class Plans(unittest.TestCase):
|
||||
def test_takes_the_earliest_release_where_no_earlier_one_was_named_since_the_last_cut(self):
|
||||
self.assertEqual(planned(LATER, LastCut("v0.1.0", "", 4, [LATER]), "origin/main", BRANCH).first.id, 9)
|
||||
|
||||
def test_counts_the_items_of_a_release_already_cut_as_the_next_releases_and_says_to_move_them(self):
|
||||
plan = planned(TODO, LastCut("v0.2.0", "", 4, []), "origin/main", BRANCH)
|
||||
self.assertEqual((plan.first.id, plan.first.release), (3, (0, 3, 0)))
|
||||
self.assertEqual({item.release for item in plan.items}, {(0, 3, 0)})
|
||||
self.assertEqual(plan.carried, CarriedOver((0, 3, 0), (5, 3, 7, 8)))
|
||||
said = rendered(dataclasses.replace(item_facts(), plan=plan), LastCut("v0.2.0", "", 4, []))
|
||||
self.assertIn("- Items 5, 3, 7 and 8 are filed under a release already cut, so they count as release 0.3.0's, the next.", said)
|
||||
self.assertIn("`~/.claude/bin/todo-item move`", said)
|
||||
self.assertIn("- The next release, after the last cut, that origin/main's todo.md names: 0.3.0. Its first item that does not wait: item 3,", said)
|
||||
self.assertNotIn("already cut", rendered(item_facts()))
|
||||
|
||||
def test_says_to_move_one_or_two_items_of_a_release_already_cut_in_the_singular_or_the_plural(self):
|
||||
cut = LastCut("v0.2.0", "", 4, [])
|
||||
for todo, ids, said in ((SHIPPED_BUT_3, (3,), "- Item 3 is filed under a release already cut, so it counts as release 0.3.0's, the next. Move it there"), (SHIPPED_BUT_3 + NINTH.replace("| 9 | 0.3.0 |", "| 4 | 0.1.0 |"), (3, 4), "- Items 3 and 4 are filed under a release already cut, so they count as release 0.3.0's, the next. Move them there")):
|
||||
with self.subTest(ids=ids):
|
||||
plan = planned(todo, cut, "origin/main", BRANCH)
|
||||
self.assertEqual(plan.carried, CarriedOver((0, 3, 0), ids))
|
||||
self.assertIn(said, rendered(dataclasses.replace(item_facts(), plan=plan), cut))
|
||||
|
||||
def test_says_the_plan_files_items_under_a_release_already_cut(self):
|
||||
why = planned(TODO, LastCut("v0.2.0", "", 4, []), "origin/main", BRANCH).why
|
||||
why = planned(TODO.replace(NINTH, ""), LastCut("v0.2.0", "", 4, []), "origin/main", BRANCH).why
|
||||
self.assertIn("release 0.2.0", why)
|
||||
self.assertIn("v0.2.0", why)
|
||||
self.assertIn("not after", why)
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -126,7 +126,7 @@ class Main(unittest.TestCase):
|
||||
result = reply(Rung(args[args.index("--model") + 1], args[args.index("--effort") + 1]), "said Verdict: interrupt" in prompt.rsplit("latest last:", 1)[-1])
|
||||
return subprocess.CompletedProcess(args, 0, json.dumps(result), "")
|
||||
|
||||
effects = Effects(claude=claude, claude_on_terminal=unused, discard_typed=unused, dm=unused, execv=unused, git=unused, input=unused, local_time=unused, memory=unused, now=unused, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused)
|
||||
effects = Effects(claude=claude, claude_on_terminal=unused, discard_typed=unused, dm=unused, execv=unused, git=unused, input=unused, local_time=unused, memory=unused, now=unused, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused, tmux=unused, tmux_on_terminal=unused)
|
||||
out, err = io.StringIO(), io.StringIO()
|
||||
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
|
||||
code = main.main(argv, {}, self.home, effects)
|
||||
|
||||
@@ -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
|
||||
@@ -972,7 +983,7 @@ class LarvReviewTool(unittest.TestCase):
|
||||
checkout = pathlib.Path(temp, "acme")
|
||||
checkout.mkdir()
|
||||
config = configured(self, checkout) / "config.toml"
|
||||
config.write_text(config.read_text().replace('"checkout:todo.md"', '"jira:https://acme.atlassian.net/browse/ABC-12"') + 'env-file = "~/acme.env"\n')
|
||||
config.write_text(config.read_text().replace('"checkout:todo.md"', '"jira:https://acme.atlassian.net/browse/ABC-12"') + 'env-file = "~/acme.env"\njira-score-formula = "V"\njira-score-bar = 1\n')
|
||||
(checkout / "todo.md").write_text("the owners' own notes\n")
|
||||
self.enterContext(contextlib.chdir(checkout))
|
||||
said: list[str] = []
|
||||
@@ -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")
|
||||
@@ -1235,16 +1250,18 @@ class LarvReviewTool(unittest.TestCase):
|
||||
credentials = self.config.parents[2] / "acme.env"
|
||||
credentials.write_text("ATLASSIAN_EMAIL=me@example.com\nATLASSIAN_API_TOKEN=s3cret\n")
|
||||
credentials.chmod(0o600)
|
||||
self.config.write_text(PROJECT_CONFIG.replace('"checkout:todo.md"', f'"{epic}"').replace('"checkout:README.md"', f'"{epic}"') + 'env-file = "~/acme.env"\n')
|
||||
self.config.write_text(PROJECT_CONFIG.replace('"checkout:todo.md"', f'"{epic}"').replace('"checkout:README.md"', f'"{epic}"') + 'env-file = "~/acme.env"\njira-score-formula = "V"\njira-score-bar = 1\n')
|
||||
ran = self.run_tool("reviewer-header", "prose")
|
||||
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"
|
||||
|
||||
@@ -10,6 +10,7 @@ from claude_code.transcript import human_turns, read_transcript
|
||||
from loop_claude.stop import needs_human, needs_terminal, Stop
|
||||
from model_routing.ladder import Rung
|
||||
from loop_claude.direct_message import tell
|
||||
from loop_claude import tmux
|
||||
|
||||
ANSWER_QUESTION = "answer the question above"
|
||||
# TALK, what the human types at loop-claude's terminal to open claude for the question, and ASK_ANSWER were picked on 2026-10-17 by a bench of three readers seated as the README's audience, as ~/.claude/CLAUDE.md → "Working loop" → "Bench a syntax with the people who write it." has it.
|
||||
@@ -36,17 +37,26 @@ class Talked:
|
||||
"""The human typed in the worker's claude session."""
|
||||
|
||||
|
||||
def interrupt(question: str, answer_here: bool, session: WorkerSession, effects: Effects) -> str | Talked | Stop:
|
||||
"""Prints question for the human and returns their answer: where answer_here, the first line typed at loop-claude's terminal, stripped, or Talked once they typed in the worker's claude session, which TALK opens; else Talked once they typed in that session, which opens at once on the terminal. A Stop where loop-claude is off a terminal, or they type no answer, or the input ends."""
|
||||
say(f"\n{question}", effects)
|
||||
def interrupt(question: str, answer_here: bool, session: WorkerSession, window: tmux.Window, effects: Effects) -> str | Talked | Stop:
|
||||
"""Prints question for the human, in window, and returns their answer. While it waits, the window's name ends in tmux.WAITS, and the bell it rings shows in tmux's status bar. The answer: where answer_here, the first line typed at loop-claude's terminal, stripped, or Talked once they typed in the worker's claude session, which TALK opens; else Talked once they typed in that session, which opens at once on the terminal. A Stop where loop-claude is off a terminal, or they type no answer, or the input ends."""
|
||||
# The bell ends the question's line, so it rings once the question can be read.
|
||||
say(f"\n{question}{tmux.BELL}", effects)
|
||||
on_terminal = effects.on_terminal()
|
||||
if on_terminal:
|
||||
# Keys typed while the worker ran wait on the terminal, and would answer a question no one has read, here or in claude's session, which reads them too. Of a pasted answer, the first line answers; the rest wait, and the next question drops them. A longer answer goes through TALK.
|
||||
effects.discard_typed()
|
||||
tmux.mark(window, True, effects.tmux)
|
||||
# After the discard, so an answer typed while the DM sends counts; before the terminal check, so a loop that cannot ask still tells the human what it would have asked.
|
||||
tell(f"loop-claude in {session.root} asks:\n\n{question}", effects)
|
||||
if stop := needs_terminal(ANSWER_QUESTION, on_terminal):
|
||||
return stop
|
||||
tell(f"loop-claude in {session.root} asks, in the tmux window {window.target}:\n\n{question}", effects)
|
||||
answer = needs_terminal(ANSWER_QUESTION, on_terminal) or answered(answer_here, session, effects)
|
||||
# A loop that stops unanswered leaves the mark on its window.
|
||||
if not isinstance(answer, Stop):
|
||||
tmux.mark(window, False, effects.tmux)
|
||||
return answer
|
||||
|
||||
|
||||
def answered(answer_here: bool, session: WorkerSession, effects: Effects) -> str | Talked | Stop:
|
||||
"""The human's answer, as interrupt returns it."""
|
||||
answer = typed_answer(effects) if answer_here else TALK
|
||||
if answer != TALK:
|
||||
return answer
|
||||
|
||||
@@ -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),
|
||||
))
|
||||
|
||||
|
||||
@@ -53,17 +53,22 @@ def preflight_facts(printed: str) -> str:
|
||||
return f"loop-claude ran `~/.claude/bin/chunk-preflight` at the checkout root just before this run. Take what it printed as found rather than finding it again:\n\n{printed}"
|
||||
|
||||
|
||||
def held_by_others(items: list[int]) -> str:
|
||||
"""Keeps a fresh worker off the plan items the project's other chunks hold, running or stopped."""
|
||||
return f"\n\nOther chunks of this project, running or stopped, hold {'items ' if len(items) > 1 else 'item '}{', '.join(map(str, items))}. Leave those items out of this chunk, even where the facts above list them as items that may join it."
|
||||
|
||||
|
||||
def preflight_failed(reason: str) -> str:
|
||||
"""Has the worker find the facts chunk-preflight would have, its worktree among them."""
|
||||
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 +76,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 +123,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 +146,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 +163,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 +203,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,9 +22,9 @@ 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 loop_claude.tmux import Window
|
||||
from model_routing import worker_rungs
|
||||
|
||||
|
||||
@@ -39,6 +40,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
|
||||
@@ -52,6 +55,8 @@ class Cycle:
|
||||
todo: Plan | Failure
|
||||
# Empty when the previous cycle's verdict was not Unfinished.
|
||||
unfinished_evidence: str
|
||||
# The tmux window the loop runs in, which an interrupt marks.
|
||||
window: Window
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
@@ -79,7 +84,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 +105,7 @@ def archived(project_archive: pathlib.Path, transcript_path: str, task: str, out
|
||||
|
||||
def judge_of(cycle: Cycle) -> Rung:
|
||||
"""The judge's rung, which the archive names beside each verdict."""
|
||||
return judge_rung(cycle.judge_model)
|
||||
return judge_rung(cycle.ladder, cycle.judge_model)
|
||||
|
||||
|
||||
def step(cycle: Cycle, state: Active) -> Event | Stop:
|
||||
@@ -138,12 +143,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:
|
||||
@@ -196,7 +201,7 @@ def keep_rejection(cycle: Cycle, transcript_path: str, rejected: Rejected) -> St
|
||||
def ask(cycle: Cycle, transcript_path: str, ruling: Interrupt | QuotedAnswer) -> HumanTyped | HumanTalked | Stop:
|
||||
"""The human's answer to a ruling that rule archived as it ruled; the human's answer then grows the transcript."""
|
||||
# Only the human may cut a release, so a release ready to cut opens claude's session at once.
|
||||
answer = interrupt(question_for(ruling), not (isinstance(ruling, Interrupt) and ruling.release_ready), worker_session(cycle, transcript_path), cycle.effects)
|
||||
answer = interrupt(question_for(ruling), not (isinstance(ruling, Interrupt) and ruling.release_ready), worker_session(cycle, transcript_path), cycle.window, cycle.effects)
|
||||
match answer:
|
||||
case Stop():
|
||||
return answer
|
||||
|
||||
@@ -8,13 +8,15 @@ from loop_effects.effects import Effects, say
|
||||
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 loop_claude.loop.chunk_windows import held_beside, item_of
|
||||
from chunk_preflight.main import ITEM
|
||||
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 +36,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:
|
||||
@@ -61,15 +63,16 @@ def archived_route(archive_folder: pathlib.Path, loop: Loop) -> Route | None:
|
||||
def chunk_start(loop: Loop) -> tuple[str, typing.Callable[[], Item | None]]:
|
||||
"""The facts for a fresh worker's prompt, empty where the session is open, and the reader of the item that routes the chunk. The reader reads the default branch as last fetched: for a fresh chunk, by the preflight that runs first; for an open session, which runs none, by whatever fetched last."""
|
||||
facts = "" if session_open(loop.session) else chunk_facts(loop)
|
||||
return facts, lambda: plan_item(fetched_plan(loop), loop.effects)
|
||||
return facts, lambda: plan_item(fetched_plan(loop), item_of(loop.window.name), loop.effects)
|
||||
|
||||
|
||||
def chunk_facts(loop: Loop) -> str:
|
||||
"""What `chunk-preflight --worktree` printed at the checkout root, for a fresh worker's prompt, or why it could not run."""
|
||||
done = loop.effects.python([str(loop.launcher.with_name("chunk-preflight")), "--worktree"], loop.root)
|
||||
if done.returncode:
|
||||
return prompts.preflight_failed(done.stderr.strip() or f"it exited {done.returncode}")
|
||||
return prompts.preflight_facts(done.stdout.strip())
|
||||
"""What `chunk-preflight --worktree` printed at the checkout root, for a fresh worker's prompt, or why it could not run. The chunk of a window named for an item starts from that item, and either ends with the items the project's other chunks hold."""
|
||||
item = item_of(loop.window.name)
|
||||
done = loop.effects.python([str(loop.launcher.with_name("chunk-preflight")), "--worktree", *([] if item is None else [ITEM, str(item)])], loop.root)
|
||||
facts = prompts.preflight_failed(done.stderr.strip() or f"it exited {done.returncode}") if done.returncode else prompts.preflight_facts(done.stdout.strip())
|
||||
held = held_beside(loop.window.name, loop.root, loop.paths, loop.effects)
|
||||
return facts + (prompts.held_by_others(held) if held else "")
|
||||
|
||||
|
||||
def fetched_plan(loop: Loop) -> DefaultPlan | Failure:
|
||||
@@ -83,13 +86,13 @@ def fetched_plan(loop: Loop) -> DefaultPlan | Failure:
|
||||
return ref if isinstance(ref, Failure) else project_plan(config, ref, loop.root, loop.effects.git)
|
||||
|
||||
|
||||
def plan_item(plan: DefaultPlan | Failure, effects: Effects) -> Item | None:
|
||||
"""The item that routes a chunk, release_standing.chunk_item's pick from the default branch; None without one, so the chunk runs on the project's rung."""
|
||||
def plan_item(plan: DefaultPlan | Failure, window_item: int | None, effects: Effects) -> Item | None:
|
||||
"""The item that routes a chunk: the one its window is named for, or else release_standing.chunk_item's pick from the default branch; None without one, so the chunk runs on the project's rung."""
|
||||
# It prints the reason itself, through effects, like the other loop-claude functions that print. todo.md item 51 moves them all to one injected effect, so changing this one alone would be undone.
|
||||
if isinstance(plan, Failure):
|
||||
item: Item | Failure | None = plan
|
||||
else:
|
||||
item = routed_item(plan.todo, plan.cut)
|
||||
item = routed_item(plan.todo, plan.cut, window_item)
|
||||
if isinstance(item, Failure):
|
||||
say(f"routing on the project's rung: {item.reason}", effects)
|
||||
return None
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
"""The chunks of one project that run at once, each in its own tmux window: which may start now, and how each starts (docs/decisions.md → `loop-claude: each chunk runs in its own tmux window`)."""
|
||||
import contextlib
|
||||
import fcntl
|
||||
import pathlib
|
||||
import re
|
||||
import typing
|
||||
|
||||
from touch_predictions.beside import Beside, chunks_beside
|
||||
from loop_claude.cycle import chunk_items
|
||||
from git_cli.git_repo import default_ref
|
||||
from loop_effects.effects import Effects, say
|
||||
from failure import Failure
|
||||
from project_config.main import located
|
||||
from loop_claude.loop.reload import LoopRun
|
||||
from chunk_preflight.gathered import NoItem, Plan
|
||||
from touch_predictions.prediction import overlaps, predicted, Touches
|
||||
from loop_state.paths import Paths
|
||||
from chunk_preflight.choices import planned
|
||||
from transcript_archive.project_key import project_key
|
||||
from release_plan.release_standing import project_plan
|
||||
from claude_code.transcript import read_transcript
|
||||
from claude_code.session import Session, session_named, transcript_file
|
||||
from loop_claude import tmux
|
||||
|
||||
# Under the home folder, a folder per project key holds LOCK.
|
||||
STATE = ".local/state/loop-claude"
|
||||
# The file a loop keeps locked with flock while it lists the project's windows and starts new ones, so two loops whose chunks finish together don't start a chunk twice.
|
||||
LOCK = "starting"
|
||||
# The flag that tells the loop in a window its chunk, as `--chunk item-372`. Nobody types it, so no panel picked it.
|
||||
CHUNK_FLAG = "--chunk"
|
||||
# The chunk of a plan that names no item for the next chunk: a release to plan, a release review, or a task outside the plan.
|
||||
NO_ITEM = "no-item"
|
||||
# Seconds a fetch of origin may take before a chunk starts; past them, the plan reads as last fetched.
|
||||
FETCH_TIMEOUT = 60
|
||||
# The prefix of the variables loop-claude reads. A window gets the tmux server's environment, not the starting terminal's, so they are handed to each window by name.
|
||||
HANDED = "LOOP_CLAUDE_"
|
||||
|
||||
|
||||
def window_name(item_id: int) -> str:
|
||||
return f"item-{item_id}"
|
||||
|
||||
|
||||
def item_of(chunk: str) -> int | None:
|
||||
"""The ID of the plan item a chunk starts from; None for NO_ITEM."""
|
||||
named = re.fullmatch(r"item-([0-9]+)", chunk)
|
||||
return int(named[1]) if named else None
|
||||
|
||||
|
||||
def chunk_session(key: str, chunk: str, claude_code_transcripts: pathlib.Path) -> Session:
|
||||
"""The worker's session for a chunk. A rerun finds a chunk left open by this name. "A " is the human's cue in the session picker that the session is the loop's."""
|
||||
return session_named(f"A {key} loop-claude {chunk}", claude_code_transcripts)
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def starting(home: pathlib.Path, key: str) -> typing.Iterator[None]:
|
||||
"""Holds the project's LOCK. Raises OSError where the file cannot be opened or locked."""
|
||||
folder = home / STATE / key
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
with open(folder / LOCK, "a") as lock:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX)
|
||||
yield
|
||||
|
||||
|
||||
def held_items(chunks: typing.Iterable[str], key: str, claude_code_transcripts: pathlib.Path) -> set[int]:
|
||||
"""The plan items these chunks hold: the one each started from, and those its worker names on its latest `Chunk items:` line so far. A chunk whose transcript cannot be read holds the item it started from."""
|
||||
held: set[int] = set()
|
||||
for chunk in chunks:
|
||||
held.update(filter(None, [item_of(chunk)]))
|
||||
transcript = transcript_file(chunk_session(key, chunk, claude_code_transcripts))
|
||||
entries = read_transcript(transcript) if transcript else []
|
||||
held.update([] if isinstance(entries, Failure) else chunk_items.named(entries))
|
||||
return held
|
||||
|
||||
|
||||
def may_start(plan: Plan | NoItem, running: list[str], held: set[int], limit: int) -> list[str]:
|
||||
"""The chunks to start now beside the running ones, whose chunks hold the items in held: the plan's next item and the items touch_predictions picks to run beside it, in the plan's order, up to limit chunks running at once. Each leaves out an item in held, and one whose `Touches:` prediction overlaps a held item's, or where either has none. A plan without an item starts NO_ITEM, and only alone."""
|
||||
if isinstance(plan, NoItem):
|
||||
return [] if running else [NO_ITEM]
|
||||
beside = chunks_beside(plan.items, plan.first)
|
||||
picked = [plan.first.id, *(beside.picked if isinstance(beside, Beside) else [])]
|
||||
details = {item.id: item.detail for item in plan.items}
|
||||
# chunks_beside checks overlaps against the plan's next item only, and a running chunk's item may no longer be that one once an item merged. A held item that left the plan overlaps nothing.
|
||||
theirs = [predicted(details[item_id]) for item_id in sorted(held) if item_id in details]
|
||||
free = [item_id for item_id in picked if item_id not in held and clear_of(predicted(details[item_id]), theirs)]
|
||||
return [window_name(item_id) for item_id in free][: max(limit - len(running), 0)]
|
||||
|
||||
|
||||
def clear_of(ours: Touches | Failure | None, theirs: list[Touches | Failure | None]) -> bool:
|
||||
"""Whether a prediction overlaps none of theirs; not where one of them is missing or unreadable, unless theirs is empty."""
|
||||
return not theirs or (isinstance(ours, dict) and all(isinstance(touches, dict) and not overlaps(ours, touches) for touches in theirs))
|
||||
|
||||
|
||||
def next_plan(root: str, home: pathlib.Path, effects: Effects) -> Plan | NoItem | Failure:
|
||||
"""The plan on the default branch, fetched now where origin answers, with its next item, as chunk-preflight reads it."""
|
||||
config = located(root, home)
|
||||
if isinstance(config, Failure):
|
||||
return config
|
||||
# A chunk that just merged left the plan on origin. A fetch that fails leaves the plan as last fetched, which chunk-preflight then reads too.
|
||||
effects.git("fetch", "--quiet", "origin", cwd=root, timeout=FETCH_TIMEOUT)
|
||||
ref = default_ref(root, FETCH_TIMEOUT, run=effects.git)
|
||||
if isinstance(ref, Failure):
|
||||
return ref
|
||||
held = project_plan(config, ref, root, effects.git)
|
||||
return planned(held.todo, held.cut, ref, config.branch, None if config.tracked("plan") else config.plan_label)
|
||||
|
||||
|
||||
def start_chunks(loop_run: LoopRun, leaving: bool, paths: Paths, env: typing.Mapping[str, str], launcher: pathlib.Path, effects: Effects) -> list[str] | Failure:
|
||||
"""Starts a loop-claude in a new window for each chunk of loop_run's project that may start now, and returns the chunks started. leaving says that loop_run's own chunk finished, so its window no longer counts as running; without it, the human started loop-claude. A plan that cannot be read starts NO_ITEM, as a plan without an item does. A Failure says why a chunk could not start; those before it run."""
|
||||
config = located(loop_run.root, paths.home)
|
||||
if isinstance(config, Failure):
|
||||
return config
|
||||
key = project_key(loop_run.root, paths.home)
|
||||
session = tmux.session_name(key)
|
||||
handed = {name: value for name, value in env.items() if name.startswith(HANDED)}
|
||||
try:
|
||||
with starting(paths.home, key):
|
||||
windows = tmux.listed(session, effects.tmux)
|
||||
if windows and (owned := tmux.owner(session, effects.tmux)) != loop_run.root:
|
||||
return Failure(f"the tmux session {session} runs the chunks of {owned or 'another checkout'}, whose key maps to the same session name; rename one of the two checkouts' folders")
|
||||
running = [window.name for window in windows if not window.dead and not (leaving and window.name == loop_run.chunk)]
|
||||
# Below 0 where the config lowered parallel-chunks while more chunks ran.
|
||||
room = max(config.parallel_chunks - len(running), 0)
|
||||
# A loop that the human stopped, or that failed, keeps its window, dead, with its last lines and its items. Only the human's loop-claude <task> starts it again, before any other chunk.
|
||||
stopped = [window.name for window in windows if window.dead]
|
||||
chunks = [] if leaving else stopped[:room]
|
||||
if len(chunks) < room:
|
||||
plan = next_plan(loop_run.root, paths.home, effects)
|
||||
if isinstance(plan, Failure):
|
||||
# Such as in a checkout without a default branch, where chunk-preflight fails too: the worker is told why and finds the facts itself.
|
||||
say(f"starting a chunk without a plan item, since the plan cannot be read: {plan.reason}", effects)
|
||||
plan = NoItem(plan.reason)
|
||||
held = held_items(running + stopped, key, paths.claude_code_transcripts)
|
||||
chunks += [chunk for chunk in may_start(plan, running + chunks, held, config.parallel_chunks) if chunk not in stopped]
|
||||
for chunk in chunks:
|
||||
stale = [window for window in windows if window.name == chunk and window.dead]
|
||||
for window in stale:
|
||||
tmux.close(window, effects.tmux)
|
||||
windows = [window for window in windows if window not in stale]
|
||||
command = [str(launcher), CHUNK_FLAG, chunk, loop_run.task]
|
||||
if failed := tmux.start_window(tmux.Window(session, chunk, ""), loop_run.root, handed, command, not windows, effects.tmux):
|
||||
return failed
|
||||
windows.append(tmux.Listed(chunk, "", False))
|
||||
return chunks
|
||||
except OSError as failure:
|
||||
return Failure(f"cannot lock {paths.home / STATE / key / LOCK}: {failure.strerror}")
|
||||
|
||||
|
||||
def held_beside(chunk: str, root: str, paths: Paths, effects: Effects) -> list[int]:
|
||||
"""The plan items that the project's other chunks hold now, running or stopped, which a chunk starting as `chunk` leaves to them. It waits for a loop that is starting windows, so chunks started together see each other. Where the lock cannot be taken, it reads the windows without it."""
|
||||
key = project_key(root, paths.home)
|
||||
with contextlib.suppress(OSError), starting(paths.home, key):
|
||||
pass
|
||||
others = [window.name for window in tmux.listed(tmux.session_name(key), effects.tmux) if window.name != chunk]
|
||||
return sorted(held_items(others, key, paths.claude_code_transcripts))
|
||||
@@ -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)
|
||||
|
||||
@@ -6,23 +6,25 @@ from transcript_archive.location import archive_root, project_archive
|
||||
from loop_claude.loop.chunk_start import archived_route, chunk_start, fetched_todo, routed
|
||||
from loop_claude.loop.routing_check import check_routing
|
||||
from loop_claude.project.checkout import checkout_root
|
||||
from loop_claude.loop.chunk_windows import CHUNK_FLAG, chunk_session, start_chunks
|
||||
from loop_claude.loop.close import closed_cycle
|
||||
from loop_claude.cycle.run import Cycle, run_cycle
|
||||
from loop_claude.loop.reload import decode_handed, exec_if_edited, fingerprint, LoopRun, RELOAD_FLAG
|
||||
from loop_effects.effects import Effects, say
|
||||
from failure import Failure
|
||||
from loop_claude.verdicts import Finished
|
||||
from loop_claude.project.model_choice import get_or_ask_models
|
||||
from git_cli.git_repo import Git
|
||||
from loop_claude.loop.usage import HELP
|
||||
from loop_claude.loop.this_loop import Loop
|
||||
from loop_state.paths import Paths
|
||||
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.stop import Stop
|
||||
from loop_claude.direct_message import tell
|
||||
from loop_claude import tmux
|
||||
|
||||
|
||||
def main(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launcher: pathlib.Path, cwd: pathlib.Path, effects: Effects) -> int:
|
||||
@@ -35,8 +37,8 @@ def main(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launcher:
|
||||
raise
|
||||
if stop.reason:
|
||||
say(stop.reason, effects, stdout=not stop.code)
|
||||
# Every stop but the human's own Ctrl-C and the help is DMed where the project's config can be read and sets `env-file`, so a loop left overnight never ends unseen. A loop given no task prints the help.
|
||||
if stop.code != 130 and stop.reason != HELP:
|
||||
# Every stop with a reason, but the help, is DMed where the project's config can be read and sets `env-file`, so a loop left overnight never ends unseen. A loop given no task prints the help. Ctrl-C stops without a reason. So does the loop that started the project's windows once it attaches or prints how to, and a loop whose chunk finished once it started the next chunks, since the project's chunks go on.
|
||||
if stop.reason not in ("", HELP):
|
||||
tell(f"loop-claude in {cwd} stopped: {stop.reason}", effects)
|
||||
return stop.code
|
||||
|
||||
@@ -45,10 +47,18 @@ def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launc
|
||||
loop_run = loop_run_from(argv, cwd, effects)
|
||||
if isinstance(loop_run, Stop):
|
||||
return loop_run
|
||||
# Before anything starts: a worktree, a claude session or a tmux window.
|
||||
if reason := tmux.unusable(effects.tmux):
|
||||
return Stop(1, reason)
|
||||
if loop_run.chunk is None:
|
||||
return windows_opened(loop_run, env, paths, launcher, effects)
|
||||
pane = env.get("TMUX_PANE")
|
||||
if not pane:
|
||||
return Stop(1, f"{CHUNK_FLAG} is how loop-claude starts itself in a tmux window; run loop-claude <task>")
|
||||
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)
|
||||
loop = Loop(root=loop_run.root, session=session, paths=paths, env=env, launcher=launcher, effects=effects)
|
||||
key = project_key(loop_run.root, paths.home)
|
||||
window = tmux.Window(tmux.session_name(key), loop_run.chunk, pane)
|
||||
loop = Loop(root=loop_run.root, session=chunk_session(key, loop_run.chunk, paths.claude_code_transcripts), window=window, paths=paths, env=env, launcher=launcher, effects=effects)
|
||||
while True:
|
||||
if stop := exec_if_edited(loop, baseline, loop_run):
|
||||
return stop
|
||||
@@ -59,17 +69,42 @@ 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
|
||||
# Off the ladder the worker runs on the project's model itself, which its route names.
|
||||
if stop := check_routing(archive_root(paths.home, env), cycle.project or cycle.route.rung, loop):
|
||||
return stop
|
||||
if isinstance(concluded.verdict, Finished):
|
||||
return handed_on(loop_run, loop)
|
||||
|
||||
|
||||
def windows_opened(loop_run: LoopRun, env: typing.Mapping[str, str], paths: Paths, launcher: pathlib.Path, effects: Effects) -> Stop:
|
||||
"""What the loop-claude the human runs does: starts each chunk that may start now in a window of the project's tmux session, then puts that session on the terminal until the human detaches."""
|
||||
started = start_chunks(loop_run, False, paths, env, launcher, effects)
|
||||
if isinstance(started, Failure):
|
||||
return Stop(1, started.reason)
|
||||
session = tmux.session_name(project_key(loop_run.root, paths.home))
|
||||
say(f"started {', '.join(started)} in the tmux session {session}" if started else f"the tmux session {session} runs every chunk that may run now, so `{loop_run.task}` started in no new window", effects, stdout=True)
|
||||
if not effects.on_terminal():
|
||||
say(f"not on a terminal; see the chunks with `tmux attach -t ={session}`", effects, stdout=True)
|
||||
return Stop(0, "")
|
||||
shown = tmux.show(session, "TMUX" in env)
|
||||
return Stop(1, f"`tmux {' '.join(shown)}` failed; the chunks go on in the tmux session") if effects.tmux_on_terminal(shown) else Stop(0, "")
|
||||
|
||||
|
||||
def handed_on(loop_run: LoopRun, loop: Loop) -> Stop:
|
||||
"""The stop of a loop whose chunk finished, once it has started each chunk that may start now. Its window closes as it exits."""
|
||||
started = start_chunks(loop_run, True, loop.paths, loop.env, loop.launcher, loop.effects)
|
||||
if isinstance(started, Failure):
|
||||
return Stop(1, f"the chunk finished, but the next could not start: {started.reason}")
|
||||
say(f"the chunk finished; started {', '.join(started) or 'no other, since the chunks running fill what may run now'}", loop.effects, stdout=True)
|
||||
return Stop(0, "")
|
||||
|
||||
|
||||
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,23 +114,38 @@ 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, window=loop.window)
|
||||
|
||||
|
||||
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:
|
||||
if argv[:1] != [RELOAD_FLAG]:
|
||||
task = " ".join(argv)
|
||||
chunk, words = (argv[1], argv[2:]) if len(argv) >= 2 and argv[0] == CHUNK_FLAG else (None, argv)
|
||||
task = " ".join(words)
|
||||
if task in ("", "-h", "--help"):
|
||||
return Stop(0 if task else 1, HELP)
|
||||
root = checkout_root(cwd, effects)
|
||||
return root if isinstance(root, Stop) else LoopRun(0, root, task, "")
|
||||
return root if isinstance(root, Stop) else LoopRun(0, root, task, "", chunk=chunk)
|
||||
loop_run = decode_handed(argv[1]) if len(argv) == 2 else None
|
||||
if not (loop_run and loop_run.root and loop_run.task):
|
||||
return Stop(1, f"the edited loop-claude cannot read the state the running one handed it, likely because the edit changed that handover; rerun loop-claude <task>. Handed: {' '.join(argv[1:])}")
|
||||
|
||||
@@ -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 chunk this loop runs in its tmux window, as chunk_windows names it: `item-372`, or `no-item`. None for the loop-claude the human started, which starts the windows; a loop started before chunks ran in windows reloads with None too, and so starts the project's windows; its open claude session, named for its slot, is left in the session picker (docs/decisions.md → `loop-claude: each chunk runs in its own tmux window, …`).
|
||||
chunk: str | None = None
|
||||
|
||||
|
||||
class Unreadable(Exception):
|
||||
@@ -38,8 +40,10 @@ def decode_handed(handed: str) -> LoopRun | None:
|
||||
except ValueError:
|
||||
return None
|
||||
# A loop started before 0.11.0 hands the items loop-inbox listed; dropping them keeps it running across its reload.
|
||||
# One started before chunks ran in tmux windows hands the slot it held.
|
||||
if isinstance(fields, dict):
|
||||
fields.pop("items_taken_in", None)
|
||||
fields.pop("slot", None)
|
||||
try:
|
||||
return LoopRun(**decoded_fields(fields, LOOP_RUN_FIELDS, "cycle_number", "root", "task", "unfinished_evidence"))
|
||||
except Unreadable:
|
||||
@@ -75,7 +79,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), "chunk": lambda value: None if value is None else exactly(str)(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]
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ import typing
|
||||
from loop_effects.effects import Effects
|
||||
from loop_state.paths import Paths
|
||||
from claude_code.session import Session
|
||||
from loop_claude.tmux import Window
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
@@ -14,6 +15,8 @@ class Loop:
|
||||
root: str
|
||||
# The worker's session.
|
||||
session: Session
|
||||
# The tmux window the loop runs in.
|
||||
window: Window
|
||||
paths: Paths
|
||||
env: typing.Mapping[str, str]
|
||||
# The loop-claude script, whose edits reload the loop and beside which chunk-preflight lies.
|
||||
|
||||
@@ -10,43 +10,70 @@ 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,
|
||||
either of which stops that one chunk.
|
||||
Words: ~/.claude/CLAUDE.md → "Vocabulary".
|
||||
|
||||
loop-claude needs tmux 3.2 or later, and checks it before it starts anything. Each chunk runs in its
|
||||
own window of one tmux session per project, named loop-<key>, such as loop-claude-config. <key> is
|
||||
the checkout's path relative to ~/code, or to / outside it, with a dash for each character other
|
||||
than a letter, a digit, _ or -. The tmux session's @loop-root option names its checkout, and a
|
||||
checkout whose key maps to a tmux session another checkout runs is refused. loop-claude <task>
|
||||
starts the chunks that may start now, then attaches to the tmux session, or switches to it inside
|
||||
tmux; detaching leaves the chunks running. Off a terminal it prints the command that attaches. Where
|
||||
no chunk may start, it says so, and the task starts in no new window. At most parallel-chunks chunks
|
||||
run at once, a whole number the project's config sets, 1 by default. The first starts from the
|
||||
plan's next item, and each other from an item whose `Touches:` prediction overlaps neither one
|
||||
before it nor an item another chunk holds (touch-predictions --help). A window is named for the item
|
||||
its chunk starts from, as item-372; a chunk without a plan item, such as planning a release or its
|
||||
release review, runs alone in the window no-item.
|
||||
|
||||
Each window runs a loop-claude for that one chunk, started with --chunk <window>, which nobody
|
||||
types. As a chunk finishes, its loop starts each chunk that may start then, with the task it ran
|
||||
itself, and exits, which closes its window. A loop that stops, by Ctrl-C, an exit below or a
|
||||
failure, keeps its window, with its last lines, and its chunk keeps its items; the next loop-claude
|
||||
<task> starts it again before any other. To stop every chunk, press Ctrl-C in each window. A chunk's
|
||||
claude session is named "A <key> loop-claude <window>", so a rerun resumes a chunk left open, and is
|
||||
deleted when the chunk finishes. A fresh worker is told the items the project's other chunks hold,
|
||||
running or stopped: each one's own and those on its latest `Chunk items:` line, and leaves them out.
|
||||
|
||||
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:
|
||||
loop-claude prints the question in the chunk's window and rings its bell. Until it is answered the
|
||||
window's name ends in " ?", as in "item-372 ?", which tmux's status bar shows. The human answers it
|
||||
there:
|
||||
- A line of text: the worker resumes headless with it. The judge reads it as the human's, so the
|
||||
chunk stays unfinished until the answer is recorded.
|
||||
- /talk: opens the worker's session with `claude --resume` on the terminal, to read the diff or
|
||||
discuss first. Once that claude exits, the judge rules on what was typed there.
|
||||
- /talk: opens the worker's claude session with `claude --resume` on the terminal, to read the diff
|
||||
or discuss first. Once that claude exits, the judge rules on what was typed there.
|
||||
- Enter alone: stops the loop.
|
||||
A release ready to cut opens that session on the terminal at once, since only the human may cut it.
|
||||
While claude is open, Ctrl-C reaches it alone, and the loop goes on.
|
||||
Where the project's config sets notifier, loop-claude also sends the human each question, each
|
||||
release ready to cut and each stop as a DM, as bin/notify sends it. Two stops are
|
||||
left out: Ctrl-C, and printing this help. A DM that fails is said on stderr, and the loop goes on.
|
||||
A release ready to cut opens that claude session on the terminal at once, since only the human may
|
||||
cut it. While claude is open, Ctrl-C reaches it alone, and the loop goes on. Where the project's
|
||||
config sets notifier, loop-claude also sends the human each question, naming its tmux window as
|
||||
<session>:<window>, each release ready to cut and each stop as a DM, as bin/notify sends it. Four
|
||||
stops are left out: Ctrl-C, printing this help, the loop-claude that started the windows once it
|
||||
attaches or prints how to, and a loop whose chunk finished once it started the next chunks. A DM
|
||||
that fails is said on stderr, and the loop goes on.
|
||||
|
||||
As a chunk starts, before it is routed, loop-claude runs bin/chunk-preflight --worktree and quotes
|
||||
what it prints in the first prompt (prompts.preflight_facts in bin/loop_claude/cycle/prompts.py);
|
||||
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.
|
||||
As a chunk starts, before it is routed, loop-claude runs bin/chunk-preflight --worktree, adding
|
||||
--item <ID> in a window named for an item, and quotes what it prints in the first prompt
|
||||
(prompts.preflight_facts in bin/loop_claude/cycle/prompts.py); 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
|
||||
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
|
||||
At every interrupt, and as every cycle ends, Ctrl-C and a failure included, the claude 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,
|
||||
then each verdict, quoted answer, rejected judge reply, step-up and stop, each opened by its UTC
|
||||
time. The layout, and when a copy is replaced, are in bin/transcript_archive/__init__.py.
|
||||
@@ -65,8 +92,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 +107,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 +139,16 @@ 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
|
||||
- tmux is missing or older than 3.2
|
||||
- --chunk is given outside a tmux window
|
||||
- a chunk's window cannot be started, as when the project's config cannot be read, or the tmux
|
||||
session runs another checkout's chunks
|
||||
- the tmux session cannot be put on the terminal
|
||||
- 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 +173,5 @@ 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 loop-claude <task> starts the chunks that may start, a stopped one first, and each
|
||||
resumes its claude session where it is open."""
|
||||
|
||||
@@ -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)
|
||||
|
||||
+41
-38
@@ -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
|
||||
|
||||
@@ -45,53 +45,56 @@ ESCALATION_CAP = 2
|
||||
JUDGE_REPLAYED = ("claude-opus-5-5",)
|
||||
|
||||
|
||||
def routed_item(plan: Plan | Failure, cut: LastCut) -> Item | Failure | None:
|
||||
"""The item release_standing.chunk_item picks from plan, weighed against the last cut; None when there is none, or it lacks L, E or I."""
|
||||
def routed_item(plan: Plan | Failure, cut: LastCut, item_id: int | None = None) -> Item | Failure | None:
|
||||
"""The plan's item item_id, or without one the item release_standing.chunk_item picks from plan, weighed against the last cut; None when there is none, or it lacks L, E or I."""
|
||||
if isinstance(plan, NoItemsTable):
|
||||
return None
|
||||
if isinstance(plan, Failure):
|
||||
return plan
|
||||
pick = chunk_item(plan.items, cut)
|
||||
takes = pick.item if isinstance(pick, Next) else None
|
||||
if item_id is None:
|
||||
pick = chunk_item(plan.items, cut)
|
||||
takes = pick.item if isinstance(pick, Next) else None
|
||||
else:
|
||||
takes = next((item for item in plan.items if item.id == item_id), 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 +104,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 +136,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 +145,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 +155,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
|
||||
@@ -28,6 +29,26 @@ OFF_LADDER = '{"model": "worker-model"}'
|
||||
OFF_LADDER_ROUTE = {"rung": {"model": "worker-model", "effort": ""}, "item": 0, "likelihood": 0, "escape_and_impact": 0, "unfinished": 0, "escape_and_impact_taken_in": 0, "escalated_at": 0}
|
||||
|
||||
|
||||
# A tmux that logs each command. It prints $FAKE_TMUX_VERSION for -V, $FAKE_TMUX_OWNER for show-options, and the file $FAKE_TMUX_WINDOWS for list-windows, where it finds no session without the file, and for any other command the ID of a new window.
|
||||
FAKE_TMUX = """#!{python}
|
||||
import json, os, pathlib, sys
|
||||
|
||||
argv = sys.argv[1:]
|
||||
with open(os.environ["FAKE_TMUX_LOG"], "a") as log:
|
||||
log.write(json.dumps(argv) + "\\n")
|
||||
windows = pathlib.Path(os.environ["FAKE_TMUX_WINDOWS"])
|
||||
if argv[0] == "-V":
|
||||
print(os.environ.get("FAKE_TMUX_VERSION", "tmux 3.2"))
|
||||
elif argv[0] == "show-options":
|
||||
print(os.environ["FAKE_TMUX_OWNER"])
|
||||
elif argv[0] == "list-windows":
|
||||
if not windows.exists():
|
||||
sys.exit("no server running")
|
||||
print(windows.read_text(), end="")
|
||||
else:
|
||||
print("@7")
|
||||
"""
|
||||
|
||||
# Plays claude from FAKE_CLAUDE_SCENARIO, one step per call, logging each call; a step for another role,
|
||||
# or none left, is Ctrl-C to loop-claude, which otherwise loops forever.
|
||||
FAKE_CLAUDE = """#!{python}
|
||||
@@ -165,9 +186,11 @@ class Run:
|
||||
code: int
|
||||
sleeps: list
|
||||
starts: list
|
||||
# stderr and stdout are without the local time that opens each message loop-claude prints; raw_stderr and raw_stdout keep it.
|
||||
# stderr and stdout are without the local time that opens each message loop-claude prints, and stderr without the bell an interrupt rings; raw_stderr and raw_stdout keep them.
|
||||
stderr: str
|
||||
stdout: str
|
||||
# Each tmux command run, as its arguments.
|
||||
tmux: list
|
||||
raw_stderr: str
|
||||
raw_stdout: str
|
||||
|
||||
@@ -194,6 +217,8 @@ class Checkout:
|
||||
fake.mkdir()
|
||||
(fake / "claude").write_text(FAKE_CLAUDE.format(python=sys.executable))
|
||||
(fake / "claude").chmod(0o755)
|
||||
(fake / "tmux").write_text(FAKE_TMUX.format(python=sys.executable))
|
||||
(fake / "tmux").chmod(0o755)
|
||||
(fake / "git").symlink_to(shutil.which("git"))
|
||||
site = self.temp / "site"
|
||||
site.mkdir()
|
||||
@@ -202,6 +227,11 @@ class Checkout:
|
||||
self.env.update({
|
||||
"FAKE_CLAUDE_LOG": str(self.temp / "calls.jsonl"),
|
||||
"FAKE_MEMINFO": str(self.temp / "meminfo"),
|
||||
"FAKE_TMUX_LOG": str(self.temp / "tmux.jsonl"),
|
||||
"FAKE_TMUX_WINDOWS": str(self.temp / "tmux-windows"),
|
||||
"FAKE_TMUX_OWNER": str(self.root),
|
||||
# The pane of the window the loop under test runs in.
|
||||
"TMUX_PANE": "%3",
|
||||
"FAKE_CLAUDE_SCENARIO": str(self.temp / "scenario.json"),
|
||||
"GIT_CONFIG_GLOBAL": os.devnull,
|
||||
"GIT_CONFIG_NOSYSTEM": "1",
|
||||
@@ -223,15 +253,20 @@ class Checkout:
|
||||
self.git("add", "todo.md")
|
||||
self.git("commit", "--quiet", "-m", "plan")
|
||||
|
||||
def run(self, steps, argv=(TASK,), cwd=None, terminal_input=None, stdout_on_terminal=True, before_typing=None, typed_early=""):
|
||||
for name in ("FAKE_CLAUDE_LOG", "LOOP_TEST_LOG"):
|
||||
def run(self, steps, argv=None, cwd=None, terminal_input=None, stdout_on_terminal=True, before_typing=None, typed_early="", chunk="no-item"):
|
||||
"""Runs loop-claude with argv, or without one as the loop of the window `chunk`, on TASK. Off a terminal, a window's loop whose chunk finished is run again while steps remain, as the window it starts for the next chunk would."""
|
||||
for name in ("FAKE_CLAUDE_LOG", "LOOP_TEST_LOG", "FAKE_TMUX_LOG"):
|
||||
pathlib.Path(self.env[name]).unlink(missing_ok=True)
|
||||
pathlib.Path(self.env["FAKE_CLAUDE_SCENARIO"]).write_text(json.dumps(steps))
|
||||
command = [sys.executable, str(self.script), *argv]
|
||||
command = [sys.executable, str(self.script), *(("--chunk", chunk, TASK) if argv is None else argv)]
|
||||
cwd = cwd or self.root
|
||||
if terminal_input is None:
|
||||
done = subprocess.run(command, capture_output=True, cwd=cwd, env=self.env, stdin=subprocess.DEVNULL, text=True, timeout=60)
|
||||
code, stdout, stderr = done.returncode, done.stdout, done.stderr
|
||||
code, stdout, stderr = 0, "", ""
|
||||
runs = 0
|
||||
while code == 0 and (runs == 0 or (argv is None and json.loads(pathlib.Path(self.env["FAKE_CLAUDE_SCENARIO"]).read_text()))):
|
||||
runs += 1
|
||||
done = subprocess.run(command, capture_output=True, cwd=cwd, env=self.env, stdin=subprocess.DEVNULL, text=True, timeout=60)
|
||||
code, stdout, stderr = done.returncode, stdout + done.stdout, stderr + done.stderr
|
||||
else:
|
||||
code, stdout, stderr = self.run_on_terminal(command, cwd, terminal_input, stdout_on_terminal, before_typing, typed_early)
|
||||
started = lines(pathlib.Path(self.env["LOOP_TEST_LOG"]))
|
||||
@@ -240,8 +275,9 @@ class Checkout:
|
||||
code=code,
|
||||
sleeps=[event["sleep"] for event in started if "sleep" in event],
|
||||
starts=[event["argv"] for event in started if "argv" in event],
|
||||
stderr=unstamped(stderr),
|
||||
stderr=unstamped(stderr).replace("\a", ""),
|
||||
stdout=unstamped(stdout),
|
||||
tmux=lines(pathlib.Path(self.env["FAKE_TMUX_LOG"])),
|
||||
raw_stderr=stderr,
|
||||
raw_stdout=stdout,
|
||||
)
|
||||
@@ -393,7 +429,7 @@ class Premises(unittest.TestCase):
|
||||
write_config(checkout.home, root)
|
||||
checkout.git("init", "--quiet", str(root))
|
||||
run = checkout.run([worker()], cwd=root)
|
||||
self.assertEqual(argument(run.calls[0], "--name"), f"A {str(root).lstrip('/')} loop-claude")
|
||||
self.assertEqual(argument(run.calls[0], "--name"), f"A {str(root).lstrip('/')} loop-claude no-item")
|
||||
|
||||
|
||||
class Cycles(unittest.TestCase):
|
||||
@@ -413,7 +449,7 @@ class Cycles(unittest.TestCase):
|
||||
self.assertEqual(run.roles(), ["worker", "judge", "worker", "judge", "worker", "judge"])
|
||||
workers = [call for call in run.calls if call["role"] == "worker"]
|
||||
session = argument(workers[0], "--session-id")
|
||||
self.assertEqual(argument(workers[0], "--name"), "A proj loop-claude")
|
||||
self.assertEqual(argument(workers[0], "--name"), "A proj loop-claude no-item")
|
||||
self.assertEqual(argument(workers[1], "--resume"), session)
|
||||
self.assertIsNone(argument(workers[1], "--session-id"))
|
||||
self.assertIsNone(argument(workers[1], "--name"))
|
||||
@@ -432,8 +468,10 @@ class Cycles(unittest.TestCase):
|
||||
self.assertIn("landed-it", run.calls[3]["stdin"])
|
||||
self.assertNotIn("landed-it", run.calls[5]["stdin"])
|
||||
self.assertEqual([path.name for path in checkout.transcripts()[0].parent.iterdir()], [checkout.transcripts()[0].name])
|
||||
self.assertIn("=== cycle 3, worker on worker-model ===", run.stdout)
|
||||
self.assertEqual(len(re.findall(rf"(?m)^{STAMP} === cycle 3, worker on worker-model ===$", run.raw_stdout)), 1)
|
||||
self.assertIn("=== cycle 2, worker on worker-model ===", run.stdout)
|
||||
self.assertEqual(len(re.findall(rf"(?m)^{STAMP} === cycle 2, worker on worker-model ===$", run.raw_stdout)), 1)
|
||||
# The finished chunk's loop started the next chunk's window and ended; the checkout has no default branch to read a plan from.
|
||||
self.assertIn("landed-it\nthe chunk finished; started no-item\n\n=== cycle 1, worker on worker-model ===\nnext chunk\n", run.stdout)
|
||||
copies = {verdict.removeprefix(f"Task: {TASK}\n\n"): copy for copy, verdict in checkout.archived().items()}
|
||||
self.assertEqual(sorted(copies), [f"<UTC> Stopped: Ctrl-C\n\nWorker: {OFF_LADDER}\n", f"<UTC> Verdict: finished\n\nEvidence:\n> landed-it\n\nConfig: <config>\nJudge: judge-model\nWorker: {OFF_LADDER}\n", f"<UTC> Verdict: unfinished\n\nEvidence:\n> started\n\nConfig: <config>\nJudge: judge-model\nWorker: {OFF_LADDER}\n"])
|
||||
self.assertIn('"text": "landed-it"', copies[f"<UTC> Verdict: finished\n\nEvidence:\n> landed-it\n\nConfig: <config>\nJudge: judge-model\nWorker: {OFF_LADDER}\n"])
|
||||
@@ -467,6 +505,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 +645,23 @@ 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_window_of_the_project_runs_its_own_session_and_leaves_the_first_ones_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()
|
||||
self.assertEqual(argument(first.calls[0], "--name"), "A proj loop-claude no-item")
|
||||
second = checkout.run([worker(say="second chunk"), judge(evidence="second chunk")], chunk="item-2")
|
||||
self.assertEqual(argument(second.calls[0], "--name"), "A proj loop-claude item-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)
|
||||
@@ -717,6 +804,111 @@ class Cycles(unittest.TestCase):
|
||||
self.assertEqual((run.code, run.roles()), (130, ["worker", "judge"] * 12))
|
||||
|
||||
|
||||
# Items 4 and 9 with predictions that do not overlap, so both may run at once, and item 12, which overlaps item 4.
|
||||
BESIDE = TAKEN_IN_AT_L_4 + "| 12 | 0.1.0 | | **Do most.** | 2 | 1 | 2 | 3 | 2 | 1 by 9 | 10 |\n\n## Details\n\n### 4. Do it.\n\nTouches:\n\n- `a.py`\n\n### 9. Do more.\n\nTouches:\n\n- `b.py`\n\n### 12. Do most.\n\nTouches:\n\n- `a.py`\n"
|
||||
|
||||
|
||||
class Windows(unittest.TestCase):
|
||||
def checkout(self, parallel=None):
|
||||
"""A checkout whose plan is BESIDE, with parallel-chunks set where given."""
|
||||
checkout = Checkout(self)
|
||||
checkout.commit_plan(BESIDE)
|
||||
if parallel:
|
||||
config = checkout.home / ".claude-projects" / "proj" / "config.toml"
|
||||
config.write_text(f"parallel-chunks = {parallel}\n" + config.read_text())
|
||||
return checkout
|
||||
|
||||
def started(self, run):
|
||||
"""The window each new-session or new-window made, with the command it runs."""
|
||||
return [(command[0], command[command.index("-n") + 1], command[command.index("--") + 1:]) for command in run.tmux if command[0] in ("new-session", "new-window")]
|
||||
|
||||
def test_starts_one_chunk_in_a_window_of_the_projects_session_by_default(self):
|
||||
checkout = self.checkout()
|
||||
run = checkout.run([], argv=["ship", "it"])
|
||||
self.assertEqual((run.code, run.calls, run.stderr), (0, [], ""))
|
||||
self.assertEqual(run.tmux, [
|
||||
["-V"],
|
||||
["list-windows", "-t", "=loop-proj", "-F", "#{window_name}\t#{pane_dead}\t#{window_id}"],
|
||||
["new-session", "-d", "-s", "loop-proj", "-n", "item-4", "-c", str(checkout.root), "-e", "LOOP_CLAUDE_JUDGE_MODEL=judge-model", "-e", "LOOP_CLAUDE_WORKER_MODEL=worker-model", "-P", "-F", "#{window_id}", "--", str(checkout.script), "--chunk", "item-4", "ship it"],
|
||||
["set-option", "-t", "=loop-proj:", "@loop-root", str(checkout.root)],
|
||||
["set-option", "-w", "-t", "@7", "remain-on-exit", "failed"],
|
||||
])
|
||||
self.assertEqual(run.stdout, "started item-4 in the tmux session loop-proj\nnot on a terminal; see the chunks with `tmux attach -t =loop-proj`\n")
|
||||
|
||||
def test_starts_up_to_the_configured_number_of_chunks_whose_predictions_do_not_overlap(self):
|
||||
run = self.checkout(parallel=3).run([], argv=[TASK])
|
||||
self.assertEqual([(made, window) for made, window, _ in self.started(run)], [("new-session", "item-4"), ("new-window", "item-9")])
|
||||
self.assertIn("started item-4, item-9 in the tmux session loop-proj\n", run.stdout)
|
||||
|
||||
def test_starts_only_what_the_running_windows_leave_room_for(self):
|
||||
checkout = self.checkout(parallel=2)
|
||||
# Item 4's chunk runs and waits for the human; item 9's loop failed, so its window stays, dead.
|
||||
pathlib.Path(checkout.env["FAKE_TMUX_WINDOWS"]).write_text("item-4 ?\t0\t@1\nitem-9\t1\t@2\n")
|
||||
run = checkout.run([], argv=[TASK])
|
||||
self.assertEqual([command for command in run.tmux if command[0] == "kill-window"], [["kill-window", "-t", "@2"]])
|
||||
self.assertEqual([(made, window) for made, window, _ in self.started(run)], [("new-window", "item-9")])
|
||||
pathlib.Path(checkout.env["FAKE_TMUX_WINDOWS"]).write_text("item-4\t0\t@1\nitem-9\t0\t@2\n")
|
||||
run = checkout.run([], argv=[TASK])
|
||||
self.assertEqual((self.started(run), run.code), ([], 0))
|
||||
self.assertIn(f"the tmux session loop-proj runs every chunk that may run now, so `{TASK}` started in no new window\n", run.stdout)
|
||||
|
||||
def test_a_finished_chunk_starts_the_next_one_its_window_leaves_room_for(self):
|
||||
checkout = self.checkout(parallel=2)
|
||||
pathlib.Path(checkout.env["FAKE_TMUX_WINDOWS"]).write_text("item-4\t0\t@1\nitem-9\t0\t@2\n")
|
||||
run = checkout.run([worker(say="merged"), judge(finished=True, evidence="merged")], chunk="item-9")
|
||||
self.assertEqual((run.code, run.roles()), (0, ["worker", "judge"]))
|
||||
# Item 9 is still in the checkout's plan, since nothing merged here; the window that leaves holds it no longer, and item 4's chunk still runs.
|
||||
self.assertEqual(self.started(run), [("new-window", "item-9", [str(checkout.script), "--chunk", "item-9", TASK])])
|
||||
self.assertIn("the chunk finished; started item-9\n", run.stdout)
|
||||
|
||||
def test_a_finished_chunk_starts_the_next_item_from_the_plan_its_merge_left_on_origin(self):
|
||||
checkout = Checkout(self)
|
||||
origin = checkout.temp / "origin.git"
|
||||
checkout.git("init", "--quiet", "--bare", "--initial-branch=main", str(origin))
|
||||
checkout.git("symbolic-ref", "HEAD", "refs/heads/main")
|
||||
checkout.commit_plan(TODO)
|
||||
checkout.git("remote", "add", "origin", str(origin))
|
||||
checkout.git("push", "--quiet", "--set-upstream", "origin", "main")
|
||||
# Item 4's chunk runs a cycle and stays open, so the rerun below resumes it and runs no chunk-preflight, which would fetch.
|
||||
self.assertEqual(checkout.run([worker(), judge()], chunk="item-4").code, 130)
|
||||
# Item 4's chunk merges, which leaves item 6 next on origin; the checkout fetched before it.
|
||||
elsewhere = checkout.temp / "elsewhere"
|
||||
checkout.git("clone", "--quiet", str(origin), str(elsewhere))
|
||||
(elsewhere / "todo.md").write_text(TODO.replace("| 4 | 0.1.0 |", "| 6 | 0.1.0 |"))
|
||||
checkout.git("-C", str(elsewhere), "commit", "--quiet", "--all", "-m", "Finish item 4")
|
||||
checkout.git("-C", str(elsewhere), "push", "--quiet", "origin", "main")
|
||||
run = checkout.run([worker(say="merged"), judge(finished=True, evidence="merged")], chunk="item-4")
|
||||
self.assertEqual(self.started(run), [("new-session", "item-6", [str(checkout.script), "--chunk", "item-6", TASK])])
|
||||
|
||||
def test_tells_a_fresh_worker_the_items_the_other_running_chunks_hold_and_starts_from_its_windows_item(self):
|
||||
checkout = self.checkout(parallel=2)
|
||||
checkout.env["LOOP_CLAUDE_WORKER_MODEL"] = "claude-opus-5-5"
|
||||
pathlib.Path(checkout.env["FAKE_TMUX_WINDOWS"]).write_text("item-4\t0\t@1\nitem-9\t0\t@2\n")
|
||||
run = checkout.run([worker()], chunk="item-9")
|
||||
prompt = argument(run.calls[0], "-p")
|
||||
self.assertIn("The item this chunk starts from, named with --item: item 9, L 4, E + I 3.", prompt)
|
||||
self.assertIn("Other chunks of this project, running or stopped, hold item 4. Leave those items out of this chunk, even where the facts above list them as items that may join it.", prompt)
|
||||
self.assertIn("routed by item 9's L of 4", prompt)
|
||||
|
||||
def test_refuses_to_start_on_a_tmux_older_than_needed_or_without_one(self):
|
||||
checkout = self.checkout()
|
||||
checkout.env["FAKE_TMUX_VERSION"] = "tmux 3.1c"
|
||||
run = checkout.run([], argv=[TASK])
|
||||
self.assertEqual((run.code, run.stderr, run.tmux), (1, "loop-claude runs each chunk in a tmux window, and needs tmux 3.2 or later; it found tmux 3.1c\n", [["-V"]]))
|
||||
(pathlib.Path(checkout.env["PATH"]) / "tmux").unlink()
|
||||
run = checkout.run([], argv=[TASK])
|
||||
self.assertEqual((run.code, run.stderr), (1, "loop-claude runs each chunk in a tmux window, and needs tmux 3.2 or later; it found no tmux\n"))
|
||||
|
||||
def test_marks_the_window_while_an_interrupt_waits_and_rings_its_bell(self):
|
||||
checkout = self.checkout()
|
||||
run = checkout.run([worker(say="A or B?"), judge(interrupt=True, question="A or B?")], chunk="item-4")
|
||||
self.assertEqual(run.code, 2)
|
||||
self.assertEqual([command for command in run.tmux if command[0] == "rename-window"], [["rename-window", "-t", "%3", "item-4 ?"]])
|
||||
self.assertEqual(run.raw_stderr.count("\a"), 1)
|
||||
run = checkout.run([worker(say="A or B?"), judge(interrupt=True, question="A or B?"), worker()], chunk="item-4", terminal_input="B\n", before_typing=ANSWERING)
|
||||
self.assertEqual([command for command in run.tmux if command[0] == "rename-window"], [["rename-window", "-t", "%3", "item-4 ?"], ["rename-window", "-t", "%3", "item-4"]])
|
||||
|
||||
|
||||
class Interrupt(unittest.TestCase):
|
||||
def test_exits_2_off_a_terminal_and_resumes_on_the_next_run(self):
|
||||
checkout = Checkout(self)
|
||||
@@ -917,17 +1109,28 @@ 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, "chunk": "no-item"} for cycle in (2, 3, 4)])
|
||||
self.assertIn("=== cycle 5,", run.stdout)
|
||||
|
||||
outside = checkout.temp / "outside"
|
||||
outside.mkdir()
|
||||
state = {"cycle_number": 3, "root": str(checkout.root), "task": TASK, "unfinished_evidence": "", "route": None}
|
||||
state = {"cycle_number": 3, "root": str(checkout.root), "task": TASK, "unfinished_evidence": "", "route": None, "chunk": "no-item"}
|
||||
run = checkout.run([worker()], argv=["--reloaded", json.dumps(state)], cwd=outside)
|
||||
self.assertEqual((run.code, run.roles()), (130, ["worker", "judge"]))
|
||||
self.assertEqual(run.calls[0]["cwd"], str(checkout.root))
|
||||
self.assertIn("=== cycle 4,", run.stdout)
|
||||
|
||||
def test_a_loop_started_before_chunks_ran_in_windows_reloads_into_starting_the_projects_windows(self):
|
||||
checkout = Checkout(self)
|
||||
state = {"cycle_number": 3, "root": str(checkout.root), "task": TASK, "unfinished_evidence": "", "route": None, "slot": 0}
|
||||
run = checkout.run([worker()], argv=["--reloaded", json.dumps(state)])
|
||||
self.assertEqual((run.code, run.calls), (0, []))
|
||||
self.assertEqual([command[0] for command in run.tmux], ["-V", "list-windows", "new-session", "set-option", "set-option"])
|
||||
self.assertIn("started no-item in the tmux session loop-proj\n", run.stdout)
|
||||
|
||||
def test_stops_where_a_reload_hands_no_state(self):
|
||||
checkout = Checkout(self)
|
||||
|
||||
run = checkout.run([], argv=["--reloaded", "{}"])
|
||||
self.assertEqual((run.code, run.calls), (1, []))
|
||||
self.assertIn("rerun loop-claude <task>", run.stderr)
|
||||
|
||||
+610
-134
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,101 @@
|
||||
"""The tmux commands loop-claude runs: each chunk's loop runs in its own window of one tmux session named for the project (docs/decisions.md → `loop-claude: each chunk runs in its own tmux window`)."""
|
||||
import dataclasses
|
||||
import re
|
||||
import subprocess
|
||||
import typing
|
||||
|
||||
from failure import Failure
|
||||
|
||||
# Runs tmux with these arguments and returns what it printed; exit 127 where tmux cannot start.
|
||||
Tmux = typing.Callable[[list[str]], subprocess.CompletedProcess[str]]
|
||||
|
||||
# The oldest tmux that has every command and option used here. Its CHANGES file dates the newest two to 3.2: `remain-on-exit failed` and `new-session -e`.
|
||||
NEEDED = (3, 2)
|
||||
# What a window's name ends in while its chunk waits for the human. tmux's status bar shows the name, and `!` after it once the bell rang.
|
||||
WAITS = " ?"
|
||||
BELL = "\a"
|
||||
# The session option that names the checkout whose chunks the session runs, since two checkouts' keys may map to one session name.
|
||||
OWNER = "@loop-root"
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Window:
|
||||
"""The tmux window a chunk's loop runs in."""
|
||||
session: str
|
||||
# Without WAITS.
|
||||
name: str
|
||||
# The ID of the loop's pane, which $TMUX_PANE holds. It targets the window whatever its name is.
|
||||
pane: str
|
||||
|
||||
@property
|
||||
def target(self) -> str:
|
||||
"""What `tmux attach -t` and `tmux select-window -t` take to reach the window."""
|
||||
return f"{self.session}:{self.name}"
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Listed:
|
||||
"""A window of the project's session, as tmux lists it."""
|
||||
# Without WAITS.
|
||||
name: str
|
||||
# tmux's ID of the window, such as `@3`.
|
||||
id: str
|
||||
# Whether its loop has exited: `remain-on-exit failed` keeps the window of a loop that failed, so its last lines stay readable.
|
||||
dead: bool
|
||||
|
||||
|
||||
def unusable(run: Tmux) -> str | None:
|
||||
"""Why loop-claude cannot use this machine's tmux, naming the version found and the one needed; None where it is NEEDED or later."""
|
||||
found = run(["-V"]).stdout.strip()
|
||||
version = re.search(r"([0-9]+)\.([0-9]+)", found)
|
||||
if version and (int(version[1]), int(version[2])) >= NEEDED:
|
||||
return None
|
||||
return f"loop-claude runs each chunk in a tmux window, and needs tmux {NEEDED[0]}.{NEEDED[1]} or later; it found {found or 'no tmux'}"
|
||||
|
||||
|
||||
def session_name(key: str) -> str:
|
||||
"""The tmux session of the project with this key, such as `loop-claude-config`. tmux reads `.` and `:` in a target as separators, so every character but a letter, a digit, `_` and `-` becomes a dash."""
|
||||
return "loop-" + re.sub(r"[^A-Za-z0-9_-]", "-", key)
|
||||
|
||||
|
||||
def listed(session: str, run: Tmux) -> list[Listed]:
|
||||
"""The windows of session; none where tmux lists none, as while the session doesn't exist or no tmux server runs."""
|
||||
done = run(["list-windows", "-t", f"={session}", "-F", "#{window_name}\t#{pane_dead}\t#{window_id}"])
|
||||
rows = [line.split("\t") for line in done.stdout.splitlines()] if done.returncode == 0 else []
|
||||
return [Listed(row[0].removesuffix(WAITS), row[2], row[1] == "1") for row in rows if len(row) == 3]
|
||||
|
||||
|
||||
def start_window(window: Window, cwd: str, env: typing.Mapping[str, str], command: list[str], first: bool, run: Tmux) -> Failure | None:
|
||||
"""Starts command in a new window of window's session, in cwd with env added to its environment, and leaves the client where it is. first makes the session too. A Failure says why tmux started none."""
|
||||
make = ["new-session", "-d", "-s", window.session] if first else ["new-window", "-d", "-t", f"={window.session}:"]
|
||||
variables = [flag for name, value in env.items() for flag in ("-e", f"{name}={value}")]
|
||||
# tmux reads a `;` that ends an argument as the end of the command, unless a backslash precedes it.
|
||||
words = [re.sub(r";$", r"\\;", word) for word in command]
|
||||
done = run([*make, "-n", window.name, "-c", cwd, *variables, "-P", "-F", "#{window_id}", "--", *words])
|
||||
if done.returncode:
|
||||
return Failure(f"tmux could not start the window {window.target}: {done.stderr.strip() or f'it exited {done.returncode}'}")
|
||||
if first:
|
||||
# set-option and show-options read a target as a pane's, so `=session` alone names no session.
|
||||
run(["set-option", "-t", f"={window.session}:", OWNER, cwd])
|
||||
# By the ID, since a window of the same name may still be closing. A loop that fails before the option is set closes its window, and its stop is still sent as a DM.
|
||||
run(["set-option", "-w", "-t", done.stdout.strip(), "remain-on-exit", "failed"])
|
||||
return None
|
||||
|
||||
|
||||
def owner(session: str, run: Tmux) -> str:
|
||||
"""The checkout whose chunks session runs, as OWNER names it; empty where it names none."""
|
||||
return run(["show-options", "-qv", "-t", f"={session}:", OWNER]).stdout.strip()
|
||||
|
||||
|
||||
def close(window: Listed, run: Tmux) -> None:
|
||||
run(["kill-window", "-t", window.id])
|
||||
|
||||
|
||||
def mark(window: Window, waits: bool, run: Tmux) -> None:
|
||||
"""Renames window to end in WAITS while its chunk waits for the human, and back once it doesn't."""
|
||||
run(["rename-window", "-t", window.pane, window.name + (WAITS if waits else "")])
|
||||
|
||||
|
||||
def show(session: str, inside: bool) -> list[str]:
|
||||
"""The tmux arguments that put session on the human's terminal: inside tmux the client switches to it, and outside a new client attaches."""
|
||||
return ["switch-client" if inside else "attach-session", "-t", f"={session}"]
|
||||
@@ -51,6 +51,10 @@ class Effects:
|
||||
python: typing.Callable[[list[str], str], subprocess.CompletedProcess[str]]
|
||||
sleep: typing.Callable[[float], None]
|
||||
stream_claude: typing.Callable[[list[str], str, dict[str, str]], Streaming]
|
||||
# Runs tmux with these arguments, as run_tmux does.
|
||||
tmux: typing.Callable[[list[str]], subprocess.CompletedProcess[str]]
|
||||
# Runs tmux on the terminal, as to attach a session, and returns its exit code once the human detaches.
|
||||
tmux_on_terminal: typing.Callable[[list[str]], int]
|
||||
|
||||
|
||||
class StreamingClaude:
|
||||
@@ -82,6 +86,8 @@ def system_effects(backends: typing.Mapping[Notifier, Backend[typing.Any]] = BAC
|
||||
python=lambda args, cwd: run_python(args, cwd, PYTHON_TIMEOUT),
|
||||
sleep=time.sleep,
|
||||
stream_claude=StreamingClaude,
|
||||
tmux=run_tmux,
|
||||
tmux_on_terminal=lambda args: subprocess.run(["tmux", *args]).returncode,
|
||||
)
|
||||
|
||||
|
||||
@@ -106,6 +112,15 @@ def run_python(args: list[str], cwd: str, timeout: float) -> subprocess.Complete
|
||||
return subprocess.CompletedProcess(command, 1, "", f"stopped after {timeout} s")
|
||||
|
||||
|
||||
def run_tmux(args: list[str]) -> subprocess.CompletedProcess[str]:
|
||||
"""Runs tmux and returns what it printed. A tmux that cannot start, as where none is installed, reads as exit 127, saying why on stderr."""
|
||||
command = ["tmux", *args]
|
||||
try:
|
||||
return subprocess.run(command, capture_output=True, encoding="utf-8", errors="replace", stdin=subprocess.DEVNULL)
|
||||
except OSError as failure:
|
||||
return subprocess.CompletedProcess(command, 127, "", f"could not start: {failure}")
|
||||
|
||||
|
||||
def say(text: str, effects: Effects, *, stdout: bool = False) -> None:
|
||||
"""Prints text on stderr, or on stdout where stdout, opening the first line of words with the machine's local time. Blank lines before those words stay blank, and later lines get no time."""
|
||||
body = text.lstrip("\n")
|
||||
|
||||
@@ -84,6 +84,36 @@ class ClaudeOnTerminal(unittest.TestCase):
|
||||
|
||||
|
||||
|
||||
class TmuxEffect(unittest.TestCase):
|
||||
"""Each test runs a fake tmux off its own PATH, without $TMUX, so the human's tmux server is never reached."""
|
||||
|
||||
def fake_tmux(self, folder):
|
||||
tmux = pathlib.Path(folder, "tmux")
|
||||
tmux.write_text(f"#!{sys.executable}\nimport sys\nprint(' '.join(sys.argv[1:]))\nsys.exit(4)\n")
|
||||
tmux.chmod(0o755)
|
||||
return unittest.mock.patch.dict(os.environ, {"PATH": folder, "TMUX": "", "TMUX_PANE": ""})
|
||||
|
||||
def test_runs_tmux_and_returns_what_it_printed(self):
|
||||
with tempfile.TemporaryDirectory() as folder, self.fake_tmux(folder):
|
||||
done = system_effects().tmux(["list-windows", "-t", "=loop-proj"])
|
||||
self.assertEqual((done.returncode, done.stdout), (4, "list-windows -t =loop-proj\n"))
|
||||
|
||||
def test_reads_output_that_is_not_utf_8_with_each_bad_byte_replaced(self):
|
||||
with tempfile.TemporaryDirectory() as folder, self.fake_tmux(folder):
|
||||
pathlib.Path(folder, "tmux").write_text(f"#!{sys.executable}\nimport sys\nsys.stdout.buffer.write(b'caf\\xe9')\n")
|
||||
self.assertEqual(system_effects().tmux(["list-windows"]).stdout, "caf\ufffd")
|
||||
|
||||
def test_reads_a_tmux_that_cannot_start_as_exit_127(self):
|
||||
with tempfile.TemporaryDirectory() as folder, unittest.mock.patch.dict(os.environ, {"PATH": folder}):
|
||||
done = system_effects().tmux(["-V"])
|
||||
self.assertEqual((done.args, done.returncode, done.stdout), (["tmux", "-V"], 127, ""))
|
||||
self.assertIn("could not start", done.stderr)
|
||||
|
||||
def test_runs_tmux_on_the_terminal_and_returns_its_exit_code(self):
|
||||
with tempfile.TemporaryDirectory() as folder, self.fake_tmux(folder), contextlib.redirect_stdout(io.StringIO()):
|
||||
self.assertEqual(system_effects().tmux_on_terminal(["attach-session", "-t", "=loop-proj"]), 4)
|
||||
|
||||
|
||||
class PythonEffect(unittest.TestCase):
|
||||
def test_runs_a_script_in_the_given_directory(self):
|
||||
with tempfile.TemporaryDirectory() as cwd:
|
||||
|
||||
@@ -27,7 +27,7 @@ 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."""
|
||||
"""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."""
|
||||
for slot in range(slots):
|
||||
fd = os.open(folder / f"slot-{slot}", os.O_RDWR | os.O_CREAT, 0o644)
|
||||
try:
|
||||
|
||||
+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
|
||||
|
||||
@@ -72,6 +72,13 @@ class PlanStoreContract:
|
||||
self.assertEqual(self.items(store)[id_].release, release_of("0.3.0"))
|
||||
self.assertEqual(self.items(store)[id_].detail, "")
|
||||
|
||||
def test_an_edit_with_a_comment_sets_the_fields_as_one_without(self) -> None:
|
||||
store = self.new_store()
|
||||
id_ = self.filed(store, FIRST, "Why it counts.")
|
||||
self.assertEqual(store.edit(id_, {"L": "2"}, None, "A small change to one module."), Written(id_))
|
||||
item = self.items(store)[id_]
|
||||
self.assertEqual((item.scores["L"], item.detail), (2, "Why it counts."))
|
||||
|
||||
def test_finish_removes_the_item_and_keeps_the_others(self) -> None:
|
||||
store = self.new_store()
|
||||
first, second = self.filed(store, FIRST, "Why it counts."), self.filed(store, SECOND, "Later detail.")
|
||||
|
||||
@@ -12,6 +12,8 @@ class MemoryPlan:
|
||||
"""A plan held in memory, as a tracker holds one: in the order filed, unranked, with no bar. Where fails is set, every read and write fails with it as the reason."""
|
||||
rows: dict[int, dict[str, str]] = dataclasses.field(default_factory=dict)
|
||||
details: dict[int, str] = dataclasses.field(default_factory=dict)
|
||||
# Each comment an edit gave, under its item's ID, as a tracker posts them on the item's issue.
|
||||
comments: dict[int, list[str]] = dataclasses.field(default_factory=dict)
|
||||
next_id: int = 1
|
||||
label: str = "the plan in memory"
|
||||
tracked: str | None = None
|
||||
@@ -26,10 +28,13 @@ class MemoryPlan:
|
||||
def add(self, fields: dict[str, str], detail: str) -> Written | Failure:
|
||||
return self.put(self.next_id, cells(fields), detail)
|
||||
|
||||
def edit(self, id_: int, fields: dict[str, str], detail: str | None) -> Written | Failure:
|
||||
def edit(self, id_: int, fields: dict[str, str], detail: str | None, comment: str | None = None) -> Written | Failure:
|
||||
if id_ not in self.rows:
|
||||
return Failure(f"{self.label} holds no item {id_}")
|
||||
return self.put(id_, self.rows[id_] | cells(fields), self.details.get(id_, "") if detail is None else detail)
|
||||
written = self.put(id_, self.rows[id_] | cells(fields), self.details.get(id_, "") if detail is None else detail)
|
||||
if comment is not None and isinstance(written, Written):
|
||||
self.comments.setdefault(id_, []).append(comment)
|
||||
return written
|
||||
|
||||
def finish(self, id_: int) -> Written | Failure:
|
||||
if self.fails or id_ not in self.rows:
|
||||
|
||||
+244
-27
@@ -1,8 +1,8 @@
|
||||
"""A plan kept as the child issues of one Jira Cloud epic, read and filed into over Jira's REST API.
|
||||
"""A plan kept as the child issues of one Jira Cloud epic, read, filed into, edited 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.
|
||||
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 person filed holds none, and reads as an item without scores.
|
||||
|
||||
`add` files an item as a new child issue, marked with FILED_BY. edit and finish are a Failure until todo.md's items 382 and 383."""
|
||||
`add` files an item as a new child issue, marked with FILED_BY, and ranks it among the issues the loop filed, by the score the config's formula gives, as `placing` says. `finish` moves an item's issue to a done status. `edit` changes an issue the loop filed, but never its links. Of an issue a person filed it sets only the scores, with a comment that tells the team why."""
|
||||
import base64
|
||||
import dataclasses
|
||||
import pathlib
|
||||
@@ -13,10 +13,11 @@ 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
|
||||
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 release_plan import ranking
|
||||
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,16 +30,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 and filed into so far: edit and finish its issues 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.
|
||||
# The key in PROPERTY's value that marks an issue the loop filed, and its value. An edit of an issue without it, which a person filed, writes only PROPERTY and a comment.
|
||||
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"
|
||||
# What a failed edit ends with, for the same reason.
|
||||
PERHAPS_EDITED = "unless Jira refused the request, the issue may have changed: look at {key} before editing the item again"
|
||||
# The scores a caller sets, L, E, I and S; R is worked out from them.
|
||||
SET_SCORES = tuple(name for name in SHAPE.score_columns if name not in SHAPE.derived)
|
||||
# The fields of PROPERTY's value that an edit may set.
|
||||
SCORED = (*SET_SCORES, MOVES, "Exempt")
|
||||
|
||||
# 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]
|
||||
@@ -46,6 +56,11 @@ ToMarkdown = typing.Callable[[list[dict[str, typing.Any]]], list[str] | Refused
|
||||
ToAdf = typing.Callable[[str], dict[str, typing.Any] | Failure]
|
||||
|
||||
|
||||
class ReadsScoring(typing.Protocol):
|
||||
def read(self) -> ranking.Scoring | Failure:
|
||||
"""The scoring `add` scores an item by: the config's formula and bar, with the goal weights that the goals file, the decision log and the comprehension history give."""
|
||||
|
||||
|
||||
def http_json(method: str, url: str, authorization: str, body: object) -> object:
|
||||
return json_request.http_json(method, url, authorization, body, TIMEOUT, error_message)
|
||||
|
||||
@@ -84,6 +99,10 @@ class JiraPlan:
|
||||
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
|
||||
# How add scores an item: by the config's formula and bar, with the goal weights the project's records give.
|
||||
scoring: ReadsScoring = dataclasses.field(kw_only=True)
|
||||
|
||||
@property
|
||||
def label(self) -> str:
|
||||
@@ -104,12 +123,18 @@ 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:
|
||||
"""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).
|
||||
"""Files the item as a child issue, where it scores at the config's bar or above or is exempt, and ranks it as `placing` says.
|
||||
|
||||
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."""
|
||||
Jira takes the links and the rank after the issue. One it refuses leaves the issue filed, so the write counts as landed, and a note says what to do by hand."""
|
||||
filing = filing_of(fields, detail, self.epic)
|
||||
if isinstance(filing, Failure):
|
||||
return filing
|
||||
scoring = self.scoring.read()
|
||||
if isinstance(scoring, Failure):
|
||||
return Failure(f"cannot score the item to file: {scoring.reason}")
|
||||
value = filed_score(filing.item, scoring)
|
||||
if isinstance(value, Failure):
|
||||
return value
|
||||
authorization = basic_auth(self.env_file)
|
||||
if isinstance(authorization, Failure):
|
||||
return authorization
|
||||
@@ -122,21 +147,44 @@ class JiraPlan:
|
||||
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
|
||||
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)}
|
||||
# `item` reads only an open child as a blocker, so a link to any other issue would be lost on the next read.
|
||||
if missing := next((blocker for blocker in filing.blockers if blocker not in held), None):
|
||||
return Failure(f"{self.label} holds no item {number(missing)} to be blocked by")
|
||||
before = placing(answered, filing.item, value, scoring)
|
||||
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)}")
|
||||
return Written(number(key), self.linked_and_ranked(key, filing.blockers, before, authorization))
|
||||
|
||||
def linked_and_ranked(self, key: str, blockers: tuple[str, ...], before: str | None | Failure, authorization: str) -> tuple[str, ...]:
|
||||
"""Links the filed issue named key as blocked by each of blockers, and ranks it just before the issue named before; a note for each Jira refuses."""
|
||||
notes = []
|
||||
for blocker in filing.blockers:
|
||||
for blocker in 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))
|
||||
if isinstance(before, Failure):
|
||||
notes.append(f"filed {key}, but cannot rank it: {before.reason}; rank it in Jira")
|
||||
elif before is not None and (refused := self.rank_refusal(key, before, authorization)):
|
||||
notes.append(f"filed {key}, but cannot rank it before {before}: {refused}; rank it in Jira")
|
||||
return tuple(notes)
|
||||
|
||||
def rank_refusal(self, key: str, before: str, authorization: str) -> str | None:
|
||||
"""Ranks the issue named key just before the issue named before; why Jira refused, or None where it didn't. Jira answers a rank it made with no body, and one it refused with an error, or with an entry per issue that holds the errors."""
|
||||
answer = self.http("PUT", f"{self.epic.site}/rest/agile/1.0/issue/rank", authorization, {"issues": [key], "rankBeforeIssue": before})
|
||||
if isinstance(answer, Failure):
|
||||
return answer.reason
|
||||
entries = answer.get("entries") if isinstance(answer, dict) else None
|
||||
refused = [entry for entry in entries if isinstance(entry, dict) and entry.get("status") != 200] if isinstance(entries, list) else []
|
||||
return "; ".join(str(error) for entry in refused for error in entry.get("errors") or [f"Jira answered {entry.get('status')}"]) or None
|
||||
|
||||
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."""
|
||||
@@ -145,21 +193,73 @@ class JiraPlan:
|
||||
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")
|
||||
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 name 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."""
|
||||
def edit(self, id_: int, fields: dict[str, str], detail: str | None, comment: str | None = None) -> Written | Failure:
|
||||
"""Sets the fields and the detail in one request, so Jira takes all of the edit or none, and then posts comment on the issue. `revision_of` says what an edit may set.
|
||||
|
||||
A comment Jira refuses leaves the edit made, so the write counts as landed, and a note says to post the comment by hand."""
|
||||
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
|
||||
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)
|
||||
key = f"{project_of(self.epic.key)}-{id_}"
|
||||
raw = next((raw for raw in answered if isinstance(raw, dict) and raw.get("key") == key), None)
|
||||
if raw is None:
|
||||
return Failure(f"{self.label} holds no item {id_}")
|
||||
issue = issue_of(raw)
|
||||
if isinstance(issue, Failure):
|
||||
return issue
|
||||
revision = revision_of(issue, cells(fields), detail, comment)
|
||||
if isinstance(revision, Failure):
|
||||
return revision
|
||||
body = revision.body
|
||||
if detail is not None:
|
||||
description = self.to_adf(detail) if detail.strip() else None
|
||||
if isinstance(description, Failure):
|
||||
return Failure(f"cannot convert the item's detail to a Jira description: {description.reason}")
|
||||
body = body | {"fields": body.get("fields", {}) | {"description": description}}
|
||||
said = self.to_adf(comment) if comment and comment.strip() else None
|
||||
if isinstance(said, Failure):
|
||||
return Failure(f"cannot convert the comment to a Jira comment: {said.reason}")
|
||||
if revision.release is not None:
|
||||
version = self.fix_version(revision.release, authorization)
|
||||
if isinstance(version, Failure):
|
||||
return version
|
||||
body = body | {"fields": body.get("fields", {}) | {"fixVersions": [{"name": version}]}}
|
||||
url = f"{self.epic.site}/rest/api/3/issue/{key}"
|
||||
edited = self.http("PUT", url, authorization, body)
|
||||
if isinstance(edited, Failure):
|
||||
return Failure(f"cannot edit {key}: {edited.reason}; {PERHAPS_EDITED.format(key=key)}")
|
||||
if said is None:
|
||||
return Written(id_)
|
||||
posted = self.http("POST", f"{url}/comment", authorization, {"body": said})
|
||||
return Written(id_, (f"edited {key}, but cannot post the comment: {posted.reason}; post it in Jira",) if isinstance(posted, Failure) else ())
|
||||
|
||||
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)
|
||||
@@ -172,6 +272,8 @@ class Filing:
|
||||
scores: dict[str, typing.Any]
|
||||
# The key of each issue the item is blocked by.
|
||||
blockers: tuple[str, ...]
|
||||
# The item as ranking scores it, under the ID 0, since Jira numbers it once filed.
|
||||
item: Item
|
||||
|
||||
|
||||
def filing_of(fields: dict[str, str], detail: str, epic: Epic) -> Filing | Failure:
|
||||
@@ -183,15 +285,16 @@ def filing_of(fields: dict[str, str], detail: str, epic: Epic) -> Filing | Failu
|
||||
if unfit := unfit_text(summary, detail):
|
||||
return unfit
|
||||
release = named.get("Release", "")
|
||||
if parsed(release) is None:
|
||||
version = parsed(release)
|
||||
if version 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 isinstance(parsed_moves := parse_moves("to file", moves), Failure):
|
||||
return parsed_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, ""))
|
||||
@@ -202,7 +305,122 @@ def filing_of(fields: dict[str, str], detail: str, epic: Epic) -> Filing | Failu
|
||||
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))
|
||||
return Filing(issue_fields, release, value, tuple(f"{project}-{blocker}" for blocker in blockers), Item(0, version, exempt, summary, levels, parsed_moves, blockers))
|
||||
|
||||
|
||||
def filed_score(item: Item, scoring: ranking.Scoring) -> float | Failure:
|
||||
"""The item's score, or why it may not be filed: it lacks a score the formula may use, names a goal it may not, or scores under the bar without being exempt."""
|
||||
if missing := next((name for name in SET_SCORES if name not in item.scores), None):
|
||||
return Failure(f"the item to file has no {missing}: score it on {', '.join(SET_SCORES[:-1])} and {SET_SCORES[-1]}")
|
||||
value = ranking.item_score(item, scoring, "the item to file")
|
||||
if not isinstance(value, Failure) and ranking.falls_under(item, value, scoring.bar):
|
||||
return Failure(f"the item to file scores {value:.1f}, under the bar {scoring.bar:g}; don't file it, or mark it with a reason the bar doesn't apply")
|
||||
return value
|
||||
|
||||
|
||||
def placing(answered: list[object], new: Item, value: float, scoring: ranking.Scoring) -> str | None | Failure:
|
||||
"""The key of the issue to rank the new item, which scores value, just before; None where it stays last, where Jira files it. answered is the epic's open children in backlog order.
|
||||
|
||||
Only the issues the loop filed count, so the team's rank of every other issue stays as it is. The new item goes before the first of them that ranks after it as todo.md orders a release's items, blockers aside: a question first, then a security finding, as ranking.FIRST orders them, then the higher score. A tie goes after the older issue. Release doesn't count, as docs/decisions.md records."""
|
||||
place = (ranking.FIRST.get(new.exempt, len(ranking.FIRST)), -value)
|
||||
for raw in answered:
|
||||
issue = issue_of(raw)
|
||||
if isinstance(issue, Failure):
|
||||
return issue
|
||||
if not isinstance(issue.scores, dict) or issue.scores.get(FILED_BY[0]) != FILED_BY[1]:
|
||||
continue
|
||||
scored = scores(issue.key, issue.scores)
|
||||
if isinstance(scored, Failure):
|
||||
return scored
|
||||
levels, moves, exempt = scored
|
||||
if missing := next((name for name in SET_SCORES if name not in levels), None):
|
||||
return Failure(f"{issue.key} holds no {missing}")
|
||||
# Only the scores and the moves change a score.
|
||||
other = ranking.item_score(dataclasses.replace(new, scores=levels, moves=moves), scoring, issue.key)
|
||||
if isinstance(other, Failure):
|
||||
return other
|
||||
if (ranking.FIRST.get(exempt, len(ranking.FIRST)), -other) > place:
|
||||
return issue.key
|
||||
return None
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Revision:
|
||||
"""An edit checked as far as the issue and the flags allow. The description, the comment and the Fix Version's name still need the codec or a request."""
|
||||
# The body of the request that edits the issue, without its description and its Fix Version.
|
||||
body: dict[str, typing.Any]
|
||||
# The release to move the issue to; None where the edit names none.
|
||||
release: str | None
|
||||
|
||||
|
||||
def revision_of(issue: Issue, named: dict[str, str], detail: str | None, comment: str | None) -> Revision | Failure:
|
||||
"""The edit of issue that sets the cells in named, and the detail unless None, or why it cannot be made.
|
||||
|
||||
The summary, description and Fix Version of an issue a person filed are the team's, so there an edit may set only SCORED. Jira's screens don't show PROPERTY, so such an edit needs a comment, which tells the team. L, E, I and S are set together, so no issue is left partly scored. An issue the loop filed also keeps the label SECURITY in step with its Exempt. No edit changes a link."""
|
||||
held = issue.scores
|
||||
if not isinstance(held, dict):
|
||||
return Failure(f"{issue.key}'s issue property {PROPERTY} is not a JSON object")
|
||||
if BLOCKED_BY in named:
|
||||
return Failure(f"the loop doesn't change an issue's links: link {issue.key} in Jira")
|
||||
own = held.get(FILED_BY[0]) == FILED_BY[1]
|
||||
if not own and ("Item" in named or "Release" in named or detail is not None):
|
||||
return Failure(f"a person filed {issue.key}, so the loop sets only its scores: change its summary, description and Fix Version in Jira")
|
||||
if not own and not (comment and comment.strip()):
|
||||
return Failure(f"a person filed {issue.key}, and Jira doesn't show its team the scores: pass a comment saying that it is scored, and why")
|
||||
body: dict[str, typing.Any] = {}
|
||||
if "Item" in named:
|
||||
summary = plain(named["Item"]).strip()
|
||||
if not summary:
|
||||
return Failure("the item has no tagline")
|
||||
body["fields"] = {"summary": summary}
|
||||
if unfit := unfit_text(named.get("Item", ""), detail or ""):
|
||||
return unfit
|
||||
release = named.get("Release")
|
||||
if release is not None and parsed(release) is None:
|
||||
return Failure(f"the item's Release {release!r} is not a version such as 1.2.0")
|
||||
if not is_exempt(named.get("Exempt", "")):
|
||||
return Failure(f"the item's Exempt {named['Exempt']!r} is not empty or one of {', '.join(EXEMPTIONS[1:])}")
|
||||
if any(name in named for name in SCORED):
|
||||
texts = {name: str(value) for name, value in held.items()} | {name: named[name] for name in SCORED if name in named}
|
||||
scored = scores(issue.key, texts)
|
||||
if isinstance(scored, Failure):
|
||||
return scored
|
||||
if scored[0] and any(name not in scored[0] for name in SET_SCORES):
|
||||
return Failure(f"{issue.key} would hold some of {', '.join(SET_SCORES)} and not the rest: set them together")
|
||||
value = held | scored[0] | {MOVES: texts.get(MOVES, ""), "Exempt": scored[2]}
|
||||
body["properties"] = [{"key": PROPERTY, "value": value}]
|
||||
if own and (scored[2] == SECURITY) != (held.get("Exempt") == SECURITY):
|
||||
body["update"] = {"labels": [{"add" if scored[2] == SECURITY else "remove": SECURITY}]}
|
||||
return Revision(body, release)
|
||||
|
||||
|
||||
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:
|
||||
@@ -219,7 +437,7 @@ def basic_auth(env_file: pathlib.Path) -> str | Failure:
|
||||
|
||||
|
||||
def children(epic: Epic, authorization: str, http: Http) -> list[object] | Failure:
|
||||
"""The epic's open child issues in backlog order, which is the order the team ranks them in. An issue in a done status is a finished item, so it is no longer in the plan."""
|
||||
"""The epic's open child issues in backlog order, which the team ranks, apart from where add ranks an issue it files. An issue in a done status is a finished item, so it is no longer in the plan."""
|
||||
# The search answers no issues for an epic the account cannot see, as for one whose children are all done; asking for the epic itself tells them apart.
|
||||
seen = http("GET", f"{epic.site}/rest/api/3/issue/{epic.key}?fields=summary", authorization, None)
|
||||
if isinstance(seen, Failure):
|
||||
@@ -295,7 +513,6 @@ def item(issue: Issue, project: str, ids: set[int]) -> Item | Failure:
|
||||
"""The item an issue holds, without its detail. It is blocked by each of its blockers among ids, the plan's items: a blocker that is done or lies outside the epic doesn't make the item wait."""
|
||||
release = earliest_release(issue.fix_versions)
|
||||
if release is None:
|
||||
# Until a project can tie its releases to something other than semver versions, an item with no release cannot be placed in the plan.
|
||||
return Failure(f"{issue.key} names no Fix Version that is a semver version, such as 1.2.0; set one in Jira")
|
||||
scored = scores(issue.key, issue.scores)
|
||||
if isinstance(scored, Failure):
|
||||
|
||||
+41
-16
@@ -12,8 +12,8 @@ from release_plan.todo_table import BLOCKED_BY, Item, item_details, items, MOVES
|
||||
from failure import Failure
|
||||
from git_cli.git_repo import file_at, git, Git
|
||||
from record_store.stores import goals_store, store as record_store, RecordStore
|
||||
from project_config.settings import JiraScoring, ProjectConfig
|
||||
from plan_store import markdown_edits
|
||||
from project_config.settings import ProjectConfig
|
||||
from release_plan import ranking
|
||||
from release_plan.release import Release
|
||||
from text_files.file_writes import replace_file
|
||||
@@ -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` reads and files, and fails an edit or a finish until todo.md's items 382 and 383. A write that fails leaves the plan as it was, except where its Failure says a tracker may hold the item all the same, as when Jira's answer to a new issue is lost."""
|
||||
"""A project's plan. plan_store.contract holds every backend that writes to the same behaviour; `jira_epic` doesn't hold it yet: it changes no link, and its own tests stand in for Jira. 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, an edit or a finish is lost."""
|
||||
|
||||
@property
|
||||
def label(self) -> str:
|
||||
@@ -63,8 +63,10 @@ class PlanStore(typing.Protocol):
|
||||
def add(self, fields: dict[str, str], detail: str) -> Written | Failure:
|
||||
"""Files an item under an ID the backend picks. fields holds each of FIELDS the caller sets; detail may be empty."""
|
||||
|
||||
def edit(self, id_: int, fields: dict[str, str], detail: str | None) -> Written | Failure:
|
||||
"""Sets item id_'s fields to those given, and its detail unless None, leaving the rest. Moving an item sets its Release."""
|
||||
def edit(self, id_: int, fields: dict[str, str], detail: str | None, comment: str | None = None) -> Written | Failure:
|
||||
"""Sets item id_'s fields to those given, and its detail unless None, leaving the rest. Moving an item sets its Release.
|
||||
|
||||
comment tells the plan's other readers why, in the project's language. A tracker posts it on the item's issue; a backend with no place for comments drops it."""
|
||||
|
||||
def finish(self, id_: int) -> Written | Failure:
|
||||
"""Removes item id_ with its detail."""
|
||||
@@ -98,7 +100,7 @@ class FilePlan:
|
||||
filed = markdown_edits.added(texts[0], cells(fields), detail, self.label)
|
||||
return filed if isinstance(filed, Failure) else self.kept(*filed, texts)
|
||||
|
||||
def edit(self, id_: int, fields: dict[str, str], detail: str | None) -> Written | Failure:
|
||||
def edit(self, id_: int, fields: dict[str, str], detail: str | None, comment: str | None = None) -> Written | Failure:
|
||||
texts = self.texts()
|
||||
if isinstance(texts, Failure):
|
||||
return texts
|
||||
@@ -137,16 +139,36 @@ class FilePlan:
|
||||
plan = read_text(self.path, MISSING)
|
||||
if isinstance(plan, Failure):
|
||||
return plan
|
||||
goals = self.goals.read()
|
||||
if isinstance(goals, Failure):
|
||||
return goals
|
||||
if not goals:
|
||||
return Failure(f"{self.goals.label}: missing or empty; {GOALS_HINT}")
|
||||
decisions = self.decisions.read()
|
||||
if isinstance(decisions, Failure):
|
||||
return decisions
|
||||
history = self.history.read()
|
||||
return history if isinstance(history, Failure) else (plan, goals, decisions, history)
|
||||
weighing = weighing_texts(self.goals, self.decisions, self.history)
|
||||
return weighing if isinstance(weighing, Failure) else (plan, *weighing)
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class StatedScoring:
|
||||
"""The scoring of a plan in Jira: the formula and bar the project's config states, with goal weights that ranking reads from the goals file, the decision log and the comprehension history."""
|
||||
stated: JiraScoring
|
||||
goals: RecordStore
|
||||
decisions: RecordStore
|
||||
history: RecordStore
|
||||
floor: decimal.Decimal
|
||||
|
||||
def read(self) -> ranking.Scoring | Failure:
|
||||
weighing = weighing_texts(self.goals, self.decisions, self.history)
|
||||
return weighing if isinstance(weighing, Failure) else ranking.config_scoring(self.stated.formula, self.stated.bar, *weighing, self.floor)
|
||||
|
||||
|
||||
def weighing_texts(goals: RecordStore, decisions: RecordStore, history: RecordStore) -> tuple[str, str, str] | Failure:
|
||||
"""What ranking weighs the goals by: the goals file, the decision log and the comprehension history. The last two are empty when missing; a goals file that is missing or empty is a Failure."""
|
||||
goals_text = goals.read()
|
||||
if isinstance(goals_text, Failure):
|
||||
return goals_text
|
||||
if not goals_text:
|
||||
return Failure(f"{goals.label}: missing or empty; {GOALS_HINT}")
|
||||
decisions_text = decisions.read()
|
||||
if isinstance(decisions_text, Failure):
|
||||
return decisions_text
|
||||
history_text = history.read()
|
||||
return history_text if isinstance(history_text, Failure) else (goals_text, decisions_text, history_text)
|
||||
|
||||
|
||||
def store(config: ProjectConfig) -> PlanStore:
|
||||
@@ -157,7 +179,10 @@ 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)
|
||||
# load refuses a config that names an epic and no formula or bar.
|
||||
assert config.jira_scoring is not None
|
||||
scoring = StatedScoring(config.jira_scoring, goals_store(config), record_store(config, "decisions"), record_store(config, "comprehension-history"), config.readability_floor)
|
||||
return JiraPlan(config.epic, config.env_file, finish_by=config.jira_finish, scoring=scoring)
|
||||
|
||||
|
||||
def file_plan(config: ProjectConfig, path: pathlib.Path | None = None) -> FilePlan:
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import base64
|
||||
import dataclasses
|
||||
import pathlib
|
||||
import sys
|
||||
import tempfile
|
||||
@@ -7,11 +8,12 @@ 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 DEFAULT_FLOOR, 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, Written
|
||||
from release_plan import ranking
|
||||
from adf_codec.convert import Refused
|
||||
from release_plan.release import release_of
|
||||
|
||||
@@ -63,7 +65,7 @@ class JiraPlan(unittest.TestCase):
|
||||
return [text_of(document) for document in documents]
|
||||
|
||||
def store(self) -> jira_epic.JiraPlan:
|
||||
return jira_epic.JiraPlan(EPIC, self.env, self.http, self.to_markdown)
|
||||
return jira_epic.JiraPlan(EPIC, self.env, self.http, self.to_markdown, scoring=Stated())
|
||||
|
||||
def read(self, *issues: dict[str, object]) -> Plan | Failure:
|
||||
self.pages, self.calls = [{"issues": list(issues)}], []
|
||||
@@ -181,12 +183,12 @@ class JiraPlan(unittest.TestCase):
|
||||
self.assertEqual(self.converted, [[adf("One."), adf("Three."), adf("Four.")]])
|
||||
|
||||
def test_a_description_the_codec_refuses_fails_the_read_naming_the_issue(self):
|
||||
store = jira_epic.JiraPlan(EPIC, self.env, self.http, lambda documents: Refused(1, Failure("adf-codec refused")))
|
||||
store = jira_epic.JiraPlan(EPIC, self.env, self.http, lambda documents: Refused(1, Failure("adf-codec refused")), scoring=Stated())
|
||||
self.pages = [{"issues": [issue("ABC-33", description=adf("x")), issue("ABC-34"), issue("ABC-35", description=adf("y"))]}]
|
||||
self.assertEqual(store.read(), Failure("ABC-35's description: adf-codec refused"))
|
||||
|
||||
def test_a_codec_that_cannot_run_fails_the_read(self):
|
||||
store = jira_epic.JiraPlan(EPIC, self.env, self.http, lambda documents: Failure("docker is not installed"))
|
||||
store = jira_epic.JiraPlan(EPIC, self.env, self.http, lambda documents: Failure("docker is not installed"), scoring=Stated())
|
||||
self.pages = [{"issues": [issue("ABC-34", description=adf("x"))]}]
|
||||
self.assertEqual(store.read(), Failure("cannot convert the descriptions of ABC-12's children to markdown: docker is not installed"))
|
||||
|
||||
@@ -210,13 +212,6 @@ class JiraPlan(unittest.TestCase):
|
||||
self.pages = [{"issues": [issue("OTHER-5")]}]
|
||||
self.assertNotIn("s3cret", self.store().read().reason) # type: ignore[union-attr]
|
||||
|
||||
def test_edit_and_finish_fail_since_the_store_only_files(self):
|
||||
store = self.store()
|
||||
for written in (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 and filed into so far: edit and finish its issues 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))
|
||||
|
||||
@@ -227,6 +222,24 @@ 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"}
|
||||
RANK = "https://acme.atlassian.net/rest/agile/1.0/issue/rank"
|
||||
# Goal 1 weighs 1 and goal 2, a maintain goal, 0.5, so under the formula V / 2**S, FIELDS scores 9 / 2 = 4.5.
|
||||
README = "# P\n\n## Goals\n\n**Void:** code health, since a test project has no code to read.\n\n1. **Achieve:** Fast.\n2. **Maintain:** Correct.\n\n## Audience\n\nMe.\n"
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Stated:
|
||||
"""Stands in for the scoring a project's config states, with the goal weights README gives."""
|
||||
formula: str = "V / 2**S"
|
||||
bar: float = 1
|
||||
|
||||
def read(self) -> ranking.Scoring | Failure:
|
||||
return ranking.config_scoring(self.formula, self.bar, README, "", "", DEFAULT_FLOOR)
|
||||
|
||||
|
||||
def filed(key: str, moves: str = "1 by 9", s: int = 1, exempt: str = "") -> dict[str, object]:
|
||||
"""An open child the loop filed, which scores 9 / 2**s with moves "1 by 9"."""
|
||||
return issue(key, scores=PROPERTY | {"Moves": moves, "S": s, "Exempt": exempt})
|
||||
|
||||
|
||||
class Filing(unittest.TestCase):
|
||||
@@ -239,25 +252,27 @@ class Filing(unittest.TestCase):
|
||||
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"}}]
|
||||
self.ranked: object = None
|
||||
self.scoring = Stated()
|
||||
|
||||
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."""
|
||||
"""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, self.linked to a new link and self.ranked to a rank."""
|
||||
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"})
|
||||
return {SEARCH: {"issues": self.open}, ISSUES: self.created, LINKS: self.linked, VERSIONS: self.versions, RANK: self.ranked}.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)
|
||||
return jira_epic.JiraPlan(EPIC, self.env, self.http, text_of, self.to_adf, scoring=self.scoring).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, {
|
||||
self.assertEqual([call for call in self.calls if call[1] != SEARCH and "/issue/ABC-12" not in call[1]], [("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}],
|
||||
})])
|
||||
@@ -310,6 +325,7 @@ class Filing(unittest.TestCase):
|
||||
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.scoring = Stated(bar=0)
|
||||
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]
|
||||
|
||||
@@ -349,7 +365,7 @@ class Filing(unittest.TestCase):
|
||||
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.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 name a release it has"))
|
||||
self.assertEqual(self.sent(ISSUES), [])
|
||||
|
||||
def test_fix_versions_that_cannot_be_read_fail_before_anything_is_filed(self):
|
||||
@@ -374,6 +390,339 @@ class Filing(unittest.TestCase):
|
||||
self.assertIsInstance(self.add(), Failure)
|
||||
self.assertEqual(self.calls, [])
|
||||
|
||||
def test_an_item_under_the_bar_fails_before_any_request(self):
|
||||
self.assertEqual(self.add(FIELDS | {"Moves": "2 by 1", "S": "3"}), Failure("the item to file scores 0.1, under the bar 1; don't file it, or mark it with a reason the bar doesn't apply"))
|
||||
self.assertEqual(self.calls, [])
|
||||
|
||||
def test_the_bar_holds_the_score_rounded_to_one_decimal(self):
|
||||
for formula, bar, filed_ in (("0.96", 1, True), ("0.6", 0.7, False)):
|
||||
with self.subTest(formula=formula, bar=bar):
|
||||
self.scoring = Stated(formula=formula, bar=bar)
|
||||
self.assertEqual(self.add() == Written(40), filed_)
|
||||
|
||||
def test_an_exempt_item_under_the_bar_files(self):
|
||||
self.assertEqual(self.add(FIELDS | {"Moves": "", "Exempt": "owner"}), Written(40))
|
||||
|
||||
def test_an_item_that_names_a_goal_the_goals_file_lacks_fails_before_any_request(self):
|
||||
self.assertEqual(self.add(FIELDS | {"Moves": "3 by 1"}), Failure("the item to file cites goal 3, which the goals file's ## Goals does not number"))
|
||||
self.assertEqual(self.calls, [])
|
||||
|
||||
def test_an_item_without_every_score_fails_before_any_request(self):
|
||||
self.assertEqual(self.add({name: value for name, value in FIELDS.items() if name != "S"}), Failure("the item to file has no S: score it on L, E, I and S"))
|
||||
self.assertEqual(self.calls, [])
|
||||
|
||||
def test_a_formula_that_does_not_parse_fails_before_any_request(self):
|
||||
self.scoring = Stated(formula="V +")
|
||||
self.assertEqual(self.add(), Failure("cannot score the item to file: the formula 'V +' does not parse"))
|
||||
self.assertEqual(self.calls, [])
|
||||
|
||||
def test_a_formula_that_gives_the_item_no_finite_score_fails_before_any_request(self):
|
||||
self.scoring = Stated(formula="1 ** (1 / (S - S))")
|
||||
self.assertEqual(self.add(), Failure("the formula gives the item to file no finite score"))
|
||||
self.assertEqual(self.calls, [])
|
||||
|
||||
def test_ranks_the_item_just_before_the_first_issue_the_loop_filed_that_scores_lower(self):
|
||||
# ABC-30 and ABC-33 are a person's, ABC-31 a security finding, and ABC-32 scores as much as the new item.
|
||||
self.open = [issue("ABC-30"), filed("ABC-31", s=4, exempt="security"), filed("ABC-32"), issue("ABC-33", scores={"L": 1, "E": 1, "I": 1, "S": 4, "Moves": "1 by 1"}), filed("ABC-34", s=2), filed("ABC-35", s=3)]
|
||||
self.assertEqual(self.add(), Written(40))
|
||||
self.assertEqual(self.sent(RANK), [{"issues": ["ABC-40"], "rankBeforeIssue": "ABC-34"}])
|
||||
self.assertEqual([method for method, url, _ in self.calls if url == RANK], ["PUT"])
|
||||
|
||||
def test_ranks_a_security_finding_just_before_the_first_issue_the_loop_filed_that_isnt_one(self):
|
||||
self.open = [issue("ABC-30"), filed("ABC-31", exempt="security"), filed("ABC-32"), filed("ABC-33", s=4)]
|
||||
self.assertEqual(self.add(FIELDS | {"Exempt": "security", "S": "4"}), Written(40))
|
||||
self.assertEqual(self.sent(RANK), [{"issues": ["ABC-40"], "rankBeforeIssue": "ABC-32"}])
|
||||
|
||||
def test_ranks_a_question_just_before_the_first_issue_the_loop_filed_that_isnt_one(self):
|
||||
self.open = [filed("ABC-31", exempt="question"), filed("ABC-32", s=4, exempt="security")]
|
||||
self.assertEqual(self.add(FIELDS | {"Exempt": "question"}), Written(40))
|
||||
self.assertEqual(self.sent(RANK), [{"issues": ["ABC-40"], "rankBeforeIssue": "ABC-32"}])
|
||||
|
||||
def test_leaves_the_item_last_where_no_issue_the_loop_filed_scores_lower(self):
|
||||
self.open = [issue("ABC-30", scores={}), filed("ABC-31"), filed("ABC-32", s=2, exempt="security")]
|
||||
self.assertEqual(self.add(), Written(40))
|
||||
self.assertEqual(self.sent(RANK), [])
|
||||
|
||||
def test_a_rank_jira_refuses_leaves_the_item_filed_with_a_note(self):
|
||||
self.open = [filed("ABC-34", s=2)]
|
||||
refusals = (
|
||||
(Failure("PUT /rest/agile/1.0/issue/rank answered 403: Forbidden"), "PUT /rest/agile/1.0/issue/rank answered 403: Forbidden"),
|
||||
({"entries": [{"issueKey": "ABC-40", "status": 400, "errors": ["Rank is not configured"]}]}, "Rank is not configured"),
|
||||
({"entries": [{"status": 200}, {"status": 400}, {"status": 404, "errors": ["gone", "locked"]}]}, "Jira answered 400; gone; locked"),
|
||||
)
|
||||
for answer, reason in refusals:
|
||||
with self.subTest(answer=answer):
|
||||
self.ranked = answer
|
||||
self.assertEqual(self.add(), Written(40, (f"filed ABC-40, but cannot rank it before ABC-34: {reason}; rank it in Jira",)))
|
||||
|
||||
def test_an_issue_the_loop_filed_that_does_not_score_leaves_the_item_filed_unranked_with_a_note(self):
|
||||
unscored = {name: value for name, value in PROPERTY.items() if name != "S"}
|
||||
for open_, reason in (
|
||||
(filed("ABC-34", moves="3 by 1", s=2), "ABC-34 cites goal 3, which the goals file's ## Goals does not number"),
|
||||
(issue("ABC-34", scores=unscored), "ABC-34 holds no S"),
|
||||
(issue("ABC-34", scores=PROPERTY | {"L": 11}), "item ABC-34's L '11' is not a whole number from 1 to 4"),
|
||||
):
|
||||
with self.subTest(reason=reason):
|
||||
self.calls.clear()
|
||||
self.open = [open_]
|
||||
self.assertEqual(self.add(), Written(40, (f"filed ABC-40, but cannot rank it: {reason}; rank it in Jira",)))
|
||||
self.assertEqual(self.sent(RANK), [])
|
||||
|
||||
|
||||
TRANSITIONS = "https://acme.atlassian.net/rest/api/3/issue/ABC-34/transitions"
|
||||
|
||||
|
||||
COMMENT = "Scored for planning: a small change to one module."
|
||||
PERHAPS_EDITED = "unless Jira refused the request, the issue may have changed: look at ABC-34 before editing the item again"
|
||||
|
||||
|
||||
class Editing(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]] = []
|
||||
# The loop filed ABC-34. A person filed ABC-35, which nobody scored, and ABC-36, which holds scores.
|
||||
self.open: list[object] = [issue("ABC-34", scores=PROPERTY), issue("ABC-35"), issue("ABC-36", scores={"L": 3, "E": 1, "I": 1, "S": 2})]
|
||||
self.edited: object = None
|
||||
self.commented: object = {"id": "10100"}
|
||||
self.versions: object = [{"name": "0.1.0"}, {"name": "v0.2.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.edited to an edit and self.commented to a new comment."""
|
||||
self.calls.append((method, url, body))
|
||||
assert authorization == AUTHORIZATION
|
||||
if method == "PUT":
|
||||
return self.edited
|
||||
return self.commented if url.endswith("/comment") else {SEARCH: {"issues": self.open}, VERSIONS: self.versions}.get(url, {"key": "ABC-12"})
|
||||
|
||||
def to_adf(self, markdown: str) -> dict[str, object] | Failure:
|
||||
return adf(markdown)
|
||||
|
||||
def edit(self, id_: int, fields: dict[str, str], detail: str | None = None, comment: str | None = None):
|
||||
return jira_epic.JiraPlan(EPIC, self.env, self.http, text_of, self.to_adf, scoring=Stated()).edit(id_, fields, detail, comment)
|
||||
|
||||
def writes(self) -> list[tuple[str, str, object]]:
|
||||
"""Each request that changes Jira, in order."""
|
||||
return [call for call in self.calls if call[0] == "PUT" or call[1].endswith("/comment")]
|
||||
|
||||
def test_sets_the_summary_description_and_scores_of_an_issue_the_loop_filed_in_one_request(self):
|
||||
self.assertEqual(self.edit(34, {"Tagline": "**Count every run.**", "L": "2", "Moves": ""}, "Why it counts."), Written(34))
|
||||
self.assertEqual(self.writes(), [("PUT", f"{ISSUES}/ABC-34", {
|
||||
"fields": {"summary": "Count every run.", "description": adf("Why it counts.")},
|
||||
"properties": [{"key": "plan-item", "value": PROPERTY | {"L": 2, "Moves": ""}}],
|
||||
})])
|
||||
|
||||
def test_sends_only_what_the_edit_names(self):
|
||||
self.edit(34, {"Tagline": "Count every run."})
|
||||
self.edit(34, {"E": "3"})
|
||||
self.assertEqual([body for _, _, body in self.writes()], [{"fields": {"summary": "Count every run."}}, {"properties": [{"key": "plan-item", "value": PROPERTY | {"E": 3}}]}])
|
||||
|
||||
def test_an_empty_detail_removes_the_description(self):
|
||||
self.edit(34, {}, " \n")
|
||||
self.assertEqual(self.writes(), [("PUT", f"{ISSUES}/ABC-34", {"fields": {"description": None}})])
|
||||
|
||||
def test_an_edit_of_the_release_sets_the_fix_version_as_the_project_spells_it(self):
|
||||
self.assertEqual(self.edit(34, {"Release": "0.2.0"}), Written(34))
|
||||
self.assertEqual(self.writes(), [("PUT", f"{ISSUES}/ABC-34", {"fields": {"fixVersions": [{"name": "v0.2.0"}]}})])
|
||||
|
||||
def test_an_edit_of_the_release_and_the_tagline_sends_both(self):
|
||||
self.edit(34, {"Release": "0.2.0", "Tagline": "Count every run."})
|
||||
self.assertEqual(self.writes()[0][2], {"fields": {"summary": "Count every run.", "fixVersions": [{"name": "v0.2.0"}]}})
|
||||
|
||||
def test_an_empty_tagline_fails_before_any_write(self):
|
||||
self.assertEqual(self.edit(34, {"Tagline": "** **"}), Failure("the item has no tagline"))
|
||||
self.assertEqual(self.writes(), [])
|
||||
|
||||
def test_a_release_the_project_has_no_fix_version_for_fails_before_any_write(self):
|
||||
self.assertEqual(self.edit(34, {"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 name a release it has"))
|
||||
self.assertEqual(self.writes(), [])
|
||||
|
||||
def test_an_exempt_that_becomes_or_stops_being_security_adds_or_removes_the_label(self):
|
||||
self.edit(34, {"Exempt": "security"})
|
||||
self.open = [issue("ABC-34", scores=PROPERTY | {"Exempt": "security"})]
|
||||
self.edit(34, {"Exempt": "owner"})
|
||||
self.edit(34, {"Exempt": "security"})
|
||||
self.assertEqual([body.get("update") for _, _, body in self.writes()], [{"labels": [{"add": "security"}]}, {"labels": [{"remove": "security"}]}, None]) # type: ignore[attr-defined]
|
||||
|
||||
def test_scores_an_issue_a_person_filed_and_comments_why(self):
|
||||
self.assertEqual(self.edit(35, {"L": "2", "E": "2", "I": "3", "S": "3", "Moves": "1 by 4"}, None, COMMENT), Written(35))
|
||||
self.assertEqual(self.writes(), [
|
||||
("PUT", f"{ISSUES}/ABC-35", {"properties": [{"key": "plan-item", "value": {"L": 2, "E": 2, "I": 3, "S": 3, "Moves": "1 by 4", "Exempt": ""}}]}),
|
||||
("POST", f"{ISSUES}/ABC-35/comment", {"body": adf(COMMENT)}),
|
||||
])
|
||||
|
||||
def test_rescores_a_persons_issue_that_holds_scores_keeping_the_rest(self):
|
||||
self.edit(36, {"L": "2"}, None, COMMENT)
|
||||
self.assertEqual(self.writes()[0][2], {"properties": [{"key": "plan-item", "value": {"L": 2, "E": 1, "I": 1, "S": 2, "Moves": "", "Exempt": ""}}]})
|
||||
|
||||
def test_a_persons_issue_is_never_labelled(self):
|
||||
self.edit(36, {"Exempt": "security"}, None, COMMENT)
|
||||
self.assertNotIn("update", self.writes()[0][2]) # type: ignore[operator]
|
||||
|
||||
def test_scoring_a_persons_issue_without_a_comment_fails_before_any_write(self):
|
||||
for comment in (None, "", " \n"):
|
||||
with self.subTest(comment=comment):
|
||||
self.assertEqual(self.edit(35, {"L": "2"}, None, comment), Failure("a person filed ABC-35, and Jira doesn't show its team the scores: pass a comment saying that it is scored, and why"))
|
||||
self.assertEqual(self.writes(), [])
|
||||
|
||||
def test_what_a_person_wrote_or_planned_is_never_edited(self):
|
||||
for fields, detail in (({"Tagline": "Count every run."}, None), ({}, "Why."), ({}, ""), ({"Release": "0.2.0"}, None), ({"Tagline": "Count.", "Release": "0.2.0", "L": "1"}, "")):
|
||||
with self.subTest(fields=fields, detail=detail):
|
||||
self.assertEqual(self.edit(36, fields, detail, COMMENT), Failure("a person filed ABC-36, so the loop sets only its scores: change its summary, description and Fix Version in Jira"))
|
||||
self.assertEqual(self.writes(), [])
|
||||
|
||||
def test_scoring_an_unscored_issue_in_part_fails_before_any_write(self):
|
||||
self.assertEqual(self.edit(35, {"L": "2", "E": "2"}, None, COMMENT), Failure("ABC-35 would hold some of L, E, I, S and not the rest: set them together"))
|
||||
self.assertEqual(self.edit(35, {"Exempt": "question"}, None, COMMENT), Written(35))
|
||||
self.assertEqual(len(self.writes()), 2)
|
||||
|
||||
def test_a_comment_on_an_edit_of_the_loops_own_issue_is_posted_too(self):
|
||||
self.edit(34, {"L": "2"}, None, COMMENT)
|
||||
self.assertEqual(self.writes()[1], ("POST", f"{ISSUES}/ABC-34/comment", {"body": adf(COMMENT)}))
|
||||
|
||||
def test_a_comment_jira_refuses_leaves_the_edit_made_with_a_note(self):
|
||||
self.commented = Failure("HTTP 403")
|
||||
self.assertEqual(self.edit(36, {"L": "2"}, None, COMMENT), Written(36, ("edited ABC-36, but cannot post the comment: HTTP 403; post it in Jira",)))
|
||||
|
||||
def test_an_edit_of_the_blockers_fails_since_the_store_changes_no_link(self):
|
||||
self.assertEqual(self.edit(34, {"Blocked by": "35"}), Failure("the loop doesn't change an issue's links: link ABC-34 in Jira"))
|
||||
self.assertEqual(self.writes(), [])
|
||||
|
||||
def test_an_issue_that_is_no_open_child_of_the_epic_is_not_edited(self):
|
||||
self.assertEqual(self.edit(40, {"L": "2"}), Failure("jira:https://acme.atlassian.net/browse/ABC-12 holds no item 40"))
|
||||
self.assertEqual(self.writes(), [])
|
||||
|
||||
def test_each_field_out_of_format_fails_before_any_write_saying_how(self):
|
||||
for fields, detail, reason in (
|
||||
({"L": "9"}, None, "item ABC-34's L '9' is not a whole number from 1 to 4"),
|
||||
({"Moves": "much"}, None, "item ABC-34's Moves 'much' is not"),
|
||||
({"Exempt": "tired"}, None, f"the item's Exempt 'tired' is not empty or one of {', '.join(EXEMPTIONS[1:])}"),
|
||||
({"Release": "soon"}, None, "the item's Release 'soon' is not a version such as 1.2.0"),
|
||||
({"Tagline": " "}, None, "the item has no tagline"),
|
||||
({"Tagline": "Count\nruns."}, None, "the tagline holds a line break; keep it on one line"),
|
||||
({}, "## Why", "the detail holds a ## or ### heading"),
|
||||
):
|
||||
with self.subTest(fields=fields, detail=detail):
|
||||
failed = self.edit(34, fields, detail)
|
||||
self.assertIsInstance(failed, Failure)
|
||||
self.assertIn(reason, failed.reason)
|
||||
self.assertEqual(self.writes(), [])
|
||||
|
||||
def test_a_detail_or_a_comment_that_does_not_convert_fails_before_any_write(self):
|
||||
self.to_adf = lambda markdown: Failure("the codec is down") # type: ignore[method-assign]
|
||||
self.assertEqual(self.edit(34, {}, "Why."), Failure("cannot convert the item's detail to a Jira description: the codec is down"))
|
||||
self.assertEqual(self.edit(34, {"L": "2"}, None, COMMENT), Failure("cannot convert the comment to a Jira comment: the codec is down"))
|
||||
self.assertEqual(self.writes(), [])
|
||||
|
||||
def test_an_edit_jira_refuses_fails_with_jiras_reason_and_posts_no_comment(self):
|
||||
self.edited = Failure("HTTP 400: Summary is too long")
|
||||
self.assertEqual(self.edit(34, {"L": "2"}, None, COMMENT), Failure(f"cannot edit ABC-34: HTTP 400: Summary is too long; {PERHAPS_EDITED}"))
|
||||
self.assertEqual(len(self.writes()), 1)
|
||||
|
||||
def test_an_issue_in_another_shape_or_a_search_that_fails_fails_the_edit(self):
|
||||
self.open = [{"key": "ABC-34", "fields": {}}]
|
||||
self.assertIn("ABC-34 is not in the shape", self.edit(34, {"L": "2"}).reason)
|
||||
self.open = [issue("ABC-34", scores=["odd"])] # type: ignore[arg-type]
|
||||
self.assertEqual(self.edit(34, {"L": "2"}), Failure("ABC-34's issue property plan-item is not a JSON object"))
|
||||
self.assertEqual(self.writes(), [])
|
||||
|
||||
def test_a_missing_env_file_fails_before_any_request(self):
|
||||
self.env.unlink()
|
||||
self.assertIsInstance(self.edit(34, {"L": "2"}), Failure)
|
||||
self.assertEqual(self.calls, [])
|
||||
|
||||
def test_what_it_edits_reads_back_as_the_item(self):
|
||||
self.edit(34, {"Tagline": "Count every run.", "S": "4"}, "Why it counts.")
|
||||
body = self.writes()[0][2]
|
||||
held = issue("ABC-34", summary=body["fields"]["summary"], scores=body["properties"][0]["value"], description=body["fields"]["description"]) # type: ignore[index]
|
||||
self.open = [held]
|
||||
plan = jira_epic.JiraPlan(EPIC, self.env, self.http, lambda documents: [text_of(document) for document in documents], scoring=Stated()).read()
|
||||
assert isinstance(plan, Plan), plan
|
||||
self.assertEqual((plan.items[0].tagline, plan.items[0].scores["S"], plan.items[0].scores["L"], plan.items[0].detail), ("**Count every run.**", 4, 1, "Why it counts."))
|
||||
|
||||
|
||||
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, scoring=Stated()).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):
|
||||
|
||||
@@ -8,9 +8,9 @@ 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, JiraScoring, ProjectConfig, SETTINGS
|
||||
from failure import Failure
|
||||
from record_store.stores import FileStore
|
||||
from record_store.stores import FileStore, goals_store, store as record_store
|
||||
from plan_store.contract import FIRST, MOVES, PlanStoreContract, SECOND
|
||||
from plan_store.jira_epic import JiraPlan
|
||||
from plan_store.fakes import MemoryPlan
|
||||
@@ -207,8 +207,39 @@ class Store(unittest.TestCase):
|
||||
|
||||
def test_an_epic_picks_jira_with_the_env_files_credentials(self):
|
||||
epic = Epic("https://acme.atlassian.net", "ABC-12")
|
||||
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))
|
||||
picked = stores.store(self.config(epic=epic, env_file=pathlib.Path("/secrets/acme.env"), jira_scoring=JiraScoring("V", 1)))
|
||||
self.assertEqual(picked, JiraPlan(epic, pathlib.Path("/secrets/acme.env"), picked.http, scoring=picked.scoring))
|
||||
|
||||
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, jira_scoring=JiraScoring("V", 1)))
|
||||
self.assertEqual(picked.finish_by, finish)
|
||||
|
||||
def test_an_epic_scores_by_the_configs_formula_and_bar_and_the_projects_records(self):
|
||||
config = self.config(epic=Epic("https://acme.atlassian.net", "ABC-12"), env_file=pathlib.Path("/secrets/acme.env"), jira_scoring=JiraScoring("V / 2**S", 1.5), readability_floor=decimal.Decimal("6.5"))
|
||||
picked = stores.store(config)
|
||||
self.assertEqual(picked.scoring, stores.StatedScoring(JiraScoring("V / 2**S", 1.5), goals_store(config), record_store(config, "decisions"), record_store(config, "comprehension-history"), decimal.Decimal("6.5")))
|
||||
|
||||
|
||||
class StatedScoring(unittest.TestCase):
|
||||
def test_weighs_the_goals_the_goals_file_holds(self):
|
||||
scoring = stores.StatedScoring(JiraScoring("V / 2**S", 1.5), MemoryStore(README), MemoryStore(), MemoryStore(), DEFAULT_FLOOR).read()
|
||||
assert not isinstance(scoring, Failure), scoring
|
||||
self.assertEqual((scoring.bar, list(scoring.goals)), (1.5, ["1", "2", "2.1"]))
|
||||
|
||||
def test_weighs_code_health_by_the_history_and_the_floor_it_is_given(self):
|
||||
for floor, under in ((DEFAULT_FLOOR, True), (decimal.Decimal("6.0"), False)):
|
||||
with self.subTest(floor=floor):
|
||||
scoring = stores.StatedScoring(JiraScoring("V", 1), MemoryStore("## Goals\n\n1. **Achieve:** A.\n"), MemoryStore(), MemoryStore(SCORED.format(overall="6.99")), floor).read()
|
||||
assert not isinstance(scoring, Failure), scoring
|
||||
self.assertEqual(scoring.weights["code health"] > scoring.weights["1"] * 2, under)
|
||||
|
||||
def test_a_goals_file_that_is_empty_or_cannot_be_read_fails(self):
|
||||
for goals, reason in ((MemoryStore(), "the record in memory: missing or empty"), (MemoryStore(fails="Jira answered 403"), "Jira answered 403")):
|
||||
with self.subTest(reason=reason):
|
||||
read = stores.StatedScoring(JiraScoring("V", 1), goals, MemoryStore(), MemoryStore(), DEFAULT_FLOOR).read()
|
||||
assert isinstance(read, Failure), read
|
||||
self.assertTrue(read.reason.startswith(reason), read.reason)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
+52
-10
@@ -20,25 +20,57 @@ 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.
|
||||
|
||||
Such a config must also set two settings. `jira-score-formula` is the formula that scores an item.
|
||||
`jira-score-bar` is the lowest score at which `todo-item add` files an item that isn't exempt, as a
|
||||
bare number. They hold what a todo.md states as `Score` and `Bar`, which `rank_todo.py --help` describes:
|
||||
|
||||
jira-score-formula = "100 * V / (2**S + 8)"
|
||||
jira-score-bar = 1
|
||||
|
||||
`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;
|
||||
@@ -59,8 +91,12 @@ aims for. While the panel's overall score is under it, code health weighs 4 time
|
||||
ranking, and a scoring run with a mean under it asks for a floor item. A legacy project, whose code
|
||||
scores low, may lower it. Left out, it is 7.0.
|
||||
|
||||
`project-config tooling-on-host` and `project-config readability-floor` print their values; the full
|
||||
listing shows each only where the config changes it from what it is when left out.
|
||||
`parallel-chunks` is an optional setting, a whole number of 1 or more: the most chunks of the project
|
||||
loop-claude runs at once, each in its own tmux window. Left out, it is 1.
|
||||
|
||||
`project-config tooling-on-host`, `project-config readability-floor` and `project-config parallel-chunks`
|
||||
print their values; the full listing shows each only where the config changes it from what it is when
|
||||
left out.
|
||||
|
||||
Four optional settings say how the project writes, for a project whose owners don't write as
|
||||
~/.claude/CLAUDE.md does:
|
||||
@@ -95,13 +131,16 @@ 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, names a Jira `plan` and leaves out `jira-score-formula` or `jira-score-bar`, sets
|
||||
one of those two without a `plan` in Jira, sets the formula to one that doesn't parse or the bar to anything
|
||||
but a number, sets `readability-floor` to anything but a number
|
||||
from 1 to 10, or sets `parallel-chunks` to anything but a whole number of 1 or more, 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, JIRA_SCORE_BAR, JIRA_SCORE_FORMULA, load, NOTIFIER, OPTIONAL, PARALLEL_CHUNKS, 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
|
||||
@@ -125,15 +164,18 @@ def main(argv: list[str]) -> int:
|
||||
if argv == [READABILITY_FLOOR]:
|
||||
print(config.readability_floor)
|
||||
return 0
|
||||
if argv == [PARALLEL_CHUNKS]:
|
||||
print(config.parallel_chunks)
|
||||
return 0
|
||||
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_SCORE_FORMULA: config.jira_scoring.formula, JIRA_SCORE_BAR: f"{config.jira_scoring.bar:g}"} if config.jira_scoring 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
|
||||
defaults = ProjectConfig(config.key, config.folder, config.top, {}).texts
|
||||
listed = [f"{name}: {path}" for name, path in paths.items()] + [f"{name}: true" for name, on in switches.items() if on] + ([f"{READABILITY_FLOOR}: {config.readability_floor}"] if config.readability_floor != DEFAULT_FLOOR else []) + [f"{name}: {text}" for name, text in config.texts.items() if text != defaults[name]]
|
||||
listed = [f"{name}: {path}" for name, path in paths.items()] + [f"{name}: true" for name, on in switches.items() if on] + ([f"{READABILITY_FLOOR}: {config.readability_floor}"] if config.readability_floor != DEFAULT_FLOOR else []) + ([f"{PARALLEL_CHUNKS}: {config.parallel_chunks}"] if config.parallel_chunks != 1 else []) + [f"{name}: {text}" for name, text in config.texts.items() if text != defaults[name]]
|
||||
print(paths[argv[0]] if argv else "\n".join(listed))
|
||||
return 0
|
||||
|
||||
|
||||
+107
-15
@@ -10,12 +10,15 @@ import tomllib
|
||||
import typing
|
||||
|
||||
from failure import Failure
|
||||
from release_plan.formula import parse_formula
|
||||
from release_plan.todo_table import SHAPE
|
||||
from project_config import templates
|
||||
from release_plan.ranking import variables
|
||||
|
||||
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.
|
||||
@@ -32,6 +35,8 @@ TOOLING_ON_HOST = "tooling-on-host"
|
||||
READABILITY_FLOOR = "readability-floor"
|
||||
# The floor where the config leaves it out, which every dimension and the overall should reach; docs/decisions.md → "comprehension floor" says it doesn't block anything.
|
||||
DEFAULT_FLOOR = decimal.Decimal("7.0")
|
||||
# The most chunks of the project loop-claude runs at once, each in its own tmux window; 1 where left out. Three readers seated as the README's audience picked the spelling 2-1 over concurrent-chunks.
|
||||
PARALLEL_CHUNKS = "parallel-chunks"
|
||||
# The optional text settings. `language` is the language the project's prose is written in, by its English name. The others are templates, as `templates` says.
|
||||
LANGUAGE = "language"
|
||||
COMMIT_TITLE = "commit-title"
|
||||
@@ -39,21 +44,30 @@ 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)
|
||||
# Two settings, needed where `plan` names a Jira epic and allowed only there: what a todo.md states under ## Scoring.
|
||||
JIRA_SCORE_FORMULA = "jira-score-formula"
|
||||
JIRA_SCORE_BAR = "jira-score-bar"
|
||||
JIRA_SCORE = (JIRA_SCORE_FORMULA, JIRA_SCORE_BAR)
|
||||
OPTIONAL = (BRANCH, COMMIT_TITLE, ENV_FILE, JIRA_FINISH_STATUS, JIRA_FINISH_TRANSITION, JIRA_SCORE_BAR, JIRA_SCORE_FORMULA, LANGUAGE, NOTIFIER, PARALLEL_CHUNKS, 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 +80,36 @@ 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 JiraScoring:
|
||||
"""How a plan in Jira scores an item: by formula, such as `100 * V / (2**S + 8)`, with bar the lowest score at which one is filed."""
|
||||
formula: str
|
||||
bar: float
|
||||
|
||||
|
||||
@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
|
||||
@@ -78,6 +119,7 @@ class ProjectConfig:
|
||||
wait_for_approval: bool = False
|
||||
tooling_on_host: bool = False
|
||||
readability_floor: decimal.Decimal = DEFAULT_FLOOR
|
||||
parallel_chunks: int = 1
|
||||
language: str = "English"
|
||||
commit_title: str = templates.TITLE
|
||||
pull_request_title: str = templates.TITLE
|
||||
@@ -88,6 +130,12 @@ 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 config's `jira-score-formula` and `jira-score-bar`, which it sets where `plan` names an epic.
|
||||
jira_scoring: JiraScoring | 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 +149,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,33 +190,71 @@ 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
|
||||
parallel = values.get(PARALLEL_CHUNKS, 1)
|
||||
finish = [name for setting in JIRA_FINISH if (name := name_of(values.get(setting)))]
|
||||
formula, bar = values.get(JIRA_SCORE_FORMULA), values.get(JIRA_SCORE_BAR)
|
||||
scoring = JiraScoring(formula, bar_value) if isinstance(formula, str) and (bar_value := bar_of(bar)) is not None else None
|
||||
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"`plan` names a Jira epic, so `{name}` must be set, as `project-config --help` shows" for name in JIRA_SCORE if epics["plan"] and name not in values),
|
||||
*(f"`{name}` is set, so `plan` must name a Jira epic" for name in JIRA_SCORE if name in values and not epics["plan"]),
|
||||
*([f"`{JIRA_SCORE_FORMULA}` is {formula!r}: {fault}"] if JIRA_SCORE_FORMULA in values and (fault := formula_fault(formula)) else []),
|
||||
*([f"`{JIRA_SCORE_BAR}` is {bar!r}, not a bare number, such as `{JIRA_SCORE_BAR} = 1`"] if JIRA_SCORE_BAR in values and bar_of(bar) is None else []),
|
||||
*(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"`{PARALLEL_CHUNKS}` is {parallel!r}, not a whole number of 1 or more, such as `{PARALLEL_CHUNKS} = 2`"] if type(parallel) is not int or parallel < 1 else []),
|
||||
*(f"`{name}` is {values[name]!r}, {fault}" for name, check in checks.items() if name in values and (fault := check(values[name]))),
|
||||
]
|
||||
if faults:
|
||||
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.
|
||||
# faults names a floor or a `parallel-chunks` value the config misspells, and a formula or bar a plan in Jira lacks or 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)
|
||||
assert isinstance(parallel, int)
|
||||
assert scoring is not None or not epics["plan"]
|
||||
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, parallel, **{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, jira_scoring=scoring, pages=pages)
|
||||
|
||||
|
||||
def formula_fault(value: object) -> str | None:
|
||||
"""Why value is no formula that may score an item, as todo.md's `Score` line states one; None where it is one."""
|
||||
if not isinstance(value, str):
|
||||
return "not a formula, such as \"100 * V / (2**S + 8)\""
|
||||
parsed = parse_formula(value, variables(SHAPE))
|
||||
return parsed.reason if isinstance(parsed, Failure) else None
|
||||
|
||||
|
||||
def bar_of(value: object) -> float | None:
|
||||
"""The bar value spells, an integer or a float; None where it spells none, as for a boolean or TOML's nan or inf, as floor_of says."""
|
||||
if isinstance(value, bool) or not isinstance(value, int | float) or (isinstance(value, float) and not math.isfinite(value)):
|
||||
return None
|
||||
return float(value)
|
||||
|
||||
|
||||
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 +263,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, JiraScoring, 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,13 @@ 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'
|
||||
JIRA_SCORING = 'jira-score-formula = "100 * V / (2**S + 8)"\njira-score-bar = 1\n'
|
||||
JIRA_CLIENT = CLIENT.replace("folder:todo.md", JIRA_PLAN) + 'env-file = "~/acme.env"\n' + JIRA_SCORING
|
||||
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 +88,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 +157,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 +242,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 +301,60 @@ 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_jira_plan_holds_the_formula_and_bar_it_scores_by(self) -> None:
|
||||
self.write("acme", JIRA_CLIENT.replace("jira-score-bar = 1", "jira-score-bar = 0.5"))
|
||||
named = load(self.checkout, self.checkout, self.home)
|
||||
assert isinstance(named, ProjectConfig), named
|
||||
self.assertEqual(named.jira_scoring, JiraScoring("100 * V / (2**S + 8)", 0.5))
|
||||
|
||||
def test_a_plan_in_a_file_holds_no_formula_or_bar_of_the_configs(self) -> None:
|
||||
self.write("acme", CLIENT)
|
||||
named = load(self.checkout, self.checkout, self.home)
|
||||
assert isinstance(named, ProjectConfig), named
|
||||
self.assertIsNone(named.jira_scoring)
|
||||
|
||||
def test_a_jira_plan_without_a_formula_or_a_bar_fails_naming_each(self) -> None:
|
||||
self.write("acme", JIRA_CLIENT.replace(JIRA_SCORING, ""))
|
||||
self.assertIn("`plan` names a Jira epic, so `jira-score-formula` must be set, as `project-config --help` shows; `plan` names a Jira epic, so `jira-score-bar` must be set", self.failure())
|
||||
|
||||
def test_a_scoring_setting_misspelt_or_beside_a_plan_in_a_file_fails_naming_it(self) -> None:
|
||||
config = self.write("acme", JIRA_CLIENT) / "config.toml"
|
||||
for formula, bar in (('" "', "true"), ("3", '"1"'), ('"V"', "nan")):
|
||||
with self.subTest(formula=formula, bar=bar):
|
||||
config.write_text(JIRA_CLIENT.replace(JIRA_SCORING, f"jira-score-formula = {formula}\njira-score-bar = {bar}\n"))
|
||||
reason = self.failure()
|
||||
self.assertIn("jira-score-bar` is", reason)
|
||||
self.assertEqual("jira-score-formula` is" in reason, formula != '"V"')
|
||||
config.write_text(CLIENT + JIRA_SCORING)
|
||||
self.assertIn("`jira-score-formula` is set, so `plan` must name a Jira epic; `jira-score-bar` is set, so `plan` must name a Jira epic", self.failure())
|
||||
|
||||
def test_a_formula_that_doesnt_parse_fails_naming_the_setting_and_why(self) -> None:
|
||||
config = self.write("acme", JIRA_CLIENT) / "config.toml"
|
||||
for formula, why in (("V +", "the formula 'V +' does not parse"), ("X", "the formula 'X' may hold only numbers, E, I, L, R, S, V, + - * / ** and parentheses")):
|
||||
with self.subTest(formula=formula):
|
||||
config.write_text(JIRA_CLIENT.replace('"100 * V / (2**S + 8)"', f'"{formula}"'))
|
||||
self.assertIn(f"`jira-score-formula` is '{formula}': {why}", 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 +397,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")
|
||||
@@ -352,6 +462,28 @@ class LoadTest(ConfigCase):
|
||||
self.assertIn("`readability-floor` is ", found.reason)
|
||||
self.assertIn(", not a number from 1 to 10; write a bare number, such as `readability-floor = 7.0`", found.reason)
|
||||
|
||||
def test_parallel_chunks_is_an_optional_whole_number_from_1_that_is_1_where_left_out(self) -> None:
|
||||
folder = self.write("acme", CLIENT)
|
||||
left_out = load(self.checkout, self.checkout, self.home)
|
||||
assert isinstance(left_out, ProjectConfig), left_out
|
||||
self.assertEqual(left_out.parallel_chunks, 1)
|
||||
for spelled in (1, 3, 12):
|
||||
with self.subTest(spelled):
|
||||
(folder / "config.toml").write_text(CLIENT + f"parallel-chunks = {spelled}\n")
|
||||
found = load(self.checkout, self.checkout, self.home)
|
||||
assert isinstance(found, ProjectConfig), found
|
||||
self.assertEqual(found.parallel_chunks, spelled)
|
||||
|
||||
def test_parallel_chunks_that_is_no_whole_number_from_1_fails_naming_it(self) -> None:
|
||||
folder = self.write("acme", CLIENT)
|
||||
for spelled in ('"2"', "0", "-1", "2.0", "true", "inf"):
|
||||
with self.subTest(spelled):
|
||||
(folder / "config.toml").write_text(CLIENT + f"parallel-chunks = {spelled}\n")
|
||||
found = load(self.checkout, self.checkout, self.home)
|
||||
assert isinstance(found, Failure), found
|
||||
self.assertIn("`parallel-chunks` is ", found.reason)
|
||||
self.assertIn(", not a whole number of 1 or more, such as `parallel-chunks = 2`", found.reason)
|
||||
|
||||
def test_the_language_and_the_templates_are_optional_and_default_to_english_bare_summaries_and_item_branches(self) -> None:
|
||||
folder = self.write("acme", CLIENT)
|
||||
left_out = load(self.checkout, self.checkout, self.home)
|
||||
@@ -387,7 +519,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, jira-score-bar, jira-score-formula, language, notifier, parallel-chunks, 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 +638,22 @@ 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_the_formula_and_bar_a_jira_plan_scores_by(self) -> None:
|
||||
self.write("acme", JIRA_CLIENT.replace("jira-score-bar = 1", "jira-score-bar = 0.5"))
|
||||
self.assertEqual((self.run_tool("jira-score-formula").stdout, self.run_tool("jira-score-bar").stdout), ("100 * V / (2**S + 8)\n", "0.5\n"))
|
||||
self.assertIn("jira-score-formula: 100 * V / (2**S + 8)\njira-score-bar: 0.5\n", self.run_tool().stdout)
|
||||
|
||||
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")
|
||||
@@ -526,6 +674,14 @@ class ToolTest(ConfigCase):
|
||||
self.assertEqual((self.run_tool("tooling-on-host").stdout, self.run_tool("readability-floor").stdout), ("true\n", "5\n"))
|
||||
self.assertEqual(self.run_tool().stdout.splitlines()[-2:], ["tooling-on-host: true", "readability-floor: 5"])
|
||||
|
||||
def test_prints_parallel_chunks_and_lists_it_only_where_the_config_changes_it(self) -> None:
|
||||
folder = self.write("acme", CLIENT)
|
||||
self.assertEqual(self.run_tool("parallel-chunks").stdout, "1\n")
|
||||
self.assertNotIn("parallel-chunks", self.run_tool().stdout)
|
||||
(folder / "config.toml").write_text(CLIENT + "parallel-chunks = 3\n")
|
||||
self.assertEqual(self.run_tool("parallel-chunks").stdout, "3\n")
|
||||
self.assertIn("parallel-chunks: 3", self.run_tool().stdout.splitlines())
|
||||
|
||||
def test_prints_the_language_and_each_template_and_lists_them_only_where_the_config_sets_them(self) -> None:
|
||||
folder = self.write("acme", CLIENT)
|
||||
defaults = {"language": "English", "commit-title": "{summary}", "pull-request-title": "{summary}", "branch": "item-{id}"}
|
||||
|
||||
@@ -10,26 +10,36 @@ save refuses them: edit the epic in Jira.
|
||||
|
||||
open prints the path of a file holding the record's text, and nothing else. Read and edit that
|
||||
file. Where the record is kept as a file, the path is that file. Where it is kept elsewhere, the
|
||||
path is a copy under ~/.local/state/project-record/<key>/, written afresh with the record as it
|
||||
stands, so open it again before each edit. A record that doesn't exist yet has no file at the path:
|
||||
path is a copy under ~/.local/state/project-record/<key>/<worktree>/, a folder named for the
|
||||
worktree that ran open, so two worktrees of one project don't share a copy. The copy is written
|
||||
afresh with the record as it stands, so open it again before each edit. open also removes the
|
||||
folders of worktrees git no longer lists. A record that doesn't exist yet has no file at the path:
|
||||
create it there.
|
||||
|
||||
save stores the file's text in the record, and prints one line saying so. Where the record is kept
|
||||
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 hashlib
|
||||
import pathlib
|
||||
import shutil
|
||||
import sys
|
||||
|
||||
from failure import Failure
|
||||
from record_store.stores import FileStore, goals_store, local_file, RECORDS, RecordStore, store, stored
|
||||
from git_cli.git_repo import git, Git
|
||||
from project_config.main import located
|
||||
from project_config.settings import ProjectConfig
|
||||
|
||||
# Not git's verbs, such as checkout and commit: those read as acting on the repo.
|
||||
COMMANDS = ("open", "save")
|
||||
# Where the copy of a record kept outside files goes, under the user's home, in a folder per project.
|
||||
# Where the copy of a record kept outside files goes, under the user's home, in a folder per project and worktree.
|
||||
COPIES = ".local/state/project-record"
|
||||
# The goals file opens like a record, though it is a setting of its own.
|
||||
GOALS = "goals-and-audience"
|
||||
@@ -44,7 +54,7 @@ def main(argv: list[str]) -> int:
|
||||
return 2
|
||||
home = pathlib.Path.home()
|
||||
config = located(None, home)
|
||||
done = config if isinstance(config, Failure) else act(argv[0], 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 performed(config, argv[0], argv[1], home)
|
||||
if isinstance(done, Failure):
|
||||
print(f"project-record: {done.reason}", file=sys.stderr)
|
||||
return 1
|
||||
@@ -52,6 +62,36 @@ def main(argv: list[str]) -> int:
|
||||
return 0
|
||||
|
||||
|
||||
def performed(config: ProjectConfig, command: str, name: str, home: pathlib.Path, run: Git = git) -> str | Failure:
|
||||
"""What command, one of COMMANDS, prints for the record called name. An open also prunes the copies of removed worktrees."""
|
||||
if command == "open":
|
||||
pruned(config, home, run)
|
||||
return act(command, *opened(config, name, home))
|
||||
|
||||
|
||||
def opened(config: ProjectConfig, name: str, home: pathlib.Path) -> tuple[RecordStore, pathlib.Path]:
|
||||
"""The store of the record called name, and the copy it gets where it isn't kept as a file. A store that keeps the version it read, for a later save, keeps it beside the copy."""
|
||||
copy = home / COPIES / config.key / worktree_folder(config.top) / f"{name}.md"
|
||||
return (goals_store(config) if name == GOALS else store(config, name, copy.with_suffix(".version"))), copy
|
||||
|
||||
|
||||
def worktree_folder(top: pathlib.Path) -> str:
|
||||
"""The name of the folder that holds the copies of the worktree at top: the worktree's own name, for a reader, and a hash of its path, since two worktrees in different folders may share a name."""
|
||||
return f"{top.name}-{hashlib.sha256(str(top).encode()).hexdigest()[:8]}"
|
||||
|
||||
|
||||
def pruned(config: ProjectConfig, home: pathlib.Path, run: Git = git) -> None:
|
||||
"""Remove the copies of the worktrees git no longer lists, so the folders don't pile up one per chunk. Best effort: a folder that stays only takes disk, and where git can't list the worktrees nothing is removed."""
|
||||
listed = run("worktree", "list", "--porcelain")
|
||||
folders = home / COPIES / config.key
|
||||
if isinstance(listed, Failure) or not folders.is_dir():
|
||||
return
|
||||
worktrees = [config.top, *(pathlib.Path(line.removeprefix("worktree ")) for line in listed.splitlines() if line.startswith("worktree "))]
|
||||
kept = {worktree_folder(worktree) for worktree in worktrees}
|
||||
for stale in (folder for folder in folders.iterdir() if folder.is_dir() and folder.name not in kept):
|
||||
shutil.rmtree(stale, ignore_errors=True)
|
||||
|
||||
|
||||
def act(command: str, record: RecordStore, copy: pathlib.Path) -> str | Failure:
|
||||
"""What command, one of COMMANDS, prints for record. copy is where a record kept outside files gets its file."""
|
||||
if command == "open":
|
||||
|
||||
@@ -8,13 +8,103 @@ 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"
|
||||
|
||||
|
||||
COPIES = pathlib.Path("/home/me/.local/state/project-record/acme")
|
||||
|
||||
|
||||
def worktree_config(top: str, **kept: Page) -> ProjectConfig:
|
||||
return ProjectConfig("acme", pathlib.Path("/home/me/.claude-projects/acme"), pathlib.Path(top), {"goals-and-audience": pathlib.Path(top, "README.md")}, pathlib.Path("/home/me/acme.env"), pages=kept)
|
||||
|
||||
|
||||
class Opened(unittest.TestCase):
|
||||
def test_a_record_on_a_confluence_page_keeps_the_version_it_read_beside_its_copy(self):
|
||||
page = Page("https://acme.atlassian.net", "2293761", "confluence:https://acme.atlassian.net/wiki/spaces/ENG/pages/2293761")
|
||||
record, copy = main.opened(worktree_config("/code/acme", decisions=page), "decisions", pathlib.Path("/home/me"))
|
||||
self.assertEqual((copy.parent.parent, copy.name), (COPIES, "decisions.md"))
|
||||
self.assertRegex(copy.parent.name, r"^acme-[0-9a-f]{8}$")
|
||||
assert isinstance(record, ConfluencePage), record
|
||||
self.assertEqual(record.kept, copy.with_suffix(".version"))
|
||||
|
||||
def test_the_goals_file_opens_through_the_goals_store(self):
|
||||
record, copy = main.opened(worktree_config("/code/acme"), "goals-and-audience", pathlib.Path("/home/me"))
|
||||
self.assertEqual((record.label, copy.parent.parent, copy.name), ("/code/acme/README.md", COPIES, "goals-and-audience.md"))
|
||||
|
||||
def test_two_worktrees_of_one_project_get_copies_that_differ(self):
|
||||
home = pathlib.Path("/home/me")
|
||||
main_checkout = main.opened(worktree_config("/code/acme"), "goals-and-audience", home)[1]
|
||||
other = main.opened(worktree_config("/code/acme-item-5"), "goals-and-audience", home)[1]
|
||||
self.assertNotEqual(main_checkout, other)
|
||||
|
||||
def test_one_worktree_always_gets_the_same_copy(self):
|
||||
home = pathlib.Path("/home/me")
|
||||
first = main.opened(worktree_config("/code/acme"), "goals-and-audience", home)[1]
|
||||
self.assertEqual(first, main.opened(worktree_config("/code/acme"), "goals-and-audience", home)[1])
|
||||
|
||||
def test_two_worktrees_named_alike_in_different_folders_get_copies_that_differ(self):
|
||||
home = pathlib.Path("/home/me")
|
||||
first = main.opened(worktree_config("/code/acme-item-5"), "goals-and-audience", home)[1]
|
||||
second = main.opened(worktree_config("/other/acme-item-5"), "goals-and-audience", home)[1]
|
||||
self.assertNotEqual(first, second)
|
||||
|
||||
|
||||
class Pruned(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.home = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory()))
|
||||
self.config = worktree_config("/code/acme-item-5")
|
||||
self.folders = self.home / ".local/state/project-record/acme"
|
||||
for top in ("/code/acme", "/code/acme-item-5", "/code/acme-item-6"):
|
||||
copy = main.opened(worktree_config(top), "goals-and-audience", self.home)[1]
|
||||
copy.parent.mkdir(parents=True)
|
||||
copy.write_text("edit")
|
||||
|
||||
def kept(self) -> set[str]:
|
||||
return {folder.name for folder in self.folders.iterdir()}
|
||||
|
||||
def listed(self, *tops: str):
|
||||
return lambda *args, **kwargs: "" if args != ("worktree", "list", "--porcelain") else "".join(f"worktree {top}\nHEAD abc\nbranch refs/heads/x\n\n" for top in tops)
|
||||
|
||||
def test_removes_the_copies_of_worktrees_git_no_longer_lists_and_keeps_the_others(self):
|
||||
main.pruned(self.config, self.home, self.listed("/code/acme", "/code/acme-item-5"))
|
||||
self.assertEqual(self.kept(), {main.worktree_folder(pathlib.Path(top)) for top in ("/code/acme", "/code/acme-item-5")})
|
||||
|
||||
def test_always_keeps_the_copy_of_the_worktree_that_asked(self):
|
||||
main.pruned(self.config, self.home, self.listed("/code/acme"))
|
||||
self.assertIn(main.worktree_folder(pathlib.Path("/code/acme-item-5")), self.kept())
|
||||
|
||||
def test_removes_nothing_where_git_cannot_list_the_worktrees(self):
|
||||
main.pruned(self.config, self.home, lambda *args, **kwargs: Failure("not a repository"))
|
||||
self.assertEqual(len(self.kept()), 3)
|
||||
|
||||
def test_leaves_files_beside_the_folders_alone(self):
|
||||
(self.folders / "decisions.md").write_text("from before the folders")
|
||||
main.pruned(self.config, self.home, self.listed("/code/acme"))
|
||||
self.assertTrue((self.folders / "decisions.md").exists())
|
||||
|
||||
def test_a_copy_that_cannot_be_removed_does_not_fail_the_open(self):
|
||||
self.folders.chmod(0o500)
|
||||
self.addCleanup(self.folders.chmod, 0o700)
|
||||
main.pruned(self.config, self.home, self.listed("/code/acme"))
|
||||
self.assertEqual(len(self.kept()), 3)
|
||||
|
||||
def test_an_open_prunes_and_a_save_does_not(self):
|
||||
run = self.listed("/code/acme", "/code/acme-item-5")
|
||||
self.assertEqual(main.performed(self.config, "save", "goals-and-audience", self.home, run), "/code/acme-item-5/README.md is the record itself, so nothing is left to store.")
|
||||
self.assertEqual(len(self.kept()), 3)
|
||||
self.assertEqual(main.performed(self.config, "open", "goals-and-audience", self.home, run), "/code/acme-item-5/README.md")
|
||||
self.assertEqual(self.kept(), {main.worktree_folder(pathlib.Path(top)) for top in ("/code/acme", "/code/acme-item-5")})
|
||||
|
||||
def test_does_nothing_where_the_project_has_no_copies(self):
|
||||
main.pruned(worktree_config("/code/acme"), self.home / "elsewhere", self.listed("/code/acme"))
|
||||
|
||||
|
||||
class Act(unittest.TestCase):
|
||||
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):
|
||||
|
||||
+42
-16
@@ -70,7 +70,7 @@ def rank(text: str, goals_text: str, decisions: str, history: str, floor: decima
|
||||
ranked = rank_details(rewrite_table(lines, table, shape, scored), [item for item, _ in scored])
|
||||
if isinstance(ranked, Failure):
|
||||
return ranked
|
||||
under_bar = [under_the_bar(item, value, scoring.bar, items) for item, value in scored if not item.exempt and round(value, 1) < scoring.bar]
|
||||
under_bar = [under_the_bar(item, value, scoring.bar, items) for item, value in scored if falls_under(item, value, scoring.bar)]
|
||||
return Ranked(ranked, under_bar, notes(items, scoring))
|
||||
|
||||
|
||||
@@ -115,22 +115,30 @@ def under_the_bar(item: Item, value: float, bar: float, items: list[Item]) -> st
|
||||
|
||||
|
||||
def read_scoring(text: str, lines: list[str], goals_text: str, decisions: str, history: str, shape: Shape, floor: decimal.Decimal) -> Scoring | Failure:
|
||||
goals = ranked_goals(goals_text, decisions)
|
||||
if isinstance(goals, Failure):
|
||||
return goals
|
||||
formula = parse_formula(stated(text, "Score"), variables(shape))
|
||||
if isinstance(formula, Failure):
|
||||
return formula
|
||||
bar = number(stated(text, "Bar"), "the bar")
|
||||
if isinstance(bar, Failure):
|
||||
return bar
|
||||
next_id = stated(text, "Next ID")
|
||||
if isinstance(next_id, Failure) or not re.fullmatch(r"[0-9]+", next_id):
|
||||
return next_id if isinstance(next_id, Failure) else Failure(f"Next ID {next_id!r} is not a whole number")
|
||||
return scoring_of(stated(text, "Score"), number(stated(text, "Bar"), "the bar"), goals_text, decisions, history, floor, shape=shape, lines=lines, next_id=int(next_id))
|
||||
|
||||
|
||||
def config_scoring(formula: str, bar: float, goals_text: str, decisions: str, history: str, floor: decimal.Decimal) -> Scoring | Failure:
|
||||
"""The scoring of a plan in Jira, whose formula and bar the project's config states. Jira numbers the issues, so no Next ID applies."""
|
||||
return scoring_of(formula, bar, goals_text, decisions, history, floor, shape=SHAPE, lines=[], next_id=0)
|
||||
|
||||
|
||||
def scoring_of(formula_text: str | Failure, bar: float | Failure, goals_text: str, decisions: str, history: str, floor: decimal.Decimal, *, shape: Shape, lines: list[str], next_id: int) -> Scoring | Failure:
|
||||
goals = ranked_goals(goals_text, decisions)
|
||||
if isinstance(goals, Failure):
|
||||
return goals
|
||||
formula = parse_formula(formula_text, variables(shape))
|
||||
if isinstance(formula, Failure):
|
||||
return formula
|
||||
if isinstance(bar, Failure):
|
||||
return bar
|
||||
weights = weigh(lines, history, goals, shape, floor)
|
||||
if isinstance(weights, Failure):
|
||||
return weights
|
||||
return Scoring(shape, formula, bar, int(next_id), dict(goals), weights)
|
||||
return Scoring(shape, formula, bar, next_id, dict(goals), weights)
|
||||
|
||||
|
||||
def weigh(lines: list[str], history: str, goals: list[tuple[str, Mark]], shape: Shape, floor: decimal.Decimal) -> dict[str, float] | Failure:
|
||||
@@ -287,19 +295,37 @@ def parse_item(row: str, scoring: Scoring, table: Table) -> Item | Failure:
|
||||
if scoring.shape is OLD_SHAPE:
|
||||
return item
|
||||
# R is written here, as the Score is, so --check finds a stale one, and a reader keeps the R the table stored.
|
||||
return with_risk(item)
|
||||
|
||||
|
||||
def with_risk(item: Item) -> Item:
|
||||
return dataclasses.replace(item, scores=item.scores | {"R": risk(item.scores["L"], item.scores["E"], item.scores["I"])})
|
||||
|
||||
|
||||
def cited_goals_failure(item: Item, scoring: Scoring) -> Failure | None:
|
||||
"""Why the item may not name one of the goals it names, such as one the goals file voids or does not number; None when it may name each. todo_table's parse_moves holds the rules a Moves cell keeps on its own."""
|
||||
def falls_under(item: Item, value: float, bar: float) -> bool:
|
||||
"""Whether the item, which scores value, may not be planned: it scores under the bar, rounded as todo.md shows a Score, and isn't exempt."""
|
||||
return not item.exempt and round(value, 1) < bar
|
||||
|
||||
|
||||
def item_score(item: Item, scoring: Scoring, name: str) -> float | Failure:
|
||||
"""The score of an item that holds no R, such as an issue in Jira; refused where it names a goal it may not. name is what a message calls the item."""
|
||||
if broken := cited_goals_failure(item, scoring, name):
|
||||
return broken
|
||||
value = score(scoring.formula, with_risk(item), scoring)
|
||||
return Failure(f"the formula gives {name} no finite score") if isinstance(value, Failure) else value
|
||||
|
||||
|
||||
def cited_goals_failure(item: Item, scoring: Scoring, name: str = "") -> Failure | None:
|
||||
"""Why the item may not name one of the goals it names, such as one the goals file voids or does not number; None when it may name each. name is what a message calls the item, `item <ID>` where empty. todo_table's parse_moves holds the rules a Moves cell keeps on its own."""
|
||||
name = name or f"item {item.id}"
|
||||
if scoring.shape is OLD_SHAPE:
|
||||
unknown = [goal for goal, _ in item.moves if goal not in scoring.weights]
|
||||
return Failure(f"item {item.id} cites goal {', '.join(unknown)}, which the goal weights do not list") if unknown else None
|
||||
return Failure(f"{name} cites goal {', '.join(unknown)}, which the goal weights do not list") if unknown else None
|
||||
for goal, _ in item.moves:
|
||||
if goal == CODE_HEALTH and goal not in scoring.goals:
|
||||
return Failure(f"item {item.id} names {CODE_HEALTH}, which the goals file voids; drop it from the item's {MOVES}, or the void from the goals file")
|
||||
return Failure(f"{name} names {CODE_HEALTH}, which the goals file voids; drop it from the item's {MOVES}, or the void from the goals file")
|
||||
if goal not in scoring.goals:
|
||||
return Failure(f"item {item.id} cites goal {goal}, which the goals file's ## Goals does not number")
|
||||
return Failure(f"{name} cites goal {goal}, which the goals file's ## Goals does not number")
|
||||
return None
|
||||
|
||||
|
||||
|
||||
@@ -156,18 +156,32 @@ def todos_since(tag: str | None | Failure, ref: str, plan: str | None, cwd: str,
|
||||
def chunk_item(found: list[Item], cut: LastCut) -> Pick:
|
||||
"""The pick from todo.md's items, weighed against the last cut. Routing and chunk-preflight both pick with it, so they name one item."""
|
||||
upcoming = next_release(found, cut)
|
||||
return standing(upcoming, next_item(found), cut.reviewed) if isinstance(upcoming, Upcoming) else upcoming
|
||||
return standing(upcoming, next_item(carried(found, cut)), cut.reviewed) if isinstance(upcoming, Upcoming) else upcoming
|
||||
|
||||
|
||||
def carried(found: list[Item], cut: LastCut) -> list[Item]:
|
||||
"""found, with the release of each item that the plan files under the last cut's version, or an earlier one, replaced by the next release: the earliest after the cut that the plan holds or todo.md has named since it.
|
||||
|
||||
Someone cut a release while it held those items, and the loop works on: lilleman's call, 2026-11-16. found itself where nothing is cut, and where no release after the cut is known, since naming one is the human's.
|
||||
"""
|
||||
version = cut_version(cut)
|
||||
named = named_releases(cut.todos_since)
|
||||
known = {item.release for item in found} | (set() if isinstance(named, Failure) else named)
|
||||
after = set() if version is None else {release for release in known if release > version}
|
||||
if not after or all(item.release >= min(after) for item in found):
|
||||
return found
|
||||
return [dataclasses.replace(item, release=max(item.release, min(after))) for item in found]
|
||||
|
||||
|
||||
def next_release(found: list[Item], cut: LastCut) -> Upcoming | Cut | Unknown:
|
||||
"""The next release after cut, and whether work has landed towards it. found holds the plan's items.
|
||||
|
||||
Cut where the plan files items under the last cut's version or earlier, and Unknown where the tags, or todo.md's texts since the cut, cannot be read.
|
||||
Cut where the plan files items under the last cut's version or earlier and no later release is known for carried to file them under, and Unknown where the tags, or todo.md's texts since the cut, cannot be read.
|
||||
Where the branch has no tag, todos_since holds every version of todo.md, so a release todo.md named whose items are all done still reads as the next release.
|
||||
"""
|
||||
if isinstance(cut.tag, Failure):
|
||||
return Unknown()
|
||||
earliest = min((item.release for item in found), default=None)
|
||||
earliest = min((item.release for item in carried(found, cut)), default=None)
|
||||
version = cut_version(cut)
|
||||
if version is None:
|
||||
return Upcoming(earliest, True, has_unreleased(cut))
|
||||
@@ -186,6 +200,7 @@ def next_release(found: list[Item], cut: LastCut) -> Upcoming | Cut | Unknown:
|
||||
|
||||
def cut_version(cut: LastCut) -> Release | None:
|
||||
"""Which version is cut. It is the tag's, or None where the tag names no version. On a branch with no tag, it is the newest version under a dated CHANGELOG.md heading, else BEFORE_FIRST_RELEASE."""
|
||||
# The loop reads no other mark of a cut, such as another tag spelling or a Jira Fix Version marked released, until lilleman says to add one: his call, 2026-11-16.
|
||||
if cut.tag is None:
|
||||
return dated_cut(cut.tag, cut.changelog) or BEFORE_FIRST_RELEASE
|
||||
return tagged(cut.tag) if isinstance(cut.tag, str) else None
|
||||
|
||||
@@ -271,6 +271,19 @@ class CodeHealth(unittest.TestCase):
|
||||
"""A scoring run's entry, without the history's title."""
|
||||
return SCORED.format(overall=overall).removeprefix("# Comprehension history\n\n").replace("2026-10-08T12", at).replace("PR #1 at aaaaaaa", read)
|
||||
|
||||
def test_a_plan_in_jira_weighs_the_goals_as_todo_md_does(self):
|
||||
# As the two tests below: code health weighs 1 / 1.97 at or over the floor and four times that under it, goal 1 0.97 / 1.97.
|
||||
for floor, code_health in ((DEFAULT_FLOOR, 4 / 1.97), (decimal.Decimal("6.0"), 1 / 1.97)):
|
||||
with self.subTest(floor=floor):
|
||||
stated = ranking.config_scoring("V", 1, self.readme, "", SCORED.format(overall="6.99"), floor)
|
||||
assert not isinstance(stated, Failure), stated
|
||||
self.assertEqual(set(stated.weights), {"code health", "1"})
|
||||
self.assertAlmostEqual(stated.weights["code health"], code_health)
|
||||
self.assertAlmostEqual(stated.weights["1"], 0.97 / 1.97)
|
||||
opted_out = ranking.config_scoring("V", 1, self.readme, "## review opt-out: the comprehension check\n\nCosts rounds.\n", "", DEFAULT_FLOOR)
|
||||
assert isinstance(opted_out, Failure), opted_out
|
||||
self.assertTrue(opted_out.reason.startswith("docs/decisions.md opts out of the comprehension check"), opted_out.reason)
|
||||
|
||||
def test_ranks_code_health_first_among_the_achieve_goals_at_an_overall_of_7_or_above(self):
|
||||
# Code health, then goal 1: weights 1 / 1.97 and 0.97 / 1.97, an item moving one by 1 at S 1 scoring 50 times its weight.
|
||||
self.assertEqual(self.scores(SCORED.format(overall="7.00")), {"| 1": "25.4", "| 2": "24.6"})
|
||||
@@ -461,6 +474,16 @@ class OldShape(unittest.TestCase):
|
||||
|
||||
def test_refuses_an_item_citing_a_goal_the_weights_do_not_list(self):
|
||||
self.assertEqual(self.ranked(OLD_SHAPE.replace("| 2.1, 1 | 0 |", "| 2.1, 9 | 0 |")), Failure("item 3 cites goal 9, which the goal weights do not list"))
|
||||
self.assertEqual(self.ranked(OLD_SHAPE.replace("| 2.1, 1 | 0 |", "| 9, 8 | 0 |")), Failure("item 3 cites goal 9, 8, which the goal weights do not list"))
|
||||
|
||||
def test_refuses_a_bar_or_next_id_that_is_no_number_naming_the_line(self):
|
||||
for todo, reason in (
|
||||
(TODO.replace("`Bar = 2`", "`Bar = x`"), "the bar 'x' is not a finite number"),
|
||||
(TODO.replace("`Next ID = 6`\n", ""), "todo.md states `Next ID = ...` 0 times; state it once, on a line of its own under ## Scoring"),
|
||||
(TODO.replace("`Next ID = 6`", "`Next ID = x`"), "Next ID 'x' is not a whole number"),
|
||||
):
|
||||
with self.subTest(reason=reason):
|
||||
self.assertEqual(self.ranked(todo), Failure(reason))
|
||||
|
||||
def test_refuses_a_formula_over_v(self):
|
||||
self.assertEqual(self.ranked(OLD_SHAPE.replace("-R - S/4 + 2*A + 2*G*W", "V")), Failure("the formula 'V' may hold only numbers, A, G, R, S, W, + - * / ** and parentheses"))
|
||||
|
||||
@@ -77,6 +77,33 @@ class NextRelease(unittest.TestCase):
|
||||
self.assertEqual(release_standing.next_release([one((1, 3, 0))], cut(Failure("count unreadable"))), release_standing.Upcoming((1, 3, 0), True, Failure("count unreadable")))
|
||||
|
||||
|
||||
class Carried(unittest.TestCase):
|
||||
def test_files_each_item_of_a_release_already_cut_under_the_earliest_release_the_plan_names_after_the_cut(self):
|
||||
held = [dataclasses.replace(one((1, 2, 3)), id=1), dataclasses.replace(one((1, 2, 0)), id=2), dataclasses.replace(one((1, 4, 0)), id=3), dataclasses.replace(one((1, 3, 0)), id=4)]
|
||||
carried = release_standing.carried(held, release_standing.LastCut("v1.2.3", "", 4, []))
|
||||
self.assertEqual([(item.id, item.release) for item in carried], [(1, (1, 3, 0)), (2, (1, 3, 0)), (3, (1, 4, 0)), (4, (1, 3, 0))])
|
||||
|
||||
def test_leaves_the_plan_as_it_is_where_nothing_is_cut_or_it_names_no_release_after_the_cut(self):
|
||||
held = [one((1, 2, 3))]
|
||||
for tag in ("v1.2.3", "v1.2.2", None, Failure("tags unreadable")):
|
||||
with self.subTest(tag=tag):
|
||||
self.assertIs(release_standing.carried(held, release_standing.LastCut(tag, "", 4, [])), held)
|
||||
|
||||
def test_files_them_under_a_release_todo_md_named_since_the_cut_though_the_plan_holds_no_item_of_it(self):
|
||||
held = [one((1, 2, 3)), dataclasses.replace(one((1, 4, 0)), id=2)]
|
||||
cut = release_standing.LastCut("v1.2.3", "", 4, naming({(1, 2, 3), (1, 3, 0)}))
|
||||
self.assertEqual([item.release for item in release_standing.carried(held, cut)], [(1, 3, 0), (1, 4, 0)])
|
||||
self.assertEqual(release_standing.chunk_item(held, cut), release_standing.Next((1, 3, 0), dataclasses.replace(held[0], release=(1, 3, 0))))
|
||||
self.assertEqual(release_standing.carried(held[:1], dataclasses.replace(cut, todos_since=Failure("log unreadable"))), held[:1])
|
||||
|
||||
def test_takes_the_cut_releases_item_first_as_the_next_releases(self):
|
||||
held = [dataclasses.replace(one((1, 2, 3)), id=1), dataclasses.replace(one((1, 3, 0)), id=2)]
|
||||
cut = release_standing.LastCut("v1.2.3", "", 4, [])
|
||||
self.assertEqual(release_standing.chunk_item(held, cut), release_standing.Next((1, 3, 0), dataclasses.replace(held[0], release=(1, 3, 0))))
|
||||
self.assertEqual(release_standing.next_release(held, cut), release_standing.Upcoming((1, 3, 0), True, True))
|
||||
self.assertEqual(release_standing.next_release(held[:1], cut), release_standing.Cut((1, 2, 3)))
|
||||
|
||||
|
||||
class ChunkItem(unittest.TestCase):
|
||||
def test_takes_the_earliest_release_where_it_is_the_next_and_else_says_whether_the_next_is_ready_to_cut_or_to_plan(self):
|
||||
cases = (
|
||||
@@ -91,7 +118,8 @@ class ChunkItem(unittest.TestCase):
|
||||
(Failure("tags unreadable"), 4, (0, 2, 0), set(), release_standing.Unknown()),
|
||||
(Failure("tags unreadable"), 4, None, set(), release_standing.Unknown()),
|
||||
("v1.2.3", 4, (1, 2, 3), set(), release_standing.Cut((1, 2, 3))),
|
||||
("v1.2.3", 4, (1, 2, 2), {(1, 2, 4)}, release_standing.Cut((1, 2, 2))),
|
||||
("v1.2.3", 4, (1, 2, 2), set(), release_standing.Cut((1, 2, 2))),
|
||||
("v1.2.3", 4, (1, 2, 2), {(1, 2, 4)}, release_standing.Next((1, 2, 4), one((1, 2, 4)))),
|
||||
("v1.2.3", 4, (1, 3, 0), {(1, 2, 4), (1, 3, 0)}, release_standing.ReadyToCut((1, 2, 4))),
|
||||
("v0.9.2", 4, (1, 0, 0), {(0, 9, 3)}, release_standing.ReadyToCut((0, 9, 3))),
|
||||
("v1.2.3", 4, (1, 4, 0), {(1, 2, 2), (1, 3, 0)}, release_standing.ReadyToCut((1, 3, 0))),
|
||||
@@ -140,7 +168,8 @@ class ChunkItem(unittest.TestCase):
|
||||
self.assertNotEqual(release_standing.chunk_item([], without_unreleased), release_standing.ReviewDue((0, 0, 1)), "0.0.1 is cut under its dated heading")
|
||||
later = [HEADER + ROW.format(id=1, release="0.0.1") + ROW.format(id=2, release="0.1.0"), HEADER + ROW.format(id=2, release="0.1.0")]
|
||||
self.assertEqual(release_standing.chunk_item(plan_under((0, 1, 0)), release_standing.LastCut(None, changelog, 4, later)), release_standing.Next((0, 1, 0), one((0, 1, 0))))
|
||||
self.assertEqual(release_standing.chunk_item(plan_under((0, 0, 1)), release_standing.LastCut(None, changelog, 4, later)), release_standing.Cut((0, 0, 1)))
|
||||
self.assertEqual(release_standing.chunk_item(plan_under((0, 0, 1)), release_standing.LastCut(None, changelog, 4, later)), release_standing.Next((0, 1, 0), one((0, 1, 0))))
|
||||
self.assertEqual(release_standing.chunk_item(plan_under((0, 0, 1)), release_standing.LastCut(None, changelog, 4, history)), release_standing.Cut((0, 0, 1)))
|
||||
|
||||
def test_counts_neither_an_undated_heading_nor_a_heading_behind_a_tag_as_cut(self):
|
||||
history = [HEADER + ROW.format(id=1, release="0.0.1"), HEADER]
|
||||
|
||||
@@ -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."""
|
||||
|
||||
@@ -35,7 +42,7 @@ 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:
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -74,11 +75,11 @@ class HttpJson(unittest.TestCase):
|
||||
|
||||
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):
|
||||
@@ -96,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()
|
||||
@@ -126,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):
|
||||
|
||||
@@ -267,7 +267,7 @@ class Main(unittest.TestCase):
|
||||
result = result if "api_error_status" in result else {"type": "result", "structured_output": {"found": [n + 1 for n in result["found"]]}}
|
||||
return subprocess.CompletedProcess(args, 0, json.dumps(result), "")
|
||||
|
||||
effects = Effects(claude=claude, claude_on_terminal=unused, discard_typed=unused, dm=unused, execv=unused, git=system_effects().git, input=unused, local_time=unused, memory=unused, now=unused, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused)
|
||||
effects = Effects(claude=claude, claude_on_terminal=unused, discard_typed=unused, dm=unused, execv=unused, git=system_effects().git, input=unused, local_time=unused, memory=unused, now=unused, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused, tmux=unused, tmux_on_terminal=unused)
|
||||
out, err = io.StringIO(), io.StringIO()
|
||||
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
|
||||
code = main.main(argv, {}, self.home, effects)
|
||||
|
||||
@@ -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):
|
||||
@@ -1219,7 +1279,7 @@ class TodoRankCheck(unittest.TestCase):
|
||||
|
||||
def test_a_plan_in_jira_is_not_checked_in_the_checkout_or_the_configs_folder(self):
|
||||
checkout = self.changed_plan(f"{self.folder}/clone", self.STUB)
|
||||
self.config.write_text(self.config.read_text().replace('"checkout:todo.md"', '"jira:https://acme.atlassian.net/browse/ABC-12"') + 'env-file = "~/acme.env"\n')
|
||||
self.config.write_text(self.config.read_text().replace('"checkout:todo.md"', '"jira:https://acme.atlassian.net/browse/ABC-12"') + 'env-file = "~/acme.env"\njira-score-formula = "V"\njira-score-bar = 1\n')
|
||||
folder = str(self.config.parent)
|
||||
git(folder, "init", "-q")
|
||||
(self.config.parent / "todo.md").write_text("# todo\n")
|
||||
|
||||
@@ -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
@@ -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")
|
||||
|
||||
@@ -62,7 +62,7 @@ class Main(unittest.TestCase):
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
config = configured(self, pathlib.Path(temp)) / "config.toml"
|
||||
self.enterContext(contextlib.chdir(temp))
|
||||
config.write_text(config.read_text().replace('"checkout:todo.md"', '"jira:https://acme.atlassian.net/browse/ABC-12"') + 'env-file = "~/acme.env"\n')
|
||||
config.write_text(config.read_text().replace('"checkout:todo.md"', '"jira:https://acme.atlassian.net/browse/ABC-12"') + 'env-file = "~/acme.env"\njira-score-formula = "V"\njira-score-bar = 1\n')
|
||||
todo = pathlib.Path(temp, "todo.md")
|
||||
todo.write_text(TODO)
|
||||
for args in ((), (str(todo),), ("--check", str(todo))):
|
||||
|
||||
+31
-10
@@ -6,12 +6,12 @@ usage: todo-item list [--release <version>]
|
||||
[--blocked-by <IDs>] [--exempt <reason>] <tagline> [<<'EOF' detail EOF]
|
||||
todo-item edit <ID> [--tagline <tagline>] [--l <L>] [--e <E>] [--i <I>] [--s <S>] [--moves <moves>]
|
||||
[--blocked-by <IDs>] [--exempt <reason>] [--detail <<'EOF' detail EOF | --clear-detail]
|
||||
[--comment <why>]
|
||||
todo-item move <ID> --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. In a Jira epic, list,
|
||||
show and add work, and edit, move and finish fail so far. Each command that changes
|
||||
`project-config plan` prints: a markdown file, todo.md, or a Jira epic. 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,19 +28,32 @@ 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.
|
||||
In a Jira epic, add files a Task under the epic, 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`. The item scores by the config's `jira-score-formula`, and
|
||||
add refuses it under `jira-score-bar` unless it is exempt. add then asks Jira to rank the new issue
|
||||
just before the first issue the loop filed that ranks after it: a question before any other, then a
|
||||
security finding, then the higher score. Where none does, it stays last. A person's issues don't
|
||||
count, and keep their rank. Where Jira files the issue and then refuses a --blocked-by link or the
|
||||
rank, add still prints `Filed item <ID> …`, and says on stderr what to do 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.
|
||||
Text on stdin without --detail, and --detail without text on stdin, are refused, so no detail is
|
||||
dropped or wiped by mistake. It prints `Edited item <ID> in <plan>.` It doesn't write anything where
|
||||
ranking fails or scores the item under the bar.
|
||||
In a Jira epic, edit changes an issue the loop filed: its summary, description and scores, and
|
||||
the label `security` with --exempt. It doesn't change a link, so --blocked-by fails.
|
||||
Of an issue a person filed it sets only the scores, --moves and --exempt, and only with --comment.
|
||||
The four scores are set together where the issue holds none yet.
|
||||
--comment is posted as a comment on the Jira issue, for the client's team, in the project's
|
||||
language. Jira doesn't show the team the scores, so say that the issue is scored, and why.
|
||||
A todo.md keeps no comment, so there the flag doesn't do anything.
|
||||
Where Jira takes the edit and then refuses the comment, edit still prints `Edited item <ID> …`,
|
||||
and says on stderr to post the comment in Jira.
|
||||
|
||||
move sets the item's release, as edit sets a cell. It prints `Moved item <ID> to release <version> in <plan>.`
|
||||
In a Jira epic, move sets the Fix Version of an issue the loop filed; a person moves their own.
|
||||
|
||||
finish removes the item and its detail. With --changelog it adds the bullet first under
|
||||
CHANGELOG.md's ## Unreleased, or a ## heading that says unreleased, creating the section, or the
|
||||
@@ -48,10 +61,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. The one exception is an add to a
|
||||
Jira epic that Jira didn't answer or answered brokenly: the message then says the issue may exist.
|
||||
`not edited:`, `not moved:` or `not finished:` means it didn't write anything. The one exception is an add,
|
||||
an edit, a move or a finish in a Jira epic that Jira didn't answer or answered brokenly: the message then
|
||||
says the issue may exist, may have changed or may have moved.
|
||||
"""
|
||||
import argparse
|
||||
import pathlib
|
||||
@@ -119,6 +139,7 @@ def parser() -> argparse.ArgumentParser:
|
||||
detail = editing.add_mutually_exclusive_group()
|
||||
detail.add_argument("--detail", action="store_true")
|
||||
detail.add_argument("--clear-detail", action="store_true")
|
||||
editing.add_argument("--comment")
|
||||
moving = commands.add_parser("move")
|
||||
moving.add_argument("id", type=int)
|
||||
moving.add_argument("--release", required=True)
|
||||
@@ -192,7 +213,7 @@ def edit(args: argparse.Namespace, plan: PlanStore, text: str) -> str | Failure:
|
||||
detail = text if args.detail else "" if args.clear_detail else None
|
||||
if not fields(args) and detail is None:
|
||||
return Failure("not edited: no flag names a change; todo-item --help lists them")
|
||||
return reported(plan.edit(args.id, fields(args), detail), "not edited", lambda written: f"Edited item {written.id} in {plan.label}.")
|
||||
return reported(plan.edit(args.id, fields(args), detail, args.comment), "not edited", lambda written: f"Edited item {written.id} in {plan.label}.")
|
||||
|
||||
|
||||
def finish(args: argparse.Namespace, plan: PlanStore, changelog: RecordStore) -> str | Failure:
|
||||
|
||||
@@ -13,6 +13,7 @@ from project_config.settings import DEFAULT_FLOOR
|
||||
from todo_item import edits, main
|
||||
from failure import Failure
|
||||
from project_config.main import located
|
||||
from plan_store.fakes import MemoryPlan
|
||||
from release_plan import plan_file, ranking
|
||||
from plan_store.stores import plan_of
|
||||
from todo_item.table import table
|
||||
@@ -415,6 +416,18 @@ class Edit(TodoItem):
|
||||
|
||||
def test_refuses_an_edit_that_changes_nothing(self):
|
||||
self.assertEqual(self.run_main("edit", "3"), (1, "", "not edited: no flag names a change; todo-item --help lists them\n"))
|
||||
self.assertEqual(self.run_main("edit", "3", "--comment", "Why.")[::2], (1, "not edited: no flag names a change; todo-item --help lists them\n"))
|
||||
|
||||
def test_an_edit_hands_the_comment_to_the_plan(self):
|
||||
for argv, comments in ((["--comment", "A small change."], {3: ["A small change."]}), ([], {})):
|
||||
with self.subTest(argv=argv):
|
||||
plan = MemoryPlan({3: {"Release": "0.1.0", "Item": "**Count the runs.**", "L": "1", "E": "2", "I": "3", "S": "1"}})
|
||||
self.assertEqual(main.edit(main.parser().parse_args(["edit", "3", "--l", "3", *argv]), plan, ""), "Edited item 3 in the plan in memory.")
|
||||
self.assertEqual((plan.rows[3]["L"], plan.comments), ("3", comments))
|
||||
|
||||
def test_a_plan_in_a_file_takes_an_edit_with_a_comment_and_keeps_no_comment(self):
|
||||
self.assertEqual(self.run_main("edit", "3", "--l", "3", "--comment", "A small change.")[:2], (0, f"Edited item 3 in {self.todo}.\n"))
|
||||
self.assertNotIn("A small change.", self.todo.read_text())
|
||||
|
||||
def test_leaves_the_file_ranked(self):
|
||||
self.run_main("edit", "1", "--s", "2", "--moves", "1 by 10")
|
||||
|
||||
@@ -3819,3 +3819,163 @@ Inherited architect, decided by:
|
||||
- Locality: `bin/review_rules/review_folder.py:17` `made_review_folder`: `home` is passed in from the command table, so each unit's inputs show in its signature; at the base `Path.home()` was read deep inside
|
||||
- Shape: `bin/larv_review/scoring_setup.py:169` `prepare_scoring`: counts against the change: about 75 lines with a dozen early returns, and `prompt_parts` builds one path twice
|
||||
- Shape: `bin/review_rules/round_titles.py:13` `OPENING`: the round-title spelling is written once next to the regexes that parse it
|
||||
|
||||
## 2026-11-15T21:26:29Z, PR #554 at bcb04e3
|
||||
|
||||
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|
||||
|---|---|---|---|---|---|
|
||||
| Junior A | 6.5 | 5 | 5.5 | 5 | 5.5 |
|
||||
| Mid A | 7 | 6 | 6.5 | 6 | 6.5 |
|
||||
| Maintainability senior | 7 | 5.5 | 6 | 6 | 6 |
|
||||
| Inherited architect | 6.5 | 6 | 5.5 | 5.5 | 6 |
|
||||
| Mean | 6.75 | 5.63 | 5.88 | 5.63 | 6.00 |
|
||||
|
||||
Junior A, hardest first:
|
||||
|
||||
- Locality, Self-sufficiency: `bin/loop_claude/routing.py:113` `unfinished_route`: five rung notions, two step-up counters and a seven-row verdict table at once, and the reasons in the decision log
|
||||
- Shape: `bin/release_plan/release_standing.py:162` `next_release`: many edge-case branches and `str | None | Failure` threaded through every field of `LastCut`
|
||||
- Locality, Shape: `bin/loop_claude/cycle/run.py:151` `rule`: judges, stamps, annotates, steps the rung up and archives, and no single unit owns the archive's order
|
||||
- Self-sufficiency: `bin/loop_claude/cycle/judge.py:22` `INTERRUPT_RULES`: policy partly in prompt text and partly in Python checks, with nothing saying which the code enforces
|
||||
- Locality: `bin/loop_claude/loop/reload.py:95` `exec_if_edited`: an edit to any `.py` under `bin/` makes a running loop re-exec, and a renamed `LoopRun` field breaks the reload
|
||||
- Shape: `bin/model_routing/ladder.py:86` `review_rung`: a three-way rule whose docstring quotes a whole decision title
|
||||
- Self-sufficiency: `bin/larv_review/main.py:1` module docstring: twelve subcommands' rules in about 155 lines of prose that cross-reference SKILL.md
|
||||
- Shape: `bin/loop_claude/loop/chunk_start.py:24` `fetched_todo`: nearly the same plan read as `fetched_plan`, told apart only by a docstring
|
||||
|
||||
Mid A, hardest first:
|
||||
|
||||
- Shape: `bin/release_plan/release_standing.py:162` `next_release`: a three-state tag, `BEFORE_FIRST_RELEASE`, `nothing_cut` and `is_earliest` held at once, and comments that explain each branch alone
|
||||
- Locality: `bin/loop_claude/routing.py:113` `unfinished_route`: five rungs, the escalation mark and the unfinished count feed one answer across three files
|
||||
- Locality, Shape: `bin/chunk_pr/main.py:298` `merged`: a while loop around the queue turn, variables bound only on some paths, and no comment stating the loop's invariant
|
||||
- Shape: `bin/chunk_preflight/main.py:128` `preflight`: lines 142-143 pack a conditional re-`located` and an eight-argument `Gathered` into two lines
|
||||
- Shape: `bin/release_plan/ranking.py:48` `rank`: two table shapes branch through the whole module, and the defect rule sits far from where scores are read
|
||||
- Self-sufficiency: `bin/larv_review/plan.py:77` `plan_reasons`: six inputs joined into one answer, and why each matters is in SKILL.md §3
|
||||
- Shape: `bin/rule_hook/env_file.py:34` `reaching`: `and` and `or` mixed without parentheses, and four path spellings in a lookaround regex
|
||||
- Self-sufficiency: `bin/loop_claude/cycle/judge.py:197` `quotes_checked`: long prompt text inside the `Reply` field metadata mixes the prompt with the schema
|
||||
|
||||
Maintainability senior, hardest first:
|
||||
|
||||
- Locality, Shape: `bin/chunk_pr/main.py:298` `merged`: a while loop holding a queue turn, approval waits and a `done` set only on some paths, with no loop invariant stated
|
||||
- Locality, Self-sufficiency: `bin/loop_claude/routing.py:113` `unfinished_route`: five rungs, the escalation count and the mark from another file, and each step's reason in the decision log
|
||||
- Locality, Self-sufficiency: `skills/larv-review/SKILL.md:146` "Comprehension check": paragraphs of four or five conditions, each pointing to a hook, a CLI's help or another rule file
|
||||
- Shape: `bin/release_plan/release_standing.py:162` `next_release`: three sources of a cut, the `is_earliest` expression and `LastCut` fields typed `str | None | Failure`
|
||||
- Shape: `bin/release_plan/ranking.py:136` `weigh`: two live table shapes double every path, and `Shape` is built from positional tuples of callables
|
||||
- Locality, Shape: `bin/loop_claude/cycle/run.py:151` `rule`: judges, stamps, archives and steps up, beside a 17-field `Cycle` passed around whole
|
||||
- Shape: `bin/chunk_pr/main.py:438` `remeasure`: control flow inside chained `isinstance(x, Failure) or …` expressions, and `finished` unpacks five runs by position
|
||||
- Shape: `bin/chunk_preflight/main.py:128` `preflight`: the whole fallback logic packed into lines 142-143
|
||||
|
||||
Inherited architect, would restructure first:
|
||||
|
||||
- Navigation, Shape: `README.md:193` the `bin/` roles: about 70 flat entries under `bin/`, where only this list tells a tool from a library
|
||||
- Navigation, Shape: `bin/larv_review/main.py:222` `COMMANDS`: the package named for the review mostly holds the comprehension check, and the review loop is prose in SKILL.md
|
||||
- Locality, Shape: `bin/chunk_pr/main.py:384` `levelled_and_finished`: merges, finishes items, pushes, asks whether a scoring run is owed and remeasures under a name that gives two of the five
|
||||
- Locality: `bin/chunk_pr/main.py:349` `unplanned`: matches the error text of `todo-item show`, as `finished` does, where `plan_store` reads the plan
|
||||
- Navigation: `bin/rule_hook/round_cap.py:10` `round_cap_breaches`: the round cap is enforced in the hook, not in `larv_review`, where a reader looks first
|
||||
- Shape: `bin/deploy_release/forge.py:1` module: the forge lives in `deploy_release` and in `chunk_preflight.choices.forge_of`, neither a home its name gives
|
||||
- Shape: `bin/rule_hook/rules.py:26` `RULES`: the file is the registry and also four rules' checkers, so where a new rule goes is undecided
|
||||
- Self-sufficiency: `bin/plan_store/stores.py:5` module docstring: cites plan items 365, 366 and 368 as part of the contract, as routing and ladder code cite decisions
|
||||
|
||||
## 2026-11-16T12:09:27Z, PR #560 at 55235a0
|
||||
|
||||
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|
||||
|---|---|---|---|---|---|
|
||||
| Junior A | 7 | 5.5 | 6.5 | 6 | 6 |
|
||||
| Mid A | 7.5 | 6.5 | 7 | 6.5 | 7 |
|
||||
| Maintainability senior | 7 | 6 | 6.5 | 6 | 6.5 |
|
||||
| Inherited architect | 7 | 6.5 | 6 | 6 | 6.5 |
|
||||
| Mean | 7.13 | 6.13 | 6.50 | 6.13 | 6.50 |
|
||||
|
||||
Junior A, hardest first:
|
||||
|
||||
- Locality: `skills/larv-review/SKILL.md:90` "Re-entry": six rules held at once with the round cap, the release-review caps and the mechanical-answers exception, as dense prose rather than a decision table
|
||||
- Locality, Self-sufficiency: `bin/release_plan/release_standing.py:176` `next_release`: three sources of the cut version and release names replayed from todo.md's history; `is_earliest` carries the meaning of "the plan is current" without naming it
|
||||
- Locality: `bin/loop_claude/routing.py:116` `unfinished_route`: five rungs, a counter and an escalation mark from another module; the docstring table makes it tractable
|
||||
- Shape: `bin/release_plan/ranking.py:239` `score`: the OLD_SHAPE and SHAPE split runs through every layer, and `weight_of` packs a three-way rule into one line
|
||||
- Self-sufficiency: `bin/loop_claude/cycle/judge.py:197` `quotes_checked`: six quote kinds each with its own fallback; `INTERRUPT_RULES` is behaviour the code cannot verify
|
||||
- Locality: `bin/loop_claude/cycle/run.py:154` `rule`: the order of stamping, archiving and stepping matters across three functions
|
||||
- Shape: `bin/loop_claude/cycle/prompts.py:66` `review_launches`: a prompt assembled from five helpers that may each return nothing
|
||||
|
||||
Mid A, hardest first:
|
||||
|
||||
- Locality: `bin/loop_claude/routing.py:116` `unfinished_route`: five interacting rungs, a counter and an escalation mark; the module table resolves it, the escalation-mark rule must stay open beside it
|
||||
- Locality: `bin/release_plan/release_standing.py:176` `next_release`: four cut cases plus renamed releases; the order of the checks carries meaning the docstrings don't explain
|
||||
- Locality: `bin/chunk_pr/main.py:298` `merged`: a loop around a flock with approval and comment checks and two exception exits; `done` assigned only under branches
|
||||
- Self-sufficiency: `bin/loop_claude/cycle/judge.py:197` `quotes_checked`: the prompt text at `judge.py:22` is behaviour written as English
|
||||
- Shape: `bin/release_plan/ranking.py:239` `score`: two table shapes double the branches, and `weight_of`'s defect rule needs a second read
|
||||
- Self-sufficiency: `bin/rule_hook/repeat_read.py:114` `shown_lines`: ISO-string time comparisons and harness behaviour nothing else lets a reader check
|
||||
- Locality: `skills/larv-review/SKILL.md:82` "Round cap": Done, Cap and Re-entry cross-reference each other and point out to three other files
|
||||
- Shape: `bin/chunk_pr/main.py:407` `finished`: five subprocess results destructured by position
|
||||
|
||||
Maintainability senior, hardest first:
|
||||
|
||||
- Locality: `bin/release_plan/release_standing.py:176` `next_release`: four regimes at once; `carried` reapplied in three places, one relying on `zip` keeping order
|
||||
- Locality: `bin/release_plan/ranking.py:239` `score`: one Score depends on five inputs held in other files, and the two shapes fork every function
|
||||
- Locality: `bin/loop_claude/routing.py:116` `unfinished_route`: rungs, a counter and a mark interact; the table resolves most of it
|
||||
- Locality: `bin/loop_claude/loop/chunk_windows.py:107` `start_chunks`: about 40 lines under one flock that check the owner, split running from stopped, compute room, read the plan and filter, with local state tracked by hand
|
||||
- Self-sufficiency: `bin/loop_claude/cycle/judge.py:197` `quotes_checked`: behaviour split between English rules for a model and verbatim checks
|
||||
- Shape: `bin/plan_store/jira_epic.py:356` `revision_of`: indexes an untyped tuple from `scores` at `jira_epic.py:530`
|
||||
- Locality: `skills/larv-review/SKILL.md:82` "Round cap": dense rules with exceptions pointing to other sections and files
|
||||
- Self-sufficiency: `bin/larv_review/main.py:1` the module docstring: the whole contract of ten subcommands in one block
|
||||
|
||||
Inherited architect, would restructure first:
|
||||
|
||||
- Navigation, Shape: `bin/release_plan/todo_table.py:1` the plan model: lives under `release_plan/`, while the plan is also in `plan_store/`, `todo_item/`, `rank_todo.py` and `larv_review/plan.py`, under three names
|
||||
- Locality: `bin/review_rules/round_titles.py:63` `past_cap`: the round cap is split across this, `rule_hook/round_cap.py:10`, `larv-review round-count` and SKILL.md's "Round cap"
|
||||
- Shape: `bin/release_plan/named_code.py:5` `named_paths`: nothing in the module is code
|
||||
- Shape: `bin/loop_claude/verdicts.py:11` `TakenIn.highest_likelihood`: L is a likelihood in the field and a level in the prose
|
||||
- Shape: `bin/loop_claude/loop/routing_check.py:20` the routing check: "routing" names four concepts across `model_routing/`, `routing_figures/` and this module
|
||||
- Navigation: `README.md:197` the `bin/` package list: the 72-entry `bin/` level has only the README's two lists as its index
|
||||
- Self-sufficiency: `bin/review_rules/round_titles.py:7` `CAP`: the why is deferred to a decision-log title in a 200 KB file
|
||||
|
||||
## 2026-11-16T12:13:26Z, PR #560 rerun at 55235a0
|
||||
|
||||
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|
||||
|---|---|---|---|---|---|
|
||||
| Junior A | 7.5 | 6 | 7 | 6.5 | 6.5 |
|
||||
| Mid A | 7 | 5.5 | 6 | 5.5 | 6 |
|
||||
| Maintainability senior | 8 | 6.5 | 7 | 7 | 7 |
|
||||
| Inherited architect | 7 | 6.5 | 6 | 7 | 6.5 |
|
||||
| Mean | 7.38 | 6.13 | 6.50 | 6.50 | 6.50 |
|
||||
|
||||
Junior A, hardest first:
|
||||
|
||||
- Locality, Self-sufficiency: `bin/release_plan/release_standing.py:176` `next_release`: five `LastCut` fields, a sentinel, renames and carried items at once; the `is_earliest` expression stayed opaque, and the full case table lives only in chunk-preflight's help
|
||||
- Locality: `bin/loop_claude/routing.py:116` `unfinished_route`: the escalation mark spans `escalation_mark.py`, `judge.py`, `verdicts.py`, `route.py` and `reload.py`
|
||||
- Self-sufficiency: `bin/rule_hook/folder_search.py:89` `skips`: mirrors rg's and ag's flag handling, which nothing in the repo lets a reader check
|
||||
- Shape: `bin/release_plan/ranking.py:239` `score`: the old-shape branches run through every function of ranking
|
||||
- Locality: `bin/loop_claude/cycle/judge.py:197` `quotes_checked`: the verdict changes shape in three places after the checks
|
||||
- Navigation: `bin/larv_review/main.py:1` the help docstring: 155 lines of rules, with no pointer to the module that enforces each
|
||||
- Locality: `bin/rule_hook/reviewer_rung.py:19` `SEAT`: a launch counts as a review by matching prompt sentences kept in Markdown
|
||||
- Locality: `bin/loop_claude/loop/reload.py:97` `exec_if_edited`: a running loop re-executes itself on any edit and hands its state over as JSON
|
||||
|
||||
Mid A, hardest first:
|
||||
|
||||
- Locality: `bin/chunk_pr/main.py:298` `merged`: `done` bound only under some branches, and the approval wait is a fall-through rather than a named branch; `levelled_and_finished` returns a finish failure only after the push
|
||||
- Locality: `bin/loop_claude/routing.py:116` `unfinished_route`: five rungs, a counter and a mark; only the module table makes the step line readable
|
||||
- Self-sufficiency: `bin/release_plan/release_standing.py:176` `next_release`: three kinds of "none", and the reason `carried` rewrites releases is a dated call with no rule in the code
|
||||
- Shape: `bin/release_plan/ranking.py:239` `score`: two table shapes through every function, and `MAINTAIN_WEIGHT`'s reason in the decision log
|
||||
- Self-sufficiency: `bin/loop_claude/cycle/judge.py:197` `quotes_checked`: the judge's prompt is spread over field metadata, rule constants and a sentence from `escalation_mark.py`
|
||||
- Locality: `skills/larv-review/SKILL.md:35` "§3. Passes": control flow as prose whose sub-sections point at each other, enforced only partly by code
|
||||
- Locality: `bin/rule_hook/rules.py:26` `RULES`: each rule's spec is a paragraph apart from the module that implements it
|
||||
- Self-sufficiency: `bin/larv_review/main.py:1` the module docstring: the only full spec of a dozen subcommands
|
||||
|
||||
Maintainability senior, hardest first:
|
||||
|
||||
- Locality: `bin/release_plan/release_standing.py:176` `next_release`: state from git history, a sentinel, and `carried` run twice, whose agreement must be checked by hand
|
||||
- Locality: `bin/loop_claude/routing.py:116` `unfinished_route`: five rungs, a count and a mark; table cells need the `steps` docstring to parse
|
||||
- Shape: `bin/release_plan/ranking.py:144` `weigh`: two table shapes through every step, and `Scoring.weights` means different things per shape
|
||||
- Shape: `bin/plan_store/jira_epic.py:356` `revision_of`: indexes the untyped tuple `scores` returns by position
|
||||
- Locality: `bin/loop_claude/loop/chunk_windows.py:107` `start_chunks`: a flock, running and dead windows, `leaving`, `room`, the restart of stopped windows, held items and a NoItem fallback in one function, with the limit applied again in `may_start`
|
||||
- Locality: `bin/chunk_pr/main.py:298` `merged`: whether `done` is bound when read depends on three `if ready` branches lining up
|
||||
- Self-sufficiency: `bin/loop_claude/cycle/judge.py:22` `INTERRUPT_RULES`: what the model is asked and what code checks need both files open
|
||||
- Self-sufficiency: `bin/rule_hook/rules.py:44` `RULES`: the env-file-read spec is a 120-word string kept in step with code elsewhere
|
||||
|
||||
Inherited architect, would restructure first:
|
||||
|
||||
- Locality, Shape: `bin/plan_store/stores.py:1` the plan store: `release_plan` and `plan_store` import each other, and the goals file sits under `release_plan`
|
||||
- Shape: `bin/larv_review/plan.py:22` `scoring_run_due`: the scoring-run trigger is spread over `plan.py`, `owed.py`, `unmeasured.py` and `scoring.py`, and `plan.py` isn't about the plan
|
||||
- Locality: `bin/review_rules/round_titles.py:45` the round cap: constants, commit enforcement in `rule_hook/round_cap.py:10`, the launch refusal in `larv_review/reviewer_header.py:73`, the printout and SKILL.md's prose
|
||||
- Shape: `bin/loop_claude/cycle/run.py:55` `Cycle.todo`: says todo.md where the plan may be a Jira epic, as `fetched_todo` and `INTERRUPT_RULES` do
|
||||
- Shape: `bin/loop_claude/hand_over.py:23` `hand_over`: shares its name with the reload's handover of state in `loop/reload.py:36` `decode_handed`
|
||||
- Locality: `bin/loop_claude/loop/close.py:18` `closed_cycle`: a second "close" beside `cycle/run.py:234` `close`
|
||||
- Navigation, Shape: `README.md:197` the `bin/` package list: 74 entries at one level with the README's list as the only index
|
||||
- Self-sufficiency: `bin/loop_claude/loop/routing_check.py:1` the module docstring: names `state.CYCLES_PER_CHECK` without saying which module `state` is
|
||||
|
||||
+67
-17
@@ -15,11 +15,13 @@ Each project principle states one rule that the decisions below apply; their ent
|
||||
- bin/: a test parametrizes its cases with `subTest`, since pytest's `parametrize` doesn't reach a unittest `TestCase`
|
||||
- bin/: the tools run on the host's Python, with no container, and so do their tests outside CI
|
||||
- bin/: the tools support only the latest stable Python, and the tests, written in plain unittest, run on it in four pytest-xdist workers
|
||||
- chunk-pr: the chunks of a project merge one at a time on a machine, each finishing its plan items in its turn, and a pull request that waits for an approval leaves the queue while it waits
|
||||
- deploy: this repo keeps no `AGENTS.md`, since `~/.claude` is its checkout; its principles and decision titles head `docs/decisions.md`, its working rules follow them there, and its `.claude/settings.json` excludes every `.claude/CLAUDE.md`, so a session in the clone loads only the clone's `CLAUDE.md`
|
||||
- loop-claude: each verdict records the claude-config release and commit that ran it, the raw tokens each thread spent by model and kind since the previous outcome that recorded a spend, and the human's typed answer the judge quotes as reversing a choice the worker took on its own recommendation
|
||||
- loop-claude: one session per project, its id derived from the checkout's path relative to `~/code`, or to `/` outside it
|
||||
- loop-claude: each chunk runs in its own tmux window, of one tmux session per project, up to `parallel-chunks` at once, and needs tmux 3.2; its claude session is named after its window, 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 +44,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
|
||||
@@ -77,6 +79,20 @@ Valid while the archive's file names, the Vocabulary and the panel keep these wo
|
||||
|
||||
2026-10-28, lilleman, through todo item 245. Serves goal 1.5: the suite gates every chunk. The suite took 198 s, 102 s of which went to rerunning it on the oldest Python README Install named, 3.11. README Install now asks for the latest stable Python as `python3`, and mypy checks every tool under `bin/` for the version Install names. README's Test line runs the tests in four pytest-xdist workers through `uvx`: 29 s on a 16-CPU machine. Four is one heavy slot's CPUs, `CPUS_PER_SLOT` in `bin/machine_load/slots.py`, so a gate under `run-heavy` loads only the slot it waits for. The line pins pytest and pytest-xdist, as `test_types.py` pins mypy, so every machine runs the gate the same way. It passes the path of `python3`, since `uvx --python python3` picks a Python uv installed itself, which may be older. The tests use stdlib `unittest` alone, and pytest only runs them, so plain `python3 -m unittest` runs the same tests one at a time and another runner can replace pytest. Valid while every machine taking the checkout gets the latest stable Python soon after its release.
|
||||
|
||||
## chunk-pr: the chunks of a project merge one at a time on a machine, each finishing its plan items in its turn, and a pull request that waits for an approval leaves the queue while it waits
|
||||
|
||||
2026-11-15, lilleman's call of 2026-11-13 in item 374, which split item 361. Serves goals 1.5 and 1.4: with several chunks open, every chunk removed its item from `todo.md` and added a bullet to `CHANGELOG.md` in its branch, so each merge left the others a conflict, a gate rerun and often a review round. `chunk-pr merge --finish <ID>` now makes those edits in the chunk's turn, on top of every chunk merged before. The worker's choices follow. The first differs from the call, and the rest settle what it left open:
|
||||
|
||||
- **A merge of the default branch, where the call said rebase.** A rebase rewrites commits the pull request already shows. The forge then drops the approval and the review threads' places. rule-hook counts a pass's rounds by the branch's commit titles, and a rebase gives each of those commits a new hash. `chunk-pr sync` already merges, and the turn reuses it.
|
||||
- **The queue is a file in the git folder the checkout's worktrees share**, held with flock for the turn (`bin/chunk_pr/main.py` → `QUEUE`). Every chunk of the project on the machine finds it without a config or a key. Two machines don't share it: there the second chunk merges without the first one's changes in its head, unless the branch protection requires an up-to-date branch. A turn lasts as long as its checks, which chunk-pr waits 30 minutes for on Gitea. So a merge waits 30 minutes for its turn, then fails naming the pull request that held the queue last, whose number the holder writes into the file.
|
||||
- **The turn holds the queue through the checks**, so what merges is what the checks ran on. A project without forge checks waits the minute `chunk-pr --help` names.
|
||||
- **The wait for an approval is outside the turn.** The first turn pushes the finished branch, so the approver reads what merges. Once approved, the pull request takes a new turn. Where the default branch moved meanwhile, that turn merges it in, and a branch protection that dismisses approvals on a push asks the approver again. A finish that fails is pushed with whatever the turn merged in, so the pull request's head stays the commit checked out. `larv-review scoring-run-owed` runs after the finish is committed, since it counts as shipped the items the committed plan no longer holds.
|
||||
- **A reviewer's comment ends the wait, in place of the loop watching for one.** `chunk-pr merge` runs in the worker's own session, so its failure is what resumes the worker, which answers and runs it again. A comment that waits is a review thread nobody resolved whose last comment someone other than the pull request's author wrote: the worker answers as that author, so an answered thread waits for the reviewer again. A comment outside a thread doesn't end the wait, since bots write those too. An approved pull request with such a thread stays unmerged too: a client's reviewer who approves and asks for one more thing gets an answer first.
|
||||
- **A paired ruling runs again once the default branch has moved past it**, on the last measured commit as before: `review: the comprehension check records …` says why the base stays. `chunk-pr merge` stops while the default branch holds commits the branch's last commit of a ruling doesn't, whoever merged them in: the turn, `chunk-pr sync` or the worker after a conflict. What the ruling says never stops the merge (project principle 2). A scoring run reads no base, so it stays.
|
||||
- **An item the plan doesn't hold is named on merge's last line, not refused.** chunk-pr cannot tell an item an earlier run finished from a mistyped ID, so the reader does. Such a run still commits the plan and the changelog, since the earlier run may have stopped between `todo-item finish` and its commit. chunk-pr checks that an ID is a number before its turn, and leaves every other rule of `todo-item finish` to that tool.
|
||||
|
||||
Valid while a chunk's worker runs `chunk-pr merge` itself, and one machine runs a project's loops.
|
||||
|
||||
## chunks: a chunk takes every unblocked item of its release that fires the same review passes, whatever its purpose, and an item above R 5 ships alone
|
||||
|
||||
2026-10-22, lilleman, through todo item 217. Serves goal 1.4: each review has a fixed cost, so more items per chunk cost less per item. Across the 165 finished chunks loop-claude archived up to that day, a chunk took a median of 1.30M tokens with one item and 1.33M with two, and three in four chunks shipped one item. The old rule also asked one PR title to state what the items achieve together; lilleman dropped it, since unrelated items that fire the same passes cost one review.
|
||||
@@ -119,9 +135,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 +157,25 @@ 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: each chunk runs in its own tmux window, of one tmux session per project, up to `parallel-chunks` at once, and needs tmux 3.2; its claude session is named after its window, 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:
|
||||
|
||||
- **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").
|
||||
|
||||
2026-11-16, lilleman's second call of 2026-11-13 splitting item 361: lilleman knows tmux and prefers it. Each chunk runs in its own window of one tmux session per project, `loop-<key>`, up to the number the config's `parallel-chunks` sets, 1 by default. tmux runs even at 1, so every project runs the same workflow (goal 1.3). A window waiting for the human ends its name in ` ?` and rings the bell, and the DM names `<session>:<window>`. The worker's choices, for what the call left open (`bin/loop_claude/tmux.py`, `bin/loop_claude/loop/chunk_windows.py`):
|
||||
|
||||
- **The window, in place of item 372's lock-file slot, names the claude session**, as `A <key> loop-claude item-372`. The loop-claude the human runs starts the windows and attaches; each window runs `loop-claude --chunk <window>`, so a loop knows its chunk before it names its claude session, and a rerun still resumes the chunk left open.
|
||||
- **A finishing chunk starts the next; only the human restarts a stopped one.** As its chunk finishes, a window's loop starts each chunk that may start then and exits, so its window closes. `remain-on-exit failed` keeps the window of a loop that stopped any other way, Ctrl-C included, with its last lines, and its chunk keeps its items. A finishing chunk never restarts it, since the human may have stopped it on purpose; the next `loop-claude <task>` starts it again before any other chunk. One flock under `~/.local/state/loop-claude/<key>/` serializes the starts, so two chunks finishing together don't start one chunk twice.
|
||||
- **The other chunks' items are told, not locked.** A fresh worker is told the items each other chunk holds, running or stopped: its window's item and those on its latest `Chunk items:` line. A chunk starts beside the others only where its item's `Touches:` prediction overlaps none of those items' predictions, since the plan's next item, which chunk-preflight's pick checks against, may already have merged.
|
||||
- **The tmux session names its checkout.** Two checkouts whose keys differ only in a character other than a letter, a digit, `_` or `-` map to one session name, so the session's `@loop-root` option names the checkout that made it, and another checkout's loop-claude refuses it.
|
||||
- **tmux 3.2 is the oldest that has every command and option used.** tmux's `CHANGES` dates the newest two to "CHANGES FROM 3.1c TO 3.2": `new-session -e`, and the `remain-on-exit` value that keeps only a failed program's pane.
|
||||
- **A loop started before this release isn't moved into a window.** One that reloads into this release starts its project's windows afresh, and leaves its chunk's open claude session, named for its slot, in the session picker. Carrying a slot's session into a window is not worth the code for a one-human audience, so the changelog asks the human to finish or stop every running loop before taking the release.
|
||||
|
||||
Valid while claude takes `--session-id` and resumes by it, and the human runs loop-claude where tmux is installed.
|
||||
|
||||
## loop-claude: the archive keeps the raw transcript, and a failed archive stops the loop
|
||||
|
||||
@@ -268,6 +300,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 each worktree opens its own copy of a record, as loop-claude's side-by-side chunks need.
|
||||
|
||||
- **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>/<worktree>/<record>.version`, since `save` runs in a later process. The store keeps the version itself, so `write` still takes only the text. Every other tool reads and writes a record in one process, and its store keeps the version in memory, so a read by another tool, such as larv-review's, never moves the version an edit in `project-record` rests on. The folder `<worktree>` is named for the worktree that ran `open`, and `open` removes the folders of worktrees git no longer lists, so a chunk's copy doesn't outlive its worktree.
|
||||
- **The page holds ADF, which adf-codec converts both ways**, so a teammate reads the record as Confluence renders it. Where adf-codec cannot convert the markdown, the write fails with adf-codec's error. A node markdown cannot hold reads as text: a mention as its name, a macro as `_(<macro> not included)_`. So the next write replaces it with that text, and a record page should hold only what markdown can.
|
||||
|
||||
## project config: a tool that reads a file's commits says where it does not support that file, and the work goes on
|
||||
|
||||
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:
|
||||
@@ -297,13 +339,17 @@ Messages keep each file's usual name, such as `todo.md`, as its label, since the
|
||||
|
||||
2026-11-14, larv-review, on lilleman's calls of 2026-11-12 and 2026-11-14. Serves goal 1.6: a client's team keeps planning in its own Jira. Valid while a client's plan fits one epic in one Jira project.
|
||||
|
||||
- **One epic is one project's plan, and Jira's backlog rank orders it.** The team sets the rank, so the loop's score doesn't break ties and the loop doesn't reorder anything (lilleman, 2026-11-12). An item is an open child issue; one in a done status category is finished.
|
||||
- **One epic is one project's plan, and Jira's backlog rank orders it.** The team sets the rank, so the loop's score doesn't break ties and the loop never reranks an issue once filed (lilleman, 2026-11-12). An item is an open child issue; one in a done status category is finished.
|
||||
- **A bench of readers picked the spelling.** Three fresh readers, seated as the person who writes a client's `config.toml`, each picked `plan = "jira:https://<site>/browse/<key>"` over the bare address, a `jira:<key>` beside a `jira-site` key, and a `[plan]` table. Each also picked one pair of env-file keys, `ATLASSIAN_EMAIL` and `ATLASSIAN_API_TOKEN`, for Jira and Confluence over a pair for each, since one account's token opens both.
|
||||
- **An item's ID stays a whole number: the issue's number in the epic's Jira project.** About 30 modules read an ID as an int, and the `branch` and title templates already spell a ticket's name, as `ABC-{id}`. So the store refuses a child issue from another Jira project, and counts a blocker only among the plan's own items (`bin/plan_store/jira_epic.py`).
|
||||
- **The scores sit in one issue property, `plan-item`**, which needs no Jira admin (lilleman, 2026-11-12). An issue without it reads as an item nobody scored.
|
||||
- **The release is the earliest Fix Version named as a semver version**, and an issue with none fails the read, naming it, until todo.md's item 359 ties releases to something else.
|
||||
- **The 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 and files, and doesn't edit or finish an issue** until todo.md's items 382 and 383. `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 release is the earliest Fix Version named as a semver version**, and an issue with none fails the read, naming it.
|
||||
- **The loop files an item as a Task under the epic, and marks it as its own** (lilleman's calls of 2026-11-12). `"Filed by": "loop"` in the `plan-item` property tells such an issue from one a person filed, whose summary and description the loop never edits. Task is an issue type every Jira Software project template has; a project without it refuses the issue, saying so. The issue takes the project's Fix Version named as the release, with a leading v or without, and the store refuses an item whose release the project has no Fix Version for, before it files anything. A security finding also gets the label `security`, and its text never holds a secret's value. Jira 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 config states the formula and the bar, and the store ranks a new issue among the loop's own** (lilleman, 2026-11-12 and 2026-11-15). A plan in Jira has no `## Scoring`, so a config whose `plan` names an epic must set `jira-score-formula` and `jira-score-bar`. It fails to load without them, or with a formula that doesn't parse, since no setting a config needs has a default. A bench of readers picked the spelling: three fresh readers, seated as the person who writes a client's `config.toml`, each picked those keys over `jira-score` and `jira-bar`, `score-formula` and `score-bar`, and bare `score` and `bar`. The prefix matches the other Jira-only settings, "formula" says the value is no score, and "score-bar" says what the bar applies to. The store scores the item as `rank_todo.py` scores a row, with the goal weights from the goals file, the decision log and the comprehension history. It refuses an item under the bar that isn't exempt, or one whose Moves names a goal the goals file lacks, before it files anything. Then it ranks the issue just before the first issue the loop filed that ranks after it. A person's issues don't count, so the team's rank of each stays as it is. The order is todo.md's within a release: a question first, then a security finding, then the higher score, with a tie after the older issue. Questions go first because `rank_todo.py` ranks them ahead of security findings, since an answer may change other items (the loop's choice, 2026-11-16). Release doesn't count, since lilleman's call ranks by score among the loop's issues. A rank Jira refuses, or an issue of the loop's that no longer scores, leaves the new issue filed and last, with a note to rank it by hand.
|
||||
- **The store edits and moves only an issue the loop filed, and of an issue a person filed it sets only the scores** (lilleman's calls of 2026-11-12). On its own issue it sets the summary, description, scores and Fix Version in one request, so Jira takes all of an edit or none, and it keeps the label `security` in step with Exempt. Of a person's issue it writes only the `plan-item` property, and a comment: the team's screens don't show the property, so the comment tells the team why the scores changed, and the store refuses the edit without one. The comment's text comes from whoever scores, in the project's `language`. Where Jira takes the edit and then refuses the comment, the edit counts as made, and a note says to post the comment by hand. No edit changes a link, until `todo.md` item 389.
|
||||
- **The loop may re-score a person's issue that already holds scores, and never moves it.** lilleman's calls of 2026-11-12 cover an issue nobody scored, and say nothing of one that holds scores; larv-review chose on 2026-11-16, through todo item 382. A re-score changes only the loop's own reading of the issue, and not what the person wrote, so it is allowed, with a comment as the first scores need. L, E, I and S are set together, so no issue is left partly scored. The Fix Version says when the team ships the issue, and a release is its team's, so the store refuses the move and `CLAUDE.md` has the worker ask the human to move the issue.
|
||||
- **`todo-item edit --comment` carries the comment, and a plan in a file takes the flag and keeps no comment**, so one command works in every project, as goal 1.3 asks. A bench of readers picked the spelling: three fresh readers, seated as the consultant who runs the loop in a client's project, each picked `--comment` over `--reason`, `--why` and `--because`. Only it says the text is posted where the team reads it, and `--reason` read as `--exempt`'s reason.
|
||||
- **The store 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
|
||||
|
||||
@@ -317,7 +363,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.
|
||||
|
||||
@@ -369,6 +415,8 @@ The base is the last measured commit: the default branch's newest merged change
|
||||
|
||||
2026-11-11, lilleman. Serves goal 1.1. Item 296 made `chunk-pr merge` refuse while a scoring run the plan calls is unrecorded on the branch, so a missing run can block a merge. No score or ruling does, and the titles say so: "no score blocks a merge".
|
||||
|
||||
2026-11-15, lilleman, on the worker's proposal in item 374, replacing the call of 2026-11-13. The call asked that a ruling never charge one chunk with another's change, by reading against the new base after a rebase. Only the release review runs a paired ruling, and it measures the whole release, so its base stays the last measured commit. What another chunk's merge changes is the head: a ruling recorded before the merge came in read a head that never merges. So `chunk-pr merge` stops where the default branch has moved since the branch last recorded a paired ruling, and the worker runs the ruling again at the new head.
|
||||
|
||||
## review: the premises chunk's whole review is the human's approval
|
||||
|
||||
2026-09-20, lilleman. Serves goal 1.1. A reviewer's finding on that chunk could only be declined by citing the goals the chunk exists to write. Valid while every decline must name a goal or a technical principle.
|
||||
@@ -532,9 +580,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.
|
||||
|
||||
@@ -554,6 +602,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
|
||||
@@ -660,13 +710,13 @@ Valid while the worker writes the tests that larv-review's reviewers hold to the
|
||||
|
||||
- **The spelling.** A `Touches:` line, then one bullet per file: the path in backticks, then its parts, each a name in backticks or `lines <first>-<last>`, with `(small)` after a part the item changes only a little; a path or a name that holds a backtick takes a longer run of backticks with a space inside each end, as a Markdown code span does. A path alone is the whole file. Three readers seated as the README's audience picked the bulleted list over one line and over a table, since backticks hold a heading's commas, colons and parentheses. Two of the three put `(small)` after the part and outside the backticks, and two left line ranges unquoted. Each picked a different config key: `touch-predictions` was one reader's first choice and the second choice of the other two.
|
||||
- **A part's boundaries.** Python's `ast` module names the innermost function or class, a top-level assignment by the name it sets, and `(module)` for the rest. A Markdown file's parts are its headings outside fenced code. Any other file, and Python that doesn't parse, falls back to line ranges. A table row is no part of its own: the item named one, but the tables chunks collide on are the plan's and the changelog's, which don't count.
|
||||
- **What doesn't count.** The plan and every record the config names, the changelog among them, since every chunk writes them: `todo.md` item 374 writes the plan and the changelog at merge time, and the other records are appended to. `touch-predictions record` leaves them out of what a chunk touched, and the rule keeps them out of predictions.
|
||||
- **The pick.** `chunk-preflight` takes the items of the next release that don't wait, in the plan's order, each where it overlaps neither the next item nor an item taken before it. The call asked for the set that keeps the most chunks running. The plan's order comes first all the same: the largest set could start a low-ranked item in place of one ranked above it, and with more ready items than the parallel limit, either set fills the limit. `todo.md` item 375 takes as many of the picked items as its limit allows.
|
||||
- **What doesn't count.** The plan and every record the config names, the changelog among them, since every chunk writes them: `chunk-pr merge --finish` writes the plan and the changelog at merge time, and the other records are appended to. `touch-predictions record` leaves them out of what a chunk touched, and the rule keeps them out of predictions.
|
||||
- **The pick.** `chunk-preflight` takes the items of the next release that don't wait, in the plan's order, each where it overlaps neither the next item nor an item taken before it. The call asked for the set that keeps the most chunks running. The plan's order comes first all the same: the largest set could start a low-ranked item in place of one ranked above it, and with more ready items than the parallel limit, either set fills the limit. loop-claude starts as many of the picked items as `parallel-chunks` allows.
|
||||
- **An overlap that is taken.** Two items may share a part where either marks it `(small)`. The call takes an overlap only for a small change to the same part, and a few lines re-apply onto whatever the other chunk did to it.
|
||||
- **Which items share a chunk** stays the worker's choice, by the review passes they fire, so the pick names items, and an item the next chunk takes starts no chunk of its own.
|
||||
- **The record is optional.** No path setting has a default, and a mandatory one would stop every project until its owner edits the config (goal 1.6). A project that leaves `touch-predictions` out is still picked for, and keeps no record. The worker runs `touch-predictions record` before it removes the chunk's items (`skills/larv-review/SKILL.md` §5), since the prediction leaves the plan with the item, and a plan in Jira keeps no history to read it back from.
|
||||
|
||||
Valid while `todo.md` item 375 runs chunks by this pick. Once the record holds enough chunks to show how often the predictions miss, an item, not filed yet, revisits the pick's order and the `(small)` rule.
|
||||
Valid while loop-claude starts a project's chunks side by side by this pick (`bin/loop_claude/loop/chunk_windows.py` `may_start`), which also checks each new chunk against the running chunks' items. Once the record holds enough chunks to show how often the predictions miss, an item, not filed yet, revisits the pick's order and the `(small)` rule.
|
||||
|
||||
## 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
|
||||
|
||||
@@ -721,7 +771,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.
|
||||
|
||||
|
||||
@@ -2185,3 +2185,163 @@ Read most (opens and searches):
|
||||
- `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
|
||||
|
||||
## Reading cost, chunk ba82c458ad98, finished 2026-11-15T13:51:17Z
|
||||
|
||||
120652 new input tokens before the first commit.
|
||||
|
||||
Read most (opens and searches):
|
||||
|
||||
- `docs/decisions.md` 10
|
||||
- `bin/loop_claude/test_black_box.py` 8
|
||||
- `bin/loop_claude/loop/usage.py` 5
|
||||
- `CHANGELOG.md` 3
|
||||
- `CLAUDE.md` 3
|
||||
- `bin/claude_code/session.py` 2
|
||||
- `bin/command_lines/shell_command.py` 2
|
||||
- `bin/loop_claude/loop/main.py` 2
|
||||
- `rules/todo-items.md` 2
|
||||
- `README.md` 1
|
||||
|
||||
## Reading cost, chunk 8026e60ea27c, finished 2026-11-15T21:44:03Z
|
||||
|
||||
199967 new input tokens before the first commit.
|
||||
|
||||
Read most (opens and searches):
|
||||
|
||||
- `docs/decisions.md` 11
|
||||
- `bin/chunk_pr/test_chunk_pr.py` 8
|
||||
- `skills/larv-review/SKILL.md` 8
|
||||
- `CLAUDE.md` 5
|
||||
- `README.md` 5
|
||||
- `bin/chunk_pr/main.py` 5
|
||||
- `bin/project_config/templates.py` 4
|
||||
- `rules/todo-items.md` 4
|
||||
- `bin/project_config/main.py` 3
|
||||
- `bin/chunk_pr/approval.py` 2
|
||||
|
||||
## Reading cost, chunk 0851f830bb67, finished 2026-11-15T22:41:58Z
|
||||
|
||||
50560 new input tokens before the first commit.
|
||||
|
||||
Read most (opens and searches):
|
||||
|
||||
- `README.md` 1
|
||||
- `bin/project_config/main.py` 1
|
||||
- `bin/project_config/settings.py` 1
|
||||
- `bin/project_record/main.py` 1
|
||||
- `bin/project_record/test_project_record.py` 1
|
||||
- `docs/decisions.md` 1
|
||||
- `rules/decisions.md` 1
|
||||
- `settings.json` 1
|
||||
|
||||
## Reading cost, chunk a8246f8e9771, finished 2026-11-16T00:48:07Z
|
||||
|
||||
97222 new input tokens before the first commit.
|
||||
|
||||
Read most (opens and searches):
|
||||
|
||||
- `todo.md` 7
|
||||
- `bin/project_config/settings.py` 3
|
||||
- `rules/todo-items.md` 3
|
||||
- `docs/score-anchors.md` 2
|
||||
- `bin/release_plan/release.py` 1
|
||||
- `bin/release_plan/release_standing.py` 1
|
||||
|
||||
## Reading cost, chunk c497e828c613, finished 2026-11-16T01:20:21Z
|
||||
|
||||
171945 new input tokens before the first commit.
|
||||
|
||||
Read most (opens and searches):
|
||||
|
||||
- `bin/todo_item/main.py` 8
|
||||
- `bin/plan_store/jira_epic.py` 6
|
||||
- `README.md` 5
|
||||
- `bin/todo_item/test_todo_item.py` 5
|
||||
- `CLAUDE.md` 4
|
||||
- `bin/plan_store/stores.py` 4
|
||||
- `bin/plan_store/test_jira_epic.py` 4
|
||||
- `docs/decisions.md` 4
|
||||
- `bin/plan_store/contract.py` 3
|
||||
- `bin/plan_store/fakes.py` 3
|
||||
|
||||
## Reading cost, chunk 956d742d7ba4, finished 2026-11-16T02:13:55Z
|
||||
|
||||
276709 new input tokens before the first commit.
|
||||
|
||||
Read most (opens and searches):
|
||||
|
||||
- `bin/plan_store/jira_epic.py` 14
|
||||
- `bin/project_config/test_project_config.py` 8
|
||||
- `bin/plan_store/test_jira_epic.py` 7
|
||||
- `bin/project_config/settings.py` 7
|
||||
- `bin/plan_store/stores.py` 6
|
||||
- `bin/release_plan/ranking.py` 4
|
||||
- `README.md` 3
|
||||
- `bin/larv_review/test_larv_review.py` 3
|
||||
- `bin/project_config/main.py` 3
|
||||
- `bin/release_plan/formula.py` 3
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
paths:
|
||||
- "**/AGENTS.md"
|
||||
- "**/docs/decisions.md"
|
||||
- "**/project-record/*/decisions.md"
|
||||
- "**/project-record/*/*/decisions.md"
|
||||
---
|
||||
|
||||
# Decisions: one home, each linked to a goal or a technical principle
|
||||
|
||||
+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. `todo-item add` files an item there as a new child issue, and `todo-item` can't edit, move or finish 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.
|
||||
- **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. `todo-item --help` says what `edit` and `move` change there. 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.
|
||||
@@ -145,7 +145,7 @@ Launch one principles-auditor on the trigger in §3, so the project is read once
|
||||
|
||||
### Comprehension check
|
||||
|
||||
The comprehension check records how hard the project is for its contributor to read (`~/.claude/rules/goals-and-audience.md`), and no score blocks a merge; only a run the plan calls and the branch lacks does, per "Scoring run". Simulated readers, the seats, launched per `~/.claude/skills/comprehension-panel/SKILL.md`, each read the whole project, not the diff. It reports no findings and is no pass: it runs once, in §5, after every pass is done, the auto-reviewer included, so it reads the branch as review left it. It runs a paired ruling in the release review, even where an opt-out skips its architect, and a scoring run where one is due. It skips only as "Opt-out" or "Suspended" below says.
|
||||
The comprehension check records how hard the project is for its contributor to read (`~/.claude/rules/goals-and-audience.md`), and no score blocks a merge; only a run the plan calls and the branch lacks does, per "Scoring run". Simulated readers, the seats, launched per `~/.claude/skills/comprehension-panel/SKILL.md`, each read the whole project, not the diff. It reports no findings and is no pass: it runs in §5, after every pass is done, the auto-reviewer included, so it reads the branch as review left it. It runs a paired ruling in the release review, even where an opt-out skips its architect, and a scoring run where one is due. It skips only as "Opt-out" or "Suspended" below says.
|
||||
|
||||
**Paired ruling.** Each seat votes whether the project reads better, the same or worse at this branch's head than at the base.
|
||||
|
||||
@@ -153,7 +153,7 @@ The comprehension check records how hard the project is for its contributor to r
|
||||
- **Head.** The head holds `origin/<default branch>`, merged in at §4 step 1, so it differs from the default branch only by this branch's change.
|
||||
- **Seats.** Mid A and the inherited architect. Write what they read and their replies into a votes file in the chunk's review folder, in the shape `~/.claude/bin/larv-review --help` shows, and run `~/.claude/bin/larv-review record-ruling <votes file>`. On `Split:`, launch the maintainability senior and Junior A together, add their lines, and run it again.
|
||||
|
||||
**Scoring run**, when `~/.claude/bin/larv-review needs-scoring-run <the IDs of the items the chunk ships, if any>` prints `Scoring run due:`. Run `needs-scoring-run` before removing the chunk's items from `todo.md`. `chunk-pr merge` refuses until the branch's committed history records every run the plan calls, which `larv-review scoring-run-owed` counts at merge time from the merge base; an earlier due line is only a snapshot.
|
||||
**Scoring run**, when `~/.claude/bin/larv-review needs-scoring-run <the IDs of the items the chunk ships, if any>` prints `Scoring run due:`. `chunk-pr merge` refuses until the branch's committed history records every run the plan calls, which `larv-review scoring-run-owed` counts at merge time from the merge base; an earlier due line is only a snapshot.
|
||||
|
||||
- **Seats.** Junior A, Mid A, the maintainability senior and the inherited architect each score the project at the head from 1 to 10 overall and on four dimensions: Navigation, Locality, Shape and Self-sufficiency. Run `~/.claude/bin/larv-review prepare-scoring`, adding `--preloaded <text>` only where its default list of pre-loaded files is wrong. It makes the worktree the seats read and prints each seat's prompt file; launch each seat with its file's text as its prompt. Write their lines into a scores file and run `~/.claude/bin/larv-review record-scoring <scores file> <the same item IDs>`, which appends the run to the history and prints the four seats' means.
|
||||
- **Floor item.** Where `record-scoring` prints `Floor:`, a `Next:` line follows: file one floor item, or refresh the open one. A floor item is a plan item meant to bring every mean to the project's readability floor, which `record-scoring`'s `Floor:` line names. File it as one ambitious refactor, not touch-ups. It restructures the area behind the places `larv-review places` prints for this run, chosen where they bear on the lowest dimension, sized to bring every mean to that floor, and quotes those places. Its tagline opens with `Reach the comprehension floor:`, so its own chunk runs a scoring run; while a mean stays under the floor, that run's `Next:` line asks for the next floor item. Mark it `owner`, since the human asked that such a project always hold one, so no score deletes it. Put it in the earliest release the plan names after the one the chunk ships into, or else in the next version after that one that `~/.claude/rules/todo-items.md` allows, so the floor doesn't hold up any release. While one is open, refresh its places and aim from the newest run instead of filing another; the item the chunk ships doesn't count as open. Commit it with the run, as "Record" says.
|
||||
@@ -200,9 +200,15 @@ Launch prose-reviewer with what the diff touched and every section this review c
|
||||
## 5. Goal alignment, then merge
|
||||
|
||||
1. Read the finished PR against the goals file's goals and code health, unless that file voids it: does anything in it work against one? It breaks a maintain goal → do not merge; redesign the change or drop its item. It works against an achieve goal → do not merge; ask the human, stating the conflict.
|
||||
2. Run the comprehension check (§3) where it runs; it runs once. When `origin/<default branch>` moves after that, return to §4, and keep the ruling and scoring run already recorded.
|
||||
3. Run `~/.claude/bin/touch-predictions record <ID>...` in the worktree, naming the chunk's items: it records what they were predicted to touch beside what the branch touched, where the project's config names that record. A later pass through this step, after a return to §4, skips it, since the items have left the plan. Then remove the chunk's items from `todo.md` per `~/.claude/CLAUDE.md` → "Working loop" in the branch. Commit and push both; the commit re-enters no pass.
|
||||
4. Aligned and every pass done → **merge** with `~/.claude/bin/chunk-pr merge`, run in the background with its `timeout` set to 7200000 ms, since its wait can outlast the Bash tool's default. It waits for the pull request's checks to pass, and for a human's approval where the project's config sets `wait-for-approval` (`chunk-pr --help`), then takes the first merge method the repository allows on its forge. A repo whose `AGENTS.md` names another method merges that way with the forge's CLI instead, once the pull request's checks pass, `~/.claude/bin/larv-review scoring-run-owed` exits 0 and, where `~/.claude/bin/project-config wait-for-approval` prints `true`, GitHub reports the pull request approved. A repo withholds this in its `AGENTS.md` → leave the PR ready and unmerged, and say which line withheld it.
|
||||
2. Run the comprehension check (§3) where it runs. When `origin/<default branch>` moves after that, return to §4, and keep the scoring run already recorded. Where the chunk recorded a paired ruling, run it again at the new head and record it: it read the head before the other chunk's merge came in.
|
||||
3. Run `~/.claude/bin/touch-predictions record <ID>...` in the worktree, naming the chunk's items: it records what they were predicted to touch beside what the branch touched, where the project's config names that record. A later pass through this step, after a return to §4, skips it. Commit and push it; the commit re-enters no pass. Leave the chunk's items in the plan, and write no changelog bullet in the branch: step 4 does both, so that `todo.md` and `CHANGELOG.md` never conflict between chunks. Revise any decision that cites an item now, since `todo-item finish` refuses while one does.
|
||||
4. Aligned and every pass done → **merge** with `~/.claude/bin/chunk-pr merge`, run in the background with its `timeout` set to 7200000 ms, since its wait can outlast the Bash tool's default. Give it one `--finish <ID>` per item the chunk ships, each with the arguments `todo-item finish` takes (`todo-item --help`), as in `chunk-pr merge --finish 12 --changelog '<bullet>' --finish 13 --no-changelog`. The project's chunks merge one at a time. In its turn, `chunk-pr merge` merges `origin/<default branch>` into the branch, finishes those items, pushes, and waits for the pull request's checks to pass; then it takes the first merge method the repository allows on its forge. Where it stops, do what it asks and run it again with the same arguments:
|
||||
- **A merge conflict.** Resolve it, commit and push. Rerun only the passes whose triggers the resolution's own lines meet (§3), each in a round of its own.
|
||||
- **A paired ruling to run again.** `chunk-pr merge` has merged the default branch in and pushed. Run the ruling at that head, record it, commit and push. Don't return to §4 for it: the next turn waits for the checks at the new head.
|
||||
- **An owed scoring run, or a queue another pull request holds.** Record the run, or wait, as the message says.
|
||||
- **A reviewer's comment**, where the project's config sets `wait-for-approval` (`chunk-pr --help`) and the pull request waits for a human's approval. Answer it in its thread on the forge, and fix what it asks as a finding of the chunk. The wait doesn't hold the queue, so other chunks merge meanwhile.
|
||||
|
||||
A repo whose `AGENTS.md` names another method merges that way with the forge's CLI instead, after it finishes the chunk's items with `todo-item finish` in the branch, and once the pull request's checks pass, `~/.claude/bin/larv-review scoring-run-owed` exits 0 and, where `~/.claude/bin/project-config wait-for-approval` prints `true`, GitHub reports the pull request approved. A repo withholds this in its `AGENTS.md` → leave the PR ready and unmerged, and say which line withheld it.
|
||||
5. Merged → run `~/.claude/bin/chunk-pr clean` in the chunk's worktree, and put a failure it prints in the summary.
|
||||
6. Stop. The next chunk gets a fresh session.
|
||||
|
||||
|
||||
@@ -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,21 +6,12 @@
|
||||
|
||||
`Bar = 0.1`
|
||||
|
||||
`Next ID = 385`
|
||||
`Next ID = 390`
|
||||
|
||||
## Items
|
||||
|
||||
| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |
|
||||
|---|---|---|---|---|---|---|---|---|---|---|---|
|
||||
| 384 | 0.11.0 | | question | **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 |
|
||||
| 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 |
|
||||
| 383 | 0.11.0 | | | **Move a finished item of a Jira plan by the transition, and to the status, that the project's config names.** | 4 | 2 | 3 | 7 | 3 | 1.6 by 3 | 1.0 |
|
||||
| 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 |
|
||||
| 359 | 0.11.0 | | | **Tie a project's releases to what its config names: semver tags, Jira Fix Versions, sprints, or none.** | 3 | 2 | 3 | 6 | 4 | 1.6 by 3 | 0.8 |
|
||||
| 382 | 0.11.0 | | | **Edit a Jira issue the loop filed, and score an unscored issue a teammate filed with a comment saying why.** | 4 | 2 | 3 | 7 | 4 | 1.6 by 3 | 0.8 |
|
||||
| 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 |
|
||||
| 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 |
|
||||
@@ -33,14 +24,16 @@
|
||||
| 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 | 382, 383 | | **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, 383 | | **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, 383 | | **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, 383, 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 |
|
||||
| 389 | 0.12.0 | | decision | **Set a Jira issue's "is blocked by" links from `todo-item edit --blocked-by`, on an issue the loop filed.** | 2 | 2 | 2 | 4 | 4 | 1.6 by 2 | 0.5 |
|
||||
| 365 | 0.13.0 | | | **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 | | | **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 | | | **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 | | | **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 |
|
||||
@@ -49,7 +42,7 @@
|
||||
| 273 | 0.14.0 | | decision | **Re-tune the E + I steps of `REVIEW_STEPS` for 6 to 8 once 10 finished chunks have scored an E + I of 6 or more, from how well E + I orders their review rounds and 🔴 findings.** | 1 | 2 | 2 | 3 | 2 | 1.1 by 2, 1.4 by 3 | 2.0 |
|
||||
| 268 | 0.14.0 | | | **End a run whose release is ready to cut with a notice on loop-claude's terminal, in place of an interrupt that waits for an answer.** | 2 | 2 | 3 | 5 | 3 | 1 by 5 | 1.9 |
|
||||
| 171 | 0.14.0 | | decision | **Group the routing figures' review rounds by the reviewers' rung as well as the worker's, so a call blames a rung only for rounds its own reviews raised.** | 3 | 2 | 2 | 5 | 4 | 1.2 by 3, 1.4 by 3 | 1.8 |
|
||||
| 300 | 0.14.0 | | owner | **Reach the comprehension floor: restructure the places the comprehension seats found hardest to follow, so the project reads at 7.0 or above on every dimension, Locality and Self-sufficiency first; today the scoring run at 8f03747 scored Navigation 6.75, Locality 5.63, Shape 5.75, Self-sufficiency 5.63 and Overall 6.00.** | 4 | 2 | 3 | 7 | 8 | code health by 8 | 1.7 |
|
||||
| 300 | 0.14.0 | | owner | **Reach the comprehension floor: restructure the places the comprehension seats found hardest to follow, so the project reads at 7.0 or above on every dimension, Locality first; today the scoring run at 55235a0 scored Navigation 7.38, Locality 6.13, Shape 6.50, Self-sufficiency 6.50 and Overall 6.50.** | 4 | 2 | 3 | 7 | 8 | code health by 8 | 1.7 |
|
||||
| 264 | 0.14.0 | | | **Report the comprehension seats and the escalated subagents as subagent types of their own in `routing-figures.md`, with their dollars.** | 2 | 2 | 1 | 3 | 3 | 1.4 by 5 | 1.7 |
|
||||
| 323 | 0.14.0 | | | **Count a release review as landed once its pull request has merged, whatever its commits are titled.** | 3 | 2 | 3 | 6 | 3 | 1.4 by 3, 1.5 by 2 | 1.7 |
|
||||
| 342 | 0.14.0 | | | **Research the tooling agents read, search and run commands with once more, and file an item for each tool that cuts tokens a replay shows keep quality.** | 1 | 2 | 1 | 2 | 3 | 1.4 by 3, 1.5 by 2 | 1.7 |
|
||||
@@ -62,6 +55,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 |
|
||||
@@ -80,69 +74,6 @@
|
||||
|
||||
## Details
|
||||
|
||||
### 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.
|
||||
|
||||
Question for lilleman: where does a plan in Jira state its score formula and its bar? A `todo.md` states both under `## Scoring`, as the project's own to tune, and a Jira epic has no such place. One option is two settings in the project's `config.toml`. Another is to rank without a score: security findings first, then by Moves.
|
||||
|
||||
### 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.
|
||||
|
||||
### 383. Move a finished item of a Jira plan by the transition, and to the status, that the project's config names.
|
||||
|
||||
Split from item 352 on 2026-11-15; lilleman's call, 2026-11-12: a finished item moves by the transition and to the status the config names, since each Jira workflow differs. The loop may transition any issue in the epic. A bench of readers, seated as the person who writes a client's `config.toml`, picks the setting's spelling. Once this item and item 382 have shipped, `PlanStore`'s docstring stops saying that `jira_epic` fails an edit or a finish.
|
||||
|
||||
Touches:
|
||||
- `bin/plan_store/jira_epic.py`: `JiraPlan.finish`
|
||||
- `bin/plan_store/test_jira_epic.py`: new tests of `finish`
|
||||
- `bin/project_config/settings.py`: `OPTIONAL`, `ProjectConfig`, `load`
|
||||
- `bin/project_config/main.py`: the help
|
||||
- `bin/todo_item/main.py`: the help
|
||||
|
||||
### 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.
|
||||
|
||||
Where the rebase conflicts, the chunk's worker resolves it, and only the review passes whose triggers the resolution meets rerun (`larv-review` §3). The paired ruling reruns against the new base after every rebase that brought in another chunk's merge. This revises `docs/decisions.md`'s entry on the last measured commit, so a ruling never charges one chunk with another's change. A chunk whose pull request waits for the approvals item 360 waits for stays in the queue without blocking the next one. It resumes in its own session when a review comment arrives, answers it, and goes back to waiting.
|
||||
|
||||
`bin/chunk_preflight/choices.py:80` `forge_of` is a place the comprehension seats found hard: forge code split across tools. Where this item touches it, build on item 287's forge module if that has shipped.
|
||||
|
||||
### 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
|
||||
|
||||
### 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.
|
||||
|
||||
Before starting anything — a worktree, a session, a window — loop-claude checks that tmux is installed at the needed version or later. Where it is missing or older, it stops and names the version it found and the one it needs. The needed version is the oldest that has every tmux command and option loop-claude uses, read from tmux's `CHANGES` file and cited in the decision that records it.
|
||||
|
||||
The config key for the parallel limit is a syntax users write, so a panel seated from the README's audience picks its spelling (`CLAUDE.md` → "Working loop" → "Bench a syntax"). run-heavy already sizes its slots from the machine, at one per 4 CPUs and with memory from `MemTotal`, so a larger VM runs more heavy commands at once without a change here.
|
||||
|
||||
### 319. 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.
|
||||
|
||||
On SWE-bench Verified with Haiku 4.5 and Opus 4.7, handing the strong model the weak model's transcript solved 69.2% at $1.61 a task; starting the strong model fresh solved 79.2% at $0.90 (arXiv 2608.24358, The Handoff Tax). A model switch also rereads the whole context uncached (Claude Code prompt caching docs). A worker that steps from Sonnet 5.5 to Opus 5.5 by `--resume` is the raw handoff; an effort-only step within one model keeps the cache and isn't. The escalated subagent, which starts fresh with the trigger's evidence, already follows the pattern that won.
|
||||
@@ -220,6 +151,15 @@ Add a `larv-review` subcommand that prints a round title's prefix, up to and inc
|
||||
|
||||
Left with the model: the summary after the `;`, and answering the findings.
|
||||
|
||||
### 389. Set a Jira issue's "is blocked by" links from `todo-item edit --blocked-by`, on an issue the loop filed.
|
||||
|
||||
Filed by item 382's chunk on 2026-11-16. `JiraPlan.edit` refuses an edit of Blocked by, saying to link the issue in Jira, so a worker cannot mark an item it filed as blocked once it exists. Read each link's id from the search's `issuelinks`, make a link per new blocker as `add` does, and delete one per blocker removed, after `missing_blocker`'s check. Say in `docs/decisions.md` whether the loop may link an issue a person filed; the decision on the Jira epic as a plan says the loop writes only the scores of such an issue.
|
||||
|
||||
Touches:
|
||||
- `bin/plan_store/jira_epic.py`: `Issue`, `issue_of`, `JiraPlan.edit`, `revision_of`
|
||||
- `bin/plan_store/test_jira_epic.py`: `Editing`
|
||||
- `bin/todo_item/main.py`: the help
|
||||
|
||||
### 365. 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.
|
||||
|
||||
lilleman's call, 2026-11-12: 0.10.0 and 0.11.0 switch the history tools off for a plan outside the checkout, and 0.13.0 holds only their ports. In Jira a dropped item, which `Drop item` commit titles mark today, is an issue resolved by a resolution the config names.
|
||||
@@ -275,6 +215,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.
|
||||
@@ -339,28 +285,27 @@ Releases are the human's, and `CLAUDE.md` → "Working loop" already ends the lo
|
||||
|
||||
Raised by the goals audit of PR #296. `bin/routing_figures/calls.py` groups a chunk's review rounds by the rung its worker started on, and calls for a routing change when a lower rung took more of them. Since PR #296 the reviewers may run above the worker's rung, on the one their item's E + I picks, and no figure groups rounds by it, though the archived worker line names the E + I it follows from. A cheap worker on an item of high E + I gets stronger reviewers, who may raise more rounds, and a call could then blame the worker's rung for them: an interrupt of lilleman that settles nothing (goal 1.2).
|
||||
|
||||
### 300. Reach the comprehension floor: restructure the places the comprehension seats found hardest to follow, so the project reads at 7.0 or above on every dimension, Locality and Self-sufficiency first; today the scoring run at 8f03747 scored Navigation 6.75, Locality 5.63, Shape 5.75, Self-sufficiency 5.63 and Overall 6.00.
|
||||
### 300. Reach the comprehension floor: restructure the places the comprehension seats found hardest to follow, so the project reads at 7.0 or above on every dimension, Locality first; today the scoring run at 55235a0 scored Navigation 7.38, Locality 6.13, Shape 6.50, Self-sufficiency 6.50 and Overall 6.50.
|
||||
|
||||
Filed by the comprehension check of PR #473 at 13d1550 (`larv-review record-scoring`), which printed `Floor:` and `Next:`, and refreshed from the second run of PR #520 at 8f03747. The lowest means are Locality and Self-sufficiency, 5.63 each: the seats name state shared across modules, such as the route and the archive order, and reasons that sit in `docs/decisions.md`, `CLAUDE.md` or `skills/larv-review/SKILL.md` rather than beside the code. Refresh this item's places and aim from the newest run before the chunk starts; do not file a second floor item.
|
||||
Filed by the comprehension check of PR #473 at 13d1550 (`larv-review record-scoring`), which printed `Floor:` and `Next:`, and refreshed from the two runs of PR #560 at 55235a0. The lowest mean is Locality, 6.13 in both runs: the seats name rules held partly in agent-facing prose and partly in code, and state that one unit can't be read without three others open. Self-sufficiency and Shape follow at 6.50. Refresh this item's places and aim from the newest run before the chunk starts; do not file a second floor item.
|
||||
|
||||
Aim: one ambitious refactor of the areas below, sized so every mean reaches 7.0 on the chunk's own scoring run. Where a place is already easier to read when the chunk starts, drop it.
|
||||
|
||||
Places the seats named, hardest first (`larv-review places`):
|
||||
Places the seats named, hardest first (`larv-review places`), Locality first:
|
||||
|
||||
- Locality, Self-sufficiency: `bin/loop_claude/routing.py:93` `unfinished_route`, with `escalated_route`: the floor, the cap counted from `item_rung`, the escalation mark, the unfinished count and the E + I taken in are held at once across four files, and why they combine sits in the decision log. Every seat named it; three would least want to change it.
|
||||
- Shape, Self-sufficiency: `bin/release_plan/release_standing.py:168` `next_release`, with `standing`: `str | None | Failure` fields in `LastCut`, the `BEFORE_FIRST_RELEASE` sentinel and `nothing_cut` meet in the `is_earliest` test, read as truth tables; four tools choose the next release through it.
|
||||
- Locality: `bin/loop_claude/cycle/run.py:154` `rule`, with `:67` `run_cycle` and `:94` `archived`: archives twice in an order that matters and that nothing enforces, the archive helpers sit in the cycle runner though `loop/close.py` imports them, and `run_cycle` replaces `cycle.route` outside the state machine.
|
||||
- Shape: `bin/release_plan/ranking.py:47` `rank`, `:134` `weigh`, `:229` `score` and `:240` `weight_of`: every function forks on `SHAPE` versus `OLD_SHAPE`, and the constants' reasons are only "docs/decisions.md records the choice".
|
||||
- Shape: `bin/rule_hook/todo_check.py:22` `todo_breaches`, with `:42` `folder_breaches`: three paths, `held()` beside `located()`, the checkout's own script only under `same_repo`, and a blob hashed by hand.
|
||||
- Locality, Self-sufficiency: `bin/larv_review/plan.py:66` `plan_reasons` and `bin/larv_review/owed.py:46` `shortfall`: the rule for when a scoring run is due is split between the 155-line help and the code, and the number owed hangs on the wording `EMPTIED_WORDS`.
|
||||
- Self-sufficiency: `bin/loop_claude/cycle/judge.py:21` `INTERRUPT_RULES`, with `:196` `quotes_checked`: behaviour held in prompt text and schema descriptions the code can't explain, and prompts that quote `CLAUDE.md` wording.
|
||||
- Self-sufficiency: `skills/larv-review/SKILL.md:82` "Round cap": dense rules that point at `CLAUDE.md`, `review-findings.md` and the rules files, read three times before the code matched.
|
||||
- Self-sufficiency: `bin/rule_hook/round_cap.py:26` `earlier_titles`: fails open on the unattended path where git cannot list the branch's titles, and the round title is spelt by hand in SKILL.md, `larv_review/main.py` and `reviewer_header.py` beside `round_titles.py`.
|
||||
- Locality, Shape: `bin/chunk_preflight/choices.py:80` `forge_of`: forge identity and forge calls live in two tool packages, so a second forge lands in three.
|
||||
- Navigation, Shape: `README.md:131` `bin/`: about 63 entries at one level, the shared libraries told apart only by README prose.
|
||||
- Shape: `bin/loop_claude/loop/reload.py:220` `decoded_route`: one dense guard, and renaming a `LoopRun` field stops a running loop.
|
||||
- Shape: `README.md:3` trial folders: four finished experiments at the root beside the working areas.
|
||||
- Self-sufficiency: the seats on this run name the decision-log titles that code cites for a constant's reason (`routing: …` in `routing.py`, `ladder.py`, `judge.py`) as the largest cost; state each reason beside its constant.
|
||||
- Locality, Self-sufficiency: `bin/release_plan/release_standing.py:176` `next_release`, with `:162` `carried`: the cut from a tag, a dated heading or `BEFORE_FIRST_RELEASE`, release names replayed from the plan's history, and renames meet in the `is_earliest` test at `:198`; `carried` is reapplied in `chunk_item` and in `chunk_preflight/choices.py` `planned`, one relying on `zip` keeping order. All eight seats named it; four would least want to change it.
|
||||
- Locality: `bin/loop_claude/routing.py:116` `unfinished_route`, with `:131` `escalated_route`: five rungs, the unfinished count and the escalation mark, which spans `escalation_mark.py`, `judge.py`, `verdicts.py`, `route.py` and `reload.py`. Seven seats named it; the module table is what makes it readable.
|
||||
- Locality: `bin/chunk_pr/main.py:298` `merged`, with `:384` `levelled_and_finished` and `:407` `finished`: a loop around the queue turn binds `done` only under some `if ready` branches, the approval wait is a fall-through, and `finished` destructures five subprocess results by position.
|
||||
- Locality: `skills/larv-review/SKILL.md:82` "Round cap" and `:90` "Re-entry", with `bin/review_rules/round_titles.py:45` and `:63` `past_cap`, `bin/rule_hook/round_cap.py:10` and `bin/larv_review/reviewer_header.py:73`: the round cap lives in five places, and SKILL.md's Done, Cap, Re-entry and Mechanical answers point at each other as prose.
|
||||
- Locality: `bin/loop_claude/loop/chunk_windows.py:107` `start_chunks`: under one flock it checks the session's owner, splits running from stopped windows, computes the room, reads the plan with a fallback, gathers held items and filters again, with the limit applied a second time in `may_start`.
|
||||
- Shape, Locality: `bin/release_plan/ranking.py:239` `score`, `:144` `weigh` and `:250` `weight_of`: every function forks on `SHAPE` versus `OLD_SHAPE`, and one Score depends on five inputs held in other files.
|
||||
- Locality, Shape: `bin/plan_store/stores.py:1` and `bin/release_plan/todo_table.py:1`: `release_plan` and `plan_store` import each other, the plan has three names, and the goals file sits under `release_plan`.
|
||||
- Shape: `bin/larv_review/plan.py:22` `scoring_run_due`, with `owed.py`, `unmeasured.py` and `scoring.py`: the scoring-run trigger is spread over four modules, three of whose names don't say it, in a flat 14-module package that mixes rounds, the comprehension check and its triggers.
|
||||
- Self-sufficiency: `bin/loop_claude/cycle/judge.py:22` `INTERRUPT_RULES`, with `:197` `quotes_checked`: the judge's behaviour is held partly in prompt text and field metadata and partly in Python checks.
|
||||
- Shape: `bin/plan_store/jira_epic.py:356` `revision_of`: indexes the untyped tuple `scores` at `:530` returns by position.
|
||||
- Shape: `bin/loop_claude/cycle/run.py:55` `Cycle.todo`, `bin/loop_claude/hand_over.py:23` `hand_over` and `bin/release_plan/named_code.py:5`: names that say todo.md where the plan may be a Jira epic, a handover that is not the reload's, and a module with no code in it.
|
||||
- Navigation, Shape: `README.md:197` the `bin/` package list: 74 entries at one level, with the README's list as the only index.
|
||||
- Self-sufficiency: every seat names the decision-log titles that code cites for a reason (`routing.py:1`, `ranking.py:20`, `loop/routing_check.py:1`) as a cost; state each reason beside its constant and keep the citation as a footnote.
|
||||
|
||||
Scored L 4 because the refactor touches several components that hold known defects, E 2 because review and a manual check see a regression, I 3 because every session runs these tools. The chunk runs a scoring run, since it is a floor item.
|
||||
|
||||
@@ -431,6 +376,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