Compare commits
112 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 3c85562bb9 | |||
| 242f87a9b3 | |||
| 8d24f73971 | |||
| 2fc9f7212c | |||
| 31da587415 | |||
| 79e0f755e2 | |||
| fde2718a97 | |||
| a06a6dec22 | |||
| 8deef3b4ac | |||
| ba0356adae | |||
| a7a6640ea1 | |||
| 50ce373c40 | |||
| fda61ac06e | |||
| ba21a1efcd | |||
| a60bfdbc1c | |||
| f58250d0ce | |||
| 3f7d85c48e | |||
| 64454f86a8 | |||
| b62dea42fc | |||
| d01d0d421e | |||
| f2b7eb7fd2 | |||
| a921b08207 | |||
| e2c4e94cb2 | |||
| 251b0e8f02 | |||
| bac9cf9756 | |||
| 880d0c6342 | |||
| 068ab77ce3 | |||
| 4985e6a2a9 | |||
| 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 |
+5
-4
@@ -30,6 +30,8 @@
|
||||
!bin/adf_codec/node_shim/package-lock.json
|
||||
!bin/adf_codec/node_shim/package.json
|
||||
!bin/adf_codec/node_shim/shim.mjs
|
||||
!bin/atlassian/
|
||||
!bin/atlassian/*.py
|
||||
!bin/branch_chunks/
|
||||
!bin/branch_chunks/*.py
|
||||
!bin/chunk-pr
|
||||
@@ -67,19 +69,20 @@
|
||||
!bin/loop_state/*.py
|
||||
!bin/machine_load/
|
||||
!bin/machine_load/*.py
|
||||
!bin/mattermost_dm/
|
||||
!bin/mattermost_dm/*.py
|
||||
!bin/metric-bench
|
||||
!bin/metric_bench/
|
||||
!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
|
||||
!bin/notifier/
|
||||
!bin/notifier/*.py
|
||||
!bin/notify
|
||||
!bin/plan/
|
||||
!bin/plan/*.py
|
||||
!bin/plan_store/
|
||||
!bin/plan_store/*.py
|
||||
!bin/project-config
|
||||
@@ -125,8 +128,6 @@
|
||||
!bin/score_outcomes/*.py
|
||||
!bin/settings_filter.py
|
||||
!bin/setup.cfg
|
||||
!bin/slack_dm/
|
||||
!bin/slack_dm/*.py
|
||||
!bin/statusline.py
|
||||
!bin/subagent-rung
|
||||
!bin/subagent_rung/
|
||||
|
||||
+14
-2
@@ -2,12 +2,19 @@
|
||||
|
||||
## Unreleased
|
||||
|
||||
- `adf_codec.convert` can now convert ADF to markdown and back without losing a block's `localId` or the empty paragraphs Jira uses for spacing, so a Jira or Confluence document read and saved back unedited comes back identical: `markdown_to_adf_lossless`, `adf_to_markdown_lossless` and `adfs_to_markdown_lossless`. No tool calls them yet.
|
||||
- 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.
|
||||
- CLAUDE.md, the todo-items rule, and loop-claude's worker and judge prompts and `--help` 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.
|
||||
- A project's config may set `tooling-on-host = true`, so the loop runs a legacy project's language runtime, package manager, tests and task runner directly on the host.
|
||||
- A project's config may set `readability-floor` to a number from 1 to 10: the comprehension score under which code health is very important. It is 7.0 where left out.
|
||||
@@ -22,11 +29,16 @@
|
||||
- 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's `run-heavy` rule also refuses a heavy command run through `uv run`, `poetry run`, `sudo` or `doas` outside `run-heavy`, such as `uv run mutmut run` or `sudo docker build`. Run it as `~/.claude/bin/run-heavy uv run mutmut run`.
|
||||
- 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 and finishes an item but doesn't edit or move one yet. Two open the file itself: whoever plans a release, to compare Scores across releases, which `todo-item list` doesn't print; and whoever edits `## Scoring` or `## Renamed`, or reshapes an old table.
|
||||
- **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.
|
||||
@@ -97,7 +98,7 @@ The rules only reviewers apply, for quality, comments, READMEs and prose, are th
|
||||
- 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.
|
||||
|
||||
@@ -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, 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/`; `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.
|
||||
|
||||
@@ -105,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.
|
||||
@@ -120,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 an issue yet. `todo-item edit` and `move` fail, so edit its issues in Jira. For `todo-item finish`, the config names the workflow transition that finishes an item and the status it leads to, both as Jira shows them: `jira-finish-transition = "Mark as done"` and `jira-finish-status = "Done"`. Finish then moves the item's issue by that transition. It refuses a transition that leads to another status, or to one Jira doesn't count as done, and fails where the config sets neither. `todo-item add` needs the item's release among the Jira project's Fix Versions, named as `1.2.0` or `v1.2.0`. `rank_todo.py` doesn't rank it, since Jira's backlog does. The four things not supported for a plan outside the checkout, above, are not supported for a plan in Jira either.
|
||||
A 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.
|
||||
|
||||
@@ -136,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:
|
||||
@@ -162,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.
|
||||
@@ -183,17 +189,18 @@ 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.
|
||||
|
||||
`bin/` is the import root: each launcher puts it on `sys.path`, so a module imports another by its path under `bin/`, such as `from claude_code.entries import parse_entry`. Each tool's package holds its tests. Beside the packages, `bin/`'s root holds only the launchers, the tools of one file with their tests, `test_env.py`, `failure.py` and `setup.cfg`. `failure.py`'s `Failure`, which modules across `bin/` return for a failed step, belongs to no single package. `branch_chunks/`, `claude_code/`, `command_lines/`, `git_cli/`, `loop_effects/`, `loop_state/`, `machine_load/`, `model_routing/`, `notifier/`, `plan_store/`, `record_store/`, `release_plan/`, `review_rules/`, `rung_replay/`, `text_files/` and `transcript_archive/` serve more than one tool.
|
||||
`bin/` is the import root: each launcher puts it on `sys.path`, so a module imports another by its path under `bin/`, such as `from claude_code.entries import parse_entry`. Each tool's package holds its tests. Beside the packages, `bin/`'s root holds only the launchers, the tools of one file with their tests, `test_env.py`, `failure.py` and `setup.cfg`. `failure.py`'s `Failure`, which modules across `bin/` return for a failed step, belongs to no single package. `atlassian/`, `branch_chunks/`, `claude_code/`, `command_lines/`, `git_cli/`, `loop_effects/`, `loop_state/`, `machine_load/`, `model_routing/`, `notifier/`, `plan/`, `plan_store/`, `record_store/`, `release_plan/`, `review_rules/`, `rung_replay/`, `text_files/` and `transcript_archive/` serve more than one tool. No package imports one that imports it back, which `repo_checks/test_package_cycles.py` checks.
|
||||
|
||||
- `adf_codec/` converts markdown to ADF, the rich text of Jira Cloud and Confluence, and back, in a throwaway container running a pinned `@larvit/adf-codec`. It builds the container's image inside a heavy slot.
|
||||
- `atlassian/` holds what the Jira and Confluence backends share (`client.py`): one Atlassian account's credentials, the request both backends send, and each service's error messages.
|
||||
- `branch_chunks/` cuts a default branch into chunks and finds, for each, the items it shipped and the later chunks that fixed its code, for `score_outcomes` and `routing_figures`. It imports `reading_cost`'s record path.
|
||||
- `command_lines/` reads a shell command: its simple commands, and a docker call's subcommand and memory limits, for `command_patterns`, `reading_cost`, `routing_figures`, `rule_hook` and `run_heavy`.
|
||||
- `chunk_pr` imports `deploy_release`'s forge calls, and `forge_of` as `deploy_release` does.
|
||||
- `command_lines/` reads a shell command: its simple commands, and a docker call's subcommand and memory limits, for `command_patterns`, `reading_cost`, `routing_figures`, `rule_hook` and `run_heavy`.
|
||||
- `deploy_release` imports `chunk_preflight`'s `forge_of`, which tells a GitHub origin from a Gitea one, and `release_plan`'s `release_standing`.
|
||||
- `git_cli/` runs git for every tool (`git_repo.py`), and reads the git calls in a shell command (`git_command.py`).
|
||||
- `judge_replay` imports `loop_claude`'s judge, verdicts, premises and records.
|
||||
@@ -201,14 +208,15 @@ 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.
|
||||
- `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.
|
||||
- `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`. Its backends are `mattermost.py` and `slack.py`.
|
||||
- `plan/` is the plan's core, and imports neither `plan_store` nor `release_plan`. It holds an item and the items table's format (`todo_table.py`), releases (`release.py`), the ranking (`ranking.py`, with its score formula in `formula.py` and its blocker order in `blockers.py`), the paths an item's text names (`named_paths.py`) and `citations.py`, which holds `todo.md` and `docs/decisions.md` to each other. `goals_file.py` reads the goals file's sections, goals and goal weights, for the ranking and for `loop_claude`'s premises.
|
||||
- `plan_store/` reads and writes a project's plan through the store the project's config names (`stores.py`). Every backend meets `plans.py`'s `PlanStore`: a markdown file (`todo_md.py`, which also ranks and checks the file in place, with its text edits in `markdown_edits.py`) or a Jira epic (`jira_epic.py`). `scoring.py` reads the goal weights that both backends rank by. `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`): 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`.
|
||||
- `release_plan/` says which release is next and whether it is ready to cut (`release_standing.py`), from the plan, the changelog and the tags, and picks the item the next chunk takes first (`next_chunk.py`), for `chunk_preflight` and `loop_claude`.
|
||||
- `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`, `plan_store` and `record_store`.
|
||||
- `rest_client/` sends a JSON request to a REST API and reads its credentials from an env file, for `notifier`, `atlassian` 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.
|
||||
|
||||
+40
-10
@@ -1,6 +1,10 @@
|
||||
"""Converts markdown to ADF (Atlassian Document Format, the rich text of Jira Cloud and Confluence) and back.
|
||||
|
||||
It runs @larvit/adf-codec, a Node package, in a throwaway container that holds node_shim/shim.mjs; the shim's header says what its exit status means.
|
||||
|
||||
adf-codec has two pairs of calls, and each function here names the one it runs:
|
||||
- The lossless pair, `*_lossless`, for a document that already exists in Jira or Confluence and is edited and saved back. It keeps each block's localId and the empty paragraphs Jira uses for spacing, so a document read and saved unedited comes back identical.
|
||||
- The portable pair, with no suffix, for new text written from scratch, and for markdown shown to a person. It drops the localId and the empty paragraphs, so saving a document that exists changes it.
|
||||
"""
|
||||
import contextlib
|
||||
import dataclasses
|
||||
@@ -31,7 +35,7 @@ class Ran:
|
||||
err: str
|
||||
|
||||
|
||||
# Runs the shim in the given mode (`to-adf` or `to-markdown`) on a text, or fails to run it.
|
||||
# Runs the shim in the given mode (`to-adf`, `to-markdown`, `to-adf-lossless` or `to-markdown-lossless`) on a text, or fails to run it.
|
||||
Run = typing.Callable[[str, str], Ran | Failure]
|
||||
# Runs a docker command line on a text, in at most the given seconds, or fails to run it.
|
||||
Docker = typing.Callable[[list[str], str, int], Ran | Failure]
|
||||
@@ -149,9 +153,8 @@ def refusal(out: str) -> Refused | Failure:
|
||||
return Failure(f"the adf-codec shim refused with output that is not an error: {out.strip()}")
|
||||
|
||||
|
||||
def markdown_to_adf(markdown: str, run: Run = container_run) -> dict[str, typing.Any] | Failure:
|
||||
"""The ADF document for the markdown."""
|
||||
out = answer("to-adf", markdown, run)
|
||||
def to_adf(mode: str, markdown: str, run: Run) -> dict[str, typing.Any] | Failure:
|
||||
out = answer(mode, markdown, run)
|
||||
if isinstance(out, Refused):
|
||||
return out.failure
|
||||
if isinstance(out, Failure):
|
||||
@@ -163,11 +166,10 @@ def markdown_to_adf(markdown: str, run: Run = container_run) -> dict[str, typing
|
||||
return document
|
||||
|
||||
|
||||
def adfs_to_markdown(documents: list[dict[str, typing.Any]], run: Run = container_run) -> list[str] | Refused | Failure:
|
||||
"""The markdown for each ADF document, in their order, from one container run, so a caller with many documents pays one container start."""
|
||||
def to_markdowns(mode: str, documents: list[dict[str, typing.Any]], run: Run) -> list[str] | Refused | Failure:
|
||||
if not documents:
|
||||
return []
|
||||
out = answer("to-markdown", json.dumps(documents), run)
|
||||
out = answer(mode, json.dumps(documents), run)
|
||||
if isinstance(out, Refused) and not 0 <= out.index < len(documents):
|
||||
return Failure(f"the adf-codec shim refused a document at index {out.index}, past the {len(documents)} it was handed")
|
||||
if isinstance(out, Refused | Failure):
|
||||
@@ -181,9 +183,37 @@ def adfs_to_markdown(documents: list[dict[str, typing.Any]], run: Run = containe
|
||||
return texts
|
||||
|
||||
|
||||
def adf_to_markdown(document: dict[str, typing.Any], run: Run = container_run) -> str | Failure:
|
||||
"""The markdown for the ADF document."""
|
||||
texts = adfs_to_markdown([document], run)
|
||||
def one_markdown(texts: list[str] | Refused | Failure) -> str | Failure:
|
||||
if isinstance(texts, Refused):
|
||||
return texts.failure
|
||||
return texts if isinstance(texts, Failure) else texts[0]
|
||||
|
||||
|
||||
def markdown_to_adf(markdown: str, run: Run = container_run) -> dict[str, typing.Any] | Failure:
|
||||
"""The ADF document for the markdown, by the portable pair."""
|
||||
return to_adf("to-adf", markdown, run)
|
||||
|
||||
|
||||
def markdown_to_adf_lossless(markdown: str, run: Run = container_run) -> dict[str, typing.Any] | Failure:
|
||||
"""The ADF document for the markdown, by the lossless pair."""
|
||||
return to_adf("to-adf-lossless", markdown, run)
|
||||
|
||||
|
||||
def adfs_to_markdown(documents: list[dict[str, typing.Any]], run: Run = container_run) -> list[str] | Refused | Failure:
|
||||
"""The markdown for each ADF document, in their order, by the portable pair, from one container run, so a caller with many documents pays one container start."""
|
||||
return to_markdowns("to-markdown", documents, run)
|
||||
|
||||
|
||||
def adfs_to_markdown_lossless(documents: list[dict[str, typing.Any]], run: Run = container_run) -> list[str] | Refused | Failure:
|
||||
"""The markdown for each ADF document, in their order, by the lossless pair, from one container run."""
|
||||
return to_markdowns("to-markdown-lossless", documents, run)
|
||||
|
||||
|
||||
def adf_to_markdown(document: dict[str, typing.Any], run: Run = container_run) -> str | Failure:
|
||||
"""The markdown for the ADF document, by the portable pair."""
|
||||
return one_markdown(adfs_to_markdown([document], run))
|
||||
|
||||
|
||||
def adf_to_markdown_lossless(document: dict[str, typing.Any], run: Run = container_run) -> str | Failure:
|
||||
"""The markdown for the ADF document, by the lossless pair."""
|
||||
return one_markdown(adfs_to_markdown_lossless([document], run))
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
// Converts between markdown and ADF with @larvit/adf-codec's portable calls. The mode is the one argument:
|
||||
// Converts between markdown and ADF with @larvit/adf-codec. The mode is the one argument:
|
||||
// to-adf stdin is markdown, stdout is the ADF document as JSON
|
||||
// to-markdown stdin is a JSON array of ADF documents, stdout a JSON array of their markdown texts, in their order
|
||||
// to-adf-lossless, to-markdown-lossless the same, through adf-codec's lossless pair in place of its portable pair
|
||||
// Exit 0: stdout holds the answer. Exit 2: adf-codec refused the input, and stdout holds {"error": {code, message, path, position?}},
|
||||
// with "index", the refused document's place in the array, beside "error" in to-markdown.
|
||||
// Exit 1: the shim could not run, and stderr says why.
|
||||
import { adfToPortableMarkdown, portableMarkdownToAdf } from '@larvit/adf-codec'
|
||||
import { adfToLosslessMarkdown, adfToPortableMarkdown, losslessMarkdownToAdf, portableMarkdownToAdf } from '@larvit/adf-codec'
|
||||
|
||||
const REFUSED = 2
|
||||
|
||||
@@ -19,17 +20,17 @@ function refuse(refusal) {
|
||||
return REFUSED
|
||||
}
|
||||
|
||||
function toAdf(markdown) {
|
||||
const result = portableMarkdownToAdf(markdown)
|
||||
function toAdf(convert, markdown) {
|
||||
const result = convert(markdown)
|
||||
if (!result.ok) return refuse({ error: result.error })
|
||||
process.stdout.write(JSON.stringify(result.value))
|
||||
return 0
|
||||
}
|
||||
|
||||
function toMarkdown(documents) {
|
||||
function toMarkdown(convert, documents) {
|
||||
const texts = []
|
||||
for (const [index, document] of documents.entries()) {
|
||||
const result = adfToPortableMarkdown(document)
|
||||
const result = convert(document)
|
||||
if (!result.ok) return refuse({ index, error: result.error })
|
||||
texts.push(result.value)
|
||||
}
|
||||
@@ -39,9 +40,11 @@ function toMarkdown(documents) {
|
||||
|
||||
async function main(mode) {
|
||||
const input = await readStdin()
|
||||
if (mode === 'to-adf') return toAdf(input)
|
||||
if (mode === 'to-markdown') return toMarkdown(JSON.parse(input))
|
||||
throw new Error(`mode must be to-adf or to-markdown, not ${mode}`)
|
||||
if (mode === 'to-adf') return toAdf(portableMarkdownToAdf, input)
|
||||
if (mode === 'to-adf-lossless') return toAdf(losslessMarkdownToAdf, input)
|
||||
if (mode === 'to-markdown') return toMarkdown(adfToPortableMarkdown, JSON.parse(input))
|
||||
if (mode === 'to-markdown-lossless') return toMarkdown(adfToLosslessMarkdown, JSON.parse(input))
|
||||
throw new Error(`mode must be to-adf, to-adf-lossless, to-markdown or to-markdown-lossless, not ${mode}`)
|
||||
}
|
||||
|
||||
main(process.argv[2]).then(
|
||||
|
||||
@@ -66,6 +66,36 @@ def test_adf_to_markdown_returns_the_text_of_its_one_document():
|
||||
assert run.calls == [("to-markdown", json.dumps([DOC]))]
|
||||
|
||||
|
||||
def test_markdown_to_adf_lossless_runs_the_lossless_mode():
|
||||
run = fake(0, json.dumps(DOC))
|
||||
assert convert.markdown_to_adf_lossless("Hi\n", run) == DOC
|
||||
assert run.calls == [("to-adf-lossless", "Hi\n")]
|
||||
|
||||
|
||||
def test_adfs_to_markdown_lossless_sends_every_document_in_one_lossless_run():
|
||||
run = fake(0, json.dumps(["a\n", "b\n"]))
|
||||
assert convert.adfs_to_markdown_lossless([DOC, DOC], run) == ["a\n", "b\n"]
|
||||
assert run.calls == [("to-markdown-lossless", json.dumps([DOC, DOC]))]
|
||||
|
||||
|
||||
def test_adf_to_markdown_lossless_returns_the_text_of_its_one_document():
|
||||
run = fake(0, json.dumps(["a\n"]))
|
||||
assert convert.adf_to_markdown_lossless(DOC, run) == "a\n"
|
||||
assert run.calls == [("to-markdown-lossless", json.dumps([DOC]))]
|
||||
|
||||
|
||||
def test_adfs_to_markdown_lossless_names_a_refused_documents_index():
|
||||
refusal = {"index": 1, "error": {"code": "not-an-adf-document", "message": "no type", "path": []}}
|
||||
refused = convert.adfs_to_markdown_lossless([DOC, DOC], fake(2, json.dumps(refusal)))
|
||||
assert refused == convert.Refused(1, Failure("adf-codec refused the input with not-an-adf-document: no type (at the document)"))
|
||||
|
||||
|
||||
def test_adfs_to_markdown_lossless_of_no_documents_runs_no_container():
|
||||
run = fake(1)
|
||||
assert convert.adfs_to_markdown_lossless([], run) == []
|
||||
assert run.calls == []
|
||||
|
||||
|
||||
def test_a_refusal_becomes_a_failure_with_adf_codecs_code_and_message():
|
||||
refusal = {"error": {"code": "malformed-pipe-table", "message": "row has too many cells", "path": [], "position": {"line": 3, "offset": 9}}}
|
||||
failure = convert.markdown_to_adf("| a |\n", fake(2, json.dumps(refusal)))
|
||||
@@ -279,3 +309,28 @@ def test_round_trip_through_the_real_container():
|
||||
assert isinstance(second, convert.Refused) and second.index == 1 and "not-an-adf-document" in second.failure.reason
|
||||
crashed = convert.answer("to-markdown", "not json", convert.container_run)
|
||||
assert isinstance(crashed, Failure) and crashed.reason.startswith("the adf-codec shim failed with exit 1: ")
|
||||
|
||||
|
||||
# A Jira description as Jira stores it: every block carries a localId, and an empty paragraph spaces two blocks.
|
||||
JIRA_DESCRIPTION = {
|
||||
"type": "doc", "version": 1, "content": [
|
||||
{"type": "heading", "attrs": {"level": 2, "localId": "h-1"}, "content": [{"type": "text", "text": "Goal"}]},
|
||||
{"type": "paragraph", "attrs": {"localId": "p-1"}, "content": [{"type": "text", "text": "Keep "}, {"type": "text", "text": "this", "marks": [{"type": "strong"}]}]},
|
||||
{"type": "paragraph", "attrs": {"localId": "p-2"}},
|
||||
{"type": "bulletList", "attrs": {"localId": "l-1"}, "content": [
|
||||
{"type": "listItem", "attrs": {"localId": "i-1"}, "content": [{"type": "paragraph", "attrs": {"localId": "p-3"}, "content": [{"type": "text", "text": "one"}]}]},
|
||||
]},
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.skipif(shutil.which("docker") is None or subprocess.run(["docker", "info"], capture_output=True, timeout=20).returncode != 0, reason="needs a docker daemon")
|
||||
def test_the_lossless_pair_gives_back_a_jira_description_identical_and_the_portable_pair_does_not():
|
||||
markdown = convert.adf_to_markdown_lossless(JIRA_DESCRIPTION)
|
||||
assert isinstance(markdown, str)
|
||||
assert convert.markdown_to_adf_lossless(markdown) == JIRA_DESCRIPTION
|
||||
assert convert.adfs_to_markdown_lossless([JIRA_DESCRIPTION, JIRA_DESCRIPTION]) == [markdown, markdown]
|
||||
portable = convert.markdown_to_adf(convert.adf_to_markdown(JIRA_DESCRIPTION))
|
||||
assert portable != JIRA_DESCRIPTION
|
||||
second = convert.adfs_to_markdown_lossless([JIRA_DESCRIPTION, {"type": "nope"}])
|
||||
assert isinstance(second, convert.Refused) and second.index == 1
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
"""What the Jira and Confluence backends share: one Atlassian account's credentials, the request both backends send, and each service's error messages."""
|
||||
import base64
|
||||
import pathlib
|
||||
import typing
|
||||
|
||||
from failure import Failure
|
||||
from rest_client import json_request
|
||||
from rest_client.env_file import read_env
|
||||
from adf_codec.convert import Refused
|
||||
|
||||
# One pair of keys for Jira and Confluence: one Atlassian account's API token opens both.
|
||||
KEYS = ("ATLASSIAN_EMAIL", "ATLASSIAN_API_TOKEN")
|
||||
# Seconds each connect and each read may wait.
|
||||
TIMEOUT = 30
|
||||
|
||||
# Sends a request with the Authorization header given, the body as JSON where there is one, and returns the JSON answer, None where the answer has no body, or a Failure saying why there is none.
|
||||
Http = typing.Callable[[str, str, str, object], object]
|
||||
ToMarkdown = typing.Callable[[list[dict[str, typing.Any]]], list[str] | Refused | Failure]
|
||||
ToAdf = typing.Callable[[str], dict[str, typing.Any] | Failure]
|
||||
|
||||
|
||||
def basic_auth(env_file: pathlib.Path) -> str | Failure:
|
||||
"""The Authorization header for the email and API token that env_file holds."""
|
||||
values = read_env(env_file, KEYS, "an API token")
|
||||
if isinstance(values, Failure):
|
||||
return values
|
||||
return "Basic " + base64.b64encode(":".join(values[key] for key in KEYS).encode()).decode()
|
||||
|
||||
|
||||
def jira_json(method: str, url: str, authorization: str, body: object) -> object:
|
||||
return json_request.http_json(method, url, authorization, body, TIMEOUT, jira_errors)
|
||||
|
||||
|
||||
def jira_errors(answer: object) -> str:
|
||||
"""Jira's messages in the JSON of an error answer; empty where it holds none."""
|
||||
if not isinstance(answer, dict):
|
||||
return ""
|
||||
messages, errors = answer.get("errorMessages"), answer.get("errors")
|
||||
found = [*(messages if isinstance(messages, list) else []), *(errors.values() if isinstance(errors, dict) else [])]
|
||||
return "; ".join(text for text in found if isinstance(text, str))
|
||||
|
||||
|
||||
def confluence_json(method: str, url: str, authorization: str, body: object) -> object:
|
||||
return json_request.http_json(method, url, authorization, body, TIMEOUT, confluence_errors)
|
||||
|
||||
|
||||
def confluence_errors(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))
|
||||
@@ -0,0 +1,65 @@
|
||||
import base64
|
||||
import json
|
||||
import pathlib
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from atlassian import client
|
||||
from rest_client.json_request import ErrorAnswer
|
||||
from failure import Failure
|
||||
from rest_client.test_json_request import Served
|
||||
|
||||
AUTHORIZATION = "Basic " + base64.b64encode(b"me@example.com:s3cret").decode()
|
||||
|
||||
|
||||
class Credentials(unittest.TestCase):
|
||||
def test_builds_basic_auth_from_the_env_files_email_and_token(self):
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
env = pathlib.Path(temp, "acme.env")
|
||||
env.write_text("ATLASSIAN_EMAIL=me@example.com\nATLASSIAN_API_TOKEN=s3cret\n")
|
||||
env.chmod(0o600)
|
||||
self.assertEqual(client.basic_auth(env), AUTHORIZATION)
|
||||
|
||||
def test_a_missing_env_file_fails(self):
|
||||
self.assertIsInstance(client.basic_auth(pathlib.Path("/nonexistent/acme.env")), Failure)
|
||||
|
||||
|
||||
class Jira(Served):
|
||||
def test_an_error_answer_fails_with_jiras_messages_and_its_status(self):
|
||||
base = self.serve((400, b'{"errorMessages": ["One."], "errors": {"jql": "Two."}}'))
|
||||
self.assertEqual(client.jira_json("POST", f"{base}/rest/api/3/search/jql", AUTHORIZATION, {"jql": "x"}), ErrorAnswer("POST /rest/api/3/search/jql answered 400: One.; Two.", 400))
|
||||
[(_, _, headers, body)] = self.server.got # type: ignore[attr-defined]
|
||||
self.assertEqual((headers["Authorization"], json.loads(body)), (AUTHORIZATION, {"jql": "x"}))
|
||||
|
||||
def test_reads_jiras_messages_from_an_error_answer(self):
|
||||
cases = (
|
||||
({"errorMessages": ["Issue does not exist or you do not have permission to see it."], "errors": {}}, "Issue does not exist or you do not have permission to see it."),
|
||||
({"errorMessages": ["One."], "errors": {"jql": "Two."}}, "One.; Two."),
|
||||
({"errorMessages": "One.", "errors": ["Two."]}, ""),
|
||||
({"errorMessages": [7, "One."]}, "One."),
|
||||
(["One."], ""),
|
||||
)
|
||||
for answer, message in cases:
|
||||
with self.subTest(answer=answer):
|
||||
self.assertEqual(client.jira_errors(answer), message)
|
||||
|
||||
|
||||
class Confluence(Served):
|
||||
def test_an_error_answer_fails_with_confluences_messages_and_its_status(self):
|
||||
base = self.serve((409, b'{"errors": [{"status": 409, "title": "Version must be incremented"}]}'))
|
||||
self.assertEqual(client.confluence_json("PUT", f"{base}/wiki/api/v2/pages/1", AUTHORIZATION, {"version": {"number": 2}}), ErrorAnswer("PUT /wiki/api/v2/pages/1 answered 409: Version must be incremented", 409))
|
||||
[(_, _, headers, body)] = self.server.got # type: ignore[attr-defined]
|
||||
self.assertEqual((headers["Authorization"], json.loads(body)), (AUTHORIZATION, {"version": {"number": 2}}))
|
||||
|
||||
def test_reads_confluences_messages_from_an_error_answer(self):
|
||||
self.assertEqual(client.confluence_errors({"errors": [{"status": 409, "title": "Version must be incremented"}, {"title": "and more"}, "odd"]}), "Version must be incremented; and more")
|
||||
self.assertEqual(client.confluence_errors({"message": "Not Found"}), "Not Found")
|
||||
self.assertEqual(client.confluence_errors({"errors": "odd"}), "")
|
||||
self.assertEqual(client.confluence_errors(["odd"]), "")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -4,7 +4,7 @@ import typing
|
||||
|
||||
from failure import Failure
|
||||
from review_rules.comprehension_history import HISTORY
|
||||
from release_plan.todo_table import Item, items
|
||||
from plan.todo_table import Item, items
|
||||
from reading_cost.figures import RECORD
|
||||
from project_config import templates
|
||||
from text_files.utc_stamp import utc
|
||||
|
||||
@@ -5,7 +5,7 @@ import re
|
||||
import typing
|
||||
|
||||
from branch_chunks.cut import Branch, BranchChunk, NOT_WORK
|
||||
from release_plan.todo_table import Exempt, Item
|
||||
from plan.todo_table import Exempt, Item
|
||||
from review_rules.round_titles import title_counts
|
||||
|
||||
# The Exempt cells, per ~/.claude/rules/todo-items.md, that mark an item fixing a defect.
|
||||
|
||||
@@ -17,7 +17,7 @@ from project_config.test_project_config import configured
|
||||
from failure import Failure
|
||||
from git_cli.git_repo import git
|
||||
from test_env import isolated_env
|
||||
from release_plan.todo_table import Item
|
||||
from plan.todo_table import Item
|
||||
|
||||
HEADER = "| ID | Release | Exempt | Item | R | S | C | A | G | Goals | Score |\n|---|---|---|---|---|---|---|---|---|---|---|\n"
|
||||
WITHOUT_C = "| ID | Release | Exempt | Item | R | S | A | G | Goals | Score |\n|---|---|---|---|---|---|---|---|---|---|\n"
|
||||
|
||||
+53
-27
@@ -8,42 +8,68 @@ from failure import Failure
|
||||
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
|
||||
|
||||
|
||||
def awaited(forge: Forge, run: Run) -> bool | Failure:
|
||||
"""Whether merge waits for an approval: the project config's `wait-for-approval`. A config that cannot be read fails, so that merge never skips an approval the config may require. chunk-pr reads approvals on GitHub only, so a Gitea project that sets it fails too."""
|
||||
answer = run([str(BIN / "project-config"), "wait-for-approval"])
|
||||
if isinstance(answer, Failure):
|
||||
return answer
|
||||
if answer.strip() not in ("true", "false"):
|
||||
return Failure(f"project-config wait-for-approval printed {answer.strip()[:80]!r}, not true or false")
|
||||
if answer.strip() == "true" and forge != "gh":
|
||||
def awaited(forge: Forge, wait_for_approval: bool) -> bool | Failure:
|
||||
"""Whether merge waits for an approval: the project config's `wait-for-approval`. chunk-pr reads approvals on GitHub only, so a Gitea project that sets it fails, and merge never skips an approval the config requires."""
|
||||
if wait_for_approval and forge != "gh":
|
||||
return Failure("the project's config sets wait-for-approval, but chunk-pr reads approvals on GitHub only, so it cannot merge this pull request; ask the human to merge it")
|
||||
return answer.strip() == "true"
|
||||
return wait_for_approval
|
||||
|
||||
|
||||
# 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")
|
||||
|
||||
+294
-70
@@ -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,10 @@ 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 functools
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
@@ -59,17 +84,29 @@ 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
|
||||
from chunk_preflight.choices import forge_of
|
||||
from project_config.main import located
|
||||
from project_config.settings import ProjectConfig
|
||||
from plan_store.plans import says_no_item
|
||||
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: "
|
||||
# The project's config, loaded once per step, on the first call that needs it.
|
||||
Config = typing.Callable[[], ProjectConfig | Failure]
|
||||
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], ...]] = {
|
||||
@@ -82,7 +119,7 @@ def main(argv: list[str]) -> int:
|
||||
if argv[:1] in (["-h"], ["--help"]):
|
||||
print(__doc__.strip())
|
||||
return 0
|
||||
done = step(argv, runner(os.getcwd()))
|
||||
done = step(argv, runner(os.getcwd()), functools.cache(lambda: located(os.getcwd(), pathlib.Path.home())))
|
||||
if isinstance(done, Failure):
|
||||
print(f"chunk-pr: {done.reason}", file=sys.stderr)
|
||||
return 1
|
||||
@@ -90,31 +127,34 @@ def main(argv: list[str]) -> int:
|
||||
return 0
|
||||
|
||||
|
||||
def step(argv: list[str], run: Run) -> str | Failure:
|
||||
def step(argv: list[str], run: Run, config: Config) -> str | Failure:
|
||||
"""Run the step argv names: the line to print, or a Failure. A malformed argv doesn't run anything."""
|
||||
match argv:
|
||||
case ["open", title, *body] if len(body) <= 1 and not title.startswith("-"):
|
||||
return Failure("give a title of one line") if not one_line(title) else misfit(title, run) or opened(title, body[0] if body else "", run)
|
||||
return Failure("give a title of one line") if not one_line(title) else misfit(title, run, config) or opened(title, body[0] if body else "", run)
|
||||
case ["sync"]:
|
||||
return synced(run)
|
||||
return synced(run, config)
|
||||
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)
|
||||
return Failure("give a title of one line") if title and not one_line(title[0]) else (misfit(title[0], run, config) if title else None) or marked_ready(run, title[0] if title else None)
|
||||
case ["merge", *given]:
|
||||
finishes = finishes_of(given)
|
||||
return Failure(USAGE) if finishes is None else merged(run, config, finishes=finishes)
|
||||
case ["clean"]:
|
||||
return cleaned(run)
|
||||
return Failure(USAGE)
|
||||
|
||||
|
||||
def misfit(title: str, run: Run) -> Failure | None:
|
||||
"""Why title doesn't fit the `pull-request-title` template the project's config names; None where it fits. A branch that doesn't fit the config's `branch` template is no plan item's, so it has no ID for {id}, and any title fits there. A config that cannot be read fails, so that no pull request reaches the project's owners under a title they don't use."""
|
||||
read = [run([str(BIN / "project-config"), "pull-request-title"]), run([str(BIN / "project-config"), "branch"]), run(["git", "symbolic-ref", "--short", "HEAD"])]
|
||||
if failed := next((answer for answer in read if isinstance(answer, Failure)), None):
|
||||
return failed
|
||||
template, branch_template, branch = (answer.strip("\n") for answer in read if isinstance(answer, str))
|
||||
if not templates.branch_fits(branch_template, branch) or templates.fits(template, title.strip()):
|
||||
def misfit(title: str, run: Run, config: Config) -> Failure | None:
|
||||
"""Why title doesn't fit the `pull-request-title` template the project's config names, as templates.misfits rules; None where it fits. A config that cannot be read fails, so that no pull request reaches the project's owners under a title they don't use."""
|
||||
loaded = config()
|
||||
if isinstance(loaded, Failure):
|
||||
return loaded
|
||||
branch = run(["git", "symbolic-ref", "--short", "HEAD"])
|
||||
if isinstance(branch, Failure):
|
||||
return branch
|
||||
if not templates.misfits(loaded.pull_request_title, loaded.branch, branch.strip("\n"), title):
|
||||
return None
|
||||
return Failure(f"title the pull request as the project's config asks, `{template}`, where {{id}} is the ID of the chunk's first item; {title.strip()!r} doesn't fit")
|
||||
return Failure(f"title the pull request as the project's config asks, `{loaded.pull_request_title}`, where {{id}} is the ID of the chunk's first item; {title.strip()!r} doesn't fit")
|
||||
|
||||
|
||||
def one_line(title: str) -> bool:
|
||||
@@ -185,7 +225,7 @@ def opened(title: str, body: str, run: Run) -> str | Failure:
|
||||
return number if isinstance(number, Failure) else f"Opened draft pull request #{number}."
|
||||
|
||||
|
||||
def synced(run: Run) -> str | Failure:
|
||||
def synced(run: Run, config: Config) -> str | Failure:
|
||||
found = checkout(run)
|
||||
if isinstance(found, Failure):
|
||||
return found
|
||||
@@ -195,28 +235,16 @@ 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}."
|
||||
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}")
|
||||
todo = pathlib.Path(plan.strip())
|
||||
if not todo.is_file():
|
||||
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}."
|
||||
loaded = config()
|
||||
if isinstance(loaded, Failure):
|
||||
return Failure(f"{done.removesuffix('.')}, but the plan to check cannot be found: {loaded.reason}")
|
||||
todo = loaded.plan_file
|
||||
# A plan in Jira is no file, and Jira's backlog ranks it.
|
||||
if todo is None or not todo.is_file():
|
||||
return done
|
||||
ranked = run([str(BIN / "rank_todo.py"), "--check", str(todo)])
|
||||
if isinstance(ranked, Failure):
|
||||
@@ -224,6 +252,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 +288,210 @@ 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, config: Config, 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
|
||||
waits = awaited(forge, run)
|
||||
forge, number, _ = found
|
||||
loaded = config()
|
||||
if isinstance(loaded, Failure):
|
||||
return loaded
|
||||
waits = awaited(forge, loaded.wait_for_approval)
|
||||
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(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
|
||||
pull_request = Merging(forge, number, method, str(base), required, waits)
|
||||
while True:
|
||||
with turn(file, number, sleep) as untaken:
|
||||
taken = untaken or merge_turn(pull_request, finishes, loaded, run, sleep)
|
||||
if not isinstance(taken, AwaitsApproval):
|
||||
return taken if isinstance(taken, Failure) else taken + absent
|
||||
# Out of the queue, so the project's other chunks merge while this one waits.
|
||||
waited = approved(number, run, sleep)
|
||||
if isinstance(waited, Failure):
|
||||
return waited
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Merging:
|
||||
"""A pull request that merge takes turns for: its forge and number, the merge method, the default branch it merges into with the checks that branch requires, and whether it waits for an approval."""
|
||||
forge: Forge
|
||||
number: str
|
||||
method: str
|
||||
base: str
|
||||
required: set[str]
|
||||
waits: bool
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class AwaitsApproval:
|
||||
"""The pull request passed its checks but awaits a human's approval, so merge leaves the queue until it has one."""
|
||||
|
||||
|
||||
def merge_turn(pull_request: Merging, finishes: typing.Sequence[list[str]], config: ProjectConfig, run: Run, sleep: typing.Callable[[float], None]) -> str | AwaitsApproval | Failure:
|
||||
"""One turn in the queue: level the branch and finish its items, wait for its checks, and merge it where nothing still waits. What merged it, or why it waits or fails."""
|
||||
head = levelled_and_finished(run, pull_request.base, finishes, config)
|
||||
checked = head if isinstance(head, Failure) else checks_passed(pull_request.forge, pull_request.number, head, pull_request.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])
|
||||
ready = approval(pull_request.number, run) if pull_request.waits else True
|
||||
if isinstance(ready, Failure):
|
||||
return ready
|
||||
if not ready:
|
||||
return AwaitsApproval()
|
||||
asked = unanswered(pull_request.number, run) if pull_request.waits else None
|
||||
if asked is not None:
|
||||
return asked
|
||||
if pull_request.forge == "gh":
|
||||
done = run(["gh", "pr", "merge", pull_request.number, pull_request.method, "--match-head-commit", str(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('--')})."
|
||||
done = gitea(run, f"repos/{{owner}}/{{repo}}/pulls/{pull_request.number}/merge", f"Do={pull_request.method}", f"head_commit_id={head}")
|
||||
return done if isinstance(done, Failure) else f"Merged pull request #{pull_request.number} ({pull_request.method.removeprefix('--')})."
|
||||
|
||||
|
||||
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 not says_no_item(shown.reason, finish[0]):
|
||||
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 ""
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def turn(queue: pathlib.Path, number: str, sleep: typing.Callable[[float], None]) -> typing.Iterator[Failure | 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. Gives None while it holds the queue; a Failure, without the queue, where another merge still holds it after QUEUE_SECONDS or the file cannot be opened or locked."""
|
||||
try:
|
||||
fd = os.open(queue, os.O_RDWR | os.O_CREAT, 0o644)
|
||||
except OSError as failure:
|
||||
yield Failure(f"cannot take a turn in the merge queue, {queue}: {failure.strerror}")
|
||||
return
|
||||
try:
|
||||
yield held_turn(fd, queue, number, sleep)
|
||||
finally:
|
||||
os.close(fd)
|
||||
|
||||
|
||||
def held_turn(fd: int, queue: pathlib.Path, number: str, sleep: typing.Callable[[float], None]) -> Failure | None:
|
||||
"""Lock the open queue file fd for pull request number and write its number there, for a merge that waits to name; None once held, else why it isn't."""
|
||||
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:
|
||||
holder = os.pread(fd, 20, 0).decode(errors="replace").strip()
|
||||
return Failure(f"the merge queue stayed held for {QUEUE_SECONDS // 60} minutes, last by pull request #{holder or '?'}, so this one took no turn; run chunk-pr merge again")
|
||||
sleep(QUEUE_POLL_SECONDS)
|
||||
os.ftruncate(fd, 0)
|
||||
os.pwrite(fd, number.encode(), 0)
|
||||
except OSError as failure:
|
||||
return Failure(f"cannot take a turn in the merge queue, {queue}: {failure.strerror}")
|
||||
return None
|
||||
|
||||
|
||||
def levelled_and_finished(run: Run, base: str, finishes: typing.Sequence[list[str]], config: ProjectConfig) -> 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, config))), 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, config) or head[0]
|
||||
|
||||
|
||||
def finished(run: Run, branch: str, finish: list[str], config: ProjectConfig) -> 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 not says_no_item(shown.reason, finish[0]):
|
||||
return shown
|
||||
finishing = "" if isinstance(shown, Failure) else run([str(BIN / "todo-item"), "finish", *finish])
|
||||
if isinstance(finishing, Failure):
|
||||
return finishing
|
||||
title = templates.title_of(config.commit_title, config.branch, branch, finish[0], f"Finish item {finish[0]} in the plan")
|
||||
# A plan in Jira, or a changelog on a Confluence page, is no file to commit.
|
||||
records = [record for record in (config.plan_file, config.paths.get("changelog")) if record is not None and record.is_file()]
|
||||
return committed(run, title, records)
|
||||
|
||||
|
||||
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, config: ProjectConfig) -> 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 = config.paths.get("comprehension-history")
|
||||
# A history on a Confluence page is outside the checkout.
|
||||
if history is None:
|
||||
return None
|
||||
top = answers(run, ["rev-parse", "--show-toplevel"])
|
||||
if isinstance(top, Failure) or not history.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", "--", str(history)])
|
||||
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:
|
||||
|
||||
+395
-88
@@ -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,12 @@ 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 project_config.settings import ProjectConfig
|
||||
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"
|
||||
@@ -28,7 +34,14 @@ OWED = [str(pathlib.Path(__file__).resolve().parents[1] / "larv-review"), "scori
|
||||
TITLE = [str(pathlib.Path(__file__).resolve().parents[1] / "project-config"), "pull-request-title"]
|
||||
BRANCH = [str(pathlib.Path(__file__).resolve().parents[1] / "project-config"), "branch"]
|
||||
WAITS = [str(pathlib.Path(__file__).resolve().parents[1] / "project-config"), "wait-for-approval"]
|
||||
# The settings a fake checkout's answers hold, each under `project-config <setting>` as the tool once read it.
|
||||
PROJECT_CONFIG = str(pathlib.Path(__file__).resolve().parents[1] / "project-config")
|
||||
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 +58,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,8 +69,20 @@ 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 config(self) -> ProjectConfig | Failure:
|
||||
"""The project's config, from the settings the answers hold under PROJECT_CONFIG; a Failure where one of them is, as where no config names the checkout."""
|
||||
named = {key[1]: answer for key, answer in self.answers.items() if key[0] == PROJECT_CONFIG}
|
||||
if failed := next((answer for answer in named.values() if isinstance(answer, Failure)), None):
|
||||
return failed
|
||||
texts = {name: str(answer).strip() for name, answer in named.items()}
|
||||
paths = {name: pathlib.Path(texts[name]) for name in ("plan", "changelog", "comprehension-history") if texts.get(name, "").startswith("/")}
|
||||
return ProjectConfig("proj", pathlib.Path("/config"), pathlib.Path("/checkout"), paths, wait_for_approval=texts.get("wait-for-approval") == "true", commit_title=texts.get("commit-title", "{summary}"), pull_request_title=texts.get("pull-request-title", "{summary}"), branch=texts.get("branch", "item-{id}"))
|
||||
|
||||
def __call__(self, command: list[str]) -> str | Failure:
|
||||
self.ran.append(command)
|
||||
if command[0] == ("tea" if self.github else "gh"):
|
||||
@@ -74,6 +101,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 +111,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]
|
||||
|
||||
|
||||
@@ -93,32 +122,32 @@ class Open(unittest.TestCase):
|
||||
checkout = Checkout(GITHUB, open=argv[0] == "ready")
|
||||
checkout.answers[tuple(TITLE)] = "PAY-{id} - {summary}\n"
|
||||
checkout.answers[tuple(BRANCH)] = "feature/PAY-{id}\n"
|
||||
self.assertNotIsInstance(step(argv, checkout), Failure)
|
||||
self.assertNotIsInstance(step(argv, checkout, checkout.config), Failure)
|
||||
checkout.answers[("git", "symbolic-ref", "--short", "HEAD")] = "feature/PAY-7\n"
|
||||
refused = step(argv, checkout)
|
||||
refused = step(argv, checkout, checkout.config)
|
||||
assert isinstance(refused, Failure), refused
|
||||
self.assertIn("'Release review of 0.3.0' doesn't fit", refused.reason)
|
||||
|
||||
def test_github_pushes_and_opens_a_draft_into_the_default_branch(self):
|
||||
checkout = Checkout(GITHUB, open=False)
|
||||
opened = step(["open", "ABC-1 - Do it", "The body."], checkout)
|
||||
opened = step(["open", "ABC-1 - Do it", "The body."], checkout, checkout.config)
|
||||
self.assertEqual(checkout.acted(), [PUSH, ["gh", "pr", "create", "--draft", "--head", "item-7", "--base", "main", "--title", "ABC-1 - Do it", "--body", "The body."]])
|
||||
self.assertEqual(opened, "Opened draft pull request #12.")
|
||||
|
||||
def test_gitea_opens_a_draft_with_tea(self):
|
||||
checkout = Checkout(GITEA, open=False)
|
||||
self.assertEqual(step(["open", "Do it"], checkout), "Opened draft pull request #12.")
|
||||
self.assertEqual(step(["open", "Do it"], checkout, checkout.config), "Opened draft pull request #12.")
|
||||
self.assertEqual(checkout.acted(), [PUSH, ["tea", "pulls", "create", "--draft", "--head", "item-7", "--base", "main", "--title", "Do it", "--description", ""]])
|
||||
|
||||
def test_an_open_pull_request_is_kept(self):
|
||||
checkout = Checkout(GITEA, open=True)
|
||||
self.assertEqual(step(["open", "Do it"], checkout), "Pull request #12 is open already.")
|
||||
self.assertEqual(step(["open", "Do it"], checkout, checkout.config), "Pull request #12 is open already.")
|
||||
self.assertEqual(checkout.acted(), [PUSH])
|
||||
|
||||
def test_on_the_default_branch_it_refuses_and_pushes_nothing(self):
|
||||
checkout = Checkout(GITEA, open=False)
|
||||
checkout.answers[("git", "symbolic-ref", "--short", "HEAD")] = "main\n"
|
||||
self.assertIsInstance(step(["open", "Do it"], checkout), Failure)
|
||||
self.assertIsInstance(step(["open", "Do it"], checkout, checkout.config), Failure)
|
||||
self.assertEqual(checkout.acted(), [])
|
||||
|
||||
def test_a_title_that_does_not_fit_the_configs_template_is_refused_before_anything_runs(self):
|
||||
@@ -126,75 +155,75 @@ class Open(unittest.TestCase):
|
||||
with self.subTest(argv=argv):
|
||||
checkout = Checkout(GITHUB, open=argv[0] == "ready")
|
||||
checkout.answers[tuple(TITLE)] = "PAY-{id} - {summary}\n"
|
||||
refused = step(argv, checkout)
|
||||
refused = step(argv, checkout, checkout.config)
|
||||
assert isinstance(refused, Failure), refused
|
||||
self.assertIn("`PAY-{id} - {summary}`", refused.reason)
|
||||
self.assertEqual(checkout.acted(), [])
|
||||
self.assertNotIsInstance(step([argv[0], "PAY-7 - Do it"], checkout), Failure)
|
||||
self.assertNotIsInstance(step([argv[0], "PAY-7 - Do it"], checkout, checkout.config), Failure)
|
||||
checkout.answers[tuple(TITLE)] = Failure("no config names the checkout")
|
||||
self.assertEqual(step(argv, checkout), Failure("no config names the checkout"))
|
||||
self.assertEqual(step(argv, checkout, checkout.config), Failure("no config names the checkout"))
|
||||
checkout.answers[tuple(TITLE)] = "PAY-{id} - {summary}\n"
|
||||
checkout.answers[tuple(BRANCH)] = Failure("`branch` is 'x', which holds no {id}")
|
||||
self.assertEqual(step(argv, checkout), Failure("`branch` is 'x', which holds no {id}"))
|
||||
self.assertEqual(step(argv, checkout, checkout.config), Failure("`branch` is 'x', which holds no {id}"))
|
||||
untitled = Checkout(GITHUB, open=True)
|
||||
untitled.answers[tuple(TITLE)] = Failure("no config names the checkout")
|
||||
self.assertNotIsInstance(step(["ready"], untitled), Failure)
|
||||
self.assertNotIsInstance(step(["ready"], untitled, untitled.config), Failure)
|
||||
|
||||
def test_a_title_of_more_than_one_line_or_a_second_body_is_refused_before_anything_runs(self):
|
||||
for argv, refusal in ((["open", "Do it\nand more"], "give a title of one line"), (["open", " "], "give a title of one line"), (["open", "Do it", "Body", "More"], USAGE)):
|
||||
with self.subTest(argv):
|
||||
checkout = Checkout(GITHUB, open=False)
|
||||
self.assertEqual(step(argv, checkout), Failure(refusal))
|
||||
self.assertEqual(step(argv, checkout, checkout.config), Failure(refusal))
|
||||
self.assertEqual(checkout.ran, [])
|
||||
|
||||
def test_a_failed_listing_after_the_create_is_returned(self):
|
||||
checkout = Checkout(GITHUB, open=False)
|
||||
checkout.answers[("gh", "pr", "create", "--draft", "--head", "item-7", "--base", "main", "--title", "Do it", "--body", "")] = Failure("gh pr create: done")
|
||||
self.assertEqual(step(["open", "Do it"], checkout), Failure("gh pr create: done"))
|
||||
self.assertEqual(step(["open", "Do it"], checkout, checkout.config), Failure("gh pr create: done"))
|
||||
checkout = Checkout(GITHUB, open=False)
|
||||
listings = iter(["", Failure("gh pr list: offline")])
|
||||
original = checkout.__call__
|
||||
checkout_call = lambda command: next(listings) if command == GH_LIST else original(command)
|
||||
self.assertEqual(step(["open", "Do it"], checkout_call), Failure("gh pr list: offline"))
|
||||
self.assertEqual(step(["open", "Do it"], checkout_call, checkout.config), Failure("gh pr list: offline"))
|
||||
|
||||
|
||||
class Ready(unittest.TestCase):
|
||||
def test_github_marks_it_ready(self):
|
||||
checkout = Checkout(GITHUB, open=True)
|
||||
self.assertEqual(step(["ready"], checkout), "Marked pull request #12 ready.")
|
||||
self.assertEqual(step(["ready"], checkout, checkout.config), "Marked pull request #12 ready.")
|
||||
self.assertEqual(checkout.acted(), [["gh", "pr", "ready", "12"]])
|
||||
|
||||
def test_gitea_marks_it_ready_with_tea(self):
|
||||
checkout = Checkout(GITEA, open=True)
|
||||
self.assertEqual(step(["ready"], checkout), "Marked pull request #12 ready.")
|
||||
self.assertEqual(step(["ready"], checkout, checkout.config), "Marked pull request #12 ready.")
|
||||
self.assertEqual(checkout.acted(), [["tea", "pulls", "edit", "12", "--ready"]])
|
||||
|
||||
def test_github_sets_a_given_title_then_marks_it_ready(self):
|
||||
checkout = Checkout(GITHUB, open=True)
|
||||
self.assertEqual(step(["ready", "Ship it"], checkout), "Marked pull request #12 ready, titled “Ship it”.")
|
||||
self.assertEqual(step(["ready", "Ship it"], checkout, checkout.config), "Marked pull request #12 ready, titled “Ship it”.")
|
||||
self.assertEqual(checkout.acted(), [["gh", "pr", "edit", "12", "--title", "Ship it"], ["gh", "pr", "ready", "12"]])
|
||||
|
||||
def test_gitea_sets_a_given_title_in_the_call_that_marks_it_ready(self):
|
||||
checkout = Checkout(GITEA, open=True)
|
||||
self.assertEqual(step(["ready", "Ship it"], checkout), "Marked pull request #12 ready, titled “Ship it”.")
|
||||
self.assertEqual(step(["ready", "Ship it"], checkout, checkout.config), "Marked pull request #12 ready, titled “Ship it”.")
|
||||
self.assertEqual(checkout.acted(), [["tea", "pulls", "edit", "12", "--title", "Ship it", "--ready"]])
|
||||
|
||||
def test_a_title_of_more_than_one_line_or_none_is_refused_before_anything_runs(self):
|
||||
for argv, refusal in ((["ready", "Ship\nit"], "give a title of one line"), (["ready", " "], "give a title of one line"), (["ready", "Ship it", "twice"], USAGE)):
|
||||
with self.subTest(argv=argv):
|
||||
checkout = Checkout(GITHUB, open=True)
|
||||
self.assertEqual(step(argv, checkout), Failure(refusal))
|
||||
self.assertEqual(step(argv, checkout, checkout.config), Failure(refusal))
|
||||
self.assertEqual(checkout.ran, [])
|
||||
|
||||
def test_a_failed_title_edit_on_github_leaves_it_a_draft(self):
|
||||
checkout = Checkout(GITHUB, open=True)
|
||||
checkout.answers[("gh", "pr", "edit", "12", "--title", "Ship it")] = Failure("gh pr edit: denied")
|
||||
self.assertEqual(step(["ready", "Ship it"], checkout), Failure("gh pr edit: denied"))
|
||||
self.assertEqual(step(["ready", "Ship it"], checkout, checkout.config), Failure("gh pr edit: denied"))
|
||||
self.assertNotIn(["gh", "pr", "ready", "12"], checkout.ran)
|
||||
|
||||
def test_without_an_open_pull_request_at_the_head_it_fails_naming_the_branch(self):
|
||||
checkout = Checkout(GITHUB, open=False)
|
||||
ready = step(["ready"], checkout)
|
||||
ready = step(["ready"], checkout, checkout.config)
|
||||
self.assertIsInstance(ready, Failure)
|
||||
self.assertIn("item-7", ready.reason)
|
||||
self.assertEqual(checkout.acted(), [])
|
||||
@@ -202,10 +231,10 @@ class Ready(unittest.TestCase):
|
||||
def test_a_failed_ready_or_git_call_is_returned(self):
|
||||
checkout = Checkout(GITEA, open=True)
|
||||
checkout.answers[("tea", "pulls", "edit", "12", "--ready")] = Failure("tea pulls edit: denied")
|
||||
self.assertEqual(step(["ready"], checkout), Failure("tea pulls edit: denied"))
|
||||
self.assertEqual(step(["ready"], checkout, checkout.config), Failure("tea pulls edit: denied"))
|
||||
checkout = Checkout(GITEA, open=True)
|
||||
checkout.answers[("git", "symbolic-ref", "--short", "HEAD")] = Failure("git symbolic-ref: HEAD is detached")
|
||||
self.assertEqual(step(["ready"], checkout), Failure("git symbolic-ref: HEAD is detached"))
|
||||
self.assertEqual(step(["ready"], checkout, checkout.config), Failure("git symbolic-ref: HEAD is detached"))
|
||||
self.assertEqual(checkout.acted(), [])
|
||||
|
||||
|
||||
@@ -232,34 +261,34 @@ class Sync(unittest.TestCase):
|
||||
|
||||
def test_a_branch_behind_the_default_branch_merges_it(self):
|
||||
checkout = self.checkout(behind=3)
|
||||
self.assertEqual(step(["sync"], checkout), "Merged origin/main into item-7.")
|
||||
self.assertEqual(step(["sync"], checkout, checkout.config), "Merged origin/main into item-7.")
|
||||
self.assertEqual(checkout.acted(), [FETCH, MERGE])
|
||||
|
||||
def test_a_branch_that_holds_the_default_branch_merges_nothing(self):
|
||||
checkout = self.checkout(behind=0)
|
||||
self.assertEqual(step(["sync"], checkout), "item-7 already holds origin/main.")
|
||||
self.assertEqual(step(["sync"], checkout, checkout.config), "item-7 already holds origin/main.")
|
||||
self.assertEqual(checkout.acted(), [FETCH])
|
||||
|
||||
def test_a_worktree_with_a_todo_md_runs_the_rank_check_after_the_merge(self):
|
||||
checkout = self.checkout(behind=1, todo=True)
|
||||
self.assertEqual(step(["sync"], checkout), f"Merged origin/main into item-7.\nrank_todo.py --check todo.md passed.")
|
||||
self.assertEqual(step(["sync"], checkout, checkout.config), f"Merged origin/main into item-7.\nrank_todo.py --check todo.md passed.")
|
||||
self.assertEqual(checkout.acted(), [FETCH, MERGE, [RANK, "--check", self.todo]])
|
||||
|
||||
def test_a_checkout_no_config_names_fails_naming_what_it_did(self):
|
||||
checkout = self.checkout(behind=0, todo=True)
|
||||
checkout.answers[PLAN] = Failure("no config names the checkout")
|
||||
self.assertEqual(step(["sync"], checkout), Failure("item-7 already holds origin/main, but the plan to check cannot be found: no config names the checkout"))
|
||||
self.assertEqual(step(["sync"], checkout, checkout.config), Failure("item-7 already holds origin/main, but the plan to check cannot be found: no config names the checkout"))
|
||||
|
||||
def test_a_failing_rank_check_fails_naming_what_it_did(self):
|
||||
checkout = self.checkout(behind=0, todo=True)
|
||||
checkout.answers[(RANK, "--check", self.todo)] = Failure("rank_todo.py --check: item 3 is out of order")
|
||||
self.assertEqual(step(["sync"], checkout), Failure("item-7 already holds origin/main, but rank_todo.py --check todo.md failed: rank_todo.py --check: item 3 is out of order"))
|
||||
self.assertEqual(step(["sync"], checkout, checkout.config), Failure("item-7 already holds origin/main, but rank_todo.py --check todo.md failed: rank_todo.py --check: item 3 is out of order"))
|
||||
|
||||
def test_a_conflict_leaves_the_merge_in_progress_and_names_the_conflicted_files(self):
|
||||
checkout = self.checkout(behind=2, todo=True)
|
||||
checkout.answers[tuple(MERGE)] = Failure("git merge --quiet: CONFLICT")
|
||||
checkout.answers[CONFLICTED] = "todo.md\nREADME.md\n"
|
||||
self.assertEqual(step(["sync"], checkout), Failure("merging origin/main into item-7 conflicts in todo.md, README.md; the merge stays in progress: resolve them and commit"))
|
||||
self.assertEqual(step(["sync"], checkout, checkout.config), Failure("merging origin/main into item-7 conflicts in todo.md, README.md; the merge stays in progress: resolve them and commit"))
|
||||
self.assertNotIn([RANK, "--check", self.todo], checkout.ran)
|
||||
self.assertNotIn(["git", "merge", "--abort"], checkout.ran)
|
||||
|
||||
@@ -267,48 +296,53 @@ class Sync(unittest.TestCase):
|
||||
checkout = self.checkout(behind=2)
|
||||
checkout.answers[tuple(MERGE)] = Failure("git merge --quiet: untracked files would be overwritten")
|
||||
checkout.answers[CONFLICTED] = ""
|
||||
self.assertEqual(step(["sync"], checkout), Failure("git merge --quiet: untracked files would be overwritten"))
|
||||
self.assertEqual(step(["sync"], checkout, checkout.config), Failure("git merge --quiet: untracked files would be overwritten"))
|
||||
|
||||
def test_on_the_default_branch_it_refuses_and_fetches_nothing(self):
|
||||
checkout = self.checkout(behind=0)
|
||||
checkout.answers[("git", "symbolic-ref", "--short", "HEAD")] = "main\n"
|
||||
self.assertEqual(step(["sync"], checkout), Failure("main is origin's default branch; sync the chunk's branch"))
|
||||
self.assertEqual(step(["sync"], checkout, checkout.config), Failure("main is origin's default branch; sync the chunk's branch"))
|
||||
self.assertNotIn(FETCH, checkout.ran)
|
||||
|
||||
def test_a_failed_fetch_is_returned(self):
|
||||
checkout = self.checkout(behind=0)
|
||||
checkout.answers[tuple(FETCH)] = Failure("git fetch --quiet: could not read from remote")
|
||||
self.assertEqual(step(["sync"], checkout), Failure("git fetch --quiet: could not read from remote"))
|
||||
self.assertEqual(step(["sync"], checkout, checkout.config), 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)
|
||||
self.assertIsInstance(step(["merge", "--gate-passed"], checkout), Failure)
|
||||
self.assertIsInstance(step(["merge", "--gate-passed"], checkout, checkout.config), Failure)
|
||||
self.assertEqual(checkout.ran, [])
|
||||
|
||||
def test_an_option_given_as_a_title_runs_nothing(self):
|
||||
for argv in (["ready", "--help"], ["open", "-h"]):
|
||||
checkout = Checkout(GITHUB, open=True)
|
||||
self.assertEqual(step(argv, checkout), Failure(USAGE))
|
||||
self.assertEqual(step(argv, checkout, checkout.config), Failure(USAGE))
|
||||
self.assertEqual(checkout.ran, [])
|
||||
|
||||
def test_github_waits_for_the_checks_before_merging(self):
|
||||
checkout = Checkout(GITHUB, open=True)
|
||||
self.assertEqual(step(["merge"], checkout), "Merged pull request #12 (merge).")
|
||||
self.assertEqual(step(["merge"], checkout, checkout.config), "Merged pull request #12 (merge).")
|
||||
self.assertEqual(checkout.ran[-2:], [GH_CHECKS, ["gh", "pr", "merge", "12", "--merge", "--match-head-commit", HEAD]])
|
||||
|
||||
def test_a_failed_check_on_github_leaves_it_unmerged(self):
|
||||
checkout = Checkout(GITHUB, open=True)
|
||||
checkout.answers[tuple(GH_CHECKS)] = Failure("gh pr checks 12: CI / tests\tfail")
|
||||
self.assertEqual(step(["merge"], checkout), Failure("gh pr checks 12: CI / tests\tfail"))
|
||||
self.assertEqual(checkout.acted(), [])
|
||||
self.assertEqual(step(["merge"], checkout, checkout.config), Failure("gh pr checks 12: CI / tests\tfail"))
|
||||
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)
|
||||
checkout.answers[tuple(GH_CHECKS)] = Failure("no checks reported on the 'item-7' branch")
|
||||
slept: list[float] = []
|
||||
self.assertEqual(merged(checkout, slept.append), "Merged pull request #12 (merge).")
|
||||
self.assertEqual(merged(checkout, checkout.config, slept.append), "Merged pull request #12 (merge).")
|
||||
self.assertEqual(sum(slept), 60)
|
||||
self.assertEqual(checkout.ran.count(GH_CHECKS), 7)
|
||||
|
||||
@@ -316,7 +350,7 @@ class Merge(unittest.TestCase):
|
||||
checkout = Checkout(GITEA, open=True)
|
||||
checkout.statuses = [json.dumps({"total_count": 0, "state": "pending", "statuses": []})] * 7
|
||||
slept: list[float] = []
|
||||
self.assertEqual(merged(checkout, slept.append), "Merged pull request #12 (merge).")
|
||||
self.assertEqual(merged(checkout, checkout.config, slept.append), "Merged pull request #12 (merge).")
|
||||
self.assertEqual(sum(slept), 60)
|
||||
|
||||
def requiring_approval(self, origin: str = GITHUB, *decisions: str) -> Checkout:
|
||||
@@ -329,33 +363,33 @@ class Merge(unittest.TestCase):
|
||||
def test_a_project_without_wait_for_approval_never_reads_the_review_decision(self):
|
||||
checkout = Checkout(GITHUB, open=True)
|
||||
checkout.decisions = ["REVIEW_REQUIRED"]
|
||||
self.assertEqual(step(["merge"], checkout), "Merged pull request #12 (merge).")
|
||||
self.assertEqual(step(["merge"], checkout, checkout.config), "Merged pull request #12 (merge).")
|
||||
self.assertNotIn(GH_DECISION, checkout.ran)
|
||||
|
||||
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(step(["merge"], checkout, checkout.config), "Merged pull request #12 (merge).")
|
||||
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(merged(checkout, checkout.config, slept.append), "Merged pull request #12 (merge).")
|
||||
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")
|
||||
slept: list[float] = []
|
||||
failed = merged(checkout, slept.append)
|
||||
failed = merged(checkout, checkout.config, slept.append)
|
||||
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(merged(checkout, checkout.config, slept.append), "Merged pull request #12 (merge).")
|
||||
self.assertEqual(sum(slept), 90 * 60)
|
||||
|
||||
def test_a_review_decision_it_cannot_read_or_does_not_know_leaves_it_unmerged(self):
|
||||
@@ -363,40 +397,38 @@ class Merge(unittest.TestCase):
|
||||
with self.subTest(answer):
|
||||
checkout = self.requiring_approval()
|
||||
checkout.unreadable = answer
|
||||
self.assertIsInstance(step(["merge"], checkout), Failure)
|
||||
self.assertEqual(checkout.acted(), [])
|
||||
self.assertIsInstance(step(["merge"], checkout, checkout.config), Failure)
|
||||
self.assertEqual(changes(checkout), [])
|
||||
|
||||
def test_requested_changes_leave_it_unmerged_without_waiting(self):
|
||||
checkout = self.requiring_approval(GITHUB, "CHANGES_REQUESTED")
|
||||
slept: list[float] = []
|
||||
failed = merged(checkout, slept.append)
|
||||
failed = merged(checkout, checkout.config, 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):
|
||||
with self.subTest(decision):
|
||||
checkout = self.requiring_approval(GITHUB, decision)
|
||||
failed = step(["merge"], checkout)
|
||||
failed = step(["merge"], checkout, checkout.config)
|
||||
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)
|
||||
failed = step(["merge"], checkout, checkout.config)
|
||||
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", ""):
|
||||
with self.subTest(answer):
|
||||
checkout = Checkout(GITHUB, open=True)
|
||||
checkout.answers[tuple(WAITS)] = answer
|
||||
self.assertIsInstance(step(["merge"], checkout), Failure)
|
||||
self.assertEqual(checkout.acted(), [])
|
||||
def test_a_config_it_cannot_read_leaves_it_unmerged(self):
|
||||
checkout = Checkout(GITHUB, open=True)
|
||||
checkout.answers[tuple(WAITS)] = Failure("no config names the checkout")
|
||||
self.assertEqual(step(["merge"], checkout, checkout.config), Failure("no config names the checkout"))
|
||||
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."""
|
||||
@@ -412,79 +444,354 @@ class Merge(unittest.TestCase):
|
||||
def test_gitea_waits_until_the_required_check_reports_and_passes_then_merges(self):
|
||||
checkout = self.protected([], [("CI / tests (pull_request)", "pending")], [("CI / tests (pull_request)", "success")])
|
||||
slept: list[float] = []
|
||||
self.assertEqual(merged(checkout, slept.append), "Merged pull request #12 (merge).")
|
||||
self.assertEqual(merged(checkout, checkout.config, slept.append), "Merged pull request #12 (merge).")
|
||||
self.assertEqual(len(slept), 2)
|
||||
self.assertEqual(checkout.ran.count(TEA_STATUS), 3)
|
||||
|
||||
def test_a_failed_check_on_gitea_leaves_it_unmerged(self):
|
||||
checkout = self.protected([("CI / tests (pull_request)", "pending")], [("CI / tests (pull_request)", "failure")])
|
||||
self.assertIsInstance(merged(checkout, lambda _: None), Failure)
|
||||
self.assertEqual(checkout.acted(), [])
|
||||
self.assertIsInstance(merged(checkout, checkout.config, lambda _: None), Failure)
|
||||
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.assertEqual(merged(checkout, checkout.config, 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.assertEqual(merged(checkout, checkout.config, 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)
|
||||
failed = merged(checkout, checkout.config, 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):
|
||||
with self.subTest(origin=origin):
|
||||
checkout = Checkout(origin, open=True)
|
||||
checkout.answers[tuple(OWED)] = Failure("larv-review scoring-run-owed: the chunk owes 2 scoring runs")
|
||||
self.assertEqual(step(["merge"], checkout), Failure("larv-review scoring-run-owed: the chunk owes 2 scoring runs"))
|
||||
self.assertEqual(checkout.acted(), [])
|
||||
self.assertEqual(step(["merge"], checkout, checkout.config), Failure("larv-review scoring-run-owed: the chunk owes 2 scoring runs"))
|
||||
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(step(["merge"], checkout, checkout.config), "Merged pull request #12 (merge).")
|
||||
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]])
|
||||
step(["merge"], checkout, checkout.config)
|
||||
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(step(["merge"], checkout, checkout.config), "Merged pull request #12 (fast-forward-only).")
|
||||
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.assertIsInstance(step(["merge"], checkout, checkout.config), Failure)
|
||||
self.assertEqual(changes(checkout), [])
|
||||
|
||||
def test_a_forge_failure_is_returned(self):
|
||||
checkout = Checkout(GITHUB, open=True)
|
||||
checkout.answers[("gh", "pr", "merge", "12", "--merge", "--match-head-commit", HEAD)] = Failure("gh pr merge: head moved")
|
||||
self.assertEqual(step(["merge"], checkout), Failure("gh pr merge: head moved"))
|
||||
self.assertEqual(step(["merge"], checkout, checkout.config), Failure("gh pr merge: head moved"))
|
||||
checkout = Checkout(GITHUB, open=True)
|
||||
checkout.answers[tuple(GH_SETTINGS)] = "not json"
|
||||
self.assertIsInstance(step(["merge"], checkout), Failure)
|
||||
self.assertIsInstance(step(["merge"], checkout, checkout.config), Failure)
|
||||
|
||||
def test_a_failed_settings_read_is_returned_unmerged(self):
|
||||
for origin, settings in ((GITHUB, GH_SETTINGS), (GITEA, TEA_SETTINGS)):
|
||||
with self.subTest(origin):
|
||||
checkout = Checkout(origin, open=True)
|
||||
checkout.answers[tuple(settings)] = Failure("settings: denied")
|
||||
self.assertEqual(step(["merge"], checkout), Failure("settings: denied"))
|
||||
self.assertEqual(checkout.acted(), [])
|
||||
self.assertEqual(step(["merge"], checkout, checkout.config), Failure("settings: denied"))
|
||||
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, checkout.config), 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__, checkout.config), "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__, checkout.config)
|
||||
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__, checkout.config, 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__, checkout.config), "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__, checkout.config, 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__, checkout.config, 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, checkout.config, 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__, checkout.config, 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__, checkout.config, 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__, checkout.config, 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"]):
|
||||
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, checkout.config, 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__, checkout.config, 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__, checkout.config, 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__, checkout.config, 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, checkout.config, 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, checkout.config, 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, checkout.config, 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, checkout.config)
|
||||
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, checkout.config, 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__, checkout.config)
|
||||
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__, checkout.config), "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__, checkout.config), 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, checkout.config, 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, checkout.config, 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, checkout.config), 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,60 +1,12 @@
|
||||
"""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 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
|
||||
from chunk_preflight.gathered import Forge
|
||||
|
||||
# The command each forge's CLI lists pull requests with; pulls_command adds the flags that pick their rows and fields.
|
||||
PULLS_LIST: dict[Forge, tuple[str, ...]] = {"gh": ("gh", "pr", "list"), "tea": ("tea", "pulls", "list")}
|
||||
|
||||
|
||||
def cut_name(cut: LastCut) -> str | None:
|
||||
"""How the preflight names the last cut: the tag, or the version under its dated CHANGELOG.md heading; None where nothing is cut."""
|
||||
if cut.tag is not None:
|
||||
return None if isinstance(cut.tag, Failure) else cut.tag
|
||||
headed = dated_cut(cut.tag, cut.changelog)
|
||||
return None if headed is None else f"{version(headed)} (dated in CHANGELOG.md)"
|
||||
|
||||
|
||||
def plan_name(default: str, outside: str | None) -> str:
|
||||
"""How the preflight names the plan it read: the default branch's todo.md, or the file or Jira epic, where the project's config puts it outside the checkout."""
|
||||
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."""
|
||||
where = plan_name(default, outside)
|
||||
if isinstance(todo, NoItemsTable):
|
||||
return NoItem(f"{where} holds no items table.")
|
||||
if isinstance(todo, Failure):
|
||||
return NoItem(f"{where} cannot be read: {todo.reason}.")
|
||||
found = todo.items
|
||||
if isinstance(cut.tag, Failure):
|
||||
return NoItem(f"{default}'s tags cannot be read: {cut.tag.reason}. So which release is next cannot be told. Find the next release yourself.")
|
||||
named = cut_name(cut)
|
||||
last_cut = f"the last cut, {named}" if named is not None else "the start, since no release is cut yet"
|
||||
pick = chunk_item(found, cut)
|
||||
if isinstance(pick, Cut):
|
||||
return NoItem(f"{where} files items under release {version(pick.release)}, which is not after {last_cut}; ask the human which release they belong to.")
|
||||
if isinstance(pick, Unknown):
|
||||
return NoItem(f"{where} may hold no item for the next release after {last_cut}: todo.md's texts since then, or the count of changes since then, cannot be read. Find the next release yourself.")
|
||||
if isinstance(pick, ReadyToCut | ReviewDue | Unplanned):
|
||||
upcoming = f"release {version(pick.release)}, the next after {last_cut}" if pick.release else f"the next release after {last_cut}"
|
||||
if isinstance(pick, ReviewDue):
|
||||
return NoItem(f"{where} holds no item for {upcoming}, and changes are unreleased, so that release's release review is due: no commit titled `Release review of <release>` has landed {'since the cut' if named is not None else 'yet'}. This chunk is that review, as `~/.claude/skills/larv-review/SKILL.md` → \"Release review\" says; once it merges and the release holds no item, the release is ready to cut.")
|
||||
if isinstance(pick, ReadyToCut):
|
||||
return NoItem(f"{where} holds no item for {upcoming}, and changes are unreleased, and its release review has landed, so that release is finished and ready to cut. The working loop stops here. If todo.md renamed that release instead, add `- <old release> renamed to <new release>` to todo.md's `## Renamed` section.")
|
||||
return NoItem(f"{where} holds no item for {upcoming}, and no change is unreleased, so that release is to be planned first.")
|
||||
first = pick.item
|
||||
if first is None:
|
||||
return NoItem(f"every item of release {version(pick.release)} in {where} waits." if pick.release is not None else f"{where}'s items table holds no item.")
|
||||
return Plan(found, first, f"{first.tagline}\n\n{first.detail}".strip(), branch)
|
||||
|
||||
|
||||
def worktree_on(porcelain: str, branch: str) -> pathlib.Path | None:
|
||||
"""The worktree on branch, in what `git worktree list --porcelain` printed; None where none is."""
|
||||
for block in porcelain.split("\n\n"):
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
"""The lines the preflight prints, stated from what it gathered."""
|
||||
from release_plan.todo_table import bundle_candidates, BUNDLE_MAX_R, Item, ships_alone
|
||||
from plan.todo_table import bundle_candidates, BUNDLE_MAX_R, Item, ships_alone
|
||||
from touch_predictions.beside import chunks_beside
|
||||
from chunk_preflight.choices import cut_name, PULLS_LIST
|
||||
from release_plan.next_chunk import cut_name, NextChunk, NoItem
|
||||
from release_plan.release_standing import dated_cut, LastCut, unreleased_entries, UNSEEN_RELEASES
|
||||
from failure import Failure
|
||||
from chunk_preflight.gathered import Forge, Gathered, ItemFacts, NamedPath, NoItem, Plan, Ran
|
||||
from chunk_preflight.gathered import Forge, Gathered, ItemFacts, NamedPath, Ran
|
||||
from text_files.markdown_text import listed, quoted
|
||||
from release_plan.release import version
|
||||
from chunk_preflight.choices import PULLS_LIST
|
||||
from plan.release import version
|
||||
|
||||
|
||||
# CLAUDE.md → "Working loop" lets up to ten tiny items share a chunk, so a worker never needs more. A release with 24 joinable items would otherwise put about 155 lines of detail in every prompt.
|
||||
@@ -45,7 +46,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,7 +59,16 @@ def item_lines(plan: str, item: ItemFacts) -> list[str]:
|
||||
]
|
||||
|
||||
|
||||
def joining_details(plan: Plan) -> list[str]:
|
||||
def carried_lines(plan: NextChunk) -> 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: NextChunk) -> 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)
|
||||
if not joining:
|
||||
@@ -90,7 +101,7 @@ def open_pulls(stdout: str, forge: Forge, branch: str) -> list[str]:
|
||||
return [f"#{row[0]} {row[2]}" for row in rows if len(row) == 3 and row[1] == branch]
|
||||
|
||||
|
||||
def bundled(plan: Plan) -> list[str]:
|
||||
def bundled(plan: NextChunk) -> list[str]:
|
||||
first, candidates = plan.first, bundle_candidates(plan.items, plan.first)
|
||||
if ships_alone(first):
|
||||
return [f"- Item {first.id} has R above {BUNDLE_MAX_R}, so it ships alone."]
|
||||
@@ -100,7 +111,7 @@ def bundled(plan: Plan) -> list[str]:
|
||||
return [f'- The items of release {version(first.release)} that may join the chunk of item {first.id}, where `~/.claude/CLAUDE.md` → "Working loop" lets them share it:', *listed]
|
||||
|
||||
|
||||
def beside(plan: Plan) -> list[str]:
|
||||
def beside(plan: NextChunk) -> list[str]:
|
||||
"""The items that may start chunks while first's runs, by touch_predictions' pick; no line where none of the release's items holds a prediction."""
|
||||
first = plan.first
|
||||
found = chunks_beside(plan.items, first)
|
||||
|
||||
@@ -4,9 +4,8 @@ import pathlib
|
||||
import typing
|
||||
|
||||
from failure import Failure
|
||||
from release_plan.todo_table import Item
|
||||
from release_plan.release_standing import LastCut
|
||||
from project_config import templates
|
||||
from release_plan.next_chunk import NextChunk, NoItem
|
||||
|
||||
# The CLI that lists a forge's pull requests: gh for a github.com origin, tea for any other.
|
||||
Forge = typing.Literal["gh", "tea"]
|
||||
@@ -20,27 +19,6 @@ class Ran:
|
||||
stderr: str
|
||||
|
||||
|
||||
@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."""
|
||||
items: list[Item]
|
||||
first: Item
|
||||
# first's tagline and detail.
|
||||
text: str
|
||||
branch_template: str
|
||||
|
||||
@property
|
||||
def branch(self) -> str:
|
||||
"""The branch first's worktree is on."""
|
||||
return templates.branch_of(self.branch_template, self.first.id)
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class NoItem:
|
||||
"""Why the plan names no item for the next chunk, as a sentence the worker reads."""
|
||||
why: str
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Worktree:
|
||||
path: pathlib.Path
|
||||
@@ -60,7 +38,7 @@ class NamedPath:
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class ItemFacts:
|
||||
"""What the preflight found or made for the plan's first item."""
|
||||
plan: Plan
|
||||
plan: NextChunk
|
||||
worktree: Worktree | Failure
|
||||
# The forge whose CLI listed the open pull requests, and how it ran; None without an origin remote.
|
||||
pulls: tuple[Forge, Ran | Failure] | None
|
||||
@@ -79,7 +57,7 @@ class Gathered:
|
||||
cut: LastCut
|
||||
# What was found or made for the plan's first item; else why the plan names none.
|
||||
item: ItemFacts | NoItem
|
||||
# The plan that was read, as choices.plan_name names it.
|
||||
# The plan that was read, as release_plan.next_chunk.plan_name names it.
|
||||
plan: str
|
||||
# Each path the project's config sets, and the epic of a plan kept in Jira, by its setting: in the item's worktree where one was made or continued, else in the checkout.
|
||||
places: dict[str, str]
|
||||
|
||||
+27
-20
@@ -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.
|
||||
"""
|
||||
@@ -75,11 +78,12 @@ import typing
|
||||
|
||||
from git_cli.git_repo import commit_exists, default_branch, file_at, git, top
|
||||
from failure import Failure
|
||||
from chunk_preflight.gathered import Forge, Gathered, ItemFacts, NamedPath, NoItem, Plan, Ran, Worktree
|
||||
from chunk_preflight.choices import forge_of, plan_name, planned, pulls_command, worktree_add, worktree_on
|
||||
from chunk_preflight.gathered import Forge, Gathered, ItemFacts, NamedPath, Ran, Worktree
|
||||
from chunk_preflight.choices import forge_of, pulls_command, worktree_add, worktree_on
|
||||
from chunk_preflight.facts import JOINING_DETAILS, render
|
||||
from project_config.main import located
|
||||
from release_plan.named_code import named_paths
|
||||
from plan.named_paths import named_paths
|
||||
from release_plan.next_chunk import NextChunk, NoItem, plan_name, planned
|
||||
from release_plan.release_standing import project_plan
|
||||
|
||||
BIN = pathlib.Path(__file__).resolve().parents[1]
|
||||
@@ -90,16 +94,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 +114,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 +132,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,14 +143,14 @@ 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.plan, 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
|
||||
return render(Gathered(ref, note, held.cut, item, plan_name(ref, outside), (config if isinstance(made, Failure) else made).places, outside is not None, config.texts))
|
||||
|
||||
|
||||
def item_facts(root: pathlib.Path, default: str, plan: Plan, timeout: float, make: bool) -> ItemFacts:
|
||||
def item_facts(root: pathlib.Path, default: str, plan: NextChunk, timeout: float, make: bool) -> ItemFacts:
|
||||
worktree = item_worktree(root, plan.branch, default) if make else Failure(f"none made, since it ran without {WORKTREE}.")
|
||||
path = worktree.path if isinstance(worktree, Worktree) else None
|
||||
return ItemFacts(plan, worktree, pull_listing(root, plan.branch, timeout), named_files(plan.text, path or root), tools_run(plan.first.id, path, timeout) if path else [])
|
||||
|
||||
@@ -10,15 +10,17 @@ import unittest
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from project_config.templates import BRANCH
|
||||
from release_plan.next_chunk import CarriedOver, NoItem
|
||||
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 chunk_preflight.gathered import Gathered, ItemFacts, NamedPath, 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
|
||||
from release_plan import next_chunk
|
||||
from chunk_preflight.facts import open_pulls, render
|
||||
from plan_store.stores import plan_of
|
||||
from plan_store.todo_md import plan_of
|
||||
from project_config.test_project_config import write_config
|
||||
|
||||
BIN = pathlib.Path(__file__).resolve().parents[1]
|
||||
@@ -54,6 +56,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 +321,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)
|
||||
@@ -361,8 +390,8 @@ class ChunkPreflightTool(unittest.TestCase):
|
||||
|
||||
|
||||
def planned(todo, *rest):
|
||||
"""choices.planned for the plan a todo.md's text holds, or for the Failure given."""
|
||||
return choices.planned(plan_of(todo) if isinstance(todo, str) else todo, *rest)
|
||||
"""next_chunk.planned for the plan a todo.md's text holds, or for the Failure given."""
|
||||
return next_chunk.planned(plan_of(todo) if isinstance(todo, str) else todo, *rest)
|
||||
|
||||
|
||||
def item_facts(todo=TODO, **fields):
|
||||
@@ -387,6 +416,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 +560,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 +617,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)
|
||||
|
||||
@@ -5,8 +5,8 @@ import re
|
||||
import shlex
|
||||
import typing
|
||||
|
||||
# Launchers that run the tool named later in their words, such as uvx --with pytest mutmut run.
|
||||
LAUNCHERS = frozenset({"bunx", "env", "nice", "npx", "pipx", "pnpm", "run-heavy", "time", "timeout", "uvx", "yarn"})
|
||||
# Launchers that run the tool named later in their words, such as uvx --with pytest mutmut run, uv run mutmut run or sudo docker build.
|
||||
LAUNCHERS = frozenset({"bunx", "doas", "env", "nice", "npx", "pipx", "pnpm", "poetry", "run-heavy", "sudo", "time", "timeout", "uv", "uvx", "yarn"})
|
||||
HEREDOC = re.compile(r"<<-?[ \t]*([\"']?)([A-Za-z_]\w*)\1[^\n]*\n.*?^[ \t]*\2[ \t]*$", re.DOTALL | re.MULTILINE)
|
||||
ASSIGNMENT = re.compile(r"[A-Za-z_][A-Za-z0-9_]*=")
|
||||
OPERATOR = set("\n();&|<>")
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
Each step first checks whether an earlier run did it, so a rerun continues where the last run stopped.
|
||||
"""
|
||||
import pathlib
|
||||
import re
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
@@ -13,11 +12,11 @@ from project_config.settings import DEFAULT_FLOOR
|
||||
from git_cli.git_repo import default_ref, git
|
||||
from deploy_release.deploy import deploy
|
||||
from failure import Failure
|
||||
from plan_store.stores import FilePlan
|
||||
from plan_store.todo_md import FilePlan
|
||||
from record_store.stores import FileStore
|
||||
from deploy_release import forge
|
||||
from chunk_preflight.choices import forge_of
|
||||
from release_plan.release import newest_tag, Release, version
|
||||
from plan.release import newest_tag, Release, UNRELEASED_HEADING, version
|
||||
from project_config import templates
|
||||
|
||||
|
||||
@@ -119,9 +118,9 @@ def ready_release(clone: str, ref: str) -> Release | Failure:
|
||||
"""The next release, as chunk-preflight works it out, where it is ready to cut: it holds no item in todo.md, its release review has landed and changes are unreleased."""
|
||||
# No project's config names the clone, so its changelog is read at the fixed path, on ref like the plan, and its titles as they stand.
|
||||
plan = default_plan(clone, ref, clone_plan(clone), FileStore(pathlib.Path(clone, "CHANGELOG.md"), "CHANGELOG.md"), templates.BARE)
|
||||
if isinstance(plan.todo, Failure):
|
||||
return Failure(f"todo.md on {ref} cannot be read: {plan.todo.reason}")
|
||||
match chunk_item(plan.todo.items, plan.cut):
|
||||
if isinstance(plan.plan, Failure):
|
||||
return Failure(f"todo.md on {ref} cannot be read: {plan.plan.reason}")
|
||||
match chunk_item(plan.plan.items, plan.cut):
|
||||
case ReadyToCut(release=release) if release is not None:
|
||||
return release
|
||||
case ReadyToCut():
|
||||
@@ -211,7 +210,7 @@ def push_cut_commit(clone: str, ref: str, branch: str, named: str, title: str, r
|
||||
if isinstance(added := git("worktree", "add", "--quiet", "--detach", str(worktree), ref, cwd=clone), Failure):
|
||||
return added
|
||||
changelog = worktree / "CHANGELOG.md"
|
||||
renamed, count = re.subn(r"^## Unreleased$", f"## {named}", changelog.read_text() if changelog.exists() else "", count=1, flags=re.MULTILINE)
|
||||
renamed, count = UNRELEASED_HEADING.subn(f"## {named}", changelog.read_text() if changelog.exists() else "", count=1)
|
||||
if not count:
|
||||
return Failure(f"CHANGELOG.md on {ref} has no ## Unreleased section to rename")
|
||||
changelog.write_text(renamed)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""Move a checkout to this repo's newest release, as a bare `deploy-release` does."""
|
||||
from failure import Failure
|
||||
from git_cli.git_repo import git
|
||||
from release_plan.release import newest_tag, parsed, tagged
|
||||
from plan.release import newest_tag, parsed, tagged
|
||||
from text_files.markdown_text import sections
|
||||
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -7,11 +7,11 @@ from larv_review.plan import checkout_plan, plan_reasons
|
||||
from git_cli.git_repo import commit_exists
|
||||
from larv_review.ruling import counted, overall, ruling, split, surplus, votes
|
||||
from failure import Failure
|
||||
from plan_store.stores import file_plan, store as plan_store
|
||||
from larv_review.seats import FIRST_SEATS, scores, seats_file, SeatsFile
|
||||
from larv_review.scoring import floor_step, means, under_floor
|
||||
from record_store.held import Held
|
||||
from project_config.main import located
|
||||
from release_plan import plan_file
|
||||
from plan_store.stores import store as plan_store
|
||||
from record_store.stores import RecordStore, store
|
||||
from larv_review.scoring_setup import removed_setup
|
||||
|
||||
@@ -84,10 +84,11 @@ def rerank(home: pathlib.Path, warn: Say) -> Failure | None:
|
||||
if todo is None:
|
||||
# A plan in Jira is ranked by Jira's backlog, which no score moves.
|
||||
return None
|
||||
ranked = plan_file.rank_file(todo, config)
|
||||
plan = file_plan(config, todo)
|
||||
ranked = plan.rank()
|
||||
if isinstance(ranked, Failure):
|
||||
return Failure(f"recorded the run, but rank_todo.py cannot rank {todo}: {ranked.reason}. Fix what that names, then run rank_todo.py on {todo}, not record-scoring again")
|
||||
for line in plan_file.report_lines(todo, ranked):
|
||||
for line in plan.reported(ranked):
|
||||
warn(line)
|
||||
if ranked.under_bar:
|
||||
return Failure(f"recorded the run and ranked {todo}, but the lines above name items now under the bar. Settle each as its line says, then run rank_todo.py on {todo}, not record-scoring again")
|
||||
@@ -145,22 +146,29 @@ def read_agreement(home: pathlib.Path) -> str | Failure:
|
||||
|
||||
def history_file(home: pathlib.Path) -> tuple[RecordStore, str] | Failure:
|
||||
"""The store the project's config names for its comprehension history, and the history's text, empty where there is none yet."""
|
||||
held = held_history(home)
|
||||
return held if isinstance(held, Failure) else (held[0], held[1].text)
|
||||
|
||||
|
||||
def held_history(home: pathlib.Path) -> tuple[RecordStore, Held] | Failure:
|
||||
"""The store the project's config names for its comprehension history, and the history as it stands, with the version a write over it names."""
|
||||
config = located(None, home)
|
||||
if isinstance(config, Failure):
|
||||
return config
|
||||
history = store(config, "comprehension-history")
|
||||
text = history.read()
|
||||
return text if isinstance(text, Failure) else (history, text)
|
||||
held = history.held()
|
||||
return held if isinstance(held, Failure) else (history, held)
|
||||
|
||||
|
||||
def append(read: str, entry: str, home: pathlib.Path) -> str | Failure:
|
||||
"""Appends entry and returns the line the tool prints; a Failure where the history already holds an entry on what the seats read."""
|
||||
read_history = history_file(home)
|
||||
if isinstance(read_history, Failure):
|
||||
return read_history
|
||||
history, text = read_history
|
||||
if recorded(text, read):
|
||||
read_history = held_history(home)
|
||||
return read_history if isinstance(read_history, Failure) else appended_to(*read_history, read, entry)
|
||||
|
||||
|
||||
def appended_to(history: RecordStore, held: Held, read: str, entry: str) -> str | Failure:
|
||||
"""Writes entry onto held, the history as history's store read it, over held's version; the line the tool prints, or why the entry isn't written."""
|
||||
if recorded(held.text, read):
|
||||
return Failure(f"{history.label} already holds an entry on {read}; record each ruling or run once")
|
||||
if unwritten := history.write(appended(text, entry)):
|
||||
return unwritten
|
||||
return f"Appended to {history.label}."
|
||||
written = history.write(appended(held.text, entry), held.version)
|
||||
return written if isinstance(written, Failure) else f"Appended to {history.label}."
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
import pathlib
|
||||
import typing
|
||||
|
||||
from larv_review.plan import EMPTIED_WORDS, plan_reasons
|
||||
from larv_review.plan import Emptied, plan_reasons
|
||||
from review_rules.comprehension_history import entries
|
||||
from failure import Failure
|
||||
from git_cli.git_repo import file_at, git
|
||||
from project_config.main import located
|
||||
from release_plan.todo_table import NoItemsTable
|
||||
from plan_store.stores import store as plan_store, PlanStore
|
||||
from plan.todo_table import NoItemsTable
|
||||
from plan_store.stores import store as plan_store
|
||||
from plan_store.plans import PlanStore
|
||||
from record_store.stores import store
|
||||
|
||||
|
||||
@@ -48,7 +49,7 @@ def owed_scoring_run(default: str, home: pathlib.Path, warn: typing.Callable[[st
|
||||
|
||||
def shortfall(reasons: list[str], recorded: int) -> Failure | None:
|
||||
"""Which scoring runs the plan's reasons call that recorded, the count the branch added to the history, leaves unrecorded; None where it holds them all."""
|
||||
needed = 2 if any(reason.endswith(EMPTIED_WORDS) for reason in reasons) else 1
|
||||
needed = 2 if any(isinstance(reason, Emptied) for reason in reasons) else 1
|
||||
if recorded >= needed:
|
||||
return None
|
||||
return Failure(f"the chunk owes {needed} scoring run{'s' if needed > 1 else ''} and the branch's committed history records {max(recorded, 0)}: it {' and '.join(reasons)}. larv-review's SKILL.md → 'Scoring run' says how to run and record {'them' if needed > 1 else 'it'}{"; → 'Second run' says how the second is titled" if needed > 1 else ""}")
|
||||
|
||||
+13
-10
@@ -1,23 +1,27 @@
|
||||
import pathlib
|
||||
|
||||
from release_plan.release_standing import Cut, LastCut, next_release, project_plan, Unknown
|
||||
from release_plan.release_standing import Cut, LastCut, next_release, project_plan, standing_of, Unknown
|
||||
from failure import Failure
|
||||
from larv_review.scoring import is_floor_item
|
||||
from release_plan.todo_table import Item, NoItemsTable
|
||||
from plan.todo_table import Item, NoItemsTable
|
||||
from project_config.main import located
|
||||
from release_plan.goals_file import OPTED_OUT
|
||||
from plan_store.stores import Plan, PlanStore
|
||||
from plan.goals_file import OPTED_OUT
|
||||
from plan_store.plans import Plan, PlanStore
|
||||
from plan_store import stores as plan_stores
|
||||
from project_config.settings import ProjectConfig
|
||||
from release_plan.release import Release, version
|
||||
from plan.release import Release, version
|
||||
from record_store import stores
|
||||
from larv_review.unmeasured import unmeasured_cut
|
||||
|
||||
|
||||
# The words that end the reason a chunk empties a release. Such a chunk is due two scoring runs; a chunk with any other reason, one.
|
||||
# The words that end the reason a chunk empties a release; SKILL.md → "Second run" quotes them.
|
||||
EMPTIED_WORDS = "with no plan item"
|
||||
|
||||
|
||||
class Emptied(str):
|
||||
"""The reason a chunk empties a release, which makes it due two scoring runs; a chunk with only other reasons is due one."""
|
||||
|
||||
|
||||
def scoring_run_due(before: list[Item], after: list[Item], ships: list[int], landed_release: Release | None, renamed: frozenset[Release], unmeasured: str | None = None) -> list[str] | Failure:
|
||||
"""Why the plan calls a scoring run, empty when it does not.
|
||||
|
||||
@@ -34,8 +38,7 @@ def scoring_run_due(before: list[Item], after: list[Item], ships: list[int], lan
|
||||
reasons.append(f"follows {unmeasured}")
|
||||
for release in emptied(before, after, shipped, renamed):
|
||||
if work_landed(release, shipped, landed_release):
|
||||
# SKILL.md → "Second run" keys on this wording.
|
||||
reasons.append(f"leaves release {version(release)} {EMPTIED_WORDS}")
|
||||
reasons.append(Emptied(f"leaves release {version(release)} {EMPTIED_WORDS}"))
|
||||
return reasons
|
||||
|
||||
|
||||
@@ -49,7 +52,7 @@ def landed_towards(found: list[Item], cut: LastCut) -> Release | None | Failure:
|
||||
"""The next release on the default branch, once work has landed towards it: once one or more changes are unreleased, as `release_standing.unreleased_changes` counts them. None where there is no next release, or no change is unreleased. found is the default branch's plan."""
|
||||
if isinstance(cut.tag, Failure):
|
||||
return Failure(f"could not tell the next release: the default branch's tags cannot be read: {cut.tag.reason}")
|
||||
upcoming = next_release(found, cut)
|
||||
upcoming = next_release(standing_of(found, cut), cut)
|
||||
if isinstance(upcoming, Unknown):
|
||||
return Failure("could not tell the next release: the default branch's todo.md history cannot be read")
|
||||
# Cut's release is the last cut's version or earlier, so no work lands towards it.
|
||||
@@ -86,7 +89,7 @@ def plan_reasons(ref: str, ids: list[int] | None, home: pathlib.Path) -> list[st
|
||||
if OPTED_OUT.search(decisions):
|
||||
return []
|
||||
held = project_plan(config, ref, checkout)
|
||||
before = held.todo
|
||||
before = held.plan
|
||||
read = checkout_plan(plan_stores.store(config))
|
||||
if isinstance(read, Failure):
|
||||
return read
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
"""The plan as a listing a reviewer reads with the Read tool, whatever store holds the plan."""
|
||||
from failure import Failure
|
||||
from release_plan.todo_table import Item
|
||||
from plan_store.stores import PlanStore
|
||||
from release_plan.release import version
|
||||
from plan.todo_table import Item
|
||||
from plan_store.plans import PlanStore
|
||||
from plan.release import version
|
||||
|
||||
|
||||
def plan_listing(plan: PlanStore) -> str:
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import decimal
|
||||
|
||||
from review_rules.comprehension_history import DIMENSIONS
|
||||
from release_plan.todo_table import Item
|
||||
from plan.todo_table import Item
|
||||
|
||||
# A floor item's tagline opens with this phrase, which a tagline quoting or mentioning the floor never does; a floor item's chunk runs a scoring run.
|
||||
FLOOR_ITEM = "Reach the comprehension floor:"
|
||||
|
||||
@@ -15,18 +15,20 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from larv_review.agreement import agreement_report, ruling_agreement, run_agreement
|
||||
from review_rules.comprehension_history import appended, entries, HistoryChange, latest_places, Place, recorded, ruling_entry, scoring_entry, ScoringRun, Seat
|
||||
from larv_review.plan import checkout_plan, EMPTIED_WORDS, landed_towards, plan_reasons, scoring_run_due
|
||||
from larv_review.history_commands import appended_to
|
||||
from larv_review.plan import checkout_plan, Emptied, EMPTIED_WORDS, landed_towards, plan_reasons, scoring_run_due
|
||||
from review_rules import comprehension_history
|
||||
from project_config.test_project_config import configured
|
||||
from larv_review.ruling import counted, ruling, split, surplus, votes
|
||||
from larv_review.history_commands import decided, rerank
|
||||
from project_config.settings import DEFAULT_FLOOR
|
||||
from failure import Failure
|
||||
from plan_store.stores import FilePlan
|
||||
from plan_store.todo_md import FilePlan
|
||||
from record_store.stores import FileStore
|
||||
from larv_review.scoring import floor_step, means, under_floor
|
||||
from record_store.held import Held
|
||||
from test_env import isolated_env
|
||||
from release_plan.todo_table import Item, items, NoItemsTable
|
||||
from plan.todo_table import Item, items, NoItemsTable
|
||||
from release_plan.release_standing import LastCut
|
||||
from larv_review.ruling_base import measured_commit
|
||||
from record_store.fakes import MemoryStore
|
||||
@@ -459,13 +461,23 @@ class LandedTowards(unittest.TestCase):
|
||||
self.assertEqual(landed_towards(plan, LastCut(Failure("fatal: bad object"), "", 3, [])), Failure("could not tell the next release: the default branch's tags cannot be read: fatal: bad object"))
|
||||
|
||||
|
||||
class AppendedTo(unittest.TestCase):
|
||||
def test_writes_the_entry_over_the_version_the_history_was_read_at(self):
|
||||
history = MemoryStore(label="history.md", version=5)
|
||||
self.assertEqual(appended_to(history, Held("", "5"), "PR #2 at abcdef1\n", "## an entry\n"), "Appended to history.md.")
|
||||
self.assertEqual(history.overs, ["5"])
|
||||
|
||||
|
||||
class Shortfall(unittest.TestCase):
|
||||
def test_skill_md_names_the_words_that_end_the_reason_a_release_empties(self):
|
||||
self.assertIn(EMPTIED_WORDS, (pathlib.Path(__file__).resolve().parents[2] / "skills" / "larv-review" / "SKILL.md").read_text(encoding="utf-8"))
|
||||
|
||||
def test_a_chunk_that_empties_a_release_owes_two_runs_and_any_other_reason_one(self):
|
||||
emptied = ["leaves release 0.1.0 with no plan item"]
|
||||
emptied = [Emptied("leaves release 0.1.0 with no plan item")]
|
||||
floor = ["ships item 2, a floor item"]
|
||||
# The type, not the words, makes a reason call two runs.
|
||||
self.assertIn("owes 1 scoring run and", shortfall(["leaves release 0.1.0 with no plan item"], 0).reason)
|
||||
self.assertIsInstance(scoring_run_due([item(1, (0, 1, 0))], [], [], (0, 1, 0), set())[0], Emptied)
|
||||
self.assertIn("owes 2 scoring runs and the branch's committed history records 1", shortfall(emptied + floor, 1).reason)
|
||||
self.assertIn("owes 1 scoring run and", shortfall(floor, 0).reason)
|
||||
self.assertIn("records 0:", shortfall(floor, -1).reason)
|
||||
@@ -983,7 +995,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] = []
|
||||
@@ -1250,7 +1262,7 @@ 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)
|
||||
|
||||
@@ -4,7 +4,7 @@ import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from plan_store.stores import BLOCKED_BY
|
||||
from plan.todo_table import BLOCKED_BY
|
||||
from plan_store.contract import FIRST, SECOND
|
||||
from plan_store.fakes import MemoryPlan
|
||||
from larv_review.plan_listing import plan_listing
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
"""The todo.md items a chunk takes: those the worker names on its latest `Chunk items:` line, scored as todo.md scores them (docs/decisions.md → `routing: loop-claude reads the items a chunk takes`)."""
|
||||
"""The plan items a chunk takes: those the worker names on its latest `Chunk items:` line, scored as the plan scores them (docs/decisions.md → `routing: loop-claude reads the items a chunk takes`)."""
|
||||
import re
|
||||
|
||||
from claude_code.entries import AssistantTurn, Entry, Text
|
||||
from failure import Failure
|
||||
from loop_claude.quotes import plain
|
||||
from plan_store.stores import Plan
|
||||
from plan_store.plans import Plan
|
||||
from loop_claude.verdicts import TakenIn
|
||||
|
||||
# The label opening the line; prompts.NAME_THE_ITEMS asks the worker for it.
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -31,7 +31,7 @@ INTERRUPT_RULES = (
|
||||
"- it is blocked on something only the human can supply: a credential, a version bump, a choice "
|
||||
"outside the repo, or a release ready to cut, which only the human may publish\n"
|
||||
"- it flags that the goals need changing\n"
|
||||
"- it flags that the plan in todo.md or the task itself is unclear or missing, and recommends no way on\n\n"
|
||||
"- it flags that the plan or the task itself is unclear or missing, and recommends no way on\n\n"
|
||||
"interrupt=false otherwise. A choice in the repo that no rule reserves for the human is the worker's to make, "
|
||||
"so its taking its own recommendation on one is no reason to interrupt. Where it asks about such a choice and "
|
||||
"recommends an answer, quote the sentence of that rule telling it to take the option it would recommend, even "
|
||||
|
||||
@@ -1,18 +1,18 @@
|
||||
"""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
|
||||
|
||||
# Where the judge may quote an answer from, named as the human and the worker see them; of the goals file the judge sees only the premises.
|
||||
QUOTE_SOURCES = listed(("the goals file's Goals and Audience", *RECORD_FILES, *HUMAN_RULE_NAMES), "or")
|
||||
# Where the worker may write an answer the human typed, so it counts as recorded.
|
||||
ANSWER_DESTINATIONS = "the goals file's Goals or Audience, " + ", ".join(RECORD_FILES) + ", todo.md or a comment"
|
||||
ANSWER_DESTINATIONS = "the goals file's Goals or Audience, " + ", ".join(RECORD_FILES) + ", the plan or a comment"
|
||||
ANSWERS_RECORDED = f"every answer the human typed in it that a later chunk could need is recorded in {ANSWER_DESTINATIONS} at the one place it governs"
|
||||
# How review_launches names the reviews: "each reviewer" covers every pass with an agent.
|
||||
EACH_REVIEWER = "each reviewer"
|
||||
@@ -23,29 +23,29 @@ THE_SECURITY_PASS = "the security pass's subagent"
|
||||
# Workers only, not CLAUDE.md, which reviewers load too: a reviewer under a like rule missed findings.
|
||||
READING_RULE = "Read in small pieces: never read more than 80 lines of a file at once, nor take a tool output over 3,000 characters into your context."
|
||||
# chunk_items reads the latest such line; three fresh readers picked the label (docs/decisions.md → `routing: loop-claude reads the items a chunk takes`).
|
||||
NAME_THE_ITEMS = f"Name every todo.md item this chunk takes on one line, as in `{CHUNK_ITEMS} 297 (L 3, E + I 5), 298 (L 3, E + I 7)`, and write the whole line again whenever the set changes."
|
||||
NAME_THE_ITEMS = f"Name every plan item this chunk takes on one line, as in `{CHUNK_ITEMS} 297 (L 3, E + I 5), 298 (L 3, E + I 7)`, and write the whole line again whenever the set changes."
|
||||
|
||||
|
||||
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}"
|
||||
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 plan 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),
|
||||
))
|
||||
|
||||
|
||||
def recount(route: Route) -> str:
|
||||
"""Has the worker count the routing item's size again once it knows the code, since the L that routed it was scored before anyone read that code."""
|
||||
return f"After your first read of the code, count item {route.item}'s size again: the lines, files and components you will change. Where that count would change its L, have a subagent that scores todo.md items re-score it; a re-score whose L picks a rung above yours is escalation trigger 1."
|
||||
return f"After your first read of the code, count item {route.item}'s size again: the lines, files and components you will change. Where that count would change its L, have a subagent that scores plan items re-score it; a re-score whose L picks a rung above yours is escalation trigger 1."
|
||||
|
||||
|
||||
def preflight_facts(printed: str) -> str:
|
||||
@@ -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]:
|
||||
"""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 []
|
||||
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 plan items. On an Opus 5.5 project: `Your rung is below the project's: launch each subagent that files or scores plan 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 plan 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,16 +14,17 @@ 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
|
||||
from plan_store.plans import Plan
|
||||
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
|
||||
@@ -48,10 +51,12 @@ class Cycle:
|
||||
route: Route
|
||||
session: Session
|
||||
task: str
|
||||
# todo.md on the default branch as the cycle starts, which scores the items the worker names.
|
||||
todo: Plan | Failure
|
||||
# The plan on the default branch as the cycle starts, which scores the items the worker names.
|
||||
plan: 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:
|
||||
@@ -155,7 +160,7 @@ def rule(cycle: Cycle, transcript_path: str, quoted_answers: int) -> Ruled | Sto
|
||||
if isinstance(verdict, Stop):
|
||||
return verdict
|
||||
if not isinstance(verdict, Finished):
|
||||
verdict = dataclasses.replace(verdict, taken_in=chunk_items.taken_in(entries, cycle.todo))
|
||||
verdict = dataclasses.replace(verdict, taken_in=chunk_items.taken_in(entries, cycle.plan))
|
||||
if not isinstance(verdict, Interrupt | QuotedAnswer):
|
||||
return Ruled(verdict)
|
||||
annotation = annotation_of(cycle, transcript_path, entries, verdict.judged)
|
||||
@@ -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
|
||||
|
||||
@@ -7,42 +7,39 @@ from release_plan.release_standing import DefaultPlan, project_plan, UNSEEN_RELE
|
||||
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 release_plan.todo_table import Item
|
||||
from loop_claude.loop.chunk_windows import held_beside, item_of
|
||||
from chunk_preflight.main import ITEM
|
||||
from 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 plan_store.plans import Plan
|
||||
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.
|
||||
ORIGIN_TIMEOUT = 60
|
||||
|
||||
|
||||
def fetched_todo(loop: Loop) -> Plan | Failure:
|
||||
"""The plan, which scores the items a chunk takes: on the default branch as last fetched, or as it stands where the project's config puts it outside the checkout. fetched_plan reads it too, but also the release tag, CHANGELOG.md and each todo.md since the tag, which scoring the items doesn't need. Where it can't be read or scored, it says why."""
|
||||
ref = default_ref(loop.root, ORIGIN_TIMEOUT, run=loop.effects.git)
|
||||
config = located(loop.root, loop.paths.home)
|
||||
if isinstance(config, Failure):
|
||||
todo: Plan | Failure = config
|
||||
else:
|
||||
todo = ref if isinstance(ref, Failure) else held_at(ref, plan_store(config), loop.root, loop.effects.git)
|
||||
if isinstance(todo, Failure):
|
||||
say(f"the items the worker names lift no rung: {todo.reason}", loop.effects)
|
||||
return todo
|
||||
def scored_plan(default: DefaultPlan | Failure, effects: Effects) -> Plan | Failure:
|
||||
"""The plan, which scores the items a chunk takes, from what the default branch holds; where it can't be read or scored, it says why."""
|
||||
plan = default.plan if isinstance(default, DefaultPlan) else default
|
||||
if isinstance(plan, Failure):
|
||||
say(f"the items the worker names lift no rung: {plan.reason}", effects)
|
||||
return plan
|
||||
|
||||
|
||||
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:
|
||||
@@ -58,38 +55,39 @@ def archived_route(archive_folder: pathlib.Path, loop: Loop) -> Route | None:
|
||||
return route
|
||||
|
||||
|
||||
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)
|
||||
def chunk_start(loop: Loop) -> tuple[str, DefaultPlan | Failure]:
|
||||
"""The facts for a fresh worker's prompt, empty where the session is open, and what the default branch holds, read once for the cycle: it routes the chunk, through plan_item, and scores the items the worker names, through scored_plan. It 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."""
|
||||
fresh = not session_open(loop.session)
|
||||
return chunk_facts(loop) if fresh else "", fetched_plan(loop, fresh)
|
||||
|
||||
|
||||
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:
|
||||
"""What the default branch, as last fetched, holds for routing; the plan and the changelog as they stand where the project's config puts them outside the checkout. It says UNSEEN_RELEASES for such a plan."""
|
||||
def fetched_plan(loop: Loop, announce: bool = True) -> DefaultPlan | Failure:
|
||||
"""What the default branch, as last fetched, holds for routing; the plan and the changelog as they stand where the project's config puts them outside the checkout. Where announce is True, as when a chunk starts, it says UNSEEN_RELEASES for such a plan, so the human reads it once per chunk, not every cycle."""
|
||||
config = located(loop.root, loop.paths.home)
|
||||
if isinstance(config, Failure):
|
||||
return config
|
||||
if config.tracked("plan") is None:
|
||||
if announce and config.tracked("plan") is None:
|
||||
say(UNSEEN_RELEASES, loop.effects)
|
||||
ref = default_ref(loop.root, ORIGIN_TIMEOUT, run=loop.effects.git)
|
||||
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.plan, plan.cut, window_item)
|
||||
if isinstance(item, Failure):
|
||||
say(f"routing on the project's rung: {item.reason}", effects)
|
||||
return None
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
"""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 dataclasses
|
||||
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 release_plan.next_chunk import NextChunk, NoItem, planned
|
||||
from touch_predictions.prediction import overlaps, predicted, Touches
|
||||
from loop_state.paths import Paths
|
||||
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
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Room:
|
||||
"""What a project's windows leave room for, under its limit of chunks at once."""
|
||||
# The chunks whose windows run.
|
||||
running: list[str]
|
||||
# The chunks whose windows are dead: their loop stopped or failed, and the window keeps its last lines and its items.
|
||||
stopped: list[str]
|
||||
# The stopped chunks to start again, before any chunk from the plan.
|
||||
restart: list[str]
|
||||
# How many chunks from the plan may start beside them.
|
||||
left: int
|
||||
|
||||
|
||||
def room_of(windows: list[tmux.Listed], own: str | None, leaving: bool, limit: int) -> Room:
|
||||
"""The room windows leave under limit. own is the chunk of the loop that asks, None for the human's loop-claude <task>. leaving is True where own's chunk finished: its window no longer counts as running, and no stopped chunk starts again, since only a loop that isn't leaving, such as the human's loop-claude <task>, restarts one."""
|
||||
running = [window.name for window in windows if not window.dead and not (leaving and window.name == own)]
|
||||
# Below 0 where the config lowered parallel-chunks while more chunks ran.
|
||||
room = max(limit - len(running), 0)
|
||||
stopped = [window.name for window in windows if window.dead]
|
||||
restart = [] if leaving else stopped[:room]
|
||||
return Room(running, stopped, restart, room - len(restart))
|
||||
|
||||
|
||||
def may_start(plan: NextChunk | NoItem, running: list[str], held: set[int], room: 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 room of them. 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 or room < 1 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(room, 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) -> NextChunk | 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.plan, 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")
|
||||
room = room_of(windows, loop_run.chunk, leaving, config.parallel_chunks)
|
||||
chunks = list(room.restart)
|
||||
if room.left:
|
||||
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(room.running + room.stopped, key, paths.claude_code_transcripts)
|
||||
chunks += [chunk for chunk in may_start(plan, room.running + room.restart, held, room.left) if chunk not in room.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)
|
||||
wait_for_starts(paths.home, key)
|
||||
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))
|
||||
|
||||
|
||||
def wait_for_starts(home: pathlib.Path, key: str) -> None:
|
||||
"""Returns once no loop of the project is starting windows: start_chunks holds LOCK while it starts them. Where the lock cannot be taken, it returns at once."""
|
||||
with contextlib.suppress(OSError), starting(home, key):
|
||||
pass
|
||||
@@ -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)
|
||||
|
||||
@@ -3,26 +3,28 @@ import pathlib
|
||||
import typing
|
||||
|
||||
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.chunk_start import archived_route, chunk_start, plan_item, routed, scored_plan
|
||||
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, item_of, 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,37 @@ 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)
|
||||
facts, default = chunk_start(loop)
|
||||
project = ladder.project_rung(models.worker)
|
||||
route = routed(loop_run.route, ladder, project, models.worker, lambda: archived_route(archive_folder, loop), lambda: plan_item(default, item_of(loop.window.name), loop.effects))
|
||||
say(f"\n=== cycle {loop_run.cycle_number}, worker on {route.rung} ===", loop.effects, stdout=True)
|
||||
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)
|
||||
if ladder_file != SHIPPED:
|
||||
say(own_ladder(ladder_file, models.worker, project is None), loop.effects)
|
||||
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, plan=scored_plan(default, loop.effects), 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.
|
||||
|
||||
@@ -8,13 +8,13 @@ as goals-and-audience: a file, or a Jira epic's description. `project-config goa
|
||||
prints where it is. The task runs at the checkout root. Each cycle a worker runs the task. A chunk's
|
||||
first worker prompt also quotes the premises. They, with code health (~/.claude/CLAUDE.md →
|
||||
"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
|
||||
chunk's plan 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 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
|
||||
into the premises, AGENTS.md, docs/decisions.md, the plan or a 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
|
||||
@@ -22,31 +22,58 @@ asked again after its answer. A question the human answered earlier in the chunk
|
||||
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.
|
||||
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 plan 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
|
||||
@@ -76,9 +104,25 @@ each review's rung in bin/model_routing/review_choice.py, and the prompts' wordi
|
||||
bin/loop_claude/cycle/prompts.py. Each verdict, interrupt, quoted answer, stop and
|
||||
step-up in the archive ends with a Worker: line, the route as JSON (Route.worker_line in
|
||||
bin/model_routing/route.py); a rerun resumes an open chunk on the latest route named there. A
|
||||
todo.md or an archive that cannot be read or parsed is said on stderr, and the chunk is routed
|
||||
plan 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
|
||||
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."""
|
||||
|
||||
@@ -3,7 +3,7 @@ import pathlib
|
||||
from failure import Failure
|
||||
from record_store.stores import goals_store
|
||||
from project_config.main import located
|
||||
from release_plan.goals_file import section
|
||||
from plan.goals_file import section
|
||||
|
||||
|
||||
def read_premises(root: str, home: pathlib.Path) -> str | Failure:
|
||||
|
||||
@@ -5,10 +5,10 @@ from project_config.main import located
|
||||
from loop_claude.project.text_file import read_utf8
|
||||
from record_store.stores import store
|
||||
|
||||
# The records the judge reads beside the premises: these project files, then the human's rules below.
|
||||
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 records the judge reads beside the premises, by the name that heads each, with the setting in the project's config that places it; then the human's rules below.
|
||||
WORKING_RULES = ("AGENTS.md", "working-rules")
|
||||
DECISIONS = ("docs/decisions.md", "decisions")
|
||||
RECORD_FILES = (WORKING_RULES[0], DECISIONS[0])
|
||||
# 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"
|
||||
@@ -27,8 +27,8 @@ def read_records(root: str, home: pathlib.Path, claude_dir: pathlib.Path) -> str
|
||||
if isinstance(config, Failure):
|
||||
return Failure(f"{config.reason} - {CONSEQUENCE}.")
|
||||
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)]
|
||||
decisions = store(config, DECISIONS[1]).read()
|
||||
texts = [(WORKING_RULES[0], file_text(config.paths[WORKING_RULES[1]])), (DECISIONS[0], Failure(f"{decisions.reason} - {CONSEQUENCE}.") if isinstance(decisions, Failure) else decisions)]
|
||||
texts += [(named(rule, home, claude_dir), file_text(rule)) for rule in rules]
|
||||
records = []
|
||||
for heading, text in texts:
|
||||
|
||||
+43
-40
@@ -30,12 +30,12 @@ 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 plan_store.stores import Plan
|
||||
from plan.todo_table import Item, NoItemsTable
|
||||
from model_routing.ladder import Ladder, Rung
|
||||
from plan_store.plans import Plan
|
||||
from model_routing.route import Route
|
||||
|
||||
UNFINISHED_PER_STEP = 2
|
||||
@@ -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,13 +449,13 @@ 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"))
|
||||
self.assertEqual(argument(workers[2], "--session-id"), session)
|
||||
self.assertTrue(argument(workers[0], "-p").startswith(f"{TASK}\n\nContinue any open draft PR"))
|
||||
self.assertTrue(argument(workers[0], "-p").endswith("The chunk's todo.md items, or else the task above, set its scope. The goals below, " 'which rank after code health (~/.claude/CLAUDE.md → "Shared goal") unless the goals file voids it' ", choose between ways to deliver that scope, and never widen it.\n\nFrom the goals file, " f"{checkout.root}/README.md:\n## Goals\n1. Work.\n\n## Audience\nMe."))
|
||||
self.assertTrue(argument(workers[0], "-p").endswith("The chunk's plan items, or else the task above, set its scope. The goals below, " 'which rank after code health (~/.claude/CLAUDE.md → "Shared goal") unless the goals file voids it' ", choose between ways to deliver that scope, and never widen it.\n\nFrom the goals file, " f"{checkout.root}/README.md:\n## Goals\n1. Work.\n\n## Audience\nMe."))
|
||||
self.assertIn("main or master", argument(workers[0], "-p"))
|
||||
self.assertNotIn(TASK, argument(workers[1], "-p"))
|
||||
self.assertIn("Even then, it is finished only once every answer the human typed in it", argument(workers[1], "-p"))
|
||||
@@ -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)
|
||||
|
||||
+631
-137
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,103 @@
|
||||
"""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, or why it could not mark a session it made as this checkout's."""
|
||||
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}'}")
|
||||
# set-option and show-options read a target as a pane's, so `=session` alone names no session.
|
||||
owned = run(["set-option", "-t", f"={window.session}:", OWNER, cwd]) if first else None
|
||||
# By the ID, since a window of the same name may still be closing. A failed remain-on-exit doesn't matter: a loop that fails before it 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"])
|
||||
# Without the owner, start_chunks cannot tell this checkout's session from another's, so no further chunk may start in it.
|
||||
if owned is not None and owned.returncode:
|
||||
return Failure(f"tmux started the session {window.session} but could not mark it as this checkout's: {owned.stderr.strip() or f'it exited {owned.returncode}'}")
|
||||
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}"]
|
||||
@@ -6,7 +6,7 @@ from claude_code.tokens import Tokens
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class TakenIn:
|
||||
"""The levels of the todo.md items the worker names on its latest `Chunk items:` line, as cycle.chunk_items reads them. The item the chunk was routed on counts only where the worker names it."""
|
||||
"""The highest L, and the highest E + I, among the plan items the worker names on its latest `Chunk items:` line, as cycle.chunk_items reads them. The item the chunk was routed on counts only where the worker names it."""
|
||||
# The highest L among them, 0 for none: an escalation steps up from the rung that L picks, and an unfinished verdict also raises the worker to it.
|
||||
highest_likelihood: int = 0
|
||||
# The highest E + I among them, 0 for none: after an unfinished verdict, it routes the next cycle's reviewers.
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -3,7 +3,7 @@ import dataclasses
|
||||
import json
|
||||
import typing
|
||||
|
||||
from release_plan.todo_table import LEVELS
|
||||
from plan.todo_table import LEVELS
|
||||
from model_routing.ladder import REVIEW_STEPS, Rung
|
||||
|
||||
# How a worker opens the prompt of a subagent it escalates a task to, `Escalation trigger 2: …`: docs/decisions.md → `routing: a worker hands a task one rung up`.
|
||||
|
||||
@@ -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 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
|
||||
|
||||
@@ -3,12 +3,11 @@ import dataclasses
|
||||
import pathlib
|
||||
import typing
|
||||
|
||||
from project_config.settings import CONFIG, Notifier, NOTIFIER, NOTIFIERS, ProjectConfig
|
||||
from failure import Failure
|
||||
from rest_client.json_request import Http
|
||||
from project_config.main import located
|
||||
import mattermost_dm.dm
|
||||
from project_config.settings import Notifier, NOTIFIER, NOTIFIERS, ProjectConfig
|
||||
import slack_dm.dm
|
||||
from notifier import mattermost, slack
|
||||
|
||||
# Sends one message, with the credentials already read.
|
||||
Sender = typing.Callable[[str], Failure | None]
|
||||
@@ -25,8 +24,8 @@ class Backend[C]:
|
||||
|
||||
# The one place each notifier is wired to the network: a caller that tests a send passes a table with its own `http`.
|
||||
BACKENDS: dict[Notifier, Backend[typing.Any]] = {
|
||||
"mattermost": Backend(mattermost_dm.dm.read_config, mattermost_dm.dm.send, mattermost_dm.dm.http_json, mattermost_dm.dm.KEYS),
|
||||
"slack": Backend(slack_dm.dm.read_config, slack_dm.dm.send, slack_dm.dm.http_json, slack_dm.dm.KEYS),
|
||||
"mattermost": Backend(mattermost.read_config, mattermost.send, mattermost.http_json, mattermost.KEYS),
|
||||
"slack": Backend(slack.read_config, slack.send, slack.http_json, slack.KEYS),
|
||||
}
|
||||
assert tuple(BACKENDS) == NOTIFIERS
|
||||
|
||||
@@ -34,9 +33,9 @@ assert tuple(BACKENDS) == NOTIFIERS
|
||||
def sender_of(project: ProjectConfig, backends: typing.Mapping[Notifier, Backend[typing.Any]]) -> Sender | Failure:
|
||||
"""A sender through the project's notifier in backends, with the credentials in its env file read. A Failure where the project names no notifier or its env file cannot be used."""
|
||||
if project.notifier is None:
|
||||
return Failure(f"{project.folder / 'config.toml'} sets no `{NOTIFIER}`; set `notifier` to {' or '.join(NOTIFIERS)}, and `env-file` to the file that holds that service's keys ({'; '.join(f'{name}: {', '.join(backend.keys)}' for name, backend in backends.items())})")
|
||||
return Failure(f"{project.folder / CONFIG} sets no `{NOTIFIER}`; set `notifier` to {' or '.join(NOTIFIERS)}, and `env-file` to the file that holds that service's keys ({'; '.join(f'{name}: {', '.join(backend.keys)}' for name, backend in backends.items())})")
|
||||
if project.env_file is None:
|
||||
return Failure(f"{project.folder / 'config.toml'} sets `{NOTIFIER}` but no `env-file`, the file that holds its credentials")
|
||||
return Failure(f"{project.folder / CONFIG} sets `{NOTIFIER}` but no `env-file`, the file that holds its credentials")
|
||||
backend = backends[project.notifier]
|
||||
config = backend.read_config(project.env_file)
|
||||
if isinstance(config, Failure):
|
||||
|
||||
@@ -6,7 +6,7 @@ import unittest.mock
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from mattermost_dm import dm
|
||||
from notifier import mattermost as dm
|
||||
from failure import Failure
|
||||
|
||||
CONFIG = dm.Config("https://chat.example", "secret-token", "lilleman")
|
||||
@@ -16,9 +16,9 @@ from rest_client.json_request import Http
|
||||
from test_env import isolated_env
|
||||
from project_config.main import located
|
||||
from notifier import main, notify
|
||||
from mattermost_dm.test_mattermost_dm import mattermost
|
||||
from notifier.test_mattermost import mattermost
|
||||
from project_config.settings import Notifier
|
||||
from slack_dm.test_slack_dm import Slack
|
||||
from notifier.test_slack import Slack
|
||||
from loop_effects.effects import system_effects
|
||||
|
||||
TOOL = pathlib.Path(__file__).resolve().parents[1] / "notify"
|
||||
|
||||
@@ -6,7 +6,7 @@ import unittest.mock
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from slack_dm import dm
|
||||
from notifier import slack as dm
|
||||
from failure import Failure
|
||||
|
||||
CONFIG = dm.Config("xoxb-secret", "U0123ABCD")
|
||||
@@ -3,8 +3,8 @@ import dataclasses
|
||||
import graphlib
|
||||
|
||||
from failure import Failure
|
||||
from release_plan.todo_table import Item
|
||||
from release_plan.release import version
|
||||
from plan.todo_table import Item
|
||||
from plan.release import version
|
||||
|
||||
|
||||
def blockers_first(scored: list[tuple[Item, float]]) -> list[tuple[Item, float]] | Failure:
|
||||
@@ -1,7 +1,7 @@
|
||||
import re
|
||||
|
||||
from failure import Failure
|
||||
from release_plan.todo_table import Item
|
||||
from plan.todo_table import Item
|
||||
|
||||
|
||||
def check_citations(items: list[Item], decisions: str) -> Failure | None:
|
||||
@@ -4,7 +4,7 @@ import decimal
|
||||
import re
|
||||
import typing
|
||||
|
||||
from release_plan.todo_table import CODE_HEALTH
|
||||
from plan.todo_table import CODE_HEALTH
|
||||
from failure import Failure
|
||||
from text_files.markdown_text import sections
|
||||
|
||||
@@ -7,15 +7,15 @@ import math
|
||||
import re
|
||||
import typing
|
||||
|
||||
from release_plan.todo_table import BLOCKED_BY, cells, CODE_HEALTH, DETAILS, Exempt, HEADER_START, Item, item_details, items_table, MOVES, OLD_SHAPE, parse_row, renames, risk, Shape, SHAPE, shape_of, Table, table_rows
|
||||
from release_plan.blockers import blocked_through, blockers_first
|
||||
from release_plan.citations import check_citations
|
||||
from release_plan.formula import evaluate, parse_formula
|
||||
from plan.todo_table import BLOCKED_BY, cells, CODE_HEALTH, detail_heading, DETAILS, Exempt, HEADER_START, Item, item_details, items_table, MOVES, OLD_SHAPE, parse_row, renames, risk, row_cells, Shape, SHAPE, shape_of, Table, table_rows, tagline_text
|
||||
from plan.blockers import blocked_through, blockers_first
|
||||
from plan.citations import check_citations
|
||||
from plan.formula import evaluate, parse_formula
|
||||
from failure import Failure
|
||||
from release_plan.goals_file import goal_weights, Mark, ranked_goals
|
||||
from plan.goals_file import goal_weights, Mark, ranked_goals
|
||||
from review_rules.comprehension_history import latest_overall
|
||||
from text_files.markdown_text import listed
|
||||
from release_plan.release import version
|
||||
from plan.release import version
|
||||
|
||||
# What a point of an item's move on a maintain goal is worth. A defect that restores the goal weighs it at least this much per point. docs/decisions.md records the choice and its data.
|
||||
MAINTAIN_WEIGHT = 0.5
|
||||
@@ -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,25 +295,43 @@ 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
|
||||
|
||||
|
||||
def render_item(item: Item, value: float, shape: Shape, columns: tuple[str, ...]) -> str:
|
||||
"""The item's row, each cell under its column."""
|
||||
written = {"ID": str(item.id), "Release": version(item.release), BLOCKED_BY: ", ".join(map(str, item.blocked_by)), "Exempt": item.exempt, "Item": item.tagline, **{name: str(score) for name, score in item.scores.items()}, shape.goals_column: shape.write_goals(item.moves), "Score": f"{value:.1f}"}
|
||||
written = row_cells(item, shape) | {"Score": f"{value:.1f}"}
|
||||
return "| " + " | ".join(written[column] for column in columns) + " |"
|
||||
|
||||
|
||||
@@ -316,7 +342,7 @@ def rank_details(text: str, items: list[Item]) -> str | Failure:
|
||||
return details if isinstance(details, Failure) else text
|
||||
if unknown := sorted(set(details) - {item.id for item in items}):
|
||||
return Failure(f"## Details holds item {', '.join(map(str, unknown))}, which the items table does not")
|
||||
headed = [f"### {item.id}. {item.tagline.strip('*').replace(chr(92) + '|', '|')}\n\n{details[item.id]}\n" for item in items if item.id in details]
|
||||
headed = [f"{detail_heading(item.id, tagline_text(item.tagline))}\n\n{details[item.id]}\n" for item in items if item.id in details]
|
||||
ranked = "\n" + "\n".join(headed) if headed else "\n"
|
||||
tail = "\n" if section.end() < len(text) else ""
|
||||
return text[:section.start(1)] + ranked + tail + text[section.end():]
|
||||
@@ -10,6 +10,9 @@ VERSION = r"[0-9]+\.[0-9]+\.[0-9]+"
|
||||
DATE_DIGITS = (4, 2, 2)
|
||||
DATED = re.compile(rf"({VERSION}) - " + "-".join(f"[0-9]{{{digits}}}" for digits in DATE_DIGITS))
|
||||
TAG = re.compile(rf"v({VERSION})")
|
||||
# The title of CHANGELOG.md's section for news not yet released: Unreleased, or a title that says unreleased, such as `0.6.0 (unreleased)`, as a project's own changelog may head it; and its ## heading.
|
||||
UNRELEASED_TITLE = r"(?i:.*unreleased.*)"
|
||||
UNRELEASED_HEADING = re.compile(rf"^## {UNRELEASED_TITLE}$", re.M)
|
||||
|
||||
|
||||
def release_of(version: str) -> Release:
|
||||
@@ -5,10 +5,10 @@ import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from release_plan.test_ranking import DECISIONS, README, TODO
|
||||
from plan.test_ranking import DECISIONS, README, TODO
|
||||
from project_config.settings import DEFAULT_FLOOR
|
||||
from failure import Failure
|
||||
from release_plan import ranking, todo_table
|
||||
from plan import ranking, todo_table
|
||||
|
||||
|
||||
class Blockers(unittest.TestCase):
|
||||
@@ -4,10 +4,10 @@ import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from release_plan.test_ranking import DECISIONS, README, TODO
|
||||
from plan.test_ranking import DECISIONS, README, TODO
|
||||
from project_config.settings import DEFAULT_FLOOR
|
||||
from failure import Failure
|
||||
from release_plan import ranking
|
||||
from plan import ranking
|
||||
|
||||
|
||||
class Formula(unittest.TestCase):
|
||||
@@ -1,7 +1,7 @@
|
||||
import unittest
|
||||
|
||||
from failure import Failure
|
||||
from release_plan.goals_file import section
|
||||
from plan.goals_file import section
|
||||
|
||||
GOALS_FILE = "# P\n## Goals\n1. g\n## Audience\nme\n"
|
||||
|
||||
@@ -4,7 +4,7 @@ import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from release_plan.named_code import named_files, named_paths
|
||||
from plan.named_paths import named_files, named_paths
|
||||
|
||||
|
||||
class NamedPaths(unittest.TestCase):
|
||||
@@ -12,10 +12,11 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
from project_config.test_project_config import configured
|
||||
from project_config.settings import DEFAULT_FLOOR
|
||||
from failure import Failure
|
||||
from release_plan import goals_file, plan_file, ranking
|
||||
from plan_store.stores import file_plan
|
||||
from plan import goals_file, ranking
|
||||
from project_config.main import located
|
||||
from repo_checks import ROOT
|
||||
from release_plan import todo_table
|
||||
from plan import todo_table
|
||||
|
||||
# Voids code health, so these tests weigh only the project's own goals; class CodeHealth weighs it.
|
||||
VOID = "**Void:** code health, since a test project has no code to read.\n\n"
|
||||
@@ -271,6 +272,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"})
|
||||
@@ -365,7 +379,7 @@ class CodeHealth(unittest.TestCase):
|
||||
pathlib.Path(temp, "docs").mkdir()
|
||||
pathlib.Path(temp, "docs", "comprehension-history.md").write_text(SCORED.format(overall="7.00"))
|
||||
with contextlib.redirect_stderr(io.StringIO()):
|
||||
ranked = plan_file.rank_file(todo, located(temp, pathlib.Path.home()))
|
||||
ranked = file_plan(located(temp, pathlib.Path.home()), todo).rank()
|
||||
self.assertIsInstance(ranked, ranking.Ranked)
|
||||
self.assertEqual(ranked.under_bar, [])
|
||||
self.assertIn("| code health by 1 | 25.4 |", todo.read_text())
|
||||
@@ -382,10 +396,10 @@ class CodeHealth(unittest.TestCase):
|
||||
pathlib.Path(temp, "docs").mkdir()
|
||||
pathlib.Path(temp, "docs", "comprehension-history.md").write_text(SCORED.format(overall="6.50"))
|
||||
with contextlib.redirect_stderr(io.StringIO()):
|
||||
ranked = plan_file.rank_file(todo, located(temp, pathlib.Path.home()))
|
||||
ranked = file_plan(located(temp, pathlib.Path.home()), todo).rank()
|
||||
self.assertIsInstance(ranked, ranking.Ranked)
|
||||
self.assertIn("| code health by 1 | 25.4 |", todo.read_text())
|
||||
self.assertEqual(plan_file.check_failures(todo, located(temp, pathlib.Path.home())), [])
|
||||
self.assertEqual(file_plan(located(temp, pathlib.Path.home()), todo).check(), [])
|
||||
|
||||
|
||||
class Risk(unittest.TestCase):
|
||||
@@ -461,6 +475,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"))
|
||||
@@ -7,7 +7,7 @@ import unittest
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from test_env import isolated_env
|
||||
from release_plan.release import newest_tag, tagged
|
||||
from plan.release import newest_tag, tagged
|
||||
|
||||
|
||||
class NewestTag(unittest.TestCase):
|
||||
@@ -4,7 +4,7 @@ import typing
|
||||
|
||||
from failure import Failure
|
||||
from text_files.markdown_text import FENCE, sections
|
||||
from release_plan.release import parsed, Release, release_of, VERSION
|
||||
from plan.release import parsed, Release, release_of, version, VERSION
|
||||
|
||||
# Each score a Shape names, and each goal's move, runs from 1 to TOP_SCORE, but for the levels L, E and I, which run from 1 to their LEVELS: ~/.claude/rules/todo-items.md defines each level.
|
||||
TOP_SCORE = 10
|
||||
@@ -43,7 +43,7 @@ class Shape:
|
||||
risk_columns: tuple[str, ...]
|
||||
# The scores rank_todo.py works out and writes, so a blank cell reads as no score yet.
|
||||
derived: tuple[str, ...]
|
||||
# The column naming the goals an item serves; read_goals reads it, given the item's ID to name in a failure, and write_goals writes it back.
|
||||
# The column naming the goals an item serves; read_goals reads it, given what a failure calls the item, and write_goals writes it back.
|
||||
goals_column: str
|
||||
read_goals: typing.Callable[[str, str], Moves | Failure]
|
||||
write_goals: typing.Callable[[Moves], str]
|
||||
@@ -59,17 +59,17 @@ class Shape:
|
||||
return tuple(column for column in self.columns if column not in self.optional)
|
||||
|
||||
|
||||
def parse_moves(id_: str, cell: str) -> Moves | Failure:
|
||||
def parse_moves(label: str, cell: str) -> Moves | Failure:
|
||||
"""A Moves cell: empty, or each goal the item moves, named once, and how far. ranking.py's cited_goals_failure holds the rules that need the goals file."""
|
||||
matches = [re.fullmatch(rf"([0-9]+(?:\.[0-9]+)*|{CODE_HEALTH}) by ([0-9]+)", move) for move in cell.split(", ")] if cell else []
|
||||
moves = tuple((match.group(1), int(match.group(2))) for match in matches if match)
|
||||
if len(moves) < len(matches) or any(not 1 <= by <= TOP_SCORE for _, by in moves):
|
||||
return Failure(f"item {id_}'s {MOVES} {cell!r} is not empty or goals such as `1.1 by 8, {CODE_HEALTH} by 5`, each moved by a whole number from 1 to {TOP_SCORE}")
|
||||
return Failure(f"{label}'s {MOVES} {cell!r} is not empty or goals such as `1.1 by 8, {CODE_HEALTH} by 5`, each moved by a whole number from 1 to {TOP_SCORE}")
|
||||
goals = [goal for goal, _ in moves]
|
||||
if repeated := [goal for goal in goals if goals.count(goal) > 1]:
|
||||
return Failure(f"item {id_} cites goal {repeated[0]} twice; name each goal once")
|
||||
return Failure(f"{label} cites goal {repeated[0]} twice; name each goal once")
|
||||
if nested := [(parent, goal) for parent in goals for goal in goals if goal.startswith(parent + ".")]:
|
||||
return Failure(f"item {id_} names goal {nested[0][0]} and its sub-goal {nested[0][1]}; name one, never both: the sub-goal where the move serves it, else the parent")
|
||||
return Failure(f"{label} names goal {nested[0][0]} and its sub-goal {nested[0][1]}; name one, never both: the sub-goal where the move serves it, else the parent")
|
||||
return moves
|
||||
|
||||
|
||||
@@ -77,7 +77,7 @@ def write_moves(moves: Moves) -> str:
|
||||
return ", ".join(f"{goal} by {by}" for goal, by in moves)
|
||||
|
||||
|
||||
def parse_cited(id_: str, cell: str) -> Moves:
|
||||
def parse_cited(label: str, cell: str) -> Moves:
|
||||
"""An old-shape Goals cell, such as `2.1, 1`: each goal it cites, with no move."""
|
||||
return tuple((goal.strip(), None) for goal in cell.split(","))
|
||||
|
||||
@@ -268,49 +268,64 @@ def parse_row(row: str, table: Table) -> Item | Failure:
|
||||
if isinstance(found, Failure):
|
||||
return found
|
||||
named = dict(zip(table.columns, found))
|
||||
exempt = check_cells(row, named)
|
||||
if isinstance(exempt, Failure):
|
||||
return exempt
|
||||
id_, tagline = named["ID"], named["Item"]
|
||||
if not re.fullmatch(r"[0-9]+", id_) or int(id_) < 1:
|
||||
return Failure(f"the ID {id_!r} is not a positive whole number: {row}")
|
||||
if not re.fullmatch(r"\*\*[^*].*[^*]\*\*", tagline):
|
||||
return Failure(f"item {id_}'s Item cell is not one bold tagline: {tagline}")
|
||||
shape = shape_of(table.columns)
|
||||
scores = parse_scores(named["ID"], {name: cell for name, cell in named.items() if cell or name not in shape.derived}, shape.score_columns)
|
||||
fields = item_fields({name: cell for name, cell in named.items() if cell or name not in shape.derived}, f"item {id_}", shape, int(id_))
|
||||
if isinstance(fields, Failure):
|
||||
return fields
|
||||
assert fields.release is not None, "table_rows refuses a table without a Release column"
|
||||
return Item(int(id_), fields.release, fields.exempt, tagline, fields.scores, fields.moves, fields.blocked_by)
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class ItemFields:
|
||||
"""The cells of an item that a caller named, each held to the items table's format. A cell it didn't name reads as empty, and the release as None."""
|
||||
release: Release | None = None
|
||||
exempt: Exempt = ""
|
||||
scores: dict[str, int] = dataclasses.field(default_factory=dict)
|
||||
moves: Moves = ()
|
||||
blocked_by: tuple[int, ...] = ()
|
||||
|
||||
|
||||
def item_fields(named: dict[str, str], label: str, shape: Shape = SHAPE, id_: int | None = None) -> ItemFields | Failure:
|
||||
"""Each of the Release, Exempt, score, goals and Blocked-by cells that named holds by column name, held to shape's format; the one check every plan backend makes of an item's cells. label opens each message, such as "item 12" or "the item to file". id_ is the item's own ID, which its Blocked by may not name."""
|
||||
release = named.get("Release")
|
||||
if release is not None and parsed(release) is None:
|
||||
return Failure(f"{label}'s Release {release!r} is not a semver version, such as 1.2.0")
|
||||
exempt = named.get("Exempt", "")
|
||||
if not is_exempt(exempt):
|
||||
return Failure(f"{label}'s Exempt {exempt!r} is not empty or one of {', '.join(EXEMPTIONS[1:])}")
|
||||
scores = parse_scores(label, named, shape.score_columns)
|
||||
if isinstance(scores, Failure):
|
||||
return scores
|
||||
blocked_by = parse_blockers(named["ID"], named.get(BLOCKED_BY, ""))
|
||||
if isinstance(blocked_by, Failure):
|
||||
return blocked_by
|
||||
moves = shape.read_goals(named["ID"], named[shape.goals_column])
|
||||
moves = shape.read_goals(label, named.get(shape.goals_column, ""))
|
||||
if isinstance(moves, Failure):
|
||||
return moves
|
||||
return Item(int(named["ID"]), release_of(named["Release"]), exempt, named["Item"], scores, moves, blocked_by)
|
||||
blocked_by = parse_ids(named.get(BLOCKED_BY, ""))
|
||||
if blocked_by is None:
|
||||
return Failure(f"{label}'s {BLOCKED_BY} {named[BLOCKED_BY]!r} is not empty or IDs separated by \", \"")
|
||||
if id_ in blocked_by:
|
||||
return Failure(f"{label} is blocked by itself; drop {id_} from its {BLOCKED_BY}")
|
||||
return ItemFields(None if release is None else release_of(release), exempt, scores, moves, blocked_by)
|
||||
|
||||
|
||||
def is_exempt(cell: str) -> typing.TypeGuard[Exempt]:
|
||||
return cell in EXEMPTIONS
|
||||
|
||||
|
||||
def check_cells(row: str, named: dict[str, str]) -> Exempt | Failure:
|
||||
"""Holds the row's ID, Release, Exempt and Item cells to the format: the row's Exempt cell, or why a cell breaks it."""
|
||||
id_, release, exempt, tagline = named["ID"], named["Release"], named["Exempt"], named["Item"]
|
||||
if not re.fullmatch(r"[0-9]+", id_) or int(id_) < 1:
|
||||
return Failure(f"the ID {id_!r} is not a positive whole number: {row}")
|
||||
if parsed(release) is None:
|
||||
return Failure(f"item {id_}'s release {release!r} is not a semver version")
|
||||
if not is_exempt(exempt):
|
||||
return Failure(f"item {id_}'s Exempt {exempt!r} is not empty or one of {', '.join(EXEMPTIONS[1:])}")
|
||||
if not re.fullmatch(r"\*\*[^*].*[^*]\*\*", tagline):
|
||||
return Failure(f"item {id_}'s Item cell is not one bold tagline: {tagline}")
|
||||
return exempt
|
||||
|
||||
|
||||
def parse_scores(id_: str, named: dict[str, str], names: tuple[str, ...]) -> dict[str, int] | Failure:
|
||||
"""Each score in names that the row holds; only an optional one may be missing, since the table holds every needed column."""
|
||||
def parse_scores(label: str, named: dict[str, str], names: tuple[str, ...]) -> dict[str, int] | Failure:
|
||||
"""Each score in names that named holds; only an optional one may be missing, since the table holds every needed column."""
|
||||
scores: dict[str, int] = {}
|
||||
for name in names:
|
||||
if name not in named:
|
||||
continue
|
||||
top = LEVELS.get(name, TOP_SCORE)
|
||||
if not re.fullmatch(r"[0-9]+", named[name]) or not 1 <= int(named[name]) <= top:
|
||||
return Failure(f"item {id_}'s {name} {named[name]!r} is not a whole number from 1 to {top}")
|
||||
return Failure(f"{label}'s {name} {named[name]!r} is not a whole number from 1 to {top}")
|
||||
scores[name] = int(named[name])
|
||||
return scores
|
||||
|
||||
@@ -322,10 +337,21 @@ def parse_ids(cell: str) -> tuple[int, ...] | None:
|
||||
return tuple(int(id_) for id_ in cell.split(", ") if id_)
|
||||
|
||||
|
||||
def parse_blockers(id_: str, cell: str) -> tuple[int, ...] | Failure:
|
||||
blocked_by = parse_ids(cell)
|
||||
if blocked_by is None:
|
||||
return Failure(f"item {id_}'s {BLOCKED_BY} {cell!r} is not empty or IDs separated by \", \"")
|
||||
if int(id_) in blocked_by:
|
||||
return Failure(f"item {id_} is blocked by itself; drop {id_} from its {BLOCKED_BY}")
|
||||
return blocked_by
|
||||
def row_cells(item: Item, shape: Shape) -> dict[str, str]:
|
||||
"""item's cells by column name, as a row of a table in shape holds them; the Score, which only ranking works out, aside."""
|
||||
return {"ID": str(item.id), "Release": version(item.release), BLOCKED_BY: ", ".join(map(str, item.blocked_by)), "Exempt": item.exempt, "Item": item.tagline, **{name: str(score) for name, score in item.scores.items()}, shape.goals_column: shape.write_goals(item.moves)}
|
||||
|
||||
|
||||
def tagline_text(cell: str) -> str:
|
||||
"""The tagline an Item cell holds, as plain text: without the bold, each | unescaped."""
|
||||
return cell.strip().removeprefix("**").removesuffix("**").replace("\\|", "|")
|
||||
|
||||
|
||||
def detail_heading(id_: int, tagline: str) -> str:
|
||||
"""The heading under ## Details that opens item id_'s detail; tagline is plain text."""
|
||||
return f"### {id_}. {tagline}"
|
||||
|
||||
|
||||
def items_shape(found: list[Item]) -> Shape:
|
||||
"""The shape a table of found needs: OLD_SHAPE where an item holds a score only that shape has, as a plan not yet reshaped does."""
|
||||
return OLD_SHAPE if any(set(item.scores) - set(SHAPE.score_columns) for item in found) else SHAPE
|
||||
@@ -1,10 +1,10 @@
|
||||
"""What every plan backend must hold, as tests. A backend's test case inherits PlanStoreContract and unittest.TestCase, and builds its store in new_store. record_store.contract is its twin for records."""
|
||||
import typing
|
||||
|
||||
from release_plan.todo_table import BLOCKED_BY, Item, MOVES
|
||||
from plan.todo_table import BLOCKED_BY, Item, MOVES
|
||||
from failure import Failure
|
||||
from plan_store.stores import Plan, PlanStore, TAGLINE, Written
|
||||
from release_plan.release import release_of
|
||||
from plan_store.plans import Plan, PlanStore, TAGLINE, Written
|
||||
from plan.release import release_of
|
||||
|
||||
FIRST = {"Release": "0.1.0", TAGLINE: "Count the runs.", "L": "1", "E": "2", "I": "3", "S": "1", MOVES: "1 by 9"}
|
||||
SECOND = {"Release": "0.2.0", TAGLINE: "Ship the later thing.", "L": "2", "E": "1", "I": "1", "S": "2", MOVES: "1 by 8", "Exempt": "owner"}
|
||||
@@ -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.")
|
||||
|
||||
+11
-6
@@ -2,9 +2,9 @@
|
||||
import dataclasses
|
||||
|
||||
from plan_store.markdown_edits import bold_cell, plain
|
||||
from plan_store.stores import cells, Plan, Written
|
||||
from plan_store.plans import cells, no_item, Plan, Written
|
||||
from failure import Failure
|
||||
from release_plan.todo_table import Item, parse_row, SHAPE, Table
|
||||
from plan.todo_table import Item, parse_row, SHAPE, Table
|
||||
|
||||
|
||||
@dataclasses.dataclass
|
||||
@@ -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,14 +28,17 @@ 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)
|
||||
return Failure(no_item(self.label, id_))
|
||||
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:
|
||||
return Failure(self.fails or f"{self.label} holds no item {id_}")
|
||||
return Failure(self.fails or no_item(self.label, id_))
|
||||
del self.rows[id_]
|
||||
self.details.pop(id_, None)
|
||||
return Written(id_)
|
||||
|
||||
+221
-102
@@ -1,36 +1,30 @@
|
||||
"""A plan kept as the child issues of one Jira Cloud epic, read, filed into and finished 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, and `finish` moves an item's issue to a done status. edit is a Failure until todo.md's item 382."""
|
||||
import base64
|
||||
`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 dataclasses
|
||||
import pathlib
|
||||
import re
|
||||
import typing
|
||||
|
||||
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 atlassian.client import basic_auth, Http, jira_json, ToAdf, ToMarkdown
|
||||
from plan.todo_table import BLOCKED_BY, Item, item_fields, ItemFields, MOVES, SHAPE
|
||||
from plan_store.markdown_edits import bold_cell, plain, unfit_text
|
||||
from plan_store.stores import cells, Plan, Written
|
||||
from plan_store.plans import cells, no_item, Plan, Written
|
||||
from project_config.settings import Epic, Finish, JIRA_FINISH_STATUS, JIRA_FINISH_TRANSITION
|
||||
from failure import Failure
|
||||
from rest_client import json_request
|
||||
from release_plan.release import parsed, Release, tagged
|
||||
from rest_client.env_file import read_env
|
||||
from plan.release import parsed, Release, tagged
|
||||
from plan import ranking
|
||||
|
||||
# One pair of keys for Jira and Confluence: one Atlassian account's API token opens both.
|
||||
KEYS = ("ATLASSIAN_EMAIL", "ATLASSIAN_API_TOKEN")
|
||||
# The issue property that holds an item's scores, as a JSON object such as {"L": 2, "E": 2, "I": 3, "S": 3, "Moves": "1.6 by 4", "Exempt": ""}.
|
||||
PROPERTY = "plan-item"
|
||||
ISSUE_KEY = re.compile(r"([A-Z][A-Z0-9_]*)-([0-9]+)")
|
||||
# Seconds each connect and each read may wait.
|
||||
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 = "the loop doesn't edit an issue of a plan in Jira yet: edit it in Jira"
|
||||
# The key in PROPERTY's value that marks an issue the loop filed, and its value. The loop never edits the summary or description of an issue without it, which a person filed.
|
||||
# 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"
|
||||
@@ -43,24 +37,17 @@ DONE = "done"
|
||||
PERHAPS_FILED = "unless Jira refused the request, the issue may exist: look under {epic} before filing the item again"
|
||||
# What a failed move ends with, for the same reason.
|
||||
PERHAPS_MOVED = "unless Jira refused the request, the issue may have moved: look at {key} before finishing the item again"
|
||||
|
||||
# Sends a request with the Authorization header given, the body as JSON where there is one, and returns the JSON answer, None where the answer has no body, or a Failure saying why there is none.
|
||||
Http = typing.Callable[[str, str, str, object], object]
|
||||
ToMarkdown = typing.Callable[[list[dict[str, typing.Any]]], list[str] | Refused | Failure]
|
||||
ToAdf = typing.Callable[[str], dict[str, typing.Any] | Failure]
|
||||
# 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")
|
||||
|
||||
|
||||
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:
|
||||
"""Jira's messages in the JSON of an error answer; empty where it holds none."""
|
||||
if not isinstance(answer, dict):
|
||||
return ""
|
||||
messages, errors = answer.get("errorMessages"), answer.get("errors")
|
||||
found = [*(messages if isinstance(messages, list) else []), *(errors.values() if isinstance(errors, dict) else [])]
|
||||
return "; ".join(text for text in found if isinstance(text, str))
|
||||
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."""
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
@@ -73,7 +60,7 @@ class Issue:
|
||||
# The key of each issue this one "is blocked by".
|
||||
blockers: tuple[str, ...]
|
||||
# PROPERTY's value; an empty object where the issue holds none.
|
||||
scores: object
|
||||
scores: dict[str, typing.Any]
|
||||
|
||||
@property
|
||||
def number(self) -> int:
|
||||
@@ -85,11 +72,13 @@ class JiraPlan:
|
||||
"""The plan under epic, read and written with the credentials env_file holds."""
|
||||
epic: Epic
|
||||
env_file: pathlib.Path
|
||||
http: Http = http_json
|
||||
http: Http = jira_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:
|
||||
@@ -110,39 +99,66 @@ 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
|
||||
issue_fields = filing.fields
|
||||
if detail.strip():
|
||||
description = self.to_adf(detail)
|
||||
if isinstance(description, Failure):
|
||||
return Failure(f"cannot convert the item's detail to a Jira description: {description.reason}")
|
||||
issue_fields = issue_fields | {"description": description}
|
||||
description = self.description_of(detail)
|
||||
if isinstance(description, Failure):
|
||||
return description
|
||||
issue_fields = filing.fields | ({"description": description} if description else {})
|
||||
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."""
|
||||
@@ -151,18 +167,63 @@ 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 child(self, id_: int, authorization: str) -> dict[str, typing.Any] | Failure:
|
||||
"""Item id_'s issue, as the epic's open children answer it; a Failure where none of them is item id_."""
|
||||
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)
|
||||
key = f"{project_of(self.epic.key)}-{id_}"
|
||||
found = next((raw for raw in answered if isinstance(raw, dict) and raw.get("key") == key), None)
|
||||
return Failure(no_item(self.label, id_)) if found is None else found
|
||||
|
||||
def edit(self, id_: int, fields: dict[str, str], detail: str | None) -> Written | Failure:
|
||||
return Failure(READ_ONLY)
|
||||
def description_of(self, detail: str) -> dict[str, typing.Any] | None | Failure:
|
||||
"""The Jira description that holds detail, as ADF; None for a blank detail, which leaves an issue without one."""
|
||||
if not detail.strip():
|
||||
return None
|
||||
description = self.to_adf(detail)
|
||||
return Failure(f"cannot convert the item's detail to a Jira description: {description.reason}") if isinstance(description, Failure) else description
|
||||
|
||||
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
|
||||
raw = self.child(id_, authorization)
|
||||
if isinstance(raw, Failure):
|
||||
return raw
|
||||
issue = issue_of(raw)
|
||||
if isinstance(issue, Failure):
|
||||
return issue
|
||||
key = issue.key
|
||||
revision = revision_of(issue, cells(fields), detail, comment)
|
||||
if isinstance(revision, Failure):
|
||||
return revision
|
||||
body = revision.body
|
||||
if detail is not None:
|
||||
description = self.description_of(detail)
|
||||
if isinstance(description, Failure):
|
||||
return description
|
||||
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:
|
||||
"""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."""
|
||||
@@ -171,12 +232,10 @@ class JiraPlan:
|
||||
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
|
||||
raw = self.child(id_, authorization)
|
||||
if isinstance(raw, Failure):
|
||||
return raw
|
||||
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):
|
||||
@@ -198,6 +257,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:
|
||||
@@ -209,26 +270,97 @@ 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:
|
||||
return Failure(f"the item's Release {release!r} is not a version such as 1.2.0")
|
||||
# Named so the shared messages read "item to file's L": they open with "item" and an ID, which this item has none of yet.
|
||||
levels = parse_scores("to file", named, SHAPE.score_columns)
|
||||
if isinstance(levels, Failure):
|
||||
return levels
|
||||
moves, exempt = named.get(MOVES, ""), named.get("Exempt", "")
|
||||
if isinstance(unfit_moves := parse_moves("to file", moves), Failure):
|
||||
return unfit_moves
|
||||
if not is_exempt(exempt):
|
||||
return Failure(f"the item's Exempt {exempt!r} is not empty or one of {', '.join(EXEMPTIONS[1:])}")
|
||||
blockers = parse_ids(named.get(BLOCKED_BY, ""))
|
||||
if blockers is None:
|
||||
return Failure(f"the item's {BLOCKED_BY} {named[BLOCKED_BY]!r} is not empty or IDs separated by \", \"")
|
||||
checked = item_fields(named | {"Release": release}, "the item to file")
|
||||
if isinstance(checked, Failure):
|
||||
return checked
|
||||
assert checked.release is not None, "item_fields refuses an empty Release"
|
||||
project = project_of(epic.key)
|
||||
issue_fields: dict[str, typing.Any] = {"project": {"key": project}, "parent": {"key": epic.key}, "issuetype": {"name": ISSUE_TYPE}, "summary": summary}
|
||||
if exempt == SECURITY:
|
||||
if checked.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))
|
||||
value = checked.scores | {MOVES: named.get(MOVES, ""), "Exempt": checked.exempt, FILED_BY[0]: FILED_BY[1]}
|
||||
return Filing(issue_fields, release, value, tuple(f"{project}-{blocker}" for blocker in checked.blocked_by), Item(0, checked.release, checked.exempt, summary, checked.scores, checked.moves, checked.blocked_by))
|
||||
|
||||
|
||||
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 issue.scores.get(FILED_BY[0]) != FILED_BY[1]:
|
||||
continue
|
||||
scored = scores(issue.key, issue.scores)
|
||||
if isinstance(scored, Failure):
|
||||
return scored
|
||||
if missing := next((name for name in SET_SCORES if name not in scored.scores), 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=scored.scores, moves=scored.moves), scoring, issue.key)
|
||||
if isinstance(other, Failure):
|
||||
return other
|
||||
if (ranking.FIRST.get(scored.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 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 isinstance(checked := item_fields({name: named[name] for name in ("Release", "Exempt") if name in named}, f"item {issue.key}"), Failure):
|
||||
return checked
|
||||
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.scores and any(name not in scored.scores 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.scores | {MOVES: texts.get(MOVES, ""), "Exempt": scored.exempt}
|
||||
body["properties"] = [{"key": PROPERTY, "value": value}]
|
||||
if own and (scored.exempt == SECURITY) != (held.get("Exempt") == SECURITY):
|
||||
body["update"] = {"labels": [{"add" if scored.exempt == SECURITY else "remove": SECURITY}]}
|
||||
return Revision(body, release)
|
||||
|
||||
|
||||
def offer_of(raw: object) -> tuple[str, str, str, str] | None:
|
||||
@@ -265,16 +397,8 @@ def project_of(key: str) -> str:
|
||||
return key.rpartition("-")[0]
|
||||
|
||||
|
||||
def basic_auth(env_file: pathlib.Path) -> str | Failure:
|
||||
"""The Authorization header for the email and API token that env_file holds."""
|
||||
values = read_env(env_file, KEYS, "an API token")
|
||||
if isinstance(values, Failure):
|
||||
return values
|
||||
return "Basic " + base64.b64encode(":".join(values[key] for key in KEYS).encode()).decode()
|
||||
|
||||
|
||||
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):
|
||||
@@ -302,14 +426,19 @@ def children(epic: Epic, authorization: str, http: Http) -> list[object] | Failu
|
||||
def issue_of(raw: object) -> Issue | Failure:
|
||||
"""The issue in one entry of the search's answer, or which issue is not in the shape Jira documents, and how."""
|
||||
key = raw.get("key") if isinstance(raw, dict) else None
|
||||
if not isinstance(key, str) or not ISSUE_KEY.fullmatch(key):
|
||||
if not isinstance(raw, dict) or not isinstance(key, str) or not ISSUE_KEY.fullmatch(key):
|
||||
return Failure("the search answered an issue without an issue key")
|
||||
# The answer's nested fields are read as Jira documents them; one missing or of another type ends the read here, as a Failure, so no later step meets it.
|
||||
try:
|
||||
fields = typing.cast(dict[str, typing.Any], raw)["fields"]
|
||||
fields = raw["fields"]
|
||||
blockers = tuple(link["inwardIssue"]["key"] for link in fields["issuelinks"] if "inwardIssue" in link and link["type"]["inward"] == "is blocked by")
|
||||
issue = Issue(key, fields["summary"].strip(), fields["description"], tuple(version["name"] for version in fields["fixVersions"]), blockers, typing.cast(dict[str, typing.Any], raw).get("properties", {}).get(PROPERTY, {}))
|
||||
held = raw.get("properties", {}).get(PROPERTY, {})
|
||||
summary, description, versions = fields["summary"].strip(), fields["description"], tuple(version["name"] for version in fields["fixVersions"])
|
||||
except (AttributeError, KeyError, TypeError) as failure:
|
||||
return Failure(f"{key} is not in the shape Jira Cloud's REST API version 3 documents: {failure!r}")
|
||||
if not isinstance(held, dict):
|
||||
return Failure(f"{key}'s issue property {PROPERTY} is not a JSON object")
|
||||
issue = Issue(key, summary, description, versions, blockers, held)
|
||||
if not isinstance(issue.description, dict | None) or not all(isinstance(name, str) for name in issue.fix_versions + issue.blockers) or not all(ISSUE_KEY.fullmatch(blocker) for blocker in issue.blockers):
|
||||
return Failure(f"{key} is not in the shape Jira Cloud's REST API version 3 documents: its description, a Fix Version's name or a linked issue's key holds another kind of value")
|
||||
return issue
|
||||
@@ -350,13 +479,12 @@ 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):
|
||||
return scored
|
||||
blockers = {number(key) for key in issue.blockers if project_of(key) == project}
|
||||
return Item(issue.number, release, scored[2], bold_cell(issue.summary), scored[0], scored[1], tuple(sorted(blockers & ids)), "")
|
||||
return Item(issue.number, release, scored.exempt, bold_cell(issue.summary), scored.scores, scored.moves, tuple(sorted(blockers & ids)), "")
|
||||
|
||||
|
||||
def earliest_release(names: tuple[str, ...]) -> Release | None:
|
||||
@@ -365,18 +493,9 @@ def earliest_release(names: tuple[str, ...]) -> Release | None:
|
||||
return min(releases, default=None)
|
||||
|
||||
|
||||
def scores(key: str, held: object) -> tuple[dict[str, int], typing.Any, typing.Any] | Failure:
|
||||
def scores(key: str, held: dict[str, typing.Any]) -> ItemFields | Failure:
|
||||
"""The scores, Moves and Exempt that an issue's PROPERTY value holds, each in the format the items table of a todo.md takes."""
|
||||
if not isinstance(held, dict):
|
||||
return Failure(f"{key}'s issue property {PROPERTY} is not a JSON object")
|
||||
named = {name: str(value) for name, value in held.items()}
|
||||
levels = parse_scores(key, named, SHAPE.score_columns)
|
||||
if isinstance(levels, Failure):
|
||||
return levels
|
||||
moves = parse_moves(key, named.get(MOVES, ""))
|
||||
if isinstance(moves, Failure):
|
||||
return moves
|
||||
exempt = named.get("Exempt", "")
|
||||
if not is_exempt(exempt):
|
||||
return Failure(f"{key}'s issue property {PROPERTY} holds the Exempt {exempt!r}, which is not empty or one of {', '.join(EXEMPTIONS[1:])}")
|
||||
return levels, moves, exempt
|
||||
named = {name: str(value) for name, value in held.items() if name in (*SHAPE.score_columns, MOVES, "Exempt")}
|
||||
checked = item_fields(named, f"item {key}")
|
||||
# Jira's screens don't show PROPERTY, so the message says where the value is.
|
||||
return Failure(f"{checked.reason}; {key} holds it in its issue property {PROPERTY}") if isinstance(checked, Failure) else checked
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
"""The text edits behind the markdown plan: filing an item in todo.md, changing one and removing one. Each returns new text; ranking.rank then orders the table and details and writes the derived cells."""
|
||||
import re
|
||||
|
||||
from release_plan.todo_table import cells, DETAILS, item_details, items_table, Table
|
||||
from plan.todo_table import cells, detail_heading, DETAILS, item_details, items_table, Table, tagline_text
|
||||
from failure import Failure
|
||||
from release_plan.ranking import stated
|
||||
from plan_store.plans import no_item
|
||||
from plan.ranking import stated
|
||||
|
||||
# A line that would end ## Details (##) or could open another item's detail (###).
|
||||
HEADING = re.compile(r"^#{2,3} ", re.M)
|
||||
@@ -47,7 +48,7 @@ def edited(todo: str, id_: int, named: dict[str, str], detail: str | None, label
|
||||
if isinstance(details, Failure):
|
||||
return details
|
||||
row = dict(zip(table.columns, held))
|
||||
tagline = plain(named["Item"]) if "Item" in named else plain(row["Item"]).replace("\\|", "|")
|
||||
tagline = plain(named["Item"]) if "Item" in named else tagline_text(row["Item"])
|
||||
kept = details.get(id_, "") if detail is None else detail
|
||||
if unfit := unfit_text(tagline, "" if detail is None else detail):
|
||||
return unfit
|
||||
@@ -90,7 +91,7 @@ def with_detail(text: str, id_: int, tagline: str, detail: str) -> str:
|
||||
"""text with detail first under ## Details, headed by id_ and tagline; text itself where detail is blank."""
|
||||
if not detail.strip():
|
||||
return text
|
||||
entry = f"### {id_}. {tagline}\n\n{detail.strip()}\n"
|
||||
entry = f"{detail_heading(id_, tagline)}\n\n{detail.strip()}\n"
|
||||
section = DETAILS.search(text)
|
||||
if section is None:
|
||||
return text.rstrip("\n") + f"\n\n## Details\n\n{entry}"
|
||||
@@ -113,7 +114,7 @@ def row_index(table: Table, id_: int, label: str) -> int | Failure:
|
||||
return found
|
||||
if found[0] == str(id_):
|
||||
return at
|
||||
return Failure(f"{label} holds no item {id_}")
|
||||
return Failure(no_item(label, id_))
|
||||
|
||||
|
||||
def held_table(lines: list[str], label: str) -> Table | Failure:
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
"""What every plan backend reads and writes: a Plan, a Written, the PlanStore protocol they all meet, and the fields a caller may set on an item."""
|
||||
import dataclasses
|
||||
import typing
|
||||
|
||||
from plan.todo_table import BLOCKED_BY, Item, MOVES
|
||||
from failure import Failure
|
||||
from plan.release import Release
|
||||
|
||||
TAGLINE = "Tagline"
|
||||
# What a caller may set on an item, each as text in the format `rank_todo.py --help` states for the cell of that name. TAGLINE is the Item cell, bold or not.
|
||||
FIELDS = ("Release", BLOCKED_BY, "Exempt", TAGLINE, "L", "E", "I", "S", MOVES)
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Plan:
|
||||
"""A plan as one read found it."""
|
||||
# Each item with its detail, in the order the backend supplies: by release and then by rank for a markdown file, by backlog rank for a tracker.
|
||||
items: list[Item]
|
||||
# The releases the plan marks renamed. Such a release holds no item because its items moved, not because it is finished.
|
||||
renamed: frozenset[Release] = frozenset()
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Written:
|
||||
"""A write that landed."""
|
||||
id: int
|
||||
# What the backend says of the plan after the write, for stderr, such as an item now under the bar.
|
||||
notes: tuple[str, ...] = ()
|
||||
|
||||
|
||||
class PlanStore(typing.Protocol):
|
||||
"""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:
|
||||
"""What a message calls the plan, such as its path."""
|
||||
|
||||
@property
|
||||
def tracked(self) -> str | None:
|
||||
"""The plan's path from the checkout's top, as git names a file in a commit; None where no commit holds a version of it, as for a file outside the checkout or a tracker."""
|
||||
|
||||
def read(self) -> Plan | Failure:
|
||||
"""The plan as it stands. A NoItemsTable where the project has not set one up."""
|
||||
|
||||
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, 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."""
|
||||
|
||||
|
||||
def no_item(label: str, id_: int | str) -> str:
|
||||
"""What every store says of an item id_ that the plan label names doesn't hold. `chunk-pr merge` reads `todo-item show`'s answer by it, through says_no_item."""
|
||||
return f"{label} holds no item {id_}"
|
||||
|
||||
|
||||
def says_no_item(reason: str, id_: int | str) -> bool:
|
||||
"""Whether a failure's reason, such as `todo-item show`'s, says the plan doesn't hold item id_, as no_item words it."""
|
||||
return no_item("", id_) in reason
|
||||
|
||||
|
||||
def cells(fields: dict[str, str]) -> dict[str, str]:
|
||||
"""fields by the items table's column names."""
|
||||
unknown = set(fields) - set(FIELDS)
|
||||
if unknown:
|
||||
# A programming error, so nothing catches it: a caller takes its fields from FIELDS.
|
||||
raise ValueError(f"{', '.join(sorted(unknown))}: not a field; the fields are {', '.join(FIELDS)}")
|
||||
return {"Item" if name == TAGLINE else name: value for name, value in fields.items()}
|
||||
@@ -0,0 +1,39 @@
|
||||
"""The goal weights a plan is ranked by, read from the goals file, the decision log and the comprehension history, for the markdown plan and for the scoring of a plan in Jira."""
|
||||
import dataclasses
|
||||
import decimal
|
||||
|
||||
from failure import Failure
|
||||
from project_config.settings import JiraScoring
|
||||
from plan import ranking
|
||||
from record_store.stores import RecordStore
|
||||
|
||||
# What the reader of a missing or empty goals file is told.
|
||||
GOALS_HINT = "rank_todo.py weighs goals from the goals file the project's config names as goals-and-audience"
|
||||
|
||||
|
||||
@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)
|
||||
+11
-179
@@ -1,163 +1,30 @@
|
||||
"""The one way a tool reads or writes a project's plan: through the store its config names.
|
||||
|
||||
The config's `plan` setting names the backend. A path names a markdown file, todo.md. `jira:` and an epic's address name a Jira epic, whose open child issues are the plan: `jira_epic` reads them, and files an item as a new child issue. An agent reads and changes the plan with `todo-item`, which works through the same store.
|
||||
The config's `plan` setting names the backend. A path names a markdown file, todo.md, which `todo_md` keeps. `jira:` and an epic's address name a Jira epic, whose open child issues are the plan: `jira_epic` reads them, and files an item as a new child issue. An agent reads and changes the plan with `todo-item`, which works through the same store.
|
||||
|
||||
A tool that reads what a past commit held, such as `score-outcomes`, still parses that commit's todo.md itself, with `release_plan.todo_table`: only the markdown backend has commits, and todo.md's items 365, 366 and 368 port those tools to the other backends."""
|
||||
import dataclasses
|
||||
import decimal
|
||||
A tool that reads what a past commit held, such as `score-outcomes`, still parses that commit's todo.md itself, with `plan.todo_table`: only the markdown backend has commits, and todo.md's items 365, 366 and 368 port those tools to the other backends."""
|
||||
import pathlib
|
||||
import typing
|
||||
|
||||
from release_plan.todo_table import BLOCKED_BY, Item, item_details, items, MOVES, NoItemsTable, renames
|
||||
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 plan_store import markdown_edits
|
||||
from plan_store.todo_md import FilePlan, plan_of
|
||||
from record_store.stores import goals_store, store as record_store
|
||||
from plan_store.jira_epic import JiraPlan
|
||||
from plan_store.plans import Plan, PlanStore
|
||||
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
|
||||
|
||||
TAGLINE = "Tagline"
|
||||
# What a caller may set on an item, each as text in the format `rank_todo.py --help` states for the cell of that name. TAGLINE is the Item cell, bold or not.
|
||||
FIELDS = ("Release", BLOCKED_BY, "Exempt", TAGLINE, "L", "E", "I", "S", MOVES)
|
||||
|
||||
|
||||
# What the reader of a missing todo.md is told.
|
||||
MISSING = "every project keeps a todo.md, and rank_todo.py --help shows one"
|
||||
# What the reader of a missing or empty goals file is told.
|
||||
GOALS_HINT = "rank_todo.py weighs goals from the goals file the project's config names as goals-and-audience"
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Plan:
|
||||
"""A plan as one read found it."""
|
||||
# Each item with its detail, in the order the backend supplies: by release and then by rank for a markdown file, by backlog rank for a tracker.
|
||||
items: list[Item]
|
||||
# The releases the plan marks renamed. Such a release holds no item because its items moved, not because it is finished.
|
||||
renamed: frozenset[Release] = frozenset()
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Written:
|
||||
"""A write that landed."""
|
||||
id: int
|
||||
# What the backend says of the plan after the write, for stderr, such as an item now under the bar.
|
||||
notes: tuple[str, ...] = ()
|
||||
|
||||
|
||||
class PlanStore(typing.Protocol):
|
||||
"""A project's plan. plan_store.contract holds every backend that writes to the same behaviour; `jira_epic` reads, files and finishes, and fails an edit until todo.md's item 382. A write that fails leaves the plan as it was, except where its Failure says the tracker may have taken the write all the same, as when Jira's answer to a new issue or to a move is lost."""
|
||||
|
||||
@property
|
||||
def label(self) -> str:
|
||||
"""What a message calls the plan, such as its path."""
|
||||
|
||||
@property
|
||||
def tracked(self) -> str | None:
|
||||
"""The plan's path from the checkout's top, as git names a file in a commit; None where no commit holds a version of it, as for a file outside the checkout or a tracker."""
|
||||
|
||||
def read(self) -> Plan | Failure:
|
||||
"""The plan as it stands. A NoItemsTable where the project has not set one up."""
|
||||
|
||||
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 finish(self, id_: int) -> Written | Failure:
|
||||
"""Removes item id_ with its detail."""
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class FilePlan:
|
||||
"""A plan kept as a markdown file at path, in the shape `rank_todo.py --help` shows. Every write ranks the file, reading the goals file from goals, the decision log and the comprehension history."""
|
||||
path: pathlib.Path
|
||||
tracked: str | None
|
||||
goals: RecordStore
|
||||
decisions: RecordStore
|
||||
history: RecordStore
|
||||
# The project's readability floor: while the comprehension overall is under it, ranking weighs code health 4 times as much.
|
||||
floor: decimal.Decimal
|
||||
|
||||
@property
|
||||
def label(self) -> str:
|
||||
return str(self.path)
|
||||
|
||||
def read(self) -> Plan | Failure:
|
||||
if not self.path.exists():
|
||||
return NoItemsTable(f"{self.path}: not found; {MISSING}")
|
||||
text = read_text(self.path, MISSING)
|
||||
return text if isinstance(text, Failure) else plan_of(text)
|
||||
|
||||
def add(self, fields: dict[str, str], detail: str) -> Written | Failure:
|
||||
texts = self.texts()
|
||||
if isinstance(texts, Failure):
|
||||
return texts
|
||||
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:
|
||||
texts = self.texts()
|
||||
if isinstance(texts, Failure):
|
||||
return texts
|
||||
text = markdown_edits.edited(texts[0], id_, cells(fields), detail, self.label)
|
||||
return text if isinstance(text, Failure) else self.kept(id_, text, texts)
|
||||
|
||||
def kept(self, id_: int, text: str, texts: tuple[str, str, str, str]) -> Written | Failure:
|
||||
"""Ranks text, the file with item id_ filed or edited, and writes it where the item scores at the bar or above."""
|
||||
ranked = ranking.rank(text, *texts[1:], self.floor)
|
||||
if isinstance(ranked, Failure):
|
||||
return ranked
|
||||
# The write may lower another item under the bar, which the notes then say; the write is refused only where the written item itself scores under the bar.
|
||||
if under := [line for line in ranked.under_bar if line.startswith(f"item {id_} ")]:
|
||||
return Failure(under[0])
|
||||
return self.written(id_, ranked)
|
||||
|
||||
def finish(self, id_: int) -> Written | Failure:
|
||||
texts = self.texts()
|
||||
if isinstance(texts, Failure):
|
||||
return texts
|
||||
text = markdown_edits.finished(texts[0], id_, self.label)
|
||||
if isinstance(text, Failure):
|
||||
return text
|
||||
ranked = ranking.rank(text, *texts[1:], self.floor)
|
||||
return ranked if isinstance(ranked, Failure) else self.written(id_, ranked)
|
||||
|
||||
def written(self, id_: int, ranked: ranking.Ranked) -> Written | Failure:
|
||||
"""Writes ranked's text to the file."""
|
||||
unwritten = replace_file(self.path.resolve(), ranked.text.encode("utf-8"))
|
||||
if unwritten:
|
||||
return Failure(f"{self.path}: {unwritten.reason}")
|
||||
return Written(id_, tuple(f"{self.path}: {line}" for line in ranked.notes + ranked.under_bar))
|
||||
|
||||
def texts(self) -> tuple[str, str, str, str] | Failure:
|
||||
"""What ranking reads: the file, the goals file, the decision log and the comprehension history. The last two are empty when missing; a missing plan, or a goals file that is missing or empty, is a Failure."""
|
||||
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)
|
||||
from plan_store.scoring import StatedScoring
|
||||
|
||||
|
||||
def store(config: ProjectConfig) -> PlanStore:
|
||||
"""The store config names for the plan."""
|
||||
if config.epic is None:
|
||||
return file_plan(config)
|
||||
# Imported here, since jira_epic builds on this module's Plan and Written.
|
||||
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, finish_by=config.jira_finish)
|
||||
# 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:
|
||||
@@ -171,38 +38,3 @@ def held_at(revision: str, plan: PlanStore, cwd: str, run: Git = git) -> Plan |
|
||||
return plan.read()
|
||||
text = file_at(revision, plan.tracked, cwd, run)
|
||||
return text if isinstance(text, Failure) else plan_of(text)
|
||||
|
||||
|
||||
def plan_of(todo: str) -> Plan | Failure:
|
||||
"""The plan a todo.md's text holds."""
|
||||
found = items(todo)
|
||||
if isinstance(found, Failure):
|
||||
return found
|
||||
details = item_details(todo)
|
||||
if isinstance(details, Failure):
|
||||
return details
|
||||
marked = renames(todo)
|
||||
if isinstance(marked, Failure):
|
||||
return marked
|
||||
return Plan([dataclasses.replace(item, detail=details.get(item.id, "")) for item in found], frozenset(marked))
|
||||
|
||||
|
||||
def cells(fields: dict[str, str]) -> dict[str, str]:
|
||||
"""fields by the items table's column names."""
|
||||
unknown = set(fields) - set(FIELDS)
|
||||
if unknown:
|
||||
# A programming error, so nothing catches it: a caller takes its fields from FIELDS.
|
||||
raise ValueError(f"{', '.join(sorted(unknown))}: not a field; the fields are {', '.join(FIELDS)}")
|
||||
return {"Item" if name == TAGLINE else name: value for name, value in fields.items()}
|
||||
|
||||
|
||||
def read_text(path: pathlib.Path, missing: str) -> str | Failure:
|
||||
"""path's text; where it is missing, a Failure saying missing."""
|
||||
try:
|
||||
return path.read_text(encoding="utf-8")
|
||||
except FileNotFoundError:
|
||||
return Failure(f"{path}: not found; {missing}")
|
||||
except OSError as failure:
|
||||
return Failure(f"{path}: {failure.strerror}")
|
||||
except UnicodeDecodeError:
|
||||
return Failure(f"{path}: not UTF-8")
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import base64
|
||||
import dataclasses
|
||||
import pathlib
|
||||
import sys
|
||||
import tempfile
|
||||
@@ -7,13 +8,14 @@ import unittest.mock
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from project_config.settings import Epic, Finish
|
||||
from release_plan.todo_table import EXEMPTIONS
|
||||
from project_config.settings import DEFAULT_FLOOR, Epic, Finish
|
||||
from plan.todo_table import EXEMPTIONS
|
||||
from failure import Failure
|
||||
from plan_store import jira_epic
|
||||
from plan_store.stores import Plan, Written
|
||||
from plan_store.plans import Plan, Written
|
||||
from plan import ranking
|
||||
from adf_codec.convert import Refused
|
||||
from release_plan.release import release_of
|
||||
from plan.release import release_of
|
||||
|
||||
EPIC = Epic("https://acme.atlassian.net", "ABC-12")
|
||||
SEARCH = "https://acme.atlassian.net/rest/api/3/search/jql"
|
||||
@@ -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)}], []
|
||||
@@ -142,7 +144,7 @@ class JiraPlan(unittest.TestCase):
|
||||
self.assertIn("ABC-34", failure.reason) # type: ignore[union-attr]
|
||||
|
||||
def test_an_exempt_out_of_format_fails_naming_the_reasons_it_may_hold(self):
|
||||
self.assertEqual(self.read(issue("ABC-34", scores={"Exempt": "because"})), Failure("ABC-34's issue property plan-item holds the Exempt 'because', which is not empty or one of decision, defect, owner, principle, question, security"))
|
||||
self.assertEqual(self.read(issue("ABC-34", scores={"Exempt": "because"})), Failure("item ABC-34's Exempt 'because' is not empty or one of decision, defect, owner, principle, question, security; ABC-34 holds it in its issue property plan-item"))
|
||||
|
||||
def test_reads_every_page(self):
|
||||
self.pages = [{"issues": [issue("ABC-1")], "nextPageToken": "t1"}, {"issues": [issue("ABC-2")]}]
|
||||
@@ -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,10 +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_fails_since_the_store_does_not_edit_yet(self):
|
||||
self.assertEqual(self.store().edit(34, {"L": "2"}, None), Failure("the loop doesn't edit an issue of a plan in Jira yet: edit it in Jira"))
|
||||
self.assertEqual(self.calls + self.epic_calls, [])
|
||||
|
||||
def test_names_itself_by_the_configs_spelling_and_no_commit_holds_it(self):
|
||||
self.assertEqual((self.store().label, self.store().tracked), ("jira:https://acme.atlassian.net/browse/ABC-12", None))
|
||||
|
||||
@@ -224,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):
|
||||
@@ -236,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}],
|
||||
})])
|
||||
@@ -297,9 +315,9 @@ class Filing(unittest.TestCase):
|
||||
def test_each_field_out_of_format_fails_saying_how(self):
|
||||
cases = (
|
||||
({"Tagline": "** **"}, "the item has no tagline"),
|
||||
({"L": "9"}, "item to file's L '9' is not a whole number from 1 to 4"),
|
||||
({"Exempt": "whim"}, f"the item's Exempt 'whim' is not empty or one of {', '.join(EXEMPTIONS[1:])}"),
|
||||
({"Blocked by": "ABC-34"}, "the item's Blocked by 'ABC-34' is not empty or IDs separated by \", \""),
|
||||
({"L": "9"}, "the item to file's L '9' is not a whole number from 1 to 4"),
|
||||
({"Exempt": "whim"}, f"the item to file's Exempt 'whim' is not empty or one of {', '.join(EXEMPTIONS[1:])}"),
|
||||
({"Blocked by": "ABC-34"}, "the item to file's Blocked by 'ABC-34' is not empty or IDs separated by \", \""),
|
||||
)
|
||||
for change, reason in cases:
|
||||
with self.subTest(change=change):
|
||||
@@ -307,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]
|
||||
|
||||
@@ -315,7 +334,7 @@ class Filing(unittest.TestCase):
|
||||
self.add(FIELDS | {"Colour": "red"})
|
||||
|
||||
def test_an_item_without_a_release_fails_naming_the_field(self):
|
||||
self.assertEqual(self.add({name: value for name, value in FIELDS.items() if name != "Release"}), Failure("the item's Release '' is not a version such as 1.2.0"))
|
||||
self.assertEqual(self.add({name: value for name, value in FIELDS.items() if name != "Release"}), Failure("the item to file's Release '' is not a semver version, such as 1.2.0"))
|
||||
|
||||
def test_a_detail_that_does_not_convert_fails_before_any_request(self):
|
||||
self.to_adf = lambda markdown: Failure("docker is not running") # type: ignore[method-assign]
|
||||
@@ -346,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):
|
||||
@@ -371,10 +390,258 @@ 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; ABC-34 holds it in its issue property plan-item"),
|
||||
):
|
||||
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"item ABC-34's Exempt 'tired' is not empty or one of {', '.join(EXEMPTIONS[1:])}"),
|
||||
({"Release": "soon"}, None, "item ABC-34's Release 'soon' is not a semver 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}}}
|
||||
|
||||
@@ -398,7 +665,7 @@ class Finishing(unittest.TestCase):
|
||||
return {SEARCH: {"issues": self.open}}.get(url, {"key": "ABC-12"})
|
||||
|
||||
def finish(self, id_: int = 34, by: Finish | None = Finish("Mark as done", "Done")):
|
||||
return jira_epic.JiraPlan(EPIC, self.env, self.http, text_of, finish_by=by).finish(id_)
|
||||
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]
|
||||
@@ -457,24 +724,6 @@ class Finishing(unittest.TestCase):
|
||||
self.assertEqual(self.calls, [])
|
||||
|
||||
|
||||
class Requests(unittest.TestCase):
|
||||
def test_sends_each_request_through_the_shared_client_with_jiras_error_messages(self):
|
||||
with unittest.mock.patch.object(jira_epic.json_request, "http_json", return_value={"issues": []}) as sent:
|
||||
self.assertEqual(jira_epic.http_json("POST", SEARCH, AUTHORIZATION, {"jql": "x"}), {"issues": []})
|
||||
sent.assert_called_once_with("POST", SEARCH, AUTHORIZATION, {"jql": "x"}, 30, jira_epic.error_message)
|
||||
|
||||
def test_reads_jiras_messages_from_an_error_answer(self):
|
||||
cases = (
|
||||
({"errorMessages": ["Issue does not exist or you do not have permission to see it."], "errors": {}}, "Issue does not exist or you do not have permission to see it."),
|
||||
({"errorMessages": ["One."], "errors": {"jql": "Two."}}, "One.; Two."),
|
||||
({"errorMessages": "One.", "errors": ["Two."]}, ""),
|
||||
({"errorMessages": [7, "One."]}, "One."),
|
||||
(["One."], ""),
|
||||
)
|
||||
for answer, message in cases:
|
||||
with self.subTest(answer=answer):
|
||||
self.assertEqual(jira_epic.error_message(answer), message)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@@ -8,23 +8,23 @@ import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from project_config.settings import DEFAULT_FLOOR, Epic, Finish, 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
|
||||
from record_store.fakes import MemoryStore
|
||||
from release_plan.todo_table import NoItemsTable
|
||||
from release_plan.test_ranking import README, SCORED, VOID
|
||||
from release_plan.release import release_of
|
||||
from plan_store import stores
|
||||
from plan.todo_table import NoItemsTable
|
||||
from plan_store import plans, scoring, stores, todo_md
|
||||
from plan.test_ranking import README, SCORED, VOID
|
||||
from plan.release import release_of
|
||||
|
||||
EMPTY = "# todo\n\n## Scoring\n\n`Score = 100 * V / 2**S`\n\n`Bar = 2`\n\n`Next ID = 1`\n\n## Items\n\n| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |\n|---|---|---|---|---|---|---|---|---|---|---|---|\n"
|
||||
|
||||
|
||||
class MemoryPlanContract(PlanStoreContract, unittest.TestCase):
|
||||
def new_store(self) -> stores.PlanStore:
|
||||
def new_store(self) -> plans.PlanStore:
|
||||
return MemoryPlan()
|
||||
|
||||
|
||||
@@ -32,10 +32,10 @@ class FilePlanContract(PlanStoreContract, unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.folder = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory()))
|
||||
|
||||
def new_store(self) -> stores.FilePlan:
|
||||
def new_store(self) -> todo_md.FilePlan:
|
||||
(self.folder / "todo.md").write_text(EMPTY)
|
||||
(self.folder / "README.md").write_text(README)
|
||||
return stores.FilePlan(self.folder / "todo.md", "todo.md", FileStore(self.folder / "README.md", None), MemoryStore(), MemoryStore(), DEFAULT_FLOOR)
|
||||
return todo_md.FilePlan(self.folder / "todo.md", "todo.md", FileStore(self.folder / "README.md", None), MemoryStore(), MemoryStore(), DEFAULT_FLOOR)
|
||||
|
||||
|
||||
class FilePlan(FilePlanContract):
|
||||
@@ -62,7 +62,7 @@ class FilePlan(FilePlanContract):
|
||||
def test_an_edited_tagline_heads_the_detail_too(self):
|
||||
store = self.new_store()
|
||||
id_ = self.filed(store, FIRST, "Why it counts.")
|
||||
store.edit(id_, {stores.TAGLINE: "Count `a | b` runs."}, None)
|
||||
store.edit(id_, {plans.TAGLINE: "Count `a | b` runs."}, None)
|
||||
text = (self.folder / "todo.md").read_text()
|
||||
self.assertIn("| **Count `a \\| b` runs.** |", text)
|
||||
self.assertIn(f"### {id_}. Count `a | b` runs.\n\nWhy it counts.\n", text)
|
||||
@@ -84,7 +84,7 @@ class FilePlan(FilePlanContract):
|
||||
self.assertEqual(self.filed(store, FIRST), 10)
|
||||
todo.write_text("".join(line.replace("| 4 | 1 | 1 by 9 |", "| 4 | 10 | 1 by 9 |") if line.startswith("| 10 ") else line for line in todo.read_text().splitlines(keepends=True)))
|
||||
written = store.edit(first, {"E": "2"}, None)
|
||||
assert isinstance(written, stores.Written), written
|
||||
assert isinstance(written, plans.Written), written
|
||||
self.assertIn("item 10 ", written.notes[0])
|
||||
|
||||
def test_an_id_it_holds_no_item_for_fails_naming_the_file(self):
|
||||
@@ -118,7 +118,7 @@ class FilePlan(FilePlanContract):
|
||||
def test_reads_the_releases_marked_renamed(self):
|
||||
store = self.new_store()
|
||||
(self.folder / "todo.md").write_text(EMPTY + "\n## Renamed\n\n- 0.2.1 renamed to 0.3.0\n")
|
||||
self.assertEqual(store.read(), stores.Plan([], frozenset({release_of("0.2.1")})))
|
||||
self.assertEqual(store.read(), plans.Plan([], frozenset({release_of("0.2.1")})))
|
||||
|
||||
def test_a_field_it_does_not_know_is_a_programming_error(self):
|
||||
with self.assertRaises(ValueError):
|
||||
@@ -130,9 +130,9 @@ class FilePlan(FilePlanContract):
|
||||
id_ = self.filed(store, FIRST)
|
||||
before = (self.folder / "todo.md").read_text()
|
||||
broken, split = "the tagline holds a line break; keep it on one line", "the detail holds a ## or ### heading, which would split ## Details; use #### or drop the #s"
|
||||
self.assertEqual(store.add(FIRST | {stores.TAGLINE: "Count\nthe runs."}, ""), Failure(broken))
|
||||
self.assertEqual(store.add(FIRST | {plans.TAGLINE: "Count\nthe runs."}, ""), Failure(broken))
|
||||
self.assertEqual(store.add(FIRST, "## Why\n"), Failure(split))
|
||||
self.assertEqual(store.edit(id_, {stores.TAGLINE: "Count\nthe runs."}, None), Failure(broken))
|
||||
self.assertEqual(store.edit(id_, {plans.TAGLINE: "Count\nthe runs."}, None), Failure(broken))
|
||||
self.assertEqual(store.edit(id_, {}, "### Why\n"), Failure(split))
|
||||
self.assertEqual((self.folder / "todo.md").read_text(), before)
|
||||
|
||||
@@ -157,7 +157,7 @@ class FilePlan(FilePlanContract):
|
||||
(self.folder / "README.md").write_text(README.replace(VOID, ""))
|
||||
kept, finished = self.filed(store, FIRST | {MOVES: "code health by 1"}), self.filed(store, SECOND)
|
||||
row = [line for line in (self.folder / "todo.md").read_text().splitlines() if line.startswith(f"| {kept} ")]
|
||||
self.assertIsInstance(store.finish(finished), stores.Written)
|
||||
self.assertIsInstance(store.finish(finished), plans.Written)
|
||||
self.assertIn(row[0], (self.folder / "todo.md").read_text())
|
||||
return row[0]
|
||||
self.assertNotEqual(health_row("6.0"), health_row("7.0"))
|
||||
@@ -200,21 +200,47 @@ class Store(unittest.TestCase):
|
||||
def test_a_path_picks_the_markdown_file(self):
|
||||
config = self.config()
|
||||
picked = stores.store(dataclasses.replace(config, paths=config.paths | {"plan": pathlib.Path("/checkout/todo.md")}))
|
||||
self.assertEqual((type(picked), picked.label, picked.tracked), (stores.FilePlan, "/checkout/todo.md", "todo.md"))
|
||||
self.assertEqual((type(picked), picked.label, picked.tracked), (todo_md.FilePlan, "/checkout/todo.md", "todo.md"))
|
||||
|
||||
def test_the_markdown_file_ranks_with_the_configs_floor(self):
|
||||
self.assertEqual(stores.file_plan(self.config(readability_floor=decimal.Decimal("6.5")), pathlib.Path("/checkout/todo.md")).floor, decimal.Decimal("6.5"))
|
||||
|
||||
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))
|
||||
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, scoring.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):
|
||||
weighed = scoring.StatedScoring(JiraScoring("V / 2**S", 1.5), MemoryStore(README), MemoryStore(), MemoryStore(), DEFAULT_FLOOR).read()
|
||||
assert not isinstance(weighed, Failure), weighed
|
||||
self.assertEqual((weighed.bar, list(weighed.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):
|
||||
weighed = scoring.StatedScoring(JiraScoring("V", 1), MemoryStore("## Goals\n\n1. **Achieve:** A.\n"), MemoryStore(), MemoryStore(SCORED.format(overall="6.99")), floor).read()
|
||||
assert not isinstance(weighed, Failure), weighed
|
||||
self.assertEqual(weighed.weights["code health"] > weighed.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 = scoring.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__":
|
||||
unittest.main()
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
"""A plan kept as a markdown file, todo.md, in the shape `rank_todo.py --help` shows: read, filed into, edited, finished, and ranked or checked in place."""
|
||||
import dataclasses
|
||||
import decimal
|
||||
import pathlib
|
||||
|
||||
from plan_store.plans import cells, Plan, Written
|
||||
from failure import Failure
|
||||
from plan.todo_table import item_details, items, NoItemsTable, renames
|
||||
from plan_store import markdown_edits
|
||||
from plan import ranking
|
||||
from record_store.stores import RecordStore
|
||||
from text_files.file_writes import replace_file
|
||||
from plan_store.scoring import weighing_texts
|
||||
|
||||
# What the reader of a missing todo.md is told.
|
||||
MISSING = "every project keeps a todo.md, and rank_todo.py --help shows one"
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class FilePlan:
|
||||
"""A plan kept as a markdown file at path. Every write ranks the file, reading the goals file from goals, the decision log and the comprehension history."""
|
||||
path: pathlib.Path
|
||||
tracked: str | None
|
||||
goals: RecordStore
|
||||
decisions: RecordStore
|
||||
history: RecordStore
|
||||
# The project's readability floor: while the comprehension overall is under it, ranking weighs code health 4 times as much.
|
||||
floor: decimal.Decimal
|
||||
|
||||
@property
|
||||
def label(self) -> str:
|
||||
return str(self.path)
|
||||
|
||||
def read(self) -> Plan | Failure:
|
||||
if not self.path.exists():
|
||||
return NoItemsTable(f"{self.path}: not found; {MISSING}")
|
||||
text = read_text(self.path, MISSING)
|
||||
return text if isinstance(text, Failure) else plan_of(text)
|
||||
|
||||
def add(self, fields: dict[str, str], detail: str) -> Written | Failure:
|
||||
texts = self.texts()
|
||||
if isinstance(texts, Failure):
|
||||
return texts
|
||||
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, comment: str | None = None) -> Written | Failure:
|
||||
texts = self.texts()
|
||||
if isinstance(texts, Failure):
|
||||
return texts
|
||||
text = markdown_edits.edited(texts[0], id_, cells(fields), detail, self.label)
|
||||
return text if isinstance(text, Failure) else self.kept(id_, text, texts)
|
||||
|
||||
def kept(self, id_: int, text: str, texts: tuple[str, str, str, str]) -> Written | Failure:
|
||||
"""Ranks text, the file with item id_ filed or edited, and writes it where the item scores at the bar or above."""
|
||||
ranked = ranking.rank(text, *texts[1:], self.floor)
|
||||
if isinstance(ranked, Failure):
|
||||
return ranked
|
||||
# The write may lower another item under the bar, which the notes then say; the write is refused only where the written item itself scores under the bar.
|
||||
if under := [line for line in ranked.under_bar if line.startswith(f"item {id_} ")]:
|
||||
return Failure(under[0])
|
||||
return self.written(id_, ranked)
|
||||
|
||||
def finish(self, id_: int) -> Written | Failure:
|
||||
texts = self.texts()
|
||||
if isinstance(texts, Failure):
|
||||
return texts
|
||||
text = markdown_edits.finished(texts[0], id_, self.label)
|
||||
if isinstance(text, Failure):
|
||||
return text
|
||||
ranked = ranking.rank(text, *texts[1:], self.floor)
|
||||
return ranked if isinstance(ranked, Failure) else self.written(id_, ranked)
|
||||
|
||||
def rank(self) -> ranking.Ranked | Failure:
|
||||
"""Ranks the file in place, writing it where ranking changed it. The caller prints `reported`'s lines."""
|
||||
texts = self.texts()
|
||||
if isinstance(texts, Failure):
|
||||
return texts
|
||||
ranked = ranking.rank(*texts, self.floor)
|
||||
if isinstance(ranked, Failure):
|
||||
return ranked
|
||||
if ranked.text != texts[0] and (unwritten := self.replaced(ranked.text)):
|
||||
return unwritten
|
||||
return ranked
|
||||
|
||||
def check(self) -> list[str]:
|
||||
"""Why `rank_todo.py --check` fails on the file, empty when it passes: the file is not ranked, or an item scores under the bar."""
|
||||
texts = self.texts()
|
||||
if isinstance(texts, Failure):
|
||||
return [texts.reason]
|
||||
ranked = ranking.rank(*texts, self.floor)
|
||||
if isinstance(ranked, Failure):
|
||||
return [ranked.reason]
|
||||
unranked = [] if ranked.text == texts[0] else [f"{self.path}: not ranked; run rank_todo.py on it"]
|
||||
return unranked + [f"{self.path}: {line}" for line in ranked.under_bar]
|
||||
|
||||
def reported(self, ranked: ranking.Ranked) -> list[str]:
|
||||
"""Ranking's notes and under-bar lines, each prefixed with the file's path, as a tool prints them on stderr."""
|
||||
return [f"{self.path}: {line}" for line in ranked.notes + ranked.under_bar]
|
||||
|
||||
def written(self, id_: int, ranked: ranking.Ranked) -> Written | Failure:
|
||||
"""Writes ranked's text to the file."""
|
||||
return self.replaced(ranked.text) or Written(id_, tuple(self.reported(ranked)))
|
||||
|
||||
def replaced(self, text: str) -> Failure | None:
|
||||
unwritten = replace_file(self.path.resolve(), text.encode("utf-8"))
|
||||
return Failure(f"{self.path}: {unwritten.reason}") if unwritten else None
|
||||
|
||||
def texts(self) -> tuple[str, str, str, str] | Failure:
|
||||
"""What ranking reads: the file, the goals file, the decision log and the comprehension history. The last two are empty when missing; a missing plan, or a goals file that is missing or empty, is a Failure."""
|
||||
plan = read_text(self.path, MISSING)
|
||||
if isinstance(plan, Failure):
|
||||
return plan
|
||||
weighing = weighing_texts(self.goals, self.decisions, self.history)
|
||||
return weighing if isinstance(weighing, Failure) else (plan, *weighing)
|
||||
|
||||
|
||||
def plan_of(todo: str) -> Plan | Failure:
|
||||
"""The plan a todo.md's text holds."""
|
||||
found = items(todo)
|
||||
if isinstance(found, Failure):
|
||||
return found
|
||||
details = item_details(todo)
|
||||
if isinstance(details, Failure):
|
||||
return details
|
||||
marked = renames(todo)
|
||||
if isinstance(marked, Failure):
|
||||
return marked
|
||||
return Plan([dataclasses.replace(item, detail=details.get(item.id, "")) for item in found], frozenset(marked))
|
||||
|
||||
|
||||
def read_text(path: pathlib.Path, missing: str) -> str | Failure:
|
||||
"""path's text; where it is missing, a Failure saying missing."""
|
||||
try:
|
||||
return path.read_text(encoding="utf-8")
|
||||
except FileNotFoundError:
|
||||
return Failure(f"{path}: not found; {missing}")
|
||||
except OSError as failure:
|
||||
return Failure(f"{path}: {failure.strerror}")
|
||||
except UnicodeDecodeError:
|
||||
return Failure(f"{path}: not UTF-8")
|
||||
+27
-20
@@ -31,6 +31,13 @@ and readme.md, since the reviewers and the rules name those files.
|
||||
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,
|
||||
@@ -84,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:
|
||||
@@ -121,13 +132,15 @@ Exit 1, naming each fault on stderr, where no config names the checkout, or its
|
||||
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`, sets `jira-finish-transition` or `jira-finish-status` to anything but a name, without the other or
|
||||
without a `plan` in Jira, or sets `readability-floor` to anything but a number
|
||||
from 1 to 10, and where `env-file`, `jira-finish-transition`, `jira-finish-status`, `notifier` or `touch-predictions` is asked for and not set. No path setting has a default.
|
||||
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, JIRA_FINISH_STATUS, JIRA_FINISH_TRANSITION, load, NOTIFIER, OPTIONAL, ProjectConfig, READABILITY_FLOOR, SETTINGS, TOOLING_ON_HOST, Unnamed, WAIT_FOR_APPROVAL
|
||||
from project_config.settings import CONFIG, ENV_FILE, JIRA_FINISH_STATUS, JIRA_FINISH_TRANSITION, JIRA_SCORE_BAR, JIRA_SCORE_FORMULA, load, OPTIONAL, ProjectConfig, SCALARS, SETTINGS, Unnamed
|
||||
from failure import Failure
|
||||
from git_cli.git_repo import git, Git
|
||||
from project_config import templates
|
||||
@@ -144,23 +157,17 @@ def main(argv: list[str]) -> int:
|
||||
if isinstance(config, Failure):
|
||||
print(config.reason, file=sys.stderr)
|
||||
return 1
|
||||
switches = {WAIT_FOR_APPROVAL: config.wait_for_approval, TOOLING_ON_HOST: config.tooling_on_host}
|
||||
if argv and argv[0] in switches:
|
||||
print("true" if switches[argv[0]] else "false")
|
||||
return 0
|
||||
if argv == [READABILITY_FLOOR]:
|
||||
print(config.readability_floor)
|
||||
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 {}), **({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:
|
||||
# A one-value setting prints its value, its default where the config leaves it out; one without a default, as `notifier`, prints only where set.
|
||||
scalars = {scalar.name: scalar.shown(value) for scalar in SCALARS if (value := getattr(config, scalar.field)) is not None}
|
||||
paths = {**config.places, **({ENV_FILE: str(config.env_file)} if config.env_file 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 {})}
|
||||
shown = paths | scalars
|
||||
if argv and argv[0] not in shown:
|
||||
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]]
|
||||
print(paths[argv[0]] if argv else "\n".join(listed))
|
||||
# The listing leaves out each one-value setting at its default.
|
||||
defaults = ProjectConfig(config.key, config.folder, config.top, {})
|
||||
listed = [*(f"{name}: {path}" for name, path in paths.items()), *(f"{scalar.name}: {scalars[scalar.name]}" for scalar in SCALARS if getattr(config, scalar.field) != getattr(defaults, scalar.field))]
|
||||
print(shown[argv[0]] if argv else "\n".join(listed))
|
||||
return 0
|
||||
|
||||
|
||||
|
||||
+112
-21
@@ -10,7 +10,10 @@ import tomllib
|
||||
import typing
|
||||
|
||||
from failure import Failure
|
||||
from plan.formula import parse_formula
|
||||
from plan.todo_table import SHAPE
|
||||
from project_config import templates
|
||||
from plan.ranking import variables
|
||||
|
||||
PROJECTS = ".claude-projects"
|
||||
CONFIG = "config.toml"
|
||||
@@ -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"
|
||||
@@ -43,7 +48,12 @@ TOUCH_PREDICTIONS = "touch-predictions"
|
||||
JIRA_FINISH_TRANSITION = "jira-finish-transition"
|
||||
JIRA_FINISH_STATUS = "jira-finish-status"
|
||||
JIRA_FINISH = (JIRA_FINISH_TRANSITION, JIRA_FINISH_STATUS)
|
||||
OPTIONAL = (BRANCH, COMMIT_TITLE, ENV_FILE, JIRA_FINISH_STATUS, JIRA_FINISH_TRANSITION, LANGUAGE, NOTIFIER, PULL_REQUEST_TITLE, READABILITY_FLOOR, TOOLING_ON_HOST, TOUCH_PREDICTIONS, WAIT_FOR_APPROVAL)
|
||||
# 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)
|
||||
# The settings allowed only where `plan` names a Jira epic.
|
||||
JIRA_PLAN_ONLY = (*JIRA_FINISH, *JIRA_SCORE)
|
||||
# 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 = {
|
||||
@@ -59,11 +69,6 @@ PAGE_SPELLING = '"confluence:https://<site>/wiki/spaces/<space>/pages/<page ID>"
|
||||
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."""
|
||||
@@ -83,6 +88,13 @@ class Finish:
|
||||
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."""
|
||||
@@ -91,6 +103,11 @@ class Page:
|
||||
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 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."""
|
||||
@@ -103,6 +120,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
|
||||
@@ -115,6 +133,8 @@ class ProjectConfig:
|
||||
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)
|
||||
|
||||
@@ -174,38 +194,94 @@ def load(top: pathlib.Path, main: pathlib.Path, home: pathlib.Path) -> ProjectCo
|
||||
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
|
||||
scalars = {scalar: scalar.read(values[scalar.name]) for scalar in SCALARS if scalar.name in values}
|
||||
finish = [name for setting in JIRA_FINISH if (name := name_of(values.get(setting)))]
|
||||
checks = {LANGUAGE: language_fault, COMMIT_TITLE: templates.title_fault, PULL_REQUEST_TITLE: templates.title_fault, BRANCH: templates.branch_fault}
|
||||
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
|
||||
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"`{scalar.name}` is {values[scalar.name]!r}, {read.reason}" for scalar, read in scalars.items() if isinstance(read, Unfit)),
|
||||
*(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"`{ENV_FILE}` is {values[ENV_FILE]!r}, not {OUTSIDE}"] if misplaced else []),
|
||||
# Each setting that reaches a service needs the file that holds its credentials.
|
||||
*(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),
|
||||
*(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),
|
||||
*([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 []),
|
||||
# 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 set, so `plan` must name a Jira epic" for name in JIRA_PLAN_ONLY 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 {values[name]!r}, not the name Jira shows, such as \"{example}\"" for name, example in zip(JIRA_FINISH, ("Mark as done", "Done")) if name in values and not name_of(values[name])),
|
||||
*(f"`{name}` is set, so `{other}` must be too" for name, other in (JIRA_FINISH, JIRA_FINISH[::-1]) if name in values and other not in values),
|
||||
*(f"`{name}` is set, so `plan` must name a Jira epic" for name in JIRA_FINISH if name in values and not epics["plan"]),
|
||||
*(f"`{name}` is {value!r}, not true or false" for name, value in ((WAIT_FOR_APPROVAL, waits), (TOOLING_ON_HOST, on_host)) if not isinstance(value, bool)),
|
||||
*([f"`{READABILITY_FLOOR}` is {values[READABILITY_FLOOR]!r}, not a number from 1 to 10; write a bare number, such as `{READABILITY_FLOOR} = 7.0`"] if floor is None else []),
|
||||
*(f"`{name}` is {values[name]!r}, {fault}" for name, check in checks.items() if name in values and (fault := check(values[name]))),
|
||||
*([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 []),
|
||||
]
|
||||
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.
|
||||
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, jira_finish=Finish(*finish) if finish else None, pages=pages)
|
||||
# faults names a formula or bar a plan in Jira lacks or misspells.
|
||||
assert scoring is not None or not epics["plan"]
|
||||
defaulted = ProjectConfig(file.parent.name, file.parent, top, {name: path for name, path in paths.items() if path}, env_file, epic=epics["plan"], goals_epic=epics["goals-and-audience"], jira_finish=Finish(*finish) if finish else None, jira_scoring=scoring, pages=pages)
|
||||
return dataclasses.replace(defaulted, **{scalar.field: read for scalar, read in scalars.items()})
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Unfit:
|
||||
"""Why a setting's value doesn't fit it, as the end of the sentence "`<setting>` is <value>, <reason>"."""
|
||||
reason: str
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Scalar:
|
||||
"""An optional setting that holds one value, not a path: the ProjectConfig field it sets, whose default is its value where the config leaves it out, how its value is read, and how `project-config <name>` prints it."""
|
||||
name: str
|
||||
field: str
|
||||
# The value, or Unfit; typed Any, since each Scalar reads into its own field's type.
|
||||
read: typing.Callable[[object], typing.Any]
|
||||
shown: typing.Callable[[typing.Any], str] = str
|
||||
|
||||
|
||||
def switch(value: object) -> bool | Unfit:
|
||||
return value if isinstance(value, bool) else Unfit("not true or false")
|
||||
|
||||
|
||||
def floor_read(value: object) -> decimal.Decimal | Unfit:
|
||||
floor = floor_of(value)
|
||||
return Unfit(f"not a number from 1 to 10; write a bare number, such as `{READABILITY_FLOOR} = 7.0`") if floor is None else floor
|
||||
|
||||
|
||||
def parallel_read(value: object) -> int | Unfit:
|
||||
return value if type(value) is int and value >= 1 else Unfit(f"not a whole number of 1 or more, such as `{PARALLEL_CHUNKS} = 2`")
|
||||
|
||||
|
||||
def notifier_read(value: object) -> Notifier | Unfit:
|
||||
return next((name for name in NOTIFIERS if name == value), None) or Unfit(f"not {' or '.join(NOTIFIERS)}")
|
||||
|
||||
|
||||
def text_read(fault: typing.Callable[[object], str | None]) -> typing.Callable[[object], str | Unfit]:
|
||||
"""A text setting's reader, from the check that says why a value doesn't fit."""
|
||||
def read(value: object) -> str | Unfit:
|
||||
found = fault(value)
|
||||
return Unfit(found) if found else str(value)
|
||||
return read
|
||||
|
||||
|
||||
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:
|
||||
@@ -240,6 +316,21 @@ def language_fault(value: object) -> str | None:
|
||||
return None if named else 'not a language\'s English name in words of letters, such as "Swedish" or "Brazilian Portuguese"'
|
||||
|
||||
|
||||
# Each one-value setting, in the order `project-config` lists them.
|
||||
SCALARS = (
|
||||
Scalar(WAIT_FOR_APPROVAL, "wait_for_approval", switch, lambda on: "true" if on else "false"),
|
||||
Scalar(TOOLING_ON_HOST, "tooling_on_host", switch, lambda on: "true" if on else "false"),
|
||||
Scalar(READABILITY_FLOOR, "readability_floor", floor_read),
|
||||
Scalar(PARALLEL_CHUNKS, "parallel_chunks", parallel_read),
|
||||
Scalar(NOTIFIER, "notifier", notifier_read),
|
||||
Scalar(LANGUAGE, "language", text_read(language_fault)),
|
||||
Scalar(COMMIT_TITLE, "commit_title", text_read(templates.title_fault)),
|
||||
Scalar(PULL_REQUEST_TITLE, "pull_request_title", text_read(templates.title_fault)),
|
||||
Scalar(BRANCH, "branch", text_read(templates.branch_fault)),
|
||||
)
|
||||
OPTIONAL = tuple(sorted((ENV_FILE, TOUCH_PREDICTIONS, *JIRA_PLAN_ONLY, *(scalar.name for scalar in SCALARS))))
|
||||
|
||||
|
||||
def lies_in(path: pathlib.Path, *places: pathlib.Path) -> bool:
|
||||
"""Whether path lies in one of places. Both sides are resolved, so a symlink can't lead a path out of the place it names."""
|
||||
return any(path.resolve().is_relative_to(place.resolve()) for place in places)
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user