Compare commits
66 Commits
patch-0.10.1
...
item-375
| Author | SHA1 | Date | |
|---|---|---|---|
| d01d0d421e | |||
| a921b08207 | |||
| e2c4e94cb2 | |||
| 251b0e8f02 | |||
| 55235a07d8 | |||
| 96e1b364f1 | |||
| 30b0e9e0a7 | |||
| 255d5f7bb1 | |||
| 986697ab52 | |||
| fa9d487afd | |||
| fbd1b5e99d | |||
| f3eaf19f62 | |||
| 4e02971bfe | |||
| 3fd7e15255 | |||
| 2de1e7e74e | |||
| eecb0387ca | |||
| 7fc64d860a | |||
| 00c1dd2480 | |||
| f768ef3272 | |||
| cf1180734c | |||
| 727ed70ecb | |||
| 9d9c5a3352 | |||
| 2db4759c2a | |||
| 9d685c52b3 | |||
| c56b3166a0 | |||
| b6a53ef98b | |||
| c46a117088 | |||
| 121aba05ea | |||
| eb5a63edd2 | |||
| 2707cfc04e | |||
| 53a54e50dd | |||
| 2e9d9dd714 | |||
| 0681e9be17 | |||
| 2fdc75d035 | |||
| bad76b07c8 | |||
| 9dd8441f3b | |||
| 1210f8cd68 | |||
| 0f0ba7fa43 | |||
| 37078cffa9 | |||
| 30129051ad | |||
| 58055f0fac | |||
| 55ad029df2 | |||
| b89ac805d3 | |||
| 8b649682dc | |||
| 4447e89e48 | |||
| 3c522160c9 | |||
| 39bf6e6d94 | |||
| 0339a515fc | |||
| 75c3c581ef | |||
| cca16e702a | |||
| 36d9ddb6f5 | |||
| dbc8cfe854 | |||
| fffba3d454 | |||
| 2695e9b530 | |||
| 4873ee9e74 | |||
| 70e3c0b9de | |||
| 93a4da0728 | |||
| bcb04e32d4 | |||
| 37fcedc5bf | |||
| e18555be3e | |||
| 2136413dd6 | |||
| e37518db29 | |||
| 9e0a6d4d7b | |||
| aff46cd64e | |||
| 0109f97cd7 | |||
| 85f3b74d4f |
+6
-1
@@ -2,7 +2,12 @@
|
||||
|
||||
## Unreleased
|
||||
|
||||
- Two loop-claude runs in one project now work side by side, each on its own chunk. Each loop holds a slot of the project, a locked file under `~/.local/state/loop-claude/<key>/`, and names its session after it: the first loop's session keeps its name, `A <key> loop-claude`, and the second's is `A <key> loop-claude 2`. A rerun resumes a chunk left open first. A commit in the config's folder now takes only the file it changed, as `git commit -m <title> -- <file>`.
|
||||
- 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.
|
||||
|
||||
@@ -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.
|
||||
@@ -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".
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -164,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.
|
||||
@@ -205,7 +209,7 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a
|
||||
- `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 shipped routing ladder (`routing-ladder.json`) and its steps (`ladder.py`), and reads a ladder from that file or a project's own (`ladder_file.py`), for loop-claude, `rule_hook`, both replay tools and `subagent-rung`. It finds a project's config folder through `project_config`. It also holds the list prices, which `routing_figures` and `transcript_archive` read.
|
||||
- `notifier/` sends the human a DM through the notifier a project's config names, for `notify` and for loop-claude through `loop_effects`; `mattermost_dm/` and `slack_dm/` are its two backends.
|
||||
- `plan_store/` reads and writes a project's plan through the store the project's config names (`stores.py`), with the markdown file's edits in `markdown_edits.py`. `contract.py` holds the tests every backend that writes must pass, which `jira_epic.py` doesn't yet, and `fakes.py` a plan in memory.
|
||||
- `plan_store/` reads and writes a project's plan through the store the project's config names (`stores.py`), with the markdown file's edits in `markdown_edits.py`. `contract.py` holds the tests every backend that writes must pass, which `jira_epic.py` doesn't yet, since it changes no link, and `fakes.py` a plan in memory.
|
||||
- `rank_todo.py`, `settings_filter.py` and `statusline.py` are tools of one file each, tested beside them.
|
||||
- `record_store/` reads and writes a project's records, each through the store the project's config names (`stores.py`): 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`.
|
||||
|
||||
+49
-17
@@ -9,7 +9,7 @@ from chunk_preflight.gathered import Forge
|
||||
from deploy_release.forge import Run
|
||||
|
||||
BIN = pathlib.Path(__file__).resolve().parents[1]
|
||||
# A human answers in hours, so merge polls once a minute and gives up after 90 minutes, which leaves room for the checks wait inside the 2 hours a background command may run, so that the give-up message prints.
|
||||
# A human answers in hours, so merge polls once a minute and gives up after 90 minutes. That leaves half an hour for the queue and the checks inside the 2 hours a background command may run; a run that needs more is killed before the give-up message prints, and its next run goes on from what it pushed.
|
||||
POLL_SECONDS = 60
|
||||
WAIT_SECONDS = 90 * 60
|
||||
|
||||
@@ -26,24 +26,56 @@ def awaited(forge: Forge, run: Run) -> bool | Failure:
|
||||
return answer.strip() == "true"
|
||||
|
||||
|
||||
# Each review thread, with whether it is resolved and who wrote its last comment, beside who opened the pull request. gh fills {owner} and {repo} from the checkout.
|
||||
THREADS = """query($owner: String!, $repo: String!, $number: Int!) { repository(owner: $owner, name: $repo) { pullRequest(number: $number) {
|
||||
author { login }
|
||||
reviewThreads(first: 100) { nodes { isResolved path comments(last: 1) { nodes { author { login } } } } }
|
||||
} } }"""
|
||||
|
||||
|
||||
def approval(number: str, run: Run) -> bool | Failure:
|
||||
"""Whether GitHub reports pull request number approved, as its branch protection asks, read once: False while it still wants a review. A Failure where a reviewer requested changes, or where the protection asks for no review."""
|
||||
viewed = run(["gh", "pr", "view", number, "--json", "reviewDecision"])
|
||||
try:
|
||||
decision = viewed if isinstance(viewed, Failure) else json.loads(viewed)["reviewDecision"]
|
||||
except (ValueError, KeyError, TypeError):
|
||||
return Failure(f"gh pr view printed no review decision: {str(viewed).strip()[:200]}")
|
||||
if isinstance(decision, Failure):
|
||||
return decision
|
||||
if decision == "CHANGES_REQUESTED":
|
||||
return Failure(f"a reviewer requested changes on pull request {number}")
|
||||
if not decision:
|
||||
return Failure("wait-for-approval is set, but the branch protection requires no review, so GitHub reports no decision; ask the human to require a review in the protection or to set wait-for-approval to false")
|
||||
if decision not in ("APPROVED", "REVIEW_REQUIRED"):
|
||||
return Failure(f"GitHub reports the review decision {decision!r} on pull request {number}, and chunk-pr doesn't know that decision")
|
||||
return decision == "APPROVED"
|
||||
|
||||
|
||||
def approved(number: str, run: Run, sleep: typing.Callable[[float], None] = time.sleep) -> Failure | None:
|
||||
"""None once GitHub reports pull request number approved, as its branch protection asks; a Failure where a reviewer requested changes, where the protection asks for no review, or where no approval came within WAIT_SECONDS."""
|
||||
"""None once GitHub reports pull request number approved; a Failure where `approval` fails, where a reviewer's comment waits for an answer, or where no approval came within WAIT_SECONDS."""
|
||||
for waited in range(0, WAIT_SECONDS + 1, POLL_SECONDS):
|
||||
viewed = run(["gh", "pr", "view", number, "--json", "reviewDecision"])
|
||||
try:
|
||||
decision = viewed if isinstance(viewed, Failure) else json.loads(viewed)["reviewDecision"]
|
||||
except (ValueError, KeyError, TypeError):
|
||||
return Failure(f"gh pr view printed no review decision: {str(viewed).strip()[:200]}")
|
||||
if isinstance(decision, Failure):
|
||||
return decision
|
||||
if decision == "APPROVED":
|
||||
return None
|
||||
if decision == "CHANGES_REQUESTED":
|
||||
return Failure(f"a reviewer requested changes on pull request {number}")
|
||||
if not decision:
|
||||
return Failure("wait-for-approval is set, but the branch protection requires no review, so GitHub reports no decision; ask the human to require a review in the protection or to set wait-for-approval to false")
|
||||
if decision != "REVIEW_REQUIRED":
|
||||
return Failure(f"GitHub reports the review decision {decision!r} on pull request {number}, and chunk-pr doesn't know that decision")
|
||||
read = approval(number, run)
|
||||
if read is True or isinstance(read, Failure):
|
||||
return None if read is True else read
|
||||
asked = unanswered(number, run)
|
||||
if asked is not None:
|
||||
return asked
|
||||
if waited < WAIT_SECONDS:
|
||||
sleep(POLL_SECONDS)
|
||||
return Failure(f"pull request {number} wasn't approved within {WAIT_SECONDS // 60} minutes; run chunk-pr merge again once it is")
|
||||
|
||||
|
||||
def unanswered(number: str, run: Run) -> Failure | None:
|
||||
"""A Failure naming the files where a reviewer's comment waits for an answer on pull request number: a review thread nobody resolved, whose last comment someone other than the pull request's author wrote. So a thread the worker answered, as that author, waits for the reviewer again. None where no thread waits."""
|
||||
read = run(["gh", "api", "graphql", "-f", f"query={THREADS}", "-F", "owner={owner}", "-F", "repo={repo}", "-F", f"number={number}"])
|
||||
try:
|
||||
pull = read if isinstance(read, Failure) else json.loads(read)["data"]["repository"]["pullRequest"]
|
||||
if isinstance(pull, Failure):
|
||||
return pull
|
||||
author = pull["author"]["login"]
|
||||
waiting = sorted({thread["path"] for thread in pull["reviewThreads"]["nodes"] if not thread["isResolved"] and any(comment["author"]["login"] != author for comment in thread["comments"]["nodes"])})
|
||||
except (ValueError, KeyError, TypeError):
|
||||
return Failure(f"gh api graphql printed no review threads: {str(read).strip()[:200]}")
|
||||
if not waiting:
|
||||
return None
|
||||
return Failure(f"a reviewer's comment on pull request {number} waits for an answer, in {', '.join(waiting)}; answer it in its thread, push any fix, and run chunk-pr merge again")
|
||||
|
||||
+235
-53
@@ -3,7 +3,7 @@
|
||||
usage: chunk-pr open <title> [<body>]
|
||||
chunk-pr sync
|
||||
chunk-pr ready [<title>]
|
||||
chunk-pr merge
|
||||
chunk-pr merge [--finish <ID> [--changelog <bullet> | --no-changelog]]...
|
||||
chunk-pr clean
|
||||
|
||||
Run it in the chunk's worktree, on the chunk's branch. ready and merge act on the branch's open
|
||||
@@ -25,22 +25,44 @@ ready marks the pull request ready for review. On Gitea a draft is a pull req
|
||||
starts with `WIP: `, so there it drops that prefix. Given <title>, one line, which it holds
|
||||
to the template as open does, it sets that
|
||||
as the pull request's title first; where that fails, the pull request stays a draft.
|
||||
merge waits for the pull request's checks, and those origin's default branch requires, to pass
|
||||
on the head, then merges the pull request, and only while its head is still the commit
|
||||
checked out, so a push after the gate is never merged. Where no check reports within a
|
||||
minute, it takes the pull request as having none. It refuses where a check fails, or, on
|
||||
Gitea, where the checks have not all passed within 30 minutes; on GitHub, gh watches them
|
||||
until they end. Run it in the background.
|
||||
It takes the first merge method the repository allows of: a merge commit, fast-forward
|
||||
only, a rebase followed by a merge commit, a rebase, a squash. GitHub offers only the
|
||||
merge commit, the rebase and the squash. It also refuses where `larv-review
|
||||
scoring-run-owed` exits 1, because the chunk owes a scoring run it has not recorded.
|
||||
merge merges the pull request in its turn: the chunks of one project on this machine take
|
||||
turns, one at a time. Run it in the background. In its turn it:
|
||||
1. fetches origin and merges its default branch into the branch, as sync does;
|
||||
2. finishes each plan item a --finish names with `todo-item finish`, passing on
|
||||
--changelog or --no-changelog, and commits what that changed in the plan and the
|
||||
changelog, so both change only at merge time, on top of every chunk merged before;
|
||||
3. pushes, also where step 2 failed after step 1 brought changes in;
|
||||
4. waits for the pull request's checks, and those origin's default branch requires, to
|
||||
pass on the head; where no check reports within a minute, it takes the pull request
|
||||
as having none;
|
||||
5. merges the pull request, only while its head is still the commit checked out, so a
|
||||
push after the gate is never merged. It takes the first merge method the repository
|
||||
allows of: a merge commit, fast-forward only, a rebase followed by a merge commit, a
|
||||
rebase, a squash. GitHub offers only the merge commit, the rebase and the squash.
|
||||
Its last line names each --finish item the plan did not hold when it began: an earlier
|
||||
run finished that item, or its ID is mistyped.
|
||||
Where the project's config sets `wait-for-approval = true` (`project-config --help`), it
|
||||
also waits, once the checks have passed, until GitHub reports the pull request approved
|
||||
as its branch protection requires. It refuses at once where a reviewer requested changes,
|
||||
where the protection requires no review, on Gitea, and where it cannot read the config.
|
||||
After 90 minutes without an approval it refuses too; run it again once the pull request
|
||||
is approved.
|
||||
merges only once GitHub reports the pull request approved as its branch protection
|
||||
requires. It waits for that outside its turn, so other chunks merge meanwhile, and takes
|
||||
a new turn once approved.
|
||||
It stops, without merging, and says what to do before running it again:
|
||||
- on a merge conflict in step 1, naming the conflicted files, with the merge in progress;
|
||||
- where `larv-review scoring-run-owed` exits 1 after step 3, because the chunk owes a
|
||||
scoring run it has not recorded;
|
||||
- where origin's default branch has moved since the branch last recorded a paired
|
||||
ruling, since that ruling read a head that no longer merges;
|
||||
- where a check fails, or, on Gitea, where the checks have not all passed within 30
|
||||
minutes; on GitHub, gh watches them until they end;
|
||||
- where other pull requests still hold the turn after 30 minutes, naming the last;
|
||||
- with `wait-for-approval`: where a reviewer requested changes, where the protection
|
||||
requires no review, on Gitea, where it cannot read the config, and after 90 minutes
|
||||
without an approval;
|
||||
- with `wait-for-approval`, approved or not: where a reviewer's comment waits for an
|
||||
answer, which is a review thread nobody resolved whose last comment is not the pull
|
||||
request author's. Answer it in its thread and push any fix.
|
||||
A run that waits for an approval takes two turns, so it can last the 90 minutes and,
|
||||
twice, the 30 minutes in the queue and the checks. One killed before that left the
|
||||
branch pushed, so run it again.
|
||||
clean acts once the forge reports the branch's pull request merged at the commit checked out,
|
||||
by any merge method. It fetches origin, fast-forwards the main checkout to origin's
|
||||
default branch, removes the chunk's worktree, then deletes the local branch; origin's
|
||||
@@ -51,7 +73,9 @@ clean acts once the forge reports the branch's pull request merged at the com
|
||||
|
||||
It prints what it did, exit 0, or why it failed, exit 1.
|
||||
"""
|
||||
import contextlib
|
||||
import dataclasses
|
||||
import fcntl
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
@@ -59,7 +83,7 @@ import sys
|
||||
import time
|
||||
import typing
|
||||
|
||||
from chunk_pr.approval import approved, awaited
|
||||
from chunk_pr.approval import approval, approved, awaited, unanswered
|
||||
from deploy_release.forge import checks_passed, gitea, merged_pull, open_pull, required_checks, Run, runner
|
||||
from failure import Failure
|
||||
from chunk_preflight.gathered import Forge
|
||||
@@ -69,7 +93,14 @@ from project_config import templates
|
||||
BIN = pathlib.Path(__file__).resolve().parents[1]
|
||||
# How long merge waits for a check to report before it takes a pull request without any as passed: CI queues its checks within seconds of a push, and merge may run right after one.
|
||||
NO_CHECKS_SECONDS = 60
|
||||
USAGE = "usage: chunk-pr open <title> [<body>] | chunk-pr sync | chunk-pr ready [<title>] | chunk-pr merge | chunk-pr clean"
|
||||
# The file, in the git folder that every worktree of the checkout shares, that a merge keeps locked with flock for its turn: so every chunk of the project on this machine queues on it.
|
||||
QUEUE = "chunk-pr-merge-queue"
|
||||
# A turn lasts as long as its checks, which chunk-pr waits half an hour for on Gitea, so a queue still held after that is reported, not waited out.
|
||||
QUEUE_SECONDS = 30 * 60
|
||||
QUEUE_POLL_SECONDS = 10
|
||||
# The line record-ruling writes into the comprehension history, as git's -G reads it.
|
||||
RULING = "^Ruling: "
|
||||
USAGE = "usage: chunk-pr open <title> [<body>] | chunk-pr sync | chunk-pr ready [<title>] | chunk-pr merge [--finish <ID> [--changelog <bullet> | --no-changelog]]... | chunk-pr clean"
|
||||
|
||||
# Each forge's merge methods in the order merge prefers them, as the repository setting that allows the method and the method's name in the forge's merge call. A merge commit and a fast-forward keep the branch's commits as they are; a rebase or a squash rewrites them.
|
||||
METHODS: dict[Forge, tuple[tuple[str, str], ...]] = {
|
||||
@@ -99,8 +130,9 @@ def step(argv: list[str], run: Run) -> str | Failure:
|
||||
return synced(run)
|
||||
case ["ready", *title] if len(title) <= 1 and not any(given.startswith("-") for given in title):
|
||||
return Failure("give a title of one line") if title and not one_line(title[0]) else (misfit(title[0], run) if title else None) or marked_ready(run, title[0] if title else None)
|
||||
case ["merge"]:
|
||||
return merged(run)
|
||||
case ["merge", *given]:
|
||||
finishes = finishes_of(given)
|
||||
return Failure(USAGE) if finishes is None else merged(run, finishes=finishes)
|
||||
case ["clean"]:
|
||||
return cleaned(run)
|
||||
return Failure(USAGE)
|
||||
@@ -195,23 +227,10 @@ def synced(run: Run) -> str | Failure:
|
||||
return base
|
||||
if branch == base:
|
||||
return Failure(f"{branch} is origin's default branch; sync the chunk's branch")
|
||||
fetched = run(["git", "fetch", "--quiet", "origin"])
|
||||
if isinstance(fetched, Failure):
|
||||
return fetched
|
||||
behind = answers(run, ["rev-list", "--count", f"HEAD..origin/{base}"], ["rev-parse", "--show-toplevel"])
|
||||
if isinstance(behind, Failure):
|
||||
return behind
|
||||
count, root = behind
|
||||
if count == "0":
|
||||
done = f"{branch} already holds origin/{base}."
|
||||
else:
|
||||
merged = run(["git", "merge", "--quiet", "--no-edit", f"origin/{base}"])
|
||||
if isinstance(merged, Failure):
|
||||
conflicted = answers(run, ["diff", "--name-only", "--diff-filter=U"])
|
||||
if isinstance(conflicted, Failure) or not conflicted[0]:
|
||||
return merged
|
||||
return Failure(f"merging origin/{base} into {branch} conflicts in {', '.join(conflicted[0].splitlines())}; the merge stays in progress: resolve them and commit")
|
||||
done = f"Merged origin/{base} into {branch}."
|
||||
level = levelled(run, branch, base)
|
||||
if isinstance(level, Failure):
|
||||
return level
|
||||
done = f"Merged origin/{base} into {branch}." if level else f"{branch} already holds origin/{base}."
|
||||
plan = run([str(BIN / "project-config"), "plan"])
|
||||
if isinstance(plan, Failure):
|
||||
return Failure(f"{done.removesuffix('.')}, but the plan to check cannot be found: {plan.reason}")
|
||||
@@ -224,6 +243,25 @@ def synced(run: Run) -> str | Failure:
|
||||
return f"{done}\nrank_todo.py --check todo.md passed."
|
||||
|
||||
|
||||
def levelled(run: Run, branch: str, base: str, resolve: str = "resolve them and commit") -> bool | Failure:
|
||||
"""Fetch origin and merge its base into branch, the one checked out: whether that brought anything in. On a conflict the merge stays in progress, and the Failure names the conflicted files and ends with resolve, the caller's words for what to do about them."""
|
||||
fetched = run(["git", "fetch", "--quiet", "origin"])
|
||||
if isinstance(fetched, Failure):
|
||||
return fetched
|
||||
behind = answers(run, ["rev-list", "--count", f"HEAD..origin/{base}"])
|
||||
if isinstance(behind, Failure):
|
||||
return behind
|
||||
if behind[0] == "0":
|
||||
return False
|
||||
merged = run(["git", "merge", "--quiet", "--no-edit", f"origin/{base}"])
|
||||
if isinstance(merged, Failure):
|
||||
conflicted = answers(run, ["diff", "--name-only", "--diff-filter=U"])
|
||||
if isinstance(conflicted, Failure) or not conflicted[0]:
|
||||
return merged
|
||||
return Failure(f"merging origin/{base} into {branch} conflicts in {', '.join(conflicted[0].splitlines())}; the merge stays in progress: {resolve}")
|
||||
return True
|
||||
|
||||
|
||||
def marked_ready(run: Run, title: str | None) -> str | Failure:
|
||||
found = pull(run)
|
||||
if isinstance(found, Failure):
|
||||
@@ -241,33 +279,177 @@ def marked_ready(run: Run, title: str | None) -> str | Failure:
|
||||
return f"Marked pull request #{number} ready, titled “{title}”." if title is not None else f"Marked pull request #{number} ready."
|
||||
|
||||
|
||||
def merged(run: Run, sleep: typing.Callable[[float], None] = time.sleep) -> str | Failure:
|
||||
def finishes_of(given: list[str]) -> list[list[str]] | None:
|
||||
"""`todo-item finish`'s arguments for each item that merge's flags name, in their order; None where the flags are malformed."""
|
||||
finishes, rest = [], given
|
||||
while rest:
|
||||
match rest:
|
||||
case ["--finish", item, "--changelog", bullet, *rest] if item.isdigit():
|
||||
finishes.append([item, "--changelog", bullet])
|
||||
case ["--finish", item, "--no-changelog", *rest] if item.isdigit():
|
||||
finishes.append([item, "--no-changelog"])
|
||||
case ["--finish", item, *rest] if item.isdigit():
|
||||
finishes.append([item])
|
||||
case _:
|
||||
return None
|
||||
return finishes
|
||||
|
||||
|
||||
def merged(run: Run, sleep: typing.Callable[[float], None] = time.sleep, finishes: typing.Sequence[list[str]] = ()) -> str | Failure:
|
||||
"""Merge the branch's pull request in the project's merge queue. Each pass of the loop is one turn in the queue; a pull request that still wants its approval leaves the queue while it waits, so the next chunk merges meanwhile, and takes a new turn once approved."""
|
||||
found = pull(run)
|
||||
if isinstance(found, Failure):
|
||||
return found
|
||||
forge, number, head = found
|
||||
forge, number, _ = found
|
||||
waits = awaited(forge, run)
|
||||
if isinstance(waits, Failure):
|
||||
return waits
|
||||
owed = run([str(BIN / "larv-review"), "scoring-run-owed"])
|
||||
if isinstance(owed, Failure):
|
||||
return owed
|
||||
method = merge_method(forge, run)
|
||||
if isinstance(method, Failure):
|
||||
return method
|
||||
base = default_branch(run)
|
||||
required = base if isinstance(base, Failure) else required_checks(forge, base, run)
|
||||
checked = required if isinstance(required, Failure) else checks_passed(forge, number, head, required, run, sleep, NO_CHECKS_SECONDS)
|
||||
if isinstance(checked, Failure):
|
||||
return checked
|
||||
approval = approved(number, run, sleep) if waits else None
|
||||
if isinstance(approval, Failure):
|
||||
return approval
|
||||
if forge == "gh":
|
||||
done = run(["gh", "pr", "merge", number, method, "--match-head-commit", head])
|
||||
else:
|
||||
done = gitea(run, f"repos/{{owner}}/{{repo}}/pulls/{number}/merge", f"Do={method}", f"head_commit_id={head}")
|
||||
return done if isinstance(done, Failure) else f"Merged pull request #{number} ({method.removeprefix('--')})."
|
||||
if isinstance(required, Failure):
|
||||
return required
|
||||
queue = answers(run, ["rev-parse", "--path-format=absolute", "--git-common-dir"])
|
||||
if isinstance(queue, Failure):
|
||||
return queue
|
||||
absent = unplanned(run, finishes)
|
||||
if isinstance(absent, Failure):
|
||||
return absent
|
||||
file = pathlib.Path(queue[0]) / QUEUE
|
||||
while True:
|
||||
try:
|
||||
with turn(file, number, sleep):
|
||||
head = levelled_and_finished(run, str(base), finishes)
|
||||
checked = head if isinstance(head, Failure) else checks_passed(forge, number, head, required, run, sleep, NO_CHECKS_SECONDS)
|
||||
if isinstance(checked, Failure):
|
||||
return checked
|
||||
ready = approval(number, run) if waits else True
|
||||
asked = unanswered(number, run) if waits and ready is True else None
|
||||
if isinstance(ready, Failure):
|
||||
return ready
|
||||
if asked is not None:
|
||||
return asked
|
||||
if ready and forge == "gh":
|
||||
done = run(["gh", "pr", "merge", number, method, "--match-head-commit", str(head)])
|
||||
elif ready:
|
||||
done = gitea(run, f"repos/{{owner}}/{{repo}}/pulls/{number}/merge", f"Do={method}", f"head_commit_id={head}")
|
||||
if ready:
|
||||
return done if isinstance(done, Failure) else f"Merged pull request #{number} ({method.removeprefix('--')}).{absent}"
|
||||
except Held as held:
|
||||
return Failure(f"the merge queue stayed held for {QUEUE_SECONDS // 60} minutes, last by pull request #{held.args[0] or '?'}, so this one took no turn; run chunk-pr merge again")
|
||||
except OSError as failure:
|
||||
return Failure(f"cannot take a turn in the merge queue, {file}: {failure.strerror}")
|
||||
waited = approved(number, run, sleep)
|
||||
if isinstance(waited, Failure):
|
||||
return waited
|
||||
|
||||
|
||||
def unplanned(run: Run, finishes: typing.Sequence[list[str]]) -> str | Failure:
|
||||
"""A sentence for merge's last line, naming each item of finishes the plan doesn't hold as merge begins: an earlier run finished it, or its ID is mistyped, and only the reader can tell which. Empty where the plan holds them all."""
|
||||
absent = []
|
||||
for finish in finishes:
|
||||
shown = run([str(BIN / "todo-item"), "show", finish[0]])
|
||||
if isinstance(shown, Failure) and f"holds no item {finish[0]}" not in shown.reason:
|
||||
return shown
|
||||
absent += [finish[0]] if isinstance(shown, Failure) else []
|
||||
return f" The plan held no item {', '.join(absent)} when merge began, so merge left the plan as it was there." if absent else ""
|
||||
|
||||
|
||||
class Held(Exception):
|
||||
"""Other merges kept the queue for QUEUE_SECONDS; the argument is the number of the pull request that held it last."""
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def turn(queue: pathlib.Path, number: str, sleep: typing.Callable[[float], None]) -> typing.Iterator[None]:
|
||||
"""Hold the project's merge queue as pull request number: wait until no other chunk-pr merge on this machine holds it, and free it on the way out, however that is. Raises Held where another one still holds it after QUEUE_SECONDS, and OSError where the file cannot be opened or locked."""
|
||||
fd = os.open(queue, os.O_RDWR | os.O_CREAT, 0o644)
|
||||
try:
|
||||
for waited in range(0, QUEUE_SECONDS + 1, QUEUE_POLL_SECONDS):
|
||||
try:
|
||||
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
break
|
||||
except BlockingIOError:
|
||||
if waited == QUEUE_SECONDS:
|
||||
raise Held(os.pread(fd, 20, 0).decode(errors="replace").strip()) from None
|
||||
sleep(QUEUE_POLL_SECONDS)
|
||||
os.ftruncate(fd, 0)
|
||||
os.pwrite(fd, number.encode(), 0)
|
||||
yield
|
||||
finally:
|
||||
os.close(fd)
|
||||
|
||||
|
||||
def levelled_and_finished(run: Run, base: str, finishes: typing.Sequence[list[str]]) -> str | Failure:
|
||||
"""What merge does to the branch inside its turn, before the checks: merge origin's base into it, finish the plan items, and push. The head to merge, or why the worker must act first. Whatever it committed is pushed before it fails, so the pull request's head stays the commit checked out."""
|
||||
found = checkout(run)
|
||||
if isinstance(found, Failure):
|
||||
return found
|
||||
_, branch, before = found
|
||||
moved = levelled(run, branch, base, "resolve them, commit, push, and run chunk-pr merge again")
|
||||
if isinstance(moved, Failure):
|
||||
return moved
|
||||
failed = next((failure for finish in finishes if (failure := finished(run, branch, finish))), None)
|
||||
head = answers(run, ["rev-parse", "HEAD"])
|
||||
if isinstance(head, Failure):
|
||||
return head
|
||||
pushed = run(["git", "push", "--quiet", "origin", branch]) if head[0] != before else ""
|
||||
if isinstance(pushed, Failure):
|
||||
return pushed
|
||||
# The scoring run is asked for only now: scoring-run-owed counts as shipped the items the committed plan no longer holds.
|
||||
owed = failed or run([str(BIN / "larv-review"), "scoring-run-owed"])
|
||||
if isinstance(owed, Failure):
|
||||
return owed
|
||||
return remeasure(run, base) or head[0]
|
||||
|
||||
|
||||
def finished(run: Run, branch: str, finish: list[str]) -> Failure | None:
|
||||
"""Finish one plan item with `todo-item finish` and commit what that changed. An item the plan no longer holds was finished by an earlier run of merge, which may have stopped before its commit: so the plan and the changelog are committed either way."""
|
||||
shown = run([str(BIN / "todo-item"), "show", finish[0]])
|
||||
if isinstance(shown, Failure) and f"holds no item {finish[0]}" not in shown.reason:
|
||||
return shown
|
||||
read = ["" if isinstance(shown, Failure) else run([str(BIN / "todo-item"), "finish", *finish]), run([str(BIN / "project-config"), "commit-title"]), run([str(BIN / "project-config"), "branch"]), run([str(BIN / "project-config"), "plan"]), run([str(BIN / "project-config"), "changelog"])]
|
||||
if failed := next((answer for answer in read if isinstance(answer, Failure)), None):
|
||||
return failed
|
||||
_, template, branch_template, *records = (str(answer).strip() for answer in read)
|
||||
summary = f"Finish item {finish[0]} in the plan"
|
||||
# A branch that doesn't fit the config's `branch` template has no ID for {id}, so its titles are the summary alone, as CLAUDE.md → "Git, commits, and PRs" says.
|
||||
title = template.replace(templates.ID, finish[0]).replace(templates.SUMMARY, summary) if templates.branch_fits(branch_template, branch) else summary
|
||||
return committed(run, title, [pathlib.Path(record) for record in records if pathlib.Path(record).is_file()])
|
||||
|
||||
|
||||
def committed(run: Run, title: str, files: list[pathlib.Path]) -> Failure | None:
|
||||
"""Commit what changed in files under title, each in the git repository that holds it, and only those files: a record the config keeps in its own folder is committed there, where another chunk may commit at the same time."""
|
||||
held: dict[str, list[str]] = {}
|
||||
for file in files:
|
||||
top = run(["git", "-C", str(file.parent), "rev-parse", "--show-toplevel"])
|
||||
if isinstance(top, Failure):
|
||||
return top
|
||||
held.setdefault(top.strip(), []).append(str(file))
|
||||
for top, paths in held.items():
|
||||
changed = run(["git", "-C", top, "status", "--porcelain", "--", *paths])
|
||||
steps = [changed] if isinstance(changed, Failure) or not changed.strip() else [run(["git", "-C", top, "add", "--", *paths]), run(["git", "-C", top, "commit", "--quiet", "-m", title, "--", *paths])]
|
||||
if failed := next((step for step in steps if isinstance(step, Failure)), None):
|
||||
return failed
|
||||
return None
|
||||
|
||||
|
||||
def remeasure(run: Run, base: str) -> Failure | None:
|
||||
"""A Failure where origin's base has moved since the branch last recorded a paired ruling: that ruling read a head that no longer merges. None where the branch recorded none, or the project keeps its history outside the checkout."""
|
||||
history = run([str(BIN / "project-config"), "comprehension-history"])
|
||||
if isinstance(history, Failure):
|
||||
return history
|
||||
top = answers(run, ["rev-parse", "--show-toplevel"])
|
||||
if isinstance(top, Failure) or not pathlib.Path(history.strip()).resolve().is_relative_to(top[0]):
|
||||
return top if isinstance(top, Failure) else None
|
||||
ruled = answers(run, ["log", "-1", "--format=%H", "-G", RULING, f"origin/{base}..HEAD", "--", history.strip()])
|
||||
if isinstance(ruled, Failure) or not ruled[0].strip():
|
||||
return ruled if isinstance(ruled, Failure) else None
|
||||
since = answers(run, ["rev-list", "--count", f"{ruled[0].strip()}..origin/{base}"])
|
||||
if isinstance(since, Failure) or since[0].strip() == "0":
|
||||
return since if isinstance(since, Failure) else None
|
||||
return Failure(f"origin/{base} moved after the branch recorded its paired ruling, and its changes are merged in and pushed; run the paired ruling again at the new head, record it, push, and run chunk-pr merge again")
|
||||
|
||||
|
||||
def merge_method(forge: Forge, run: Run) -> str | Failure:
|
||||
|
||||
+319
-22
@@ -1,5 +1,9 @@
|
||||
import contextlib
|
||||
import fcntl
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
@@ -7,10 +11,11 @@ import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from chunk_pr.main import cleaned, merged, step, USAGE
|
||||
from chunk_pr.main import cleaned, merged, QUEUE, step, turn, USAGE
|
||||
from failure import Failure
|
||||
from test_env import isolated_env
|
||||
from deploy_release.forge import Run
|
||||
from chunk_pr.approval import THREADS
|
||||
|
||||
TOOL = pathlib.Path(__file__).resolve().parents[1] / "chunk-pr"
|
||||
GITHUB = "git@github.com:me/project.git"
|
||||
@@ -29,6 +34,11 @@ TITLE = [str(pathlib.Path(__file__).resolve().parents[1] / "project-config"), "p
|
||||
BRANCH = [str(pathlib.Path(__file__).resolve().parents[1] / "project-config"), "branch"]
|
||||
WAITS = [str(pathlib.Path(__file__).resolve().parents[1] / "project-config"), "wait-for-approval"]
|
||||
GH_DECISION = ["gh", "pr", "view", "12", "--json", "reviewDecision"]
|
||||
GH_THREADS = ["gh", "api", "graphql", "-f", f"query={THREADS}", "-F", "owner={owner}", "-F", "repo={repo}", "-F", "number=12"]
|
||||
BEHIND = ["git", "rev-list", "--count", "HEAD..origin/main"]
|
||||
COMMON = ["git", "rev-parse", "--path-format=absolute", "--git-common-dir"]
|
||||
# The folder the fake checkouts name as their shared git folder, where merge keeps its queue's file.
|
||||
GIT_FOLDER = tempfile.TemporaryDirectory()
|
||||
|
||||
|
||||
class Checkout:
|
||||
@@ -45,6 +55,8 @@ class Checkout:
|
||||
self.decisions = ["APPROVED"]
|
||||
# Set, what GitHub prints instead of a decision's JSON.
|
||||
self.unreadable: str | Failure | None = None
|
||||
# The pull request's review threads, as GitHub's GraphQL API prints them; its author is `worker`.
|
||||
self.threads: list[dict[str, object]] = []
|
||||
self.ran: list[list[str]] = []
|
||||
self.answers: dict[tuple[str, ...], str | Failure] = {
|
||||
("git", "remote", "get-url", "origin"): f"{origin}\n",
|
||||
@@ -54,6 +66,9 @@ class Checkout:
|
||||
tuple(WAITS): "false\n",
|
||||
tuple(TITLE): "{summary}\n",
|
||||
tuple(BRANCH): "item-{id}\n",
|
||||
tuple(BEHIND): "0\n",
|
||||
tuple(COMMON): f"{GIT_FOLDER.name}\n",
|
||||
("git", "rev-parse", "--show-toplevel"): "/checkout\n",
|
||||
}
|
||||
|
||||
def __call__(self, command: list[str]) -> str | Failure:
|
||||
@@ -74,6 +89,8 @@ class Checkout:
|
||||
return self.unreadable
|
||||
if command == GH_DECISION:
|
||||
return json.dumps({"reviewDecision": self.decisions.pop(0) if len(self.decisions) > 1 else self.decisions[0]})
|
||||
if command == GH_THREADS:
|
||||
return json.dumps({"data": {"repository": {"pullRequest": {"author": {"login": "worker"}, "reviewThreads": {"nodes": self.threads}}}}})
|
||||
if command == TEA_BRANCH:
|
||||
return json.dumps({"enable_status_check": False})
|
||||
if command in (GH_SETTINGS, TEA_SETTINGS):
|
||||
@@ -82,7 +99,7 @@ class Checkout:
|
||||
|
||||
def acted(self) -> list[list[str]]:
|
||||
"""What it ran beyond reading the checkout, the pull requests and the repository's settings."""
|
||||
reads = [GH_LIST, GH_DECISION, TEA_LIST, GH_SETTINGS, TEA_SETTINGS, OWED, GH_CHECKS, TEA_BRANCH, TEA_STATUS]
|
||||
reads = [GH_LIST, GH_DECISION, TEA_LIST, GH_SETTINGS, TEA_SETTINGS, OWED, GH_CHECKS, TEA_BRANCH, TEA_STATUS, GH_THREADS]
|
||||
return [command for command in self.ran if tuple(command) not in self.answers and command not in reads]
|
||||
|
||||
|
||||
@@ -281,6 +298,11 @@ class Sync(unittest.TestCase):
|
||||
self.assertEqual(step(["sync"], checkout), Failure("git fetch --quiet: could not read from remote"))
|
||||
|
||||
|
||||
def changes(checkout: Checkout) -> list[list[str]]:
|
||||
"""What a merge ran, leaving out what it read, the project's config included, and the fetch each turn opens with."""
|
||||
return [command for command in checkout.acted() if command != FETCH and not command[0].endswith("/project-config")]
|
||||
|
||||
|
||||
class Merge(unittest.TestCase):
|
||||
def test_the_gate_passed_flag_it_no_longer_takes_is_refused_before_anything_runs(self):
|
||||
checkout = Checkout(GITHUB, open=True)
|
||||
@@ -302,7 +324,7 @@ class Merge(unittest.TestCase):
|
||||
checkout = Checkout(GITHUB, open=True)
|
||||
checkout.answers[tuple(GH_CHECKS)] = Failure("gh pr checks 12: CI / tests\tfail")
|
||||
self.assertEqual(step(["merge"], checkout), Failure("gh pr checks 12: CI / tests\tfail"))
|
||||
self.assertEqual(checkout.acted(), [])
|
||||
self.assertEqual(changes(checkout), [])
|
||||
|
||||
def test_github_waits_a_minute_for_checks_to_report_before_taking_none_as_passed(self):
|
||||
checkout = Checkout(GITHUB, open=True)
|
||||
@@ -335,13 +357,13 @@ class Merge(unittest.TestCase):
|
||||
def test_an_approved_pull_request_merges_after_the_checks_and_the_approval(self):
|
||||
checkout = self.requiring_approval()
|
||||
self.assertEqual(step(["merge"], checkout), "Merged pull request #12 (merge).")
|
||||
self.assertEqual(checkout.ran[-3:], [GH_CHECKS, GH_DECISION, ["gh", "pr", "merge", "12", "--merge", "--match-head-commit", HEAD]])
|
||||
self.assertEqual(checkout.ran[-4:], [GH_CHECKS, GH_DECISION, GH_THREADS, ["gh", "pr", "merge", "12", "--merge", "--match-head-commit", HEAD]])
|
||||
|
||||
def test_it_waits_a_minute_at_a_time_while_the_branch_protection_still_wants_a_review(self):
|
||||
checkout = self.requiring_approval(GITHUB, "REVIEW_REQUIRED", "REVIEW_REQUIRED", "APPROVED")
|
||||
slept: list[float] = []
|
||||
self.assertEqual(merged(checkout, slept.append), "Merged pull request #12 (merge).")
|
||||
self.assertEqual(slept, [60, 60])
|
||||
self.assertEqual(slept, [60])
|
||||
|
||||
def test_an_approval_that_never_comes_leaves_it_unmerged_after_90_minutes(self):
|
||||
checkout = self.requiring_approval(GITHUB, "REVIEW_REQUIRED")
|
||||
@@ -350,10 +372,10 @@ class Merge(unittest.TestCase):
|
||||
self.assertIsInstance(failed, Failure)
|
||||
self.assertIn("90 minutes", failed.reason)
|
||||
self.assertEqual(sum(slept), 90 * 60)
|
||||
self.assertEqual(checkout.acted(), [])
|
||||
self.assertEqual(changes(checkout), [])
|
||||
|
||||
def test_an_approval_that_comes_in_the_last_minute_still_merges(self):
|
||||
checkout = self.requiring_approval(GITHUB, *["REVIEW_REQUIRED"] * 90, "APPROVED")
|
||||
checkout = self.requiring_approval(GITHUB, *["REVIEW_REQUIRED"] * 91, "APPROVED")
|
||||
slept: list[float] = []
|
||||
self.assertEqual(merged(checkout, slept.append), "Merged pull request #12 (merge).")
|
||||
self.assertEqual(sum(slept), 90 * 60)
|
||||
@@ -364,7 +386,7 @@ class Merge(unittest.TestCase):
|
||||
checkout = self.requiring_approval()
|
||||
checkout.unreadable = answer
|
||||
self.assertIsInstance(step(["merge"], checkout), Failure)
|
||||
self.assertEqual(checkout.acted(), [])
|
||||
self.assertEqual(changes(checkout), [])
|
||||
|
||||
def test_requested_changes_leave_it_unmerged_without_waiting(self):
|
||||
checkout = self.requiring_approval(GITHUB, "CHANGES_REQUESTED")
|
||||
@@ -372,7 +394,7 @@ class Merge(unittest.TestCase):
|
||||
failed = merged(checkout, slept.append)
|
||||
self.assertIsInstance(failed, Failure)
|
||||
self.assertIn("requested changes", failed.reason)
|
||||
self.assertEqual((slept, checkout.acted()), ([], []))
|
||||
self.assertEqual((slept, changes(checkout)), ([], []))
|
||||
|
||||
def test_a_branch_protection_that_asks_for_no_review_leaves_it_unmerged_naming_the_setting(self):
|
||||
for decision in ("", None):
|
||||
@@ -381,14 +403,14 @@ class Merge(unittest.TestCase):
|
||||
failed = step(["merge"], checkout)
|
||||
self.assertIsInstance(failed, Failure)
|
||||
self.assertIn("requires no review", failed.reason)
|
||||
self.assertEqual(checkout.acted(), [])
|
||||
self.assertEqual(changes(checkout), [])
|
||||
|
||||
def test_gitea_with_wait_for_approval_leaves_it_unmerged_since_chunk_pr_reads_approvals_on_github_only(self):
|
||||
checkout = self.requiring_approval(GITEA)
|
||||
failed = step(["merge"], checkout)
|
||||
self.assertIsInstance(failed, Failure)
|
||||
self.assertIn("GitHub", failed.reason)
|
||||
self.assertEqual(checkout.acted(), [])
|
||||
self.assertEqual(changes(checkout), [])
|
||||
|
||||
def test_a_config_it_cannot_read_or_that_prints_neither_true_nor_false_leaves_it_unmerged(self):
|
||||
for answer in (Failure("no config names the checkout"), "maybe\n", ""):
|
||||
@@ -396,7 +418,7 @@ class Merge(unittest.TestCase):
|
||||
checkout = Checkout(GITHUB, open=True)
|
||||
checkout.answers[tuple(WAITS)] = answer
|
||||
self.assertIsInstance(step(["merge"], checkout), Failure)
|
||||
self.assertEqual(checkout.acted(), [])
|
||||
self.assertEqual(changes(checkout), [])
|
||||
|
||||
def protected(self, *reads: list[tuple[str, str]]) -> Checkout:
|
||||
"""A Gitea Checkout whose main requires a check matching CI / tests*, its status at HEAD holding each of reads in turn."""
|
||||
@@ -419,28 +441,28 @@ class Merge(unittest.TestCase):
|
||||
def test_a_failed_check_on_gitea_leaves_it_unmerged(self):
|
||||
checkout = self.protected([("CI / tests (pull_request)", "pending")], [("CI / tests (pull_request)", "failure")])
|
||||
self.assertIsInstance(merged(checkout, lambda _: None), Failure)
|
||||
self.assertEqual(checkout.acted(), [])
|
||||
self.assertEqual(changes(checkout), [])
|
||||
|
||||
def test_a_branch_protection_it_cannot_read_leaves_it_unmerged(self):
|
||||
checkout = Checkout(GITEA, open=True)
|
||||
checkout.answers[tuple(TEA_BRANCH)] = Failure("tea api: 500")
|
||||
self.assertEqual(merged(checkout, self.fail), Failure("tea api: 500"))
|
||||
self.assertNotIn(TEA_STATUS, checkout.ran)
|
||||
self.assertEqual(checkout.acted(), [])
|
||||
self.assertEqual(changes(checkout), [])
|
||||
|
||||
def test_an_unknown_default_branch_leaves_it_unmerged_reading_no_checks(self):
|
||||
checkout = Checkout(GITEA, open=True)
|
||||
checkout.answers[("git", "symbolic-ref", "--short", "refs/remotes/origin/HEAD")] = Failure("no such ref")
|
||||
self.assertEqual(merged(checkout, self.fail), Failure("origin records no default branch; set it with `git remote set-head origin --auto`: no such ref"))
|
||||
self.assertNotIn(TEA_STATUS, checkout.ran)
|
||||
self.assertEqual(checkout.acted(), [])
|
||||
self.assertEqual(changes(checkout), [])
|
||||
|
||||
def test_gitea_checks_that_never_pass_leave_it_unmerged(self):
|
||||
checkout = self.protected(*[[("CI / tests (pull_request)", "pending")]] * 1000)
|
||||
failed = merged(checkout, lambda _: None)
|
||||
self.assertIsInstance(failed, Failure)
|
||||
self.assertIn("gave up on pull request 12", failed.reason)
|
||||
self.assertEqual(checkout.acted(), [])
|
||||
self.assertEqual(changes(checkout), [])
|
||||
|
||||
def test_a_scoring_run_the_chunk_owes_and_has_not_recorded_refuses_the_merge(self):
|
||||
for origin in (GITHUB, GITEA):
|
||||
@@ -448,27 +470,27 @@ class Merge(unittest.TestCase):
|
||||
checkout = Checkout(origin, open=True)
|
||||
checkout.answers[tuple(OWED)] = Failure("larv-review scoring-run-owed: the chunk owes 2 scoring runs")
|
||||
self.assertEqual(step(["merge"], checkout), Failure("larv-review scoring-run-owed: the chunk owes 2 scoring runs"))
|
||||
self.assertEqual(checkout.acted(), [])
|
||||
self.assertEqual(changes(checkout), [])
|
||||
|
||||
def test_github_merges_with_a_merge_commit_pinned_to_the_head(self):
|
||||
checkout = Checkout(GITHUB, open=True, allowed=("squashMergeAllowed", "mergeCommitAllowed"))
|
||||
self.assertEqual(step(["merge"], checkout), "Merged pull request #12 (merge).")
|
||||
self.assertEqual(checkout.acted(), [["gh", "pr", "merge", "12", "--merge", "--match-head-commit", HEAD]])
|
||||
self.assertEqual(changes(checkout), [["gh", "pr", "merge", "12", "--merge", "--match-head-commit", HEAD]])
|
||||
|
||||
def test_github_without_merge_commits_rebases(self):
|
||||
checkout = Checkout(GITHUB, open=True, allowed=("squashMergeAllowed", "rebaseMergeAllowed"))
|
||||
step(["merge"], checkout)
|
||||
self.assertEqual(checkout.acted(), [["gh", "pr", "merge", "12", "--rebase", "--match-head-commit", HEAD]])
|
||||
self.assertEqual(changes(checkout), [["gh", "pr", "merge", "12", "--rebase", "--match-head-commit", HEAD]])
|
||||
|
||||
def test_gitea_merges_fast_forward_only_where_only_that_and_squash_are_allowed(self):
|
||||
checkout = Checkout(GITEA, open=True, allowed=("allow_squash_merge", "allow_fast_forward_only_merge"))
|
||||
self.assertEqual(step(["merge"], checkout), "Merged pull request #12 (fast-forward-only).")
|
||||
self.assertEqual(checkout.acted(), [["tea", "api", "--method", "POST", "--field", "Do=fast-forward-only", "--field", f"head_commit_id={HEAD}", "repos/{owner}/{repo}/pulls/12/merge"]])
|
||||
self.assertEqual(changes(checkout), [["tea", "api", "--method", "POST", "--field", "Do=fast-forward-only", "--field", f"head_commit_id={HEAD}", "repos/{owner}/{repo}/pulls/12/merge"]])
|
||||
|
||||
def test_a_repository_allowing_no_known_method_is_refused_unmerged(self):
|
||||
checkout = Checkout(GITEA, open=True, allowed=("allow_manual_merge",))
|
||||
self.assertIsInstance(step(["merge"], checkout), Failure)
|
||||
self.assertEqual(checkout.acted(), [])
|
||||
self.assertEqual(changes(checkout), [])
|
||||
|
||||
def test_a_forge_failure_is_returned(self):
|
||||
checkout = Checkout(GITHUB, open=True)
|
||||
@@ -484,7 +506,282 @@ class Merge(unittest.TestCase):
|
||||
checkout = Checkout(origin, open=True)
|
||||
checkout.answers[tuple(settings)] = Failure("settings: denied")
|
||||
self.assertEqual(step(["merge"], checkout), Failure("settings: denied"))
|
||||
self.assertEqual(checkout.acted(), [])
|
||||
self.assertEqual(changes(checkout), [])
|
||||
|
||||
|
||||
def queue_is_free() -> bool:
|
||||
"""Whether another merge could take its turn now."""
|
||||
fd = os.open(pathlib.Path(GIT_FOLDER.name) / QUEUE, os.O_RDWR | os.O_CREAT)
|
||||
try:
|
||||
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
except BlockingIOError:
|
||||
return False
|
||||
finally:
|
||||
os.close(fd)
|
||||
return True
|
||||
|
||||
|
||||
class MergeQueue(unittest.TestCase):
|
||||
PUSHED = ["git", "push", "--quiet", "origin", "item-7"]
|
||||
TODO_ITEM = str(pathlib.Path(__file__).resolve().parents[1] / "todo-item")
|
||||
CONFIG = str(pathlib.Path(__file__).resolve().parents[1] / "project-config")
|
||||
|
||||
def moved(self, checkout: Checkout) -> Checkout:
|
||||
"""checkout with origin's main two commits ahead of the branch, whose head is `decaf` once main is merged in."""
|
||||
checkout.answers[tuple(BEHIND)] = "2\n"
|
||||
run = checkout.__call__
|
||||
def merging(command: list[str]) -> str | Failure:
|
||||
answer = run(command)
|
||||
if command == MERGE and not isinstance(answer, Failure):
|
||||
checkout.answers[("git", "rev-parse", "HEAD")] = "decaf\n"
|
||||
return answer
|
||||
checkout.__call__ = merging # type: ignore[method-assign]
|
||||
return checkout
|
||||
|
||||
def with_plan(self, checkout: Checkout, held: bool = True) -> tuple[Checkout, str]:
|
||||
"""checkout in a project whose config names a todo.md and a CHANGELOG.md in one folder, which is returned, and titles commits `[{id}] {summary}`. The plan holds item 7 where held. A commit moves the head to `f00d`."""
|
||||
folder = tempfile.mkdtemp()
|
||||
self.addCleanup(shutil.rmtree, folder)
|
||||
for name in ("todo.md", "CHANGELOG.md"):
|
||||
(pathlib.Path(folder) / name).write_text("")
|
||||
checkout.answers.update({
|
||||
(self.TODO_ITEM, "show", "7"): "From todo.md:\n" if held else Failure("todo-item show 7: todo.md holds no item 7"),
|
||||
(self.CONFIG, "plan"): f"{folder}/todo.md\n",
|
||||
(self.CONFIG, "changelog"): f"{folder}/CHANGELOG.md\n",
|
||||
(self.CONFIG, "commit-title"): "[{id}] {summary}\n",
|
||||
("git", "-C", folder, "rev-parse", "--show-toplevel"): f"{folder}\n",
|
||||
("git", "-C", folder, "status", "--porcelain", "--", f"{folder}/todo.md", f"{folder}/CHANGELOG.md"): " M todo.md\n",
|
||||
})
|
||||
run = checkout.__call__
|
||||
def committing(command: list[str]) -> str | Failure:
|
||||
if command[3:4] == ["commit"]:
|
||||
checkout.answers[("git", "rev-parse", "HEAD")] = "f00d\n"
|
||||
return run(command)
|
||||
checkout.__call__ = committing # type: ignore[method-assign]
|
||||
return checkout, folder
|
||||
|
||||
@staticmethod
|
||||
def thread(path: str, last: str, resolved: bool = False) -> dict[str, object]:
|
||||
return {"isResolved": resolved, "path": path, "comments": {"nodes": [{"author": {"login": last}}]}}
|
||||
|
||||
def test_malformed_finish_flags_dont_run_anything(self):
|
||||
for flags in (["--finish"], ["--finish", "abc"], ["--changelog", "Bullet."], ["12"], ["--finish", "--no-changelog"], ["--finish", "7", "--changelog"], ["--finish", "7", "--no-changelog", "--changelog", "Bullet."]):
|
||||
with self.subTest(flags):
|
||||
checkout = Checkout(GITHUB, open=True)
|
||||
self.assertEqual(step(["merge", *flags], checkout), Failure(USAGE))
|
||||
self.assertEqual(checkout.ran, [])
|
||||
|
||||
def test_a_branch_behind_the_default_branch_merges_it_in_and_pushes_before_the_checks(self):
|
||||
checkout = self.moved(Checkout(GITHUB, open=True))
|
||||
self.assertEqual(merged(checkout.__call__), "Merged pull request #12 (merge).")
|
||||
self.assertEqual(changes(checkout), [MERGE, self.PUSHED, ["gh", "pr", "merge", "12", "--merge", "--match-head-commit", "decaf"]])
|
||||
self.assertLess(checkout.ran.index(self.PUSHED), checkout.ran.index(GH_CHECKS))
|
||||
|
||||
def test_a_conflict_with_the_default_branch_leaves_it_unmerged_naming_the_files_and_frees_the_queue(self):
|
||||
checkout = self.moved(Checkout(GITHUB, open=True))
|
||||
checkout.answers[tuple(MERGE)] = Failure("git merge --quiet: CONFLICT")
|
||||
checkout.answers[("git", "diff", "--name-only", "--diff-filter=U")] = "bin/tool.py\n"
|
||||
failed = merged(checkout.__call__)
|
||||
self.assertIsInstance(failed, Failure)
|
||||
self.assertIn("conflicts in bin/tool.py; the merge stays in progress: resolve them, commit, push, and run chunk-pr merge again", failed.reason)
|
||||
self.assertEqual((changes(checkout), MERGE in checkout.ran), ([], True))
|
||||
self.assertTrue(queue_is_free())
|
||||
|
||||
def test_a_finished_item_is_committed_under_the_configs_title_and_pushed_before_the_merge(self):
|
||||
checkout, folder = self.with_plan(Checkout(GITHUB, open=True))
|
||||
files = [f"{folder}/todo.md", f"{folder}/CHANGELOG.md"]
|
||||
self.assertEqual(merged(checkout.__call__, finishes=[["7", "--changelog", "Exports keep their order."]]), "Merged pull request #12 (merge).")
|
||||
self.assertEqual(changes(checkout)[:1], [[self.TODO_ITEM, "finish", "7", "--changelog", "Exports keep their order."]])
|
||||
self.assertEqual(changes(checkout)[-4:], [
|
||||
["git", "-C", folder, "add", "--", *files],
|
||||
["git", "-C", folder, "commit", "--quiet", "-m", "[7] Finish item 7 in the plan", "--", *files],
|
||||
self.PUSHED,
|
||||
["gh", "pr", "merge", "12", "--merge", "--match-head-commit", "f00d"],
|
||||
])
|
||||
|
||||
def test_the_flags_reach_todo_item_as_given(self):
|
||||
checkout, _ = self.with_plan(Checkout(GITHUB, open=True))
|
||||
checkout.answers.update({(self.TODO_ITEM, "show", "8"): "From todo.md:\n", (self.TODO_ITEM, "show", "9"): "From todo.md:\n"})
|
||||
self.assertEqual(step(["merge", "--finish", "7", "--no-changelog", "--finish", "8", "--finish", "9", "--changelog", "Exports keep their order."], checkout.__call__), "Merged pull request #12 (merge).")
|
||||
self.assertEqual([command[1:] for command in checkout.ran if command[:2] == [self.TODO_ITEM, "finish"]], [["finish", "7", "--no-changelog"], ["finish", "8"], ["finish", "9", "--changelog", "Exports keep their order."]])
|
||||
|
||||
def test_an_item_the_plan_no_longer_holds_is_named_on_the_last_line_and_what_an_earlier_run_left_uncommitted_is_committed(self):
|
||||
checkout, folder = self.with_plan(Checkout(GITHUB, open=True), held=False)
|
||||
self.assertEqual(merged(checkout.__call__, finishes=[["7"]]), "Merged pull request #12 (merge). The plan held no item 7 when merge began, so merge left the plan as it was there.")
|
||||
self.assertNotIn([self.TODO_ITEM, "finish", "7"], checkout.ran)
|
||||
self.assertEqual([command[3] for command in changes(checkout)[:-1]], ["add", "commit", "origin"])
|
||||
self.assertEqual(changes(checkout)[-1], ["gh", "pr", "merge", "12", "--merge", "--match-head-commit", "f00d"])
|
||||
|
||||
def test_each_item_the_plan_no_longer_holds_is_named(self):
|
||||
checkout, _ = self.with_plan(Checkout(GITHUB, open=True), held=False)
|
||||
checkout.answers[(self.TODO_ITEM, "show", "8")] = Failure("todo-item show 8: todo.md holds no item 8")
|
||||
self.assertIn("The plan held no item 7, 8 when merge began", str(merged(checkout.__call__, finishes=[["7"], ["8"]])))
|
||||
|
||||
def test_a_plan_that_turns_unreadable_inside_the_turn_leaves_it_unmerged(self):
|
||||
checkout, _ = self.with_plan(Checkout(GITHUB, open=True))
|
||||
run, shows = checkout.__call__, []
|
||||
def run_whose_second_show_fails(command: list[str]) -> str | Failure:
|
||||
shows.extend([command] if command[1:2] == ["show"] else [])
|
||||
return Failure("todo-item show 7: unreadable") if command[1:2] == ["show"] and len(shows) == 2 else run(command)
|
||||
self.assertEqual(merged(run_whose_second_show_fails, finishes=[["7"]]), Failure("todo-item show 7: unreadable"))
|
||||
self.assertNotIn([self.TODO_ITEM, "finish", "7"], checkout.ran)
|
||||
|
||||
def test_a_finish_that_changes_no_file_commits_and_pushes_nothing(self):
|
||||
for clean in ("status", "records"):
|
||||
with self.subTest(clean):
|
||||
checkout, folder = self.with_plan(Checkout(GITHUB, open=True))
|
||||
if clean == "status":
|
||||
checkout.answers[("git", "-C", folder, "status", "--porcelain", "--", f"{folder}/todo.md", f"{folder}/CHANGELOG.md")] = "\n"
|
||||
else:
|
||||
checkout.answers.update({(self.CONFIG, "plan"): "PAY-1\n", (self.CONFIG, "changelog"): f"{folder}/none.md\n"})
|
||||
self.assertEqual(merged(checkout.__call__, finishes=[["7", "--no-changelog"]]), "Merged pull request #12 (merge).")
|
||||
self.assertEqual(changes(checkout), [[self.TODO_ITEM, "finish", "7", "--no-changelog"], ["gh", "pr", "merge", "12", "--merge", "--match-head-commit", HEAD]])
|
||||
|
||||
def test_a_branch_outside_the_branch_template_titles_the_finish_with_the_summary_alone(self):
|
||||
checkout, folder = self.with_plan(Checkout(GITHUB, open=True))
|
||||
checkout.answers[tuple(BRANCH)] = "feature/PAY-{id}\n"
|
||||
merged(checkout.__call__, finishes=[["7"]])
|
||||
self.assertIn("Finish item 7 in the plan", [command[6] for command in checkout.ran if command[3:4] == ["commit"]])
|
||||
|
||||
def test_a_plan_it_cannot_read_or_an_item_it_cannot_finish_leaves_it_unmerged(self):
|
||||
for failing in ("show", "finish"):
|
||||
with self.subTest(failing):
|
||||
checkout, _ = self.with_plan(Checkout(GITHUB, open=True))
|
||||
checkout.answers[(self.TODO_ITEM, failing, "7")] = Failure(f"todo-item {failing} 7: no config names the checkout")
|
||||
self.assertEqual(merged(checkout.__call__, finishes=[["7"]]), Failure(f"todo-item {failing} 7: no config names the checkout"))
|
||||
self.assertNotIn(self.PUSHED, checkout.ran)
|
||||
|
||||
def test_a_step_of_the_turn_that_fails_leaves_it_unmerged_with_that_failure(self):
|
||||
_, folder = self.with_plan(Checkout(GITHUB, open=True))
|
||||
for failing in (FETCH, BEHIND, COMMON, self.PUSHED, ["git", "-C", "<plan>", "rev-parse", "--show-toplevel"], ["git", "-C", "<plan>", "add"], ["git", "-C", "<plan>", "commit"], [self.CONFIG, "comprehension-history"]):
|
||||
with self.subTest(failing):
|
||||
checkout, folder = self.with_plan(Checkout(GITHUB, open=True))
|
||||
run = checkout.__call__
|
||||
def failing_run(command: list[str]) -> str | Failure:
|
||||
asked = ["<plan>" if part == folder else part for part in command]
|
||||
return Failure("that step failed") if tuple(asked[:len(failing)]) == tuple(failing) else run(command)
|
||||
self.assertEqual(merged(failing_run, finishes=[["7"]]), Failure("that step failed"))
|
||||
self.assertNotIn("merge", [command[2] for command in checkout.ran if command[0] == "gh"])
|
||||
|
||||
def test_a_finish_that_fails_after_the_default_branch_was_merged_in_still_pushes_the_branch(self):
|
||||
checkout, _ = self.with_plan(self.moved(Checkout(GITHUB, open=True)))
|
||||
checkout.answers[(self.TODO_ITEM, "finish", "7")] = Failure("todo-item finish 7: a decision cites item 7")
|
||||
self.assertEqual(merged(checkout.__call__, finishes=[["7"]]), Failure("todo-item finish 7: a decision cites item 7"))
|
||||
self.assertEqual(changes(checkout), [MERGE, self.PUSHED])
|
||||
|
||||
def test_the_scoring_run_is_asked_for_once_the_finish_is_committed_and_one_owed_leaves_it_unmerged(self):
|
||||
checkout, _ = self.with_plan(Checkout(GITHUB, open=True))
|
||||
commit = lambda: next(index for index, command in enumerate(checkout.ran) if command[3:4] == ["commit"])
|
||||
self.assertEqual(merged(checkout.__call__, finishes=[["7"]]), "Merged pull request #12 (merge).")
|
||||
self.assertLess(commit(), checkout.ran.index(OWED))
|
||||
checkout, _ = self.with_plan(Checkout(GITHUB, open=True))
|
||||
checkout.answers[tuple(OWED)] = Failure("the chunk owes 1 scoring run")
|
||||
self.assertEqual(merged(checkout.__call__, finishes=[["7"]]), Failure("the chunk owes 1 scoring run"))
|
||||
self.assertEqual(changes(checkout)[-1], self.PUSHED)
|
||||
|
||||
def test_a_merge_holds_the_queue_through_the_checks_and_frees_it_while_it_waits_for_an_approval(self):
|
||||
checkout = Checkout(GITHUB, open=True)
|
||||
checkout.answers[tuple(WAITS)] = "true\n"
|
||||
checkout.decisions = ["REVIEW_REQUIRED", "REVIEW_REQUIRED", "APPROVED"]
|
||||
free: dict[str, bool] = {}
|
||||
def run(command: list[str]) -> str | Failure:
|
||||
if command == GH_CHECKS:
|
||||
free.setdefault("during the checks", queue_is_free())
|
||||
return checkout(command)
|
||||
self.assertEqual(merged(run, lambda seconds: free.setdefault("waiting for the approval", queue_is_free())), "Merged pull request #12 (merge).")
|
||||
self.assertEqual(free, {"during the checks": False, "waiting for the approval": True})
|
||||
self.assertEqual(checkout.ran.count(FETCH), 2)
|
||||
|
||||
def test_a_reviewers_comment_ends_the_wait_naming_its_file_until_the_author_answers_or_it_is_resolved(self):
|
||||
checkout = Checkout(GITHUB, open=True)
|
||||
checkout.answers[tuple(WAITS)] = "true\n"
|
||||
checkout.decisions = ["REVIEW_REQUIRED"]
|
||||
checkout.threads = [self.thread("bin/asked.py", "reviewer"), self.thread("bin/answered.py", "worker"), self.thread("bin/resolved.py", "reviewer", resolved=True)]
|
||||
slept: list[float] = []
|
||||
failed = merged(checkout, slept.append)
|
||||
self.assertIsInstance(failed, Failure)
|
||||
self.assertIn("waits for an answer, in bin/asked.py;", failed.reason)
|
||||
self.assertEqual((slept, changes(checkout)), ([], []))
|
||||
checkout.threads = checkout.threads[1:]
|
||||
checkout.decisions = ["REVIEW_REQUIRED", "REVIEW_REQUIRED", "APPROVED"]
|
||||
self.assertEqual(merged(checkout, slept.append), "Merged pull request #12 (merge).")
|
||||
|
||||
def test_an_approved_pull_request_with_a_comment_that_waits_for_an_answer_stays_unmerged(self):
|
||||
checkout = Checkout(GITHUB, open=True)
|
||||
checkout.answers[tuple(WAITS)] = "true\n"
|
||||
checkout.threads = [self.thread("bin/asked.py", "reviewer")]
|
||||
failed = merged(checkout)
|
||||
self.assertIsInstance(failed, Failure)
|
||||
self.assertIn("waits for an answer, in bin/asked.py;", failed.reason)
|
||||
self.assertEqual(changes(checkout), [])
|
||||
|
||||
def test_review_threads_it_cannot_read_leave_it_unmerged(self):
|
||||
for answer, reason in ((Failure("gh api graphql failed"), "gh api graphql failed"), ("not json", "gh api graphql printed no review threads: not json"), ("{}", "gh api graphql printed no review threads: {}")):
|
||||
with self.subTest(answer):
|
||||
checkout = Checkout(GITHUB, open=True)
|
||||
checkout.answers.update({tuple(WAITS): "true\n", tuple(GH_THREADS): answer})
|
||||
checkout.decisions = ["REVIEW_REQUIRED"]
|
||||
self.assertEqual(merged(checkout, lambda seconds: None), Failure(reason))
|
||||
self.assertEqual(changes(checkout), [])
|
||||
|
||||
def test_a_default_branch_that_moved_after_the_branchs_last_paired_ruling_stops_for_a_new_one(self):
|
||||
history = "/checkout/docs/comprehension-history.md"
|
||||
ruled = ["git", "log", "-1", "--format=%H", "-G", "^Ruling: ", "origin/main..HEAD", "--", history]
|
||||
since = ["git", "rev-list", "--count", "bead..origin/main"]
|
||||
for name, answers, stops in (
|
||||
("moved since the ruling", {tuple(ruled): "bead\n", tuple(since): "2\n"}, True),
|
||||
("ruled at this head", {tuple(ruled): "bead\n", tuple(since): "0\n"}, False),
|
||||
("no ruling", {tuple(ruled): "\n"}, False),
|
||||
):
|
||||
with self.subTest(name):
|
||||
checkout = Checkout(GITHUB, open=True)
|
||||
checkout.answers.update({(self.CONFIG, "comprehension-history"): f"{history}\n", **answers})
|
||||
done = merged(checkout.__call__)
|
||||
self.assertEqual(isinstance(done, Failure) and "run the paired ruling again" in done.reason, stops, done)
|
||||
self.assertEqual(changes(checkout), [] if stops else [["gh", "pr", "merge", "12", "--merge", "--match-head-commit", HEAD]])
|
||||
|
||||
def test_a_history_outside_the_checkout_or_one_git_cannot_read_never_stops_or_fails_the_merge_wrongly(self):
|
||||
ruled = ("git", "log", "-1", "--format=%H", "-G", "^Ruling: ", "origin/main..HEAD", "--", "/checkout/history.md")
|
||||
checkout = Checkout(GITHUB, open=True)
|
||||
checkout.answers[(self.CONFIG, "comprehension-history")] = "/elsewhere/history.md\n"
|
||||
self.assertEqual(merged(checkout.__call__), "Merged pull request #12 (merge).")
|
||||
self.assertNotIn("log", [command[1] for command in checkout.ran])
|
||||
for failing in (ruled, ("git", "rev-list", "--count", "bead..origin/main"), ("git", "rev-parse", "--show-toplevel")):
|
||||
with self.subTest(failing):
|
||||
checkout = Checkout(GITHUB, open=True)
|
||||
checkout.answers.update({(self.CONFIG, "comprehension-history"): "/checkout/history.md\n", ruled: "bead\n"})
|
||||
checkout.answers[failing] = Failure("git failed")
|
||||
self.assertEqual(merged(checkout.__call__), Failure("git failed"))
|
||||
|
||||
def test_a_turn_keeps_every_other_merge_out_until_it_ends_even_by_an_error(self):
|
||||
with self.assertRaises(ValueError):
|
||||
with turn(pathlib.Path(GIT_FOLDER.name) / QUEUE, "12", lambda seconds: None):
|
||||
self.assertFalse(queue_is_free())
|
||||
raise ValueError
|
||||
self.assertTrue(queue_is_free())
|
||||
|
||||
def test_a_queue_another_pull_request_holds_for_half_an_hour_leaves_it_unmerged_naming_the_holder(self):
|
||||
checkout = Checkout(GITHUB, open=True)
|
||||
slept: list[float] = []
|
||||
with turn(pathlib.Path(GIT_FOLDER.name) / QUEUE, "1234", lambda seconds: None):
|
||||
pass
|
||||
with turn(pathlib.Path(GIT_FOLDER.name) / QUEUE, "31", lambda seconds: None):
|
||||
failed = merged(checkout, slept.append)
|
||||
self.assertEqual(failed, Failure("the merge queue stayed held for 30 minutes, last by pull request #31, so this one took no turn; run chunk-pr merge again"))
|
||||
self.assertEqual((sum(slept), set(slept), changes(checkout)), (30 * 60, {10}, []))
|
||||
|
||||
def test_a_queue_freed_while_it_waits_gives_it_the_turn(self):
|
||||
checkout = Checkout(GITHUB, open=True)
|
||||
holder = contextlib.ExitStack()
|
||||
holder.enter_context(turn(pathlib.Path(GIT_FOLDER.name) / QUEUE, "31", lambda seconds: None))
|
||||
self.assertEqual(merged(checkout, lambda seconds: holder.close()), "Merged pull request #12 (merge).")
|
||||
|
||||
def test_a_queue_it_cannot_open_leaves_it_unmerged(self):
|
||||
checkout = Checkout(GITHUB, open=True)
|
||||
checkout.answers[tuple(COMMON)] = "/nonexistent/folder\n"
|
||||
self.assertEqual(merged(checkout), Failure("cannot take a turn in the merge queue, /nonexistent/folder/chunk-pr-merge-queue: No such file or directory"))
|
||||
self.assertEqual(checkout.acted(), [])
|
||||
|
||||
|
||||
|
||||
class Clean(unittest.TestCase):
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"""The pure choices the preflight's steps act on."""
|
||||
import pathlib
|
||||
|
||||
from release_plan.release_standing import chunk_item, Cut, dated_cut, LastCut, ReadyToCut, ReviewDue, Unknown, Unplanned
|
||||
from release_plan.release_standing import carried, chunk_item, Cut, dated_cut, LastCut, ReadyToCut, ReviewDue, Unknown, Unplanned
|
||||
from chunk_preflight.gathered import CarriedOver, Forge, NoItem, Plan
|
||||
from failure import Failure
|
||||
from chunk_preflight.gathered import Forge, NoItem, Plan
|
||||
from release_plan.todo_table import NoItemsTable
|
||||
from plan_store import stores as plan_stores
|
||||
from release_plan.release import version
|
||||
@@ -25,8 +25,8 @@ def plan_name(default: str, outside: str | None) -> str:
|
||||
return outside if outside else f"{default}'s todo.md"
|
||||
|
||||
|
||||
def planned(todo: plan_stores.Plan | Failure, cut: LastCut, default: str, branch: str, outside: str | None = None) -> Plan | NoItem:
|
||||
"""todo, which is the project's plan as its store read it and which plan_name names, with the item the next chunk takes first, release_standing.chunk_item's pick; else why there is none. branch is the project's `branch` template."""
|
||||
def planned(todo: plan_stores.Plan | Failure, cut: LastCut, default: str, branch: str, outside: str | None = None, item_id: int | None = None) -> Plan | NoItem:
|
||||
"""todo, which is the project's plan as its store read it and which plan_name names, with the item the next chunk takes first: the item of item_id where one is given, else release_standing.chunk_item's pick. Else why there is none. branch is the project's `branch` template."""
|
||||
where = plan_name(default, outside)
|
||||
if isinstance(todo, NoItemsTable):
|
||||
return NoItem(f"{where} holds no items table.")
|
||||
@@ -52,7 +52,15 @@ def planned(todo: plan_stores.Plan | Failure, cut: LastCut, default: str, branch
|
||||
first = pick.item
|
||||
if first is None:
|
||||
return NoItem(f"every item of release {version(pick.release)} in {where} waits." if pick.release is not None else f"{where}'s items table holds no item.")
|
||||
return Plan(found, first, f"{first.tagline}\n\n{first.detail}".strip(), branch)
|
||||
held = carried(found, cut)
|
||||
moved = [(was, now) for was, now in zip(found, held) if was.release != now.release]
|
||||
# Every carried item takes one release, the next.
|
||||
over = CarriedOver(moved[0][1].release, tuple(was.id for was, _ in moved)) if moved else None
|
||||
if item_id is not None:
|
||||
first = next((item for item in held if item.id == item_id), None)
|
||||
if first is None:
|
||||
return NoItem(f"{where} holds no item {item_id}, the one --item names; it may have shipped.")
|
||||
return Plan(held, first, f"{first.tagline}\n\n{first.detail}".strip(), branch, over, item_id is not None)
|
||||
|
||||
|
||||
def worktree_on(porcelain: str, branch: str) -> pathlib.Path | None:
|
||||
|
||||
@@ -45,7 +45,8 @@ def item_lines(plan: str, item: ItemFacts) -> list[str]:
|
||||
first = item.plan.first
|
||||
worktree = item.worktree.reason if isinstance(item.worktree, Failure) else f"{item.worktree.path}, {item.worktree.how}"
|
||||
return [
|
||||
f"- The earliest release in {plan}: {version(first.release)}. Its first item that does not wait: item {first.id}, {levels(first)}.",
|
||||
f"- The {'next release, after the last cut, that ' + plan + ' names' if item.plan.carried else 'earliest release in ' + plan}: {version(first.release)}. {'The item this chunk starts from, named with --item' if item.plan.named else 'Its first item that does not wait'}: item {first.id}, {levels(first)}.",
|
||||
*carried_lines(item.plan),
|
||||
f"- Worktree: {worktree}",
|
||||
f"- Open pull requests from {item.plan.branch}: {pulls_text(item.pulls, item.plan.branch)}",
|
||||
*bundled(item.plan),
|
||||
@@ -57,6 +58,15 @@ def item_lines(plan: str, item: ItemFacts) -> list[str]:
|
||||
]
|
||||
|
||||
|
||||
def carried_lines(plan: Plan) -> list[str]:
|
||||
"""What the worker does about the items of a release someone cut while it held them."""
|
||||
over = plan.carried
|
||||
if over is None:
|
||||
return []
|
||||
items, count, them = (f"Items {listed([str(id_) for id_ in over.ids], 'and')} are", "they count", "them") if len(over.ids) > 1 else (f"Item {over.ids[0]} is", "it counts", "it")
|
||||
return [f"- {items} filed under a release already cut, so {count} as release {version(over.into)}'s, the next. Move {them} there as this chunk's first change, with `~/.claude/bin/todo-item move`, and say so in the chunk's opening line. Where todo-item cannot move this plan's items, as in a Jira plan, leave {them} and ask the human, in the chunk's summary, to move {them}."]
|
||||
|
||||
|
||||
def joining_details(plan: Plan) -> list[str]:
|
||||
"""The detail of each of the first JOINING_DETAILS items that may join the chunk, in the table's order, and what the worker lacks: an item with no detail, or the items left out."""
|
||||
joining = bundle_candidates(plan.items, plan.first)
|
||||
|
||||
@@ -6,6 +6,7 @@ import typing
|
||||
from failure import Failure
|
||||
from release_plan.todo_table import Item
|
||||
from release_plan.release_standing import LastCut
|
||||
from release_plan.release import Release
|
||||
from project_config import templates
|
||||
|
||||
# The CLI that lists a forge's pull requests: gh for a github.com origin, tea for any other.
|
||||
@@ -20,6 +21,13 @@ class Ran:
|
||||
stderr: str
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class CarriedOver:
|
||||
"""The items, by ID in the plan's order, that the plan files under a release already cut, and that count as `into`'s, the next release: release_standing.carried."""
|
||||
into: Release
|
||||
ids: tuple[int, ...]
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Plan:
|
||||
"""The default branch's plan items, each with its detail, and `first`: the item the next chunk takes first."""
|
||||
@@ -28,6 +36,10 @@ class Plan:
|
||||
# first's tagline and detail.
|
||||
text: str
|
||||
branch_template: str
|
||||
# The items of a release already cut, which `items` and `first` hold as the next release's. None where every item's release is after the last cut.
|
||||
carried: CarriedOver | None = None
|
||||
# Whether --item named first, in place of the next release's first item that does not wait.
|
||||
named: bool = False
|
||||
|
||||
@property
|
||||
def branch(self) -> str:
|
||||
|
||||
+22
-16
@@ -1,6 +1,6 @@
|
||||
"""Find the mechanical facts a chunk starts from, so its worker starts from them; with --worktree, also make its worktree.
|
||||
|
||||
usage: chunk-preflight [--worktree]
|
||||
usage: chunk-preflight [--worktree] [--item <ID>]
|
||||
|
||||
Run it inside a project checkout. It fetches origin, when the checkout has that remote, and takes
|
||||
origin's default branch, or else the local main or master. Without --worktree, it still fetches,
|
||||
@@ -16,18 +16,21 @@ and prints that the release reviews and the cuts are the human's to call. It pri
|
||||
newest version CHANGELOG.md heads `## X.Y.Z - YYYY-MM-DD`; an undated heading doesn't count.
|
||||
Then how many entries the default branch's CHANGELOG.md holds under ## Unreleased, or else how
|
||||
many commits followed the cut: the tag, or the commit that added that heading;
|
||||
- the next release and its first item that does not wait, the item loop-claude routes on, with
|
||||
its L and E + I. An item waits while it is marked question, or while an item still in todo.md
|
||||
- the next release and its first item that does not wait, the item loop-claude routes on, with its L
|
||||
and E + I; with --item <ID>, the plan item of that ID instead, which loop-claude names in a window
|
||||
named for an item. An item waits while it is marked question, or while an item still in todo.md
|
||||
blocks it. Where the last cut is a version x.y.z, the next release is the earliest after x.y.z
|
||||
that todo.md has named at that cut or since, less a release its ## Renamed section marks
|
||||
renamed. Where nothing is cut, it is the earliest release todo.md has ever named, less those
|
||||
renamed, so a release whose items are all done still reads as next.
|
||||
that todo.md has named at that cut or since, less a release its ## Renamed section marks renamed.
|
||||
Where nothing is cut, it is the earliest release todo.md has ever named, less those renamed, so a
|
||||
release whose items are all done still reads as next.
|
||||
Where the next release holds no item, it says so, naming it where todo.md named it since the cut:
|
||||
its release review due where changes are unreleased (the ## Unreleased entries, or else the
|
||||
commits since the cut) and no commit titled `Release review of <release>` followed the tag,
|
||||
finished and ready to cut once one did, and else to be planned first. On a branch with no tag,
|
||||
such a commit counts only where its <release> is after the version under the dated heading.
|
||||
Where todo.md's earliest release is x.y.z or earlier, it says todo.md files items under a release
|
||||
Where todo.md files items under x.y.z or earlier, someone cut a release that still held them:
|
||||
they count as the next release, the earliest after x.y.z that todo.md names or has named
|
||||
since the cut, and a line says to move them there. Where there is no such release, it says todo.md files items under a release
|
||||
already cut;
|
||||
- with --worktree, the item's worktree: a sibling of the checkout named <checkout>-<branch>,
|
||||
each / of the branch a dash, on the branch the config's `branch` template names, which is
|
||||
@@ -63,7 +66,7 @@ running after {timeout} seconds, or after the seconds CHUNK_PREFLIGHT_TIMEOUT se
|
||||
stopped fetch reads origin as last fetched. With no item, it makes no worktree and runs none of
|
||||
those four tools, --worktree or not.
|
||||
|
||||
Exit 1, saying why, on any argument other than --worktree, -h or --help, on a
|
||||
Exit 1, saying why, on any argument other than --worktree, --item with an ID, -h or --help, on a
|
||||
CHUNK_PREFLIGHT_TIMEOUT that is no number of seconds above 0, when git cannot start or finds no
|
||||
checkout or no default branch, or when no config names the checkout or its config cannot be read.
|
||||
"""
|
||||
@@ -90,16 +93,19 @@ TIMEOUT = 60
|
||||
TIMEOUT_SETTING = "CHUNK_PREFLIGHT_TIMEOUT"
|
||||
# The flag that makes the item's worktree and runs TOOLS in it. Three readers seated as the README's audience picked it 2-1 over --start.
|
||||
WORKTREE = "--worktree"
|
||||
# The flag that names the chunk's item. Three readers seated as the README's audience picked it 3-0 over --for, --start and a bare ID.
|
||||
ITEM = "--item"
|
||||
|
||||
|
||||
def main(argv: list[str], env: typing.Mapping[str, str]) -> int:
|
||||
if argv in (["-h"], ["--help"]):
|
||||
print(__doc__.strip().format(timeout=TIMEOUT, JOINING_DETAILS=JOINING_DETAILS))
|
||||
return 0
|
||||
if argv not in ([], [WORKTREE]):
|
||||
print(f"unknown arguments {' '.join(argv)}; usage: chunk-preflight [{WORKTREE}]", file=sys.stderr)
|
||||
rest = [arg for arg in argv if arg != WORKTREE]
|
||||
if len(argv) - len(rest) > 1 or not (rest == [] or (len(rest) == 2 and rest[0] == ITEM and re.fullmatch(r"[0-9]+", rest[1], re.ASCII))):
|
||||
print(f"unknown arguments {' '.join(argv)}; usage: chunk-preflight [{WORKTREE}] [{ITEM} <ID>]", file=sys.stderr)
|
||||
return 1
|
||||
printed = run(env.get(TIMEOUT_SETTING), argv == [WORKTREE])
|
||||
printed = run(env.get(TIMEOUT_SETTING), WORKTREE in argv, int(rest[1]) if rest else None)
|
||||
if isinstance(printed, Failure):
|
||||
print(printed.reason, file=sys.stderr)
|
||||
return 1
|
||||
@@ -107,13 +113,13 @@ def main(argv: list[str], env: typing.Mapping[str, str]) -> int:
|
||||
return 0
|
||||
|
||||
|
||||
def run(setting: str | None, make: bool) -> list[str] | Failure:
|
||||
"""The preflight's lines, given the setting TIMEOUT_SETTING holds and whether to make the item's worktree; a Failure where the setting is no number of seconds above 0, or git finds no checkout or no default branch."""
|
||||
def run(setting: str | None, make: bool, item_id: int | None = None) -> list[str] | Failure:
|
||||
"""The preflight's lines, given the setting TIMEOUT_SETTING holds, whether to make the item's worktree, and the ID --item names; a Failure where the setting is no number of seconds above 0, or git finds no checkout or no default branch."""
|
||||
timeout = seconds(setting)
|
||||
if isinstance(timeout, Failure):
|
||||
return timeout
|
||||
root = top()
|
||||
return root if isinstance(root, Failure) else preflight(pathlib.Path(root), timeout, make)
|
||||
return root if isinstance(root, Failure) else preflight(pathlib.Path(root), timeout, make, item_id)
|
||||
|
||||
|
||||
def seconds(setting: str | None) -> float | Failure:
|
||||
@@ -125,7 +131,7 @@ def seconds(setting: str | None) -> float | Failure:
|
||||
return Failure(f"{TIMEOUT_SETTING}={setting!r} is no number of seconds above 0")
|
||||
|
||||
|
||||
def preflight(root: pathlib.Path, timeout: float, make: bool) -> list[str] | Failure:
|
||||
def preflight(root: pathlib.Path, timeout: float, make: bool, item_id: int | None) -> list[str] | Failure:
|
||||
"""Gathers the facts step by step, each step taking what the ones before it found, and renders them; a Failure where the checkout has no default branch."""
|
||||
default = default_branch(stale_ok=True, timeout=timeout)
|
||||
if isinstance(default, Failure):
|
||||
@@ -136,7 +142,7 @@ def preflight(root: pathlib.Path, timeout: float, make: bool) -> list[str] | Fai
|
||||
return config
|
||||
outside = None if config.tracked("plan") else config.plan_label
|
||||
held = project_plan(config, ref, str(root))
|
||||
plan = planned(held.todo, held.cut, ref, config.branch, outside)
|
||||
plan = planned(held.todo, held.cut, ref, config.branch, outside, item_id)
|
||||
item = plan if isinstance(plan, NoItem) else item_facts(root, ref, plan, timeout, make)
|
||||
# A `checkout:` path lands in the worktree the chunk works in.
|
||||
made = located(str(item.worktree.path), pathlib.Path.home()) if isinstance(item, ItemFacts) and isinstance(item.worktree, Worktree) else config
|
||||
|
||||
@@ -10,10 +10,10 @@ import unittest
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from project_config.templates import BRANCH
|
||||
from chunk_preflight.gathered import CarriedOver, Gathered, ItemFacts, NamedPath, NoItem, Ran, Worktree
|
||||
from chunk_preflight import choices
|
||||
from failure import Failure
|
||||
from chunk_preflight.choices import forge_of, worktree_add
|
||||
from chunk_preflight.gathered import Gathered, ItemFacts, NamedPath, NoItem, Ran, Worktree
|
||||
from test_env import isolated_env
|
||||
from release_plan.release_standing import LastCut, UNSEEN_RELEASES
|
||||
from chunk_preflight.main import line_count, ran, seconds, TIMEOUT
|
||||
@@ -54,6 +54,10 @@ Change `src/app.py`'s `run` and the files under `src`, not `gone.py`.
|
||||
SHIPPED = TODO.replace("| 3 | 0.2.0 | | | **Do the next thing.** | 2 | 2 | 3 | 5 | 3 | 1 by 9 | 56.2 |\n", "").replace("| 7 | 0.2.0 | 3 |", "| 7 | 0.2.0 | |").replace("### 3. Do the next thing.", "### 7. Do the thing after.")
|
||||
# The plan once release 0.2.0 has shipped all its items: only release 0.3.0's item 9 is left.
|
||||
LATER = TODO[:TODO.index("| 5 |")] + "| 9 | 0.3.0 | | | **Do a later thing.** | 1 | 1 | 1 | 1 | 1 | 1 by 9 | 90.0 |\n"
|
||||
# Item 9's row, the only one under release 0.3.0.
|
||||
NINTH = "| 9 | 0.3.0 | | | **Do a later thing.** | 1 | 1 | 1 | 1 | 1 | 1 by 9 | 90.0 |\n"
|
||||
# A plan whose release 0.2.0 holds item 3 alone, before release 0.3.0's item 9.
|
||||
SHIPPED_BUT_3 = TODO[:TODO.index("| 5 |")] + "| 3 | 0.2.0 | | | **Do the next thing.** | 2 | 2 | 3 | 5 | 3 | 1 by 9 | 56.2 |\n" + NINTH
|
||||
# An items table that holds no row.
|
||||
EMPTY = TODO[:TODO.index("| 5 |")]
|
||||
CHANGELOG = "# Changelog\n\n## Unreleased\n\n- One.\n - A nested line.\n- Two.\n\n## 0.1.0\n\n- Old.\n"
|
||||
@@ -315,6 +319,29 @@ class ChunkPreflightTool(unittest.TestCase):
|
||||
self.assertFalse((repo.temp / "proj-item-3").exists())
|
||||
self.assertNotIn("item-3", repo.git(repo.root, "branch", "--list"))
|
||||
|
||||
def test_item_names_the_item_the_chunk_starts_from_in_place_of_the_plans_next(self):
|
||||
repo = Repo(self)
|
||||
for args in (["--item", "7"], ["--worktree", "--item", "7"], ["--item", "7", "--worktree"]):
|
||||
with self.subTest(args):
|
||||
done = repo.preflight(*args)
|
||||
self.assertEqual((done.returncode, done.stderr), (0, ""))
|
||||
self.assertIn("0.2.0. The item this chunk starts from, named with --item: item 7, L 1, E + I 2.", done.stdout)
|
||||
self.assertNotIn("Its first item that does not wait", done.stdout)
|
||||
self.assertTrue((repo.temp / "proj-item-7").is_dir())
|
||||
self.assertFalse((repo.temp / "proj-item-3").exists())
|
||||
|
||||
def test_item_names_no_item_where_the_plan_no_longer_holds_it(self):
|
||||
done = Repo(self).preflight("--worktree", "--item", "4")
|
||||
self.assertEqual((done.returncode, done.stderr), (0, ""))
|
||||
self.assertIn("- No plan item: origin/main's todo.md holds no item 4, the one --item names; it may have shipped. No worktree was made.", done.stdout)
|
||||
|
||||
def test_exits_1_on_an_item_that_is_no_id(self):
|
||||
for args in (["--item"], ["--item", "x"], ["--item", "7", "8"]):
|
||||
with self.subTest(args):
|
||||
done = Repo(self).preflight(*args)
|
||||
self.assertEqual((done.returncode, done.stdout), (1, ""))
|
||||
self.assertIn(f"unknown arguments {' '.join(args)}; usage: chunk-preflight [--worktree] [--item <ID>]", done.stderr)
|
||||
|
||||
def test_exits_1_on_an_argument_other_than_worktree(self):
|
||||
done = Repo(self).preflight("--start")
|
||||
self.assertEqual(done.returncode, 1)
|
||||
@@ -387,6 +414,10 @@ class Render(unittest.TestCase):
|
||||
self.assertIn("item 7, L 1, E + I 2, S 1: **Do the thing after.**", said)
|
||||
self.assertNotIn("item 8,", said)
|
||||
|
||||
def test_says_the_item_was_named_with_item(self):
|
||||
said = rendered(item_facts(plan=planned(TODO, CUT, "origin/main", BRANCH, None, 7)))
|
||||
self.assertIn("origin/main's todo.md: 0.2.0. The item this chunk starts from, named with --item: item 7, L 1, E + I 2.", said)
|
||||
|
||||
def test_states_each_fact_once_with_the_paths_between_the_worktree_and_the_open_pull_requests(self):
|
||||
lines = render(gathered(item_facts()))
|
||||
self.assertEqual([line.partition(":")[0] for line in lines[:6]], ["- Last version cut", "- The earliest release in origin/main's todo.md", "- Worktree", "- The project's config puts its files and plan at", "- The project's config sets", "- Open pull requests from item-3"])
|
||||
@@ -527,6 +558,14 @@ class Plans(unittest.TestCase):
|
||||
self.assertIn("L 'x'", planned(TODO.replace("| 2 | 2 | 3 | 5 |", "| x | 2 | 3 | 5 |"), CUT, "origin/main", BRANCH).why)
|
||||
self.assertIn("## Details holds a fenced code block", planned(TODO + "```\n", CUT, "origin/main", BRANCH).why)
|
||||
|
||||
def test_takes_the_item_item_names_even_one_that_waits_or_says_it_left_the_plan(self):
|
||||
# Item 7 waits for item 3, which another chunk runs.
|
||||
named = planned(TODO, CUT, "origin/main", BRANCH, None, 7)
|
||||
self.assertEqual((named.first.id, named.first.tagline, named.named), (7, "**Do the thing after.**", True))
|
||||
self.assertTrue(named.text.startswith("**Do the thing after.**"), named.text)
|
||||
self.assertFalse(planned(TODO, CUT, "origin/main", BRANCH).named)
|
||||
self.assertEqual(planned(TODO, CUT, "origin/main", BRANCH, None, 4), NoItem("origin/main's todo.md holds no item 4, the one --item names; it may have shipped."))
|
||||
|
||||
def test_tells_a_plan_with_no_items_table_from_one_whose_table_holds_no_item(self):
|
||||
without = planned("", CUT, "origin/main", BRANCH).why
|
||||
self.assertIn("origin/main", without)
|
||||
@@ -576,8 +615,27 @@ class Plans(unittest.TestCase):
|
||||
def test_takes_the_earliest_release_where_no_earlier_one_was_named_since_the_last_cut(self):
|
||||
self.assertEqual(planned(LATER, LastCut("v0.1.0", "", 4, [LATER]), "origin/main", BRANCH).first.id, 9)
|
||||
|
||||
def test_counts_the_items_of_a_release_already_cut_as_the_next_releases_and_says_to_move_them(self):
|
||||
plan = planned(TODO, LastCut("v0.2.0", "", 4, []), "origin/main", BRANCH)
|
||||
self.assertEqual((plan.first.id, plan.first.release), (3, (0, 3, 0)))
|
||||
self.assertEqual({item.release for item in plan.items}, {(0, 3, 0)})
|
||||
self.assertEqual(plan.carried, CarriedOver((0, 3, 0), (5, 3, 7, 8)))
|
||||
said = rendered(dataclasses.replace(item_facts(), plan=plan), LastCut("v0.2.0", "", 4, []))
|
||||
self.assertIn("- Items 5, 3, 7 and 8 are filed under a release already cut, so they count as release 0.3.0's, the next.", said)
|
||||
self.assertIn("`~/.claude/bin/todo-item move`", said)
|
||||
self.assertIn("- The next release, after the last cut, that origin/main's todo.md names: 0.3.0. Its first item that does not wait: item 3,", said)
|
||||
self.assertNotIn("already cut", rendered(item_facts()))
|
||||
|
||||
def test_says_to_move_one_or_two_items_of_a_release_already_cut_in_the_singular_or_the_plural(self):
|
||||
cut = LastCut("v0.2.0", "", 4, [])
|
||||
for todo, ids, said in ((SHIPPED_BUT_3, (3,), "- Item 3 is filed under a release already cut, so it counts as release 0.3.0's, the next. Move it there"), (SHIPPED_BUT_3 + NINTH.replace("| 9 | 0.3.0 |", "| 4 | 0.1.0 |"), (3, 4), "- Items 3 and 4 are filed under a release already cut, so they count as release 0.3.0's, the next. Move them there")):
|
||||
with self.subTest(ids=ids):
|
||||
plan = planned(todo, cut, "origin/main", BRANCH)
|
||||
self.assertEqual(plan.carried, CarriedOver((0, 3, 0), ids))
|
||||
self.assertIn(said, rendered(dataclasses.replace(item_facts(), plan=plan), cut))
|
||||
|
||||
def test_says_the_plan_files_items_under_a_release_already_cut(self):
|
||||
why = planned(TODO, LastCut("v0.2.0", "", 4, []), "origin/main", BRANCH).why
|
||||
why = planned(TODO.replace(NINTH, ""), LastCut("v0.2.0", "", 4, []), "origin/main", BRANCH).why
|
||||
self.assertIn("release 0.2.0", why)
|
||||
self.assertIn("v0.2.0", why)
|
||||
self.assertIn("not after", why)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -983,7 +983,7 @@ class LarvReviewTool(unittest.TestCase):
|
||||
checkout = pathlib.Path(temp, "acme")
|
||||
checkout.mkdir()
|
||||
config = configured(self, checkout) / "config.toml"
|
||||
config.write_text(config.read_text().replace('"checkout:todo.md"', '"jira:https://acme.atlassian.net/browse/ABC-12"') + 'env-file = "~/acme.env"\n')
|
||||
config.write_text(config.read_text().replace('"checkout:todo.md"', '"jira:https://acme.atlassian.net/browse/ABC-12"') + 'env-file = "~/acme.env"\njira-score-formula = "V"\njira-score-bar = 1\n')
|
||||
(checkout / "todo.md").write_text("the owners' own notes\n")
|
||||
self.enterContext(contextlib.chdir(checkout))
|
||||
said: list[str] = []
|
||||
@@ -1250,7 +1250,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)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -53,6 +53,11 @@ 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}"
|
||||
|
||||
@@ -24,6 +24,7 @@ from loop_claude.cycle.retry import retried
|
||||
from model_routing.route import Route
|
||||
from loop_claude.cycle import spend
|
||||
from loop_claude.stop import Stop
|
||||
from loop_claude.tmux import Window
|
||||
from model_routing import worker_rungs
|
||||
|
||||
|
||||
@@ -54,6 +55,8 @@ class Cycle:
|
||||
todo: Plan | Failure
|
||||
# Empty when the previous cycle's verdict was not Unfinished.
|
||||
unfinished_evidence: str
|
||||
# The tmux window the loop runs in, which an interrupt marks.
|
||||
window: Window
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
@@ -198,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
|
||||
|
||||
@@ -1,46 +0,0 @@
|
||||
"""The slot a loop holds in its project, so that loops of one project, each on its own chunk, run side by side, each in a session named after its slot."""
|
||||
import dataclasses
|
||||
import os
|
||||
import pathlib
|
||||
|
||||
from failure import Failure
|
||||
from machine_load.slots import first_free_slot
|
||||
from loop_claude.loop.reload import LoopRun
|
||||
from loop_state.paths import Paths
|
||||
from transcript_archive.project_key import project_key
|
||||
from claude_code.session import Session, session_named, session_open
|
||||
|
||||
# Under the home folder, a folder per project key holds a file per slot, which a running loop keeps locked with flock.
|
||||
SLOTS = ".local/state/loop-claude"
|
||||
# A bound no project reaches. Once todo.md item 375 lands, the project's config sets how many loops run at once.
|
||||
MOST = 64
|
||||
|
||||
|
||||
def held_slot(home: pathlib.Path, key: str, claude_code_transcripts: pathlib.Path) -> int | Failure:
|
||||
"""The slot this loop takes, or why it could take none: the lowest free slot whose session is open, so that a rerun resumes a chunk left open, or else the lowest free slot. The loop holds it until it exits; a reload's exec keeps the lock."""
|
||||
folder = home / SLOTS / key
|
||||
order = sorted(range(MOST), key=lambda slot: not session_open(session_named(session_name(key, slot), claude_code_transcripts)))
|
||||
try:
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
taken = first_free_slot(folder, order)
|
||||
except OSError as failure:
|
||||
return Failure(f"cannot take a slot in {folder}: {failure.strerror}")
|
||||
if taken is None:
|
||||
return Failure(f"{MOST} loops of this project are running already; `fuser {folder}/slot-*` names them")
|
||||
slot, fd = taken
|
||||
os.set_inheritable(fd, True)
|
||||
return slot
|
||||
|
||||
|
||||
def session_name(key: str, slot: int) -> str:
|
||||
""""A " is the human's cue in the session picker that the session is the loop's. Slot 0 keeps the name every loop had before slots, so a chunk left open before slots resumes in it."""
|
||||
return f"A {key} loop-claude" if slot == 0 else f"A {key} loop-claude {slot + 1}"
|
||||
|
||||
|
||||
def slotted(loop_run: LoopRun, paths: Paths) -> tuple[LoopRun, Session] | Failure:
|
||||
"""loop_run holding its slot, and the worker's session, named after the slot. A reloaded script keeps the slot it is handed."""
|
||||
key = project_key(loop_run.root, paths.home)
|
||||
slot = held_slot(paths.home, key, paths.claude_code_transcripts) if loop_run.slot is None else loop_run.slot
|
||||
if isinstance(slot, Failure):
|
||||
return slot
|
||||
return dataclasses.replace(loop_run, slot=slot), session_named(session_name(key, slot), paths.claude_code_transcripts)
|
||||
@@ -8,6 +8,8 @@ from loop_effects.effects import Effects, say
|
||||
from failure import Failure
|
||||
from loop_claude.routing import first_route, kept, routed_item
|
||||
from plan_store.stores import held_at, Plan, store as plan_store
|
||||
from loop_claude.loop.chunk_windows import held_beside, item_of
|
||||
from chunk_preflight.main import ITEM
|
||||
from release_plan.todo_table import Item
|
||||
from model_routing.ladder import Ladder, Rung
|
||||
from transcript_archive.read import latest_worker
|
||||
@@ -61,15 +63,16 @@ def archived_route(archive_folder: pathlib.Path, loop: Loop) -> Route | None:
|
||||
def chunk_start(loop: Loop) -> tuple[str, typing.Callable[[], Item | None]]:
|
||||
"""The facts for a fresh worker's prompt, empty where the session is open, and the reader of the item that routes the chunk. The reader reads the default branch as last fetched: for a fresh chunk, by the preflight that runs first; for an open session, which runs none, by whatever fetched last."""
|
||||
facts = "" if session_open(loop.session) else chunk_facts(loop)
|
||||
return facts, lambda: plan_item(fetched_plan(loop), loop.effects)
|
||||
return facts, lambda: plan_item(fetched_plan(loop), item_of(loop.window.name), loop.effects)
|
||||
|
||||
|
||||
def chunk_facts(loop: Loop) -> str:
|
||||
"""What `chunk-preflight --worktree` printed at the checkout root, for a fresh worker's prompt, or why it could not run."""
|
||||
done = loop.effects.python([str(loop.launcher.with_name("chunk-preflight")), "--worktree"], loop.root)
|
||||
if done.returncode:
|
||||
return prompts.preflight_failed(done.stderr.strip() or f"it exited {done.returncode}")
|
||||
return prompts.preflight_facts(done.stdout.strip())
|
||||
"""What `chunk-preflight --worktree` printed at the checkout root, for a fresh worker's prompt, or why it could not run. The chunk of a window named for an item starts from that item, and either ends with the items the project's other chunks hold."""
|
||||
item = item_of(loop.window.name)
|
||||
done = loop.effects.python([str(loop.launcher.with_name("chunk-preflight")), "--worktree", *([] if item is None else [ITEM, str(item)])], loop.root)
|
||||
facts = prompts.preflight_failed(done.stderr.strip() or f"it exited {done.returncode}") if done.returncode else prompts.preflight_facts(done.stdout.strip())
|
||||
held = held_beside(loop.window.name, loop.root, loop.paths, loop.effects)
|
||||
return facts + (prompts.held_by_others(held) if held else "")
|
||||
|
||||
|
||||
def fetched_plan(loop: Loop) -> DefaultPlan | Failure:
|
||||
@@ -83,13 +86,13 @@ def fetched_plan(loop: Loop) -> DefaultPlan | Failure:
|
||||
return ref if isinstance(ref, Failure) else project_plan(config, ref, loop.root, loop.effects.git)
|
||||
|
||||
|
||||
def plan_item(plan: DefaultPlan | Failure, effects: Effects) -> Item | None:
|
||||
"""The item that routes a chunk, release_standing.chunk_item's pick from the default branch; None without one, so the chunk runs on the project's rung."""
|
||||
def plan_item(plan: DefaultPlan | Failure, window_item: int | None, effects: Effects) -> Item | None:
|
||||
"""The item that routes a chunk: the one its window is named for, or else release_standing.chunk_item's pick from the default branch; None without one, so the chunk runs on the project's rung."""
|
||||
# It prints the reason itself, through effects, like the other loop-claude functions that print. todo.md item 51 moves them all to one injected effect, so changing this one alone would be undone.
|
||||
if isinstance(plan, Failure):
|
||||
item: Item | Failure | None = plan
|
||||
else:
|
||||
item = routed_item(plan.todo, plan.cut)
|
||||
item = routed_item(plan.todo, plan.cut, window_item)
|
||||
if isinstance(item, Failure):
|
||||
say(f"routing on the project's rung: {item.reason}", effects)
|
||||
return None
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
"""The chunks of one project that run at once, each in its own tmux window: which may start now, and how each starts (docs/decisions.md → `loop-claude: each chunk runs in its own tmux window`)."""
|
||||
import contextlib
|
||||
import fcntl
|
||||
import pathlib
|
||||
import re
|
||||
import typing
|
||||
|
||||
from touch_predictions.beside import Beside, chunks_beside
|
||||
from loop_claude.cycle import chunk_items
|
||||
from git_cli.git_repo import default_ref
|
||||
from loop_effects.effects import Effects, say
|
||||
from failure import Failure
|
||||
from project_config.main import located
|
||||
from loop_claude.loop.reload import LoopRun
|
||||
from chunk_preflight.gathered import NoItem, Plan
|
||||
from touch_predictions.prediction import overlaps, predicted, Touches
|
||||
from loop_state.paths import Paths
|
||||
from chunk_preflight.choices import planned
|
||||
from transcript_archive.project_key import project_key
|
||||
from release_plan.release_standing import project_plan
|
||||
from claude_code.transcript import read_transcript
|
||||
from claude_code.session import Session, session_named, transcript_file
|
||||
from loop_claude import tmux
|
||||
|
||||
# Under the home folder, a folder per project key holds LOCK.
|
||||
STATE = ".local/state/loop-claude"
|
||||
# The file a loop keeps locked with flock while it lists the project's windows and starts new ones, so two loops whose chunks finish together don't start a chunk twice.
|
||||
LOCK = "starting"
|
||||
# The flag that tells the loop in a window its chunk, as `--chunk item-372`. Nobody types it, so no panel picked it.
|
||||
CHUNK_FLAG = "--chunk"
|
||||
# The chunk of a plan that names no item for the next chunk: a release to plan, a release review, or a task outside the plan.
|
||||
NO_ITEM = "no-item"
|
||||
# Seconds a fetch of origin may take before a chunk starts; past them, the plan reads as last fetched.
|
||||
FETCH_TIMEOUT = 60
|
||||
# The prefix of the variables loop-claude reads. A window gets the tmux server's environment, not the starting terminal's, so they are handed to each window by name.
|
||||
HANDED = "LOOP_CLAUDE_"
|
||||
|
||||
|
||||
def window_name(item_id: int) -> str:
|
||||
return f"item-{item_id}"
|
||||
|
||||
|
||||
def item_of(chunk: str) -> int | None:
|
||||
"""The ID of the plan item a chunk starts from; None for NO_ITEM."""
|
||||
named = re.fullmatch(r"item-([0-9]+)", chunk)
|
||||
return int(named[1]) if named else None
|
||||
|
||||
|
||||
def chunk_session(key: str, chunk: str, claude_code_transcripts: pathlib.Path) -> Session:
|
||||
"""The worker's session for a chunk. A rerun finds a chunk left open by this name. "A " is the human's cue in the session picker that the session is the loop's."""
|
||||
return session_named(f"A {key} loop-claude {chunk}", claude_code_transcripts)
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def starting(home: pathlib.Path, key: str) -> typing.Iterator[None]:
|
||||
"""Holds the project's LOCK. Raises OSError where the file cannot be opened or locked."""
|
||||
folder = home / STATE / key
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
with open(folder / LOCK, "a") as lock:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX)
|
||||
yield
|
||||
|
||||
|
||||
def held_items(chunks: typing.Iterable[str], key: str, claude_code_transcripts: pathlib.Path) -> set[int]:
|
||||
"""The plan items these chunks hold: the one each started from, and those its worker names on its latest `Chunk items:` line so far. A chunk whose transcript cannot be read holds the item it started from."""
|
||||
held: set[int] = set()
|
||||
for chunk in chunks:
|
||||
held.update(filter(None, [item_of(chunk)]))
|
||||
transcript = transcript_file(chunk_session(key, chunk, claude_code_transcripts))
|
||||
entries = read_transcript(transcript) if transcript else []
|
||||
held.update([] if isinstance(entries, Failure) else chunk_items.named(entries))
|
||||
return held
|
||||
|
||||
|
||||
def may_start(plan: Plan | NoItem, running: list[str], held: set[int], limit: int) -> list[str]:
|
||||
"""The chunks to start now beside the running ones, whose chunks hold the items in held: the plan's next item and the items touch_predictions picks to run beside it, in the plan's order, up to limit chunks running at once. Each leaves out an item in held, and one whose `Touches:` prediction overlaps a held item's, or where either has none. A plan without an item starts NO_ITEM, and only alone."""
|
||||
if isinstance(plan, NoItem):
|
||||
return [] if running else [NO_ITEM]
|
||||
beside = chunks_beside(plan.items, plan.first)
|
||||
picked = [plan.first.id, *(beside.picked if isinstance(beside, Beside) else [])]
|
||||
details = {item.id: item.detail for item in plan.items}
|
||||
# chunks_beside checks overlaps against the plan's next item only, and a running chunk's item may no longer be that one once an item merged. A held item that left the plan overlaps nothing.
|
||||
theirs = [predicted(details[item_id]) for item_id in sorted(held) if item_id in details]
|
||||
free = [item_id for item_id in picked if item_id not in held and clear_of(predicted(details[item_id]), theirs)]
|
||||
return [window_name(item_id) for item_id in free][: max(limit - len(running), 0)]
|
||||
|
||||
|
||||
def clear_of(ours: Touches | Failure | None, theirs: list[Touches | Failure | None]) -> bool:
|
||||
"""Whether a prediction overlaps none of theirs; not where one of them is missing or unreadable, unless theirs is empty."""
|
||||
return not theirs or (isinstance(ours, dict) and all(isinstance(touches, dict) and not overlaps(ours, touches) for touches in theirs))
|
||||
|
||||
|
||||
def next_plan(root: str, home: pathlib.Path, effects: Effects) -> Plan | NoItem | Failure:
|
||||
"""The plan on the default branch, fetched now where origin answers, with its next item, as chunk-preflight reads it."""
|
||||
config = located(root, home)
|
||||
if isinstance(config, Failure):
|
||||
return config
|
||||
# A chunk that just merged left the plan on origin. A fetch that fails leaves the plan as last fetched, which chunk-preflight then reads too.
|
||||
effects.git("fetch", "--quiet", "origin", cwd=root, timeout=FETCH_TIMEOUT)
|
||||
ref = default_ref(root, FETCH_TIMEOUT, run=effects.git)
|
||||
if isinstance(ref, Failure):
|
||||
return ref
|
||||
held = project_plan(config, ref, root, effects.git)
|
||||
return planned(held.todo, held.cut, ref, config.branch, None if config.tracked("plan") else config.plan_label)
|
||||
|
||||
|
||||
def start_chunks(loop_run: LoopRun, leaving: bool, paths: Paths, env: typing.Mapping[str, str], launcher: pathlib.Path, effects: Effects) -> list[str] | Failure:
|
||||
"""Starts a loop-claude in a new window for each chunk of loop_run's project that may start now, and returns the chunks started. leaving says that loop_run's own chunk finished, so its window no longer counts as running; without it, the human started loop-claude. A plan that cannot be read starts NO_ITEM, as a plan without an item does. A Failure says why a chunk could not start; those before it run."""
|
||||
config = located(loop_run.root, paths.home)
|
||||
if isinstance(config, Failure):
|
||||
return config
|
||||
key = project_key(loop_run.root, paths.home)
|
||||
session = tmux.session_name(key)
|
||||
handed = {name: value for name, value in env.items() if name.startswith(HANDED)}
|
||||
try:
|
||||
with starting(paths.home, key):
|
||||
windows = tmux.listed(session, effects.tmux)
|
||||
if windows and (owned := tmux.owner(session, effects.tmux)) != loop_run.root:
|
||||
return Failure(f"the tmux session {session} runs the chunks of {owned or 'another checkout'}, whose key maps to the same session name; rename one of the two checkouts' folders")
|
||||
running = [window.name for window in windows if not window.dead and not (leaving and window.name == loop_run.chunk)]
|
||||
# Below 0 where the config lowered parallel-chunks while more chunks ran.
|
||||
room = max(config.parallel_chunks - len(running), 0)
|
||||
# A loop that the human stopped, or that failed, keeps its window, dead, with its last lines and its items. Only the human's loop-claude <task> starts it again, before any other chunk.
|
||||
stopped = [window.name for window in windows if window.dead]
|
||||
chunks = [] if leaving else stopped[:room]
|
||||
if len(chunks) < room:
|
||||
plan = next_plan(loop_run.root, paths.home, effects)
|
||||
if isinstance(plan, Failure):
|
||||
# Such as in a checkout without a default branch, where chunk-preflight fails too: the worker is told why and finds the facts itself.
|
||||
say(f"starting a chunk without a plan item, since the plan cannot be read: {plan.reason}", effects)
|
||||
plan = NoItem(plan.reason)
|
||||
held = held_items(running + stopped, key, paths.claude_code_transcripts)
|
||||
chunks += [chunk for chunk in may_start(plan, running + chunks, held, config.parallel_chunks) if chunk not in stopped]
|
||||
for chunk in chunks:
|
||||
stale = [window for window in windows if window.name == chunk and window.dead]
|
||||
for window in stale:
|
||||
tmux.close(window, effects.tmux)
|
||||
windows = [window for window in windows if window not in stale]
|
||||
command = [str(launcher), CHUNK_FLAG, chunk, loop_run.task]
|
||||
if failed := tmux.start_window(tmux.Window(session, chunk, ""), loop_run.root, handed, command, not windows, effects.tmux):
|
||||
return failed
|
||||
windows.append(tmux.Listed(chunk, "", False))
|
||||
return chunks
|
||||
except OSError as failure:
|
||||
return Failure(f"cannot lock {paths.home / STATE / key / LOCK}: {failure.strerror}")
|
||||
|
||||
|
||||
def held_beside(chunk: str, root: str, paths: Paths, effects: Effects) -> list[int]:
|
||||
"""The plan items that the project's other chunks hold now, running or stopped, which a chunk starting as `chunk` leaves to them. It waits for a loop that is starting windows, so chunks started together see each other. Where the lock cannot be taken, it reads the windows without it."""
|
||||
key = project_key(root, paths.home)
|
||||
with contextlib.suppress(OSError), starting(paths.home, key):
|
||||
pass
|
||||
others = [window.name for window in tmux.listed(tmux.session_name(key), effects.tmux) if window.name != chunk]
|
||||
return sorted(held_items(others, key, paths.claude_code_transcripts))
|
||||
@@ -6,11 +6,13 @@ from transcript_archive.location import archive_root, project_archive
|
||||
from loop_claude.loop.chunk_start import archived_route, chunk_start, fetched_todo, routed
|
||||
from loop_claude.loop.routing_check import check_routing
|
||||
from loop_claude.project.checkout import checkout_root
|
||||
from loop_claude.loop.chunk_windows import CHUNK_FLAG, chunk_session, start_chunks
|
||||
from loop_claude.loop.close import closed_cycle
|
||||
from loop_claude.cycle.run import Cycle, run_cycle
|
||||
from loop_claude.loop.reload import decode_handed, exec_if_edited, fingerprint, LoopRun, RELOAD_FLAG
|
||||
from loop_effects.effects import Effects, say
|
||||
from failure import Failure
|
||||
from loop_claude.verdicts import Finished
|
||||
from loop_claude.project.model_choice import get_or_ask_models
|
||||
from git_cli.git_repo import Git
|
||||
from loop_claude.loop.usage import HELP
|
||||
@@ -20,9 +22,9 @@ from transcript_archive.project_key import project_key
|
||||
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 loop_claude.loop.chunk_slot import slotted
|
||||
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,12 +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)
|
||||
held = slotted(loop_run, paths)
|
||||
if isinstance(held, Failure):
|
||||
return Stop(1, held.reason)
|
||||
loop_run, session = held
|
||||
loop = Loop(root=loop_run.root, session=session, paths=paths, env=env, launcher=launcher, effects=effects)
|
||||
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
|
||||
@@ -68,6 +76,31 @@ def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launc
|
||||
# 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:
|
||||
@@ -96,7 +129,7 @@ def next_cycle(loop_run: LoopRun, loop: Loop) -> Cycle | Stop:
|
||||
if ladder_file != SHIPPED:
|
||||
say(own_ladder(ladder_file, models.worker, project is None), loop.effects)
|
||||
todo = fetched_todo(loop)
|
||||
return Cycle(config=setup_version(loop.paths.claude_dir, loop.effects.git), effects=loop.effects, facts=facts, judge_model=models.judge, ladder=ladder, premises=premises, project=project, project_archive=archive_folder, records=records, root=loop.root, route=route, session=loop.session, task=loop_run.task, todo=todo, unfinished_evidence=loop_run.unfinished_evidence)
|
||||
return Cycle(config=setup_version(loop.paths.claude_dir, loop.effects.git), effects=loop.effects, facts=facts, judge_model=models.judge, ladder=ladder, premises=premises, project=project, project_archive=archive_folder, records=records, root=loop.root, route=route, session=loop.session, task=loop_run.task, todo=todo, unfinished_evidence=loop_run.unfinished_evidence, window=loop.window)
|
||||
|
||||
|
||||
def own_ladder(file: pathlib.Path, model: str, unrouted: bool) -> str:
|
||||
@@ -107,11 +140,12 @@ def own_ladder(file: pathlib.Path, model: str, unrouted: bool) -> str:
|
||||
|
||||
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,8 +25,8 @@ class LoopRun:
|
||||
route: Route | None = None
|
||||
# How many unfinished verdicts the chunk has had running; a finished chunk and a rerun each set it to 0. It stays apart from route and unfinished_evidence, though all three change together at each verdict: merging or renaming a field stops a running loop at its next reload.
|
||||
unfinished_run: int = 0
|
||||
# The project's slot this loop holds (chunk_slot.py); None until it takes one. A loop started before slots reloads with None, and so takes a slot then.
|
||||
slot: int | None = None
|
||||
# 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):
|
||||
@@ -40,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:
|
||||
@@ -77,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), "slot": lambda value: None if value is None else exactly(int)(value)}
|
||||
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:
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -22,35 +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.
|
||||
|
||||
Loops of one project run side by side, each on one chunk at a time. Each holds a slot of the
|
||||
project, the file slot-<n> under ~/.local/state/loop-claude/<key>/, locked while the loop runs.
|
||||
<key> is the checkout's path relative to ~/code, or to / outside it. A loop takes the lowest free
|
||||
slot whose session is open, so a rerun resumes a chunk left open, or else the lowest free slot.
|
||||
slot-0's session is named "A <key> loop-claude", and slot-<n>'s "A <key> loop-claude <n+1>".
|
||||
The session is deleted when its chunk finishes. At every
|
||||
interrupt, and as every cycle ends, Ctrl-C and a failure included, the session's transcript is
|
||||
copied into a folder per chunk under $LOOP_CLAUDE_TRANSCRIPTS/<key> (default root
|
||||
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.
|
||||
@@ -116,7 +139,11 @@ loop-claude --help succeeds: the loop reloads into the edited script.
|
||||
Exit 1, saying why, when:
|
||||
- no task is given
|
||||
- git cannot start or finds no checkout
|
||||
- its slot in the project cannot be taken
|
||||
- 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
|
||||
@@ -146,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 an open session that no running loop holds, the lowest one first."""
|
||||
Rerunning loop-claude <task> starts the chunks that may start, a stopped one first, and each
|
||||
resumes its claude session where it is open."""
|
||||
|
||||
@@ -45,14 +45,17 @@ 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
|
||||
|
||||
|
||||
|
||||
@@ -29,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}
|
||||
@@ -166,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
|
||||
|
||||
@@ -195,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()
|
||||
@@ -203,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",
|
||||
@@ -224,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"]))
|
||||
@@ -241,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,
|
||||
)
|
||||
@@ -394,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):
|
||||
@@ -414,7 +449,7 @@ class Cycles(unittest.TestCase):
|
||||
self.assertEqual(run.roles(), ["worker", "judge", "worker", "judge", "worker", "judge"])
|
||||
workers = [call for call in run.calls if call["role"] == "worker"]
|
||||
session = argument(workers[0], "--session-id")
|
||||
self.assertEqual(argument(workers[0], "--name"), "A proj loop-claude")
|
||||
self.assertEqual(argument(workers[0], "--name"), "A proj loop-claude no-item")
|
||||
self.assertEqual(argument(workers[1], "--resume"), session)
|
||||
self.assertIsNone(argument(workers[1], "--session-id"))
|
||||
self.assertIsNone(argument(workers[1], "--name"))
|
||||
@@ -433,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"])
|
||||
@@ -608,19 +645,15 @@ class Cycles(unittest.TestCase):
|
||||
self.assertIsNotNone(argument(run.calls[0], "--resume"))
|
||||
self.assertEqual((argument(run.calls[0], "--model"), argument(run.calls[0], "--effort")), ("claude-fable-5-2", "medium"))
|
||||
|
||||
def test_a_second_loop_in_the_project_runs_its_own_session_and_leaves_the_first_loops_open_chunk_alone(self):
|
||||
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()
|
||||
slot = checkout.home / ".local" / "state" / "loop-claude" / "proj" / "slot-0"
|
||||
slot.parent.mkdir(parents=True, exist_ok=True)
|
||||
# The test holds the first loop's slot, as the first loop does while it runs.
|
||||
with open(slot, "a") as running:
|
||||
fcntl.flock(running, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
second = checkout.run([worker(say="second chunk"), judge(evidence="second chunk")])
|
||||
self.assertEqual(argument(second.calls[0], "--name"), "A proj loop-claude 2")
|
||||
self.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)
|
||||
@@ -771,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)
|
||||
@@ -971,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, "slot": 0} 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)
|
||||
|
||||
@@ -21,13 +21,14 @@ from routing_figures import archive, state
|
||||
from routing_figures.calls import Call
|
||||
from loop_claude.project import checkout, model_choice, records
|
||||
from loop_claude.cycle import chunk_items
|
||||
from loop_claude.loop import chunk_slot, chunk_start, close
|
||||
from loop_claude.loop import chunk_start, chunk_windows, close
|
||||
from project_config.test_project_config import configured
|
||||
from release_plan.release_standing import DefaultPlan, LastCut, UNSEEN_RELEASES
|
||||
from loop_effects.effects import Effects, PYTHON_TIMEOUT
|
||||
from claude_code import entries, reply, session
|
||||
from failure import Failure
|
||||
from loop_claude.verdicts import Finished, Interrupt, Judged, QuotedAnswer, TakenIn, Unfinished
|
||||
from chunk_preflight import gathered
|
||||
from git_cli.git_repo import git
|
||||
from loop_claude.cycle import interrupt, judge, prompts, retry, run, spend, states, worker
|
||||
from claude_code.reply import Limited
|
||||
@@ -42,7 +43,9 @@ from model_routing.route import Route, route_from, WorkerLine
|
||||
from loop_claude import routing
|
||||
from model_routing.ladder import Rung
|
||||
from loop_claude.stop import Stop
|
||||
from loop_claude import tmux
|
||||
from claude_code.tokens import Tokens, tokens_of
|
||||
from touch_predictions.test_touch_predictions import plan as touch_plan
|
||||
from text_files.utc_stamp import utc
|
||||
from loop_claude.cycle.judge import verdict_from
|
||||
|
||||
@@ -76,18 +79,28 @@ def human(content):
|
||||
return {"type": "user", "message": {"content": content}}
|
||||
|
||||
|
||||
# The window the loops under test run in.
|
||||
WINDOW = tmux.Window("loop-proj", "item-7", "%4")
|
||||
|
||||
|
||||
def a_loop(effects, **fields):
|
||||
"""A loop in /r on effects, with fields in place of its defaults."""
|
||||
home = pathlib.Path("/h")
|
||||
defaults = {"root": "/r", "session": session.session_named("A proj loop-claude", home / ".claude" / "projects"), "paths": paths.paths_from(home), "env": {}, "launcher": pathlib.Path("/b/loop-claude")}
|
||||
defaults = {"root": "/r", "session": session.session_named("A proj loop-claude", home / ".claude" / "projects"), "paths": paths.paths_from(home), "env": {}, "launcher": pathlib.Path("/b/loop-claude"), "window": WINDOW}
|
||||
return this_loop.Loop(**{**defaults, **fields}, effects=effects)
|
||||
|
||||
|
||||
class FakeEffects:
|
||||
"""Effects that record each call and answer from a script, one answer per call."""
|
||||
|
||||
def __init__(self, claude=(), on_terminal_claude=(), git=(), inputs=(), python=(), streams=(), on_terminal=True, free_memory=(), dm_failures=()):
|
||||
def __init__(self, claude=(), on_terminal_claude=(), git=(), inputs=(), python=(), streams=(), on_terminal=True, free_memory=(), dm_failures=(), tmux_version="tmux 3.2", windows=None, owner="/r"):
|
||||
self.calls = []
|
||||
# Each tmux command run. They stay out of self.calls, as the DMs do. tmux prints `windows` for list-windows, or without them finds no session.
|
||||
self.tmux_calls = []
|
||||
self.tmux_version = tmux_version
|
||||
self.windows = windows
|
||||
# The checkout the session's @loop-root option names.
|
||||
self.owner = owner
|
||||
# Each direct message sent. They stay out of self.calls, so a test that lists every call doesn't list them. Without a script, each is sent.
|
||||
self.dms = []
|
||||
self.dm_failures = list(dm_failures)
|
||||
@@ -115,8 +128,16 @@ class FakeEffects:
|
||||
python=lambda args, cwd: self.answer("python", (args, cwd)),
|
||||
sleep=lambda seconds: self.calls.append(("sleep", seconds)),
|
||||
stream_claude=self.stream,
|
||||
tmux=self.tmux,
|
||||
tmux_on_terminal=lambda args: self.tmux(args).returncode,
|
||||
)
|
||||
|
||||
def tmux(self, args):
|
||||
self.tmux_calls.append(args)
|
||||
if args[0] == "list-windows":
|
||||
return subprocess.CompletedProcess(args, 1 if self.windows is None else 0, self.windows or "", "no server")
|
||||
return subprocess.CompletedProcess(args, 0, {"-V": self.tmux_version + "\n", "show-options": self.owner + "\n"}.get(args[0], "@9\n"), "")
|
||||
|
||||
def dm(self, text):
|
||||
self.dms.append(text)
|
||||
return self.dm_failures.pop(0) if self.dm_failures else None
|
||||
@@ -265,7 +286,7 @@ class Cycles(unittest.TestCase):
|
||||
self.archive = project_archive(str(self.home / "code" / "proj"), self.home, {})
|
||||
|
||||
def cycle(self, fake, records="", unfinished_evidence="", facts="- A preflight fact."):
|
||||
return run.Cycle(config=CONFIG, effects=fake.effects(), facts=facts, judge_model="judge-model", ladder=LADDER, premises="## Goals", project=None, project_archive=self.archive, records=records, root=str(self.home), route=Route(Rung("worker-model")), session=self.session, task="Do it.", todo=plan_of(""), unfinished_evidence=unfinished_evidence)
|
||||
return run.Cycle(config=CONFIG, window=WINDOW, effects=fake.effects(), facts=facts, judge_model="judge-model", ladder=LADDER, premises="## Goals", project=None, project_archive=self.archive, records=records, root=str(self.home), route=Route(Rung("worker-model")), session=self.session, task="Do it.", todo=plan_of(""), unfinished_evidence=unfinished_evidence)
|
||||
|
||||
def archived_outcomes(self):
|
||||
return sorted(path.read_text() for path in self.archive.glob("*/*.outcomes.md"))
|
||||
@@ -560,7 +581,7 @@ Spent since 2026-09-21T14:13:20Z, in tokens of input, cache write 5m, cache writ
|
||||
fake = FakeEffects(streams=[worker, worker], claude=[judged("interrupt"), judged("unfinished")], inputs=["Use B."])
|
||||
with contextlib.redirect_stderr(io.StringIO()) as said:
|
||||
self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Unfinished("working", entries_read=6))
|
||||
self.assertIn(f"\n{STAMP} Which one?\n", said.getvalue())
|
||||
self.assertIn(f"\n{STAMP} Which one?\a\n", said.getvalue())
|
||||
self.assertEqual(fake.made("claude_on_terminal"), [])
|
||||
resumed = fake.made("stream_claude")[1]
|
||||
self.assertEqual(resumed[resumed.index("--resume") + 1], str(self.session.id))
|
||||
@@ -627,7 +648,7 @@ Spent since 2026-09-21T14:13:20Z, in tokens of input, cache write 5m, cache writ
|
||||
with contextlib.redirect_stderr(io.StringIO()) as said:
|
||||
self.assertEqual(run.run_cycle(self.cycle(fake, records="From AGENTS.md:\nUse B. Use A.")), Stop(2, "the human is needed to answer the question above, but nothing was typed"))
|
||||
self.assertEqual(len(fake.made("stream_claude")), 1)
|
||||
self.assertIn(f"\n{STAMP} Which one?\n", said.getvalue())
|
||||
self.assertIn(f"\n{STAMP} Which one?\a\n", said.getvalue())
|
||||
self.assertNotIn("Use ... A.", said.getvalue())
|
||||
|
||||
@unittest.skipIf(os.geteuid() == 0, "root writes into a read-only directory")
|
||||
@@ -733,10 +754,11 @@ class Interrupts(unittest.TestCase):
|
||||
self.session = interrupt.WorkerSession(str(self.home), uuid.uuid7(), Rung("m", "high"), str(self.transcript), {"LOOP_CLAUDE_WORKER_RUNG": "m at high effort"})
|
||||
|
||||
def put(self, fake, answer_here=True, effects=None, question="Which one?"):
|
||||
"""interrupt's answer and what it said."""
|
||||
"""interrupt's answer and what it said, without the bell it rang, which self.bells counts."""
|
||||
with contextlib.redirect_stderr(io.StringIO()) as said:
|
||||
answer = interrupt.interrupt(question, answer_here, self.session, effects or fake.effects())
|
||||
return answer, said.getvalue()
|
||||
answer = interrupt.interrupt(question, answer_here, self.session, WINDOW, effects or fake.effects())
|
||||
self.bells = said.getvalue().count(tmux.BELL)
|
||||
return answer, said.getvalue().replace(tmux.BELL, "")
|
||||
|
||||
def typed_there(self, args):
|
||||
"""The claude opened on the terminal: the human types a line in the worker's session, and it ends."""
|
||||
@@ -754,7 +776,19 @@ class Interrupts(unittest.TestCase):
|
||||
with self.subTest(on_terminal=on_terminal):
|
||||
fake = FakeEffects(inputs=["Use B."], on_terminal=on_terminal)
|
||||
self.put(fake)
|
||||
self.assertEqual(fake.dms, [f"loop-claude in {self.home} asks:\n\nWhich one?"])
|
||||
self.assertEqual(fake.dms, [f"loop-claude in {self.home} asks, in the tmux window loop-proj:item-7:\n\nWhich one?"])
|
||||
|
||||
def test_marks_its_window_and_rings_the_bell_while_it_waits_and_clears_the_mark_once_answered(self):
|
||||
fake = FakeEffects(inputs=["Use B."])
|
||||
answer, said = self.put(fake)
|
||||
self.assertEqual(answer, "Use B.")
|
||||
self.assertEqual(self.bells, 1)
|
||||
self.assertEqual(fake.tmux_calls, [["rename-window", "-t", "%4", "item-7 ?"], ["rename-window", "-t", "%4", "item-7"]])
|
||||
|
||||
def test_a_loop_that_stops_unanswered_leaves_its_window_marked(self):
|
||||
fake = FakeEffects(on_terminal=False)
|
||||
self.put(fake)
|
||||
self.assertEqual(fake.tmux_calls, [["rename-window", "-t", "%4", "item-7 ?"]])
|
||||
|
||||
def test_drops_the_keys_typed_before_the_question_ahead_of_the_dm_so_an_answer_typed_while_it_sends_counts(self):
|
||||
fake = FakeEffects(inputs=["Use B."])
|
||||
@@ -984,7 +1018,9 @@ class Routing(unittest.TestCase):
|
||||
|
||||
def test_routes_on_no_item_where_the_release_after_the_last_cut_has_none(self):
|
||||
self.assertEqual(routed_item(TODO, LastCut("v0.1.0", "", 3, [TODO])).id, 3)
|
||||
self.assertIsNone(routed_item(TODO, LastCut("v0.2.0", "", 3, [TODO])))
|
||||
# Someone cut 0.2.0 while it held items: they count as 0.3.0's, the next release, and where no later release is known, no item routes.
|
||||
self.assertEqual(routed_item(TODO, LastCut("v0.2.0", "", 3, [TODO])).id, 3)
|
||||
self.assertIsNone(routed_item(re.sub(r"(?m)^\| \d+ \| 0\.3\.0 \|.*\n", "", TODO), LastCut("v0.2.0", "", 3, [])))
|
||||
later_only = TODO[:TODO.index("| 7 |")] + TODO[TODO.index("| 1 | 0.3.0 |"):]
|
||||
self.assertIsNone(routed_item(later_only, LastCut("v0.1.0", "", 3, [TODO])))
|
||||
self.assertIsNone(routed_item(later_only, LastCut("v0.1.0", "", 0, [TODO])))
|
||||
@@ -1123,14 +1159,33 @@ class Routing(unittest.TestCase):
|
||||
|
||||
class RouteSources(unittest.TestCase):
|
||||
def test_routes_on_the_plan_item_and_says_why_it_routes_on_the_projects_rung(self):
|
||||
self.assertIsNone(chunk_start.plan_item(DefaultPlan(plan_of(""), NO_CUT), FakeEffects().effects()))
|
||||
self.assertEqual(chunk_start.plan_item(DefaultPlan(plan_of(TODO), LastCut("v0.1.0", "", 3, [TODO])), FakeEffects().effects()).id, 3)
|
||||
self.assertIsNone(chunk_start.plan_item(DefaultPlan(plan_of(TODO), LastCut("v0.2.0", "", 3, [TODO])), FakeEffects().effects()))
|
||||
self.assertIsNone(chunk_start.plan_item(DefaultPlan(plan_of(""), NO_CUT), None, FakeEffects().effects()))
|
||||
self.assertEqual(chunk_start.plan_item(DefaultPlan(plan_of(TODO), LastCut("v0.1.0", "", 3, [TODO])), None, FakeEffects().effects()).id, 3)
|
||||
self.assertIsNone(chunk_start.plan_item(DefaultPlan(plan_of(TODO), LastCut("v0.3.0", "", 3, [TODO])), None, FakeEffects().effects()))
|
||||
|
||||
def test_routes_a_window_named_for_an_item_on_that_item_whatever_the_plan_takes_next(self):
|
||||
plan = DefaultPlan(plan_of(TODO), LastCut("v0.1.0", "", 3, [TODO]))
|
||||
later = next(item.id for item in plan.todo.items if item.id != 3)
|
||||
self.assertEqual(chunk_start.plan_item(plan, later, FakeEffects().effects()).id, later)
|
||||
# An item that left the plan, as once it shipped.
|
||||
self.assertIsNone(chunk_start.plan_item(plan, 999, FakeEffects().effects()))
|
||||
with unittest.mock.patch.object(chunk_start, "session_open", return_value=True), unittest.mock.patch.object(chunk_start, "fetched_plan", return_value=plan) as fetched:
|
||||
for window, routed in ((tmux.Window("loop-proj", f"item-{later}", "%4"), later), (tmux.Window("loop-proj", "no-item", "%4"), 3)):
|
||||
with self.subTest(window=window.name):
|
||||
loop = a_loop(FakeEffects().effects(), window=window)
|
||||
facts, reader = chunk_start.chunk_start(loop)
|
||||
self.assertEqual((facts, reader().id), ("", routed))
|
||||
fetched.assert_called_with(loop)
|
||||
# Where the plan cannot be read, the reader says so through the loop's effects, and routes on the project's rung.
|
||||
fetched.return_value = Failure("no origin remote")
|
||||
with contextlib.redirect_stderr(io.StringIO()) as said:
|
||||
self.assertIsNone(chunk_start.chunk_start(a_loop(FakeEffects().effects()))[1]())
|
||||
self.assertIn("routing on the project's rung: no origin remote", said.getvalue())
|
||||
unreadable = Failure("git show origin/main:todo.md printed text that is not UTF-8")
|
||||
for plan, said in ((DefaultPlan(plan_of(TODO.replace("| 4 | 2 | 3 |", "| x | 2 | 3 |")), NO_CUT), "routing on the project's rung: item 3's L 'x' is not a whole number from 1 to 4\n"), (DefaultPlan(unreadable, NO_CUT), f"routing on the project's rung: {unreadable.reason}\n"), (Failure("no origin remote"), "routing on the project's rung: no origin remote\n")):
|
||||
with self.subTest(said=said):
|
||||
with contextlib.redirect_stderr(io.StringIO()) as stderr:
|
||||
self.assertIsNone(chunk_start.plan_item(plan, FakeEffects().effects()))
|
||||
self.assertIsNone(chunk_start.plan_item(plan, None, FakeEffects().effects()))
|
||||
self.assertTrue(stderr.getvalue().startswith(f"{STAMP} {said}"), stderr.getvalue())
|
||||
|
||||
def test_says_why_the_items_the_worker_names_lift_no_rung(self):
|
||||
@@ -1208,61 +1263,272 @@ class RouteSources(unittest.TestCase):
|
||||
self.assertTrue(stderr.getvalue().startswith(f"{STAMP} routing the chunk afresh: could not read the archive"), stderr.getvalue())
|
||||
|
||||
|
||||
class ChunkSlots(unittest.TestCase):
|
||||
class TmuxCommands(unittest.TestCase):
|
||||
def test_refuses_a_tmux_older_than_needed_naming_both_versions(self):
|
||||
for found, reason in (("tmux 3.2", None), ("tmux 3.8", None), ("tmux next-3.4", None), ("tmux 10.0", None),
|
||||
("tmux 3.1c", "loop-claude runs each chunk in a tmux window, and needs tmux 3.2 or later; it found tmux 3.1c"),
|
||||
("tmux 2.9a", "loop-claude runs each chunk in a tmux window, and needs tmux 3.2 or later; it found tmux 2.9a"),
|
||||
("", "loop-claude runs each chunk in a tmux window, and needs tmux 3.2 or later; it found no tmux")):
|
||||
with self.subTest(found=found):
|
||||
fake = FakeEffects(tmux_version=found)
|
||||
self.assertEqual(tmux.unusable(fake.tmux), reason)
|
||||
self.assertEqual(fake.tmux_calls, [["-V"]])
|
||||
|
||||
def test_names_the_session_for_the_project(self):
|
||||
self.assertEqual(tmux.session_name("claude-config"), "loop-claude-config")
|
||||
# tmux reads `.` and `:` in a target as separators.
|
||||
self.assertEqual(tmux.session_name("my.site:2 x"), "loop-my-site-2-x")
|
||||
self.assertEqual(tmux.session_name("Acme/Billing"), "loop-Acme-Billing")
|
||||
|
||||
def test_lists_the_windows_without_the_waiting_mark(self):
|
||||
fake = FakeEffects(windows="item-372 ?\t0\t@1\nitem-380\t1\t@2\nno-item\t0\t@5\n")
|
||||
self.assertEqual(tmux.listed("loop-proj", fake.tmux), [tmux.Listed("item-372", "@1", False), tmux.Listed("item-380", "@2", True), tmux.Listed("no-item", "@5", False)])
|
||||
self.assertEqual(fake.tmux_calls, [["list-windows", "-t", "=loop-proj", "-F", "#{window_name}\t#{pane_dead}\t#{window_id}"]])
|
||||
self.assertEqual(tmux.listed("loop-proj", FakeEffects().tmux), [])
|
||||
failed = lambda args: subprocess.CompletedProcess(args, 1, "item-1\t0\t@1\n", "no server")
|
||||
self.assertEqual(tmux.listed("loop-proj", failed), [])
|
||||
|
||||
def test_the_first_window_makes_the_session_and_each_later_one_joins_it(self):
|
||||
fake = FakeEffects()
|
||||
window = tmux.Window("loop-proj", "item-7", "")
|
||||
self.assertIsNone(tmux.start_window(window, "/r", {"LOOP_CLAUDE_X": "1"}, ["/b/loop-claude", "--chunk", "item-7", "ship it;"], True, fake.tmux))
|
||||
self.assertIsNone(tmux.start_window(window, "/r", {}, ["/b/loop-claude"], False, fake.tmux))
|
||||
self.assertEqual(fake.tmux_calls, [
|
||||
["new-session", "-d", "-s", "loop-proj", "-n", "item-7", "-c", "/r", "-e", "LOOP_CLAUDE_X=1", "-P", "-F", "#{window_id}", "--", "/b/loop-claude", "--chunk", "item-7", "ship it\;"],
|
||||
["set-option", "-t", "=loop-proj:", "@loop-root", "/r"],
|
||||
["set-option", "-w", "-t", "@9", "remain-on-exit", "failed"],
|
||||
["new-window", "-d", "-t", "=loop-proj:", "-n", "item-7", "-c", "/r", "-P", "-F", "#{window_id}", "--", "/b/loop-claude"],
|
||||
["set-option", "-w", "-t", "@9", "remain-on-exit", "failed"],
|
||||
])
|
||||
|
||||
def test_says_why_tmux_started_no_window(self):
|
||||
failed = lambda args: subprocess.CompletedProcess(args, 1, "", "duplicate session: loop-proj\n")
|
||||
silent = lambda args: subprocess.CompletedProcess(args, 2, "", "")
|
||||
window = tmux.Window("loop-proj", "item-7", "")
|
||||
self.assertEqual(tmux.start_window(window, "/r", {}, ["x"], True, failed), Failure("tmux could not start the window loop-proj:item-7: duplicate session: loop-proj"))
|
||||
self.assertEqual(tmux.start_window(window, "/r", {}, ["x"], True, silent), Failure("tmux could not start the window loop-proj:item-7: it exited 2"))
|
||||
|
||||
def test_reads_the_checkout_the_session_names(self):
|
||||
fake = FakeEffects(owner="/c/proj")
|
||||
self.assertEqual(tmux.owner("loop-proj", fake.tmux), "/c/proj")
|
||||
self.assertEqual(fake.tmux_calls, [["show-options", "-qv", "-t", "=loop-proj:", "@loop-root"]])
|
||||
|
||||
def test_marks_a_waiting_window_by_its_pane_and_clears_the_mark(self):
|
||||
fake = FakeEffects()
|
||||
tmux.mark(WINDOW, True, fake.tmux)
|
||||
tmux.mark(WINDOW, False, fake.tmux)
|
||||
tmux.close(tmux.Listed("item-7", "@3", True), fake.tmux)
|
||||
self.assertEqual(fake.tmux_calls, [["rename-window", "-t", "%4", "item-7 ?"], ["rename-window", "-t", "%4", "item-7"], ["kill-window", "-t", "@3"]])
|
||||
self.assertEqual(WINDOW.target, "loop-proj:item-7")
|
||||
|
||||
def test_shows_the_session_by_attaching_or_inside_tmux_by_switching(self):
|
||||
self.assertEqual(tmux.show("loop-proj", False), ["attach-session", "-t", "=loop-proj"])
|
||||
self.assertEqual(tmux.show("loop-proj", True), ["switch-client", "-t", "=loop-proj"])
|
||||
|
||||
|
||||
class ChunkWindows(unittest.TestCase):
|
||||
def plan(self, *touched):
|
||||
"""A plan of items 1, 2 and on, each predicted to touch the path given for it."""
|
||||
items = touch_plan(*((number, "1.0.0", "", f"- `{path}`") for number, path in enumerate(touched, 1)))
|
||||
return gathered.Plan(items=items, first=items[0], text="", branch_template="")
|
||||
|
||||
def test_starts_the_next_item_and_those_picked_beside_it_up_to_the_limit(self):
|
||||
# Item 2 overlaps item 1, so it waits for it; items 3 and 4 run beside it.
|
||||
plan = self.plan("a.py", "a.py", "c.py", "d.py")
|
||||
self.assertEqual(chunk_windows.may_start(plan, [], set(), 1), ["item-1"])
|
||||
self.assertEqual(chunk_windows.may_start(plan, [], set(), 2), ["item-1", "item-3"])
|
||||
self.assertEqual(chunk_windows.may_start(plan, [], set(), 9), ["item-1", "item-3", "item-4"])
|
||||
|
||||
def test_leaves_the_items_running_chunks_hold_and_counts_them_against_the_limit(self):
|
||||
plan = self.plan("a.py", "a.py", "c.py", "d.py")
|
||||
self.assertEqual(chunk_windows.may_start(plan, ["item-1"], {1, 3}, 2), ["item-4"])
|
||||
self.assertEqual(chunk_windows.may_start(plan, ["item-1"], {1}, 3), ["item-3", "item-4"])
|
||||
self.assertEqual(chunk_windows.may_start(plan, ["item-1", "item-3"], {1, 3}, 2), [])
|
||||
self.assertEqual(chunk_windows.may_start(plan, ["item-1", "item-3", "item-4"], {1, 3, 4}, 2), [])
|
||||
|
||||
def test_starts_no_item_that_overlaps_a_running_chunks_items(self):
|
||||
# Item 1 merged, so 2 is the plan's next item; it overlaps item 3, which still runs, at c.py.
|
||||
items = touch_plan((2, "1.0.0", "", "- `a.py`\n- `c.py`"), (3, "1.0.0", "", "- `c.py`"), (4, "1.0.0", "", "- `d.py`"))
|
||||
plan = gathered.Plan(items=items, first=items[0], text="", branch_template="")
|
||||
self.assertEqual(chunk_windows.may_start(plan, ["item-3"], {3}, 3), ["item-4"])
|
||||
# A running chunk's item without a prediction leaves no other item free to start beside it.
|
||||
unpredicted = touch_plan((2, "1.0.0", "", "- `a.py`"), (3, "1.0.0", "", None))
|
||||
self.assertEqual(chunk_windows.may_start(gathered.Plan(items=unpredicted, first=unpredicted[0], text="", branch_template=""), ["item-3"], {3}, 3), [])
|
||||
# A held item that left the plan, as once it merged, overlaps nothing.
|
||||
self.assertEqual(chunk_windows.may_start(plan, ["item-9"], {9}, 3), ["item-2", "item-4"])
|
||||
|
||||
def test_a_plan_without_an_item_starts_one_chunk_and_only_alone(self):
|
||||
none = gathered.NoItem("release 1.0.0 has no items")
|
||||
self.assertEqual(chunk_windows.may_start(none, [], set(), 3), ["no-item"])
|
||||
self.assertEqual(chunk_windows.may_start(none, ["item-1"], {1}, 3), [])
|
||||
|
||||
def test_names_a_window_for_its_item_and_reads_the_item_back(self):
|
||||
self.assertEqual(chunk_windows.window_name(372), "item-372")
|
||||
self.assertEqual([chunk_windows.item_of(chunk) for chunk in ("item-372", "no-item", "item-", "item-3x", "xitem-3")], [372, None, None, None, None])
|
||||
# Only ASCII digits name an item, as window_name writes them.
|
||||
self.assertIsNone(chunk_windows.item_of("item-\u0663"))
|
||||
|
||||
def test_starts_only_the_next_item_where_the_touch_predictions_cannot_be_read(self):
|
||||
with unittest.mock.patch.object(chunk_windows, "chunks_beside", return_value="item 1's Touches: list cannot be read"):
|
||||
self.assertEqual(chunk_windows.may_start(self.plan("a.py", "c.py"), [], set(), 3), ["item-1"])
|
||||
|
||||
def test_a_chunk_whose_transcript_cannot_be_read_holds_the_item_it_started_from(self):
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
transcripts = pathlib.Path(temp)
|
||||
folder = transcripts / "-r"
|
||||
folder.mkdir()
|
||||
# A folder in place of the transcript file, so reading it fails.
|
||||
(folder / f"{chunk_windows.chunk_session('proj', 'item-7', transcripts).id}.jsonl").mkdir()
|
||||
self.assertEqual(chunk_windows.held_items(["item-7"], "proj", transcripts), {7})
|
||||
|
||||
def test_tells_a_chunk_the_items_the_projects_other_live_chunks_hold(self):
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
home = pathlib.Path(temp)
|
||||
held = paths.paths_from(home)
|
||||
folder = held.claude_code_transcripts / "-r"
|
||||
folder.mkdir(parents=True)
|
||||
lines = [assistant({"type": "text", "text": "Chunk items: 8 (L 1, E + I 2), 11 (L 2, E + I 3)"})]
|
||||
(folder / f"{chunk_windows.chunk_session('r', 'item-8', held.claude_code_transcripts).id}.jsonl").write_text("".join(json.dumps(line) + "\n" for line in lines))
|
||||
# Its own window, item-7, holds nothing for it; item-9's stopped chunk holds its item.
|
||||
fake = FakeEffects(windows="item-7\t0\t@1\nitem-8 ?\t0\t@2\nitem-9\t1\t@3\nitem-10\t0\t@4\n")
|
||||
self.assertEqual(chunk_windows.held_beside("item-7", "/r", held, fake.effects()), [8, 9, 10, 11])
|
||||
self.assertEqual(fake.tmux_calls, [["list-windows", "-t", "=loop-r", "-F", "#{window_name}\t#{pane_dead}\t#{window_id}"]])
|
||||
|
||||
|
||||
class StartChunks(unittest.TestCase):
|
||||
"""start_chunks: the windows a loop opens for the chunks that may start now."""
|
||||
LAUNCHER = pathlib.Path("/b/loop-claude")
|
||||
|
||||
def setUp(self):
|
||||
temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(temp.cleanup)
|
||||
self.home = pathlib.Path(temp.name)
|
||||
self.paths = paths.paths_from(self.home)
|
||||
self.addCleanup(self.release)
|
||||
made = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(made.cleanup)
|
||||
self.root = pathlib.Path(made.name, "r")
|
||||
self.home = configured(self, self.root).parents[1]
|
||||
self.session = "loop-" + str(self.root).lstrip("/").replace("/", "-").replace(".", "-")
|
||||
# Items 1 and 2 overlap, so 2 waits; 3 runs beside 1.
|
||||
self.plan = ChunkWindows.plan(self, "a.py", "a.py", "c.py")
|
||||
|
||||
def held(self):
|
||||
"""This process's open files on a slot, each with whether an exec keeps it."""
|
||||
folder = self.home / chunk_slot.SLOTS
|
||||
found = {}
|
||||
for fd in os.listdir("/proc/self/fd"):
|
||||
with contextlib.suppress(OSError):
|
||||
if pathlib.Path(os.readlink(f"/proc/self/fd/{fd}")).is_relative_to(folder):
|
||||
found[os.readlink(f"/proc/self/fd/{fd}")] = os.get_inheritable(int(fd))
|
||||
return found
|
||||
def limit(self, chunks):
|
||||
config = self.home / ".claude-projects" / self.root.name / "config.toml"
|
||||
config.write_text(config.read_text() + f"parallel-chunks = {chunks}\n")
|
||||
|
||||
def release(self):
|
||||
folder = str(self.home / chunk_slot.SLOTS)
|
||||
for fd in os.listdir("/proc/self/fd"):
|
||||
with contextlib.suppress(OSError):
|
||||
if os.readlink(f"/proc/self/fd/{fd}").startswith(folder):
|
||||
os.close(int(fd))
|
||||
def start(self, fake, chunk=None, leaving=False, plan=None, env=None, owner=None):
|
||||
"""start_chunks' answer, for a session whose @loop-root names owner, by default this checkout."""
|
||||
fake.owner = str(self.root) if owner is None else owner
|
||||
run = main.LoopRun(0, str(self.root), "ship it", "", chunk=chunk)
|
||||
with unittest.mock.patch.object(chunk_windows, "next_plan", return_value=plan or self.plan) as planned, contextlib.redirect_stderr(io.StringIO()) as said:
|
||||
effects = fake.effects()
|
||||
started = chunk_windows.start_chunks(run, leaving, paths.paths_from(self.home), env or {}, self.LAUNCHER, effects)
|
||||
self.said = said.getvalue()
|
||||
self.planned = planned.call_count
|
||||
if planned.call_count:
|
||||
planned.assert_called_once_with(str(self.root), self.home, effects)
|
||||
return started
|
||||
|
||||
def test_each_loop_takes_the_lowest_free_slot_and_names_its_session_after_it(self):
|
||||
loop_run = main.LoopRun(cycle_number=0, root=str(self.home / "code" / "proj"), task="do it", unfinished_evidence="")
|
||||
first, second = chunk_slot.slotted(loop_run, self.paths), chunk_slot.slotted(loop_run, self.paths)
|
||||
self.assertEqual((first[0], first[1].name), (dataclasses.replace(loop_run, slot=0), "A proj loop-claude"))
|
||||
self.assertEqual((second[0].slot, second[1].name), (1, "A proj loop-claude 2"))
|
||||
self.assertEqual(second[1], session.session_named("A proj loop-claude 2", self.paths.claude_code_transcripts))
|
||||
folder = self.home / ".local" / "state" / "loop-claude" / "proj"
|
||||
self.assertEqual(self.held(), {str(folder / "slot-0"): True, str(folder / "slot-1"): True})
|
||||
def starts(self, fake):
|
||||
"""The window starts of fake's tmux calls, each as (command, window name, what it runs)."""
|
||||
return [(call[0], call[call.index("-n") + 1], call[call.index("--") + 1:]) for call in fake.tmux_calls if call[0] in ("new-session", "new-window")]
|
||||
|
||||
def test_a_rerun_takes_the_lowest_free_slot_whose_session_is_open_before_a_lower_closed_one(self):
|
||||
loop_run = main.LoopRun(cycle_number=0, root=str(self.home / "code" / "proj"), task="do it", unfinished_evidence="")
|
||||
for name in ("A proj loop-claude 3", "A proj loop-claude 4"):
|
||||
transcript = self.paths.claude_code_transcripts / "-home-proj" / f"{session.session_named(name, self.paths.claude_code_transcripts).id}.jsonl"
|
||||
transcript.parent.mkdir(parents=True, exist_ok=True)
|
||||
transcript.write_text("")
|
||||
self.assertEqual([chunk_slot.slotted(loop_run, self.paths)[0].slot for _ in range(4)], [2, 3, 0, 1])
|
||||
def test_opens_a_window_for_each_chunk_that_may_start_the_first_making_the_session(self):
|
||||
self.limit(2)
|
||||
fake = FakeEffects()
|
||||
self.assertEqual(self.start(fake, env={"LOOP_CLAUDE_WORKER_MODEL": "m", "PATH": "/bin"}), ["item-1", "item-3"])
|
||||
self.assertEqual(self.starts(fake), [("new-session", "item-1", [str(self.LAUNCHER), "--chunk", "item-1", "ship it"]), ("new-window", "item-3", [str(self.LAUNCHER), "--chunk", "item-3", "ship it"])])
|
||||
first = next(call for call in fake.tmux_calls if call[0] == "new-session")
|
||||
self.assertEqual((first[first.index("-s") + 1], first[first.index("-c") + 1]), (self.session, str(self.root)))
|
||||
# Only loop-claude's own variables are handed on, since a window gets the tmux server's environment.
|
||||
self.assertEqual([word for word in first if "=" in word], ["LOOP_CLAUDE_WORKER_MODEL=m"])
|
||||
self.assertEqual(fake.tmux_calls[0], ["list-windows", "-t", f"={self.session}", "-F", "#{window_name}\t#{pane_dead}\t#{window_id}"])
|
||||
# The session names the checkout whose chunks it runs.
|
||||
self.assertIn(["set-option", "-t", f"={self.session}:", "@loop-root", str(self.root)], fake.tmux_calls)
|
||||
|
||||
def test_a_reload_keeps_the_slot_it_is_handed_and_takes_no_other(self):
|
||||
loop_run = main.LoopRun(cycle_number=3, root="/srv/proj", task="do it", unfinished_evidence="", slot=2)
|
||||
self.assertEqual(chunk_slot.slotted(loop_run, self.paths), (loop_run, session.session_named("A srv/proj loop-claude 3", self.paths.claude_code_transcripts)))
|
||||
self.assertEqual(self.held(), {})
|
||||
def test_refuses_a_session_that_runs_another_checkouts_chunks(self):
|
||||
for owner, named in (("/c/acme.api", "/c/acme.api"), ("", "another checkout")):
|
||||
with self.subTest(owner=owner):
|
||||
fake = FakeEffects(windows="item-5\t0\t@1\n")
|
||||
self.assertEqual(self.start(fake, owner=owner), Failure(f"the tmux session {self.session} runs the chunks of {named}, whose key maps to the same session name; rename one of the two checkouts' folders"))
|
||||
self.assertEqual(self.starts(fake), [])
|
||||
self.assertIn(["show-options", "-qv", "-t", f"={self.session}:", "@loop-root"], fake.tmux_calls)
|
||||
|
||||
def test_says_why_it_takes_no_slot(self):
|
||||
loop_run = main.LoopRun(cycle_number=0, root="/srv/proj", task="do it", unfinished_evidence="")
|
||||
with unittest.mock.patch.object(chunk_slot, "MOST", 1):
|
||||
chunk_slot.slotted(loop_run, self.paths)
|
||||
self.assertEqual(chunk_slot.slotted(loop_run, self.paths), Failure(f"1 loops of this project are running already; `fuser {self.home}/.local/state/loop-claude/srv/proj/slot-*` names them"))
|
||||
(self.home / ".local" / "state" / "loop-claude").mkdir(parents=True, exist_ok=True)
|
||||
(self.home / ".local" / "state" / "loop-claude" / "other").write_text("")
|
||||
self.assertEqual(chunk_slot.slotted(dataclasses.replace(loop_run, root="/other"), self.paths), Failure(f"cannot take a slot in {self.home}/.local/state/loop-claude/other: File exists"))
|
||||
def test_leaves_out_the_items_a_running_chunk_names_on_its_chunk_items_line(self):
|
||||
self.limit(2)
|
||||
transcripts = paths.paths_from(self.home).claude_code_transcripts
|
||||
folder = transcripts / "-r"
|
||||
folder.mkdir(parents=True)
|
||||
opened = chunk_windows.chunk_session(str(self.root).lstrip("/"), "item-5", transcripts)
|
||||
(folder / f"{opened.id}.jsonl").write_text(json.dumps(assistant({"type": "text", "text": "Chunk items: 5 (L 1, E + I 2), 1 (L 1, E + I 2)"})) + "\n")
|
||||
self.assertEqual(self.start(FakeEffects(windows="item-5\t0\t@1\n")), ["item-3"])
|
||||
|
||||
def test_starts_one_chunk_without_parallel_chunks(self):
|
||||
fake = FakeEffects()
|
||||
self.assertEqual(self.start(fake), ["item-1"])
|
||||
|
||||
def test_starts_none_and_reads_no_plan_while_the_running_chunks_fill_the_limit(self):
|
||||
self.limit(2)
|
||||
fake = FakeEffects(windows="item-5\t0\t@1\nitem-6 ?\t0\t@2\n")
|
||||
self.assertEqual((self.start(fake), self.planned, self.starts(fake)), ([], 0, []))
|
||||
# More chunks run than the limit allows, as after it was lowered; a stopped chunk still waits.
|
||||
fake = FakeEffects(windows="item-5\t0\t@1\nitem-6\t0\t@2\nitem-7\t0\t@3\nitem-8\t1\t@4\nitem-9\t1\t@5\n")
|
||||
self.assertEqual((self.start(fake), self.planned), ([], 0))
|
||||
|
||||
def test_a_finishing_chunks_own_window_counts_as_no_longer_running(self):
|
||||
fake = FakeEffects(windows="item-5\t0\t@1\n")
|
||||
self.assertEqual(self.start(fake, chunk="item-5"), [])
|
||||
fake = FakeEffects(windows="item-5\t0\t@1\n")
|
||||
self.assertEqual(self.start(fake, chunk="item-5", leaving=True), ["item-1"])
|
||||
# The session exists, since the finishing loop's window is still in it.
|
||||
self.assertEqual(self.starts(fake)[0][0], "new-window")
|
||||
|
||||
def test_the_humans_loop_claude_starts_a_stopped_chunk_again_first_closing_its_dead_window(self):
|
||||
fake = FakeEffects(windows="item-5\t1\t@3\n")
|
||||
self.assertEqual((self.start(fake), self.planned), (["item-5"], 0))
|
||||
self.assertIn(["kill-window", "-t", "@3"], fake.tmux_calls)
|
||||
# Its dead window was the session's last, so the session is made again.
|
||||
self.assertEqual(self.starts(fake)[0][0], "new-session")
|
||||
self.limit(2)
|
||||
fake = FakeEffects(windows="item-5\t1\t@3\n")
|
||||
self.assertEqual(self.start(fake), ["item-5", "item-1"])
|
||||
|
||||
def test_a_finishing_chunk_leaves_a_stopped_chunk_and_its_items_to_the_human(self):
|
||||
self.limit(2)
|
||||
transcripts = paths.paths_from(self.home).claude_code_transcripts
|
||||
folder = transcripts / "-r"
|
||||
folder.mkdir(parents=True)
|
||||
opened = chunk_windows.chunk_session(str(self.root).lstrip("/"), "item-5", transcripts)
|
||||
(folder / f"{opened.id}.jsonl").write_text(json.dumps(assistant({"type": "text", "text": "Chunk items: 5 (L 1, E + I 2), 1 (L 1, E + I 2)"})) + "\n")
|
||||
fake = FakeEffects(windows="item-7\t0\t@1\nitem-5\t1\t@3\n")
|
||||
# Item 1 is the stopped chunk's, so item 3 starts; the stopped one doesn't count against parallel-chunks.
|
||||
self.assertEqual(self.start(fake, chunk="item-7", leaving=True), ["item-3"])
|
||||
self.assertEqual([call for call in fake.tmux_calls if call[0] == "kill-window"], [])
|
||||
fake = FakeEffects(windows="item-7\t0\t@1\nno-item\t1\t@3\n")
|
||||
self.assertEqual(self.start(fake, chunk="item-7", leaving=True, plan=gathered.NoItem("release 1.0.0 has no items")), [])
|
||||
|
||||
def test_starts_the_chunk_without_a_plan_item_where_the_plan_cannot_be_read(self):
|
||||
fake = FakeEffects()
|
||||
self.assertEqual(self.start(fake, plan=Failure("no origin/main")), ["no-item"])
|
||||
self.assertIn("starting a chunk without a plan item, since the plan cannot be read: no origin/main", self.said)
|
||||
|
||||
def test_says_why_a_window_could_not_start(self):
|
||||
with unittest.mock.patch.object(tmux, "start_window", return_value=Failure("tmux could not start the window")):
|
||||
self.assertEqual(self.start(FakeEffects()), Failure("tmux could not start the window"))
|
||||
|
||||
def test_says_why_it_cannot_take_the_lock_on_starting_windows(self):
|
||||
(self.home / ".local" / "state").mkdir(parents=True)
|
||||
(self.home / ".local" / "state" / "loop-claude").write_text("")
|
||||
started = self.start(FakeEffects())
|
||||
self.assertIsInstance(started, Failure)
|
||||
self.assertTrue(started.reason.startswith(f"cannot lock {self.home}/.local/state/loop-claude/"), started.reason)
|
||||
|
||||
def test_a_chunk_holds_its_own_item_and_those_on_its_latest_chunk_items_line(self):
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
transcripts = pathlib.Path(temp)
|
||||
opened = chunk_windows.chunk_session("proj", "item-7", transcripts)
|
||||
self.assertEqual(opened.name, "A proj loop-claude item-7")
|
||||
folder = transcripts / "-r"
|
||||
folder.mkdir()
|
||||
lines = [assistant({"type": "text", "text": "Chunk items: 7 (L 1, E + I 2)"}), assistant({"type": "text", "text": "Chunk items: 7 (L 1, E + I 2), 9 (L 2, E + I 3)"})]
|
||||
(folder / f"{opened.id}.jsonl").write_text("".join(json.dumps(line) + "\n" for line in lines))
|
||||
self.assertEqual(chunk_windows.held_items(["item-7", "item-8", "no-item"], "proj", transcripts), {7, 8, 9})
|
||||
|
||||
|
||||
class Steps(unittest.TestCase):
|
||||
@@ -1335,10 +1601,27 @@ class ChunkFacts(unittest.TestCase):
|
||||
def test_runs_the_preflight_at_the_checkout_root_and_quotes_what_it_printed(self):
|
||||
fake = FakeEffects(python=[ran("- A fact.\n")])
|
||||
said = chunk_start.chunk_facts(a_loop(fake.effects(), launcher=self.LAUNCHER))
|
||||
self.assertEqual(fake.made("python"), [(["/b/chunk-preflight", "--worktree"], "/r")])
|
||||
self.assertIn("\n\n- A fact.", said)
|
||||
self.assertEqual(fake.made("python"), [(["/b/chunk-preflight", "--worktree", "--item", "7"], "/r")])
|
||||
self.assertTrue(said.endswith("\n\n- A fact."), said)
|
||||
self.assertNotIn("yourself", said)
|
||||
|
||||
def test_a_chunk_without_an_item_runs_the_preflight_without_naming_one(self):
|
||||
fake = FakeEffects(python=[ran("- A fact.\n")])
|
||||
chunk_start.chunk_facts(a_loop(fake.effects(), launcher=self.LAUNCHER, window=tmux.Window("loop-proj", "no-item", "%4")))
|
||||
self.assertEqual(fake.made("python"), [(["/b/chunk-preflight", "--worktree"], "/r")])
|
||||
|
||||
def test_the_facts_end_with_the_items_the_projects_other_running_chunks_hold(self):
|
||||
# The loop's own window, a stopped one and two that run, one of them waiting for the human.
|
||||
fake = FakeEffects(python=[ran("- A fact.\n")], windows="item-7\t0\t@1\nitem-5\t1\t@2\nitem-12 ?\t0\t@3\nitem-9\t0\t@4\n")
|
||||
said = chunk_start.chunk_facts(a_loop(fake.effects(), launcher=self.LAUNCHER))
|
||||
self.assertTrue(said.endswith("- A fact.\n\nOther chunks of this project, running or stopped, hold items 5, 9, 12. Leave those items out of this chunk, even where the facts above list them as items that may join it."), said)
|
||||
self.assertEqual(prompts.held_by_others([9]), "\n\nOther chunks of this project, running or stopped, hold item 9. Leave those items out of this chunk, even where the facts above list them as items that may join it.")
|
||||
self.assertTrue(prompts.held_by_others([4, 9]).startswith("\n\nOther chunks of this project, running or stopped, hold items 4, 9."))
|
||||
# A worker whose preflight failed is told them too.
|
||||
fake = FakeEffects(python=[ran(code=1, stderr="git could not start\n")], windows="item-9\t0\t@4\n")
|
||||
said = chunk_start.chunk_facts(a_loop(fake.effects(), launcher=self.LAUNCHER))
|
||||
self.assertTrue(said.endswith("Other chunks of this project, running or stopped, hold item 9. Leave those items out of this chunk, even where the facts above list them as items that may join it."), said)
|
||||
|
||||
def test_has_the_worker_find_the_facts_itself_where_the_preflight_failed(self):
|
||||
for failed, why in ((ran(code=1, stderr="git could not start\n"), "git could not start"), (ran(code=1), "exited 1")):
|
||||
with self.subTest(why=why):
|
||||
@@ -1351,7 +1634,7 @@ class ChunkFacts(unittest.TestCase):
|
||||
opened = session.session_named("A proj loop-claude", pathlib.Path(home, "projects"))
|
||||
fresh = FakeEffects(python=[ran("- A fact.\n")])
|
||||
facts, _ = chunk_start.chunk_start(a_loop(fresh.effects(), session=opened, launcher=self.LAUNCHER))
|
||||
self.assertEqual((fresh.made("python"), "- A fact." in facts), ([(["/b/chunk-preflight", "--worktree"], "/r")], True))
|
||||
self.assertEqual((fresh.made("python"), "- A fact." in facts), ([(["/b/chunk-preflight", "--worktree", "--item", "7"], "/r")], True))
|
||||
transcript = pathlib.Path(home, "projects", "-fake", f"{opened.id}.jsonl")
|
||||
transcript.parent.mkdir(parents=True)
|
||||
transcript.write_text("")
|
||||
@@ -1922,6 +2205,10 @@ class LoopRuns(unittest.TestCase):
|
||||
state = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="")
|
||||
self.assertEqual(reload.decode_handed(json.dumps(dataclasses.asdict(state) | {"items_taken_in": [12, 14]})), state)
|
||||
|
||||
def test_drops_the_slot_that_a_loop_started_before_chunks_ran_in_windows_hands_on(self):
|
||||
state = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="")
|
||||
self.assertEqual(reload.decode_handed(json.dumps({key: value for key, value in dataclasses.asdict(state).items() if key != "chunk"} | {"slot": 1})), state)
|
||||
|
||||
def test_stops_when_the_reload_cannot_start_python(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
launcher = pathlib.Path(root, "loop-claude")
|
||||
@@ -1930,6 +2217,106 @@ class LoopRuns(unittest.TestCase):
|
||||
self.assertEqual(reload.exec_if_edited(a_loop(fake.effects(), launcher=launcher), "stale", main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="")), Stop(1, "could not reload loop-claude: No such file or directory; rerun loop-claude <task>"))
|
||||
|
||||
|
||||
class WindowStarts(unittest.TestCase):
|
||||
"""The loop-claude the human runs, which starts the windows, and the stop of a window's loop whose chunk finished."""
|
||||
HOME = pathlib.Path("/h")
|
||||
|
||||
def run_loop(self, argv, fake, env=None, started=("item-3", "item-4")):
|
||||
"""run_loop's stop and what it said on stdout, with start_chunks answering `started`; self.asked holds what start_chunks was asked."""
|
||||
with unittest.mock.patch.object(main, "start_chunks", return_value=list(started) if isinstance(started, tuple) else started) as start, contextlib.redirect_stdout(io.StringIO()) as said:
|
||||
stop = main.run_loop(argv, env or {}, paths.paths_from(self.HOME), pathlib.Path("/b/loop-claude"), CWD, fake.effects())
|
||||
self.asked = [call.args[:2] for call in start.call_args_list]
|
||||
return stop, said.getvalue()
|
||||
|
||||
def test_refuses_to_start_anything_on_a_tmux_older_than_needed(self):
|
||||
fake = FakeEffects(git=["/r\n"], tmux_version="tmux 3.1c")
|
||||
self.assertEqual(self.run_loop(["do it"], fake), (Stop(1, "loop-claude runs each chunk in a tmux window, and needs tmux 3.2 or later; it found tmux 3.1c"), ""))
|
||||
self.assertEqual((fake.tmux_calls, self.asked), ([["-V"]], []))
|
||||
|
||||
def test_prints_the_help_without_tmux(self):
|
||||
fake = FakeEffects(tmux_version="")
|
||||
self.assertEqual(self.run_loop(["--help"], fake)[0], Stop(0, usage.HELP))
|
||||
self.assertEqual(fake.tmux_calls, [])
|
||||
|
||||
def test_starts_the_chunks_then_attaches_to_the_session_or_inside_tmux_switches_to_it(self):
|
||||
for env, shown in (({}, ["attach-session", "-t", "=loop-r"]), ({"TMUX": "/tmp/tmux-1000/default,1,0"}, ["switch-client", "-t", "=loop-r"])):
|
||||
with self.subTest(shown=shown):
|
||||
fake = FakeEffects(git=["/r\n"])
|
||||
stop, said = self.run_loop(["do", "it"], fake, env)
|
||||
self.assertEqual((stop, said), (Stop(0, ""), f"{STAMP} started item-3, item-4 in the tmux session loop-r\n"))
|
||||
self.assertEqual(fake.tmux_calls, [["-V"], shown])
|
||||
self.assertEqual(self.asked, [(main.LoopRun(0, "/r", "do it", ""), False)])
|
||||
|
||||
def test_hands_the_window_starts_its_paths_environment_launcher_and_effects(self):
|
||||
fake = FakeEffects(git=["/r\n"], on_terminal=False)
|
||||
effects, env, launcher = fake.effects(), {"LOOP_CLAUDE_X": "1"}, pathlib.Path("/b/loop-claude")
|
||||
with unittest.mock.patch.object(main, "start_chunks", return_value=["item-3"]) as start, contextlib.redirect_stdout(io.StringIO()):
|
||||
main.run_loop(["do it"], env, paths.paths_from(self.HOME), launcher, CWD, effects)
|
||||
self.assertEqual(start.call_args.args, (main.LoopRun(0, "/r", "do it", ""), False, paths.paths_from(self.HOME), env, launcher, effects))
|
||||
|
||||
def test_a_window_loop_runs_its_chunk_in_its_own_session_and_window_and_hands_on_once_it_finished(self):
|
||||
fake = FakeEffects(git=["/r\n"])
|
||||
effects, env = fake.effects(), {"TMUX_PANE": "%4"}
|
||||
launcher = pathlib.Path("/b/loop-claude")
|
||||
cycle = unittest.mock.Mock(project="claude-opus-5-5")
|
||||
unfinished = unittest.mock.Mock(verdict=unittest.mock.Mock(spec=Unfinished))
|
||||
finished = unittest.mock.Mock(verdict=unittest.mock.Mock(spec=Finished))
|
||||
closed = [main.LoopRun(1, "/r", "do it", "", chunk="item-3"), main.LoopRun(2, "/r", "do it", "", chunk="item-3")]
|
||||
with unittest.mock.patch.object(main, "fingerprint", return_value=""), unittest.mock.patch.object(main, "exec_if_edited", return_value=None), unittest.mock.patch.object(main, "next_cycle", return_value=cycle) as next_cycle, \
|
||||
unittest.mock.patch.object(main, "run_cycle", side_effect=[unfinished, finished]), unittest.mock.patch.object(main, "closed_cycle", side_effect=closed), \
|
||||
unittest.mock.patch.object(main, "check_routing", return_value=None), unittest.mock.patch.object(main, "handed_on", return_value=Stop(0, "")) as handed_on:
|
||||
stop = main.run_loop(["--chunk", "item-3", "do it"], env, paths.paths_from(self.HOME), launcher, CWD, effects)
|
||||
loop = this_loop.Loop(root="/r", session=session.session_named("A r loop-claude item-3", self.HOME / ".claude" / "projects"), window=tmux.Window("loop-r", "item-3", "%4"), paths=paths.paths_from(self.HOME), env=env, launcher=launcher, effects=effects)
|
||||
self.assertEqual(stop, Stop(0, ""))
|
||||
self.assertEqual([call.args for call in next_cycle.call_args_list], [(main.LoopRun(1, "/r", "do it", "", chunk="item-3"), loop), (main.LoopRun(2, "/r", "do it", "", chunk="item-3"), loop)])
|
||||
handed_on.assert_called_once_with(closed[1], loop)
|
||||
|
||||
def test_a_window_loop_given_no_task_prints_the_help(self):
|
||||
self.assertEqual(main.loop_run_from(["--chunk", "item-3"], CWD, FakeEffects(git=["/r\n"]).effects()), Stop(1, usage.HELP))
|
||||
|
||||
def test_a_window_loop_outside_a_checkout_stops(self):
|
||||
self.assertIsInstance(main.loop_run_from(["--chunk", "item-3", "do it"], CWD, FakeEffects(git=[Failure("git cannot start")]).effects()), Stop)
|
||||
|
||||
def test_says_that_nothing_started_where_the_session_already_runs_every_chunk_that_may(self):
|
||||
self.assertEqual(self.run_loop(["do it"], FakeEffects(git=["/r\n"]), started=())[1], f"{STAMP} the tmux session loop-r runs every chunk that may run now, so `do it` started in no new window\n")
|
||||
|
||||
def test_off_a_terminal_it_prints_how_to_attach(self):
|
||||
fake = FakeEffects(git=["/r\n"], on_terminal=False)
|
||||
stop, said = self.run_loop(["do it"], fake)
|
||||
self.assertEqual(stop, Stop(0, ""))
|
||||
self.assertTrue(said.endswith(f"{STAMP} not on a terminal; see the chunks with `tmux attach -t =loop-r`\n"), said)
|
||||
self.assertEqual(fake.tmux_calls, [["-V"]])
|
||||
|
||||
def test_stops_where_no_chunk_could_start(self):
|
||||
self.assertEqual(self.run_loop(["do it"], FakeEffects(git=["/r\n"]), started=Failure("no plan"))[0], Stop(1, "no plan"))
|
||||
|
||||
def test_stops_where_tmux_cannot_show_the_session(self):
|
||||
fake = FakeEffects(git=["/r\n"])
|
||||
effects = dataclasses.replace(fake.effects(), tmux_on_terminal=lambda args: 1)
|
||||
with unittest.mock.patch.object(main, "start_chunks", return_value=["item-3"]), contextlib.redirect_stdout(io.StringIO()):
|
||||
stop = main.run_loop(["do it"], {}, paths.paths_from(self.HOME), pathlib.Path("/b/loop-claude"), CWD, effects)
|
||||
self.assertEqual(stop, Stop(1, "`tmux attach-session -t =loop-r` failed; the chunks go on in the tmux session"))
|
||||
|
||||
def test_a_window_loop_outside_tmux_stops(self):
|
||||
fake = FakeEffects(git=["/r\n"])
|
||||
self.assertEqual(self.run_loop(["--chunk", "item-3", "do it"], fake)[0], Stop(1, "--chunk is how loop-claude starts itself in a tmux window; run loop-claude <task>"))
|
||||
self.assertEqual(self.asked, [])
|
||||
|
||||
def test_reads_the_chunk_a_window_loop_is_started_with(self):
|
||||
self.assertEqual(main.loop_run_from(["--chunk", "item-3", "do", "it"], CWD, FakeEffects(git=["/r\n"]).effects()), main.LoopRun(0, "/r", "do it", "", chunk="item-3"))
|
||||
self.assertEqual(main.loop_run_from(["do", "it"], CWD, FakeEffects(git=["/r\n"]).effects()), main.LoopRun(0, "/r", "do it", ""))
|
||||
|
||||
def test_a_finished_chunk_starts_each_chunk_that_may_start_and_stops_without_a_reason(self):
|
||||
loop_run = main.LoopRun(4, "/r", "do it", "", chunk="item-7")
|
||||
for started, said, stop in ((["item-9", "item-12"], "the chunk finished; started item-9, item-12", Stop(0, "")), ([], "the chunk finished; started no other, since the chunks running fill what may run now", Stop(0, "")),
|
||||
(Failure("no plan"), "", Stop(1, "the chunk finished, but the next could not start: no plan"))):
|
||||
with self.subTest(started=started), unittest.mock.patch.object(main, "start_chunks", return_value=started) as start, contextlib.redirect_stdout(io.StringIO()) as printed:
|
||||
loop = a_loop(FakeEffects().effects(), env={"LOOP_CLAUDE_X": "1"})
|
||||
self.assertEqual(main.handed_on(loop_run, loop), stop)
|
||||
self.assertEqual(printed.getvalue(), f"{STAMP} {said}\n" if said else "")
|
||||
self.assertEqual(start.call_args.args, (loop_run, True, loop.paths, loop.env, loop.launcher, loop.effects))
|
||||
|
||||
|
||||
class StopDms(unittest.TestCase):
|
||||
def run_main(self, argv, fake):
|
||||
with tempfile.TemporaryDirectory() as home, contextlib.redirect_stderr(io.StringIO()) as said, contextlib.redirect_stdout(io.StringIO()):
|
||||
@@ -1942,6 +2329,12 @@ class StopDms(unittest.TestCase):
|
||||
self.assertEqual(self.run_main(["do it"], fake)[0], 2)
|
||||
self.assertEqual(fake.dms, [f"loop-claude in {CWD} stopped: the human is needed to look at the chunk, but it stayed unfinished"])
|
||||
|
||||
def test_skips_the_dm_of_a_stop_without_a_reason_as_once_the_windows_started(self):
|
||||
fake = FakeEffects()
|
||||
with unittest.mock.patch.object(main, "run_loop", return_value=Stop(0, "")):
|
||||
self.assertEqual(self.run_main(["do it"], fake), (0, ""))
|
||||
self.assertEqual(fake.dms, [])
|
||||
|
||||
def test_skips_the_dm_where_ctrl_c_stopped_the_loop(self):
|
||||
fake = FakeEffects()
|
||||
with unittest.mock.patch.object(main, "run_loop", side_effect=KeyboardInterrupt):
|
||||
@@ -2019,7 +2412,11 @@ class ExitContract(unittest.TestCase):
|
||||
("cycle/run.py", "close", "1", "failure.reason", read),
|
||||
("cycle/run.py", "close", "1", "failure.reason", "a finished chunk's session cannot be deleted"),
|
||||
("loop/close.py", "closed_cycle", "1", "failure.reason", read),
|
||||
("loop/main.py", "run_loop", "1", "held.reason", "its slot in the project cannot be taken"),
|
||||
("loop/main.py", "run_loop", "1", "reason", "tmux is missing or older than 3.2"),
|
||||
("loop/main.py", "run_loop", "1", "f'{CHUNK_FLAG} is how loop-claude starts itself", "--chunk is given outside a tmux window"),
|
||||
("loop/main.py", "windows_opened", "1", "started.reason", "a chunk's window cannot be started"),
|
||||
("loop/main.py", "windows_opened", "1", "f\"`tmux {' '.join(shown)}` failed", "the tmux session cannot be put on the terminal"),
|
||||
("loop/main.py", "handed_on", "1", "f'the chunk finished, but the next could not start", "a chunk's window cannot be started"),
|
||||
("loop/main.py", "next_cycle", "1", "premises.reason", premises_),
|
||||
("loop/main.py", "next_cycle", "1", "records.reason", unreadable),
|
||||
("loop/main.py", "next_cycle", "1", "ladder_file.reason", premises_),
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
"""The tmux commands loop-claude runs: each chunk's loop runs in its own window of one tmux session named for the project (docs/decisions.md → `loop-claude: each chunk runs in its own tmux window`)."""
|
||||
import dataclasses
|
||||
import re
|
||||
import subprocess
|
||||
import typing
|
||||
|
||||
from failure import Failure
|
||||
|
||||
# Runs tmux with these arguments and returns what it printed; exit 127 where tmux cannot start.
|
||||
Tmux = typing.Callable[[list[str]], subprocess.CompletedProcess[str]]
|
||||
|
||||
# The oldest tmux that has every command and option used here. Its CHANGES file dates the newest two to 3.2: `remain-on-exit failed` and `new-session -e`.
|
||||
NEEDED = (3, 2)
|
||||
# What a window's name ends in while its chunk waits for the human. tmux's status bar shows the name, and `!` after it once the bell rang.
|
||||
WAITS = " ?"
|
||||
BELL = "\a"
|
||||
# The session option that names the checkout whose chunks the session runs, since two checkouts' keys may map to one session name.
|
||||
OWNER = "@loop-root"
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Window:
|
||||
"""The tmux window a chunk's loop runs in."""
|
||||
session: str
|
||||
# Without WAITS.
|
||||
name: str
|
||||
# The ID of the loop's pane, which $TMUX_PANE holds. It targets the window whatever its name is.
|
||||
pane: str
|
||||
|
||||
@property
|
||||
def target(self) -> str:
|
||||
"""What `tmux attach -t` and `tmux select-window -t` take to reach the window."""
|
||||
return f"{self.session}:{self.name}"
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Listed:
|
||||
"""A window of the project's session, as tmux lists it."""
|
||||
# Without WAITS.
|
||||
name: str
|
||||
# tmux's ID of the window, such as `@3`.
|
||||
id: str
|
||||
# Whether its loop has exited: `remain-on-exit failed` keeps the window of a loop that failed, so its last lines stay readable.
|
||||
dead: bool
|
||||
|
||||
|
||||
def unusable(run: Tmux) -> str | None:
|
||||
"""Why loop-claude cannot use this machine's tmux, naming the version found and the one needed; None where it is NEEDED or later."""
|
||||
found = run(["-V"]).stdout.strip()
|
||||
version = re.search(r"([0-9]+)\.([0-9]+)", found)
|
||||
if version and (int(version[1]), int(version[2])) >= NEEDED:
|
||||
return None
|
||||
return f"loop-claude runs each chunk in a tmux window, and needs tmux {NEEDED[0]}.{NEEDED[1]} or later; it found {found or 'no tmux'}"
|
||||
|
||||
|
||||
def session_name(key: str) -> str:
|
||||
"""The tmux session of the project with this key, such as `loop-claude-config`. tmux reads `.` and `:` in a target as separators, so every character but a letter, a digit, `_` and `-` becomes a dash."""
|
||||
return "loop-" + re.sub(r"[^A-Za-z0-9_-]", "-", key)
|
||||
|
||||
|
||||
def listed(session: str, run: Tmux) -> list[Listed]:
|
||||
"""The windows of session; none where tmux lists none, as while the session doesn't exist or no tmux server runs."""
|
||||
done = run(["list-windows", "-t", f"={session}", "-F", "#{window_name}\t#{pane_dead}\t#{window_id}"])
|
||||
rows = [line.split("\t") for line in done.stdout.splitlines()] if done.returncode == 0 else []
|
||||
return [Listed(row[0].removesuffix(WAITS), row[2], row[1] == "1") for row in rows if len(row) == 3]
|
||||
|
||||
|
||||
def start_window(window: Window, cwd: str, env: typing.Mapping[str, str], command: list[str], first: bool, run: Tmux) -> Failure | None:
|
||||
"""Starts command in a new window of window's session, in cwd with env added to its environment, and leaves the client where it is. first makes the session too. A Failure says why tmux started none."""
|
||||
make = ["new-session", "-d", "-s", window.session] if first else ["new-window", "-d", "-t", f"={window.session}:"]
|
||||
variables = [flag for name, value in env.items() for flag in ("-e", f"{name}={value}")]
|
||||
# tmux reads a `;` that ends an argument as the end of the command, unless a backslash precedes it.
|
||||
words = [re.sub(r";$", r"\\;", word) for word in command]
|
||||
done = run([*make, "-n", window.name, "-c", cwd, *variables, "-P", "-F", "#{window_id}", "--", *words])
|
||||
if done.returncode:
|
||||
return Failure(f"tmux could not start the window {window.target}: {done.stderr.strip() or f'it exited {done.returncode}'}")
|
||||
if first:
|
||||
# set-option and show-options read a target as a pane's, so `=session` alone names no session.
|
||||
run(["set-option", "-t", f"={window.session}:", OWNER, cwd])
|
||||
# By the ID, since a window of the same name may still be closing. A loop that fails before the option is set closes its window, and its stop is still sent as a DM.
|
||||
run(["set-option", "-w", "-t", done.stdout.strip(), "remain-on-exit", "failed"])
|
||||
return None
|
||||
|
||||
|
||||
def owner(session: str, run: Tmux) -> str:
|
||||
"""The checkout whose chunks session runs, as OWNER names it; empty where it names none."""
|
||||
return run(["show-options", "-qv", "-t", f"={session}:", OWNER]).stdout.strip()
|
||||
|
||||
|
||||
def close(window: Listed, run: Tmux) -> None:
|
||||
run(["kill-window", "-t", window.id])
|
||||
|
||||
|
||||
def mark(window: Window, waits: bool, run: Tmux) -> None:
|
||||
"""Renames window to end in WAITS while its chunk waits for the human, and back once it doesn't."""
|
||||
run(["rename-window", "-t", window.pane, window.name + (WAITS if waits else "")])
|
||||
|
||||
|
||||
def show(session: str, inside: bool) -> list[str]:
|
||||
"""The tmux arguments that put session on the human's terminal: inside tmux the client switches to it, and outside a new client attaches."""
|
||||
return ["switch-client" if inside else "attach-session", "-t", f"={session}"]
|
||||
@@ -51,6 +51,10 @@ class Effects:
|
||||
python: typing.Callable[[list[str], str], subprocess.CompletedProcess[str]]
|
||||
sleep: typing.Callable[[float], None]
|
||||
stream_claude: typing.Callable[[list[str], str, dict[str, str]], Streaming]
|
||||
# Runs tmux with these arguments, as run_tmux does.
|
||||
tmux: typing.Callable[[list[str]], subprocess.CompletedProcess[str]]
|
||||
# Runs tmux on the terminal, as to attach a session, and returns its exit code once the human detaches.
|
||||
tmux_on_terminal: typing.Callable[[list[str]], int]
|
||||
|
||||
|
||||
class StreamingClaude:
|
||||
@@ -82,6 +86,8 @@ def system_effects(backends: typing.Mapping[Notifier, Backend[typing.Any]] = BAC
|
||||
python=lambda args, cwd: run_python(args, cwd, PYTHON_TIMEOUT),
|
||||
sleep=time.sleep,
|
||||
stream_claude=StreamingClaude,
|
||||
tmux=run_tmux,
|
||||
tmux_on_terminal=lambda args: subprocess.run(["tmux", *args]).returncode,
|
||||
)
|
||||
|
||||
|
||||
@@ -106,6 +112,15 @@ def run_python(args: list[str], cwd: str, timeout: float) -> subprocess.Complete
|
||||
return subprocess.CompletedProcess(command, 1, "", f"stopped after {timeout} s")
|
||||
|
||||
|
||||
def run_tmux(args: list[str]) -> subprocess.CompletedProcess[str]:
|
||||
"""Runs tmux and returns what it printed. A tmux that cannot start, as where none is installed, reads as exit 127, saying why on stderr."""
|
||||
command = ["tmux", *args]
|
||||
try:
|
||||
return subprocess.run(command, capture_output=True, encoding="utf-8", errors="replace", stdin=subprocess.DEVNULL)
|
||||
except OSError as failure:
|
||||
return subprocess.CompletedProcess(command, 127, "", f"could not start: {failure}")
|
||||
|
||||
|
||||
def say(text: str, effects: Effects, *, stdout: bool = False) -> None:
|
||||
"""Prints text on stderr, or on stdout where stdout, opening the first line of words with the machine's local time. Blank lines before those words stay blank, and later lines get no time."""
|
||||
body = text.lstrip("\n")
|
||||
|
||||
@@ -84,6 +84,36 @@ class ClaudeOnTerminal(unittest.TestCase):
|
||||
|
||||
|
||||
|
||||
class TmuxEffect(unittest.TestCase):
|
||||
"""Each test runs a fake tmux off its own PATH, without $TMUX, so the human's tmux server is never reached."""
|
||||
|
||||
def fake_tmux(self, folder):
|
||||
tmux = pathlib.Path(folder, "tmux")
|
||||
tmux.write_text(f"#!{sys.executable}\nimport sys\nprint(' '.join(sys.argv[1:]))\nsys.exit(4)\n")
|
||||
tmux.chmod(0o755)
|
||||
return unittest.mock.patch.dict(os.environ, {"PATH": folder, "TMUX": "", "TMUX_PANE": ""})
|
||||
|
||||
def test_runs_tmux_and_returns_what_it_printed(self):
|
||||
with tempfile.TemporaryDirectory() as folder, self.fake_tmux(folder):
|
||||
done = system_effects().tmux(["list-windows", "-t", "=loop-proj"])
|
||||
self.assertEqual((done.returncode, done.stdout), (4, "list-windows -t =loop-proj\n"))
|
||||
|
||||
def test_reads_output_that_is_not_utf_8_with_each_bad_byte_replaced(self):
|
||||
with tempfile.TemporaryDirectory() as folder, self.fake_tmux(folder):
|
||||
pathlib.Path(folder, "tmux").write_text(f"#!{sys.executable}\nimport sys\nsys.stdout.buffer.write(b'caf\\xe9')\n")
|
||||
self.assertEqual(system_effects().tmux(["list-windows"]).stdout, "caf\ufffd")
|
||||
|
||||
def test_reads_a_tmux_that_cannot_start_as_exit_127(self):
|
||||
with tempfile.TemporaryDirectory() as folder, unittest.mock.patch.dict(os.environ, {"PATH": folder}):
|
||||
done = system_effects().tmux(["-V"])
|
||||
self.assertEqual((done.args, done.returncode, done.stdout), (["tmux", "-V"], 127, ""))
|
||||
self.assertIn("could not start", done.stderr)
|
||||
|
||||
def test_runs_tmux_on_the_terminal_and_returns_its_exit_code(self):
|
||||
with tempfile.TemporaryDirectory() as folder, self.fake_tmux(folder), contextlib.redirect_stdout(io.StringIO()):
|
||||
self.assertEqual(system_effects().tmux_on_terminal(["attach-session", "-t", "=loop-proj"]), 4)
|
||||
|
||||
|
||||
class PythonEffect(unittest.TestCase):
|
||||
def test_runs_a_script_in_the_given_directory(self):
|
||||
with tempfile.TemporaryDirectory() as cwd:
|
||||
|
||||
@@ -28,12 +28,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 the lowest slot this call locked; None while every slot is held. Raises OSError where a slot file cannot be opened or locked."""
|
||||
return first_free_slot(folder, range(slots))
|
||||
|
||||
|
||||
def first_free_slot(folder: pathlib.Path, order: typing.Iterable[int]) -> tuple[int, int] | None:
|
||||
"""The number and open file of the first slot in order that this call locked; None while every slot in order is held. Raises OSError where a slot file cannot be opened or locked."""
|
||||
for slot in order:
|
||||
for slot in range(slots):
|
||||
fd = os.open(folder / f"slot-{slot}", os.O_RDWR | os.O_CREAT, 0o644)
|
||||
try:
|
||||
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
|
||||
@@ -72,6 +72,13 @@ class PlanStoreContract:
|
||||
self.assertEqual(self.items(store)[id_].release, release_of("0.3.0"))
|
||||
self.assertEqual(self.items(store)[id_].detail, "")
|
||||
|
||||
def test_an_edit_with_a_comment_sets_the_fields_as_one_without(self) -> None:
|
||||
store = self.new_store()
|
||||
id_ = self.filed(store, FIRST, "Why it counts.")
|
||||
self.assertEqual(store.edit(id_, {"L": "2"}, None, "A small change to one module."), Written(id_))
|
||||
item = self.items(store)[id_]
|
||||
self.assertEqual((item.scores["L"], item.detail), (2, "Why it counts."))
|
||||
|
||||
def test_finish_removes_the_item_and_keeps_the_others(self) -> None:
|
||||
store = self.new_store()
|
||||
first, second = self.filed(store, FIRST, "Why it counts."), self.filed(store, SECOND, "Later detail.")
|
||||
|
||||
@@ -12,6 +12,8 @@ class MemoryPlan:
|
||||
"""A plan held in memory, as a tracker holds one: in the order filed, unranked, with no bar. Where fails is set, every read and write fails with it as the reason."""
|
||||
rows: dict[int, dict[str, str]] = dataclasses.field(default_factory=dict)
|
||||
details: dict[int, str] = dataclasses.field(default_factory=dict)
|
||||
# Each comment an edit gave, under its item's ID, as a tracker posts them on the item's issue.
|
||||
comments: dict[int, list[str]] = dataclasses.field(default_factory=dict)
|
||||
next_id: int = 1
|
||||
label: str = "the plan in memory"
|
||||
tracked: str | None = None
|
||||
@@ -26,10 +28,13 @@ class MemoryPlan:
|
||||
def add(self, fields: dict[str, str], detail: str) -> Written | Failure:
|
||||
return self.put(self.next_id, cells(fields), detail)
|
||||
|
||||
def edit(self, id_: int, fields: dict[str, str], detail: str | None) -> Written | Failure:
|
||||
def edit(self, id_: int, fields: dict[str, str], detail: str | None, comment: str | None = None) -> Written | Failure:
|
||||
if id_ not in self.rows:
|
||||
return Failure(f"{self.label} holds no item {id_}")
|
||||
return self.put(id_, self.rows[id_] | cells(fields), self.details.get(id_, "") if detail is None else detail)
|
||||
written = self.put(id_, self.rows[id_] | cells(fields), self.details.get(id_, "") if detail is None else detail)
|
||||
if comment is not None and isinstance(written, Written):
|
||||
self.comments.setdefault(id_, []).append(comment)
|
||||
return written
|
||||
|
||||
def finish(self, id_: int) -> Written | Failure:
|
||||
if self.fails or id_ not in self.rows:
|
||||
|
||||
+187
-25
@@ -1,8 +1,8 @@
|
||||
"""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."""
|
||||
`add` files an item as a new child issue, marked with FILED_BY, and ranks it among the issues the loop filed, by the score the config's formula gives, as `placing` says. `finish` moves an item's issue to a done status. `edit` changes an issue the loop filed, but never its links. Of an issue a person filed it sets only the scores, with a comment that tells the team why."""
|
||||
import base64
|
||||
import dataclasses
|
||||
import pathlib
|
||||
@@ -17,6 +17,7 @@ from project_config.settings import Epic, Finish, JIRA_FINISH_STATUS, JIRA_FINIS
|
||||
from failure import Failure
|
||||
from rest_client import json_request
|
||||
from release_plan.release import parsed, Release, tagged
|
||||
from release_plan import ranking
|
||||
from rest_client.env_file import read_env
|
||||
|
||||
# One pair of keys for Jira and Confluence: one Atlassian account's API token opens both.
|
||||
@@ -29,8 +30,7 @@ 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,6 +43,12 @@ 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"
|
||||
# What a failed edit ends with, for the same reason.
|
||||
PERHAPS_EDITED = "unless Jira refused the request, the issue may have changed: look at {key} before editing the item again"
|
||||
# The scores a caller sets, L, E, I and S; R is worked out from them.
|
||||
SET_SCORES = tuple(name for name in SHAPE.score_columns if name not in SHAPE.derived)
|
||||
# The fields of PROPERTY's value that an edit may set.
|
||||
SCORED = (*SET_SCORES, MOVES, "Exempt")
|
||||
|
||||
# Sends a request with the Authorization header given, the body as JSON where there is one, and returns the JSON answer, None where the answer has no body, or a Failure saying why there is none.
|
||||
Http = typing.Callable[[str, str, str, object], object]
|
||||
@@ -50,6 +56,11 @@ ToMarkdown = typing.Callable[[list[dict[str, typing.Any]]], list[str] | Refused
|
||||
ToAdf = typing.Callable[[str], dict[str, typing.Any] | Failure]
|
||||
|
||||
|
||||
class ReadsScoring(typing.Protocol):
|
||||
def read(self) -> ranking.Scoring | Failure:
|
||||
"""The scoring `add` scores an item by: the config's formula and bar, with the goal weights that the goals file, the decision log and the comprehension history give."""
|
||||
|
||||
|
||||
def http_json(method: str, url: str, authorization: str, body: object) -> object:
|
||||
return json_request.http_json(method, url, authorization, body, TIMEOUT, error_message)
|
||||
|
||||
@@ -90,6 +101,8 @@ class JiraPlan:
|
||||
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,12 +123,18 @@ class JiraPlan:
|
||||
return next((issue for issue in issues if isinstance(issue, Failure)), None) or plan_of([issue for issue in issues if isinstance(issue, Issue)], self.epic, self.to_markdown)
|
||||
|
||||
def add(self, fields: dict[str, str], detail: str) -> Written | Failure:
|
||||
"""Files the item as a child issue, which Jira ranks last in the backlog. No bar applies and the goals file isn't read, since a plan in Jira has no place for a formula or a bar yet (todo.md's item 384).
|
||||
"""Files the item as a child issue, where it scores at the config's bar or above or is exempt, and ranks it as `placing` says.
|
||||
|
||||
Jira takes the links after the issue. A link it refuses leaves the issue filed, so the write counts as landed, and a note names each link to make by hand."""
|
||||
Jira takes the links and the rank after the issue. One it refuses leaves the issue filed, so the write counts as landed, and a note says what to do by hand."""
|
||||
filing = filing_of(fields, detail, self.epic)
|
||||
if isinstance(filing, Failure):
|
||||
return filing
|
||||
scoring = self.scoring.read()
|
||||
if isinstance(scoring, Failure):
|
||||
return Failure(f"cannot score the item to file: {scoring.reason}")
|
||||
value = filed_score(filing.item, scoring)
|
||||
if isinstance(value, Failure):
|
||||
return value
|
||||
authorization = basic_auth(self.env_file)
|
||||
if isinstance(authorization, Failure):
|
||||
return authorization
|
||||
@@ -128,21 +147,44 @@ class JiraPlan:
|
||||
version = self.fix_version(filing.release, authorization)
|
||||
if isinstance(version, Failure):
|
||||
return version
|
||||
if filing.blockers and (missing := self.missing_blocker(filing.blockers, authorization)):
|
||||
return missing
|
||||
answered = children(self.epic, authorization, self.http)
|
||||
if isinstance(answered, Failure):
|
||||
return answered
|
||||
held = {raw.get("key") for raw in answered if isinstance(raw, dict)}
|
||||
# `item` reads only an open child as a blocker, so a link to any other issue would be lost on the next read.
|
||||
if missing := next((blocker for blocker in filing.blockers if blocker not in held), None):
|
||||
return Failure(f"{self.label} holds no item {number(missing)} to be blocked by")
|
||||
before = placing(answered, filing.item, value, scoring)
|
||||
created = self.http("POST", f"{self.epic.site}/rest/api/3/issue", authorization, {"fields": issue_fields | {"fixVersions": [{"name": version}]}, "properties": [{"key": PROPERTY, "value": filing.scores}]})
|
||||
if isinstance(created, Failure):
|
||||
return Failure(f"cannot file the item under {self.epic.key}: {created.reason}; {PERHAPS_FILED.format(epic=self.epic.key)}")
|
||||
key = created.get("key") if isinstance(created, dict) else None
|
||||
if not isinstance(key, str) or not ISSUE_KEY.fullmatch(key) or project_of(key) != project_of(self.epic.key):
|
||||
return Failure(f"Jira answered the new issue without an issue key in {project_of(self.epic.key)}; {PERHAPS_FILED.format(epic=self.epic.key)}")
|
||||
return Written(number(key), self.linked_and_ranked(key, filing.blockers, before, authorization))
|
||||
|
||||
def linked_and_ranked(self, key: str, blockers: tuple[str, ...], before: str | None | Failure, authorization: str) -> tuple[str, ...]:
|
||||
"""Links the filed issue named key as blocked by each of blockers, and ranks it just before the issue named before; a note for each Jira refuses."""
|
||||
notes = []
|
||||
for blocker in filing.blockers:
|
||||
for blocker in blockers:
|
||||
# Jira names the two ends by the link type's sides: the inward issue blocks the outward one, which then reads "is blocked by" it.
|
||||
linked = self.http("POST", f"{self.epic.site}/rest/api/3/issueLink", authorization, {"type": {"name": BLOCKS}, "inwardIssue": {"key": blocker}, "outwardIssue": {"key": key}})
|
||||
if isinstance(linked, Failure):
|
||||
notes.append(f"filed {key}, but cannot link it as blocked by {blocker}: {linked.reason}; link it in Jira")
|
||||
return Written(number(key), tuple(notes))
|
||||
if isinstance(before, Failure):
|
||||
notes.append(f"filed {key}, but cannot rank it: {before.reason}; rank it in Jira")
|
||||
elif before is not None and (refused := self.rank_refusal(key, before, authorization)):
|
||||
notes.append(f"filed {key}, but cannot rank it before {before}: {refused}; rank it in Jira")
|
||||
return tuple(notes)
|
||||
|
||||
def rank_refusal(self, key: str, before: str, authorization: str) -> str | None:
|
||||
"""Ranks the issue named key just before the issue named before; why Jira refused, or None where it didn't. Jira answers a rank it made with no body, and one it refused with an error, or with an entry per issue that holds the errors."""
|
||||
answer = self.http("PUT", f"{self.epic.site}/rest/agile/1.0/issue/rank", authorization, {"issues": [key], "rankBeforeIssue": before})
|
||||
if isinstance(answer, Failure):
|
||||
return answer.reason
|
||||
entries = answer.get("entries") if isinstance(answer, dict) else None
|
||||
refused = [entry for entry in entries if isinstance(entry, dict) and entry.get("status") != 200] if isinstance(entries, list) else []
|
||||
return "; ".join(str(error) for entry in refused for error in entry.get("errors") or [f"Jira answered {entry.get('status')}"]) or None
|
||||
|
||||
def fix_version(self, release: str, authorization: str) -> str | Failure:
|
||||
"""The name of the Jira project's Fix Version for release, which a project may spell with a leading v, as `earliest_release` reads it."""
|
||||
@@ -151,18 +193,50 @@ class JiraPlan:
|
||||
if isinstance(versions, Failure):
|
||||
return Failure(f"cannot read {project}'s Fix Versions: {versions.reason}")
|
||||
names = {name for version in versions if isinstance(version, dict) and isinstance(name := version.get("name"), str)} if isinstance(versions, list) else set()
|
||||
return next((name for name in (release, f"v{release}") if name in names), None) or Failure(f"the Jira project {project} has no Fix Version {release} or v{release}; create it in Jira, or file the item under a release it has")
|
||||
return next((name for name in (release, f"v{release}") if name in names), None) or Failure(f"the Jira project {project} has no Fix Version {release} or v{release}; create it in Jira, or name a release it has")
|
||||
|
||||
def missing_blocker(self, blockers: tuple[str, ...], authorization: str) -> Failure | None:
|
||||
"""A Failure naming the first of blockers that is no open child of the epic. `item` reads only an open child as a blocker, so a link to any other issue would be lost on the next read."""
|
||||
def edit(self, id_: int, fields: dict[str, str], detail: str | None, comment: str | None = None) -> Written | Failure:
|
||||
"""Sets the fields and the detail in one request, so Jira takes all of the edit or none, and then posts comment on the issue. `revision_of` says what an edit may set.
|
||||
|
||||
A comment Jira refuses leaves the edit made, so the write counts as landed, and a note says to post the comment by hand."""
|
||||
authorization = basic_auth(self.env_file)
|
||||
if isinstance(authorization, Failure):
|
||||
return authorization
|
||||
answered = children(self.epic, authorization, self.http)
|
||||
if isinstance(answered, Failure):
|
||||
return answered
|
||||
held = {raw.get("key") for raw in answered if isinstance(raw, dict)}
|
||||
return next((Failure(f"{self.label} holds no item {number(blocker)} to be blocked by") for blocker in blockers if blocker not in held), None)
|
||||
|
||||
def edit(self, id_: int, fields: dict[str, str], detail: str | None) -> Written | Failure:
|
||||
return Failure(READ_ONLY)
|
||||
key = f"{project_of(self.epic.key)}-{id_}"
|
||||
raw = next((raw for raw in answered if isinstance(raw, dict) and raw.get("key") == key), None)
|
||||
if raw is None:
|
||||
return Failure(f"{self.label} holds no item {id_}")
|
||||
issue = issue_of(raw)
|
||||
if isinstance(issue, Failure):
|
||||
return issue
|
||||
revision = revision_of(issue, cells(fields), detail, comment)
|
||||
if isinstance(revision, Failure):
|
||||
return revision
|
||||
body = revision.body
|
||||
if detail is not None:
|
||||
description = self.to_adf(detail) if detail.strip() else None
|
||||
if isinstance(description, Failure):
|
||||
return Failure(f"cannot convert the item's detail to a Jira description: {description.reason}")
|
||||
body = body | {"fields": body.get("fields", {}) | {"description": description}}
|
||||
said = self.to_adf(comment) if comment and comment.strip() else None
|
||||
if isinstance(said, Failure):
|
||||
return Failure(f"cannot convert the comment to a Jira comment: {said.reason}")
|
||||
if revision.release is not None:
|
||||
version = self.fix_version(revision.release, authorization)
|
||||
if isinstance(version, Failure):
|
||||
return version
|
||||
body = body | {"fields": body.get("fields", {}) | {"fixVersions": [{"name": version}]}}
|
||||
url = f"{self.epic.site}/rest/api/3/issue/{key}"
|
||||
edited = self.http("PUT", url, authorization, body)
|
||||
if isinstance(edited, Failure):
|
||||
return Failure(f"cannot edit {key}: {edited.reason}; {PERHAPS_EDITED.format(key=key)}")
|
||||
if said is None:
|
||||
return Written(id_)
|
||||
posted = self.http("POST", f"{url}/comment", authorization, {"body": said})
|
||||
return Written(id_, (f"edited {key}, but cannot post the comment: {posted.reason}; post it in Jira",) if isinstance(posted, Failure) else ())
|
||||
|
||||
def finish(self, id_: int) -> Written | Failure:
|
||||
"""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."""
|
||||
@@ -198,6 +272,8 @@ class Filing:
|
||||
scores: dict[str, typing.Any]
|
||||
# The key of each issue the item is blocked by.
|
||||
blockers: tuple[str, ...]
|
||||
# The item as ranking scores it, under the ID 0, since Jira numbers it once filed.
|
||||
item: Item
|
||||
|
||||
|
||||
def filing_of(fields: dict[str, str], detail: str, epic: Epic) -> Filing | Failure:
|
||||
@@ -209,15 +285,16 @@ def filing_of(fields: dict[str, str], detail: str, epic: Epic) -> Filing | Failu
|
||||
if unfit := unfit_text(summary, detail):
|
||||
return unfit
|
||||
release = named.get("Release", "")
|
||||
if parsed(release) is None:
|
||||
version = parsed(release)
|
||||
if version is None:
|
||||
return Failure(f"the item's Release {release!r} is not a version such as 1.2.0")
|
||||
# Named so the shared messages read "item to file's L": they open with "item" and an ID, which this item has none of yet.
|
||||
levels = parse_scores("to file", named, SHAPE.score_columns)
|
||||
if isinstance(levels, Failure):
|
||||
return levels
|
||||
moves, exempt = named.get(MOVES, ""), named.get("Exempt", "")
|
||||
if isinstance(unfit_moves := parse_moves("to file", moves), Failure):
|
||||
return unfit_moves
|
||||
if isinstance(parsed_moves := parse_moves("to file", moves), Failure):
|
||||
return parsed_moves
|
||||
if not is_exempt(exempt):
|
||||
return Failure(f"the item's Exempt {exempt!r} is not empty or one of {', '.join(EXEMPTIONS[1:])}")
|
||||
blockers = parse_ids(named.get(BLOCKED_BY, ""))
|
||||
@@ -228,7 +305,93 @@ def filing_of(fields: dict[str, str], detail: str, epic: Epic) -> Filing | Failu
|
||||
if exempt == SECURITY:
|
||||
issue_fields["labels"] = [SECURITY]
|
||||
value = levels | {MOVES: moves, "Exempt": exempt, FILED_BY[0]: FILED_BY[1]}
|
||||
return Filing(issue_fields, release, value, tuple(f"{project}-{blocker}" for blocker in blockers))
|
||||
return Filing(issue_fields, release, value, tuple(f"{project}-{blocker}" for blocker in blockers), Item(0, version, exempt, summary, levels, parsed_moves, blockers))
|
||||
|
||||
|
||||
def filed_score(item: Item, scoring: ranking.Scoring) -> float | Failure:
|
||||
"""The item's score, or why it may not be filed: it lacks a score the formula may use, names a goal it may not, or scores under the bar without being exempt."""
|
||||
if missing := next((name for name in SET_SCORES if name not in item.scores), None):
|
||||
return Failure(f"the item to file has no {missing}: score it on {', '.join(SET_SCORES[:-1])} and {SET_SCORES[-1]}")
|
||||
value = ranking.item_score(item, scoring, "the item to file")
|
||||
if not isinstance(value, Failure) and ranking.falls_under(item, value, scoring.bar):
|
||||
return Failure(f"the item to file scores {value:.1f}, under the bar {scoring.bar:g}; don't file it, or mark it with a reason the bar doesn't apply")
|
||||
return value
|
||||
|
||||
|
||||
def placing(answered: list[object], new: Item, value: float, scoring: ranking.Scoring) -> str | None | Failure:
|
||||
"""The key of the issue to rank the new item, which scores value, just before; None where it stays last, where Jira files it. answered is the epic's open children in backlog order.
|
||||
|
||||
Only the issues the loop filed count, so the team's rank of every other issue stays as it is. The new item goes before the first of them that ranks after it as todo.md orders a release's items, blockers aside: a question first, then a security finding, as ranking.FIRST orders them, then the higher score. A tie goes after the older issue. Release doesn't count, as docs/decisions.md records."""
|
||||
place = (ranking.FIRST.get(new.exempt, len(ranking.FIRST)), -value)
|
||||
for raw in answered:
|
||||
issue = issue_of(raw)
|
||||
if isinstance(issue, Failure):
|
||||
return issue
|
||||
if not isinstance(issue.scores, dict) or issue.scores.get(FILED_BY[0]) != FILED_BY[1]:
|
||||
continue
|
||||
scored = scores(issue.key, issue.scores)
|
||||
if isinstance(scored, Failure):
|
||||
return scored
|
||||
levels, moves, exempt = scored
|
||||
if missing := next((name for name in SET_SCORES if name not in levels), None):
|
||||
return Failure(f"{issue.key} holds no {missing}")
|
||||
# Only the scores and the moves change a score.
|
||||
other = ranking.item_score(dataclasses.replace(new, scores=levels, moves=moves), scoring, issue.key)
|
||||
if isinstance(other, Failure):
|
||||
return other
|
||||
if (ranking.FIRST.get(exempt, len(ranking.FIRST)), -other) > place:
|
||||
return issue.key
|
||||
return None
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Revision:
|
||||
"""An edit checked as far as the issue and the flags allow. The description, the comment and the Fix Version's name still need the codec or a request."""
|
||||
# The body of the request that edits the issue, without its description and its Fix Version.
|
||||
body: dict[str, typing.Any]
|
||||
# The release to move the issue to; None where the edit names none.
|
||||
release: str | None
|
||||
|
||||
|
||||
def revision_of(issue: Issue, named: dict[str, str], detail: str | None, comment: str | None) -> Revision | Failure:
|
||||
"""The edit of issue that sets the cells in named, and the detail unless None, or why it cannot be made.
|
||||
|
||||
The summary, description and Fix Version of an issue a person filed are the team's, so there an edit may set only SCORED. Jira's screens don't show PROPERTY, so such an edit needs a comment, which tells the team. L, E, I and S are set together, so no issue is left partly scored. An issue the loop filed also keeps the label SECURITY in step with its Exempt. No edit changes a link."""
|
||||
held = issue.scores
|
||||
if not isinstance(held, dict):
|
||||
return Failure(f"{issue.key}'s issue property {PROPERTY} is not a JSON object")
|
||||
if BLOCKED_BY in named:
|
||||
return Failure(f"the loop doesn't change an issue's links: link {issue.key} in Jira")
|
||||
own = held.get(FILED_BY[0]) == FILED_BY[1]
|
||||
if not own and ("Item" in named or "Release" in named or detail is not None):
|
||||
return Failure(f"a person filed {issue.key}, so the loop sets only its scores: change its summary, description and Fix Version in Jira")
|
||||
if not own and not (comment and comment.strip()):
|
||||
return Failure(f"a person filed {issue.key}, and Jira doesn't show its team the scores: pass a comment saying that it is scored, and why")
|
||||
body: dict[str, typing.Any] = {}
|
||||
if "Item" in named:
|
||||
summary = plain(named["Item"]).strip()
|
||||
if not summary:
|
||||
return Failure("the item has no tagline")
|
||||
body["fields"] = {"summary": summary}
|
||||
if unfit := unfit_text(named.get("Item", ""), detail or ""):
|
||||
return unfit
|
||||
release = named.get("Release")
|
||||
if release is not None and parsed(release) is None:
|
||||
return Failure(f"the item's Release {release!r} is not a version such as 1.2.0")
|
||||
if not is_exempt(named.get("Exempt", "")):
|
||||
return Failure(f"the item's Exempt {named['Exempt']!r} is not empty or one of {', '.join(EXEMPTIONS[1:])}")
|
||||
if any(name in named for name in SCORED):
|
||||
texts = {name: str(value) for name, value in held.items()} | {name: named[name] for name in SCORED if name in named}
|
||||
scored = scores(issue.key, texts)
|
||||
if isinstance(scored, Failure):
|
||||
return scored
|
||||
if scored[0] and any(name not in scored[0] for name in SET_SCORES):
|
||||
return Failure(f"{issue.key} would hold some of {', '.join(SET_SCORES)} and not the rest: set them together")
|
||||
value = held | scored[0] | {MOVES: texts.get(MOVES, ""), "Exempt": scored[2]}
|
||||
body["properties"] = [{"key": PROPERTY, "value": value}]
|
||||
if own and (scored[2] == SECURITY) != (held.get("Exempt") == SECURITY):
|
||||
body["update"] = {"labels": [{"add" if scored[2] == SECURITY else "remove": SECURITY}]}
|
||||
return Revision(body, release)
|
||||
|
||||
|
||||
def offer_of(raw: object) -> tuple[str, str, str, str] | None:
|
||||
@@ -274,7 +437,7 @@ def basic_auth(env_file: pathlib.Path) -> str | Failure:
|
||||
|
||||
|
||||
def children(epic: Epic, authorization: str, http: Http) -> list[object] | Failure:
|
||||
"""The epic's open child issues in backlog order, which is the order the team ranks them in. An issue in a done status is a finished item, so it is no longer in the plan."""
|
||||
"""The epic's open child issues in backlog order, which the team ranks, apart from where add ranks an issue it files. An issue in a done status is a finished item, so it is no longer in the plan."""
|
||||
# The search answers no issues for an epic the account cannot see, as for one whose children are all done; asking for the epic itself tells them apart.
|
||||
seen = http("GET", f"{epic.site}/rest/api/3/issue/{epic.key}?fields=summary", authorization, None)
|
||||
if isinstance(seen, Failure):
|
||||
@@ -350,7 +513,6 @@ def item(issue: Issue, project: str, ids: set[int]) -> Item | Failure:
|
||||
"""The item an issue holds, without its detail. It is blocked by each of its blockers among ids, the plan's items: a blocker that is done or lies outside the epic doesn't make the item wait."""
|
||||
release = earliest_release(issue.fix_versions)
|
||||
if release is None:
|
||||
# Until a project can tie its releases to something other than semver versions, an item with no release cannot be placed in the plan.
|
||||
return Failure(f"{issue.key} names no Fix Version that is a semver version, such as 1.2.0; set one in Jira")
|
||||
scored = scores(issue.key, issue.scores)
|
||||
if isinstance(scored, Failure):
|
||||
|
||||
+41
-16
@@ -12,8 +12,8 @@ from release_plan.todo_table import BLOCKED_BY, Item, item_details, items, MOVES
|
||||
from failure import Failure
|
||||
from git_cli.git_repo import file_at, git, Git
|
||||
from record_store.stores import goals_store, store as record_store, RecordStore
|
||||
from project_config.settings import JiraScoring, ProjectConfig
|
||||
from plan_store import markdown_edits
|
||||
from project_config.settings import ProjectConfig
|
||||
from release_plan import ranking
|
||||
from release_plan.release import Release
|
||||
from text_files.file_writes import replace_file
|
||||
@@ -47,7 +47,7 @@ class Written:
|
||||
|
||||
|
||||
class PlanStore(typing.Protocol):
|
||||
"""A project's plan. plan_store.contract holds every backend that writes to the same behaviour; `jira_epic` reads, 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."""
|
||||
"""A project's plan. plan_store.contract holds every backend that writes to the same behaviour; `jira_epic` doesn't hold it yet: it changes no link, and its own tests stand in for Jira. A write that fails leaves the plan as it was, except where its Failure says the tracker may have taken the write all the same, as when Jira's answer to a new issue, an edit or a finish is lost."""
|
||||
|
||||
@property
|
||||
def label(self) -> str:
|
||||
@@ -63,8 +63,10 @@ class PlanStore(typing.Protocol):
|
||||
def add(self, fields: dict[str, str], detail: str) -> Written | Failure:
|
||||
"""Files an item under an ID the backend picks. fields holds each of FIELDS the caller sets; detail may be empty."""
|
||||
|
||||
def edit(self, id_: int, fields: dict[str, str], detail: str | None) -> Written | Failure:
|
||||
"""Sets item id_'s fields to those given, and its detail unless None, leaving the rest. Moving an item sets its Release."""
|
||||
def edit(self, id_: int, fields: dict[str, str], detail: str | None, comment: str | None = None) -> Written | Failure:
|
||||
"""Sets item id_'s fields to those given, and its detail unless None, leaving the rest. Moving an item sets its Release.
|
||||
|
||||
comment tells the plan's other readers why, in the project's language. A tracker posts it on the item's issue; a backend with no place for comments drops it."""
|
||||
|
||||
def finish(self, id_: int) -> Written | Failure:
|
||||
"""Removes item id_ with its detail."""
|
||||
@@ -98,7 +100,7 @@ class FilePlan:
|
||||
filed = markdown_edits.added(texts[0], cells(fields), detail, self.label)
|
||||
return filed if isinstance(filed, Failure) else self.kept(*filed, texts)
|
||||
|
||||
def edit(self, id_: int, fields: dict[str, str], detail: str | None) -> Written | Failure:
|
||||
def edit(self, id_: int, fields: dict[str, str], detail: str | None, comment: str | None = None) -> Written | Failure:
|
||||
texts = self.texts()
|
||||
if isinstance(texts, Failure):
|
||||
return texts
|
||||
@@ -137,16 +139,36 @@ class FilePlan:
|
||||
plan = read_text(self.path, MISSING)
|
||||
if isinstance(plan, Failure):
|
||||
return plan
|
||||
goals = self.goals.read()
|
||||
if isinstance(goals, Failure):
|
||||
return goals
|
||||
if not goals:
|
||||
return Failure(f"{self.goals.label}: missing or empty; {GOALS_HINT}")
|
||||
decisions = self.decisions.read()
|
||||
if isinstance(decisions, Failure):
|
||||
return decisions
|
||||
history = self.history.read()
|
||||
return history if isinstance(history, Failure) else (plan, goals, decisions, history)
|
||||
weighing = weighing_texts(self.goals, self.decisions, self.history)
|
||||
return weighing if isinstance(weighing, Failure) else (plan, *weighing)
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class StatedScoring:
|
||||
"""The scoring of a plan in Jira: the formula and bar the project's config states, with goal weights that ranking reads from the goals file, the decision log and the comprehension history."""
|
||||
stated: JiraScoring
|
||||
goals: RecordStore
|
||||
decisions: RecordStore
|
||||
history: RecordStore
|
||||
floor: decimal.Decimal
|
||||
|
||||
def read(self) -> ranking.Scoring | Failure:
|
||||
weighing = weighing_texts(self.goals, self.decisions, self.history)
|
||||
return weighing if isinstance(weighing, Failure) else ranking.config_scoring(self.stated.formula, self.stated.bar, *weighing, self.floor)
|
||||
|
||||
|
||||
def weighing_texts(goals: RecordStore, decisions: RecordStore, history: RecordStore) -> tuple[str, str, str] | Failure:
|
||||
"""What ranking weighs the goals by: the goals file, the decision log and the comprehension history. The last two are empty when missing; a goals file that is missing or empty is a Failure."""
|
||||
goals_text = goals.read()
|
||||
if isinstance(goals_text, Failure):
|
||||
return goals_text
|
||||
if not goals_text:
|
||||
return Failure(f"{goals.label}: missing or empty; {GOALS_HINT}")
|
||||
decisions_text = decisions.read()
|
||||
if isinstance(decisions_text, Failure):
|
||||
return decisions_text
|
||||
history_text = history.read()
|
||||
return history_text if isinstance(history_text, Failure) else (goals_text, decisions_text, history_text)
|
||||
|
||||
|
||||
def store(config: ProjectConfig) -> PlanStore:
|
||||
@@ -157,7 +179,10 @@ def store(config: ProjectConfig) -> PlanStore:
|
||||
from plan_store.jira_epic import JiraPlan
|
||||
# load refuses a config that names an epic and no env-file.
|
||||
assert config.env_file is not None
|
||||
return JiraPlan(config.epic, config.env_file, 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:
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import base64
|
||||
import dataclasses
|
||||
import pathlib
|
||||
import sys
|
||||
import tempfile
|
||||
@@ -7,11 +8,12 @@ import unittest.mock
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from project_config.settings import Epic, Finish
|
||||
from project_config.settings import DEFAULT_FLOOR, Epic, Finish
|
||||
from release_plan.todo_table import EXEMPTIONS
|
||||
from failure import Failure
|
||||
from plan_store import jira_epic
|
||||
from plan_store.stores import Plan, Written
|
||||
from release_plan import ranking
|
||||
from adf_codec.convert import Refused
|
||||
from release_plan.release import release_of
|
||||
|
||||
@@ -63,7 +65,7 @@ class JiraPlan(unittest.TestCase):
|
||||
return [text_of(document) for document in documents]
|
||||
|
||||
def store(self) -> jira_epic.JiraPlan:
|
||||
return jira_epic.JiraPlan(EPIC, self.env, self.http, self.to_markdown)
|
||||
return jira_epic.JiraPlan(EPIC, self.env, self.http, self.to_markdown, scoring=Stated())
|
||||
|
||||
def read(self, *issues: dict[str, object]) -> Plan | Failure:
|
||||
self.pages, self.calls = [{"issues": list(issues)}], []
|
||||
@@ -181,12 +183,12 @@ class JiraPlan(unittest.TestCase):
|
||||
self.assertEqual(self.converted, [[adf("One."), adf("Three."), adf("Four.")]])
|
||||
|
||||
def test_a_description_the_codec_refuses_fails_the_read_naming_the_issue(self):
|
||||
store = jira_epic.JiraPlan(EPIC, self.env, self.http, lambda documents: Refused(1, Failure("adf-codec refused")))
|
||||
store = jira_epic.JiraPlan(EPIC, self.env, self.http, lambda documents: Refused(1, Failure("adf-codec refused")), scoring=Stated())
|
||||
self.pages = [{"issues": [issue("ABC-33", description=adf("x")), issue("ABC-34"), issue("ABC-35", description=adf("y"))]}]
|
||||
self.assertEqual(store.read(), Failure("ABC-35's description: adf-codec refused"))
|
||||
|
||||
def test_a_codec_that_cannot_run_fails_the_read(self):
|
||||
store = jira_epic.JiraPlan(EPIC, self.env, self.http, lambda documents: Failure("docker is not installed"))
|
||||
store = jira_epic.JiraPlan(EPIC, self.env, self.http, lambda documents: Failure("docker is not installed"), scoring=Stated())
|
||||
self.pages = [{"issues": [issue("ABC-34", description=adf("x"))]}]
|
||||
self.assertEqual(store.read(), Failure("cannot convert the descriptions of ABC-12's children to markdown: docker is not installed"))
|
||||
|
||||
@@ -210,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}],
|
||||
})])
|
||||
@@ -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]
|
||||
|
||||
@@ -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"),
|
||||
):
|
||||
with self.subTest(reason=reason):
|
||||
self.calls.clear()
|
||||
self.open = [open_]
|
||||
self.assertEqual(self.add(), Written(40, (f"filed ABC-40, but cannot rank it: {reason}; rank it in Jira",)))
|
||||
self.assertEqual(self.sent(RANK), [])
|
||||
|
||||
|
||||
TRANSITIONS = "https://acme.atlassian.net/rest/api/3/issue/ABC-34/transitions"
|
||||
|
||||
|
||||
COMMENT = "Scored for planning: a small change to one module."
|
||||
PERHAPS_EDITED = "unless Jira refused the request, the issue may have changed: look at ABC-34 before editing the item again"
|
||||
|
||||
|
||||
class Editing(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.env = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory())) / "acme.env"
|
||||
self.env.write_text("ATLASSIAN_EMAIL=me@example.com\nATLASSIAN_API_TOKEN=s3cret\n")
|
||||
self.env.chmod(0o600)
|
||||
self.calls: list[tuple[str, str, object]] = []
|
||||
# The loop filed ABC-34. A person filed ABC-35, which nobody scored, and ABC-36, which holds scores.
|
||||
self.open: list[object] = [issue("ABC-34", scores=PROPERTY), issue("ABC-35"), issue("ABC-36", scores={"L": 3, "E": 1, "I": 1, "S": 2})]
|
||||
self.edited: object = None
|
||||
self.commented: object = {"id": "10100"}
|
||||
self.versions: object = [{"name": "0.1.0"}, {"name": "v0.2.0"}]
|
||||
|
||||
def http(self, method: str, url: str, authorization: str, body: object) -> object:
|
||||
"""Stands in for Jira: answers the epic, self.versions for the project's Fix Versions, self.open to the search, self.edited to an edit and self.commented to a new comment."""
|
||||
self.calls.append((method, url, body))
|
||||
assert authorization == AUTHORIZATION
|
||||
if method == "PUT":
|
||||
return self.edited
|
||||
return self.commented if url.endswith("/comment") else {SEARCH: {"issues": self.open}, VERSIONS: self.versions}.get(url, {"key": "ABC-12"})
|
||||
|
||||
def to_adf(self, markdown: str) -> dict[str, object] | Failure:
|
||||
return adf(markdown)
|
||||
|
||||
def edit(self, id_: int, fields: dict[str, str], detail: str | None = None, comment: str | None = None):
|
||||
return jira_epic.JiraPlan(EPIC, self.env, self.http, text_of, self.to_adf, scoring=Stated()).edit(id_, fields, detail, comment)
|
||||
|
||||
def writes(self) -> list[tuple[str, str, object]]:
|
||||
"""Each request that changes Jira, in order."""
|
||||
return [call for call in self.calls if call[0] == "PUT" or call[1].endswith("/comment")]
|
||||
|
||||
def test_sets_the_summary_description_and_scores_of_an_issue_the_loop_filed_in_one_request(self):
|
||||
self.assertEqual(self.edit(34, {"Tagline": "**Count every run.**", "L": "2", "Moves": ""}, "Why it counts."), Written(34))
|
||||
self.assertEqual(self.writes(), [("PUT", f"{ISSUES}/ABC-34", {
|
||||
"fields": {"summary": "Count every run.", "description": adf("Why it counts.")},
|
||||
"properties": [{"key": "plan-item", "value": PROPERTY | {"L": 2, "Moves": ""}}],
|
||||
})])
|
||||
|
||||
def test_sends_only_what_the_edit_names(self):
|
||||
self.edit(34, {"Tagline": "Count every run."})
|
||||
self.edit(34, {"E": "3"})
|
||||
self.assertEqual([body for _, _, body in self.writes()], [{"fields": {"summary": "Count every run."}}, {"properties": [{"key": "plan-item", "value": PROPERTY | {"E": 3}}]}])
|
||||
|
||||
def test_an_empty_detail_removes_the_description(self):
|
||||
self.edit(34, {}, " \n")
|
||||
self.assertEqual(self.writes(), [("PUT", f"{ISSUES}/ABC-34", {"fields": {"description": None}})])
|
||||
|
||||
def test_an_edit_of_the_release_sets_the_fix_version_as_the_project_spells_it(self):
|
||||
self.assertEqual(self.edit(34, {"Release": "0.2.0"}), Written(34))
|
||||
self.assertEqual(self.writes(), [("PUT", f"{ISSUES}/ABC-34", {"fields": {"fixVersions": [{"name": "v0.2.0"}]}})])
|
||||
|
||||
def test_an_edit_of_the_release_and_the_tagline_sends_both(self):
|
||||
self.edit(34, {"Release": "0.2.0", "Tagline": "Count every run."})
|
||||
self.assertEqual(self.writes()[0][2], {"fields": {"summary": "Count every run.", "fixVersions": [{"name": "v0.2.0"}]}})
|
||||
|
||||
def test_an_empty_tagline_fails_before_any_write(self):
|
||||
self.assertEqual(self.edit(34, {"Tagline": "** **"}), Failure("the item has no tagline"))
|
||||
self.assertEqual(self.writes(), [])
|
||||
|
||||
def test_a_release_the_project_has_no_fix_version_for_fails_before_any_write(self):
|
||||
self.assertEqual(self.edit(34, {"Release": "0.3.0"}), Failure("the Jira project ABC has no Fix Version 0.3.0 or v0.3.0; create it in Jira, or name a release it has"))
|
||||
self.assertEqual(self.writes(), [])
|
||||
|
||||
def test_an_exempt_that_becomes_or_stops_being_security_adds_or_removes_the_label(self):
|
||||
self.edit(34, {"Exempt": "security"})
|
||||
self.open = [issue("ABC-34", scores=PROPERTY | {"Exempt": "security"})]
|
||||
self.edit(34, {"Exempt": "owner"})
|
||||
self.edit(34, {"Exempt": "security"})
|
||||
self.assertEqual([body.get("update") for _, _, body in self.writes()], [{"labels": [{"add": "security"}]}, {"labels": [{"remove": "security"}]}, None]) # type: ignore[attr-defined]
|
||||
|
||||
def test_scores_an_issue_a_person_filed_and_comments_why(self):
|
||||
self.assertEqual(self.edit(35, {"L": "2", "E": "2", "I": "3", "S": "3", "Moves": "1 by 4"}, None, COMMENT), Written(35))
|
||||
self.assertEqual(self.writes(), [
|
||||
("PUT", f"{ISSUES}/ABC-35", {"properties": [{"key": "plan-item", "value": {"L": 2, "E": 2, "I": 3, "S": 3, "Moves": "1 by 4", "Exempt": ""}}]}),
|
||||
("POST", f"{ISSUES}/ABC-35/comment", {"body": adf(COMMENT)}),
|
||||
])
|
||||
|
||||
def test_rescores_a_persons_issue_that_holds_scores_keeping_the_rest(self):
|
||||
self.edit(36, {"L": "2"}, None, COMMENT)
|
||||
self.assertEqual(self.writes()[0][2], {"properties": [{"key": "plan-item", "value": {"L": 2, "E": 1, "I": 1, "S": 2, "Moves": "", "Exempt": ""}}]})
|
||||
|
||||
def test_a_persons_issue_is_never_labelled(self):
|
||||
self.edit(36, {"Exempt": "security"}, None, COMMENT)
|
||||
self.assertNotIn("update", self.writes()[0][2]) # type: ignore[operator]
|
||||
|
||||
def test_scoring_a_persons_issue_without_a_comment_fails_before_any_write(self):
|
||||
for comment in (None, "", " \n"):
|
||||
with self.subTest(comment=comment):
|
||||
self.assertEqual(self.edit(35, {"L": "2"}, None, comment), Failure("a person filed ABC-35, and Jira doesn't show its team the scores: pass a comment saying that it is scored, and why"))
|
||||
self.assertEqual(self.writes(), [])
|
||||
|
||||
def test_what_a_person_wrote_or_planned_is_never_edited(self):
|
||||
for fields, detail in (({"Tagline": "Count every run."}, None), ({}, "Why."), ({}, ""), ({"Release": "0.2.0"}, None), ({"Tagline": "Count.", "Release": "0.2.0", "L": "1"}, "")):
|
||||
with self.subTest(fields=fields, detail=detail):
|
||||
self.assertEqual(self.edit(36, fields, detail, COMMENT), Failure("a person filed ABC-36, so the loop sets only its scores: change its summary, description and Fix Version in Jira"))
|
||||
self.assertEqual(self.writes(), [])
|
||||
|
||||
def test_scoring_an_unscored_issue_in_part_fails_before_any_write(self):
|
||||
self.assertEqual(self.edit(35, {"L": "2", "E": "2"}, None, COMMENT), Failure("ABC-35 would hold some of L, E, I, S and not the rest: set them together"))
|
||||
self.assertEqual(self.edit(35, {"Exempt": "question"}, None, COMMENT), Written(35))
|
||||
self.assertEqual(len(self.writes()), 2)
|
||||
|
||||
def test_a_comment_on_an_edit_of_the_loops_own_issue_is_posted_too(self):
|
||||
self.edit(34, {"L": "2"}, None, COMMENT)
|
||||
self.assertEqual(self.writes()[1], ("POST", f"{ISSUES}/ABC-34/comment", {"body": adf(COMMENT)}))
|
||||
|
||||
def test_a_comment_jira_refuses_leaves_the_edit_made_with_a_note(self):
|
||||
self.commented = Failure("HTTP 403")
|
||||
self.assertEqual(self.edit(36, {"L": "2"}, None, COMMENT), Written(36, ("edited ABC-36, but cannot post the comment: HTTP 403; post it in Jira",)))
|
||||
|
||||
def test_an_edit_of_the_blockers_fails_since_the_store_changes_no_link(self):
|
||||
self.assertEqual(self.edit(34, {"Blocked by": "35"}), Failure("the loop doesn't change an issue's links: link ABC-34 in Jira"))
|
||||
self.assertEqual(self.writes(), [])
|
||||
|
||||
def test_an_issue_that_is_no_open_child_of_the_epic_is_not_edited(self):
|
||||
self.assertEqual(self.edit(40, {"L": "2"}), Failure("jira:https://acme.atlassian.net/browse/ABC-12 holds no item 40"))
|
||||
self.assertEqual(self.writes(), [])
|
||||
|
||||
def test_each_field_out_of_format_fails_before_any_write_saying_how(self):
|
||||
for fields, detail, reason in (
|
||||
({"L": "9"}, None, "item ABC-34's L '9' is not a whole number from 1 to 4"),
|
||||
({"Moves": "much"}, None, "item ABC-34's Moves 'much' is not"),
|
||||
({"Exempt": "tired"}, None, f"the item's Exempt 'tired' is not empty or one of {', '.join(EXEMPTIONS[1:])}"),
|
||||
({"Release": "soon"}, None, "the item's Release 'soon' is not a version such as 1.2.0"),
|
||||
({"Tagline": " "}, None, "the item has no tagline"),
|
||||
({"Tagline": "Count\nruns."}, None, "the tagline holds a line break; keep it on one line"),
|
||||
({}, "## Why", "the detail holds a ## or ### heading"),
|
||||
):
|
||||
with self.subTest(fields=fields, detail=detail):
|
||||
failed = self.edit(34, fields, detail)
|
||||
self.assertIsInstance(failed, Failure)
|
||||
self.assertIn(reason, failed.reason)
|
||||
self.assertEqual(self.writes(), [])
|
||||
|
||||
def test_a_detail_or_a_comment_that_does_not_convert_fails_before_any_write(self):
|
||||
self.to_adf = lambda markdown: Failure("the codec is down") # type: ignore[method-assign]
|
||||
self.assertEqual(self.edit(34, {}, "Why."), Failure("cannot convert the item's detail to a Jira description: the codec is down"))
|
||||
self.assertEqual(self.edit(34, {"L": "2"}, None, COMMENT), Failure("cannot convert the comment to a Jira comment: the codec is down"))
|
||||
self.assertEqual(self.writes(), [])
|
||||
|
||||
def test_an_edit_jira_refuses_fails_with_jiras_reason_and_posts_no_comment(self):
|
||||
self.edited = Failure("HTTP 400: Summary is too long")
|
||||
self.assertEqual(self.edit(34, {"L": "2"}, None, COMMENT), Failure(f"cannot edit ABC-34: HTTP 400: Summary is too long; {PERHAPS_EDITED}"))
|
||||
self.assertEqual(len(self.writes()), 1)
|
||||
|
||||
def test_an_issue_in_another_shape_or_a_search_that_fails_fails_the_edit(self):
|
||||
self.open = [{"key": "ABC-34", "fields": {}}]
|
||||
self.assertIn("ABC-34 is not in the shape", self.edit(34, {"L": "2"}).reason)
|
||||
self.open = [issue("ABC-34", scores=["odd"])] # type: ignore[arg-type]
|
||||
self.assertEqual(self.edit(34, {"L": "2"}), Failure("ABC-34's issue property plan-item is not a JSON object"))
|
||||
self.assertEqual(self.writes(), [])
|
||||
|
||||
def test_a_missing_env_file_fails_before_any_request(self):
|
||||
self.env.unlink()
|
||||
self.assertIsInstance(self.edit(34, {"L": "2"}), Failure)
|
||||
self.assertEqual(self.calls, [])
|
||||
|
||||
def test_what_it_edits_reads_back_as_the_item(self):
|
||||
self.edit(34, {"Tagline": "Count every run.", "S": "4"}, "Why it counts.")
|
||||
body = self.writes()[0][2]
|
||||
held = issue("ABC-34", summary=body["fields"]["summary"], scores=body["properties"][0]["value"], description=body["fields"]["description"]) # type: ignore[index]
|
||||
self.open = [held]
|
||||
plan = jira_epic.JiraPlan(EPIC, self.env, self.http, lambda documents: [text_of(document) for document in documents], scoring=Stated()).read()
|
||||
assert isinstance(plan, Plan), plan
|
||||
self.assertEqual((plan.items[0].tagline, plan.items[0].scores["S"], plan.items[0].scores["L"], plan.items[0].detail), ("**Count every run.**", 4, 1, "Why it counts."))
|
||||
|
||||
|
||||
def transition(id_: str, name: str, status: str, category: str = "done") -> dict[str, object]:
|
||||
return {"id": id_, "name": name, "to": {"name": status, "statusCategory": {"key": category}}}
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -8,9 +8,9 @@ import unittest
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from project_config.settings import DEFAULT_FLOOR, Epic, 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
|
||||
@@ -207,14 +207,40 @@ class Store(unittest.TestCase):
|
||||
|
||||
def test_an_epic_picks_jira_with_the_env_files_credentials(self):
|
||||
epic = Epic("https://acme.atlassian.net", "ABC-12")
|
||||
picked = stores.store(self.config(epic=epic, env_file=pathlib.Path("/secrets/acme.env")))
|
||||
self.assertEqual(picked, JiraPlan(epic, pathlib.Path("/secrets/acme.env"), picked.http))
|
||||
picked = stores.store(self.config(epic=epic, env_file=pathlib.Path("/secrets/acme.env"), jira_scoring=JiraScoring("V", 1)))
|
||||
self.assertEqual(picked, JiraPlan(epic, pathlib.Path("/secrets/acme.env"), picked.http, scoring=picked.scoring))
|
||||
|
||||
def test_an_epic_finishes_an_item_as_the_config_says(self):
|
||||
finish = Finish("Mark as done", "Done")
|
||||
picked = stores.store(self.config(epic=Epic("https://acme.atlassian.net", "ABC-12"), env_file=pathlib.Path("/secrets/acme.env"), jira_finish=finish))
|
||||
picked = stores.store(self.config(epic=Epic("https://acme.atlassian.net", "ABC-12"), env_file=pathlib.Path("/secrets/acme.env"), jira_finish=finish, jira_scoring=JiraScoring("V", 1)))
|
||||
self.assertEqual(picked.finish_by, finish)
|
||||
|
||||
def test_an_epic_scores_by_the_configs_formula_and_bar_and_the_projects_records(self):
|
||||
config = self.config(epic=Epic("https://acme.atlassian.net", "ABC-12"), env_file=pathlib.Path("/secrets/acme.env"), jira_scoring=JiraScoring("V / 2**S", 1.5), readability_floor=decimal.Decimal("6.5"))
|
||||
picked = stores.store(config)
|
||||
self.assertEqual(picked.scoring, stores.StatedScoring(JiraScoring("V / 2**S", 1.5), goals_store(config), record_store(config, "decisions"), record_store(config, "comprehension-history"), decimal.Decimal("6.5")))
|
||||
|
||||
|
||||
class StatedScoring(unittest.TestCase):
|
||||
def test_weighs_the_goals_the_goals_file_holds(self):
|
||||
scoring = stores.StatedScoring(JiraScoring("V / 2**S", 1.5), MemoryStore(README), MemoryStore(), MemoryStore(), DEFAULT_FLOOR).read()
|
||||
assert not isinstance(scoring, Failure), scoring
|
||||
self.assertEqual((scoring.bar, list(scoring.goals)), (1.5, ["1", "2", "2.1"]))
|
||||
|
||||
def test_weighs_code_health_by_the_history_and_the_floor_it_is_given(self):
|
||||
for floor, under in ((DEFAULT_FLOOR, True), (decimal.Decimal("6.0"), False)):
|
||||
with self.subTest(floor=floor):
|
||||
scoring = stores.StatedScoring(JiraScoring("V", 1), MemoryStore("## Goals\n\n1. **Achieve:** A.\n"), MemoryStore(), MemoryStore(SCORED.format(overall="6.99")), floor).read()
|
||||
assert not isinstance(scoring, Failure), scoring
|
||||
self.assertEqual(scoring.weights["code health"] > scoring.weights["1"] * 2, under)
|
||||
|
||||
def test_a_goals_file_that_is_empty_or_cannot_be_read_fails(self):
|
||||
for goals, reason in ((MemoryStore(), "the record in memory: missing or empty"), (MemoryStore(fails="Jira answered 403"), "Jira answered 403")):
|
||||
with self.subTest(reason=reason):
|
||||
read = stores.StatedScoring(JiraScoring("V", 1), goals, MemoryStore(), MemoryStore(), DEFAULT_FLOOR).read()
|
||||
assert isinstance(read, Failure), read
|
||||
self.assertTrue(read.reason.startswith(reason), read.reason)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
||||
@@ -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, DEFAULT_FLOOR, ENV_FILE, JIRA_FINISH_STATUS, JIRA_FINISH_TRANSITION, JIRA_SCORE_BAR, JIRA_SCORE_FORMULA, load, NOTIFIER, OPTIONAL, PARALLEL_CHUNKS, ProjectConfig, READABILITY_FLOOR, SETTINGS, TOOLING_ON_HOST, Unnamed, WAIT_FOR_APPROVAL
|
||||
from failure import Failure
|
||||
from git_cli.git_repo import git, Git
|
||||
from project_config import templates
|
||||
@@ -151,15 +164,18 @@ def main(argv: list[str]) -> int:
|
||||
if argv == [READABILITY_FLOOR]:
|
||||
print(config.readability_floor)
|
||||
return 0
|
||||
if argv == [PARALLEL_CHUNKS]:
|
||||
print(config.parallel_chunks)
|
||||
return 0
|
||||
if argv and argv[0] in config.texts:
|
||||
print(config.texts[argv[0]])
|
||||
return 0
|
||||
paths = {**config.places, **({ENV_FILE: str(config.env_file)} if config.env_file else {}), **({NOTIFIER: config.notifier} if config.notifier else {}), **({JIRA_FINISH_TRANSITION: config.jira_finish.transition, JIRA_FINISH_STATUS: config.jira_finish.status} if config.jira_finish else {})}
|
||||
paths = {**config.places, **({ENV_FILE: str(config.env_file)} if config.env_file else {}), **({NOTIFIER: config.notifier} if config.notifier else {}), **({JIRA_SCORE_FORMULA: config.jira_scoring.formula, JIRA_SCORE_BAR: f"{config.jira_scoring.bar:g}"} if config.jira_scoring else {}), **({JIRA_FINISH_TRANSITION: config.jira_finish.transition, JIRA_FINISH_STATUS: config.jira_finish.status} if config.jira_finish else {})}
|
||||
if argv and argv[0] not in paths:
|
||||
print(f"{config.folder / CONFIG} sets no `{argv[0]}`", file=sys.stderr)
|
||||
return 1
|
||||
defaults = ProjectConfig(config.key, config.folder, config.top, {}).texts
|
||||
listed = [f"{name}: {path}" for name, path in paths.items()] + [f"{name}: true" for name, on in switches.items() if on] + ([f"{READABILITY_FLOOR}: {config.readability_floor}"] if config.readability_floor != DEFAULT_FLOOR else []) + [f"{name}: {text}" for name, text in config.texts.items() if text != defaults[name]]
|
||||
listed = [f"{name}: {path}" for name, path in paths.items()] + [f"{name}: true" for name, on in switches.items() if on] + ([f"{READABILITY_FLOOR}: {config.readability_floor}"] if config.readability_floor != DEFAULT_FLOOR else []) + ([f"{PARALLEL_CHUNKS}: {config.parallel_chunks}"] if config.parallel_chunks != 1 else []) + [f"{name}: {text}" for name, text in config.texts.items() if text != defaults[name]]
|
||||
print(paths[argv[0]] if argv else "\n".join(listed))
|
||||
return 0
|
||||
|
||||
|
||||
@@ -10,7 +10,10 @@ import tomllib
|
||||
import typing
|
||||
|
||||
from failure import Failure
|
||||
from release_plan.formula import parse_formula
|
||||
from release_plan.todo_table import SHAPE
|
||||
from project_config import templates
|
||||
from release_plan.ranking import variables
|
||||
|
||||
PROJECTS = ".claude-projects"
|
||||
CONFIG = "config.toml"
|
||||
@@ -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,11 @@ 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)
|
||||
OPTIONAL = (BRANCH, COMMIT_TITLE, ENV_FILE, JIRA_FINISH_STATUS, JIRA_FINISH_TRANSITION, JIRA_SCORE_BAR, JIRA_SCORE_FORMULA, LANGUAGE, NOTIFIER, PARALLEL_CHUNKS, PULL_REQUEST_TITLE, READABILITY_FLOOR, TOOLING_ON_HOST, TOUCH_PREDICTIONS, WAIT_FOR_APPROVAL)
|
||||
# What opens a setting that names a Jira Cloud epic in place of a path: `jira:`, then the epic's address as the browser shows it. The settings below may name an epic; each reads its own part of it.
|
||||
JIRA = "jira:"
|
||||
EPIC_SPELLINGS = {
|
||||
@@ -78,6 +87,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."""
|
||||
@@ -103,6 +119,7 @@ class ProjectConfig:
|
||||
wait_for_approval: bool = False
|
||||
tooling_on_host: bool = False
|
||||
readability_floor: decimal.Decimal = DEFAULT_FLOOR
|
||||
parallel_chunks: int = 1
|
||||
language: str = "English"
|
||||
commit_title: str = templates.TITLE
|
||||
pull_request_title: str = templates.TITLE
|
||||
@@ -115,6 +132,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)
|
||||
|
||||
@@ -178,7 +197,10 @@ def load(top: pathlib.Path, main: pathlib.Path, home: pathlib.Path) -> ProjectCo
|
||||
waits = values.get(WAIT_FOR_APPROVAL, False)
|
||||
on_host = values.get(TOOLING_ON_HOST, False)
|
||||
floor = floor_of(values[READABILITY_FLOOR]) if READABILITY_FLOOR in values else DEFAULT_FLOOR
|
||||
parallel = values.get(PARALLEL_CHUNKS, 1)
|
||||
finish = [name for setting in JIRA_FINISH if (name := name_of(values.get(setting)))]
|
||||
formula, bar = values.get(JIRA_SCORE_FORMULA), values.get(JIRA_SCORE_BAR)
|
||||
scoring = JiraScoring(formula, bar_value) if isinstance(formula, str) and (bar_value := bar_of(bar)) is not None else None
|
||||
checks = {LANGUAGE: language_fault, COMMIT_TITLE: templates.title_fault, PULL_REQUEST_TITLE: templates.title_fault, BRANCH: templates.branch_fault}
|
||||
faults = [
|
||||
*(f"`{name}` is missing" for name in SETTINGS if name not in values),
|
||||
@@ -197,15 +219,37 @@ def load(top: pathlib.Path, main: pathlib.Path, home: pathlib.Path) -> ProjectCo
|
||||
*(f"`{name}` is {values[name]!r}, not the name Jira shows, such as \"{example}\"" for name, example in zip(JIRA_FINISH, ("Mark as done", "Done")) if name in values and not name_of(values[name])),
|
||||
*(f"`{name}` is set, so `{other}` must be too" for name, other in (JIRA_FINISH, JIRA_FINISH[::-1]) if name in values and other not in values),
|
||||
*(f"`{name}` is set, so `plan` must name a Jira epic" for name in JIRA_FINISH if name in values and not epics["plan"]),
|
||||
*(f"`plan` names a Jira epic, so `{name}` must be set, as `project-config --help` shows" for name in JIRA_SCORE if epics["plan"] and name not in values),
|
||||
*(f"`{name}` is set, so `plan` must name a Jira epic" for name in JIRA_SCORE if name in values and not epics["plan"]),
|
||||
*([f"`{JIRA_SCORE_FORMULA}` is {formula!r}: {fault}"] if JIRA_SCORE_FORMULA in values and (fault := formula_fault(formula)) else []),
|
||||
*([f"`{JIRA_SCORE_BAR}` is {bar!r}, not a bare number, such as `{JIRA_SCORE_BAR} = 1`"] if JIRA_SCORE_BAR in values and bar_of(bar) is None else []),
|
||||
*(f"`{name}` is {value!r}, not true or false" for name, value in ((WAIT_FOR_APPROVAL, waits), (TOOLING_ON_HOST, on_host)) if not isinstance(value, bool)),
|
||||
*([f"`{READABILITY_FLOOR}` is {values[READABILITY_FLOOR]!r}, not a number from 1 to 10; write a bare number, such as `{READABILITY_FLOOR} = 7.0`"] if floor is None else []),
|
||||
*([f"`{PARALLEL_CHUNKS}` is {parallel!r}, not a whole number of 1 or more, such as `{PARALLEL_CHUNKS} = 2`"] if type(parallel) is not int or parallel < 1 else []),
|
||||
*(f"`{name}` is {values[name]!r}, {fault}" for name, check in checks.items() if name in values and (fault := check(values[name]))),
|
||||
]
|
||||
if faults:
|
||||
return Failure(f"{file}: {'; '.join(faults)}. The settings are {', '.join(SETTINGS)}, and optionally {', '.join(OPTIONAL[:-1])} and {OPTIONAL[-1]}.")
|
||||
# faults names a floor the config misspells.
|
||||
# faults names a floor or a `parallel-chunks` value the config misspells, and a formula or bar a plan in Jira lacks or misspells.
|
||||
assert floor is not None
|
||||
return ProjectConfig(file.parent.name, file.parent, top, {name: path for name, path in paths.items() if path}, env_file, waits is True, on_host is True, floor, **{name.replace("-", "_"): str(values[name]) for name in checks if name in values}, epic=epics["plan"], goals_epic=epics["goals-and-audience"], notifier=notifier, jira_finish=Finish(*finish) if finish else None, pages=pages)
|
||||
assert isinstance(parallel, int)
|
||||
assert scoring is not None or not epics["plan"]
|
||||
return ProjectConfig(file.parent.name, file.parent, top, {name: path for name, path in paths.items() if path}, env_file, waits is True, on_host is True, floor, parallel, **{name.replace("-", "_"): str(values[name]) for name in checks if name in values}, epic=epics["plan"], goals_epic=epics["goals-and-audience"], notifier=notifier, jira_finish=Finish(*finish) if finish else None, jira_scoring=scoring, pages=pages)
|
||||
|
||||
|
||||
def formula_fault(value: object) -> str | None:
|
||||
"""Why value is no formula that may score an item, as todo.md's `Score` line states one; None where it is one."""
|
||||
if not isinstance(value, str):
|
||||
return "not a formula, such as \"100 * V / (2**S + 8)\""
|
||||
parsed = parse_formula(value, variables(SHAPE))
|
||||
return parsed.reason if isinstance(parsed, Failure) else None
|
||||
|
||||
|
||||
def bar_of(value: object) -> float | None:
|
||||
"""The bar value spells, an integer or a float; None where it spells none, as for a boolean or TOML's nan or inf, as floor_of says."""
|
||||
if isinstance(value, bool) or not isinstance(value, int | float) or (isinstance(value, float) and not math.isfinite(value)):
|
||||
return None
|
||||
return float(value)
|
||||
|
||||
|
||||
def name_of(value: object) -> str | None:
|
||||
|
||||
@@ -9,7 +9,7 @@ import unittest.mock
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
|
||||
from project_config.settings import env_files, Epic, Finish, held, load, NOTIFIERS, OUTSIDE, Page, ProjectConfig, SETTINGS, Unnamed
|
||||
from project_config.settings import env_files, Epic, Finish, held, JiraScoring, load, NOTIFIERS, OUTSIDE, Page, ProjectConfig, SETTINGS, Unnamed
|
||||
from failure import Failure
|
||||
from test_env import isolated_env
|
||||
from project_config.main import located, title_templates
|
||||
@@ -31,7 +31,8 @@ standards = "~/.claude/skills/larv-review/standards"
|
||||
"""
|
||||
|
||||
JIRA_PLAN = "jira:https://acme.atlassian.net/browse/ABC-12"
|
||||
JIRA_CLIENT = CLIENT.replace("folder:todo.md", JIRA_PLAN) + 'env-file = "~/acme.env"\n'
|
||||
JIRA_SCORING = 'jira-score-formula = "100 * V / (2**S + 8)"\njira-score-bar = 1\n'
|
||||
JIRA_CLIENT = CLIENT.replace("folder:todo.md", JIRA_PLAN) + 'env-file = "~/acme.env"\n' + JIRA_SCORING
|
||||
DECISIONS_PAGE = "confluence:https://acme.atlassian.net/wiki/spaces/ENG/pages/2293761/Decisions"
|
||||
|
||||
|
||||
@@ -320,6 +321,40 @@ class LoadTest(ConfigCase):
|
||||
(self.home / ".claude-projects" / "acme" / "config.toml").write_text(CLIENT + 'jira-finish-transition = "Mark as done"\njira-finish-status = "Done"\n')
|
||||
self.assertIn("`jira-finish-transition` is set, so `plan` must name a Jira epic; `jira-finish-status` is set, so `plan` must name a Jira epic", self.failure())
|
||||
|
||||
def test_a_jira_plan_holds_the_formula_and_bar_it_scores_by(self) -> None:
|
||||
self.write("acme", JIRA_CLIENT.replace("jira-score-bar = 1", "jira-score-bar = 0.5"))
|
||||
named = load(self.checkout, self.checkout, self.home)
|
||||
assert isinstance(named, ProjectConfig), named
|
||||
self.assertEqual(named.jira_scoring, JiraScoring("100 * V / (2**S + 8)", 0.5))
|
||||
|
||||
def test_a_plan_in_a_file_holds_no_formula_or_bar_of_the_configs(self) -> None:
|
||||
self.write("acme", CLIENT)
|
||||
named = load(self.checkout, self.checkout, self.home)
|
||||
assert isinstance(named, ProjectConfig), named
|
||||
self.assertIsNone(named.jira_scoring)
|
||||
|
||||
def test_a_jira_plan_without_a_formula_or_a_bar_fails_naming_each(self) -> None:
|
||||
self.write("acme", JIRA_CLIENT.replace(JIRA_SCORING, ""))
|
||||
self.assertIn("`plan` names a Jira epic, so `jira-score-formula` must be set, as `project-config --help` shows; `plan` names a Jira epic, so `jira-score-bar` must be set", self.failure())
|
||||
|
||||
def test_a_scoring_setting_misspelt_or_beside_a_plan_in_a_file_fails_naming_it(self) -> None:
|
||||
config = self.write("acme", JIRA_CLIENT) / "config.toml"
|
||||
for formula, bar in (('" "', "true"), ("3", '"1"'), ('"V"', "nan")):
|
||||
with self.subTest(formula=formula, bar=bar):
|
||||
config.write_text(JIRA_CLIENT.replace(JIRA_SCORING, f"jira-score-formula = {formula}\njira-score-bar = {bar}\n"))
|
||||
reason = self.failure()
|
||||
self.assertIn("jira-score-bar` is", reason)
|
||||
self.assertEqual("jira-score-formula` is" in reason, formula != '"V"')
|
||||
config.write_text(CLIENT + JIRA_SCORING)
|
||||
self.assertIn("`jira-score-formula` is set, so `plan` must name a Jira epic; `jira-score-bar` is set, so `plan` must name a Jira epic", self.failure())
|
||||
|
||||
def test_a_formula_that_doesnt_parse_fails_naming_the_setting_and_why(self) -> None:
|
||||
config = self.write("acme", JIRA_CLIENT) / "config.toml"
|
||||
for formula, why in (("V +", "the formula 'V +' does not parse"), ("X", "the formula 'X' may hold only numbers, E, I, L, R, S, V, + - * / ** and parentheses")):
|
||||
with self.subTest(formula=formula):
|
||||
config.write_text(JIRA_CLIENT.replace('"100 * V / (2**S + 8)"', f'"{formula}"'))
|
||||
self.assertIn(f"`jira-score-formula` is '{formula}': {why}", self.failure())
|
||||
|
||||
def test_a_notifier_that_is_unknown_or_has_no_env_file_fails_naming_it(self) -> None:
|
||||
self.write("acme", CLIENT + 'env-file = "~/acme.env"\nnotifier = "teams"\n')
|
||||
self.assertIn("`notifier` is 'teams', not mattermost or slack", self.failure())
|
||||
@@ -427,6 +462,28 @@ class LoadTest(ConfigCase):
|
||||
self.assertIn("`readability-floor` is ", found.reason)
|
||||
self.assertIn(", not a number from 1 to 10; write a bare number, such as `readability-floor = 7.0`", found.reason)
|
||||
|
||||
def test_parallel_chunks_is_an_optional_whole_number_from_1_that_is_1_where_left_out(self) -> None:
|
||||
folder = self.write("acme", CLIENT)
|
||||
left_out = load(self.checkout, self.checkout, self.home)
|
||||
assert isinstance(left_out, ProjectConfig), left_out
|
||||
self.assertEqual(left_out.parallel_chunks, 1)
|
||||
for spelled in (1, 3, 12):
|
||||
with self.subTest(spelled):
|
||||
(folder / "config.toml").write_text(CLIENT + f"parallel-chunks = {spelled}\n")
|
||||
found = load(self.checkout, self.checkout, self.home)
|
||||
assert isinstance(found, ProjectConfig), found
|
||||
self.assertEqual(found.parallel_chunks, spelled)
|
||||
|
||||
def test_parallel_chunks_that_is_no_whole_number_from_1_fails_naming_it(self) -> None:
|
||||
folder = self.write("acme", CLIENT)
|
||||
for spelled in ('"2"', "0", "-1", "2.0", "true", "inf"):
|
||||
with self.subTest(spelled):
|
||||
(folder / "config.toml").write_text(CLIENT + f"parallel-chunks = {spelled}\n")
|
||||
found = load(self.checkout, self.checkout, self.home)
|
||||
assert isinstance(found, Failure), found
|
||||
self.assertIn("`parallel-chunks` is ", found.reason)
|
||||
self.assertIn(", not a whole number of 1 or more, such as `parallel-chunks = 2`", found.reason)
|
||||
|
||||
def test_the_language_and_the_templates_are_optional_and_default_to_english_bare_summaries_and_item_branches(self) -> None:
|
||||
folder = self.write("acme", CLIENT)
|
||||
left_out = load(self.checkout, self.checkout, self.home)
|
||||
@@ -462,7 +519,7 @@ class LoadTest(ConfigCase):
|
||||
|
||||
def test_the_failure_for_a_misplaced_env_file_and_a_missing_setting_names_both_and_lists_every_setting(self) -> None:
|
||||
folder = self.write("acme", "".join(line + "\n" for line in CLIENT.splitlines() if not line.startswith("plan")) + 'env-file = "checkout:.env"\n')
|
||||
self.assertEqual(self.failure(), f"{folder / 'config.toml'}: `plan` is missing; `env-file` is 'checkout:.env', not {OUTSIDE}. The settings are {', '.join(SETTINGS)}, and optionally branch, commit-title, env-file, jira-finish-status, jira-finish-transition, language, notifier, pull-request-title, readability-floor, tooling-on-host, touch-predictions and wait-for-approval.")
|
||||
self.assertEqual(self.failure(), f"{folder / 'config.toml'}: `plan` is missing; `env-file` is 'checkout:.env', not {OUTSIDE}. The settings are {', '.join(SETTINGS)}, and optionally branch, commit-title, env-file, jira-finish-status, jira-finish-transition, jira-score-bar, jira-score-formula, language, notifier, parallel-chunks, pull-request-title, readability-floor, tooling-on-host, touch-predictions and wait-for-approval.")
|
||||
|
||||
def test_two_configs_naming_one_checkout_fail_naming_both(self) -> None:
|
||||
self.write("acme", CLIENT)
|
||||
@@ -592,6 +649,11 @@ class ToolTest(ConfigCase):
|
||||
self.assertEqual(self.run_tool("jira-finish-status").stdout, "Done\n")
|
||||
self.assertEqual(self.run_tool().stdout.splitlines()[-2:], ["jira-finish-transition: Mark as done", "jira-finish-status: Done"])
|
||||
|
||||
def test_prints_the_formula_and_bar_a_jira_plan_scores_by(self) -> None:
|
||||
self.write("acme", JIRA_CLIENT.replace("jira-score-bar = 1", "jira-score-bar = 0.5"))
|
||||
self.assertEqual((self.run_tool("jira-score-formula").stdout, self.run_tool("jira-score-bar").stdout), ("100 * V / (2**S + 8)\n", "0.5\n"))
|
||||
self.assertIn("jira-score-formula: 100 * V / (2**S + 8)\njira-score-bar: 0.5\n", self.run_tool().stdout)
|
||||
|
||||
def test_prints_true_or_false_for_wait_for_approval_and_lists_it_only_where_the_config_sets_it(self) -> None:
|
||||
folder = self.write("acme", CLIENT)
|
||||
left_out = self.run_tool("wait-for-approval")
|
||||
@@ -612,6 +674,14 @@ class ToolTest(ConfigCase):
|
||||
self.assertEqual((self.run_tool("tooling-on-host").stdout, self.run_tool("readability-floor").stdout), ("true\n", "5\n"))
|
||||
self.assertEqual(self.run_tool().stdout.splitlines()[-2:], ["tooling-on-host: true", "readability-floor: 5"])
|
||||
|
||||
def test_prints_parallel_chunks_and_lists_it_only_where_the_config_changes_it(self) -> None:
|
||||
folder = self.write("acme", CLIENT)
|
||||
self.assertEqual(self.run_tool("parallel-chunks").stdout, "1\n")
|
||||
self.assertNotIn("parallel-chunks", self.run_tool().stdout)
|
||||
(folder / "config.toml").write_text(CLIENT + "parallel-chunks = 3\n")
|
||||
self.assertEqual(self.run_tool("parallel-chunks").stdout, "3\n")
|
||||
self.assertIn("parallel-chunks: 3", self.run_tool().stdout.splitlines())
|
||||
|
||||
def test_prints_the_language_and_each_template_and_lists_them_only_where_the_config_sets_them(self) -> None:
|
||||
folder = self.write("acme", CLIENT)
|
||||
defaults = {"language": "English", "commit-title": "{summary}", "pull-request-title": "{summary}", "branch": "item-{id}"}
|
||||
|
||||
@@ -10,8 +10,10 @@ save refuses them: edit the epic in Jira.
|
||||
|
||||
open prints the path of a file holding the record's text, and nothing else. Read and edit that
|
||||
file. Where the record is kept as a file, the path is that file. Where it is kept elsewhere, the
|
||||
path is a copy under ~/.local/state/project-record/<key>/, written afresh with the record as it
|
||||
stands, so open it again before each edit. A record that doesn't exist yet has no file at the path:
|
||||
path is a copy under ~/.local/state/project-record/<key>/<worktree>/, a folder named for the
|
||||
worktree that ran open, so two worktrees of one project don't share a copy. The copy is written
|
||||
afresh with the record as it stands, so open it again before each edit. open also removes the
|
||||
folders of worktrees git no longer lists. A record that doesn't exist yet has no file at the path:
|
||||
create it there.
|
||||
|
||||
save stores the file's text in the record, and prints one line saying so. Where the record is kept
|
||||
@@ -24,17 +26,20 @@ writes the copy afresh.
|
||||
|
||||
Exit 2 on bad arguments, and 1, saying why, on any other failure.
|
||||
"""
|
||||
import hashlib
|
||||
import pathlib
|
||||
import shutil
|
||||
import sys
|
||||
|
||||
from failure import Failure
|
||||
from record_store.stores import FileStore, goals_store, local_file, RECORDS, RecordStore, store, stored
|
||||
from git_cli.git_repo import git, Git
|
||||
from project_config.main import located
|
||||
from project_config.settings import ProjectConfig
|
||||
|
||||
# Not git's verbs, such as checkout and commit: those read as acting on the repo.
|
||||
COMMANDS = ("open", "save")
|
||||
# Where the copy of a record kept outside files goes, under the user's home, in a folder per project.
|
||||
# Where the copy of a record kept outside files goes, under the user's home, in a folder per project and worktree.
|
||||
COPIES = ".local/state/project-record"
|
||||
# The goals file opens like a record, though it is a setting of its own.
|
||||
GOALS = "goals-and-audience"
|
||||
@@ -49,7 +54,7 @@ def main(argv: list[str]) -> int:
|
||||
return 2
|
||||
home = pathlib.Path.home()
|
||||
config = located(None, home)
|
||||
done = config if isinstance(config, Failure) else act(argv[0], *opened(config, argv[1], home))
|
||||
done = config if isinstance(config, Failure) else performed(config, argv[0], argv[1], home)
|
||||
if isinstance(done, Failure):
|
||||
print(f"project-record: {done.reason}", file=sys.stderr)
|
||||
return 1
|
||||
@@ -57,12 +62,36 @@ def main(argv: list[str]) -> int:
|
||||
return 0
|
||||
|
||||
|
||||
def performed(config: ProjectConfig, command: str, name: str, home: pathlib.Path, run: Git = git) -> str | Failure:
|
||||
"""What command, one of COMMANDS, prints for the record called name. An open also prunes the copies of removed worktrees."""
|
||||
if command == "open":
|
||||
pruned(config, home, run)
|
||||
return act(command, *opened(config, name, home))
|
||||
|
||||
|
||||
def opened(config: ProjectConfig, name: str, home: pathlib.Path) -> tuple[RecordStore, pathlib.Path]:
|
||||
"""The store of the record called name, and the copy it gets where it isn't kept as a file. A store that keeps the version it read, for a later save, keeps it beside the copy."""
|
||||
copy = home / COPIES / config.key / f"{name}.md"
|
||||
copy = home / COPIES / config.key / worktree_folder(config.top) / f"{name}.md"
|
||||
return (goals_store(config) if name == GOALS else store(config, name, copy.with_suffix(".version"))), copy
|
||||
|
||||
|
||||
def worktree_folder(top: pathlib.Path) -> str:
|
||||
"""The name of the folder that holds the copies of the worktree at top: the worktree's own name, for a reader, and a hash of its path, since two worktrees in different folders may share a name."""
|
||||
return f"{top.name}-{hashlib.sha256(str(top).encode()).hexdigest()[:8]}"
|
||||
|
||||
|
||||
def pruned(config: ProjectConfig, home: pathlib.Path, run: Git = git) -> None:
|
||||
"""Remove the copies of the worktrees git no longer lists, so the folders don't pile up one per chunk. Best effort: a folder that stays only takes disk, and where git can't list the worktrees nothing is removed."""
|
||||
listed = run("worktree", "list", "--porcelain")
|
||||
folders = home / COPIES / config.key
|
||||
if isinstance(listed, Failure) or not folders.is_dir():
|
||||
return
|
||||
worktrees = [config.top, *(pathlib.Path(line.removeprefix("worktree ")) for line in listed.splitlines() if line.startswith("worktree "))]
|
||||
kept = {worktree_folder(worktree) for worktree in worktrees}
|
||||
for stale in (folder for folder in folders.iterdir() if folder.is_dir() and folder.name not in kept):
|
||||
shutil.rmtree(stale, ignore_errors=True)
|
||||
|
||||
|
||||
def act(command: str, record: RecordStore, copy: pathlib.Path) -> str | Failure:
|
||||
"""What command, one of COMMANDS, prints for record. copy is where a record kept outside files gets its file."""
|
||||
if command == "open":
|
||||
|
||||
@@ -17,19 +17,92 @@ from project_config.settings import Page, ProjectConfig
|
||||
TOOL = pathlib.Path(__file__).resolve().parents[1] / "project-record"
|
||||
|
||||
|
||||
COPIES = pathlib.Path("/home/me/.local/state/project-record/acme")
|
||||
|
||||
|
||||
def worktree_config(top: str, **kept: Page) -> ProjectConfig:
|
||||
return ProjectConfig("acme", pathlib.Path("/home/me/.claude-projects/acme"), pathlib.Path(top), {"goals-and-audience": pathlib.Path(top, "README.md")}, pathlib.Path("/home/me/acme.env"), pages=kept)
|
||||
|
||||
|
||||
class Opened(unittest.TestCase):
|
||||
def test_a_record_on_a_confluence_page_keeps_the_version_it_read_beside_its_copy(self):
|
||||
page = Page("https://acme.atlassian.net", "2293761", "confluence:https://acme.atlassian.net/wiki/spaces/ENG/pages/2293761")
|
||||
config = ProjectConfig("acme", pathlib.Path("/home/me/.claude-projects/acme"), pathlib.Path("/code/acme"), {}, pathlib.Path("/home/me/acme.env"), pages={"decisions": page})
|
||||
record, copy = main.opened(config, "decisions", pathlib.Path("/home/me"))
|
||||
self.assertEqual(copy, pathlib.Path("/home/me/.local/state/project-record/acme/decisions.md"))
|
||||
record, copy = main.opened(worktree_config("/code/acme", decisions=page), "decisions", pathlib.Path("/home/me"))
|
||||
self.assertEqual((copy.parent.parent, copy.name), (COPIES, "decisions.md"))
|
||||
self.assertRegex(copy.parent.name, r"^acme-[0-9a-f]{8}$")
|
||||
assert isinstance(record, ConfluencePage), record
|
||||
self.assertEqual(record.kept, pathlib.Path("/home/me/.local/state/project-record/acme/decisions.version"))
|
||||
self.assertEqual(record.kept, copy.with_suffix(".version"))
|
||||
|
||||
def test_the_goals_file_opens_through_the_goals_store(self):
|
||||
config = ProjectConfig("acme", pathlib.Path("/home/me/.claude-projects/acme"), pathlib.Path("/code/acme"), {"goals-and-audience": pathlib.Path("/code/acme/README.md")})
|
||||
record, copy = main.opened(config, "goals-and-audience", pathlib.Path("/home/me"))
|
||||
self.assertEqual((record.label, copy), ("/code/acme/README.md", pathlib.Path("/home/me/.local/state/project-record/acme/goals-and-audience.md")))
|
||||
record, copy = main.opened(worktree_config("/code/acme"), "goals-and-audience", pathlib.Path("/home/me"))
|
||||
self.assertEqual((record.label, copy.parent.parent, copy.name), ("/code/acme/README.md", COPIES, "goals-and-audience.md"))
|
||||
|
||||
def test_two_worktrees_of_one_project_get_copies_that_differ(self):
|
||||
home = pathlib.Path("/home/me")
|
||||
main_checkout = main.opened(worktree_config("/code/acme"), "goals-and-audience", home)[1]
|
||||
other = main.opened(worktree_config("/code/acme-item-5"), "goals-and-audience", home)[1]
|
||||
self.assertNotEqual(main_checkout, other)
|
||||
|
||||
def test_one_worktree_always_gets_the_same_copy(self):
|
||||
home = pathlib.Path("/home/me")
|
||||
first = main.opened(worktree_config("/code/acme"), "goals-and-audience", home)[1]
|
||||
self.assertEqual(first, main.opened(worktree_config("/code/acme"), "goals-and-audience", home)[1])
|
||||
|
||||
def test_two_worktrees_named_alike_in_different_folders_get_copies_that_differ(self):
|
||||
home = pathlib.Path("/home/me")
|
||||
first = main.opened(worktree_config("/code/acme-item-5"), "goals-and-audience", home)[1]
|
||||
second = main.opened(worktree_config("/other/acme-item-5"), "goals-and-audience", home)[1]
|
||||
self.assertNotEqual(first, second)
|
||||
|
||||
|
||||
class Pruned(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.home = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory()))
|
||||
self.config = worktree_config("/code/acme-item-5")
|
||||
self.folders = self.home / ".local/state/project-record/acme"
|
||||
for top in ("/code/acme", "/code/acme-item-5", "/code/acme-item-6"):
|
||||
copy = main.opened(worktree_config(top), "goals-and-audience", self.home)[1]
|
||||
copy.parent.mkdir(parents=True)
|
||||
copy.write_text("edit")
|
||||
|
||||
def kept(self) -> set[str]:
|
||||
return {folder.name for folder in self.folders.iterdir()}
|
||||
|
||||
def listed(self, *tops: str):
|
||||
return lambda *args, **kwargs: "" if args != ("worktree", "list", "--porcelain") else "".join(f"worktree {top}\nHEAD abc\nbranch refs/heads/x\n\n" for top in tops)
|
||||
|
||||
def test_removes_the_copies_of_worktrees_git_no_longer_lists_and_keeps_the_others(self):
|
||||
main.pruned(self.config, self.home, self.listed("/code/acme", "/code/acme-item-5"))
|
||||
self.assertEqual(self.kept(), {main.worktree_folder(pathlib.Path(top)) for top in ("/code/acme", "/code/acme-item-5")})
|
||||
|
||||
def test_always_keeps_the_copy_of_the_worktree_that_asked(self):
|
||||
main.pruned(self.config, self.home, self.listed("/code/acme"))
|
||||
self.assertIn(main.worktree_folder(pathlib.Path("/code/acme-item-5")), self.kept())
|
||||
|
||||
def test_removes_nothing_where_git_cannot_list_the_worktrees(self):
|
||||
main.pruned(self.config, self.home, lambda *args, **kwargs: Failure("not a repository"))
|
||||
self.assertEqual(len(self.kept()), 3)
|
||||
|
||||
def test_leaves_files_beside_the_folders_alone(self):
|
||||
(self.folders / "decisions.md").write_text("from before the folders")
|
||||
main.pruned(self.config, self.home, self.listed("/code/acme"))
|
||||
self.assertTrue((self.folders / "decisions.md").exists())
|
||||
|
||||
def test_a_copy_that_cannot_be_removed_does_not_fail_the_open(self):
|
||||
self.folders.chmod(0o500)
|
||||
self.addCleanup(self.folders.chmod, 0o700)
|
||||
main.pruned(self.config, self.home, self.listed("/code/acme"))
|
||||
self.assertEqual(len(self.kept()), 3)
|
||||
|
||||
def test_an_open_prunes_and_a_save_does_not(self):
|
||||
run = self.listed("/code/acme", "/code/acme-item-5")
|
||||
self.assertEqual(main.performed(self.config, "save", "goals-and-audience", self.home, run), "/code/acme-item-5/README.md is the record itself, so nothing is left to store.")
|
||||
self.assertEqual(len(self.kept()), 3)
|
||||
self.assertEqual(main.performed(self.config, "open", "goals-and-audience", self.home, run), "/code/acme-item-5/README.md")
|
||||
self.assertEqual(self.kept(), {main.worktree_folder(pathlib.Path(top)) for top in ("/code/acme", "/code/acme-item-5")})
|
||||
|
||||
def test_does_nothing_where_the_project_has_no_copies(self):
|
||||
main.pruned(worktree_config("/code/acme"), self.home / "elsewhere", self.listed("/code/acme"))
|
||||
|
||||
|
||||
class Act(unittest.TestCase):
|
||||
|
||||
+42
-16
@@ -70,7 +70,7 @@ def rank(text: str, goals_text: str, decisions: str, history: str, floor: decima
|
||||
ranked = rank_details(rewrite_table(lines, table, shape, scored), [item for item, _ in scored])
|
||||
if isinstance(ranked, Failure):
|
||||
return ranked
|
||||
under_bar = [under_the_bar(item, value, scoring.bar, items) for item, value in scored if not item.exempt and round(value, 1) < scoring.bar]
|
||||
under_bar = [under_the_bar(item, value, scoring.bar, items) for item, value in scored if falls_under(item, value, scoring.bar)]
|
||||
return Ranked(ranked, under_bar, notes(items, scoring))
|
||||
|
||||
|
||||
@@ -115,22 +115,30 @@ def under_the_bar(item: Item, value: float, bar: float, items: list[Item]) -> st
|
||||
|
||||
|
||||
def read_scoring(text: str, lines: list[str], goals_text: str, decisions: str, history: str, shape: Shape, floor: decimal.Decimal) -> Scoring | Failure:
|
||||
goals = ranked_goals(goals_text, decisions)
|
||||
if isinstance(goals, Failure):
|
||||
return goals
|
||||
formula = parse_formula(stated(text, "Score"), variables(shape))
|
||||
if isinstance(formula, Failure):
|
||||
return formula
|
||||
bar = number(stated(text, "Bar"), "the bar")
|
||||
if isinstance(bar, Failure):
|
||||
return bar
|
||||
next_id = stated(text, "Next ID")
|
||||
if isinstance(next_id, Failure) or not re.fullmatch(r"[0-9]+", next_id):
|
||||
return next_id if isinstance(next_id, Failure) else Failure(f"Next ID {next_id!r} is not a whole number")
|
||||
return scoring_of(stated(text, "Score"), number(stated(text, "Bar"), "the bar"), goals_text, decisions, history, floor, shape=shape, lines=lines, next_id=int(next_id))
|
||||
|
||||
|
||||
def config_scoring(formula: str, bar: float, goals_text: str, decisions: str, history: str, floor: decimal.Decimal) -> Scoring | Failure:
|
||||
"""The scoring of a plan in Jira, whose formula and bar the project's config states. Jira numbers the issues, so no Next ID applies."""
|
||||
return scoring_of(formula, bar, goals_text, decisions, history, floor, shape=SHAPE, lines=[], next_id=0)
|
||||
|
||||
|
||||
def scoring_of(formula_text: str | Failure, bar: float | Failure, goals_text: str, decisions: str, history: str, floor: decimal.Decimal, *, shape: Shape, lines: list[str], next_id: int) -> Scoring | Failure:
|
||||
goals = ranked_goals(goals_text, decisions)
|
||||
if isinstance(goals, Failure):
|
||||
return goals
|
||||
formula = parse_formula(formula_text, variables(shape))
|
||||
if isinstance(formula, Failure):
|
||||
return formula
|
||||
if isinstance(bar, Failure):
|
||||
return bar
|
||||
weights = weigh(lines, history, goals, shape, floor)
|
||||
if isinstance(weights, Failure):
|
||||
return weights
|
||||
return Scoring(shape, formula, bar, int(next_id), dict(goals), weights)
|
||||
return Scoring(shape, formula, bar, next_id, dict(goals), weights)
|
||||
|
||||
|
||||
def weigh(lines: list[str], history: str, goals: list[tuple[str, Mark]], shape: Shape, floor: decimal.Decimal) -> dict[str, float] | Failure:
|
||||
@@ -287,19 +295,37 @@ def parse_item(row: str, scoring: Scoring, table: Table) -> Item | Failure:
|
||||
if scoring.shape is OLD_SHAPE:
|
||||
return item
|
||||
# R is written here, as the Score is, so --check finds a stale one, and a reader keeps the R the table stored.
|
||||
return with_risk(item)
|
||||
|
||||
|
||||
def with_risk(item: Item) -> Item:
|
||||
return dataclasses.replace(item, scores=item.scores | {"R": risk(item.scores["L"], item.scores["E"], item.scores["I"])})
|
||||
|
||||
|
||||
def cited_goals_failure(item: Item, scoring: Scoring) -> Failure | None:
|
||||
"""Why the item may not name one of the goals it names, such as one the goals file voids or does not number; None when it may name each. todo_table's parse_moves holds the rules a Moves cell keeps on its own."""
|
||||
def falls_under(item: Item, value: float, bar: float) -> bool:
|
||||
"""Whether the item, which scores value, may not be planned: it scores under the bar, rounded as todo.md shows a Score, and isn't exempt."""
|
||||
return not item.exempt and round(value, 1) < bar
|
||||
|
||||
|
||||
def item_score(item: Item, scoring: Scoring, name: str) -> float | Failure:
|
||||
"""The score of an item that holds no R, such as an issue in Jira; refused where it names a goal it may not. name is what a message calls the item."""
|
||||
if broken := cited_goals_failure(item, scoring, name):
|
||||
return broken
|
||||
value = score(scoring.formula, with_risk(item), scoring)
|
||||
return Failure(f"the formula gives {name} no finite score") if isinstance(value, Failure) else value
|
||||
|
||||
|
||||
def cited_goals_failure(item: Item, scoring: Scoring, name: str = "") -> Failure | None:
|
||||
"""Why the item may not name one of the goals it names, such as one the goals file voids or does not number; None when it may name each. name is what a message calls the item, `item <ID>` where empty. todo_table's parse_moves holds the rules a Moves cell keeps on its own."""
|
||||
name = name or f"item {item.id}"
|
||||
if scoring.shape is OLD_SHAPE:
|
||||
unknown = [goal for goal, _ in item.moves if goal not in scoring.weights]
|
||||
return Failure(f"item {item.id} cites goal {', '.join(unknown)}, which the goal weights do not list") if unknown else None
|
||||
return Failure(f"{name} cites goal {', '.join(unknown)}, which the goal weights do not list") if unknown else None
|
||||
for goal, _ in item.moves:
|
||||
if goal == CODE_HEALTH and goal not in scoring.goals:
|
||||
return Failure(f"item {item.id} names {CODE_HEALTH}, which the goals file voids; drop it from the item's {MOVES}, or the void from the goals file")
|
||||
return Failure(f"{name} names {CODE_HEALTH}, which the goals file voids; drop it from the item's {MOVES}, or the void from the goals file")
|
||||
if goal not in scoring.goals:
|
||||
return Failure(f"item {item.id} cites goal {goal}, which the goals file's ## Goals does not number")
|
||||
return Failure(f"{name} cites goal {goal}, which the goals file's ## Goals does not number")
|
||||
return None
|
||||
|
||||
|
||||
|
||||
@@ -156,18 +156,32 @@ def todos_since(tag: str | None | Failure, ref: str, plan: str | None, cwd: str,
|
||||
def chunk_item(found: list[Item], cut: LastCut) -> Pick:
|
||||
"""The pick from todo.md's items, weighed against the last cut. Routing and chunk-preflight both pick with it, so they name one item."""
|
||||
upcoming = next_release(found, cut)
|
||||
return standing(upcoming, next_item(found), cut.reviewed) if isinstance(upcoming, Upcoming) else upcoming
|
||||
return standing(upcoming, next_item(carried(found, cut)), cut.reviewed) if isinstance(upcoming, Upcoming) else upcoming
|
||||
|
||||
|
||||
def carried(found: list[Item], cut: LastCut) -> list[Item]:
|
||||
"""found, with the release of each item that the plan files under the last cut's version, or an earlier one, replaced by the next release: the earliest after the cut that the plan holds or todo.md has named since it.
|
||||
|
||||
Someone cut a release while it held those items, and the loop works on: lilleman's call, 2026-11-16. found itself where nothing is cut, and where no release after the cut is known, since naming one is the human's.
|
||||
"""
|
||||
version = cut_version(cut)
|
||||
named = named_releases(cut.todos_since)
|
||||
known = {item.release for item in found} | (set() if isinstance(named, Failure) else named)
|
||||
after = set() if version is None else {release for release in known if release > version}
|
||||
if not after or all(item.release >= min(after) for item in found):
|
||||
return found
|
||||
return [dataclasses.replace(item, release=max(item.release, min(after))) for item in found]
|
||||
|
||||
|
||||
def next_release(found: list[Item], cut: LastCut) -> Upcoming | Cut | Unknown:
|
||||
"""The next release after cut, and whether work has landed towards it. found holds the plan's items.
|
||||
|
||||
Cut where the plan files items under the last cut's version or earlier, and Unknown where the tags, or todo.md's texts since the cut, cannot be read.
|
||||
Cut where the plan files items under the last cut's version or earlier and no later release is known for carried to file them under, and Unknown where the tags, or todo.md's texts since the cut, cannot be read.
|
||||
Where the branch has no tag, todos_since holds every version of todo.md, so a release todo.md named whose items are all done still reads as the next release.
|
||||
"""
|
||||
if isinstance(cut.tag, Failure):
|
||||
return Unknown()
|
||||
earliest = min((item.release for item in found), default=None)
|
||||
earliest = min((item.release for item in carried(found, cut)), default=None)
|
||||
version = cut_version(cut)
|
||||
if version is None:
|
||||
return Upcoming(earliest, True, has_unreleased(cut))
|
||||
@@ -186,6 +200,7 @@ def next_release(found: list[Item], cut: LastCut) -> Upcoming | Cut | Unknown:
|
||||
|
||||
def cut_version(cut: LastCut) -> Release | None:
|
||||
"""Which version is cut. It is the tag's, or None where the tag names no version. On a branch with no tag, it is the newest version under a dated CHANGELOG.md heading, else BEFORE_FIRST_RELEASE."""
|
||||
# The loop reads no other mark of a cut, such as another tag spelling or a Jira Fix Version marked released, until lilleman says to add one: his call, 2026-11-16.
|
||||
if cut.tag is None:
|
||||
return dated_cut(cut.tag, cut.changelog) or BEFORE_FIRST_RELEASE
|
||||
return tagged(cut.tag) if isinstance(cut.tag, str) else None
|
||||
|
||||
@@ -271,6 +271,19 @@ class CodeHealth(unittest.TestCase):
|
||||
"""A scoring run's entry, without the history's title."""
|
||||
return SCORED.format(overall=overall).removeprefix("# Comprehension history\n\n").replace("2026-10-08T12", at).replace("PR #1 at aaaaaaa", read)
|
||||
|
||||
def test_a_plan_in_jira_weighs_the_goals_as_todo_md_does(self):
|
||||
# As the two tests below: code health weighs 1 / 1.97 at or over the floor and four times that under it, goal 1 0.97 / 1.97.
|
||||
for floor, code_health in ((DEFAULT_FLOOR, 4 / 1.97), (decimal.Decimal("6.0"), 1 / 1.97)):
|
||||
with self.subTest(floor=floor):
|
||||
stated = ranking.config_scoring("V", 1, self.readme, "", SCORED.format(overall="6.99"), floor)
|
||||
assert not isinstance(stated, Failure), stated
|
||||
self.assertEqual(set(stated.weights), {"code health", "1"})
|
||||
self.assertAlmostEqual(stated.weights["code health"], code_health)
|
||||
self.assertAlmostEqual(stated.weights["1"], 0.97 / 1.97)
|
||||
opted_out = ranking.config_scoring("V", 1, self.readme, "## review opt-out: the comprehension check\n\nCosts rounds.\n", "", DEFAULT_FLOOR)
|
||||
assert isinstance(opted_out, Failure), opted_out
|
||||
self.assertTrue(opted_out.reason.startswith("docs/decisions.md opts out of the comprehension check"), opted_out.reason)
|
||||
|
||||
def test_ranks_code_health_first_among_the_achieve_goals_at_an_overall_of_7_or_above(self):
|
||||
# Code health, then goal 1: weights 1 / 1.97 and 0.97 / 1.97, an item moving one by 1 at S 1 scoring 50 times its weight.
|
||||
self.assertEqual(self.scores(SCORED.format(overall="7.00")), {"| 1": "25.4", "| 2": "24.6"})
|
||||
@@ -461,6 +474,16 @@ class OldShape(unittest.TestCase):
|
||||
|
||||
def test_refuses_an_item_citing_a_goal_the_weights_do_not_list(self):
|
||||
self.assertEqual(self.ranked(OLD_SHAPE.replace("| 2.1, 1 | 0 |", "| 2.1, 9 | 0 |")), Failure("item 3 cites goal 9, which the goal weights do not list"))
|
||||
self.assertEqual(self.ranked(OLD_SHAPE.replace("| 2.1, 1 | 0 |", "| 9, 8 | 0 |")), Failure("item 3 cites goal 9, 8, which the goal weights do not list"))
|
||||
|
||||
def test_refuses_a_bar_or_next_id_that_is_no_number_naming_the_line(self):
|
||||
for todo, reason in (
|
||||
(TODO.replace("`Bar = 2`", "`Bar = x`"), "the bar 'x' is not a finite number"),
|
||||
(TODO.replace("`Next ID = 6`\n", ""), "todo.md states `Next ID = ...` 0 times; state it once, on a line of its own under ## Scoring"),
|
||||
(TODO.replace("`Next ID = 6`", "`Next ID = x`"), "Next ID 'x' is not a whole number"),
|
||||
):
|
||||
with self.subTest(reason=reason):
|
||||
self.assertEqual(self.ranked(todo), Failure(reason))
|
||||
|
||||
def test_refuses_a_formula_over_v(self):
|
||||
self.assertEqual(self.ranked(OLD_SHAPE.replace("-R - S/4 + 2*A + 2*G*W", "V")), Failure("the formula 'V' may hold only numbers, A, G, R, S, W, + - * / ** and parentheses"))
|
||||
|
||||
@@ -77,6 +77,33 @@ class NextRelease(unittest.TestCase):
|
||||
self.assertEqual(release_standing.next_release([one((1, 3, 0))], cut(Failure("count unreadable"))), release_standing.Upcoming((1, 3, 0), True, Failure("count unreadable")))
|
||||
|
||||
|
||||
class Carried(unittest.TestCase):
|
||||
def test_files_each_item_of_a_release_already_cut_under_the_earliest_release_the_plan_names_after_the_cut(self):
|
||||
held = [dataclasses.replace(one((1, 2, 3)), id=1), dataclasses.replace(one((1, 2, 0)), id=2), dataclasses.replace(one((1, 4, 0)), id=3), dataclasses.replace(one((1, 3, 0)), id=4)]
|
||||
carried = release_standing.carried(held, release_standing.LastCut("v1.2.3", "", 4, []))
|
||||
self.assertEqual([(item.id, item.release) for item in carried], [(1, (1, 3, 0)), (2, (1, 3, 0)), (3, (1, 4, 0)), (4, (1, 3, 0))])
|
||||
|
||||
def test_leaves_the_plan_as_it_is_where_nothing_is_cut_or_it_names_no_release_after_the_cut(self):
|
||||
held = [one((1, 2, 3))]
|
||||
for tag in ("v1.2.3", "v1.2.2", None, Failure("tags unreadable")):
|
||||
with self.subTest(tag=tag):
|
||||
self.assertIs(release_standing.carried(held, release_standing.LastCut(tag, "", 4, [])), held)
|
||||
|
||||
def test_files_them_under_a_release_todo_md_named_since_the_cut_though_the_plan_holds_no_item_of_it(self):
|
||||
held = [one((1, 2, 3)), dataclasses.replace(one((1, 4, 0)), id=2)]
|
||||
cut = release_standing.LastCut("v1.2.3", "", 4, naming({(1, 2, 3), (1, 3, 0)}))
|
||||
self.assertEqual([item.release for item in release_standing.carried(held, cut)], [(1, 3, 0), (1, 4, 0)])
|
||||
self.assertEqual(release_standing.chunk_item(held, cut), release_standing.Next((1, 3, 0), dataclasses.replace(held[0], release=(1, 3, 0))))
|
||||
self.assertEqual(release_standing.carried(held[:1], dataclasses.replace(cut, todos_since=Failure("log unreadable"))), held[:1])
|
||||
|
||||
def test_takes_the_cut_releases_item_first_as_the_next_releases(self):
|
||||
held = [dataclasses.replace(one((1, 2, 3)), id=1), dataclasses.replace(one((1, 3, 0)), id=2)]
|
||||
cut = release_standing.LastCut("v1.2.3", "", 4, [])
|
||||
self.assertEqual(release_standing.chunk_item(held, cut), release_standing.Next((1, 3, 0), dataclasses.replace(held[0], release=(1, 3, 0))))
|
||||
self.assertEqual(release_standing.next_release(held, cut), release_standing.Upcoming((1, 3, 0), True, True))
|
||||
self.assertEqual(release_standing.next_release(held[:1], cut), release_standing.Cut((1, 2, 3)))
|
||||
|
||||
|
||||
class ChunkItem(unittest.TestCase):
|
||||
def test_takes_the_earliest_release_where_it_is_the_next_and_else_says_whether_the_next_is_ready_to_cut_or_to_plan(self):
|
||||
cases = (
|
||||
@@ -91,7 +118,8 @@ class ChunkItem(unittest.TestCase):
|
||||
(Failure("tags unreadable"), 4, (0, 2, 0), set(), release_standing.Unknown()),
|
||||
(Failure("tags unreadable"), 4, None, set(), release_standing.Unknown()),
|
||||
("v1.2.3", 4, (1, 2, 3), set(), release_standing.Cut((1, 2, 3))),
|
||||
("v1.2.3", 4, (1, 2, 2), {(1, 2, 4)}, release_standing.Cut((1, 2, 2))),
|
||||
("v1.2.3", 4, (1, 2, 2), set(), release_standing.Cut((1, 2, 2))),
|
||||
("v1.2.3", 4, (1, 2, 2), {(1, 2, 4)}, release_standing.Next((1, 2, 4), one((1, 2, 4)))),
|
||||
("v1.2.3", 4, (1, 3, 0), {(1, 2, 4), (1, 3, 0)}, release_standing.ReadyToCut((1, 2, 4))),
|
||||
("v0.9.2", 4, (1, 0, 0), {(0, 9, 3)}, release_standing.ReadyToCut((0, 9, 3))),
|
||||
("v1.2.3", 4, (1, 4, 0), {(1, 2, 2), (1, 3, 0)}, release_standing.ReadyToCut((1, 3, 0))),
|
||||
@@ -140,7 +168,8 @@ class ChunkItem(unittest.TestCase):
|
||||
self.assertNotEqual(release_standing.chunk_item([], without_unreleased), release_standing.ReviewDue((0, 0, 1)), "0.0.1 is cut under its dated heading")
|
||||
later = [HEADER + ROW.format(id=1, release="0.0.1") + ROW.format(id=2, release="0.1.0"), HEADER + ROW.format(id=2, release="0.1.0")]
|
||||
self.assertEqual(release_standing.chunk_item(plan_under((0, 1, 0)), release_standing.LastCut(None, changelog, 4, later)), release_standing.Next((0, 1, 0), one((0, 1, 0))))
|
||||
self.assertEqual(release_standing.chunk_item(plan_under((0, 0, 1)), release_standing.LastCut(None, changelog, 4, later)), release_standing.Cut((0, 0, 1)))
|
||||
self.assertEqual(release_standing.chunk_item(plan_under((0, 0, 1)), release_standing.LastCut(None, changelog, 4, later)), release_standing.Next((0, 1, 0), one((0, 1, 0))))
|
||||
self.assertEqual(release_standing.chunk_item(plan_under((0, 0, 1)), release_standing.LastCut(None, changelog, 4, history)), release_standing.Cut((0, 0, 1)))
|
||||
|
||||
def test_counts_neither_an_undated_heading_nor_a_heading_behind_a_tag_as_cut(self):
|
||||
history = [HEADER + ROW.format(id=1, release="0.0.1"), HEADER]
|
||||
|
||||
@@ -267,7 +267,7 @@ class Main(unittest.TestCase):
|
||||
result = result if "api_error_status" in result else {"type": "result", "structured_output": {"found": [n + 1 for n in result["found"]]}}
|
||||
return subprocess.CompletedProcess(args, 0, json.dumps(result), "")
|
||||
|
||||
effects = Effects(claude=claude, claude_on_terminal=unused, discard_typed=unused, dm=unused, execv=unused, git=system_effects().git, input=unused, local_time=unused, memory=unused, now=unused, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused)
|
||||
effects = Effects(claude=claude, claude_on_terminal=unused, discard_typed=unused, dm=unused, execv=unused, git=system_effects().git, input=unused, local_time=unused, memory=unused, now=unused, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused, tmux=unused, tmux_on_terminal=unused)
|
||||
out, err = io.StringIO(), io.StringIO()
|
||||
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
|
||||
code = main.main(argv, {}, self.home, effects)
|
||||
|
||||
@@ -1279,7 +1279,7 @@ class TodoRankCheck(unittest.TestCase):
|
||||
|
||||
def test_a_plan_in_jira_is_not_checked_in_the_checkout_or_the_configs_folder(self):
|
||||
checkout = self.changed_plan(f"{self.folder}/clone", self.STUB)
|
||||
self.config.write_text(self.config.read_text().replace('"checkout:todo.md"', '"jira:https://acme.atlassian.net/browse/ABC-12"') + 'env-file = "~/acme.env"\n')
|
||||
self.config.write_text(self.config.read_text().replace('"checkout:todo.md"', '"jira:https://acme.atlassian.net/browse/ABC-12"') + 'env-file = "~/acme.env"\njira-score-formula = "V"\njira-score-bar = 1\n')
|
||||
folder = str(self.config.parent)
|
||||
git(folder, "init", "-q")
|
||||
(self.config.parent / "todo.md").write_text("# todo\n")
|
||||
|
||||
@@ -62,7 +62,7 @@ class Main(unittest.TestCase):
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
config = configured(self, pathlib.Path(temp)) / "config.toml"
|
||||
self.enterContext(contextlib.chdir(temp))
|
||||
config.write_text(config.read_text().replace('"checkout:todo.md"', '"jira:https://acme.atlassian.net/browse/ABC-12"') + 'env-file = "~/acme.env"\n')
|
||||
config.write_text(config.read_text().replace('"checkout:todo.md"', '"jira:https://acme.atlassian.net/browse/ABC-12"') + 'env-file = "~/acme.env"\njira-score-formula = "V"\njira-score-bar = 1\n')
|
||||
todo = pathlib.Path(temp, "todo.md")
|
||||
todo.write_text(TODO)
|
||||
for args in ((), (str(todo),), ("--check", str(todo))):
|
||||
|
||||
+25
-11
@@ -6,12 +6,12 @@ usage: todo-item list [--release <version>]
|
||||
[--blocked-by <IDs>] [--exempt <reason>] <tagline> [<<'EOF' detail EOF]
|
||||
todo-item edit <ID> [--tagline <tagline>] [--l <L>] [--e <E>] [--i <I>] [--s <S>] [--moves <moves>]
|
||||
[--blocked-by <IDs>] [--exempt <reason>] [--detail <<'EOF' detail EOF | --clear-detail]
|
||||
[--comment <why>]
|
||||
todo-item move <ID> --release <version>
|
||||
todo-item finish <ID> [--changelog <bullet> | --no-changelog]
|
||||
|
||||
Run inside a checkout. Every command works on the plan the project's config names, which
|
||||
`project-config plan` prints: a markdown file, todo.md, or a Jira epic. In a Jira epic, list,
|
||||
show, add and finish work, and edit and move fail so far. Each command that changes
|
||||
`project-config plan` prints: a markdown file, todo.md, or a Jira epic. Each command that changes
|
||||
a todo.md ranks it as rank_todo.py does, and so reads the goals file, docs/decisions.md and the
|
||||
comprehension history, each where the config puts it.
|
||||
The cells take the format rank_todo.py --help states; the letter flags take upper case too, as --L.
|
||||
@@ -28,19 +28,32 @@ list and show read only the plan, and print no Score: an item's place in list's
|
||||
add files the item under the next free ID, with the tagline in bold, and the detail it reads from
|
||||
stdin, if any. The detail may hold no ## or ### heading.
|
||||
It prints `Filed item <ID> in <plan>.` It doesn't write anything where ranking fails or scores the item under the bar.
|
||||
In a Jira epic, add files a Task under the epic, last in the backlog, and <ID> is the new issue's
|
||||
number. The release must be one of the Jira project's Fix Versions, named as 1.2.0 or v1.2.0 there,
|
||||
and --exempt security also labels the issue `security`. No bar applies there yet. Where Jira files
|
||||
the issue and then refuses a --blocked-by link, add still prints `Filed item <ID> …`, and says on
|
||||
stderr which link to make in Jira.
|
||||
In a Jira epic, add files a Task under the epic, and <ID> is the new issue's number. The release
|
||||
must be one of the Jira project's Fix Versions, named as 1.2.0 or v1.2.0 there, and --exempt
|
||||
security also labels the issue `security`. The item scores by the config's `jira-score-formula`, and
|
||||
add refuses it under `jira-score-bar` unless it is exempt. add then asks Jira to rank the new issue
|
||||
just before the first issue the loop filed that ranks after it: a question before any other, then a
|
||||
security finding, then the higher score. Where none does, it stays last. A person's issues don't
|
||||
count, and keep their rank. Where Jira files the issue and then refuses a --blocked-by link or the
|
||||
rank, add still prints `Filed item <ID> …`, and says on stderr what to do in Jira.
|
||||
|
||||
edit sets the cells whose flag is given and leaves the rest; an empty value, as in --blocked-by "",
|
||||
empties the cell. --detail replaces the detail with the text on stdin, and --clear-detail removes it.
|
||||
Text on stdin without --detail, and --detail without text on stdin, are refused, so no detail is
|
||||
dropped or wiped by mistake. It prints `Edited item <ID> in <plan>.` It doesn't write anything where
|
||||
ranking fails or scores the item under the bar.
|
||||
In a Jira epic, edit changes an issue the loop filed: its summary, description and scores, and
|
||||
the label `security` with --exempt. It doesn't change a link, so --blocked-by fails.
|
||||
Of an issue a person filed it sets only the scores, --moves and --exempt, and only with --comment.
|
||||
The four scores are set together where the issue holds none yet.
|
||||
--comment is posted as a comment on the Jira issue, for the client's team, in the project's
|
||||
language. Jira doesn't show the team the scores, so say that the issue is scored, and why.
|
||||
A todo.md keeps no comment, so there the flag doesn't do anything.
|
||||
Where Jira takes the edit and then refuses the comment, edit still prints `Edited item <ID> …`,
|
||||
and says on stderr to post the comment in Jira.
|
||||
|
||||
move sets the item's release, as edit sets a cell. It prints `Moved item <ID> to release <version> in <plan>.`
|
||||
In a Jira epic, move sets the Fix Version of an issue the loop filed; a person moves their own.
|
||||
|
||||
finish removes the item and its detail. With --changelog it adds the bullet first under
|
||||
CHANGELOG.md's ## Unreleased, or a ## heading that says unreleased, creating the section, or the
|
||||
@@ -56,9 +69,9 @@ from its present status, or where the transition leads to another status or to o
|
||||
count as done. An issue that no chunk built is dropped in Jira, not with finish, which would mark it done.
|
||||
|
||||
Exit 2 on bad arguments, and 1, saying why, on any other failure. A message opening `not filed:`,
|
||||
`not edited:`, `not moved:` or `not finished:` means it didn't write anything. The one exception is an add to, or a
|
||||
finish in, a Jira epic that Jira didn't answer or answered brokenly: the message then says the issue
|
||||
may exist, or may have moved.
|
||||
`not edited:`, `not moved:` or `not finished:` means it didn't write anything. The one exception is an add,
|
||||
an edit, a move or a finish in a Jira epic that Jira didn't answer or answered brokenly: the message then
|
||||
says the issue may exist, may have changed or may have moved.
|
||||
"""
|
||||
import argparse
|
||||
import pathlib
|
||||
@@ -126,6 +139,7 @@ def parser() -> argparse.ArgumentParser:
|
||||
detail = editing.add_mutually_exclusive_group()
|
||||
detail.add_argument("--detail", action="store_true")
|
||||
detail.add_argument("--clear-detail", action="store_true")
|
||||
editing.add_argument("--comment")
|
||||
moving = commands.add_parser("move")
|
||||
moving.add_argument("id", type=int)
|
||||
moving.add_argument("--release", required=True)
|
||||
@@ -199,7 +213,7 @@ def edit(args: argparse.Namespace, plan: PlanStore, text: str) -> str | Failure:
|
||||
detail = text if args.detail else "" if args.clear_detail else None
|
||||
if not fields(args) and detail is None:
|
||||
return Failure("not edited: no flag names a change; todo-item --help lists them")
|
||||
return reported(plan.edit(args.id, fields(args), detail), "not edited", lambda written: f"Edited item {written.id} in {plan.label}.")
|
||||
return reported(plan.edit(args.id, fields(args), detail, args.comment), "not edited", lambda written: f"Edited item {written.id} in {plan.label}.")
|
||||
|
||||
|
||||
def finish(args: argparse.Namespace, plan: PlanStore, changelog: RecordStore) -> str | Failure:
|
||||
|
||||
@@ -13,6 +13,7 @@ from project_config.settings import DEFAULT_FLOOR
|
||||
from todo_item import edits, main
|
||||
from failure import Failure
|
||||
from project_config.main import located
|
||||
from plan_store.fakes import MemoryPlan
|
||||
from release_plan import plan_file, ranking
|
||||
from plan_store.stores import plan_of
|
||||
from todo_item.table import table
|
||||
@@ -415,6 +416,18 @@ class Edit(TodoItem):
|
||||
|
||||
def test_refuses_an_edit_that_changes_nothing(self):
|
||||
self.assertEqual(self.run_main("edit", "3"), (1, "", "not edited: no flag names a change; todo-item --help lists them\n"))
|
||||
self.assertEqual(self.run_main("edit", "3", "--comment", "Why.")[::2], (1, "not edited: no flag names a change; todo-item --help lists them\n"))
|
||||
|
||||
def test_an_edit_hands_the_comment_to_the_plan(self):
|
||||
for argv, comments in ((["--comment", "A small change."], {3: ["A small change."]}), ([], {})):
|
||||
with self.subTest(argv=argv):
|
||||
plan = MemoryPlan({3: {"Release": "0.1.0", "Item": "**Count the runs.**", "L": "1", "E": "2", "I": "3", "S": "1"}})
|
||||
self.assertEqual(main.edit(main.parser().parse_args(["edit", "3", "--l", "3", *argv]), plan, ""), "Edited item 3 in the plan in memory.")
|
||||
self.assertEqual((plan.rows[3]["L"], plan.comments), ("3", comments))
|
||||
|
||||
def test_a_plan_in_a_file_takes_an_edit_with_a_comment_and_keeps_no_comment(self):
|
||||
self.assertEqual(self.run_main("edit", "3", "--l", "3", "--comment", "A small change.")[:2], (0, f"Edited item 3 in {self.todo}.\n"))
|
||||
self.assertNotIn("A small change.", self.todo.read_text())
|
||||
|
||||
def test_leaves_the_file_ranked(self):
|
||||
self.run_main("edit", "1", "--s", "2", "--moves", "1 by 10")
|
||||
|
||||
@@ -3819,3 +3819,163 @@ Inherited architect, decided by:
|
||||
- Locality: `bin/review_rules/review_folder.py:17` `made_review_folder`: `home` is passed in from the command table, so each unit's inputs show in its signature; at the base `Path.home()` was read deep inside
|
||||
- Shape: `bin/larv_review/scoring_setup.py:169` `prepare_scoring`: counts against the change: about 75 lines with a dozen early returns, and `prompt_parts` builds one path twice
|
||||
- Shape: `bin/review_rules/round_titles.py:13` `OPENING`: the round-title spelling is written once next to the regexes that parse it
|
||||
|
||||
## 2026-11-15T21:26:29Z, PR #554 at bcb04e3
|
||||
|
||||
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|
||||
|---|---|---|---|---|---|
|
||||
| Junior A | 6.5 | 5 | 5.5 | 5 | 5.5 |
|
||||
| Mid A | 7 | 6 | 6.5 | 6 | 6.5 |
|
||||
| Maintainability senior | 7 | 5.5 | 6 | 6 | 6 |
|
||||
| Inherited architect | 6.5 | 6 | 5.5 | 5.5 | 6 |
|
||||
| Mean | 6.75 | 5.63 | 5.88 | 5.63 | 6.00 |
|
||||
|
||||
Junior A, hardest first:
|
||||
|
||||
- Locality, Self-sufficiency: `bin/loop_claude/routing.py:113` `unfinished_route`: five rung notions, two step-up counters and a seven-row verdict table at once, and the reasons in the decision log
|
||||
- Shape: `bin/release_plan/release_standing.py:162` `next_release`: many edge-case branches and `str | None | Failure` threaded through every field of `LastCut`
|
||||
- Locality, Shape: `bin/loop_claude/cycle/run.py:151` `rule`: judges, stamps, annotates, steps the rung up and archives, and no single unit owns the archive's order
|
||||
- Self-sufficiency: `bin/loop_claude/cycle/judge.py:22` `INTERRUPT_RULES`: policy partly in prompt text and partly in Python checks, with nothing saying which the code enforces
|
||||
- Locality: `bin/loop_claude/loop/reload.py:95` `exec_if_edited`: an edit to any `.py` under `bin/` makes a running loop re-exec, and a renamed `LoopRun` field breaks the reload
|
||||
- Shape: `bin/model_routing/ladder.py:86` `review_rung`: a three-way rule whose docstring quotes a whole decision title
|
||||
- Self-sufficiency: `bin/larv_review/main.py:1` module docstring: twelve subcommands' rules in about 155 lines of prose that cross-reference SKILL.md
|
||||
- Shape: `bin/loop_claude/loop/chunk_start.py:24` `fetched_todo`: nearly the same plan read as `fetched_plan`, told apart only by a docstring
|
||||
|
||||
Mid A, hardest first:
|
||||
|
||||
- Shape: `bin/release_plan/release_standing.py:162` `next_release`: a three-state tag, `BEFORE_FIRST_RELEASE`, `nothing_cut` and `is_earliest` held at once, and comments that explain each branch alone
|
||||
- Locality: `bin/loop_claude/routing.py:113` `unfinished_route`: five rungs, the escalation mark and the unfinished count feed one answer across three files
|
||||
- Locality, Shape: `bin/chunk_pr/main.py:298` `merged`: a while loop around the queue turn, variables bound only on some paths, and no comment stating the loop's invariant
|
||||
- Shape: `bin/chunk_preflight/main.py:128` `preflight`: lines 142-143 pack a conditional re-`located` and an eight-argument `Gathered` into two lines
|
||||
- Shape: `bin/release_plan/ranking.py:48` `rank`: two table shapes branch through the whole module, and the defect rule sits far from where scores are read
|
||||
- Self-sufficiency: `bin/larv_review/plan.py:77` `plan_reasons`: six inputs joined into one answer, and why each matters is in SKILL.md §3
|
||||
- Shape: `bin/rule_hook/env_file.py:34` `reaching`: `and` and `or` mixed without parentheses, and four path spellings in a lookaround regex
|
||||
- Self-sufficiency: `bin/loop_claude/cycle/judge.py:197` `quotes_checked`: long prompt text inside the `Reply` field metadata mixes the prompt with the schema
|
||||
|
||||
Maintainability senior, hardest first:
|
||||
|
||||
- Locality, Shape: `bin/chunk_pr/main.py:298` `merged`: a while loop holding a queue turn, approval waits and a `done` set only on some paths, with no loop invariant stated
|
||||
- Locality, Self-sufficiency: `bin/loop_claude/routing.py:113` `unfinished_route`: five rungs, the escalation count and the mark from another file, and each step's reason in the decision log
|
||||
- Locality, Self-sufficiency: `skills/larv-review/SKILL.md:146` "Comprehension check": paragraphs of four or five conditions, each pointing to a hook, a CLI's help or another rule file
|
||||
- Shape: `bin/release_plan/release_standing.py:162` `next_release`: three sources of a cut, the `is_earliest` expression and `LastCut` fields typed `str | None | Failure`
|
||||
- Shape: `bin/release_plan/ranking.py:136` `weigh`: two live table shapes double every path, and `Shape` is built from positional tuples of callables
|
||||
- Locality, Shape: `bin/loop_claude/cycle/run.py:151` `rule`: judges, stamps, archives and steps up, beside a 17-field `Cycle` passed around whole
|
||||
- Shape: `bin/chunk_pr/main.py:438` `remeasure`: control flow inside chained `isinstance(x, Failure) or …` expressions, and `finished` unpacks five runs by position
|
||||
- Shape: `bin/chunk_preflight/main.py:128` `preflight`: the whole fallback logic packed into lines 142-143
|
||||
|
||||
Inherited architect, would restructure first:
|
||||
|
||||
- Navigation, Shape: `README.md:193` the `bin/` roles: about 70 flat entries under `bin/`, where only this list tells a tool from a library
|
||||
- Navigation, Shape: `bin/larv_review/main.py:222` `COMMANDS`: the package named for the review mostly holds the comprehension check, and the review loop is prose in SKILL.md
|
||||
- Locality, Shape: `bin/chunk_pr/main.py:384` `levelled_and_finished`: merges, finishes items, pushes, asks whether a scoring run is owed and remeasures under a name that gives two of the five
|
||||
- Locality: `bin/chunk_pr/main.py:349` `unplanned`: matches the error text of `todo-item show`, as `finished` does, where `plan_store` reads the plan
|
||||
- Navigation: `bin/rule_hook/round_cap.py:10` `round_cap_breaches`: the round cap is enforced in the hook, not in `larv_review`, where a reader looks first
|
||||
- Shape: `bin/deploy_release/forge.py:1` module: the forge lives in `deploy_release` and in `chunk_preflight.choices.forge_of`, neither a home its name gives
|
||||
- Shape: `bin/rule_hook/rules.py:26` `RULES`: the file is the registry and also four rules' checkers, so where a new rule goes is undecided
|
||||
- Self-sufficiency: `bin/plan_store/stores.py:5` module docstring: cites plan items 365, 366 and 368 as part of the contract, as routing and ladder code cite decisions
|
||||
|
||||
## 2026-11-16T12:09:27Z, PR #560 at 55235a0
|
||||
|
||||
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|
||||
|---|---|---|---|---|---|
|
||||
| Junior A | 7 | 5.5 | 6.5 | 6 | 6 |
|
||||
| Mid A | 7.5 | 6.5 | 7 | 6.5 | 7 |
|
||||
| Maintainability senior | 7 | 6 | 6.5 | 6 | 6.5 |
|
||||
| Inherited architect | 7 | 6.5 | 6 | 6 | 6.5 |
|
||||
| Mean | 7.13 | 6.13 | 6.50 | 6.13 | 6.50 |
|
||||
|
||||
Junior A, hardest first:
|
||||
|
||||
- Locality: `skills/larv-review/SKILL.md:90` "Re-entry": six rules held at once with the round cap, the release-review caps and the mechanical-answers exception, as dense prose rather than a decision table
|
||||
- Locality, Self-sufficiency: `bin/release_plan/release_standing.py:176` `next_release`: three sources of the cut version and release names replayed from todo.md's history; `is_earliest` carries the meaning of "the plan is current" without naming it
|
||||
- Locality: `bin/loop_claude/routing.py:116` `unfinished_route`: five rungs, a counter and an escalation mark from another module; the docstring table makes it tractable
|
||||
- Shape: `bin/release_plan/ranking.py:239` `score`: the OLD_SHAPE and SHAPE split runs through every layer, and `weight_of` packs a three-way rule into one line
|
||||
- Self-sufficiency: `bin/loop_claude/cycle/judge.py:197` `quotes_checked`: six quote kinds each with its own fallback; `INTERRUPT_RULES` is behaviour the code cannot verify
|
||||
- Locality: `bin/loop_claude/cycle/run.py:154` `rule`: the order of stamping, archiving and stepping matters across three functions
|
||||
- Shape: `bin/loop_claude/cycle/prompts.py:66` `review_launches`: a prompt assembled from five helpers that may each return nothing
|
||||
|
||||
Mid A, hardest first:
|
||||
|
||||
- Locality: `bin/loop_claude/routing.py:116` `unfinished_route`: five interacting rungs, a counter and an escalation mark; the module table resolves it, the escalation-mark rule must stay open beside it
|
||||
- Locality: `bin/release_plan/release_standing.py:176` `next_release`: four cut cases plus renamed releases; the order of the checks carries meaning the docstrings don't explain
|
||||
- Locality: `bin/chunk_pr/main.py:298` `merged`: a loop around a flock with approval and comment checks and two exception exits; `done` assigned only under branches
|
||||
- Self-sufficiency: `bin/loop_claude/cycle/judge.py:197` `quotes_checked`: the prompt text at `judge.py:22` is behaviour written as English
|
||||
- Shape: `bin/release_plan/ranking.py:239` `score`: two table shapes double the branches, and `weight_of`'s defect rule needs a second read
|
||||
- Self-sufficiency: `bin/rule_hook/repeat_read.py:114` `shown_lines`: ISO-string time comparisons and harness behaviour nothing else lets a reader check
|
||||
- Locality: `skills/larv-review/SKILL.md:82` "Round cap": Done, Cap and Re-entry cross-reference each other and point out to three other files
|
||||
- Shape: `bin/chunk_pr/main.py:407` `finished`: five subprocess results destructured by position
|
||||
|
||||
Maintainability senior, hardest first:
|
||||
|
||||
- Locality: `bin/release_plan/release_standing.py:176` `next_release`: four regimes at once; `carried` reapplied in three places, one relying on `zip` keeping order
|
||||
- Locality: `bin/release_plan/ranking.py:239` `score`: one Score depends on five inputs held in other files, and the two shapes fork every function
|
||||
- Locality: `bin/loop_claude/routing.py:116` `unfinished_route`: rungs, a counter and a mark interact; the table resolves most of it
|
||||
- Locality: `bin/loop_claude/loop/chunk_windows.py:107` `start_chunks`: about 40 lines under one flock that check the owner, split running from stopped, compute room, read the plan and filter, with local state tracked by hand
|
||||
- Self-sufficiency: `bin/loop_claude/cycle/judge.py:197` `quotes_checked`: behaviour split between English rules for a model and verbatim checks
|
||||
- Shape: `bin/plan_store/jira_epic.py:356` `revision_of`: indexes an untyped tuple from `scores` at `jira_epic.py:530`
|
||||
- Locality: `skills/larv-review/SKILL.md:82` "Round cap": dense rules with exceptions pointing to other sections and files
|
||||
- Self-sufficiency: `bin/larv_review/main.py:1` the module docstring: the whole contract of ten subcommands in one block
|
||||
|
||||
Inherited architect, would restructure first:
|
||||
|
||||
- Navigation, Shape: `bin/release_plan/todo_table.py:1` the plan model: lives under `release_plan/`, while the plan is also in `plan_store/`, `todo_item/`, `rank_todo.py` and `larv_review/plan.py`, under three names
|
||||
- Locality: `bin/review_rules/round_titles.py:63` `past_cap`: the round cap is split across this, `rule_hook/round_cap.py:10`, `larv-review round-count` and SKILL.md's "Round cap"
|
||||
- Shape: `bin/release_plan/named_code.py:5` `named_paths`: nothing in the module is code
|
||||
- Shape: `bin/loop_claude/verdicts.py:11` `TakenIn.highest_likelihood`: L is a likelihood in the field and a level in the prose
|
||||
- Shape: `bin/loop_claude/loop/routing_check.py:20` the routing check: "routing" names four concepts across `model_routing/`, `routing_figures/` and this module
|
||||
- Navigation: `README.md:197` the `bin/` package list: the 72-entry `bin/` level has only the README's two lists as its index
|
||||
- Self-sufficiency: `bin/review_rules/round_titles.py:7` `CAP`: the why is deferred to a decision-log title in a 200 KB file
|
||||
|
||||
## 2026-11-16T12:13:26Z, PR #560 rerun at 55235a0
|
||||
|
||||
| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall |
|
||||
|---|---|---|---|---|---|
|
||||
| Junior A | 7.5 | 6 | 7 | 6.5 | 6.5 |
|
||||
| Mid A | 7 | 5.5 | 6 | 5.5 | 6 |
|
||||
| Maintainability senior | 8 | 6.5 | 7 | 7 | 7 |
|
||||
| Inherited architect | 7 | 6.5 | 6 | 7 | 6.5 |
|
||||
| Mean | 7.38 | 6.13 | 6.50 | 6.50 | 6.50 |
|
||||
|
||||
Junior A, hardest first:
|
||||
|
||||
- Locality, Self-sufficiency: `bin/release_plan/release_standing.py:176` `next_release`: five `LastCut` fields, a sentinel, renames and carried items at once; the `is_earliest` expression stayed opaque, and the full case table lives only in chunk-preflight's help
|
||||
- Locality: `bin/loop_claude/routing.py:116` `unfinished_route`: the escalation mark spans `escalation_mark.py`, `judge.py`, `verdicts.py`, `route.py` and `reload.py`
|
||||
- Self-sufficiency: `bin/rule_hook/folder_search.py:89` `skips`: mirrors rg's and ag's flag handling, which nothing in the repo lets a reader check
|
||||
- Shape: `bin/release_plan/ranking.py:239` `score`: the old-shape branches run through every function of ranking
|
||||
- Locality: `bin/loop_claude/cycle/judge.py:197` `quotes_checked`: the verdict changes shape in three places after the checks
|
||||
- Navigation: `bin/larv_review/main.py:1` the help docstring: 155 lines of rules, with no pointer to the module that enforces each
|
||||
- Locality: `bin/rule_hook/reviewer_rung.py:19` `SEAT`: a launch counts as a review by matching prompt sentences kept in Markdown
|
||||
- Locality: `bin/loop_claude/loop/reload.py:97` `exec_if_edited`: a running loop re-executes itself on any edit and hands its state over as JSON
|
||||
|
||||
Mid A, hardest first:
|
||||
|
||||
- Locality: `bin/chunk_pr/main.py:298` `merged`: `done` bound only under some branches, and the approval wait is a fall-through rather than a named branch; `levelled_and_finished` returns a finish failure only after the push
|
||||
- Locality: `bin/loop_claude/routing.py:116` `unfinished_route`: five rungs, a counter and a mark; only the module table makes the step line readable
|
||||
- Self-sufficiency: `bin/release_plan/release_standing.py:176` `next_release`: three kinds of "none", and the reason `carried` rewrites releases is a dated call with no rule in the code
|
||||
- Shape: `bin/release_plan/ranking.py:239` `score`: two table shapes through every function, and `MAINTAIN_WEIGHT`'s reason in the decision log
|
||||
- Self-sufficiency: `bin/loop_claude/cycle/judge.py:197` `quotes_checked`: the judge's prompt is spread over field metadata, rule constants and a sentence from `escalation_mark.py`
|
||||
- Locality: `skills/larv-review/SKILL.md:35` "§3. Passes": control flow as prose whose sub-sections point at each other, enforced only partly by code
|
||||
- Locality: `bin/rule_hook/rules.py:26` `RULES`: each rule's spec is a paragraph apart from the module that implements it
|
||||
- Self-sufficiency: `bin/larv_review/main.py:1` the module docstring: the only full spec of a dozen subcommands
|
||||
|
||||
Maintainability senior, hardest first:
|
||||
|
||||
- Locality: `bin/release_plan/release_standing.py:176` `next_release`: state from git history, a sentinel, and `carried` run twice, whose agreement must be checked by hand
|
||||
- Locality: `bin/loop_claude/routing.py:116` `unfinished_route`: five rungs, a count and a mark; table cells need the `steps` docstring to parse
|
||||
- Shape: `bin/release_plan/ranking.py:144` `weigh`: two table shapes through every step, and `Scoring.weights` means different things per shape
|
||||
- Shape: `bin/plan_store/jira_epic.py:356` `revision_of`: indexes the untyped tuple `scores` returns by position
|
||||
- Locality: `bin/loop_claude/loop/chunk_windows.py:107` `start_chunks`: a flock, running and dead windows, `leaving`, `room`, the restart of stopped windows, held items and a NoItem fallback in one function, with the limit applied again in `may_start`
|
||||
- Locality: `bin/chunk_pr/main.py:298` `merged`: whether `done` is bound when read depends on three `if ready` branches lining up
|
||||
- Self-sufficiency: `bin/loop_claude/cycle/judge.py:22` `INTERRUPT_RULES`: what the model is asked and what code checks need both files open
|
||||
- Self-sufficiency: `bin/rule_hook/rules.py:44` `RULES`: the env-file-read spec is a 120-word string kept in step with code elsewhere
|
||||
|
||||
Inherited architect, would restructure first:
|
||||
|
||||
- Locality, Shape: `bin/plan_store/stores.py:1` the plan store: `release_plan` and `plan_store` import each other, and the goals file sits under `release_plan`
|
||||
- Shape: `bin/larv_review/plan.py:22` `scoring_run_due`: the scoring-run trigger is spread over `plan.py`, `owed.py`, `unmeasured.py` and `scoring.py`, and `plan.py` isn't about the plan
|
||||
- Locality: `bin/review_rules/round_titles.py:45` the round cap: constants, commit enforcement in `rule_hook/round_cap.py:10`, the launch refusal in `larv_review/reviewer_header.py:73`, the printout and SKILL.md's prose
|
||||
- Shape: `bin/loop_claude/cycle/run.py:55` `Cycle.todo`: says todo.md where the plan may be a Jira epic, as `fetched_todo` and `INTERRUPT_RULES` do
|
||||
- Shape: `bin/loop_claude/hand_over.py:23` `hand_over`: shares its name with the reload's handover of state in `loop/reload.py:36` `decode_handed`
|
||||
- Locality: `bin/loop_claude/loop/close.py:18` `closed_cycle`: a second "close" beside `cycle/run.py:234` `close`
|
||||
- Navigation, Shape: `README.md:197` the `bin/` package list: 74 entries at one level with the README's list as the only index
|
||||
- Self-sufficiency: `bin/loop_claude/loop/routing_check.py:1` the module docstring: names `state.CYCLES_PER_CHECK` without saying which module `state` is
|
||||
|
||||
+42
-13
@@ -15,9 +15,10 @@ Each project principle states one rule that the decisions below apply; their ent
|
||||
- bin/: a test parametrizes its cases with `subTest`, since pytest's `parametrize` doesn't reach a unittest `TestCase`
|
||||
- bin/: the tools run on the host's Python, with no container, and so do their tests outside CI
|
||||
- bin/: the tools support only the latest stable Python, and the tests, written in plain unittest, run on it in four pytest-xdist workers
|
||||
- chunk-pr: the chunks of a project merge one at a time on a machine, each finishing its plan items in its turn, and a pull request that waits for an approval leaves the queue while it waits
|
||||
- deploy: this repo keeps no `AGENTS.md`, since `~/.claude` is its checkout; its principles and decision titles head `docs/decisions.md`, its working rules follow them there, and its `.claude/settings.json` excludes every `.claude/CLAUDE.md`, so a session in the clone loads only the clone's `CLAUDE.md`
|
||||
- loop-claude: each verdict records the claude-config release and commit that ran it, the raw tokens each thread spent by model and kind since the previous outcome that recorded a spend, and the human's typed answer the judge quotes as reversing a choice the worker took on its own recommendation
|
||||
- loop-claude: one session per running loop of a project, named after the slot the loop holds, its id derived from that name; a chunk's commit in the config's folder takes only the file it changed
|
||||
- loop-claude: each chunk runs in its own tmux window, of one tmux session per project, up to `parallel-chunks` at once, and needs tmux 3.2; its claude session is named after its window, its id derived from that name; a chunk's commit in the config's folder takes only the file it changed
|
||||
- machine load: a heavy command waits for one of the machine's heavy slots, one for every 4 CPUs, which every session shares, and loop-claude starts a worker only while at least a quarter of the machine's memory is available
|
||||
- principles: about seven things per level, four or five where they act on each other, more where a reader finds them by name; crossing a limit asks for a grouping or a recorded reason
|
||||
- project config: a record may name a Confluence Cloud page as `confluence:` and its address, the loop reads and writes it as markdown, and a write never overwrites a save made since the loop's read
|
||||
@@ -78,6 +79,20 @@ Valid while the archive's file names, the Vocabulary and the panel keep these wo
|
||||
|
||||
2026-10-28, lilleman, through todo item 245. Serves goal 1.5: the suite gates every chunk. The suite took 198 s, 102 s of which went to rerunning it on the oldest Python README Install named, 3.11. README Install now asks for the latest stable Python as `python3`, and mypy checks every tool under `bin/` for the version Install names. README's Test line runs the tests in four pytest-xdist workers through `uvx`: 29 s on a 16-CPU machine. Four is one heavy slot's CPUs, `CPUS_PER_SLOT` in `bin/machine_load/slots.py`, so a gate under `run-heavy` loads only the slot it waits for. The line pins pytest and pytest-xdist, as `test_types.py` pins mypy, so every machine runs the gate the same way. It passes the path of `python3`, since `uvx --python python3` picks a Python uv installed itself, which may be older. The tests use stdlib `unittest` alone, and pytest only runs them, so plain `python3 -m unittest` runs the same tests one at a time and another runner can replace pytest. Valid while every machine taking the checkout gets the latest stable Python soon after its release.
|
||||
|
||||
## chunk-pr: the chunks of a project merge one at a time on a machine, each finishing its plan items in its turn, and a pull request that waits for an approval leaves the queue while it waits
|
||||
|
||||
2026-11-15, lilleman's call of 2026-11-13 in item 374, which split item 361. Serves goals 1.5 and 1.4: with several chunks open, every chunk removed its item from `todo.md` and added a bullet to `CHANGELOG.md` in its branch, so each merge left the others a conflict, a gate rerun and often a review round. `chunk-pr merge --finish <ID>` now makes those edits in the chunk's turn, on top of every chunk merged before. The worker's choices follow. The first differs from the call, and the rest settle what it left open:
|
||||
|
||||
- **A merge of the default branch, where the call said rebase.** A rebase rewrites commits the pull request already shows. The forge then drops the approval and the review threads' places. rule-hook counts a pass's rounds by the branch's commit titles, and a rebase gives each of those commits a new hash. `chunk-pr sync` already merges, and the turn reuses it.
|
||||
- **The queue is a file in the git folder the checkout's worktrees share**, held with flock for the turn (`bin/chunk_pr/main.py` → `QUEUE`). Every chunk of the project on the machine finds it without a config or a key. Two machines don't share it: there the second chunk merges without the first one's changes in its head, unless the branch protection requires an up-to-date branch. A turn lasts as long as its checks, which chunk-pr waits 30 minutes for on Gitea. So a merge waits 30 minutes for its turn, then fails naming the pull request that held the queue last, whose number the holder writes into the file.
|
||||
- **The turn holds the queue through the checks**, so what merges is what the checks ran on. A project without forge checks waits the minute `chunk-pr --help` names.
|
||||
- **The wait for an approval is outside the turn.** The first turn pushes the finished branch, so the approver reads what merges. Once approved, the pull request takes a new turn. Where the default branch moved meanwhile, that turn merges it in, and a branch protection that dismisses approvals on a push asks the approver again. A finish that fails is pushed with whatever the turn merged in, so the pull request's head stays the commit checked out. `larv-review scoring-run-owed` runs after the finish is committed, since it counts as shipped the items the committed plan no longer holds.
|
||||
- **A reviewer's comment ends the wait, in place of the loop watching for one.** `chunk-pr merge` runs in the worker's own session, so its failure is what resumes the worker, which answers and runs it again. A comment that waits is a review thread nobody resolved whose last comment someone other than the pull request's author wrote: the worker answers as that author, so an answered thread waits for the reviewer again. A comment outside a thread doesn't end the wait, since bots write those too. An approved pull request with such a thread stays unmerged too: a client's reviewer who approves and asks for one more thing gets an answer first.
|
||||
- **A paired ruling runs again once the default branch has moved past it**, on the last measured commit as before: `review: the comprehension check records …` says why the base stays. `chunk-pr merge` stops while the default branch holds commits the branch's last commit of a ruling doesn't, whoever merged them in: the turn, `chunk-pr sync` or the worker after a conflict. What the ruling says never stops the merge (project principle 2). A scoring run reads no base, so it stays.
|
||||
- **An item the plan doesn't hold is named on merge's last line, not refused.** chunk-pr cannot tell an item an earlier run finished from a mistyped ID, so the reader does. Such a run still commits the plan and the changelog, since the earlier run may have stopped between `todo-item finish` and its commit. chunk-pr checks that an ID is a number before its turn, and leaves every other rule of `todo-item finish` to that tool.
|
||||
|
||||
Valid while a chunk's worker runs `chunk-pr merge` itself, and one machine runs a project's loops.
|
||||
|
||||
## chunks: a chunk takes every unblocked item of its release that fires the same review passes, whatever its purpose, and an item above R 5 ships alone
|
||||
|
||||
2026-10-22, lilleman, through todo item 217. Serves goal 1.4: each review has a fixed cost, so more items per chunk cost less per item. Across the 165 finished chunks loop-claude archived up to that day, a chunk took a median of 1.30M tokens with one item and 1.33M with two, and three in four chunks shipped one item. The old rule also asked one PR title to state what the items achieve together; lilleman dropped it, since unrelated items that fire the same passes cost one review.
|
||||
@@ -142,17 +157,25 @@ Valid while `~/.claude` is a checkout of this repo.
|
||||
|
||||
2026-09-30, lilleman. Applies "Always grant explicit access to data": the sandbox `loop-claude` runs in is where access is granted, so the worker and the claude an interrupt opens run with `bypassPermissions`. The worker may read `~/.claude/.credentials.json`: it holds Claude Code's own credentials, which claude reads to run anyway. Its one seam to production is the forge: what it pushes or merges can publish through CI. Valid while `loop-claude` runs only in the sandbox README → Install names.
|
||||
|
||||
## loop-claude: one session per running loop of a project, named after the slot the loop holds, its id derived from that name; a chunk's commit in the config's folder takes only the file it changed
|
||||
## loop-claude: each chunk runs in its own tmux window, of one tmux session per project, up to `parallel-chunks` at once, and needs tmux 3.2; its claude session is named after its window, its id derived from that name; a chunk's commit in the config's folder takes only the file it changed
|
||||
|
||||
2026-09-21, lilleman; revised 2026-09-30 by lilleman. Serves goal 1. Ids derived from names keep the session picker at one entry per running loop and make any transcript under those ids loop-claude's own to delete. A checkout outside `~/code` mirroring a path inside it shares that id, and a second loop on it is not refused. Once `todo.md` item 5 lands, the id comes from the full path, so no two checkouts share one, and `loop-claude` refuses to start while another session on that id is active. Moving the checkout orphans its open sessions, archive folder and models entry: sessions stay in the picker until the human deletes them, migration code not being worth a one-human audience.
|
||||
|
||||
2026-11-15, lilleman's call of 2026-11-13 in item 372, which split item 361: loops of one project, each on its own chunk, run side by side without touching each other's state. The worker's choices, for what the call left open:
|
||||
|
||||
- **A slot, not the chunk, names the session.** A loop names its session before it knows its chunk, since a rerun resumes the open session in place of running `chunk-preflight`. So each loop holds a slot, a file it keeps locked with flock under `~/.local/state/loop-claude/<key>/` (`bin/loop_claude/loop/chunk_slot.py`): the lowest free slot whose session is open, so a rerun resumes a chunk left open, or else the lowest free slot. A session lives one chunk, so one slot holds one chunk at a time. Slot 0 keeps the name every loop had before slots, so a chunk left open before slots still resumes. A reload's exec keeps the lock and hands on the slot.
|
||||
- **The archive and the route needed no change.** The archive keys each chunk by its own transcript's first line, and a rerun's route comes from the latest verdict on that transcript, so both follow the session. The routing figures are measured across all projects, under their own lock.
|
||||
- **git's own lock serializes the config folder's commits, in place of the file lock the item asked for.** `git commit` holds `.git/index.lock`, so of two commits at once the second fails, and the worker tries again. A wrapper lock would only make it wait, and a command spelled `flock … git commit` would pass rule-hook unchecked, since it reads only a command that starts with `git`. What two chunks could still break is one committing the file the other staged, so each commits only its own file, as `git commit -m <title> -- <file>` (`CLAUDE.md` → "Git, commits, and PRs").
|
||||
|
||||
Valid while claude takes `--session-id` and resumes by it, and a loop names its session before it knows its chunk.
|
||||
2026-11-16, lilleman's second call of 2026-11-13 splitting item 361: lilleman knows tmux and prefers it. Each chunk runs in its own window of one tmux session per project, `loop-<key>`, up to the number the config's `parallel-chunks` sets, 1 by default. tmux runs even at 1, so every project runs the same workflow (goal 1.3). A window waiting for the human ends its name in ` ?` and rings the bell, and the DM names `<session>:<window>`. The worker's choices, for what the call left open (`bin/loop_claude/tmux.py`, `bin/loop_claude/loop/chunk_windows.py`):
|
||||
|
||||
- **The window, in place of item 372's lock-file slot, names the claude session**, as `A <key> loop-claude item-372`. The loop-claude the human runs starts the windows and attaches; each window runs `loop-claude --chunk <window>`, so a loop knows its chunk before it names its claude session, and a rerun still resumes the chunk left open.
|
||||
- **A finishing chunk starts the next; only the human restarts a stopped one.** As its chunk finishes, a window's loop starts each chunk that may start then and exits, so its window closes. `remain-on-exit failed` keeps the window of a loop that stopped any other way, Ctrl-C included, with its last lines, and its chunk keeps its items. A finishing chunk never restarts it, since the human may have stopped it on purpose; the next `loop-claude <task>` starts it again before any other chunk. One flock under `~/.local/state/loop-claude/<key>/` serializes the starts, so two chunks finishing together don't start one chunk twice.
|
||||
- **The other chunks' items are told, not locked.** A fresh worker is told the items each other chunk holds, running or stopped: its window's item and those on its latest `Chunk items:` line. A chunk starts beside the others only where its item's `Touches:` prediction overlaps none of those items' predictions, since the plan's next item, which chunk-preflight's pick checks against, may already have merged.
|
||||
- **The tmux session names its checkout.** Two checkouts whose keys differ only in a character other than a letter, a digit, `_` or `-` map to one session name, so the session's `@loop-root` option names the checkout that made it, and another checkout's loop-claude refuses it.
|
||||
- **tmux 3.2 is the oldest that has every command and option used.** tmux's `CHANGES` dates the newest two to "CHANGES FROM 3.1c TO 3.2": `new-session -e`, and the `remain-on-exit` value that keeps only a failed program's pane.
|
||||
- **A loop started before this release isn't moved into a window.** One that reloads into this release starts its project's windows afresh, and leaves its chunk's open claude session, named for its slot, in the session picker. Carrying a slot's session into a window is not worth the code for a one-human audience, so the changelog asks the human to finish or stop every running loop before taking the release.
|
||||
|
||||
Valid while claude takes `--session-id` and resumes by it, and the human runs loop-claude where tmux is installed.
|
||||
|
||||
## loop-claude: the archive keeps the raw transcript, and a failed archive stops the loop
|
||||
|
||||
@@ -279,12 +302,12 @@ Valid while the later fixes per finished chunk, which `score-outcomes` and the r
|
||||
|
||||
## project config: a record may name a Confluence Cloud page as `confluence:` and its address, the loop reads and writes it as markdown, and a write never overwrites a save made since the loop's read
|
||||
|
||||
2026-11-15, larv-review, on lilleman's calls of 2026-11-12. Serves goal 1.6: a client's team keeps its records in its own wiki. Valid while one record fits one page, and while one session per project opens a record's copy, which todo.md's item 375 ends.
|
||||
2026-11-15, larv-review, on lilleman's calls of 2026-11-12. Serves goal 1.6: a client's team keeps its records in its own wiki. Valid while one record fits one page, and while each worktree opens its own copy of a record, as loop-claude's side-by-side chunks need.
|
||||
|
||||
- **A bench of readers picked the spelling.** Three fresh readers, seated as the person who writes a client's `config.toml`, each picked `decisions = "confluence:https://<site>/wiki/spaces/<space>/pages/<page ID>"`, pasted from the browser with or without the title at its end, over the bare address, a page ID beside a `confluence-site` key, and a table. Each named the match with `jira:`. Any of the five records may name a page; the goals file, the plan, the working rules and the principles may not.
|
||||
- **`decisions` and `comprehension-history` may name a page only where `plan` names a Jira epic.** rule-hook ranks a plan kept as a file before tool calls, inside its 30-second limit, and ranking reads those two records. A Confluence read and two adf-codec container runs would hold up every guarded tool call, and fail it while Confluence is down. `load` refuses goals in Jira beside a plan in a file for the same reason.
|
||||
- **A write sends the version number the store read, plus one, and Confluence refuses it with 409 where someone saved the page since.** The store then fails, saying to ask the human, and doesn't write the page; the loop never overwrites a teammate's edit on its own (lilleman, 2026-11-12). A write with no read before it replaces the page as it stands, as the record contract asks.
|
||||
- **`project-record` keeps the version `open` read in a file beside its copy**, `~/.local/state/project-record/<key>/<record>.version`, since `save` runs in a later process. The store keeps the version itself, so `write` still takes only the text. Every other tool reads and writes a record in one process, and its store keeps the version in memory, so a read by another tool, such as larv-review's, never moves the version an edit in `project-record` rests on.
|
||||
- **`project-record` keeps the version `open` read in a file beside its copy**, `~/.local/state/project-record/<key>/<worktree>/<record>.version`, since `save` runs in a later process. The store keeps the version itself, so `write` still takes only the text. Every other tool reads and writes a record in one process, and its store keeps the version in memory, so a read by another tool, such as larv-review's, never moves the version an edit in `project-record` rests on. The folder `<worktree>` is named for the worktree that ran `open`, and `open` removes the folders of worktrees git no longer lists, so a chunk's copy doesn't outlive its worktree.
|
||||
- **The page holds ADF, which adf-codec converts both ways**, so a teammate reads the record as Confluence renders it. Where adf-codec cannot convert the markdown, the write fails with adf-codec's error. A node markdown cannot hold reads as text: a mention as its name, a macro as `_(<macro> not included)_`. So the next write replaces it with that text, and a record page should hold only what markdown can.
|
||||
|
||||
## project config: a tool that reads a file's commits says where it does not support that file, and the work goes on
|
||||
@@ -316,13 +339,17 @@ Messages keep each file's usual name, such as `todo.md`, as its label, since the
|
||||
|
||||
2026-11-14, larv-review, on lilleman's calls of 2026-11-12 and 2026-11-14. Serves goal 1.6: a client's team keeps planning in its own Jira. Valid while a client's plan fits one epic in one Jira project.
|
||||
|
||||
- **One epic is one project's plan, and Jira's backlog rank orders it.** The team sets the rank, so the loop's score doesn't break ties and the loop doesn't reorder anything (lilleman, 2026-11-12). An item is an open child issue; one in a done status category is finished.
|
||||
- **One epic is one project's plan, and Jira's backlog rank orders it.** The team sets the rank, so the loop's score doesn't break ties and the loop never reranks an issue once filed (lilleman, 2026-11-12). An item is an open child issue; one in a done status category is finished.
|
||||
- **A bench of readers picked the spelling.** Three fresh readers, seated as the person who writes a client's `config.toml`, each picked `plan = "jira:https://<site>/browse/<key>"` over the bare address, a `jira:<key>` beside a `jira-site` key, and a `[plan]` table. Each also picked one pair of env-file keys, `ATLASSIAN_EMAIL` and `ATLASSIAN_API_TOKEN`, for Jira and Confluence over a pair for each, since one account's token opens both.
|
||||
- **An item's ID stays a whole number: the issue's number in the epic's Jira project.** About 30 modules read an ID as an int, and the `branch` and title templates already spell a ticket's name, as `ABC-{id}`. So the store refuses a child issue from another Jira project, and counts a blocker only among the plan's own items (`bin/plan_store/jira_epic.py`).
|
||||
- **The scores sit in one issue property, `plan-item`**, which needs no Jira admin (lilleman, 2026-11-12). An issue without it reads as an item nobody scored.
|
||||
- **The release is the earliest Fix Version named as a semver version**, and an issue with none fails the read, naming it, until todo.md's item 359 ties releases to something else.
|
||||
- **The loop files an item as a Task under the epic, and marks it as its own** (lilleman's calls of 2026-11-12). `"Filed by": "loop"` in the `plan-item` property tells such an issue from one a person filed, whose summary and description the loop never edits. Task is an issue type every Jira Software project template has; a project without it refuses the issue, saying so. The issue takes the project's Fix Version named as the release, with a leading v or without, and the store refuses an item whose release the project has no Fix Version for, before it files anything. A security finding also gets the label `security`, and its text never holds a secret's value. Jira ranks the new issue last, and no bar or goals check applies, until todo.md's item 384 says where a plan in Jira states its formula. Jira takes a blocker's link only after the issue exists, so the store first checks that each blocker is an open child. A link Jira still refuses leaves the issue filed: the write counts as landed, with a note naming the link to make by hand. A failed create says the issue may exist all the same, since a lost answer doesn't tell.
|
||||
- **The store reads, files and finishes, and doesn't edit an issue** until todo.md's item 382. It finishes an item with the transition that the config's `jira-finish-transition` names, which must lead to the status `jira-finish-status` names, since each Jira workflow differs (lilleman's call, 2026-11-12); any open child of the epic may move. It refuses a status outside Jira's done status category: the read counts an issue as finished only in that category, so the item would stay in the plan. Where the issue's present status has no direct transition to the status `jira-finish-status` names, `todo-item finish` fails and a person moves the issue in Jira: the store never walks an issue through other statuses to reach it. lilleman answered on 2026-11-15: "If it is possible to move it to done without a transisiont, that should happen. If not, fail." The implementer read "without a transition" as "without a transition in between". `rank_todo.py` refuses to rank a plan in Jira, and its `--check` passes, since Jira's backlog ranks it; rule-hook's rank check skips it. Each read first asks Jira for the epic itself, since a search under an epic the account cannot see answers no issues, as a finished plan does.
|
||||
- **The release is the earliest Fix Version named as a semver version**, and an issue with none fails the read, naming it.
|
||||
- **The loop files an item as a Task under the epic, and marks it as its own** (lilleman's calls of 2026-11-12). `"Filed by": "loop"` in the `plan-item` property tells such an issue from one a person filed, whose summary and description the loop never edits. Task is an issue type every Jira Software project template has; a project without it refuses the issue, saying so. The issue takes the project's Fix Version named as the release, with a leading v or without, and the store refuses an item whose release the project has no Fix Version for, before it files anything. A security finding also gets the label `security`, and its text never holds a secret's value. Jira takes a blocker's link only after the issue exists, so the store first checks that each blocker is an open child. A link Jira still refuses leaves the issue filed: the write counts as landed, with a note naming the link to make by hand. A failed create says the issue may exist all the same, since a lost answer doesn't tell.
|
||||
- **The config states the formula and the bar, and the store ranks a new issue among the loop's own** (lilleman, 2026-11-12 and 2026-11-15). A plan in Jira has no `## Scoring`, so a config whose `plan` names an epic must set `jira-score-formula` and `jira-score-bar`. It fails to load without them, or with a formula that doesn't parse, since no setting a config needs has a default. A bench of readers picked the spelling: three fresh readers, seated as the person who writes a client's `config.toml`, each picked those keys over `jira-score` and `jira-bar`, `score-formula` and `score-bar`, and bare `score` and `bar`. The prefix matches the other Jira-only settings, "formula" says the value is no score, and "score-bar" says what the bar applies to. The store scores the item as `rank_todo.py` scores a row, with the goal weights from the goals file, the decision log and the comprehension history. It refuses an item under the bar that isn't exempt, or one whose Moves names a goal the goals file lacks, before it files anything. Then it ranks the issue just before the first issue the loop filed that ranks after it. A person's issues don't count, so the team's rank of each stays as it is. The order is todo.md's within a release: a question first, then a security finding, then the higher score, with a tie after the older issue. Questions go first because `rank_todo.py` ranks them ahead of security findings, since an answer may change other items (the loop's choice, 2026-11-16). Release doesn't count, since lilleman's call ranks by score among the loop's issues. A rank Jira refuses, or an issue of the loop's that no longer scores, leaves the new issue filed and last, with a note to rank it by hand.
|
||||
- **The store edits and moves only an issue the loop filed, and of an issue a person filed it sets only the scores** (lilleman's calls of 2026-11-12). On its own issue it sets the summary, description, scores and Fix Version in one request, so Jira takes all of an edit or none, and it keeps the label `security` in step with Exempt. Of a person's issue it writes only the `plan-item` property, and a comment: the team's screens don't show the property, so the comment tells the team why the scores changed, and the store refuses the edit without one. The comment's text comes from whoever scores, in the project's `language`. Where Jira takes the edit and then refuses the comment, the edit counts as made, and a note says to post the comment by hand. No edit changes a link, until `todo.md` item 389.
|
||||
- **The loop may re-score a person's issue that already holds scores, and never moves it.** lilleman's calls of 2026-11-12 cover an issue nobody scored, and say nothing of one that holds scores; larv-review chose on 2026-11-16, through todo item 382. A re-score changes only the loop's own reading of the issue, and not what the person wrote, so it is allowed, with a comment as the first scores need. L, E, I and S are set together, so no issue is left partly scored. The Fix Version says when the team ships the issue, and a release is its team's, so the store refuses the move and `CLAUDE.md` has the worker ask the human to move the issue.
|
||||
- **`todo-item edit --comment` carries the comment, and a plan in a file takes the flag and keeps no comment**, so one command works in every project, as goal 1.3 asks. A bench of readers picked the spelling: three fresh readers, seated as the consultant who runs the loop in a client's project, each picked `--comment` over `--reason`, `--why` and `--because`. Only it says the text is posted where the team reads it, and `--reason` read as `--exempt`'s reason.
|
||||
- **The store finishes an item with the transition that the config's `jira-finish-transition` names**, which must lead to the status `jira-finish-status` names, since each Jira workflow differs (lilleman's call, 2026-11-12); any open child of the epic may move. It refuses a status outside Jira's done status category: the read counts an issue as finished only in that category, so the item would stay in the plan. Where the issue's present status has no direct transition to the status `jira-finish-status` names, `todo-item finish` fails and a person moves the issue in Jira: the store never walks an issue through other statuses to reach it. lilleman answered on 2026-11-15: "If it is possible to move it to done without a transisiont, that should happen. If not, fail." The implementer read "without a transition" as "without a transition in between". `rank_todo.py` refuses to rank a plan in Jira, and its `--check` passes, since Jira's backlog ranks it; rule-hook's rank check skips it. Each read first asks Jira for the epic itself, since a search under an epic the account cannot see answers no issues, as a finished plan does.
|
||||
|
||||
## project config: `tooling-on-host = true` lets a project with no container setup run its language runtime, package manager, tests and task runner on the host
|
||||
|
||||
@@ -388,6 +415,8 @@ The base is the last measured commit: the default branch's newest merged change
|
||||
|
||||
2026-11-11, lilleman. Serves goal 1.1. Item 296 made `chunk-pr merge` refuse while a scoring run the plan calls is unrecorded on the branch, so a missing run can block a merge. No score or ruling does, and the titles say so: "no score blocks a merge".
|
||||
|
||||
2026-11-15, lilleman, on the worker's proposal in item 374, replacing the call of 2026-11-13. The call asked that a ruling never charge one chunk with another's change, by reading against the new base after a rebase. Only the release review runs a paired ruling, and it measures the whole release, so its base stays the last measured commit. What another chunk's merge changes is the head: a ruling recorded before the merge came in read a head that never merges. So `chunk-pr merge` stops where the default branch has moved since the branch last recorded a paired ruling, and the worker runs the ruling again at the new head.
|
||||
|
||||
## review: the premises chunk's whole review is the human's approval
|
||||
|
||||
2026-09-20, lilleman. Serves goal 1.1. A reviewer's finding on that chunk could only be declined by citing the goals the chunk exists to write. Valid while every decline must name a goal or a technical principle.
|
||||
@@ -681,13 +710,13 @@ Valid while the worker writes the tests that larv-review's reviewers hold to the
|
||||
|
||||
- **The spelling.** A `Touches:` line, then one bullet per file: the path in backticks, then its parts, each a name in backticks or `lines <first>-<last>`, with `(small)` after a part the item changes only a little; a path or a name that holds a backtick takes a longer run of backticks with a space inside each end, as a Markdown code span does. A path alone is the whole file. Three readers seated as the README's audience picked the bulleted list over one line and over a table, since backticks hold a heading's commas, colons and parentheses. Two of the three put `(small)` after the part and outside the backticks, and two left line ranges unquoted. Each picked a different config key: `touch-predictions` was one reader's first choice and the second choice of the other two.
|
||||
- **A part's boundaries.** Python's `ast` module names the innermost function or class, a top-level assignment by the name it sets, and `(module)` for the rest. A Markdown file's parts are its headings outside fenced code. Any other file, and Python that doesn't parse, falls back to line ranges. A table row is no part of its own: the item named one, but the tables chunks collide on are the plan's and the changelog's, which don't count.
|
||||
- **What doesn't count.** The plan and every record the config names, the changelog among them, since every chunk writes them: `todo.md` item 374 writes the plan and the changelog at merge time, and the other records are appended to. `touch-predictions record` leaves them out of what a chunk touched, and the rule keeps them out of predictions.
|
||||
- **The pick.** `chunk-preflight` takes the items of the next release that don't wait, in the plan's order, each where it overlaps neither the next item nor an item taken before it. The call asked for the set that keeps the most chunks running. The plan's order comes first all the same: the largest set could start a low-ranked item in place of one ranked above it, and with more ready items than the parallel limit, either set fills the limit. `todo.md` item 375 takes as many of the picked items as its limit allows.
|
||||
- **What doesn't count.** The plan and every record the config names, the changelog among them, since every chunk writes them: `chunk-pr merge --finish` writes the plan and the changelog at merge time, and the other records are appended to. `touch-predictions record` leaves them out of what a chunk touched, and the rule keeps them out of predictions.
|
||||
- **The pick.** `chunk-preflight` takes the items of the next release that don't wait, in the plan's order, each where it overlaps neither the next item nor an item taken before it. The call asked for the set that keeps the most chunks running. The plan's order comes first all the same: the largest set could start a low-ranked item in place of one ranked above it, and with more ready items than the parallel limit, either set fills the limit. loop-claude starts as many of the picked items as `parallel-chunks` allows.
|
||||
- **An overlap that is taken.** Two items may share a part where either marks it `(small)`. The call takes an overlap only for a small change to the same part, and a few lines re-apply onto whatever the other chunk did to it.
|
||||
- **Which items share a chunk** stays the worker's choice, by the review passes they fire, so the pick names items, and an item the next chunk takes starts no chunk of its own.
|
||||
- **The record is optional.** No path setting has a default, and a mandatory one would stop every project until its owner edits the config (goal 1.6). A project that leaves `touch-predictions` out is still picked for, and keeps no record. The worker runs `touch-predictions record` before it removes the chunk's items (`skills/larv-review/SKILL.md` §5), since the prediction leaves the plan with the item, and a plan in Jira keeps no history to read it back from.
|
||||
|
||||
Valid while `todo.md` item 375 runs chunks by this pick. Once the record holds enough chunks to show how often the predictions miss, an item, not filed yet, revisits the pick's order and the `(small)` rule.
|
||||
Valid while loop-claude starts a project's chunks side by side by this pick (`bin/loop_claude/loop/chunk_windows.py` `may_start`), which also checks each new chunk against the running chunks' items. Once the record holds enough chunks to show how often the predictions miss, an item, not filed yet, revisits the pick's order and the `(small)` rule.
|
||||
|
||||
## todo.md: one table of items, scored by the formula it states, held to its bar and ranked by `bin/rank_todo.py`, which ranks each blocker above the items it blocks; each achieve goal weighs by its position, code health first and four times as heavy while the comprehension panel's overall is under the project's readability floor or unmeasured, then the goals file's goals, and a maintain goal weighs 0.5 per point of the confidence an item's test, gate leg or probe adds to it; the table's order is the plan's only order
|
||||
|
||||
|
||||
@@ -2249,3 +2249,99 @@ Read most (opens and searches):
|
||||
- `bin/plan_store/stores.py` 2
|
||||
- `docs/decisions.md` 2
|
||||
- `CHANGELOG.md` 1
|
||||
|
||||
## Reading cost, chunk ba82c458ad98, finished 2026-11-15T13:51:17Z
|
||||
|
||||
120652 new input tokens before the first commit.
|
||||
|
||||
Read most (opens and searches):
|
||||
|
||||
- `docs/decisions.md` 10
|
||||
- `bin/loop_claude/test_black_box.py` 8
|
||||
- `bin/loop_claude/loop/usage.py` 5
|
||||
- `CHANGELOG.md` 3
|
||||
- `CLAUDE.md` 3
|
||||
- `bin/claude_code/session.py` 2
|
||||
- `bin/command_lines/shell_command.py` 2
|
||||
- `bin/loop_claude/loop/main.py` 2
|
||||
- `rules/todo-items.md` 2
|
||||
- `README.md` 1
|
||||
|
||||
## Reading cost, chunk 8026e60ea27c, finished 2026-11-15T21:44:03Z
|
||||
|
||||
199967 new input tokens before the first commit.
|
||||
|
||||
Read most (opens and searches):
|
||||
|
||||
- `docs/decisions.md` 11
|
||||
- `bin/chunk_pr/test_chunk_pr.py` 8
|
||||
- `skills/larv-review/SKILL.md` 8
|
||||
- `CLAUDE.md` 5
|
||||
- `README.md` 5
|
||||
- `bin/chunk_pr/main.py` 5
|
||||
- `bin/project_config/templates.py` 4
|
||||
- `rules/todo-items.md` 4
|
||||
- `bin/project_config/main.py` 3
|
||||
- `bin/chunk_pr/approval.py` 2
|
||||
|
||||
## Reading cost, chunk 0851f830bb67, finished 2026-11-15T22:41:58Z
|
||||
|
||||
50560 new input tokens before the first commit.
|
||||
|
||||
Read most (opens and searches):
|
||||
|
||||
- `README.md` 1
|
||||
- `bin/project_config/main.py` 1
|
||||
- `bin/project_config/settings.py` 1
|
||||
- `bin/project_record/main.py` 1
|
||||
- `bin/project_record/test_project_record.py` 1
|
||||
- `docs/decisions.md` 1
|
||||
- `rules/decisions.md` 1
|
||||
- `settings.json` 1
|
||||
|
||||
## Reading cost, chunk a8246f8e9771, finished 2026-11-16T00:48:07Z
|
||||
|
||||
97222 new input tokens before the first commit.
|
||||
|
||||
Read most (opens and searches):
|
||||
|
||||
- `todo.md` 7
|
||||
- `bin/project_config/settings.py` 3
|
||||
- `rules/todo-items.md` 3
|
||||
- `docs/score-anchors.md` 2
|
||||
- `bin/release_plan/release.py` 1
|
||||
- `bin/release_plan/release_standing.py` 1
|
||||
|
||||
## Reading cost, chunk c497e828c613, finished 2026-11-16T01:20:21Z
|
||||
|
||||
171945 new input tokens before the first commit.
|
||||
|
||||
Read most (opens and searches):
|
||||
|
||||
- `bin/todo_item/main.py` 8
|
||||
- `bin/plan_store/jira_epic.py` 6
|
||||
- `README.md` 5
|
||||
- `bin/todo_item/test_todo_item.py` 5
|
||||
- `CLAUDE.md` 4
|
||||
- `bin/plan_store/stores.py` 4
|
||||
- `bin/plan_store/test_jira_epic.py` 4
|
||||
- `docs/decisions.md` 4
|
||||
- `bin/plan_store/contract.py` 3
|
||||
- `bin/plan_store/fakes.py` 3
|
||||
|
||||
## Reading cost, chunk 956d742d7ba4, finished 2026-11-16T02:13:55Z
|
||||
|
||||
276709 new input tokens before the first commit.
|
||||
|
||||
Read most (opens and searches):
|
||||
|
||||
- `bin/plan_store/jira_epic.py` 14
|
||||
- `bin/project_config/test_project_config.py` 8
|
||||
- `bin/plan_store/test_jira_epic.py` 7
|
||||
- `bin/project_config/settings.py` 7
|
||||
- `bin/plan_store/stores.py` 6
|
||||
- `bin/release_plan/ranking.py` 4
|
||||
- `README.md` 3
|
||||
- `bin/larv_review/test_larv_review.py` 3
|
||||
- `bin/project_config/main.py` 3
|
||||
- `bin/release_plan/formula.py` 3
|
||||
|
||||
+1
-1
@@ -2,7 +2,7 @@
|
||||
paths:
|
||||
- "**/AGENTS.md"
|
||||
- "**/docs/decisions.md"
|
||||
- "**/project-record/*/decisions.md"
|
||||
- "**/project-record/*/*/decisions.md"
|
||||
---
|
||||
|
||||
# Decisions: one home, each linked to a goal or a technical principle
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@ paths:
|
||||
|
||||
# Todo items (`todo.md`)
|
||||
|
||||
- **A plan is mandatory in every project, and a plan kept as `todo.md` has the shape `rank_todo.py --help` shows**, which `~/.claude/bin/rank_todo.py` checks and ranks; its `--help` shows a valid file. A plan in a Jira epic is read from the epic's open child issues. `todo-item add` files an item there as a new child issue, and `todo-item finish` moves an item's issue to done, and `todo-item` can't edit or move an issue yet. Below, `todo.md` means a plan kept as a file, and "the plan" either kind. `## Scoring` holds the formula and the bar; `## Items` is one table of every item; `## Details` holds each item's detail under its ID. `## Renamed` marks each renamed release with a line such as `- 0.2.1 renamed to 0.3.0`; `rank_todo.py --help` says what a mark does. Cite an item by its ID. The formula and bar are the project's own to tune.
|
||||
- **A plan is mandatory in every project, and a plan kept as `todo.md` has the shape `rank_todo.py --help` shows**, which `~/.claude/bin/rank_todo.py` checks and ranks; its `--help` shows a valid file. A plan in a Jira epic is read from the epic's open child issues. `todo-item add` files an item there as a new child issue, and `todo-item finish` moves an item's issue to done. `todo-item --help` says what `edit` and `move` change there. Below, `todo.md` means a plan kept as a file, and "the plan" either kind. `## Scoring` holds the formula and the bar; `## Items` is one table of every item; `## Details` holds each item's detail under its ID. `## Renamed` marks each renamed release with a line such as `- 0.2.1 renamed to 0.3.0`; `rank_todo.py --help` says what a mark does. Cite an item by its ID. The formula and bar are the project's own to tune.
|
||||
- **File an item with `~/.claude/bin/todo-item add`, and change one with `todo-item edit` or `todo-item move`.** `add` and `edit --detail` read the item's detail from stdin, and all three commands rank the plan; `todo-item --help` shows the flags. `todo-item finish <ID> --no-changelog` drops an item no chunk built. Edit `todo.md` itself only for what `todo-item` has no command for: `## Scoring`, `## Renamed`, and reshaping an old table.
|
||||
- **Order items only by score and the Blocked by column.** An item's Blocked by cell lists the IDs of the items that must be done before it starts, such as `12, 14`; `rank_todo.py --help` says how it ranks them. No text in `todo.md` outside the table orders items: where an item must go first, score it so, and say why in its detail.
|
||||
- **Plan only on the project's rung or above.** loop-claude's prompt tells you when you run below it. Below it, never score or re-score an item, move it between releases, split a milestone into items, delete an item under the bar, rewrite a filed item's tagline or detail, or choose or replace an item in `docs/score-anchors.md`. Draft each new item, each change to a filed item, and each change to the anchors, instead. Before your next commit, launch one subagent to apply the drafts, score them and set their release. Launch it on the rung `CLAUDE.md`'s delegation rule gives a subagent that files or scores items. Keep the scores and releases it writes. For a security finding, launch it at once. Any rung may remove a finished item's row and detail, and score a delegated task's L. A subagent launched for another task leaves the plan alone.
|
||||
|
||||
@@ -145,7 +145,7 @@ Launch one principles-auditor on the trigger in §3, so the project is read once
|
||||
|
||||
### Comprehension check
|
||||
|
||||
The comprehension check records how hard the project is for its contributor to read (`~/.claude/rules/goals-and-audience.md`), and no score blocks a merge; only a run the plan calls and the branch lacks does, per "Scoring run". Simulated readers, the seats, launched per `~/.claude/skills/comprehension-panel/SKILL.md`, each read the whole project, not the diff. It reports no findings and is no pass: it runs once, in §5, after every pass is done, the auto-reviewer included, so it reads the branch as review left it. It runs a paired ruling in the release review, even where an opt-out skips its architect, and a scoring run where one is due. It skips only as "Opt-out" or "Suspended" below says.
|
||||
The comprehension check records how hard the project is for its contributor to read (`~/.claude/rules/goals-and-audience.md`), and no score blocks a merge; only a run the plan calls and the branch lacks does, per "Scoring run". Simulated readers, the seats, launched per `~/.claude/skills/comprehension-panel/SKILL.md`, each read the whole project, not the diff. It reports no findings and is no pass: it runs in §5, after every pass is done, the auto-reviewer included, so it reads the branch as review left it. It runs a paired ruling in the release review, even where an opt-out skips its architect, and a scoring run where one is due. It skips only as "Opt-out" or "Suspended" below says.
|
||||
|
||||
**Paired ruling.** Each seat votes whether the project reads better, the same or worse at this branch's head than at the base.
|
||||
|
||||
@@ -153,7 +153,7 @@ The comprehension check records how hard the project is for its contributor to r
|
||||
- **Head.** The head holds `origin/<default branch>`, merged in at §4 step 1, so it differs from the default branch only by this branch's change.
|
||||
- **Seats.** Mid A and the inherited architect. Write what they read and their replies into a votes file in the chunk's review folder, in the shape `~/.claude/bin/larv-review --help` shows, and run `~/.claude/bin/larv-review record-ruling <votes file>`. On `Split:`, launch the maintainability senior and Junior A together, add their lines, and run it again.
|
||||
|
||||
**Scoring run**, when `~/.claude/bin/larv-review needs-scoring-run <the IDs of the items the chunk ships, if any>` prints `Scoring run due:`. Run `needs-scoring-run` before removing the chunk's items from `todo.md`. `chunk-pr merge` refuses until the branch's committed history records every run the plan calls, which `larv-review scoring-run-owed` counts at merge time from the merge base; an earlier due line is only a snapshot.
|
||||
**Scoring run**, when `~/.claude/bin/larv-review needs-scoring-run <the IDs of the items the chunk ships, if any>` prints `Scoring run due:`. `chunk-pr merge` refuses until the branch's committed history records every run the plan calls, which `larv-review scoring-run-owed` counts at merge time from the merge base; an earlier due line is only a snapshot.
|
||||
|
||||
- **Seats.** Junior A, Mid A, the maintainability senior and the inherited architect each score the project at the head from 1 to 10 overall and on four dimensions: Navigation, Locality, Shape and Self-sufficiency. Run `~/.claude/bin/larv-review prepare-scoring`, adding `--preloaded <text>` only where its default list of pre-loaded files is wrong. It makes the worktree the seats read and prints each seat's prompt file; launch each seat with its file's text as its prompt. Write their lines into a scores file and run `~/.claude/bin/larv-review record-scoring <scores file> <the same item IDs>`, which appends the run to the history and prints the four seats' means.
|
||||
- **Floor item.** Where `record-scoring` prints `Floor:`, a `Next:` line follows: file one floor item, or refresh the open one. A floor item is a plan item meant to bring every mean to the project's readability floor, which `record-scoring`'s `Floor:` line names. File it as one ambitious refactor, not touch-ups. It restructures the area behind the places `larv-review places` prints for this run, chosen where they bear on the lowest dimension, sized to bring every mean to that floor, and quotes those places. Its tagline opens with `Reach the comprehension floor:`, so its own chunk runs a scoring run; while a mean stays under the floor, that run's `Next:` line asks for the next floor item. Mark it `owner`, since the human asked that such a project always hold one, so no score deletes it. Put it in the earliest release the plan names after the one the chunk ships into, or else in the next version after that one that `~/.claude/rules/todo-items.md` allows, so the floor doesn't hold up any release. While one is open, refresh its places and aim from the newest run instead of filing another; the item the chunk ships doesn't count as open. Commit it with the run, as "Record" says.
|
||||
@@ -200,9 +200,15 @@ Launch prose-reviewer with what the diff touched and every section this review c
|
||||
## 5. Goal alignment, then merge
|
||||
|
||||
1. Read the finished PR against the goals file's goals and code health, unless that file voids it: does anything in it work against one? It breaks a maintain goal → do not merge; redesign the change or drop its item. It works against an achieve goal → do not merge; ask the human, stating the conflict.
|
||||
2. Run the comprehension check (§3) where it runs; it runs once. When `origin/<default branch>` moves after that, return to §4, and keep the ruling and scoring run already recorded.
|
||||
3. Run `~/.claude/bin/touch-predictions record <ID>...` in the worktree, naming the chunk's items: it records what they were predicted to touch beside what the branch touched, where the project's config names that record. A later pass through this step, after a return to §4, skips it, since the items have left the plan. Then remove the chunk's items from `todo.md` per `~/.claude/CLAUDE.md` → "Working loop" in the branch. Commit and push both; the commit re-enters no pass.
|
||||
4. Aligned and every pass done → **merge** with `~/.claude/bin/chunk-pr merge`, run in the background with its `timeout` set to 7200000 ms, since its wait can outlast the Bash tool's default. It waits for the pull request's checks to pass, and for a human's approval where the project's config sets `wait-for-approval` (`chunk-pr --help`), then takes the first merge method the repository allows on its forge. A repo whose `AGENTS.md` names another method merges that way with the forge's CLI instead, once the pull request's checks pass, `~/.claude/bin/larv-review scoring-run-owed` exits 0 and, where `~/.claude/bin/project-config wait-for-approval` prints `true`, GitHub reports the pull request approved. A repo withholds this in its `AGENTS.md` → leave the PR ready and unmerged, and say which line withheld it.
|
||||
2. Run the comprehension check (§3) where it runs. When `origin/<default branch>` moves after that, return to §4, and keep the scoring run already recorded. Where the chunk recorded a paired ruling, run it again at the new head and record it: it read the head before the other chunk's merge came in.
|
||||
3. Run `~/.claude/bin/touch-predictions record <ID>...` in the worktree, naming the chunk's items: it records what they were predicted to touch beside what the branch touched, where the project's config names that record. A later pass through this step, after a return to §4, skips it. Commit and push it; the commit re-enters no pass. Leave the chunk's items in the plan, and write no changelog bullet in the branch: step 4 does both, so that `todo.md` and `CHANGELOG.md` never conflict between chunks. Revise any decision that cites an item now, since `todo-item finish` refuses while one does.
|
||||
4. Aligned and every pass done → **merge** with `~/.claude/bin/chunk-pr merge`, run in the background with its `timeout` set to 7200000 ms, since its wait can outlast the Bash tool's default. Give it one `--finish <ID>` per item the chunk ships, each with the arguments `todo-item finish` takes (`todo-item --help`), as in `chunk-pr merge --finish 12 --changelog '<bullet>' --finish 13 --no-changelog`. The project's chunks merge one at a time. In its turn, `chunk-pr merge` merges `origin/<default branch>` into the branch, finishes those items, pushes, and waits for the pull request's checks to pass; then it takes the first merge method the repository allows on its forge. Where it stops, do what it asks and run it again with the same arguments:
|
||||
- **A merge conflict.** Resolve it, commit and push. Rerun only the passes whose triggers the resolution's own lines meet (§3), each in a round of its own.
|
||||
- **A paired ruling to run again.** `chunk-pr merge` has merged the default branch in and pushed. Run the ruling at that head, record it, commit and push. Don't return to §4 for it: the next turn waits for the checks at the new head.
|
||||
- **An owed scoring run, or a queue another pull request holds.** Record the run, or wait, as the message says.
|
||||
- **A reviewer's comment**, where the project's config sets `wait-for-approval` (`chunk-pr --help`) and the pull request waits for a human's approval. Answer it in its thread on the forge, and fix what it asks as a finding of the chunk. The wait doesn't hold the queue, so other chunks merge meanwhile.
|
||||
|
||||
A repo whose `AGENTS.md` names another method merges that way with the forge's CLI instead, after it finishes the chunk's items with `todo-item finish` in the branch, and once the pull request's checks pass, `~/.claude/bin/larv-review scoring-run-owed` exits 0 and, where `~/.claude/bin/project-config wait-for-approval` prints `true`, GitHub reports the pull request approved. A repo withholds this in its `AGENTS.md` → leave the PR ready and unmerged, and say which line withheld it.
|
||||
5. Merged → run `~/.claude/bin/chunk-pr clean` in the chunk's worktree, and put a failure it prints in the summary.
|
||||
6. Stop. The next chunk gets a fresh session.
|
||||
|
||||
|
||||
@@ -6,18 +6,12 @@
|
||||
|
||||
`Bar = 0.1`
|
||||
|
||||
`Next ID = 389`
|
||||
`Next ID = 390`
|
||||
|
||||
## Items
|
||||
|
||||
| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |
|
||||
|---|---|---|---|---|---|---|---|---|---|---|---|
|
||||
| 374 | 0.11.0 | | decision | **Merge open chunks one at a time: rebase, finish the item in todo.md and CHANGELOG.md, rerun the gate and the paired ruling, and keep a chunk waiting for approval in the queue without blocking the next.** | 4 | 2 | 3 | 7 | 6 | 1.5 by 4, 1.6 by 3 | 1.0 |
|
||||
| 386 | 0.11.0 | | | **Key project-record's copies per worktree, so two chunks of one project editing the same record kept outside a file don't overwrite each other's unsaved edit.** | 2 | 2 | 2 | 4 | 2 | 1.1 by 2 | 0.8 |
|
||||
| 359 | 0.11.0 | | | **Tie a project's releases to what its config names: semver tags, Jira Fix Versions, sprints, or none.** | 3 | 2 | 3 | 6 | 4 | 1.6 by 3 | 0.8 |
|
||||
| 382 | 0.11.0 | | | **Edit a Jira issue the loop filed, and score an unscored issue a teammate filed with a comment saying why.** | 4 | 2 | 3 | 7 | 4 | 1.6 by 3 | 0.8 |
|
||||
| 384 | 0.11.0 | | | **Rank an issue the loop files in Jira by its score among the issues the loop filed, a security finding first.** | 3 | 2 | 2 | 5 | 3 | 1.6 by 2 | 0.7 |
|
||||
| 375 | 0.11.0 | 374 | decision | **Run up to the project's configured number of chunks at once, each in its own window of one tmux session named for the project, mark a window whose chunk waits for the human, and refuse to start without tmux at the needed version.** | 4 | 2 | 3 | 7 | 7 | 1.5 by 7 | 0.6 |
|
||||
| 319 | 0.12.0 | | | **Start a fresh session with a brief of the chunk when a rung step changes the worker's model, in place of resuming the old session.** | 3 | 2 | 3 | 6 | 4 | 1.1 by 2, 1.4 by 2 | 1.2 |
|
||||
| 309 | 0.12.0 | | | **Run a scoring run's second pass on one head with two seats in place of four, once `larv-review agreement` shows the seats agree with each other more than a run agrees with its rerun.** | 2 | 2 | 2 | 4 | 2 | 1.4 by 3 | 1.2 |
|
||||
| 299 | 0.12.0 | | | **Replay the archived judge verdicts through code rules and a classifier trained locally on the archive, and file an item for each verdict kind one of them decides with no missed interrupt.** | 2 | 2 | 2 | 4 | 3 | 1.4 by 3 | 1.0 |
|
||||
@@ -30,10 +24,11 @@
|
||||
| 331 | 0.12.0 | | | **Reword four decisions to expire when the rungs their replays tested change, not whenever a model joins the ladder.** | 1 | 1 | 1 | 1 | 2 | 1.4 by 2 | 0.8 |
|
||||
| 381 | 0.12.0 | | | **Read a `Touches:` list from a plan kept in Jira as from one in todo.md, with a test that converts a description through `adf_codec`.** | 1 | 2 | 1 | 2 | 2 | 1.5 by 2 | 0.7 |
|
||||
| 327 | 0.12.0 | | | **Have `larv-review` print a round commit's title prefix, counted from the round's report, and have rule-hook refuse a round title whose counts differ from it.** | 3 | 2 | 3 | 6 | 4 | 1.1 by 1, 1.4 by 1 | 0.6 |
|
||||
| 365 | 0.13.0 | 382 | | **Have `score-outcomes` read the finished and dropped items of a plan outside the checkout, from the project repo's history or from Jira's issue changelogs.** | 3 | 2 | 2 | 5 | 4 | 1.6 by 2, 1.1 by 2 | 1.2 |
|
||||
| 368 | 0.13.0 | 382 | | **Call a release review due, call a release ready to cut, and tell whether a chunk owes a scoring run, for a plan outside the checkout, from the project repo's history or from Jira.** | 3 | 2 | 2 | 5 | 4 | 1.6 by 2, 1.1 by 2 | 1.2 |
|
||||
| 366 | 0.13.0 | 382 | | **Count the chunks of a project whose plan sits outside the checkout in the routing figures, from the project repo's history or from Jira.** | 3 | 2 | 2 | 5 | 4 | 1.6 by 2, 1.4 by 2 | 1.1 |
|
||||
| 367 | 0.13.0 | 382, 384 | | **Check that every write to a Jira plan leaves it ranked, as rule-hook's `todo-rank-check` checks `todo.md` today.** | 2 | 2 | 3 | 5 | 3 | 1.6 by 2 | 0.7 |
|
||||
| 389 | 0.12.0 | | decision | **Set a Jira issue's "is blocked by" links from `todo-item edit --blocked-by`, on an issue the loop filed.** | 2 | 2 | 2 | 4 | 4 | 1.6 by 2 | 0.5 |
|
||||
| 365 | 0.13.0 | | | **Have `score-outcomes` read the finished and dropped items of a plan outside the checkout, from the project repo's history or from Jira's issue changelogs.** | 3 | 2 | 2 | 5 | 4 | 1.6 by 2, 1.1 by 2 | 1.2 |
|
||||
| 368 | 0.13.0 | | | **Call a release review due, call a release ready to cut, and tell whether a chunk owes a scoring run, for a plan outside the checkout, from the project repo's history or from Jira.** | 3 | 2 | 2 | 5 | 4 | 1.6 by 2, 1.1 by 2 | 1.2 |
|
||||
| 366 | 0.13.0 | | | **Count the chunks of a project whose plan sits outside the checkout in the routing figures, from the project repo's history or from Jira.** | 3 | 2 | 2 | 5 | 4 | 1.6 by 2, 1.4 by 2 | 1.1 |
|
||||
| 367 | 0.13.0 | | | **Check that every write to a Jira plan leaves it ranked, as rule-hook's `todo-rank-check` checks `todo.md` today.** | 2 | 2 | 3 | 5 | 3 | 1.6 by 2 | 0.7 |
|
||||
| 303 | 0.14.0 | | defect | **Archive each judge run's prompt and json reply beside the verdict it gave, so judge cost, replays and backups cover the judge as they cover the worker.** | 2 | 2 | 3 | 5 | 3 | 1.4 by 3, 3 by 2 | 4.2 |
|
||||
| 306 | 0.14.0 | | | **Set a strategy that keeps loop-claude's archive and larv-review's review folders backed up and small over the years, compressing older entries without losing any.** | 3 | 2 | 4 | 7 | 5 | 3 by 5 | 3.9 |
|
||||
| 304 | 0.14.0 | 303 | defect | **Archive each review-replay and judge-replay run's transcript beside its result, so a replay that decided a rung can be checked and re-priced later.** | 2 | 2 | 2 | 4 | 3 | 1.4 by 2, 3 by 2 | 3.8 |
|
||||
@@ -47,7 +42,7 @@
|
||||
| 273 | 0.14.0 | | decision | **Re-tune the E + I steps of `REVIEW_STEPS` for 6 to 8 once 10 finished chunks have scored an E + I of 6 or more, from how well E + I orders their review rounds and 🔴 findings.** | 1 | 2 | 2 | 3 | 2 | 1.1 by 2, 1.4 by 3 | 2.0 |
|
||||
| 268 | 0.14.0 | | | **End a run whose release is ready to cut with a notice on loop-claude's terminal, in place of an interrupt that waits for an answer.** | 2 | 2 | 3 | 5 | 3 | 1 by 5 | 1.9 |
|
||||
| 171 | 0.14.0 | | decision | **Group the routing figures' review rounds by the reviewers' rung as well as the worker's, so a call blames a rung only for rounds its own reviews raised.** | 3 | 2 | 2 | 5 | 4 | 1.2 by 3, 1.4 by 3 | 1.8 |
|
||||
| 300 | 0.14.0 | | owner | **Reach the comprehension floor: restructure the places the comprehension seats found hardest to follow, so the project reads at 7.0 or above on every dimension, Locality and Self-sufficiency first; today the scoring run at 8f03747 scored Navigation 6.75, Locality 5.63, Shape 5.75, Self-sufficiency 5.63 and Overall 6.00.** | 4 | 2 | 3 | 7 | 8 | code health by 8 | 1.7 |
|
||||
| 300 | 0.14.0 | | owner | **Reach the comprehension floor: restructure the places the comprehension seats found hardest to follow, so the project reads at 7.0 or above on every dimension, Locality first; today the scoring run at 55235a0 scored Navigation 7.38, Locality 6.13, Shape 6.50, Self-sufficiency 6.50 and Overall 6.50.** | 4 | 2 | 3 | 7 | 8 | code health by 8 | 1.7 |
|
||||
| 264 | 0.14.0 | | | **Report the comprehension seats and the escalated subagents as subagent types of their own in `routing-figures.md`, with their dollars.** | 2 | 2 | 1 | 3 | 3 | 1.4 by 5 | 1.7 |
|
||||
| 323 | 0.14.0 | | | **Count a release review as landed once its pull request has merged, whatever its commits are titled.** | 3 | 2 | 3 | 6 | 3 | 1.4 by 3, 1.5 by 2 | 1.7 |
|
||||
| 342 | 0.14.0 | | | **Research the tooling agents read, search and run commands with once more, and file an item for each tool that cuts tokens a replay shows keep quality.** | 1 | 2 | 1 | 2 | 3 | 1.4 by 3, 1.5 by 2 | 1.7 |
|
||||
@@ -79,62 +74,6 @@
|
||||
|
||||
## Details
|
||||
|
||||
### 374. Merge open chunks one at a time: rebase, finish the item in todo.md and CHANGELOG.md, rerun the gate and the paired ruling, and keep a chunk waiting for approval in the queue without blocking the next.
|
||||
|
||||
lilleman's call, 2026-11-13, splitting item 361, which also asked that a chunk keep waiting for a human approval while others run. With several chunks open, `chunk-pr merge` merges one pull request at a time. For each it rebases the branch onto the default branch, then writes the item's `todo-item finish` and its changelog bullet, then reruns the gate, then merges. Moving those edits to merge time keeps `todo.md` and `CHANGELOG.md` out of every chunk's conflicts.
|
||||
|
||||
Where the rebase conflicts, the chunk's worker resolves it, and only the review passes whose triggers the resolution meets rerun (`larv-review` §3). The paired ruling reruns against the new base after every rebase that brought in another chunk's merge. This revises `docs/decisions.md`'s entry on the last measured commit, so a ruling never charges one chunk with another's change. A chunk whose pull request waits for the approvals item 360 waits for stays in the queue without blocking the next one. It resumes in its own session when a review comment arrives, answers it, and goes back to waiting.
|
||||
|
||||
`bin/chunk_preflight/choices.py:80` `forge_of` is a place the comprehension seats found hard: forge code split across tools. Where this item touches it, build on item 287's forge module if that has shipped.
|
||||
|
||||
### 386. Key project-record's copies per worktree, so two chunks of one project editing the same record kept outside a file don't overwrite each other's unsaved edit.
|
||||
|
||||
Found in item 372's chunk. `project-record open` writes a record kept on a Confluence page to a copy under `~/.local/state/project-record/<key>/`, keyed by the project alone (`bin/project_record/main.py`, `COPIES`). Two chunks of one project, running side by side as item 375 will run them, share that copy: the second `open` rewrites it, and the first chunk's unsaved edit is lost. Key the copy by the worktree as well as the project.
|
||||
|
||||
Touches:
|
||||
- `bin/project_record/main.py`: `(module)` (small)
|
||||
- `bin/project_record/test_project_record.py`
|
||||
|
||||
### 359. Tie a project's releases to what its config names: semver tags, Jira Fix Versions, sprints, or none.
|
||||
|
||||
lilleman's call, 2026-11-12: what a release is differs per client. With none, items name no release, and the architecture and principles passes the release review runs need another trigger, which this item settles and records. Readers: `rank_todo.py`'s release order, chunk-preflight's next release, loop-claude's "release ready to cut", larv-review's release review, `CLAUDE.md` → "Working loop". Cutting a release stays the human's.
|
||||
|
||||
### 382. Edit a Jira issue the loop filed, and score an unscored issue a teammate filed with a comment saying why.
|
||||
|
||||
Split from item 352 on 2026-11-15; lilleman's calls, 2026-11-12. The loop edits the summary, description and scores of issues it created, which the `Filed by` mark in the `plan-item` property tells apart, and never the summary or description of an issue a person filed. An issue a teammate files without scores gets scored like any item, with a short comment saying it was scored and why; its scope stays as written. The comment reaches the client's team, so it is in the project's `language`, and its reason comes from whoever scores: `PlanStore.edit` and `todo-item edit` gain a way to pass it, whose spelling a bench of readers picks. Say in `docs/decisions.md` whether the loop may re-score or move a person's issue that already holds scores; the calls name neither.
|
||||
|
||||
Touches:
|
||||
- `bin/plan_store/jira_epic.py`: `JiraPlan.edit`
|
||||
- `bin/plan_store/test_jira_epic.py`: new tests of `edit`
|
||||
- `bin/plan_store/stores.py`: `PlanStore.edit`, `FilePlan.edit`
|
||||
- `bin/todo_item/main.py`: the help, `edit`'s flags
|
||||
|
||||
### 384. Rank an issue the loop files in Jira by its score among the issues the loop filed, a security finding first.
|
||||
|
||||
Split from item 352 on 2026-11-15; lilleman's call, 2026-11-12: an issue the loop files goes into Jira rank by its score among the issues the loop filed, and a security finding ranks first. The team's own rank of every other issue stays as it is.
|
||||
|
||||
lilleman's answer, 2026-11-15: a plan in Jira states its score formula and its bar as two settings in the project's `config.toml`. They hold what a `todo.md` states under `## Scoring`: a formula such as `100 * V / (2**S + 8)`, and a bar such as `1`. A bench of readers, seated as the person who writes a client's `config.toml`, picks the two settings' spelling. A config that names an epic as its plan and leaves them out fails to load, saying which to add, since no path setting has a default either.
|
||||
|
||||
With the two settings, `JiraPlan.add` scores the new item as `bin/release_plan/ranking.py` scores a row of `todo.md`: it reads the goals file, the decision log and the comprehension history for the weights. It refuses an item under the bar that isn't exempt, and checks that Moves names goals the goals file holds. Then it asks Jira to rank the new issue just before the first issue the loop filed that scores lower. A security finding goes before the first issue the loop filed that isn't one.
|
||||
|
||||
Touches:
|
||||
- `bin/plan_store/jira_epic.py`: `JiraPlan`, `JiraPlan.add`, `Issue`, and a new function that places the issue
|
||||
- `bin/plan_store/stores.py`: `store`
|
||||
- `bin/plan_store/test_jira_epic.py`: new tests of the bar and the rank
|
||||
- `bin/project_config/main.py`: the help
|
||||
- `bin/project_config/settings.py`: `OPTIONAL`, `ProjectConfig`, `load`
|
||||
- `bin/release_plan/ranking.py`: `read_scoring`, so a formula and a bar from the config score an item
|
||||
- `bin/todo_item/main.py`: the help's lines on `add` in a Jira epic
|
||||
- `docs/decisions.md`: "project config: `plan` may name a Jira Cloud epic …"
|
||||
|
||||
### 375. Run up to the project's configured number of chunks at once, each in its own window of one tmux session named for the project, mark a window whose chunk waits for the human, and refuse to start without tmux at the needed version.
|
||||
|
||||
lilleman's call, 2026-11-13, splitting item 361. lilleman knows tmux and prefers it. loop-claude runs each chunk in its own window of one tmux session named for the project, such as session `loop-claude-config` with windows `item-372` and `item-373`. It runs up to the number of chunks the project's config allows at once, with 1 as the default, and starts the next chunk item 373's pass allows as each one merges. It uses tmux even at 1, so every project runs the same workflow (goal 1.3). Each window holds a loop-claude for its one chunk, so the interrupt and `/talk` work there as on any terminal. When a chunk waits for the human, loop-claude marks its window, renaming it to end in ` ?` and ringing the bell so tmux's status bar shows it, and clears the mark once it is answered. The DM each interrupt sends names the session and window to answer in, such as `loop-claude-config:item-372`, so the human goes straight to it.
|
||||
|
||||
Before starting anything — a worktree, a session, a window — loop-claude checks that tmux is installed at the needed version or later. Where it is missing or older, it stops and names the version it found and the one it needs. The needed version is the oldest that has every tmux command and option loop-claude uses, read from tmux's `CHANGES` file and cited in the decision that records it.
|
||||
|
||||
The config key for the parallel limit is a syntax users write, so a panel seated from the README's audience picks its spelling (`CLAUDE.md` → "Working loop" → "Bench a syntax"). run-heavy already sizes its slots from the machine, at one per 4 CPUs and with memory from `MemTotal`, so a larger VM runs more heavy commands at once without a change here.
|
||||
|
||||
### 319. Start a fresh session with a brief of the chunk when a rung step changes the worker's model, in place of resuming the old session.
|
||||
|
||||
On SWE-bench Verified with Haiku 4.5 and Opus 4.7, handing the strong model the weak model's transcript solved 69.2% at $1.61 a task; starting the strong model fresh solved 79.2% at $0.90 (arXiv 2608.24358, The Handoff Tax). A model switch also rereads the whole context uncached (Claude Code prompt caching docs). A worker that steps from Sonnet 5.5 to Opus 5.5 by `--resume` is the raw handoff; an effort-only step within one model keeps the cache and isn't. The escalated subagent, which starts fresh with the trigger's evidence, already follows the pattern that won.
|
||||
@@ -212,6 +151,15 @@ Add a `larv-review` subcommand that prints a round title's prefix, up to and inc
|
||||
|
||||
Left with the model: the summary after the `;`, and answering the findings.
|
||||
|
||||
### 389. Set a Jira issue's "is blocked by" links from `todo-item edit --blocked-by`, on an issue the loop filed.
|
||||
|
||||
Filed by item 382's chunk on 2026-11-16. `JiraPlan.edit` refuses an edit of Blocked by, saying to link the issue in Jira, so a worker cannot mark an item it filed as blocked once it exists. Read each link's id from the search's `issuelinks`, make a link per new blocker as `add` does, and delete one per blocker removed, after `missing_blocker`'s check. Say in `docs/decisions.md` whether the loop may link an issue a person filed; the decision on the Jira epic as a plan says the loop writes only the scores of such an issue.
|
||||
|
||||
Touches:
|
||||
- `bin/plan_store/jira_epic.py`: `Issue`, `issue_of`, `JiraPlan.edit`, `revision_of`
|
||||
- `bin/plan_store/test_jira_epic.py`: `Editing`
|
||||
- `bin/todo_item/main.py`: the help
|
||||
|
||||
### 365. Have `score-outcomes` read the finished and dropped items of a plan outside the checkout, from the project repo's history or from Jira's issue changelogs.
|
||||
|
||||
lilleman's call, 2026-11-12: 0.10.0 and 0.11.0 switch the history tools off for a plan outside the checkout, and 0.13.0 holds only their ports. In Jira a dropped item, which `Drop item` commit titles mark today, is an issue resolved by a resolution the config names.
|
||||
@@ -337,28 +285,27 @@ Releases are the human's, and `CLAUDE.md` → "Working loop" already ends the lo
|
||||
|
||||
Raised by the goals audit of PR #296. `bin/routing_figures/calls.py` groups a chunk's review rounds by the rung its worker started on, and calls for a routing change when a lower rung took more of them. Since PR #296 the reviewers may run above the worker's rung, on the one their item's E + I picks, and no figure groups rounds by it, though the archived worker line names the E + I it follows from. A cheap worker on an item of high E + I gets stronger reviewers, who may raise more rounds, and a call could then blame the worker's rung for them: an interrupt of lilleman that settles nothing (goal 1.2).
|
||||
|
||||
### 300. Reach the comprehension floor: restructure the places the comprehension seats found hardest to follow, so the project reads at 7.0 or above on every dimension, Locality and Self-sufficiency first; today the scoring run at 8f03747 scored Navigation 6.75, Locality 5.63, Shape 5.75, Self-sufficiency 5.63 and Overall 6.00.
|
||||
### 300. Reach the comprehension floor: restructure the places the comprehension seats found hardest to follow, so the project reads at 7.0 or above on every dimension, Locality first; today the scoring run at 55235a0 scored Navigation 7.38, Locality 6.13, Shape 6.50, Self-sufficiency 6.50 and Overall 6.50.
|
||||
|
||||
Filed by the comprehension check of PR #473 at 13d1550 (`larv-review record-scoring`), which printed `Floor:` and `Next:`, and refreshed from the second run of PR #520 at 8f03747. The lowest means are Locality and Self-sufficiency, 5.63 each: the seats name state shared across modules, such as the route and the archive order, and reasons that sit in `docs/decisions.md`, `CLAUDE.md` or `skills/larv-review/SKILL.md` rather than beside the code. Refresh this item's places and aim from the newest run before the chunk starts; do not file a second floor item.
|
||||
Filed by the comprehension check of PR #473 at 13d1550 (`larv-review record-scoring`), which printed `Floor:` and `Next:`, and refreshed from the two runs of PR #560 at 55235a0. The lowest mean is Locality, 6.13 in both runs: the seats name rules held partly in agent-facing prose and partly in code, and state that one unit can't be read without three others open. Self-sufficiency and Shape follow at 6.50. Refresh this item's places and aim from the newest run before the chunk starts; do not file a second floor item.
|
||||
|
||||
Aim: one ambitious refactor of the areas below, sized so every mean reaches 7.0 on the chunk's own scoring run. Where a place is already easier to read when the chunk starts, drop it.
|
||||
|
||||
Places the seats named, hardest first (`larv-review places`):
|
||||
Places the seats named, hardest first (`larv-review places`), Locality first:
|
||||
|
||||
- Locality, Self-sufficiency: `bin/loop_claude/routing.py:93` `unfinished_route`, with `escalated_route`: the floor, the cap counted from `item_rung`, the escalation mark, the unfinished count and the E + I taken in are held at once across four files, and why they combine sits in the decision log. Every seat named it; three would least want to change it.
|
||||
- Shape, Self-sufficiency: `bin/release_plan/release_standing.py:168` `next_release`, with `standing`: `str | None | Failure` fields in `LastCut`, the `BEFORE_FIRST_RELEASE` sentinel and `nothing_cut` meet in the `is_earliest` test, read as truth tables; four tools choose the next release through it.
|
||||
- Locality: `bin/loop_claude/cycle/run.py:154` `rule`, with `:67` `run_cycle` and `:94` `archived`: archives twice in an order that matters and that nothing enforces, the archive helpers sit in the cycle runner though `loop/close.py` imports them, and `run_cycle` replaces `cycle.route` outside the state machine.
|
||||
- Shape: `bin/release_plan/ranking.py:47` `rank`, `:134` `weigh`, `:229` `score` and `:240` `weight_of`: every function forks on `SHAPE` versus `OLD_SHAPE`, and the constants' reasons are only "docs/decisions.md records the choice".
|
||||
- Shape: `bin/rule_hook/todo_check.py:22` `todo_breaches`, with `:42` `folder_breaches`: three paths, `held()` beside `located()`, the checkout's own script only under `same_repo`, and a blob hashed by hand.
|
||||
- Locality, Self-sufficiency: `bin/larv_review/plan.py:66` `plan_reasons` and `bin/larv_review/owed.py:46` `shortfall`: the rule for when a scoring run is due is split between the 155-line help and the code, and the number owed hangs on the wording `EMPTIED_WORDS`.
|
||||
- Self-sufficiency: `bin/loop_claude/cycle/judge.py:21` `INTERRUPT_RULES`, with `:196` `quotes_checked`: behaviour held in prompt text and schema descriptions the code can't explain, and prompts that quote `CLAUDE.md` wording.
|
||||
- Self-sufficiency: `skills/larv-review/SKILL.md:82` "Round cap": dense rules that point at `CLAUDE.md`, `review-findings.md` and the rules files, read three times before the code matched.
|
||||
- Self-sufficiency: `bin/rule_hook/round_cap.py:26` `earlier_titles`: fails open on the unattended path where git cannot list the branch's titles, and the round title is spelt by hand in SKILL.md, `larv_review/main.py` and `reviewer_header.py` beside `round_titles.py`.
|
||||
- Locality, Shape: `bin/chunk_preflight/choices.py:80` `forge_of`: forge identity and forge calls live in two tool packages, so a second forge lands in three.
|
||||
- Navigation, Shape: `README.md:131` `bin/`: about 63 entries at one level, the shared libraries told apart only by README prose.
|
||||
- Shape: `bin/loop_claude/loop/reload.py:220` `decoded_route`: one dense guard, and renaming a `LoopRun` field stops a running loop.
|
||||
- Shape: `README.md:3` trial folders: four finished experiments at the root beside the working areas.
|
||||
- Self-sufficiency: the seats on this run name the decision-log titles that code cites for a constant's reason (`routing: …` in `routing.py`, `ladder.py`, `judge.py`) as the largest cost; state each reason beside its constant.
|
||||
- Locality, Self-sufficiency: `bin/release_plan/release_standing.py:176` `next_release`, with `:162` `carried`: the cut from a tag, a dated heading or `BEFORE_FIRST_RELEASE`, release names replayed from the plan's history, and renames meet in the `is_earliest` test at `:198`; `carried` is reapplied in `chunk_item` and in `chunk_preflight/choices.py` `planned`, one relying on `zip` keeping order. All eight seats named it; four would least want to change it.
|
||||
- Locality: `bin/loop_claude/routing.py:116` `unfinished_route`, with `:131` `escalated_route`: five rungs, the unfinished count and the escalation mark, which spans `escalation_mark.py`, `judge.py`, `verdicts.py`, `route.py` and `reload.py`. Seven seats named it; the module table is what makes it readable.
|
||||
- Locality: `bin/chunk_pr/main.py:298` `merged`, with `:384` `levelled_and_finished` and `:407` `finished`: a loop around the queue turn binds `done` only under some `if ready` branches, the approval wait is a fall-through, and `finished` destructures five subprocess results by position.
|
||||
- Locality: `skills/larv-review/SKILL.md:82` "Round cap" and `:90` "Re-entry", with `bin/review_rules/round_titles.py:45` and `:63` `past_cap`, `bin/rule_hook/round_cap.py:10` and `bin/larv_review/reviewer_header.py:73`: the round cap lives in five places, and SKILL.md's Done, Cap, Re-entry and Mechanical answers point at each other as prose.
|
||||
- Locality: `bin/loop_claude/loop/chunk_windows.py:107` `start_chunks`: under one flock it checks the session's owner, splits running from stopped windows, computes the room, reads the plan with a fallback, gathers held items and filters again, with the limit applied a second time in `may_start`.
|
||||
- Shape, Locality: `bin/release_plan/ranking.py:239` `score`, `:144` `weigh` and `:250` `weight_of`: every function forks on `SHAPE` versus `OLD_SHAPE`, and one Score depends on five inputs held in other files.
|
||||
- Locality, Shape: `bin/plan_store/stores.py:1` and `bin/release_plan/todo_table.py:1`: `release_plan` and `plan_store` import each other, the plan has three names, and the goals file sits under `release_plan`.
|
||||
- Shape: `bin/larv_review/plan.py:22` `scoring_run_due`, with `owed.py`, `unmeasured.py` and `scoring.py`: the scoring-run trigger is spread over four modules, three of whose names don't say it, in a flat 14-module package that mixes rounds, the comprehension check and its triggers.
|
||||
- Self-sufficiency: `bin/loop_claude/cycle/judge.py:22` `INTERRUPT_RULES`, with `:197` `quotes_checked`: the judge's behaviour is held partly in prompt text and field metadata and partly in Python checks.
|
||||
- Shape: `bin/plan_store/jira_epic.py:356` `revision_of`: indexes the untyped tuple `scores` at `:530` returns by position.
|
||||
- Shape: `bin/loop_claude/cycle/run.py:55` `Cycle.todo`, `bin/loop_claude/hand_over.py:23` `hand_over` and `bin/release_plan/named_code.py:5`: names that say todo.md where the plan may be a Jira epic, a handover that is not the reload's, and a module with no code in it.
|
||||
- Navigation, Shape: `README.md:197` the `bin/` package list: 74 entries at one level, with the README's list as the only index.
|
||||
- Self-sufficiency: every seat names the decision-log titles that code cites for a reason (`routing.py:1`, `ranking.py:20`, `loop/routing_check.py:1`) as a cost; state each reason beside its constant and keep the citation as a footnote.
|
||||
|
||||
Scored L 4 because the refactor touches several components that hold known defects, E 2 because review and a manual check see a regression, I 3 because every session runs these tools. The chunk runs a scoring run, since it is a floor item.
|
||||
|
||||
|
||||
Reference in New Issue
Block a user