Compare commits

...

61 Commits

Author SHA1 Message Date
lilleman 73f7cf1a62 Drop item 352 from the plan: shipped
CI / tests (pull_request) Successful in 2m46s
2026-11-15 03:55:46 +01:00
lilleman a9c15b79a0 Answer product-owner round 2: 0 🔴, 0 🟡 (0 misread); every answer holds 2026-11-15 03:46:21 +01:00
lilleman 155f1e873c Answer stability round 2: 1 🔴, 0 🟡 (0 misread); read an empty answer to a new link as success, and skip a Fix Version whose name is no text 2026-11-15 03:46:03 +01:00
lilleman 0aa89d283e Test a Fix Versions answer that is no list 2026-11-15 03:42:32 +01:00
lilleman 669a2833c5 Answer prose round 1: 3 🔴, 7 🟡 (1 misread); make the help and PlanStore true of a filed issue, and name items by ID (fixed in the stability round's commit) 2026-11-15 03:35:48 +01:00
lilleman fe31d6eae5 Answer product-owner round 1: 1 🔴, 3 🟡 (0 misread); file under the Fix Version as the project spells it, and check it before filing (fixed in the stability round's commit) 2026-11-15 03:35:48 +01:00
lilleman 35f1f5e70f Answer stability round 1: 2 🔴, 2 🟡 (0 misread); count an item as filed once Jira holds it, try every link, say when a failed create may have filed, and drop README's stale sentence 2026-11-15 03:35:48 +01:00
lilleman af8e7ad3d1 Answer security round 1: 0 🔴, 0 🟡 (0 misread); nothing to change 2026-11-15 03:30:15 +01:00
lilleman 2a7018dc43 Pin each filing failure's message and the links' method 2026-11-15 03:24:22 +01:00
lilleman a0945b6dae Record the chunk's reading cost
CI / tests (pull_request) Successful in 2m8s
2026-11-15 03:17:33 +01:00
lilleman 800f7b3031 Sort the Jira store's imports and spell a citation as the check asks 2026-11-15 03:17:25 +01:00
lilleman 8e79cb7dc8 File a plan item as a child issue of the project's Jira epic 2026-11-15 03:16:11 +01:00
lilleman 6804b9496e Split item 352 into items 352, 382, 383 and 384 2026-11-15 03:12:53 +01:00
lilleman 50d34ce804 Re-score item 352: L 3 to 4 2026-11-15 03:10:17 +01:00
lilleman 05f8136b0f Drop item 373: shipped
CI / tests (pull_request) Successful in 2m4s
2026-11-15 03:04:08 +01:00
lilleman 1bc63d930c Answer prose round 1: 0 🔴, 9 🟡 (0 misread); say which item each sentence means, name the path setting to copy, and stop pointing at an item the plan lacks (fixed in the stability round's commit)
CI / tests (pull_request) Successful in 2m4s
2026-11-15 03:03:49 +01:00
lilleman 87049dd077 Answer product-owner round 1: 0 🔴, 1 🟡 (0 misread); give a name that holds a backtick a spelling, and file item 381 for a plan kept in Jira (fixed in the stability round's commit) 2026-11-15 03:03:49 +01:00
lilleman e171260c36 Answer stability round 1: 0 🔴, 6 🟡 (0 misread); leave blank lines and empty files out of what a chunk touched, spell a name that holds a backtick as Markdown does, pin two mutants, and sort a chunk's IDs 2026-11-15 03:03:49 +01:00
lilleman c38810e06e Test that a chunk of two items replaces its own entry
CI / tests (pull_request) Successful in 2m18s
2026-11-15 02:41:41 +01:00
lilleman 563adfbe37 Test the cases whose mutants survived: ranges, renames, non-UTF-8 text, reading on past a skipped or whole file 2026-11-15 02:37:09 +01:00
lilleman 11999981b3 Answer security round 1: 0 🔴, 0 🟡 (0 misread); nothing to change 2026-11-15 02:30:44 +01:00
lilleman 3ea3d5427e Pick the chunks that may run at once by predicted parts, and record each prediction beside what the merged chunk touched
CI / tests (pull_request) Successful in 2m47s
2026-11-15 02:29:38 +01:00
lilleman 06e4570e2e Re-score item 373 at L 4 and S 6 after the first read of the code
CI / tests (pull_request) Successful in 3m6s
2026-11-15 02:14:56 +01:00
lilleman 7afc08e280 Drop items 377 and 380: shipped
CI / tests (pull_request) Successful in 2m18s
2026-11-15 02:05:32 +01:00
lilleman a744154bd9 Answer product-owner round 1: 0 🔴, 2 🟡 (0 misread); keep the table rule to todo.md, and stop saying a shell-less reviewer opens the file (fixed in the stability round's commit)
CI / tests (pull_request) Successful in 3m23s
2026-11-15 02:04:05 +01:00
lilleman 8736402eef Answer prose round 1: 0 🔴, 8 🟡 (0 misread); scope the Jira sentences and the table rule to the plan they are true for, define the plan in one clause, and shorten the Plan: clauses (fixed in the stability round's commit) 2026-11-15 02:04:05 +01:00
lilleman 156d466703 Answer stability round 1: 0 🔴, 3 🟡 (0 misread); drop the caveat the plan listing outlived, name the listing in reviewer_header's docstring, shorten the help's new clause 2026-11-15 02:04:05 +01:00
lilleman e95826ae60 Answer security round 1: 0 🔴, 0 🟡 (0 misread); nothing to change 2026-11-15 01:59:53 +01:00
lilleman c264c1cda4 List an item's detail as the store gives it 2026-11-15 01:59:46 +01:00
lilleman ae0fba2ecd Kill the mutants of the plan listing's blocker join and detail strip 2026-11-15 01:59:05 +01:00
lilleman 4cd55dd437 Sort the plan listing's imports
CI / tests (pull_request) Successful in 2m19s
2026-11-15 01:29:48 +01:00
lilleman 48e1e9dedc Define the plan as the store its config names and reword the lines that say todo.md where a Jira plan makes them false 2026-11-15 00:43:11 +01:00
lilleman c4ed9f1592 Hand a reviewer without a shell the plan as a listing larv-review writes into the review folder 2026-11-15 00:41:51 +01:00
lilleman 6349beaf8a Drop items 362 and 363: shipped
CI / tests (pull_request) Successful in 2m22s
2026-11-15 00:33:35 +01:00
lilleman dd1a8fc203 Answer stability round 1: 0 🔴, 4 🟡 (0 misread); type each backend's config, pass the notifier table in place of an http override, type the notifier setting, list notifier/ among the shared packages
CI / tests (pull_request) Successful in 2m36s
2026-11-15 00:33:09 +01:00
lilleman eb692daee2 Kill the mutants of the notifier's help, its env-file check, its config lookup and Slack's quoting 2026-11-15 00:26:27 +01:00
lilleman ad70ec6dad Answer prose round 1: 0 🔴, 9 🟡 (0 misread); say DM throughout, untangle the notifier's help, error and README lines, and sort the new README bullets 2026-11-14 23:36:30 +01:00
lilleman a8d0a9011c Answer product-owner round 1: 0 🔴, 0 🟡 (0 misread); escape the characters Slack reads as control characters, and say the DM isn't only Mattermost's 2026-11-14 23:36:30 +01:00
lilleman 6a553b9574 Name each project's notifier in its config, with Mattermost and Slack as backends
CI / tests (pull_request) Successful in 2m3s
2026-11-14 22:53:00 +01:00
lilleman f648f4235a Sort the floor's imports where the default left them
CI / tests (pull_request) Successful in 2m0s
2026-11-14 22:15:34 +01:00
lilleman 0a664ae889 Answer prose round 1: 0 🔴, 7 🟡 (0 misread); untangle the floor's help, comments and changelog, and list what tooling-on-host covers one way 2026-11-14 22:12:07 +01:00
lilleman 6862420b51 Answer product-owner round 1: 0 🔴, 0 🟡 (0 misread); say the floor may be set either way, and ask for a bare number 2026-11-14 22:12:07 +01:00
lilleman ea0910d60d Answer stability round 1: 0 🔴, 2 🟡 (0 misread); test the config's floor in record-scoring's Floor and Next lines, make ranking ask for the floor, fail a huge integer floor by name 2026-11-14 22:12:07 +01:00
lilleman 68f867e74b Test that the plan store ranks every write with the config's floor 2026-11-14 21:57:06 +01:00
lilleman f8958fbfe0 Test that ranking reads the floor the config sets, and name the project's floor throughout the Floor item 2026-11-14 21:50:00 +01:00
lilleman 9dba8e97be Answer security round 1: 0 🔴, 0 🟡 (0 misread); no findings 2026-11-14 21:44:45 +01:00
lilleman c97e4ad21b Let a project's config allow its tooling on the host and set its readability floor
CI / tests (pull_request) Successful in 3m3s
2026-11-14 21:43:51 +01:00
lilleman fc5e78ba88 Finish item 353: take a project's goals and audience from a Jira epic's description
CI / tests (pull_request) Successful in 2m8s
2026-11-14 21:30:36 +01:00
lilleman 5c05520f1d Name the goals file among what project-record opens in the README 2026-11-14 21:27:37 +01:00
lilleman 68808e7eee Answer prose round 1: 0 🔴, 8 🟡 (0 misread); reword the README paragraph, help, docstrings and messages 2026-11-14 21:27:23 +01:00
lilleman b514dcfe85 Answer product-owner round 1: 0 🔴, 2 🟡 (1 misread); open the goals file with project-record, and say in the help where it prints 2026-11-14 21:27:23 +01:00
lilleman 3a2d72a007 Answer stability round 1: 0 🔴, 4 🟡 (0 misread); keep goals in Jira to projects whose plan is there, test the reviewer header's Jira read, drop the repeated premises tests 2026-11-14 21:27:23 +01:00
lilleman e38e45579f Answer security round 1: 0 🔴, 0 🟡 (0 misread) 2026-11-14 21:09:49 +01:00
lilleman 0d16290e38 Test each message read_premises fails with 2026-11-14 21:08:44 +01:00
lilleman 55967b5fa6 Take a project's goals and audience from a Jira epic's description where its config names one
CI / tests (pull_request) Successful in 2m1s
2026-11-14 21:01:50 +01:00
lilleman 8363514fe9 Record the reading cost before item 353's first commit 2026-11-14 21:01:47 +01:00
lilleman 415d1dc704 Re-score item 353 at L 3 and S 5, since it reaches six components 2026-11-14 20:47:02 +01:00
lilleman c99c53202d Answer product-owner round 1: 0 🔴, 0 🟡 (0 misread)
CI / tests (pull_request) Successful in 2m56s
2026-11-14 20:40:07 +01:00
lilleman 22265462e0 Answer prose round 1: 0 🔴, 2 🟡 (0 misread); reword the Jira template paragraph, README sentence and changelog bullet 2026-11-14 20:40:07 +01:00
lilleman 20f8ba29da Answer stability round 1: 0 🔴, 1 🟡 (0 misread); delete the test that repeats the PAY-{id} cases 2026-11-14 20:40:07 +01:00
lilleman 2b4c8b4cab Finish item 378: name a Jira plan's chunks by the issue key through the branch and title templates
CI / tests (pull_request) Successful in 2m7s
2026-11-14 20:37:30 +01:00
80 changed files with 2791 additions and 514 deletions
+8 -1
View File
@@ -67,7 +67,6 @@
!bin/loop_state/*.py
!bin/machine_load/
!bin/machine_load/*.py
!bin/mattermost-dm
!bin/mattermost_dm/
!bin/mattermost_dm/*.py
!bin/metric-bench
@@ -78,6 +77,9 @@
!bin/mutate-changes
!bin/mutate_changes/
!bin/mutate_changes/*.py
!bin/notifier/
!bin/notifier/*.py
!bin/notify
!bin/plan_store/
!bin/plan_store/*.py
!bin/project-config
@@ -123,6 +125,8 @@
!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/
@@ -133,6 +137,9 @@
!bin/todo-item
!bin/todo_item/
!bin/todo_item/*.py
!bin/touch-predictions
!bin/touch_predictions/
!bin/touch_predictions/*.py
!bin/transcript_archive/
!bin/transcript_archive/*.py
!bin/wait-for
+11 -2
View File
@@ -2,6 +2,14 @@
## Unreleased
- `todo-item add` files an item into a plan kept in a Jira epic: a Task under the epic, under the project's Fix Version for the release, labelled `security` for a security finding and linked to each item that blocks it. Editing and finishing an issue still happen in Jira.
- An item of the next release may predict the files and parts it will touch, under a `Touches:` line in its detail. `chunk-preflight` then names the items that may start chunks at once, and the new `touch-predictions record` keeps each prediction beside what the merged chunk touched, in the record a project's config places with `touch-predictions`.
- CLAUDE.md and the todo-items rule define the plan as a todo.md or a Jira epic, and say plan where todo.md was false for a Jira plan.
- Reviewers without a shell read the plan from a listing that larv-review writes into the review folder, whichever store holds it.
- 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.
- A project whose plan is a Jira epic can keep its goals and audience in an epic's description too: set `goals-and-audience = "jira:https://<site>/browse/<KEY>"`. The loop only reads it, and `project-record open goals-and-audience` prints a file holding its text.
- A project with a Jira plan can name each chunk's branch, worktree, commits and pull request by the issue key, as in `ABC-123` and `ABC-123 - …`. The README shows the three templates to set.
- A read of a plan in a Jira epic converts every issue description in one `adf_codec` container run, however many issues the epic holds. The codec builds its image inside one of the machine's heavy slots that `run-heavy` shares, so sessions reading at once build it once.
- A project config may name its plan as `jira:https://<site>/browse/<KEY>`: the plan is then read from the open child issues of that Jira Cloud epic, in backlog order, with the credentials in the config's `env-file`. Such a plan is only read so far: file, edit and finish its issues in Jira.
- A new `adf_codec` package converts markdown to ADF, the rich text of Jira Cloud and Confluence, and back with `@larvit/adf-codec` 0.3.1. It runs in a pinned Node container with a memory limit and no network, and returns adf-codec's error codes as a `Failure`. No tool calls it yet.
@@ -11,9 +19,10 @@
- The technical principles ask for code in files and folders before `// --- name ---` banner comments. They also ask for an entry point a newcomer finds at once: the root holds it, the README and the files a tool reads only from there.
- In a client project, the loop reads the team's own `CLAUDE.md` and `AGENTS.md` and proposes each change that aligns them with this setup in a pull request of its own. Where the team declines or doesn't answer, the loop follows the team's rule unless it breaks a project goal, and records the conflict as a decision in the `decisions` record.
- The new `project-record open <record>` prints the file in which an agent reads and edits one of a project's five records (`decisions`, `score-anchors`, `comprehension-history`, `reading-cost` and `changelog`), and `project-record save <record>` stores the edit. Every tool now reads and writes a record the same one way, so that a later release can keep a record outside files. No config needs a change.
- `loop-inbox` is gone. loop-claude now asks its questions only on its own terminal. A line typed there answers a question, and `/talk` opens the worker's session. The Mattermost DM still tells you a loop waits. To upgrade, quit any `loop-inbox` still open and remove your `~/.local/bin/loop-inbox` link. Once every loop started before the upgrade has reloaded or ended, remove the folder `~/.local/state/loop-claude/`, which nothing reads any more.
- `loop-inbox` is gone. loop-claude now asks its questions only on its own terminal. A line typed there answers a question, and `/talk` opens the worker's session. The DM still tells you a loop waits. To upgrade, quit any `loop-inbox` still open and remove your `~/.local/bin/loop-inbox` link. Once every loop started before the upgrade has reloaded or ended, remove the folder `~/.local/state/loop-claude/`, which nothing reads any more.
- 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.
- To keep Mattermost DMs, move the keys from `~/.claude/.env` into a file outside the checkout and the config's folder, such as `~/.claude-projects/<key>.env`, and name it in the project's config as `env-file`; `mattermost-dm` and loop-claude's DMs no longer read `~/.claude/.env`, and a project with no `env-file` gets none. A failure names each missing key and holds no token.
- A project's config names the service for loop-claude's DMs: `notifier = "mattermost"` or `"slack"`, with the bot's token and the recipient in the `env-file`. To upgrade, move the Mattermost keys from `~/.claude/.env` into a file outside the checkout and the config's folder, such as `~/.claude-projects/<key>.env`, name it as `env-file` and add `notifier = "mattermost"`. A project with no `notifier` gets no DM, and `~/.claude/.env` is no longer read. A failure names each missing key and holds no token.
- `mattermost-dm` is now `notify`, which sends through the project's `notifier`; `notify --help` names the keys.
## 0.10.0
+16 -16
View File
@@ -2,24 +2,24 @@
## Working loop
How work proceeds in any repo, unless the repo's `AGENTS.md` says otherwise. The *next release* is the earliest one not yet cut. A rule names a project's files by their usual paths: `todo.md`, `AGENTS.md`, `CHANGELOG.md` and the files under `docs/`. Each is where the project's config puts it, which `~/.claude/bin/project-config` prints and `chunk-preflight`'s facts quote. Read and edit a project record in the file `~/.claude/bin/project-record open <record>` prints, and run `project-record save <record>` after each edit. Other words, such as *chunk*, are defined under "Vocabulary" at the end of this file.
How work proceeds in any repo, unless the repo's `AGENTS.md` says otherwise. The *next release* is the earliest one not yet cut. A rule names a project's files by their usual paths: `todo.md`, `AGENTS.md`, `CHANGELOG.md` and the files under `docs/`. Each is where the project's config puts it, which `~/.claude/bin/project-config` prints and `chunk-preflight`'s facts quote. Where the config names a Jira epic as the plan, the plan is the epic's open child issues. Read and edit a project record in the file `~/.claude/bin/project-record open <record>` prints, and run `project-record save <record>` after each edit. Other words, such as *chunk*, are defined under "Vocabulary" at the end of this file.
- **Until the goals file has a `## Goals` and an `## Audience` section, writing them is the only work.** Not even planning in `todo.md`. In a README both are public: an outside reader judges a project by where it is heading and who it is for. Goals or an audience written anywhere else, such as `AGENTS.md` or `docs/`, do not count; the one exception is code health, which "Shared goal" below states for every project.
- **Plan `todo.md` as one scored table, in the shape whose example `~/.claude/bin/rank_todo.py --help` shows**: every item names the release that ships it. Until `todo.md` has that shape, reshaping it is the only work, and the human approves it.
- **Read and change the plan's items only with `~/.claude/bin/todo-item`**, which lists, shows, files, edits, moves and finishes them; `todo-item --help` says how. It works the same whatever holds the plan. Three open the file itself: a reviewer without a shell; whoever plans a release, to compare Scores across releases, which `todo-item list` doesn't print; and whoever edits `## Scoring` or `## Renamed`, or reshapes an old table.
- **Until the goals file has a `## Goals` and an `## Audience` section, writing them is the only work.** Not even planning. In a README both are public: an outside reader judges a project by where it is heading and who it is for. Goals or an audience written anywhere else, such as `AGENTS.md` or `docs/`, do not count; the one exception is code health, which "Shared goal" below states for every project.
- **Keep a plan in `todo.md` as one scored table, in the shape whose example `~/.claude/bin/rank_todo.py --help` shows**: every item names the release that ships it. Until `todo.md` has that shape, reshaping it is the only work, and the human approves it.
- **Read and change the plan's items only with `~/.claude/bin/todo-item`**, which lists, shows, files, edits, moves and finishes them; `todo-item --help` says how. It reads a plan in Jira as it does a file, and there it files an item but doesn't edit, move or finish one yet. Two open the file itself: whoever plans a release, to compare Scores across releases, which `todo-item list` doesn't print; and whoever edits `## Scoring` or `## Renamed`, or reshapes an old table.
- **When the next release has no items and no work has landed towards it, plan it as this chunk.** Move the highest-scoring items of later releases into it, and get the human's approval of that set before writing any code.
- **When the next release has no items left and work has landed towards it, its release review is the chunk** (`larv-review` §3 → "Release review"). **Once that has merged and the release holds no item, the release is finished: stop.** Report what it holds and that it is ready to cut. Under `/loop`, this ends the loop. Until the human cuts it, only a security fix, or an item its release review filed, lands, into that release; never start a later release's items or plan a new one.
- **Open every chunk with one line:** the last version cut, how many changes are unreleased (the entries under `CHANGELOG.md` → `## Unreleased`, or else the commits since the last tag), and the release this chunk ships into. A repo that doesn't publish anything says so once.
- **A client project's `CLAUDE.md` and `AGENTS.md` in its repo belong to its team.** Read both at the start of each chunk there. Propose each change that aligns them with this setup in a pull request of its own, never inside a chunk's; the one edit a chunk makes there is a decision's title in `AGENTS.md`. Until the team accepts a proposal, and after it declines or doesn't answer, follow the team's rule unless it breaks one of the project's goals. Record each such conflict as a decision in the `decisions` record, as `rules/decisions.md` asks: which rule you follow, why, and the open proposal's PR. Then nobody is asked twice.
- **Read the goals file's `## Goals` and `## Audience` before starting a chunk, unless your prompt quotes them.** The chunk's items set its scope. The goals choose between ways to deliver those items, and never add to them.
- **Read the plan and the decisions only as far as the chunk needs.** Where your prompt quotes `chunk-preflight`'s facts, they hold the next item's L, E + I, tagline and detail, and each item that may join it with its L, E + I, S, tagline and detail; run `todo-item` only for what they leave out. Otherwise run `~/.claude/bin/todo-item list`, which prints every item's row in the plan's order, without details. Then read the details of only the items the chunk takes, with `~/.claude/bin/todo-item show <ID>`, which prints an item's row and detail. `AGENTS.md` lists the project principles and the title of each decision no project principle covers. Read an entry in `docs/decisions.md` only where the project principle or the title leaves open what the chunk or the review needs.
- **Work one chunk at a time, and put every item that can share its review into it.** Every review has a fixed cost, so a chunk takes the next plan item plus every other item for which three things hold: they name one release; they fire the same review passes (`larv-review` §3); and no item outside the chunk blocks one of them. The items need not share a purpose. An item whose risk R, in `todo.md`, is above 5 ships alone: it joins no chunk, and none joins it. The next plan item is the first that does not wait: an item waits while it is marked `question`, until the human answers, or while an item that blocks it is still in the plan. Tiny items, a few lines of change each, need not fire the same passes: bundle up to ten that name one release, and that no item outside the chunk blocks, into one chunk. Split a milestone into items in `todo.md` before starting it. Fix a finding in the chunk's own change within the chunk. File a finding about anything else in `todo.md`.
- **Work one chunk at a time, and put every item that can share its review into it.** Every review has a fixed cost, so a chunk takes the next plan item plus every other item for which three things hold: they name one release; they fire the same review passes (`larv-review` §3); and no item outside the chunk blocks one of them. The items need not share a purpose. An item whose risk R, in the plan, is above 5 ships alone: it joins no chunk, and none joins it. The next plan item is the first that does not wait: an item waits while it is marked `question`, until the human answers, or while an item that blocks it is still in the plan. Tiny items, a few lines of change each, need not fire the same passes: bundle up to ten that name one release, and that no item outside the chunk blocks, into one chunk. Split a milestone into items in the plan before starting it. Fix a finding in the chunk's own change within the chunk. File a finding about anything else in `todo.md`.
- **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.
- **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 `todo.md` 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`.
- **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.
## Shared goal
@@ -27,7 +27,7 @@ How work proceeds in any repo, unless the repo's `AGENTS.md` says otherwise. The
Every project pursues the achieve goal below, ranked above every achieve goal its goals file states. A project whose code nobody will maintain voids it with one line under `## Goals`, before the numbered goals: `**Void:** code health, since <reason>.` So does a project that opts out of the comprehension check, since the goal then has no signal. An item's Moves cell names it as in `code health by 6`, and `rank_todo.py --help` says how much it weighs.
**Achieve:** Code health: the code stays easy to read, change safely and debug, tomorrow and after seven years of development.
- Signal: the comprehension panel's overall score rises, always. Under 7.0 it is very important.
- Signal: the comprehension panel's overall score rises, always. Under the project's readability floor it is very important. The floor is 7.0, unless the project's config sets `readability-floor`.
- Counter-signal: defects keep reappearing in functionality that already shipped, or reviewers raise blockers because the implementer misunderstood the current system.
- Why: a score that rises while changes still misread the code measures the wrong thing.
@@ -58,21 +58,21 @@ Claude Code loads a rule file when a session writes a file its `paths:` frontmat
- The decision log: `~/.claude/rules/decisions.md`.
- Goals and audience: `~/.claude/rules/goals-and-audience.md`.
- `todo.md` items, their scores and Exempt reasons: `~/.claude/rules/todo-items.md`. Read it before you file, score, edit or move an item: a session that runs `todo-item` never opens `todo.md` itself, so the rule doesn't load.
- Plan items, their scores and Exempt reasons: `~/.claude/rules/todo-items.md`. Read it before you file, score, edit or move an item: a session that runs `todo-item` never opens `todo.md` itself, so the rule doesn't load.
The rules only reviewers apply, for quality, comments, READMEs and prose, live in `~/.claude/skills/larv-review/standards/`.
## Working with the codebase
- Always start a new git worktree when doing something in a codebase, and clean it up when done. Unless told otherwise, branch it off a freshly-updated default branch (`git fetch origin`, then base on `origin/main`), not whatever happens to be checked out.
- Keep the project's main checkout (e.g. `~/code/log`, never a worktree) current: when it is behind `origin` — a merge landed, or a fetch shows it — run `git pull --ff-only` there instead of reporting the lag, never with `--autostash`: a dirty checkout is a finding to report, not to carry along.
- Run a project's language runtime, package manager, and task runner through its container/tooling setup, never directly on the host unless a decision puts them there. Example: `docker compose run --rm app <tool> …`.
- Run a project's language runtime, package manager, and task runner through its container/tooling setup, never directly on the host, unless the project's config sets `tooling-on-host = true` or a decision puts them there. Example: `docker compose run --rm app <tool> …`.
- Tear down test containers after a run.
- Give every container you start a memory limit and a swap limit, as large as its work needs: `--memory 4g --memory-swap 4g` on `docker run`, or `mem_limit` and `memswap_limit` in a compose file, scripts included. rule-hook checks only the `docker run` and `docker create` in your Bash commands.
- A heavy command loads the machine for minutes: a full gate, mutation tests, an e2e run, a `docker build`. Run each one under `~/.claude/bin/run-heavy`, as in `~/.claude/bin/run-heavy ./ci.sh`. run-heavy waits for one of the heavy slots that every session on the machine shares. It also caps each container the command makes at the slot's share of memory, where the container sets no limits; give a container that needs more its own. Run the command in the background, since run-heavy's wait can outlast the Bash tool's timeout; `~/.claude/bin/wait-for <file> [<pattern>]` waits for a line in a log the command writes.
- Delegate a task to a subagent only when you need just its conclusion: a search or read across many files, or work independent enough to run in parallel. Keep edits, and whatever you must check line by line, in your own thread: you would read a delegated diff again to check it. Score the task's L as for a `todo.md` item; a task that changes no file, such as a search, is L 1. `<model>` below is the project's model id, such as `claude-opus-5-5`: the one loop-claude's prompt names as the project's, or else your own. Launch the subagent with the model and effort of the first case that fits:
- Delegate a task to a subagent only when you need just its conclusion: a search or read across many files, or work independent enough to run in parallel. Keep edits, and whatever you must check line by line, in your own thread: you would read a delegated diff again to check it. Score the task's L as for a plan item; a task that changes no file, such as a search, is L 1. `<model>` below is the project's model id, such as `claude-opus-5-5`: the one loop-claude's prompt names as the project's, or else your own. Launch the subagent with the model and effort of the first case that fits:
1. A reviewer, a comprehension seat or the security pass: those loop-claude's prompt gives it. Given none, pass no model or effort, so it runs on your model.
2. An escalated task, below: the rung loop-claude's prompt names for escalation, or case 3's rung where the subagent files or scores `todo.md` items and that rung is higher.
3. A subagent that files or scores `todo.md` items: what `~/.claude/bin/subagent-rung --plan <model> <L>` prints, which is never below the project's rung.
2. An escalated task, below: the rung loop-claude's prompt names for escalation, or case 3's rung where the subagent files or scores plan items and that rung is higher.
3. A subagent that files or scores plan items: what `~/.claude/bin/subagent-rung --plan <model> <L>` prints, which is never below the project's rung.
4. Any other: what `~/.claude/bin/subagent-rung <model> <L>` prints.
- Escalate a task that proves too hard for your rung. Four escalation triggers say so:
1. A re-score of the item's L, made on the project's rung or above, picks a rung above yours.
@@ -96,7 +96,7 @@ The rules only reviewers apply, for quality, comments, READMEs and prose, live i
- When the work has a ticket, read it before starting: verify the change matches it and pull useful context from it.
- PR summary: short and concise. No test plan (it lives in the ticket), no link to the ticket (it's in the title).
- Branch for a ticket: exactly the ticket ID, nothing more. `ABC-123`, never `ABC-123-some-description`.
- Branch for a `todo.md` item without a ticket: `item-<ID>`, in the worktree `<checkout>-item-<ID>` beside the checkout, as `chunk-preflight` makes them. Under a `branch` template, `chunk-preflight` names both by the template.
- Branch for a plan item without a ticket: `item-<ID>`, in the worktree `<checkout>-item-<ID>` beside the checkout, as `chunk-preflight` makes them. Under a `branch` template, `chunk-preflight` names both by the template.
- Where the project's config keeps a file in the config's folder, `~/.claude-projects/<key>/`, such as the plan or a record, commit each change you make to that file in the folder's own git repo, on its only branch. Title that commit as you would title the change in the checkout: where a commit in the checkout goes with it, give it the same title.
- Use `gh` on GitHub remotes and `tea` on Gitea remotes (e.g. `gitea.larvit.se`) — same command shape: `tea pr list|create`, `tea issue`, `tea release`, `tea api`. Everything in this section applies to both.
- On GitHub and Gitea, open a chunk's pull request as a draft, mark it ready and merge it with `~/.claude/bin/chunk-pr`, which picks `gh` or `tea` from the remote; `chunk-pr --help` says how. Once it has merged, run `chunk-pr clean` in the chunk's worktree: it removes the worktree and the branch and fast-forwards the main checkout.
@@ -114,7 +114,7 @@ The rules only reviewers apply, for quality, comments, READMEs and prose, live i
Claude Code reads this section by its heading when it compacts a conversation. Keep in the summary:
- what remains before the chunk is finished;
- the task loop-claude gave, and each `todo.md` item the chunk takes with its L and E + I;
- the task loop-claude gave, and each plan item the chunk takes with its L and E + I;
- the worktree, branch and PR;
- the rung loop-claude named for each review launch, rerun and escalated subagent;
- each review pass's rounds so far, each open 🔴 and 🟡, and how the answered ones were answered;
@@ -127,14 +127,14 @@ Claude Code reads this section by its heading when it compacts a conversation. K
- **chunk** — the unit of work, shipped as one PR; "Working loop" says what it holds.
- **cycle** — in `loop-claude`, worker runs and the judge's verdict on each, until the chunk closes or is left for the next cycle. In between, the human answers any interrupt, or the worker resumes with an answer the judge quoted from the premises or the judge's records.
- **gate** — the merge gate: the checks a PR passes before it merges.
- **goals file** — the file holding a project's `## Goals` and `## Audience`: the one its config names as `goals-and-audience`, which `~/.claude/bin/project-config goals-and-audience` prints. It is `README.md`, unless a client's project keeps it in the config's folder.
- **goals file** — the file holding a project's `## Goals` and `## Audience`: the one its config names as `goals-and-audience`. Read it in the file `~/.claude/bin/project-record open goals-and-audience` prints. It is `README.md`, unless a client's project keeps it in the config's folder, or in a Jira epic's description, which the loop only reads.
- **interrupt** — `loop-claude` asking the human, on its terminal, for a decision that is theirs. They type a one-line answer there, or `/talk` to open the worker's session there with `claude --resume`. A release ready to cut opens that session at once. A routing call opens claude on that terminal too, in `~/code/claude-config`, the checkout where this setup is developed.
- **judge** — the headless claude that reads a worker's transcript each cycle and decides whether to interrupt and whether the chunk is finished.
- **judge's records** — the files the judge reads beside the premises: the project's `AGENTS.md` and `docs/decisions.md`, then the human's `~/.claude/CLAUDE.md` and the `.md` files in `~/.claude/rules/` and `~/.claude/skills/larv-review/standards/`.
- **paired ruling** — the seats vote whether the project reads better, the same or worse at the branch's head than at the base, the commit `larv-review ruling-base` prints; `larv-review --help` says how the votes make the ruling.
- **pass** — one kind of review a chunk may take, run in rounds by its reviewers until clean; `larv-review` §3 lists them.
- **place** — the smallest addressable unit, such as a function or a section heading, that a seat names with its `path:line` when it judges how hard the project is to read there.
- **plan** — the project's `todo.md`, at the path its config names as `plan`.
- **plan** — where the project keeps its items, as the `plan` setting of its config names it: a `todo.md` at a path, or a Jira epic.
- **premises** — the goals and audience under `## Goals` and `## Audience` in the project's goals file, with code health ("Shared goal") first among the goals unless the goals file voids it.
- **project's rung** — the cheapest rung on loop-claude's routing ladder of the project's model, which is the model loop-claude's prompt names as the project's, or else your own.
- **project record** — one of five documents a project keeps beside its plan, each where its config names it: `decisions`, `score-anchors`, `comprehension-history`, `reading-cost` and `changelog`.
+18 -7
View File
@@ -73,7 +73,7 @@ Then pick a model with `/model`.
Link `loop-claude` onto `PATH`: `ln -s ~/.claude/bin/loop-claude ~/.local/bin/loop-claude`. Every claude it starts, the interactive ones included, skips every permission prompt.
To get loop-claude's questions and stops as Mattermost DMs from a bot, write the server, the bot's token and your username into `~/.claude-projects/<key>.env`, in the keys `~/.claude/bin/mattermost-dm --help` names, run `chmod 600` on it, and add `env-file = "~/.claude-projects/<key>.env"` to the project's config, as Install → "Set up a project" describes. Without that setting, loop-claude sends no DM for the project; `~/.claude/.env` is no longer read.
To get loop-claude's questions and stops as DMs from a bot, write the bot's token, your username or member ID and, for Mattermost, the server into `~/.claude-projects/<key>.env`, in the keys `~/.claude/bin/notify --help` names, run `chmod 600` on it, and add `env-file = "~/.claude-projects/<key>.env"` and `notifier = "mattermost"` (or `"slack"`) to the project's config, as Install → "Set up a project" describes.
### Set up a project
@@ -96,8 +96,14 @@ principles = "~/.claude/principles"
A project may also set `env-file`, the file of `KEY=value` credentials its tools read, such as `env-file = "~/.claude-projects/log.env"`. It is a path that starts with `/` or `~/`, outside the checkout and the config's folder, so that no git remote receives it. A tool that needs a key fails and names each one the file lacks. No failure message, prompt, log line or archived loop output holds a token from the file. rule-hook refuses a Read or a Grep of the file and a Bash command that names it or searches a folder holding it with `ag`, `grep -r` or `rg`, unless the tool skips the file as hidden or ignored, so a worker doesn't read it in passing; `rule-hook --help` says which calls it checks. A project without the setting has no credentials, and never reads another project's. `project-config env-file` prints the path.
A project may also set `touch-predictions`, a path spelt as `changelog`'s is, such as `touch-predictions = "checkout:docs/touch-predictions.md"`. `touch-predictions record` appends each chunk's predicted files and parts there, beside those it touched. A project that leaves it out keeps no such record.
A project may also set `notifier` to `"mattermost"` or `"slack"`, the service that sends loop-claude's DMs. The `env-file` then holds that service's keys. A project that sets none gets no DMs, whatever its env file holds. `project-config notifier` prints the setting.
A project's config may set four more things, each optional, as `project-config --help` describes. `language` names the language its owners write in, where that isn't English: the worker writes the project's prose in it, and the prose reviewer judges the prose in it. `commit-title`, `pull-request-title` and `branch` are templates for a project that titles and names these in another way than `CLAUDE.md` → "Git, commits, and PRs" says. `chunk-preflight` names the branch and the worktree by the `branch` template. On a branch that fits it, rule-hook refuses a commit, and `chunk-pr` a pull request, whose title doesn't fit its template; on any other branch, such as a release review's, a title is the summary alone. A tool that reads a commit title, such as a round's `Answer <pass> round <n>:`, reads the template's `{summary}`: it tries `commit-title`, then `pull-request-title`, since a squash merge titles the commit as the pull request, then takes the title whole. While a project's config holds a fault, rule-hook refuses every commit there, and the tools that read its titles fail naming the fault.
A legacy project with no container setup sets `tooling-on-host = true`, so the loop runs its language runtime, package manager, tests and task runner directly on the host. One whose code the comprehension panel scores low may lower `readability-floor` from 7.0: under it, the ranking weighs code health 4 times as much, and a scoring run asks for a floor item.
A project whose pull requests need a human's approval sets `wait-for-approval = true` in its config. `chunk-pr merge` then waits, once the checks have passed, until GitHub reports the pull request approved as its branch protection requires, and merges it. It refuses on Gitea, where a reviewer requested changes and where the protection requires no review. It gives up after 90 minutes without an approval; run it again once the pull request is approved. Left out, the setting is false.
For a client's project, use one sandbox VM per client, so that one client's code, transcripts and credentials never share a machine with another's. What the client's repo should not hold lives in the config's folder, at paths written as `folder:<path>`, as `project-config --help` shows: the plan, the working rules in an `AGENTS.md` I write for the agents, the records, and the goals and audience, as `goals-and-audience = "folder:goals.md"`. Name that file `goals.md`, so the rules for goals and audience load when an agent writes it. A file outside the checkout has no commits in the checkout's history, so four things are not supported for it yet. `score-outcomes` and loop-claude's routing figures count a project's chunks only where `todo.md`, `docs/comprehension-history.md` and `docs/reading-cost.md` are at those paths in the checkout; otherwise each says so, and the loop goes on. For a plan or a comprehension history outside the checkout, `larv-review` says it cannot tell whether a scoring run is owed, and for such a history it cannot find a paired ruling's base. For a plan outside the checkout, chunk-preflight and loop-claude don't see a release whose last item has shipped, and say that its release review and its cut are yours to call. And rule-hook checks a plan outside the checkout on every call, not only when it changed.
@@ -111,7 +117,11 @@ A client that plans in Jira Cloud names an epic as its project's plan: `plan = "
- A blocker is an "is blocked by" link to another open child.
- The scores are the issue property `plan-item`, a JSON object such as `{"L": 2, "E": 2, "I": 3, "S": 3, "Moves": "1.6 by 4", "Exempt": ""}`. An issue without it reads as an item nobody scored yet.
A read fails, naming the issue, where a child is in another Jira project or names no such Fix Version. The config's `env-file` must hold `ATLASSIAN_EMAIL` and `ATLASSIAN_API_TOKEN`, an API token of that Atlassian account, and only its owner may read that file: `chmod 600` it. The loop only reads such a plan so far. `todo-item add`, `edit`, `move` and `finish` fail, so file, edit and finish its issues in Jira. `rank_todo.py` doesn't rank it, since Jira's backlog does. The four things not supported for a plan outside the checkout, above, are not supported for a plan in Jira either.
A read fails, naming the issue, where a child is in another Jira project or names no such Fix Version. The config's `env-file` must hold `ATLASSIAN_EMAIL` and `ATLASSIAN_API_TOKEN`, an API token of that Atlassian account, and only its owner may read that file: `chmod 600` it. The loop reads such a plan and files items into it, each as a Task under the epic, and doesn't edit or finish an issue yet. `todo-item edit`, `move` and `finish` fail, so edit and finish its issues in Jira. `todo-item add` needs the item's release among the Jira project's Fix Versions, named as `1.2.0` or `v1.2.0`. `rank_todo.py` doesn't rank it, since Jira's backlog does. The four things not supported for a plan outside the checkout, above, are not supported for a plan in Jira either.
A client that keeps its goals and audience in an epic's description names that epic as the goals file: `goals-and-audience = "jira:https://acme.atlassian.net/browse/ABC-12"`, which may be the plan's own epic. Such a config keeps its plan in Jira too, and reads both with the same `env-file`. The description needs `## Goals` and `## Audience` as headings, level-2 headings in Jira's editor. The loop only reads the description, so edit it in Jira; `project-record open goals-and-audience` prints a file holding its text. Whoever may edit that description sets the premises every worker and judge follows, so keep its edit rights to the people who own the project's goals.
To name a chunk's branch, worktree, commits and pull request by the issue key, as in `ABC-123` and `ABC-123 - …`, set these three templates, with your Jira project's key in place of `ABC`: `branch = "ABC-{id}"`, `commit-title = "ABC-{id} - {summary}"` and `pull-request-title = "ABC-{id} - {summary}"`. `project-config --help` says how the templates work.
```sh
mkdir -p ~/.claude-projects/acme && cd ~/.claude-projects/acme
@@ -156,11 +166,11 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a
- `judge-replay <model>` replays loop-claude's judge on archived verdicts of the projects run on the model, and prints what each rung a review climbs to misses, and the lowest rung below them that, like each candidate above it, returns them; `judge-replay --help` states the replay.
- `larv-review <command>` holds larv-review's mechanical rules: the chunk's review folder, the paired ruling's base and vote count, each pass's round count, the scoring run's trigger and setup; the comprehension history's format, its latest places and its count of how often seats agree; and each reviewer's prompt header. `larv-review --help` states them. `settings.json` → `hooks` runs `larv-review reviewer-context` as each subagent starts. A reviewer under `agents/` whose frontmatter has `omitClaudeMd: true` starts without `CLAUDE.md`, and the command hands it that file's "Shared goal", "Prose" and "Vocabulary" sections.
- `loop-claude <task>` runs a project's next chunk cycle after cycle; `loop-claude --help` states its contract.
- `mattermost-dm [<message>]` sends a message, or else stdin, from the Mattermost bot to the human; the project's `env-file` names the server, the bot's token and the human, and `mattermost-dm --help` names its keys. `loop-claude --help` says when loop-claude sends one.
- `metric-bench [history]` benches cheap static metrics of a project's Python against the places its comprehension history names as hardest; `metric-bench --help` states the metrics and the scores.
- `mutate-changes [--base <ref>] [--prefix <shell text>] [--jobs <n>]` mutation-tests the lines a branch changes and prints each mutant its tests don't kill; `mutate-changes --help` says which tool it runs for each language.
- `notify [<message>]` sends a message, or else stdin, as a DM from the bot of the project's `notifier`, Mattermost or Slack, to the human; the project's `env-file` holds the bot's token, the recipient and, for Mattermost, the server, and `notify --help` names its keys. `loop-claude --help` says when loop-claude sends one.
- `project-config [<setting>]` prints the paths a project's config sets, or the one asked for, and fails naming each setting the config leaves out; Install → "Set up a project" shows a config.
- `project-record open <record>` prints the path of a file holding one of a project's records, for an agent to read and edit, and `project-record save <record>` stores the edit; for a record kept as a file, that file is the record.
- `project-record open <record>` prints the path of a file holding one of a project's records, for an agent to read and edit, and `project-record save <record>` stores the edit; for a record kept as a file, that file is the record. `goals-and-audience` opens the goals file the same way.
- `rank_todo.py [--check] [todo.md]` scores and ranks a project's `todo.md`, by default the one its config names; `rank_todo.py --help` states the format.
- `reading-cost [--reset] [record]` appends a figure for each chunk `loop-claude` finished to a project's `docs/reading-cost.md`, and says whether the figures rise; `reading-cost --help` states the measure.
- `review-replay <pass> <model>` replays a review pass's archived rounds from the projects run on the model, on the code each reviewed, and prints the lowest rung below the project's that, like each rung above it, qualifies: it finds no less of the 🔴 and 🟡 findings than two replays on the project's rung find, within a margin, and misses no 🔴 that both found. `review-replay --help` states the replay. With `--omit-claude-md` it tests instead whether the pass's reviewer may start without `CLAUDE.md`: it replays each round three times as archived and once without the instruction files, and prints whether the reviewer passes: whether the last replay missed no more findings than the most an unchanged replay missed, with each count and each finding it missed. Each replayed reviewer skips every permission prompt, stability-reviewer has Bash, and an archived prompt may name paths on the host.
@@ -172,9 +182,10 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a
- `statusline.py` renders Claude Code's status line; `settings.json` → `statusLine` runs it.
- `subagent-rung [--plan] <model> <L>` prints the Agent tool's model and effort for a subagent's task, picked by its L from the project's model, and with `--plan` never below the project's rung; `subagent-rung --help` states the rule.
- `todo-item` reads and changes a project's plan, whatever holds it: `list` prints the items in the plan's order and `show <ID>` one item's row and detail; `add …` files an item under the next free ID, `edit <ID> …` sets an item's cells or detail, and `move <ID> --release <version>` sets an item's release; `finish <ID>` removes a finished item and adds the bullet passed with `--changelog` to `CHANGELOG.md`. Each change ranks a markdown plan. `todo-item --help` states the flags.
- `touch-predictions record <ID>...` appends what a chunk's items were predicted to touch, under `Touches:` in their details, beside the files and parts its branch touched, to the record the config names as `touch-predictions`; `touch-predictions --help` shows the spelling and how a part is named. `chunk-preflight` reads the same predictions to name the items that may start chunks at once.
- `wait-for <file> [<pattern>] [--timeout <seconds>]` waits until a file a background job writes holds a line matching the pattern, and prints it.
`bin/` is the import root: each launcher puts it on `sys.path`, so a module imports another by its path under `bin/`, such as `from claude_code.entries import parse_entry`. Each tool's package holds its tests. Beside the packages, `bin/`'s root holds only the launchers, the tools of one file with their tests, `test_env.py`, `failure.py` and `setup.cfg`. `failure.py`'s `Failure`, which modules across `bin/` return for a failed step, belongs to no single package. `branch_chunks/`, `claude_code/`, `command_lines/`, `git_cli/`, `loop_effects/`, `loop_state/`, `machine_load/`, `mattermost_dm/`, `model_routing/`, `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. `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.
- `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.
- `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.
@@ -187,14 +198,14 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a
- `loop_effects/` holds `Effects`: the processes, terminal, clock and git a tool reaches, injected so its tests can script them. loop-claude, both replay tools and `reviewer-merge-trials`' driver use it.
- `loop_state/` holds where loop-claude keeps its files (`paths.py`), which `rung_replay` reads too.
- `machine_load/` takes the machine's heavy slots, its shared lock files, for `run_heavy` and `adf_codec`, and reads the memory share that loop-claude waits for. It also gives `mutate_changes` a slot's CPU count.
- `mattermost_dm/` sends the human a Mattermost DM, for `mattermost-dm` and for loop-claude through `loop_effects`.
- `model_routing/` holds the routing ladder, which loop-claude, `rule_hook`, both replay tools and `subagent-rung` read, and the list prices, which `routing_figures` and `transcript_archive` read.
- `notifier/` sends the human a DM through the notifier a project's config names, for `notify` and for loop-claude through `loop_effects`; `mattermost_dm/` and `slack_dm/` are its two backends.
- `plan_store/` reads and writes a project's plan through the store the project's config names (`stores.py`), with the markdown file's edits in `markdown_edits.py`. `contract.py` holds the tests every backend that writes must pass, which `jira_epic.py` doesn't yet, and `fakes.py` a plan in memory.
- `rank_todo.py`, `settings_filter.py` and `statusline.py` are tools of one file each, tested beside them.
- `record_store/` reads and writes a project's records, each through the store the project's config names (`stores.py`). `contract.py` holds the tests every backend must pass, and `fakes.py` a store in memory that the tests of other tools use.
- `release_plan/` reads `todo.md`'s items table and release versions, says which release is next and whether it is ready to cut (`release_standing.py`), and ranks the plan (`ranking.py`, with its score formula in `formula.py` and its blocker order in `blockers.py`). `goals_file.py` reads the goals file's sections, goals and goal weights, for the ranking and for `loop_claude`'s premises, and `citations.py` holds `todo.md` and `docs/decisions.md` to each other. `plan_file.py` ranks, checks and writes a `todo.md`, for `larv_review`, `rank_todo.py` and `rule_hook`.
- `repo_checks/` tests the repo itself.
- `rest_client/` sends a JSON request to a REST API and reads its credentials from an env file, for `mattermost_dm` and `plan_store`.
- `rest_client/` sends a JSON request to a REST API and reads its credentials from an env file, for `mattermost_dm`, `slack_dm` and `plan_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.
+3 -3
View File
@@ -7,9 +7,9 @@ omitClaudeMd: true
You check every yardstick you are handed against the whole project, which you read once for all of them. A yardstick is either the project's goals, every goal under `## Goals` in the file your prompt's `Goals and audience:` line names, with code health (`~/.claude/CLAUDE.md` → "Shared goal") unless that file voids it, or one principles file, every principle in it.
Verdict, severities and rounds: ~/.claude/skills/larv-review/review-findings.md. Read the yardsticks, `README.md`, `docs/decisions.md` and `todo.md` first, then all of the project's code, config, tests and CI.
Verdict, severities and rounds: ~/.claude/skills/larv-review/review-findings.md. Read the yardsticks, `README.md`, `docs/decisions.md` and the plan first, then all of the project's code, config, tests and CI. Your prompt's `Plan:` line names the plan.
- Per principle or goal: every place the project departs from it, with file:line, the defect in one sentence and its concrete consequence. Then one line: followed, mostly, not followed, or does not apply and why.
- A departure a `todo.md` item plans away is named with that item, not raised.
- A decision in `docs/decisions.md` working against a goal or a technical principle is a 🔴 on the decision, unless it names the `todo.md` item that ends it. Weigh it hard: that it was decided is no reason.
- A departure a plan item plans away is named with that item, not raised.
- A decision in `docs/decisions.md` working against a goal or a technical principle is a 🔴 on the decision, unless it names the plan item that ends it. Weigh it hard: that it was decided is no reason.
- Report under one heading per yardstick.
+1 -1
View File
@@ -47,7 +47,7 @@ Before anything else, **read the technical principles** in the folder your promp
## Your Output Format
Report only a defect a persona hits; a requirement that the change breaks, of the plan, of the goals in the file your prompt's `Goals and audience:` line names, or of code health (`~/.claude/CLAUDE.md` → "Shared goal", unless that file voids it); or a breach of a technical principle. Friction that is none of these is not a finding.
Report only a defect a persona hits; a requirement that the change breaks, of the plan in the file your prompt's `Plan:` line names, of the goals in the file your prompt's `Goals and audience:` line names, or of code health (`~/.claude/CLAUDE.md` → "Shared goal", unless that file voids it); or a breach of a technical principle. Friction that is none of these is not a finding.
Verdict, severities and rounds: ~/.claude/skills/larv-review/review-findings.md. After the verdict:
+2 -2
View File
@@ -13,7 +13,7 @@ You are an elite stability-focused code reviewer with deep expertise in defensiv
1. **Scope the change.** You review every PR; a fresh invocation has no prior context, so determine the diff yourself. Diff the PR branch against its base (`gh pr diff`, or `git merge-base <base> HEAD` then `git diff`), and review the changed lines **plus enough surrounding code and callers** to judge correctness — read the whole changed file when practical; a diff alone hides whether a caller breaks. Read the PR description and, when the project uses an issue tracker (project-specific — check its docs) and the change references a ticket, that ticket: the diff is judged against its stated intent, and a scope mismatch in either direction is a finding — claimed-but-unimplemented, and implemented-but-unasked (#2).
2. **Read every file in the folder your prompt's `Technical principles:` line names**, and `~/.claude/skills/larv-review/standards/quality.md`. These are mandatory guidelines; all code MUST comply with each that applies. A file's `Applies to` line says what it covers; one without the line covers every change. Re-read each time — they change. Flag violations prominently. Where your prompt has no such line, without one, open your report by saying so.
3. **Read README.md, AGENTS.md and `docs/decisions.md`** in the current project for project-specific conventions, build instructions, tooling, and the accepted trade-offs a reviewer should honor rather than re-flag. Note the documented test, lint, and static-analysis commands — you run them unless your prompt hands you a passing run on the head (step 4).
4. **Verify, don't just read.** Where your prompt hands you the commit on which the worker's run of the test suite and static analysis last passed, and it is the head, don't run them again, and say so in Coverage & Verification. Otherwise run the test suite and static analysis/linters through the project's container tooling, unless a decision puts them on the host; tear down test containers afterwards. Run the full suite under `~/.claude/bin/run-heavy`. Run it in the background or with the Bash tool's longest timeout: that timeout includes the wait for a slot. A full-suite run catches broken callers that diff-reading misses. When a suspected bug is cheap to confirm, reproduce it — a scratch script, a targeted test run — before reporting it. Make scratch work with Bash, since Write is for your report alone. Put it in a directory you create for this run, and delete it when done; don't delete anything else, since a directory the prompt names may hold other agents' files. Leave the working tree exactly as you found it. Anything you could not run goes in Coverage & Verification, never silently skipped.
4. **Verify, don't just read.** Where your prompt hands you the commit on which the worker's run of the test suite and static analysis last passed, and it is the head, don't run them again, and say so in Coverage & Verification. Otherwise run the test suite and static analysis/linters through the project's container tooling, unless `~/.claude/bin/project-config tooling-on-host` prints true or a decision puts them on the host; tear down test containers afterwards. Run the full suite under `~/.claude/bin/run-heavy`. Run it in the background or with the Bash tool's longest timeout: that timeout includes the wait for a slot. A full-suite run catches broken callers that diff-reading misses. When a suspected bug is cheap to confirm, reproduce it — a scratch script, a targeted test run — before reporting it. Make scratch work with Bash, since Write is for your report alone. Put it in a directory you create for this run, and delete it when done; don't delete anything else, since a directory the prompt names may hold other agents' files. Leave the working tree exactly as you found it. Anything you could not run goes in Coverage & Verification, never silently skipped.
5. **Judge the surviving mutants.** Your prompt hands you what the project's mutation command printed on the change, with the commit it ran on: the mutants of changed lines that no test kills, or the message of a run that failed. Ignore a surviving mutant that leaves behaviour unchanged, or changes only message or log text no caller or user depends on. Report one 🟡 per test to add or strengthen, naming the surviving mutants it would catch. Where the prompt doesn't hand you any output, or names a commit other than the head, run the command yourself in the change's checkout, through run-heavy as in step 4: the one the project's README documents, else `~/.claude/bin/run-heavy ~/.claude/bin/mutate-changes --prefix '<how the project runs its tools>'`. `~/.claude/bin/mutate-changes --help` says which tool it runs for each language, how to set `--jobs`, and what it prints. Mutation-test the changed code that no run mutated, in a language mutate-changes doesn't cover or where a run failed, with a widely deployed mutation tool limited to the changed lines, else with mutants you make by hand. Report the wall time and mutant count in Coverage & Verification, or why nothing was mutated.
6. **Two passes minimum, then hunt absences.**
- *Breadth:* every hunk in every changed file, no skimming. Track which files you have covered; batch large diffs, never truncate the review.
@@ -130,7 +130,7 @@ Every PR gets at least this sweep.
## Output Format
Report only a defect; a requirement that the change breaks, of the plan, of the goals in the file your prompt's `Goals and audience:` line names, or of code health (`~/.claude/CLAUDE.md` → "Shared goal", unless that file voids it); a breach of a technical principle; and the places the prompt hands you. A finding that is none of these is noise, however true: leave it out.
Report only a defect; a requirement that the change breaks, of the plan in the file your prompt's `Plan:` line names, of the goals in the file your prompt's `Goals and audience:` line names, or of code health (`~/.claude/CLAUDE.md` → "Shared goal", unless that file voids it); a breach of a technical principle; and the places the prompt hands you. A finding that is none of these is noise, however true: leave it out.
Verdict, severities and rounds: ~/.claude/skills/larv-review/review-findings.md. After the verdict, a short **Coverage & Verification** block: what you ran (tests, static analysis, mutation — and their results), what you could not verify and why, and any files that got a lighter pass — never let silence imply coverage. Then the findings, most severe first, each with:
- **Location**: File and line/function
+1 -1
View File
@@ -184,7 +184,7 @@ This is where unjustified duplication and accidental complexity get caught. Run
6. **Price the reasoned complexity too.** Essential-looking complexity has a requirement behind it. For each hotspot that survives the steps above, name that requirement, then sketch the design without it. When a much simpler near-equivalent exists, report the trade as a finding: the simpler shape, the exact functionality delta, and the complexity saved. A requirement nobody has priced is not a decision — offer the trade once, plainly, and let the owner accept or reject it.
7. **Hunt the imagined requirement.** The step above prices complexity a real requirement forces; this one removes complexity no requirement forces. For every abstraction, indirection, configuration point, and layer of generality, name the present, Stage 0-recorded requirement it serves. An interface with one implementation, a plugin system with one plugin, a cache or shard — or a load-testing rig — for load nobody recorded, a canary rig for a blast radius nobody recorded, "in case we swap the database" — speculative generality is the over-engineered twin of copy-paste drift: complexity nobody's requirement chose. The future that justifies flexibility must be a recorded goal or horizon, not the author's imagination — and the shorter the horizon, the harder this step cuts. Rate removals with the same severity as unreasoned duplication.
Respect documented deliberate deviations — a stated trade-off is a valid reason (`docs/decisions.md`), unless it works against a goal or a technical principle and names no `todo.md` item ending it. Respecting it means not re-arguing the same trade with the same facts; it does not forbid offering a materially simpler alternative the decision never considered — offer it once with the exact delta, then drop it if declined. The target is the *un*reasoned: duplication, complexity, and confusion that nobody decided and nobody can defend. "Acceptable for now", "will compound later", and "converge in a future pass" are how a small drift becomes the permanent shape of the system.
Respect documented deliberate deviations — a stated trade-off is a valid reason (`docs/decisions.md`), unless it works against a goal or a technical principle and names no plan item ending it. Respecting it means not re-arguing the same trade with the same facts; it does not forbid offering a materially simpler alternative the decision never considered — offer it once with the exact delta, then drop it if declined. The target is the *un*reasoned: duplication, complexity, and confusion that nobody decided and nobody can defend. "Acceptable for now", "will compound later", and "converge in a future pass" are how a small drift becomes the permanent shape of the system.
## Communication Style
+17
View File
@@ -1,5 +1,6 @@
"""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 touch_predictions.beside import chunks_beside
from chunk_preflight.choices import cut_name, PULLS_LIST
from release_plan.release_standing import dated_cut, LastCut, unreleased_entries, UNSEEN_RELEASES
from failure import Failure
@@ -48,6 +49,7 @@ def item_lines(plan: str, item: ItemFacts) -> list[str]:
f"- Worktree: {worktree}",
f"- Open pull requests from {item.plan.branch}: {pulls_text(item.pulls, item.plan.branch)}",
*bundled(item.plan),
*beside(item.plan),
*named_lines(item.named),
f"\nItem {first.id}'s tagline and detail:\n\n{quoted(item.plan.text)}",
*joining_details(item.plan),
@@ -98,6 +100,21 @@ 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]:
"""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)
if found is None:
return []
none = f"- No item of release {version(first.release)} may start a chunk beside item {first.id}'s"
if isinstance(found, str):
return [f"{none}: {found}."]
refused = f" Not beside it: {'; '.join(found.refused)}." if found.refused else ""
if not found.picked:
return [f"{none}.{refused}"]
return [f"- The items of release {version(first.release)} that may start chunks beside item {first.id}'s: {', '.join(map(str, found.picked))}. None is predicted to touch a part that item {first.id} touches, or that an item earlier in this list touches. An item this chunk takes doesn't start a chunk of its own.{refused}"]
def named_lines(named: list[NamedPath] | Failure) -> list[str]:
if isinstance(named, Failure):
return [f"- The files the item names: cannot be listed: {named.reason}"]
+7
View File
@@ -43,6 +43,13 @@ and prints that the release reviews and the cuts are the human's to call. It pri
- the items of that release that a chunk taking the item may take too, each with its L, E + I,
S and tagline: those that are not questions, that have R 5 or less, and that no item outside
the chunk blocks; none where the item's own R is above 5;
- the other items of that release that may start chunks while the item's chunk runs, then why each
of the rest may not. An item's prediction is the bullets under a `Touches:` line in its detail,
which `touch-predictions --help` describes. Another item may start a chunk where it doesn't
wait and its prediction shares no part with the item's, or with that of an item picked before
it in the plan's order. A part either prediction marks (small) doesn't count. This line is left
out where no item of the release that doesn't wait holds a prediction. The plan and the records
belong in no prediction, since every chunk writes them;
- each file or folder git tracks that the item's tagline or detail names in backticks, with a
file's lines or a folder's files, then the item's tagline and detail, then the detail of each
of the first {JOINING_DETAILS} items that may join, or that one has none;
@@ -628,5 +628,33 @@ class Running(unittest.TestCase):
self.assertIsNone(line_count(folder))
class BesideTest(unittest.TestCase):
"""The fact that names the items that may start chunks beside the next one."""
# Items 3 and 4 touch other parts of one file, and item 6 touches what item 3 does.
ROWS = "| 4 | 0.2.0 | | | **Do four.** | 1 | 1 | 1 | 1 | 1 | 1 by 1 | 10.0 |\n| 6 | 0.2.0 | | | **Do six.** | 1 | 1 | 1 | 1 | 1 | 1 by 1 | 10.0 |\n"
DETAILS = "\nTouches:\n\n- `src/app.py`: `run`\n\n### 4. Do four.\n\nTouches:\n\n- `src/app.py`: `stop`\n\n### 6. Do six.\n\nTouches:\n\n- `src/app.py`: `run`\n"
def said(self, todo):
return [line for line in rendered(item_facts(todo)).splitlines() if "beside" in line]
def test_names_the_items_that_may_start_chunks_beside_it_and_why_the_others_may_not(self):
todo = TODO.replace("| 9 | 0.3.0", self.ROWS + "| 9 | 0.3.0") + self.DETAILS
self.assertEqual(self.said(todo), ["- The items of release 0.2.0 that may start chunks beside item 3's: 4. None is predicted to touch a part that item 3 touches, or that an item earlier in this list touches. An item this chunk takes doesn't start a chunk of its own. Not beside it: item 6, which overlaps item 3 at `src/app.py` `run`."])
def test_names_each_item_that_may_and_stops_there_when_none_is_refused(self):
todo = TODO.replace("| 9 | 0.3.0", self.ROWS + "| 9 | 0.3.0") + self.DETAILS.removesuffix("`run`\n") + "`other`\n"
self.assertEqual(self.said(todo), ["- The items of release 0.2.0 that may start chunks beside item 3's: 4, 6. None is predicted to touch a part that item 3 touches, or that an item earlier in this list touches. An item this chunk takes doesn't start a chunk of its own."])
def test_says_when_none_may(self):
todo = TODO.replace("| 9 | 0.3.0", self.ROWS + "| 9 | 0.3.0") + self.DETAILS.replace("`stop`", "`run`")
self.assertEqual(self.said(todo), ["- No item of release 0.2.0 may start a chunk beside item 3's. Not beside it: item 4, which overlaps item 3 at `src/app.py` `run`; item 6, which overlaps item 3 at `src/app.py` `run`."])
alone = TODO.replace("| 9 | 0.3.0", self.ROWS + "| 9 | 0.3.0") + "\n### 4. Do four.\n\nTouches:\n\n- `src/app.py`\n"
self.assertEqual(self.said(alone), ["- No item of release 0.2.0 may start a chunk beside item 3's: item 3's detail has no `Touches:` list."])
def test_says_nothing_in_a_plan_without_predictions(self):
self.assertEqual(self.said(TODO), [])
if __name__ == "__main__":
unittest.main()
+4 -3
View File
@@ -9,6 +9,7 @@ import sys
import tempfile
from release_plan.release_standing import chunk_item, Cut, default_plan, Next, ReadyToCut, ReviewDue, Unplanned
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
@@ -109,9 +110,9 @@ def same_origin(clone: str, checkout: str) -> Failure | None:
def clone_plan(clone: str) -> FilePlan:
"""The clone's plan, at the path this repo keeps it. ready_release only reads it; FilePlan also takes the files a write would rank it against."""
decisions, history = (FileStore(pathlib.Path(clone, path), path) for path in ("docs/decisions.md", "docs/comprehension-history.md"))
return FilePlan(pathlib.Path(clone, "todo.md"), "todo.md", pathlib.Path(clone, "README.md"), decisions, history)
"""The clone's plan, at the path this repo keeps it. ready_release only reads it; FilePlan also takes the files and the floor a write would rank it against, and the clone has no config to set the floor."""
goals, decisions, history = (FileStore(pathlib.Path(clone, path), path) for path in ("README.md", "docs/decisions.md", "docs/comprehension-history.md"))
return FilePlan(pathlib.Path(clone, "todo.md"), "todo.md", goals, decisions, history, DEFAULT_FLOOR)
def ready_release(clone: str, ref: str) -> Release | Failure:
+4 -4
View File
@@ -2,7 +2,7 @@ import pathlib
import typing
from larv_review.agreement import agreement_report
from review_rules.comprehension_history import appended, DIMENSIONS, FLOOR, heading, Heading, latest_places, recorded, ruling_entry, scoring_entry, ScoringRun, vote_text
from review_rules.comprehension_history import appended, DIMENSIONS, heading, Heading, latest_places, recorded, ruling_entry, scoring_entry, ScoringRun, vote_text
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
@@ -66,9 +66,9 @@ def record_scoring(default: str, scores_file: pathlib.Path, ids: list[int], home
return appended_to
say(appended_to)
say(f"Means: {', '.join(f'{name} {value}' for name, value in zip(DIMENSIONS, scoring.means))}.")
if under := under_floor(scoring.means):
say(f"Floor: {', '.join(under)} under the floor of {FLOOR}.")
if step := floor_step(scoring.means, plan, ids):
if under := under_floor(scoring.means, config.readability_floor):
say(f"Floor: {', '.join(under)} under the floor of {config.readability_floor}.")
if step := floor_step(scoring.means, plan, ids, config.readability_floor):
say(step)
reranked = rerank(home, warn)
removed = removed_setup(checkout, home)
+9 -7
View File
@@ -101,7 +101,8 @@ record-scoring never removed is still there, it removes it first and says so.
record-scoring takes the scores file of a run needs-scoring-run calls, whose first line names no
`, against`, and the same item IDs, and exits 1 when they call no run. It appends the seats' scores
and their means, rounded half up to two decimals, prints the means and, when a mean is under the
floor of {floor}, a line opening `Floor:` naming each one. A line opening `Next:` follows it. It
project's readability floor, a line opening `Floor:` naming each one and the floor. The config sets
the floor as `readability-floor`, {floor} where left out. A line opening `Next:` follows it. It
says to file a floor item aimed at the lowest of the four dimensions, and names the tagline's opening
`Reach the comprehension floor:`. Where the project's todo.md holds such an item other than those given, it says to
refresh that item instead. Then it ranks the project's todo.md as rank_todo.py does, since the
@@ -129,12 +130,13 @@ reviewer-header takes the name of a pass that an agent under agents/ reviews, sp
prints it, such as stability. It prints the header of the prompt that launches the pass's reviewer
in its next round: the pass and round, the branch's open pull request at its pushed head, the
worktree and branch, the merge base of HEAD and the default branch, and the paths of the reviewer's
report, the branch diff, the folder of technical principles the project's config sets and, for
architecture and stability, the places. For a reviewer whose
report, the branch diff, the folder of technical principles the project's config sets, the goals
and the plan and, for architecture and stability, the places. For a reviewer whose
definition under ~/.claude/agents/ has `omitClaudeMd: true`, it then names the file that holds the
project principles and decision titles, where the project keeps one. It writes the diff, from
that base to HEAD, into the chunk's review folder as branch-<short HEAD>.diff, and writes what
places prints into places.md; a file whose text is unchanged is left as it is. With --rerun, the
that base to HEAD, into the chunk's review folder as branch-<short HEAD>.diff, writes what
places prints into places.md, and lists the plan's items into
plan.md, whatever store holds the plan; a file whose text is unchanged is left as it is. With --rerun, the
header names the report of a relaunch one rung up, in the same round, and the report that asked for
it. It exits 1 when the pass takes no more rounds, when `project-config` fails in the checkout, when the
principles folder it names is not a folder with a file in it, or, with --rerun, when the report that
@@ -161,8 +163,8 @@ import typing
from git_cli.git_repo import branch_titles, default_branch, git, top
from review_rules.round_titles import cap, CAP, RELEASE_REVIEW_CAP, round_counts
from project_config.settings import DEFAULT_FLOOR
from failure import Failure
from review_rules.comprehension_history import FLOOR
from larv_review.history_changes import history_changes
from review_rules.reviewer_context import hook_reply
from review_rules.review_folder import made_review_folder
@@ -237,7 +239,7 @@ USAGE = f"usage: larv-review {SHAPES}"
def main(argv: list[str]) -> int:
if argv in (["-h"], ["--help"]):
print(__doc__.strip().format(commands=SHAPES, cap=CAP, release_cap=RELEASE_REVIEW_CAP, floor=FLOOR, pairs=MIN_PAIRS))
print(__doc__.strip().format(commands=SHAPES, cap=CAP, release_cap=RELEASE_REVIEW_CAP, floor=DEFAULT_FLOOR, pairs=MIN_PAIRS))
return 0
if not argv:
print(USAGE, file=sys.stderr)
+22
View File
@@ -0,0 +1,22 @@
"""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
def plan_listing(plan: PlanStore) -> str:
"""The plan's items as the store supplies them, each with its release, tagline, blockers and detail. Where the plan can't be read, says so, so a reviewer doesn't take it for empty."""
read = plan.read()
opening = f"# Plan, as {plan.label} holds it\n\n"
if isinstance(read, Failure):
return f"{opening}The plan cannot be read, so no item is listed: {read.reason}\n"
if not read.items:
return f"{opening}The plan holds no item.\n"
return opening + "\n".join(item_listing(item) for item in read.items)
def item_listing(item: Item) -> str:
blockers = ", ".join(map(str, item.blocked_by))
parts = [f"## Item {item.id}, release {version(item.release)}", item.tagline, *([f"Blocked by: {blockers}."] if blockers else []), *([item.detail] if item.detail else [])]
return "\n\n".join(parts) + "\n"
+17 -8
View File
@@ -1,4 +1,4 @@
"""reviewer-header: write the branch diff and the places into the chunk's review folder, and print the header of a reviewer's prompt."""
"""reviewer-header: write the branch diff, the places and the plan into the chunk's review folder, and print the header of a reviewer's prompt."""
import dataclasses
import pathlib
@@ -6,11 +6,13 @@ from git_cli.git_repo import branch_titles, git, top
from review_rules.round_titles import cap, round_counts
from failure import Failure
from chunk_preflight.choices import forge_of
from record_store.stores import goals_store, local_file, store
from larv_review.history_commands import history_file, places_report
from record_store.stores import local_file, store
from project_config.main import located, title_templates
from review_rules.review_folder import made_review_folder
from deploy_release.forge import open_pull, runner
from larv_review.plan_listing import plan_listing
from plan_store.stores import store as plan_store
from review_rules.reviewer_context import principles_line, starts_bare
from review_rules.review_passes import REVIEWERS
@@ -33,6 +35,8 @@ class Launch:
diff: pathlib.Path
principles: pathlib.Path
goals: pathlib.Path
# The plan's listing, for a reviewer that reads files, whatever store holds the plan.
plan: pathlib.Path
bare: bool
# The project's `AGENTS.md`, where its config puts it, and a local file of its decision log.
rules: pathlib.Path
@@ -56,6 +60,7 @@ class Launch:
f"Diff: {self.diff}",
f"Technical principles: {self.principles}",
f"Goals and audience: {self.goals}",
f"Plan: {self.plan}",
f"Prose language: {self.language}.",
*([f"Places: {self.folder / 'places.md'}"] if self.pass_ in TAKE_PLACES else []),
*([principles] if self.bare and (principles := principles_line(self.rules, self.decisions)) else []),
@@ -71,7 +76,7 @@ def unanswered_round(titles: list[str], pass_: str) -> int | Failure:
def reviewer_header(default: str, pass_: str, rerun: bool, home: pathlib.Path) -> str | Failure:
"""Writes the branch diff and the places into the review folder, and returns the header that launches pass_'s reviewer in the pass's unanswered round, or its relaunch one rung up where rerun."""
"""Writes the branch diff, the places and the plan's listing into the review folder, and returns the header that launches pass_'s reviewer in the pass's unanswered round, or its relaunch one rung up where rerun."""
titles = branch_titles(default)
if isinstance(titles, Failure):
return titles
@@ -99,17 +104,21 @@ def reviewer_header(default: str, pass_: str, rerun: bool, home: pathlib.Path) -
decisions = local_file(store(config, "decisions"), folder / "decisions.md")
if isinstance(decisions, Failure):
return decisions
launch = Launch(pass_, round_, rerun, pull_named(worktree, branch), worktree, branch, base, default, folder, folder / f"branch-{head}.diff", principles, config.paths["goals-and-audience"], starts_bare(next((agent for name, agent in REVIEWERS.items() if name == pass_), ""), home), config.paths["working-rules"], decisions, config.language)
# A reviewer reads files, so goals kept in a Jira epic's description are copied into the review folder.
goals = local_file(goals_store(config), folder / "goals.md")
if isinstance(goals, Failure):
return goals
launch = Launch(pass_, round_, rerun, pull_named(worktree, branch), worktree, branch, base, default, folder, folder / f"branch-{head}.diff", principles, goals, folder / "plan.md", starts_bare(next((agent for name, agent in REVIEWERS.items() if name == pass_), ""), home), config.paths["working-rules"], decisions, config.language)
if rerun and not launch.asked().exists():
return Failure(f"no report asked for a rerun of {pass_}'s round {round_}: {launch.asked()} is missing; relaunch before you commit the round's answers")
written = write_inputs(launch, base, home)
written = write_inputs(launch, base, home, plan_listing(plan_store(config)))
if isinstance(written, Failure):
return written
return launch.header()
def write_inputs(launch: Launch, base: str, home: pathlib.Path) -> Failure | None:
"""Writes the branch diff from base to HEAD and what `larv-review places` prints into the review folder."""
def write_inputs(launch: Launch, base: str, home: pathlib.Path, listing: str) -> Failure | None:
"""Writes the branch diff from base to HEAD, what `larv-review places` prints, and the plan's listing into the review folder."""
diff = git("diff", base, "HEAD", errors="replace")
if isinstance(diff, Failure):
return diff
@@ -117,7 +126,7 @@ def write_inputs(launch: Launch, base: str, home: pathlib.Path) -> Failure | Non
if isinstance(history, Failure):
return history
try:
for path, text in ((launch.diff, diff), (launch.folder / "places.md", places_report(history[1]) + "\n")):
for path, text in ((launch.diff, diff), (launch.folder / "places.md", places_report(history[1]) + "\n"), (launch.plan, listing)):
# review-replay copies a file into a round's replay by its mtime, so rewriting one unchanged would drop it from every earlier round.
if not path.exists() or path.read_text(encoding="utf-8") != text:
path.write_text(text, encoding="utf-8")
+7 -6
View File
@@ -1,6 +1,6 @@
import decimal
from review_rules.comprehension_history import DIMENSIONS, FLOOR
from review_rules.comprehension_history import DIMENSIONS
from release_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.
@@ -21,16 +21,17 @@ def mean(values: list[decimal.Decimal]) -> decimal.Decimal:
return (sum(values, decimal.Decimal(0)) / len(values)).quantize(decimal.Decimal("0.01"), decimal.ROUND_HALF_UP)
def under_floor(found: list[decimal.Decimal]) -> list[str]:
return [f"{name} {value}" for name, value in zip(DIMENSIONS, found) if value < FLOOR]
def under_floor(found: list[decimal.Decimal], floor: decimal.Decimal) -> list[str]:
"""Each mean in found under floor, the project's readability floor, with its dimension's name."""
return [f"{name} {value}" for name, value in zip(DIMENSIONS, found) if value < floor]
def floor_step(found: list[decimal.Decimal], plan: list[Item], ships: list[int]) -> str | None:
def floor_step(found: list[decimal.Decimal], plan: list[Item], ships: list[int], floor: decimal.Decimal) -> str | None:
"""The `Next:` line of a scoring run with a mean under the floor, None when no mean is under it (SKILL.md → "Floor item").
The line aims at the lowest of the four dimensions, or at each where they tie, since the lowest caps the overall. A floor item in plan is open unless ships holds its ID, so a chunk that ships one still files the next.
"""
if not under_floor(found):
if not under_floor(found, floor):
return None
dimensions = dict(zip(DIMENSIONS[:-1], found))
lowest = [name for name, value in dimensions.items() if value == min(dimensions.values())]
@@ -39,4 +40,4 @@ def floor_step(found: list[decimal.Decimal], plan: list[Item], ships: list[int])
rule = 'as larv-review §3 → "Floor item" says.'
if open_items := [item for item in plan if is_floor_item(item) and item.id not in ships]:
return f"Next: refresh floor item {open_items[0].id} to lift {aim}, with this run's places, and file no other, {rule}"
return f"Next: file one floor item, a refactor lifting {aim}, with a tagline that opens with `{FLOOR_ITEM}`, until every mean reaches {FLOOR}, {rule}"
return f"Next: file one floor item, a refactor lifting {aim}, with a tagline that opens with `{FLOOR_ITEM}`, until every mean reaches {floor}, {rule}"
+56 -15
View File
@@ -20,15 +20,16 @@ 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 record_store.stores import FileStore
from larv_review.scoring import floor_step, means, under_floor
from test_env import isolated_env
from release_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
from record_store.fakes import MemoryStore
from larv_review.seats import score_line, scores, seats_file, SeatsFile
from larv_review.owed import shortfall
@@ -119,42 +120,49 @@ class Seats(unittest.TestCase):
def test_rounds_each_mean_half_up_and_names_each_under_the_floor(self):
found = means([["7.5", "6.5", "7", "7", "7"], ["7.5", "7", "7", "6.5", "7"], ["7", "6.5", "7", "6.5", "6.5"], ["7.5", "6.5", "7", "6.5", "7"]])
self.assertEqual([str(mean) for mean in found], ["7.38", "6.63", "7.00", "6.63", "6.88"])
self.assertEqual(under_floor(found), ["Locality 6.63", "Self-sufficiency 6.63", "Overall 6.88"])
self.assertEqual(under_floor([decimal.Decimal("7.00")] * 5), [])
self.assertEqual(under_floor(found, DEFAULT_FLOOR), ["Locality 6.63", "Self-sufficiency 6.63", "Overall 6.88"])
self.assertEqual(under_floor([decimal.Decimal("7.00")] * 5, DEFAULT_FLOOR), [])
def test_names_only_the_means_under_the_floor_it_is_given_and_aims_the_next_item_at_it(self):
found = [decimal.Decimal(mean) for mean in ("6.50", "5.75", "6.00", "5.50", "5.94")]
self.assertEqual(under_floor(found, decimal.Decimal("6")), ["Locality 5.75", "Self-sufficiency 5.50", "Overall 5.94"])
self.assertEqual(under_floor(found, decimal.Decimal("5.5")), [])
self.assertIsNone(floor_step(found, [], [], decimal.Decimal("5.5")))
self.assertIn("until every mean reaches 6, ", floor_step(found, [], [], decimal.Decimal("6")))
def test_floor_step_files_one_item_at_the_lowest_dimension_unless_one_is_open(self):
found = [decimal.Decimal(mean) for mean in ("7.38", "6.63", "7.00", "6.50", "6.88")]
floor_item = item(5, (0, 2, 0), "**Reach the comprehension floor: restructure the reload, lifting Locality.**")
with self.subTest("none open"):
step = floor_step(found, [item(1, (0, 1, 0))], [])
step = floor_step(found, [item(1, (0, 1, 0))], [], DEFAULT_FLOOR)
self.assertTrue(step.startswith("Next: file one floor item"), step)
self.assertIn("with a tagline that opens with `Reach the comprehension floor:`,", step)
self.assertIn(" Self-sufficiency, the lowest dimension,", step)
self.assertIn('"Floor item"', step)
with self.subTest("one open"):
step = floor_step(found, [item(1, (0, 1, 0)), floor_item], [])
step = floor_step(found, [item(1, (0, 1, 0)), floor_item], [], DEFAULT_FLOOR)
self.assertTrue(step.startswith("Next: refresh floor item 5 "), step)
self.assertIn(" Self-sufficiency, the lowest dimension,", step)
self.assertIn("file no other", step)
with self.subTest("the shipped one is not open"):
self.assertTrue(floor_step(found, [floor_item], [5]).startswith("Next: file one floor item"))
self.assertTrue(floor_step(found, [floor_item], [5], DEFAULT_FLOOR).startswith("Next: file one floor item"))
with self.subTest("a tie names both"):
tied = [decimal.Decimal(mean) for mean in ("7.38", "6.50", "7.00", "6.50", "6.88")]
self.assertIn(" Locality and Self-sufficiency, the lowest dimensions,", floor_step(tied, [], []))
self.assertIn(" Locality and Self-sufficiency, the lowest dimensions,", floor_step(tied, [], [], DEFAULT_FLOOR))
with self.subTest("a tagline that only mentions the floor is no floor item"):
quoting = item(6, (0, 2, 0), "**Rename the decision `comprehension floor: …` in the log.**")
self.assertTrue(floor_step(found, [quoting], []).startswith("Next: file one floor item"))
self.assertTrue(floor_step(found, [quoting], [], DEFAULT_FLOOR).startswith("Next: file one floor item"))
with self.subTest("none under the floor"):
self.assertIsNone(floor_step([decimal.Decimal("7.00")] * 5, [floor_item], []))
self.assertIsNone(floor_step([decimal.Decimal("7.00")] * 5, [floor_item], [], DEFAULT_FLOOR))
with self.subTest("only the overall under the floor"):
step = floor_step([decimal.Decimal("7.00")] * 4 + [decimal.Decimal("6.75")], [], [])
step = floor_step([decimal.Decimal("7.00")] * 4 + [decimal.Decimal("6.75")], [], [], DEFAULT_FLOOR)
self.assertIn(" Navigation, Locality, Shape and Self-sufficiency, the lowest dimensions,", step)
self.assertIn("until every mean reaches 7.0", step)
def test_checkout_plan_fails_on_a_missing_or_tableless_todo(self):
with tempfile.TemporaryDirectory() as checkout:
path = pathlib.Path(checkout, "todo.md")
plan = FilePlan(path, "todo.md", pathlib.Path(checkout, "README.md"), MemoryStore(), MemoryStore())
plan = FilePlan(path, "todo.md", FileStore(pathlib.Path(checkout, "README.md"), None), MemoryStore(), MemoryStore(), DEFAULT_FLOOR)
with self.subTest("missing"):
self.assertEqual(checkout_plan(plan).reason, f"the project's plan: {path}: not found; every project keeps a todo.md, and rank_todo.py --help shows one")
with self.subTest("no items table"):
@@ -827,6 +835,21 @@ class LarvReviewTool(unittest.TestCase):
self.assertIn(f"cannot read {history}: not UTF-8 on line 2", ran.stderr)
self.assertEqual(history.read_bytes(), b"# Comprehension history\n\xff\n")
def test_holds_a_scoring_run_to_the_readability_floor_the_config_sets(self):
line = "Navigation 7, Locality 6.5, Shape 7, Self-sufficiency 6.5, Overall 7"
seats = "".join(f"\n{seat}: {line}\n\n- `bin/a.py:3` `f`: long\n" for seat in ("Junior A", "Mid A", "Maintainability senior", "Inherited architect"))
self.plan()
self.config.write_text(PROJECT_CONFIG + "readability-floor = 6.5\n")
ran = self.run_tool("record-scoring", self.seats_file(f"PR #2 at {self.start}\n" + seats), "1")
self.assertEqual(ran.returncode, 0, ran.stderr)
self.assertIn("\nMeans: ", ran.stdout)
self.assertNotIn("Floor:", ran.stdout)
self.config.write_text(PROJECT_CONFIG + "readability-floor = 6.8\n")
ran = self.run_tool("record-scoring", self.seats_file(f"PR #3 at {self.start}\n" + seats), "1")
self.assertEqual(ran.returncode, 0, ran.stderr)
self.assertIn("\nFloor: Locality 6.50, Self-sufficiency 6.50 under the floor of 6.8.\nNext: file one floor item,", ran.stdout)
self.assertIn("until every mean reaches 6.8,", ran.stdout)
def test_records_a_scoring_run_with_its_means(self):
line = "Navigation 7, Locality 6.5, Shape 7, Self-sufficiency 6.5, Overall 7"
seats = "".join(f"\n{seat}: {line}\n\n- `bin/a.py:3` `f`: long\n" for seat in ("Junior A", "Mid A", "Maintainability senior", "Inherited architect"))
@@ -932,7 +955,7 @@ class LarvReviewTool(unittest.TestCase):
# This checkout has no README.md beside its todo.md.
ran = self.record_sevens()
self.assertEqual(ran.returncode, 1)
self.assertIn(f"recorded the run, but rank_todo.py cannot rank {self.checkout / 'todo.md'}: {self.checkout / 'README.md'}: not found", ran.stderr)
self.assertIn(f"recorded the run, but rank_todo.py cannot rank {self.checkout / 'todo.md'}: {self.checkout / 'README.md'}: missing or empty", ran.stderr)
self.assertIn("not record-scoring again", ran.stderr)
self.assertEqual(len(entries((self.checkout / "docs" / "comprehension-history.md").read_text())), 1)
@@ -1098,11 +1121,18 @@ class LarvReviewTool(unittest.TestCase):
f"Diff: {folder}/branch-{short}.diff\n"
f"Technical principles: {self.checkout.parent}/principles\n"
f"Goals and audience: {self.checkout}/README.md\n"
f"Plan: {folder}/plan.md\n"
"Prose language: English.\n"
f"Places: {folder}/places.md\n"
)), ran.stderr)
self.assertEqual((folder / f"branch-{short}.diff").read_text(), self.git("diff", base, "HEAD"))
self.assertEqual((folder / "places.md").read_text(), self.run_tool("places").stdout)
self.assertEqual((folder / "plan.md").read_text(), (
f"# Plan, as {self.checkout}/todo.md holds it\n\n"
"## Item 1, release 0.1.0\n\n**Do it.**\n\n"
"## Item 2, release 0.2.0\n\n**Then this.**\n\n"
"## Item 3, release 0.2.0\n\n**And this.**\n"
))
def test_counts_the_round_from_the_branchs_answers_and_names_the_report_that_asked_for_a_rerun(self):
self.commit("Answer prose round 1: a")
@@ -1128,15 +1158,15 @@ class LarvReviewTool(unittest.TestCase):
for given in (["security"], ["Stability"], ["prose", "--again"], []):
self.assertEqual(self.run_tool("reviewer-header", *given).returncode, 1, given)
def test_reviewer_header_leaves_an_unchanged_diff_and_places_untouched_so_an_earlier_rounds_replay_keeps_them(self):
def test_reviewer_header_leaves_an_unchanged_diff_places_and_plan_untouched_so_an_earlier_rounds_replay_keeps_them(self):
self.commit("Work", {"a.txt": "one\n"})
folder = self.checkout.parent / ".local" / "state" / "larv-review" / "proj"
self.assertEqual(self.run_tool("reviewer-header", "stability").returncode, 0)
written = [folder / f"branch-{self.git('rev-parse', '--short', 'HEAD').strip()}.diff", folder / "places.md"]
written = [folder / f"branch-{self.git('rev-parse', '--short', 'HEAD').strip()}.diff", folder / "places.md", folder / "plan.md"]
for path in written:
os.utime(path, (0, 0))
self.assertEqual(self.run_tool("reviewer-header", "prose").returncode, 0)
self.assertEqual([path.stat().st_mtime for path in written], [0, 0])
self.assertEqual([path.stat().st_mtime for path in written], [0, 0, 0])
def test_reviewer_header_names_why_it_names_no_pull_request(self):
self.git("push", "-q", "-u", "origin", "chunk")
@@ -1199,6 +1229,17 @@ class LarvReviewTool(unittest.TestCase):
self.config.write_text(PROJECT_CONFIG.replace('"checkout:README.md"', '"folder:goals.md"'))
self.assertEqual(self.header_line("Goals and audience:", "principles"), f"Goals and audience: {self.config.parent}/goals.md")
def test_reviewer_header_fails_naming_the_epic_where_it_cannot_read_goals_kept_in_jira(self):
# Port 1 on the loopback refuses the connection, so the read fails without leaving the machine.
epic = "jira:https://127.0.0.1:1/browse/ABC-12"
credentials = self.config.parents[2] / "acme.env"
credentials.write_text("ATLASSIAN_EMAIL=me@example.com\nATLASSIAN_API_TOKEN=s3cret\n")
credentials.chmod(0o600)
self.config.write_text(PROJECT_CONFIG.replace('"checkout:todo.md"', f'"{epic}"').replace('"checkout:README.md"', f'"{epic}"') + 'env-file = "~/acme.env"\n')
ran = self.run_tool("reviewer-header", "prose")
self.assertEqual((ran.returncode, ran.stdout), (1, ""))
self.assertIn("cannot read the epic ABC-12", ran.stderr)
def test_reviewer_header_fails_with_the_configs_message_where_it_sets_no_principles_folder(self):
self.config.write_text(PROJECT_CONFIG.replace('principles = "~/principles"\n', ""))
ran = self.run_tool("reviewer-header", "prose")
+44
View File
@@ -0,0 +1,44 @@
import pathlib
import sys
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from plan_store.stores import BLOCKED_BY
from plan_store.contract import FIRST, SECOND
from plan_store.fakes import MemoryPlan
from larv_review.plan_listing import plan_listing
class PlanListing(unittest.TestCase):
def test_lists_each_item_with_its_release_tagline_blockers_and_detail_in_the_stores_order(self):
plan = MemoryPlan(label="the epic ABC-12")
plan.add(FIRST, "\nCount them where they are made.\n\nSay why.\n\n")
plan.add(SECOND | {BLOCKED_BY: "1, 7"}, "")
self.assertEqual(plan_listing(plan), (
"# Plan, as the epic ABC-12 holds it\n"
"\n"
"## Item 1, release 0.1.0\n"
"\n"
"**Count the runs.**\n"
"\n"
"Count them where they are made.\n"
"\n"
"Say why.\n"
"\n"
"## Item 2, release 0.2.0\n"
"\n"
"**Ship the later thing.**\n"
"\n"
"Blocked by: 1, 7.\n"
))
def test_says_so_where_the_plan_holds_no_item(self):
self.assertEqual(plan_listing(MemoryPlan(label="the epic ABC-12")), "# Plan, as the epic ABC-12 holds it\n\nThe plan holds no item.\n")
def test_says_why_where_the_plan_cannot_be_read_so_a_reviewer_does_not_take_it_for_empty(self):
self.assertEqual(plan_listing(MemoryPlan(label="the epic ABC-12", fails="Jira answered 401")), "# Plan, as the epic ABC-12 holds it\n\nThe plan cannot be read, so no item is listed: Jira answered 401\n")
if __name__ == "__main__":
unittest.main()
+1 -1
View File
@@ -4,4 +4,4 @@ from loop_effects.effects import Effects, say
def tell(text: str, effects: Effects) -> None:
"""DMs text to the human. Where the DM fails, it says why on stderr and goes on: the DM only copies what the terminal shows, so its failure never stops the loop."""
if failed := effects.dm(text):
say(f"could not DM you on Mattermost: {failed.reason}", effects)
say(f"could not DM you: {failed.reason}", effects)
+22 -21
View File
@@ -4,25 +4,26 @@ usage: loop-claude <task>
Run it anywhere inside a project checkout whose goals file has ## Goals and ## Audience, the
premises. The goals file is the one the project's config, ~/.claude-projects/<key>/config.toml, sets
as goals-and-audience; `project-config goals-and-audience` prints it. 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 end, the premises, and the records: the project's
AGENTS.md and docs/decisions.md, and the human's ~/.claude/CLAUDE.md, ~/.claude/rules/*.md and
~/.claude/skills/larv-review/standards/*.md, where they exist. It rules whether the chunk, the work
of one PR, is finished. A chunk stays unfinished until each answer the human typed in it that a
later chunk could need is recorded: the premises or the records hold it, or the transcript shows the
worker writing it into the premises, AGENTS.md, docs/decisions.md, todo.md or a code comment. A
choice the worker made that the premises or the records settle is not asked about. When the worker
asks a question they answer, the judge quotes the answer, loop-claude prints it, and the worker
resumes with it. A quote they do not hold word for word is dropped, and the question goes to the
human. So does a question asked again after its answer. A question the human answered earlier in the
chunk goes back to the worker with that answer, unless the question quotes the words of the answer
that leave it open. The fourth question they answer in one cycle goes to the human too, with the
quote. An unfinished chunk resumes its session next cycle, and the worker is shown the passage the
judge quoted as the work remaining. The next chunk starts a fresh session. Cycles continue until an
exit below or Ctrl-C. Words: ~/.claude/CLAUDE.md → "Vocabulary".
as goals-and-audience: a file, or a Jira epic's description. `project-config goals-and-audience`
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
end, the premises, and the records: the project's AGENTS.md and docs/decisions.md, and the human's
~/.claude/CLAUDE.md, ~/.claude/rules/*.md and ~/.claude/skills/larv-review/standards/*.md, where
they exist. It rules whether the chunk, the work of one PR, is finished. A chunk stays unfinished
until each answer the human typed in it that a later chunk could need is recorded: the premises or
the records hold it, or the transcript shows the worker writing it into the premises, AGENTS.md,
docs/decisions.md, todo.md or a code comment. A choice the worker made that the premises or the
records settle is not asked about. When the worker asks a question they answer, the judge quotes the
answer, loop-claude prints it, and the worker resumes with it. A quote they do not hold word for
word is dropped, and the question goes to the human. So does a question asked again after its
answer. A question the human answered earlier in the chunk goes back to the worker with that answer,
unless the question quotes the words of the answer that leave it open. The fourth question they
answer in one cycle goes to the human too, with the quote. An unfinished chunk resumes its session
next cycle, and the worker is shown the passage the judge quoted as the work remaining. The next
chunk starts a fresh session. Cycles continue until an exit below or Ctrl-C. Words:
~/.claude/CLAUDE.md → "Vocabulary".
A question only the human can answer is an interrupt (bin/loop_claude/cycle/interrupt.py).
loop-claude prints the question on its terminal, where the human answers it:
@@ -33,8 +34,8 @@ loop-claude prints the question on its terminal, where the human answers it:
- Enter alone: stops the loop.
A release ready to cut opens that session on the terminal at once, since only the human may cut it.
While claude is open, Ctrl-C reaches it alone, and the loop goes on.
Where the project's config sets env-file, loop-claude also sends the human each question, each
release ready to cut and each stop as a Mattermost DM, as bin/mattermost-dm sends it. Two stops are
Where the project's config sets notifier, loop-claude also sends the human each question, each
release ready to cut and each stop as a DM, as bin/notify sends it. Two stops are
left out: Ctrl-C, and printing this help. A DM that fails is said on stderr, and the loop goes on.
As a chunk starts, before it is routed, loop-claude runs bin/chunk-preflight --worktree and quotes
+13 -10
View File
@@ -1,23 +1,26 @@
import pathlib
from failure import Failure
from project_config.main import goals_file
from loop_claude.project.text_file import read_utf8
from record_store.stores import goals_store
from project_config.main import located
from release_plan.goals_file import section
def read_premises(root: str, home: pathlib.Path) -> str | Failure:
"""The goals file's path, then its ## Goals and ## Audience; the goals file is the one that the config under home of root's project names. A Failure where no config names root's checkout, the file cannot be read, or the file lacks a section, holds one twice or leaves one empty."""
path = goals_file(root, home)
if isinstance(path, Failure):
return Failure(f"{path.reason} - no premises.")
text = read_utf8(str(path.parent), path.name, "no premises")
"""Where the goals file is kept, then its ## Goals and ## Audience. The goals file is the one that the config of root's checkout, under home, names: a file or a Jira epic's description. A Failure where no config names the checkout, or the goals file cannot be read, is missing or empty, lacks a section, holds one twice or leaves one empty."""
config = located(root, home)
if isinstance(config, Failure):
return Failure(f"{config.reason} - no premises.")
goals = goals_store(config)
text = goals.read()
if isinstance(text, Failure):
return text
return Failure(f"{text.reason} - no premises.")
if not text:
return Failure(f"{goals.label} is missing or empty - no premises.")
bodies: list[str] = []
for name in ("Goals", "Audience"):
body = section(text, name)
if isinstance(body, Failure):
return Failure(f"{path} {body.reason} - no premises.")
return Failure(f"{goals.label} {body.reason} - no premises.")
bodies.append(body)
return f"{path}:\n## Goals\n{bodies[0]}\n\n## Audience\n{bodies[1]}"
return f"{goals.label}:\n## Goals\n{bodies[0]}\n\n## Audience\n{bodies[1]}"
+6 -6
View File
@@ -335,8 +335,8 @@ class Premises(unittest.TestCase):
self.assertEqual((run.code, run.calls), (1, []))
self.assertRegex(run.raw_stderr, rf"(?m)^{STAMP} .*not a git repository")
readmes = {
None: "README.md in {root}: No such file or directory - no premises.",
b"# P\n## Goals\n1. g\xff\n## Audience\nme\n": "README.md in {root} is not UTF-8 on line 3 - no premises.",
None: "{root}/README.md is missing or empty - no premises.",
b"# P\n## Goals\n1. g\xff\n## Audience\nme\n": "cannot read {root}/README.md: not UTF-8 on line 3 - no premises.",
b"# P\n## Audience\nme\n": "{root}/README.md has no ## Goals heading - no premises.",
b"# P\n## Goals\n1. g\n": "{root}/README.md has no ## Audience heading - no premises.",
b"# P\n## Goals\n\n## Audience\nme\n": "{root}/README.md has no text under ## Goals - no premises.",
@@ -356,7 +356,7 @@ class Premises(unittest.TestCase):
(checkout.root / "README.md").mkdir()
run = checkout.run([worker()])
self.assertEqual((run.code, run.calls), (1, []))
self.assertEqual(run.stderr.strip(), f"README.md in {checkout.root}: Is a directory - no premises.")
self.assertEqual(run.stderr.strip(), f"cannot read {checkout.root}/README.md: Is a directory - no premises.")
(checkout.home / ".claude-projects" / "proj" / "config.toml").unlink()
run = checkout.run([worker()])
self.assertEqual((run.code, run.calls), (1, []))
@@ -741,17 +741,17 @@ class Interrupt(unittest.TestCase):
self.assertEqual(run.code, 2)
self.assertEqual(len(checkout.archived()), 2)
def test_sends_the_dm_through_the_env_file_the_config_names_and_no_credential_reaches_a_prompt_a_line_printed_or_a_file_written(self):
def test_sends_the_dm_through_the_notifier_and_env_file_the_config_names_and_no_credential_reaches_a_prompt_a_line_printed_or_a_file_written(self):
checkout = Checkout(self)
token = "tok-3f9a1c7e-sentinel"
env_file = checkout.home / ".claude-projects" / "proj.env"
env_file.write_text(f"MATTERMOST_URL=https://127.0.0.1:1\nMATTERMOST_TOKEN={token}\nMATTERMOST_RECIPIENT=lilleman\n")
env_file.chmod(0o600)
with (checkout.home / ".claude-projects" / "proj" / "config.toml").open("a") as config:
config.write('env-file = "~/.claude-projects/proj.env"\n')
config.write('env-file = "~/.claude-projects/proj.env"\nnotifier = "mattermost"\n')
run = checkout.run([worker(say="Shall I use A or B?"), judge(interrupt=True, evidence="Shall I use A or B?", question="A or B?")])
self.assertEqual((run.code, run.roles()), (2, ["worker", "judge"]))
self.assertIn("could not DM you on Mattermost: cannot reach https://127.0.0.1:1", run.stderr)
self.assertIn("could not DM you: cannot reach https://127.0.0.1:1", run.stderr)
held = [run.raw_stdout, run.raw_stderr, json.dumps(run.calls), json.dumps(run.starts)]
held += [file.read_text(errors="replace") for file in checkout.home.rglob("*") if file.is_file() and file != env_file and not file.is_symlink()]
self.assertGreater(len(held), 8, "the walk reached the archive, the state and the transcripts")
+2 -2
View File
@@ -763,7 +763,7 @@ class Interrupts(unittest.TestCase):
def test_says_why_a_dm_failed_and_still_takes_the_answer(self):
fake = FakeEffects(inputs=["Use B."], dm_failures=[Failure("cannot reach https://chat.example: timed out")])
self.assertEqual(self.put(fake), ("Use B.", f"\n{STAMP} Which one?\n{STAMP} could not DM you on Mattermost: cannot reach https://chat.example: timed out\n"))
self.assertEqual(self.put(fake), ("Use B.", f"\n{STAMP} Which one?\n{STAMP} could not DM you: cannot reach https://chat.example: timed out\n"))
def test_returns_the_line_typed_after_the_question_stripped_dropping_what_was_typed_before(self):
fake = FakeEffects(inputs=[" Use B. "])
@@ -1893,7 +1893,7 @@ class StopDms(unittest.TestCase):
def test_says_why_the_dm_of_a_stop_failed_after_the_reason(self):
fake = FakeEffects(dm_failures=[Failure("cannot reach https://chat.example: timed out")])
self.assertTrue(self.run_main([main.RELOAD_FLAG, "3"], fake)[1].endswith(f"Handed: 3\n{STAMP} could not DM you on Mattermost: cannot reach https://chat.example: timed out\n"))
self.assertTrue(self.run_main([main.RELOAD_FLAG, "3"], fake)[1].endswith(f"Handed: 3\n{STAMP} could not DM you: cannot reach https://chat.example: timed out\n"))
def test_skips_the_dm_where_it_prints_its_help(self):
for argv, code in (([], 1), (["--help"], 0)):
+6 -4
View File
@@ -12,10 +12,11 @@ import termios
import time
import typing
from mattermost_dm.dm import dm, http_json
from notifier.notify import Backend, BACKENDS, notify
from failure import Failure
from git_cli import git_repo
from machine_load.memory import Memory, read_memory
from project_config.settings import Notifier
# Seconds before a Python script loop-claude runs is stopped, so a hung one, such as chunk-preflight, cannot hold the loop.
PYTHON_TIMEOUT = 600
@@ -35,7 +36,7 @@ class Effects:
claude_on_terminal: typing.Callable[[list[str], str, dict[str, str]], int]
# Drops what was typed on the terminal and not yet read.
discard_typed: typing.Callable[[], None]
# Sends the human a direct message on Mattermost, as `mattermost-dm` does, for the project whose checkout holds the current directory; a Failure where it could not.
# Sends the human a direct message through the notifier the project's config names, as `notify` does, for the project whose checkout holds the current directory; a Failure where it could not.
dm: typing.Callable[[str], Failure | None]
execv: typing.Callable[[str, list[str]], None]
git: git_repo.Git
@@ -64,12 +65,13 @@ class StreamingClaude:
return self.proc.wait()
def system_effects() -> Effects:
def system_effects(backends: typing.Mapping[Notifier, Backend[typing.Any]] = BACKENDS) -> Effects:
"""The effects on this machine; `backends` are the notifiers loop-claude's DM can go through, where a test swaps in one that sends nowhere."""
return Effects(
claude=lambda args, cwd, stdin: subprocess.run(["claude", *args], capture_output=True, cwd=cwd, input=stdin, text=True),
claude_on_terminal=claude_on_terminal,
discard_typed=lambda: termios.tcflush(sys.stdin, termios.TCIFLUSH),
dm=lambda text: dm(text, None, pathlib.Path.home(), http_json),
dm=lambda text: notify(text, None, pathlib.Path.home(), backends),
execv=os.execv,
git=git_repo.git,
input=input,
-9
View File
@@ -1,9 +0,0 @@
#!/usr/bin/env python3
import pathlib
import sys
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from mattermost_dm import dm, main
sys.exit(main.main(sys.argv[1:], sys.stdin, lambda: dm.config_of(None, pathlib.Path.home()), dm.http_json, sys.stderr))
+3 -27
View File
@@ -1,21 +1,17 @@
"""Sends a direct message from a Mattermost bot to one user, through Mattermost's REST API v4."""
"""Sends a direct message from a Mattermost bot to one user, through Mattermost's REST API v4. The `notifier` setting `mattermost` picks it."""
import dataclasses
import pathlib
import typing
import urllib.parse
from failure import Failure
from rest_client.json_request import Http
from rest_client import json_request
from project_config.main import located
from rest_client.env_file import read_env
KEYS = ("MATTERMOST_URL", "MATTERMOST_TOKEN", "MATTERMOST_RECIPIENT")
# Seconds each connect and each read may wait, so an unreachable server holds loop-claude's interrupt only briefly.
TIMEOUT = 10
# Sends a request, the body as JSON where there is one, and returns the JSON answer, or a Failure saying why there is none.
Http = typing.Callable[[str, str, str, object], object]
@dataclasses.dataclass(frozen=True)
class Config:
@@ -58,7 +54,7 @@ def id_of(answer: object, request: str) -> str | Failure:
def http_json(method: str, url: str, token: str, body: object) -> object:
"""The JSON that url answers to the bot's request, or a Failure saying why there is none."""
"""The JSON that url answers to the bot's request, None where the answer has no body, or a Failure saying why there is none."""
return json_request.http_json(method, url, f"Bearer {token}", body, TIMEOUT, error_message)
@@ -67,23 +63,3 @@ def error_message(answer: object) -> str:
message = answer.get("message") if isinstance(answer, dict) else None
return message if isinstance(message, str) else ""
def dm(text: str, directory: str | None, home: pathlib.Path, http: Http) -> Failure | None:
"""Sends text to the recipient that the project's env file names. The project is the one whose checkout holds directory, and its config names the file.
The DM is skipped where the config sets no env-file, since the project hasn't asked for DMs. It is skipped too where no config can be read: loop-claude has stopped with that reason, and without a config there is no file to read the recipient from."""
project = located(directory, home)
if isinstance(project, Failure) or project.env_file is None:
return None
config = read_config(project.env_file)
return config if isinstance(config, Failure) else send(config, text, http)
def config_of(directory: str | None, home: pathlib.Path) -> Config | Failure:
"""The server, token and recipient in the env file that the config of the project holding directory names."""
project = located(directory, home)
if isinstance(project, Failure):
return project
if project.env_file is None:
return Failure(f"{project.folder / 'config.toml'} sets no `env-file`; set it to the file that holds {', '.join(KEYS[:-1])} and {KEYS[-1]}")
return read_config(project.env_file)
-47
View File
@@ -1,47 +0,0 @@
"""Send a direct message from the Mattermost bot to the human.
usage: mattermost-dm [<message>]
Sends <message>, or else stdin, from the bot to the recipient that a project's env file names. Run it
inside the project's checkout, or a worktree of it. The project's config,
~/.claude-projects/<key>/config.toml, names the env file in `env-file`, a path outside the checkout
and the config's folder, such as "~/.claude-projects/<key>.env". The file holds three KEY=value lines,
and only its owner may read it, since it holds the bot's token:
MATTERMOST_URL=https://chat.example
MATTERMOST_TOKEN=<the bot's access token>
MATTERMOST_RECIPIENT=<the recipient's username>
Exit 0 once the message is sent.
Exit 1, saying why, when Mattermost cannot be reached or refuses the message.
Exit 2, saying why, on misuse: bad arguments, an empty message, a directory with no project config,
a config that sets no `env-file`, or an env file that is missing or unreadable, lacks a key, names a
server off https, or that others may read. None of these messages holds the token.
"""
import typing
from mattermost_dm.dm import Config, Http, send
from failure import Failure
USAGE = "usage: mattermost-dm [<message>]"
def main(argv: list[str], stdin: typing.TextIO, config: typing.Callable[[], Config | Failure], http: Http, stderr: typing.TextIO) -> int:
if argv[:1] in (["-h"], ["--help"]):
print(__doc__.strip())
return 0
if len(argv) > 1:
print(f"mattermost-dm: takes one message, or none to read stdin; got {len(argv)} arguments\n{USAGE}", file=stderr)
return 2
message = (argv[0] if argv else stdin.read()).strip()
if not message:
print("mattermost-dm: the message is empty", file=stderr)
return 2
found = config()
if isinstance(found, Failure):
print(f"mattermost-dm: {found.reason}", file=stderr)
return 2
if failed := send(found, message, http):
print(f"mattermost-dm: {failed.reason}", file=stderr)
return 1
return 0
+3 -121
View File
@@ -1,7 +1,4 @@
import contextlib
import io
import pathlib
import subprocess
import sys
import tempfile
import unittest
@@ -9,18 +6,14 @@ import unittest.mock
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from project_config.test_project_config import configured
from mattermost_dm import dm, main
from mattermost_dm import dm
from failure import Failure
from test_env import isolated_env
from loop_effects.effects import system_effects
TOOL = pathlib.Path(__file__).resolve().parents[1] / "mattermost-dm"
CONFIG = dm.Config("https://chat.example", "secret-token", "lilleman")
def env_file(folder: str, text: str, mode: int = 0o600, name: str = ".env") -> pathlib.Path:
path = pathlib.Path(folder) / name
def env_file(folder: str, text: str, mode: int = 0o600) -> pathlib.Path:
path = pathlib.Path(folder) / ".env"
path.write_text(text)
path.chmod(mode)
return path
@@ -120,116 +113,5 @@ class HttpJson(unittest.TestCase):
self.assertEqual(dm.error_message(answer), message)
class Project(unittest.TestCase):
"""A home with a git checkout that a config names; `folder` is the config's folder."""
def setUp(self) -> None:
made = tempfile.TemporaryDirectory()
self.addCleanup(made.cleanup)
self.home = pathlib.Path(made.name).resolve()
self.checkout = self.home / "code" / "proj"
self.checkout.mkdir(parents=True)
self.folder = configured(self, self.checkout, home=self.home)
def name_env_file(self, text: str | None = None) -> pathlib.Path:
"""Makes the config name ~/.claude-projects/proj.env, holding text where that is not None."""
with (self.folder / "config.toml").open("a") as config:
config.write('env-file = "~/.claude-projects/proj.env"\n')
path = self.home / ".claude-projects" / "proj.env"
return path if text is None else env_file(str(path.parent), text, name=path.name)
class Dm(Project):
def test_sends_through_the_env_file_the_config_names(self):
self.name_env_file("MATTERMOST_URL=https://chat.example\nMATTERMOST_TOKEN=secret-token\nMATTERMOST_RECIPIENT=lilleman\n")
server = mattermost()
self.assertIsNone(dm.dm("Which one?", str(self.checkout), self.home, server))
self.assertEqual(server.requests[-1], ("POST", "https://chat.example/api/v4/posts", "secret-token", {"channel_id": "channel-id", "message": "Which one?"}))
def test_loop_claudes_dm_posts_the_text_for_the_project_holding_the_current_directory(self):
self.name_env_file("MATTERMOST_URL=https://chat.example\nMATTERMOST_TOKEN=secret-token\nMATTERMOST_RECIPIENT=lilleman\n")
server = mattermost()
with unittest.mock.patch("loop_effects.effects.http_json", server), contextlib.chdir(self.checkout):
self.assertIsNone(system_effects().dm("Which one?"))
self.assertEqual(server.requests[-1], ("POST", "https://chat.example/api/v4/posts", "secret-token", {"channel_id": "channel-id", "message": "Which one?"}))
def test_skips_the_dm_for_a_project_whose_config_names_no_env_file_even_where_the_old_shared_file_exists(self):
(self.home / ".claude").mkdir()
env_file(str(self.home / ".claude"), "MATTERMOST_URL=https://chat.example\nMATTERMOST_TOKEN=other-projects-token\nMATTERMOST_RECIPIENT=lilleman\n", name=".env")
server = mattermost()
self.assertIsNone(dm.dm("Which one?", str(self.checkout), self.home, server))
self.assertEqual(server.requests, [])
def test_fails_naming_the_file_where_the_config_names_one_that_is_not_there(self):
path = self.name_env_file()
self.assertEqual(dm.dm("Which one?", str(self.checkout), self.home, mattermost()), Failure(f"{path} does not exist; it needs MATTERMOST_URL, MATTERMOST_TOKEN and MATTERMOST_RECIPIENT"))
def test_fails_naming_the_mistake_where_the_env_file_is_there_but_wrong(self):
path = self.name_env_file("MATTERMOST_URL=https://chat.example\n")
self.assertEqual(dm.dm("Which one?", str(self.checkout), self.home, mattermost()), Failure(f"{path} lacks MATTERMOST_TOKEN and MATTERMOST_RECIPIENT"))
def test_skips_the_dm_where_no_config_names_the_checkout_since_loop_claude_stops_on_that_itself(self):
other = self.home / "code" / "other"
other.mkdir()
subprocess.run(["git", "init", "--quiet", str(other)], check=True, env=isolated_env())
server = mattermost()
self.assertIsNone(dm.dm("Which one?", str(other), self.home, server))
self.assertEqual(server.requests, [])
def test_config_of_names_the_setting_to_add_where_the_config_names_no_env_file(self):
failed = dm.config_of(str(self.checkout), self.home)
assert isinstance(failed, Failure), failed
self.assertEqual(failed.reason, f"{self.folder / 'config.toml'} sets no `env-file`; set it to the file that holds MATTERMOST_URL, MATTERMOST_TOKEN and MATTERMOST_RECIPIENT")
def test_config_of_reads_the_env_file_the_config_names(self):
self.name_env_file("MATTERMOST_URL=https://chat.example/\nMATTERMOST_TOKEN=secret-token\nMATTERMOST_RECIPIENT=lilleman\n")
self.assertEqual(dm.config_of(str(self.checkout), self.home), CONFIG)
def test_the_failure_for_an_unreachable_server_names_the_server_and_not_the_token(self):
self.name_env_file("MATTERMOST_URL=https://127.0.0.1:1\nMATTERMOST_TOKEN=secret-token\nMATTERMOST_RECIPIENT=lilleman\n")
failed = dm.dm("Which one?", str(self.checkout), self.home, dm.http_json)
assert isinstance(failed, Failure), failed
self.assertIn("cannot reach https://127.0.0.1:1", failed.reason)
self.assertNotIn("secret-token", failed.reason)
class Main(Project):
def run_main(self, argv: list[str], stdin: str = "", config: object = CONFIG, server: object = None) -> tuple[int, str]:
stderr = io.StringIO()
sent = server or mattermost()
code = main.main(argv, io.StringIO(stdin), lambda: config, sent, stderr) # type: ignore[arg-type]
return code, stderr.getvalue()
def test_sends_its_argument_or_else_stdin_and_exits_0(self):
for argv, stdin in ((["Which one?"], ""), ([], "Which one?\n")):
with self.subTest(argv=argv):
server = mattermost()
self.assertEqual(self.run_main(argv, stdin, server=server), (0, ""))
self.assertEqual(server.requests[-1][3], {"channel_id": "channel-id", "message": "Which one?"})
def test_exits_2_on_misuse_naming_it(self):
missing = Failure("/h/.claude/.env does not exist; it needs MATTERMOST_URL, MATTERMOST_TOKEN and MATTERMOST_RECIPIENT")
for argv, stdin, config, said in (
([], " \n", CONFIG, "mattermost-dm: the message is empty\n"),
(["a", "b"], "", CONFIG, f"mattermost-dm: takes one message, or none to read stdin; got 2 arguments\n{main.USAGE}\n"),
(["hi"], "", missing, f"mattermost-dm: {missing.reason}\n"),
):
with self.subTest(argv=argv, stdin=stdin):
self.assertEqual(self.run_main(argv, stdin, config), (2, said))
def test_exits_1_naming_why_the_send_failed(self):
server = mattermost()
server.answers[("GET", "/api/v4/users/me")] = Failure("GET /api/v4/users/me answered 401: Invalid or expired session, please login again.")
self.assertEqual(self.run_main(["hi"], server=server), (1, "mattermost-dm: GET /api/v4/users/me answered 401: Invalid or expired session, please login again.\n"))
def test_the_launcher_prints_help_and_reads_the_env_file_the_projects_config_names(self):
env = {**isolated_env(), "HOME": str(self.home)}
helped = subprocess.run([sys.executable, str(TOOL), "--help"], capture_output=True, text=True, env=env, cwd=self.checkout)
self.assertEqual((helped.returncode, helped.stdout.splitlines()[0]), (0, main.__doc__.strip().splitlines()[0]))
path = self.name_env_file()
sent = subprocess.run([sys.executable, str(TOOL), "hi"], capture_output=True, text=True, env=env, cwd=self.checkout)
self.assertEqual((sent.returncode, sent.stderr), (2, f"mattermost-dm: {path} does not exist; it needs MATTERMOST_URL, MATTERMOST_TOKEN and MATTERMOST_RECIPIENT\n"))
if __name__ == "__main__":
unittest.main()
View File
+55
View File
@@ -0,0 +1,55 @@
"""Send a message from the notifier's bot to the human.
usage: notify [<message>]
Sends <message>, or else stdin, through the notifier that a project's config names, from the bot to the
recipient that the project's env file names. Run it inside the project's checkout, or a worktree of it.
The project's config, ~/.claude-projects/<key>/config.toml, sets `notifier` to "mattermost" or "slack"
and `env-file` to a path outside the checkout and the config's folder, such as
"~/.claude-projects/<key>.env". The env file holds the notifier's KEY=value lines, and only its owner
may read it, since it holds the bot's token. For mattermost:
MATTERMOST_URL=https://chat.example
MATTERMOST_TOKEN=<the bot's access token>
MATTERMOST_RECIPIENT=<the recipient's username>
For slack, a bot token with the `chat:write` scope, and the recipient's member ID, which Slack shows
under Profile → ⋮ → Copy member ID:
SLACK_TOKEN=<the bot's token, xoxb-…>
SLACK_RECIPIENT=<the recipient's member ID, U…>
Exit 0 once the message is sent.
Exit 1, saying why, when the notifier cannot be reached or refuses the message.
Exit 2, saying why, on misuse: bad arguments, an empty message, a directory with no project config,
a config that sets no `notifier` or no `env-file`, or an env file that is missing or unreadable, lacks
a key, names a Mattermost server off https, or that others may read. None of these messages holds the
token.
"""
import typing
from failure import Failure
from notifier.notify import Sender
USAGE = "usage: notify [<message>]"
def main(argv: list[str], stdin: typing.TextIO, sender: typing.Callable[[], Sender | Failure], stderr: typing.TextIO) -> int:
if argv[:1] in (["-h"], ["--help"]):
print(__doc__.strip())
return 0
if len(argv) > 1:
print(f"notify: takes one message, or none to read stdin; got {len(argv)} arguments\n{USAGE}", file=stderr)
return 2
message = (argv[0] if argv else stdin.read()).strip()
if not message:
print("notify: the message is empty", file=stderr)
return 2
found = sender()
if isinstance(found, Failure):
print(f"notify: {found.reason}", file=stderr)
return 2
if failed := found(message):
print(f"notify: {failed.reason}", file=stderr)
return 1
return 0
+61
View File
@@ -0,0 +1,61 @@
"""Sends a DM through the notifier that a project's config names."""
import dataclasses
import pathlib
import typing
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
# Sends one message, with the credentials already read.
Sender = typing.Callable[[str], Failure | None]
@dataclasses.dataclass(frozen=True)
class Backend[C]:
"""What one notifier needs: `read_config` reads its credentials from an env file, and returns what `send` takes as its config; `send` posts a message with them through `http`; `keys` are the env file's keys."""
read_config: typing.Callable[[pathlib.Path], C | Failure]
send: typing.Callable[[C, str, Http], Failure | None]
http: Http
keys: tuple[str, ...]
# 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),
}
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())})")
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")
backend = backends[project.notifier]
config = backend.read_config(project.env_file)
if isinstance(config, Failure):
return config
return lambda message: backend.send(config, message, backend.http)
def notify(text: str, directory: str | None, home: pathlib.Path, backends: typing.Mapping[Notifier, Backend[typing.Any]]) -> Failure | None:
"""Sends text through the notifier of the project whose checkout holds directory.
The DM is skipped where the config names no notifier, since the project hasn't asked for DMs. It is skipped too where no config can be read: loop-claude has stopped with that reason, and without a config there is no notifier to ask."""
project = located(directory, home)
if isinstance(project, Failure) or project.notifier is None:
return None
sender = sender_of(project, backends)
return sender if isinstance(sender, Failure) else sender(text)
def sender_in(directory: str | None, home: pathlib.Path, backends: typing.Mapping[Notifier, Backend[typing.Any]]) -> Sender | Failure:
"""sender_of the project whose checkout holds directory."""
project = located(directory, home)
return project if isinstance(project, Failure) else sender_of(project, backends)
+179
View File
@@ -0,0 +1,179 @@
import contextlib
import dataclasses
import io
import pathlib
import subprocess
import sys
import tempfile
import typing
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from project_config.test_project_config import configured
from failure import Failure
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 project_config.settings import Notifier
from slack_dm.test_slack_dm import Slack
from loop_effects.effects import system_effects
TOOL = pathlib.Path(__file__).resolve().parents[1] / "notify"
MATTERMOST_KEYS = "MATTERMOST_URL=https://chat.example\nMATTERMOST_TOKEN=secret-token\nMATTERMOST_RECIPIENT=lilleman\n"
SLACK_KEYS = "SLACK_TOKEN=xoxb-secret\nSLACK_RECIPIENT=U0123ABCD\n"
MATTERMOST_POST = ("POST", "https://chat.example/api/v4/posts", "secret-token", {"channel_id": "channel-id", "message": "Which one?"})
SLACK_POST = ("POST", "https://slack.com/api/chat.postMessage", "xoxb-secret", {"channel": "U0123ABCD", "text": "Which one?"})
MISSING_MATTERMOST = "does not exist; it needs MATTERMOST_URL, MATTERMOST_TOKEN and MATTERMOST_RECIPIENT"
def through(name: Notifier, http: Http) -> dict[Notifier, notify.Backend[typing.Any]]:
"""The notifier table with the named backend sending through http."""
return {**notify.BACKENDS, name: dataclasses.replace(notify.BACKENDS[name], http=http)}
class Project(unittest.TestCase):
"""A home with a git checkout that a config names; `folder` is the config's folder."""
def setUp(self) -> None:
made = tempfile.TemporaryDirectory()
self.addCleanup(made.cleanup)
self.home = pathlib.Path(made.name).resolve()
self.checkout = self.home / "code" / "proj"
self.checkout.mkdir(parents=True)
self.folder = configured(self, self.checkout, home=self.home)
def name_notifier(self, notifier: str | None, keys: str | None = None) -> pathlib.Path:
"""Makes the config name ~/.claude-projects/proj.env as its env file, and the notifier where there is one; the file holds keys where that is not None."""
with (self.folder / "config.toml").open("a") as config:
config.write('env-file = "~/.claude-projects/proj.env"\n' + (f'notifier = "{notifier}"\n' if notifier else ""))
path = self.home / ".claude-projects" / "proj.env"
if keys is not None:
path.write_text(keys)
path.chmod(0o600)
return path
class Notify(Project):
def test_sends_through_mattermost_where_the_config_names_it(self):
self.name_notifier("mattermost", MATTERMOST_KEYS)
server = mattermost()
self.assertIsNone(notify.notify("Which one?", str(self.checkout), self.home, through("mattermost", server)))
self.assertEqual(server.requests[-1], MATTERMOST_POST)
def test_sends_through_slack_where_the_config_names_it(self):
self.name_notifier("slack", SLACK_KEYS)
slack = Slack({"ok": True})
self.assertIsNone(notify.notify("Which one?", str(self.checkout), self.home, through("slack", slack)))
self.assertEqual(slack.requests, [SLACK_POST])
def test_loop_claudes_dm_goes_through_the_notifier_for_the_project_holding_the_current_directory(self):
self.name_notifier("slack", SLACK_KEYS)
slack = Slack({"ok": True})
with contextlib.chdir(self.checkout):
self.assertIsNone(system_effects(through("slack", slack)).dm("Which one?"))
self.assertEqual(slack.requests, [SLACK_POST])
def test_skips_the_notice_for_a_project_that_names_no_notifier_even_where_its_env_file_holds_the_keys(self):
self.name_notifier(None, MATTERMOST_KEYS)
server = mattermost()
self.assertIsNone(notify.notify("Which one?", str(self.checkout), self.home, through("mattermost", server)))
self.assertEqual(server.requests, [])
def test_skips_the_notice_where_no_config_names_the_checkout_since_loop_claude_stops_on_that_itself(self):
other = self.home / "code" / "other"
other.mkdir()
subprocess.run(["git", "init", "--quiet", str(other)], check=True, env=isolated_env())
server = mattermost()
self.assertIsNone(notify.notify("Which one?", str(other), self.home, through("mattermost", server)))
self.assertEqual(server.requests, [])
def test_fails_naming_the_file_or_the_key_where_the_env_file_is_missing_or_wrong(self):
path = self.name_notifier("slack")
self.assertEqual(notify.notify("hi", str(self.checkout), self.home, through("slack", Slack({"ok": True}))), Failure(f"{path} does not exist; it needs SLACK_TOKEN and SLACK_RECIPIENT"))
path.write_text("SLACK_TOKEN=xoxb-secret\n")
path.chmod(0o600)
self.assertEqual(notify.notify("hi", str(self.checkout), self.home, through("slack", Slack({"ok": True}))), Failure(f"{path} lacks SLACK_RECIPIENT"))
def test_the_failure_for_an_unreachable_server_names_the_server_and_not_the_token(self):
self.name_notifier("mattermost", MATTERMOST_KEYS.replace("https://chat.example", "https://127.0.0.1:1"))
failed = notify.notify("Which one?", str(self.checkout), self.home, notify.BACKENDS)
assert isinstance(failed, Failure), failed
self.assertIn("cannot reach https://127.0.0.1:1", failed.reason)
self.assertNotIn("secret-token", failed.reason)
def test_sender_in_fails_for_an_env_file_that_no_notifier_reads(self):
self.name_notifier(None, MATTERMOST_KEYS)
failed = notify.sender_in(str(self.checkout), self.home, notify.BACKENDS)
assert isinstance(failed, Failure), failed
self.assertIn("sets no `notifier`", failed.reason)
def test_sender_of_names_the_missing_env_file_for_a_config_built_by_hand_with_a_notifier_and_none(self):
self.name_notifier("slack", SLACK_KEYS)
project = located(str(self.checkout), self.home)
assert not isinstance(project, Failure), project
failed = notify.sender_of(dataclasses.replace(project, env_file=None), notify.BACKENDS)
self.assertEqual(failed, Failure(f"{self.folder / 'config.toml'} sets `notifier` but no `env-file`, the file that holds its credentials"))
def test_sender_in_fails_with_the_configs_reason_where_no_config_names_the_checkout(self):
other = self.home / "code" / "other"
other.mkdir()
subprocess.run(["git", "init", "--quiet", str(other)], check=True, env=isolated_env())
self.assertIsInstance(notify.sender_in(str(other), self.home, notify.BACKENDS), Failure)
def test_sender_in_names_the_settings_to_add_where_the_config_names_no_notifier(self):
failed = notify.sender_in(str(self.checkout), self.home, notify.BACKENDS)
assert isinstance(failed, Failure), failed
self.assertEqual(failed.reason, f"{self.folder / 'config.toml'} sets no `notifier`; set `notifier` to mattermost or slack, and `env-file` to the file that holds that service's keys (mattermost: MATTERMOST_URL, MATTERMOST_TOKEN, MATTERMOST_RECIPIENT; slack: SLACK_TOKEN, SLACK_RECIPIENT)")
class Main(Project):
def run_main(self, argv: list[str], stdin: str = "", sender: object = None) -> tuple[int, str]:
stderr = io.StringIO()
ready = sender or (lambda message: None)
code = main.main(argv, io.StringIO(stdin), lambda: ready, stderr) # type: ignore[arg-type]
return code, stderr.getvalue()
def test_sends_its_argument_or_else_stdin_and_exits_0(self):
for argv, stdin in ((["Which one?"], ""), ([], "Which one?\n")):
with self.subTest(argv=argv):
sent: list[str] = []
self.assertEqual(self.run_main(argv, stdin, lambda message: sent.append(message)), (0, ""))
self.assertEqual(sent, ["Which one?"])
def test_prints_help_for_either_help_flag_whatever_follows_it(self):
for argv in (["-h"], ["--help"], ["--help", "extra"]):
with self.subTest(argv=argv), contextlib.redirect_stdout(io.StringIO()) as printed:
self.assertEqual(self.run_main(argv), (0, ""))
self.assertEqual(printed.getvalue(), main.__doc__.strip() + "\n")
def test_exits_2_on_misuse_naming_it(self):
for argv, stdin, said in (
([], " \n", "notify: the message is empty\n"),
(["a", "b"], "", f"notify: takes one message, or none to read stdin; got 2 arguments\n{main.USAGE}\n"),
):
with self.subTest(argv=argv, stdin=stdin):
self.assertEqual(self.run_main(argv, stdin), (2, said))
def test_exits_2_naming_the_config_fault_where_there_is_no_sender(self):
stderr = io.StringIO()
self.assertEqual(main.main(["hi"], io.StringIO(), lambda: Failure("/h/proj.env does not exist"), stderr), 2) # type: ignore[arg-type]
self.assertEqual(stderr.getvalue(), "notify: /h/proj.env does not exist\n")
def test_exits_1_naming_why_the_send_failed(self):
failed = Failure("POST /api/chat.postMessage refused the message: invalid_auth")
self.assertEqual(self.run_main(["hi"], sender=lambda message: failed), (1, f"notify: {failed.reason}\n"))
def test_the_launcher_prints_help_and_reads_the_env_file_the_projects_config_names(self):
env = {**isolated_env(), "HOME": str(self.home)}
helped = subprocess.run([sys.executable, str(TOOL), "--help"], capture_output=True, text=True, env=env, cwd=self.checkout)
self.assertEqual((helped.returncode, helped.stdout.splitlines()[0]), (0, main.__doc__.strip().splitlines()[0]))
path = self.name_notifier("mattermost")
sent = subprocess.run([sys.executable, str(TOOL), "hi"], capture_output=True, text=True, env=env, cwd=self.checkout)
self.assertEqual((sent.returncode, sent.stderr), (2, f"notify: {path} {MISSING_MATTERMOST}\n"))
if __name__ == "__main__":
unittest.main()
Executable
+9
View File
@@ -0,0 +1,9 @@
#!/usr/bin/env python3
import pathlib
import sys
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from notifier import main, notify
sys.exit(main.main(sys.argv[1:], sys.stdin, lambda: notify.sender_in(None, pathlib.Path.home(), notify.BACKENDS), sys.stderr))
+121 -13
View File
@@ -1,22 +1,22 @@
"""A plan kept as the child issues of one Jira Cloud epic, read over Jira's REST API.
"""A plan kept as the child issues of one Jira Cloud epic, read and filed into over Jira's REST API.
An item is an open child issue. Its ID is the issue's number, so every child must be in the epic's own Jira project: ABC-34 is item 34 of the plan under ABC-12. The summary is the tagline, the description the detail, the earliest Fix Version the release, and an "is blocked by" link a blocker. L, E, I, S, Moves and Exempt sit in one issue property, PROPERTY, which needs no Jira admin to set up; an issue a teammate filed holds none, and reads as an item without scores.
The store only reads so far: every write is a Failure."""
`add` files an item as a new child issue, marked with FILED_BY. edit and finish are a Failure until todo.md's items 382 and 383."""
import base64
import dataclasses
import pathlib
import re
import typing
from adf_codec.convert import adfs_to_markdown, Refused
from plan_store.markdown_edits import bold_cell
from adf_codec.convert import adfs_to_markdown, markdown_to_adf, Refused
from release_plan.todo_table import BLOCKED_BY, EXEMPTIONS, is_exempt, Item, MOVES, parse_ids, parse_moves, parse_scores, SHAPE
from plan_store.markdown_edits import bold_cell, plain, unfit_text
from plan_store.stores import cells, Plan, Written
from project_config.settings import Epic
from release_plan.todo_table import EXEMPTIONS, is_exempt, Item, MOVES, parse_moves, parse_scores, SHAPE
from failure import Failure
from rest_client import json_request
from release_plan.release import parsed, Release, tagged
from plan_store.stores import Plan, Written
from rest_client.env_file import read_env
# One pair of keys for Jira and Confluence: one Atlassian account's API token opens both.
@@ -29,11 +29,21 @@ TIMEOUT = 30
PAGE = 100
# The pages one read asks for at most, so an answer that never names a last page ends the read.
MAX_PAGES = 100
READ_ONLY = "a plan in Jira is only read so far: file, edit and finish its issues in Jira"
READ_ONLY = "a plan in Jira is only read and filed into so far: edit and finish its issues in Jira"
# The key in PROPERTY's value that marks an issue the loop filed, and its value. The loop never edits the summary or description of an issue without it, which a person filed.
FILED_BY = ("Filed by", "loop")
# The issue type of an issue the loop files, which Jira Software's project templates all have; a project without it refuses the issue, saying so.
ISSUE_TYPE = "Task"
# The name of the link type whose inward side reads "is blocked by", as Jira Cloud ships it.
BLOCKS = "Blocks"
SECURITY = "security"
# What a failed create ends with: a request Jira never answered, or answered brokenly, may still have filed the issue.
PERHAPS_FILED = "unless Jira refused the request, the issue may exist: look under {epic} before filing the item again"
# Sends a request with the Authorization header given, the body as JSON where there is one, and returns the JSON answer, or a Failure saying why there is none.
# Sends a request with the Authorization header given, the body as JSON where there is one, and returns the JSON answer, None where the answer has no body, or a Failure saying why there is none.
Http = typing.Callable[[str, str, str, object], object]
ToMarkdown = typing.Callable[[list[dict[str, typing.Any]]], list[str] | Refused | Failure]
ToAdf = typing.Callable[[str], dict[str, typing.Any] | Failure]
def http_json(method: str, url: str, authorization: str, body: object) -> object:
@@ -68,11 +78,12 @@ class Issue:
@dataclasses.dataclass(frozen=True)
class JiraPlan:
"""The plan under epic, read with the credentials env_file holds."""
"""The plan under epic, read and written with the credentials env_file holds."""
epic: Epic
env_file: pathlib.Path
http: Http = http_json
to_markdown: ToMarkdown = adfs_to_markdown
to_adf: ToAdf = markdown_to_adf
@property
def label(self) -> str:
@@ -93,7 +104,56 @@ class JiraPlan:
return next((issue for issue in issues if isinstance(issue, Failure)), None) or plan_of([issue for issue in issues if isinstance(issue, Issue)], self.epic, self.to_markdown)
def add(self, fields: dict[str, str], detail: str) -> Written | Failure:
return Failure(READ_ONLY)
"""Files the item as a child issue, which Jira ranks last in the backlog. No bar applies and the goals file isn't read, since a plan in Jira has no place for a formula or a bar yet (todo.md's item 384).
Jira takes the links after the issue. A link it refuses leaves the issue filed, so the write counts as landed, and a note names each link to make by hand."""
filing = filing_of(fields, detail, self.epic)
if isinstance(filing, Failure):
return filing
authorization = basic_auth(self.env_file)
if isinstance(authorization, Failure):
return authorization
issue_fields = filing.fields
if detail.strip():
description = self.to_adf(detail)
if isinstance(description, Failure):
return Failure(f"cannot convert the item's detail to a Jira description: {description.reason}")
issue_fields = issue_fields | {"description": description}
version = self.fix_version(filing.release, authorization)
if isinstance(version, Failure):
return version
if filing.blockers and (missing := self.missing_blocker(filing.blockers, authorization)):
return missing
created = self.http("POST", f"{self.epic.site}/rest/api/3/issue", authorization, {"fields": issue_fields | {"fixVersions": [{"name": version}]}, "properties": [{"key": PROPERTY, "value": filing.scores}]})
if isinstance(created, Failure):
return Failure(f"cannot file the item under {self.epic.key}: {created.reason}; {PERHAPS_FILED.format(epic=self.epic.key)}")
key = created.get("key") if isinstance(created, dict) else None
if not isinstance(key, str) or not ISSUE_KEY.fullmatch(key) or project_of(key) != project_of(self.epic.key):
return Failure(f"Jira answered the new issue without an issue key in {project_of(self.epic.key)}; {PERHAPS_FILED.format(epic=self.epic.key)}")
notes = []
for blocker in filing.blockers:
# Jira names the two ends by the link type's sides: the inward issue blocks the outward one, which then reads "is blocked by" it.
linked = self.http("POST", f"{self.epic.site}/rest/api/3/issueLink", authorization, {"type": {"name": BLOCKS}, "inwardIssue": {"key": blocker}, "outwardIssue": {"key": key}})
if isinstance(linked, Failure):
notes.append(f"filed {key}, but cannot link it as blocked by {blocker}: {linked.reason}; link it in Jira")
return Written(number(key), tuple(notes))
def fix_version(self, release: str, authorization: str) -> str | Failure:
"""The name of the Jira project's Fix Version for release, which a project may spell with a leading v, as `earliest_release` reads it."""
project = project_of(self.epic.key)
versions = self.http("GET", f"{self.epic.site}/rest/api/3/project/{project}/versions", authorization, None)
if isinstance(versions, Failure):
return Failure(f"cannot read {project}'s Fix Versions: {versions.reason}")
names = {name for version in versions if isinstance(version, dict) and isinstance(name := version.get("name"), str)} if isinstance(versions, list) else set()
return next((name for name in (release, f"v{release}") if name in names), None) or Failure(f"the Jira project {project} has no Fix Version {release} or v{release}; create it in Jira, or file the item under a release it has")
def missing_blocker(self, blockers: tuple[str, ...], authorization: str) -> Failure | None:
"""A Failure naming the first of blockers that is no open child of the epic. `item` reads only an open child as a blocker, so a link to any other issue would be lost on the next read."""
answered = children(self.epic, authorization, self.http)
if isinstance(answered, Failure):
return answered
held = {raw.get("key") for raw in answered if isinstance(raw, dict)}
return next((Failure(f"{self.label} holds no item {number(blocker)} to be blocked by") for blocker in blockers if blocker not in held), None)
def edit(self, id_: int, fields: dict[str, str], detail: str | None) -> Written | Failure:
return Failure(READ_ONLY)
@@ -102,6 +162,54 @@ class JiraPlan:
return Failure(READ_ONLY)
@dataclasses.dataclass(frozen=True)
class Filing:
"""An item checked and ready to file."""
# The new issue's fields, without its description and its Fix Version.
fields: dict[str, typing.Any]
release: str
# PROPERTY's value.
scores: dict[str, typing.Any]
# The key of each issue the item is blocked by.
blockers: tuple[str, ...]
def filing_of(fields: dict[str, str], detail: str, epic: Epic) -> Filing | Failure:
"""The issue to file for an item with these fields under epic, or why a field cannot be filed."""
named = cells(fields)
summary = plain(named.get("Item", "")).strip()
if not summary:
return Failure("the item has no tagline")
if unfit := unfit_text(summary, detail):
return unfit
release = named.get("Release", "")
if parsed(release) is None:
return Failure(f"the item's Release {release!r} is not a version such as 1.2.0")
# Named so the shared messages read "item to file's L": they open with "item" and an ID, which this item has none of yet.
levels = parse_scores("to file", named, SHAPE.score_columns)
if isinstance(levels, Failure):
return levels
moves, exempt = named.get(MOVES, ""), named.get("Exempt", "")
if isinstance(unfit_moves := parse_moves("to file", moves), Failure):
return unfit_moves
if not is_exempt(exempt):
return Failure(f"the item's Exempt {exempt!r} is not empty or one of {', '.join(EXEMPTIONS[1:])}")
blockers = parse_ids(named.get(BLOCKED_BY, ""))
if blockers is None:
return Failure(f"the item's {BLOCKED_BY} {named[BLOCKED_BY]!r} is not empty or IDs separated by \", \"")
project = project_of(epic.key)
issue_fields: dict[str, typing.Any] = {"project": {"key": project}, "parent": {"key": epic.key}, "issuetype": {"name": ISSUE_TYPE}, "summary": summary}
if exempt == SECURITY:
issue_fields["labels"] = [SECURITY]
value = levels | {MOVES: moves, "Exempt": exempt, FILED_BY[0]: FILED_BY[1]}
return Filing(issue_fields, release, value, tuple(f"{project}-{blocker}" for blocker in blockers))
def project_of(key: str) -> str:
"""The key of the Jira project an issue key lies in."""
return key.rpartition("-")[0]
def basic_auth(env_file: pathlib.Path) -> str | Failure:
"""The Authorization header for the email and API token that env_file holds."""
values = read_env(env_file, KEYS, "an API token")
@@ -154,8 +262,8 @@ def issue_of(raw: object) -> Issue | Failure:
def plan_of(issues: list[Issue], epic: Epic, to_markdown: ToMarkdown) -> Plan | Failure:
"""The plan the issues hold, in their order."""
project = epic.key.rpartition("-")[0]
if strangers := [issue.key for issue in issues if issue.key.rpartition("-")[0] != project]:
project = project_of(epic.key)
if strangers := [issue.key for issue in issues if project_of(issue.key) != project]:
return Failure(f"{strangers[0]} is a child of {epic.key} in another Jira project, and an item's ID is its number in {project}; move it into {project} or out of the epic")
ids = {issue.number for issue in issues}
items = [item(issue, project, ids) for issue in issues]
@@ -192,7 +300,7 @@ def item(issue: Issue, project: str, ids: set[int]) -> Item | Failure:
scored = scores(issue.key, issue.scores)
if isinstance(scored, Failure):
return scored
blockers = {number(key) for key in issue.blockers if key.rpartition("-")[0] == project}
blockers = {number(key) for key in issue.blockers if project_of(key) == project}
return Item(issue.number, release, scored[2], bold_cell(issue.summary), scored[0], scored[1], tuple(sorted(blockers & ids)), "")
+18 -11
View File
@@ -1,19 +1,20 @@
"""The one way a tool reads or writes a project's plan: through the store its config names.
The config's `plan` setting names the backend. A path names a markdown file, todo.md. `jira:` and an epic's address name a Jira epic, whose open child issues `jira_epic` reads and nothing writes yet. An agent reads and changes the plan with `todo-item`, which works through the same store.
The config's `plan` setting names the backend. A path names a markdown file, todo.md. `jira:` and an epic's address name a Jira epic, whose open child issues are the plan: `jira_epic` reads them, and files an item as a new child issue. An agent reads and changes the plan with `todo-item`, which works through the same store.
A tool that reads what a past commit held, such as `score-outcomes`, still parses that commit's todo.md itself, with `release_plan.todo_table`: only the markdown backend has commits, and todo.md's items 365, 366 and 368 port those tools to the other backends."""
import dataclasses
import decimal
import pathlib
import typing
from release_plan.todo_table import BLOCKED_BY, Item, item_details, items, MOVES, NoItemsTable, renames
from failure import Failure
from git_cli.git_repo import file_at, git, Git
from record_store.stores import goals_store, store as record_store, RecordStore
from plan_store import markdown_edits
from project_config.settings import ProjectConfig
from release_plan import ranking
from record_store.stores import store as record_store, RecordStore
from release_plan.release import Release
from text_files.file_writes import replace_file
@@ -22,8 +23,10 @@ TAGLINE = "Tagline"
FIELDS = ("Release", BLOCKED_BY, "Exempt", TAGLINE, "L", "E", "I", "S", MOVES)
# What a missing todo.md's reader is told.
# 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)
@@ -44,7 +47,7 @@ class Written:
class PlanStore(typing.Protocol):
"""A project's plan. plan_store.contract holds every backend that writes to the same behaviour; `jira_epic` only reads until todo.md's item 352. A write that fails leaves the plan as it was."""
"""A project's plan. plan_store.contract holds every backend that writes to the same behaviour; `jira_epic` reads and files, and fails an edit or a finish until todo.md's items 382 and 383. A write that fails leaves the plan as it was, except where its Failure says a tracker may hold the item all the same, as when Jira's answer to a new issue is lost."""
@property
def label(self) -> str:
@@ -69,12 +72,14 @@ class PlanStore(typing.Protocol):
@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 at goals, the decision log and the comprehension history."""
"""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: pathlib.Path
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:
@@ -102,7 +107,7 @@ class FilePlan:
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:])
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.
@@ -117,7 +122,7 @@ class FilePlan:
text = markdown_edits.finished(texts[0], id_, self.label)
if isinstance(text, Failure):
return text
ranked = ranking.rank(text, *texts[1:])
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:
@@ -128,13 +133,15 @@ class FilePlan:
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 goals file is a Failure."""
"""What ranking reads: the file, the goals file, the decision log and the comprehension history. The last two are empty when missing; a missing plan, or a goals file that is missing or empty, is a Failure."""
plan = read_text(self.path, MISSING)
if isinstance(plan, Failure):
return plan
goals = read_text(self.goals, "rank_todo.py weighs goals from the file the project's config names as goals-and-audience")
goals = self.goals.read()
if isinstance(goals, Failure):
return goals
if not goals:
return Failure(f"{self.goals.label}: missing or empty; {GOALS_HINT}")
decisions = self.decisions.read()
if isinstance(decisions, Failure):
return decisions
@@ -155,7 +162,7 @@ def store(config: ProjectConfig) -> PlanStore:
def file_plan(config: ProjectConfig, path: pathlib.Path | None = None) -> FilePlan:
"""The markdown file config names as its plan, for a tool that works on the file itself, as ranking does. path stands in for the configured one where given."""
return FilePlan(path or config.paths["plan"], config.tracked("plan"), config.paths["goals-and-audience"], record_store(config, "decisions"), record_store(config, "comprehension-history"))
return FilePlan(path or config.paths["plan"], config.tracked("plan"), goals_store(config), record_store(config, "decisions"), record_store(config, "comprehension-history"), config.readability_floor)
def held_at(revision: str, plan: PlanStore, cwd: str, run: Git = git) -> Plan | Failure:
+159 -4
View File
@@ -8,9 +8,10 @@ import unittest.mock
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from project_config.settings import Epic
from release_plan.todo_table import EXEMPTIONS
from failure import Failure
from plan_store import jira_epic
from plan_store.stores import Plan
from plan_store.stores import Plan, Written
from adf_codec.convert import Refused
from release_plan.release import release_of
@@ -209,17 +210,171 @@ class JiraPlan(unittest.TestCase):
self.pages = [{"issues": [issue("OTHER-5")]}]
self.assertNotIn("s3cret", self.store().read().reason) # type: ignore[union-attr]
def test_every_write_fails_since_the_store_only_reads(self):
def test_edit_and_finish_fail_since_the_store_only_files(self):
store = self.store()
for written in (store.add({}, ""), store.edit(34, {"L": "2"}, None), store.finish(34)):
for written in (store.edit(34, {"L": "2"}, None), store.finish(34)):
with self.subTest(written=written):
self.assertEqual(written, Failure("a plan in Jira is only read so far: file, edit and finish its issues in Jira"))
self.assertEqual(written, Failure("a plan in Jira is only read and filed into so far: edit and finish its issues in Jira"))
self.assertEqual(self.calls + self.epic_calls, [])
def test_names_itself_by_the_configs_spelling_and_no_commit_holds_it(self):
self.assertEqual((self.store().label, self.store().tracked), ("jira:https://acme.atlassian.net/browse/ABC-12", None))
ISSUES = "https://acme.atlassian.net/rest/api/3/issue"
LINKS = "https://acme.atlassian.net/rest/api/3/issueLink"
VERSIONS = "https://acme.atlassian.net/rest/api/3/project/ABC/versions"
PERHAPS_FILED = "unless Jira refused the request, the issue may exist: look under ABC-12 before filing the item again"
FIELDS = {"Release": "0.1.0", "Tagline": "Count the runs.", "L": "1", "E": "2", "I": "3", "S": "1", "Moves": "1 by 9"}
PROPERTY = {"L": 1, "E": 2, "I": 3, "S": 1, "Moves": "1 by 9", "Exempt": "", "Filed by": "loop"}
class Filing(unittest.TestCase):
def setUp(self) -> None:
self.env = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory())) / "acme.env"
self.env.write_text("ATLASSIAN_EMAIL=me@example.com\nATLASSIAN_API_TOKEN=s3cret\n")
self.env.chmod(0o600)
self.calls: list[tuple[str, str, object]] = []
self.open: list[dict[str, object]] = []
self.created: object = {"id": "10040", "key": "ABC-40"}
self.linked: object = None
self.versions: object = [{"name": "0.1.0"}, {"name": "v0.2.0"}, "odd", {"name": ["0.1.0"]}, {"name": {"en": "0.1.0"}}]
def http(self, method: str, url: str, authorization: str, body: object) -> object:
"""Stands in for Jira: answers the epic, self.versions for the project's Fix Versions, self.open to the search, self.created to a new issue and self.linked to a new link."""
self.calls.append((method, url, body))
assert authorization == AUTHORIZATION
return {SEARCH: {"issues": self.open}, ISSUES: self.created, LINKS: self.linked, VERSIONS: self.versions}.get(url, {"key": "ABC-12"})
def to_adf(self, markdown: str) -> dict[str, object] | Failure:
return adf(markdown)
def add(self, fields: dict[str, str] = FIELDS, detail: str = ""):
return jira_epic.JiraPlan(EPIC, self.env, self.http, text_of, self.to_adf).add(fields, detail)
def sent(self, url: str) -> list[object]:
return [body for _, sent_to, body in self.calls if sent_to == url]
def test_files_the_item_as_a_task_under_the_epic_marked_as_the_loops(self):
self.assertEqual(self.add(), Written(40))
self.assertEqual(self.calls, [("GET", VERSIONS, None), ("POST", ISSUES, {
"fields": {"project": {"key": "ABC"}, "parent": {"key": "ABC-12"}, "issuetype": {"name": "Task"}, "summary": "Count the runs.", "fixVersions": [{"name": "0.1.0"}]},
"properties": [{"key": "plan-item", "value": PROPERTY}],
})])
def test_a_bold_tagline_is_filed_plain(self):
self.add(FIELDS | {"Tagline": "**Count the runs.**"})
self.assertEqual(self.sent(ISSUES)[0]["fields"]["summary"], "Count the runs.") # type: ignore[index]
def test_the_detail_is_the_description_as_adf(self):
self.add(detail="Why it counts.")
self.assertEqual(self.sent(ISSUES)[0]["fields"]["description"], adf("Why it counts.")) # type: ignore[index]
def test_a_security_finding_is_labelled_security(self):
self.add(FIELDS | {"Exempt": "security"})
sent, = self.sent(ISSUES)
self.assertEqual((sent["fields"]["labels"], sent["properties"][0]["value"]["Exempt"]), (["security"], "security")) # type: ignore[index]
def test_no_other_item_is_labelled(self):
self.add(FIELDS | {"Exempt": "owner"})
self.assertNotIn("labels", self.sent(ISSUES)[0]["fields"]) # type: ignore[index]
def test_links_the_issue_as_blocked_by_each_blocker_once_filed(self):
self.open = [issue("ABC-34"), issue("ABC-35")]
self.assertEqual(self.add(FIELDS | {"Blocked by": "34, 35"}), Written(40))
self.assertEqual([(method, url) for method, url, _ in self.calls][-3:], [("POST", ISSUES), ("POST", LINKS), ("POST", LINKS)])
self.assertEqual(self.sent(LINKS), [{"type": {"name": "Blocks"}, "inwardIssue": {"key": f"ABC-{blocker}"}, "outwardIssue": {"key": "ABC-40"}} for blocker in (34, 35)])
def test_a_blocker_that_is_no_open_child_fails_before_anything_is_filed(self):
self.open = [issue("ABC-34")]
self.assertEqual(self.add(FIELDS | {"Blocked by": "34, 36"}), Failure("jira:https://acme.atlassian.net/browse/ABC-12 holds no item 36 to be blocked by"))
self.assertEqual(self.sent(ISSUES), [])
def test_a_field_out_of_format_fails_before_any_request(self):
cases = ({"L": "9"}, {"Release": "soon"}, {"Release": ""}, {"Moves": "much"}, {"Exempt": "whim"}, {"Blocked by": "ABC-34"}, {"Tagline": "Count\nthe runs."}, {"Tagline": " "})
for change in cases:
with self.subTest(change=change):
self.assertIsInstance(self.add(FIELDS | change), Failure)
self.assertEqual(self.calls, [])
def test_each_field_out_of_format_fails_saying_how(self):
cases = (
({"Tagline": "** **"}, "the item has no tagline"),
({"L": "9"}, "item to file's L '9' is not a whole number from 1 to 4"),
({"Exempt": "whim"}, f"the item's Exempt 'whim' is not empty or one of {', '.join(EXEMPTIONS[1:])}"),
({"Blocked by": "ABC-34"}, "the item's Blocked by 'ABC-34' is not empty or IDs separated by \", \""),
)
for change, reason in cases:
with self.subTest(change=change):
self.assertEqual(self.add(FIELDS | change), Failure(reason))
self.assertEqual(self.add({name: value for name, value in FIELDS.items() if name != "Tagline"}), Failure("the item has no tagline"))
def test_an_item_without_moves_files_with_none(self):
self.assertEqual(self.add({name: value for name, value in FIELDS.items() if name != "Moves"}), Written(40))
self.assertEqual(self.sent(ISSUES)[0]["properties"][0]["value"]["Moves"], "") # type: ignore[index]
def test_a_field_the_plan_does_not_have_is_a_programming_error(self):
with self.assertRaises(ValueError):
self.add(FIELDS | {"Colour": "red"})
def test_an_item_without_a_release_fails_naming_the_field(self):
self.assertEqual(self.add({name: value for name, value in FIELDS.items() if name != "Release"}), Failure("the item's Release '' is not a version such as 1.2.0"))
def test_a_detail_that_does_not_convert_fails_before_any_request(self):
self.to_adf = lambda markdown: Failure("docker is not running") # type: ignore[method-assign]
self.assertEqual(self.add(detail="Why."), Failure("cannot convert the item's detail to a Jira description: docker is not running"))
self.assertEqual(self.calls, [])
def test_an_item_jira_refuses_fails_with_jiras_reason(self):
self.created = Failure("POST /rest/api/3/issue answered 400: Version name '0.1.0' is not valid")
self.assertEqual(self.add(), Failure(f"cannot file the item under ABC-12: POST /rest/api/3/issue answered 400: Version name '0.1.0' is not valid; {PERHAPS_FILED}"))
def test_an_answer_that_names_no_issue_of_the_epics_project_fails(self):
for answer in ({}, {"key": 7}, {"key": "OTHER-5"}, ["ABC-40"]):
with self.subTest(answer=answer):
self.created = answer
self.assertEqual(self.add(), Failure(f"Jira answered the new issue without an issue key in ABC; {PERHAPS_FILED}"))
def test_a_link_jira_refuses_leaves_the_item_filed_with_a_note_and_the_other_links_made(self):
refusal = "POST /rest/api/3/issueLink answered 404: No issue link type with name 'Blocks' found."
self.open, self.linked = [issue("ABC-34"), issue("ABC-35")], Failure(refusal)
self.assertEqual(self.add(FIELDS | {"Blocked by": "34, 35"}), Written(40, tuple(f"filed ABC-40, but cannot link it as blocked by ABC-{blocker}: {refusal}; link it in Jira" for blocker in (34, 35))))
self.assertEqual(len(self.sent(LINKS)), 2)
def test_files_under_the_fix_version_as_the_project_spells_it(self):
self.assertEqual(self.add(FIELDS | {"Release": "0.2.0"}), Written(40))
self.assertEqual(self.sent(ISSUES)[0]["fields"]["fixVersions"], [{"name": "v0.2.0"}]) # type: ignore[index]
def test_a_release_the_project_has_no_fix_version_for_fails_before_anything_is_filed(self):
for versions in ([{"name": "0.1.0"}], {"name": "0.3.0"}, [], 7):
with self.subTest(versions=versions):
self.versions = versions
self.assertEqual(self.add(FIELDS | {"Release": "0.3.0"}), Failure("the Jira project ABC has no Fix Version 0.3.0 or v0.3.0; create it in Jira, or file the item under a release it has"))
self.assertEqual(self.sent(ISSUES), [])
def test_fix_versions_that_cannot_be_read_fail_before_anything_is_filed(self):
self.versions = Failure("GET /rest/api/3/project/ABC/versions answered 403: Forbidden")
self.assertEqual(self.add(), Failure("cannot read ABC's Fix Versions: GET /rest/api/3/project/ABC/versions answered 403: Forbidden"))
self.assertEqual(self.sent(ISSUES), [])
def test_what_it_files_reads_back_as_the_item(self):
self.add(FIELDS | {"Exempt": "owner"}, "Why it counts.")
sent, = self.sent(ISSUES)
raw = {"key": "ABC-40", "fields": sent["fields"] | {"issuelinks": []}, "properties": {entry["key"]: entry["value"] for entry in sent["properties"]}} # type: ignore[index, operator, union-attr]
filed = jira_epic.issue_of(raw)
assert isinstance(filed, jira_epic.Issue), filed
plan = jira_epic.plan_of([filed], EPIC, lambda documents: [text_of(document) for document in documents])
assert isinstance(plan, Plan), plan
item, = plan.items
self.assertEqual((item.id, item.release, item.exempt, item.tagline, item.moves, item.detail), (40, release_of("0.1.0"), "owner", "**Count the runs.**", (("1", 9),), "Why it counts."))
self.assertEqual({name: item.scores[name] for name in "LEIS"}, {"L": 1, "E": 2, "I": 3, "S": 1})
def test_a_missing_env_file_fails_before_any_request(self):
self.env.unlink()
self.assertIsInstance(self.add(), Failure)
self.assertEqual(self.calls, [])
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:
+21 -4
View File
@@ -1,4 +1,5 @@
import dataclasses
import decimal
import os
import pathlib
import sys
@@ -7,14 +8,15 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from project_config.settings import Epic, ProjectConfig, SETTINGS
from project_config.settings import DEFAULT_FLOOR, Epic, ProjectConfig, SETTINGS
from failure import Failure
from plan_store.contract import FIRST, PlanStoreContract, SECOND
from record_store.stores import FileStore
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
from release_plan.test_ranking import README, SCORED, VOID
from release_plan.release import release_of
from plan_store import stores
@@ -33,7 +35,7 @@ class FilePlanContract(PlanStoreContract, unittest.TestCase):
def new_store(self) -> stores.FilePlan:
(self.folder / "todo.md").write_text(EMPTY)
(self.folder / "README.md").write_text(README)
return stores.FilePlan(self.folder / "todo.md", "todo.md", self.folder / "README.md", MemoryStore(), MemoryStore())
return stores.FilePlan(self.folder / "todo.md", "todo.md", FileStore(self.folder / "README.md", None), MemoryStore(), MemoryStore(), DEFAULT_FLOOR)
class FilePlan(FilePlanContract):
@@ -148,6 +150,18 @@ class FilePlan(FilePlanContract):
self.assertEqual(store.add(FIRST, ""), Failure("no history"))
def test_ranks_every_write_with_its_floor(self):
# At an overall of 6.50 code health weighs 4 times under the default floor of 7.0, and once at a floor of 6.0.
def health_row(floor):
store = dataclasses.replace(self.new_store(), history=MemoryStore(SCORED.format(overall="6.50")), floor=decimal.Decimal(floor))
(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.assertIn(row[0], (self.folder / "todo.md").read_text())
return row[0]
self.assertNotEqual(health_row("6.0"), health_row("7.0"))
class HeldAt(unittest.TestCase):
def test_reads_the_revisions_file_where_commits_hold_the_plan(self):
shown = []
@@ -188,6 +202,9 @@ class Store(unittest.TestCase):
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"))
def test_the_markdown_file_ranks_with_the_configs_floor(self):
self.assertEqual(stores.file_plan(self.config(readability_floor=decimal.Decimal("6.5")), pathlib.Path("/checkout/todo.md")).floor, decimal.Decimal("6.5"))
def test_an_epic_picks_jira_with_the_env_files_credentials(self):
epic = Epic("https://acme.atlassian.net", "ABC-12")
picked = stores.store(self.config(epic=epic, env_file=pathlib.Path("/secrets/acme.env")))
+50 -13
View File
@@ -26,16 +26,42 @@ starts with / or ~/. In a worktree, a "checkout:" path is the worktree's own fil
Jira's backlog order, and `project-config plan` prints the setting as the config spells it. Such a
config must set `env-file`, and that file must hold ATLASSIAN_EMAIL and ATLASSIAN_API_TOKEN.
`goals-and-audience` may name a Jira Cloud epic the same way, where `plan` names one too. The
epic's description is then the goals file, with ## Goals and ## Audience as headings, and
`project-config goals-and-audience` prints the setting as the config spells it. The description is
only read: edit it in Jira.
`env-file` is an optional setting: the file of KEY=value credentials the project's tools read,
a path that starts with / or ~/ and lies outside the checkout and the config's folder, such as
"~/.claude-projects/acme-billing.env". Where it is left out, the project has no credentials file, and
a tool that needs one fails naming the setting. It is printed with the others only where it is set.
`touch-predictions` is an optional setting, a path spelt as `changelog`'s is: the record where
`touch-predictions record` appends what each chunk was predicted to touch beside what it touched. Left
out, the project keeps no such record. It is printed with the others only where it is set.
`notifier` is an optional setting, "mattermost" or "slack": the service that sends loop-claude's DMs and
`notify`'s messages to the human. Setting it requires `env-file`, which holds that service's keys;
`notify --help` names them. Left out, the project gets no DMs. It is printed with the others only where it
is set.
`wait-for-approval` is an optional setting, true or false: whether `chunk-pr merge` waits for a human's
approval of the pull request, as its branch protection requires on GitHub, before it merges. Left out, it is
false. `project-config wait-for-approval` prints true or false; the full listing shows the setting only where
it is true.
`tooling-on-host` is an optional setting, true or false: whether the loop may run the project's language
runtime, package manager, tests and task runner directly on the host, for a project with no container
setup. Left out, it is false, and they run through the project's container setup.
`readability-floor` is an optional setting, a number from 1 to 10: the comprehension score a project
aims for. While the panel's overall score is under it, code health weighs 4 times as much in the plan's
ranking, and a scoring run with a mean under it asks for a floor item. A legacy project, whose code
scores low, may lower it. Left out, it is 7.0.
`project-config tooling-on-host` and `project-config readability-floor` print their values; the full
listing shows each only where the config changes it from what it is when left out.
Four optional settings say how the project writes, for a project whose owners don't write as
~/.claude/CLAUDE.md does:
@@ -56,14 +82,26 @@ a title for its summary tries `commit-title`, then `pull-request-title`, then ta
`project-config <setting>` prints each one's value, and the full listing shows it only where the
config changes it from what it is when left out.
In a Jira plan an item's ID is its issue's number. To name a chunk by its issue key, write the
Jira project's key before {id}, as here for the key ABC:
branch = "ABC-{id}"
commit-title = "ABC-{id} - {summary}"
pull-request-title = "ABC-{id} - {summary}"
The chunk for the issue ABC-123 is then on the branch ABC-123, in the worktree <checkout>-ABC-123,
and its commits and pull request are titled "ABC-123 - …".
Exit 1, naming each fault on stderr, where no config names the checkout, or its config leaves out a
setting, names an unknown one, misspells a path, a language or a template, or sets `wait-for-approval` to anything but true or
false, and where `env-file` is asked for and not set. No path setting has a default.
setting, names an unknown one, misspells a path, a language or a template, sets `wait-for-approval` or
`tooling-on-host` to anything but true or false, sets `notifier` to anything but mattermost or slack or
without `env-file`, or sets `readability-floor` to anything but a number
from 1 to 10, and where `env-file`, `notifier` or `touch-predictions` is asked for and not set. No path setting has a default.
"""
import pathlib
import sys
from project_config.settings import CONFIG, ENV_FILE, load, OPTIONAL, ProjectConfig, SETTINGS, Unnamed, WAIT_FOR_APPROVAL
from project_config.settings import CONFIG, DEFAULT_FLOOR, ENV_FILE, load, NOTIFIER, OPTIONAL, ProjectConfig, READABILITY_FLOOR, SETTINGS, TOOLING_ON_HOST, Unnamed, WAIT_FOR_APPROVAL
from failure import Failure
from git_cli.git_repo import git, Git
from project_config import templates
@@ -80,18 +118,22 @@ def main(argv: list[str]) -> int:
if isinstance(config, Failure):
print(config.reason, file=sys.stderr)
return 1
if argv == [WAIT_FOR_APPROVAL]:
print("true" if config.wait_for_approval else "false")
switches = {WAIT_FOR_APPROVAL: config.wait_for_approval, TOOLING_ON_HOST: config.tooling_on_host}
if argv and argv[0] in switches:
print("true" if switches[argv[0]] else "false")
return 0
if argv == [READABILITY_FLOOR]:
print(config.readability_floor)
return 0
if argv and argv[0] in config.texts:
print(config.texts[argv[0]])
return 0
paths = {**config.places, **({ENV_FILE: str(config.env_file)} if config.env_file else {})}
paths = {**config.places, **({ENV_FILE: str(config.env_file)} if config.env_file else {}), **({NOTIFIER: config.notifier} if config.notifier else {})}
if argv and argv[0] not in paths:
print(f"{config.folder / CONFIG} sets no `{ENV_FILE}`", file=sys.stderr)
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"{WAIT_FOR_APPROVAL}: true"] if config.wait_for_approval else []) + [f"{name}: {text}" for name, text in config.texts.items() if text != defaults[name]]
listed = [f"{name}: {path}" for name, path in paths.items()] + [f"{name}: true" for name, on in switches.items() if on] + ([f"{READABILITY_FLOOR}: {config.readability_floor}"] if config.readability_floor != DEFAULT_FLOOR else []) + [f"{name}: {text}" for name, text in config.texts.items() if text != defaults[name]]
print(paths[argv[0]] if argv else "\n".join(listed))
return 0
@@ -119,8 +161,3 @@ def project() -> ProjectConfig | Failure:
"""The config of the project whose checkout holds the current directory, under the user's home."""
return located(None, pathlib.Path.home())
def goals_file(directory: str, home: pathlib.Path) -> pathlib.Path | Failure:
"""The file holding the premises, `## Goals` and `## Audience`, of the project whose checkout holds directory, as its config under home names it."""
config = located(directory, home)
return config if isinstance(config, Failure) else config.paths["goals-and-audience"]
+60 -16
View File
@@ -2,9 +2,12 @@
No path setting has a default, so that a client's project never runs on another project's files: a missing config or setting is a Failure that names it."""
import dataclasses
import decimal
import math
import pathlib
import re
import tomllib
import typing
from failure import Failure
from project_config import templates
@@ -17,17 +20,32 @@ SETTINGS = ("plan", "working-rules", "decisions", "score-anchors", "comprehensio
SPELLING = '"checkout:<path>" for a path in the checkout, "folder:<path>" for one in the config\'s folder, or a path that starts with / or ~/'
# A path setting a project may leave out: the file of KEY=value credentials its tools read. It has no default either: a project without it asks for no credentials, and never reads another project's.
ENV_FILE = "env-file"
# The optional boolean setting: whether `chunk-pr merge` waits for a human's approval of the pull request. False where left out.
# An optional setting: the service that sends the loop's DMs to the human, one of NOTIFIERS. A project that names none gets no DMs, so a client's env file of Jira credentials is never read for a chat token.
NOTIFIER = "notifier"
Notifier = typing.Literal["mattermost", "slack"]
NOTIFIERS: tuple[Notifier, ...] = typing.get_args(Notifier)
# An optional boolean setting: whether `chunk-pr merge` waits for a human's approval of the pull request. False where left out.
WAIT_FOR_APPROVAL = "wait-for-approval"
# An optional boolean setting: whether the loop may run the project's language runtime, package manager, tests and task runner on the host, for a project with no container setup. False where left out.
TOOLING_ON_HOST = "tooling-on-host"
# An optional number setting: the comprehension score under which code health is very important. A legacy project, whose code scores low, may lower it.
READABILITY_FLOOR = "readability-floor"
# The floor where the config leaves it out, which every dimension and the overall should reach; docs/decisions.md → "comprehension floor" says it doesn't block anything.
DEFAULT_FLOOR = decimal.Decimal("7.0")
# The optional text settings. `language` is the language the project's prose is written in, by its English name. The others are templates, as `templates` says.
LANGUAGE = "language"
COMMIT_TITLE = "commit-title"
PULL_REQUEST_TITLE = "pull-request-title"
BRANCH = "branch"
OPTIONAL = (BRANCH, COMMIT_TITLE, ENV_FILE, LANGUAGE, PULL_REQUEST_TITLE, WAIT_FOR_APPROVAL)
# What opens a `plan` setting that names a Jira Cloud epic in place of a path: `jira:`, then the epic's address as the browser shows it. `plan` is the one setting that may name something other than a path.
# An optional path setting: main's help says what it places.
TOUCH_PREDICTIONS = "touch-predictions"
OPTIONAL = (BRANCH, COMMIT_TITLE, ENV_FILE, LANGUAGE, NOTIFIER, PULL_REQUEST_TITLE, READABILITY_FLOOR, TOOLING_ON_HOST, TOUCH_PREDICTIONS, WAIT_FOR_APPROVAL)
# 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_SPELLING = '"jira:https://<site>/browse/<epic\'s key>" for a plan kept as a Jira Cloud epic\'s child issues'
EPIC_SPELLINGS = {
"goals-and-audience": '"jira:https://<site>/browse/<epic\'s key>" for goals and audience kept in a Jira Cloud epic\'s description',
"plan": '"jira:https://<site>/browse/<epic\'s key>" for a plan kept as a Jira Cloud epic\'s child issues',
}
OUTSIDE = "a path that starts with / or ~/ and lies outside the checkout and the config's folder, so that no git remote receives the credentials"
@@ -44,13 +62,13 @@ class Epic:
@property
def spelling(self) -> str:
"""The epic as a config's `plan` setting spells it."""
"""The epic as a config spells it."""
return f"{JIRA}{self.site}/browse/{self.key}"
@dataclasses.dataclass(frozen=True)
class ProjectConfig:
"""folder is `~/.claude-projects/<key>`, top is the worktree that asked, and paths holds each of SETTINGS as an absolute path, except `plan` where the plan is kept in Jira."""
"""folder is `~/.claude-projects/<key>`, top is the worktree that asked, and paths holds each of SETTINGS as an absolute path, except `plan` and `goals-and-audience` where they are kept in Jira."""
key: str
folder: pathlib.Path
top: pathlib.Path
@@ -58,12 +76,18 @@ class ProjectConfig:
# The config's `env-file`, or None where it sets none.
env_file: pathlib.Path | None = None
wait_for_approval: bool = False
tooling_on_host: bool = False
readability_floor: decimal.Decimal = DEFAULT_FLOOR
language: str = "English"
commit_title: str = templates.TITLE
pull_request_title: str = templates.TITLE
branch: str = templates.BRANCH
# The epic whose child issues are the plan, where the config's `plan` names one.
epic: Epic | None = None
# The epic whose description holds the goals and audience, where the config's `goals-and-audience` names one.
goals_epic: Epic | None = None
# The config's `notifier`, or None where it names none.
notifier: Notifier | None = None
@property
def plan_file(self) -> pathlib.Path | None:
@@ -77,8 +101,9 @@ class ProjectConfig:
@property
def places(self) -> dict[str, str]:
"""Where each of SETTINGS is kept, in SETTINGS' order: a path, or the epic as the config spells it."""
return {name: self.plan_label if name == "plan" else str(self.paths[name]) for name in SETTINGS if name == "plan" or name in self.paths}
"""Where each of SETTINGS is kept, in SETTINGS' order, then TOUCH_PREDICTIONS where the config sets it: a path, or the epic as the config spells it."""
epics = {"plan": self.epic, "goals-and-audience": self.goals_epic}
return {name: epic.spelling if (epic := epics.get(name)) else str(self.paths[name]) for name in (*SETTINGS, TOUCH_PREDICTIONS) if epics.get(name) or name in self.paths}
@property
def texts(self) -> dict[str, str]:
@@ -115,33 +140,52 @@ def load(top: pathlib.Path, main: pathlib.Path, home: pathlib.Path) -> ProjectCo
if len(named) > 1:
return Failure(f"{' and '.join(str(file) for file, _ in named)} each name the checkout {main}; only one config may")
file, values = named[0]
paths = {name: placed(values[name], top, file.parent, home) for name in SETTINGS if name in values}
epic = epic_of(values.get("plan"))
paths = {name: placed(values[name], top, file.parent, home) for name in (*SETTINGS, TOUCH_PREDICTIONS) if name in values}
epics = {name: epic_of(values.get(name)) for name in EPIC_SPELLINGS}
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
checks = {LANGUAGE: language_fault, COMMIT_TITLE: templates.title_fault, PULL_REQUEST_TITLE: templates.title_fault, BRANCH: templates.branch_fault}
faults = [
*(f"`{name}` is missing" for name in SETTINGS if name not in values),
*(f"`{name}` is not a setting" for name in values if name not in (*SETTINGS, *OPTIONAL)),
*(f"`{name}` is {values[name]!r}, not {SPELLING}" for name, path in paths.items() if path is None and name != "plan"),
*([f"`plan` is {values['plan']!r}, not {SPELLING}, or {EPIC_SPELLING}"] if "plan" in values and paths["plan"] is None and epic is None else []),
*([f"`plan` names a Jira epic, so `{ENV_FILE}` must name the file that holds its credentials"] if epic and ENV_FILE not in values else []),
*(f"`{name}` is {values[name]!r}, not {SPELLING}" for name, path in paths.items() if path is None and name not in EPIC_SPELLINGS),
*(f"`{name}` is {values[name]!r}, not {SPELLING}, 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}` names a Jira epic, so `{ENV_FILE}` must name the file that holds its credentials" for name, epic in epics.items() if epic and ENV_FILE not in values),
# rule-hook ranks a plan kept as a file before tool calls, inside the hook's time limit, which a read from Jira mustn't hold up.
*(["`goals-and-audience` names a Jira epic, so `plan` must name one too"] if epics["goals-and-audience"] and not epics["plan"] else []),
*([f"`{ENV_FILE}` is {values[ENV_FILE]!r}, not {OUTSIDE}"] if misplaced else []),
*([f"`{WAIT_FOR_APPROVAL}` is {waits!r}, not true or false"] if not isinstance(waits, bool) 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 {value!r}, not true or false" for name, value in ((WAIT_FOR_APPROVAL, waits), (TOOLING_ON_HOST, on_host)) if not isinstance(value, bool)),
*([f"`{READABILITY_FLOOR}` is {values[READABILITY_FLOOR]!r}, not a number from 1 to 10; write a bare number, such as `{READABILITY_FLOOR} = 7.0`"] if floor is None else []),
*(f"`{name}` is {values[name]!r}, {fault}" for name, check in checks.items() if name in values and (fault := check(values[name]))),
]
if faults:
return Failure(f"{file}: {'; '.join(faults)}. The settings are {', '.join(SETTINGS)}, and optionally {', '.join(OPTIONAL[:-1])} and {OPTIONAL[-1]}.")
return ProjectConfig(file.parent.name, file.parent, top, {name: path for name, path in paths.items() if path}, env_file, waits is True, **{name.replace("-", "_"): str(values[name]) for name in checks if name in values}, epic=epic)
# faults names a floor the config misspells.
assert floor is not None
return ProjectConfig(file.parent.name, file.parent, top, {name: path for name, path in paths.items() if path}, env_file, waits is True, on_host is True, floor, **{name.replace("-", "_"): str(values[name]) for name in checks if name in values}, epic=epics["plan"], goals_epic=epics["goals-and-audience"], notifier=notifier)
def epic_of(value: object) -> Epic | None:
"""The epic a `plan` setting's value spells; None where it spells none. Only https, so the credentials are never sent in the clear."""
"""The epic a setting's value spells; None where it spells none. Only https, so the credentials are never sent in the clear."""
spelt = isinstance(value, str) and re.fullmatch(rf"{JIRA}(https://[A-Za-z0-9.-]+(?::[0-9]+)?)/browse/([A-Z][A-Z0-9_]*-[0-9]+)", value)
return Epic(spelt.group(1), spelt.group(2)) if spelt else None
def floor_of(value: object) -> decimal.Decimal | None:
"""The floor value spells, an integer or a float from 1 to 10; None where it spells none. Not a string, nor a boolean, which Python counts as an integer, nor TOML's nan or inf."""
# An integer too large for a float makes math.isfinite raise, so only a float is checked.
if isinstance(value, bool) or not isinstance(value, int | float) or (isinstance(value, float) and not math.isfinite(value)):
return None
floor = decimal.Decimal(str(value))
return floor if 1 <= floor <= 10 else None
def language_fault(value: object) -> str | None:
"""Why value names no language; None where it does. Only words, since the name is quoted to every worker and reviewer as an instruction."""
named = isinstance(value, str) and re.fullmatch(r"[^\W\d_]+(?:[ -][^\W\d_]+)*", value)
+129 -2
View File
@@ -1,3 +1,4 @@
import decimal
import os
import pathlib
import subprocess
@@ -8,7 +9,7 @@ import unittest.mock
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from project_config.settings import env_files, Epic, held, load, OUTSIDE, ProjectConfig, SETTINGS, Unnamed
from project_config.settings import env_files, Epic, held, load, NOTIFIERS, OUTSIDE, ProjectConfig, SETTINGS, Unnamed
from failure import Failure
from test_env import isolated_env
from project_config.main import title_templates
@@ -116,6 +117,42 @@ class LoadTest(ConfigCase):
for config in (self.home / ".claude-projects").glob("*/config.toml"):
config.unlink()
def test_goals_and_audience_spelt_as_a_jira_epic_is_no_path(self) -> None:
self.write("acme", JIRA_CLIENT.replace("folder:goals.md", "jira:https://acme.atlassian.net/browse/ABC-7"))
found = load(self.checkout, self.checkout, self.home)
assert isinstance(found, ProjectConfig), found
self.assertEqual(found.goals_epic, Epic("https://acme.atlassian.net", "ABC-7"))
self.assertEqual(found.places["goals-and-audience"], "jira:https://acme.atlassian.net/browse/ABC-7")
self.assertEqual(tuple(found.places), SETTINGS)
self.assertNotIn("goals-and-audience", found.paths)
def test_goals_and_the_plan_may_name_the_same_epic(self) -> None:
self.write("acme", JIRA_CLIENT.replace("folder:goals.md", JIRA_PLAN))
found = load(self.checkout, self.checkout, self.home)
assert isinstance(found, ProjectConfig), found
self.assertEqual(found.goals_epic, found.epic)
def test_goals_in_jira_need_the_plan_in_jira(self) -> None:
self.write("acme", CLIENT.replace("folder:goals.md", JIRA_PLAN) + 'env-file = "~/acme.env"\n')
self.assertIn("`goals-and-audience` names a Jira epic, so `plan` must name one too", self.failure())
def test_goals_kept_as_a_file_have_no_epic(self) -> None:
folder = self.write("acme", CLIENT)
found = load(self.checkout, self.checkout, self.home)
assert isinstance(found, ProjectConfig), found
self.assertEqual((found.goals_epic, found.places["goals-and-audience"]), (None, str(folder / "goals.md")))
def test_goals_in_jira_need_an_env_file(self) -> None:
self.write("acme", CLIENT.replace("folder:goals.md", JIRA_PLAN))
self.assertIn("`goals-and-audience` names a Jira epic, so `env-file` must name the file that holds its credentials", self.failure())
def test_goals_that_spell_no_path_and_no_epic_name_both_spellings(self) -> None:
self.write("acme", CLIENT.replace("folder:goals.md", "jira:http://acme.atlassian.net/browse/ABC-12") + 'env-file = "~/acme.env"\n')
reason = self.failure()
self.assertIn("`goals-and-audience` is 'jira:http://acme.atlassian.net/browse/ABC-12', not ", reason)
self.assertIn("jira:https://<site>/browse/<epic's key>", reason)
self.assertIn("description", reason)
def test_a_worktree_finds_the_main_checkouts_config_and_reads_its_own_files(self) -> None:
self.write("acme", CLIENT)
worktree = self.home / "code" / "acme-billing-item-3"
@@ -196,6 +233,24 @@ class LoadTest(ConfigCase):
assert isinstance(named, ProjectConfig), named
self.assertEqual(named.env_file, self.home / ".claude-projects" / "acme.env")
def test_the_notifier_is_optional_and_names_mattermost_or_slack_beside_an_env_file(self) -> None:
self.write("acme", CLIENT)
left_out = load(self.checkout, self.checkout, self.home)
assert isinstance(left_out, ProjectConfig), left_out
self.assertIsNone(left_out.notifier, "a project that names none has asked for no notices")
for index, name in enumerate(NOTIFIERS):
with self.subTest(name):
self.write(f"acme-{index}", CLIENT.replace("acme-billing", f"acme-{index}") + f'env-file = "~/acme.env"\nnotifier = "{name}"\n')
named = load(self.home / "code" / f"acme-{index}", self.home / "code" / f"acme-{index}", self.home)
assert isinstance(named, ProjectConfig), named
self.assertEqual(named.notifier, name)
def test_a_notifier_that_is_unknown_or_has_no_env_file_fails_naming_it(self) -> None:
self.write("acme", CLIENT + 'env-file = "~/acme.env"\nnotifier = "teams"\n')
self.assertIn("`notifier` is 'teams', not mattermost or slack", self.failure())
(self.home / ".claude-projects" / "acme" / "config.toml").write_text(CLIENT + 'notifier = "slack"\n')
self.assertIn("`notifier` names a notifier, so `env-file` must name the file that holds its credentials", self.failure())
def test_an_env_file_in_the_checkout_or_the_configs_folder_or_spelt_loosely_fails_naming_it(self) -> None:
cases = {
"a checkout: path": lambda home: '"checkout:.env"',
@@ -224,6 +279,20 @@ class LoadTest(ConfigCase):
assert isinstance(found, Failure), found
self.assertIn("`env-file`", found.reason)
def test_touch_predictions_is_an_optional_path_listed_after_the_others_only_where_set(self) -> None:
folder = self.write("acme", CLIENT)
left_out = load(self.checkout, self.checkout, self.home)
assert isinstance(left_out, ProjectConfig)
self.assertNotIn("touch-predictions", left_out.places)
(folder / "config.toml").write_text(CLIENT + 'touch-predictions = "folder:docs/touch-predictions.md"\n', encoding="utf-8")
found = load(self.checkout, self.checkout, self.home)
assert isinstance(found, ProjectConfig)
self.assertEqual(list(found.places)[-2:], ["principles", "touch-predictions"])
self.assertEqual(found.paths["touch-predictions"], folder / "docs/touch-predictions.md")
self.assertIsNone(found.tracked("touch-predictions"))
(folder / "config.toml").write_text(CLIENT + 'touch-predictions = "docs/touch-predictions.md"\n', encoding="utf-8")
self.assertIn("`touch-predictions` is 'docs/touch-predictions.md', not \"checkout:<path>\"", self.failure())
def test_wait_for_approval_is_an_optional_boolean_that_is_false_where_left_out(self) -> None:
folder = self.write("acme", CLIENT)
left_out = load(self.checkout, self.checkout, self.home)
@@ -245,6 +314,44 @@ class LoadTest(ConfigCase):
assert isinstance(found, Failure), found
self.assertIn(f"`wait-for-approval` is {eval(spelled)!r}, not true or false", found.reason)
def test_tooling_on_host_is_an_optional_boolean_that_is_false_where_left_out(self) -> None:
folder = self.write("acme", CLIENT)
left_out = load(self.checkout, self.checkout, self.home)
assert isinstance(left_out, ProjectConfig), left_out
self.assertFalse(left_out.tooling_on_host)
for spelled, expected in (("true", True), ("false", False)):
with self.subTest(spelled):
(folder / "config.toml").write_text(CLIENT + f"tooling-on-host = {spelled}\n")
found = load(self.checkout, self.checkout, self.home)
assert isinstance(found, ProjectConfig), found
self.assertEqual(found.tooling_on_host, expected)
(folder / "config.toml").write_text(CLIENT + 'tooling-on-host = "yes"\n')
found = load(self.checkout, self.checkout, self.home)
assert isinstance(found, Failure), found
self.assertIn("`tooling-on-host` is 'yes', not true or false", found.reason)
def test_the_readability_floor_is_an_optional_number_from_1_to_10_that_is_7_where_left_out(self) -> None:
folder = self.write("acme", CLIENT)
left_out = load(self.checkout, self.checkout, self.home)
assert isinstance(left_out, ProjectConfig), left_out
self.assertEqual(left_out.readability_floor, decimal.Decimal("7.0"))
for spelled, expected in (("5", "5"), ("6.5", "6.5"), ("1", "1"), ("10.0", "10.0")):
with self.subTest(spelled):
(folder / "config.toml").write_text(CLIENT + f"readability-floor = {spelled}\n")
found = load(self.checkout, self.checkout, self.home)
assert isinstance(found, ProjectConfig), found
self.assertEqual(found.readability_floor, decimal.Decimal(expected))
def test_a_readability_floor_that_is_no_number_from_1_to_10_fails_naming_it(self) -> None:
folder = self.write("acme", CLIENT)
for spelled in ('"7.0"', "0.5", "11", "true", "nan", "inf", "1" + "0" * 400):
with self.subTest(spelled):
(folder / "config.toml").write_text(CLIENT + f"readability-floor = {spelled}\n")
found = load(self.checkout, self.checkout, self.home)
assert isinstance(found, Failure), found
self.assertIn("`readability-floor` is ", found.reason)
self.assertIn(", not a number from 1 to 10; write a bare number, such as `readability-floor = 7.0`", found.reason)
def test_the_language_and_the_templates_are_optional_and_default_to_english_bare_summaries_and_item_branches(self) -> None:
folder = self.write("acme", CLIENT)
left_out = load(self.checkout, self.checkout, self.home)
@@ -280,7 +387,7 @@ class LoadTest(ConfigCase):
def test_the_failure_for_a_misplaced_env_file_and_a_missing_setting_names_both_and_lists_every_setting(self) -> None:
folder = self.write("acme", "".join(line + "\n" for line in CLIENT.splitlines() if not line.startswith("plan")) + 'env-file = "checkout:.env"\n')
self.assertEqual(self.failure(), f"{folder / 'config.toml'}: `plan` is missing; `env-file` is 'checkout:.env', not {OUTSIDE}. The settings are {', '.join(SETTINGS)}, and optionally branch, commit-title, env-file, language, pull-request-title and wait-for-approval.")
self.assertEqual(self.failure(), f"{folder / 'config.toml'}: `plan` is missing; `env-file` is 'checkout:.env', not {OUTSIDE}. The settings are {', '.join(SETTINGS)}, and optionally branch, commit-title, env-file, language, notifier, pull-request-title, readability-floor, tooling-on-host, touch-predictions and wait-for-approval.")
def test_two_configs_naming_one_checkout_fail_naming_both(self) -> None:
self.write("acme", CLIENT)
@@ -390,6 +497,15 @@ class ToolTest(ConfigCase):
self.assertEqual((one.returncode, one.stdout), (0, f"{self.home}/.claude-projects/acme.env\n"))
self.assertEqual(self.run_tool().stdout.splitlines()[-1], f"env-file: {self.home}/.claude-projects/acme.env")
def test_prints_the_notifier_where_the_config_sets_one_and_fails_asking_for_it_where_it_does_not(self) -> None:
folder = self.write("acme", CLIENT)
unset = self.run_tool("notifier")
self.assertEqual((unset.returncode, unset.stdout, unset.stderr), (1, "", f"{folder / 'config.toml'} sets no `notifier`\n"))
self.assertNotIn("notifier", self.run_tool().stdout)
(folder / "config.toml").write_text(CLIENT + 'env-file = "~/.claude-projects/acme.env"\nnotifier = "slack"\n')
self.assertEqual(self.run_tool("notifier").stdout, "slack\n")
self.assertEqual(self.run_tool().stdout.splitlines()[-1], "notifier: slack")
def test_prints_true_or_false_for_wait_for_approval_and_lists_it_only_where_the_config_sets_it(self) -> None:
folder = self.write("acme", CLIENT)
left_out = self.run_tool("wait-for-approval")
@@ -399,6 +515,17 @@ class ToolTest(ConfigCase):
self.assertEqual(self.run_tool("wait-for-approval").stdout, "true\n")
self.assertEqual(self.run_tool().stdout.splitlines()[-1], "wait-for-approval: true")
def test_prints_tooling_on_host_and_the_readability_floor_and_lists_them_only_where_the_config_changes_them(self) -> None:
folder = self.write("acme", CLIENT)
for setting, value in (("tooling-on-host", "false"), ("readability-floor", "7.0")):
with self.subTest(setting):
left_out = self.run_tool(setting)
self.assertEqual((left_out.returncode, left_out.stdout, left_out.stderr), (0, f"{value}\n", ""))
self.assertNotIn(setting, self.run_tool().stdout)
(folder / "config.toml").write_text(CLIENT + "tooling-on-host = true\nreadability-floor = 5\n")
self.assertEqual((self.run_tool("tooling-on-host").stdout, self.run_tool("readability-floor").stdout), ("true\n", "5\n"))
self.assertEqual(self.run_tool().stdout.splitlines()[-2:], ["tooling-on-host: true", "readability-floor: 5"])
def test_prints_the_language_and_each_template_and_lists_them_only_where_the_config_sets_them(self) -> None:
folder = self.write("acme", CLIENT)
defaults = {"language": "English", "commit-title": "{summary}", "pull-request-title": "{summary}", "branch": "item-{id}"}
+9 -5
View File
@@ -4,7 +4,9 @@ usage: project-record open <record>
project-record save <record>
Run inside a checkout, or a worktree of one. <record> is one of decisions, score-anchors,
comprehension-history, reading-cost and changelog, each kept where the project's config names it.
comprehension-history, reading-cost and changelog, each kept where the project's config names it,
or goals-and-audience, the goals file. Goals kept in a Jira epic's description are only read, so
save refuses them: edit the epic in Jira.
open prints the path of a file holding the record's text, and nothing else. Read and edit that
file. Where the record is kept as a file, the path is that file. Where it is kept elsewhere, the
@@ -22,25 +24,27 @@ import pathlib
import sys
from failure import Failure
from record_store.stores import FileStore, local_file, RECORDS, RecordStore, store, stored
from record_store.stores import FileStore, goals_store, local_file, RECORDS, RecordStore, store, stored
from project_config.main import located
# Not git's verbs, such as checkout and commit: those read as acting on the repo.
COMMANDS = ("open", "save")
# Where the copy of a record kept outside files goes, under the user's home, in a folder per project.
COPIES = ".local/state/project-record"
# The goals file opens like a record, though it is a setting of its own.
GOALS = "goals-and-audience"
def main(argv: list[str]) -> int:
if argv[:1] in (["-h"], ["--help"]):
print(__doc__.strip())
return 0
if len(argv) != 2 or argv[0] not in COMMANDS or argv[1] not in RECORDS:
print(f"usage: project-record {'|'.join(COMMANDS)} <record>, where <record> is one of {', '.join(RECORDS)}", file=sys.stderr)
if len(argv) != 2 or argv[0] not in COMMANDS or argv[1] not in (*RECORDS, GOALS):
print(f"usage: project-record {'|'.join(COMMANDS)} <record>, where <record> is one of {', '.join((*RECORDS, GOALS))}", file=sys.stderr)
return 2
home = pathlib.Path.home()
config = located(None, home)
done = config if isinstance(config, Failure) else act(argv[0], store(config, argv[1]), home / COPIES / config.key / f"{argv[1]}.md")
done = config if isinstance(config, Failure) else act(argv[0], goals_store(config) if argv[1] == GOALS else store(config, argv[1]), home / COPIES / config.key / f"{argv[1]}.md")
if isinstance(done, Failure):
print(f"project-record: {done.reason}", file=sys.stderr)
return 1
+5 -1
View File
@@ -53,11 +53,15 @@ class BlackBox(unittest.TestCase):
self.assertEqual((saved.returncode, saved.stdout, saved.stderr), (0, f"{self.top}/docs/decisions.md is the record itself, so nothing is left to store.\n", ""))
self.assertFalse((pathlib.Path(os.environ["HOME"]) / ".local").exists(), "a file record gets no copy")
def test_the_goals_file_opens_as_the_config_names_it(self):
opened = self.run_tool("open", "goals-and-audience")
self.assertEqual((opened.returncode, opened.stdout, opened.stderr), (0, f"{self.top}/README.md\n", ""))
def test_exits_2_with_the_usage_on_an_unknown_command_or_record(self):
for args in ([], ["open"], ["open", "plan"], ["close", "decisions"], ["open", "decisions", "changelog"]):
ran = self.run_tool(*args)
self.assertEqual((ran.returncode, ran.stdout), (2, ""), args)
self.assertIn("usage: project-record open|save <record>, where <record> is one of decisions, score-anchors, comprehension-history, reading-cost, changelog", ran.stderr)
self.assertIn("usage: project-record open|save <record>, where <record> is one of decisions, score-anchors, comprehension-history, reading-cost, changelog, goals-and-audience", ran.stderr)
def test_exits_1_saying_why_where_no_config_names_the_checkout(self):
(pathlib.Path(os.environ["HOME"]) / ".claude-projects" / self.top.name / "config.toml").unlink()
+4 -3
View File
@@ -44,9 +44,10 @@ A valid todo.md; ## Details and each item's detail are optional:
file's achieve goals follow in reading order, a sub-goal such as 1.1 included. Each weighs 0.97 times the one
before, and the weights sum to 1. With 5 achieve goals the first weighs 0.212 and the last 0.188.
With 15 they weigh 0.082 and 0.053. The overall is the mean of the overall means of every scoring
run on docs/comprehension-history.md's newest scored commit. While it is under 7.0, or the history
holds no scoring run, code health weighs 4 times its weight by position, and the other goals keep
theirs. A line `**Void:** code health, since <reason>.` in the goals file's ## Goals drops code
run on docs/comprehension-history.md's newest scored commit. While it is under the project's
readability floor, or the history holds no scoring run, code health weighs 4 times its weight by
position, and the other goals keep theirs. The config sets the floor as `readability-floor`, 7.0
where left out. A line `**Void:** code health, since <reason>.` in the goals file's ## Goals drops code
health, and an item may not name it. A project must void it where its docs/decisions.md has a
`## review opt-out:` title naming the comprehension check. An item that adds a test,
a gate leg or a probe that fails where a maintain goal breaks may name that goal, by how much
+53
View File
@@ -0,0 +1,53 @@
"""A project's goals and audience kept as the description of one Jira Cloud epic, read over Jira's REST API with the credentials of the config's env-file, and converted by the adf-codec shim.
The store only reads: a write, such as `project-record save goals-and-audience`, fails, saying to edit the epic in Jira."""
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 project_config.settings import Epic
from failure import Failure
READ_ONLY = "goals and audience kept in Jira are only read: edit the epic's description in Jira"
@dataclasses.dataclass(frozen=True)
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
to_markdown: ToMarkdown = adfs_to_markdown
@property
def label(self) -> str:
return self.epic.spelling
@property
def tracked(self) -> str | None:
return None
def read(self) -> str | Failure:
"""The description as markdown; empty where the epic has none."""
authorization = basic_auth(self.env_file)
if isinstance(authorization, Failure):
return authorization
key = self.epic.key
answer = self.http("GET", f"{self.epic.site}/rest/api/3/issue/{key}?fields=description", authorization, None)
if isinstance(answer, Failure):
return Failure(f"cannot read the epic {key}: {answer.reason}")
fields = answer.get("fields") if isinstance(answer, dict) else None
if not isinstance(fields, dict) or "description" not in fields or not isinstance(fields["description"], dict | None):
return Failure(f"the epic {key} is not in the shape Jira Cloud's REST API version 3 documents: its description field is missing, or neither a document nor null")
if fields["description"] is None:
return ""
texts = self.to_markdown([fields["description"]])
if isinstance(texts, Refused):
return Failure(f"{key}'s description: {texts.failure.reason}")
if isinstance(texts, Failure):
return Failure(f"cannot convert {key}'s description to markdown: {texts.reason}")
return texts[0]
def write(self, text: str) -> Failure | None:
return Failure(READ_ONLY)
+20 -2
View File
@@ -1,13 +1,13 @@
"""The one way a tool reads or writes a project's records: through the store its config names for each.
Each record has its own setting in the config, so a project may keep one record in its wiki and another as a file. The setting's value names the backend. A path names a markdown file, the only backend so far."""
Each record has its own setting in the config, so a project may keep one record in its wiki and another as a file. The setting's value names the backend. A path names a markdown file, the only backend of a record so far; the goals file may also be a Jira epic's description, which `goals_store` picks."""
import dataclasses
import pathlib
import typing
from failure import Failure
from git_cli.git_repo import file_at, git, Git
from project_config.settings import ProjectConfig
from project_config.settings import ProjectConfig, TOUCH_PREDICTIONS
from text_files.file_writes import replace_file
# The settings in a project's config that each name a record.
@@ -68,6 +68,24 @@ def store(config: ProjectConfig, record: str) -> RecordStore:
return FileStore(config.paths[record], config.tracked(record))
def touch_predictions_store(config: ProjectConfig) -> RecordStore | None:
"""The store of the touch-predictions record, the one record a config may leave out; None where it does."""
if TOUCH_PREDICTIONS not in config.paths:
return None
return FileStore(config.paths[TOUCH_PREDICTIONS], config.tracked(TOUCH_PREDICTIONS))
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)
def held_at(revision: str, record: RecordStore, cwd: str, run: Git = git) -> str | Failure:
"""record's text at revision, read in the checkout at cwd, where its commits hold the record; else as it stands. Empty where there is no such record."""
return record.read() if record.tracked is None else file_at(revision, record.tracked, cwd, run)
+89
View File
@@ -0,0 +1,89 @@
import base64
import pathlib
import sys
import tempfile
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from project_config.settings import Epic
from record_store.jira_description import EpicDescription
from failure import Failure
from adf_codec.convert import Refused
EPIC = Epic("https://acme.atlassian.net", "ABC-12")
AUTHORIZATION = "Basic " + base64.b64encode(b"me@example.com:s3cret").decode()
GOALS = {"type": "doc", "version": 1, "content": [{"type": "heading", "attrs": {"level": 2}, "content": [{"type": "text", "text": "Goals"}]}]}
class EpicDescriptionTest(unittest.TestCase):
def setUp(self) -> None:
self.env = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory())) / "acme.env"
self.env.write_text("ATLASSIAN_EMAIL=me@example.com\nATLASSIAN_API_TOKEN=s3cret\n")
self.env.chmod(0o600)
self.answer: object = {"key": "ABC-12", "fields": {"description": GOALS}}
self.calls: list[tuple[str, str, str, object]] = []
self.converted: list[list[dict[str, object]]] = []
self.markdown: list[str] | Refused | Failure = ["## Goals\n1. **Achieve:** Ship.\n"]
def http(self, method: str, url: str, authorization: str, body: object) -> object:
self.calls.append((method, url, authorization, body))
return self.answer
def to_markdown(self, documents: list[dict[str, object]]) -> list[str] | Refused | Failure:
self.converted.append(documents)
return self.markdown
def store(self) -> EpicDescription:
return EpicDescription(EPIC, self.env, self.http, self.to_markdown)
def test_reads_the_epics_description_as_markdown(self) -> None:
self.assertEqual(self.store().read(), "## Goals\n1. **Achieve:** Ship.\n")
self.assertEqual(self.calls, [("GET", "https://acme.atlassian.net/rest/api/3/issue/ABC-12?fields=description", AUTHORIZATION, None)])
self.assertEqual(self.converted, [[GOALS]])
def test_is_named_as_the_config_spells_it_and_held_in_no_commit(self) -> None:
self.assertEqual((self.store().label, self.store().tracked), ("jira:https://acme.atlassian.net/browse/ABC-12", None))
def test_an_epic_without_a_description_reads_empty(self) -> None:
self.answer = {"key": "ABC-12", "fields": {"description": None}}
self.assertEqual(self.store().read(), "")
self.assertEqual(self.converted, [])
def test_an_unreadable_epic_fails_naming_it(self) -> None:
self.answer = Failure("HTTP 404: Issue does not exist")
found = self.store().read()
assert isinstance(found, Failure), found
self.assertIn("ABC-12", found.reason)
self.assertIn("HTTP 404", found.reason)
def test_an_answer_in_another_shape_fails(self) -> None:
for answer in ({"key": "ABC-12"}, {"fields": {"description": "text"}}, ["ABC-12"]):
with self.subTest(answer):
self.answer = answer
found = self.store().read()
assert isinstance(found, Failure), found
self.assertIn("ABC-12", found.reason)
def test_a_description_the_shim_refuses_fails(self) -> None:
for markdown in (Refused(0, Failure("an unsupported node")), Failure("docker is not running")):
with self.subTest(markdown):
self.markdown = markdown
found = self.store().read()
assert isinstance(found, Failure), found
self.assertIn("ABC-12", found.reason)
def test_missing_credentials_fail(self) -> None:
self.env.unlink()
self.assertIsInstance(self.store().read(), Failure)
self.assertEqual(self.calls, [])
def test_writing_fails_since_the_store_only_reads(self) -> None:
found = self.store().write("## Goals\n")
assert isinstance(found, Failure), found
self.assertIn("Jira", found.reason)
self.assertEqual(self.calls, [])
if __name__ == "__main__":
unittest.main()
+14 -1
View File
@@ -6,9 +6,10 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from project_config.settings import Epic, ProjectConfig
from record_store.jira_description import EpicDescription
from failure import Failure
from record_store.fakes import MemoryStore
from project_config.settings import ProjectConfig
from record_store.contract import RecordStoreContract
from record_store import stores
@@ -171,5 +172,17 @@ class Store(unittest.TestCase):
self.assertEqual(str(refused.exception), "plan is not a record; the records are decisions, score-anchors, comprehension-history, reading-cost, changelog")
class GoalsStore(unittest.TestCase):
def test_goals_kept_as_a_file_are_that_file(self):
top = pathlib.Path("/code/acme")
store = stores.goals_store(ProjectConfig("acme", pathlib.Path("/home/me/.claude-projects/acme"), top, {"goals-and-audience": top / "README.md"}))
self.assertEqual((store.label, store.tracked), ("/code/acme/README.md", "README.md"))
def test_goals_kept_in_jira_are_the_epics_description(self):
epic = Epic("https://acme.atlassian.net", "ABC-12")
store = stores.goals_store(ProjectConfig("acme", pathlib.Path("/home/me/.claude-projects/acme"), pathlib.Path("/code/acme"), {}, pathlib.Path("/home/me/acme.env"), goals_epic=epic))
self.assertEqual(store, EpicDescription(epic, pathlib.Path("/home/me/acme.env")))
if __name__ == "__main__":
unittest.main()
+4 -5
View File
@@ -6,12 +6,11 @@ import typing
from release_plan.todo_table import CODE_HEALTH
from failure import Failure
from review_rules.comprehension_history import FLOOR
from text_files.markdown_text import sections
# What each achieve goal weighs of the one above it; docs/decisions.md records the choice.
GOAL_STEP = 0.97
# Code health weighs this many times its weight by position while the comprehension panel's overall is under FLOOR, or unmeasured; lilleman's choice, which docs/decisions.md records.
# Code health weighs this many times its weight by position while the comprehension panel's overall is under the project's readability floor, or unmeasured; lilleman's choice, which docs/decisions.md records.
UNDER_FLOOR = 4
# Any **Void:** line of the goals file's ## Goals; ranked_goals accepts only `**Void:** code health, since <reason>.`, as ~/.claude/CLAUDE.md → "Shared goal" spells it.
VOID = re.compile(r"^\*\*Void:\*\* (.*)$", re.M)
@@ -72,13 +71,13 @@ def numbered(body: str) -> list[tuple[str, Mark]] | Failure:
return goals
def goal_weights(goals: list[tuple[str, Mark]], overall: decimal.Decimal | None) -> dict[str, float] | Failure:
"""Each achieve goal's weight: the one ranked k of n weighs GOAL_STEP ** (k - 1) / (1 + GOAL_STEP + ... + GOAL_STEP ** (n - 1)), so the weights sum to 1. Code health, where goals holds it, then weighs UNDER_FLOOR times that while the overall is under FLOOR or None, and the other goals keep their weights. Every weight is 0 where goals holds no achieve goal, as where the goals file voids code health and marks no goal **Achieve:**; an item then scores V 0 unless it names a maintain goal, and only an exempt one passes the bar. A maintain goal has no weight here: weight_of weighs it per item."""
def goal_weights(goals: list[tuple[str, Mark]], overall: decimal.Decimal | None, floor: decimal.Decimal) -> dict[str, float] | Failure:
"""Each achieve goal's weight: the one ranked k of n weighs GOAL_STEP ** (k - 1) / (1 + GOAL_STEP + ... + GOAL_STEP ** (n - 1)), so the weights sum to 1. Code health, where goals holds it, then weighs UNDER_FLOOR times that while the overall is None or under floor, the project's readability floor, and the other goals keep their weights. Every weight is 0 where goals holds no achieve goal, as where the goals file voids code health and marks no goal **Achieve:**; an item then scores V 0 unless it names a maintain goal, and only an exempt one passes the bar. A maintain goal has no weight here: weight_of weighs it per item."""
if unmarked := [number for number, mark in goals if mark is None]:
return Failure(f"the goals file's goal {unmarked[0]} is marked neither **Maintain:** nor **Achieve:**; mark it, as ~/.claude/rules/goals-and-audience.md says, so rank_todo.py knows which goals score")
achieve = [number for number, mark in goals if mark == "Achieve"]
total = sum(GOAL_STEP**rank for rank in range(len(achieve)))
weights = {number: GOAL_STEP**rank / total for rank, number in enumerate(achieve)}
if CODE_HEALTH in weights and (overall is None or overall < FLOOR):
if CODE_HEALTH in weights and (overall is None or overall < floor):
weights[CODE_HEALTH] *= UNDER_FLOOR
return weights
+2 -2
View File
@@ -13,7 +13,7 @@ def rank_file(todo: pathlib.Path, config: ProjectConfig) -> Ranked | Failure:
texts = file_plan(config, todo).texts()
if isinstance(texts, Failure):
return texts
ranked = rank(*texts)
ranked = rank(*texts, config.readability_floor)
if isinstance(ranked, Failure):
return ranked
if ranked.text != texts[0] and (unwritten := write(todo, ranked.text)):
@@ -31,7 +31,7 @@ def check_failures(todo: pathlib.Path, config: ProjectConfig) -> list[str]:
texts = file_plan(config, todo).texts()
if isinstance(texts, Failure):
return [texts.reason]
ranked = rank(*texts)
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"]
+8 -6
View File
@@ -2,6 +2,7 @@
"""
import ast
import dataclasses
import decimal
import math
import re
import typing
@@ -44,13 +45,14 @@ class Ranked:
notes: list[str]
def rank(text: str, goals_text: str, decisions: str, history: str) -> Ranked | Failure:
def rank(text: str, goals_text: str, decisions: str, history: str, floor: decimal.Decimal) -> Ranked | Failure:
"""floor is the project's readability floor, which its config sets."""
lines = text.split("\n")
table = read_table(lines)
if isinstance(table, Failure):
return table
shape = shape_of(table.columns)
scoring = read_scoring(text, lines, goals_text, decisions, history, shape)
scoring = read_scoring(text, lines, goals_text, decisions, history, shape, floor)
if isinstance(scoring, Failure):
return scoring
items = read_items(table, scoring)
@@ -112,7 +114,7 @@ def under_the_bar(item: Item, value: float, bar: float, items: list[Item]) -> st
return f"item {item.id} scores {value:.1f}, under the bar {bar:g}; delete it{blocked}, or mark it with a reason the bar does not apply"
def read_scoring(text: str, lines: list[str], goals_text: str, decisions: str, history: str, shape: Shape) -> Scoring | Failure:
def read_scoring(text: str, lines: list[str], goals_text: str, decisions: str, history: str, shape: Shape, floor: decimal.Decimal) -> Scoring | Failure:
goals = ranked_goals(goals_text, decisions)
if isinstance(goals, Failure):
return goals
@@ -125,13 +127,13 @@ def read_scoring(text: str, lines: list[str], goals_text: str, decisions: str, h
next_id = stated(text, "Next ID")
if isinstance(next_id, Failure) or not re.fullmatch(r"[0-9]+", next_id):
return next_id if isinstance(next_id, Failure) else Failure(f"Next ID {next_id!r} is not a whole number")
weights = weigh(lines, history, goals, shape)
weights = weigh(lines, history, goals, shape, floor)
if isinstance(weights, Failure):
return weights
return Scoring(shape, formula, bar, int(next_id), dict(goals), weights)
def weigh(lines: list[str], history: str, goals: list[tuple[str, Mark]], shape: Shape) -> dict[str, float] | Failure:
def weigh(lines: list[str], history: str, goals: list[tuple[str, Mark]], shape: Shape, floor: decimal.Decimal) -> dict[str, float] | Failure:
"""Each goal's weight. In OLD_SHAPE, the goals file's goals weigh what todo.md states, and code health has no weight, so no item may name it. Otherwise goal_weights gives each its weight, at the overall latest_overall reads where the goals hold code health."""
if shape is OLD_SHAPE:
return parse_weights(lines, [number for number, _ in goals if number != CODE_HEALTH])
@@ -140,7 +142,7 @@ def weigh(lines: list[str], history: str, goals: list[tuple[str, Mark]], shape:
overall = latest_overall(history) if CODE_HEALTH in dict(goals) else None
if isinstance(overall, Failure):
return overall
return goal_weights(goals, overall)
return goal_weights(goals, overall, floor)
def read_table(lines: list[str]) -> Table | Failure:
+2 -1
View File
@@ -6,13 +6,14 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from release_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
class Blockers(unittest.TestCase):
def ranked(self, todo):
return ranking.rank(todo, README, DECISIONS, "")
return ranking.rank(todo, README, DECISIONS, "", DEFAULT_FLOOR)
def test_ranks_each_blocker_just_above_the_first_item_it_blocks(self):
ranked = self.ranked(TODO.replace("| 3 | 0.1.0 | |", "| 3 | 0.1.0 | 5, 2 |"))
+2 -1
View File
@@ -5,13 +5,14 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from release_plan.test_ranking import DECISIONS, README, TODO
from project_config.settings import DEFAULT_FLOOR
from failure import Failure
from release_plan import ranking
class Formula(unittest.TestCase):
def ranked(self, todo):
return ranking.rank(todo, README, DECISIONS, "")
return ranking.rank(todo, README, DECISIONS, "", DEFAULT_FLOOR)
def test_refuses_a_formula_that_is_more_than_arithmetic_over_the_scores(self):
for formula in ("__import__('os')", "R.real", "X + 1", "C + 1", "A + V", "G + V", "W * V", "R ^ 2", "R +", "R / (S - 2)", "R\x00", "1" * 400, " + ".join(["R"] * 300), "-" * 100000 + "R", "10 ** 10 ** 10", "(-8) ** (1 / 3)", "0 ** -1"):
+44 -18
View File
@@ -1,4 +1,5 @@
import contextlib
import decimal
import io
import pathlib
import re
@@ -9,6 +10,7 @@ import unittest
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 project_config.main import located
@@ -107,7 +109,7 @@ def numbered_goals(goals_text):
class Rank(unittest.TestCase):
def ranked(self, todo=TODO, readme=README, decisions=DECISIONS):
return ranking.rank(todo, readme, decisions, "")
return ranking.rank(todo, readme, decisions, "", DEFAULT_FLOOR)
def test_scores_and_sorts_by_release_then_security_then_score_and_orders_the_details_to_match(self):
ranked = self.ranked()
@@ -128,13 +130,13 @@ class Rank(unittest.TestCase):
def test_weighs_each_achieve_goal_97_percent_of_the_one_above_and_no_maintain_goal(self):
readme = "## Goals\n\n1. **Achieve:** A.\n 1. **Maintain:** B.\n 2. **Achieve:** C.\n2. **Achieve:** D.\n"
self.assertEqual({goal: round(weight, 4) for goal, weight in goals_file.goal_weights(numbered_goals(readme), None).items()}, {"1": 0.3435, "1.2": 0.3332, "2": 0.3232})
self.assertEqual({goal: round(weight, 4) for goal, weight in goals_file.goal_weights(numbered_goals(readme), None, DEFAULT_FLOOR).items()}, {"1": 0.3435, "1.2": 0.3332, "2": 0.3232})
def test_weighs_5_achieve_goals_from_0212_to_0188_and_15_from_0082_to_0053(self):
for count, first, last in ((5, 0.212, 0.188), (15, 0.082, 0.053)):
with self.subTest(count=count):
goals = numbered_goals("## Goals\n\n" + "".join(f"{number}. **Achieve:** G.\n" for number in range(1, count + 1)))
weights = list(goals_file.goal_weights(goals, None).values())
weights = list(goals_file.goal_weights(goals, None, DEFAULT_FLOOR).values())
self.assertEqual((round(weights[0], 3), round(weights[-1], 3), round(sum(weights), 6)), (first, last, 1))
def test_scores_an_item_by_the_weights_of_the_goals_it_moves(self):
@@ -262,7 +264,7 @@ class CodeHealth(unittest.TestCase):
todo = TODO.split("| 1 | 0.2.0", 1)[0].replace("`Bar = 2`", "`Bar = 0.1`") + "| 1 | 0.1.0 | | | **Read easier.** | 1 | 1 | 1 | 1 | 1 | code health by 1 | 0 |\n| 2 | 0.1.0 | | | **Do A.** | 1 | 1 | 1 | 1 | 1 | 1 by 1 | 0 |\n"
def scores(self, history, readme=readme):
ranked = ranking.rank(self.todo, readme, "", history)
ranked = ranking.rank(self.todo, readme, "", history, DEFAULT_FLOOR)
return ranked if isinstance(ranked, Failure) else {line.split(" | ")[0]: line.rsplit(" | ", 1)[1].rstrip(" |") for line in ranked.text.splitlines() if line.startswith("| ") and " 0.1.0 " in line}
def entry(self, overall, at="2026-10-08T12", read="PR #1 at aaaaaaa"):
@@ -278,6 +280,13 @@ class CodeHealth(unittest.TestCase):
with self.subTest(history=history):
self.assertEqual(self.scores(history), {"| 1": "101.5", "| 2": "24.6"})
def test_weighs_code_health_four_times_as_much_only_under_the_floor_it_is_given(self):
for floor, value in (("6.0", "25.4"), ("6.5", "101.5")):
with self.subTest(floor=floor):
ranked = ranking.rank(self.todo, self.readme, "", SCORED.format(overall="6.25"), decimal.Decimal(floor))
assert isinstance(ranked, ranking.Ranked), ranked
self.assertIn(f"| **Read easier.** | 1 | 1 | 1 | 1 | 1 | code health by 1 | {value} |", ranked.text)
def test_weighs_by_the_newest_scored_commit_wherever_the_file_holds_it(self):
older = self.entry("6.50")
newer = self.entry("7.25", "2026-10-10T12", "PR #1 at bbbbbbb")
@@ -313,7 +322,7 @@ class CodeHealth(unittest.TestCase):
def test_drops_code_health_where_readme_voids_it(self):
voided = "## Goals\n\n**Void:** code health, since it is a one-off script.\n\n1. **Achieve:** A.\n"
self.assertEqual(self.scores("", voided), Failure("item 1 names code health, which the goals file voids; drop it from the item's Moves, or the void from the goals file"))
ranked = ranking.rank(self.todo.replace("code health by 1", "1 by 2"), voided, "", "")
ranked = ranking.rank(self.todo.replace("code health by 1", "1 by 2"), voided, "", "", DEFAULT_FLOOR)
self.assertIn("| **Read easier.** | 1 | 1 | 1 | 1 | 1 | 1 by 2 | 100.0 |", ranked.text)
def test_weighs_a_defects_maintain_goal_as_code_health_four_times_over_under_an_overall_of_7(self):
@@ -321,18 +330,18 @@ class CodeHealth(unittest.TestCase):
todo = self.todo.replace("| 2 | 0.1.0 | | | **Do A.** | 1 | 1 | 1 | 1 | 1 | 1 by 1 |", "| 2 | 0.1.0 | | defect | **Restore B.** | 1 | 1 | 1 | 1 | 1 | 2 by 1 |")
for history, value in (("", "101.5"), (SCORED.format(overall="7.00"), "25.4")):
with self.subTest(history=history):
self.assertIn(f"| **Restore B.** | 1 | 1 | 1 | 1 | 1 | 2 by 1 | {value} |", ranking.rank(todo, readme, "", history).text)
self.assertIn(f"| **Restore B.** | 1 | 1 | 1 | 1 | 1 | 2 by 1 | {value} |", ranking.rank(todo, readme, "", history, DEFAULT_FLOOR).text)
def test_refuses_a_plan_whose_project_opts_out_of_the_comprehension_check_yet_keeps_code_health(self):
opted_out = "## review opt-out: the architect and the comprehension check\n\nCosts rounds.\n"
self.assertEqual(ranking.rank(self.todo, self.readme, opted_out, ""), Failure("docs/decisions.md opts out of the comprehension check, so code health has no signal; void it in the goals file's ## Goals with `**Void:** code health, since <reason>.`, as ~/.claude/CLAUDE.md → 'Shared goal' says"))
self.assertIsInstance(ranking.rank(self.todo, self.readme, opted_out.replace(" and the comprehension check", ""), ""), ranking.Ranked)
self.assertEqual(ranking.rank(self.todo, self.readme, opted_out, "", DEFAULT_FLOOR), Failure("docs/decisions.md opts out of the comprehension check, so code health has no signal; void it in the goals file's ## Goals with `**Void:** code health, since <reason>.`, as ~/.claude/CLAUDE.md → 'Shared goal' says"))
self.assertIsInstance(ranking.rank(self.todo, self.readme, opted_out.replace(" and the comprehension check", ""), "", DEFAULT_FLOOR), ranking.Ranked)
voided = "## Goals\n\n**Void:** code health, since nobody reads the probes.\n\n1. **Achieve:** A.\n"
self.assertIsInstance(ranking.rank(self.todo.replace("code health by 1", "1 by 2"), voided, opted_out, ""), ranking.Ranked)
self.assertIsInstance(ranking.rank(self.todo.replace("code health by 1", "1 by 2"), voided, opted_out, "", DEFAULT_FLOOR), ranking.Ranked)
def test_ranks_a_project_that_voids_code_health_whatever_its_history_holds(self):
voided = "## Goals\n\n**Void:** code health, since it is a one-off script.\n\n1. **Achieve:** A.\n"
self.assertIsInstance(ranking.rank(self.todo.replace("code health by 1", "1 by 2"), voided, "", SCORED.format(overall="high")), ranking.Ranked)
self.assertIsInstance(ranking.rank(self.todo.replace("code health by 1", "1 by 2"), voided, "", SCORED.format(overall="high"), DEFAULT_FLOOR), ranking.Ranked)
def test_refuses_a_void_of_anything_but_code_health(self):
self.assertEqual(self.scores("", "## Goals\n\n**Void:** speed, since nobody waits.\n\n1. **Achieve:** A.\n"), Failure("the goals file's ## Goals voids `speed, since nobody waits.`; only code health may be voided, as `**Void:** code health, since <reason>.`"))
@@ -361,11 +370,28 @@ class CodeHealth(unittest.TestCase):
self.assertEqual(ranked.under_bar, [])
self.assertIn("| code health by 1 | 25.4 |", todo.read_text())
def test_ranks_and_checks_with_the_floor_the_config_sets(self):
# At an overall of 6.50, code health weighs 4 times under the default floor of 7.0, and once at a floor of 6.0.
with tempfile.TemporaryDirectory() as temp:
todo = pathlib.Path(temp, "todo.md")
todo.write_text(self.todo)
folder = configured(self, pathlib.Path(temp), goals="folder:goals.md")
(folder / "goals.md").write_text(self.readme)
with (folder / "config.toml").open("a") as config:
config.write("readability-floor = 6.0\n")
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()))
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())), [])
class Risk(unittest.TestCase):
"""R is L + E + I - 2, which rank_todo.py writes, at least 7 when I is 5 and at least 5 when I is 4."""
def ranked(self, todo):
return ranking.rank(todo, README, DECISIONS, "")
return ranking.rank(todo, README, DECISIONS, "", DEFAULT_FLOOR)
def test_writes_r_from_l_e_and_i_over_a_stale_or_missing_r(self):
ranked = self.ranked(TODO).text
@@ -414,7 +440,7 @@ class Risk(unittest.TestCase):
class OldShape(unittest.TestCase):
"""A table with A, G and Goals, from before the Moves column, ranks by the formula and goal weights it states until its project reshapes it."""
def ranked(self, todo=OLD_SHAPE, readme=README):
return ranking.rank(todo, readme, DECISIONS, "")
return ranking.rank(todo, readme, DECISIONS, "", DEFAULT_FLOOR)
def test_scores_by_the_stated_weights_and_says_to_reshape(self):
ranked = self.ranked()
@@ -441,7 +467,7 @@ class OldShape(unittest.TestCase):
def test_ranks_a_table_from_before_c_joined_and_says_to_reshape_it(self):
legacy = OLD_SHAPE.split("## Items")[0] + "## Items\n\n| ID | Release | Exempt | Item | R | S | A | G | Goals | Score |\n|---|---|---|---|---|---|---|---|---|---|\n| 2 | 0.1.0 | | **Tighten the tests.** | 2 | 4 | 5 | 5 | 2.1 | 0 |\n"
self.assertEqual(ranking.rank(legacy, README, "", "").notes, [ranking.RESHAPE])
self.assertEqual(ranking.rank(legacy, README, "", "", DEFAULT_FLOOR).notes, [ranking.RESHAPE])
def test_refuses_a_table_with_both_moves_and_goals(self):
both = OLD_SHAPE.replace("| Goals | Score |\n|---|", "| Goals | Moves | Score |\n|---|---|").replace(" | 0 |\n", " | 1 by 1 | 0 |\n")
@@ -451,7 +477,7 @@ class OldShape(unittest.TestCase):
def test_names_the_goals_column_a_table_misspells_by_its_shape(self):
misspelt = TODO.replace("| S | Moves |", "| S | Move |")
self.assertEqual(ranking.rank(misspelt, README, DECISIONS, ""), Failure("todo.md's items table has no Moves column; rank_todo.py --help shows a valid one"))
self.assertEqual(ranking.rank(misspelt, README, DECISIONS, "", DEFAULT_FLOOR), Failure("todo.md's items table has no Moves column; rank_todo.py --help shows a valid one"))
self.assertEqual(todo_table.items(misspelt), Failure("todo.md's items table has no Moves column; rank_todo.py --help shows a valid one"))
self.assertEqual(self.ranked(OLD_SHAPE.replace("| G | Goals |", "| G | Goal |")), Failure("todo.md's items table has no Goals column; rank_todo.py --help shows a valid one"))
@@ -466,15 +492,15 @@ class Renamed(unittest.TestCase):
self.assertIsInstance(todo_table.renames(f"## Renamed\n\n{bad}\n"), Failure)
def test_fails_on_a_renamed_section_that_does_not_parse(self):
failed = ranking.rank(TODO + "\n## Renamed\n\nsoon\n", README, DECISIONS, "")
failed = ranking.rank(TODO + "\n## Renamed\n\nsoon\n", README, DECISIONS, "", DEFAULT_FLOOR)
self.assertIsInstance(failed, Failure)
self.assertIn("## Renamed", failed.reason)
def test_ranks_a_plan_with_a_valid_renamed_section(self):
self.assertIsInstance(ranking.rank(TODO + "\n## Renamed\n\n- 0.3.0 renamed to 0.4.0\n", README, DECISIONS, ""), ranking.Ranked)
self.assertIsInstance(ranking.rank(TODO + "\n## Renamed\n\n- 0.3.0 renamed to 0.4.0\n", README, DECISIONS, "", DEFAULT_FLOOR), ranking.Ranked)
def test_fails_on_an_item_filed_under_a_release_the_plan_marks_renamed(self):
live = ranking.rank(TODO + "\n## Renamed\n\n- 0.2.0 renamed to 0.3.0\n", README, DECISIONS, "")
live = ranking.rank(TODO + "\n## Renamed\n\n- 0.2.0 renamed to 0.3.0\n", README, DECISIONS, "", DEFAULT_FLOOR)
self.assertIsInstance(live, Failure)
self.assertIn("marks release 0.2.0 renamed but files item 1 under it", live.reason)
@@ -483,5 +509,5 @@ class Renamed(unittest.TestCase):
class ThisRepo(unittest.TestCase):
def test_todo_md_is_ranked_with_nothing_under_the_bar(self):
text = (ROOT / "todo.md").read_text(encoding="utf-8")
ranked = ranking.rank(text, *((ROOT / name).read_text(encoding="utf-8") for name in ("README.md", "docs/decisions.md", "docs/comprehension-history.md")))
ranked = ranking.rank(text, *((ROOT / name).read_text(encoding="utf-8") for name in ("README.md", "docs/decisions.md", "docs/comprehension-history.md")), DEFAULT_FLOOR)
self.assertEqual(ranked, ranking.Ranked(text, [], []))
+2 -2
View File
@@ -8,13 +8,13 @@ import unittest
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 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 project_config.settings import ProjectConfig, SETTINGS
from release_plan import release_standing
from release_plan import todo_table
from release_plan.release import version
@@ -26,7 +26,7 @@ ROW = "| {id} | {release} | | | **Do {id}.** | 1 | 1 | 1 | 1 | 1 | 1 by 1 | 10
def plan_at(path: pathlib.Path, tracked: str | None) -> FilePlan:
"""The markdown plan at path, which these tests only read."""
return FilePlan(path, tracked, path.parent / "README.md", MemoryStore(), MemoryStore())
return FilePlan(path, tracked, FileStore(path.parent / "README.md", None), MemoryStore(), MemoryStore(), DEFAULT_FLOOR)
def plan_in(repo: str) -> FilePlan:
+6 -1
View File
@@ -19,11 +19,14 @@ class NoRedirect(urllib.request.HTTPRedirectHandler):
return None
# Sends a request: method, url, token and the body as JSON where there is one. It returns the JSON answer, None where the answer has no body, or a Failure saying why there is none.
Http = typing.Callable[[str, str, str, object], object]
OPENER = urllib.request.build_opener(NoRedirect)
def http_json(method: str, url: str, authorization: str, body: object, seconds: int, message_of: MessageOf) -> object:
"""The JSON that url answers to a request with the Authorization header given, and body as JSON where there is one. A Failure names the server where it cannot be reached, and the request where it answers an error, breaks HTTP or answers something other than JSON. Each connect and each read may wait that many seconds."""
"""The JSON that url answers to a request with the Authorization header given, and body as JSON where there is one; None where it answers a success without a body, as Jira does to a new issue link. A Failure names the server where it cannot be reached, and the request where it answers an error, breaks HTTP or answers something other than JSON. Each connect and each read may wait that many seconds."""
request_name = f"{method} {urllib.parse.urlsplit(url).path}"
data = None if body is None else json.dumps(body).encode()
request = urllib.request.Request(url, data, {"Authorization": authorization, "Content-Type": "application/json", "Accept": "application/json"}, method=method)
@@ -38,6 +41,8 @@ def http_json(method: str, url: str, authorization: str, body: object, seconds:
except (OSError, ValueError) as failure:
server = urllib.parse.urlunsplit(urllib.parse.urlsplit(url)[:2] + ("", "", ""))
return Failure(f"cannot reach {server}: {getattr(failure, 'reason', failure)}")
if not raw.strip():
return None
try:
return json.loads(raw)
except ValueError:
+6
View File
@@ -66,6 +66,12 @@ class HttpJson(unittest.TestCase):
[(method, path, headers, body)] = self.server.got # type: ignore[attr-defined]
self.assertEqual((method, path, headers["Authorization"], headers["Content-Type"], headers["Accept"], json.loads(body)), ("POST", "/api/v4/posts", "Bearer secret-token", "application/json", "application/json", {"message": "hi"}))
def test_reads_an_answer_without_a_body_as_none(self):
for body in (b"", b"\n"):
with self.subTest(body=body):
base = self.serve((201, body))
self.assertIsNone(send("POST", f"{base}/rest/api/3/issueLink", "t", {"type": {"name": "Blocks"}}))
def test_names_the_request_the_status_and_the_apis_message_on_an_error(self):
base = self.serve((401, b'{"message": "Invalid or expired session, please login again."}'))
self.assertEqual(send("GET", f"{base}/api/v4/users/me", "bad", None), Failure("GET /api/v4/users/me answered 401: Invalid or expired session, please login again."))
@@ -9,8 +9,6 @@ from text_files.utc_stamp import utc
ARCHITECT = "Inherited architect"
DECIDED_BY = "decided by"
DIMENSIONS = ("Navigation", "Locality", "Shape", "Self-sufficiency", "Overall")
# The comprehension floor, which every dimension and the overall should reach; docs/decisions.md → "comprehension floor" says it doesn't block anything.
FLOOR = decimal.Decimal("7.0")
HARDEST_FIRST = "hardest first"
HEADING = re.compile(r"^([^,]+), (.+) at ([0-9a-f]{7,40})(?:, against ([0-9a-f]{7,40}))?$")
HISTORY = "docs/comprehension-history.md"
View File
+52
View File
@@ -0,0 +1,52 @@
"""Sends a direct message from a Slack app's bot to one user, through Slack's Web API. The `notifier` setting `slack` picks it."""
import dataclasses
import html
import pathlib
from failure import Failure
from rest_client.json_request import Http
from rest_client import json_request
from rest_client.env_file import read_env
KEYS = ("SLACK_TOKEN", "SLACK_RECIPIENT")
# Slack's one host for every workspace.
API = "https://slack.com/api"
# Seconds each connect and each read may wait, so an unreachable server holds loop-claude's interrupt only briefly.
TIMEOUT = 10
@dataclasses.dataclass(frozen=True)
class Config:
token: str
recipient: str
def read_config(path: pathlib.Path) -> Config | Failure:
"""The bot token and recipient that path's KEY=value lines hold."""
values = read_env(path, KEYS, "the bot's token")
if isinstance(values, Failure):
return values
return Config(*(values[key] for key in KEYS))
def send(config: Config, message: str, http: Http) -> Failure | None:
"""Posts message to the recipient's member ID, which Slack opens as a DM from the app's bot; the bot needs the `chat:write` scope. Slack reads `&`, `<` and `>` as control characters, so they are escaped as its docs ask."""
answer = http("POST", f"{API}/chat.postMessage", config.token, {"channel": config.recipient, "text": html.escape(message, quote=False)})
if isinstance(answer, Failure):
return answer
if isinstance(answer, dict) and answer.get("ok") is True:
return None
# Slack answers 200 with `ok` false and a short code, such as `channel_not_found` or `invalid_auth`.
error = answer.get("error") if isinstance(answer, dict) else None
return Failure(f"POST /api/chat.postMessage refused the message: {error if isinstance(error, str) and error else 'no error code'}")
def http_json(method: str, url: str, token: str, body: object) -> object:
"""The JSON that url answers to the bot's request, None where the answer has no body, or a Failure saying why there is none."""
return json_request.http_json(method, url, f"Bearer {token}", body, TIMEOUT, error_message)
def error_message(answer: object) -> str:
"""Slack's error code in the JSON of an error answer; empty where it holds none."""
error = answer.get("error") if isinstance(answer, dict) else None
return error if isinstance(error, str) else ""
+88
View File
@@ -0,0 +1,88 @@
import pathlib
import sys
import tempfile
import unittest
import unittest.mock
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from slack_dm import dm
from failure import Failure
CONFIG = dm.Config("xoxb-secret", "U0123ABCD")
class Slack:
"""Slack's answer to every request, recording each one it gets."""
def __init__(self, answer: object) -> None:
self.answer = answer
self.requests: list[tuple[str, str, str, object]] = []
def __call__(self, method: str, url: str, token: str, body: object) -> object:
self.requests.append((method, url, token, body))
return self.answer
def env_file(folder: str, text: str, mode: int = 0o600) -> pathlib.Path:
path = pathlib.Path(folder) / "slack.env"
path.write_text(text)
path.chmod(mode)
return path
class ReadConfig(unittest.TestCase):
def test_reads_the_token_and_the_recipient_skipping_comments_and_quotes(self):
with tempfile.TemporaryDirectory() as folder:
path = env_file(folder, '# acme\nSLACK_TOKEN="xoxb-secret"\nSLACK_RECIPIENT = U0123ABCD\nOTHER=1\n')
self.assertEqual(dm.read_config(path), CONFIG)
def test_names_each_key_missing_and_refuses_a_file_others_can_read(self):
with tempfile.TemporaryDirectory() as folder:
path = env_file(folder, "SLACK_TOKEN=xoxb-secret\n")
self.assertEqual(dm.read_config(path), Failure(f"{path} lacks SLACK_RECIPIENT"))
path = env_file(folder, "SLACK_TOKEN=t\nSLACK_RECIPIENT=r\n", 0o640)
self.assertEqual(dm.read_config(path), Failure(f"{path} holds the bot's token, so only its owner may read it; run chmod 600 {path}"))
class Send(unittest.TestCase):
def test_posts_the_message_to_the_recipients_member_id_with_the_token(self):
slack = Slack({"ok": True, "ts": "1.2"})
self.assertIsNone(dm.send(CONFIG, "Which one?", slack))
self.assertEqual(slack.requests, [("POST", "https://slack.com/api/chat.postMessage", "xoxb-secret", {"channel": "U0123ABCD", "text": "Which one?"})])
def test_escapes_the_three_characters_slack_reads_as_control_characters(self):
slack = Slack({"ok": True})
self.assertIsNone(dm.send(CONFIG, "Use <b> & [<setting>]?", slack))
self.assertEqual(slack.requests[0][3], {"channel": "U0123ABCD", "text": "Use &lt;b&gt; &amp; [&lt;setting&gt;]?"})
def test_leaves_quotes_as_they_are_since_slack_reads_only_three_characters_as_control(self):
slack = Slack({"ok": True})
self.assertIsNone(dm.send(CONFIG, "Use \"a\" or 'b'?", slack))
self.assertEqual(slack.requests[0][3]["text"], "Use \"a\" or 'b'?")
def test_fails_naming_slacks_error_code_where_slack_answers_ok_false(self):
self.assertEqual(dm.send(CONFIG, "hi", Slack({"ok": False, "error": "invalid_auth"})), Failure("POST /api/chat.postMessage refused the message: invalid_auth"))
def test_fails_on_an_answer_that_says_neither_ok_nor_an_error(self):
for answer in ({}, ["ok"], {"ok": "true"}, {"ok": False, "error": 7}):
with self.subTest(answer=answer):
self.assertEqual(dm.send(CONFIG, "hi", Slack(answer)), Failure("POST /api/chat.postMessage refused the message: no error code"))
def test_passes_on_the_failure_of_the_request_itself(self):
failed = Failure("cannot reach https://slack.com: timed out")
self.assertEqual(dm.send(CONFIG, "hi", Slack(failed)), failed)
class HttpJson(unittest.TestCase):
def test_sends_the_token_as_a_bearer_and_reads_slacks_code_from_an_error(self):
with unittest.mock.patch.object(dm.json_request, "http_json", return_value={"ok": True}) as sent:
self.assertEqual(dm.http_json("POST", "https://slack.com/api/chat.postMessage", "xoxb-secret", {"text": "hi"}), {"ok": True})
sent.assert_called_once_with("POST", "https://slack.com/api/chat.postMessage", "Bearer xoxb-secret", {"text": "hi"}, dm.TIMEOUT, dm.error_message)
for answer, code in (({"error": "ratelimited"}, "ratelimited"), ({"error": 7}, ""), ({}, ""), (["error"], "")):
with self.subTest(answer=answer):
self.assertEqual(dm.error_message(answer), code)
if __name__ == "__main__":
unittest.main()
+5 -4
View File
@@ -9,6 +9,7 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from project_config.test_project_config import configured
from release_plan.test_ranking import DECISIONS, OLD_SHAPE, README, TODO
from project_config.settings import DEFAULT_FLOOR
from release_plan import goals_file, ranking
import rank_todo
@@ -33,9 +34,9 @@ class Main(unittest.TestCase):
self.assertEqual(self.run_main(str(todo)), (0, ""))
self.assertEqual(self.run_main("--check", str(todo)), (0, ""))
pathlib.Path(temp, "README.md").write_bytes(b"\xff")
self.assertEqual(self.run_main(str(todo)), (1, f"{temp}/README.md: not UTF-8\n"))
self.assertEqual(self.run_main(str(todo)), (1, f"cannot read {temp}/README.md: not UTF-8 on line 1\n"))
pathlib.Path(temp, "README.md").unlink()
self.assertEqual(self.run_main(str(todo)), (1, f"{temp}/README.md: not found; rank_todo.py weighs goals from the file the project's config names as goals-and-audience\n"))
self.assertEqual(self.run_main(str(todo)), (1, f"{temp}/README.md: missing or empty; rank_todo.py weighs goals from the goals file the project's config names as goals-and-audience\n"))
todo.unlink()
self.assertEqual(self.run_main(str(todo)), (1, f"{todo}: not found; every project keeps a todo.md, and rank_todo.py --help shows one\n"))
@@ -116,7 +117,7 @@ class Main(unittest.TestCase):
def test_shows_a_valid_file_in_help_and_names_arguments_it_cannot_read(self):
self.assertEqual(self.run_main("--help")[0], 0)
skeleton = "\n".join(line[4:] for line in rank_todo.__doc__.split("\n") if line.startswith(" "))
ranked = ranking.rank(skeleton, "## Goals\n\n1. **Achieve:** Work.\n", "", "")
ranked = ranking.rank(skeleton, "## Goals\n\n1. **Achieve:** Work.\n", "", "", DEFAULT_FLOOR)
self.assertIsInstance(ranked, ranking.Ranked)
self.assertEqual((ranked.under_bar, ranked.notes), ([], []))
self.assertEqual(self.run_main("--fix"), (1, "rank_todo.py: cannot read the arguments --fix; usage: rank_todo.py [--check] [todo.md]\n"))
@@ -124,4 +125,4 @@ class Main(unittest.TestCase):
def test_states_the_goal_weights_the_ranking_computes(self):
for figure in (goals_file.GOAL_STEP, 0.212, 0.188, 0.082, 0.053):
self.assertIn(str(figure), rank_todo.__doc__)
self.assertIn(f"While it is under {goals_file.FLOOR}, or the history holds no scoring run, code health weighs {goals_file.UNDER_FLOOR} times its weight by position, and the other goals keep theirs.", " ".join(rank_todo.__doc__.split()))
self.assertIn(f"While it is under the project's readability floor, or the history holds no scoring run, code health weighs {goals_file.UNDER_FLOOR} times its weight by position, and the other goals keep theirs. The config sets the floor as `readability-floor`, {DEFAULT_FLOOR} where left out.", " ".join(rank_todo.__doc__.split()))
+9 -3
View File
@@ -10,8 +10,8 @@ usage: todo-item list [--release <version>]
todo-item finish <ID> [--changelog <bullet> | --no-changelog]
Run inside a checkout. Every command works on the plan the project's config names, which
`project-config plan` prints: a markdown file, todo.md, or a Jira epic. A plan in a Jira epic is
only read so far: list and show work, and add, edit, move and finish fail. Each command that changes
`project-config plan` prints: a markdown file, todo.md, or a Jira epic. In a Jira epic, list,
show and add work, and edit, move and finish fail so far. Each command that changes
a todo.md ranks it as rank_todo.py does, and so reads the goals file, docs/decisions.md and the
comprehension history, each where the config puts it.
The cells take the format rank_todo.py --help states; the letter flags take upper case too, as --L.
@@ -28,6 +28,11 @@ list and show read only the plan, and print no Score: an item's place in list's
add files the item under the next free ID, with the tagline in bold, and the detail it reads from
stdin, if any. The detail may hold no ## or ### heading.
It prints `Filed item <ID> in <plan>.` It doesn't write anything where ranking fails or scores the item under the bar.
In a Jira epic, add files a Task under the epic, last in the backlog, and <ID> is the new issue's
number. The release must be one of the Jira project's Fix Versions, named as 1.2.0 or v1.2.0 there,
and --exempt security also labels the issue `security`. No bar applies there yet. Where Jira files
the issue and then refuses a --blocked-by link, add still prints `Filed item <ID> …`, and says on
stderr which link to make in Jira.
edit sets the cells whose flag is given and leaves the rest; an empty value, as in --blocked-by "",
empties the cell. --detail replaces the detail with the text on stdin, and --clear-detail removes it.
@@ -45,7 +50,8 @@ mistake. It prints `Finished item <ID> in <plan>.` It doesn't write anything whi
finish <ID> --no-changelog also drops an item no chunk built.
Exit 2 on bad arguments, and 1, saying why, on any other failure. A message opening `not filed:`,
`not edited:`, `not moved:` or `not finished:` means it didn't write anything.
`not edited:`, `not moved:` or `not finished:` means it didn't write anything. The one exception is an add to a
Jira epic that Jira didn't answer or answered brokenly: the message then says the issue may exist.
"""
import argparse
import pathlib
+2 -1
View File
@@ -9,6 +9,7 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent))
from project_config.test_project_config import configured
from release_plan.test_ranking import DECISIONS, README, TODO
from project_config.settings import DEFAULT_FLOOR
from todo_item import edits, main
from failure import Failure
from project_config.main import located
@@ -41,7 +42,7 @@ class TodoItem(unittest.TestCase):
(self.folder / "README.md").write_text(README)
(self.folder / "docs").mkdir()
(self.folder / "docs" / "decisions.md").write_text(DECISIONS)
ranked = ranking.rank(TODO, README, DECISIONS, "")
ranked = ranking.rank(TODO, README, DECISIONS, "", DEFAULT_FLOOR)
assert not isinstance(ranked, ranking.Failure)
self.todo.write_text(ranked.text)
+9
View File
@@ -0,0 +1,9 @@
#!/usr/bin/env python3
import pathlib
import sys
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from touch_predictions import main
sys.exit(main.main(sys.argv[1:]))
View File
+45
View File
@@ -0,0 +1,45 @@
"""Which of a release's items may start chunks beside the next chunk, by what each is predicted to touch."""
import dataclasses
from failure import Failure
from release_plan.todo_table import Item, waiting
from touch_predictions.prediction import LABEL, overlaps, predicted, Touches
@dataclasses.dataclass(frozen=True)
class Beside:
"""The IDs of the items that may start chunks beside first's, in the plan's order, and why each other item may not."""
picked: list[int]
refused: list[str]
def chunks_beside(found: list[Item], first: Item) -> Beside | str | None:
"""The items that may start chunks while first's runs, with why each other item may not. Else why no item may, as a sentence's end; None where no item of first's release that doesn't wait holds a prediction, as in a project that doesn't write any.
An item may where it names first's release, doesn't wait, and overlaps neither first nor an item picked before it in the plan's order. The plan's order decides, not the largest set: a larger set could start a low-ranked item in place of one ranked above it. It cannot know which items first's chunk takes, so chunk-preflight's line tells its reader to leave those out."""
waits = waiting(found, set())
ready = [item for item in found if item.release == first.release and item.id not in waits]
if not any(LABEL in item.detail.splitlines() for item in ready):
return None
ours = predicted(first.detail)
if not isinstance(ours, dict):
return f"item {first.id}'s {unread(ours)}"
taken: dict[int, Touches] = {first.id: ours}
refused = []
for item in ready:
theirs = predicted(item.detail)
if item.id == first.id:
continue
if not isinstance(theirs, dict):
refused.append(f"item {item.id}, whose {unread(theirs)}")
continue
shared = next(((id_, places) for id_, touches in taken.items() if (places := overlaps(theirs, touches))), None)
if shared:
refused.append(f"item {item.id}, which overlaps item {shared[0]} at {', '.join(shared[1])}")
else:
taken[item.id] = theirs
return Beside([id_ for id_ in taken if id_ != first.id], refused)
def unread(prediction: Failure | None) -> str:
return f"detail has no `{LABEL}` list" if prediction is None else f"`{LABEL}` list cannot be read: {prediction.reason}"
+56
View File
@@ -0,0 +1,56 @@
"""The files and parts a diff touched, named as a prediction names them."""
import re
from failure import Failure
from git_cli.git_repo import git, Git
from touch_predictions.prediction import Part, Touches
from touch_predictions.file_parts import part_names
HUNK = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@", re.M)
def touched(base: str, head: str, cwd: str, skipped: set[str], run: Git = git) -> Touches | Failure:
"""What the diff from base to head touched, less the paths in skipped. A file added, deleted or without text hunks is touched whole. A rename reads as a file deleted and one added."""
listed = run("diff", "--no-renames", "--name-status", "-z", base, head, "--", cwd=cwd)
if isinstance(listed, Failure):
return listed
fields = listed.split("\0")
touches: Touches = {}
for status, path in sorted(zip(fields[::2], fields[1::2]), key=lambda pair: pair[1]):
if path in skipped:
continue
parts = modified(base, head, path, cwd, run) if status == "M" else ()
if isinstance(parts, Failure):
return parts
touches[path] = parts
return touches
def modified(base: str, head: str, path: str, cwd: str, run: Git) -> tuple[Part, ...] | Failure:
"""The parts of path whose lines the diff removed, in base's text, or added, in head's; line ranges of head's text where either text has no names. A separator, as file_parts defines it, names its part only where the diff changed no other line."""
diff = run("diff", "--no-renames", "-U0", base, head, "--", path, cwd=cwd, errors="replace")
if isinstance(diff, Failure):
return diff
hunks = [(int(old), int(olds or 1), int(new), int(news or 1)) for old, olds, new, news in HUNK.findall(diff)]
sides = []
for revision, lines in ((base, [line for old, olds, _, _ in hunks for line in range(old, old + olds)]), (head, [line for _, _, new, news in hunks for line in range(new, new + news)])):
text = run("show", f"{revision}:{path}", cwd=cwd, errors="replace")
if isinstance(text, Failure):
return text
sides.append((text, lines))
names = named(path, sides, separators=False) or named(path, sides, separators=True)
if names is None:
# A hunk that only deletes lines counts as the line above them, or as line 1 where it deleted the file's first lines.
return tuple(Part(f"lines {max(new, 1)}-{max(new + max(news, 1) - 1, 1)}") for _, _, new, news in hunks)
return tuple(Part(name) for name in sorted(names))
def named(path: str, sides: list[tuple[str, list[int]]], separators: bool) -> set[str] | None:
"""The parts the lines of each side lie in, each side a text and its lines; None where either text has no names."""
names: set[str] = set()
for text, lines in sides:
found = part_names(path, text, lines, separators)
if found is None:
return None
names |= found
return names
+95
View File
@@ -0,0 +1,95 @@
"""The parts of a file that given lines lie in, by the names a prediction uses for them.
Where each language's boundaries come from:
- Python, a path ending .py: the standard `ast` module. A part is a function or class, named with the classes and functions around it, as in `Plan.branch`; a top-level assignment, by the name it sets; or `(module)` for any other top-level line.
- Markdown, a path ending .md: the heading lines outside fenced code. A part is the nearest heading above, spelt as its line, as in `## Goals`; `(top)` before the first.
- Any other file, and Python that doesn't parse: no names, so diff_parts falls back to line ranges.
A separator is a blank line that Python holds between two statements, or Markdown anywhere. It names no part: git ends the hunk of an inserted function with the blank lines after it, and opens an appended section's with the one before it."""
import ast
import io
import re
import typing
MODULE = "(module)"
TOP = "(top)"
HEADING = re.compile(r"#{1,6} \S")
FENCE = re.compile(r" {0,3}(`{3,}|~{3,})(.*)")
DEFINITION = ast.FunctionDef | ast.AsyncFunctionDef | ast.ClassDef
def part_names(path: str, text: str, lines: typing.Iterable[int], separators: bool = False) -> set[str] | None:
"""The part each of lines, counted from 1, lies in; None where the file's kind has no names. A separator among lines names its part only where separators is set."""
if path.endswith(".py"):
return python_parts(text, lines, separators)
if path.endswith(".md"):
return markdown_parts(text, lines, separators)
return None
def python_parts(text: str, lines: typing.Iterable[int], separators: bool) -> set[str] | None:
try:
tree = ast.parse(text)
except (SyntaxError, ValueError):
return None
# Each top-level statement's first and last line, then each part's with its name.
statements = [(first_line(statement), statement.end_lineno or statement.lineno) for statement in tree.body]
spans = [(*lines_, assigned(statement)) for lines_, statement in zip(statements, tree.body) if not isinstance(statement, DEFINITION)]
spans.extend(nested(tree, ""))
blank = {number for number, row in enumerate(io.StringIO(text), 1) if not row.strip()}
names: set[str] = set()
for line in lines:
if not any(first <= line <= last for first, last in statements):
if line in blank and not separators:
continue
if not statements:
names.add(MODULE)
continue
# A line between two statements, such as a comment, goes with the one below it; one after the last, with the last.
line = min((first for first, _ in statements if first > line), default=statements[-1][0])
names.add(max((span for span in spans if span[0] <= line <= span[1]), key=lambda span: span[0])[2])
return names
def nested(node: ast.AST, prefix: str) -> list[tuple[int, int, str]]:
"""Each function and class under node, at any depth, named from prefix."""
found = []
for child in ast.iter_child_nodes(node):
if isinstance(child, DEFINITION):
found.append((first_line(child), child.end_lineno or child.lineno, prefix + child.name))
found.extend(nested(child, f"{prefix}{child.name}."))
else:
found.extend(nested(child, prefix))
return found
def first_line(statement: ast.stmt) -> int:
"""A statement's first line, which is its first decorator's where it has one."""
return min([statement.lineno, *(decorator.lineno for decorator in getattr(statement, "decorator_list", []))])
def assigned(statement: ast.stmt) -> str:
"""The part a top-level statement that is no function or class makes: the one name it assigns, else the module."""
targets = statement.targets if isinstance(statement, ast.Assign) else [statement.target] if isinstance(statement, ast.AnnAssign) else []
return targets[0].id if len(targets) == 1 and isinstance(targets[0], ast.Name) else MODULE
def markdown_parts(text: str, lines: typing.Iterable[int], separators: bool) -> set[str]:
wanted, names = set(lines), set()
# fence is the run of characters that opened the fenced code a line lies in, and empty outside one.
heading, fence = TOP, ""
for number, line in enumerate(text.splitlines(), 1):
found = FENCE.match(line)
if fence:
# CommonMark: a fence closes on a run of its own character, at least as long, with no text after it.
if found and found.group(1).startswith(fence) and not found.group(2).strip():
fence = ""
elif found:
fence = found.group(1)
elif HEADING.match(line):
heading = line.rstrip()
if number in wanted and (separators or line.strip()):
names.add(heading)
# A line past the end, as a deletion at the end names, lies under the last heading.
return names | ({heading} if any(line > len(text.splitlines()) for line in wanted) else set())
+114
View File
@@ -0,0 +1,114 @@
"""Record what a chunk's items were predicted to touch beside what its branch touched.
usage: touch-predictions record <ID>...
Run it in the chunk's worktree, on the chunk's branch, with every review fix committed and before
`todo-item finish` removes the items; <ID>... are the plan items the chunk takes. It reads each
item's prediction from its detail in the project's plan: the bullets under a `Touches:` line, one
per file, as in
Touches:
- `bin/a.py`: `main`, `Plan.branch` (small)
- `README.md`: `## Goals`
- `bin/run.sh`: lines 10-20
- `docs/new.md`
A path alone is the whole file, and (small) marks a part the item changes only a little. A path or
a name that holds a backtick takes a longer run of backticks with a space inside each end, as a
Markdown code span does: `` ## The `foo` tool ``. It names what the branch touched the same way,
from the diff between the branch's merge base with the default branch and HEAD:
- in a .py file, by Python's `ast` module: the innermost function or class a changed line lies in,
named with those around it; a top-level assignment by the name it sets; `(module)` for any other
top-level line. A comment between two statements goes with the one below it;
- in a .md file, by the nearest heading above the line, outside fenced code, spelt as its line;
`(top)` before the first heading;
- in any other file, and in Python that doesn't parse, by the line ranges the diff changed, as they
stand at HEAD;
- a file the branch added or deleted, or changed without text hunks, as the path alone. A rename
reads as a file deleted and one added.
A changed blank line names no part where the file has other changed lines, unless it lies inside a
Python statement.
It leaves out the plan and the project's records, which every chunk writes. It appends
`## Chunk <IDs>, <UTC time>, at <commit>`, the IDs in rising order, with both lists to the record
the project's config names as `touch-predictions`, in place of an entry the record already holds
for the same items. Commit the record with the chunk. Where the config leaves the setting out, it
says so and exits 0.
Exit 1, saying why: on any other arguments; when no config names the checkout; when the plan or
the record cannot be read or written; when the plan holds no item <ID>; when a `Touches:` list
cannot be read; or when git cannot name the merge base or the diff.
"""
import sys
import time
from git_cli.git_repo import default_ref, git
from failure import Failure
from plan_store.stores import store as plan_store
from touch_predictions.prediction import predicted, together, Touches
from project_config.main import project
from project_config.settings import ProjectConfig, TOUCH_PREDICTIONS
from touch_predictions import record
from record_store.stores import RECORDS, touch_predictions_store
from touch_predictions.diff_parts import touched
from text_files.utc_stamp import utc
def main(argv: list[str]) -> int:
if argv[:1] in (["-h"], ["--help"]):
print(__doc__.strip())
return 0
if argv[:1] != ["record"] or len(argv) < 2 or not all(id_.isascii() and id_.isdigit() for id_ in argv[1:]):
print("usage: touch-predictions record <ID>...", file=sys.stderr)
return 1
config = project()
done = config if isinstance(config, Failure) else recorded(config, sorted({int(id_) for id_ in argv[1:]}))
if isinstance(done, Failure):
print(f"touch-predictions: {done.reason}", file=sys.stderr)
return 1
print(done)
return 0
def recorded(config: ProjectConfig, ids: list[int]) -> str | Failure:
"""Appends the entry of the chunk that takes the items ids, and says so; or says that the project keeps no record."""
store = touch_predictions_store(config)
if store is None:
return f"The project's config sets no `{TOUCH_PREDICTIONS}`, so nothing is recorded."
prediction = predictions(config, ids)
if isinstance(prediction, Failure):
return prediction
cwd = str(config.top)
default = default_ref(cwd)
base = default if isinstance(default, Failure) else git("merge-base", default, "HEAD", cwd=cwd)
head = base if isinstance(base, Failure) else git("rev-parse", "--short", "HEAD", cwd=cwd)
if isinstance(base, Failure) or isinstance(head, Failure):
return head if isinstance(head, Failure) else base
# Every chunk writes the plan and the records, so they are left out of what a chunk touched.
skipped = {path for name in ("plan", *RECORDS, TOUCH_PREDICTIONS) if (path := config.tracked(name))}
touches = touched(base.strip(), "HEAD", cwd, skipped)
if isinstance(touches, Failure):
return touches
failed = record.append(store, ids, record.entry(ids, utc(time.time()), head.strip(), prediction, touches))
return failed or f"Recorded what chunk {', '.join(map(str, ids))} was predicted to touch, and what it touched, in {store.label}."
def predictions(config: ProjectConfig, ids: list[int]) -> Touches | None | Failure:
"""What the items ids predict between them; None where none of them predicts anything."""
plan = plan_store(config).read()
if isinstance(plan, Failure):
return plan
details = {item.id: item.detail for item in plan.items}
found = []
for id_ in ids:
if id_ not in details:
return Failure(f"the plan holds no item {id_}")
prediction = predicted(details[id_])
if isinstance(prediction, Failure):
return Failure(f"item {id_}: {prediction.reason}")
if prediction is not None:
found.append(prediction)
return together(found) if found else None
+148
View File
@@ -0,0 +1,148 @@
"""An item's prediction of the files and parts it will touch, as its detail spells it, and where two predictions overlap.
The spelling, which the decision `todo.md: an item of the next release predicts the files and parts it will touch …` gives the reasons for:
Touches:
- `bin/a.py`: `main`, `Plan.branch` (small)
- `bin/run.sh`: lines 10-20
- `docs/new.md`
A path alone is the whole file, and (small) marks a part the item changes only a little. file_parts says how a part is named.
A path or a name that holds a backtick is spelt as a Markdown code span that holds one: in a longer run of backticks than any it holds, with a space inside each end, as in `` ## The `foo` tool ``. So every path and name on one line has a spelling."""
import dataclasses
import re
from failure import Failure
LABEL = "Touches:"
SMALL = " (small)"
RANGE = re.compile(r"lines (\d+)-(\d+)")
BACKTICKS = re.compile(r"`+")
@dataclasses.dataclass(frozen=True)
class Part:
"""A part of a file, by the name file_parts gives it or as `lines <first>-<last>`; small where the item changes it only a little."""
name: str
small: bool = False
# Each file's parts by its path; no parts where the whole file is touched.
Touches = dict[str, tuple[Part, ...]]
def predicted(detail: str) -> Touches | None | Failure:
"""The prediction in an item's detail: the bullets under its `Touches:` line, up to the first other text. None where the detail has no such line."""
lines = detail.splitlines()
if LABEL not in lines:
return None
touches: Touches = {}
for line in lines[lines.index(LABEL) + 1:]:
if not line.strip():
continue
if not line.startswith("- "):
break
read = bullet(line)
if read is None:
return Failure(f"the bullet {line!r} under `{LABEL}` is not a path in backticks, then optionally a colon and its parts, each a name in backticks or `lines <first>-<last>`, and optionally `{SMALL}`")
if any(span and span[0] > span[1] for span in map(line_range, read[1])):
return Failure(f"the bullet {line!r} under `{LABEL}` holds a line range whose first line comes after its last")
touches = together([touches, {read[0]: read[1]}])
return touches or Failure(f"no bullet follows `{LABEL}`")
def bullet(line: str) -> tuple[str, tuple[Part, ...]] | None:
"""The path and the parts a bullet names; None where it is not spelt as one."""
path = code_span(line, len("- "))
if path is None:
return None
parts = []
at, separator = path[1], ": "
while at < len(line):
if not line.startswith(separator, at):
return None
found = RANGE.match(line, at + len(separator))
part = (found.group(), found.end()) if found else code_span(line, at + len(separator))
if part is None:
return None
small = line.startswith(SMALL, part[1])
parts.append(Part(part[0], small))
at, separator = part[1] + len(SMALL) * small, ", "
return path[0], tuple(parts)
def code_span(line: str, at: int) -> tuple[str, int] | None:
"""The text of the code span that opens at index at of line, and the index after it; None where none does. The span ends at the next run of as many backticks as open it."""
opened = BACKTICKS.match(line, at)
run = opened.group() if opened else ""
closed = re.search(rf"(?<!`){run}(?!`)", line[opened.end():]) if opened else None
if opened is None or closed is None:
return None
text = line[opened.end():opened.end() + closed.start()]
if len(run) > 1:
# A longer run holds a space inside each end, which keeps a backtick at either end of the text apart from the run.
if len(text) < 3 or not text.startswith(" ") or not text.endswith(" "):
return None
text = text[1:-1]
return (text, opened.end() + closed.end()) if text else None
def rendered(touches: Touches) -> str:
"""touches as the bullets predicted reads."""
return "\n".join(f"- {code(path)}" + (": " + ", ".join(shown(part) + SMALL * part.small for part in parts) if parts else "") for path, parts in touches.items())
def shown(part: Part) -> str:
return part.name if line_range(part) else code(part.name)
def code(text: str) -> str:
"""text as the code span code_span reads."""
if "`" not in text:
return f"`{text}`"
run = "`" * (1 + max(map(len, BACKTICKS.findall(text))))
return f"{run} {text} {run}"
def line_range(part: Part) -> tuple[int, int] | None:
found = RANGE.fullmatch(part.name)
return (int(found.group(1)), int(found.group(2))) if found else None
def together(several: list[Touches]) -> Touches:
"""What several predictions touch between them. A file one of them touches whole is touched whole, and a part is small only where each that names it says so."""
joined: dict[str, dict[str, bool] | None] = {}
for touches in several:
for path, parts in touches.items():
held = joined.setdefault(path, {})
if held is None or not parts:
joined[path] = None
continue
for part in parts:
held[part.name] = held.get(part.name, True) and part.small
return {path: tuple(Part(name, small) for name, small in held.items()) if held else () for path, held in joined.items()}
def overlaps(ours: Touches, theirs: Touches) -> list[str]:
"""Each place both touch: a file either touches whole, by its path alone, and else each part as ours names it. A part either side marks small is left out: a conflict there is cheap to settle, and a chunk that waits costs hours."""
found = []
for path, parts in ours.items():
if path not in theirs:
continue
if not parts or not theirs[path]:
found.append(f"`{path}`")
continue
found.extend(f"`{path}` {shown(part)}" for part in parts if any(same_part(part, other) and not (part.small or other.small) for other in theirs[path]))
return found
def same_part(one: Part, other: Part) -> bool:
"""Whether two parts of one file share lines, as far as their names tell: line ranges that share a line, a line range and a name, since the name doesn't say which lines it holds, equal names, or a class and what it holds."""
spans = line_range(one), line_range(other)
if spans[0] and spans[1]:
return spans[0][0] <= spans[1][1] and spans[1][0] <= spans[0][1]
if spans[0] or spans[1]:
return True
return one.name == other.name or one.name.startswith(f"{other.name}.") or other.name.startswith(f"{one.name}.")
+27
View File
@@ -0,0 +1,27 @@
"""The touch-predictions record: one entry per chunk, its prediction beside what its diff touched."""
import re
from failure import Failure
from record_store.stores import RecordStore
from touch_predictions.prediction import rendered, Touches
from text_files.utc_stamp import STAMPED
TITLE = "# Touch predictions"
def entry(items: list[int], at: str, head: str, predicted: Touches | None, touched: Touches) -> str:
"""A chunk's entry: the items it took, the UTC time at, the short commit its diff ends at, and both lists in a prediction's spelling. predicted is None where no item predicted anything."""
return f"## Chunk {', '.join(map(str, items))}, {at}, at {head}\n\n{listed('Predicted', predicted)}\n\n{listed('Touched', touched)}\n"
def listed(label: str, touches: Touches | None) -> str:
return f"{label}:\n\n{rendered(touches)}" if touches else f"{label}: none."
def append(store: RecordStore, items: list[int], text: str) -> Failure | None:
"""Appends text, the entry of the chunk that took items, in place of each entry the record holds for the same items: a fix after the first entry changes what the chunk touched."""
held = store.read()
if isinstance(held, Failure):
return held
kept = re.sub(rf"^## Chunk {', '.join(map(str, items))}, {STAMPED},.*?(?=^## |\Z)", "", held, flags=re.M | re.S)
return store.write(f"{kept.rstrip() or TITLE}\n\n{text}")
@@ -0,0 +1,489 @@
import os
import pathlib
import re
import subprocess
import sys
import tempfile
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from touch_predictions.beside import Beside, chunks_beside
from touch_predictions import diff_parts, file_parts, record
from failure import Failure
from test_env import isolated_env
from record_store.fakes import MemoryStore
from touch_predictions.prediction import overlaps, Part, predicted, rendered, together
from plan_store.stores import plan_of
from project_config.test_project_config import write_config
DETAIL = """A planning call.
Touches:
- `bin/a.py`: `main`, `Plan.branch` (small)
- `README.md`: `## Goals, and (more): things`
- `bin/run.sh`: lines 10-20
- `docs/new.md`
More prose, with `bin/b.py` named.
"""
PYTHON = """\"\"\"Docstring.\"\"\"
import os
LIMIT = 3
# A comment that belongs to first.
def first():
return 1
class Plan:
size: int = 0
@property
def branch(self):
def inner():
return 2
return inner()
if os.name:
pass
"""
MARKDOWN = """Intro.
# Title
Text.
```
## Not a heading
```
## Goals
1. One.
"""
class PredictedTest(unittest.TestCase):
def test_reads_each_bullet_of_the_touches_list(self) -> None:
self.assertEqual(predicted(DETAIL), {
"bin/a.py": (Part("main"), Part("Plan.branch", small=True)),
"README.md": (Part("## Goals, and (more): things"),),
"bin/run.sh": (Part("lines 10-20"),),
"docs/new.md": (),
})
def test_a_detail_without_the_list_predicts_nothing(self) -> None:
self.assertIsNone(predicted("Only prose, with `bin/a.py` named."))
def test_a_bullet_it_cannot_read_is_a_failure_that_quotes_it(self) -> None:
for bullet in ("- bin/a.py: main", "- `bin/a.py`: main", "- `bin/a.py`: lines 20-10", "- `bin/a.py`: `main` `other`"):
with self.subTest(bullet):
found = predicted(f"Touches:\n\n{bullet}\n")
assert isinstance(found, Failure)
self.assertIn(bullet, found.reason)
def test_an_empty_list_is_a_failure(self) -> None:
self.assertIsInstance(predicted("Touches:\n\nProse.\n"), Failure)
found = predicted("Touches:\n")
assert isinstance(found, Failure)
self.assertEqual(found.reason, "no bullet follows `Touches:`")
def test_reads_a_list_right_under_its_label_a_one_line_range_and_a_name_of_any_letters(self) -> None:
self.assertEqual(predicted("Touches:\n- `a.py`: `Xray`, lines 5-5\n"), {"a.py": (Part("Xray"), Part("lines 5-5"))})
def test_rendered_reads_back(self) -> None:
touches = predicted(DETAIL)
assert isinstance(touches, dict)
self.assertEqual(predicted(f"Touches:\n\n{rendered(touches)}\n"), touches)
def test_a_name_that_holds_backticks_takes_a_longer_run_with_a_space_inside_each_end(self) -> None:
self.assertEqual(predicted("Touches:\n- `a.md`: `` ## The `foo` tool `` (small), ``` `` ```, `` `x` ``\n"), {"a.md": (Part("## The `foo` tool", small=True), Part("``"), Part("`x`"))})
self.assertEqual(rendered({"a.md": (Part("## The `foo` tool", small=True), Part("``"))}), "- `a.md`: `` ## The `foo` tool `` (small), ``` `` ```")
def test_a_name_ends_only_at_a_run_as_long_as_the_one_that_opens_it(self) -> None:
self.assertEqual(predicted("Touches:\n- `a.md`: `` a ``` b ``, `c``d`\n"), {"a.md": (Part("a ``` b"), Part("c``d"))})
def test_a_path_holds_any_character_and_a_single_backtick_keeps_a_names_spaces(self) -> None:
self.assertEqual(predicted("Touches:\n- `my file.md`: ` x `\n- `` a`b.md ``\n"), {"my file.md": (Part(" x "),), "a`b.md": ()})
def test_rendered_reads_back_whatever_a_path_or_a_name_holds(self) -> None:
touches = {"my file.md": (Part("## todo.md: under `Touches:` in its detail"), Part("## ``a`` and `b`", small=True), Part("`"), Part("## ends in `x`"), Part(" x "), Part("lines 2-3")), "a`b.md": (), "c, d: e.md": (Part("# T"),)}
self.assertEqual(predicted(f"Touches:\n\n{rendered(touches)}\n"), touches)
def test_a_longer_run_without_its_spaces_or_its_end_or_a_name_is_a_failure(self) -> None:
for bullet in ("- `a.md`: ``## A``", "- `a.md`: `` ## A", "- `a.md`: `` ## A `", "- `a.md`: `` ``", "- `a.md`: ", "- `a.md`:", "- `a.md`: `f`, ", "- `a.md`: `f`,`g`", "- ``", "- `a.md` (small)", "- `a.md`: `f` (small) (small)"):
with self.subTest(bullet):
self.assertIsInstance(predicted(f"Touches:\n\n{bullet}\n"), Failure)
def test_a_range_that_runs_backwards_is_a_failure_that_says_so(self) -> None:
found = predicted("Touches:\n\n- `bin/a.py`: `f`, lines 20-10\n")
assert isinstance(found, Failure)
self.assertEqual(found.reason, "the bullet '- `bin/a.py`: `f`, lines 20-10' under `Touches:` holds a line range whose first line comes after its last")
def test_together_joins_items_and_keeps_small_only_where_each_says_so(self) -> None:
joined = together([{"a.py": (Part("f", small=True), Part("g", small=True))}, {"a.py": (Part("f"),), "b.md": ()}, {"b.md": (Part("# T"),)}])
self.assertEqual(joined, {"a.py": (Part("f"), Part("g", small=True)), "b.md": ()})
def test_together_keeps_a_part_not_small_once_one_says_so_and_reads_on_past_a_whole_file(self) -> None:
joined = together([{"a.py": (Part("f"),), "b.md": ()}, {"b.md": (Part("# T"),), "a.py": (Part("f", small=True),), "c.py": (Part("h"),)}])
self.assertEqual(joined, {"a.py": (Part("f"),), "b.md": (), "c.py": (Part("h"),)})
class OverlapsTest(unittest.TestCase):
def test_other_files_and_other_parts_do_not_overlap(self) -> None:
self.assertEqual(overlaps({"a.py": (Part("f"),)}, {"a.py": (Part("g"),), "b.py": ()}), [])
def test_the_same_part_overlaps(self) -> None:
self.assertEqual(overlaps({"a.py": (Part("f"), Part("g"))}, {"a.py": (Part("g"),)}), ["`a.py` `g`"])
def test_a_class_overlaps_its_method_but_not_a_name_it_only_starts(self) -> None:
self.assertEqual(overlaps({"a.py": (Part("Plan"),)}, {"a.py": (Part("Plan.branch"), Part("Planned"))}), ["`a.py` `Plan`"])
def test_a_whole_file_overlaps_any_part_of_it(self) -> None:
self.assertEqual(overlaps({"a.py": ()}, {"a.py": (Part("g", small=True),)}), ["`a.py`"])
def test_reads_on_past_a_file_only_one_touches_and_past_a_whole_file(self) -> None:
theirs = {"a.py": (), "b.py": (Part("g"),)}
self.assertEqual(overlaps({"z.py": (Part("f"),), "a.py": (), "b.py": (Part("g"),)}, theirs), ["`a.py`", "`b.py` `g`"])
def test_line_ranges_overlap_where_they_share_a_line(self) -> None:
self.assertEqual(overlaps({"x.sh": (Part("lines 1-10"),)}, {"x.sh": (Part("lines 10-12"),)}), ["`x.sh` lines 1-10"])
self.assertEqual(overlaps({"x.sh": (Part("lines 1-9"),)}, {"x.sh": (Part("lines 10-12"),)}), [])
self.assertEqual(overlaps({"x.sh": (Part("lines 10-12"),)}, {"x.sh": (Part("lines 1-10"),)}), ["`x.sh` lines 10-12"])
self.assertEqual(overlaps({"x.sh": (Part("lines 11-12"),)}, {"x.sh": (Part("lines 1-10"),)}), [])
def test_a_line_range_overlaps_a_named_part_since_nothing_tells_them_apart(self) -> None:
self.assertEqual(overlaps({"a.py": (Part("lines 1-9"),)}, {"a.py": (Part("f"),)}), ["`a.py` lines 1-9"])
self.assertEqual(overlaps({"a.py": (Part("f"),)}, {"a.py": (Part("lines 1-9"),)}), ["`a.py` `f`"])
def test_a_small_change_on_either_side_is_taken(self) -> None:
self.assertEqual(overlaps({"a.py": (Part("f", small=True),)}, {"a.py": (Part("f"),)}), [])
self.assertEqual(overlaps({"a.py": (Part("f"),)}, {"a.py": (Part("f", small=True),)}), [])
class FilePartsTest(unittest.TestCase):
def names(self, path: str, text: str, *lines: int) -> set[str] | None:
return file_parts.part_names(path, text, lines)
def test_python_names_the_innermost_function_or_class(self) -> None:
self.assertEqual(self.names("a.py", PYTHON, 9), {"first"})
self.assertEqual(self.names("a.py", PYTHON, 13), {"Plan"})
self.assertEqual(self.names("a.py", PYTHON, 15, 18), {"Plan.branch", "Plan.branch.inner"})
def test_python_names_a_top_level_assignment_and_calls_the_rest_the_module(self) -> None:
self.assertEqual(self.names("a.py", PYTHON, 4), {"LIMIT"})
self.assertEqual(self.names("a.py", PYTHON, 1, 2, 22), {"(module)"})
def test_python_gives_a_line_between_statements_to_the_next_one(self) -> None:
self.assertEqual(self.names("a.py", PYTHON, 7), {"first"})
self.assertEqual(self.names("a.py", PYTHON, 99), {"(module)"})
self.assertEqual(self.names("a.py", "", 1), {"(module)"})
def test_python_names_no_part_for_a_blank_line_between_statements(self) -> None:
text = "def a():\n\treturn 1\n\n\ndef b():\n\treturn 2\n\n# end\n\n"
self.assertEqual(self.names("a.py", text, 1, 2, 3, 4), {"a"})
self.assertEqual(self.names("a.py", text, 3, 4), set())
self.assertEqual(self.names("a.py", text, 7, 9), set())
self.assertEqual(self.names("a.py", text, 8), {"b"})
self.assertEqual(self.names("a.py", "# only\n\n", 2), set())
def test_python_names_the_part_a_blank_line_inside_a_statement_lies_in(self) -> None:
self.assertEqual(self.names("a.py", "def a():\n\tx = 1\n\n\treturn x\n\nT = \"\"\"\n\n\"\"\"\n", 3, 7), {"a", "T"})
def test_blank_lines_name_their_parts_where_separators_count(self) -> None:
text = "def a():\n\treturn 1\n\n\ndef b():\n\treturn 2\n\n"
self.assertEqual(file_parts.part_names("a.py", text, [3, 7], separators=True), {"b"})
self.assertEqual(file_parts.part_names("a.py", "# only\n\n", [2], separators=True), {"(module)"})
self.assertEqual(file_parts.part_names("a.md", "# A\n\n", [2], separators=True), {"# A"})
def test_python_without_statements_names_the_module_only_for_a_line(self) -> None:
self.assertEqual(self.names("a.py", ""), set())
self.assertEqual(self.names("a.py", "# only a comment\n"), set())
self.assertEqual(self.names("a.py", "# only a comment\n", 1), {"(module)"})
def test_python_that_does_not_parse_has_no_names(self) -> None:
self.assertIsNone(self.names("a.py", "def (:\n", 1))
def test_python_names_a_function_under_another_statement_and_an_annotated_assignment(self) -> None:
text = "if True:\n\tdef f():\n\t\treturn 1\n\nclass C:\n\tif True:\n\t\tdef m(self):\n\t\t\treturn 2\n\nX: int = 1\n"
self.assertEqual(self.names("a.py", text, 3, 8, 10), {"f", "C.m", "X"})
def test_python_gives_a_line_after_the_last_statement_to_it(self) -> None:
self.assertEqual(self.names("a.py", "A = 1\nB = 2\nC = 3\n# end\n", 4), {"C"})
self.assertEqual(self.names("a.py", "class A:\n\tdef f(self):\n\t\tpass\n\n# end\n", 5), {"A"})
def test_markdown_drops_a_headings_trailing_space_and_puts_a_line_past_the_end_under_the_last_heading(self) -> None:
self.assertEqual(self.names("a.md", "# A \ntext\n## B\n", 2, 4), {"# A", "## B"})
def test_markdown_names_the_heading_above_and_skips_fenced_lines(self) -> None:
self.assertEqual(self.names("a.md", MARKDOWN, 1), {"(top)"})
self.assertEqual(self.names("a.md", MARKDOWN, 3, 5, 8), {"# Title"})
self.assertEqual(self.names("a.md", MARKDOWN, 13), {"## Goals"})
def test_markdown_names_no_part_for_a_blank_line(self) -> None:
self.assertEqual(self.names("a.md", "# A\ntext\n\n## End\nmore\n", 3, 4, 5), {"## End"})
self.assertEqual(self.names("a.md", "# A\n \t\n", 2), set())
def test_markdown_closes_a_fence_only_on_its_own_character_at_least_as_long(self) -> None:
self.assertEqual(self.names("a.md", "# A\n````\n```\n# not\n````\n# B\ntext\n", 4, 7), {"# A", "# B"})
self.assertEqual(self.names("a.md", "# A\n```\n~~~\n# not\n```\n# B\ntext\n", 4, 7), {"# A", "# B"})
self.assertEqual(self.names("a.md", "# A\n~~~\n~~~ not the end\n# not\n~~~~~ \n# B\ntext\n", 4, 7), {"# A", "# B"})
def test_any_other_file_has_no_names(self) -> None:
self.assertIsNone(self.names("run.sh", "echo\n", 1))
def plan(*items: tuple[int, str, str, str]) -> list:
"""A plan's items, each given as its ID, release, the IDs that block it and the bullets of its prediction, none for an item without one."""
rows = "".join(f"| {id_} | {release} | {blocked} | | **Do {id_}.** | 1 | 1 | 1 | 1 | 1 | 1 by 1 | 10.0 |\n" for id_, release, blocked, _ in items)
details = "".join(f"### {id_}. Do {id_}.\n\nTouches:\n\n{bullets}\n\n" for id_, _, _, bullets in items if bullets)
found = plan_of(f"# todo\n\n## Scoring\n\n`Score = 100 * V / (2**S + 8)`\n\n`Bar = 0.1`\n\n`Next ID = 99`\n\n## Items\n\n| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |\n|---|---|---|---|---|---|---|---|---|---|---|---|\n{rows}\n## Details\n\n{details}")
assert not isinstance(found, Failure), found
return found.items
class ChunksBesideTest(unittest.TestCase):
def test_picks_in_the_plans_order_each_item_that_overlaps_none_before_it(self) -> None:
items = plan((1, "0.2.0", "", "- `a.py`: `f`"), (2, "0.2.0", "", "- `a.py`: `g`\n- `b.py`"), (3, "0.2.0", "", "- `b.py`: `h`"), (4, "0.2.0", "", "- `a.py`: `f`"), (5, "0.2.0", "", "- `c.py`"))
self.assertEqual(chunks_beside(items, items[0]), Beside([2, 5], ["item 3, which overlaps item 2 at `b.py`", "item 4, which overlaps item 1 at `a.py` `f`"]))
def test_leaves_out_an_item_that_waits_or_names_a_later_release(self) -> None:
items = plan((1, "0.2.0", "", "- `a.py`"), (2, "0.2.0", "1", "- `b.py`"), (3, "0.3.0", "", "- `c.py`"))
self.assertEqual(chunks_beside(items, items[0]), Beside([], []))
def test_refuses_an_item_without_a_prediction_it_can_read(self) -> None:
items = plan((1, "0.2.0", "", "- `a.py`"), (2, "0.2.0", "", ""), (3, "0.2.0", "", "- b.py"))
found = chunks_beside(items, items[0])
assert isinstance(found, Beside)
self.assertEqual(found.picked, [])
self.assertEqual(found.refused[0], "item 2, whose detail has no `Touches:` list")
self.assertTrue(found.refused[1].startswith("item 3, whose `Touches:` list cannot be read: the bullet '- b.py'"))
def test_no_item_starts_beside_one_that_predicts_nothing(self) -> None:
items = plan((1, "0.2.0", "", ""), (2, "0.2.0", "", "- `b.py`"))
self.assertEqual(chunks_beside(items, items[0]), "item 1's detail has no `Touches:` list")
items = plan((1, "0.2.0", "", "- a.py"), (2, "0.2.0", "", "- `b.py`"))
found = chunks_beside(items, items[0])
assert isinstance(found, str)
self.assertTrue(found.startswith("item 1's `Touches:` list cannot be read: the bullet '- a.py'"), found)
def test_names_each_place_an_item_overlaps(self) -> None:
items = plan((1, "0.2.0", "", "- `a.py`: `f`, `g`"), (2, "0.2.0", "", "- `a.py`: `f`, `g`"))
self.assertEqual(chunks_beside(items, items[0]), Beside([], ["item 2, which overlaps item 1 at `a.py` `f`, `a.py` `g`"]))
def test_says_nothing_where_no_item_predicts(self) -> None:
items = plan((1, "0.2.0", "", ""), (2, "0.2.0", "", ""), (3, "0.3.0", "", "- `c.py`"))
self.assertIsNone(chunks_beside(items, items[0]))
class Repo:
"""A git checkout in a temporary folder."""
def __init__(self, folder: str) -> None:
self.folder = folder
self.run("init", "-q", "-b", "main")
def run(self, *args: str) -> str:
return subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", *args], cwd=self.folder, check=True, capture_output=True, text=True).stdout.strip()
def commit(self, files: dict[str, str | bytes | None]) -> str:
for name, text in files.items():
path = pathlib.Path(self.folder, name)
if text is None:
path.unlink()
elif isinstance(text, bytes):
path.write_bytes(text)
else:
path.write_text(text, encoding="utf-8")
self.run("add", "-A")
self.run("commit", "-qm", "x")
return self.run("rev-parse", "HEAD")
class TouchedTest(unittest.TestCase):
def setUp(self) -> None:
folder = tempfile.TemporaryDirectory()
self.addCleanup(folder.cleanup)
self.repo = Repo(folder.name)
self.base = self.repo.commit({"a.py": PYTHON, "a.md": MARKDOWN, "run.sh": "one\ntwo\nthree\nfour\n", "gone.py": "x = 1\n", "todo.md": "plan\n", "blob.bin": b"\x00\x01"})
def touched(self, files: dict[str, str | bytes | None], *skipped: str) -> object:
return diff_parts.touched(self.base, self.repo.commit(files), self.repo.folder, set(skipped))
def test_names_the_parts_of_changed_lines_on_both_sides(self) -> None:
changed = PYTHON.replace("\treturn 1\n", "\treturn 3\n").replace("LIMIT = 3\n", "").replace("\tpass\n", "\tpass\n\n\ndef last():\n\tpass\n")
self.assertEqual(self.touched({"a.py": changed, "a.md": MARKDOWN + "2. Two.\n"}), {
"a.md": (Part("## Goals"),),
"a.py": (Part("LIMIT"), Part("first"), Part("last")),
})
def test_an_added_or_deleted_file_is_touched_whole(self) -> None:
self.assertEqual(self.touched({"new.py": "y = 2\n", "gone.py": None}), {"gone.py": (), "new.py": ()})
def test_a_file_without_names_falls_back_to_the_new_sides_line_ranges(self) -> None:
self.assertEqual(self.touched({"run.sh": "one\n2\n3\nfour\nfive\n"}), {"run.sh": (Part("lines 2-3"), Part("lines 5-5"))})
def test_a_deletion_falls_back_to_the_line_it_left(self) -> None:
self.assertEqual(self.touched({"run.sh": "one\nfour\n"}), {"run.sh": (Part("lines 1-1"),)})
def test_a_binary_file_is_touched_whole(self) -> None:
self.assertEqual(self.touched({"blob.bin": b"\x00\x02"}), {"blob.bin": ()})
def test_python_that_stops_parsing_falls_back_to_line_ranges(self) -> None:
self.assertEqual(self.touched({"gone.py": "def (:\n"}), {"gone.py": (Part("lines 1-1"),)})
def test_skipped_paths_do_not_count(self) -> None:
self.assertEqual(self.touched({"todo.md": "plan\nmore\n", "gone.py": "x = 2\n"}, "todo.md"), {"gone.py": (Part("x"),)})
def test_reads_on_past_a_skipped_path(self) -> None:
self.assertEqual(self.touched({"a.md": "# New\n", "gone.py": "x = 3\n"}, "a.md"), {"gone.py": (Part("x"),)})
def test_a_renamed_file_is_one_deleted_and_one_added(self) -> None:
self.repo.run("mv", "a.py", "b.py")
self.assertEqual(self.touched({}), {"a.py": (), "b.py": ()})
def test_lists_the_paths_in_order_whatever_happened_to_each(self) -> None:
found = self.touched({"z.py": "y = 2\n", "gone.py": "x = 2\n"})
assert isinstance(found, dict)
self.assertEqual(list(found), ["gone.py", "z.py"])
def test_reads_the_diff_up_to_head_and_no_later(self) -> None:
head = self.repo.commit({"gone.py": "x = 2\n"})
self.repo.commit({"gone.py": "x = 2\ny = 3\n", "run.sh": "one\n"})
self.assertEqual(diff_parts.touched(self.base, head, self.repo.folder, set()), {"gone.py": (Part("x"),)})
def test_reads_the_diff_up_to_head_whatever_the_work_tree_holds(self) -> None:
text = "def f():\n\treturn 1\n\n\ndef g():\n\treturn 2\n"
self.base = self.repo.commit({"gone.py": text})
head = self.repo.commit({"gone.py": text.replace("return 2", "return 3")})
pathlib.Path(self.repo.folder, "gone.py").write_text("def new():\n\treturn 0\n\n\n" + text.replace("return 2", "return 3"), encoding="utf-8")
self.assertEqual(diff_parts.touched(self.base, head, self.repo.folder, set()), {"gone.py": (Part("g"),)})
def test_an_inserted_function_or_section_does_not_name_its_neighbours(self) -> None:
text = "def a():\n\treturn 1\n\n\ndef b():\n\treturn 2\n\n\ndef c():\n\treturn 3\n"
self.base = self.repo.commit({"m.py": text, "m.md": "# A\ntext\n\n## B\ntext\n", "pkg.py": "", "c.py": "# only a comment\n"})
self.assertEqual(self.touched({"m.py": text.replace("def b", "def new():\n\treturn 9\n\n\ndef b"), "m.md": "# A\ntext\n\n## B\ntext\n\n## End\nmore\n", "pkg.py": "def f():\n\treturn 1\n", "c.py": "# only a comment\n\n\ndef g():\n\treturn 1\n"}), {
"c.py": (Part("g"),),
"m.md": (Part("## End"),),
"m.py": (Part("new"),),
"pkg.py": (Part("f"),),
})
def test_a_deleted_function_does_not_name_the_next_one(self) -> None:
text = "def a():\n\treturn 1\n\n\ndef b():\n\treturn 2\n\n\ndef c():\n\treturn 3\n"
self.base = self.repo.commit({"m.py": text})
self.assertEqual(self.touched({"m.py": text.replace("def b():\n\treturn 2\n\n\n", "")}), {"m.py": (Part("b"),)})
def test_a_change_of_blank_lines_alone_names_the_part_they_go_with(self) -> None:
self.assertEqual(self.touched({"a.py": PYTHON.replace("\n\nclass Plan", "\n\n\nclass Plan"), "a.md": MARKDOWN.replace("Text.\n", "Text.\n\n")}), {"a.md": (Part("# Title"),), "a.py": (Part("Plan"),)})
def test_reads_text_that_is_not_utf_8(self) -> None:
self.repo.commit({"n.md": b"# T\ncaf\xe9\n"})
self.base = self.repo.run("rev-parse", "HEAD")
self.assertEqual(self.touched({"n.md": b"# T\ncaf\xe9s\n"}), {"n.md": (Part("# T"),)})
def test_an_unknown_base_is_a_failure(self) -> None:
self.assertIsInstance(diff_parts.touched("nope", "HEAD", self.repo.folder, set()), Failure)
class EntryTest(unittest.TestCase):
def test_appends_the_prediction_beside_the_touched_parts(self) -> None:
store = MemoryStore("# Touch predictions\n\n## Chunk 1, 2026-01-01T00:00:00Z, at aaaaaaa\n\nPredicted: none.\n\nTouched: none.\n")
failed = record.append(store, [373, 374], record.entry([373, 374], "2026-11-15T10:00:00Z", "abc1234", {"a.py": (Part("f", small=True),)}, {"a.py": (Part("f"), Part("g")), "b.md": ()}))
self.assertIsNone(failed)
self.assertEqual(store.read(), "# Touch predictions\n\n## Chunk 1, 2026-01-01T00:00:00Z, at aaaaaaa\n\nPredicted: none.\n\nTouched: none.\n\n## Chunk 373, 374, 2026-11-15T10:00:00Z, at abc1234\n\nPredicted:\n\n- `a.py`: `f` (small)\n\nTouched:\n\n- `a.py`: `f`, `g`\n- `b.md`\n")
def test_starts_an_empty_record_with_its_title(self) -> None:
store = MemoryStore("")
record.append(store, [5], record.entry([5], "2026-11-15T10:00:00Z", "abc1234", None, {}))
self.assertEqual(store.read(), "# Touch predictions\n\n## Chunk 5, 2026-11-15T10:00:00Z, at abc1234\n\nPredicted: none.\n\nTouched: none.\n")
def test_replaces_the_entry_of_the_same_items_and_keeps_the_others(self) -> None:
store = MemoryStore("")
for items, head in (([5], "aaaaaaa"), ([5, 6], "bbbbbbb"), ([7], "ccccccc"), ([5], "ddddddd"), ([5, 6], "eeeeeee")):
record.append(store, items, record.entry(items, "2026-11-15T10:00:00Z", head, None, {}))
self.assertEqual([line.split(" at ")[1] for line in store.text.splitlines() if line.startswith("## ")], ["ccccccc", "ddddddd", "eeeeeee"])
self.assertEqual(store.text.count("\n\n\n"), 0)
def test_a_record_that_cannot_be_read_is_a_failure(self) -> None:
self.assertEqual(record.append(MemoryStore(fails="no disk"), [5], "x"), Failure("no disk"))
class RecordCommandTest(unittest.TestCase):
"""`touch-predictions record`, run as a program in a configured checkout on a chunk's branch."""
APP = "def run():\n\treturn 1\n\n\ndef stop():\n\treturn 2\n"
TODO = "# todo\n\n## Scoring\n\n`Score = 100 * V / (2**S + 8)`\n\n`Bar = 0.1`\n\n`Next ID = 9`\n\n## Items\n\n| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |\n|---|---|---|---|---|---|---|---|---|---|---|---|\n| 3 | 0.2.0 | | | **Do three.** | 1 | 1 | 1 | 1 | 1 | 1 by 1 | 10.0 |\n| 4 | 0.2.0 | | | **Do four.** | 1 | 1 | 1 | 1 | 1 | 1 by 1 | 10.0 |\n\n## Details\n\n### 3. Do three.\n\nTouches:\n\n- `app.py`: `run`\n\n### 4. Do four.\n\nNo prediction.\n"
def setUp(self) -> None:
made = tempfile.TemporaryDirectory()
self.addCleanup(made.cleanup)
self.home = pathlib.Path(made.name, "home")
self.checkout = pathlib.Path(made.name, "proj")
self.checkout.mkdir()
self.repo = Repo(str(self.checkout))
self.config = write_config(self.home, self.checkout) / "config.toml"
self.repo.commit({"app.py": self.APP, "todo.md": self.TODO})
self.repo.run("checkout", "-q", "-b", "item-3")
self.repo.commit({"app.py": self.APP.replace("return 1", "return 3").replace("return 2", "return 4"), "todo.md": self.TODO + "\nMore.\n", "CHANGELOG.md": "- New.\n"})
def record(self, *args: str) -> subprocess.CompletedProcess[str]:
tool = pathlib.Path(__file__).resolve().parents[1] / "touch-predictions"
return subprocess.run([sys.executable, str(tool), *args], cwd=self.checkout, env={**isolated_env(), "HOME": str(self.home), "GIT_CONFIG_GLOBAL": os.devnull}, capture_output=True, text=True)
def set_record(self) -> pathlib.Path:
self.config.write_text(self.config.read_text(encoding="utf-8") + 'touch-predictions = "checkout:docs/touch-predictions.md"\n', encoding="utf-8")
return self.checkout / "docs/touch-predictions.md"
def test_appends_the_items_prediction_beside_what_the_branch_touched_less_the_plan_and_records(self) -> None:
path = self.set_record()
ran = self.record("record", "3", "4")
self.assertEqual((ran.returncode, ran.stderr), (0, ""))
self.assertEqual(ran.stdout, f"Recorded what chunk 3, 4 was predicted to touch, and what it touched, in {path}.\n")
head = self.repo.run("rev-parse", "--short", "HEAD")
entry = re.fullmatch(rf"# Touch predictions\n\n## Chunk 3, 4, \d{{4}}-\d\d-\d\dT\d\d:\d\d:\d\dZ, at {head}\n\n(.*)", path.read_text(encoding="utf-8"), re.S)
assert entry is not None
self.assertEqual(entry.group(1), "Predicted:\n\n- `app.py`: `run`\n\nTouched:\n\n- `app.py`: `run`, `stop`\n")
def test_a_second_run_replaces_the_entry_and_leaves_the_record_out_of_what_was_touched(self) -> None:
path = self.set_record()
self.record("record", "3")
self.repo.commit({})
self.assertEqual(self.record("record", "3").returncode, 0)
text = path.read_text(encoding="utf-8")
self.assertEqual(text.count("## Chunk 3, "), 1)
self.assertNotIn("touch-predictions.md", text)
def test_names_a_chunk_by_its_ids_in_order_each_once(self) -> None:
path = self.set_record()
self.record("record", "3", "4")
ran = self.record("record", "4", "3", "4")
self.assertEqual(ran.stdout, f"Recorded what chunk 3, 4 was predicted to touch, and what it touched, in {path}.\n")
self.assertEqual(re.findall(r"^## Chunk ([\d, ]+), \d{4}", path.read_text(encoding="utf-8"), re.M), ["3, 4"])
def test_records_nothing_where_the_config_leaves_the_setting_out(self) -> None:
ran = self.record("record", "3")
self.assertEqual((ran.returncode, ran.stdout), (0, "The project's config sets no `touch-predictions`, so nothing is recorded.\n"))
self.assertFalse((self.checkout / "docs").exists())
def test_fails_on_an_item_the_plan_lacks_a_list_it_cannot_read_and_other_arguments(self) -> None:
path = self.set_record()
for args, said in ((("record", "8"), "touch-predictions: the plan holds no item 8\n"), (("record",), "usage: touch-predictions record <ID>...\n"), (("record", "x"), "usage: touch-predictions record <ID>...\n"), ((), "usage: touch-predictions record <ID>...\n")):
with self.subTest(args):
ran = self.record(*args)
self.assertEqual((ran.returncode, ran.stdout, ran.stderr), (1, "", said))
(self.checkout / "todo.md").write_text(self.TODO.replace("- `app.py`: `run`", "- app.py"), encoding="utf-8")
ran = self.record("record", "3")
self.assertEqual(ran.returncode, 1)
self.assertTrue(ran.stderr.startswith("touch-predictions: item 3: the bullet '- app.py'"), ran.stderr)
self.assertFalse(path.exists())
if __name__ == "__main__":
unittest.main()
+27 -6
View File
@@ -23,6 +23,7 @@ Each project principle states one rule that the decisions below apply; their ent
- project config: a tool that reads a file's commits says where it does not support that file, and the work goes on
- project config: `language` names the prose's language by its English name, and `commit-title`, `pull-request-title` and `branch` are brace templates over `{id}` and `{summary}`
- project config: `plan` may name a Jira Cloud epic as `jira:` and its address, the plan is its open child issues in backlog order, and an issue's number is the item's ID
- project config: `tooling-on-host = true` lets a project with no container setup run its language runtime, package manager, tests and task runner on the host
- review: a release review fixes its findings in the release it reviews, and files under that release only a finding that needs a human answer, adds a feature or outlasts its five rounds
- review: a reviewer or comprehension seat that rules the work below standard may ask to rerun once, one rung up, in the same round; the ruling that stands is an escalation trigger for the worker unless the fix changes only prose, and never for the judge
- review: a reviewer under `agents/` marks a 🔴 or 🟡 `[misread]` where the implementer misread code that had already shipped, each round title counts the marked findings, and `score-outcomes` lists them per chunk
@@ -37,7 +38,8 @@ Each project principle states one rule that the decisions below apply; their ent
- routing: the worker changes rung only as a chunk starts, after every second unfinished verdict, when it names a chunk item that picks a higher rung, or when it cites an escalation trigger the judge finds
- tests: each test earns its keep as the technical principles' test bullet says, and the worker takes a test's expected values from its item, never from the code
- the repo may name bender, bender-infra and ai-sandbox
- todo.md: one table of items, scored by the formula it states, held to its bar and ranked by `bin/rank_todo.py`, which ranks each blocker above the items it blocks; each achieve goal weighs by its position, code health first and four times as heavy while the comprehension panel's overall is under 7.0 or unmeasured, then the goals file's goals, and a maintain goal weighs 0.5 per point of the confidence an item's test, gate leg or probe adds to it; the table's order is the plan's only order
- todo.md: an item of the next release predicts the files and parts it will touch under `Touches:` in its detail; chunk-preflight takes, in the plan's order, the items that overlap none taken before them as the chunks that may run at once, and the optional `touch-predictions` record keeps each chunk's prediction beside what it touched
- todo.md: one table of items, scored by the formula it states, held to its bar and ranked by `bin/rank_todo.py`, which ranks each blocker above the items it blocks; each achieve goal weighs by its position, code health first and four times as heavy while the comprehension panel's overall is under the project's readability floor or unmeasured, then the goals file's goals, and a maintain goal weighs 0.5 per point of the confidence an item's test, gate leg or probe adds to it; the table's order is the plan's only order
- todo.md: only a session or subagent on the project's rung or above scores or reshapes the plan; one below it drafts new items and changes to filed ones for a subagent at or above that rung to apply and score, and removes finished ones
- todo.md: tools and agents read and change the plan as it stands only through `bin/plan_store` and `todo-item`; a tool that reads what a past commit held, ranks the file or checks its rank still parses `todo.md`
- worker: a chunk's worker writes the simplest change that solves its item, test first wherever a test can check the change, and reads a technical principle only where the item, a finding or its own record names it; larv-review's reviewers hold the change to the principles and to the standards in `skills/larv-review/standards/`
@@ -81,9 +83,9 @@ Valid while the archive's file names, the Vocabulary and the panel keep these wo
The cap is 5, `bin/release_plan/todo_table.py`'s `BUNDLE_MAX_R`, from the same chunks: by the highest R among a chunk's items, the median was 0.9M to 1.5M tokens at R 1 to 5, and 2.7M at R 6, where the 90th percentile was 8.8M. A risky item that runs long re-runs review over every item bundled with it. R 5 is also the least R an I 4 item gets, so an item that could take everything down shares a chunk only where its L + E is 3 or less, and an irreversible I 5 item, at R 7 or more, never does. Valid while a review's cost is mostly fixed per chunk; revisit once 30 chunks have shipped bundles under it.
## comprehension floor: every dimension and the overall at 7.0 or above is the target, and no score blocks a merge or release
## comprehension floor: every dimension and the overall at the project's readability floor or above is the target, and no score blocks a merge or release
2026-09-27, lilleman, restating the 2026-09-24 target and extending it to the overall. Serves goal 1. 2026-10-13, lilleman: the floor doesn't block anything, and `review: the comprehension check records …` says why. Valid while the scoring run keeps its four seats.
2026-09-27, lilleman, restating the 2026-09-24 target and extending it to the overall. Serves goal 1. 2026-10-13, lilleman: the floor doesn't block anything, and `review: the comprehension check records …` says why. Valid while the scoring run keeps its four seats. 2026-11-12, lilleman, through todo item 358: a project's config sets this floor as `readability-floor`, its readability floor, since legacy code scores low. It is 7.0 where left out, and the signal stays that the score rises. Readers seated as the person who writes the config picked the key, 2 of 3.
## deploy: `~/.claude` holds only a release, which `deploy-release` moves it to; this repo is developed in `~/code/claude-config`, where loop-claude runs its chunks like any project's
@@ -300,7 +302,12 @@ Messages keep each file's usual name, such as `todo.md`, as its label, since the
- **An item's ID stays a whole number: the issue's number in the epic's Jira project.** About 30 modules read an ID as an int, and the `branch` and title templates already spell a ticket's name, as `ABC-{id}`. So the store refuses a child issue from another Jira project, and counts a blocker only among the plan's own items (`bin/plan_store/jira_epic.py`).
- **The scores sit in one issue property, `plan-item`**, which needs no Jira admin (lilleman, 2026-11-12). An issue without it reads as an item nobody scored.
- **The release is the earliest Fix Version named as a semver version**, and an issue with none fails the read, naming it, until todo.md's item 359 ties releases to something else.
- **The store only reads**, until todo.md's item 352 writes. `rank_todo.py` refuses to rank a plan in Jira, and its `--check` passes, since Jira's backlog ranks it; rule-hook's rank check skips it. Each read first asks Jira for the epic itself, since a search under an epic the account cannot see answers no issues, as a finished plan does.
- **The loop files an item as a Task under the epic, and marks it as its own** (lilleman's calls of 2026-11-12). `"Filed by": "loop"` in the `plan-item` property tells such an issue from one a person filed, whose summary and description the loop never edits. Task is an issue type every Jira Software project template has; a project without it refuses the issue, saying so. The issue takes the project's Fix Version named as the release, with a leading v or without, and the store refuses an item whose release the project has no Fix Version for, before it files anything. A security finding also gets the label `security`, and its text never holds a secret's value. Jira ranks the new issue last, and no bar or goals check applies, until todo.md's item 384 says where a plan in Jira states its formula. Jira takes a blocker's link only after the issue exists, so the store first checks that each blocker is an open child. A link Jira still refuses leaves the issue filed: the write counts as landed, with a note naming the link to make by hand. A failed create says the issue may exist all the same, since a lost answer doesn't tell.
- **The store reads and files, and doesn't edit or finish an issue** until todo.md's items 382 and 383. `rank_todo.py` refuses to rank a plan in Jira, and its `--check` passes, since Jira's backlog ranks it; rule-hook's rank check skips it. Each read first asks Jira for the epic itself, since a search under an epic the account cannot see answers no issues, as a finished plan does.
## project config: `tooling-on-host = true` lets a project with no container setup run its language runtime, package manager, tests and task runner on the host
2026-11-12, lilleman, through todo item 358. Serves goal 1.6: a legacy product may have no container setup, and the loop works in it without its owners adding one. `CLAUDE.md`'s container rule and the stability reviewer follow the setting. rule-hook checks only how a container starts, its memory limits and its image's pin, never where a runtime runs, so it needs no change. A decision may still put one tool on the host where the project has containers, as this repo's `bin/` decision does. Readers seated as the person who writes the config picked the key, 2 of 3. Valid while the loop runs on the machine that holds the checkout.
## review: a release review fixes its findings in the release it reviews, and files under that release only a finding that needs a human answer, adds a feature or outlasts its five rounds
@@ -647,7 +654,21 @@ Valid while the worker writes the tests that larv-review's reviewers hold to the
2026-10-04, lilleman, answering the principles audit of PR #215. Serves goal 4, which keeps credentials, transcripts and memory files off the remote; the names of the host, its infrastructure project and the sandbox VM are none of those. Valid while the repo names them without their addresses or credentials.
## todo.md: one table of items, scored by the formula it states, held to its bar and ranked by `bin/rank_todo.py`, which ranks each blocker above the items it blocks; each achieve goal weighs by its position, code health first and four times as heavy while the comprehension panel's overall is under 7.0 or unmeasured, then the goals file's goals, and a maintain goal weighs 0.5 per point of the confidence an item's test, gate leg or probe adds to it; the table's order is the plan's only order
## todo.md: an item of the next release predicts the files and parts it will touch under `Touches:` in its detail; chunk-preflight takes, in the plan's order, the items that overlap none taken before them as the chunks that may run at once, and the optional `touch-predictions` record keeps each chunk's prediction beside what it touched
2026-11-15, lilleman's call of 2026-11-13 in item 373, which split item 361. Serves goal 1.5, held to goal 1.4: several chunks of one project run at once only where they are unlikely to touch the same lines, since a conflict costs a rebase, a gate rerun and often a review round. A session on the project's rung or above writes each prediction, as `rules/todo-items.md` says, and `bin/touch_predictions/` reads it. The choices the call left open:
- **The spelling.** A `Touches:` line, then one bullet per file: the path in backticks, then its parts, each a name in backticks or `lines <first>-<last>`, with `(small)` after a part the item changes only a little; a path or a name that holds a backtick takes a longer run of backticks with a space inside each end, as a Markdown code span does. A path alone is the whole file. Three readers seated as the README's audience picked the bulleted list over one line and over a table, since backticks hold a heading's commas, colons and parentheses. Two of the three put `(small)` after the part and outside the backticks, and two left line ranges unquoted. Each picked a different config key: `touch-predictions` was one reader's first choice and the second choice of the other two.
- **A part's boundaries.** Python's `ast` module names the innermost function or class, a top-level assignment by the name it sets, and `(module)` for the rest. A Markdown file's parts are its headings outside fenced code. Any other file, and Python that doesn't parse, falls back to line ranges. A table row is no part of its own: the item named one, but the tables chunks collide on are the plan's and the changelog's, which don't count.
- **What doesn't count.** The plan and every record the config names, the changelog among them, since every chunk writes them: `todo.md` item 374 writes the plan and the changelog at merge time, and the other records are appended to. `touch-predictions record` leaves them out of what a chunk touched, and the rule keeps them out of predictions.
- **The pick.** `chunk-preflight` takes the items of the next release that don't wait, in the plan's order, each where it overlaps neither the next item nor an item taken before it. The call asked for the set that keeps the most chunks running. The plan's order comes first all the same: the largest set could start a low-ranked item in place of one ranked above it, and with more ready items than the parallel limit, either set fills the limit. `todo.md` item 375 takes as many of the picked items as its limit allows.
- **An overlap that is taken.** Two items may share a part where either marks it `(small)`. The call takes an overlap only for a small change to the same part, and a few lines re-apply onto whatever the other chunk did to it.
- **Which items share a chunk** stays the worker's choice, by the review passes they fire, so the pick names items, and an item the next chunk takes starts no chunk of its own.
- **The record is optional.** No path setting has a default, and a mandatory one would stop every project until its owner edits the config (goal 1.6). A project that leaves `touch-predictions` out is still picked for, and keeps no record. The worker runs `touch-predictions record` before it removes the chunk's items (`skills/larv-review/SKILL.md` §5), since the prediction leaves the plan with the item, and a plan in Jira keeps no history to read it back from.
Valid while `todo.md` item 375 runs chunks by this pick. Once the record holds enough chunks to show how often the predictions miss, an item, not filed yet, revisits the pick's order and the `(small)` rule.
## todo.md: one table of items, scored by the formula it states, held to its bar and ranked by `bin/rank_todo.py`, which ranks each blocker above the items it blocks; each achieve goal weighs by its position, code health first and four times as heavy while the comprehension panel's overall is under the project's readability floor or unmeasured, then the goals file's goals, and a maintain goal weighs 0.5 per point of the confidence an item's test, gate leg or probe adds to it; the table's order is the plan's only order
2026-10-02, lilleman. Serves goal 1: findings were filed faster than chunks closed them, so the plan grew without telling what mattered. Each item is scored as `~/.claude/rules/todo-items.md` says; this repo's formula counts value highest and size least. The format is mandatory in every project, as the premises are (goal 1.3); the formula and bar are each project's own. A script ranks the table so a re-rank after each addition or edit is deterministic and cheap. Valid while one human sets the bar and reads the ranking, and while the items marked `principle` stay few enough to rank.
@@ -698,7 +719,7 @@ Four choices the item left open:
- **`list` and `show` print no Score.** The store hands items over in the backend's order, and a tracker has no score, so an item's place in `list` says how it ranks within its release. Whoever plans a release compares Scores across releases, and so opens `todo.md`, until a store hands over a score.
- **The spellings `list [--release]`, `move <ID> --release`, and `edit <ID>` with one flag per cell, `--detail` from stdin and `--clear-detail`** are those a panel of three fresh readers, seated as the audience, picked over a positional release, `set` and `retarget`. `edit` refuses stdin text without `--detail`, and `--detail` without text, so no detail is dropped or wiped by mistake.
`rules/todo-items.md` loads when a session itself reads or writes a `todo.md`, which a session that runs `todo-item` never does, so `CLAUDE.md` → "Topic rules" asks for it before an item is filed, scored, edited or moved. A reviewer without a shell still opens the file; todo item 351 hands it the plan another way. Valid while `todo-item` is the only command that changes a plan's items.
`rules/todo-items.md` loads when a session itself reads or writes a `todo.md`, which a session that runs `todo-item` never does, so `CLAUDE.md` → "Topic rules" asks for it before an item is filed, scored, edited or moved. A reviewer without a shell reads the plan from the listing `larv-review reviewer-header` writes, which the header's `Plan:` line names. Valid while `todo-item` is the only command that changes a plan's items.
## worker: a chunk's worker writes the simplest change that solves its item, test first wherever a test can check the change, and reads a technical principle only where the item, a finding or its own record names it; larv-review's reviewers hold the change to the principles and to the standards in `skills/larv-review/standards/`
+118
View File
@@ -2067,3 +2067,121 @@ Read most (opens and searches):
- `bin/plan_store/contract.py` 1
- `bin/release_plan/todo_table.py` 1
- `bin/todo_item/main.py` 1
## Reading cost, chunk ca7c9a18d77d, finished 2026-11-14T19:36:20Z
87192 new input tokens before the first commit.
Read most (opens and searches):
- `bin/plan_store/test_jira_epic.py` 11
- `bin/adf_codec/convert.py` 3
- `bin/adf_codec/test_adf_codec.py` 3
- `bin/plan_store/jira_epic.py` 3
- `bin/run_heavy/main.py` 3
- `README.md` 2
- `bin/adf_codec/__init__.py` 2
- `bin/machine_load/slots.py` 2
- `docs/decisions.md` 2
- `bin/adf_codec/node_shim/Dockerfile` 1
## Reading cost, chunk 514c7381359c, finished 2026-11-14T19:43:45Z
60112 new input tokens before the first commit.
Read most (opens and searches):
- `README.md` 6
- `bin/chunk_preflight/main.py` 2
- `bin/chunk_preflight/test_chunk_preflight.py` 2
- `bin/project_config/main.py` 2
- `bin/chunk_preflight/choices.py` 1
- `bin/project_config/templates.py` 1
- `bin/project_config/test_templates.py` 1
- `ci.sh` 1
- `docs/decisions.md` 1
- `todo.md` 1
## Reading cost, chunk c1c3ab1d8e14, finished 2026-11-14T20:33:37Z
135080 new input tokens before the first commit.
Read most (opens and searches):
- `bin/plan_store/stores.py` 4
- `bin/project_config/settings.py` 4
- `bin/project_config/test_project_config.py` 4
- `bin/larv_review/reviewer_header.py` 3
- `bin/plan_store/jira_epic.py` 3
- `bin/project_config/main.py` 3
- `bin/release_plan/goals_file.py` 2
- `skills/larv-review/SKILL.md` 2
- `bin/adf_codec/convert.py` 1
- `bin/loop_claude/loop/usage.py` 1
## Reading cost, chunk 566d96364f2d, finished 2026-11-14T21:20:32Z
287363 new input tokens before the first commit.
Read most (opens and searches):
- `bin/project_config/test_project_config.py` 9
- `docs/decisions.md` 9
- `bin/larv_review/test_larv_review.py` 8
- `bin/release_plan/ranking.py` 6
- `bin/release_plan/test_ranking.py` 6
- `bin/larv_review/main.py` 5
- `bin/plan_store/stores.py` 5
- `bin/project_config/main.py` 5
- `bin/project_config/settings.py` 4
- `bin/release_plan/goals_file.py` 4
## Reading cost, chunk be2b74d8a78d, finished 2026-11-14T23:39:10Z
120395 new input tokens before the first commit.
Read most (opens and searches):
- `bin/project_config/test_project_config.py` 10
- `README.md` 9
- `bin/project_config/main.py` 7
- `bin/project_config/settings.py` 5
- `bin/mattermost_dm/test_mattermost_dm.py` 4
- `CHANGELOG.md` 3
- `bin/loop_effects/effects.py` 3
- `bin/mattermost_dm/dm.py` 3
- `.gitignore` 2
- `bin/loop_claude/direct_message.py` 2
## Reading cost, chunk f2d04ba767bd, finished 2026-11-15T01:11:32Z
85940 new input tokens before the first commit.
Read most (opens and searches):
- `bin/larv_review/test_larv_review.py` 8
- `bin/larv_review/reviewer_header.py` 5
- `bin/plan_store/stores.py` 4
- `README.md` 3
- `skills/larv-review/SKILL.md` 3
- `skills/larv-review/review-findings.md` 3
- `todo.md` 3
- `agents/principles-auditor.md` 2
- `bin/larv_review/main.py` 2
- `bin/larv_review/plan.py` 2
## Reading cost, chunk b3bdb6c3ea26, finished 2026-11-15T02:08:49Z
103160 new input tokens before the first commit.
Read most (opens and searches):
- `rules/todo-items.md` 3
- `todo.md` 2
- `bin/chunk_preflight/choices.py` 1
- `bin/chunk_preflight/facts.py` 1
- `bin/chunk_preflight/gathered.py` 1
- `bin/chunk_preflight/main.py` 1
- `bin/release_plan/release_standing.py` 1
- `docs/decisions.md` 1
- `docs/score-anchors.md` 1
+1 -1
View File
@@ -6,7 +6,7 @@ paths:
# Goals and Audience
A project's goals and audience live in its goals file (`~/.claude/CLAUDE.md` → "Vocabulary"): `README.md`, or a client project's `goals.md` in its config's folder.
A project's goals and audience live in its goals file (`~/.claude/CLAUDE.md` → "Vocabulary"): `README.md`, or a client project's `goals.md` in its config's folder or its plan epic's description in Jira.
- **Goals** state the project's aim and intent, not promises: one numbered line each, like slogans, in priority order; a sub-goal is indented under its goal — "1. Blazing fast performance. 2. Correctness is more important than many features." A goal names no step of the work, such as a check to run first, and rarely an implementation. How a goal is met goes in a method section further down the goals file and names the goal it serves. BANNED as a goal: `Kill weak candidates early, with the cheap checks first.` GOOD: the goal `Keep research on a budget, so it scales in both time and cost.`, with the cheap checks moved to the method section, naming that goal.
- **Mark each goal `**Maintain:**` or `**Achieve:**`.** A maintain goal is a state to hold: a change that breaks it is redesigned or dropped, whatever its value to other goals. An achieve goal is a direction to pursue, weighed against the other achieve goals. Under each achieve goal, three indented bullets: `Signal:` what moving towards it looks like, `Counter-signal:` what shows it is bought at a wrong price, and `Why:` one line on how the two connect. A goal with sub-goals states its own signal. A maintain goal has no bullets. BANNED: an unmarked goal; an achieve goal with no signal; `**Achieve:** Delivery speed.` with the signal `faster`. GOOD: `**Achieve:** Delivery speed.` with `Signal: hours from a chunk's start to its merge fall.`, `Counter-signal: 🔴 findings per chunk rise.` and `Why: speed bought by skipping review shows up as defects.`
+3 -2
View File
@@ -5,10 +5,10 @@ paths:
# Todo items (`todo.md`)
- **`todo.md` is mandatory in every project, in the shape `rank_todo.py --help` shows**, which `~/.claude/bin/rank_todo.py` checks and ranks; its `--help` shows a valid file. `## Scoring` holds the formula and the bar; `## Items` is one table of every item; `## Details` holds each item's detail under its ID. `## Renamed` marks each renamed release with a line such as `- 0.2.1 renamed to 0.3.0`; `rank_todo.py --help` says what a mark does. Cite an item by its ID. The formula and bar are the project's own to tune.
- **A plan is mandatory in every project, and a plan kept as `todo.md` has the shape `rank_todo.py --help` shows**, which `~/.claude/bin/rank_todo.py` checks and ranks; its `--help` shows a valid file. A plan in a Jira epic is read from the epic's open child issues. `todo-item add` files an item there as a new child issue, and `todo-item` can't edit, move or finish an issue yet. Below, `todo.md` means a plan kept as a file, and "the plan" either kind. `## Scoring` holds the formula and the bar; `## Items` is one table of every item; `## Details` holds each item's detail under its ID. `## Renamed` marks each renamed release with a line such as `- 0.2.1 renamed to 0.3.0`; `rank_todo.py --help` says what a mark does. Cite an item by its ID. The formula and bar are the project's own to tune.
- **File an item with `~/.claude/bin/todo-item add`, and change one with `todo-item edit` or `todo-item move`.** `add` and `edit --detail` read the item's detail from stdin, and all three commands rank the plan; `todo-item --help` shows the flags. `todo-item finish <ID> --no-changelog` drops an item no chunk built. Edit `todo.md` itself only for what `todo-item` has no command for: `## Scoring`, `## Renamed`, and reshaping an old table.
- **Order items only by score and the Blocked by column.** An item's Blocked by cell lists the IDs of the items that must be done before it starts, such as `12, 14`; `rank_todo.py --help` says how it ranks them. No text in `todo.md` outside the table orders items: where an item must go first, score it so, and say why in its detail.
- **Plan only on the project's rung or above.** loop-claude's prompt tells you when you run below it. Below it, never score or re-score an item, move it between releases, split a milestone into items, delete an item under the bar, rewrite a filed item's tagline or detail, or choose or replace an item in `docs/score-anchors.md`. Draft each new item, each change to a filed item, and each change to the anchors, instead. Before your next commit, launch one subagent to apply the drafts, score them and set their release. Launch it on the rung `CLAUDE.md`'s delegation rule gives a subagent that files or scores items. Keep the scores and releases it writes. For a security finding, launch it at once. Any rung may remove a finished item's row and detail, and score a delegated task's L. A subagent launched for another task leaves `todo.md` alone.
- **Plan only on the project's rung or above.** loop-claude's prompt tells you when you run below it. Below it, never score or re-score an item, move it between releases, split a milestone into items, delete an item under the bar, rewrite a filed item's tagline or detail, or choose or replace an item in `docs/score-anchors.md`. Draft each new item, each change to a filed item, and each change to the anchors, instead. Before your next commit, launch one subagent to apply the drafts, score them and set their release. Launch it on the rung `CLAUDE.md`'s delegation rule gives a subagent that files or scores items. Keep the scores and releases it writes. For a security finding, launch it at once. Any rung may remove a finished item's row and detail, and score a delegated task's L. A subagent launched for another task leaves the plan alone.
- **An item's release allows the bump that semver read strictly asks for.** An item that changes what exists needs a major, or before 1.0.0 a minor. One that only adds needs a minor, and a fix a patch.
- **Score an item when it is filed or edited.** S, the size of the change, is a whole number from 1 to 10. Score L, E and I by the levels below, each level about ten times as likely, or as damaging, as the one below it. `rank_todo.py` writes R, the risk that the change creates serious bugs or issues: L + E + I − 2, at least 7 when I is 5 and at least 5 when I is 4, since a severe enough consequence outranks how unlikely it is. A task's L picks its worker's rung, and its E + I its reviewers' rung.
@@ -30,3 +30,4 @@ paths:
- **The Exempt cell keeps an item whatever its score:** `security` for a security finding, `defect` for a 🔴 finding or an item that restores a maintain goal the project breaks today, `question` for a question only the human can answer, which ranks first in its release, `decision` for an item `docs/decisions.md` cites, `owner` for an item the human told you to keep, and, where no other reason fits, `principle` for a 🟡 finding against a file in the config's principles folder, whose item's detail names that principle. Every item `docs/decisions.md` cites carries one of these reasons.
- **A maintain goal vetoes an item that breaks it,** whatever the item scores: redesign the item so it holds the goal, or drop it.
- **When you remove an item that no chunk built, title the commit `Drop item <ID>: <why>`,** or `Drop items 12, 14 and 15: <why>` for several. Such an item was deleted under the bar, vetoed, superseded or moot; a finished item is not one. Without the title, `score-outcomes` credits the item with the work of the chunk that removed it, where that chunk changed more than `todo.md`.
- **Predict, in the detail of each item of the next release, what the item will touch.** When you plan the next release, or file or move an item into it, give the item's detail a `Touches:` line, then one bullet per file the item will change. Each bullet names the file, then the parts of it the item will change: a function, a class or a section heading, or line ranges where the file has none of these. A path alone means the whole file. Read the code first; a prediction from the item's text alone misses. `~/.claude/bin/touch-predictions --help` shows the spelling and how a part is named; a name that holds a backtick takes a longer run of backticks with a space inside each end, as a Markdown code span does. Mark a part `(small)` where the item changes only a few lines of it. Leave out the plan and the project's records, which every chunk writes. `chunk-preflight` reads the predictions to name the items that may start chunks at once, and `touch-predictions record` keeps each beside what its chunk touched.
+3 -3
View File
@@ -65,7 +65,7 @@ Give a reviewer without Bash `git ls-files`'s output in its prompt, since some h
`~/.claude/bin/larv-review` holds this section's mechanical rules: the chunk's review folder, the round count, the paired ruling's base and vote count, the scoring run's trigger; the history's format, its latest places and its count of how often seats agree; and the header of each reviewer's prompt. Run it in the chunk's worktree; `~/.claude/bin/larv-review --help` states each rule. On exit 1, repair what its message names and run it again; when you cannot, ask the user.
**Reports.** Run `~/.claude/bin/larv-review reviewer-header <pass>` in the chunk's worktree, and open each prompt to an agent under `~/.claude/agents/` with what it prints; then say in a few lines what the change does and which files it touches. The command makes the chunk's review folder and writes the branch diff into it. The header names that diff, the reviewer's full report, `<pass>-round-<n>.md`, in the folder, the folder of technical principles the project's config sets, and for architecture and stability the places too. For a reviewer whose definition starts it without `CLAUDE.md`, the header's last line names the file that holds the project principles and decision titles, which the reviewer reads first. For a relaunch one rung up, add `--rerun`: the report becomes `<pass>-round-<n>-rerun.md`, and the header names the report that asked. Before you answer a 🔴 or 🟡, read its entry: Grep the report for the finding's place, with the lines after it, rather than Read the whole report. rule-hook refuses a reviewer's Edit and MultiEdit, and any Write outside `~/.local/state/larv-review/`. Keep the folder after the merge: `review-replay` replays a round from the reports its prompt names.
**Reports.** Run `~/.claude/bin/larv-review reviewer-header <pass>` in the chunk's worktree, and open each prompt to an agent under `~/.claude/agents/` with what it prints; then say in a few lines what the change does and which files it touches. The command makes the chunk's review folder and writes the branch diff and the plan's listing into it. The header names that diff, the reviewer's full report, `<pass>-round-<n>.md`, in the folder, the folder of technical principles the project's config sets, the listing, and for architecture and stability the places too. For a reviewer whose definition starts it without `CLAUDE.md`, the header's last line names the file that holds the project principles and decision titles, which the reviewer reads first. For a relaunch one rung up, add `--rerun`: the report becomes `<pass>-round-<n>-rerun.md`, and the header names the report that asked. Before you answer a 🔴 or 🟡, read its entry: Grep the report for the finding's place, with the lines after it, rather than Read the whole report. rule-hook refuses a reviewer's Edit and MultiEdit, and any Write outside `~/.local/state/larv-review/`. Keep the folder after the merge: `review-replay` replays a round from the reports its prompt names.
**Precedent, then ask** — for the full scan:
@@ -156,7 +156,7 @@ The comprehension check records how hard the project is for its contributor to r
**Scoring run**, when `~/.claude/bin/larv-review needs-scoring-run <the IDs of the items the chunk ships, if any>` prints `Scoring run due:`. Run `needs-scoring-run` before removing the chunk's items from `todo.md`. `chunk-pr merge` refuses until the branch's committed history records every run the plan calls, which `larv-review scoring-run-owed` counts at merge time from the merge base; an earlier due line is only a snapshot.
- **Seats.** Junior A, Mid A, the maintainability senior and the inherited architect each score the project at the head from 1 to 10 overall and on four dimensions: Navigation, Locality, Shape and Self-sufficiency. Run `~/.claude/bin/larv-review prepare-scoring`, adding `--preloaded <text>` only where its default list of pre-loaded files is wrong. It makes the worktree the seats read and prints each seat's prompt file; launch each seat with its file's text as its prompt. Write their lines into a scores file and run `~/.claude/bin/larv-review record-scoring <scores file> <the same item IDs>`, which appends the run to the history and prints the four seats' means.
- **Floor item.** Where `record-scoring` prints `Floor:`, a `Next:` line follows: file one floor item, or refresh the open one. A floor item is a plan item meant to bring every mean to 7.0. File it as one ambitious refactor, not touch-ups. It restructures the area behind the places `larv-review places` prints for this run, chosen where they bear on the lowest dimension, sized to bring every mean to 7.0, and quotes those places. Its tagline opens with `Reach the comprehension floor:`, so its own chunk runs a scoring run; while a mean stays under 7.0, that run's `Next:` line asks for the next floor item. Mark it `owner`, since the human asked that such a project always hold one, so no score deletes it. Put it in the earliest release the plan names after the one the chunk ships into, or else in the next version after that one that `~/.claude/rules/todo-items.md` allows, so the floor doesn't hold up any release. While one is open, refresh its places and aim from the newest run instead of filing another; the item the chunk ships doesn't count as open. Commit it with the run, as "Record" says.
- **Floor item.** Where `record-scoring` prints `Floor:`, a `Next:` line follows: file one floor item, or refresh the open one. A floor item is a plan item meant to bring every mean to the project's readability floor, which `record-scoring`'s `Floor:` line names. File it as one ambitious refactor, not touch-ups. It restructures the area behind the places `larv-review places` prints for this run, chosen where they bear on the lowest dimension, sized to bring every mean to that floor, and quotes those places. Its tagline opens with `Reach the comprehension floor:`, so its own chunk runs a scoring run; while a mean stays under the floor, that run's `Next:` line asks for the next floor item. Mark it `owner`, since the human asked that such a project always hold one, so no score deletes it. Put it in the earliest release the plan names after the one the chunk ships into, or else in the next version after that one that `~/.claude/rules/todo-items.md` allows, so the floor doesn't hold up any release. While one is open, refresh its places and aim from the newest run instead of filing another; the item the chunk ships doesn't count as open. Commit it with the run, as "Record" says.
- **Second run.** Where `needs-scoring-run` printed that the chunk `leaves release … with no plan item`, run `prepare-scoring` again and launch the same four seats afresh on the same head. Their scores file's first line is `<PR or branch> rerun at <commit>`. Record it with the same `record-scoring` command.
- **Agreement.** After the second run, run `~/.claude/bin/larv-review agreement` and put its counts in the summary. On `Assumption fails:`, ask the user whether to keep the paired ruling or change the decision `review: the comprehension check records …`. Record the answer as a decision in the repo whose history was counted, with the counts that led to the ask. A later run asks again only when the rulings' rate falls, or the runs' rate rises, against the recorded counts.
@@ -201,7 +201,7 @@ Launch prose-reviewer with what the diff touched and every section this review c
1. Read the finished PR against the goals file's goals and code health, unless that file voids it: does anything in it work against one? It breaks a maintain goal → do not merge; redesign the change or drop its item. It works against an achieve goal → do not merge; ask the human, stating the conflict.
2. Run the comprehension check (§3) where it runs; it runs once. When `origin/<default branch>` moves after that, return to §4, and keep the ruling and scoring run already recorded.
3. Remove the chunk's items from `todo.md` per `~/.claude/CLAUDE.md` → "Working loop" in the branch, commit and push that; the commit re-enters no pass.
3. Run `~/.claude/bin/touch-predictions record <ID>...` in the worktree, naming the chunk's items: it records what they were predicted to touch beside what the branch touched, where the project's config names that record. A later pass through this step, after a return to §4, skips it, since the items have left the plan. Then remove the chunk's items from `todo.md` per `~/.claude/CLAUDE.md` → "Working loop" in the branch. Commit and push both; the commit re-enters no pass.
4. Aligned and every pass done → **merge** with `~/.claude/bin/chunk-pr merge`, run in the background with its `timeout` set to 7200000 ms, since its wait can outlast the Bash tool's default. It waits for the pull request's checks to pass, and for a human's approval where the project's config sets `wait-for-approval` (`chunk-pr --help`), then takes the first merge method the repository allows on its forge. A repo whose `AGENTS.md` names another method merges that way with the forge's CLI instead, once the pull request's checks pass, `~/.claude/bin/larv-review scoring-run-owed` exits 0 and, where `~/.claude/bin/project-config wait-for-approval` prints `true`, GitHub reports the pull request approved. A repo withholds this in its `AGENTS.md` → leave the PR ready and unmerged, and say which line withheld it.
5. Merged → run `~/.claude/bin/chunk-pr clean` in the chunk's worktree, and put a failure it prints in the summary.
6. Stop. The next chunk gets a fresh session.
+1 -1
View File
@@ -2,7 +2,7 @@
Words: `~/.claude/CLAUDE.md` → "Vocabulary".
A reviewer reads and reports; it doesn't edit anything. It writes no file but its report, except the scratch files that a reviewer holding Bash makes with Bash. Read `docs/decisions.md` and `todo.md` first: a finding declined or disproved in `docs/decisions.md` or in a comment at the code it concerns, or filed in `todo.md`, is not raised again, unless the decline works against a goal or a technical principle and names no `todo.md` item ending it.
A reviewer reads and reports; it doesn't edit anything. It writes no file but its report, except the scratch files that a reviewer holding Bash makes with Bash. Read `docs/decisions.md` first and the plan, which your prompt's `Plan:` line names: a finding declined or disproved in `docs/decisions.md` or in a comment at the code it concerns, or filed in the plan, is not raised again, unless the decline works against a goal or a technical principle and names no plan item ending it.
## Severity
+36 -56
View File
@@ -6,27 +6,21 @@
`Bar = 0.1`
`Next ID = 381`
`Next ID = 385`
## Items
| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 378 | 0.11.0 | | | **Name the branches, worktrees and commit and PR titles of a Jira plan's chunks by the issue key, as in `ABC-123` and `ABC-123 - ...`.** | 2 | 2 | 3 | 5 | 2 | 1.6 by 4 | 1.4 |
| 353 | 0.11.0 | | | **Let a project's config take its goals and audience from a Jira epic's description, under the same two headings.** | 2 | 2 | 3 | 5 | 3 | 1.6 by 4 | 1.3 |
| 358 | 0.11.0 | | | **Let a project's config allow its runtime and tests on the host, and set the comprehension score under which code health is very important.** | 2 | 2 | 3 | 5 | 3 | 1.6 by 4 | 1.3 |
| 362 | 0.11.0 | | | **Send loop-claude's notices through the notifier a project's config names, with Mattermost as the first backend.** | 2 | 1 | 2 | 3 | 3 | 1.6 by 3 | 1.0 |
| 363 | 0.11.0 | 362 | | **Add a Slack backend to the notifier, sending each notice as a DM from a bot.** | 2 | 1 | 2 | 3 | 3 | 1.6 by 4 | 1.3 |
| 377 | 0.11.0 | | | **Hand a reviewer without a shell the plan as a listing `larv-review` writes into the review folder, whatever store holds the plan.** | 2 | 2 | 3 | 5 | 3 | 1.6 by 4 | 1.3 |
| 373 | 0.11.0 | | | **Pick the next release's chunks that may run at once by the files and the parts of files each is predicted to touch, and record the prediction beside what each merged chunk touched.** | 3 | 2 | 2 | 5 | 5 | 1.5 by 4, 1.4 by 2 | 1.3 |
| 352 | 0.11.0 | | | **Write a project's plan to its Jira epic: file items as child issues, edit those the loop filed, score unscored issues with a comment, and move a finished item to the status its config names.** | 3 | 2 | 3 | 6 | 5 | 1.6 by 6 | 1.2 |
| 384 | 0.11.0 | | question | **Rank an issue the loop files in Jira by its score among the issues the loop filed, a security finding first.** | 3 | 2 | 2 | 5 | 3 | 1.6 by 2 | 0.7 |
| 355 | 0.11.0 | | | **Store a record on the Confluence Cloud page its config names, as markdown converted through the adf-codec shim, and interrupt the human when a teammate saved the page since the loop read it.** | 3 | 2 | 3 | 6 | 5 | 1.6 by 6 | 1.2 |
| 356 | 0.11.0 | | | **Hand reviewers the review standards from the folder a project's config names, in place of `~/.claude/skills/larv-review/standards/`.** | 2 | 2 | 3 | 5 | 2 | 1.6 by 3 | 1.1 |
| 383 | 0.11.0 | | | **Move a finished item of a Jira plan by the transition, and to the status, that the project's config names.** | 4 | 2 | 3 | 7 | 3 | 1.6 by 3 | 1.0 |
| 372 | 0.11.0 | | | **Key loop-claude's session, archive, routing state and config-folder commits per chunk, so two chunks of one project run side by side without touching each other's state.** | 3 | 2 | 3 | 6 | 6 | 1.5 by 3 | 0.4 |
| 374 | 0.11.0 | 372 | | **Merge open chunks one at a time: rebase, finish the item in todo.md and CHANGELOG.md, rerun the gate and the paired ruling, and keep a chunk waiting for approval in the queue without blocking the next.** | 4 | 2 | 3 | 7 | 6 | 1.5 by 4, 1.6 by 3 | 1.0 |
| 374 | 0.11.0 | 372 | decision | **Merge open chunks one at a time: rebase, finish the item in todo.md and CHANGELOG.md, rerun the gate and the paired ruling, and keep a chunk waiting for approval in the queue without blocking the next.** | 4 | 2 | 3 | 7 | 6 | 1.5 by 4, 1.6 by 3 | 1.0 |
| 359 | 0.11.0 | | | **Tie a project's releases to what its config names: semver tags, Jira Fix Versions, sprints, or none.** | 3 | 2 | 3 | 6 | 4 | 1.6 by 3 | 0.8 |
| 380 | 0.11.0 | | | **Define "plan" in `CLAUDE.md` → "Vocabulary" as the store a project's config names as `plan`, a `todo.md` or a Jira epic, and reword each line of `CLAUDE.md` and `rules/todo-items.md` that says `todo.md` where it is false for a plan in Jira.** | 1 | 2 | 3 | 4 | 2 | 1.6 by 2 | 0.7 |
| 375 | 0.11.0 | 372, 373, 374 | | **Run up to the project's configured number of chunks at once, each in its own window of one tmux session named for the project, mark a window whose chunk waits for the human, and refuse to start without tmux at the needed version.** | 4 | 2 | 3 | 7 | 7 | 1.5 by 7 | 0.6 |
| 382 | 0.11.0 | | | **Edit a Jira issue the loop filed, and score an unscored issue a teammate filed with a comment saying why.** | 4 | 2 | 3 | 7 | 4 | 1.6 by 3 | 0.8 |
| 375 | 0.11.0 | 372, 374 | decision | **Run up to the project's configured number of chunks at once, each in its own window of one tmux session named for the project, mark a window whose chunk waits for the human, and refuse to start without tmux at the needed version.** | 4 | 2 | 3 | 7 | 7 | 1.5 by 7 | 0.6 |
| 319 | 0.12.0 | | | **Start a fresh session with a brief of the chunk when a rung step changes the worker's model, in place of resuming the old session.** | 3 | 2 | 3 | 6 | 4 | 1.1 by 2, 1.4 by 2 | 1.2 |
| 309 | 0.12.0 | | | **Run a scoring run's second pass on one head with two seats in place of four, once `larv-review agreement` shows the seats agree with each other more than a run agrees with its rerun.** | 2 | 2 | 2 | 4 | 2 | 1.4 by 3 | 1.2 |
| 299 | 0.12.0 | | | **Replay the archived judge verdicts through code rules and a classifier trained locally on the archive, and file an item for each verdict kind one of them decides with no missed interrupt.** | 2 | 2 | 2 | 4 | 3 | 1.4 by 3 | 1.0 |
@@ -37,11 +31,12 @@
| 310 | 0.12.0 | | | **Compact a waiting worker's session shortly before its prompt cache expires, only when the human has not answered an interrupt by then.** | 3 | 2 | 3 | 6 | 4 | 1.4 by 3 | 0.9 |
| 298 | 0.12.0 | | | **Send the judge only the decision entries and the transcript tail a verdict needs, and keep the cut only where `judge-replay` changes no verdict kind.** | 3 | 3 | 3 | 7 | 4 | 1.4 by 2, 1.5 by 1 | 0.9 |
| 331 | 0.12.0 | | | **Reword four decisions to expire when the rungs their replays tested change, not whenever a model joins the ladder.** | 1 | 1 | 1 | 1 | 2 | 1.4 by 2 | 0.8 |
| 381 | 0.12.0 | | | **Read a `Touches:` list from a plan kept in Jira as from one in todo.md, with a test that converts a description through `adf_codec`.** | 1 | 2 | 1 | 2 | 2 | 1.5 by 2 | 0.7 |
| 327 | 0.12.0 | | | **Have `larv-review` print a round commit's title prefix, counted from the round's report, and have rule-hook refuse a round title whose counts differ from it.** | 3 | 2 | 3 | 6 | 4 | 1.1 by 1, 1.4 by 1 | 0.6 |
| 365 | 0.13.0 | 352 | | **Have `score-outcomes` read the finished and dropped items of a plan outside the checkout, from the project repo's history or from Jira's issue changelogs.** | 3 | 2 | 2 | 5 | 4 | 1.6 by 2, 1.1 by 2 | 1.2 |
| 368 | 0.13.0 | 352 | | **Call a release review due, call a release ready to cut, and tell whether a chunk owes a scoring run, for a plan outside the checkout, from the project repo's history or from Jira.** | 3 | 2 | 2 | 5 | 4 | 1.6 by 2, 1.1 by 2 | 1.2 |
| 366 | 0.13.0 | 352 | | **Count the chunks of a project whose plan sits outside the checkout in the routing figures, from the project repo's history or from Jira.** | 3 | 2 | 2 | 5 | 4 | 1.6 by 2, 1.4 by 2 | 1.1 |
| 367 | 0.13.0 | 352 | | **Check that every write to a Jira plan leaves it ranked, as rule-hook's `todo-rank-check` checks `todo.md` today.** | 2 | 2 | 3 | 5 | 3 | 1.6 by 2 | 0.7 |
| 365 | 0.13.0 | 382, 383 | | **Have `score-outcomes` read the finished and dropped items of a plan outside the checkout, from the project repo's history or from Jira's issue changelogs.** | 3 | 2 | 2 | 5 | 4 | 1.6 by 2, 1.1 by 2 | 1.2 |
| 368 | 0.13.0 | 382, 383 | | **Call a release review due, call a release ready to cut, and tell whether a chunk owes a scoring run, for a plan outside the checkout, from the project repo's history or from Jira.** | 3 | 2 | 2 | 5 | 4 | 1.6 by 2, 1.1 by 2 | 1.2 |
| 366 | 0.13.0 | 382, 383 | | **Count the chunks of a project whose plan sits outside the checkout in the routing figures, from the project repo's history or from Jira.** | 3 | 2 | 2 | 5 | 4 | 1.6 by 2, 1.4 by 2 | 1.1 |
| 367 | 0.13.0 | 382, 383, 384 | | **Check that every write to a Jira plan leaves it ranked, as rule-hook's `todo-rank-check` checks `todo.md` today.** | 2 | 2 | 3 | 5 | 3 | 1.6 by 2 | 0.7 |
| 303 | 0.14.0 | | defect | **Archive each judge run's prompt and json reply beside the verdict it gave, so judge cost, replays and backups cover the judge as they cover the worker.** | 2 | 2 | 3 | 5 | 3 | 1.4 by 3, 3 by 2 | 4.2 |
| 306 | 0.14.0 | | | **Set a strategy that keeps loop-claude's archive and larv-review's review folders backed up and small over the years, compressing older entries without losing any.** | 3 | 2 | 4 | 7 | 5 | 3 by 5 | 3.9 |
| 304 | 0.14.0 | 303 | defect | **Archive each review-replay and judge-replay run's transcript beside its result, so a replay that decided a rung can be checked and re-priced later.** | 2 | 2 | 2 | 4 | 3 | 1.4 by 2, 3 by 2 | 3.8 |
@@ -85,41 +80,11 @@
## Details
### 378. Name the branches, worktrees and commit and PR titles of a Jira plan's chunks by the issue key, as in `ABC-123` and `ABC-123 - ...`.
### 384. Rank an issue the loop files in Jira by its score among the issues the loop filed, a security finding first.
lilleman's call, 2026-11-14: split from item 351. Item IDs stay `int`: the Jira store holds the project key and an issue's number is the item's ID. A branch template `ABC-{id}` and a commit-title template `ABC-{id} - {summary}` already give the ticket-style names `CLAUDE.md`'s ticket rules ask for. Make a project with a Jira plan get them without spelling its key twice, or document the two templates where the plan setting is documented, whichever is simpler, and check `chunk-preflight` names the worktree the same way.
Split from item 352 on 2026-11-15; lilleman's call, 2026-11-12: an issue the loop files goes into Jira rank by its score among the issues the loop filed, and a security finding ranks first. The team's own rank of every other issue stays as it is.
### 353. Let a project's config take its goals and audience from a Jira epic's description, under the same two headings.
lilleman's call, 2026-11-12: this client keeps its goals and audience in the plan epic's description. The source is a config setting, never hard-coded; item 346 builds the file source this one adds to. Read through the adf-codec shim.
### 358. Let a project's config allow its runtime and tests on the host, and set the comprehension score under which code health is very important.
lilleman's calls, 2026-11-12. Legacy products may have no container setup, so the config may allow host tooling; `CLAUDE.md`'s container rule and rule-hook then follow it. In 0.10.0 a decision in the project's records can put tooling on the host instead. The comprehension panel will score legacy code low, and today code health under 7.0 is very important. The config sets that floor, 7.0 in the configs of the projects under `~/code`; the signal stays that the score rises.
### 362. Send loop-claude's notices through the notifier a project's config names, with Mattermost as the first backend.
lilleman's call, 2026-11-12: each project names its notifier, server and recipient, so client notices can go to a client's workspace. Today `bin/mattermost-dm` reads one server from `~/.claude/.env` for every project.
### 363. Add a Slack backend to the notifier, sending each notice as a DM from a bot.
lilleman asked for a Slack driver on 2026-11-12, for clients on Slack. The bot token comes from the project's env file.
### 377. Hand a reviewer without a shell the plan as a listing `larv-review` writes into the review folder, whatever store holds the plan.
lilleman's call, 2026-11-14: split from item 351. A reviewer without a shell reads the plan with the Read tool today, as `todo.md`; the agents under `agents/` and `skills/larv-review/review-findings.md` say so. A plan in Jira has no file to read. Write the listing through the plan's store, beside `places.md`, and point the agents and `review-findings.md` at it. Where the change touches `bin/larv_review/plan.py` `plan_reasons`, which the comprehension seats found hard, make it easier to read.
### 373. Pick the next release's chunks that may run at once by the files and the parts of files each is predicted to touch, and record the prediction beside what each merged chunk touched.
lilleman's call, 2026-11-13, splitting item 361. A planning pass, on the project's rung or above, predicts for each item of the next release the files it will touch and, within each file, the parts: a function, a class, a section heading, a table row. It writes the prediction into the item's detail, where `chunk-preflight` reads it. Two chunks may run together where their predicted parts don't overlap, even in one file. `todo.md` and `CHANGELOG.md` don't count, since item 374 writes them at merge time.
A conflict is not a catastrophe; lilleman expects projects where wall-clock time matters most and tokens spent per hour don't, while tokens per delivered chunk still do (goals 1.4 and 1.5). So the pass picks the set that keeps the most chunks running within the project's parallel limit, item 375's config key, and takes an overlap only where it predicts a small change to the same part. The rules for a chunk hold as today: a chunk takes every item that can share its review, an item with R above 5 forms its own chunk, an item waits while an item that blocks it is still in the plan, and only the next release's items start.
Record each chunk's predicted parts beside the parts its merged diff touched, so a later item can measure how often the predictions miss and tune the pass. Name the source of each part's boundaries per language, such as the Python `ast` module, or say where the pass falls back to line ranges.
### 352. Write a project's plan to its Jira epic: file items as child issues, edit those the loop filed, score unscored issues with a comment, and move a finished item to the status its config names.
lilleman's calls, 2026-11-12. Without asking, the loop may create child issues in the epic, edit the summary, description and scores of issues it created, and comment on and transition any issue in the epic. It never edits the summary or description of an issue a person filed. An issue a teammate files without scores gets scored like any item, with a short comment saying it was scored and why; its scope stays as written. A finished item moves by the transition and to the status the config names, since each Jira workflow differs. An issue the loop files goes into Jira rank by its score among the issues the loop filed. A security finding is filed in the epic like any item, labelled `security` and ranked first, never with a secret's value. R is above 5, so this item ships alone.
Question for lilleman: where does a plan in Jira state its score formula and its bar? A `todo.md` states both under `## Scoring`, as the project's own to tune, and a Jira epic has no such place. One option is two settings in the project's `config.toml`. Another is to rank without a score: security findings first, then by Moves.
### 355. Store a record on the Confluence Cloud page its config names, as markdown converted through the adf-codec shim, and interrupt the human when a teammate saved the page since the loop read it.
@@ -129,6 +94,17 @@ lilleman's calls, 2026-11-12: one page per record, whose ID the config names. Th
lilleman's call, 2026-11-12: the folder replaces the default, as item 347's principles folder does. Readers: the reviewers under `agents/`, the judge's records, larv-review, and the repo check that keeps the standards present.
### 383. Move a finished item of a Jira plan by the transition, and to the status, that the project's config names.
Split from item 352 on 2026-11-15; lilleman's call, 2026-11-12: a finished item moves by the transition and to the status the config names, since each Jira workflow differs. The loop may transition any issue in the epic. A bench of readers, seated as the person who writes a client's `config.toml`, picks the setting's spelling. Once this item and item 382 have shipped, `PlanStore`'s docstring stops saying that `jira_epic` fails an edit or a finish.
Touches:
- `bin/plan_store/jira_epic.py`: `JiraPlan.finish`
- `bin/plan_store/test_jira_epic.py`: new tests of `finish`
- `bin/project_config/settings.py`: `OPTIONAL`, `ProjectConfig`, `load`
- `bin/project_config/main.py`: the help
- `bin/todo_item/main.py`: the help
### 372. Key loop-claude's session, archive, routing state and config-folder commits per chunk, so two chunks of one project run side by side without touching each other's state.
lilleman's call, 2026-11-13, splitting item 361. Items 373 to 375 run several chunks of one project at once. Today a project has one session and one chunk at a time. This item makes two loop-claudes in one project, each on its own chunk, safe to run side by side. It doesn't yet start them; item 375 does that.
@@ -149,15 +125,15 @@ Where the rebase conflicts, the chunk's worker resolves it, and only the review
lilleman's call, 2026-11-12: what a release is differs per client. With none, items name no release, and the architecture and principles passes the release review runs need another trigger, which this item settles and records. Readers: `rank_todo.py`'s release order, chunk-preflight's next release, loop-claude's "release ready to cut", larv-review's release review, `CLAUDE.md` → "Working loop". Cutting a release stays the human's.
### 380. Define "plan" in `CLAUDE.md` → "Vocabulary" as the store a project's config names as `plan`, a `todo.md` or a Jira epic, and reword each line of `CLAUDE.md` and `rules/todo-items.md` that says `todo.md` where it is false for a plan in Jira.
### 382. Edit a Jira issue the loop filed, and score an unscored issue a teammate filed with a comment saying why.
Since item 351 a project's config may name its plan as `jira:https://<site>/browse/<KEY>`, read from the epic's open child issues; `bin/todo-item --help` and `project-config --help` describe it. `CLAUDE.md` → "Vocabulary" still defines **plan** as "the project's `todo.md`, at the path its config names as `plan`", which is false for such a project.
Split from item 352 on 2026-11-15; lilleman's calls, 2026-11-12. The loop edits the summary, description and scores of issues it created, which the `Filed by` mark in the `plan-item` property tells apart, and never the summary or description of an issue a person filed. An issue a teammate files without scores gets scored like any item, with a short comment saying it was scored and why; its scope stays as written. The comment reaches the client's team, so it is in the project's `language`, and its reason comes from whoever scores: `PlanStore.edit` and `todo-item edit` gain a way to pass it, whose spelling a bench of readers picks. Say in `docs/decisions.md` whether the loop may re-score or move a person's issue that already holds scores; the calls name neither.
Start with the definition, then read every line that says `todo.md` in `CLAUDE.md` and `rules/todo-items.md`. Reword a line only where it is false for a plan in Jira, such as "`todo.md` is mandatory in every project" and "Plan `todo.md` as one scored table"; prefer the word "plan", which the definition then covers. Leave a line that is about the file itself: the table's shape, `## Scoring`, `## Renamed`, `rank_todo.py`, and the `paths:` frontmatter that loads the rule. "Working loop" already says a rule names a project's files by their usual paths, so a line that only names the plan as `todo.md` may stay where that sentence covers it; say there that the plan may be no file at all.
A plan in Jira is only read today, until item 352 writes one. Don't describe filing, scoring or finishing an item in Jira as working; say what holds now, and leave the rest to item 352.
Both files load into every session of every project, hence I 3. Keep the change to prose: it adds no rule and removes none.
Touches:
- `bin/plan_store/jira_epic.py`: `JiraPlan.edit`
- `bin/plan_store/test_jira_epic.py`: new tests of `edit`
- `bin/plan_store/stores.py`: `PlanStore.edit`, `FilePlan.edit`
- `bin/todo_item/main.py`: the help, `edit`'s flags
### 375. Run up to the project's configured number of chunks at once, each in its own window of one tmux session named for the project, mark a window whose chunk waits for the human, and refuse to start without tmux at the needed version.
@@ -232,6 +208,10 @@ The architect's 🔀 answer on PR #493 (item 292): four decisions expire "when a
lilleman approved rewording all four as above on 2026-11-12.
### 381. Read a `Touches:` list from a plan kept in Jira as from one in todo.md, with a test that converts a description through `adf_codec`.
The product-owner pass of item 373's chunk asked it, 2026-11-15: `bin/touch_predictions/prediction.py` → `predicted` needs a line that is exactly `Touches:` and bullets that open `- `. A Jira issue's description reaches it through `bin/adf_codec/`, whose library chooses the bullet marker and may escape backticks or a trailing colon. No test shows that a list written in Jira comes out in that shape. Where it doesn't, read the shape the codec writes too.
### 327. Have `larv-review` print a round commit's title prefix, counted from the round's report, and have rule-hook refuse a round title whose counts differ from it.
The 0.8.0 audit (item 284) measured, over the 35 chunks that shipped 0.7.0: 72 commit calls in 33 chunks titled `Answer <pass> round <n>: R 🔴, Y 🟡 (K misread); <what changed>`, about 11k command tokens, most of them the summary. Each worker counts R, Y and K by hand. All three are in the round's report, `<pass>-round-<n>.md` in the review folder: R and Y are its finding headings, and K counts the findings the reviewer marked `[misread]`, as `bin/review_rules/round_titles.py` says. That module parses the counts for `score-outcomes`, which reports them as goal 1.1's signal, and rule-hook's `round_cap.py` checks only the round number, so nothing checks today that the counts match the report. Of the 8 titles whose report the audit could match, none miscounted; one report wrote its markers at line start rather than in `###` headings, so the reports' format varies by reviewer.