Compare commits

...

35 Commits

Author SHA1 Message Date
lilleman e4529bee9c Finish item 394 in the plan
CI / tests (pull_request) Successful in 3m7s
2026-11-17 00:02:47 +01:00
lilleman 8c17462321 Answer product-owner round 1: 0 🔴, 0 🟡 (0 misread); the error text now names Jira
CI / tests (pull_request) Failing after 3m5s
2026-11-17 00:01:09 +01:00
lilleman 315b4da925 Answer stability round 1: 0 🔴, 0 🟡 (0 misread); the Otherwise nit and the preflight count are answered in the summary 2026-11-17 00:01:09 +01:00
lilleman 2c504133b8 Answer prose round 1: 0 🔴, 3 🟡 (0 misread); the Jira sentence moves after the finish sentence, the help and error text name Jira, and the test names lose the negation 2026-11-17 00:01:09 +01:00
lilleman 1c031866a4 Answer security round 1: 0 🔴, 0 🟡 (0 misread); the indentation note was fixed as a style change 2026-11-16 23:58:50 +01:00
lilleman 1598b6178e Indent the Jira finish call as its case's other bodies 2026-11-16 23:58:40 +01:00
lilleman ac9566510c Test that a failing finish in a Jira plan says not finished 2026-11-16 23:49:16 +01:00
lilleman 3afbb55451 Write no changelog bullet for a plan kept in Jira: todo-item finish there needs no changelog flag and refuses --changelog
CI / tests (pull_request) Successful in 3m17s
2026-11-16 23:40:13 +01:00
lilleman 4b5086153a Make the Touches lists of items 303, 306, 287 and 387 readable: mark only named parts small
CI / tests (pull_request) Successful in 3m14s
2026-11-16 23:33:26 +01:00
lilleman 5bb49dc623 File item 394 and move items 303, 306, 304, 287, 387, 338 and 288 into 0.12.0
CI / tests (pull_request) Successful in 3m21s
2026-11-16 23:23:24 +01:00
lilleman ce98a50027 Cut release 0.11.0
CI / tests (pull_request) Successful in 3m5s
2026-11-16 21:30:33 +01:00
lilleman 3c85562bb9 Answer prose round 1: 0 🔴, 4 🟡 (0 misread); the entry says what OTLP is and sends, the archive traces each cycle, and both lists keep their order
CI / tests (pull_request) Successful in 3m5s
2026-11-16 21:25:46 +01:00
lilleman 242f87a9b3 Record that the tools send no OTLP traces, logs or metrics, and loop-claude's archive is the trace of each cycle
CI / tests (pull_request) Successful in 3m7s
2026-11-16 21:23:54 +01:00
lilleman 8d24f73971 Record the comprehension check: paired ruling better at 31da587 against 64454f8, both seats voting better overall
CI / tests (pull_request) Successful in 3m8s
2026-11-16 16:57:45 +01:00
lilleman 2fc9f7212c Point Gathered.plan and CarriedOver at where plan_name and the moved items live now, and name next_chunk.py in the README 2026-11-16 16:57:25 +01:00
lilleman 31da587415 Answer stability round 1: 0 🔴, 14 🟡 (0 misread); tests that kill the surviving mutants, with a versioned MemoryStore and appended_to, plan/named_paths.py, TakenIn's docstring and the run-heavy rule naming LAUNCHERS; three places left to item 300
CI / tests (pull_request) Successful in 3m10s
2026-11-16 16:53:36 +01:00
lilleman 79e0f755e2 Answer product-owner round 1: 0 🔴, 2 🟡 (0 misread); the changelog says what the wider run-heavy rule refuses and that loop-claude's prompts say plan, a bad value in a Jira issue's property names the property, and a Jira edit's refusal names the issue 2026-11-16 16:48:05 +01:00
lilleman fde2718a97 Answer prose round 1: 0 🔴, 9 🟡 (0 misread); each 🟡 and 🟢 rewritten as the report asks, items 392 and 393 included, and item 300's quoted places left for its next refresh 2026-11-16 16:48:04 +01:00
lilleman a06a6dec22 Say in project-record's help that a save refuses after a teammate's save since the last save too
CI / tests (pull_request) Successful in 2m45s
2026-11-16 16:24:06 +01:00
lilleman 8deef3b4ac Answer overrides round 2: 0 🔴, 0 🟡 (0 misread); the todo-rank-check override on ba21a1ef stands, and those on two empty commits are moot 2026-11-16 16:23:45 +01:00
lilleman ba0356adae Answer principles round 2: 0 🔴, 1 🟡 (0 misread); start_window fails only where it cannot mark a new session as the checkout's, so a started chunk never reads as one that didn't start 2026-11-16 16:23:45 +01:00
lilleman a7a6640ea1 Answer architecture round 3: 0 🔴, 2 🟡 (0 misread); a record write names its version, even None, in every backend, and the unreleased section is read through markdown_text.section by one title pattern 2026-11-16 16:17:12 +01:00
lilleman 50ce373c40 Answer overrides round 1: 0 🔴, 0 🟡 (0 misread); both todo-rank-check overrides stand
CI / tests (pull_request) Successful in 2m44s
2026-11-16 16:12:36 +01:00
lilleman fda61ac06e Answer security round 1: 0 🔴, 0 🟡 (0 misread); security-review found nothing, and the full scan could not run in a subagent 2026-11-16 16:12:36 +01:00
lilleman ba21a1efcd Answer principles round 1: 2 🔴, 9 🟡 (0 misread); explicit record versions in place of the Confluence store's hidden state, the routing ruling filed as item 393 for 0.12.0, rule-hook catching heavy runs through uv, poetry, sudo and doas, one unreleased heading, one owner of the no-item message, typed Jira issues, a turn that gives its failure as a value, outcome tests for the Atlassian client, an Emptied reason type, an injected clock and git in touch-predictions, and paired record names 2026-11-16 16:12:36 +01:00
lilleman a60bfdbc1c Answer architecture round 2: 0 🔴, 1 🟡 (0 misread); the answer destinations and the help say the plan, and the notice of releases a plan outside the checkout hides prints once per chunk 2026-11-16 14:54:27 +01:00
lilleman f58250d0ce Answer architecture round 1: 4 🔴, 5 🟡 (0 misread); one-way plan packages with a plan core and an Atlassian client, one parse and print of an item's cells, a pure chunk-start decision, a settings table, one plan read and one standing per pick, one config load in chunk-pr, notifier backends in notifier, and the bin regroup filed as item 392 2026-11-16 14:47:46 +01:00
lilleman 3f7d85c48e Release review of 0.11.0
CI / tests (pull_request) Successful in 2m47s
2026-11-16 13:55:47 +01:00
lilleman 64454f86a8 Merge remote-tracking branch 'origin/main' into adf-lossless
CI / tests (pull_request) Successful in 2m48s
# Conflicts:
#	todo.md
2026-11-16 13:32:34 +01:00
lilleman b62dea42fc Answer stability round 1: 0 🔴, 0 🟡 (0 misread); approved
CI / tests (pull_request) Successful in 1m46s
2026-11-16 13:16:54 +01:00
lilleman f2b7eb7fd2 Answer prose round 1: 0 🔴, 6 🟡 (0 misread); say each pair's use once in the module docstring, name what the changelog entry keeps, and make item 391 stand alone 2026-11-16 13:16:50 +01:00
lilleman bac9cf9756 Answer overrides round 1: 0 🔴, 0 🟡 (0 misread); the override stands 2026-11-16 13:08:38 +01:00
lilleman 880d0c6342 Answer security round 1: 0 🔴, 0 🟡 (0 misread); no finding 2026-11-16 13:08:38 +01:00
lilleman 068ab77ce3 Record reading cost 2026-11-16 13:07:39 +01:00
lilleman 4985e6a2a9 Convert ADF to markdown and back through adf-codec's lossless pair
CI / tests (pull_request) Successful in 1m47s
2026-11-16 13:07:30 +01:00
126 changed files with 2127 additions and 1411 deletions
+4 -4
View File
@@ -30,6 +30,8 @@
!bin/adf_codec/node_shim/package-lock.json
!bin/adf_codec/node_shim/package.json
!bin/adf_codec/node_shim/shim.mjs
!bin/atlassian/
!bin/atlassian/*.py
!bin/branch_chunks/
!bin/branch_chunks/*.py
!bin/chunk-pr
@@ -67,8 +69,6 @@
!bin/loop_state/*.py
!bin/machine_load/
!bin/machine_load/*.py
!bin/mattermost_dm/
!bin/mattermost_dm/*.py
!bin/metric-bench
!bin/metric_bench/
!bin/metric_bench/*.py
@@ -81,6 +81,8 @@
!bin/notifier/
!bin/notifier/*.py
!bin/notify
!bin/plan/
!bin/plan/*.py
!bin/plan_store/
!bin/plan_store/*.py
!bin/project-config
@@ -126,8 +128,6 @@
!bin/score_outcomes/*.py
!bin/settings_filter.py
!bin/setup.cfg
!bin/slack_dm/
!bin/slack_dm/*.py
!bin/statusline.py
!bin/subagent-rung
!bin/subagent_rung/
+7 -1
View File
@@ -2,6 +2,11 @@
## Unreleased
- A plan kept as a Jira epic takes no changelog bullet: `todo-item finish` there needs neither `--changelog` nor `--no-changelog`, and refuses `--changelog`, since the issues' history is the changelog.
## 0.11.0
- `adf_codec.convert` can now convert ADF to markdown and back without losing a block's `localId` or the empty paragraphs Jira uses for spacing, so a Jira or Confluence document read and saved back unedited comes back identical: `markdown_to_adf_lossless`, `adf_to_markdown_lossless` and `adfs_to_markdown_lossless`. No tool calls them yet.
- A config whose `plan` names a Jira epic must now set `jira-score-formula` and `jira-score-bar`, and fails to load without them. `todo-item add` scores the item by them, refuses one under the bar unless it is exempt, and ranks the new issue among the issues the loop filed: questions first, then security findings, then by score. A person's issues keep their rank.
- `todo-item edit` and `move` work on a plan kept in a Jira epic. They change only an issue the loop filed, and never a link. Of an issue a person filed, `edit` sets only the scores, and posts the new `--comment` on the issue to tell the team why; a plan in a file takes the flag and keeps no comment.
- A release someone else cut while it still held plan items no longer stops the loop: those items count as the next release's, `chunk-preflight` tells the worker to move them there, and `loop-claude` routes on them. Where the plan names no later release and `todo.md` named none since the cut, the loop still asks which release they belong to.
@@ -13,7 +18,7 @@
- A project's config may keep each of its five records on a Confluence Cloud page: set, for example, `decisions = "confluence:https://<site>/wiki/spaces/<space>/pages/<page ID>"`, with the credentials in the config's `env-file`. `decisions` and `comprehension-history` may name a page only where `plan` names a Jira epic. The loop reads and writes the page as markdown, so a save replaces a mention or a macro on it with plain text. It never overwrites a teammate's edit: where someone saved the page since the loop read it, `project-record save` refuses and the loop asks you.
- `todo-item add` files an item into a plan kept in a Jira epic: a Task under the epic, under the project's Fix Version for the release, labelled `security` for a security finding and linked to each item that blocks it. Editing an issue still happens in Jira.
- An item of the next release may predict the files and parts it will touch, under a `Touches:` line in its detail. `chunk-preflight` then names the items that may start chunks at once, and the new `touch-predictions record` keeps each prediction beside what the merged chunk touched, in the record a project's config places with `touch-predictions`.
- CLAUDE.md and the todo-items rule define the plan as a todo.md or a Jira epic, and say plan where todo.md was false for a Jira plan.
- CLAUDE.md, the todo-items rule, and loop-claude's worker and judge prompts and `--help` define the plan as a todo.md or a Jira epic, and say plan where todo.md was false for a Jira plan.
- Reviewers without a shell read the plan from a listing that larv-review writes into the review folder, whichever store holds it.
- A project's config may set `tooling-on-host = true`, so the loop runs a legacy project's language runtime, package manager, tests and task runner directly on the host.
- A project's config may set `readability-floor` to a number from 1 to 10: the comprehension score under which code health is very important. It is 7.0 where left out.
@@ -29,6 +34,7 @@
- In a client project, the loop reads the team's own `CLAUDE.md` and `AGENTS.md` and proposes each change that aligns them with this setup in a pull request of its own. Where the team declines or doesn't answer, the loop follows the team's rule unless it breaks a project goal, and records the conflict as a decision in the `decisions` record.
- The new `project-record open <record>` prints the file in which an agent reads and edits one of a project's five records (`decisions`, `score-anchors`, `comprehension-history`, `reading-cost` and `changelog`), and `project-record save <record>` stores the edit. Every tool now reads and writes a record the same one way, so that a later release can keep a record outside files. No config needs a change.
- `loop-inbox` is gone. loop-claude now asks its questions only on its own terminal. A line typed there answers a question, and `/talk` opens the worker's session. The DM still tells you a loop waits. To upgrade, quit any `loop-inbox` still open and remove your `~/.local/bin/loop-inbox` link.
- rule-hook's `run-heavy` rule also refuses a heavy command run through `uv run`, `poetry run`, `sudo` or `doas` outside `run-heavy`, such as `uv run mutmut run` or `sudo docker build`. Run it as `~/.claude/bin/run-heavy uv run mutmut run`.
- rule-hook refuses a Read or a Grep of `~/.claude/.env` or of the `env-file` any project's config names, and a Bash command that names either or searches a folder holding either with `ag`, `grep -r` or `rg`, unless the tool skips the file as hidden or ignored, so that a worker doesn't put a credential in its transcript in passing. A command that hides the path, such as behind a glob or a variable, still goes through.
- A project's config names the service for loop-claude's DMs: `notifier = "mattermost"` or `"slack"`, with the bot's token and the recipient in the `env-file`. To upgrade, move the Mattermost keys from `~/.claude/.env` into a file outside the checkout and the config's folder, such as `~/.claude-projects/<key>.env`, name it as `env-file` and add `notifier = "mattermost"`. A project with no `notifier` gets no DM, and `~/.claude/.env` is no longer read. A failure names each missing key and holds no token.
- `mattermost-dm` is now `notify`, which sends through the project's `notifier`; `notify --help` names the keys.
+1 -1
View File
@@ -18,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. A chunk finishes its items as it merges, through `chunk-pr merge --finish <ID>`, which takes the same flags (`larv-review` §5).
- **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 plan kept in Jira takes no bullet, since the issues' history is its changelog: `finish` there refuses `--changelog`. 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.
+9 -7
View File
@@ -190,16 +190,17 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a
- `settings_filter.py` is git's clean filter for `settings.json`: it drops `"model"` and sorts the keys. `.gitattributes` sets the filter `settings` on `settings.json`, and Install's `git config` line makes this script that filter.
- `statusline.py` renders Claude Code's status line; `settings.json` → `statusLine` runs it.
- `subagent-rung [--plan] <model> <L>` prints the Agent tool's model and effort for a subagent's task, picked by its L from the project's model on the project's routing ladder, and with `--plan` never below the project's rung; `subagent-rung --help` states the rule.
- `todo-item` reads and changes a project's plan, whatever holds it: `list` prints the items in the plan's order and `show <ID>` one item's row and detail; `add …` files an item under the next free ID, `edit <ID> …` sets an item's cells or detail, and `move <ID> --release <version>` sets an item's release; `finish <ID>` removes a finished item and adds the bullet passed with `--changelog` to `CHANGELOG.md`. Each change ranks a markdown plan. `todo-item --help` states the flags.
- `todo-item` reads and changes a project's plan, whatever holds it: `list` prints the items in the plan's order and `show <ID>` one item's row and detail; `add …` files an item under the next free ID, `edit <ID> …` sets an item's cells or detail, and `move <ID> --release <version>` sets an item's release; `finish <ID>` removes a finished item and adds the bullet passed with `--changelog` to `CHANGELOG.md`, except for a plan kept in Jira. Each change ranks a markdown plan. `todo-item --help` states the flags.
- `touch-predictions record <ID>...` appends what a chunk's items were predicted to touch, under `Touches:` in their details, beside the files and parts its branch touched, to the record the config names as `touch-predictions`; `touch-predictions --help` shows the spelling and how a part is named. `chunk-preflight` reads the same predictions to name the items that may start chunks at once.
- `wait-for <file> [<pattern>] [--timeout <seconds>]` waits until a file a background job writes holds a line matching the pattern, and prints it.
`bin/` is the import root: each launcher puts it on `sys.path`, so a module imports another by its path under `bin/`, such as `from claude_code.entries import parse_entry`. Each tool's package holds its tests. Beside the packages, `bin/`'s root holds only the launchers, the tools of one file with their tests, `test_env.py`, `failure.py` and `setup.cfg`. `failure.py`'s `Failure`, which modules across `bin/` return for a failed step, belongs to no single package. `branch_chunks/`, `claude_code/`, `command_lines/`, `git_cli/`, `loop_effects/`, `loop_state/`, `machine_load/`, `model_routing/`, `notifier/`, `plan_store/`, `record_store/`, `release_plan/`, `review_rules/`, `rung_replay/`, `text_files/` and `transcript_archive/` serve more than one tool.
`bin/` is the import root: each launcher puts it on `sys.path`, so a module imports another by its path under `bin/`, such as `from claude_code.entries import parse_entry`. Each tool's package holds its tests. Beside the packages, `bin/`'s root holds only the launchers, the tools of one file with their tests, `test_env.py`, `failure.py` and `setup.cfg`. `failure.py`'s `Failure`, which modules across `bin/` return for a failed step, belongs to no single package. `atlassian/`, `branch_chunks/`, `claude_code/`, `command_lines/`, `git_cli/`, `loop_effects/`, `loop_state/`, `machine_load/`, `model_routing/`, `notifier/`, `plan/`, `plan_store/`, `record_store/`, `release_plan/`, `review_rules/`, `rung_replay/`, `text_files/` and `transcript_archive/` serve more than one tool. No package imports one that imports it back, which `repo_checks/test_package_cycles.py` checks.
- `adf_codec/` converts markdown to ADF, the rich text of Jira Cloud and Confluence, and back, in a throwaway container running a pinned `@larvit/adf-codec`. It builds the container's image inside a heavy slot.
- `atlassian/` holds what the Jira and Confluence backends share (`client.py`): one Atlassian account's credentials, the request both backends send, and each service's error messages.
- `branch_chunks/` cuts a default branch into chunks and finds, for each, the items it shipped and the later chunks that fixed its code, for `score_outcomes` and `routing_figures`. It imports `reading_cost`'s record path.
- `command_lines/` reads a shell command: its simple commands, and a docker call's subcommand and memory limits, for `command_patterns`, `reading_cost`, `routing_figures`, `rule_hook` and `run_heavy`.
- `chunk_pr` imports `deploy_release`'s forge calls, and `forge_of` as `deploy_release` does.
- `command_lines/` reads a shell command: its simple commands, and a docker call's subcommand and memory limits, for `command_patterns`, `reading_cost`, `routing_figures`, `rule_hook` and `run_heavy`.
- `deploy_release` imports `chunk_preflight`'s `forge_of`, which tells a GitHub origin from a Gitea one, and `release_plan`'s `release_standing`.
- `git_cli/` runs git for every tool (`git_repo.py`), and reads the git calls in a shell command (`git_command.py`).
- `judge_replay` imports `loop_claude`'s judge, verdicts, premises and records.
@@ -208,13 +209,14 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a
- `loop_state/` holds where loop-claude keeps its files (`paths.py`), which `rung_replay` reads too.
- `machine_load/` takes the machine's heavy slots, its shared lock files, for `run_heavy` and `adf_codec`, and reads the memory share that loop-claude waits for. It also gives `mutate_changes` a slot's CPU count.
- `model_routing/` holds the 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, since it changes no link, and `fakes.py` a plan in memory.
- `notifier/` sends the human a DM through the notifier a project's config names, for `notify` and for loop-claude through `loop_effects`. Its backends are `mattermost.py` and `slack.py`.
- `plan/` is the plan's core, and imports neither `plan_store` nor `release_plan`. It holds an item and the items table's format (`todo_table.py`), releases (`release.py`), the ranking (`ranking.py`, with its score formula in `formula.py` and its blocker order in `blockers.py`), the paths an item's text names (`named_paths.py`) and `citations.py`, which holds `todo.md` and `docs/decisions.md` to each other. `goals_file.py` reads the goals file's sections, goals and goal weights, for the ranking and for `loop_claude`'s premises.
- `plan_store/` reads and writes a project's plan through the store the project's config names (`stores.py`). Every backend meets `plans.py`'s `PlanStore`: a markdown file (`todo_md.py`, which also ranks and checks the file in place, with its text edits in `markdown_edits.py`) or a Jira epic (`jira_epic.py`). `scoring.py` reads the goal weights that both backends rank by. `contract.py` holds the tests every backend that writes must pass, which `jira_epic.py` doesn't yet, since it changes no link, and `fakes.py` a plan in memory.
- `rank_todo.py`, `settings_filter.py` and `statusline.py` are tools of one file each, tested beside them.
- `record_store/` reads and writes a project's records, each through the store the project's config names (`stores.py`): a markdown file, a Confluence Cloud page (`confluence_page.py`), or, for the goals, a Jira epic's description (`jira_description.py`). `contract.py` holds the tests every backend must pass, and `fakes.py` a store in memory that the tests of other tools use.
- `release_plan/` reads `todo.md`'s items table and release versions, says which release is next and whether it is ready to cut (`release_standing.py`), and ranks the plan (`ranking.py`, with its score formula in `formula.py` and its blocker order in `blockers.py`). `goals_file.py` reads the goals file's sections, goals and goal weights, for the ranking and for `loop_claude`'s premises, and `citations.py` holds `todo.md` and `docs/decisions.md` to each other. `plan_file.py` ranks, checks and writes a `todo.md`, for `larv_review`, `rank_todo.py` and `rule_hook`.
- `release_plan/` says which release is next and whether it is ready to cut (`release_standing.py`), from the plan, the changelog and the tags, and picks the item the next chunk takes first (`next_chunk.py`), for `chunk_preflight` and `loop_claude`.
- `repo_checks/` tests the repo itself.
- `rest_client/` sends a JSON request to a REST API and reads its credentials from an env file, for `mattermost_dm`, `slack_dm`, `plan_store` and `record_store`.
- `rest_client/` sends a JSON request to a REST API and reads its credentials from an env file, for `notifier`, `atlassian` and `record_store`.
- `review_rules/` holds the larv-review rules that several tools apply: its passes, its review folder, its round commit titles and the comprehension history's format.
- `routing_figures/` measures loop-claude's archive, and each of its projects' default branches, for loop-claude's routing calls.
- `rung_replay/` holds what `judge_replay` and `review_replay` share: the parallel replay runner, the argument reader, the candidate rungs and the exits, and `judge_replay`'s rung search. It reads `loop_claude`'s retry count and models file, and finds that file through `loop_state`'s paths.
+40 -10
View File
@@ -1,6 +1,10 @@
"""Converts markdown to ADF (Atlassian Document Format, the rich text of Jira Cloud and Confluence) and back.
It runs @larvit/adf-codec, a Node package, in a throwaway container that holds node_shim/shim.mjs; the shim's header says what its exit status means.
adf-codec has two pairs of calls, and each function here names the one it runs:
- The lossless pair, `*_lossless`, for a document that already exists in Jira or Confluence and is edited and saved back. It keeps each block's localId and the empty paragraphs Jira uses for spacing, so a document read and saved unedited comes back identical.
- The portable pair, with no suffix, for new text written from scratch, and for markdown shown to a person. It drops the localId and the empty paragraphs, so saving a document that exists changes it.
"""
import contextlib
import dataclasses
@@ -31,7 +35,7 @@ class Ran:
err: str
# Runs the shim in the given mode (`to-adf` or `to-markdown`) on a text, or fails to run it.
# Runs the shim in the given mode (`to-adf`, `to-markdown`, `to-adf-lossless` or `to-markdown-lossless`) on a text, or fails to run it.
Run = typing.Callable[[str, str], Ran | Failure]
# Runs a docker command line on a text, in at most the given seconds, or fails to run it.
Docker = typing.Callable[[list[str], str, int], Ran | Failure]
@@ -149,9 +153,8 @@ def refusal(out: str) -> Refused | Failure:
return Failure(f"the adf-codec shim refused with output that is not an error: {out.strip()}")
def markdown_to_adf(markdown: str, run: Run = container_run) -> dict[str, typing.Any] | Failure:
"""The ADF document for the markdown."""
out = answer("to-adf", markdown, run)
def to_adf(mode: str, markdown: str, run: Run) -> dict[str, typing.Any] | Failure:
out = answer(mode, markdown, run)
if isinstance(out, Refused):
return out.failure
if isinstance(out, Failure):
@@ -163,11 +166,10 @@ def markdown_to_adf(markdown: str, run: Run = container_run) -> dict[str, typing
return document
def adfs_to_markdown(documents: list[dict[str, typing.Any]], run: Run = container_run) -> list[str] | Refused | Failure:
"""The markdown for each ADF document, in their order, from one container run, so a caller with many documents pays one container start."""
def to_markdowns(mode: str, documents: list[dict[str, typing.Any]], run: Run) -> list[str] | Refused | Failure:
if not documents:
return []
out = answer("to-markdown", json.dumps(documents), run)
out = answer(mode, json.dumps(documents), run)
if isinstance(out, Refused) and not 0 <= out.index < len(documents):
return Failure(f"the adf-codec shim refused a document at index {out.index}, past the {len(documents)} it was handed")
if isinstance(out, Refused | Failure):
@@ -181,9 +183,37 @@ def adfs_to_markdown(documents: list[dict[str, typing.Any]], run: Run = containe
return texts
def adf_to_markdown(document: dict[str, typing.Any], run: Run = container_run) -> str | Failure:
"""The markdown for the ADF document."""
texts = adfs_to_markdown([document], run)
def one_markdown(texts: list[str] | Refused | Failure) -> str | Failure:
if isinstance(texts, Refused):
return texts.failure
return texts if isinstance(texts, Failure) else texts[0]
def markdown_to_adf(markdown: str, run: Run = container_run) -> dict[str, typing.Any] | Failure:
"""The ADF document for the markdown, by the portable pair."""
return to_adf("to-adf", markdown, run)
def markdown_to_adf_lossless(markdown: str, run: Run = container_run) -> dict[str, typing.Any] | Failure:
"""The ADF document for the markdown, by the lossless pair."""
return to_adf("to-adf-lossless", markdown, run)
def adfs_to_markdown(documents: list[dict[str, typing.Any]], run: Run = container_run) -> list[str] | Refused | Failure:
"""The markdown for each ADF document, in their order, by the portable pair, from one container run, so a caller with many documents pays one container start."""
return to_markdowns("to-markdown", documents, run)
def adfs_to_markdown_lossless(documents: list[dict[str, typing.Any]], run: Run = container_run) -> list[str] | Refused | Failure:
"""The markdown for each ADF document, in their order, by the lossless pair, from one container run."""
return to_markdowns("to-markdown-lossless", documents, run)
def adf_to_markdown(document: dict[str, typing.Any], run: Run = container_run) -> str | Failure:
"""The markdown for the ADF document, by the portable pair."""
return one_markdown(adfs_to_markdown([document], run))
def adf_to_markdown_lossless(document: dict[str, typing.Any], run: Run = container_run) -> str | Failure:
"""The markdown for the ADF document, by the lossless pair."""
return one_markdown(adfs_to_markdown_lossless([document], run))
+12 -9
View File
@@ -1,10 +1,11 @@
// Converts between markdown and ADF with @larvit/adf-codec's portable calls. The mode is the one argument:
// Converts between markdown and ADF with @larvit/adf-codec. The mode is the one argument:
// to-adf stdin is markdown, stdout is the ADF document as JSON
// to-markdown stdin is a JSON array of ADF documents, stdout a JSON array of their markdown texts, in their order
// to-adf-lossless, to-markdown-lossless the same, through adf-codec's lossless pair in place of its portable pair
// Exit 0: stdout holds the answer. Exit 2: adf-codec refused the input, and stdout holds {"error": {code, message, path, position?}},
// with "index", the refused document's place in the array, beside "error" in to-markdown.
// Exit 1: the shim could not run, and stderr says why.
import { adfToPortableMarkdown, portableMarkdownToAdf } from '@larvit/adf-codec'
import { adfToLosslessMarkdown, adfToPortableMarkdown, losslessMarkdownToAdf, portableMarkdownToAdf } from '@larvit/adf-codec'
const REFUSED = 2
@@ -19,17 +20,17 @@ function refuse(refusal) {
return REFUSED
}
function toAdf(markdown) {
const result = portableMarkdownToAdf(markdown)
function toAdf(convert, markdown) {
const result = convert(markdown)
if (!result.ok) return refuse({ error: result.error })
process.stdout.write(JSON.stringify(result.value))
return 0
}
function toMarkdown(documents) {
function toMarkdown(convert, documents) {
const texts = []
for (const [index, document] of documents.entries()) {
const result = adfToPortableMarkdown(document)
const result = convert(document)
if (!result.ok) return refuse({ index, error: result.error })
texts.push(result.value)
}
@@ -39,9 +40,11 @@ function toMarkdown(documents) {
async function main(mode) {
const input = await readStdin()
if (mode === 'to-adf') return toAdf(input)
if (mode === 'to-markdown') return toMarkdown(JSON.parse(input))
throw new Error(`mode must be to-adf or to-markdown, not ${mode}`)
if (mode === 'to-adf') return toAdf(portableMarkdownToAdf, input)
if (mode === 'to-adf-lossless') return toAdf(losslessMarkdownToAdf, input)
if (mode === 'to-markdown') return toMarkdown(adfToPortableMarkdown, JSON.parse(input))
if (mode === 'to-markdown-lossless') return toMarkdown(adfToLosslessMarkdown, JSON.parse(input))
throw new Error(`mode must be to-adf, to-adf-lossless, to-markdown or to-markdown-lossless, not ${mode}`)
}
main(process.argv[2]).then(
+55
View File
@@ -66,6 +66,36 @@ def test_adf_to_markdown_returns_the_text_of_its_one_document():
assert run.calls == [("to-markdown", json.dumps([DOC]))]
def test_markdown_to_adf_lossless_runs_the_lossless_mode():
run = fake(0, json.dumps(DOC))
assert convert.markdown_to_adf_lossless("Hi\n", run) == DOC
assert run.calls == [("to-adf-lossless", "Hi\n")]
def test_adfs_to_markdown_lossless_sends_every_document_in_one_lossless_run():
run = fake(0, json.dumps(["a\n", "b\n"]))
assert convert.adfs_to_markdown_lossless([DOC, DOC], run) == ["a\n", "b\n"]
assert run.calls == [("to-markdown-lossless", json.dumps([DOC, DOC]))]
def test_adf_to_markdown_lossless_returns_the_text_of_its_one_document():
run = fake(0, json.dumps(["a\n"]))
assert convert.adf_to_markdown_lossless(DOC, run) == "a\n"
assert run.calls == [("to-markdown-lossless", json.dumps([DOC]))]
def test_adfs_to_markdown_lossless_names_a_refused_documents_index():
refusal = {"index": 1, "error": {"code": "not-an-adf-document", "message": "no type", "path": []}}
refused = convert.adfs_to_markdown_lossless([DOC, DOC], fake(2, json.dumps(refusal)))
assert refused == convert.Refused(1, Failure("adf-codec refused the input with not-an-adf-document: no type (at the document)"))
def test_adfs_to_markdown_lossless_of_no_documents_runs_no_container():
run = fake(1)
assert convert.adfs_to_markdown_lossless([], run) == []
assert run.calls == []
def test_a_refusal_becomes_a_failure_with_adf_codecs_code_and_message():
refusal = {"error": {"code": "malformed-pipe-table", "message": "row has too many cells", "path": [], "position": {"line": 3, "offset": 9}}}
failure = convert.markdown_to_adf("| a |\n", fake(2, json.dumps(refusal)))
@@ -279,3 +309,28 @@ def test_round_trip_through_the_real_container():
assert isinstance(second, convert.Refused) and second.index == 1 and "not-an-adf-document" in second.failure.reason
crashed = convert.answer("to-markdown", "not json", convert.container_run)
assert isinstance(crashed, Failure) and crashed.reason.startswith("the adf-codec shim failed with exit 1: ")
# A Jira description as Jira stores it: every block carries a localId, and an empty paragraph spaces two blocks.
JIRA_DESCRIPTION = {
"type": "doc", "version": 1, "content": [
{"type": "heading", "attrs": {"level": 2, "localId": "h-1"}, "content": [{"type": "text", "text": "Goal"}]},
{"type": "paragraph", "attrs": {"localId": "p-1"}, "content": [{"type": "text", "text": "Keep "}, {"type": "text", "text": "this", "marks": [{"type": "strong"}]}]},
{"type": "paragraph", "attrs": {"localId": "p-2"}},
{"type": "bulletList", "attrs": {"localId": "l-1"}, "content": [
{"type": "listItem", "attrs": {"localId": "i-1"}, "content": [{"type": "paragraph", "attrs": {"localId": "p-3"}, "content": [{"type": "text", "text": "one"}]}]},
]},
],
}
@pytest.mark.skipif(shutil.which("docker") is None or subprocess.run(["docker", "info"], capture_output=True, timeout=20).returncode != 0, reason="needs a docker daemon")
def test_the_lossless_pair_gives_back_a_jira_description_identical_and_the_portable_pair_does_not():
markdown = convert.adf_to_markdown_lossless(JIRA_DESCRIPTION)
assert isinstance(markdown, str)
assert convert.markdown_to_adf_lossless(markdown) == JIRA_DESCRIPTION
assert convert.adfs_to_markdown_lossless([JIRA_DESCRIPTION, JIRA_DESCRIPTION]) == [markdown, markdown]
portable = convert.markdown_to_adf(convert.adf_to_markdown(JIRA_DESCRIPTION))
assert portable != JIRA_DESCRIPTION
second = convert.adfs_to_markdown_lossless([JIRA_DESCRIPTION, {"type": "nope"}])
assert isinstance(second, convert.Refused) and second.index == 1
+51
View File
@@ -0,0 +1,51 @@
"""What the Jira and Confluence backends share: one Atlassian account's credentials, the request both backends send, and each service's error messages."""
import base64
import pathlib
import typing
from failure import Failure
from rest_client import json_request
from rest_client.env_file import read_env
from adf_codec.convert import Refused
# One pair of keys for Jira and Confluence: one Atlassian account's API token opens both.
KEYS = ("ATLASSIAN_EMAIL", "ATLASSIAN_API_TOKEN")
# Seconds each connect and each read may wait.
TIMEOUT = 30
# Sends a request with the Authorization header given, the body as JSON where there is one, and returns the JSON answer, None where the answer has no body, or a Failure saying why there is none.
Http = typing.Callable[[str, str, str, object], object]
ToMarkdown = typing.Callable[[list[dict[str, typing.Any]]], list[str] | Refused | Failure]
ToAdf = typing.Callable[[str], dict[str, typing.Any] | Failure]
def basic_auth(env_file: pathlib.Path) -> str | Failure:
"""The Authorization header for the email and API token that env_file holds."""
values = read_env(env_file, KEYS, "an API token")
if isinstance(values, Failure):
return values
return "Basic " + base64.b64encode(":".join(values[key] for key in KEYS).encode()).decode()
def jira_json(method: str, url: str, authorization: str, body: object) -> object:
return json_request.http_json(method, url, authorization, body, TIMEOUT, jira_errors)
def jira_errors(answer: object) -> str:
"""Jira's messages in the JSON of an error answer; empty where it holds none."""
if not isinstance(answer, dict):
return ""
messages, errors = answer.get("errorMessages"), answer.get("errors")
found = [*(messages if isinstance(messages, list) else []), *(errors.values() if isinstance(errors, dict) else [])]
return "; ".join(text for text in found if isinstance(text, str))
def confluence_json(method: str, url: str, authorization: str, body: object) -> object:
return json_request.http_json(method, url, authorization, body, TIMEOUT, confluence_errors)
def confluence_errors(answer: object) -> str:
"""Confluence's messages in the JSON of an error answer; empty where it holds none."""
errors = answer.get("errors") if isinstance(answer, dict) else None
found = [error.get("title") for error in errors if isinstance(error, dict)] if isinstance(errors, list) else [answer.get("message")] if isinstance(answer, dict) else []
return "; ".join(text for text in found if isinstance(text, str))
+65
View File
@@ -0,0 +1,65 @@
import base64
import json
import pathlib
import sys
import tempfile
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from atlassian import client
from rest_client.json_request import ErrorAnswer
from failure import Failure
from rest_client.test_json_request import Served
AUTHORIZATION = "Basic " + base64.b64encode(b"me@example.com:s3cret").decode()
class Credentials(unittest.TestCase):
def test_builds_basic_auth_from_the_env_files_email_and_token(self):
with tempfile.TemporaryDirectory() as temp:
env = pathlib.Path(temp, "acme.env")
env.write_text("ATLASSIAN_EMAIL=me@example.com\nATLASSIAN_API_TOKEN=s3cret\n")
env.chmod(0o600)
self.assertEqual(client.basic_auth(env), AUTHORIZATION)
def test_a_missing_env_file_fails(self):
self.assertIsInstance(client.basic_auth(pathlib.Path("/nonexistent/acme.env")), Failure)
class Jira(Served):
def test_an_error_answer_fails_with_jiras_messages_and_its_status(self):
base = self.serve((400, b'{"errorMessages": ["One."], "errors": {"jql": "Two."}}'))
self.assertEqual(client.jira_json("POST", f"{base}/rest/api/3/search/jql", AUTHORIZATION, {"jql": "x"}), ErrorAnswer("POST /rest/api/3/search/jql answered 400: One.; Two.", 400))
[(_, _, headers, body)] = self.server.got # type: ignore[attr-defined]
self.assertEqual((headers["Authorization"], json.loads(body)), (AUTHORIZATION, {"jql": "x"}))
def test_reads_jiras_messages_from_an_error_answer(self):
cases = (
({"errorMessages": ["Issue does not exist or you do not have permission to see it."], "errors": {}}, "Issue does not exist or you do not have permission to see it."),
({"errorMessages": ["One."], "errors": {"jql": "Two."}}, "One.; Two."),
({"errorMessages": "One.", "errors": ["Two."]}, ""),
({"errorMessages": [7, "One."]}, "One."),
(["One."], ""),
)
for answer, message in cases:
with self.subTest(answer=answer):
self.assertEqual(client.jira_errors(answer), message)
class Confluence(Served):
def test_an_error_answer_fails_with_confluences_messages_and_its_status(self):
base = self.serve((409, b'{"errors": [{"status": 409, "title": "Version must be incremented"}]}'))
self.assertEqual(client.confluence_json("PUT", f"{base}/wiki/api/v2/pages/1", AUTHORIZATION, {"version": {"number": 2}}), ErrorAnswer("PUT /wiki/api/v2/pages/1 answered 409: Version must be incremented", 409))
[(_, _, headers, body)] = self.server.got # type: ignore[attr-defined]
self.assertEqual((headers["Authorization"], json.loads(body)), (AUTHORIZATION, {"version": {"number": 2}}))
def test_reads_confluences_messages_from_an_error_answer(self):
self.assertEqual(client.confluence_errors({"errors": [{"status": 409, "title": "Version must be incremented"}, {"title": "and more"}, "odd"]}), "Version must be incremented; and more")
self.assertEqual(client.confluence_errors({"message": "Not Found"}), "Not Found")
self.assertEqual(client.confluence_errors({"errors": "odd"}), "")
self.assertEqual(client.confluence_errors(["odd"]), "")
if __name__ == "__main__":
unittest.main()
+1 -1
View File
@@ -4,7 +4,7 @@ import typing
from failure import Failure
from review_rules.comprehension_history import HISTORY
from release_plan.todo_table import Item, items
from plan.todo_table import Item, items
from reading_cost.figures import RECORD
from project_config import templates
from text_files.utc_stamp import utc
+1 -1
View File
@@ -5,7 +5,7 @@ import re
import typing
from branch_chunks.cut import Branch, BranchChunk, NOT_WORK
from release_plan.todo_table import Exempt, Item
from plan.todo_table import Exempt, Item
from review_rules.round_titles import title_counts
# The Exempt cells, per ~/.claude/rules/todo-items.md, that mark an item fixing a defect.
+1 -1
View File
@@ -17,7 +17,7 @@ from project_config.test_project_config import configured
from failure import Failure
from git_cli.git_repo import git
from test_env import isolated_env
from release_plan.todo_table import Item
from plan.todo_table import Item
HEADER = "| ID | Release | Exempt | Item | R | S | C | A | G | Goals | Score |\n|---|---|---|---|---|---|---|---|---|---|---|\n"
WITHOUT_C = "| ID | Release | Exempt | Item | R | S | A | G | Goals | Score |\n|---|---|---|---|---|---|---|---|---|---|\n"
+4 -10
View File
@@ -8,22 +8,16 @@ from failure import Failure
from chunk_preflight.gathered import Forge
from deploy_release.forge import Run
BIN = pathlib.Path(__file__).resolve().parents[1]
# A human answers in hours, so merge polls once a minute and gives up after 90 minutes. That leaves half an hour for the queue and the checks inside the 2 hours a background command may run; a run that needs more is killed before the give-up message prints, and its next run goes on from what it pushed.
POLL_SECONDS = 60
WAIT_SECONDS = 90 * 60
def awaited(forge: Forge, run: Run) -> bool | Failure:
"""Whether merge waits for an approval: the project config's `wait-for-approval`. A config that cannot be read fails, so that merge never skips an approval the config may require. chunk-pr reads approvals on GitHub only, so a Gitea project that sets it fails too."""
answer = run([str(BIN / "project-config"), "wait-for-approval"])
if isinstance(answer, Failure):
return answer
if answer.strip() not in ("true", "false"):
return Failure(f"project-config wait-for-approval printed {answer.strip()[:80]!r}, not true or false")
if answer.strip() == "true" and forge != "gh":
def awaited(forge: Forge, wait_for_approval: bool) -> bool | Failure:
"""Whether merge waits for an approval: the project config's `wait-for-approval`. chunk-pr reads approvals on GitHub only, so a Gitea project that sets it fails, and merge never skips an approval the config requires."""
if wait_for_approval and forge != "gh":
return Failure("the project's config sets wait-for-approval, but chunk-pr reads approvals on GitHub only, so it cannot merge this pull request; ask the human to merge it")
return answer.strip() == "true"
return wait_for_approval
# Each review thread, with whether it is resolved and who wrote its last comment, beside who opened the pull request. gh fills {owner} and {repo} from the checkout.
+120 -77
View File
@@ -29,8 +29,9 @@ merge merges the pull request in its turn: the chunks of one project on this
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;
--changelog or --no-changelog (a Jira plan takes no --changelog, as todo-item says),
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
@@ -76,6 +77,7 @@ It prints what it did, exit 0, or why it failed, exit 1.
import contextlib
import dataclasses
import fcntl
import functools
import json
import os
import pathlib
@@ -88,6 +90,9 @@ from deploy_release.forge import checks_passed, gitea, merged_pull, open_pull, r
from failure import Failure
from chunk_preflight.gathered import Forge
from chunk_preflight.choices import forge_of
from project_config.main import located
from project_config.settings import ProjectConfig
from plan_store.plans import says_no_item
from project_config import templates
BIN = pathlib.Path(__file__).resolve().parents[1]
@@ -100,6 +105,8 @@ QUEUE_SECONDS = 30 * 60
QUEUE_POLL_SECONDS = 10
# The line record-ruling writes into the comprehension history, as git's -G reads it.
RULING = "^Ruling: "
# The project's config, loaded once per step, on the first call that needs it.
Config = typing.Callable[[], ProjectConfig | Failure]
USAGE = "usage: chunk-pr open <title> [<body>] | chunk-pr sync | chunk-pr ready [<title>] | chunk-pr merge [--finish <ID> [--changelog <bullet> | --no-changelog]]... | chunk-pr clean"
# Each forge's merge methods in the order merge prefers them, as the repository setting that allows the method and the method's name in the forge's merge call. A merge commit and a fast-forward keep the branch's commits as they are; a rebase or a squash rewrites them.
@@ -113,7 +120,7 @@ def main(argv: list[str]) -> int:
if argv[:1] in (["-h"], ["--help"]):
print(__doc__.strip())
return 0
done = step(argv, runner(os.getcwd()))
done = step(argv, runner(os.getcwd()), functools.cache(lambda: located(os.getcwd(), pathlib.Path.home())))
if isinstance(done, Failure):
print(f"chunk-pr: {done.reason}", file=sys.stderr)
return 1
@@ -121,32 +128,34 @@ def main(argv: list[str]) -> int:
return 0
def step(argv: list[str], run: Run) -> str | Failure:
def step(argv: list[str], run: Run, config: Config) -> str | Failure:
"""Run the step argv names: the line to print, or a Failure. A malformed argv doesn't run anything."""
match argv:
case ["open", title, *body] if len(body) <= 1 and not title.startswith("-"):
return Failure("give a title of one line") if not one_line(title) else misfit(title, run) or opened(title, body[0] if body else "", run)
return Failure("give a title of one line") if not one_line(title) else misfit(title, run, config) or opened(title, body[0] if body else "", run)
case ["sync"]:
return synced(run)
return synced(run, config)
case ["ready", *title] if len(title) <= 1 and not any(given.startswith("-") for given in title):
return Failure("give a title of one line") if title and not one_line(title[0]) else (misfit(title[0], run) if title else None) or marked_ready(run, title[0] if title else None)
return Failure("give a title of one line") if title and not one_line(title[0]) else (misfit(title[0], run, config) if title else None) or marked_ready(run, title[0] if title else None)
case ["merge", *given]:
finishes = finishes_of(given)
return Failure(USAGE) if finishes is None else merged(run, finishes=finishes)
return Failure(USAGE) if finishes is None else merged(run, config, finishes=finishes)
case ["clean"]:
return cleaned(run)
return Failure(USAGE)
def misfit(title: str, run: Run) -> Failure | None:
"""Why title doesn't fit the `pull-request-title` template the project's config names; None where it fits. A branch that doesn't fit the config's `branch` template is no plan item's, so it has no ID for {id}, and any title fits there. A config that cannot be read fails, so that no pull request reaches the project's owners under a title they don't use."""
read = [run([str(BIN / "project-config"), "pull-request-title"]), run([str(BIN / "project-config"), "branch"]), run(["git", "symbolic-ref", "--short", "HEAD"])]
if failed := next((answer for answer in read if isinstance(answer, Failure)), None):
return failed
template, branch_template, branch = (answer.strip("\n") for answer in read if isinstance(answer, str))
if not templates.branch_fits(branch_template, branch) or templates.fits(template, title.strip()):
def misfit(title: str, run: Run, config: Config) -> Failure | None:
"""Why title doesn't fit the `pull-request-title` template the project's config names, as templates.misfits rules; None where it fits. A config that cannot be read fails, so that no pull request reaches the project's owners under a title they don't use."""
loaded = config()
if isinstance(loaded, Failure):
return loaded
branch = run(["git", "symbolic-ref", "--short", "HEAD"])
if isinstance(branch, Failure):
return branch
if not templates.misfits(loaded.pull_request_title, loaded.branch, branch.strip("\n"), title):
return None
return Failure(f"title the pull request as the project's config asks, `{template}`, where {{id}} is the ID of the chunk's first item; {title.strip()!r} doesn't fit")
return Failure(f"title the pull request as the project's config asks, `{loaded.pull_request_title}`, where {{id}} is the ID of the chunk's first item; {title.strip()!r} doesn't fit")
def one_line(title: str) -> bool:
@@ -217,7 +226,7 @@ def opened(title: str, body: str, run: Run) -> str | Failure:
return number if isinstance(number, Failure) else f"Opened draft pull request #{number}."
def synced(run: Run) -> str | Failure:
def synced(run: Run, config: Config) -> str | Failure:
found = checkout(run)
if isinstance(found, Failure):
return found
@@ -231,11 +240,12 @@ def synced(run: Run) -> str | Failure:
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}")
todo = pathlib.Path(plan.strip())
if not todo.is_file():
loaded = config()
if isinstance(loaded, Failure):
return Failure(f"{done.removesuffix('.')}, but the plan to check cannot be found: {loaded.reason}")
todo = loaded.plan_file
# A plan in Jira is no file, and Jira's backlog ranks it.
if todo is None or not todo.is_file():
return done
ranked = run([str(BIN / "rank_todo.py"), "--check", str(todo)])
if isinstance(ranked, Failure):
@@ -295,13 +305,16 @@ def finishes_of(given: list[str]) -> list[list[str]] | None:
return finishes
def merged(run: Run, sleep: typing.Callable[[float], None] = time.sleep, finishes: typing.Sequence[list[str]] = ()) -> str | Failure:
def merged(run: Run, config: Config, sleep: typing.Callable[[float], None] = time.sleep, finishes: typing.Sequence[list[str]] = ()) -> str | Failure:
"""Merge the branch's pull request in the project's merge queue. Each pass of the loop is one turn in the queue; a pull request that still wants its approval leaves the queue while it waits, so the next chunk merges meanwhile, and takes a new turn once approved."""
found = pull(run)
if isinstance(found, Failure):
return found
forge, number, _ = found
waits = awaited(forge, run)
loaded = config()
if isinstance(loaded, Failure):
return loaded
waits = awaited(forge, loaded.wait_for_approval)
if isinstance(waits, Failure):
return waits
method = merge_method(forge, run)
@@ -318,53 +331,82 @@ def merged(run: Run, sleep: typing.Callable[[float], None] = time.sleep, finishe
if isinstance(absent, Failure):
return absent
file = pathlib.Path(queue[0]) / QUEUE
pull_request = Merging(forge, number, method, str(base), required, waits)
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}")
with turn(file, number, sleep) as untaken:
taken = untaken or merge_turn(pull_request, finishes, loaded, run, sleep)
if not isinstance(taken, AwaitsApproval):
return taken if isinstance(taken, Failure) else taken + absent
# Out of the queue, so the project's other chunks merge while this one waits.
waited = approved(number, run, sleep)
if isinstance(waited, Failure):
return waited
@dataclasses.dataclass(frozen=True)
class Merging:
"""A pull request that merge takes turns for: its forge and number, the merge method, the default branch it merges into with the checks that branch requires, and whether it waits for an approval."""
forge: Forge
number: str
method: str
base: str
required: set[str]
waits: bool
@dataclasses.dataclass(frozen=True)
class AwaitsApproval:
"""The pull request passed its checks but awaits a human's approval, so merge leaves the queue until it has one."""
def merge_turn(pull_request: Merging, finishes: typing.Sequence[list[str]], config: ProjectConfig, run: Run, sleep: typing.Callable[[float], None]) -> str | AwaitsApproval | Failure:
"""One turn in the queue: level the branch and finish its items, wait for its checks, and merge it where nothing still waits. What merged it, or why it waits or fails."""
head = levelled_and_finished(run, pull_request.base, finishes, config)
checked = head if isinstance(head, Failure) else checks_passed(pull_request.forge, pull_request.number, head, pull_request.required, run, sleep, NO_CHECKS_SECONDS)
if isinstance(checked, Failure):
return checked
ready = approval(pull_request.number, run) if pull_request.waits else True
if isinstance(ready, Failure):
return ready
if not ready:
return AwaitsApproval()
asked = unanswered(pull_request.number, run) if pull_request.waits else None
if asked is not None:
return asked
if pull_request.forge == "gh":
done = run(["gh", "pr", "merge", pull_request.number, pull_request.method, "--match-head-commit", str(head)])
else:
done = gitea(run, f"repos/{{owner}}/{{repo}}/pulls/{pull_request.number}/merge", f"Do={pull_request.method}", f"head_commit_id={head}")
return done if isinstance(done, Failure) else f"Merged pull request #{pull_request.number} ({pull_request.method.removeprefix('--')})."
def unplanned(run: Run, finishes: typing.Sequence[list[str]]) -> str | Failure:
"""A sentence for merge's last line, naming each item of finishes the plan doesn't hold as merge begins: an earlier run finished it, or its ID is mistyped, and only the reader can tell which. Empty where the plan holds them all."""
absent = []
for finish in finishes:
shown = run([str(BIN / "todo-item"), "show", finish[0]])
if isinstance(shown, Failure) and f"holds no item {finish[0]}" not in shown.reason:
if isinstance(shown, Failure) and not says_no_item(shown.reason, finish[0]):
return shown
absent += [finish[0]] if isinstance(shown, Failure) else []
return f" The plan held no item {', '.join(absent)} when merge began, so merge left the plan as it was there." if absent else ""
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)
def turn(queue: pathlib.Path, number: str, sleep: typing.Callable[[float], None]) -> typing.Iterator[Failure | None]:
"""Hold the project's merge queue as pull request number: wait until no other chunk-pr merge on this machine holds it, and free it on the way out, however that is. Gives None while it holds the queue; a Failure, without the queue, where another merge still holds it after QUEUE_SECONDS or the file cannot be opened or locked."""
try:
fd = os.open(queue, os.O_RDWR | os.O_CREAT, 0o644)
except OSError as failure:
yield Failure(f"cannot take a turn in the merge queue, {queue}: {failure.strerror}")
return
try:
yield held_turn(fd, queue, number, sleep)
finally:
os.close(fd)
def held_turn(fd: int, queue: pathlib.Path, number: str, sleep: typing.Callable[[float], None]) -> Failure | None:
"""Lock the open queue file fd for pull request number and write its number there, for a merge that waits to name; None once held, else why it isn't."""
try:
for waited in range(0, QUEUE_SECONDS + 1, QUEUE_POLL_SECONDS):
try:
@@ -372,16 +414,17 @@ def turn(queue: pathlib.Path, number: str, sleep: typing.Callable[[float], None]
break
except BlockingIOError:
if waited == QUEUE_SECONDS:
raise Held(os.pread(fd, 20, 0).decode(errors="replace").strip()) from None
holder = os.pread(fd, 20, 0).decode(errors="replace").strip()
return Failure(f"the merge queue stayed held for {QUEUE_SECONDS // 60} minutes, last by pull request #{holder or '?'}, so this one took no turn; run chunk-pr merge again")
sleep(QUEUE_POLL_SECONDS)
os.ftruncate(fd, 0)
os.pwrite(fd, number.encode(), 0)
yield
finally:
os.close(fd)
except OSError as failure:
return Failure(f"cannot take a turn in the merge queue, {queue}: {failure.strerror}")
return None
def levelled_and_finished(run: Run, base: str, finishes: typing.Sequence[list[str]]) -> str | Failure:
def levelled_and_finished(run: Run, base: str, finishes: typing.Sequence[list[str]], config: ProjectConfig) -> str | Failure:
"""What merge does to the branch inside its turn, before the checks: merge origin's base into it, finish the plan items, and push. The head to merge, or why the worker must act first. Whatever it committed is pushed before it fails, so the pull request's head stays the commit checked out."""
found = checkout(run)
if isinstance(found, Failure):
@@ -390,7 +433,7 @@ def levelled_and_finished(run: Run, base: str, finishes: typing.Sequence[list[st
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)
failed = next((failure for finish in finishes if (failure := finished(run, branch, finish, config))), None)
head = answers(run, ["rev-parse", "HEAD"])
if isinstance(head, Failure):
return head
@@ -401,22 +444,21 @@ def levelled_and_finished(run: Run, base: str, finishes: typing.Sequence[list[st
owed = failed or run([str(BIN / "larv-review"), "scoring-run-owed"])
if isinstance(owed, Failure):
return owed
return remeasure(run, base) or head[0]
return remeasure(run, base, config) or head[0]
def finished(run: Run, branch: str, finish: list[str]) -> Failure | None:
def finished(run: Run, branch: str, finish: list[str], config: ProjectConfig) -> Failure | None:
"""Finish one plan item with `todo-item finish` and commit what that changed. An item the plan no longer holds was finished by an earlier run of merge, which may have stopped before its commit: so the plan and the changelog are committed either way."""
shown = run([str(BIN / "todo-item"), "show", finish[0]])
if isinstance(shown, Failure) and f"holds no item {finish[0]}" not in shown.reason:
if isinstance(shown, Failure) and not says_no_item(shown.reason, finish[0]):
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()])
finishing = "" if isinstance(shown, Failure) else run([str(BIN / "todo-item"), "finish", *finish])
if isinstance(finishing, Failure):
return finishing
title = templates.title_of(config.commit_title, config.branch, branch, finish[0], f"Finish item {finish[0]} in the plan")
# A plan in Jira, or a changelog on a Confluence page, is no file to commit.
records = [record for record in (config.plan_file, config.paths.get("changelog")) if record is not None and record.is_file()]
return committed(run, title, records)
def committed(run: Run, title: str, files: list[pathlib.Path]) -> Failure | None:
@@ -435,15 +477,16 @@ def committed(run: Run, title: str, files: list[pathlib.Path]) -> Failure | None
return None
def remeasure(run: Run, base: str) -> Failure | None:
def remeasure(run: Run, base: str, config: ProjectConfig) -> Failure | None:
"""A Failure where origin's base has moved since the branch last recorded a paired ruling: that ruling read a head that no longer merges. None where the branch recorded none, or the project keeps its history outside the checkout."""
history = run([str(BIN / "project-config"), "comprehension-history"])
if isinstance(history, Failure):
return history
history = config.paths.get("comprehension-history")
# A history on a Confluence page is outside the checkout.
if history is None:
return None
top = answers(run, ["rev-parse", "--show-toplevel"])
if isinstance(top, Failure) or not pathlib.Path(history.strip()).resolve().is_relative_to(top[0]):
if isinstance(top, Failure) or not history.resolve().is_relative_to(top[0]):
return top if isinstance(top, Failure) else None
ruled = answers(run, ["log", "-1", "--format=%H", "-G", RULING, f"origin/{base}..HEAD", "--", history.strip()])
ruled = answers(run, ["log", "-1", "--format=%H", "-G", RULING, f"origin/{base}..HEAD", "--", str(history)])
if isinstance(ruled, Failure) or not ruled[0].strip():
return ruled if isinstance(ruled, Failure) else None
since = answers(run, ["rev-list", "--count", f"{ruled[0].strip()}..origin/{base}"])
+104 -94
View File
@@ -14,6 +14,7 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from chunk_pr.main import cleaned, merged, QUEUE, step, turn, USAGE
from failure import Failure
from test_env import isolated_env
from project_config.settings import ProjectConfig
from deploy_release.forge import Run
from chunk_pr.approval import THREADS
@@ -33,6 +34,8 @@ OWED = [str(pathlib.Path(__file__).resolve().parents[1] / "larv-review"), "scori
TITLE = [str(pathlib.Path(__file__).resolve().parents[1] / "project-config"), "pull-request-title"]
BRANCH = [str(pathlib.Path(__file__).resolve().parents[1] / "project-config"), "branch"]
WAITS = [str(pathlib.Path(__file__).resolve().parents[1] / "project-config"), "wait-for-approval"]
# The settings a fake checkout's answers hold, each under `project-config <setting>` as the tool once read it.
PROJECT_CONFIG = str(pathlib.Path(__file__).resolve().parents[1] / "project-config")
GH_DECISION = ["gh", "pr", "view", "12", "--json", "reviewDecision"]
GH_THREADS = ["gh", "api", "graphql", "-f", f"query={THREADS}", "-F", "owner={owner}", "-F", "repo={repo}", "-F", "number=12"]
BEHIND = ["git", "rev-list", "--count", "HEAD..origin/main"]
@@ -71,6 +74,15 @@ class Checkout:
("git", "rev-parse", "--show-toplevel"): "/checkout\n",
}
def config(self) -> ProjectConfig | Failure:
"""The project's config, from the settings the answers hold under PROJECT_CONFIG; a Failure where one of them is, as where no config names the checkout."""
named = {key[1]: answer for key, answer in self.answers.items() if key[0] == PROJECT_CONFIG}
if failed := next((answer for answer in named.values() if isinstance(answer, Failure)), None):
return failed
texts = {name: str(answer).strip() for name, answer in named.items()}
paths = {name: pathlib.Path(texts[name]) for name in ("plan", "changelog", "comprehension-history") if texts.get(name, "").startswith("/")}
return ProjectConfig("proj", pathlib.Path("/config"), pathlib.Path("/checkout"), paths, wait_for_approval=texts.get("wait-for-approval") == "true", commit_title=texts.get("commit-title", "{summary}"), pull_request_title=texts.get("pull-request-title", "{summary}"), branch=texts.get("branch", "item-{id}"))
def __call__(self, command: list[str]) -> str | Failure:
self.ran.append(command)
if command[0] == ("tea" if self.github else "gh"):
@@ -110,32 +122,32 @@ class Open(unittest.TestCase):
checkout = Checkout(GITHUB, open=argv[0] == "ready")
checkout.answers[tuple(TITLE)] = "PAY-{id} - {summary}\n"
checkout.answers[tuple(BRANCH)] = "feature/PAY-{id}\n"
self.assertNotIsInstance(step(argv, checkout), Failure)
self.assertNotIsInstance(step(argv, checkout, checkout.config), Failure)
checkout.answers[("git", "symbolic-ref", "--short", "HEAD")] = "feature/PAY-7\n"
refused = step(argv, checkout)
refused = step(argv, checkout, checkout.config)
assert isinstance(refused, Failure), refused
self.assertIn("'Release review of 0.3.0' doesn't fit", refused.reason)
def test_github_pushes_and_opens_a_draft_into_the_default_branch(self):
checkout = Checkout(GITHUB, open=False)
opened = step(["open", "ABC-1 - Do it", "The body."], checkout)
opened = step(["open", "ABC-1 - Do it", "The body."], checkout, checkout.config)
self.assertEqual(checkout.acted(), [PUSH, ["gh", "pr", "create", "--draft", "--head", "item-7", "--base", "main", "--title", "ABC-1 - Do it", "--body", "The body."]])
self.assertEqual(opened, "Opened draft pull request #12.")
def test_gitea_opens_a_draft_with_tea(self):
checkout = Checkout(GITEA, open=False)
self.assertEqual(step(["open", "Do it"], checkout), "Opened draft pull request #12.")
self.assertEqual(step(["open", "Do it"], checkout, checkout.config), "Opened draft pull request #12.")
self.assertEqual(checkout.acted(), [PUSH, ["tea", "pulls", "create", "--draft", "--head", "item-7", "--base", "main", "--title", "Do it", "--description", ""]])
def test_an_open_pull_request_is_kept(self):
checkout = Checkout(GITEA, open=True)
self.assertEqual(step(["open", "Do it"], checkout), "Pull request #12 is open already.")
self.assertEqual(step(["open", "Do it"], checkout, checkout.config), "Pull request #12 is open already.")
self.assertEqual(checkout.acted(), [PUSH])
def test_on_the_default_branch_it_refuses_and_pushes_nothing(self):
checkout = Checkout(GITEA, open=False)
checkout.answers[("git", "symbolic-ref", "--short", "HEAD")] = "main\n"
self.assertIsInstance(step(["open", "Do it"], checkout), Failure)
self.assertIsInstance(step(["open", "Do it"], checkout, checkout.config), Failure)
self.assertEqual(checkout.acted(), [])
def test_a_title_that_does_not_fit_the_configs_template_is_refused_before_anything_runs(self):
@@ -143,75 +155,75 @@ class Open(unittest.TestCase):
with self.subTest(argv=argv):
checkout = Checkout(GITHUB, open=argv[0] == "ready")
checkout.answers[tuple(TITLE)] = "PAY-{id} - {summary}\n"
refused = step(argv, checkout)
refused = step(argv, checkout, checkout.config)
assert isinstance(refused, Failure), refused
self.assertIn("`PAY-{id} - {summary}`", refused.reason)
self.assertEqual(checkout.acted(), [])
self.assertNotIsInstance(step([argv[0], "PAY-7 - Do it"], checkout), Failure)
self.assertNotIsInstance(step([argv[0], "PAY-7 - Do it"], checkout, checkout.config), Failure)
checkout.answers[tuple(TITLE)] = Failure("no config names the checkout")
self.assertEqual(step(argv, checkout), Failure("no config names the checkout"))
self.assertEqual(step(argv, checkout, checkout.config), Failure("no config names the checkout"))
checkout.answers[tuple(TITLE)] = "PAY-{id} - {summary}\n"
checkout.answers[tuple(BRANCH)] = Failure("`branch` is 'x', which holds no {id}")
self.assertEqual(step(argv, checkout), Failure("`branch` is 'x', which holds no {id}"))
self.assertEqual(step(argv, checkout, checkout.config), Failure("`branch` is 'x', which holds no {id}"))
untitled = Checkout(GITHUB, open=True)
untitled.answers[tuple(TITLE)] = Failure("no config names the checkout")
self.assertNotIsInstance(step(["ready"], untitled), Failure)
self.assertNotIsInstance(step(["ready"], untitled, untitled.config), Failure)
def test_a_title_of_more_than_one_line_or_a_second_body_is_refused_before_anything_runs(self):
for argv, refusal in ((["open", "Do it\nand more"], "give a title of one line"), (["open", " "], "give a title of one line"), (["open", "Do it", "Body", "More"], USAGE)):
with self.subTest(argv):
checkout = Checkout(GITHUB, open=False)
self.assertEqual(step(argv, checkout), Failure(refusal))
self.assertEqual(step(argv, checkout, checkout.config), Failure(refusal))
self.assertEqual(checkout.ran, [])
def test_a_failed_listing_after_the_create_is_returned(self):
checkout = Checkout(GITHUB, open=False)
checkout.answers[("gh", "pr", "create", "--draft", "--head", "item-7", "--base", "main", "--title", "Do it", "--body", "")] = Failure("gh pr create: done")
self.assertEqual(step(["open", "Do it"], checkout), Failure("gh pr create: done"))
self.assertEqual(step(["open", "Do it"], checkout, checkout.config), Failure("gh pr create: done"))
checkout = Checkout(GITHUB, open=False)
listings = iter(["", Failure("gh pr list: offline")])
original = checkout.__call__
checkout_call = lambda command: next(listings) if command == GH_LIST else original(command)
self.assertEqual(step(["open", "Do it"], checkout_call), Failure("gh pr list: offline"))
self.assertEqual(step(["open", "Do it"], checkout_call, checkout.config), Failure("gh pr list: offline"))
class Ready(unittest.TestCase):
def test_github_marks_it_ready(self):
checkout = Checkout(GITHUB, open=True)
self.assertEqual(step(["ready"], checkout), "Marked pull request #12 ready.")
self.assertEqual(step(["ready"], checkout, checkout.config), "Marked pull request #12 ready.")
self.assertEqual(checkout.acted(), [["gh", "pr", "ready", "12"]])
def test_gitea_marks_it_ready_with_tea(self):
checkout = Checkout(GITEA, open=True)
self.assertEqual(step(["ready"], checkout), "Marked pull request #12 ready.")
self.assertEqual(step(["ready"], checkout, checkout.config), "Marked pull request #12 ready.")
self.assertEqual(checkout.acted(), [["tea", "pulls", "edit", "12", "--ready"]])
def test_github_sets_a_given_title_then_marks_it_ready(self):
checkout = Checkout(GITHUB, open=True)
self.assertEqual(step(["ready", "Ship it"], checkout), "Marked pull request #12 ready, titled “Ship it”.")
self.assertEqual(step(["ready", "Ship it"], checkout, checkout.config), "Marked pull request #12 ready, titled “Ship it”.")
self.assertEqual(checkout.acted(), [["gh", "pr", "edit", "12", "--title", "Ship it"], ["gh", "pr", "ready", "12"]])
def test_gitea_sets_a_given_title_in_the_call_that_marks_it_ready(self):
checkout = Checkout(GITEA, open=True)
self.assertEqual(step(["ready", "Ship it"], checkout), "Marked pull request #12 ready, titled “Ship it”.")
self.assertEqual(step(["ready", "Ship it"], checkout, checkout.config), "Marked pull request #12 ready, titled “Ship it”.")
self.assertEqual(checkout.acted(), [["tea", "pulls", "edit", "12", "--title", "Ship it", "--ready"]])
def test_a_title_of_more_than_one_line_or_none_is_refused_before_anything_runs(self):
for argv, refusal in ((["ready", "Ship\nit"], "give a title of one line"), (["ready", " "], "give a title of one line"), (["ready", "Ship it", "twice"], USAGE)):
with self.subTest(argv=argv):
checkout = Checkout(GITHUB, open=True)
self.assertEqual(step(argv, checkout), Failure(refusal))
self.assertEqual(step(argv, checkout, checkout.config), Failure(refusal))
self.assertEqual(checkout.ran, [])
def test_a_failed_title_edit_on_github_leaves_it_a_draft(self):
checkout = Checkout(GITHUB, open=True)
checkout.answers[("gh", "pr", "edit", "12", "--title", "Ship it")] = Failure("gh pr edit: denied")
self.assertEqual(step(["ready", "Ship it"], checkout), Failure("gh pr edit: denied"))
self.assertEqual(step(["ready", "Ship it"], checkout, checkout.config), Failure("gh pr edit: denied"))
self.assertNotIn(["gh", "pr", "ready", "12"], checkout.ran)
def test_without_an_open_pull_request_at_the_head_it_fails_naming_the_branch(self):
checkout = Checkout(GITHUB, open=False)
ready = step(["ready"], checkout)
ready = step(["ready"], checkout, checkout.config)
self.assertIsInstance(ready, Failure)
self.assertIn("item-7", ready.reason)
self.assertEqual(checkout.acted(), [])
@@ -219,10 +231,10 @@ class Ready(unittest.TestCase):
def test_a_failed_ready_or_git_call_is_returned(self):
checkout = Checkout(GITEA, open=True)
checkout.answers[("tea", "pulls", "edit", "12", "--ready")] = Failure("tea pulls edit: denied")
self.assertEqual(step(["ready"], checkout), Failure("tea pulls edit: denied"))
self.assertEqual(step(["ready"], checkout, checkout.config), Failure("tea pulls edit: denied"))
checkout = Checkout(GITEA, open=True)
checkout.answers[("git", "symbolic-ref", "--short", "HEAD")] = Failure("git symbolic-ref: HEAD is detached")
self.assertEqual(step(["ready"], checkout), Failure("git symbolic-ref: HEAD is detached"))
self.assertEqual(step(["ready"], checkout, checkout.config), Failure("git symbolic-ref: HEAD is detached"))
self.assertEqual(checkout.acted(), [])
@@ -249,34 +261,34 @@ class Sync(unittest.TestCase):
def test_a_branch_behind_the_default_branch_merges_it(self):
checkout = self.checkout(behind=3)
self.assertEqual(step(["sync"], checkout), "Merged origin/main into item-7.")
self.assertEqual(step(["sync"], checkout, checkout.config), "Merged origin/main into item-7.")
self.assertEqual(checkout.acted(), [FETCH, MERGE])
def test_a_branch_that_holds_the_default_branch_merges_nothing(self):
checkout = self.checkout(behind=0)
self.assertEqual(step(["sync"], checkout), "item-7 already holds origin/main.")
self.assertEqual(step(["sync"], checkout, checkout.config), "item-7 already holds origin/main.")
self.assertEqual(checkout.acted(), [FETCH])
def test_a_worktree_with_a_todo_md_runs_the_rank_check_after_the_merge(self):
checkout = self.checkout(behind=1, todo=True)
self.assertEqual(step(["sync"], checkout), f"Merged origin/main into item-7.\nrank_todo.py --check todo.md passed.")
self.assertEqual(step(["sync"], checkout, checkout.config), f"Merged origin/main into item-7.\nrank_todo.py --check todo.md passed.")
self.assertEqual(checkout.acted(), [FETCH, MERGE, [RANK, "--check", self.todo]])
def test_a_checkout_no_config_names_fails_naming_what_it_did(self):
checkout = self.checkout(behind=0, todo=True)
checkout.answers[PLAN] = Failure("no config names the checkout")
self.assertEqual(step(["sync"], checkout), Failure("item-7 already holds origin/main, but the plan to check cannot be found: no config names the checkout"))
self.assertEqual(step(["sync"], checkout, checkout.config), Failure("item-7 already holds origin/main, but the plan to check cannot be found: no config names the checkout"))
def test_a_failing_rank_check_fails_naming_what_it_did(self):
checkout = self.checkout(behind=0, todo=True)
checkout.answers[(RANK, "--check", self.todo)] = Failure("rank_todo.py --check: item 3 is out of order")
self.assertEqual(step(["sync"], checkout), Failure("item-7 already holds origin/main, but rank_todo.py --check todo.md failed: rank_todo.py --check: item 3 is out of order"))
self.assertEqual(step(["sync"], checkout, checkout.config), Failure("item-7 already holds origin/main, but rank_todo.py --check todo.md failed: rank_todo.py --check: item 3 is out of order"))
def test_a_conflict_leaves_the_merge_in_progress_and_names_the_conflicted_files(self):
checkout = self.checkout(behind=2, todo=True)
checkout.answers[tuple(MERGE)] = Failure("git merge --quiet: CONFLICT")
checkout.answers[CONFLICTED] = "todo.md\nREADME.md\n"
self.assertEqual(step(["sync"], checkout), Failure("merging origin/main into item-7 conflicts in todo.md, README.md; the merge stays in progress: resolve them and commit"))
self.assertEqual(step(["sync"], checkout, checkout.config), Failure("merging origin/main into item-7 conflicts in todo.md, README.md; the merge stays in progress: resolve them and commit"))
self.assertNotIn([RANK, "--check", self.todo], checkout.ran)
self.assertNotIn(["git", "merge", "--abort"], checkout.ran)
@@ -284,18 +296,18 @@ class Sync(unittest.TestCase):
checkout = self.checkout(behind=2)
checkout.answers[tuple(MERGE)] = Failure("git merge --quiet: untracked files would be overwritten")
checkout.answers[CONFLICTED] = ""
self.assertEqual(step(["sync"], checkout), Failure("git merge --quiet: untracked files would be overwritten"))
self.assertEqual(step(["sync"], checkout, checkout.config), Failure("git merge --quiet: untracked files would be overwritten"))
def test_on_the_default_branch_it_refuses_and_fetches_nothing(self):
checkout = self.checkout(behind=0)
checkout.answers[("git", "symbolic-ref", "--short", "HEAD")] = "main\n"
self.assertEqual(step(["sync"], checkout), Failure("main is origin's default branch; sync the chunk's branch"))
self.assertEqual(step(["sync"], checkout, checkout.config), Failure("main is origin's default branch; sync the chunk's branch"))
self.assertNotIn(FETCH, checkout.ran)
def test_a_failed_fetch_is_returned(self):
checkout = self.checkout(behind=0)
checkout.answers[tuple(FETCH)] = Failure("git fetch --quiet: could not read from remote")
self.assertEqual(step(["sync"], checkout), Failure("git fetch --quiet: could not read from remote"))
self.assertEqual(step(["sync"], checkout, checkout.config), Failure("git fetch --quiet: could not read from remote"))
def changes(checkout: Checkout) -> list[list[str]]:
@@ -306,31 +318,31 @@ def changes(checkout: Checkout) -> list[list[str]]:
class Merge(unittest.TestCase):
def test_the_gate_passed_flag_it_no_longer_takes_is_refused_before_anything_runs(self):
checkout = Checkout(GITHUB, open=True)
self.assertIsInstance(step(["merge", "--gate-passed"], checkout), Failure)
self.assertIsInstance(step(["merge", "--gate-passed"], checkout, checkout.config), Failure)
self.assertEqual(checkout.ran, [])
def test_an_option_given_as_a_title_runs_nothing(self):
for argv in (["ready", "--help"], ["open", "-h"]):
checkout = Checkout(GITHUB, open=True)
self.assertEqual(step(argv, checkout), Failure(USAGE))
self.assertEqual(step(argv, checkout, checkout.config), Failure(USAGE))
self.assertEqual(checkout.ran, [])
def test_github_waits_for_the_checks_before_merging(self):
checkout = Checkout(GITHUB, open=True)
self.assertEqual(step(["merge"], checkout), "Merged pull request #12 (merge).")
self.assertEqual(step(["merge"], checkout, checkout.config), "Merged pull request #12 (merge).")
self.assertEqual(checkout.ran[-2:], [GH_CHECKS, ["gh", "pr", "merge", "12", "--merge", "--match-head-commit", HEAD]])
def test_a_failed_check_on_github_leaves_it_unmerged(self):
checkout = Checkout(GITHUB, open=True)
checkout.answers[tuple(GH_CHECKS)] = Failure("gh pr checks 12: CI / tests\tfail")
self.assertEqual(step(["merge"], checkout), Failure("gh pr checks 12: CI / tests\tfail"))
self.assertEqual(step(["merge"], checkout, checkout.config), Failure("gh pr checks 12: CI / tests\tfail"))
self.assertEqual(changes(checkout), [])
def test_github_waits_a_minute_for_checks_to_report_before_taking_none_as_passed(self):
checkout = Checkout(GITHUB, open=True)
checkout.answers[tuple(GH_CHECKS)] = Failure("no checks reported on the 'item-7' branch")
slept: list[float] = []
self.assertEqual(merged(checkout, slept.append), "Merged pull request #12 (merge).")
self.assertEqual(merged(checkout, checkout.config, slept.append), "Merged pull request #12 (merge).")
self.assertEqual(sum(slept), 60)
self.assertEqual(checkout.ran.count(GH_CHECKS), 7)
@@ -338,7 +350,7 @@ class Merge(unittest.TestCase):
checkout = Checkout(GITEA, open=True)
checkout.statuses = [json.dumps({"total_count": 0, "state": "pending", "statuses": []})] * 7
slept: list[float] = []
self.assertEqual(merged(checkout, slept.append), "Merged pull request #12 (merge).")
self.assertEqual(merged(checkout, checkout.config, slept.append), "Merged pull request #12 (merge).")
self.assertEqual(sum(slept), 60)
def requiring_approval(self, origin: str = GITHUB, *decisions: str) -> Checkout:
@@ -351,24 +363,24 @@ class Merge(unittest.TestCase):
def test_a_project_without_wait_for_approval_never_reads_the_review_decision(self):
checkout = Checkout(GITHUB, open=True)
checkout.decisions = ["REVIEW_REQUIRED"]
self.assertEqual(step(["merge"], checkout), "Merged pull request #12 (merge).")
self.assertEqual(step(["merge"], checkout, checkout.config), "Merged pull request #12 (merge).")
self.assertNotIn(GH_DECISION, checkout.ran)
def test_an_approved_pull_request_merges_after_the_checks_and_the_approval(self):
checkout = self.requiring_approval()
self.assertEqual(step(["merge"], checkout), "Merged pull request #12 (merge).")
self.assertEqual(step(["merge"], checkout, checkout.config), "Merged pull request #12 (merge).")
self.assertEqual(checkout.ran[-4:], [GH_CHECKS, GH_DECISION, GH_THREADS, ["gh", "pr", "merge", "12", "--merge", "--match-head-commit", HEAD]])
def test_it_waits_a_minute_at_a_time_while_the_branch_protection_still_wants_a_review(self):
checkout = self.requiring_approval(GITHUB, "REVIEW_REQUIRED", "REVIEW_REQUIRED", "APPROVED")
slept: list[float] = []
self.assertEqual(merged(checkout, slept.append), "Merged pull request #12 (merge).")
self.assertEqual(merged(checkout, checkout.config, slept.append), "Merged pull request #12 (merge).")
self.assertEqual(slept, [60])
def test_an_approval_that_never_comes_leaves_it_unmerged_after_90_minutes(self):
checkout = self.requiring_approval(GITHUB, "REVIEW_REQUIRED")
slept: list[float] = []
failed = merged(checkout, slept.append)
failed = merged(checkout, checkout.config, slept.append)
self.assertIsInstance(failed, Failure)
self.assertIn("90 minutes", failed.reason)
self.assertEqual(sum(slept), 90 * 60)
@@ -377,7 +389,7 @@ class Merge(unittest.TestCase):
def test_an_approval_that_comes_in_the_last_minute_still_merges(self):
checkout = self.requiring_approval(GITHUB, *["REVIEW_REQUIRED"] * 91, "APPROVED")
slept: list[float] = []
self.assertEqual(merged(checkout, slept.append), "Merged pull request #12 (merge).")
self.assertEqual(merged(checkout, checkout.config, slept.append), "Merged pull request #12 (merge).")
self.assertEqual(sum(slept), 90 * 60)
def test_a_review_decision_it_cannot_read_or_does_not_know_leaves_it_unmerged(self):
@@ -385,13 +397,13 @@ class Merge(unittest.TestCase):
with self.subTest(answer):
checkout = self.requiring_approval()
checkout.unreadable = answer
self.assertIsInstance(step(["merge"], checkout), Failure)
self.assertIsInstance(step(["merge"], checkout, checkout.config), Failure)
self.assertEqual(changes(checkout), [])
def test_requested_changes_leave_it_unmerged_without_waiting(self):
checkout = self.requiring_approval(GITHUB, "CHANGES_REQUESTED")
slept: list[float] = []
failed = merged(checkout, slept.append)
failed = merged(checkout, checkout.config, slept.append)
self.assertIsInstance(failed, Failure)
self.assertIn("requested changes", failed.reason)
self.assertEqual((slept, changes(checkout)), ([], []))
@@ -400,25 +412,23 @@ class Merge(unittest.TestCase):
for decision in ("", None):
with self.subTest(decision):
checkout = self.requiring_approval(GITHUB, decision)
failed = step(["merge"], checkout)
failed = step(["merge"], checkout, checkout.config)
self.assertIsInstance(failed, Failure)
self.assertIn("requires no review", failed.reason)
self.assertEqual(changes(checkout), [])
def test_gitea_with_wait_for_approval_leaves_it_unmerged_since_chunk_pr_reads_approvals_on_github_only(self):
checkout = self.requiring_approval(GITEA)
failed = step(["merge"], checkout)
failed = step(["merge"], checkout, checkout.config)
self.assertIsInstance(failed, Failure)
self.assertIn("GitHub", failed.reason)
self.assertEqual(changes(checkout), [])
def test_a_config_it_cannot_read_or_that_prints_neither_true_nor_false_leaves_it_unmerged(self):
for answer in (Failure("no config names the checkout"), "maybe\n", ""):
with self.subTest(answer):
checkout = Checkout(GITHUB, open=True)
checkout.answers[tuple(WAITS)] = answer
self.assertIsInstance(step(["merge"], checkout), Failure)
self.assertEqual(changes(checkout), [])
def test_a_config_it_cannot_read_leaves_it_unmerged(self):
checkout = Checkout(GITHUB, open=True)
checkout.answers[tuple(WAITS)] = Failure("no config names the checkout")
self.assertEqual(step(["merge"], checkout, checkout.config), Failure("no config names the checkout"))
self.assertEqual(changes(checkout), [])
def protected(self, *reads: list[tuple[str, str]]) -> Checkout:
"""A Gitea Checkout whose main requires a check matching CI / tests*, its status at HEAD holding each of reads in turn."""
@@ -434,32 +444,32 @@ class Merge(unittest.TestCase):
def test_gitea_waits_until_the_required_check_reports_and_passes_then_merges(self):
checkout = self.protected([], [("CI / tests (pull_request)", "pending")], [("CI / tests (pull_request)", "success")])
slept: list[float] = []
self.assertEqual(merged(checkout, slept.append), "Merged pull request #12 (merge).")
self.assertEqual(merged(checkout, checkout.config, slept.append), "Merged pull request #12 (merge).")
self.assertEqual(len(slept), 2)
self.assertEqual(checkout.ran.count(TEA_STATUS), 3)
def test_a_failed_check_on_gitea_leaves_it_unmerged(self):
checkout = self.protected([("CI / tests (pull_request)", "pending")], [("CI / tests (pull_request)", "failure")])
self.assertIsInstance(merged(checkout, lambda _: None), Failure)
self.assertIsInstance(merged(checkout, checkout.config, lambda _: None), Failure)
self.assertEqual(changes(checkout), [])
def test_a_branch_protection_it_cannot_read_leaves_it_unmerged(self):
checkout = Checkout(GITEA, open=True)
checkout.answers[tuple(TEA_BRANCH)] = Failure("tea api: 500")
self.assertEqual(merged(checkout, self.fail), Failure("tea api: 500"))
self.assertEqual(merged(checkout, checkout.config, self.fail), Failure("tea api: 500"))
self.assertNotIn(TEA_STATUS, checkout.ran)
self.assertEqual(changes(checkout), [])
def test_an_unknown_default_branch_leaves_it_unmerged_reading_no_checks(self):
checkout = Checkout(GITEA, open=True)
checkout.answers[("git", "symbolic-ref", "--short", "refs/remotes/origin/HEAD")] = Failure("no such ref")
self.assertEqual(merged(checkout, self.fail), Failure("origin records no default branch; set it with `git remote set-head origin --auto`: no such ref"))
self.assertEqual(merged(checkout, checkout.config, self.fail), Failure("origin records no default branch; set it with `git remote set-head origin --auto`: no such ref"))
self.assertNotIn(TEA_STATUS, checkout.ran)
self.assertEqual(changes(checkout), [])
def test_gitea_checks_that_never_pass_leave_it_unmerged(self):
checkout = self.protected(*[[("CI / tests (pull_request)", "pending")]] * 1000)
failed = merged(checkout, lambda _: None)
failed = merged(checkout, checkout.config, lambda _: None)
self.assertIsInstance(failed, Failure)
self.assertIn("gave up on pull request 12", failed.reason)
self.assertEqual(changes(checkout), [])
@@ -469,43 +479,43 @@ class Merge(unittest.TestCase):
with self.subTest(origin=origin):
checkout = Checkout(origin, open=True)
checkout.answers[tuple(OWED)] = Failure("larv-review scoring-run-owed: the chunk owes 2 scoring runs")
self.assertEqual(step(["merge"], checkout), Failure("larv-review scoring-run-owed: the chunk owes 2 scoring runs"))
self.assertEqual(step(["merge"], checkout, checkout.config), Failure("larv-review scoring-run-owed: the chunk owes 2 scoring runs"))
self.assertEqual(changes(checkout), [])
def test_github_merges_with_a_merge_commit_pinned_to_the_head(self):
checkout = Checkout(GITHUB, open=True, allowed=("squashMergeAllowed", "mergeCommitAllowed"))
self.assertEqual(step(["merge"], checkout), "Merged pull request #12 (merge).")
self.assertEqual(step(["merge"], checkout, checkout.config), "Merged pull request #12 (merge).")
self.assertEqual(changes(checkout), [["gh", "pr", "merge", "12", "--merge", "--match-head-commit", HEAD]])
def test_github_without_merge_commits_rebases(self):
checkout = Checkout(GITHUB, open=True, allowed=("squashMergeAllowed", "rebaseMergeAllowed"))
step(["merge"], checkout)
step(["merge"], checkout, checkout.config)
self.assertEqual(changes(checkout), [["gh", "pr", "merge", "12", "--rebase", "--match-head-commit", HEAD]])
def test_gitea_merges_fast_forward_only_where_only_that_and_squash_are_allowed(self):
checkout = Checkout(GITEA, open=True, allowed=("allow_squash_merge", "allow_fast_forward_only_merge"))
self.assertEqual(step(["merge"], checkout), "Merged pull request #12 (fast-forward-only).")
self.assertEqual(step(["merge"], checkout, checkout.config), "Merged pull request #12 (fast-forward-only).")
self.assertEqual(changes(checkout), [["tea", "api", "--method", "POST", "--field", "Do=fast-forward-only", "--field", f"head_commit_id={HEAD}", "repos/{owner}/{repo}/pulls/12/merge"]])
def test_a_repository_allowing_no_known_method_is_refused_unmerged(self):
checkout = Checkout(GITEA, open=True, allowed=("allow_manual_merge",))
self.assertIsInstance(step(["merge"], checkout), Failure)
self.assertIsInstance(step(["merge"], checkout, checkout.config), Failure)
self.assertEqual(changes(checkout), [])
def test_a_forge_failure_is_returned(self):
checkout = Checkout(GITHUB, open=True)
checkout.answers[("gh", "pr", "merge", "12", "--merge", "--match-head-commit", HEAD)] = Failure("gh pr merge: head moved")
self.assertEqual(step(["merge"], checkout), Failure("gh pr merge: head moved"))
self.assertEqual(step(["merge"], checkout, checkout.config), Failure("gh pr merge: head moved"))
checkout = Checkout(GITHUB, open=True)
checkout.answers[tuple(GH_SETTINGS)] = "not json"
self.assertIsInstance(step(["merge"], checkout), Failure)
self.assertIsInstance(step(["merge"], checkout, checkout.config), Failure)
def test_a_failed_settings_read_is_returned_unmerged(self):
for origin, settings in ((GITHUB, GH_SETTINGS), (GITEA, TEA_SETTINGS)):
with self.subTest(origin):
checkout = Checkout(origin, open=True)
checkout.answers[tuple(settings)] = Failure("settings: denied")
self.assertEqual(step(["merge"], checkout), Failure("settings: denied"))
self.assertEqual(step(["merge"], checkout, checkout.config), Failure("settings: denied"))
self.assertEqual(changes(checkout), [])
@@ -568,12 +578,12 @@ class MergeQueue(unittest.TestCase):
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(step(["merge", *flags], checkout, checkout.config), Failure(USAGE))
self.assertEqual(checkout.ran, [])
def test_a_branch_behind_the_default_branch_merges_it_in_and_pushes_before_the_checks(self):
checkout = self.moved(Checkout(GITHUB, open=True))
self.assertEqual(merged(checkout.__call__), "Merged pull request #12 (merge).")
self.assertEqual(merged(checkout.__call__, checkout.config), "Merged pull request #12 (merge).")
self.assertEqual(changes(checkout), [MERGE, self.PUSHED, ["gh", "pr", "merge", "12", "--merge", "--match-head-commit", "decaf"]])
self.assertLess(checkout.ran.index(self.PUSHED), checkout.ran.index(GH_CHECKS))
@@ -581,7 +591,7 @@ class MergeQueue(unittest.TestCase):
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__)
failed = merged(checkout.__call__, checkout.config)
self.assertIsInstance(failed, Failure)
self.assertIn("conflicts in bin/tool.py; the merge stays in progress: resolve them, commit, push, and run chunk-pr merge again", failed.reason)
self.assertEqual((changes(checkout), MERGE in checkout.ran), ([], True))
@@ -590,7 +600,7 @@ class MergeQueue(unittest.TestCase):
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(merged(checkout.__call__, checkout.config, finishes=[["7", "--changelog", "Exports keep their order."]]), "Merged pull request #12 (merge).")
self.assertEqual(changes(checkout)[:1], [[self.TODO_ITEM, "finish", "7", "--changelog", "Exports keep their order."]])
self.assertEqual(changes(checkout)[-4:], [
["git", "-C", folder, "add", "--", *files],
@@ -602,12 +612,12 @@ class MergeQueue(unittest.TestCase):
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(step(["merge", "--finish", "7", "--no-changelog", "--finish", "8", "--finish", "9", "--changelog", "Exports keep their order."], checkout.__call__, checkout.config), "Merged pull request #12 (merge).")
self.assertEqual([command[1:] for command in checkout.ran if command[:2] == [self.TODO_ITEM, "finish"]], [["finish", "7", "--no-changelog"], ["finish", "8"], ["finish", "9", "--changelog", "Exports keep their order."]])
def test_an_item_the_plan_no_longer_holds_is_named_on_the_last_line_and_what_an_earlier_run_left_uncommitted_is_committed(self):
checkout, folder = self.with_plan(Checkout(GITHUB, open=True), held=False)
self.assertEqual(merged(checkout.__call__, 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.assertEqual(merged(checkout.__call__, checkout.config, finishes=[["7"]]), "Merged pull request #12 (merge). The plan held no item 7 when merge began, so merge left the plan as it was there.")
self.assertNotIn([self.TODO_ITEM, "finish", "7"], checkout.ran)
self.assertEqual([command[3] for command in changes(checkout)[:-1]], ["add", "commit", "origin"])
self.assertEqual(changes(checkout)[-1], ["gh", "pr", "merge", "12", "--merge", "--match-head-commit", "f00d"])
@@ -615,7 +625,7 @@ class MergeQueue(unittest.TestCase):
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"]])))
self.assertIn("The plan held no item 7, 8 when merge began", str(merged(checkout.__call__, checkout.config, finishes=[["7"], ["8"]])))
def test_a_plan_that_turns_unreadable_inside_the_turn_leaves_it_unmerged(self):
checkout, _ = self.with_plan(Checkout(GITHUB, open=True))
@@ -623,7 +633,7 @@ class MergeQueue(unittest.TestCase):
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.assertEqual(merged(run_whose_second_show_fails, checkout.config, finishes=[["7"]]), Failure("todo-item show 7: unreadable"))
self.assertNotIn([self.TODO_ITEM, "finish", "7"], checkout.ran)
def test_a_finish_that_changes_no_file_commits_and_pushes_nothing(self):
@@ -634,13 +644,13 @@ class MergeQueue(unittest.TestCase):
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(merged(checkout.__call__, checkout.config, finishes=[["7", "--no-changelog"]]), "Merged pull request #12 (merge).")
self.assertEqual(changes(checkout), [[self.TODO_ITEM, "finish", "7", "--no-changelog"], ["gh", "pr", "merge", "12", "--merge", "--match-head-commit", HEAD]])
def test_a_branch_outside_the_branch_template_titles_the_finish_with_the_summary_alone(self):
checkout, folder = self.with_plan(Checkout(GITHUB, open=True))
checkout.answers[tuple(BRANCH)] = "feature/PAY-{id}\n"
merged(checkout.__call__, finishes=[["7"]])
merged(checkout.__call__, checkout.config, finishes=[["7"]])
self.assertIn("Finish item 7 in the plan", [command[6] for command in checkout.ran if command[3:4] == ["commit"]])
def test_a_plan_it_cannot_read_or_an_item_it_cannot_finish_leaves_it_unmerged(self):
@@ -648,35 +658,35 @@ class MergeQueue(unittest.TestCase):
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.assertEqual(merged(checkout.__call__, checkout.config, finishes=[["7"]]), Failure(f"todo-item {failing} 7: no config names the checkout"))
self.assertNotIn(self.PUSHED, checkout.ran)
def test_a_step_of_the_turn_that_fails_leaves_it_unmerged_with_that_failure(self):
_, folder = self.with_plan(Checkout(GITHUB, open=True))
for failing in (FETCH, BEHIND, COMMON, self.PUSHED, ["git", "-C", "<plan>", "rev-parse", "--show-toplevel"], ["git", "-C", "<plan>", "add"], ["git", "-C", "<plan>", "commit"], [self.CONFIG, "comprehension-history"]):
for failing in (FETCH, BEHIND, COMMON, self.PUSHED, ["git", "-C", "<plan>", "rev-parse", "--show-toplevel"], ["git", "-C", "<plan>", "add"], ["git", "-C", "<plan>", "commit"]):
with self.subTest(failing):
checkout, folder = self.with_plan(Checkout(GITHUB, open=True))
run = checkout.__call__
def failing_run(command: list[str]) -> str | Failure:
asked = ["<plan>" if part == folder else part for part in command]
return Failure("that step failed") if tuple(asked[:len(failing)]) == tuple(failing) else run(command)
self.assertEqual(merged(failing_run, finishes=[["7"]]), Failure("that step failed"))
self.assertEqual(merged(failing_run, checkout.config, finishes=[["7"]]), Failure("that step failed"))
self.assertNotIn("merge", [command[2] for command in checkout.ran if command[0] == "gh"])
def test_a_finish_that_fails_after_the_default_branch_was_merged_in_still_pushes_the_branch(self):
checkout, _ = self.with_plan(self.moved(Checkout(GITHUB, open=True)))
checkout.answers[(self.TODO_ITEM, "finish", "7")] = Failure("todo-item finish 7: a decision cites item 7")
self.assertEqual(merged(checkout.__call__, finishes=[["7"]]), Failure("todo-item finish 7: a decision cites item 7"))
self.assertEqual(merged(checkout.__call__, checkout.config, finishes=[["7"]]), Failure("todo-item finish 7: a decision cites item 7"))
self.assertEqual(changes(checkout), [MERGE, self.PUSHED])
def test_the_scoring_run_is_asked_for_once_the_finish_is_committed_and_one_owed_leaves_it_unmerged(self):
checkout, _ = self.with_plan(Checkout(GITHUB, open=True))
commit = lambda: next(index for index, command in enumerate(checkout.ran) if command[3:4] == ["commit"])
self.assertEqual(merged(checkout.__call__, finishes=[["7"]]), "Merged pull request #12 (merge).")
self.assertEqual(merged(checkout.__call__, checkout.config, finishes=[["7"]]), "Merged pull request #12 (merge).")
self.assertLess(commit(), checkout.ran.index(OWED))
checkout, _ = self.with_plan(Checkout(GITHUB, open=True))
checkout.answers[tuple(OWED)] = Failure("the chunk owes 1 scoring run")
self.assertEqual(merged(checkout.__call__, finishes=[["7"]]), Failure("the chunk owes 1 scoring run"))
self.assertEqual(merged(checkout.__call__, checkout.config, finishes=[["7"]]), Failure("the chunk owes 1 scoring run"))
self.assertEqual(changes(checkout)[-1], self.PUSHED)
def test_a_merge_holds_the_queue_through_the_checks_and_frees_it_while_it_waits_for_an_approval(self):
@@ -688,7 +698,7 @@ class MergeQueue(unittest.TestCase):
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(merged(run, checkout.config, lambda seconds: free.setdefault("waiting for the approval", queue_is_free())), "Merged pull request #12 (merge).")
self.assertEqual(free, {"during the checks": False, "waiting for the approval": True})
self.assertEqual(checkout.ran.count(FETCH), 2)
@@ -698,19 +708,19 @@ class MergeQueue(unittest.TestCase):
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)
failed = merged(checkout, checkout.config, slept.append)
self.assertIsInstance(failed, Failure)
self.assertIn("waits for an answer, in bin/asked.py;", failed.reason)
self.assertEqual((slept, changes(checkout)), ([], []))
checkout.threads = checkout.threads[1:]
checkout.decisions = ["REVIEW_REQUIRED", "REVIEW_REQUIRED", "APPROVED"]
self.assertEqual(merged(checkout, slept.append), "Merged pull request #12 (merge).")
self.assertEqual(merged(checkout, checkout.config, slept.append), "Merged pull request #12 (merge).")
def test_an_approved_pull_request_with_a_comment_that_waits_for_an_answer_stays_unmerged(self):
checkout = Checkout(GITHUB, open=True)
checkout.answers[tuple(WAITS)] = "true\n"
checkout.threads = [self.thread("bin/asked.py", "reviewer")]
failed = merged(checkout)
failed = merged(checkout, checkout.config)
self.assertIsInstance(failed, Failure)
self.assertIn("waits for an answer, in bin/asked.py;", failed.reason)
self.assertEqual(changes(checkout), [])
@@ -721,7 +731,7 @@ class MergeQueue(unittest.TestCase):
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(merged(checkout, checkout.config, lambda seconds: None), Failure(reason))
self.assertEqual(changes(checkout), [])
def test_a_default_branch_that_moved_after_the_branchs_last_paired_ruling_stops_for_a_new_one(self):
@@ -736,7 +746,7 @@ class MergeQueue(unittest.TestCase):
with self.subTest(name):
checkout = Checkout(GITHUB, open=True)
checkout.answers.update({(self.CONFIG, "comprehension-history"): f"{history}\n", **answers})
done = merged(checkout.__call__)
done = merged(checkout.__call__, checkout.config)
self.assertEqual(isinstance(done, Failure) and "run the paired ruling again" in done.reason, stops, done)
self.assertEqual(changes(checkout), [] if stops else [["gh", "pr", "merge", "12", "--merge", "--match-head-commit", HEAD]])
@@ -744,14 +754,14 @@ class MergeQueue(unittest.TestCase):
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.assertEqual(merged(checkout.__call__, checkout.config), "Merged pull request #12 (merge).")
self.assertNotIn("log", [command[1] for command in checkout.ran])
for failing in (ruled, ("git", "rev-list", "--count", "bead..origin/main"), ("git", "rev-parse", "--show-toplevel")):
with self.subTest(failing):
checkout = Checkout(GITHUB, open=True)
checkout.answers.update({(self.CONFIG, "comprehension-history"): "/checkout/history.md\n", ruled: "bead\n"})
checkout.answers[failing] = Failure("git failed")
self.assertEqual(merged(checkout.__call__), Failure("git failed"))
self.assertEqual(merged(checkout.__call__, checkout.config), Failure("git failed"))
def test_a_turn_keeps_every_other_merge_out_until_it_ends_even_by_an_error(self):
with self.assertRaises(ValueError):
@@ -766,7 +776,7 @@ class MergeQueue(unittest.TestCase):
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)
failed = merged(checkout, checkout.config, slept.append)
self.assertEqual(failed, Failure("the merge queue stayed held for 30 minutes, last by pull request #31, so this one took no turn; run chunk-pr merge again"))
self.assertEqual((sum(slept), set(slept), changes(checkout)), (30 * 60, {10}, []))
@@ -774,12 +784,12 @@ class MergeQueue(unittest.TestCase):
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).")
self.assertEqual(merged(checkout, checkout.config, lambda seconds: holder.close()), "Merged pull request #12 (merge).")
def test_a_queue_it_cannot_open_leaves_it_unmerged(self):
checkout = Checkout(GITHUB, open=True)
checkout.answers[tuple(COMMON)] = "/nonexistent/folder\n"
self.assertEqual(merged(checkout), Failure("cannot take a turn in the merge queue, /nonexistent/folder/chunk-pr-merge-queue: No such file or directory"))
self.assertEqual(merged(checkout, checkout.config), Failure("cannot take a turn in the merge queue, /nonexistent/folder/chunk-pr-merge-queue: No such file or directory"))
self.assertEqual(checkout.acted(), [])
+1 -57
View File
@@ -1,68 +1,12 @@
"""The pure choices the preflight's steps act on."""
import pathlib
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 release_plan.todo_table import NoItemsTable
from plan_store import stores as plan_stores
from release_plan.release import version
from chunk_preflight.gathered import Forge
# The command each forge's CLI lists pull requests with; pulls_command adds the flags that pick their rows and fields.
PULLS_LIST: dict[Forge, tuple[str, ...]] = {"gh": ("gh", "pr", "list"), "tea": ("tea", "pulls", "list")}
def cut_name(cut: LastCut) -> str | None:
"""How the preflight names the last cut: the tag, or the version under its dated CHANGELOG.md heading; None where nothing is cut."""
if cut.tag is not None:
return None if isinstance(cut.tag, Failure) else cut.tag
headed = dated_cut(cut.tag, cut.changelog)
return None if headed is None else f"{version(headed)} (dated in CHANGELOG.md)"
def plan_name(default: str, outside: str | None) -> str:
"""How the preflight names the plan it read: the default branch's todo.md, or the file or Jira epic, where the project's config puts it outside the checkout."""
return outside if outside else f"{default}'s todo.md"
def planned(todo: plan_stores.Plan | Failure, cut: LastCut, default: str, branch: str, outside: str | None = None, 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.")
if isinstance(todo, Failure):
return NoItem(f"{where} cannot be read: {todo.reason}.")
found = todo.items
if isinstance(cut.tag, Failure):
return NoItem(f"{default}'s tags cannot be read: {cut.tag.reason}. So which release is next cannot be told. Find the next release yourself.")
named = cut_name(cut)
last_cut = f"the last cut, {named}" if named is not None else "the start, since no release is cut yet"
pick = chunk_item(found, cut)
if isinstance(pick, Cut):
return NoItem(f"{where} files items under release {version(pick.release)}, which is not after {last_cut}; ask the human which release they belong to.")
if isinstance(pick, Unknown):
return NoItem(f"{where} may hold no item for the next release after {last_cut}: todo.md's texts since then, or the count of changes since then, cannot be read. Find the next release yourself.")
if isinstance(pick, ReadyToCut | ReviewDue | Unplanned):
upcoming = f"release {version(pick.release)}, the next after {last_cut}" if pick.release else f"the next release after {last_cut}"
if isinstance(pick, ReviewDue):
return NoItem(f"{where} holds no item for {upcoming}, and changes are unreleased, so that release's release review is due: no commit titled `Release review of <release>` has landed {'since the cut' if named is not None else 'yet'}. This chunk is that review, as `~/.claude/skills/larv-review/SKILL.md` → \"Release review\" says; once it merges and the release holds no item, the release is ready to cut.")
if isinstance(pick, ReadyToCut):
return NoItem(f"{where} holds no item for {upcoming}, and changes are unreleased, and its release review has landed, so that release is finished and ready to cut. The working loop stops here. If todo.md renamed that release instead, add `- <old release> renamed to <new release>` to todo.md's `## Renamed` section.")
return NoItem(f"{where} holds no item for {upcoming}, and no change is unreleased, so that release is to be planned first.")
first = pick.item
if first is None:
return NoItem(f"every item of release {version(pick.release)} in {where} waits." if pick.release is not None else f"{where}'s items table holds no item.")
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:
"""The worktree on branch, in what `git worktree list --porcelain` printed; None where none is."""
for block in porcelain.split("\n\n"):
+9 -8
View File
@@ -1,12 +1,13 @@
"""The lines the preflight prints, stated from what it gathered."""
from release_plan.todo_table import bundle_candidates, BUNDLE_MAX_R, Item, ships_alone
from plan.todo_table import bundle_candidates, BUNDLE_MAX_R, Item, ships_alone
from touch_predictions.beside import chunks_beside
from chunk_preflight.choices import cut_name, PULLS_LIST
from release_plan.next_chunk import cut_name, NextChunk, NoItem
from release_plan.release_standing import dated_cut, LastCut, unreleased_entries, UNSEEN_RELEASES
from failure import Failure
from chunk_preflight.gathered import Forge, Gathered, ItemFacts, NamedPath, NoItem, Plan, Ran
from chunk_preflight.gathered import Forge, Gathered, ItemFacts, NamedPath, Ran
from text_files.markdown_text import listed, quoted
from release_plan.release import version
from chunk_preflight.choices import PULLS_LIST
from plan.release import version
# CLAUDE.md → "Working loop" lets up to ten tiny items share a chunk, so a worker never needs more. A release with 24 joinable items would otherwise put about 155 lines of detail in every prompt.
@@ -58,7 +59,7 @@ def item_lines(plan: str, item: ItemFacts) -> list[str]:
]
def carried_lines(plan: Plan) -> list[str]:
def carried_lines(plan: NextChunk) -> list[str]:
"""What the worker does about the items of a release someone cut while it held them."""
over = plan.carried
if over is None:
@@ -67,7 +68,7 @@ def carried_lines(plan: Plan) -> list[str]:
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]:
def joining_details(plan: NextChunk) -> list[str]:
"""The detail of each of the first JOINING_DETAILS items that may join the chunk, in the table's order, and what the worker lacks: an item with no detail, or the items left out."""
joining = bundle_candidates(plan.items, plan.first)
if not joining:
@@ -100,7 +101,7 @@ def open_pulls(stdout: str, forge: Forge, branch: str) -> list[str]:
return [f"#{row[0]} {row[2]}" for row in rows if len(row) == 3 and row[1] == branch]
def bundled(plan: Plan) -> list[str]:
def bundled(plan: NextChunk) -> list[str]:
first, candidates = plan.first, bundle_candidates(plan.items, plan.first)
if ships_alone(first):
return [f"- Item {first.id} has R above {BUNDLE_MAX_R}, so it ships alone."]
@@ -110,7 +111,7 @@ def bundled(plan: Plan) -> list[str]:
return [f'- The items of release {version(first.release)} that may join the chunk of item {first.id}, where `~/.claude/CLAUDE.md` → "Working loop" lets them share it:', *listed]
def beside(plan: Plan) -> list[str]:
def beside(plan: NextChunk) -> list[str]:
"""The items that may start chunks while first's runs, by touch_predictions' pick; no line where none of the release's items holds a prediction."""
first = plan.first
found = chunks_beside(plan.items, first)
+3 -37
View File
@@ -4,10 +4,8 @@ import pathlib
import typing
from failure import Failure
from release_plan.todo_table import Item
from release_plan.release_standing import LastCut
from release_plan.release import Release
from project_config import templates
from release_plan.next_chunk import NextChunk, NoItem
# The CLI that lists a forge's pull requests: gh for a github.com origin, tea for any other.
Forge = typing.Literal["gh", "tea"]
@@ -21,38 +19,6 @@ 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."""
items: list[Item]
first: Item
# 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:
"""The branch first's worktree is on."""
return templates.branch_of(self.branch_template, self.first.id)
@dataclasses.dataclass(frozen=True)
class NoItem:
"""Why the plan names no item for the next chunk, as a sentence the worker reads."""
why: str
@dataclasses.dataclass(frozen=True)
class Worktree:
path: pathlib.Path
@@ -72,7 +38,7 @@ class NamedPath:
@dataclasses.dataclass(frozen=True)
class ItemFacts:
"""What the preflight found or made for the plan's first item."""
plan: Plan
plan: NextChunk
worktree: Worktree | Failure
# The forge whose CLI listed the open pull requests, and how it ran; None without an origin remote.
pulls: tuple[Forge, Ran | Failure] | None
@@ -91,7 +57,7 @@ class Gathered:
cut: LastCut
# What was found or made for the plan's first item; else why the plan names none.
item: ItemFacts | NoItem
# The plan that was read, as choices.plan_name names it.
# The plan that was read, as release_plan.next_chunk.plan_name names it.
plan: str
# Each path the project's config sets, and the epic of a plan kept in Jira, by its setting: in the item's worktree where one was made or continued, else in the checkout.
places: dict[str, str]
+6 -5
View File
@@ -78,11 +78,12 @@ import typing
from git_cli.git_repo import commit_exists, default_branch, file_at, git, top
from failure import Failure
from chunk_preflight.gathered import Forge, Gathered, ItemFacts, NamedPath, NoItem, Plan, Ran, Worktree
from chunk_preflight.choices import forge_of, plan_name, planned, pulls_command, worktree_add, worktree_on
from chunk_preflight.gathered import Forge, Gathered, ItemFacts, NamedPath, Ran, Worktree
from chunk_preflight.choices import forge_of, pulls_command, worktree_add, worktree_on
from chunk_preflight.facts import JOINING_DETAILS, render
from project_config.main import located
from release_plan.named_code import named_paths
from plan.named_paths import named_paths
from release_plan.next_chunk import NextChunk, NoItem, plan_name, planned
from release_plan.release_standing import project_plan
BIN = pathlib.Path(__file__).resolve().parents[1]
@@ -142,14 +143,14 @@ def preflight(root: pathlib.Path, timeout: float, make: bool, item_id: int | Non
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, item_id)
plan = planned(held.plan, held.cut, ref, config.branch, outside, item_id)
item = plan if isinstance(plan, NoItem) else item_facts(root, ref, plan, timeout, make)
# A `checkout:` path lands in the worktree the chunk works in.
made = located(str(item.worktree.path), pathlib.Path.home()) if isinstance(item, ItemFacts) and isinstance(item.worktree, Worktree) else config
return render(Gathered(ref, note, held.cut, item, plan_name(ref, outside), (config if isinstance(made, Failure) else made).places, outside is not None, config.texts))
def item_facts(root: pathlib.Path, default: str, plan: Plan, timeout: float, make: bool) -> ItemFacts:
def item_facts(root: pathlib.Path, default: str, plan: NextChunk, timeout: float, make: bool) -> ItemFacts:
worktree = item_worktree(root, plan.branch, default) if make else Failure(f"none made, since it ran without {WORKTREE}.")
path = worktree.path if isinstance(worktree, Worktree) else None
return ItemFacts(plan, worktree, pull_listing(root, plan.branch, timeout), named_files(plan.text, path or root), tools_run(plan.first.id, path, timeout) if path else [])
+6 -4
View File
@@ -10,15 +10,17 @@ 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 release_plan.next_chunk import CarriedOver, NoItem
from chunk_preflight import choices
from failure import Failure
from chunk_preflight.choices import forge_of, worktree_add
from chunk_preflight.gathered import Gathered, ItemFacts, NamedPath, Ran, Worktree
from test_env import isolated_env
from release_plan.release_standing import LastCut, UNSEEN_RELEASES
from chunk_preflight.main import line_count, ran, seconds, TIMEOUT
from release_plan import next_chunk
from chunk_preflight.facts import open_pulls, render
from plan_store.stores import plan_of
from plan_store.todo_md import plan_of
from project_config.test_project_config import write_config
BIN = pathlib.Path(__file__).resolve().parents[1]
@@ -388,8 +390,8 @@ class ChunkPreflightTool(unittest.TestCase):
def planned(todo, *rest):
"""choices.planned for the plan a todo.md's text holds, or for the Failure given."""
return choices.planned(plan_of(todo) if isinstance(todo, str) else todo, *rest)
"""next_chunk.planned for the plan a todo.md's text holds, or for the Failure given."""
return next_chunk.planned(plan_of(todo) if isinstance(todo, str) else todo, *rest)
def item_facts(todo=TODO, **fields):
+2 -2
View File
@@ -5,8 +5,8 @@ import re
import shlex
import typing
# Launchers that run the tool named later in their words, such as uvx --with pytest mutmut run.
LAUNCHERS = frozenset({"bunx", "env", "nice", "npx", "pipx", "pnpm", "run-heavy", "time", "timeout", "uvx", "yarn"})
# Launchers that run the tool named later in their words, such as uvx --with pytest mutmut run, uv run mutmut run or sudo docker build.
LAUNCHERS = frozenset({"bunx", "doas", "env", "nice", "npx", "pipx", "pnpm", "poetry", "run-heavy", "sudo", "time", "timeout", "uv", "uvx", "yarn"})
HEREDOC = re.compile(r"<<-?[ \t]*([\"']?)([A-Za-z_]\w*)\1[^\n]*\n.*?^[ \t]*\2[ \t]*$", re.DOTALL | re.MULTILINE)
ASSIGNMENT = re.compile(r"[A-Za-z_][A-Za-z0-9_]*=")
OPERATOR = set("\n();&|<>")
+6 -7
View File
@@ -3,7 +3,6 @@
Each step first checks whether an earlier run did it, so a rerun continues where the last run stopped.
"""
import pathlib
import re
import shutil
import sys
import tempfile
@@ -13,11 +12,11 @@ from project_config.settings import DEFAULT_FLOOR
from git_cli.git_repo import default_ref, git
from deploy_release.deploy import deploy
from failure import Failure
from plan_store.stores import FilePlan
from plan_store.todo_md import FilePlan
from record_store.stores import FileStore
from deploy_release import forge
from chunk_preflight.choices import forge_of
from release_plan.release import newest_tag, Release, version
from plan.release import newest_tag, Release, UNRELEASED_HEADING, version
from project_config import templates
@@ -119,9 +118,9 @@ def ready_release(clone: str, ref: str) -> Release | Failure:
"""The next release, as chunk-preflight works it out, where it is ready to cut: it holds no item in todo.md, its release review has landed and changes are unreleased."""
# No project's config names the clone, so its changelog is read at the fixed path, on ref like the plan, and its titles as they stand.
plan = default_plan(clone, ref, clone_plan(clone), FileStore(pathlib.Path(clone, "CHANGELOG.md"), "CHANGELOG.md"), templates.BARE)
if isinstance(plan.todo, Failure):
return Failure(f"todo.md on {ref} cannot be read: {plan.todo.reason}")
match chunk_item(plan.todo.items, plan.cut):
if isinstance(plan.plan, Failure):
return Failure(f"todo.md on {ref} cannot be read: {plan.plan.reason}")
match chunk_item(plan.plan.items, plan.cut):
case ReadyToCut(release=release) if release is not None:
return release
case ReadyToCut():
@@ -211,7 +210,7 @@ def push_cut_commit(clone: str, ref: str, branch: str, named: str, title: str, r
if isinstance(added := git("worktree", "add", "--quiet", "--detach", str(worktree), ref, cwd=clone), Failure):
return added
changelog = worktree / "CHANGELOG.md"
renamed, count = re.subn(r"^## Unreleased$", f"## {named}", changelog.read_text() if changelog.exists() else "", count=1, flags=re.MULTILINE)
renamed, count = UNRELEASED_HEADING.subn(f"## {named}", changelog.read_text() if changelog.exists() else "", count=1)
if not count:
return Failure(f"CHANGELOG.md on {ref} has no ## Unreleased section to rename")
changelog.write_text(renamed)
+1 -1
View File
@@ -1,7 +1,7 @@
"""Move a checkout to this repo's newest release, as a bare `deploy-release` does."""
from failure import Failure
from git_cli.git_repo import git
from release_plan.release import newest_tag, parsed, tagged
from plan.release import newest_tag, parsed, tagged
from text_files.markdown_text import sections
+22 -14
View File
@@ -7,11 +7,11 @@ from larv_review.plan import checkout_plan, plan_reasons
from git_cli.git_repo import commit_exists
from larv_review.ruling import counted, overall, ruling, split, surplus, votes
from failure import Failure
from plan_store.stores import file_plan, store as plan_store
from larv_review.seats import FIRST_SEATS, scores, seats_file, SeatsFile
from larv_review.scoring import floor_step, means, under_floor
from record_store.held import Held
from project_config.main import located
from release_plan import plan_file
from plan_store.stores import store as plan_store
from record_store.stores import RecordStore, store
from larv_review.scoring_setup import removed_setup
@@ -84,10 +84,11 @@ def rerank(home: pathlib.Path, warn: Say) -> Failure | None:
if todo is None:
# A plan in Jira is ranked by Jira's backlog, which no score moves.
return None
ranked = plan_file.rank_file(todo, config)
plan = file_plan(config, todo)
ranked = plan.rank()
if isinstance(ranked, Failure):
return Failure(f"recorded the run, but rank_todo.py cannot rank {todo}: {ranked.reason}. Fix what that names, then run rank_todo.py on {todo}, not record-scoring again")
for line in plan_file.report_lines(todo, ranked):
for line in plan.reported(ranked):
warn(line)
if ranked.under_bar:
return Failure(f"recorded the run and ranked {todo}, but the lines above name items now under the bar. Settle each as its line says, then run rank_todo.py on {todo}, not record-scoring again")
@@ -145,22 +146,29 @@ def read_agreement(home: pathlib.Path) -> str | Failure:
def history_file(home: pathlib.Path) -> tuple[RecordStore, str] | Failure:
"""The store the project's config names for its comprehension history, and the history's text, empty where there is none yet."""
held = held_history(home)
return held if isinstance(held, Failure) else (held[0], held[1].text)
def held_history(home: pathlib.Path) -> tuple[RecordStore, Held] | Failure:
"""The store the project's config names for its comprehension history, and the history as it stands, with the version a write over it names."""
config = located(None, home)
if isinstance(config, Failure):
return config
history = store(config, "comprehension-history")
text = history.read()
return text if isinstance(text, Failure) else (history, text)
held = history.held()
return held if isinstance(held, Failure) else (history, held)
def append(read: str, entry: str, home: pathlib.Path) -> str | Failure:
"""Appends entry and returns the line the tool prints; a Failure where the history already holds an entry on what the seats read."""
read_history = history_file(home)
if isinstance(read_history, Failure):
return read_history
history, text = read_history
if recorded(text, read):
read_history = held_history(home)
return read_history if isinstance(read_history, Failure) else appended_to(*read_history, read, entry)
def appended_to(history: RecordStore, held: Held, read: str, entry: str) -> str | Failure:
"""Writes entry onto held, the history as history's store read it, over held's version; the line the tool prints, or why the entry isn't written."""
if recorded(held.text, read):
return Failure(f"{history.label} already holds an entry on {read}; record each ruling or run once")
if unwritten := history.write(appended(text, entry)):
return unwritten
return f"Appended to {history.label}."
written = history.write(appended(held.text, entry), held.version)
return written if isinstance(written, Failure) else f"Appended to {history.label}."
+5 -4
View File
@@ -1,13 +1,14 @@
import pathlib
import typing
from larv_review.plan import EMPTIED_WORDS, plan_reasons
from larv_review.plan import Emptied, plan_reasons
from review_rules.comprehension_history import entries
from failure import Failure
from git_cli.git_repo import file_at, git
from project_config.main import located
from release_plan.todo_table import NoItemsTable
from plan_store.stores import store as plan_store, PlanStore
from plan.todo_table import NoItemsTable
from plan_store.stores import store as plan_store
from plan_store.plans import PlanStore
from record_store.stores import store
@@ -48,7 +49,7 @@ def owed_scoring_run(default: str, home: pathlib.Path, warn: typing.Callable[[st
def shortfall(reasons: list[str], recorded: int) -> Failure | None:
"""Which scoring runs the plan's reasons call that recorded, the count the branch added to the history, leaves unrecorded; None where it holds them all."""
needed = 2 if any(reason.endswith(EMPTIED_WORDS) for reason in reasons) else 1
needed = 2 if any(isinstance(reason, Emptied) for reason in reasons) else 1
if recorded >= needed:
return None
return Failure(f"the chunk owes {needed} scoring run{'s' if needed > 1 else ''} and the branch's committed history records {max(recorded, 0)}: it {' and '.join(reasons)}. larv-review's SKILL.md → 'Scoring run' says how to run and record {'them' if needed > 1 else 'it'}{"; → 'Second run' says how the second is titled" if needed > 1 else ""}")
+13 -10
View File
@@ -1,23 +1,27 @@
import pathlib
from release_plan.release_standing import Cut, LastCut, next_release, project_plan, Unknown
from release_plan.release_standing import Cut, LastCut, next_release, project_plan, standing_of, Unknown
from failure import Failure
from larv_review.scoring import is_floor_item
from release_plan.todo_table import Item, NoItemsTable
from plan.todo_table import Item, NoItemsTable
from project_config.main import located
from release_plan.goals_file import OPTED_OUT
from plan_store.stores import Plan, PlanStore
from plan.goals_file import OPTED_OUT
from plan_store.plans import Plan, PlanStore
from plan_store import stores as plan_stores
from project_config.settings import ProjectConfig
from release_plan.release import Release, version
from plan.release import Release, version
from record_store import stores
from larv_review.unmeasured import unmeasured_cut
# The words that end the reason a chunk empties a release. Such a chunk is due two scoring runs; a chunk with any other reason, one.
# The words that end the reason a chunk empties a release; SKILL.md → "Second run" quotes them.
EMPTIED_WORDS = "with no plan item"
class Emptied(str):
"""The reason a chunk empties a release, which makes it due two scoring runs; a chunk with only other reasons is due one."""
def scoring_run_due(before: list[Item], after: list[Item], ships: list[int], landed_release: Release | None, renamed: frozenset[Release], unmeasured: str | None = None) -> list[str] | Failure:
"""Why the plan calls a scoring run, empty when it does not.
@@ -34,8 +38,7 @@ def scoring_run_due(before: list[Item], after: list[Item], ships: list[int], lan
reasons.append(f"follows {unmeasured}")
for release in emptied(before, after, shipped, renamed):
if work_landed(release, shipped, landed_release):
# SKILL.md → "Second run" keys on this wording.
reasons.append(f"leaves release {version(release)} {EMPTIED_WORDS}")
reasons.append(Emptied(f"leaves release {version(release)} {EMPTIED_WORDS}"))
return reasons
@@ -49,7 +52,7 @@ def landed_towards(found: list[Item], cut: LastCut) -> Release | None | Failure:
"""The next release on the default branch, once work has landed towards it: once one or more changes are unreleased, as `release_standing.unreleased_changes` counts them. None where there is no next release, or no change is unreleased. found is the default branch's plan."""
if isinstance(cut.tag, Failure):
return Failure(f"could not tell the next release: the default branch's tags cannot be read: {cut.tag.reason}")
upcoming = next_release(found, cut)
upcoming = next_release(standing_of(found, cut), cut)
if isinstance(upcoming, Unknown):
return Failure("could not tell the next release: the default branch's todo.md history cannot be read")
# Cut's release is the last cut's version or earlier, so no work lands towards it.
@@ -86,7 +89,7 @@ def plan_reasons(ref: str, ids: list[int] | None, home: pathlib.Path) -> list[st
if OPTED_OUT.search(decisions):
return []
held = project_plan(config, ref, checkout)
before = held.todo
before = held.plan
read = checkout_plan(plan_stores.store(config))
if isinstance(read, Failure):
return read
+3 -3
View File
@@ -1,8 +1,8 @@
"""The plan as a listing a reviewer reads with the Read tool, whatever store holds the plan."""
from failure import Failure
from release_plan.todo_table import Item
from plan_store.stores import PlanStore
from release_plan.release import version
from plan.todo_table import Item
from plan_store.plans import PlanStore
from plan.release import version
def plan_listing(plan: PlanStore) -> str:
+1 -1
View File
@@ -1,7 +1,7 @@
import decimal
from review_rules.comprehension_history import DIMENSIONS
from release_plan.todo_table import Item
from plan.todo_table import Item
# A floor item's tagline opens with this phrase, which a tagline quoting or mentioning the floor never does; a floor item's chunk runs a scoring run.
FLOOR_ITEM = "Reach the comprehension floor:"
+16 -4
View File
@@ -15,18 +15,20 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from larv_review.agreement import agreement_report, ruling_agreement, run_agreement
from review_rules.comprehension_history import appended, entries, HistoryChange, latest_places, Place, recorded, ruling_entry, scoring_entry, ScoringRun, Seat
from larv_review.plan import checkout_plan, EMPTIED_WORDS, landed_towards, plan_reasons, scoring_run_due
from larv_review.history_commands import appended_to
from larv_review.plan import checkout_plan, Emptied, EMPTIED_WORDS, landed_towards, plan_reasons, scoring_run_due
from review_rules import comprehension_history
from project_config.test_project_config import configured
from larv_review.ruling import counted, ruling, split, surplus, votes
from larv_review.history_commands import decided, rerank
from project_config.settings import DEFAULT_FLOOR
from failure import Failure
from plan_store.stores import FilePlan
from plan_store.todo_md import FilePlan
from record_store.stores import FileStore
from larv_review.scoring import floor_step, means, under_floor
from record_store.held import Held
from test_env import isolated_env
from release_plan.todo_table import Item, items, NoItemsTable
from plan.todo_table import Item, items, NoItemsTable
from release_plan.release_standing import LastCut
from larv_review.ruling_base import measured_commit
from record_store.fakes import MemoryStore
@@ -459,13 +461,23 @@ class LandedTowards(unittest.TestCase):
self.assertEqual(landed_towards(plan, LastCut(Failure("fatal: bad object"), "", 3, [])), Failure("could not tell the next release: the default branch's tags cannot be read: fatal: bad object"))
class AppendedTo(unittest.TestCase):
def test_writes_the_entry_over_the_version_the_history_was_read_at(self):
history = MemoryStore(label="history.md", version=5)
self.assertEqual(appended_to(history, Held("", "5"), "PR #2 at abcdef1\n", "## an entry\n"), "Appended to history.md.")
self.assertEqual(history.overs, ["5"])
class Shortfall(unittest.TestCase):
def test_skill_md_names_the_words_that_end_the_reason_a_release_empties(self):
self.assertIn(EMPTIED_WORDS, (pathlib.Path(__file__).resolve().parents[2] / "skills" / "larv-review" / "SKILL.md").read_text(encoding="utf-8"))
def test_a_chunk_that_empties_a_release_owes_two_runs_and_any_other_reason_one(self):
emptied = ["leaves release 0.1.0 with no plan item"]
emptied = [Emptied("leaves release 0.1.0 with no plan item")]
floor = ["ships item 2, a floor item"]
# The type, not the words, makes a reason call two runs.
self.assertIn("owes 1 scoring run and", shortfall(["leaves release 0.1.0 with no plan item"], 0).reason)
self.assertIsInstance(scoring_run_due([item(1, (0, 1, 0))], [], [], (0, 1, 0), set())[0], Emptied)
self.assertIn("owes 2 scoring runs and the branch's committed history records 1", shortfall(emptied + floor, 1).reason)
self.assertIn("owes 1 scoring run and", shortfall(floor, 0).reason)
self.assertIn("records 0:", shortfall(floor, -1).reason)
+1 -1
View File
@@ -4,7 +4,7 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from plan_store.stores import BLOCKED_BY
from plan.todo_table import BLOCKED_BY
from plan_store.contract import FIRST, SECOND
from plan_store.fakes import MemoryPlan
from larv_review.plan_listing import plan_listing
+2 -2
View File
@@ -1,10 +1,10 @@
"""The todo.md items a chunk takes: those the worker names on its latest `Chunk items:` line, scored as todo.md scores them (docs/decisions.md → `routing: loop-claude reads the items a chunk takes`)."""
"""The plan items a chunk takes: those the worker names on its latest `Chunk items:` line, scored as the plan scores them (docs/decisions.md → `routing: loop-claude reads the items a chunk takes`)."""
import re
from claude_code.entries import AssistantTurn, Entry, Text
from failure import Failure
from loop_claude.quotes import plain
from plan_store.stores import Plan
from plan_store.plans import Plan
from loop_claude.verdicts import TakenIn
# The label opening the line; prompts.NAME_THE_ITEMS asks the worker for it.
+1 -1
View File
@@ -31,7 +31,7 @@ INTERRUPT_RULES = (
"- it is blocked on something only the human can supply: a credential, a version bump, a choice "
"outside the repo, or a release ready to cut, which only the human may publish\n"
"- it flags that the goals need changing\n"
"- it flags that the plan in todo.md or the task itself is unclear or missing, and recommends no way on\n\n"
"- it flags that the plan or the task itself is unclear or missing, and recommends no way on\n\n"
"interrupt=false otherwise. A choice in the repo that no rule reserves for the human is the worker's to make, "
"so its taking its own recommendation on one is no reason to interrupt. Where it asks about such a choice and "
"recommends an answer, quote the sentence of that rule telling it to take the option it would recommend, even "
+6 -6
View File
@@ -12,7 +12,7 @@ from claude_code.transcript import Typed
# Where the judge may quote an answer from, named as the human and the worker see them; of the goals file the judge sees only the premises.
QUOTE_SOURCES = listed(("the goals file's Goals and Audience", *RECORD_FILES, *HUMAN_RULE_NAMES), "or")
# Where the worker may write an answer the human typed, so it counts as recorded.
ANSWER_DESTINATIONS = "the goals file's Goals or Audience, " + ", ".join(RECORD_FILES) + ", todo.md or a comment"
ANSWER_DESTINATIONS = "the goals file's Goals or Audience, " + ", ".join(RECORD_FILES) + ", the plan or a comment"
ANSWERS_RECORDED = f"every answer the human typed in it that a later chunk could need is recorded in {ANSWER_DESTINATIONS} at the one place it governs"
# How review_launches names the reviews: "each reviewer" covers every pass with an agent.
EACH_REVIEWER = "each reviewer"
@@ -23,7 +23,7 @@ THE_SECURITY_PASS = "the security pass's subagent"
# Workers only, not CLAUDE.md, which reviewers load too: a reviewer under a like rule missed findings.
READING_RULE = "Read in small pieces: never read more than 80 lines of a file at once, nor take a tool output over 3,000 characters into your context."
# chunk_items reads the latest such line; three fresh readers picked the label (docs/decisions.md → `routing: loop-claude reads the items a chunk takes`).
NAME_THE_ITEMS = f"Name every todo.md item this chunk takes on one line, as in `{CHUNK_ITEMS} 297 (L 3, E + I 5), 298 (L 3, E + I 7)`, and write the whole line again whenever the set changes."
NAME_THE_ITEMS = f"Name every plan item this chunk takes on one line, as in `{CHUNK_ITEMS} 297 (L 3, E + I 5), 298 (L 3, E + I 7)`, and write the whole line again whenever the set changes."
AFTER_CODE_HEALTH = 'which rank after code health (~/.claude/CLAUDE.md → "Shared goal") unless the goals file voids it'
@@ -33,7 +33,7 @@ def fresh(task: str, premises: str, route: Route, ladder: Ladder, project: Rung
"""A chunk's first prompt; facts is preflight_facts' or preflight_failed's text."""
routed = f"{routed_by(route, ladder, project)} {recount(route)}" if route.item else " ".join(rung_sentences(route, ladder, project))
opening = f"{routed}\n\n" if routed else ""
return f"{task}\n\nContinue any open draft PR or worktree for the chunk before creating a new one. {READING_RULE} {NAME_THE_ITEMS}\n\n{opening}{facts}\n\nThe chunk's todo.md items, or else the task above, set its scope. The goals below, {AFTER_CODE_HEALTH}, choose between ways to deliver that scope, and never widen it.\n\nFrom the goals file, {premises}"
return f"{task}\n\nContinue any open draft PR or worktree for the chunk before creating a new one. {READING_RULE} {NAME_THE_ITEMS}\n\n{opening}{facts}\n\nThe chunk's plan items, or else the task above, set its scope. The goals below, {AFTER_CODE_HEALTH}, choose between ways to deliver that scope, and never widen it.\n\nFrom the goals file, {premises}"
def routed_by(route: Route, ladder: Ladder, project: Rung | None) -> str:
@@ -45,7 +45,7 @@ def routed_by(route: Route, ladder: Ladder, project: Rung | None) -> str:
def recount(route: Route) -> str:
"""Has the worker count the routing item's size again once it knows the code, since the L that routed it was scored before anyone read that code."""
return f"After your first read of the code, count item {route.item}'s size again: the lines, files and components you will change. Where that count would change its L, have a subagent that scores todo.md items re-score it; a re-score whose L picks a rung above yours is escalation trigger 1."
return f"After your first read of the code, count item {route.item}'s size again: the lines, files and components you will change. Where that count would change its L, have a subagent that scores plan items re-score it; a re-score whose L picks a rung above yours is escalation trigger 1."
def preflight_facts(printed: str) -> str:
@@ -77,8 +77,8 @@ def scan_launch(choice: ReviewChoice, route: Route) -> list[str]:
def planning_launch(route: Route, ladder: Ladder, project: Rung) -> list[str]:
"""Where the worker runs below the project's rung, the sentence naming where to launch a subagent that files or scores todo.md items. On an Opus 5.5 project: `Your rung is below the project's: launch each subagent that files or scores todo.md items on the rung `~/.claude/bin/subagent-rung --plan claude-opus-5-5 <L>` prints.`"""
return [f"Your rung is below the project's: launch each subagent that files or scores todo.md items on the rung `~/.claude/bin/subagent-rung --plan {project.model} <L>` prints."] if ladder.position(route.rung) < ladder.position(project) else []
"""Where the worker runs below the project's rung, the sentence naming where to launch a subagent that files or scores plan items. On an Opus 5.5 project: `Your rung is below the project's: launch each subagent that files or scores plan items on the rung `~/.claude/bin/subagent-rung --plan claude-opus-5-5 <L>` prints.`"""
return [f"Your rung is below the project's: launch each subagent that files or scores plan items on the rung `~/.claude/bin/subagent-rung --plan {project.model} <L>` prints."] if ladder.position(route.rung) < ladder.position(project) else []
def markdown_launch(choice: ReviewChoice) -> list[str]:
+4 -4
View File
@@ -17,7 +17,7 @@ from loop_claude.routing import judge_rung, next_route, step_up, StepUp
from model_routing.ladder import Ladder, Rung
from transcript_archive.read import last_spent
from transcript_archive import outcomes
from plan_store.stores import Plan
from plan_store.plans import Plan
from loop_claude.cycle import prompts
from claude_code.transcript import read_transcript
from loop_claude.cycle.retry import retried
@@ -51,8 +51,8 @@ class Cycle:
route: Route
session: Session
task: str
# todo.md on the default branch as the cycle starts, which scores the items the worker names.
todo: Plan | Failure
# The plan on the default branch as the cycle starts, which scores the items the worker names.
plan: Plan | Failure
# Empty when the previous cycle's verdict was not Unfinished.
unfinished_evidence: str
# The tmux window the loop runs in, which an interrupt marks.
@@ -160,7 +160,7 @@ def rule(cycle: Cycle, transcript_path: str, quoted_answers: int) -> Ruled | Sto
if isinstance(verdict, Stop):
return verdict
if not isinstance(verdict, Finished):
verdict = dataclasses.replace(verdict, taken_in=chunk_items.taken_in(entries, cycle.todo))
verdict = dataclasses.replace(verdict, taken_in=chunk_items.taken_in(entries, cycle.plan))
if not isinstance(verdict, Interrupt | QuotedAnswer):
return Ruled(verdict)
annotation = annotation_of(cycle, transcript_path, entries, verdict.judged)
+16 -21
View File
@@ -7,14 +7,14 @@ from release_plan.release_standing import DefaultPlan, project_plan, UNSEEN_RELE
from loop_effects.effects import Effects, say
from failure import Failure
from loop_claude.routing import first_route, kept, routed_item
from plan_store.stores import held_at, Plan, store as plan_store
from loop_claude.loop.chunk_windows import held_beside, item_of
from chunk_preflight.main import ITEM
from release_plan.todo_table import Item
from plan.todo_table import Item
from model_routing.ladder import Ladder, Rung
from transcript_archive.read import latest_worker
from project_config.main import located
from loop_claude.loop.this_loop import Loop
from plan_store.plans import Plan
from loop_claude.cycle import prompts
from model_routing.route import Route, route_from
from claude_code.session import session_open, transcript_file
@@ -23,17 +23,12 @@ from claude_code.session import session_open, transcript_file
ORIGIN_TIMEOUT = 60
def fetched_todo(loop: Loop) -> Plan | Failure:
"""The plan, which scores the items a chunk takes: on the default branch as last fetched, or as it stands where the project's config puts it outside the checkout. fetched_plan reads it too, but also the release tag, CHANGELOG.md and each todo.md since the tag, which scoring the items doesn't need. Where it can't be read or scored, it says why."""
ref = default_ref(loop.root, ORIGIN_TIMEOUT, run=loop.effects.git)
config = located(loop.root, loop.paths.home)
if isinstance(config, Failure):
todo: Plan | Failure = config
else:
todo = ref if isinstance(ref, Failure) else held_at(ref, plan_store(config), loop.root, loop.effects.git)
if isinstance(todo, Failure):
say(f"the items the worker names lift no rung: {todo.reason}", loop.effects)
return todo
def scored_plan(default: DefaultPlan | Failure, effects: Effects) -> Plan | Failure:
"""The plan, which scores the items a chunk takes, from what the default branch holds; where it can't be read or scored, it says why."""
plan = default.plan if isinstance(default, DefaultPlan) else default
if isinstance(plan, Failure):
say(f"the items the worker names lift no rung: {plan.reason}", effects)
return plan
def routed(route: Route | None, ladder: Ladder, project: Rung | None, model: str, archived: typing.Callable[[], Route | None], item: typing.Callable[[], Item | None]) -> Route:
@@ -60,10 +55,10 @@ def archived_route(archive_folder: pathlib.Path, loop: Loop) -> Route | None:
return route
def chunk_start(loop: Loop) -> tuple[str, typing.Callable[[], Item | None]]:
"""The facts for a fresh worker's prompt, empty where the session is open, and the reader of the item that routes the chunk. The reader reads the default branch as last fetched: for a fresh chunk, by the preflight that runs first; for an open session, which runs none, by whatever fetched last."""
facts = "" if session_open(loop.session) else chunk_facts(loop)
return facts, lambda: plan_item(fetched_plan(loop), item_of(loop.window.name), loop.effects)
def chunk_start(loop: Loop) -> tuple[str, DefaultPlan | Failure]:
"""The facts for a fresh worker's prompt, empty where the session is open, and what the default branch holds, read once for the cycle: it routes the chunk, through plan_item, and scores the items the worker names, through scored_plan. It reads the default branch as last fetched: for a fresh chunk, by the preflight that runs first; for an open session, which runs none, by whatever fetched last."""
fresh = not session_open(loop.session)
return chunk_facts(loop) if fresh else "", fetched_plan(loop, fresh)
def chunk_facts(loop: Loop) -> str:
@@ -75,12 +70,12 @@ def chunk_facts(loop: Loop) -> str:
return facts + (prompts.held_by_others(held) if held else "")
def fetched_plan(loop: Loop) -> DefaultPlan | Failure:
"""What the default branch, as last fetched, holds for routing; the plan and the changelog as they stand where the project's config puts them outside the checkout. It says UNSEEN_RELEASES for such a plan."""
def fetched_plan(loop: Loop, announce: bool = True) -> DefaultPlan | Failure:
"""What the default branch, as last fetched, holds for routing; the plan and the changelog as they stand where the project's config puts them outside the checkout. Where announce is True, as when a chunk starts, it says UNSEEN_RELEASES for such a plan, so the human reads it once per chunk, not every cycle."""
config = located(loop.root, loop.paths.home)
if isinstance(config, Failure):
return config
if config.tracked("plan") is None:
if announce and config.tracked("plan") is None:
say(UNSEEN_RELEASES, loop.effects)
ref = default_ref(loop.root, ORIGIN_TIMEOUT, run=loop.effects.git)
return ref if isinstance(ref, Failure) else project_plan(config, ref, loop.root, loop.effects.git)
@@ -92,7 +87,7 @@ def plan_item(plan: DefaultPlan | Failure, window_item: int | None, effects: Eff
if isinstance(plan, Failure):
item: Item | Failure | None = plan
else:
item = routed_item(plan.todo, plan.cut, window_item)
item = routed_item(plan.plan, plan.cut, window_item)
if isinstance(item, Failure):
say(f"routing on the project's rung: {item.reason}", effects)
return None
+43 -19
View File
@@ -1,5 +1,6 @@
"""The chunks of one project that run at once, each in its own tmux window: which may start now, and how each starts (docs/decisions.md → `loop-claude: each chunk runs in its own tmux window`)."""
import contextlib
import dataclasses
import fcntl
import pathlib
import re
@@ -12,10 +13,9 @@ 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 release_plan.next_chunk import NextChunk, NoItem, planned
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
@@ -72,17 +72,40 @@ def held_items(chunks: typing.Iterable[str], key: str, claude_code_transcripts:
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."""
@dataclasses.dataclass(frozen=True)
class Room:
"""What a project's windows leave room for, under its limit of chunks at once."""
# The chunks whose windows run.
running: list[str]
# The chunks whose windows are dead: their loop stopped or failed, and the window keeps its last lines and its items.
stopped: list[str]
# The stopped chunks to start again, before any chunk from the plan.
restart: list[str]
# How many chunks from the plan may start beside them.
left: int
def room_of(windows: list[tmux.Listed], own: str | None, leaving: bool, limit: int) -> Room:
"""The room windows leave under limit. own is the chunk of the loop that asks, None for the human's loop-claude <task>. leaving is True where own's chunk finished: its window no longer counts as running, and no stopped chunk starts again, since only a loop that isn't leaving, such as the human's loop-claude <task>, restarts one."""
running = [window.name for window in windows if not window.dead and not (leaving and window.name == own)]
# Below 0 where the config lowered parallel-chunks while more chunks ran.
room = max(limit - len(running), 0)
stopped = [window.name for window in windows if window.dead]
restart = [] if leaving else stopped[:room]
return Room(running, stopped, restart, room - len(restart))
def may_start(plan: NextChunk | NoItem, running: list[str], held: set[int], room: int) -> list[str]:
"""The chunks to start now beside the running ones, whose chunks hold the items in held: the plan's next item and the items touch_predictions picks to run beside it, in the plan's order, up to room of them. Each leaves out an item in held, and one whose `Touches:` prediction overlaps a held item's, or where either has none. A plan without an item starts NO_ITEM, and only alone."""
if isinstance(plan, NoItem):
return [] if running else [NO_ITEM]
return [] if running or room < 1 else [NO_ITEM]
beside = chunks_beside(plan.items, plan.first)
picked = [plan.first.id, *(beside.picked if isinstance(beside, Beside) else [])]
details = {item.id: item.detail for item in plan.items}
# chunks_beside checks overlaps against the plan's next item only, and a running chunk's item may no longer be that one once an item merged. A held item that left the plan overlaps nothing.
theirs = [predicted(details[item_id]) for item_id in sorted(held) if item_id in details]
free = [item_id for item_id in picked if item_id not in held and clear_of(predicted(details[item_id]), theirs)]
return [window_name(item_id) for item_id in free][: max(limit - len(running), 0)]
return [window_name(item_id) for item_id in free][: max(room, 0)]
def clear_of(ours: Touches | Failure | None, theirs: list[Touches | Failure | None]) -> bool:
@@ -90,7 +113,7 @@ def clear_of(ours: Touches | Failure | None, theirs: list[Touches | Failure | No
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:
def next_plan(root: str, home: pathlib.Path, effects: Effects) -> NextChunk | NoItem | Failure:
"""The plan on the default branch, fetched now where origin answers, with its next item, as chunk-preflight reads it."""
config = located(root, home)
if isinstance(config, Failure):
@@ -101,7 +124,7 @@ def next_plan(root: str, home: pathlib.Path, effects: Effects) -> Plan | NoItem
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)
return planned(held.plan, held.cut, ref, config.branch, None if config.tracked("plan") else config.plan_label)
def start_chunks(loop_run: LoopRun, leaving: bool, paths: Paths, env: typing.Mapping[str, str], launcher: pathlib.Path, effects: Effects) -> list[str] | Failure:
@@ -117,20 +140,16 @@ def start_chunks(loop_run: LoopRun, leaving: bool, paths: Paths, env: typing.Map
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:
room = room_of(windows, loop_run.chunk, leaving, config.parallel_chunks)
chunks = list(room.restart)
if room.left:
plan = next_plan(loop_run.root, paths.home, effects)
if isinstance(plan, Failure):
# Such as in a checkout without a default branch, where chunk-preflight fails too: the worker is told why and finds the facts itself.
say(f"starting a chunk without a plan item, since the plan cannot be read: {plan.reason}", effects)
plan = NoItem(plan.reason)
held = held_items(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]
held = held_items(room.running + room.stopped, key, paths.claude_code_transcripts)
chunks += [chunk for chunk in may_start(plan, room.running + room.restart, held, room.left) if chunk not in room.stopped]
for chunk in chunks:
stale = [window for window in windows if window.name == chunk and window.dead]
for window in stale:
@@ -148,7 +167,12 @@ def start_chunks(loop_run: LoopRun, leaving: bool, paths: Paths, env: typing.Map
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
wait_for_starts(paths.home, key)
others = [window.name for window in tmux.listed(tmux.session_name(key), effects.tmux) if window.name != chunk]
return sorted(held_items(others, key, paths.claude_code_transcripts))
def wait_for_starts(home: pathlib.Path, key: str) -> None:
"""Returns once no loop of the project is starting windows: start_chunks holds LOCK while it starts them. Where the lock cannot be taken, it returns at once."""
with contextlib.suppress(OSError), starting(home, key):
pass
+5 -6
View File
@@ -3,10 +3,10 @@ import pathlib
import typing
from transcript_archive.location import archive_root, project_archive
from loop_claude.loop.chunk_start import archived_route, chunk_start, fetched_todo, routed
from loop_claude.loop.chunk_start import archived_route, chunk_start, plan_item, routed, scored_plan
from loop_claude.loop.routing_check import check_routing
from loop_claude.project.checkout import checkout_root
from loop_claude.loop.chunk_windows import CHUNK_FLAG, chunk_session, start_chunks
from loop_claude.loop.chunk_windows import CHUNK_FLAG, chunk_session, item_of, start_chunks
from loop_claude.loop.close import closed_cycle
from loop_claude.cycle.run import Cycle, run_cycle
from loop_claude.loop.reload import decode_handed, exec_if_edited, fingerprint, LoopRun, RELOAD_FLAG
@@ -122,14 +122,13 @@ def next_cycle(loop_run: LoopRun, loop: Loop) -> Cycle | Stop:
return Stop(1, ladder.reason)
archive_folder = project_archive(loop.root, loop.paths.home, loop.env)
# After the reads above, so a loop that stops on one makes no worktree.
facts, item = chunk_start(loop)
facts, default = chunk_start(loop)
project = ladder.project_rung(models.worker)
route = routed(loop_run.route, ladder, project, models.worker, lambda: archived_route(archive_folder, loop), item)
route = routed(loop_run.route, ladder, project, models.worker, lambda: archived_route(archive_folder, loop), lambda: plan_item(default, item_of(loop.window.name), loop.effects))
say(f"\n=== cycle {loop_run.cycle_number}, worker on {route.rung} ===", loop.effects, stdout=True)
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, window=loop.window)
return Cycle(config=setup_version(loop.paths.claude_dir, loop.effects.git), effects=loop.effects, facts=facts, judge_model=models.judge, ladder=ladder, premises=premises, project=project, project_archive=archive_folder, records=records, root=loop.root, route=route, session=loop.session, task=loop_run.task, plan=scored_plan(default, loop.effects), unfinished_evidence=loop_run.unfinished_evidence, window=loop.window)
def own_ladder(file: pathlib.Path, model: str, unrouted: bool) -> str:
+4 -4
View File
@@ -8,13 +8,13 @@ as goals-and-audience: a file, or a Jira epic's description. `project-config goa
prints where it is. The task runs at the checkout root. Each cycle a worker runs the task. A chunk's
first worker prompt also quotes the premises. They, with code health (~/.claude/CLAUDE.md →
"Shared goal") ranked first unless the goals file voids it, choose between ways to deliver the
chunk's todo.md items, or else the task, and never widen them. A judge then reads the transcript's
chunk's plan items, or else the task, and never widen them. A judge then reads the transcript's
end, the premises, and the records: the project's AGENTS.md and docs/decisions.md, and the human's
~/.claude/CLAUDE.md and ~/.claude/rules/*.md, then the .md files in the folder of review standards
the project's config sets, where they exist. It rules whether the chunk, the work of one PR, is
finished. A chunk stays unfinished until each answer the human typed in it that a later chunk could
need is recorded: the premises or the records hold it, or the transcript shows the worker writing it
into the premises, AGENTS.md, docs/decisions.md, todo.md or a code comment. A choice the worker made
into the premises, AGENTS.md, docs/decisions.md, the plan or a comment. A choice the worker made
that the premises or the records settle is not asked about. When the worker asks a question they
answer, the judge quotes the answer, loop-claude prints it, and the worker resumes with it. A quote
they do not hold word for word is dropped, and the question goes to the human. So does a question
@@ -94,7 +94,7 @@ both set, nothing is asked.
The routing ladder is a list of rungs, least competent first, each a model at an effort. Where the
project's model is on it, the worker and the session /talk opens run on
the rung that the chunk's todo.md item picks, and the judge of some
the rung that the chunk's plan item picks, and the judge of some
models on another; a chunk no item routes runs on the project's model. The worker's prompts name the
rungs it launches its reviews on. The worker's rung steps up as a chunk stays unfinished, when the
worker names on its `Chunk items:` line an item that picks a higher rung, or when the judge finds
@@ -104,7 +104,7 @@ each review's rung in bin/model_routing/review_choice.py, and the prompts' wordi
bin/loop_claude/cycle/prompts.py. Each verdict, interrupt, quoted answer, stop and
step-up in the archive ends with a Worker: line, the route as JSON (Route.worker_line in
bin/model_routing/route.py); a rerun resumes an open chunk on the latest route named there. A
todo.md or an archive that cannot be read or parsed is said on stderr, and the chunk is routed
plan or an archive that cannot be read or parsed is said on stderr, and the chunk is routed
without it.
The ladder is a JSON file, each rung a model's full name and an effort of low, medium, high, xhigh
+1 -1
View File
@@ -3,7 +3,7 @@ import pathlib
from failure import Failure
from record_store.stores import goals_store
from project_config.main import located
from release_plan.goals_file import section
from plan.goals_file import section
def read_premises(root: str, home: pathlib.Path) -> str | Failure:
+6 -6
View File
@@ -5,10 +5,10 @@ from project_config.main import located
from loop_claude.project.text_file import read_utf8
from record_store.stores import store
# The records the judge reads beside the premises: these project files, then the human's rules below.
RECORD_FILES = ("AGENTS.md", "docs/decisions.md")
# The setting in the project's config that places each of RECORD_FILES.
RECORD_SETTINGS = ("working-rules", "decisions")
# The records the judge reads beside the premises, by the name that heads each, with the setting in the project's config that places it; then the human's rules below.
WORKING_RULES = ("AGENTS.md", "working-rules")
DECISIONS = ("docs/decisions.md", "decisions")
RECORD_FILES = (WORKING_RULES[0], DECISIONS[0])
# The human's rules, in the order the judge reads them: ~/.claude/CLAUDE.md, each .md file in ~/.claude/rules/,
# then each .md file in the review standards folder the project's config sets.
HUMAN_RULES_FILE = "CLAUDE.md"
@@ -27,8 +27,8 @@ def read_records(root: str, home: pathlib.Path, claude_dir: pathlib.Path) -> str
if isinstance(config, Failure):
return Failure(f"{config.reason} - {CONSEQUENCE}.")
rules = [claude_dir / HUMAN_RULES_FILE, *sorted((claude_dir / HUMAN_RULE_DIR).glob("*.md")), *sorted(config.paths["standards"].glob("*.md"))]
decisions = store(config, RECORD_SETTINGS[1]).read()
texts = [(RECORD_FILES[0], file_text(config.paths[RECORD_SETTINGS[0]])), (RECORD_FILES[1], Failure(f"{decisions.reason} - {CONSEQUENCE}.") if isinstance(decisions, Failure) else decisions)]
decisions = store(config, DECISIONS[1]).read()
texts = [(WORKING_RULES[0], file_text(config.paths[WORKING_RULES[1]])), (DECISIONS[0], Failure(f"{decisions.reason} - {CONSEQUENCE}.") if isinstance(decisions, Failure) else decisions)]
texts += [(named(rule, home, claude_dir), file_text(rule)) for rule in rules]
records = []
for heading, text in texts:
+2 -2
View File
@@ -33,9 +33,9 @@ from release_plan.release_standing import chunk_item, LastCut, Next
from loop_claude import escalation_mark
from failure import Failure
from loop_claude.verdicts import Interrupt, QuotedAnswer, Unfinished
from release_plan.todo_table import Item, NoItemsTable
from plan.todo_table import Item, NoItemsTable
from model_routing.ladder import Ladder, Rung
from plan_store.stores import Plan
from plan_store.plans import Plan
from model_routing.route import Route
UNFINISHED_PER_STEP = 2
+1 -1
View File
@@ -455,7 +455,7 @@ class Cycles(unittest.TestCase):
self.assertIsNone(argument(workers[1], "--name"))
self.assertEqual(argument(workers[2], "--session-id"), session)
self.assertTrue(argument(workers[0], "-p").startswith(f"{TASK}\n\nContinue any open draft PR"))
self.assertTrue(argument(workers[0], "-p").endswith("The chunk's todo.md items, or else the task above, set its scope. The goals below, " 'which rank after code health (~/.claude/CLAUDE.md → "Shared goal") unless the goals file voids it' ", choose between ways to deliver that scope, and never widen it.\n\nFrom the goals file, " f"{checkout.root}/README.md:\n## Goals\n1. Work.\n\n## Audience\nMe."))
self.assertTrue(argument(workers[0], "-p").endswith("The chunk's plan items, or else the task above, set its scope. The goals below, " 'which rank after code health (~/.claude/CLAUDE.md → "Shared goal") unless the goals file voids it' ", choose between ways to deliver that scope, and never widen it.\n\nFrom the goals file, " f"{checkout.root}/README.md:\n## Goals\n1. Work.\n\n## Audience\nMe."))
self.assertIn("main or master", argument(workers[0], "-p"))
self.assertNotIn(TASK, argument(workers[1], "-p"))
self.assertIn("Even then, it is finished only once every answer the human typed in it", argument(workers[1], "-p"))
+62 -36
View File
@@ -28,15 +28,15 @@ 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
from loop_claude.loop import main, reload, routing_check, this_loop, usage
from machine_load import memory
from release_plan import next_chunk
from transcript_archive import outcomes, write
from loop_state import paths
from plan_store.stores import plan_of
from plan_store.todo_md import plan_of
from transcript_archive.location import project_archive
from model_routing.ladder_file import read_ladder, SHIPPED
from model_routing.route import Route, route_from, WorkerLine
@@ -286,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, 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)
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.", plan=plan_of(""), unfinished_evidence=unfinished_evidence)
def archived_outcomes(self):
return sorted(path.read_text() for path in self.archive.glob("*/*.outcomes.md"))
@@ -1165,22 +1165,16 @@ class RouteSources(unittest.TestCase):
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)
later = next(item.id for item in plan.plan.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()))
# A chunk start reads the default branch once, for routing and for scoring the items the worker names.
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())
loop = a_loop(FakeEffects().effects())
self.assertEqual(chunk_start.chunk_start(loop), ("", plan))
# An open session is no fresh chunk, so the human isn't told again of releases the plan cannot show.
fetched.assert_called_once_with(loop, False)
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):
@@ -1189,13 +1183,13 @@ class RouteSources(unittest.TestCase):
self.assertTrue(stderr.getvalue().startswith(f"{STAMP} {said}"), stderr.getvalue())
def test_says_why_the_items_the_worker_names_lift_no_rung(self):
fetched = ["origin\n", "origin/main\n", "", "todo.md\n"]
for git, said in ((fetched + [TODO.replace("| 4 | 2 | 3 |", "| x | 2 | 3 |")], "the items the worker names lift no rung: item 3's L 'x' is not a whole number from 1 to 4\n"), ([Failure("no git")], "the items the worker names lift no rung: no git\n"), (fetched + [TODO], "")):
with self.subTest(said=said), tempfile.TemporaryDirectory() as root:
home = configured(self, pathlib.Path(root)).parents[1]
unscored = plan_of(TODO.replace("| 4 | 2 | 3 |", "| x | 2 | 3 |"))
for default, said in ((DefaultPlan(unscored, NO_CUT), "the items the worker names lift no rung: item 3's L 'x' is not a whole number from 1 to 4\n"), (Failure("no git"), "the items the worker names lift no rung: no git\n"), (DefaultPlan(plan_of(TODO), NO_CUT), "")):
with self.subTest(said=said):
with contextlib.redirect_stderr(io.StringIO()) as stderr:
chunk_start.fetched_todo(a_loop(FakeEffects(git=git).effects(), root=root, paths=paths.paths_from(home)))
scored = chunk_start.scored_plan(default, FakeEffects().effects())
self.assertEqual(stderr.getvalue(), f"{STAMP} {said}" if said else "")
self.assertEqual(scored, default.plan if isinstance(default, DefaultPlan) else default)
def test_reads_the_changelog_the_default_branch_holds_through_the_loops_git(self):
def git(*args, **options):
@@ -1219,16 +1213,19 @@ class RouteSources(unittest.TestCase):
self.assertEqual(stderr.getvalue(), "", "a plan git tracks hides no release")
config.write_text(config.read_text().replace('"checkout:todo.md"', '"folder:todo.md"'))
(folder / "todo.md").write_text(TODO)
self.assertEqual(chunk_start.fetched_todo(loop), plan_of(TODO))
unread = Failure("no git")
standing = a_loop(FakeEffects(git=["origin\n", "origin/main\n", unread, unread, unread, unread]).effects(), root=root, paths=paths.paths_from(folder.parents[1]))
with contextlib.redirect_stderr(io.StringIO()) as stderr:
held = chunk_start.fetched_plan(standing)
self.assertEqual((held.todo, held.cut.todos_since, held.cut.changelog), (plan_of(TODO), [], ""), "the plan as it stands, whatever git answers")
self.assertEqual((held.plan, held.cut.todos_since, held.cut.changelog), (plan_of(TODO), [], ""), "the plan as it stands, whatever git answers")
self.assertEqual(stderr.getvalue(), f"{STAMP} {UNSEEN_RELEASES}\n", "a release review loop-claude cannot call due is never skipped silently")
quiet = a_loop(FakeEffects(git=["origin\n", "origin/main\n", unread, unread, unread, unread]).effects(), root=root, paths=paths.paths_from(folder.parents[1]))
with contextlib.redirect_stderr(io.StringIO()) as stderr:
chunk_start.fetched_plan(quiet, announce=False)
self.assertEqual(stderr.getvalue(), "", "said once per chunk, as it starts")
config.unlink()
with contextlib.redirect_stderr(io.StringIO()) as stderr:
self.assertIn("no config names the checkout", chunk_start.fetched_todo(loop).reason)
self.assertIn("no config names the checkout", chunk_start.scored_plan(chunk_start.fetched_plan(loop), loop.effects).reason)
self.assertIn("the items the worker names lift no rung: no config names the checkout", stderr.getvalue())
self.assertIn("no config names the checkout", chunk_start.fetched_plan(loop).reason)
@@ -1308,6 +1305,17 @@ class TmuxCommands(unittest.TestCase):
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_fails_where_it_cannot_mark_a_session_it_made_as_the_checkouts_but_not_where_remain_on_exit_fails(self):
def answering(failing: str):
def run(args):
fails = args[:1] == ["set-option"] and failing in args
return subprocess.CompletedProcess(args, 1 if fails else 0, "" if fails else "@9\n", "no such session\n" if fails else "")
return run
window = tmux.Window("loop-proj", "item-7", "")
self.assertEqual(tmux.start_window(window, "/r", {}, ["x"], True, answering(tmux.OWNER)), Failure("tmux started the session loop-proj but could not mark it as this checkout's: no such session"))
self.assertIsNone(tmux.start_window(window, "/r", {}, ["x"], True, answering("remain-on-exit")))
self.assertIsNone(tmux.start_window(window, "/r", {}, ["x"], False, answering(tmux.OWNER)))
def test_reads_the_checkout_the_session_names(self):
fake = FakeEffects(owner="/c/proj")
self.assertEqual(tmux.owner("loop-proj", fake.tmux), "/c/proj")
@@ -1330,7 +1338,7 @@ 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="")
return next_chunk.NextChunk(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.
@@ -1339,26 +1347,39 @@ class ChunkWindows(unittest.TestCase):
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):
def test_leaves_the_items_running_chunks_hold_and_starts_only_as_many_as_the_room_left(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), [])
self.assertEqual(chunk_windows.may_start(plan, ["item-1"], {1, 3}, 1), ["item-4"])
self.assertEqual(chunk_windows.may_start(plan, ["item-1"], {1}, 2), ["item-3", "item-4"])
self.assertEqual(chunk_windows.may_start(plan, ["item-1"], {1}, 0), [])
def test_counts_the_running_chunks_against_the_limit_and_restarts_stopped_ones_first(self):
windows = [tmux.Listed("item-1", "", False), tmux.Listed("item-3", "", True), tmux.Listed("item-4", "", True)]
self.assertEqual(chunk_windows.room_of(windows, "item-1", False, 3), chunk_windows.Room(["item-1"], ["item-3", "item-4"], ["item-3", "item-4"], 0))
self.assertEqual(chunk_windows.room_of(windows, "item-1", False, 2), chunk_windows.Room(["item-1"], ["item-3", "item-4"], ["item-3"], 0))
self.assertEqual(chunk_windows.room_of(windows, "item-1", False, 5), chunk_windows.Room(["item-1"], ["item-3", "item-4"], ["item-3", "item-4"], 2))
def test_a_loop_whose_chunk_finished_leaves_its_room_and_restarts_no_stopped_chunk(self):
windows = [tmux.Listed("item-1", "", False), tmux.Listed("item-3", "", True)]
self.assertEqual(chunk_windows.room_of(windows, "item-1", True, 2), chunk_windows.Room([], ["item-3"], [], 2))
def test_leaves_no_room_where_more_chunks_run_than_the_limit(self):
windows = [tmux.Listed(f"item-{n}", "", False) for n in (1, 2, 3)]
self.assertEqual(chunk_windows.room_of(windows, "item-1", False, 2).left, 0)
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"])
plan = next_chunk.NextChunk(items=items, first=items[0], text="", branch_template="")
self.assertEqual(chunk_windows.may_start(plan, ["item-3"], {3}, 2), ["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), [])
self.assertEqual(chunk_windows.may_start(next_chunk.NextChunk(items=unpredicted, first=unpredicted[0], text="", branch_template=""), ["item-3"], {3}, 2), [])
# 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"])
self.assertEqual(chunk_windows.may_start(plan, ["item-9"], {9}, 2), ["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")
none = next_chunk.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), [])
@@ -1489,6 +1510,11 @@ class StartChunks(unittest.TestCase):
fake = FakeEffects(windows="item-5\t1\t@3\n")
self.assertEqual(self.start(fake), ["item-5", "item-1"])
def test_a_plan_with_no_item_starts_nothing_beside_a_restarted_chunk(self):
self.limit(2)
fake = FakeEffects(windows="item-5\t1\t@3\n")
self.assertEqual(self.start(fake, plan=next_chunk.NoItem("release 1.0.0 has no items")), ["item-5"])
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
@@ -1501,7 +1527,7 @@ class StartChunks(unittest.TestCase):
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")), [])
self.assertEqual(self.start(fake, chunk="item-7", leaving=True, plan=next_chunk.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()
@@ -1697,7 +1723,7 @@ class WorkerArgs(unittest.TestCase):
def test_keeps_every_review_on_the_projects_rung_while_the_worker_runs_below_it(self):
opus = Rung("claude-opus-5-5", "medium")
below = prompts.fresh("Do it.", "## Goals", Route(Rung("claude-sonnet-5-5", "high"), 3, 2, 4), LADDER, opus, self.FACTS)
self.assertIn(f"item 3's L of 2. Launch each reviewer, each comprehension seat and the security pass's subagent with the Agent tool set to model opus, effort medium, the project's rung.{self.SCAN} Your rung is below the project's: launch each subagent that files or scores todo.md items on the rung `~/.claude/bin/subagent-rung --plan claude-opus-5-5 <L>` prints. Where an item you take into the chunk has an E + I of 5 or more, launch each reviewer with the Agent tool set to `model fable, effort low` from 5, `model fable, effort medium` from 6, `model opus, effort xhigh` from 7 and `model fable, effort high` from 8. When an escalation trigger", below)
self.assertIn(f"item 3's L of 2. Launch each reviewer, each comprehension seat and the security pass's subagent with the Agent tool set to model opus, effort medium, the project's rung.{self.SCAN} Your rung is below the project's: launch each subagent that files or scores plan items on the rung `~/.claude/bin/subagent-rung --plan claude-opus-5-5 <L>` prints. Where an item you take into the chunk has an E + I of 5 or more, launch each reviewer with the Agent tool set to `model fable, effort low` from 5, `model fable, effort medium` from 6, `model opus, effort xhigh` from 7 and `model fable, effort high` from 8. When an escalation trigger", below)
self.assertNotIn("Launch each", prompts.fresh("Do it.", "## Goals", Route(opus, 3, 3, 4), LADDER, opus, self.FACTS))
def test_launches_reviewers_on_the_rung_the_items_e_plus_i_picks_above_the_workers(self):
+7 -5
View File
@@ -66,7 +66,7 @@ def listed(session: str, run: Tmux) -> list[Listed]:
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."""
"""Starts command in a new window of window's session, in cwd with env added to its environment, and leaves the client where it is. first makes the session too. A Failure says why tmux started none, or why it could not mark a session it made as this checkout's."""
make = ["new-session", "-d", "-s", window.session] if first else ["new-window", "-d", "-t", f"={window.session}:"]
variables = [flag for name, value in env.items() for flag in ("-e", f"{name}={value}")]
# tmux reads a `;` that ends an argument as the end of the command, unless a backslash precedes it.
@@ -74,11 +74,13 @@ def start_window(window: Window, cwd: str, env: typing.Mapping[str, str], comman
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.
# set-option and show-options read a target as a pane's, so `=session` alone names no session.
owned = run(["set-option", "-t", f"={window.session}:", OWNER, cwd]) if first else None
# By the ID, since a window of the same name may still be closing. A failed remain-on-exit doesn't matter: a loop that fails before it is set closes its window, and its stop is still sent as a DM.
run(["set-option", "-w", "-t", done.stdout.strip(), "remain-on-exit", "failed"])
# Without the owner, start_chunks cannot tell this checkout's session from another's, so no further chunk may start in it.
if owned is not None and owned.returncode:
return Failure(f"tmux started the session {window.session} but could not mark it as this checkout's: {owned.stderr.strip() or f'it exited {owned.returncode}'}")
return None
+1 -1
View File
@@ -6,7 +6,7 @@ from claude_code.tokens import Tokens
@dataclasses.dataclass(frozen=True)
class TakenIn:
"""The levels of the todo.md items the worker names on its latest `Chunk items:` line, as cycle.chunk_items reads them. The item the chunk was routed on counts only where the worker names it."""
"""The highest L, and the highest E + I, among the plan items the worker names on its latest `Chunk items:` line, as cycle.chunk_items reads them. The item the chunk was routed on counts only where the worker names it."""
# The highest L among them, 0 for none: an escalation steps up from the rung that L picks, and an unfinished verdict also raises the worker to it.
highest_likelihood: int = 0
# The highest E + I among them, 0 for none: after an unfinished verdict, it routes the next cycle's reviewers.
+1 -1
View File
@@ -3,7 +3,7 @@ import dataclasses
import json
import typing
from release_plan.todo_table import LEVELS
from plan.todo_table import LEVELS
from model_routing.ladder import REVIEW_STEPS, Rung
# How a worker opens the prompt of a subagent it escalates a task to, `Escalation trigger 2: …`: docs/decisions.md → `routing: a worker hands a task one rung up`.
+1 -1
View File
@@ -4,7 +4,7 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from release_plan.todo_table import LEVELS
from plan.todo_table import LEVELS
from model_routing.ladder_file import read_ladder, SHIPPED
from review_rules.review_passes import REVIEWERS
from model_routing.ladder import Rung, WORKER_STEPS
+6 -7
View File
@@ -3,12 +3,11 @@ import dataclasses
import pathlib
import typing
from project_config.settings import CONFIG, Notifier, NOTIFIER, NOTIFIERS, ProjectConfig
from failure import Failure
from rest_client.json_request import Http
from project_config.main import located
import mattermost_dm.dm
from project_config.settings import Notifier, NOTIFIER, NOTIFIERS, ProjectConfig
import slack_dm.dm
from notifier import mattermost, slack
# Sends one message, with the credentials already read.
Sender = typing.Callable[[str], Failure | None]
@@ -25,8 +24,8 @@ class Backend[C]:
# The one place each notifier is wired to the network: a caller that tests a send passes a table with its own `http`.
BACKENDS: dict[Notifier, Backend[typing.Any]] = {
"mattermost": Backend(mattermost_dm.dm.read_config, mattermost_dm.dm.send, mattermost_dm.dm.http_json, mattermost_dm.dm.KEYS),
"slack": Backend(slack_dm.dm.read_config, slack_dm.dm.send, slack_dm.dm.http_json, slack_dm.dm.KEYS),
"mattermost": Backend(mattermost.read_config, mattermost.send, mattermost.http_json, mattermost.KEYS),
"slack": Backend(slack.read_config, slack.send, slack.http_json, slack.KEYS),
}
assert tuple(BACKENDS) == NOTIFIERS
@@ -34,9 +33,9 @@ assert tuple(BACKENDS) == NOTIFIERS
def sender_of(project: ProjectConfig, backends: typing.Mapping[Notifier, Backend[typing.Any]]) -> Sender | Failure:
"""A sender through the project's notifier in backends, with the credentials in its env file read. A Failure where the project names no notifier or its env file cannot be used."""
if project.notifier is None:
return Failure(f"{project.folder / 'config.toml'} sets no `{NOTIFIER}`; set `notifier` to {' or '.join(NOTIFIERS)}, and `env-file` to the file that holds that service's keys ({'; '.join(f'{name}: {', '.join(backend.keys)}' for name, backend in backends.items())})")
return Failure(f"{project.folder / CONFIG} sets no `{NOTIFIER}`; set `notifier` to {' or '.join(NOTIFIERS)}, and `env-file` to the file that holds that service's keys ({'; '.join(f'{name}: {', '.join(backend.keys)}' for name, backend in backends.items())})")
if project.env_file is None:
return Failure(f"{project.folder / 'config.toml'} sets `{NOTIFIER}` but no `env-file`, the file that holds its credentials")
return Failure(f"{project.folder / CONFIG} sets `{NOTIFIER}` but no `env-file`, the file that holds its credentials")
backend = backends[project.notifier]
config = backend.read_config(project.env_file)
if isinstance(config, Failure):
@@ -6,7 +6,7 @@ import unittest.mock
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from mattermost_dm import dm
from notifier import mattermost as dm
from failure import Failure
CONFIG = dm.Config("https://chat.example", "secret-token", "lilleman")
+2 -2
View File
@@ -16,9 +16,9 @@ from rest_client.json_request import Http
from test_env import isolated_env
from project_config.main import located
from notifier import main, notify
from mattermost_dm.test_mattermost_dm import mattermost
from notifier.test_mattermost import mattermost
from project_config.settings import Notifier
from slack_dm.test_slack_dm import Slack
from notifier.test_slack import Slack
from loop_effects.effects import system_effects
TOOL = pathlib.Path(__file__).resolve().parents[1] / "notify"
@@ -6,7 +6,7 @@ import unittest.mock
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from slack_dm import dm
from notifier import slack as dm
from failure import Failure
CONFIG = dm.Config("xoxb-secret", "U0123ABCD")
@@ -3,8 +3,8 @@ import dataclasses
import graphlib
from failure import Failure
from release_plan.todo_table import Item
from release_plan.release import version
from plan.todo_table import Item
from plan.release import version
def blockers_first(scored: list[tuple[Item, float]]) -> list[tuple[Item, float]] | Failure:
@@ -1,7 +1,7 @@
import re
from failure import Failure
from release_plan.todo_table import Item
from plan.todo_table import Item
def check_citations(items: list[Item], decisions: str) -> Failure | None:
@@ -4,7 +4,7 @@ import decimal
import re
import typing
from release_plan.todo_table import CODE_HEALTH
from plan.todo_table import CODE_HEALTH
from failure import Failure
from text_files.markdown_text import sections
@@ -7,15 +7,15 @@ import math
import re
import typing
from release_plan.todo_table import BLOCKED_BY, cells, CODE_HEALTH, DETAILS, Exempt, HEADER_START, Item, item_details, items_table, MOVES, OLD_SHAPE, parse_row, renames, risk, Shape, SHAPE, shape_of, Table, table_rows
from release_plan.blockers import blocked_through, blockers_first
from release_plan.citations import check_citations
from release_plan.formula import evaluate, parse_formula
from plan.todo_table import BLOCKED_BY, cells, CODE_HEALTH, detail_heading, DETAILS, Exempt, HEADER_START, Item, item_details, items_table, MOVES, OLD_SHAPE, parse_row, renames, risk, row_cells, Shape, SHAPE, shape_of, Table, table_rows, tagline_text
from plan.blockers import blocked_through, blockers_first
from plan.citations import check_citations
from plan.formula import evaluate, parse_formula
from failure import Failure
from release_plan.goals_file import goal_weights, Mark, ranked_goals
from plan.goals_file import goal_weights, Mark, ranked_goals
from review_rules.comprehension_history import latest_overall
from text_files.markdown_text import listed
from release_plan.release import version
from plan.release import version
# What a point of an item's move on a maintain goal is worth. A defect that restores the goal weighs it at least this much per point. docs/decisions.md records the choice and its data.
MAINTAIN_WEIGHT = 0.5
@@ -331,7 +331,7 @@ def cited_goals_failure(item: Item, scoring: Scoring, name: str = "") -> Failure
def render_item(item: Item, value: float, shape: Shape, columns: tuple[str, ...]) -> str:
"""The item's row, each cell under its column."""
written = {"ID": str(item.id), "Release": version(item.release), BLOCKED_BY: ", ".join(map(str, item.blocked_by)), "Exempt": item.exempt, "Item": item.tagline, **{name: str(score) for name, score in item.scores.items()}, shape.goals_column: shape.write_goals(item.moves), "Score": f"{value:.1f}"}
written = row_cells(item, shape) | {"Score": f"{value:.1f}"}
return "| " + " | ".join(written[column] for column in columns) + " |"
@@ -342,7 +342,7 @@ def rank_details(text: str, items: list[Item]) -> str | Failure:
return details if isinstance(details, Failure) else text
if unknown := sorted(set(details) - {item.id for item in items}):
return Failure(f"## Details holds item {', '.join(map(str, unknown))}, which the items table does not")
headed = [f"### {item.id}. {item.tagline.strip('*').replace(chr(92) + '|', '|')}\n\n{details[item.id]}\n" for item in items if item.id in details]
headed = [f"{detail_heading(item.id, tagline_text(item.tagline))}\n\n{details[item.id]}\n" for item in items if item.id in details]
ranked = "\n" + "\n".join(headed) if headed else "\n"
tail = "\n" if section.end() < len(text) else ""
return text[:section.start(1)] + ranked + tail + text[section.end():]
@@ -10,6 +10,9 @@ VERSION = r"[0-9]+\.[0-9]+\.[0-9]+"
DATE_DIGITS = (4, 2, 2)
DATED = re.compile(rf"({VERSION}) - " + "-".join(f"[0-9]{{{digits}}}" for digits in DATE_DIGITS))
TAG = re.compile(rf"v({VERSION})")
# The title of CHANGELOG.md's section for news not yet released: Unreleased, or a title that says unreleased, such as `0.6.0 (unreleased)`, as a project's own changelog may head it; and its ## heading.
UNRELEASED_TITLE = r"(?i:.*unreleased.*)"
UNRELEASED_HEADING = re.compile(rf"^## {UNRELEASED_TITLE}$", re.M)
def release_of(version: str) -> Release:
@@ -5,10 +5,10 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from release_plan.test_ranking import DECISIONS, README, TODO
from plan.test_ranking import DECISIONS, README, TODO
from project_config.settings import DEFAULT_FLOOR
from failure import Failure
from release_plan import ranking, todo_table
from plan import ranking, todo_table
class Blockers(unittest.TestCase):
@@ -4,10 +4,10 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from release_plan.test_ranking import DECISIONS, README, TODO
from plan.test_ranking import DECISIONS, README, TODO
from project_config.settings import DEFAULT_FLOOR
from failure import Failure
from release_plan import ranking
from plan import ranking
class Formula(unittest.TestCase):
@@ -1,7 +1,7 @@
import unittest
from failure import Failure
from release_plan.goals_file import section
from plan.goals_file import section
GOALS_FILE = "# P\n## Goals\n1. g\n## Audience\nme\n"
@@ -4,7 +4,7 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from release_plan.named_code import named_files, named_paths
from plan.named_paths import named_files, named_paths
class NamedPaths(unittest.TestCase):
@@ -12,10 +12,11 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from project_config.test_project_config import configured
from project_config.settings import DEFAULT_FLOOR
from failure import Failure
from release_plan import goals_file, plan_file, ranking
from plan_store.stores import file_plan
from plan import goals_file, ranking
from project_config.main import located
from repo_checks import ROOT
from release_plan import todo_table
from plan import todo_table
# Voids code health, so these tests weigh only the project's own goals; class CodeHealth weighs it.
VOID = "**Void:** code health, since a test project has no code to read.\n\n"
@@ -378,7 +379,7 @@ class CodeHealth(unittest.TestCase):
pathlib.Path(temp, "docs").mkdir()
pathlib.Path(temp, "docs", "comprehension-history.md").write_text(SCORED.format(overall="7.00"))
with contextlib.redirect_stderr(io.StringIO()):
ranked = plan_file.rank_file(todo, located(temp, pathlib.Path.home()))
ranked = file_plan(located(temp, pathlib.Path.home()), todo).rank()
self.assertIsInstance(ranked, ranking.Ranked)
self.assertEqual(ranked.under_bar, [])
self.assertIn("| code health by 1 | 25.4 |", todo.read_text())
@@ -395,10 +396,10 @@ class CodeHealth(unittest.TestCase):
pathlib.Path(temp, "docs").mkdir()
pathlib.Path(temp, "docs", "comprehension-history.md").write_text(SCORED.format(overall="6.50"))
with contextlib.redirect_stderr(io.StringIO()):
ranked = plan_file.rank_file(todo, located(temp, pathlib.Path.home()))
ranked = file_plan(located(temp, pathlib.Path.home()), todo).rank()
self.assertIsInstance(ranked, ranking.Ranked)
self.assertIn("| code health by 1 | 25.4 |", todo.read_text())
self.assertEqual(plan_file.check_failures(todo, located(temp, pathlib.Path.home())), [])
self.assertEqual(file_plan(located(temp, pathlib.Path.home()), todo).check(), [])
class Risk(unittest.TestCase):
@@ -7,7 +7,7 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from test_env import isolated_env
from release_plan.release import newest_tag, tagged
from plan.release import newest_tag, tagged
class NewestTag(unittest.TestCase):
@@ -4,7 +4,7 @@ import typing
from failure import Failure
from text_files.markdown_text import FENCE, sections
from release_plan.release import parsed, Release, release_of, VERSION
from plan.release import parsed, Release, release_of, version, VERSION
# Each score a Shape names, and each goal's move, runs from 1 to TOP_SCORE, but for the levels L, E and I, which run from 1 to their LEVELS: ~/.claude/rules/todo-items.md defines each level.
TOP_SCORE = 10
@@ -43,7 +43,7 @@ class Shape:
risk_columns: tuple[str, ...]
# The scores rank_todo.py works out and writes, so a blank cell reads as no score yet.
derived: tuple[str, ...]
# The column naming the goals an item serves; read_goals reads it, given the item's ID to name in a failure, and write_goals writes it back.
# The column naming the goals an item serves; read_goals reads it, given what a failure calls the item, and write_goals writes it back.
goals_column: str
read_goals: typing.Callable[[str, str], Moves | Failure]
write_goals: typing.Callable[[Moves], str]
@@ -59,17 +59,17 @@ class Shape:
return tuple(column for column in self.columns if column not in self.optional)
def parse_moves(id_: str, cell: str) -> Moves | Failure:
def parse_moves(label: str, cell: str) -> Moves | Failure:
"""A Moves cell: empty, or each goal the item moves, named once, and how far. ranking.py's cited_goals_failure holds the rules that need the goals file."""
matches = [re.fullmatch(rf"([0-9]+(?:\.[0-9]+)*|{CODE_HEALTH}) by ([0-9]+)", move) for move in cell.split(", ")] if cell else []
moves = tuple((match.group(1), int(match.group(2))) for match in matches if match)
if len(moves) < len(matches) or any(not 1 <= by <= TOP_SCORE for _, by in moves):
return Failure(f"item {id_}'s {MOVES} {cell!r} is not empty or goals such as `1.1 by 8, {CODE_HEALTH} by 5`, each moved by a whole number from 1 to {TOP_SCORE}")
return Failure(f"{label}'s {MOVES} {cell!r} is not empty or goals such as `1.1 by 8, {CODE_HEALTH} by 5`, each moved by a whole number from 1 to {TOP_SCORE}")
goals = [goal for goal, _ in moves]
if repeated := [goal for goal in goals if goals.count(goal) > 1]:
return Failure(f"item {id_} cites goal {repeated[0]} twice; name each goal once")
return Failure(f"{label} cites goal {repeated[0]} twice; name each goal once")
if nested := [(parent, goal) for parent in goals for goal in goals if goal.startswith(parent + ".")]:
return Failure(f"item {id_} names goal {nested[0][0]} and its sub-goal {nested[0][1]}; name one, never both: the sub-goal where the move serves it, else the parent")
return Failure(f"{label} names goal {nested[0][0]} and its sub-goal {nested[0][1]}; name one, never both: the sub-goal where the move serves it, else the parent")
return moves
@@ -77,7 +77,7 @@ def write_moves(moves: Moves) -> str:
return ", ".join(f"{goal} by {by}" for goal, by in moves)
def parse_cited(id_: str, cell: str) -> Moves:
def parse_cited(label: str, cell: str) -> Moves:
"""An old-shape Goals cell, such as `2.1, 1`: each goal it cites, with no move."""
return tuple((goal.strip(), None) for goal in cell.split(","))
@@ -268,49 +268,64 @@ def parse_row(row: str, table: Table) -> Item | Failure:
if isinstance(found, Failure):
return found
named = dict(zip(table.columns, found))
exempt = check_cells(row, named)
if isinstance(exempt, Failure):
return exempt
id_, tagline = named["ID"], named["Item"]
if not re.fullmatch(r"[0-9]+", id_) or int(id_) < 1:
return Failure(f"the ID {id_!r} is not a positive whole number: {row}")
if not re.fullmatch(r"\*\*[^*].*[^*]\*\*", tagline):
return Failure(f"item {id_}'s Item cell is not one bold tagline: {tagline}")
shape = shape_of(table.columns)
scores = parse_scores(named["ID"], {name: cell for name, cell in named.items() if cell or name not in shape.derived}, shape.score_columns)
fields = item_fields({name: cell for name, cell in named.items() if cell or name not in shape.derived}, f"item {id_}", shape, int(id_))
if isinstance(fields, Failure):
return fields
assert fields.release is not None, "table_rows refuses a table without a Release column"
return Item(int(id_), fields.release, fields.exempt, tagline, fields.scores, fields.moves, fields.blocked_by)
@dataclasses.dataclass(frozen=True)
class ItemFields:
"""The cells of an item that a caller named, each held to the items table's format. A cell it didn't name reads as empty, and the release as None."""
release: Release | None = None
exempt: Exempt = ""
scores: dict[str, int] = dataclasses.field(default_factory=dict)
moves: Moves = ()
blocked_by: tuple[int, ...] = ()
def item_fields(named: dict[str, str], label: str, shape: Shape = SHAPE, id_: int | None = None) -> ItemFields | Failure:
"""Each of the Release, Exempt, score, goals and Blocked-by cells that named holds by column name, held to shape's format; the one check every plan backend makes of an item's cells. label opens each message, such as "item 12" or "the item to file". id_ is the item's own ID, which its Blocked by may not name."""
release = named.get("Release")
if release is not None and parsed(release) is None:
return Failure(f"{label}'s Release {release!r} is not a semver version, such as 1.2.0")
exempt = named.get("Exempt", "")
if not is_exempt(exempt):
return Failure(f"{label}'s Exempt {exempt!r} is not empty or one of {', '.join(EXEMPTIONS[1:])}")
scores = parse_scores(label, named, shape.score_columns)
if isinstance(scores, Failure):
return scores
blocked_by = parse_blockers(named["ID"], named.get(BLOCKED_BY, ""))
if isinstance(blocked_by, Failure):
return blocked_by
moves = shape.read_goals(named["ID"], named[shape.goals_column])
moves = shape.read_goals(label, named.get(shape.goals_column, ""))
if isinstance(moves, Failure):
return moves
return Item(int(named["ID"]), release_of(named["Release"]), exempt, named["Item"], scores, moves, blocked_by)
blocked_by = parse_ids(named.get(BLOCKED_BY, ""))
if blocked_by is None:
return Failure(f"{label}'s {BLOCKED_BY} {named[BLOCKED_BY]!r} is not empty or IDs separated by \", \"")
if id_ in blocked_by:
return Failure(f"{label} is blocked by itself; drop {id_} from its {BLOCKED_BY}")
return ItemFields(None if release is None else release_of(release), exempt, scores, moves, blocked_by)
def is_exempt(cell: str) -> typing.TypeGuard[Exempt]:
return cell in EXEMPTIONS
def check_cells(row: str, named: dict[str, str]) -> Exempt | Failure:
"""Holds the row's ID, Release, Exempt and Item cells to the format: the row's Exempt cell, or why a cell breaks it."""
id_, release, exempt, tagline = named["ID"], named["Release"], named["Exempt"], named["Item"]
if not re.fullmatch(r"[0-9]+", id_) or int(id_) < 1:
return Failure(f"the ID {id_!r} is not a positive whole number: {row}")
if parsed(release) is None:
return Failure(f"item {id_}'s release {release!r} is not a semver version")
if not is_exempt(exempt):
return Failure(f"item {id_}'s Exempt {exempt!r} is not empty or one of {', '.join(EXEMPTIONS[1:])}")
if not re.fullmatch(r"\*\*[^*].*[^*]\*\*", tagline):
return Failure(f"item {id_}'s Item cell is not one bold tagline: {tagline}")
return exempt
def parse_scores(id_: str, named: dict[str, str], names: tuple[str, ...]) -> dict[str, int] | Failure:
"""Each score in names that the row holds; only an optional one may be missing, since the table holds every needed column."""
def parse_scores(label: str, named: dict[str, str], names: tuple[str, ...]) -> dict[str, int] | Failure:
"""Each score in names that named holds; only an optional one may be missing, since the table holds every needed column."""
scores: dict[str, int] = {}
for name in names:
if name not in named:
continue
top = LEVELS.get(name, TOP_SCORE)
if not re.fullmatch(r"[0-9]+", named[name]) or not 1 <= int(named[name]) <= top:
return Failure(f"item {id_}'s {name} {named[name]!r} is not a whole number from 1 to {top}")
return Failure(f"{label}'s {name} {named[name]!r} is not a whole number from 1 to {top}")
scores[name] = int(named[name])
return scores
@@ -322,10 +337,21 @@ def parse_ids(cell: str) -> tuple[int, ...] | None:
return tuple(int(id_) for id_ in cell.split(", ") if id_)
def parse_blockers(id_: str, cell: str) -> tuple[int, ...] | Failure:
blocked_by = parse_ids(cell)
if blocked_by is None:
return Failure(f"item {id_}'s {BLOCKED_BY} {cell!r} is not empty or IDs separated by \", \"")
if int(id_) in blocked_by:
return Failure(f"item {id_} is blocked by itself; drop {id_} from its {BLOCKED_BY}")
return blocked_by
def row_cells(item: Item, shape: Shape) -> dict[str, str]:
"""item's cells by column name, as a row of a table in shape holds them; the Score, which only ranking works out, aside."""
return {"ID": str(item.id), "Release": version(item.release), BLOCKED_BY: ", ".join(map(str, item.blocked_by)), "Exempt": item.exempt, "Item": item.tagline, **{name: str(score) for name, score in item.scores.items()}, shape.goals_column: shape.write_goals(item.moves)}
def tagline_text(cell: str) -> str:
"""The tagline an Item cell holds, as plain text: without the bold, each | unescaped."""
return cell.strip().removeprefix("**").removesuffix("**").replace("\\|", "|")
def detail_heading(id_: int, tagline: str) -> str:
"""The heading under ## Details that opens item id_'s detail; tagline is plain text."""
return f"### {id_}. {tagline}"
def items_shape(found: list[Item]) -> Shape:
"""The shape a table of found needs: OLD_SHAPE where an item holds a score only that shape has, as a plan not yet reshaped does."""
return OLD_SHAPE if any(set(item.scores) - set(SHAPE.score_columns) for item in found) else SHAPE
+3 -3
View File
@@ -1,10 +1,10 @@
"""What every plan backend must hold, as tests. A backend's test case inherits PlanStoreContract and unittest.TestCase, and builds its store in new_store. record_store.contract is its twin for records."""
import typing
from release_plan.todo_table import BLOCKED_BY, Item, MOVES
from plan.todo_table import BLOCKED_BY, Item, MOVES
from failure import Failure
from plan_store.stores import Plan, PlanStore, TAGLINE, Written
from release_plan.release import release_of
from plan_store.plans import Plan, PlanStore, TAGLINE, Written
from plan.release import release_of
FIRST = {"Release": "0.1.0", TAGLINE: "Count the runs.", "L": "1", "E": "2", "I": "3", "S": "1", MOVES: "1 by 9"}
SECOND = {"Release": "0.2.0", TAGLINE: "Ship the later thing.", "L": "2", "E": "1", "I": "1", "S": "2", MOVES: "1 by 8", "Exempt": "owner"}
+4 -4
View File
@@ -2,9 +2,9 @@
import dataclasses
from plan_store.markdown_edits import bold_cell, plain
from plan_store.stores import cells, Plan, Written
from plan_store.plans import cells, no_item, Plan, Written
from failure import Failure
from release_plan.todo_table import Item, parse_row, SHAPE, Table
from plan.todo_table import Item, parse_row, SHAPE, Table
@dataclasses.dataclass
@@ -30,7 +30,7 @@ class MemoryPlan:
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 Failure(no_item(self.label, id_))
written = self.put(id_, self.rows[id_] | cells(fields), self.details.get(id_, "") if detail is None else detail)
if comment is not None and isinstance(written, Written):
self.comments.setdefault(id_, []).append(comment)
@@ -38,7 +38,7 @@ class MemoryPlan:
def finish(self, id_: int) -> Written | Failure:
if self.fails or id_ not in self.rows:
return Failure(self.fails or f"{self.label} holds no item {id_}")
return Failure(self.fails or no_item(self.label, id_))
del self.rows[id_]
self.details.pop(id_, None)
return Written(id_)
+67 -110
View File
@@ -3,30 +3,24 @@
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 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
import re
import typing
from adf_codec.convert import adfs_to_markdown, markdown_to_adf, Refused
from release_plan.todo_table import BLOCKED_BY, EXEMPTIONS, is_exempt, Item, MOVES, parse_ids, parse_moves, parse_scores, SHAPE
from atlassian.client import basic_auth, Http, jira_json, ToAdf, ToMarkdown
from plan.todo_table import BLOCKED_BY, Item, item_fields, ItemFields, MOVES, SHAPE
from plan_store.markdown_edits import bold_cell, plain, unfit_text
from plan_store.stores import cells, Plan, Written
from plan_store.plans import cells, no_item, Plan, Written
from project_config.settings import Epic, Finish, JIRA_FINISH_STATUS, JIRA_FINISH_TRANSITION
from failure import Failure
from rest_client import json_request
from release_plan.release import parsed, Release, tagged
from release_plan import ranking
from rest_client.env_file import read_env
from plan.release import parsed, Release, tagged
from plan import ranking
# One pair of keys for Jira and Confluence: one Atlassian account's API token opens both.
KEYS = ("ATLASSIAN_EMAIL", "ATLASSIAN_API_TOKEN")
# The issue property that holds an item's scores, as a JSON object such as {"L": 2, "E": 2, "I": 3, "S": 3, "Moves": "1.6 by 4", "Exempt": ""}.
PROPERTY = "plan-item"
ISSUE_KEY = re.compile(r"([A-Z][A-Z0-9_]*)-([0-9]+)")
# Seconds each connect and each read may wait.
TIMEOUT = 30
PAGE = 100
# The pages one read asks for at most, so an answer that never names a last page ends the read.
MAX_PAGES = 100
@@ -50,30 +44,12 @@ SET_SCORES = tuple(name for name in SHAPE.score_columns if name not in SHAPE.der
# 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]
ToMarkdown = typing.Callable[[list[dict[str, typing.Any]]], list[str] | Refused | Failure]
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)
def error_message(answer: object) -> str:
"""Jira's messages in the JSON of an error answer; empty where it holds none."""
if not isinstance(answer, dict):
return ""
messages, errors = answer.get("errorMessages"), answer.get("errors")
found = [*(messages if isinstance(messages, list) else []), *(errors.values() if isinstance(errors, dict) else [])]
return "; ".join(text for text in found if isinstance(text, str))
@dataclasses.dataclass(frozen=True)
class Issue:
"""A child issue as Jira answered it, checked to hold what an item is read from."""
@@ -84,7 +60,7 @@ class Issue:
# The key of each issue this one "is blocked by".
blockers: tuple[str, ...]
# PROPERTY's value; an empty object where the issue holds none.
scores: object
scores: dict[str, typing.Any]
@property
def number(self) -> int:
@@ -96,7 +72,7 @@ class JiraPlan:
"""The plan under epic, read and written with the credentials env_file holds."""
epic: Epic
env_file: pathlib.Path
http: Http = http_json
http: Http = jira_json
to_markdown: ToMarkdown = adfs_to_markdown
to_adf: ToAdf = markdown_to_adf
# How a finished item moves; None where the config doesn't say, and then `finish` is a Failure.
@@ -138,12 +114,10 @@ class JiraPlan:
authorization = basic_auth(self.env_file)
if isinstance(authorization, Failure):
return authorization
issue_fields = filing.fields
if detail.strip():
description = self.to_adf(detail)
if isinstance(description, Failure):
return Failure(f"cannot convert the item's detail to a Jira description: {description.reason}")
issue_fields = issue_fields | {"description": description}
description = self.description_of(detail)
if isinstance(description, Failure):
return description
issue_fields = filing.fields | ({"description": description} if description else {})
version = self.fix_version(filing.release, authorization)
if isinstance(version, Failure):
return version
@@ -195,6 +169,22 @@ class JiraPlan:
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 name a release it has")
def child(self, id_: int, authorization: str) -> dict[str, typing.Any] | Failure:
"""Item id_'s issue, as the epic's open children answer it; a Failure where none of them is item id_."""
answered = children(self.epic, authorization, self.http)
if isinstance(answered, Failure):
return answered
key = f"{project_of(self.epic.key)}-{id_}"
found = next((raw for raw in answered if isinstance(raw, dict) and raw.get("key") == key), None)
return Failure(no_item(self.label, id_)) if found is None else found
def description_of(self, detail: str) -> dict[str, typing.Any] | None | Failure:
"""The Jira description that holds detail, as ADF; None for a blank detail, which leaves an issue without one."""
if not detail.strip():
return None
description = self.to_adf(detail)
return Failure(f"cannot convert the item's detail to a Jira description: {description.reason}") if isinstance(description, Failure) else description
def edit(self, id_: int, fields: dict[str, str], detail: str | None, comment: str | None = None) -> Written | Failure:
"""Sets the fields and the detail in one request, so Jira takes all of the edit or none, and then posts comment on the issue. `revision_of` says what an edit may set.
@@ -202,24 +192,21 @@ class JiraPlan:
authorization = basic_auth(self.env_file)
if isinstance(authorization, Failure):
return authorization
answered = children(self.epic, authorization, self.http)
if isinstance(answered, Failure):
return answered
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_}")
raw = self.child(id_, authorization)
if isinstance(raw, Failure):
return raw
issue = issue_of(raw)
if isinstance(issue, Failure):
return issue
key = issue.key
revision = revision_of(issue, cells(fields), detail, comment)
if isinstance(revision, Failure):
return revision
body = revision.body
if detail is not None:
description = self.to_adf(detail) if detail.strip() else None
description = self.description_of(detail)
if isinstance(description, Failure):
return Failure(f"cannot convert the item's detail to a Jira description: {description.reason}")
return description
body = body | {"fields": body.get("fields", {}) | {"description": description}}
said = self.to_adf(comment) if comment and comment.strip() else None
if isinstance(said, Failure):
@@ -245,12 +232,10 @@ class JiraPlan:
authorization = basic_auth(self.env_file)
if isinstance(authorization, Failure):
return authorization
answered = children(self.epic, authorization, self.http)
if isinstance(answered, Failure):
return answered
raw = self.child(id_, authorization)
if isinstance(raw, Failure):
return raw
key = f"{project_of(self.epic.key)}-{id_}"
if not any(isinstance(raw, dict) and raw.get("key") == key for raw in answered):
return Failure(f"{self.label} holds no item {id_}")
url = f"{self.epic.site}/rest/api/3/issue/{key}/transitions"
offered = self.http("GET", url, authorization, None)
if isinstance(offered, Failure):
@@ -285,27 +270,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", "")
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(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, ""))
if blockers is None:
return Failure(f"the item's {BLOCKED_BY} {named[BLOCKED_BY]!r} is not empty or IDs separated by \", \"")
checked = item_fields(named | {"Release": release}, "the item to file")
if isinstance(checked, Failure):
return checked
assert checked.release is not None, "item_fields refuses an empty Release"
project = project_of(epic.key)
issue_fields: dict[str, typing.Any] = {"project": {"key": project}, "parent": {"key": epic.key}, "issuetype": {"name": ISSUE_TYPE}, "summary": summary}
if exempt == SECURITY:
if checked.exempt == SECURITY:
issue_fields["labels"] = [SECURITY]
value = levels | {MOVES: moves, "Exempt": exempt, FILED_BY[0]: FILED_BY[1]}
return Filing(issue_fields, release, value, tuple(f"{project}-{blocker}" for blocker in blockers), Item(0, version, exempt, summary, levels, parsed_moves, blockers))
value = checked.scores | {MOVES: named.get(MOVES, ""), "Exempt": checked.exempt, FILED_BY[0]: FILED_BY[1]}
return Filing(issue_fields, release, value, tuple(f"{project}-{blocker}" for blocker in checked.blocked_by), Item(0, checked.release, checked.exempt, summary, checked.scores, checked.moves, checked.blocked_by))
def filed_score(item: Item, scoring: ranking.Scoring) -> float | Failure:
@@ -327,19 +301,18 @@ def placing(answered: list[object], new: Item, value: float, scoring: ranking.Sc
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]:
if 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):
if missing := next((name for name in SET_SCORES if name not in scored.scores), None):
return Failure(f"{issue.key} holds no {missing}")
# Only the scores and the moves change a score.
other = ranking.item_score(dataclasses.replace(new, scores=levels, moves=moves), scoring, issue.key)
other = ranking.item_score(dataclasses.replace(new, scores=scored.scores, moves=scored.moves), scoring, issue.key)
if isinstance(other, Failure):
return other
if (ranking.FIRST.get(exempt, len(ranking.FIRST)), -other) > place:
if (ranking.FIRST.get(scored.exempt, len(ranking.FIRST)), -other) > place:
return issue.key
return None
@@ -358,8 +331,6 @@ def revision_of(issue: Issue, named: dict[str, str], detail: str | None, comment
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]
@@ -376,21 +347,19 @@ def revision_of(issue: Issue, named: dict[str, str], detail: str | None, comment
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 isinstance(checked := item_fields({name: named[name] for name in ("Release", "Exempt") if name in named}, f"item {issue.key}"), Failure):
return checked
if any(name in named for name in SCORED):
texts = {name: str(value) for name, value in held.items()} | {name: named[name] for name in SCORED if name in named}
scored = scores(issue.key, texts)
if isinstance(scored, Failure):
return scored
if scored[0] and any(name not in scored[0] for name in SET_SCORES):
if scored.scores and any(name not in scored.scores for name in SET_SCORES):
return Failure(f"{issue.key} would hold some of {', '.join(SET_SCORES)} and not the rest: set them together")
value = held | scored[0] | {MOVES: texts.get(MOVES, ""), "Exempt": scored[2]}
value = held | scored.scores | {MOVES: texts.get(MOVES, ""), "Exempt": scored.exempt}
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}]}
if own and (scored.exempt == SECURITY) != (held.get("Exempt") == SECURITY):
body["update"] = {"labels": [{"add" if scored.exempt == SECURITY else "remove": SECURITY}]}
return Revision(body, release)
@@ -428,14 +397,6 @@ def project_of(key: str) -> str:
return key.rpartition("-")[0]
def basic_auth(env_file: pathlib.Path) -> str | Failure:
"""The Authorization header for the email and API token that env_file holds."""
values = read_env(env_file, KEYS, "an API token")
if isinstance(values, Failure):
return values
return "Basic " + base64.b64encode(":".join(values[key] for key in KEYS).encode()).decode()
def children(epic: Epic, authorization: str, http: Http) -> list[object] | Failure:
"""The epic's open child issues in backlog order, which 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.
@@ -465,14 +426,19 @@ def children(epic: Epic, authorization: str, http: Http) -> list[object] | Failu
def issue_of(raw: object) -> Issue | Failure:
"""The issue in one entry of the search's answer, or which issue is not in the shape Jira documents, and how."""
key = raw.get("key") if isinstance(raw, dict) else None
if not isinstance(key, str) or not ISSUE_KEY.fullmatch(key):
if not isinstance(raw, dict) or not isinstance(key, str) or not ISSUE_KEY.fullmatch(key):
return Failure("the search answered an issue without an issue key")
# The answer's nested fields are read as Jira documents them; one missing or of another type ends the read here, as a Failure, so no later step meets it.
try:
fields = typing.cast(dict[str, typing.Any], raw)["fields"]
fields = raw["fields"]
blockers = tuple(link["inwardIssue"]["key"] for link in fields["issuelinks"] if "inwardIssue" in link and link["type"]["inward"] == "is blocked by")
issue = Issue(key, fields["summary"].strip(), fields["description"], tuple(version["name"] for version in fields["fixVersions"]), blockers, typing.cast(dict[str, typing.Any], raw).get("properties", {}).get(PROPERTY, {}))
held = raw.get("properties", {}).get(PROPERTY, {})
summary, description, versions = fields["summary"].strip(), fields["description"], tuple(version["name"] for version in fields["fixVersions"])
except (AttributeError, KeyError, TypeError) as failure:
return Failure(f"{key} is not in the shape Jira Cloud's REST API version 3 documents: {failure!r}")
if not isinstance(held, dict):
return Failure(f"{key}'s issue property {PROPERTY} is not a JSON object")
issue = Issue(key, summary, description, versions, blockers, held)
if not isinstance(issue.description, dict | None) or not all(isinstance(name, str) for name in issue.fix_versions + issue.blockers) or not all(ISSUE_KEY.fullmatch(blocker) for blocker in issue.blockers):
return Failure(f"{key} is not in the shape Jira Cloud's REST API version 3 documents: its description, a Fix Version's name or a linked issue's key holds another kind of value")
return issue
@@ -518,7 +484,7 @@ def item(issue: Issue, project: str, ids: set[int]) -> Item | Failure:
if isinstance(scored, Failure):
return scored
blockers = {number(key) for key in issue.blockers if project_of(key) == project}
return Item(issue.number, release, scored[2], bold_cell(issue.summary), scored[0], scored[1], tuple(sorted(blockers & ids)), "")
return Item(issue.number, release, scored.exempt, bold_cell(issue.summary), scored.scores, scored.moves, tuple(sorted(blockers & ids)), "")
def earliest_release(names: tuple[str, ...]) -> Release | None:
@@ -527,18 +493,9 @@ def earliest_release(names: tuple[str, ...]) -> Release | None:
return min(releases, default=None)
def scores(key: str, held: object) -> tuple[dict[str, int], typing.Any, typing.Any] | Failure:
def scores(key: str, held: dict[str, typing.Any]) -> ItemFields | Failure:
"""The scores, Moves and Exempt that an issue's PROPERTY value holds, each in the format the items table of a todo.md takes."""
if not isinstance(held, dict):
return Failure(f"{key}'s issue property {PROPERTY} is not a JSON object")
named = {name: str(value) for name, value in held.items()}
levels = parse_scores(key, named, SHAPE.score_columns)
if isinstance(levels, Failure):
return levels
moves = parse_moves(key, named.get(MOVES, ""))
if isinstance(moves, Failure):
return moves
exempt = named.get("Exempt", "")
if not is_exempt(exempt):
return Failure(f"{key}'s issue property {PROPERTY} holds the Exempt {exempt!r}, which is not empty or one of {', '.join(EXEMPTIONS[1:])}")
return levels, moves, exempt
named = {name: str(value) for name, value in held.items() if name in (*SHAPE.score_columns, MOVES, "Exempt")}
checked = item_fields(named, f"item {key}")
# Jira's screens don't show PROPERTY, so the message says where the value is.
return Failure(f"{checked.reason}; {key} holds it in its issue property {PROPERTY}") if isinstance(checked, Failure) else checked
+6 -5
View File
@@ -1,9 +1,10 @@
"""The text edits behind the markdown plan: filing an item in todo.md, changing one and removing one. Each returns new text; ranking.rank then orders the table and details and writes the derived cells."""
import re
from release_plan.todo_table import cells, DETAILS, item_details, items_table, Table
from plan.todo_table import cells, detail_heading, DETAILS, item_details, items_table, Table, tagline_text
from failure import Failure
from release_plan.ranking import stated
from plan_store.plans import no_item
from plan.ranking import stated
# A line that would end ## Details (##) or could open another item's detail (###).
HEADING = re.compile(r"^#{2,3} ", re.M)
@@ -47,7 +48,7 @@ def edited(todo: str, id_: int, named: dict[str, str], detail: str | None, label
if isinstance(details, Failure):
return details
row = dict(zip(table.columns, held))
tagline = plain(named["Item"]) if "Item" in named else plain(row["Item"]).replace("\\|", "|")
tagline = plain(named["Item"]) if "Item" in named else tagline_text(row["Item"])
kept = details.get(id_, "") if detail is None else detail
if unfit := unfit_text(tagline, "" if detail is None else detail):
return unfit
@@ -90,7 +91,7 @@ def with_detail(text: str, id_: int, tagline: str, detail: str) -> str:
"""text with detail first under ## Details, headed by id_ and tagline; text itself where detail is blank."""
if not detail.strip():
return text
entry = f"### {id_}. {tagline}\n\n{detail.strip()}\n"
entry = f"{detail_heading(id_, tagline)}\n\n{detail.strip()}\n"
section = DETAILS.search(text)
if section is None:
return text.rstrip("\n") + f"\n\n## Details\n\n{entry}"
@@ -113,7 +114,7 @@ def row_index(table: Table, id_: int, label: str) -> int | Failure:
return found
if found[0] == str(id_):
return at
return Failure(f"{label} holds no item {id_}")
return Failure(no_item(label, id_))
def held_table(lines: list[str], label: str) -> Table | Failure:
+73
View File
@@ -0,0 +1,73 @@
"""What every plan backend reads and writes: a Plan, a Written, the PlanStore protocol they all meet, and the fields a caller may set on an item."""
import dataclasses
import typing
from plan.todo_table import BLOCKED_BY, Item, MOVES
from failure import Failure
from plan.release import Release
TAGLINE = "Tagline"
# What a caller may set on an item, each as text in the format `rank_todo.py --help` states for the cell of that name. TAGLINE is the Item cell, bold or not.
FIELDS = ("Release", BLOCKED_BY, "Exempt", TAGLINE, "L", "E", "I", "S", MOVES)
@dataclasses.dataclass(frozen=True)
class Plan:
"""A plan as one read found it."""
# Each item with its detail, in the order the backend supplies: by release and then by rank for a markdown file, by backlog rank for a tracker.
items: list[Item]
# The releases the plan marks renamed. Such a release holds no item because its items moved, not because it is finished.
renamed: frozenset[Release] = frozenset()
@dataclasses.dataclass(frozen=True)
class Written:
"""A write that landed."""
id: int
# What the backend says of the plan after the write, for stderr, such as an item now under the bar.
notes: tuple[str, ...] = ()
class PlanStore(typing.Protocol):
"""A project's plan. plan_store.contract holds every backend that writes to the same behaviour; `jira_epic` doesn't hold it yet: it changes no link, and its own tests stand in for Jira. A write that fails leaves the plan as it was, except where its Failure says the tracker may have taken the write all the same, as when Jira's answer to a new issue, an edit or a finish is lost."""
@property
def label(self) -> str:
"""What a message calls the plan, such as its path."""
@property
def tracked(self) -> str | None:
"""The plan's path from the checkout's top, as git names a file in a commit; None where no commit holds a version of it, as for a file outside the checkout or a tracker."""
def read(self) -> Plan | Failure:
"""The plan as it stands. A NoItemsTable where the project has not set one up."""
def add(self, fields: dict[str, str], detail: str) -> Written | Failure:
"""Files an item under an ID the backend picks. fields holds each of FIELDS the caller sets; detail may be empty."""
def edit(self, id_: int, fields: dict[str, str], detail: str | None, comment: str | None = None) -> Written | Failure:
"""Sets item id_'s fields to those given, and its detail unless None, leaving the rest. Moving an item sets its Release.
comment tells the plan's other readers why, in the project's language. A tracker posts it on the item's issue; a backend with no place for comments drops it."""
def finish(self, id_: int) -> Written | Failure:
"""Removes item id_ with its detail."""
def no_item(label: str, id_: int | str) -> str:
"""What every store says of an item id_ that the plan label names doesn't hold. `chunk-pr merge` reads `todo-item show`'s answer by it, through says_no_item."""
return f"{label} holds no item {id_}"
def says_no_item(reason: str, id_: int | str) -> bool:
"""Whether a failure's reason, such as `todo-item show`'s, says the plan doesn't hold item id_, as no_item words it."""
return no_item("", id_) in reason
def cells(fields: dict[str, str]) -> dict[str, str]:
"""fields by the items table's column names."""
unknown = set(fields) - set(FIELDS)
if unknown:
# A programming error, so nothing catches it: a caller takes its fields from FIELDS.
raise ValueError(f"{', '.join(sorted(unknown))}: not a field; the fields are {', '.join(FIELDS)}")
return {"Item" if name == TAGLINE else name: value for name, value in fields.items()}
+39
View File
@@ -0,0 +1,39 @@
"""The goal weights a plan is ranked by, read from the goals file, the decision log and the comprehension history, for the markdown plan and for the scoring of a plan in Jira."""
import dataclasses
import decimal
from failure import Failure
from project_config.settings import JiraScoring
from plan import ranking
from record_store.stores import RecordStore
# What the reader of a missing or empty goals file is told.
GOALS_HINT = "rank_todo.py weighs goals from the goals file the project's config names as goals-and-audience"
@dataclasses.dataclass(frozen=True)
class StatedScoring:
"""The scoring of a plan in Jira: the formula and bar the project's config states, with goal weights that ranking reads from the goals file, the decision log and the comprehension history."""
stated: JiraScoring
goals: RecordStore
decisions: RecordStore
history: RecordStore
floor: decimal.Decimal
def read(self) -> ranking.Scoring | Failure:
weighing = weighing_texts(self.goals, self.decisions, self.history)
return weighing if isinstance(weighing, Failure) else ranking.config_scoring(self.stated.formula, self.stated.bar, *weighing, self.floor)
def weighing_texts(goals: RecordStore, decisions: RecordStore, history: RecordStore) -> tuple[str, str, str] | Failure:
"""What ranking weighs the goals by: the goals file, the decision log and the comprehension history. The last two are empty when missing; a goals file that is missing or empty is a Failure."""
goals_text = goals.read()
if isinstance(goals_text, Failure):
return goals_text
if not goals_text:
return Failure(f"{goals.label}: missing or empty; {GOALS_HINT}")
decisions_text = decisions.read()
if isinstance(decisions_text, Failure):
return decisions_text
history_text = history.read()
return history_text if isinstance(history_text, Failure) else (goals_text, decisions_text, history_text)
+8 -201
View File
@@ -1,182 +1,24 @@
"""The one way a tool reads or writes a project's plan: through the store its config names.
The config's `plan` setting names the backend. A path names a markdown file, todo.md. `jira:` and an epic's address name a Jira epic, whose open child issues are the plan: `jira_epic` reads them, and files an item as a new child issue. An agent reads and changes the plan with `todo-item`, which works through the same store.
The config's `plan` setting names the backend. A path names a markdown file, todo.md, which `todo_md` keeps. `jira:` and an epic's address name a Jira epic, whose open child issues are the plan: `jira_epic` reads them, and files an item as a new child issue. An agent reads and changes the plan with `todo-item`, which works through the same store.
A tool that reads what a past commit held, such as `score-outcomes`, still parses that commit's todo.md itself, with `release_plan.todo_table`: only the markdown backend has commits, and todo.md's items 365, 366 and 368 port those tools to the other backends."""
import dataclasses
import decimal
A tool that reads what a past commit held, such as `score-outcomes`, still parses that commit's todo.md itself, with `plan.todo_table`: only the markdown backend has commits, and todo.md's items 365, 366 and 368 port those tools to the other backends."""
import pathlib
import typing
from release_plan.todo_table import BLOCKED_BY, Item, item_details, items, MOVES, NoItemsTable, renames
from failure import Failure
from git_cli.git_repo import file_at, git, Git
from record_store.stores import goals_store, store as record_store, RecordStore
from project_config.settings import JiraScoring, ProjectConfig
from plan_store import markdown_edits
from release_plan import ranking
from release_plan.release import Release
from text_files.file_writes import replace_file
TAGLINE = "Tagline"
# What a caller may set on an item, each as text in the format `rank_todo.py --help` states for the cell of that name. TAGLINE is the Item cell, bold or not.
FIELDS = ("Release", BLOCKED_BY, "Exempt", TAGLINE, "L", "E", "I", "S", MOVES)
# What the reader of a missing todo.md is told.
MISSING = "every project keeps a todo.md, and rank_todo.py --help shows one"
# What the reader of a missing or empty goals file is told.
GOALS_HINT = "rank_todo.py weighs goals from the goals file the project's config names as goals-and-audience"
@dataclasses.dataclass(frozen=True)
class Plan:
"""A plan as one read found it."""
# Each item with its detail, in the order the backend supplies: by release and then by rank for a markdown file, by backlog rank for a tracker.
items: list[Item]
# The releases the plan marks renamed. Such a release holds no item because its items moved, not because it is finished.
renamed: frozenset[Release] = frozenset()
@dataclasses.dataclass(frozen=True)
class Written:
"""A write that landed."""
id: int
# What the backend says of the plan after the write, for stderr, such as an item now under the bar.
notes: tuple[str, ...] = ()
class PlanStore(typing.Protocol):
"""A project's plan. plan_store.contract holds every backend that writes to the same behaviour; `jira_epic` doesn't hold it yet: it changes no link, and its own tests stand in for Jira. A write that fails leaves the plan as it was, except where its Failure says the tracker may have taken the write all the same, as when Jira's answer to a new issue, an edit or a finish is lost."""
@property
def label(self) -> str:
"""What a message calls the plan, such as its path."""
@property
def tracked(self) -> str | None:
"""The plan's path from the checkout's top, as git names a file in a commit; None where no commit holds a version of it, as for a file outside the checkout or a tracker."""
def read(self) -> Plan | Failure:
"""The plan as it stands. A NoItemsTable where the project has not set one up."""
def add(self, fields: dict[str, str], detail: str) -> Written | Failure:
"""Files an item under an ID the backend picks. fields holds each of FIELDS the caller sets; detail may be empty."""
def edit(self, id_: int, fields: dict[str, str], detail: str | None, comment: str | None = None) -> Written | Failure:
"""Sets item id_'s fields to those given, and its detail unless None, leaving the rest. Moving an item sets its Release.
comment tells the plan's other readers why, in the project's language. A tracker posts it on the item's issue; a backend with no place for comments drops it."""
def finish(self, id_: int) -> Written | Failure:
"""Removes item id_ with its detail."""
@dataclasses.dataclass(frozen=True)
class FilePlan:
"""A plan kept as a markdown file at path, in the shape `rank_todo.py --help` shows. Every write ranks the file, reading the goals file from goals, the decision log and the comprehension history."""
path: pathlib.Path
tracked: str | None
goals: RecordStore
decisions: RecordStore
history: RecordStore
# The project's readability floor: while the comprehension overall is under it, ranking weighs code health 4 times as much.
floor: decimal.Decimal
@property
def label(self) -> str:
return str(self.path)
def read(self) -> Plan | Failure:
if not self.path.exists():
return NoItemsTable(f"{self.path}: not found; {MISSING}")
text = read_text(self.path, MISSING)
return text if isinstance(text, Failure) else plan_of(text)
def add(self, fields: dict[str, str], detail: str) -> Written | Failure:
texts = self.texts()
if isinstance(texts, Failure):
return texts
filed = markdown_edits.added(texts[0], cells(fields), detail, self.label)
return filed if isinstance(filed, Failure) else self.kept(*filed, texts)
def edit(self, id_: int, fields: dict[str, str], detail: str | None, comment: str | None = None) -> Written | Failure:
texts = self.texts()
if isinstance(texts, Failure):
return texts
text = markdown_edits.edited(texts[0], id_, cells(fields), detail, self.label)
return text if isinstance(text, Failure) else self.kept(id_, text, texts)
def kept(self, id_: int, text: str, texts: tuple[str, str, str, str]) -> Written | Failure:
"""Ranks text, the file with item id_ filed or edited, and writes it where the item scores at the bar or above."""
ranked = ranking.rank(text, *texts[1:], self.floor)
if isinstance(ranked, Failure):
return ranked
# The write may lower another item under the bar, which the notes then say; the write is refused only where the written item itself scores under the bar.
if under := [line for line in ranked.under_bar if line.startswith(f"item {id_} ")]:
return Failure(under[0])
return self.written(id_, ranked)
def finish(self, id_: int) -> Written | Failure:
texts = self.texts()
if isinstance(texts, Failure):
return texts
text = markdown_edits.finished(texts[0], id_, self.label)
if isinstance(text, Failure):
return text
ranked = ranking.rank(text, *texts[1:], self.floor)
return ranked if isinstance(ranked, Failure) else self.written(id_, ranked)
def written(self, id_: int, ranked: ranking.Ranked) -> Written | Failure:
"""Writes ranked's text to the file."""
unwritten = replace_file(self.path.resolve(), ranked.text.encode("utf-8"))
if unwritten:
return Failure(f"{self.path}: {unwritten.reason}")
return Written(id_, tuple(f"{self.path}: {line}" for line in ranked.notes + ranked.under_bar))
def texts(self) -> tuple[str, str, str, str] | Failure:
"""What ranking reads: the file, the goals file, the decision log and the comprehension history. The last two are empty when missing; a missing plan, or a goals file that is missing or empty, is a Failure."""
plan = read_text(self.path, MISSING)
if isinstance(plan, Failure):
return plan
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)
from plan_store.todo_md import FilePlan, plan_of
from record_store.stores import goals_store, store as record_store
from plan_store.jira_epic import JiraPlan
from plan_store.plans import Plan, PlanStore
from project_config.settings import ProjectConfig
from plan_store.scoring import StatedScoring
def store(config: ProjectConfig) -> PlanStore:
"""The store config names for the plan."""
if config.epic is None:
return file_plan(config)
# Imported here, since jira_epic builds on this module's Plan and Written.
from plan_store.jira_epic import JiraPlan
# load refuses a config that names an epic and no env-file.
assert config.env_file is not None
# load refuses a config that names an epic and no formula or bar.
@@ -196,38 +38,3 @@ def held_at(revision: str, plan: PlanStore, cwd: str, run: Git = git) -> Plan |
return plan.read()
text = file_at(revision, plan.tracked, cwd, run)
return text if isinstance(text, Failure) else plan_of(text)
def plan_of(todo: str) -> Plan | Failure:
"""The plan a todo.md's text holds."""
found = items(todo)
if isinstance(found, Failure):
return found
details = item_details(todo)
if isinstance(details, Failure):
return details
marked = renames(todo)
if isinstance(marked, Failure):
return marked
return Plan([dataclasses.replace(item, detail=details.get(item.id, "")) for item in found], frozenset(marked))
def cells(fields: dict[str, str]) -> dict[str, str]:
"""fields by the items table's column names."""
unknown = set(fields) - set(FIELDS)
if unknown:
# A programming error, so nothing catches it: a caller takes its fields from FIELDS.
raise ValueError(f"{', '.join(sorted(unknown))}: not a field; the fields are {', '.join(FIELDS)}")
return {"Item" if name == TAGLINE else name: value for name, value in fields.items()}
def read_text(path: pathlib.Path, missing: str) -> str | Failure:
"""path's text; where it is missing, a Failure saying missing."""
try:
return path.read_text(encoding="utf-8")
except FileNotFoundError:
return Failure(f"{path}: not found; {missing}")
except OSError as failure:
return Failure(f"{path}: {failure.strerror}")
except UnicodeDecodeError:
return Failure(f"{path}: not UTF-8")
+12 -30
View File
@@ -9,13 +9,13 @@ import unittest.mock
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from project_config.settings import DEFAULT_FLOOR, Epic, Finish
from release_plan.todo_table import EXEMPTIONS
from 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 plan_store.plans import Plan, Written
from plan import ranking
from adf_codec.convert import Refused
from release_plan.release import release_of
from plan.release import release_of
EPIC = Epic("https://acme.atlassian.net", "ABC-12")
SEARCH = "https://acme.atlassian.net/rest/api/3/search/jql"
@@ -144,7 +144,7 @@ class JiraPlan(unittest.TestCase):
self.assertIn("ABC-34", failure.reason) # type: ignore[union-attr]
def test_an_exempt_out_of_format_fails_naming_the_reasons_it_may_hold(self):
self.assertEqual(self.read(issue("ABC-34", scores={"Exempt": "because"})), Failure("ABC-34's issue property plan-item holds the Exempt 'because', which is not empty or one of decision, defect, owner, principle, question, security"))
self.assertEqual(self.read(issue("ABC-34", scores={"Exempt": "because"})), Failure("item ABC-34's Exempt 'because' is not empty or one of decision, defect, owner, principle, question, security; ABC-34 holds it in its issue property plan-item"))
def test_reads_every_page(self):
self.pages = [{"issues": [issue("ABC-1")], "nextPageToken": "t1"}, {"issues": [issue("ABC-2")]}]
@@ -315,9 +315,9 @@ class Filing(unittest.TestCase):
def test_each_field_out_of_format_fails_saying_how(self):
cases = (
({"Tagline": "** **"}, "the item has no tagline"),
({"L": "9"}, "item to file's L '9' is not a whole number from 1 to 4"),
({"Exempt": "whim"}, f"the item's Exempt 'whim' is not empty or one of {', '.join(EXEMPTIONS[1:])}"),
({"Blocked by": "ABC-34"}, "the item's Blocked by 'ABC-34' is not empty or IDs separated by \", \""),
({"L": "9"}, "the item to file's L '9' is not a whole number from 1 to 4"),
({"Exempt": "whim"}, f"the item to file's Exempt 'whim' is not empty or one of {', '.join(EXEMPTIONS[1:])}"),
({"Blocked by": "ABC-34"}, "the item to file's Blocked by 'ABC-34' is not empty or IDs separated by \", \""),
)
for change, reason in cases:
with self.subTest(change=change):
@@ -334,7 +334,7 @@ class Filing(unittest.TestCase):
self.add(FIELDS | {"Colour": "red"})
def test_an_item_without_a_release_fails_naming_the_field(self):
self.assertEqual(self.add({name: value for name, value in FIELDS.items() if name != "Release"}), Failure("the item's Release '' is not a version such as 1.2.0"))
self.assertEqual(self.add({name: value for name, value in FIELDS.items() if name != "Release"}), Failure("the item to file's Release '' is not a semver version, such as 1.2.0"))
def test_a_detail_that_does_not_convert_fails_before_any_request(self):
self.to_adf = lambda markdown: Failure("docker is not running") # type: ignore[method-assign]
@@ -460,7 +460,7 @@ class Filing(unittest.TestCase):
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"),
(issue("ABC-34", scores=PROPERTY | {"L": 11}), "item ABC-34's L '11' is not a whole number from 1 to 4; ABC-34 holds it in its issue property plan-item"),
):
with self.subTest(reason=reason):
self.calls.clear()
@@ -597,8 +597,8 @@ class Editing(unittest.TestCase):
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"),
({"Exempt": "tired"}, None, f"item ABC-34's Exempt 'tired' is not empty or one of {', '.join(EXEMPTIONS[1:])}"),
({"Release": "soon"}, None, "item ABC-34's Release 'soon' is not a semver version, such as 1.2.0"),
({"Tagline": " "}, None, "the item has no tagline"),
({"Tagline": "Count\nruns."}, None, "the tagline holds a line break; keep it on one line"),
({}, "## Why", "the detail holds a ## or ### heading"),
@@ -724,24 +724,6 @@ class Finishing(unittest.TestCase):
self.assertEqual(self.calls, [])
class Requests(unittest.TestCase):
def test_sends_each_request_through_the_shared_client_with_jiras_error_messages(self):
with unittest.mock.patch.object(jira_epic.json_request, "http_json", return_value={"issues": []}) as sent:
self.assertEqual(jira_epic.http_json("POST", SEARCH, AUTHORIZATION, {"jql": "x"}), {"issues": []})
sent.assert_called_once_with("POST", SEARCH, AUTHORIZATION, {"jql": "x"}, 30, jira_epic.error_message)
def test_reads_jiras_messages_from_an_error_answer(self):
cases = (
({"errorMessages": ["Issue does not exist or you do not have permission to see it."], "errors": {}}, "Issue does not exist or you do not have permission to see it."),
({"errorMessages": ["One."], "errors": {"jql": "Two."}}, "One.; Two."),
({"errorMessages": "One.", "errors": ["Two."]}, ""),
({"errorMessages": [7, "One."]}, "One."),
(["One."], ""),
)
for answer, message in cases:
with self.subTest(answer=answer):
self.assertEqual(jira_epic.error_message(answer), message)
if __name__ == "__main__":
unittest.main()
+22 -22
View File
@@ -15,16 +15,16 @@ from plan_store.contract import FIRST, MOVES, PlanStoreContract, SECOND
from plan_store.jira_epic import JiraPlan
from plan_store.fakes import MemoryPlan
from record_store.fakes import MemoryStore
from release_plan.todo_table import NoItemsTable
from release_plan.test_ranking import README, SCORED, VOID
from release_plan.release import release_of
from plan_store import stores
from plan.todo_table import NoItemsTable
from plan_store import plans, scoring, stores, todo_md
from plan.test_ranking import README, SCORED, VOID
from plan.release import release_of
EMPTY = "# todo\n\n## Scoring\n\n`Score = 100 * V / 2**S`\n\n`Bar = 2`\n\n`Next ID = 1`\n\n## Items\n\n| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |\n|---|---|---|---|---|---|---|---|---|---|---|---|\n"
class MemoryPlanContract(PlanStoreContract, unittest.TestCase):
def new_store(self) -> stores.PlanStore:
def new_store(self) -> plans.PlanStore:
return MemoryPlan()
@@ -32,10 +32,10 @@ class FilePlanContract(PlanStoreContract, unittest.TestCase):
def setUp(self) -> None:
self.folder = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory()))
def new_store(self) -> stores.FilePlan:
def new_store(self) -> todo_md.FilePlan:
(self.folder / "todo.md").write_text(EMPTY)
(self.folder / "README.md").write_text(README)
return stores.FilePlan(self.folder / "todo.md", "todo.md", FileStore(self.folder / "README.md", None), MemoryStore(), MemoryStore(), DEFAULT_FLOOR)
return todo_md.FilePlan(self.folder / "todo.md", "todo.md", FileStore(self.folder / "README.md", None), MemoryStore(), MemoryStore(), DEFAULT_FLOOR)
class FilePlan(FilePlanContract):
@@ -62,7 +62,7 @@ class FilePlan(FilePlanContract):
def test_an_edited_tagline_heads_the_detail_too(self):
store = self.new_store()
id_ = self.filed(store, FIRST, "Why it counts.")
store.edit(id_, {stores.TAGLINE: "Count `a | b` runs."}, None)
store.edit(id_, {plans.TAGLINE: "Count `a | b` runs."}, None)
text = (self.folder / "todo.md").read_text()
self.assertIn("| **Count `a \\| b` runs.** |", text)
self.assertIn(f"### {id_}. Count `a | b` runs.\n\nWhy it counts.\n", text)
@@ -84,7 +84,7 @@ class FilePlan(FilePlanContract):
self.assertEqual(self.filed(store, FIRST), 10)
todo.write_text("".join(line.replace("| 4 | 1 | 1 by 9 |", "| 4 | 10 | 1 by 9 |") if line.startswith("| 10 ") else line for line in todo.read_text().splitlines(keepends=True)))
written = store.edit(first, {"E": "2"}, None)
assert isinstance(written, stores.Written), written
assert isinstance(written, plans.Written), written
self.assertIn("item 10 ", written.notes[0])
def test_an_id_it_holds_no_item_for_fails_naming_the_file(self):
@@ -118,7 +118,7 @@ class FilePlan(FilePlanContract):
def test_reads_the_releases_marked_renamed(self):
store = self.new_store()
(self.folder / "todo.md").write_text(EMPTY + "\n## Renamed\n\n- 0.2.1 renamed to 0.3.0\n")
self.assertEqual(store.read(), stores.Plan([], frozenset({release_of("0.2.1")})))
self.assertEqual(store.read(), plans.Plan([], frozenset({release_of("0.2.1")})))
def test_a_field_it_does_not_know_is_a_programming_error(self):
with self.assertRaises(ValueError):
@@ -130,9 +130,9 @@ class FilePlan(FilePlanContract):
id_ = self.filed(store, FIRST)
before = (self.folder / "todo.md").read_text()
broken, split = "the tagline holds a line break; keep it on one line", "the detail holds a ## or ### heading, which would split ## Details; use #### or drop the #s"
self.assertEqual(store.add(FIRST | {stores.TAGLINE: "Count\nthe runs."}, ""), Failure(broken))
self.assertEqual(store.add(FIRST | {plans.TAGLINE: "Count\nthe runs."}, ""), Failure(broken))
self.assertEqual(store.add(FIRST, "## Why\n"), Failure(split))
self.assertEqual(store.edit(id_, {stores.TAGLINE: "Count\nthe runs."}, None), Failure(broken))
self.assertEqual(store.edit(id_, {plans.TAGLINE: "Count\nthe runs."}, None), Failure(broken))
self.assertEqual(store.edit(id_, {}, "### Why\n"), Failure(split))
self.assertEqual((self.folder / "todo.md").read_text(), before)
@@ -157,7 +157,7 @@ class FilePlan(FilePlanContract):
(self.folder / "README.md").write_text(README.replace(VOID, ""))
kept, finished = self.filed(store, FIRST | {MOVES: "code health by 1"}), self.filed(store, SECOND)
row = [line for line in (self.folder / "todo.md").read_text().splitlines() if line.startswith(f"| {kept} ")]
self.assertIsInstance(store.finish(finished), stores.Written)
self.assertIsInstance(store.finish(finished), plans.Written)
self.assertIn(row[0], (self.folder / "todo.md").read_text())
return row[0]
self.assertNotEqual(health_row("6.0"), health_row("7.0"))
@@ -200,7 +200,7 @@ class Store(unittest.TestCase):
def test_a_path_picks_the_markdown_file(self):
config = self.config()
picked = stores.store(dataclasses.replace(config, paths=config.paths | {"plan": pathlib.Path("/checkout/todo.md")}))
self.assertEqual((type(picked), picked.label, picked.tracked), (stores.FilePlan, "/checkout/todo.md", "todo.md"))
self.assertEqual((type(picked), picked.label, picked.tracked), (todo_md.FilePlan, "/checkout/todo.md", "todo.md"))
def test_the_markdown_file_ranks_with_the_configs_floor(self):
self.assertEqual(stores.file_plan(self.config(readability_floor=decimal.Decimal("6.5")), pathlib.Path("/checkout/todo.md")).floor, decimal.Decimal("6.5"))
@@ -218,26 +218,26 @@ class Store(unittest.TestCase):
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")))
self.assertEqual(picked.scoring, scoring.StatedScoring(JiraScoring("V / 2**S", 1.5), goals_store(config), record_store(config, "decisions"), record_store(config, "comprehension-history"), decimal.Decimal("6.5")))
class StatedScoring(unittest.TestCase):
def test_weighs_the_goals_the_goals_file_holds(self):
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"]))
weighed = scoring.StatedScoring(JiraScoring("V / 2**S", 1.5), MemoryStore(README), MemoryStore(), MemoryStore(), DEFAULT_FLOOR).read()
assert not isinstance(weighed, Failure), weighed
self.assertEqual((weighed.bar, list(weighed.goals)), (1.5, ["1", "2", "2.1"]))
def test_weighs_code_health_by_the_history_and_the_floor_it_is_given(self):
for floor, under in ((DEFAULT_FLOOR, True), (decimal.Decimal("6.0"), False)):
with self.subTest(floor=floor):
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)
weighed = scoring.StatedScoring(JiraScoring("V", 1), MemoryStore("## Goals\n\n1. **Achieve:** A.\n"), MemoryStore(), MemoryStore(SCORED.format(overall="6.99")), floor).read()
assert not isinstance(weighed, Failure), weighed
self.assertEqual(weighed.weights["code health"] > weighed.weights["1"] * 2, under)
def test_a_goals_file_that_is_empty_or_cannot_be_read_fails(self):
for goals, reason in ((MemoryStore(), "the record in memory: missing or empty"), (MemoryStore(fails="Jira answered 403"), "Jira answered 403")):
with self.subTest(reason=reason):
read = stores.StatedScoring(JiraScoring("V", 1), goals, MemoryStore(), MemoryStore(), DEFAULT_FLOOR).read()
read = scoring.StatedScoring(JiraScoring("V", 1), goals, MemoryStore(), MemoryStore(), DEFAULT_FLOOR).read()
assert isinstance(read, Failure), read
self.assertTrue(read.reason.startswith(reason), read.reason)
+141
View File
@@ -0,0 +1,141 @@
"""A plan kept as a markdown file, todo.md, in the shape `rank_todo.py --help` shows: read, filed into, edited, finished, and ranked or checked in place."""
import dataclasses
import decimal
import pathlib
from plan_store.plans import cells, Plan, Written
from failure import Failure
from plan.todo_table import item_details, items, NoItemsTable, renames
from plan_store import markdown_edits
from plan import ranking
from record_store.stores import RecordStore
from text_files.file_writes import replace_file
from plan_store.scoring import weighing_texts
# What the reader of a missing todo.md is told.
MISSING = "every project keeps a todo.md, and rank_todo.py --help shows one"
@dataclasses.dataclass(frozen=True)
class FilePlan:
"""A plan kept as a markdown file at path. Every write ranks the file, reading the goals file from goals, the decision log and the comprehension history."""
path: pathlib.Path
tracked: str | None
goals: RecordStore
decisions: RecordStore
history: RecordStore
# The project's readability floor: while the comprehension overall is under it, ranking weighs code health 4 times as much.
floor: decimal.Decimal
@property
def label(self) -> str:
return str(self.path)
def read(self) -> Plan | Failure:
if not self.path.exists():
return NoItemsTable(f"{self.path}: not found; {MISSING}")
text = read_text(self.path, MISSING)
return text if isinstance(text, Failure) else plan_of(text)
def add(self, fields: dict[str, str], detail: str) -> Written | Failure:
texts = self.texts()
if isinstance(texts, Failure):
return texts
filed = markdown_edits.added(texts[0], cells(fields), detail, self.label)
return filed if isinstance(filed, Failure) else self.kept(*filed, texts)
def edit(self, id_: int, fields: dict[str, str], detail: str | None, comment: str | None = None) -> Written | Failure:
texts = self.texts()
if isinstance(texts, Failure):
return texts
text = markdown_edits.edited(texts[0], id_, cells(fields), detail, self.label)
return text if isinstance(text, Failure) else self.kept(id_, text, texts)
def kept(self, id_: int, text: str, texts: tuple[str, str, str, str]) -> Written | Failure:
"""Ranks text, the file with item id_ filed or edited, and writes it where the item scores at the bar or above."""
ranked = ranking.rank(text, *texts[1:], self.floor)
if isinstance(ranked, Failure):
return ranked
# The write may lower another item under the bar, which the notes then say; the write is refused only where the written item itself scores under the bar.
if under := [line for line in ranked.under_bar if line.startswith(f"item {id_} ")]:
return Failure(under[0])
return self.written(id_, ranked)
def finish(self, id_: int) -> Written | Failure:
texts = self.texts()
if isinstance(texts, Failure):
return texts
text = markdown_edits.finished(texts[0], id_, self.label)
if isinstance(text, Failure):
return text
ranked = ranking.rank(text, *texts[1:], self.floor)
return ranked if isinstance(ranked, Failure) else self.written(id_, ranked)
def rank(self) -> ranking.Ranked | Failure:
"""Ranks the file in place, writing it where ranking changed it. The caller prints `reported`'s lines."""
texts = self.texts()
if isinstance(texts, Failure):
return texts
ranked = ranking.rank(*texts, self.floor)
if isinstance(ranked, Failure):
return ranked
if ranked.text != texts[0] and (unwritten := self.replaced(ranked.text)):
return unwritten
return ranked
def check(self) -> list[str]:
"""Why `rank_todo.py --check` fails on the file, empty when it passes: the file is not ranked, or an item scores under the bar."""
texts = self.texts()
if isinstance(texts, Failure):
return [texts.reason]
ranked = ranking.rank(*texts, self.floor)
if isinstance(ranked, Failure):
return [ranked.reason]
unranked = [] if ranked.text == texts[0] else [f"{self.path}: not ranked; run rank_todo.py on it"]
return unranked + [f"{self.path}: {line}" for line in ranked.under_bar]
def reported(self, ranked: ranking.Ranked) -> list[str]:
"""Ranking's notes and under-bar lines, each prefixed with the file's path, as a tool prints them on stderr."""
return [f"{self.path}: {line}" for line in ranked.notes + ranked.under_bar]
def written(self, id_: int, ranked: ranking.Ranked) -> Written | Failure:
"""Writes ranked's text to the file."""
return self.replaced(ranked.text) or Written(id_, tuple(self.reported(ranked)))
def replaced(self, text: str) -> Failure | None:
unwritten = replace_file(self.path.resolve(), text.encode("utf-8"))
return Failure(f"{self.path}: {unwritten.reason}") if unwritten else None
def texts(self) -> tuple[str, str, str, str] | Failure:
"""What ranking reads: the file, the goals file, the decision log and the comprehension history. The last two are empty when missing; a missing plan, or a goals file that is missing or empty, is a Failure."""
plan = read_text(self.path, MISSING)
if isinstance(plan, Failure):
return plan
weighing = weighing_texts(self.goals, self.decisions, self.history)
return weighing if isinstance(weighing, Failure) else (plan, *weighing)
def plan_of(todo: str) -> Plan | Failure:
"""The plan a todo.md's text holds."""
found = items(todo)
if isinstance(found, Failure):
return found
details = item_details(todo)
if isinstance(details, Failure):
return details
marked = renames(todo)
if isinstance(marked, Failure):
return marked
return Plan([dataclasses.replace(item, detail=details.get(item.id, "")) for item in found], frozenset(marked))
def read_text(path: pathlib.Path, missing: str) -> str | Failure:
"""path's text; where it is missing, a Failure saying missing."""
try:
return path.read_text(encoding="utf-8")
except FileNotFoundError:
return Failure(f"{path}: not found; {missing}")
except OSError as failure:
return Failure(f"{path}: {failure.strerror}")
except UnicodeDecodeError:
return Failure(f"{path}: not UTF-8")
+10 -19
View File
@@ -140,7 +140,7 @@ from 1 to 10, or sets `parallel-chunks` to anything but a whole number of 1 or m
import pathlib
import sys
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 project_config.settings import CONFIG, ENV_FILE, JIRA_FINISH_STATUS, JIRA_FINISH_TRANSITION, JIRA_SCORE_BAR, JIRA_SCORE_FORMULA, load, OPTIONAL, ProjectConfig, SCALARS, SETTINGS, Unnamed
from failure import Failure
from git_cli.git_repo import git, Git
from project_config import templates
@@ -157,26 +157,17 @@ def main(argv: list[str]) -> int:
if isinstance(config, Failure):
print(config.reason, file=sys.stderr)
return 1
switches = {WAIT_FOR_APPROVAL: config.wait_for_approval, TOOLING_ON_HOST: config.tooling_on_host}
if argv and argv[0] in switches:
print("true" if switches[argv[0]] else "false")
return 0
if argv == [READABILITY_FLOOR]:
print(config.readability_floor)
return 0
if argv == [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_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:
# A one-value setting prints its value, its default where the config leaves it out; one without a default, as `notifier`, prints only where set.
scalars = {scalar.name: scalar.shown(value) for scalar in SCALARS if (value := getattr(config, scalar.field)) is not None}
paths = {**config.places, **({ENV_FILE: str(config.env_file)} if config.env_file else {}), **({JIRA_SCORE_FORMULA: config.jira_scoring.formula, JIRA_SCORE_BAR: f"{config.jira_scoring.bar:g}"} if config.jira_scoring else {}), **({JIRA_FINISH_TRANSITION: config.jira_finish.transition, JIRA_FINISH_STATUS: config.jira_finish.status} if config.jira_finish else {})}
shown = paths | scalars
if argv and argv[0] not in shown:
print(f"{config.folder / CONFIG} sets no `{argv[0]}`", file=sys.stderr)
return 1
defaults = ProjectConfig(config.key, config.folder, config.top, {}).texts
listed = [f"{name}: {path}" for name, path in paths.items()] + [f"{name}: true" for name, on in switches.items() if on] + ([f"{READABILITY_FLOOR}: {config.readability_floor}"] if config.readability_floor != DEFAULT_FLOOR else []) + ([f"{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))
# The listing leaves out each one-value setting at its default.
defaults = ProjectConfig(config.key, config.folder, config.top, {})
listed = [*(f"{name}: {path}" for name, path in paths.items()), *(f"{scalar.name}: {scalars[scalar.name]}" for scalar in SCALARS if getattr(config, scalar.field) != getattr(defaults, scalar.field))]
print(shown[argv[0]] if argv else "\n".join(listed))
return 0
+71 -24
View File
@@ -10,10 +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 plan.formula import parse_formula
from plan.todo_table import SHAPE
from project_config import templates
from release_plan.ranking import variables
from plan.ranking import variables
PROJECTS = ".claude-projects"
CONFIG = "config.toml"
@@ -52,7 +52,8 @@ JIRA_FINISH = (JIRA_FINISH_TRANSITION, JIRA_FINISH_STATUS)
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)
# The settings allowed only where `plan` names a Jira epic.
JIRA_PLAN_ONLY = (*JIRA_FINISH, *JIRA_SCORE)
# What opens a setting that names a Jira Cloud epic in place of a path: `jira:`, then the epic's address as the browser shows it. The settings below may name an epic; each reads its own part of it.
JIRA = "jira:"
EPIC_SPELLINGS = {
@@ -193,48 +194,79 @@ def load(top: pathlib.Path, main: pathlib.Path, home: pathlib.Path) -> ProjectCo
pages = {name: page for name in RECORDS if (page := page_of(values.get(name)))}
env_file = anywhere(values.get(ENV_FILE), home)
misplaced = ENV_FILE in values and (env_file is None or lies_in(env_file, top, main, file.parent))
notifier = next((name for name in NOTIFIERS if name == values.get(NOTIFIER)), None)
waits = values.get(WAIT_FOR_APPROVAL, False)
on_host = values.get(TOOLING_ON_HOST, False)
floor = floor_of(values[READABILITY_FLOOR]) if READABILITY_FLOOR in values else DEFAULT_FLOOR
parallel = values.get(PARALLEL_CHUNKS, 1)
scalars = {scalar: scalar.read(values[scalar.name]) for scalar in SCALARS if scalar.name in values}
finish = [name for setting in JIRA_FINISH if (name := name_of(values.get(setting)))]
formula, bar = values.get(JIRA_SCORE_FORMULA), values.get(JIRA_SCORE_BAR)
scoring = JiraScoring(formula, bar_value) if isinstance(formula, str) and (bar_value := bar_of(bar)) is not None else None
checks = {LANGUAGE: language_fault, COMMIT_TITLE: templates.title_fault, PULL_REQUEST_TITLE: templates.title_fault, BRANCH: templates.branch_fault}
faults = [
*(f"`{name}` is missing" for name in SETTINGS if name not in values),
*(f"`{name}` is not a setting" for name in values if name not in (*SETTINGS, *OPTIONAL)),
*(f"`{scalar.name}` is {values[scalar.name]!r}, {read.reason}" for scalar, read in scalars.items() if isinstance(read, Unfit)),
*(f"`{name}` is {values[name]!r}, not {SPELLING}" for name, path in paths.items() if path is None and name not in (*EPIC_SPELLINGS, *RECORDS)),
*(f"`{name}` is {values[name]!r}, not {SPELLING}, or {EPIC_SPELLINGS[name]}" for name in EPIC_SPELLINGS if name in values and paths[name] is None and epics[name] is None),
*(f"`{name}` is {values[name]!r}, not {SPELLING}, or {PAGE_SPELLING}" for name in RECORDS if name in values and paths[name] is None and name not in pages),
*([f"`{ENV_FILE}` is {values[ENV_FILE]!r}, not {OUTSIDE}"] if misplaced else []),
# Each setting that reaches a service needs the file that holds its credentials.
*(f"`{name}` names a Jira epic, so `{ENV_FILE}` must name the file that holds its credentials" for name, epic in epics.items() if epic and ENV_FILE not in values),
*(f"`{name}` names a Confluence page, so `{ENV_FILE}` must name the file that holds its credentials" for name in pages if ENV_FILE not in values),
*([f"`{NOTIFIER}` names a notifier, so `{ENV_FILE}` must name the file that holds its credentials"] if NOTIFIER in values and ENV_FILE not in values else []),
# rule-hook ranks a plan kept as a file before tool calls, inside the hook's time limit, which a read from Jira or Confluence mustn't hold up.
*(["`goals-and-audience` names a Jira epic, so `plan` must name one too"] if epics["goals-and-audience"] and not epics["plan"] else []),
*(f"`{name}` names a Confluence page, so `plan` must name a Jira epic" for name in RANKED if name in pages and not epics["plan"]),
*([f"`{ENV_FILE}` is {values[ENV_FILE]!r}, not {OUTSIDE}"] if misplaced else []),
*([f"`{NOTIFIER}` is {values[NOTIFIER]!r}, not {' or '.join(NOTIFIERS)}"] if NOTIFIER in values and values[NOTIFIER] not in NOTIFIERS else []),
*([f"`{NOTIFIER}` names a notifier, so `{ENV_FILE}` must name the file that holds its credentials"] if NOTIFIER in values and ENV_FILE not in values else []),
*(f"`{name}` is set, so `plan` must name a Jira epic" for name in JIRA_PLAN_ONLY if name in values and not epics["plan"]),
*(f"`plan` names a Jira epic, so `{name}` must be set, as `project-config --help` shows" for name in JIRA_SCORE if epics["plan"] and name not in values),
*(f"`{name}` is {values[name]!r}, not the name Jira shows, such as \"{example}\"" for name, example in zip(JIRA_FINISH, ("Mark as done", "Done")) if name in values and not name_of(values[name])),
*(f"`{name}` is set, so `{other}` must be too" for name, other in (JIRA_FINISH, JIRA_FINISH[::-1]) if name in values and other not in values),
*(f"`{name}` is set, so `plan` must name a Jira epic" for name in JIRA_FINISH if name in values and not epics["plan"]),
*(f"`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 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
assert isinstance(parallel, int)
# faults names a formula or bar a plan in Jira lacks or misspells.
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)
defaulted = ProjectConfig(file.parent.name, file.parent, top, {name: path for name, path in paths.items() if path}, env_file, epic=epics["plan"], goals_epic=epics["goals-and-audience"], jira_finish=Finish(*finish) if finish else None, jira_scoring=scoring, pages=pages)
return dataclasses.replace(defaulted, **{scalar.field: read for scalar, read in scalars.items()})
@dataclasses.dataclass(frozen=True)
class Unfit:
"""Why a setting's value doesn't fit it, as the end of the sentence "`<setting>` is <value>, <reason>"."""
reason: str
@dataclasses.dataclass(frozen=True)
class Scalar:
"""An optional setting that holds one value, not a path: the ProjectConfig field it sets, whose default is its value where the config leaves it out, how its value is read, and how `project-config <name>` prints it."""
name: str
field: str
# The value, or Unfit; typed Any, since each Scalar reads into its own field's type.
read: typing.Callable[[object], typing.Any]
shown: typing.Callable[[typing.Any], str] = str
def switch(value: object) -> bool | Unfit:
return value if isinstance(value, bool) else Unfit("not true or false")
def floor_read(value: object) -> decimal.Decimal | Unfit:
floor = floor_of(value)
return Unfit(f"not a number from 1 to 10; write a bare number, such as `{READABILITY_FLOOR} = 7.0`") if floor is None else floor
def parallel_read(value: object) -> int | Unfit:
return value if type(value) is int and value >= 1 else Unfit(f"not a whole number of 1 or more, such as `{PARALLEL_CHUNKS} = 2`")
def notifier_read(value: object) -> Notifier | Unfit:
return next((name for name in NOTIFIERS if name == value), None) or Unfit(f"not {' or '.join(NOTIFIERS)}")
def text_read(fault: typing.Callable[[object], str | None]) -> typing.Callable[[object], str | Unfit]:
"""A text setting's reader, from the check that says why a value doesn't fit."""
def read(value: object) -> str | Unfit:
found = fault(value)
return Unfit(found) if found else str(value)
return read
def formula_fault(value: object) -> str | None:
@@ -284,6 +316,21 @@ def language_fault(value: object) -> str | None:
return None if named else 'not a language\'s English name in words of letters, such as "Swedish" or "Brazilian Portuguese"'
# Each one-value setting, in the order `project-config` lists them.
SCALARS = (
Scalar(WAIT_FOR_APPROVAL, "wait_for_approval", switch, lambda on: "true" if on else "false"),
Scalar(TOOLING_ON_HOST, "tooling_on_host", switch, lambda on: "true" if on else "false"),
Scalar(READABILITY_FLOOR, "readability_floor", floor_read),
Scalar(PARALLEL_CHUNKS, "parallel_chunks", parallel_read),
Scalar(NOTIFIER, "notifier", notifier_read),
Scalar(LANGUAGE, "language", text_read(language_fault)),
Scalar(COMMIT_TITLE, "commit_title", text_read(templates.title_fault)),
Scalar(PULL_REQUEST_TITLE, "pull_request_title", text_read(templates.title_fault)),
Scalar(BRANCH, "branch", text_read(templates.branch_fault)),
)
OPTIONAL = tuple(sorted((ENV_FILE, TOUCH_PREDICTIONS, *JIRA_PLAN_ONLY, *(scalar.name for scalar in SCALARS))))
def lies_in(path: pathlib.Path, *places: pathlib.Path) -> bool:
"""Whether path lies in one of places. Both sides are resolved, so a symlink can't lead a path out of the place it names."""
return any(path.resolve().is_relative_to(place.resolve()) for place in places)
+10
View File
@@ -71,6 +71,16 @@ def fits(template: str, title: str) -> bool:
return pattern(template).fullmatch(title) is not None
def misfits(template: str, branch_template: str, branch: str | None, title: str) -> bool:
"""Whether title breaks template on branch, the checkout's branch or None where HEAD is detached. On a branch that fits branch_template, a plan item's, a title must fit template. Any other branch, such as a release review's, has no ID for {id}, so every title fits there (CLAUDE.md → "Git, commits, and PRs")."""
return branch is not None and branch_fits(branch_template, branch) and not fits(template, title.strip())
def title_of(template: str, branch_template: str, branch: str, id_: str, summary: str) -> str:
"""The title template makes of summary on branch, with id_ for {id}; summary alone on a branch that doesn't fit branch_template, as misfits allows."""
return template.replace(ID, id_).replace(SUMMARY, summary) if branch_fits(branch_template, branch) else summary
def summary_of(template: str, title: str) -> str:
"""title's summary. A title that doesn't fit template is its own summary, so a commit from before the config named the template reads as it always did."""
found = pattern(template).fullmatch(title)
+4 -4
View File
@@ -21,8 +21,8 @@ as a file, there is nothing left to store, and save says so. Run it after every
steps work wherever a project keeps the record.
For a record kept on a Confluence page, save refuses where someone saved the page after open read
it, and the human decides what follows. The copy keeps the unsaved edit until open runs again and
writes the copy afresh.
it or after save last wrote it, and the human decides what follows. The copy keeps the unsaved edit
until open runs again and writes the copy afresh.
Exit 2 on bad arguments, and 1, saying why, on any other failure.
"""
@@ -70,9 +70,9 @@ def performed(config: ProjectConfig, command: str, name: str, home: pathlib.Path
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."""
"""The store of the record called name, and the copy it gets where it isn't kept as a file."""
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
return (goals_store(config) if name == GOALS else store(config, name)), copy
def worktree_folder(top: pathlib.Path) -> str:
+2 -3
View File
@@ -25,13 +25,12 @@ def worktree_config(top: str, **kept: Page) -> ProjectConfig:
class Opened(unittest.TestCase):
def test_a_record_on_a_confluence_page_keeps_the_version_it_read_beside_its_copy(self):
def test_a_record_on_a_confluence_page_gets_a_copy_in_a_folder_of_its_worktree(self):
page = Page("https://acme.atlassian.net", "2293761", "confluence:https://acme.atlassian.net/wiki/spaces/ENG/pages/2293761")
record, copy = main.opened(worktree_config("/code/acme", decisions=page), "decisions", pathlib.Path("/home/me"))
self.assertEqual((copy.parent.parent, copy.name), (COPIES, "decisions.md"))
self.assertRegex(copy.parent.name, r"^acme-[0-9a-f]{8}$")
assert isinstance(record, ConfluencePage), record
self.assertEqual(record.kept, copy.with_suffix(".version"))
self.assertIsInstance(record, ConfluencePage)
def test_the_goals_file_opens_through_the_goals_store(self):
record, copy = main.opened(worktree_config("/code/acme"), "goals-and-audience", pathlib.Path("/home/me"))
+5 -4
View File
@@ -93,8 +93,8 @@ import pathlib
import sys
from failure import Failure
from plan_store.stores import file_plan
from project_config.main import located
from release_plan import plan_file
def main(argv: list[str]) -> int:
@@ -116,15 +116,16 @@ def main(argv: list[str]) -> int:
# The goals, decisions and history are this checkout's project's, so another project's plan would be ranked by them.
if todo.resolve() != config.plan_file.resolve():
return fail(Failure(f"rank_todo.py: {todo} is not the plan this checkout's config names, {config.plan_file.resolve()}; run rank_todo.py in the checkout of the project whose plan it is"))
plan = file_plan(config, todo)
if check:
failures = plan_file.check_failures(todo, config)
failures = plan.check()
for line in failures:
print(line, file=sys.stderr)
return 1 if failures else 0
ranked = plan_file.rank_file(todo, config)
ranked = plan.rank()
if isinstance(ranked, Failure):
return fail(ranked)
for line in plan_file.report_lines(todo, ranked):
for line in plan.reported(ranked):
print(line, file=sys.stderr)
return 1 if ranked.under_bar else 0
+6 -7
View File
@@ -73,11 +73,11 @@ def main(argv: list[str]) -> int:
def update(record: RecordStore, archive: pathlib.Path, checkout: Checkout, home: str, reset_at: str | None) -> Updated | Failure:
text = record.read()
if isinstance(text, Failure):
return text
held = record.held()
if isinstance(held, Failure):
return held
# An empty record starts with its title.
text = text or "# Reading cost\n"
text = held.text or "# Reading cost\n"
figures = new_figures(text, archive, checkout, home)
if isinstance(figures, Failure):
return figures
@@ -86,9 +86,8 @@ def update(record: RecordStore, archive: pathlib.Path, checkout: Checkout, home:
readings = readings_of(text)
if isinstance(readings, Failure):
return readings
if marks and (unwritten := record.write(text)):
return unwritten
return Updated(len(figures), readings)
written = record.write(text, held.version) if marks else None
return written if isinstance(written, Failure) else Updated(len(figures), readings)
def new_figures(record: str, archive: pathlib.Path, checkout: Checkout, home: str) -> list[str] | Failure:
+8 -1
View File
@@ -19,6 +19,7 @@ from reading_cost.measure import Checkout, Reading
from failure import Failure
from reading_cost import figures, main, measure
from transcript_archive.read import finished_chunks, FinishedChunk
from record_store.held import Held
from test_env import isolated_env
from record_store.fakes import MemoryStore
from transcript_archive import outcomes
@@ -235,9 +236,15 @@ class Located(unittest.TestCase):
class Update(unittest.TestCase):
def test_writes_over_the_version_it_read(self):
record = MemoryStore("# Reading cost\n", version=2)
archive = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory()))
self.assertNotIsInstance(main.update(record, archive, Checkout("/c/p", "/c/p", frozenset(), BRANCH), "/h", "2026-11-14T00:00:00Z"), Failure)
self.assertEqual(record.overs, ["2"])
def test_fails_where_the_record_refuses_the_write(self):
class Unwritable(MemoryStore):
def write(self, text: str) -> Failure | None:
def write(self, text: str, over: str | None) -> Held | Failure:
return Failure("the wiki is down")
archive = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory()))
+31 -59
View File
@@ -1,54 +1,42 @@
"""A record kept on one Confluence Cloud page, read and written as markdown over Confluence's REST API version 2, with the credentials of the config's env-file, and converted by the adf-codec shim.
A write never overwrites a teammate's edit: it sends the version it read, and Confluence refuses it where someone saved the page since. The human then decides (lilleman, 2026-11-12)."""
A write never overwrites a teammate's edit: it sends the version after the one held() read, and Confluence refuses it where someone saved the page since. The human then decides (lilleman, 2026-11-12)."""
import dataclasses
import json
import pathlib
import typing
from adf_codec.convert import adfs_to_markdown, markdown_to_adf, Refused
from plan_store.jira_epic import basic_auth, Http, TIMEOUT, ToAdf, ToMarkdown
from atlassian.client import basic_auth, confluence_json, Http, ToAdf, ToMarkdown
from rest_client.json_request import ErrorAnswer
from failure import Failure
from rest_client import json_request
from record_store.held import Held
from project_config.settings import Page
from text_files.file_writes import replace_file
# What Confluence answers to a write whose version isn't the one after the version it holds.
CONFLICT = 409
SHAPE = "not in the shape Confluence Cloud's REST API version 2 documents"
def http_json(method: str, url: str, authorization: str, body: object) -> object:
return json_request.http_json(method, url, authorization, body, TIMEOUT, error_message)
def error_message(answer: object) -> str:
"""Confluence's messages in the JSON of an error answer; empty where it holds none."""
errors = answer.get("errors") if isinstance(answer, dict) else None
found = [error.get("title") for error in errors if isinstance(error, dict)] if isinstance(errors, list) else [answer.get("message")] if isinstance(answer, dict) else []
return "; ".join(text for text in found if isinstance(text, str))
@dataclasses.dataclass(frozen=True)
class Seen:
"""The page's version number and title as the store last read or wrote them. A write needs both."""
"""The page's version number and title as a read found them or a write left them. A write needs both, so a Held's version holds both, as JSON."""
version: int
title: str
@property
def token(self) -> str:
return json.dumps(dataclasses.asdict(self))
@dataclasses.dataclass
class ConfluencePage:
"""The text of page as markdown, read and written with the credentials env_file holds.
kept is a file that keeps the version the store read for a later process, such as `project-record save` after `project-record open`; None keeps it only in memory."""
"""The text of page as markdown, read and written with the credentials env_file holds."""
page: Page
env_file: pathlib.Path
kept: pathlib.Path | None = None
http: Http = http_json
http: Http = confluence_json
to_markdown: ToMarkdown = adfs_to_markdown
to_adf: ToAdf = markdown_to_adf
seen: Seen | None = None
@property
def label(self) -> str:
@@ -64,18 +52,19 @@ class ConfluencePage:
def read(self) -> str | Failure:
"""The page's text as markdown; empty where the page is."""
held = self.held()
return held if isinstance(held, Failure) else held.text
def held(self) -> Held | Failure:
"""The page's text as markdown, with its version and title as the version a write over it names."""
answer = self.fetched("?body-format=atlas_doc_format")
if isinstance(answer, Failure):
return answer
seen, held = answer
if not isinstance(held, str):
seen, body = answer
if not isinstance(body, str):
return Failure(f"{self.label} is {SHAPE}: it holds no body in atlas_doc_format")
text = self.converted(held)
if isinstance(text, Failure):
return text
# Kept only once the text is in hand: a version kept for a read that failed would let a later write overwrite the save it saw.
unkept = self.keep(seen)
return unkept or text
text = self.converted(body)
return text if isinstance(text, Failure) else Held(text, seen.token)
def converted(self, held: str) -> str | Failure:
"""The markdown of the body held, the JSON of an ADF document; empty where held is."""
@@ -92,14 +81,9 @@ class ConfluencePage:
return Failure(f"cannot convert {self.label} to markdown: {texts.reason}")
return texts[0]
def write(self, text: str) -> Failure | None:
"""Replaces the page's text with text, as the version after the one the store read. Where the store hasn't read the page, it replaces the page as it stands."""
seen = self.seen or self.recalled()
if seen is None:
fetched = self.fetched("")
if isinstance(fetched, Failure):
return fetched
seen = fetched[0]
def write(self, text: str, over: str | None) -> Held | Failure:
"""Replaces the page's text with text, as the version after over, the one held() gave. Where over is None, it replaces the page as it stands."""
seen = self.seen_of(over)
if isinstance(seen, Failure):
return seen
document = self.to_adf(text)
@@ -114,7 +98,7 @@ class ConfluencePage:
return Failure(f"someone saved {self.label} since the loop read version {seen.version} of it, so the loop didn't write it: never overwrite their edit, but ask the human what to do ({answer.reason})")
if isinstance(answer, Failure):
return Failure(f"cannot write {self.label}: {answer.reason}")
return self.keep(Seen(seen.version + 1, seen.title))
return Held(text, Seen(seen.version + 1, seen.title).token)
def fetched(self, query: str) -> tuple[Seen, object] | Failure:
"""The page's version and title, and the value of its body in atlas_doc_format where query asks for it; None where it doesn't."""
@@ -133,25 +117,13 @@ class ConfluencePage:
adf = body.get("atlas_doc_format") if isinstance(body, dict) else None
return Seen(number, title), adf.get("value") if isinstance(adf, dict) else None
def keep(self, seen: Seen) -> Failure | None:
self.seen = seen
if self.kept is None:
return None
def seen_of(self, over: str | None) -> Seen | Failure:
"""The version and title a write sends: those over holds, else the page's as it stands."""
if over is None:
fetched = self.fetched("")
return fetched if isinstance(fetched, Failure) else fetched[0]
try:
self.kept.parent.mkdir(parents=True, exist_ok=True)
except OSError as failure:
return Failure(f"cannot write {self.kept}: {failure.strerror}")
unwritten = replace_file(self.kept, json.dumps(dataclasses.asdict(seen)).encode())
return Failure(f"cannot write {self.kept}: {unwritten.reason}") if unwritten else None
def recalled(self) -> Seen | Failure | None:
"""The version and title the file kept holds; None where kept is None or names no file."""
if self.kept is None:
return None
try:
held: typing.Any = json.loads(self.kept.read_text(encoding="utf-8"))
held: typing.Any = json.loads(over)
return Seen(int(held["version"]), str(held["title"]))
except FileNotFoundError:
return None
except (OSError, ValueError, KeyError, TypeError) as failure:
return Failure(f"cannot read the version of {self.label} that {self.kept} keeps: {failure}")
except (ValueError, KeyError, TypeError) as failure:
return Failure(f"cannot read the version of {self.label} to write over, {over!r}: {failure}")
+14 -3
View File
@@ -1,6 +1,7 @@
"""What every record backend must hold, as tests. A backend's test case inherits RecordStoreContract and unittest.TestCase, and builds its store in new_store."""
import typing
from record_store.held import Held
from record_store.stores import RecordStore
@@ -8,6 +9,7 @@ class RecordStoreContract:
"""Runs against the store new_store returns: one that holds no record yet."""
assertEqual: typing.Callable[..., None]
assertIsNone: typing.Callable[..., None]
assertIsInstance: typing.Callable[..., None]
assertTrue: typing.Callable[..., None]
def new_store(self) -> RecordStore:
@@ -19,14 +21,23 @@ class RecordStoreContract:
def test_reads_back_what_it_wrote_to_the_character(self) -> None:
store = self.new_store()
text = "# Decisions\n\n- Å, 🔴 and a | pipe\n\n\n"
self.assertIsNone(store.write(text))
self.assertEqual(store.write(text, None), store.held())
self.assertEqual(store.read(), text)
def test_a_write_replaces_the_whole_record(self) -> None:
store = self.new_store()
store.write("first\nsecond\n")
self.assertIsNone(store.write("third\n"))
first = store.write("first\nsecond\n", None)
assert isinstance(first, Held), first
# A write over the version the last one left replaces the record, as a later save does.
self.assertIsInstance(store.write("third\n", first.version), Held)
self.assertEqual(store.read(), "third\n")
def test_holds_its_text_with_the_version_a_write_over_it_names(self) -> None:
store = self.new_store()
store.write("text\n", None)
held = store.held()
assert isinstance(held, Held), held
self.assertEqual(held.text, "text\n")
def test_names_itself_for_a_message(self) -> None:
self.assertTrue(self.new_store().label.strip())
+13 -4
View File
@@ -2,21 +2,30 @@
import dataclasses
from failure import Failure
from record_store.held import Held
@dataclasses.dataclass
class MemoryStore:
"""A record held in memory, as a backend outside git holds one. Set fails to make every read and write fail with that reason."""
"""A record held in memory, as a backend outside git holds one: versioned as a wiki page is, refusing a write over a version it no longer holds. Set fails to make every read and write fail with that reason. overs holds the version each write named, so a test can check that a caller wrote over the version it read."""
text: str = ""
label: str = "the record in memory"
tracked: str | None = None
fails: str | None = None
version: int = 0
overs: list[str | None] = dataclasses.field(default_factory=list)
def read(self) -> str | Failure:
return Failure(self.fails) if self.fails else self.text
def write(self, text: str) -> Failure | None:
def held(self) -> Held | Failure:
return Failure(self.fails) if self.fails else Held(self.text, str(self.version))
def write(self, text: str, over: str | None) -> Held | Failure:
self.overs.append(over)
if self.fails:
return Failure(self.fails)
self.text = text
return None
if over is not None and over != str(self.version):
return Failure(f"someone saved {self.label} since version {over}")
self.text, self.version = text, self.version + 1
return Held(text, str(self.version))
+9
View File
@@ -0,0 +1,9 @@
"""A record as a read found it or a write left it, which every record backend gives."""
import dataclasses
@dataclasses.dataclass(frozen=True)
class Held:
"""A record's text as one read found it or one write left it, with its version: what a write over it names, so the write refuses where someone saved the record since. None for a backend whose writes check no version, as a file's."""
text: str
version: str | None = None
+8 -3
View File
@@ -5,9 +5,10 @@ import dataclasses
import pathlib
from adf_codec.convert import adfs_to_markdown, Refused
from plan_store.jira_epic import basic_auth, Http, http_json, ToMarkdown
from atlassian.client import basic_auth, Http, jira_json, ToMarkdown
from project_config.settings import Epic
from failure import Failure
from record_store.held import Held
READ_ONLY = "goals and audience kept in Jira are only read: edit the epic's description in Jira"
@@ -17,7 +18,7 @@ class EpicDescription:
"""The description of epic as markdown, read with the credentials env_file holds."""
epic: Epic
env_file: pathlib.Path
http: Http = http_json
http: Http = jira_json
to_markdown: ToMarkdown = adfs_to_markdown
@property
@@ -49,5 +50,9 @@ class EpicDescription:
return Failure(f"cannot convert {key}'s description to markdown: {texts.reason}")
return texts[0]
def write(self, text: str) -> Failure | None:
def held(self) -> Held | Failure:
text = self.read()
return text if isinstance(text, Failure) else Held(text)
def write(self, text: str, over: str | None) -> Held | Failure:
return Failure(READ_ONLY)
+58 -25
View File
@@ -5,8 +5,11 @@ import dataclasses
import pathlib
import typing
from record_store.confluence_page import ConfluencePage
from record_store.jira_description import EpicDescription
from failure import Failure
from git_cli.git_repo import file_at, git, Git
from record_store.held import Held
from project_config.settings import ProjectConfig, RECORDS, TOUCH_PREDICTIONS
from text_files.file_writes import replace_file
@@ -25,8 +28,11 @@ class RecordStore(typing.Protocol):
def read(self) -> str | Failure:
"""The record's text as it stands, empty where it doesn't exist yet."""
def write(self, text: str) -> Failure | None:
"""Replaces the record's whole text, creating the record where it doesn't exist yet."""
def held(self) -> Held | Failure:
"""The record as it stands, with the version a write over it names."""
def write(self, text: str, over: str | None) -> Held | Failure:
"""Replaces the record's whole text, creating the record where it doesn't exist yet, and gives the record as the write left it. over is the version held() gave: where someone saved the record since, the write refuses. None replaces the record as it stands, so a caller passes it only where it read no version."""
@dataclasses.dataclass(frozen=True)
@@ -39,6 +45,10 @@ class FileStore:
def label(self) -> str:
return str(self.path)
def held(self) -> Held | Failure:
text = self.read()
return text if isinstance(text, Failure) else Held(text)
def read(self) -> str | Failure:
try:
return self.path.read_text(encoding="utf-8")
@@ -49,26 +59,24 @@ class FileStore:
except OSError as failure:
return Failure(f"cannot read {self.path}: {failure.strerror}")
def write(self, text: str) -> Failure | None:
def write(self, text: str, over: str | None) -> Held | Failure:
try:
self.path.parent.mkdir(parents=True, exist_ok=True)
except OSError as failure:
return Failure(f"cannot write {self.path}: {failure.strerror}")
unwritten = replace_file(self.path, text.encode("utf-8"))
return Failure(f"cannot write {self.path}: {unwritten.reason}") if unwritten else None
return Failure(f"cannot write {self.path}: {unwritten.reason}") if unwritten else Held(text)
def store(config: ProjectConfig, record: str, kept: pathlib.Path | None = None) -> RecordStore:
"""The store config names for record, one of RECORDS. A record on a Confluence page keeps the version it read in the file the parameter kept names, for a later process that writes it; where kept is None, the store keeps the version only in memory."""
def store(config: ProjectConfig, record: str) -> RecordStore:
"""The store config names for record, one of RECORDS."""
if record not in RECORDS:
raise ValueError(f"{record} is not a record; the records are {', '.join(RECORDS)}")
if record not in config.pages:
return FileStore(config.paths[record], config.tracked(record))
# Imported here, as in goals_store.
from record_store.confluence_page import ConfluencePage
# load refuses a config that names a page and no env-file.
assert config.env_file is not None
return ConfluencePage(config.pages[record], config.env_file, kept)
return ConfluencePage(config.pages[record], config.env_file)
def touch_predictions_store(config: ProjectConfig) -> RecordStore | None:
@@ -82,8 +90,6 @@ def goals_store(config: ProjectConfig) -> RecordStore:
"""The store config names for the goals file, which holds ## Goals and ## Audience: a markdown file, or a Jira epic's description, which the store only reads."""
if config.goals_epic is None:
return FileStore(config.paths["goals-and-audience"], config.tracked("goals-and-audience"))
# Imported here, since the Jira store builds on plan_store, which builds on this module.
from record_store.jira_description import EpicDescription
# load refuses a config that names an epic and no env-file.
assert config.env_file is not None
return EpicDescription(config.goals_epic, config.env_file)
@@ -95,27 +101,54 @@ def held_at(revision: str, record: RecordStore, cwd: str, run: Git = git) -> str
def local_file(record: RecordStore, copy: pathlib.Path) -> pathlib.Path | Failure:
"""A file holding record's text, for an agent, which reads and edits files: the record's own file where a file is its backend, else copy, written with the text as it stands. Neither exists where the record doesn't yet. `stored` puts an edited copy back."""
"""A file holding record's text, for an agent, which reads and edits files: the record's own file where a file is its backend, else copy, written with the text as it stands, and its version beside it, for `stored` to write over in a later process. Neither exists where the record doesn't yet. `stored` puts an edited copy back."""
if isinstance(record, FileStore):
return record.path
text = record.read()
if isinstance(text, Failure):
return text
if text:
return FileStore(copy, None).write(text) or copy
try:
# An earlier copy would read as the record's text, and `stored` would put it back.
copy.unlink(missing_ok=True)
except OSError as failure:
return Failure(f"cannot remove {copy}: {failure.strerror}")
return copy
held = record.held()
if isinstance(held, Failure):
return held
if held.text:
written = FileStore(copy, None).write(held.text, None)
if isinstance(written, Failure):
return written
else:
try:
# An earlier copy would read as the record's text, and `stored` would put it back.
copy.unlink(missing_ok=True)
except OSError as failure:
return Failure(f"cannot remove {copy}: {failure.strerror}")
# Kept only once the copy holds the text: a newer version beside an older copy would let a later save overwrite the edit that version holds.
return kept(copy, held.version) or copy
def stored(record: RecordStore, copy: pathlib.Path) -> Failure | None:
"""Stores in record the text of copy, the file `local_file` gave for it. Where that is the record's own file, the edit is already the record."""
"""Stores in record the text of copy, the file `local_file` gave for it, over the version kept beside it. Where that is the record's own file, the edit is already the record. The version the write left is kept for the next save."""
if isinstance(record, FileStore):
return None
text = FileStore(copy, None).read()
if isinstance(text, Failure):
return text
return record.write(text) if text else Failure(f"{copy} is missing or empty, so nothing is stored in {record.label}")
if not text:
return Failure(f"{copy} is missing or empty, so nothing is stored in {record.label}")
over = FileStore(version_file(copy), None).read()
if isinstance(over, Failure):
return over
written = record.write(text, over.strip() or None)
return written if isinstance(written, Failure) else kept(copy, written.version)
def version_file(copy: pathlib.Path) -> pathlib.Path:
"""The file beside copy that keeps the version of the record copy holds."""
return copy.with_suffix(".version")
def kept(copy: pathlib.Path, version: str | None) -> Failure | None:
"""Keeps version beside copy, or removes the file that kept an earlier one where version is None."""
if version is not None:
written = FileStore(version_file(copy), None).write(version, None)
return written if isinstance(written, Failure) else None
try:
version_file(copy).unlink(missing_ok=True)
except OSError as failure:
return Failure(f"cannot remove {version_file(copy)}: {failure.strerror}")
return None
+67 -63
View File
@@ -7,12 +7,14 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from record_store.confluence_page import ConfluencePage, error_message
from record_store.confluence_page import ConfluencePage
from rest_client.json_request import ErrorAnswer
from failure import Failure
from record_store.held import Held
from project_config.settings import Page
from record_store.contract import RecordStoreContract
from adf_codec.convert import Refused
from record_store import stores
PAGE = Page("https://acme.atlassian.net", "2293761", "confluence:https://acme.atlassian.net/wiki/spaces/ENG/pages/2293761")
URL = "https://acme.atlassian.net/wiki/api/v2/pages/2293761"
@@ -57,11 +59,10 @@ class ConfluenceCase(unittest.TestCase):
self.env = folder / "acme.env"
self.env.write_text("ATLASSIAN_EMAIL=me@example.com\nATLASSIAN_API_TOKEN=s3cret\n")
self.env.chmod(0o600)
self.kept = folder / "state" / "acme" / "decisions.version"
self.confluence = FakeConfluence()
def new_store(self, kept: pathlib.Path | None = None) -> ConfluencePage:
return ConfluencePage(PAGE, self.env, kept, self.confluence.http, to_markdown, to_adf)
def new_store(self) -> ConfluencePage:
return ConfluencePage(PAGE, self.env, self.confluence.http, to_markdown, to_adf)
class ConfluencePageContract(ConfluenceCase, RecordStoreContract):
@@ -74,60 +75,80 @@ class ConfluencePageTest(ConfluenceCase):
self.assertEqual(self.new_store().read(), "# Decisions\n")
self.assertEqual(self.confluence.calls, [("GET", f"{URL}?body-format=atlas_doc_format", AUTHORIZATION, None)])
def test_writes_markdown_as_the_version_it_read_plus_one(self) -> None:
def test_writes_markdown_as_the_version_it_is_handed_plus_one(self) -> None:
self.confluence.version = 7
store = self.new_store()
store.read()
self.assertIsNone(store.write("- a decision\n"))
held = store.held()
assert isinstance(held, Held), held
self.assertEqual(store.write("- a decision\n", held.version), Held("- a decision\n", '{"version": 8, "title": "Decisions"}'))
self.assertEqual(self.confluence.calls[-1], ("PUT", URL, AUTHORIZATION, {"id": PAGE.page_id, "status": "current", "title": "Decisions", "body": {"representation": "atlas_doc_format", "value": json.dumps(to_adf("- a decision\n"))}, "version": {"number": 8}}))
def test_refuses_to_overwrite_a_teammates_save_since_its_read_and_says_to_ask_the_human(self) -> None:
store = self.new_store()
store.read()
def test_refuses_to_overwrite_a_teammates_save_since_the_version_it_is_handed_and_says_to_ask_the_human(self) -> None:
held = self.new_store().held()
assert isinstance(held, Held), held
self.confluence.teammate_saves("their edit\n")
written = store.write("my edit\n")
written = self.new_store().write("my edit\n", held.version)
assert isinstance(written, Failure), written
self.assertIn("someone saved", written.reason)
self.assertIn("ask the human", written.reason)
self.assertIn(PAGE.spelling, written.reason)
self.assertEqual(self.new_store().read(), "their edit\n")
def test_keeps_the_version_it_read_in_its_file_for_a_later_process(self) -> None:
self.new_store(self.kept).read()
def test_keeps_no_version_itself_so_a_read_never_moves_the_version_a_write_names(self) -> None:
store = self.new_store()
held = store.held()
assert isinstance(held, Held), held
self.confluence.teammate_saves("their edit\n")
written = self.new_store(self.kept).write("my edit\n")
self.assertEqual(store.read(), "their edit\n")
written = store.write("my edit\n", held.version)
assert isinstance(written, Failure), written
self.assertIn("someone saved", written.reason)
def test_a_read_that_fails_keeps_the_version_an_earlier_read_kept(self) -> None:
self.new_store(self.kept).read()
self.confluence.teammate_saves("their edit\n")
failing = ConfluencePage(PAGE, self.env, self.kept, self.confluence.http, lambda _: Refused(0, Failure("adf-codec refused the input")), to_adf)
self.assertIsInstance(failing.read(), Failure)
self.confluence.value = "{not json"
self.assertIsInstance(self.new_store(self.kept).read(), Failure)
written = self.new_store(self.kept).write("my edit\n")
assert isinstance(written, Failure), written
self.assertIn("someone saved", written.reason)
self.assertEqual(self.confluence.version, 2)
def test_a_later_process_writes_with_the_version_an_earlier_one_read_or_wrote(self) -> None:
self.new_store(self.kept).read()
self.assertIsNone(self.new_store(self.kept).write("first\n"))
self.assertIsNone(self.new_store(self.kept).write("second\n"))
def test_a_later_write_over_the_version_an_earlier_one_left_lands(self) -> None:
held = self.new_store().held()
assert isinstance(held, Held), held
first = self.new_store().write("first\n", held.version)
assert isinstance(first, Held), first
self.assertIsInstance(self.new_store().write("second\n", first.version), Held)
self.assertEqual(self.new_store().read(), "second\n")
self.assertEqual(self.confluence.title, "Decisions")
def test_each_save_of_an_opened_copy_writes_over_the_version_the_open_or_the_last_save_left(self) -> None:
copy = self.env.parent / "copies" / "decisions.md"
self.confluence.teammate_saves("first\n")
self.assertEqual(stores.local_file(self.new_store(), copy), copy)
for text in ("mine\n", "again\n"):
copy.write_text(text)
self.assertIsNone(stores.stored(self.new_store(), copy))
self.assertEqual(self.new_store().read(), "again\n")
self.confluence.teammate_saves("theirs\n")
copy.write_text("third\n")
refused = stores.stored(self.new_store(), copy)
assert isinstance(refused, Failure), refused
self.assertIn("someone saved", refused.reason)
self.assertEqual(self.new_store().read(), "theirs\n")
def test_an_open_that_fails_keeps_the_version_an_earlier_open_kept(self) -> None:
copy = self.env.parent / "copies" / "decisions.md"
stores.local_file(self.new_store(), copy)
self.confluence.teammate_saves("their edit\n")
self.confluence.value = "{not json"
self.assertIsInstance(stores.local_file(self.new_store(), copy), Failure)
copy.write_text("my edit\n")
refused = stores.stored(self.new_store(), copy)
assert isinstance(refused, Failure), refused
self.assertIn("someone saved", refused.reason)
def test_a_write_with_no_read_replaces_the_page_as_it_stands(self) -> None:
self.confluence.teammate_saves("earlier\n")
self.assertIsNone(self.new_store().write("replaced\n"))
self.assertIsInstance(self.new_store().write("replaced\n", None), Held)
self.assertEqual(self.confluence.calls[0], ("GET", URL, AUTHORIZATION, None))
self.assertEqual(self.new_store().read(), "replaced\n")
def test_fails_on_an_answer_not_shaped_as_a_page(self) -> None:
for answer in ({}, {"title": "Decisions", "version": {}, "body": {"atlas_doc_format": {"value": ""}}}, {"version": {"number": 3}, "body": {"atlas_doc_format": {"value": ""}}}, ["not", "a", "page"]):
with self.subTest(answer):
store = ConfluencePage(PAGE, self.env, None, lambda *_: answer, to_markdown, to_adf)
store = ConfluencePage(PAGE, self.env, lambda *_: answer, to_markdown, to_adf)
read = store.read()
assert isinstance(read, Failure), read
self.assertIn("not in the shape Confluence Cloud's REST API version 2 documents", read.reason)
@@ -136,7 +157,7 @@ class ConfluencePageTest(ConfluenceCase):
for body in ({}, "text", {"atlas_doc_format": "text"}, {"atlas_doc_format": {"value": 3}}):
with self.subTest(body):
answer = {"title": "Decisions", "version": {"number": 3}, "body": body}
store = ConfluencePage(PAGE, self.env, None, lambda *_: answer, to_markdown, to_adf)
store = ConfluencePage(PAGE, self.env, lambda *_: answer, to_markdown, to_adf)
self.assertEqual(store.read(), Failure(f"{PAGE.spelling} is not in the shape Confluence Cloud's REST API version 2 documents: it holds no body in atlas_doc_format"))
def test_fails_on_a_body_that_is_not_json(self) -> None:
@@ -145,51 +166,34 @@ class ConfluencePageTest(ConfluenceCase):
def test_fails_naming_the_page_where_the_text_cannot_be_converted(self) -> None:
self.confluence.teammate_saves("text\n")
store = ConfluencePage(PAGE, self.env, None, self.confluence.http, lambda _: Failure("the shim is down"), lambda _: Failure("the shim is down"))
store = ConfluencePage(PAGE, self.env, self.confluence.http, lambda _: Failure("the shim is down"), lambda _: Failure("the shim is down"))
self.assertEqual(store.read(), Failure(f"cannot convert {PAGE.spelling} to markdown: the shim is down"))
self.assertEqual(store.write("text\n"), Failure(f"cannot convert the text for {PAGE.spelling} to ADF: the shim is down"))
self.assertEqual(store.write("text\n", None), Failure(f"cannot convert the text for {PAGE.spelling} to ADF: the shim is down"))
def test_fails_naming_the_page_where_adf_codec_refuses_its_document(self) -> None:
self.confluence.teammate_saves("text\n")
store = ConfluencePage(PAGE, self.env, None, self.confluence.http, lambda _: Refused(0, Failure("adf-codec refused the input")), to_adf)
store = ConfluencePage(PAGE, self.env, self.confluence.http, lambda _: Refused(0, Failure("adf-codec refused the input")), to_adf)
self.assertEqual(store.read(), Failure(f"{PAGE.spelling}: adf-codec refused the input"))
def test_fails_where_the_folder_of_its_file_cannot_be_made(self) -> None:
self.kept.parent.parent.mkdir(parents=True)
self.kept.parent.write_text("a file, not a folder")
read = self.new_store(self.kept).read()
assert isinstance(read, Failure), read
self.assertTrue(read.reason.startswith(f"cannot write {self.kept}: "), read.reason)
def test_a_write_confluence_refuses_otherwise_fails_naming_the_page_and_not_a_teammate(self) -> None:
answers = iter([{"title": "Decisions", "version": {"number": 3}}, ErrorAnswer("PUT /wiki/api/v2/pages/2293761 answered 403: Forbidden", 403)])
store = ConfluencePage(PAGE, self.env, None, lambda *_: next(answers), to_markdown, to_adf)
self.assertEqual(store.write("text\n"), Failure(f"cannot write {PAGE.spelling}: PUT /wiki/api/v2/pages/2293761 answered 403: Forbidden"))
store = ConfluencePage(PAGE, self.env, lambda *_: next(answers), to_markdown, to_adf)
self.assertEqual(store.write("text\n", None), Failure(f"cannot write {PAGE.spelling}: PUT /wiki/api/v2/pages/2293761 answered 403: Forbidden"))
def test_fails_where_its_file_cannot_keep_the_version(self) -> None:
self.kept.mkdir(parents=True)
read = self.new_store(self.kept).read()
assert isinstance(read, Failure), read
self.assertTrue(read.reason.startswith(f"cannot write {self.kept}: "), read.reason)
def test_fails_on_a_kept_version_it_cannot_read_and_writes_nothing(self) -> None:
self.kept.parent.mkdir(parents=True)
self.kept.write_text("{}")
written = self.new_store(self.kept).write("text\n")
def test_fails_on_a_version_it_cannot_read_and_writes_nothing(self) -> None:
written = self.new_store().write("text\n", "{}")
assert isinstance(written, Failure), written
self.assertTrue(written.reason.startswith(f"cannot read the version of {PAGE.spelling} that {self.kept} keeps: "), written.reason)
self.assertTrue(written.reason.startswith(f"cannot read the version of {PAGE.spelling} to write over, '{{}}': "), written.reason)
self.assertEqual(self.confluence.calls, [])
def test_reads_confluences_messages_from_an_error_answer(self) -> None:
self.assertEqual(error_message({"errors": [{"status": 409, "title": "Version must be incremented"}, {"title": "and more"}, "odd"]}), "Version must be incremented; and more")
self.assertEqual(error_message({"message": "Not Found"}), "Not Found")
self.assertEqual(error_message({"errors": "odd"}), "")
self.assertEqual(error_message(["odd"]), "")
def test_fails_naming_the_page_when_confluence_answers_an_error(self) -> None:
store = ConfluencePage(PAGE, self.env, None, lambda *_: ErrorAnswer("GET /wiki/api/v2/pages/2293761 answered 404: Not Found", 404), to_markdown, to_adf)
store = ConfluencePage(PAGE, self.env, lambda *_: ErrorAnswer("GET /wiki/api/v2/pages/2293761 answered 404: Not Found", 404), to_markdown, to_adf)
self.assertEqual(store.read(), Failure(f"cannot read {PAGE.spelling}: GET /wiki/api/v2/pages/2293761 answered 404: Not Found"))
def test_a_write_handed_no_version_fails_naming_the_page_where_its_version_cannot_be_read(self) -> None:
store = ConfluencePage(PAGE, self.env, lambda *_: ErrorAnswer("GET /wiki/api/v2/pages/2293761 answered 404: Not Found", 404), to_markdown, to_adf)
self.assertEqual(store.write("text\n", None), Failure(f"cannot read {PAGE.spelling}: GET /wiki/api/v2/pages/2293761 answered 404: Not Found"))
def test_fails_without_credentials_before_any_request(self) -> None:
self.env.unlink()
read = self.new_store().read()
+1 -1
View File
@@ -79,7 +79,7 @@ class EpicDescriptionTest(unittest.TestCase):
self.assertEqual(self.calls, [])
def test_writing_fails_since_the_store_only_reads(self) -> None:
found = self.store().write("## Goals\n")
found = self.store().write("## Goals\n", None)
assert isinstance(found, Failure), found
self.assertIn("Jira", found.reason)
self.assertEqual(self.calls, [])
+14 -7
View File
@@ -10,6 +10,7 @@ from record_store.confluence_page import ConfluencePage
from project_config.settings import Epic, Page, ProjectConfig
from record_store.jira_description import EpicDescription
from failure import Failure
from record_store.held import Held
from record_store.fakes import MemoryStore
from record_store.contract import RecordStoreContract
from record_store import stores
@@ -56,19 +57,19 @@ class FileStore(unittest.TestCase):
def test_a_write_that_fails_is_a_failure_naming_it(self):
(self.folder / "docs").write_text("a file where the folder goes")
path = self.folder / "docs" / "decisions.md"
written = stores.FileStore(path, None).write("text\n")
written = stores.FileStore(path, None).write("text\n", None)
self.assertIsInstance(written, Failure)
self.assertIn(f"cannot write {path}: ", written.reason)
def test_a_write_makes_each_folder_the_file_lacks(self):
path = self.folder / "records" / "acme" / "decisions.md"
self.assertIsNone(stores.FileStore(path, None).write("text\n"))
self.assertEqual(stores.FileStore(path, None).write("text\n", None), Held("text\n"))
self.assertEqual(path.read_text(), "text\n")
def test_a_write_onto_a_folder_is_a_failure_naming_it(self):
path = self.folder / "decisions.md"
path.mkdir()
written = stores.FileStore(path, None).write("text\n")
written = stores.FileStore(path, None).write("text\n", None)
self.assertIsInstance(written, Failure)
self.assertIn(f"cannot write {path}: ", written.reason)
@@ -112,7 +113,7 @@ class LocalFile(unittest.TestCase):
def test_a_file_record_is_its_own_local_file_and_no_copy_is_made(self):
record = stores.FileStore(self.folder / "decisions.md", None)
record.write("kept\n")
record.write("kept\n", None)
self.assertEqual(stores.local_file(record, self.folder / "copies" / "decisions.md"), self.folder / "decisions.md")
self.assertIsNone(stores.stored(record, self.folder / "copies" / "decisions.md"))
self.assertEqual((record.read(), (self.folder / "copies").exists()), ("kept\n", False))
@@ -142,6 +143,13 @@ class LocalFile(unittest.TestCase):
self.assertIsInstance(opened, Failure)
self.assertIn(f"cannot write {copy}: ", opened.reason)
def test_a_version_that_cannot_be_kept_beside_the_copy_is_a_failure_naming_its_file(self):
copy = self.folder / "decisions.md"
(self.folder / "decisions.version").mkdir()
opened = stores.local_file(MemoryStore("# Decisions\n"), copy)
assert isinstance(opened, Failure), opened
self.assertTrue(opened.reason.startswith(f"cannot write {self.folder / 'decisions.version'}: "), opened.reason)
def test_storing_a_missing_copy_fails_and_leaves_the_record(self):
record = MemoryStore("kept\n")
self.assertIn("is missing or empty", stores.stored(record, self.folder / "decisions.md").reason)
@@ -172,11 +180,10 @@ class Store(unittest.TestCase):
stores.store(self.config(pathlib.Path("/code/acme"), pathlib.Path("/home/me/.claude-projects/acme")), "plan")
self.assertEqual(str(refused.exception), "plan is not a record; the records are decisions, score-anchors, comprehension-history, reading-cost, changelog")
def test_a_record_on_a_confluence_page_is_that_page_keeping_its_version_where_asked(self):
def test_a_record_on_a_confluence_page_is_that_page(self):
page = Page("https://acme.atlassian.net", "2293761", "confluence:https://acme.atlassian.net/wiki/spaces/ENG/pages/2293761")
config = ProjectConfig("acme", pathlib.Path("/home/me/.claude-projects/acme"), pathlib.Path("/code/acme"), {}, pathlib.Path("/home/me/acme.env"), pages={"decisions": page})
kept = pathlib.Path("/home/me/decisions.version")
self.assertEqual(stores.store(config, "decisions", kept), ConfluencePage(page, pathlib.Path("/home/me/acme.env"), kept))
self.assertEqual(stores.store(config, "decisions"), ConfluencePage(page, pathlib.Path("/home/me/acme.env")))
class GoalsStore(unittest.TestCase):
+92
View File
@@ -0,0 +1,92 @@
"""The next chunk's pick: the plan's items weighed against the last cut, with the item the next chunk takes first, or why there is none, as chunk-preflight states it and loop-claude starts chunks by it."""
import dataclasses
from release_plan.release_standing import Cut, dated_cut, LastCut, picked, ReadyToCut, ReviewDue, standing_of, Unknown, Unplanned
from failure import Failure
from plan.todo_table import Item, NoItemsTable
from plan_store.plans import Plan
from plan.release import Release, version
from project_config import templates
@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.Standing.moved."""
into: Release
ids: tuple[int, ...]
@dataclasses.dataclass(frozen=True)
class NextChunk:
"""The plan's items, each with its detail, and `first`: the item the next chunk takes first."""
items: list[Item]
first: Item
# first's tagline and detail.
text: str
branch_template: str
# 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:
"""The branch first's worktree is on."""
return templates.branch_of(self.branch_template, self.first.id)
@dataclasses.dataclass(frozen=True)
class NoItem:
"""Why the plan names no item for the next chunk, as a sentence the worker reads."""
why: str
def cut_name(cut: LastCut) -> str | None:
"""How the preflight names the last cut: the tag, or the version under its dated CHANGELOG.md heading; None where nothing is cut."""
if cut.tag is not None:
return None if isinstance(cut.tag, Failure) else cut.tag
headed = dated_cut(cut.tag, cut.changelog)
return None if headed is None else f"{version(headed)} (dated in CHANGELOG.md)"
def plan_name(default: str, outside: str | None) -> str:
"""How the preflight names the plan it read: the default branch's todo.md, or the file or Jira epic, where the project's config puts it outside the checkout."""
return outside if outside else f"{default}'s todo.md"
def planned(read: Plan | Failure, cut: LastCut, default: str, branch: str, outside: str | None = None, item_id: int | None = None) -> NextChunk | NoItem:
"""read, 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(read, NoItemsTable):
return NoItem(f"{where} holds no items table.")
if isinstance(read, Failure):
return NoItem(f"{where} cannot be read: {read.reason}.")
found = read.items
if isinstance(cut.tag, Failure):
return NoItem(f"{default}'s tags cannot be read: {cut.tag.reason}. So which release is next cannot be told. Find the next release yourself.")
named = cut_name(cut)
last_cut = f"the last cut, {named}" if named is not None else "the start, since no release is cut yet"
weighed = standing_of(found, cut)
pick = picked(weighed, cut)
if isinstance(pick, Cut):
return NoItem(f"{where} files items under release {version(pick.release)}, which is not after {last_cut}; ask the human which release they belong to.")
if isinstance(pick, Unknown):
return NoItem(f"{where} may hold no item for the next release after {last_cut}: todo.md's texts since then, or the count of changes since then, cannot be read. Find the next release yourself.")
if isinstance(pick, ReadyToCut | ReviewDue | Unplanned):
upcoming = f"release {version(pick.release)}, the next after {last_cut}" if pick.release else f"the next release after {last_cut}"
if isinstance(pick, ReviewDue):
return NoItem(f"{where} holds no item for {upcoming}, and changes are unreleased, so that release's release review is due: no commit titled `Release review of <release>` has landed {'since the cut' if named is not None else 'yet'}. This chunk is that review, as `~/.claude/skills/larv-review/SKILL.md` → \"Release review\" says; once it merges and the release holds no item, the release is ready to cut.")
if isinstance(pick, ReadyToCut):
return NoItem(f"{where} holds no item for {upcoming}, and changes are unreleased, and its release review has landed, so that release is finished and ready to cut. The working loop stops here. If todo.md renamed that release instead, add `- <old release> renamed to <new release>` to todo.md's `## Renamed` section.")
return NoItem(f"{where} holds no item for {upcoming}, and no change is unreleased, so that release is to be planned first.")
first = pick.item
if first is None:
return NoItem(f"every item of release {version(pick.release)} in {where} waits." if pick.release is not None else f"{where}'s items table holds no item.")
held = weighed.carried
# Every carried item takes one release, the next.
over = CarriedOver(next(item.release for item in held if item.id == weighed.moved[0]), weighed.moved) if weighed.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 NextChunk(held, first, f"{first.tagline}\n\n{first.detail}".strip(), branch, over, item_id is not None)
-43
View File
@@ -1,43 +0,0 @@
"""todo.md on disk, for the tools that work on the markdown file itself: rank or check it with the texts its FilePlan reads, write it back, and give the lines ranking reports."""
import pathlib
from failure import Failure
from plan_store.stores import file_plan
from project_config.settings import ProjectConfig
from release_plan.ranking import rank, Ranked
from text_files.file_writes import replace_file
def rank_file(todo: pathlib.Path, config: ProjectConfig) -> Ranked | Failure:
"""Rank todo in place: rank the texts its FilePlan reads, and write todo where that changed it. The caller prints `report_lines`."""
texts = file_plan(config, todo).texts()
if isinstance(texts, Failure):
return texts
ranked = rank(*texts, config.readability_floor)
if isinstance(ranked, Failure):
return ranked
if ranked.text != texts[0] and (unwritten := write(todo, ranked.text)):
return unwritten
return ranked
def report_lines(todo: pathlib.Path, ranked: Ranked) -> list[str]:
"""Ranking's notes and under-bar lines, each prefixed with todo's path, as a tool prints them on stderr."""
return [f"{todo}: {line}" for line in ranked.notes + ranked.under_bar]
def check_failures(todo: pathlib.Path, config: ProjectConfig) -> list[str]:
"""Why --check fails on todo, empty when it passes."""
texts = file_plan(config, todo).texts()
if isinstance(texts, Failure):
return [texts.reason]
ranked = rank(*texts, config.readability_floor)
if isinstance(ranked, Failure):
return [ranked.reason]
unranked = [] if ranked.text == texts[0] else [f"{todo}: not ranked; run rank_todo.py on it"]
return unranked + [f"{todo}: {line}" for line in ranked.under_bar]
def write(path: pathlib.Path, text: str) -> Failure | None:
unwritten = replace_file(path.resolve(), text.encode("utf-8"))
return Failure(f"{path}: {unwritten.reason}") if unwritten else None
+47 -31
View File
@@ -2,13 +2,13 @@
import dataclasses
from git_cli.git_repo import commits_since, file_at, git, Git
from release_plan.release import dated, dated_heading_pattern, newest_tag, parsed, Release, tagged
from plan.release import dated, dated_heading_pattern, newest_tag, parsed, Release, tagged, UNRELEASED_TITLE
from failure import Failure
from release_plan.todo_table import Item, items, next_item, renames
from plan_store.stores import Plan
from plan_store import stores as plan_stores
from plan.todo_table import Item, items, next_item, renames
from plan_store.plans import Plan
from plan_store import stores as plan_stores, plans
from project_config.settings import ProjectConfig
from text_files.markdown_text import sections
from text_files.markdown_text import section, sections
from record_store import stores
from project_config import templates
@@ -38,8 +38,8 @@ class Upcoming:
"""The next release, and whether work has landed towards it, as `~/.claude/CLAUDE.md` → "Working loop" uses both."""
# The earliest release after the last cut that todo.md has named since that cut or the plan holds; without a cut, the earliest todo.md has named or the plan holds. None where there is none.
release: Release | None
# Whether it is the plan's earliest release. Also True without a cut where todo.md has never named a release and the plan holds no item.
is_earliest: bool
# Whether the plan is current: the next release is the plan's earliest, so the plan holds its items. Also True without a cut where todo.md has never named a release and the plan holds no item, since there is no release to plan, review or cut yet.
plan_is_current: bool
# Whether work has landed towards it: one or more changes are unreleased, as unreleased_changes counts them.
unreleased: bool | Failure
@@ -93,7 +93,7 @@ Pick = Next | Cut | ReadyToCut | ReviewDue | Unplanned | Unknown
class DefaultPlan:
"""What the default branch, as last fetched, holds for chunk_item."""
# The plan, a NoItemsTable where the branch holds none.
todo: Plan | Failure
plan: Plan | Failure
cut: LastCut
@@ -102,7 +102,7 @@ def project_plan(config: ProjectConfig, ref: str, root: str, run: Git = git) ->
return default_plan(root, ref, plan_stores.store(config), stores.store(config, "changelog"), config.titles, run)
def default_plan(root: str, ref: str, plan: plan_stores.PlanStore, changelog: stores.RecordStore, titles: templates.Titles, run: Git = git) -> DefaultPlan:
def default_plan(root: str, ref: str, plan: plans.PlanStore, changelog: stores.RecordStore, titles: templates.Titles, run: Git = git) -> DefaultPlan:
"""What ref, the default branch as last fetched, holds for the pick, read in the checkout at root through run. plan is the store the project's config names for its plan, changelog the store it names for the changelog, and titles its title templates."""
tag = newest_tag(root, merged_into=ref, run=run)
changes = stores.held_at(ref, changelog, root, run)
@@ -153,41 +153,57 @@ def todos_since(tag: str | None | Failure, ref: str, plan: str | None, cwd: str,
return texts
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(carried(found, cut)), cut.reviewed) if isinstance(upcoming, Upcoming) else upcoming
@dataclasses.dataclass(frozen=True)
class Standing:
"""The plan's items weighed once against the last cut, which next_release, picked and chunk-preflight all read."""
# Which version is cut, as cut_version says.
version: Release | None
# The releases todo.md has named since the cut, as named_releases reads them.
named: set[Release] | Failure
# The plan's items, each one filed under the last cut's version or earlier moved to the next release: the earliest after the cut that the plan holds or todo.md has named since. Someone cut a release while it still held those items, and the loop works on (lilleman, 2026-11-16). Where nothing is cut, or no release after the cut is known, the items stay as the plan files them, since naming a release is the human's.
carried: list[Item]
# The IDs of the items carried files under another release than the plan does, in the plan's order.
moved: tuple[int, ...]
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.
"""
def standing_of(found: list[Item], cut: LastCut) -> Standing:
"""found, the plan's items, weighed against cut."""
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]
return Standing(version, named, found, ())
held = [dataclasses.replace(item, release=max(item.release, min(after))) for item in found]
return Standing(version, named, held, tuple(was.id for was, now in zip(found, held) if was.release != now.release))
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.
def chunk_item(found: list[Item], cut: LastCut) -> Pick:
"""The pick from the plan's items, weighed against the last cut. Routing and chunk-preflight both pick with it, so they name one item."""
return picked(standing_of(found, cut), cut)
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.
def picked(weighed: Standing, cut: LastCut) -> Pick:
"""chunk_item's pick, from the plan's items already weighed against cut."""
upcoming = next_release(weighed, cut)
return pick_from(upcoming, next_item(weighed.carried), cut.reviewed) if isinstance(upcoming, Upcoming) else upcoming
def next_release(weighed: Standing, cut: LastCut) -> Upcoming | Cut | Unknown:
"""The next release after cut, and whether work has landed towards it. weighed holds the plan's items, weighed against cut.
Cut where the plan files items under the last cut's version or earlier and no later release is known to carry them to, 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 carried(found, cut)), default=None)
version = cut_version(cut)
earliest = min((item.release for item in weighed.carried), default=None)
version = weighed.version
if version is None:
return Upcoming(earliest, True, has_unreleased(cut))
if earliest is not None and earliest <= version:
return Cut(earliest)
named = named_releases(cut.todos_since)
named = weighed.named
if isinstance(named, Failure):
return Unknown()
after = {release for release in named if release > version}
@@ -219,12 +235,12 @@ def has_unreleased(cut: LastCut) -> bool | Failure:
return changes if isinstance(changes, Failure) else changes > 0
def standing(upcoming: Upcoming, first: Item | None, reviewed: bool | Failure) -> Next | ReadyToCut | ReviewDue | Unplanned | Unknown:
def pick_from(upcoming: Upcoming, first: Item | None, reviewed: bool | Failure) -> Next | ReadyToCut | ReviewDue | Unplanned | Unknown:
"""How the plan stands to upcoming, the next release. first is next_item's pick, which the pick holds where it is Next.
Unknown where the next release holds no item and the unreleased changes cannot be counted, or work has landed and git cannot say whether a release review has.
"""
if upcoming.is_earliest:
if upcoming.plan_is_current:
return Next(upcoming.release, first)
if isinstance(upcoming.unreleased, Failure):
return Unknown()
@@ -242,9 +258,9 @@ def unreleased_changes(cut: LastCut) -> int | Failure:
def unreleased_entries(changelog: str) -> int | None:
"""How many top-level `- ` entries CHANGELOG.md holds under ## Unreleased; None without that section."""
found = sections(changelog).get("Unreleased")
return None if found is None else sum(line.startswith("- ") for line in found[0].splitlines())
"""How many top-level `- ` entries CHANGELOG.md holds under its unreleased section, whose heading's title UNRELEASED_TITLE matches; None without that section."""
body = section(changelog, UNRELEASED_TITLE)
return None if body is None else sum(line.startswith("- ") for line in body)
def named_releases(todos: list[str] | Failure) -> set[Release] | Failure:
+41 -19
View File
@@ -10,20 +10,29 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from project_config.templates import BARE, Titles
from project_config.settings import DEFAULT_FLOOR, ProjectConfig, SETTINGS
from failure import Failure
from plan_store.stores import FilePlan, plan_of
from plan_store.todo_md import FilePlan, plan_of
from record_store.stores import FileStore
from test_env import isolated_env
from record_store.fakes import MemoryStore
from release_plan.todo_table import NoItemsTable
from release_plan import release_standing
from release_plan import todo_table
from release_plan.release import version
from release_plan import next_chunk, release_standing
from plan.todo_table import NoItemsTable
from plan_store.plans import Plan
from plan import todo_table
from plan.release import version
HEADER = "## Items\n\n| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |\n|---|---|---|---|---|---|---|---|---|---|---|---|\n"
ROW = "| {id} | {release} | | | **Do {id}.** | 1 | 1 | 1 | 1 | 1 | 1 by 1 | 10.0 |\n"
def next_of(found: list[todo_table.Item], cut: release_standing.LastCut) -> release_standing.Upcoming | release_standing.Cut | release_standing.Unknown:
return release_standing.next_release(release_standing.standing_of(found, cut), cut)
def carried_of(found: list[todo_table.Item], cut: release_standing.LastCut) -> list[todo_table.Item]:
return release_standing.standing_of(found, cut).carried
def plan_at(path: pathlib.Path, tracked: str | None) -> FilePlan:
"""The markdown plan at path, which these tests only read."""
return FilePlan(path, tracked, FileStore(path.parent / "README.md", None), MemoryStore(), MemoryStore(), DEFAULT_FLOOR)
@@ -68,40 +77,41 @@ class NextRelease(unittest.TestCase):
)
for tag, earliest, named, upcoming in cases:
with self.subTest(tag=tag, earliest=earliest, named=named):
self.assertEqual(release_standing.next_release(plan_under(earliest), release_standing.LastCut(tag, "", 4, naming(named))), upcoming)
self.assertEqual(next_of(plan_under(earliest), release_standing.LastCut(tag, "", 4, naming(named))), upcoming)
def test_says_work_has_landed_towards_it_where_a_change_is_unreleased(self):
cut = lambda changes: release_standing.LastCut("v1.2.3", "", changes, naming({(1, 3, 0)}))
self.assertEqual(release_standing.next_release([one((1, 3, 0))], cut(4)), release_standing.Upcoming((1, 3, 0), True, True))
self.assertEqual(release_standing.next_release([one((1, 3, 0))], cut(0)), release_standing.Upcoming((1, 3, 0), True, False))
self.assertEqual(release_standing.next_release([one((1, 3, 0))], cut(Failure("count unreadable"))), release_standing.Upcoming((1, 3, 0), True, Failure("count unreadable")))
self.assertEqual(next_of([one((1, 3, 0))], cut(4)), release_standing.Upcoming((1, 3, 0), True, True))
self.assertEqual(next_of([one((1, 3, 0))], cut(0)), release_standing.Upcoming((1, 3, 0), True, False))
self.assertEqual(next_of([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, []))
carried = carried_of(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)
self.assertIs(carried_of(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([item.release for item in carried_of(held, cut)], [(1, 3, 0), (1, 4, 0)])
self.assertEqual(release_standing.standing_of(held, cut).moved, (held[0].id,))
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])
self.assertEqual(carried_of(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)))
self.assertEqual(next_of(held, cut), release_standing.Upcoming((1, 3, 0), True, True))
self.assertEqual(next_of(held[:1], cut), release_standing.Cut((1, 2, 3)))
class ChunkItem(unittest.TestCase):
@@ -292,7 +302,7 @@ class ChunkItem(unittest.TestCase):
run("add", "CHANGELOG.md")
run("commit", "-q", "-m", "Date 0.2.0")
held = release_standing.default_plan(repo, "main", plan_in(repo), changelog_of(repo), BARE)
self.assertEqual(held.todo, plan_of(HEADER + ROW.format(id=1, release="0.2.0")))
self.assertEqual(held.plan, plan_of(HEADER + ROW.format(id=1, release="0.2.0")))
self.assertEqual(held.cut, release_standing.LastCut("v0.1.0", "# Changelog\n\n## 0.2.0 - 2026-10-03\n", 1, [HEADER + ROW.format(id=1, release="0.2.0")], False))
self.assertEqual(release_standing.chunk_item(plan_under((0, 2, 0)), held.cut), release_standing.Next((0, 2, 0), one((0, 2, 0))))
@@ -305,17 +315,17 @@ class ChunkItem(unittest.TestCase):
run("add", "todo.md")
run("commit", "-q", "-m", "A todo.md the project's owners keep")
held = release_standing.default_plan(repo, "main", plan_at(folder / "todo.md", None), FileStore(folder / "CHANGELOG.md", None), BARE)
self.assertIsInstance(held.todo, NoItemsTable, "neither file exists yet")
self.assertIsInstance(held.plan, NoItemsTable, "neither file exists yet")
self.assertEqual(held.cut, release_standing.LastCut(None, "", 1, [], False))
plan = HEADER + ROW.format(id=2, release="0.2.0")
(folder / "todo.md").write_text(plan)
(folder / "CHANGELOG.md").write_text("# Changelog\n\n## 0.1.0 - 2026-10-03\n")
held = release_standing.default_plan(repo, "main", plan_at(folder / "todo.md", None), FileStore(folder / "CHANGELOG.md", None), BARE)
self.assertEqual(held.todo, plan_of(plan))
self.assertEqual(held.plan, plan_of(plan))
self.assertEqual(held.cut, release_standing.LastCut(None, "# Changelog\n\n## 0.1.0 - 2026-10-03\n", 1, [], False), "no commit holds an earlier plan")
(folder / "todo.md").write_bytes(b"\xff")
unreadable = release_standing.default_plan(repo, "main", plan_at(folder / "todo.md", None), changelog_of(repo), BARE)
self.assertEqual((unreadable.todo, unreadable.cut.todos_since), (Failure(f"{folder}/todo.md: not UTF-8"), []))
self.assertEqual((unreadable.plan, unreadable.cut.todos_since), (Failure(f"{folder}/todo.md: not UTF-8"), []))
def test_reads_the_checkout_only_through_the_git_it_is_given(self):
repo = tempfile.mkdtemp()
@@ -343,6 +353,10 @@ class ChunkItem(unittest.TestCase):
self.assertEqual(release_standing.unreleased_entries("# Changelog\n\n## Unreleased\n\n- One.\n - A nested line.\n- Two.\n\n## 0.1.0\n\n- Old.\n"), 2)
self.assertEqual(release_standing.unreleased_entries("# Changelog\n\n## Unreleased\n\n## 0.1.0\n\n- Old.\n"), 0)
self.assertIsNone(release_standing.unreleased_entries("# Changelog\n\n## 0.1.0\n\n- Old.\n"))
# A heading inside a code fence doesn't end the section.
self.assertEqual(release_standing.unreleased_entries("# Changelog\n\n## Unreleased\n\n- One.\n\n```\n## 0.1.0\n```\n\n- Two.\n\n## 0.1.0\n\n- Old.\n"), 2)
# The section todo-item finish files a bullet under, as a project's own changelog may head it.
self.assertEqual(release_standing.unreleased_entries("# Changelog\n\n## 0.6.0 (unreleased)\n\n- One.\n\n## 0.5.0\n\n- Old.\n"), 1)
def test_names_each_release_a_todo_md_since_the_last_cut_filed_items_under(self):
texts = [HEADER + ROW.format(id=1, release="0.2.0"), "", "not a table | x |", HEADER + ROW.format(id=2, release="0.3.0")]
@@ -367,3 +381,11 @@ class ChunkItem(unittest.TestCase):
def test_fails_to_name_releases_when_the_newest_plan_marks_one_in_a_form_it_cannot_read(self):
plan = "## Items\n\n| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |\n|---|---|---|---|---|---|---|---|---|---|---|---|\n| 1 | 0.3.0 | | | **Do 1.** | 1 | 1 | 1 | 1 | 1 | 1 by 1 | 10.0 |\n"
self.assertIsInstance(release_standing.named_releases([plan, plan + "\n## Renamed\n\nsoon\n"]), Failure)
class NextChunk(unittest.TestCase):
def test_names_the_release_a_carried_item_moved_to_not_another_items(self):
later, carried, next_one = (dataclasses.replace(one(release), id=id_) for id_, release in ((9, (0, 4, 0)), (5, (0, 2, 0)), (3, (0, 3, 0))))
planned = next_chunk.planned(Plan([later, carried, next_one]), release_standing.LastCut("v0.2.0", "", 4, []), "origin/main", "item-{id}")
assert isinstance(planned, next_chunk.NextChunk), planned
self.assertEqual(planned.carried, next_chunk.CarriedOver((0, 3, 0), (5,)))

Some files were not shown because too many files have changed in this diff Show More