Compare commits

..

66 Commits

Author SHA1 Message Date
lilleman 58b098b89d Answer overrides round 2: 0 🔴, 0 🟡 (0 misread); the repeated override is accepted
CI / tests (pull_request) Successful in 2m25s
2026-11-15 14:47:46 +01:00
lilleman 564b022c93 Drop item 372 from the plan: shipped 2026-11-15 14:47:03 +01:00
lilleman e8ef498977 Answer prose round 1: 1 🔴, 6 🟡 (0 misread); keep the slot folder in the changelog, and bring the decision in line with its title 2026-11-15 14:40:43 +01:00
lilleman 4abefba032 Answer product-owner round 1: 0 🔴, 1 🟡 (0 misread); the help names the slot file and says a rerun resumes an open session first, in the stability answer 2026-11-15 14:40:43 +01:00
lilleman e8988b5192 Answer stability round 1: 0 🔴, 1 🟡 (0 misread); a loop takes the lowest free slot whose session is open first, so a rerun resumes a chunk left open 2026-11-15 14:40:43 +01:00
lilleman 4854ea0624 Answer security round 1: 0 🔴, 0 🟡 (0 misread); no finding 2026-11-15 14:33:23 +01:00
lilleman d9c4e71f8d Answer overrides round 1: 0 🔴, 0 🟡 (0 misread); the one override is accepted 2026-11-15 14:33:23 +01:00
lilleman 39163df349 Test the slot a loop takes in process 2026-11-15 14:26:53 +01:00
lilleman 1715c58548 Sort the slot import by its first name
CI / tests (pull_request) Successful in 2m14s
2026-11-15 14:19:41 +01:00
lilleman cbf007f68c Key loop-claude's session per slot, so two loops of one project run side by side 2026-11-15 14:09:55 +01:00
lilleman 510df4b31d Answer overrides round 1: 0 🔴, 0 🟡 (0 misread); the one override is accepted
CI / tests (pull_request) Successful in 1m50s
2026-11-15 13:58:37 +01:00
lilleman f830d764cd Answer prose round 1: 0 🔴, 2 🟡 (0 misread); name the status and the command, and split the answer from its reading 2026-11-15 13:58:37 +01:00
lilleman e71170a2d6 Drop item 385: finish fails where no direct transition leads to the done status
CI / tests (pull_request) Successful in 1m50s
2026-11-15 13:57:19 +01:00
lilleman 3f2046f4be Answer overrides round 2: 0 🔴, 0 🟡 (0 misread); the repeated override is accepted
CI / tests (pull_request) Successful in 1m53s
2026-11-15 13:22:45 +01:00
lilleman 54ab1e4c69 Drop item 383 from the plan: shipped
CI / tests (pull_request) Successful in 1m51s
2026-11-15 13:22:04 +01:00
lilleman d07d108943 Answer stability round 2: 0 🔴, 0 🟡 (0 misread); put the comment on a failed create back over its constant 2026-11-15 13:21:53 +01:00
lilleman e44d5bef50 Answer overrides round 1: 0 🔴, 0 🟡 (0 misread); the one override is accepted 2026-11-15 13:16:07 +01:00
lilleman b057cc0deb Answer prose round 1: 0 🔴, 6 🟡 (1 misread); reword the help, the README, the decision and the edit failure as the reviewer rewrote them 2026-11-15 13:15:11 +01:00
lilleman aa55d01564 Answer product-owner round 1: 0 🔴, 4 🟡 (0 misread); print the two finish settings, name a way out where the issue's status lacks the transition, and file item 385 for a workflow with no direct transition to done 2026-11-15 13:15:11 +01:00
lilleman b60d921427 Answer stability round 1: 1 🔴, 2 🟡 (0 misread); say in CLAUDE.md, the todo rule and the changelog that todo-item finishes an item in Jira, say that a move Jira didn't answer may have landed, and test a transition without a status category 2026-11-15 13:15:11 +01:00
lilleman 9b56738935 Test each odd shape of a transition and that the store passes the config's finish on 2026-11-15 13:04:23 +01:00
lilleman 2b5e4998cc Answer security round 1: 0 🔴, 0 🟡 (0 misread); nothing found 2026-11-15 12:54:13 +01:00
lilleman cab71cc03e Move a finished item of a Jira plan by the transition and to the status the config names
CI / tests (pull_request) Successful in 2m17s
2026-11-15 12:52:10 +01:00
lilleman d432fa207f Drop item 356 from the plan: shipped
CI / tests (pull_request) Successful in 1m47s
2026-11-15 12:42:55 +01:00
lilleman a976ef611d Answer stability round 1: 0 🔴, 1 🟡 (0 misread); the worker decision's title is fixed in prose's answer, and the judge reads standards only where they exist, since reviewer-header already fails on a typo
CI / tests (pull_request) Successful in 1m44s
2026-11-15 12:42:12 +01:00
lilleman 39e4e5d4f8 Answer prose round 1: 0 🔴, 5 🟡 (0 misread); define the review standards at first use, retitle the worker decision, say where the judge reads the rules, and reword the citation, records and help comments 2026-11-15 12:42:12 +01:00
lilleman 2e6f6d91cf Answer product-owner round 1: 0 🔴, 2 🟡 (0 misread); say in the README and help what principles and standards name and what a standards folder holds, and give the upgrade step in the changelog when the item finishes 2026-11-15 12:42:12 +01:00
lilleman b405c81d10 Test the judge's heading of a standards folder outside home 2026-11-15 12:32:21 +01:00
lilleman da5eb0d203 Answer security round 1: 0 🔴, 0 🟡 (0 misread); nothing to change 2026-11-15 12:32:15 +01:00
lilleman 1f963024c8 Hand reviewers the review standards from the folder a project's config names
CI / tests (pull_request) Successful in 1m48s
2026-11-15 12:27:57 +01:00
lilleman dfa2989e8b Record the reading cost of item 356's chunk 2026-11-15 12:21:09 +01:00
lilleman 854a8cccda Drop item 355 from the plan: shipped
CI / tests (pull_request) Successful in 2m6s
2026-11-15 12:10:26 +01:00
lilleman cce83286d3 Answer product-owner round 2: 0 🔴, 1 🟡 (0 misread); say in the help and changelog that a save flattens a mention or a macro, and bound the copy's decision by item 375 2026-11-15 12:09:24 +01:00
lilleman ac71228969 Answer stability round 2: 0 🔴, 0 🟡 (0 misread); every answer holds 2026-11-15 12:09:24 +01:00
lilleman dd9da17240 Answer prose round 1: 0 🔴, 7 🟡 (0 misread); reword save's help, the store's docstrings and touch-predictions, and sort the decision 2026-11-15 12:00:19 +01:00
lilleman addfead4c7 Answer product-owner round 1: 1 🔴, 2 🟡 (0 misread); the 🔴 is fixed in stability's answer, a lost answer still asks the human, and one session runs per project 2026-11-15 12:00:19 +01:00
lilleman e3875d2b05 Answer stability round 1: 2 🔴, 2 🟡 (2 misread); keep a page's version only after its text converts, read adf-codec's table separators, and let ranked records name a page only beside a plan in Jira 2026-11-15 12:00:19 +01:00
lilleman 6326edcd5b Answer security round 1: 0 🔴, 0 🟡 (0 misread); nothing to change 2026-11-15 11:44:28 +01:00
lilleman e78725db51 Test the goals branch of project-record's store, a refused conversion and an unmakeable state folder 2026-11-15 11:44:00 +01:00
lilleman 60bc76c876 Test the page store's failures, Confluence's error messages and where project-record keeps the version 2026-11-15 11:36:54 +01:00
lilleman 7f5c3fcbbc Store a record on the Confluence Cloud page its config names, and refuse to overwrite a teammate's save
CI / tests (pull_request) Failing after 1m54s
2026-11-15 11:27:54 +01:00
lilleman 6687c913e2 Answer prose round 1: 0 🔴, 5 🟡 (0 misread); cut two repeats, name ranking.py, say what a security finding goes before, and sort Touches
CI / tests (pull_request) Successful in 1m59s
2026-11-15 11:16:50 +01:00
lilleman a194747012 Record the answer to item 384: a plan in Jira states its formula and bar in config.toml
CI / tests (pull_request) Successful in 2m0s
2026-11-15 11:14:44 +01:00
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
57 changed files with 2609 additions and 213 deletions
+3
View File
@@ -137,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
+7 -1
View File
@@ -2,6 +2,12 @@
## Unreleased
- Two loop-claude runs in one project now work side by side, each on its own chunk. Each loop holds a slot of the project, a locked file under `~/.local/state/loop-claude/<key>/`, and names its session after it: the first loop's session keeps its name, `A <key> loop-claude`, and the second's is `A <key> loop-claude 2`. A rerun resumes a chunk left open first. A commit in the config's folder now takes only the file it changed, as `git commit -m <title> -- <file>`.
- `todo-item finish` finishes an item of a plan kept in a Jira epic: it moves the item's issue by the workflow transition, and to the status, that the config's new optional settings `jira-finish-transition` and `jira-finish-status` name, both as Jira shows them. It refuses a transition that leads to another status, or to one Jira doesn't count as done, and fails where the config sets neither.
- Reviewers and loop-claude's judge read the review standards from the folder a project's config sets as `standards`, in place of `~/.claude/skills/larv-review/standards/`. The setting is required. To upgrade, add `standards = "~/.claude/skills/larv-review/standards"` to every config under `~/.claude-projects/` right after `deploy-release` moves `~/.claude` to this release, and not before.
- A project's config may keep each of its five records on a Confluence Cloud page: set, for example, `decisions = "confluence:https://<site>/wiki/spaces/<space>/pages/<page ID>"`, with the credentials in the config's `env-file`. `decisions` and `comprehension-history` may name a page only where `plan` names a Jira epic. The loop reads and writes the page as markdown, so a save replaces a mention or a macro on it with plain text. It never overwrites a teammate's edit: where someone saved the page since the loop read it, `project-record save` refuses and the loop asks you.
- `todo-item add` files an item into a plan kept in a Jira epic: a Task under the epic, under the project's Fix Version for the release, labelled `security` for a security finding and linked to each item that blocks it. Editing an issue still happens in Jira.
- An item of the next release may predict the files and parts it will touch, under a `Touches:` line in its detail. `chunk-preflight` then names the items that may start chunks at once, and the new `touch-predictions record` keeps each prediction beside what the merged chunk touched, in the record a project's config places with `touch-predictions`.
- CLAUDE.md and the todo-items rule define the plan as a todo.md or a Jira epic, and say plan where todo.md was false for a Jira plan.
- Reviewers without a shell read the plan from a listing that larv-review writes into the review folder, whichever store holds it.
- 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.
@@ -17,7 +23,7 @@
- The technical principles ask for code in files and folders before `// --- name ---` banner comments. They also ask for an entry point a newcomer finds at once: the root holds it, the README and the files a tool reads only from there.
- In a client project, the loop reads the team's own `CLAUDE.md` and `AGENTS.md` and proposes each change that aligns them with this setup in a pull request of its own. Where the team declines or doesn't answer, the loop follows the team's rule unless it breaks a project goal, and records the conflict as a decision in the `decisions` record.
- The new `project-record open <record>` prints the file in which an agent reads and edits one of a project's five records (`decisions`, `score-anchors`, `comprehension-history`, `reading-cost` and `changelog`), and `project-record save <record>` stores the edit. Every tool now reads and writes a record the same one way, so that a later release can keep a record outside files. No config needs a change.
- `loop-inbox` is gone. loop-claude now asks its questions only on its own terminal. A line typed there answers a question, and `/talk` opens the worker's session. The DM still tells you a loop waits. To upgrade, quit any `loop-inbox` still open and remove your `~/.local/bin/loop-inbox` link. Once every loop started before the upgrade has reloaded or ended, remove the folder `~/.local/state/loop-claude/`, which nothing reads any more.
- `loop-inbox` is gone. loop-claude now asks its questions only on its own terminal. A line typed there answers a question, and `/talk` opens the worker's session. The DM still tells you a loop waits. To upgrade, quit any `loop-inbox` still open and remove your `~/.local/bin/loop-inbox` link.
- rule-hook refuses a Read or a Grep of `~/.claude/.env` or of the `env-file` any project's config names, and a Bash command that names either or searches a folder holding either with `ag`, `grep -r` or `rg`, unless the tool skips the file as hidden or ignored, so that a worker doesn't put a credential in its transcript in passing. A command that hides the path, such as behind a glob or a variable, still goes through.
- A project's config names the service for loop-claude's DMs: `notifier = "mattermost"` or `"slack"`, with the bot's token and the recipient in the `env-file`. To upgrade, move the Mattermost keys from `~/.claude/.env` into a file outside the checkout and the config's folder, such as `~/.claude-projects/<key>.env`, name it as `env-file` and add `notifier = "mattermost"`. A project with no `notifier` gets no DM, and `~/.claude/.env` is no longer read. A failure names each missing key and holds no token.
- `mattermost-dm` is now `notify`, which sends through the project's `notifier`; `notify --help` names the keys.
+7 -7
View File
@@ -2,11 +2,11 @@
## 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. Where the config names a Jira epic as the plan, the plan is the epic's open child issues, which no tool writes yet. 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 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 writes only a file for now. Two open the file itself: whoever plans a release, to compare Scores across releases, which `todo-item list` doesn't print; and whoever edits `## Scoring` or `## Renamed`, or reshapes an old table.
- **Read and change the plan's items only with `~/.claude/bin/todo-item`**, which lists, shows, files, edits, moves and finishes them; `todo-item --help` says how. It reads a plan in Jira as it does a file, and there it files and finishes an item but doesn't edit or move one yet. Two open the file itself: whoever plans a release, to compare Scores across releases, which `todo-item list` doesn't print; and whoever edits `## Scoring` or `## Renamed`, or reshapes an old table.
- **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.
@@ -46,7 +46,7 @@ Write the thing, not an introduction to it. State what holds and stop; name a re
Write negations as people say them: after a verb, or after its preposition, write `doesn't <verb> anything` or `anyone`, never `<verb> nothing` or `no one`. BANNED: `stops nothing`, `depends on no one`, `so answering in time costs nothing`. GOOD: `doesn't stop anything`, `doesn't depend on anyone`, `so answering in time doesn't cost anything`.
Reviewers hold prose to the full rules, with examples: `~/.claude/skills/larv-review/standards/prose.md`.
Reviewers hold prose to the full rules, with examples: `prose.md` in the project's review standards, which "Topic rules" below defines.
## Public API specs
- Text in public API specs (OpenAPI `description`/`title` fields, in a spec file or in code, and the generated api-docs) is read by external consumers. Never leak internal references: no ticket IDs, internal URLs, repo/system code-names, "see ticket X". Describe behaviour in consumer terms. GOOD: `Deprecated alias for paymentAccountId`. BANNED: `…will be removed (ABC-123)`.
@@ -60,7 +60,7 @@ Claude Code loads a rule file when a session writes a file its `paths:` frontmat
- Goals and audience: `~/.claude/rules/goals-and-audience.md`.
- Plan items, their scores and Exempt reasons: `~/.claude/rules/todo-items.md`. Read it before you file, score, edit or move an item: a session that runs `todo-item` never opens `todo.md` itself, so the rule doesn't load.
The rules only reviewers apply, for quality, comments, READMEs and prose, live in `~/.claude/skills/larv-review/standards/`.
The rules only reviewers apply, for quality, comments, READMEs and prose, are the project's review standards: the folder its config sets as `standards`, which `~/.claude/bin/project-config standards` prints.
## Working with the codebase
- Always start a new git worktree when doing something in a codebase, and clean it up when done. Unless told otherwise, branch it off a freshly-updated default branch (`git fetch origin`, then base on `origin/main`), not whatever happens to be checked out.
@@ -78,7 +78,7 @@ The rules only reviewers apply, for quality, comments, READMEs and prose, live i
1. A re-score of the item's L, made on the project's rung or above, picks a rung above yours.
2. The same failing test or finding survives two fix attempts.
3. A pass reports a 🔴 in round 2.
4. A review rules the work below standard: systems-architect's BLOCK, a finding against larv-review's `standards/quality.md`, or a vote `record-ruling` counts as worse, in the report that stands after any relaunch one rung up (`larv-review` §3 → "Rung up"). It doesn't fire where the fix changes only prose (`larv-review` §3 says what is prose): fix that on your own rung.
4. A review rules the work below standard: systems-architect's BLOCK, a finding against the review standards' `quality.md`, or a vote `record-ruling` counts as worse, in the report that stands after any relaunch one rung up (`larv-review` §3 → "Rung up"). It doesn't fire where the fix changes only prose (`larv-review` §3 says what is prose): fix that on your own rung.
When one fires, hand the hard part, edits included, to a subagent on the rung loop-claude's prompt names, one above yours. Open the subagent's prompt with the marker loop-claude's prompt gives, then the trigger's evidence. Each later subagent on that task runs on that rung or higher, and each further escalation trigger moves the task one rung higher, up to the highest rung loop-claude's prompt names. Ask the human before going higher. Where loop-claude's prompt names no escalation, as on the ladder's top rung or off it, keep the task in your own thread.
- Give a subagent only the access its job needs, and state the limits in its prompt. One that only reads, such as a prose review, gets no shell and no edits. A reviewer under `~/.claude/agents/` writes only its report, under `~/.local/state/larv-review/`, and rule-hook refuses it every other Write, every Edit and every MultiEdit. One that probes a build tags the image as throwaway and removes it afterwards, writes only to a folder it makes under the chunk's review folder (`~/.claude/bin/larv-review review-folder` prints it), and removes no image or file it did not create.
@@ -97,7 +97,7 @@ The rules only reviewers apply, for quality, comments, READMEs and prose, live i
- PR summary: short and concise. No test plan (it lives in the ticket), no link to the ticket (it's in the title).
- Branch for a ticket: exactly the ticket ID, nothing more. `ABC-123`, never `ABC-123-some-description`.
- Branch for a plan item without a ticket: `item-<ID>`, in the worktree `<checkout>-item-<ID>` beside the checkout, as `chunk-preflight` makes them. Under a `branch` template, `chunk-preflight` names both by the template.
- Where the project's config keeps a file in the config's folder, `~/.claude-projects/<key>/`, such as the plan or a record, commit each change you make to that file in the folder's own git repo, on its only branch. Title that commit as you would title the change in the checkout: where a commit in the checkout goes with it, give it the same title.
- Where the project's config keeps a file in the config's folder, `~/.claude-projects/<key>/`, such as the plan or a record, commit each change you make to that file in the folder's own git repo, on its only branch. Two chunks may commit there at once, so commit only that file: `git commit -m <title> -- <file>`, after `git add <file>` where it is new. Where git finds `index.lock` held, the other chunk is committing: try again. Title that commit as you would title the change in the checkout: where a commit in the checkout goes with it, give it the same title.
- Use `gh` on GitHub remotes and `tea` on Gitea remotes (e.g. `gitea.larvit.se`) — same command shape: `tea pr list|create`, `tea issue`, `tea release`, `tea api`. Everything in this section applies to both.
- On GitHub and Gitea, open a chunk's pull request as a draft, mark it ready and merge it with `~/.claude/bin/chunk-pr`, which picks `gh` or `tea` from the remote; `chunk-pr --help` says how. Once it has merged, run `chunk-pr clean` in the chunk's worktree: it removes the worktree and the branch and fast-forwards the main checkout.
@@ -130,7 +130,7 @@ Claude Code reads this section by its heading when it compacts a conversation. K
- **goals file** — the file holding a project's `## Goals` and `## Audience`: the one its config names as `goals-and-audience`. Read it in the file `~/.claude/bin/project-record open goals-and-audience` prints. It is `README.md`, unless a client's project keeps it in the config's folder, or in a Jira epic's description, which the loop only reads.
- **interrupt** — `loop-claude` asking the human, on its terminal, for a decision that is theirs. They type a one-line answer there, or `/talk` to open the worker's session there with `claude --resume`. A release ready to cut opens that session at once. A routing call opens claude on that terminal too, in `~/code/claude-config`, the checkout where this setup is developed.
- **judge** — the headless claude that reads a worker's transcript each cycle and decides whether to interrupt and whether the chunk is finished.
- **judge's records** — the files the judge reads beside the premises: the project's `AGENTS.md` and `docs/decisions.md`, then the human's `~/.claude/CLAUDE.md` and the `.md` files in `~/.claude/rules/` and `~/.claude/skills/larv-review/standards/`.
- **judge's records** — the files the judge reads beside the premises: the project's `AGENTS.md` and `docs/decisions.md`, then the human's `~/.claude/CLAUDE.md` and the `.md` files in `~/.claude/rules/`, then those in the project's review standards.
- **paired ruling** — the seats vote whether the project reads better, the same or worse at the branch's head than at the base, the commit `larv-review ruling-base` prints; `larv-review --help` says how the votes make the ruling.
- **pass** — one kind of review a chunk may take, run in rounds by its reviewers until clean; `larv-review` §3 lists them.
- **place** — the smallest addressable unit, such as a function or a section heading, that a seat names with its `path:line` when it judges how hard the project is to read there.
+11 -5
View File
@@ -1,6 +1,6 @@
# Claude Code configuration
My personal `~/.claude`, version controlled: `CLAUDE.md` and `rules/` for instructions, the words under `CLAUDE.md` → "Vocabulary"; `.claude/rules/` for the rules that load in this repo alone; `agents/` and `skills/`; `principles/` and `skills/larv-review/standards/` for what the reviewer agents hold projects to; `docs/` for decisions and the comprehension history; `settings.json` for the harness and `.claude/settings.json` for the harness inside this repo; `CHANGELOG.md` and `todo.md`; the tools in `bin/`; `workflow-bench/`, the scripts and prompts of the 2026-09-30 bench of larv-review and of the 2026-11-12 bench of the advisor tool; `reviewer-merge-trials/`, the 2026-11-09 trials of merging reviewers, with their method, results and scripts; `judge-field-trials/`, the 2026-11-11 trials of which facts code could read in place of loop-claude's judge, with their results and scripts; `stability-skip-count/`, the 2026-11-12 count of archived stability rounds, with its script, from which larv-review took when to skip a stability round 2; and `presentation/`, a page that explains this setup to newcomers, with the script that prints it to PDF.
My personal `~/.claude`, version controlled: `CLAUDE.md` and `rules/` for instructions, the words under `CLAUDE.md` → "Vocabulary"; `.claude/rules/` for the rules that load in this repo alone; `agents/` and `skills/`; `principles/` and `skills/larv-review/standards/` for what the reviewer agents hold projects to, which a project's config names as `principles` and `standards`; `docs/` for decisions and the comprehension history; `settings.json` for the harness and `.claude/settings.json` for the harness inside this repo; `CHANGELOG.md` and `todo.md`; the tools in `bin/`; `workflow-bench/`, the scripts and prompts of the 2026-09-30 bench of larv-review and of the 2026-11-12 bench of the advisor tool; `reviewer-merge-trials/`, the 2026-11-09 trials of merging reviewers, with their method, results and scripts; `judge-field-trials/`, the 2026-11-11 trials of which facts code could read in place of loop-claude's judge, with their results and scripts; `stability-skip-count/`, the 2026-11-12 count of archived stability rounds, with its script, from which larv-review took when to skip a stability round 2; and `presentation/`, a page that explains this setup to newcomers, with the script that prints it to PDF.
## Goals
@@ -79,7 +79,7 @@ To get loop-claude's questions and stops as DMs from a bot, write the bot's toke
Each project the loop runs in has a folder, `~/.claude-projects/<key>/`, where `<key>` is the project's name, and a config in it, `config.toml`. The folder is a git repo of its own, so the config has a history and a client's files never enter this repo. The loop commits each change it makes to a file there, such as the plan, in that repo, titled as its commits in the checkout. A project is a whole git checkout, never a subfolder of one.
The config names the project's main checkout and the path of every file the loop keeps for it. No path setting has a default: `project-config` fails and names each setting a config leaves out. A path is `checkout:<path>` inside the checkout, `folder:<path>` inside the config's folder, or one that starts with `/` or `~/`. Every tool reads and writes each file at the path its setting gives, and `chunk-preflight` and `todo-item` print those paths for the agents. Five of the settings name the project's records: `decisions`, `score-anchors`, `comprehension-history`, `reading-cost` and `changelog`. Keep each file's name, such as `todo.md`: the rules for a file load by its name. A project of your own keeps every file but the principles in its checkout:
The config names the project's main checkout and the path of every file the loop keeps for it. No path setting has a default: `project-config` fails and names each setting a config leaves out. A path is `checkout:<path>` inside the checkout, `folder:<path>` inside the config's folder, or one that starts with `/` or `~/`. Every tool reads and writes each file at the path its setting gives, and `chunk-preflight` and `todo-item` print those paths for the agents. Five of the settings name the project's records: `decisions`, `score-anchors`, `comprehension-history`, `reading-cost` and `changelog`. Keep each file's name, such as `todo.md`: the rules for a file load by its name. A project of your own keeps every file but the principles and the review standards in its checkout:
```toml
checkout = "~/code/log"
@@ -92,10 +92,15 @@ reading-cost = "checkout:docs/reading-cost.md"
changelog = "checkout:CHANGELOG.md"
goals-and-audience = "checkout:README.md"
principles = "~/.claude/principles"
standards = "~/.claude/skills/larv-review/standards"
```
`principles` and `standards` name the folders the reviewers hold the project to: the technical principles and the review standards. Both ship with this setup, at the paths above. A folder of your own replaces the shipped one. A standards folder must hold `quality.md`, `prose.md`, `comments.md` and `readme.md`, since the reviewers and the rules name those files.
A project may also set `env-file`, the file of `KEY=value` credentials its tools read, such as `env-file = "~/.claude-projects/log.env"`. It is a path that starts with `/` or `~/`, outside the checkout and the config's folder, so that no git remote receives it. A tool that needs a key fails and names each one the file lacks. No failure message, prompt, log line or archived loop output holds a token from the file. rule-hook refuses a Read or a Grep of the file and a Bash command that names it or searches a folder holding it with `ag`, `grep -r` or `rg`, unless the tool skips the file as hidden or ignored, so a worker doesn't read it in passing; `rule-hook --help` says which calls it checks. A project without the setting has no credentials, and never reads another project's. `project-config env-file` prints the path.
A project may also set `touch-predictions`, a path spelt as `changelog`'s is, such as `touch-predictions = "checkout:docs/touch-predictions.md"`. `touch-predictions record` appends each chunk's predicted files and parts there, beside those it touched. A project that leaves it out keeps no such record.
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.
@@ -115,7 +120,7 @@ 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 an issue yet. `todo-item edit` and `move` fail, so edit its issues in Jira. For `todo-item finish`, the config names the workflow transition that finishes an item and the status it leads to, both as Jira shows them: `jira-finish-transition = "Mark as done"` and `jira-finish-status = "Done"`. Finish then moves the item's issue by that transition. It refuses a transition that leads to another status, or to one Jira doesn't count as done, and fails where the config sets neither. `todo-item add` needs the item's release among the Jira project's Fix Versions, named as `1.2.0` or `v1.2.0`. `rank_todo.py` doesn't rank it, since Jira's backlog does. The four things not supported for a plan outside the checkout, above, are not supported for a plan in Jira either.
A 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.
@@ -180,6 +185,7 @@ 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/`, `model_routing/`, `notifier/`, `plan_store/`, `record_store/`, `release_plan/`, `review_rules/`, `rung_replay/`, `text_files/` and `transcript_archive/` serve more than one tool.
@@ -199,10 +205,10 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a
- `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.
- `record_store/` reads and writes a project's records, each through the store the project's config names (`stores.py`): a markdown file, a Confluence Cloud page (`confluence_page.py`), or, for the goals, a Jira epic's description (`jira_description.py`). `contract.py` holds the tests every backend must pass, and `fakes.py` a store in memory that the tests of other tools use.
- `release_plan/` reads `todo.md`'s items table and release versions, says which release is next and whether it is ready to cut (`release_standing.py`), and ranks the plan (`ranking.py`, with its score formula in `formula.py` and its blocker order in `blockers.py`). `goals_file.py` reads the goals file's sections, goals and goal weights, for the ranking and for `loop_claude`'s premises, and `citations.py` holds `todo.md` and `docs/decisions.md` to each other. `plan_file.py` ranks, checks and writes a `todo.md`, for `larv_review`, `rank_todo.py` and `rule_hook`.
- `repo_checks/` tests the repo itself.
- `rest_client/` sends a JSON request to a REST API and reads its credentials from an env file, for `mattermost_dm`, `slack_dm` and `plan_store`.
- `rest_client/` sends a JSON request to a REST API and reads its credentials from an env file, for `mattermost_dm`, `slack_dm`, `plan_store` and `record_store`.
- `review_rules/` holds the larv-review rules that several tools apply: its passes, its review folder, its round commit titles and the comprehension history's format.
- `routing_figures/` measures loop-claude's archive, and each of its projects' default branches, for loop-claude's routing calls.
- `rung_replay/` holds what `judge_replay` and `review_replay` share: the parallel replay runner, the argument reader, the candidate rungs and the exits, and `judge_replay`'s rung search. It reads `loop_claude`'s retry count and models file, and finds that file through `loop_state`'s paths.
+3 -3
View File
@@ -9,13 +9,13 @@ You read the prose as someone who did not write it: you see only what it says, n
The bar, read each time, since it changes:
- every file under `~/.claude/skills/larv-review/standards/`, of `quality.md` only "A false claim is a bug";
- every file in the folder your prompt's `Review standards:` line names, of `quality.md` only "A false claim is a bug";
- `~/.claude/CLAUDE.md` → "Public API specs";
- each file under `~/.claude/rules/` whose `paths:` frontmatter matches a file the diff changes.
Verdict, severities and rounds: ~/.claude/skills/larv-review/review-findings.md.
Your prompt's `Prose language:` line names the language the project's config sets. Apply every check below to prose in that language, by that language's grammar and idiom. The bar's examples are English: find the same fault in the other language, never the same English words. Prose in another language is a finding, except what `standards/prose.md` says stays English. Write your report in English.
Your prompt's `Prose language:` line names the language the project's config sets. Apply every check below to prose in that language, by that language's grammar and idiom. The bar's examples are English: find the same fault in the other language, never the same English words. Prose in another language is a finding, except what `prose.md` in the review standards says stays English. Write your report in English.
## Checks, in priority order
@@ -23,7 +23,7 @@ Run them in this order. A fix for a later check never breaks an earlier one.
1. **Easy to understand.** Read each sentence once, cold. A sentence you had to reread, a term used before it is explained, or an "it" or "them" that could point at two things is a finding. Fix: **Rewrite**, giving the plain sentence.
2. **Most important first.** Name the document's reader and what they want to know first. Check that the sections run in that order, then the paragraphs within each section, then the items within each list. If not, fix: **Reorder**, naming the new order. A section so long that a reader has to search it gets sub-headings or an index. Fix: **Split**.
3. **Default to delete.** A line the reader does not need fails. Fix: **Delete** what the code, a type, a test name, the README or another rule already says. Fix: **Move** a choice made in one place to a comment there, one made in more places to `docs/decisions.md` with its title in `AGENTS.md` unless a project principle there covers it, and a goal to the README. A pointer standing where a definition belongs (`~/.claude/skills/larv-review/standards/comments.md` → "Links and pointers", "A pointer is not a definition") gets the fix **Move back**: inline the definition, and leave the reasoning where it is.
3. **Default to delete.** A line the reader does not need fails. Fix: **Delete** what the code, a type, a test name, the README or another rule already says. Fix: **Move** a choice made in one place to a comment there, one made in more places to `docs/decisions.md` with its title in `AGENTS.md` unless a project principle there covers it, and a goal to the README. A pointer standing where a definition belongs (the review standards' `comments.md` → "Links and pointers", "A pointer is not a definition") gets the fix **Move back**: inline the definition, and leave the reasoning where it is.
4. **Short.** Words that do not clearly help 1–3 fail. Fix: **Cut**.
Also report a list whose order carries no meaning and is not sorted (the technical principles' "Deterministic order", in the folder your prompt's `Technical principles:` line names; without one, open your report by saying so), a sentence contradicting another, a claim the code shows false, and a word used against `CLAUDE.md` → "Vocabulary".
+1 -1
View File
@@ -11,7 +11,7 @@ You are an elite stability-focused code reviewer with deep expertise in defensiv
## First Steps
1. **Scope the change.** You review every PR; a fresh invocation has no prior context, so determine the diff yourself. Diff the PR branch against its base (`gh pr diff`, or `git merge-base <base> HEAD` then `git diff`), and review the changed lines **plus enough surrounding code and callers** to judge correctness — read the whole changed file when practical; a diff alone hides whether a caller breaks. Read the PR description and, when the project uses an issue tracker (project-specific — check its docs) and the change references a ticket, that ticket: the diff is judged against its stated intent, and a scope mismatch in either direction is a finding — claimed-but-unimplemented, and implemented-but-unasked (#2).
2. **Read every file in the folder your prompt's `Technical principles:` line names**, and `~/.claude/skills/larv-review/standards/quality.md`. These are mandatory guidelines; all code MUST comply with each that applies. A file's `Applies to` line says what it covers; one without the line covers every change. Re-read each time — they change. Flag violations prominently. Where your prompt has no such line, without one, open your report by saying so.
2. **Read every file in the folder your prompt's `Technical principles:` line names**, and `quality.md` in the folder your prompt's `Review standards:` line names. These are mandatory guidelines; all code MUST comply with each that applies. A file's `Applies to` line says what it covers; one without the line covers every change. Re-read each time — they change. Flag violations prominently. Where your prompt lacks either line, open your report by saying so.
3. **Read README.md, AGENTS.md and `docs/decisions.md`** in the current project for project-specific conventions, build instructions, tooling, and the accepted trade-offs a reviewer should honor rather than re-flag. Note the documented test, lint, and static-analysis commands — you run them unless your prompt hands you a passing run on the head (step 4).
4. **Verify, don't just read.** Where your prompt hands you the commit on which the worker's run of the test suite and static analysis last passed, and it is the head, don't run them again, and say so in Coverage & Verification. Otherwise run the test suite and static analysis/linters through the project's container tooling, unless `~/.claude/bin/project-config tooling-on-host` prints true or a decision puts them on the host; tear down test containers afterwards. Run the full suite under `~/.claude/bin/run-heavy`. Run it in the background or with the Bash tool's longest timeout: that timeout includes the wait for a slot. A full-suite run catches broken callers that diff-reading misses. When a suspected bug is cheap to confirm, reproduce it — a scratch script, a targeted test run — before reporting it. Make scratch work with Bash, since Write is for your report alone. Put it in a directory you create for this run, and delete it when done; don't delete anything else, since a directory the prompt names may hold other agents' files. Leave the working tree exactly as you found it. Anything you could not run goes in Coverage & Verification, never silently skipped.
5. **Judge the surviving mutants.** Your prompt hands you what the project's mutation command printed on the change, with the commit it ran on: the mutants of changed lines that no test kills, or the message of a run that failed. Ignore a surviving mutant that leaves behaviour unchanged, or changes only message or log text no caller or user depends on. Report one 🟡 per test to add or strengthen, naming the surviving mutants it would catch. Where the prompt doesn't hand you any output, or names a commit other than the head, run the command yourself in the change's checkout, through run-heavy as in step 4: the one the project's README documents, else `~/.claude/bin/run-heavy ~/.claude/bin/mutate-changes --prefix '<how the project runs its tools>'`. `~/.claude/bin/mutate-changes --help` says which tool it runs for each language, how to set `--jobs`, and what it prints. Mutation-test the changed code that no run mutated, in a language mutate-changes doesn't cover or where a run failed, with a widely deployed mutation tool limited to the changed lines, else with mutants you make by hand. Report the wall time and mutant count in Coverage & Verification, or why nothing was mutated.
+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()
+5 -5
View File
@@ -130,17 +130,17 @@ reviewer-header takes the name of a pass that an agent under agents/ reviews, sp
prints it, such as stability. It prints the header of the prompt that launches the pass's reviewer
in its next round: the pass and round, the branch's open pull request at its pushed head, the
worktree and branch, the merge base of HEAD and the default branch, and the paths of the reviewer's
report, the branch diff, the folder of technical principles the project's config sets, the goals
and the plan and, for architecture and stability, the places. For a reviewer whose
report, the branch diff, the folders of technical principles and review standards the project's
config sets, the goals and the plan and, for architecture and stability, the places. For a reviewer whose
definition under ~/.claude/agents/ has `omitClaudeMd: true`, it then names the file that holds the
project principles and decision titles, where the project keeps one. It writes the diff, from
that base to HEAD, into the chunk's review folder as branch-<short HEAD>.diff, writes what
places prints into places.md, and lists the plan's items into
plan.md, whatever store holds the plan; a file whose text is unchanged is left as it is. With --rerun, the
header names the report of a relaunch one rung up, in the same round, and the report that asked for
it. It exits 1 when the pass takes no more rounds, when `project-config` fails in the checkout, when the
principles folder it names is not a folder with a file in it, or, with --rerun, when the report that
asked is missing.
it. It exits 1 when the pass takes no more rounds, when `project-config` fails in the checkout, when
the principles or standards folder is not a folder with a file in it, or, with --rerun, when the
report that asked is missing.
reviewer-context is the SubagentStart hook. It reads the hook's input on stdin. For a reviewer
whose definition under ~/.claude/agents/ has `omitClaudeMd: true`, and so starts without CLAUDE.md,
+8 -5
View File
@@ -34,6 +34,7 @@ class Launch:
folder: pathlib.Path
diff: pathlib.Path
principles: pathlib.Path
standards: pathlib.Path
goals: pathlib.Path
# The plan's listing, for a reviewer that reads files, whatever store holds the plan.
plan: pathlib.Path
@@ -59,6 +60,7 @@ class Launch:
f"Report: write it to {report}.",
f"Diff: {self.diff}",
f"Technical principles: {self.principles}",
f"Review standards: {self.standards}",
f"Goals and audience: {self.goals}",
f"Plan: {self.plan}",
f"Prose language: {self.language}.",
@@ -97,10 +99,11 @@ def reviewer_header(default: str, pass_: str, rerun: bool, home: pathlib.Path) -
config = located(None, home)
if isinstance(config, Failure):
return config
principles = config.paths["principles"]
# A typo in the config would otherwise hand every reviewer an empty folder, and the review would run with no principles.
if not principles.is_dir() or not any(principles.iterdir()):
return Failure(f"{principles} is not a folder with a file in it; {config.folder / 'config.toml'} sets it as `principles`")
principles, standards = config.paths["principles"], config.paths["standards"]
# A typo in the config would otherwise hand every reviewer an empty folder, and the review would run with no principles or standards.
empty = next((setting for setting in ("principles", "standards") if not config.paths[setting].is_dir() or not any(config.paths[setting].iterdir())), None)
if empty is not None:
return Failure(f"{config.paths[empty]} is not a folder with a file in it; {config.folder / 'config.toml'} sets it as `{empty}`")
decisions = local_file(store(config, "decisions"), folder / "decisions.md")
if isinstance(decisions, Failure):
return decisions
@@ -108,7 +111,7 @@ def reviewer_header(default: str, pass_: str, rerun: bool, home: pathlib.Path) -
goals = local_file(goals_store(config), folder / "goals.md")
if isinstance(goals, Failure):
return goals
launch = Launch(pass_, round_, rerun, pull_named(worktree, branch), worktree, branch, base, default, folder, folder / f"branch-{head}.diff", principles, goals, folder / "plan.md", starts_bare(next((agent for name, agent in REVIEWERS.items() if name == pass_), ""), home), config.paths["working-rules"], decisions, config.language)
launch = Launch(pass_, round_, rerun, pull_named(worktree, branch), worktree, branch, base, default, folder, folder / f"branch-{head}.diff", principles, standards, goals, folder / "plan.md", starts_bare(next((agent for name, agent in REVIEWERS.items() if name == pass_), ""), home), config.paths["working-rules"], decisions, config.language)
if rerun and not launch.asked().exists():
return Failure(f"no report asked for a rerun of {pass_}'s round {round_}: {launch.asked()} is missing; relaunch before you commit the round's answers")
written = write_inputs(launch, base, home, plan_listing(plan_store(config)))
+35 -14
View File
@@ -182,6 +182,14 @@ class History(unittest.TestCase):
votes = {"Mid A": ["better", "worse", "same", "same", "better"]}
self.assertEqual(ruling_entry("2026-10-09T09:47:25Z, PR #232 at 324d650, against 12d6d75", [seat], votes, votes, "same"), "\n".join(sample) + "\n")
def test_reads_tables_whose_separators_hold_spaces_as_adf_codec_writes_them(self):
scoring = ScoringRun([Seat("Junior A", "", [])], {"Junior A": ["7", "6.5", "7", "7", "7"]}, [decimal.Decimal(mean) for mean in ("7.00", "6.50", "7.00", "7.00", "7.00")])
history = appended("", scoring_entry("2026-10-08T12:00:00Z, PR #1 at aaaaaaa", scoring))
spaced = "\n".join("| " + " | ".join(["---"] * line.count("---")) + " |" if line.startswith("|-") else line for line in history.splitlines())
self.assertNotEqual(spaced, history)
self.assertEqual(entries(spaced)[0].score_rows, entries(history)[0].score_rows)
self.assertIn("Mean", entries(spaced)[0].score_rows)
def test_reads_back_what_it_writes(self):
seats = [Seat("Mid A", said("better", "worse"), ["`bin/a.py:3` `f`: hard, with `:9` `g`"]), Seat("Inherited architect", said("worse", "worse"), [])]
written = {"Mid A": ["same", "worse", "same", "same", "better"], "Inherited architect": ["same", "worse", "same", "same", "worse"]}
@@ -475,6 +483,7 @@ reading-cost = "checkout:docs/reading-cost.md"
changelog = "checkout:CHANGELOG.md"
goals-and-audience = "checkout:README.md"
principles = "~/principles"
standards = "~/standards"
"""
@@ -497,6 +506,8 @@ class LarvReviewTool(unittest.TestCase):
self.config.write_text(PROJECT_CONFIG)
(root / "principles").mkdir()
(root / "principles" / "technical-principles.md").write_text("# Principles\n")
(root / "standards").mkdir()
(root / "standards" / "quality.md").write_text("# Quality\n")
def git(self, *args):
return subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@t", *args], cwd=self.checkout, check=True, env=self.env, capture_output=True, text=True).stdout
@@ -1120,6 +1131,7 @@ class LarvReviewTool(unittest.TestCase):
f"Report: write it to {folder}/stability-round-1.md.\n"
f"Diff: {folder}/branch-{short}.diff\n"
f"Technical principles: {self.checkout.parent}/principles\n"
f"Review standards: {self.checkout.parent}/standards\n"
f"Goals and audience: {self.checkout}/README.md\n"
f"Plan: {folder}/plan.md\n"
"Prose language: English.\n"
@@ -1212,6 +1224,9 @@ class LarvReviewTool(unittest.TestCase):
def test_reviewer_header_names_the_principles_folder_the_projects_config_sets(self):
self.assertEqual(self.header_line("Technical principles:", "prose"), f"Technical principles: {self.checkout.parent}/principles")
def test_reviewer_header_names_the_review_standards_folder_the_projects_config_sets(self):
self.assertEqual(self.header_line("Review standards:", "prose"), f"Review standards: {self.checkout.parent}/standards")
def test_reviewer_header_names_the_language_and_counts_rounds_through_the_commit_title_the_projects_config_sets(self):
self.config.write_text(PROJECT_CONFIG + 'language = "Swedish"\ncommit-title = "PAY-{id} - {summary}"\n')
self.commit("PAY-7 - Answer prose round 1: 0 🔴, 1 🟡 (0 misread); a")
@@ -1240,11 +1255,13 @@ class LarvReviewTool(unittest.TestCase):
self.assertEqual((ran.returncode, ran.stdout), (1, ""))
self.assertIn("cannot read the epic ABC-12", ran.stderr)
def test_reviewer_header_fails_with_the_configs_message_where_it_sets_no_principles_folder(self):
self.config.write_text(PROJECT_CONFIG.replace('principles = "~/principles"\n', ""))
ran = self.run_tool("reviewer-header", "prose")
self.assertEqual((ran.returncode, ran.stdout), (1, ""))
self.assertIn("`principles` is missing", ran.stderr)
def test_reviewer_header_fails_with_the_configs_message_where_it_sets_no_principles_or_standards_folder(self):
for setting in ("principles", "standards"):
with self.subTest(setting=setting):
self.config.write_text(PROJECT_CONFIG.replace(f'{setting} = "~/{setting}"\n', ""))
ran = self.run_tool("reviewer-header", "prose")
self.assertEqual((ran.returncode, ran.stdout), (1, ""))
self.assertIn(f"`{setting}` is missing", ran.stderr)
def test_reviewer_header_fails_where_no_config_names_the_checkout(self):
self.config.unlink()
@@ -1252,15 +1269,19 @@ class LarvReviewTool(unittest.TestCase):
self.assertEqual((ran.returncode, ran.stdout), (1, ""))
self.assertIn(f"no config names the checkout {self.checkout}", ran.stderr)
def test_reviewer_header_fails_where_the_principles_folder_is_missing_or_empty(self):
folder = self.checkout.parent / "principles"
(folder / "technical-principles.md").unlink()
empty = self.run_tool("reviewer-header", "prose")
folder.rmdir()
missing = self.run_tool("reviewer-header", "prose")
for ran in (empty, missing):
self.assertEqual((ran.returncode, ran.stdout), (1, ""))
self.assertIn(f"{folder} is not a folder with a file in it; {self.config} sets it as `principles`", ran.stderr)
def test_reviewer_header_fails_where_the_principles_or_standards_folder_is_missing_or_empty(self):
for setting, file in (("principles", "technical-principles.md"), ("standards", "quality.md")):
with self.subTest(setting=setting):
folder = self.checkout.parent / setting
(folder / file).unlink()
empty = self.run_tool("reviewer-header", "prose")
folder.rmdir()
missing = self.run_tool("reviewer-header", "prose")
folder.mkdir()
(folder / file).write_text("# Restored\n")
for ran in (empty, missing):
self.assertEqual((ran.returncode, ran.stdout), (1, ""))
self.assertIn(f"{folder} is not a folder with a file in it; {self.config} sets it as `{setting}`", ran.stderr)
def test_reviewer_header_gives_the_architect_the_places(self):
folder = self.checkout.parent / ".local" / "state" / "larv-review" / "proj"
+1 -1
View File
@@ -57,7 +57,7 @@ FINISHED_RULES = (
"finished=true when the chunk is complete: merged, or nothing remains that the worker could do on "
f"its own. Even then, it is finished only once {ANSWERS_RECORDED}.\n\n"
"An answer counts as recorded where the premises or the records above already hold it, the human's rules "
"(~/.claude/CLAUDE.md, ~/.claude/rules/, ~/.claude/skills/larv-review/standards/) included. "
"(~/.claude/CLAUDE.md, ~/.claude/rules/, the project's review standards, each headed by its path) included. "
f"It also counts where the transcript shows the worker writing it into {ANSWER_DESTINATIONS}, "
"but not into one of the human's rules.\n\n"
"finished=false when work remains that a further run can "
+46
View File
@@ -0,0 +1,46 @@
"""The slot a loop holds in its project, so that loops of one project, each on its own chunk, run side by side, each in a session named after its slot."""
import dataclasses
import os
import pathlib
from failure import Failure
from machine_load.slots import first_free_slot
from loop_claude.loop.reload import LoopRun
from loop_state.paths import Paths
from transcript_archive.project_key import project_key
from claude_code.session import Session, session_named, session_open
# Under the home folder, a folder per project key holds a file per slot, which a running loop keeps locked with flock.
SLOTS = ".local/state/loop-claude"
# A bound no project reaches. Once todo.md item 375 lands, the project's config sets how many loops run at once.
MOST = 64
def held_slot(home: pathlib.Path, key: str, claude_code_transcripts: pathlib.Path) -> int | Failure:
"""The slot this loop takes, or why it could take none: the lowest free slot whose session is open, so that a rerun resumes a chunk left open, or else the lowest free slot. The loop holds it until it exits; a reload's exec keeps the lock."""
folder = home / SLOTS / key
order = sorted(range(MOST), key=lambda slot: not session_open(session_named(session_name(key, slot), claude_code_transcripts)))
try:
folder.mkdir(parents=True, exist_ok=True)
taken = first_free_slot(folder, order)
except OSError as failure:
return Failure(f"cannot take a slot in {folder}: {failure.strerror}")
if taken is None:
return Failure(f"{MOST} loops of this project are running already; `fuser {folder}/slot-*` names them")
slot, fd = taken
os.set_inheritable(fd, True)
return slot
def session_name(key: str, slot: int) -> str:
""""A " is the human's cue in the session picker that the session is the loop's. Slot 0 keeps the name every loop had before slots, so a chunk left open before slots resumes in it."""
return f"A {key} loop-claude" if slot == 0 else f"A {key} loop-claude {slot + 1}"
def slotted(loop_run: LoopRun, paths: Paths) -> tuple[LoopRun, Session] | Failure:
"""loop_run holding its slot, and the worker's session, named after the slot. A reloaded script keeps the slot it is handed."""
key = project_key(loop_run.root, paths.home)
slot = held_slot(paths.home, key, paths.claude_code_transcripts) if loop_run.slot is None else loop_run.slot
if isinstance(slot, Failure):
return slot
return dataclasses.replace(loop_run, slot=slot), session_named(session_name(key, slot), paths.claude_code_transcripts)
+5 -3
View File
@@ -20,7 +20,7 @@ from transcript_archive.project_key import project_key
from model_routing.ladder import project_rung
from loop_claude.project.premises import read_premises
from loop_claude.project.records import read_records
from claude_code.session import session_named
from loop_claude.loop.chunk_slot import slotted
from loop_claude.stop import Stop
from loop_claude.direct_message import tell
@@ -46,8 +46,10 @@ def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launc
if isinstance(loop_run, Stop):
return loop_run
baseline = fingerprint(launcher)
# "A " is the human's cue in the session picker that the session is the loop's.
session = session_named(f"A {project_key(loop_run.root, paths.home)} loop-claude", paths.claude_code_transcripts)
held = slotted(loop_run, paths)
if isinstance(held, Failure):
return Stop(1, held.reason)
loop_run, session = held
loop = Loop(root=loop_run.root, session=session, paths=paths, env=env, launcher=launcher, effects=effects)
while True:
if stop := exec_if_edited(loop, baseline, loop_run):
+3 -1
View File
@@ -25,6 +25,8 @@ class LoopRun:
route: Route | None = None
# How many unfinished verdicts the chunk has had running; a finished chunk and a rerun each set it to 0. It stays apart from route and unfinished_evidence, though all three change together at each verdict: merging or renaming a field stops a running loop at its next reload.
unfinished_run: int = 0
# The project's slot this loop holds (chunk_slot.py); None until it takes one. A loop started before slots reloads with None, and so takes a slot then.
slot: int | None = None
class Unreadable(Exception):
@@ -75,7 +77,7 @@ def decoded_route(value: object) -> Route | None:
# One decoder per field of LoopRun, which a test holds to the dataclass's fields: a field missing here stops a loop at the reload after it joined.
LOOP_RUN_FIELDS = {"cycle_number": exactly(int), "root": exactly(str), "task": exactly(str), "unfinished_evidence": exactly(str), "route": decoded_route, "unfinished_run": exactly(int)}
LOOP_RUN_FIELDS = {"cycle_number": exactly(int), "root": exactly(str), "task": exactly(str), "unfinished_evidence": exactly(str), "route": decoded_route, "unfinished_run": exactly(int), "slot": lambda value: None if value is None else exactly(int)(value)}
def fingerprint(launcher: pathlib.Path) -> str:
+23 -18
View File
@@ -10,20 +10,20 @@ first worker prompt also quotes the premises. They, with code health (~/.claude/
"Shared goal") ranked first unless the goals file voids it, choose between ways to deliver the
chunk's todo.md items, or else the task, and never widen them. A judge then reads the transcript's
end, the premises, and the records: the project's AGENTS.md and docs/decisions.md, and the human's
~/.claude/CLAUDE.md, ~/.claude/rules/*.md and ~/.claude/skills/larv-review/standards/*.md, where
they exist. It rules whether the chunk, the work of one PR, is finished. A chunk stays unfinished
until each answer the human typed in it that a later chunk could need is recorded: the premises or
the records hold it, or the transcript shows the worker writing it into the premises, AGENTS.md,
docs/decisions.md, todo.md or a code comment. A choice the worker made that the premises or the
records settle is not asked about. When the worker asks a question they answer, the judge quotes the
answer, loop-claude prints it, and the worker resumes with it. A quote they do not hold word for
word is dropped, and the question goes to the human. So does a question asked again after its
answer. A question the human answered earlier in the chunk goes back to the worker with that answer,
unless the question quotes the words of the answer that leave it open. The fourth question they
answer in one cycle goes to the human too, with the quote. An unfinished chunk resumes its session
next cycle, and the worker is shown the passage the judge quoted as the work remaining. The next
chunk starts a fresh session. Cycles continue until an exit below or Ctrl-C. Words:
~/.claude/CLAUDE.md → "Vocabulary".
~/.claude/CLAUDE.md and ~/.claude/rules/*.md, then the .md files in the folder of review standards
the project's config sets, where they exist. It rules whether the chunk, the work of one PR, is
finished. A chunk stays unfinished until each answer the human typed in it that a later chunk could
need is recorded: the premises or the records hold it, or the transcript shows the worker writing it
into the premises, AGENTS.md, docs/decisions.md, todo.md or a code comment. A choice the worker made
that the premises or the records settle is not asked about. When the worker asks a question they
answer, the judge quotes the answer, loop-claude prints it, and the worker resumes with it. A quote
they do not hold word for word is dropped, and the question goes to the human. So does a question
asked again after its answer. A question the human answered earlier in the chunk goes back to the
worker with that answer, unless the question quotes the words of the answer that leave it open. The
fourth question they answer in one cycle goes to the human too, with the quote. An unfinished chunk
resumes its session next cycle, and the worker is shown the passage the judge quoted as the work
remaining. The next chunk starts a fresh session. Cycles continue until an exit below or Ctrl-C.
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:
@@ -43,8 +43,12 @@ what it prints in the first prompt (prompts.preflight_facts in bin/loop_claude/c
chunk-preflight --help says what it finds and makes. A preflight that fails, or is still running
after 600 s and is stopped, leaves the worker to find the facts itself.
Each project has one session, named "A <key> loop-claude", where <key> is the checkout's path
relative to ~/code, or to / outside it. The session is deleted when its chunk finishes. At every
Loops of one project run side by side, each on one chunk at a time. Each holds a slot of the
project, the file slot-<n> under ~/.local/state/loop-claude/<key>/, locked while the loop runs.
<key> is the checkout's path relative to ~/code, or to / outside it. A loop takes the lowest free
slot whose session is open, so a rerun resumes a chunk left open, or else the lowest free slot.
slot-0's session is named "A <key> loop-claude", and slot-<n>'s "A <key> loop-claude <n+1>".
The session is deleted when its chunk finishes. At every
interrupt, and as every cycle ends, Ctrl-C and a failure included, the session's transcript is
copied into a folder per chunk under $LOOP_CLAUDE_TRANSCRIPTS/<key> (default root
~/.claude/loop-claude-transcripts), named by its hash, with an outcomes file beside it: the task,
@@ -95,8 +99,9 @@ loop-claude --help succeeds: the loop reloads into the edited script.
Exit 1, saying why, when:
- no task is given
- git cannot start or finds no checkout
- its slot in the project cannot be taken
- the goals file, or AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/*.md or
~/.claude/skills/larv-review/standards/*.md where they exist, cannot be read or is not UTF-8
the project's review standards where they exist, cannot be read or is not UTF-8
- no config names the checkout, its config cannot be read, or the goals file holds no premises
- the models file cannot be read or written
- claude leaves no transcript
@@ -123,4 +128,4 @@ Exit 2, when the human is needed to go on:
- the claude opened for /talk, or for a release ready to cut, ends without
anything typed
- the judge rules a chunk unfinished 6 cycles running; rerun to give it 6 more
Rerunning resumes any open session."""
Rerunning resumes an open session that no running loop holds, the lowest one first."""
+14 -6
View File
@@ -9,26 +9,27 @@ from record_store.stores import store
RECORD_FILES = ("AGENTS.md", "docs/decisions.md")
# The setting in the project's config that places each of RECORD_FILES.
RECORD_SETTINGS = ("working-rules", "decisions")
# The human's rules for every project, under ~/.claude: CLAUDE.md, then each .md file in these folders, which a repo check keeps present.
# The human's rules, in the order the judge reads them: ~/.claude/CLAUDE.md, each .md file in ~/.claude/rules/,
# then each .md file in the review standards folder the project's config sets.
HUMAN_RULES_FILE = "CLAUDE.md"
HUMAN_RULE_DIRS = ("rules", "skills/larv-review/standards")
HUMAN_RULE_NAMES = (f"~/.claude/{HUMAN_RULES_FILE}", *(f"~/.claude/{folder}/" for folder in HUMAN_RULE_DIRS))
HUMAN_RULE_DIR = "rules"
HUMAN_RULE_NAMES = (f"~/.claude/{HUMAN_RULES_FILE}", f"~/.claude/{HUMAN_RULE_DIR}/", "the project's review standards")
CONSEQUENCE = "the judge cannot read the records"
def read_records(root: str, home: pathlib.Path, claude_dir: pathlib.Path) -> str | Failure:
"""The project's `AGENTS.md` and decision log, then the human's rules for every project, CLAUDE.md first, each headed by its name; one that does not exist, or is empty, is left out.
"""The project's `AGENTS.md` and decision log, then the human's rules, CLAUDE.md first, each headed by its name; one that does not exist, or is empty, is left out.
`AGENTS.md` is read where the config under home of root's project puts it, and the decision log from the store that config names. Each is headed by its name in RECORD_FILES wherever it is kept."""
config = located(root, home)
if isinstance(config, Failure):
return Failure(f"{config.reason} - {CONSEQUENCE}.")
rules = [claude_dir / HUMAN_RULES_FILE] + [rule for folder in HUMAN_RULE_DIRS for rule in sorted((claude_dir / folder).glob("*.md"))]
rules = [claude_dir / HUMAN_RULES_FILE, *sorted((claude_dir / HUMAN_RULE_DIR).glob("*.md")), *sorted(config.paths["standards"].glob("*.md"))]
decisions = store(config, RECORD_SETTINGS[1]).read()
texts = [(RECORD_FILES[0], file_text(config.paths[RECORD_SETTINGS[0]])), (RECORD_FILES[1], Failure(f"{decisions.reason} - {CONSEQUENCE}.") if isinstance(decisions, Failure) else decisions)]
texts += [(f"~/.claude/{rule.relative_to(claude_dir)}", file_text(rule)) for rule in rules]
texts += [(named(rule, home, claude_dir), file_text(rule)) for rule in rules]
records = []
for heading, text in texts:
if isinstance(text, Failure):
@@ -41,3 +42,10 @@ def read_records(root: str, home: pathlib.Path, claude_dir: pathlib.Path) -> str
def file_text(path: pathlib.Path) -> str | Failure:
"""path's text, empty where no such file exists."""
return read_utf8(str(path.parent), path.name, CONSEQUENCE) if path.exists() else ""
def named(rule: pathlib.Path, home: pathlib.Path, claude_dir: pathlib.Path) -> str:
"""rule's path as the human writes it: under ~/.claude, or ~/ for the rest of home, or else in full."""
if rule.is_relative_to(claude_dir):
return f"~/.claude/{rule.relative_to(claude_dir)}"
return f"~/{rule.relative_to(home)}" if rule.is_relative_to(home) else str(rule)
+23 -1
View File
@@ -1,5 +1,6 @@
import dataclasses
import datetime
import fcntl
import hashlib
import json
import os
@@ -575,6 +576,27 @@ class Cycles(unittest.TestCase):
self.assertIsNotNone(argument(run.calls[0], "--resume"))
self.assertEqual((argument(run.calls[0], "--model"), argument(run.calls[0], "--effort")), ("claude-fable-5-2", "medium"))
def test_a_second_loop_in_the_project_runs_its_own_session_and_leaves_the_first_loops_open_chunk_alone(self):
checkout = Checkout(self)
first = checkout.run([worker(say="first chunk"), judge(evidence="first chunk")])
session = argument(first.calls[0], "--session-id")
transcript = checkout.transcripts()[0]
kept, archived = transcript.read_bytes(), checkout.archived()
slot = checkout.home / ".local" / "state" / "loop-claude" / "proj" / "slot-0"
slot.parent.mkdir(parents=True, exist_ok=True)
# The test holds the first loop's slot, as the first loop does while it runs.
with open(slot, "a") as running:
fcntl.flock(running, fcntl.LOCK_EX | fcntl.LOCK_NB)
second = checkout.run([worker(say="second chunk"), judge(evidence="second chunk")])
self.assertEqual(argument(second.calls[0], "--name"), "A proj loop-claude 2")
self.assertNotIn(session, [argument(call, "--session-id") or argument(call, "--resume") for call in second.calls if call["role"] == "worker"])
self.assertNotIn("first chunk", second.calls[1]["stdin"])
self.assertEqual(transcript.read_bytes(), kept)
self.assertLessEqual(archived.items(), checkout.archived().items())
self.assertEqual(len(checkout.archived()), len(archived) + 1)
rerun = checkout.run([worker()])
self.assertEqual(argument(rerun.calls[0], "--resume"), session)
def test_exits_1_when_the_transcript_cannot_be_archived_and_resumes_on_the_next_run(self):
checkout = Checkout(self)
checkout.archive().parent.mkdir(parents=True)
@@ -917,7 +939,7 @@ class Reload(unittest.TestCase):
self.assertEqual(run.roles(), ["worker", "judge"] * 5)
self.assertIn("keeping the running script", run.stderr)
reloads = [json.loads(argv[1]) for argv in run.starts if argv[:1] == ["--reloaded"]]
self.assertEqual(reloads, [{"cycle_number": cycle, "root": str(checkout.root), "task": TASK, "unfinished_evidence": "working", "route": OFF_LADDER_ROUTE, "unfinished_run": cycle} for cycle in (2, 3, 4)])
self.assertEqual(reloads, [{"cycle_number": cycle, "root": str(checkout.root), "task": TASK, "unfinished_evidence": "working", "route": OFF_LADDER_ROUTE, "unfinished_run": cycle, "slot": 0} for cycle in (2, 3, 4)])
self.assertIn("=== cycle 5,", run.stdout)
outside = checkout.temp / "outside"
+74 -8
View File
@@ -21,7 +21,7 @@ from routing_figures import archive, state
from routing_figures.calls import Call
from loop_claude.project import checkout, model_choice, records
from loop_claude.cycle import chunk_items
from loop_claude.loop import chunk_start, close
from loop_claude.loop import chunk_slot, chunk_start, close
from project_config.test_project_config import configured
from release_plan.release_standing import DefaultPlan, LastCut, UNSEEN_RELEASES
from loop_effects.effects import Effects, PYTHON_TIMEOUT
@@ -250,7 +250,7 @@ class Transitions(unittest.TestCase):
class QuestionFor(unittest.TestCase):
def test_puts_an_interrupts_question_as_asked_and_a_quoted_answer_past_the_cap_with_its_quote(self):
self.assertEqual(run.question_for(Interrupt("e", "Which one?")), "Which one?")
self.assertEqual(run.question_for(QuotedAnswer("e", "Which one?", "A.")), "Which one?\n\nthe goals file's Goals and Audience, AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/ or ~/.claude/skills/larv-review/standards/ says:\nA.\n\nThose files have answered 3 questions this cycle, the most allowed, so this one comes to you.")
self.assertEqual(run.question_for(QuotedAnswer("e", "Which one?", "A.")), "Which one?\n\nthe goals file's Goals and Audience, AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/ or the project's review standards says:\nA.\n\nThose files have answered 3 questions this cycle, the most allowed, so this one comes to you.")
class Cycles(unittest.TestCase):
@@ -491,12 +491,12 @@ Spent since 2026-09-21T14:13:20Z, in tokens of input, cache write 5m, cache writ
with contextlib.redirect_stderr(io.StringIO()) as said, contextlib.redirect_stdout(io.StringIO()) as printed:
self.assertEqual(run.run_cycle(self.cycle(fake, records="From AGENTS.md:\nUse A.")), Stop(2, "the human is needed to answer the question above, but nothing was typed"))
resumed = fake.made("stream_claude")[1]
self.assertEqual(resumed[resumed.index("-p") + 1], "Your question: Which one?\n\nthe goals file's Goals and Audience, AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/ or ~/.claude/skills/larv-review/standards/ answers it:\n\nUse *A*.\n\nContinue the task.")
self.assertEqual(resumed[resumed.index("-p") + 1], "Your question: Which one?\n\nthe goals file's Goals and Audience, AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/ or the project's review standards answers it:\n\nUse *A*.\n\nContinue the task.")
self.assertEqual(len(fake.made("stream_claude")), 4)
self.assertEqual(printed.getvalue().count("=== the goals file's Goals and Audience, AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/ or ~/.claude/skills/larv-review/standards/ answered: Which one? ===\nUse *A*."), 3)
self.assertIn("Which one?\n\nthe goals file's Goals and Audience, AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/ or ~/.claude/skills/larv-review/standards/ says:\nUse *A*.\n\nThose files have answered 3 questions this cycle", said.getvalue())
quoted = f"2026-09-21T14:13:20Z Verdict: quoted answer\n\nWhich one?\n\nthe goals file's Goals and Audience, AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/ or ~/.claude/skills/larv-review/standards/ says:\n> Use *A*.\n\nEvidence:\n> working\n\nConfig: {CONFIG}\nJudge: judge-model\nWorker: {OFF_LADDER}\n"
self.assertEqual(self.archived_outcomes(), [f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: interrupt\n\nWhich one?\n\nthe goals file's Goals and Audience, AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/ or ~/.claude/skills/larv-review/standards/ says:\nUse *A*.\n\nThose files have answered 3 questions this cycle, the most allowed, so this one comes to you.\n\nEvidence:\n> working\n\nConfig: {CONFIG}\nJudge: judge-model\nWorker: {OFF_LADDER}\n\n2026-09-21T14:13:20Z Stopped: the human is needed to answer the question above, but nothing was typed\n\nWorker: {OFF_LADDER}\n", *[f"Task: Do it.\n\n{quoted}"] * 3])
self.assertEqual(printed.getvalue().count("=== the goals file's Goals and Audience, AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/ or the project's review standards answered: Which one? ===\nUse *A*."), 3)
self.assertIn("Which one?\n\nthe goals file's Goals and Audience, AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/ or the project's review standards says:\nUse *A*.\n\nThose files have answered 3 questions this cycle", said.getvalue())
quoted = f"2026-09-21T14:13:20Z Verdict: quoted answer\n\nWhich one?\n\nthe goals file's Goals and Audience, AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/ or the project's review standards says:\n> Use *A*.\n\nEvidence:\n> working\n\nConfig: {CONFIG}\nJudge: judge-model\nWorker: {OFF_LADDER}\n"
self.assertEqual(self.archived_outcomes(), [f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: interrupt\n\nWhich one?\n\nthe goals file's Goals and Audience, AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/ or the project's review standards says:\nUse *A*.\n\nThose files have answered 3 questions this cycle, the most allowed, so this one comes to you.\n\nEvidence:\n> working\n\nConfig: {CONFIG}\nJudge: judge-model\nWorker: {OFF_LADDER}\n\n2026-09-21T14:13:20Z Stopped: the human is needed to answer the question above, but nothing was typed\n\nWorker: {OFF_LADDER}\n", *[f"Task: Do it.\n\n{quoted}"] * 3])
def test_a_quoted_answer_that_cites_an_escalation_trigger_steps_the_worker_up_before_it_resumes_and_archives_the_step(self):
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 2, claude=[judged("quoted", answer="Use A.", escalation="working"), judged("finished")])
@@ -1206,6 +1206,63 @@ class RouteSources(unittest.TestCase):
self.assertTrue(stderr.getvalue().startswith(f"{STAMP} routing the chunk afresh: could not read the archive"), stderr.getvalue())
class ChunkSlots(unittest.TestCase):
def setUp(self):
temp = tempfile.TemporaryDirectory()
self.addCleanup(temp.cleanup)
self.home = pathlib.Path(temp.name)
self.paths = paths.paths_from(self.home)
self.addCleanup(self.release)
def held(self):
"""This process's open files on a slot, each with whether an exec keeps it."""
folder = self.home / chunk_slot.SLOTS
found = {}
for fd in os.listdir("/proc/self/fd"):
with contextlib.suppress(OSError):
if pathlib.Path(os.readlink(f"/proc/self/fd/{fd}")).is_relative_to(folder):
found[os.readlink(f"/proc/self/fd/{fd}")] = os.get_inheritable(int(fd))
return found
def release(self):
folder = str(self.home / chunk_slot.SLOTS)
for fd in os.listdir("/proc/self/fd"):
with contextlib.suppress(OSError):
if os.readlink(f"/proc/self/fd/{fd}").startswith(folder):
os.close(int(fd))
def test_each_loop_takes_the_lowest_free_slot_and_names_its_session_after_it(self):
loop_run = main.LoopRun(cycle_number=0, root=str(self.home / "code" / "proj"), task="do it", unfinished_evidence="")
first, second = chunk_slot.slotted(loop_run, self.paths), chunk_slot.slotted(loop_run, self.paths)
self.assertEqual((first[0], first[1].name), (dataclasses.replace(loop_run, slot=0), "A proj loop-claude"))
self.assertEqual((second[0].slot, second[1].name), (1, "A proj loop-claude 2"))
self.assertEqual(second[1], session.session_named("A proj loop-claude 2", self.paths.claude_code_transcripts))
folder = self.home / ".local" / "state" / "loop-claude" / "proj"
self.assertEqual(self.held(), {str(folder / "slot-0"): True, str(folder / "slot-1"): True})
def test_a_rerun_takes_the_lowest_free_slot_whose_session_is_open_before_a_lower_closed_one(self):
loop_run = main.LoopRun(cycle_number=0, root=str(self.home / "code" / "proj"), task="do it", unfinished_evidence="")
for name in ("A proj loop-claude 3", "A proj loop-claude 4"):
transcript = self.paths.claude_code_transcripts / "-home-proj" / f"{session.session_named(name, self.paths.claude_code_transcripts).id}.jsonl"
transcript.parent.mkdir(parents=True, exist_ok=True)
transcript.write_text("")
self.assertEqual([chunk_slot.slotted(loop_run, self.paths)[0].slot for _ in range(4)], [2, 3, 0, 1])
def test_a_reload_keeps_the_slot_it_is_handed_and_takes_no_other(self):
loop_run = main.LoopRun(cycle_number=3, root="/srv/proj", task="do it", unfinished_evidence="", slot=2)
self.assertEqual(chunk_slot.slotted(loop_run, self.paths), (loop_run, session.session_named("A srv/proj loop-claude 3", self.paths.claude_code_transcripts)))
self.assertEqual(self.held(), {})
def test_says_why_it_takes_no_slot(self):
loop_run = main.LoopRun(cycle_number=0, root="/srv/proj", task="do it", unfinished_evidence="")
with unittest.mock.patch.object(chunk_slot, "MOST", 1):
chunk_slot.slotted(loop_run, self.paths)
self.assertEqual(chunk_slot.slotted(loop_run, self.paths), Failure(f"1 loops of this project are running already; `fuser {self.home}/.local/state/loop-claude/srv/proj/slot-*` names them"))
(self.home / ".local" / "state" / "loop-claude").mkdir(parents=True, exist_ok=True)
(self.home / ".local" / "state" / "loop-claude" / "other").write_text("")
self.assertEqual(chunk_slot.slotted(dataclasses.replace(loop_run, root="/other"), self.paths), Failure(f"cannot take a slot in {self.home}/.local/state/loop-claude/other: File exists"))
class Steps(unittest.TestCase):
OPUS = Rung("claude-opus-5-5", "medium")
@@ -1469,6 +1526,14 @@ class Records(unittest.TestCase):
pathlib.Path(claude_md.parent, "skills", "larv-review", "standards").mkdir(parents=True)
pathlib.Path(claude_md.parent, "skills", "larv-review", "standards", "comments.md").write_text("# Comments\n")
self.assertTrue(records.read_records(root, claude_md.parents[1], claude_md.parent).endswith("From ~/.claude/CLAUDE.md:\n# Global\n\nFrom ~/.claude/rules/goals-and-audience.md:\n# Goals\n\nFrom ~/.claude/rules/todo-items.md:\n# Todo\n\nFrom ~/.claude/skills/larv-review/standards/comments.md:\n# Comments"))
config.write_text(config.read_text().replace('"~/.claude/skills/larv-review/standards"', '"~/review-standards"'))
pathlib.Path(claude_md.parents[1], "review-standards").mkdir()
pathlib.Path(claude_md.parents[1], "review-standards", "quality.md").write_text("# Ours\n")
self.assertTrue(records.read_records(root, claude_md.parents[1], claude_md.parent).endswith("From ~/.claude/rules/todo-items.md:\n# Todo\n\nFrom ~/review-standards/quality.md:\n# Ours"), "the config's standards folder replaces the default")
config.write_text(config.read_text().replace('"~/review-standards"', f'"{root}/standards"'))
pathlib.Path(root, "standards").mkdir()
pathlib.Path(root, "standards", "quality.md").write_text("# Elsewhere\n")
self.assertTrue(records.read_records(root, claude_md.parents[1], claude_md.parent).endswith(f"From {root}/standards/quality.md:\n# Elsewhere"), "a folder outside home is named in full")
config.write_text(config.read_text().replace('"checkout:AGENTS.md"', '"folder:AGENTS.md"').replace('"checkout:docs/decisions.md"', '"folder:log/decisions.md"'))
self.assertTrue(records.read_records(root, claude_md.parents[1], claude_md.parent).startswith("From ~/.claude/CLAUDE.md:\n# Global"), "the checkout's AGENTS.md and docs/decisions.md are its owners'")
@@ -1925,7 +1990,7 @@ class ExitContract(unittest.TestCase):
def test_every_exit_1_stop_has_its_clause_in_help(self):
read, git, premises_ = "a transcript cannot be read or archived", "git cannot start or finds no checkout", "no config names the checkout, its config cannot be read, or the goals file holds no premises"
models_ = "the models file cannot be read or written"
names = (*records.RECORD_FILES, records.HUMAN_RULE_NAMES[0], *(f"{folder}*.md" for folder in records.HUMAN_RULE_NAMES[1:]))
names = (*records.RECORD_FILES, records.HUMAN_RULE_NAMES[0], f"{records.HUMAN_RULE_NAMES[1]}*.md", records.HUMAN_RULE_NAMES[2])
unreadable = f"the goals file, or {', '.join(names[:-1])} or {names[-1]} where they exist, cannot be read or is not UTF-8"
# Every Stop whose code is not a literal 0, 2 or 130, in source order: path, function, code, start of reason, its --help clause.
clauses = [
@@ -1943,6 +2008,7 @@ class ExitContract(unittest.TestCase):
("cycle/run.py", "close", "1", "failure.reason", read),
("cycle/run.py", "close", "1", "failure.reason", "a finished chunk's session cannot be deleted"),
("loop/close.py", "closed_cycle", "1", "failure.reason", read),
("loop/main.py", "run_loop", "1", "held.reason", "its slot in the project cannot be taken"),
("loop/main.py", "next_cycle", "1", "premises.reason", premises_),
("loop/main.py", "next_cycle", "1", "records.reason", unreadable),
("loop/main.py", "loop_run_from", "0 if task else 1", "HELP", "no task is given"),
+7 -2
View File
@@ -27,8 +27,13 @@ def slot_folder(env: typing.Mapping[str, str], home: pathlib.Path) -> pathlib.Pa
def taken_slot(folder: pathlib.Path, slots: int) -> tuple[int, int] | None:
"""The number and open file of a slot this call locked; None while every slot is held. Raises OSError where a slot file cannot be opened or locked."""
for slot in range(slots):
"""The number and open file of the lowest slot this call locked; None while every slot is held. Raises OSError where a slot file cannot be opened or locked."""
return first_free_slot(folder, range(slots))
def first_free_slot(folder: pathlib.Path, order: typing.Iterable[int]) -> tuple[int, int] | None:
"""The number and open file of the first slot in order that this call locked; None while every slot in order is held. Raises OSError where a slot file cannot be opened or locked."""
for slot in order:
fd = os.open(folder / f"slot-{slot}", os.O_RDWR | os.O_CREAT, 0o644)
try:
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
+1 -1
View File
@@ -54,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)
+178 -15
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, filed into and finished over Jira's REST API.
An item is an open child issue. Its ID is the issue's number, so every child must be in the epic's own Jira project: ABC-34 is item 34 of the plan under ABC-12. The summary is the tagline, the description the detail, the earliest Fix Version the release, and an "is blocked by" link a blocker. L, E, I, S, Moves and Exempt sit in one issue property, PROPERTY, which needs no Jira admin to set up; an issue a teammate filed holds none, and reads as an item without scores.
The store only reads so far: every write is a Failure."""
`add` files an item as a new child issue, marked with FILED_BY, and `finish` moves an item's issue to a done status. edit is a Failure until todo.md's item 382."""
import base64
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 project_config.settings import Epic
from release_plan.todo_table import EXEMPTIONS, is_exempt, Item, MOVES, parse_moves, parse_scores, SHAPE
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, Finish, JIRA_FINISH_STATUS, JIRA_FINISH_TRANSITION
from failure import Failure
from rest_client import json_request
from release_plan.release import parsed, Release, tagged
from 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,25 @@ TIMEOUT = 30
PAGE = 100
# The pages one read asks for at most, so an answer that never names a last page ends the read.
MAX_PAGES = 100
READ_ONLY = "a plan in Jira is only read so far: file, edit and finish its issues in Jira"
READ_ONLY = "the loop doesn't edit an issue of a plan in Jira yet: edit it in Jira"
# The key in PROPERTY's value that marks an issue the loop filed, and its value. The loop never edits the summary or description of an issue without it, which a person filed.
FILED_BY = ("Filed by", "loop")
# The issue type of an issue the loop files, which Jira Software's project templates all have; a project without it refuses the issue, saying so.
ISSUE_TYPE = "Task"
# The name of the link type whose inward side reads "is blocked by", as Jira Cloud ships it.
BLOCKS = "Blocks"
SECURITY = "security"
# The key of the status category Jira Cloud gives every done status.
DONE = "done"
# What a failed create ends with: a request Jira never answered, or answered brokenly, may still have filed the issue.
PERHAPS_FILED = "unless Jira refused the request, the issue may exist: look under {epic} before filing the item again"
# What a failed move ends with, for the same reason.
PERHAPS_MOVED = "unless Jira refused the request, the issue may have moved: look at {key} before finishing the item again"
# 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 +82,14 @@ 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
# How a finished item moves; None where the config doesn't say, and then `finish` is a Failure.
finish_by: Finish | None = None
@property
def label(self) -> str:
@@ -93,13 +110,159 @@ 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)
def finish(self, id_: int) -> Written | Failure:
return Failure(READ_ONLY)
"""Moves item id_'s issue by the transition that the config names, to the status it names. Any open child of the epic may move, whoever filed it."""
if self.finish_by is None:
return Failure(f"the config names no transition to finish an item by: set `{JIRA_FINISH_TRANSITION}` and `{JIRA_FINISH_STATUS}`, as `project-config --help` shows")
authorization = basic_auth(self.env_file)
if isinstance(authorization, Failure):
return authorization
answered = children(self.epic, authorization, self.http)
if isinstance(answered, Failure):
return answered
key = f"{project_of(self.epic.key)}-{id_}"
if not any(isinstance(raw, dict) and raw.get("key") == key for raw in answered):
return Failure(f"{self.label} holds no item {id_}")
url = f"{self.epic.site}/rest/api/3/issue/{key}/transitions"
offered = self.http("GET", url, authorization, None)
if isinstance(offered, Failure):
return Failure(f"cannot read {key}'s transitions: {offered.reason}")
transition = transition_of(offered, key, self.finish_by)
if isinstance(transition, Failure):
return transition
moved = self.http("POST", url, authorization, {"transition": {"id": transition}})
return Failure(f"cannot move {key} by {self.finish_by.transition!r}: {moved.reason}; {PERHAPS_MOVED.format(key=key)}") if isinstance(moved, Failure) else Written(id_)
@dataclasses.dataclass(frozen=True)
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 offer_of(raw: object) -> tuple[str, str, str, str] | None:
"""One transition Jira offers, as its ID, its name, the name of the status it leads to and the key of that status's category; None where raw holds no such transition."""
to = raw.get("to") if isinstance(raw, dict) else None
category = to.get("statusCategory") if isinstance(to, dict) else None
if not isinstance(raw, dict) or not isinstance(to, dict) or not isinstance(category, dict):
return None
id_, name, status, key = raw.get("id"), raw.get("name"), to.get("name"), category.get("key")
return (id_, name, status, key) if isinstance(id_, str) and isinstance(name, str) and isinstance(status, str) and isinstance(key, str) else None
def transition_of(offered: object, key: str, finish: Finish) -> str | Failure:
"""The ID of the transition finish names, among those Jira offered for the issue named key, which are the ones its present status has; or why none of them finishes the item."""
raw = offered.get("transitions") if isinstance(offered, dict) else None
found = [offer for each in raw if (offer := offer_of(each))] if isinstance(raw, list) else []
if not isinstance(raw, list) or len(found) != len(raw):
return Failure(f"Jira answered {key}'s transitions in a shape other than the one it documents")
named = [each for each in found if each[1] == finish.transition]
if not named:
others = " and ".join(f"{name!r} to {status!r}" for _, name, status, _ in found)
return Failure(f"{key} has no transition {finish.transition!r} from its status, " + (f"only {others}: move the issue in Jira to a status that has it, or name in `{JIRA_FINISH_TRANSITION}` one that leads to a done status" if found else "nor any other the account may make"))
id_, _, status, category = next((each for each in named if each[2] == finish.status), named[0])
if status != finish.status:
return Failure(f"{key}'s transition {finish.transition!r} leads to the status {status!r}, not to {finish.status!r}, which `{JIRA_FINISH_STATUS}` names")
# `children` reads an issue as finished by its status's category, so a move to any other category would leave the item in the plan.
if category != DONE:
return Failure(f"{key}'s transition {finish.transition!r} leads to the status {status!r}, which Jira doesn't count as done, so the item would stay in the plan: name a transition to a done status")
return id_
def project_of(key: str) -> str:
"""The key of the Jira project an issue key lies in."""
return key.rpartition("-")[0]
def basic_auth(env_file: pathlib.Path) -> str | Failure:
@@ -154,8 +317,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 +355,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)), "")
+3 -3
View File
@@ -1,6 +1,6 @@
"""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
@@ -47,7 +47,7 @@ class Written:
class PlanStore(typing.Protocol):
"""A project's plan. plan_store.contract holds every backend that writes to the same behaviour; `jira_epic` 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, files and finishes, and fails an edit until todo.md's item 382. A write that fails leaves the plan as it was, except where its Failure says the tracker may have taken the write all the same, as when Jira's answer to a new issue or to a move is lost."""
@property
def label(self) -> str:
@@ -157,7 +157,7 @@ def store(config: ProjectConfig) -> PlanStore:
from plan_store.jira_epic import JiraPlan
# load refuses a config that names an epic and no env-file.
assert config.env_file is not None
return JiraPlan(config.epic, config.env_file)
return JiraPlan(config.epic, config.env_file, finish_by=config.jira_finish)
def file_plan(config: ProjectConfig, path: pathlib.Path | None = None) -> FilePlan:
+244 -7
View File
@@ -7,10 +7,11 @@ import unittest.mock
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from project_config.settings import Epic
from project_config.settings import Epic, Finish
from release_plan.todo_table import EXEMPTIONS
from failure import Failure
from plan_store import jira_epic
from plan_store.stores import Plan
from plan_store.stores import Plan, Written
from adf_codec.convert import Refused
from release_plan.release import release_of
@@ -209,17 +210,253 @@ 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):
store = self.store()
for written in (store.add({}, ""), 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"))
def test_edit_fails_since_the_store_does_not_edit_yet(self):
self.assertEqual(self.store().edit(34, {"L": "2"}, None), Failure("the loop doesn't edit an issue of a plan in Jira yet: edit it in Jira"))
self.assertEqual(self.calls + self.epic_calls, [])
def test_names_itself_by_the_configs_spelling_and_no_commit_holds_it(self):
self.assertEqual((self.store().label, self.store().tracked), ("jira:https://acme.atlassian.net/browse/ABC-12", None))
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, [])
TRANSITIONS = "https://acme.atlassian.net/rest/api/3/issue/ABC-34/transitions"
def transition(id_: str, name: str, status: str, category: str = "done") -> dict[str, object]:
return {"id": id_, "name": name, "to": {"name": status, "statusCategory": {"key": category}}}
class Finishing(unittest.TestCase):
def setUp(self) -> None:
self.env = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory())) / "acme.env"
self.env.write_text("ATLASSIAN_EMAIL=me@example.com\nATLASSIAN_API_TOKEN=s3cret\n")
self.env.chmod(0o600)
self.calls: list[tuple[str, str, object]] = []
self.open = [issue("ABC-34"), issue("ABC-35")]
self.transitions: object = {"transitions": [transition("11", "Start", "In Progress", "indeterminate"), transition("31", "Mark as done", "Done")]}
self.moved: object = None
def http(self, method: str, url: str, authorization: str, body: object) -> object:
"""Stands in for Jira: answers the epic, self.open to the search, self.transitions for ABC-34's transitions and self.moved to a transition of it."""
self.calls.append((method, url, body))
assert authorization == AUTHORIZATION
if url == TRANSITIONS:
return self.transitions if method == "GET" else self.moved
return {SEARCH: {"issues": self.open}}.get(url, {"key": "ABC-12"})
def finish(self, id_: int = 34, by: Finish | None = Finish("Mark as done", "Done")):
return jira_epic.JiraPlan(EPIC, self.env, self.http, text_of, finish_by=by).finish(id_)
def posts(self) -> list[tuple[str, str, object]]:
return [call for call in self.calls if call[0] == "POST" and call[1] != SEARCH]
def test_moves_the_issue_by_the_transition_the_config_names(self):
self.assertEqual(self.finish(), Written(34))
self.assertEqual(self.posts(), [("POST", TRANSITIONS, {"transition": {"id": "31"}})])
def test_a_config_that_names_no_transition_fails_before_any_request(self):
self.assertEqual(self.finish(by=None), Failure("the config names no transition to finish an item by: set `jira-finish-transition` and `jira-finish-status`, as `project-config --help` shows"))
self.assertEqual(self.calls, [])
def test_an_issue_that_is_no_open_child_of_the_epic_is_not_moved(self):
self.assertEqual(self.finish(36), Failure("jira:https://acme.atlassian.net/browse/ABC-12 holds no item 36"))
self.assertEqual(self.posts(), [])
def test_a_transition_the_issue_does_not_have_fails_naming_those_it_has(self):
self.assertEqual(self.finish(by=Finish("Close", "Done")), Failure("ABC-34 has no transition 'Close' from its status, only 'Start' to 'In Progress' and 'Mark as done' to 'Done': move the issue in Jira to a status that has it, or name in `jira-finish-transition` one that leads to a done status"))
self.assertEqual(self.posts(), [])
def test_a_transition_that_leads_to_another_status_fails(self):
self.assertEqual(self.finish(by=Finish("Mark as done", "Closed")), Failure("ABC-34's transition 'Mark as done' leads to the status 'Done', not to 'Closed', which `jira-finish-status` names"))
self.assertEqual(self.posts(), [])
def test_two_transitions_share_the_name_and_the_one_to_the_status_is_made(self):
self.transitions = {"transitions": [transition("30", "Close", "Rejected"), transition("31", "Close", "Done")]}
self.assertEqual(self.finish(by=Finish("Close", "Done")), Written(34))
self.assertEqual(self.posts(), [("POST", TRANSITIONS, {"transition": {"id": "31"}})])
def test_a_status_jira_does_not_count_as_done_fails_since_the_item_would_stay_in_the_plan(self):
self.assertEqual(self.finish(by=Finish("Start", "In Progress")), Failure("ABC-34's transition 'Start' leads to the status 'In Progress', which Jira doesn't count as done, so the item would stay in the plan: name a transition to a done status"))
self.assertEqual(self.posts(), [])
def test_an_issue_with_no_transition_fails_saying_so(self):
self.transitions = {"transitions": []}
self.assertEqual(self.finish(), Failure("ABC-34 has no transition 'Mark as done' from its status, nor any other the account may make"))
def test_transitions_that_cannot_be_read_fail(self):
self.transitions = Failure("HTTP 403")
self.assertEqual(self.finish(), Failure("cannot read ABC-34's transitions: HTTP 403"))
def test_transitions_in_another_shape_fail(self):
odd = [transition(31, "Mark as done", "Done"), transition("31", None, "Done"), transition("31", "Mark as done", ["Done"]), transition("31", "Mark as done", "Done", 4), {"id": "31", "name": "Mark as done", "to": "Done"}, {"id": "31", "name": "Mark as done", "to": {"name": "Done"}}, "odd"] # type: ignore[arg-type]
for answered in ([], {"transitions": "none"}, *({"transitions": [each]} for each in odd)):
with self.subTest(answered=answered):
self.transitions = answered
self.assertEqual(self.finish(), Failure("Jira answered ABC-34's transitions in a shape other than the one it documents"))
def test_a_move_jira_refuses_fails_with_jiras_reason(self):
self.moved = Failure("HTTP 400: Resolution is required")
self.assertEqual(self.finish(), Failure("cannot move ABC-34 by 'Mark as done': HTTP 400: Resolution is required; unless Jira refused the request, the issue may have moved: look at ABC-34 before finishing the item again"))
def test_a_missing_env_file_fails_before_any_request(self):
self.env.unlink()
self.assertIsInstance(self.finish(), Failure)
self.assertEqual(self.calls, [])
class Requests(unittest.TestCase):
def test_sends_each_request_through_the_shared_client_with_jiras_error_messages(self):
with unittest.mock.patch.object(jira_epic.json_request, "http_json", return_value={"issues": []}) as sent:
+6 -1
View File
@@ -8,7 +8,7 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from project_config.settings import DEFAULT_FLOOR, Epic, ProjectConfig, SETTINGS
from project_config.settings import DEFAULT_FLOOR, Epic, Finish, ProjectConfig, SETTINGS
from failure import Failure
from record_store.stores import FileStore
from plan_store.contract import FIRST, MOVES, PlanStoreContract, SECOND
@@ -210,6 +210,11 @@ class Store(unittest.TestCase):
picked = stores.store(self.config(epic=epic, env_file=pathlib.Path("/secrets/acme.env")))
self.assertEqual(picked, JiraPlan(epic, pathlib.Path("/secrets/acme.env"), picked.http))
def test_an_epic_finishes_an_item_as_the_config_says(self):
finish = Finish("Mark as done", "Done")
picked = stores.store(self.config(epic=Epic("https://acme.atlassian.net", "ABC-12"), env_file=pathlib.Path("/secrets/acme.env"), jira_finish=finish))
self.assertEqual(picked.finish_by, finish)
if __name__ == "__main__":
unittest.main()
+34 -4
View File
@@ -20,22 +20,51 @@ starts with / or ~/. In a worktree, a "checkout:" path is the worktree's own fil
changelog = "checkout:CHANGELOG.md"
goals-and-audience = "folder:goals.md"
principles = "folder:principles"
standards = "~/.claude/skills/larv-review/standards"
`principles` and `standards` name the folders the reviewers hold the project to: the technical
principles and the review standards. A standards folder must hold quality.md, prose.md, comments.md
and readme.md, since the reviewers and the rules name those files.
`plan` may name a Jira Cloud epic in place of a path, as "jira:" and the epic's address:
"jira:https://acme.atlassian.net/browse/ABC-12". The plan is then the epic's open child issues, in
Jira's backlog order, and `project-config plan` prints the setting as the config spells it. Such a
config must set `env-file`, and that file must hold ATLASSIAN_EMAIL and ATLASSIAN_API_TOKEN.
`jira-finish-transition` and `jira-finish-status` are optional settings, set together and only
beside such a plan, since each Jira workflow differs. `todo-item finish` moves an item's issue by
the workflow transition the first names. That transition must lead to the status the second names,
which must be one Jira counts as done. Write both names as Jira shows them:
jira-finish-transition = "Mark as done"
jira-finish-status = "Done"
Where the config leaves them out, `todo-item finish` fails in a Jira plan. Each is printed with the others only where it is set.
`goals-and-audience` may name a Jira Cloud epic the same way, where `plan` names one too. The
epic's description is then the goals file, with ## Goals and ## Audience as headings, and
`project-config goals-and-audience` prints the setting as the config spells it. The description is
only read: edit it in Jira.
Each record, `decisions`, `score-anchors`, `comprehension-history`, `reading-cost` and `changelog`,
may name a Confluence Cloud page in place of a path, as "confluence:" and the page's address, with or
without the title at its end: "confluence:https://acme.atlassian.net/wiki/spaces/ENG/pages/2293761".
The record is then that page's text, which `project-record` reads and writes as markdown, and
`project-config <record>` prints the setting as the config spells it. A mention or a macro on the
page reads as plain text, and a save writes that text in its place. Such a config must set
`env-file`, holding ATLASSIAN_EMAIL and ATLASSIAN_API_TOKEN, as for a Jira epic.
`decisions` and `comprehension-history` may name a page only where `plan` names a Jira epic, since
rule-hook ranks a plan kept as a file before tool calls, and a read from Confluence mustn't hold it up.
`env-file` is an optional setting: the file of KEY=value credentials the project's tools read,
a path that starts with / or ~/ and lies outside the checkout and the config's folder, such as
"~/.claude-projects/acme-billing.env". Where it is left out, the project has no credentials file, and
a tool that needs one fails naming the setting. It is printed with the others only where it is set.
`touch-predictions` is an optional setting, a path spelt as the others are, never a page: the record
where `touch-predictions record` appends what each chunk was predicted to touch beside what it touched.
Left out, the project keeps no such record. It is printed with the others only where it is set.
`notifier` is an optional setting, "mattermost" or "slack": the service that sends loop-claude's DMs and
`notify`'s messages to the human. Setting it requires `env-file`, which holds that service's keys;
`notify --help` names them. Left out, the project gets no DMs. It is printed with the others only where it
@@ -91,13 +120,14 @@ and its commits and pull request are titled "ABC-123 - …".
Exit 1, naming each fault on stderr, where no config names the checkout, or its config leaves out a
setting, names an unknown one, misspells a path, a language or a template, sets `wait-for-approval` or
`tooling-on-host` to anything but true or false, sets `notifier` to anything but mattermost or slack or
without `env-file`, or sets `readability-floor` to anything but a number
from 1 to 10, and where `env-file` or `notifier` is asked for and not set. No path setting has a default.
without `env-file`, sets `jira-finish-transition` or `jira-finish-status` to anything but a name, without the other or
without a `plan` in Jira, or sets `readability-floor` to anything but a number
from 1 to 10, and where `env-file`, `jira-finish-transition`, `jira-finish-status`, `notifier` or `touch-predictions` is asked for and not set. No path setting has a default.
"""
import pathlib
import sys
from project_config.settings import CONFIG, DEFAULT_FLOOR, ENV_FILE, load, NOTIFIER, OPTIONAL, ProjectConfig, READABILITY_FLOOR, SETTINGS, TOOLING_ON_HOST, Unnamed, WAIT_FOR_APPROVAL
from project_config.settings import CONFIG, DEFAULT_FLOOR, ENV_FILE, JIRA_FINISH_STATUS, JIRA_FINISH_TRANSITION, 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
@@ -124,7 +154,7 @@ def main(argv: list[str]) -> int:
if argv and argv[0] in config.texts:
print(config.texts[argv[0]])
return 0
paths = {**config.places, **({ENV_FILE: str(config.env_file)} if config.env_file else {}), **({NOTIFIER: config.notifier} if config.notifier else {})}
paths = {**config.places, **({ENV_FILE: str(config.env_file)} if config.env_file else {}), **({NOTIFIER: config.notifier} if config.notifier else {}), **({JIRA_FINISH_TRANSITION: config.jira_finish.transition, JIRA_FINISH_STATUS: config.jira_finish.status} if config.jira_finish else {})}
if argv and argv[0] not in paths:
print(f"{config.folder / CONFIG} sets no `{argv[0]}`", file=sys.stderr)
return 1
+60 -10
View File
@@ -15,7 +15,7 @@ from project_config import templates
PROJECTS = ".claude-projects"
CONFIG = "config.toml"
# Every path a project sets, by its role. Three readers, seated as the human who writes the config, picked the spelling from four candidates. They picked role names over file names, which a client's project doesn't share.
SETTINGS = ("plan", "working-rules", "decisions", "score-anchors", "comprehension-history", "reading-cost", "changelog", "goals-and-audience", "principles")
SETTINGS = ("plan", "working-rules", "decisions", "score-anchors", "comprehension-history", "reading-cost", "changelog", "goals-and-audience", "principles", "standards")
# They also picked a prefix over bare relative paths: each line says its own place, and a relative path with no prefix fails instead of landing somewhere by default.
SPELLING = '"checkout:<path>" for a path in the checkout, "folder:<path>" for one in the config\'s folder, or a path that starts with / or ~/'
# A path setting a project may leave out: the file of KEY=value credentials its tools read. It has no default either: a project without it asks for no credentials, and never reads another project's.
@@ -37,13 +37,25 @@ LANGUAGE = "language"
COMMIT_TITLE = "commit-title"
PULL_REQUEST_TITLE = "pull-request-title"
BRANCH = "branch"
OPTIONAL = (BRANCH, COMMIT_TITLE, ENV_FILE, LANGUAGE, NOTIFIER, PULL_REQUEST_TITLE, READABILITY_FLOOR, TOOLING_ON_HOST, WAIT_FOR_APPROVAL)
# An optional path setting: main's help says what it places.
TOUCH_PREDICTIONS = "touch-predictions"
# Two optional settings, each a name, set together and only where `plan` names a Jira epic: the name of the workflow transition that finishes an item, and of the status it must lead to. Three readers, seated as the human who writes a client's config, picked the spelling from four candidates: two flat keys, as the other settings are, with a prefix that says what they apply to.
JIRA_FINISH_TRANSITION = "jira-finish-transition"
JIRA_FINISH_STATUS = "jira-finish-status"
JIRA_FINISH = (JIRA_FINISH_TRANSITION, JIRA_FINISH_STATUS)
OPTIONAL = (BRANCH, COMMIT_TITLE, ENV_FILE, JIRA_FINISH_STATUS, JIRA_FINISH_TRANSITION, LANGUAGE, NOTIFIER, PULL_REQUEST_TITLE, READABILITY_FLOOR, TOOLING_ON_HOST, TOUCH_PREDICTIONS, WAIT_FOR_APPROVAL)
# What opens a setting that names a Jira Cloud epic in place of a path: `jira:`, then the epic's address as the browser shows it. The settings below may name an epic; each reads its own part of it.
JIRA = "jira:"
EPIC_SPELLINGS = {
"goals-and-audience": '"jira:https://<site>/browse/<epic\'s key>" for goals and audience kept in a Jira Cloud epic\'s description',
"plan": '"jira:https://<site>/browse/<epic\'s key>" for a plan kept as a Jira Cloud epic\'s child issues',
}
# The settings that each name a record, a document a project keeps beside its plan. Each may name a Confluence Cloud page in place of a path: `confluence:`, then the page's address as the browser shows it, whose last part, the title, may be left out.
RECORDS = ("decisions", "score-anchors", "comprehension-history", "reading-cost", "changelog")
CONFLUENCE = "confluence:"
# The records that ranking a plan reads.
RANKED = ("decisions", "comprehension-history")
PAGE_SPELLING = '"confluence:https://<site>/wiki/spaces/<space>/pages/<page ID>" for a record kept on a Confluence Cloud page'
OUTSIDE = "a path that starts with / or ~/ and lies outside the checkout and the config's folder, so that no git remote receives the credentials"
@@ -64,9 +76,24 @@ class Epic:
return f"{JIRA}{self.site}/browse/{self.key}"
@dataclasses.dataclass(frozen=True)
class Finish:
"""How a finished item of a Jira plan moves: by the workflow transition named transition, which must lead to the status named status."""
transition: str
status: str
@dataclasses.dataclass(frozen=True)
class Page:
"""A Confluence Cloud page: site is its site's address, such as https://acme.atlassian.net, page_id its number, and spelling the setting's value as the config writes it."""
site: str
page_id: str
spelling: str
@dataclasses.dataclass(frozen=True)
class ProjectConfig:
"""folder is `~/.claude-projects/<key>`, top is the worktree that asked, and paths holds each of SETTINGS as an absolute path, except `plan` and `goals-and-audience` where they are kept in Jira."""
"""folder is `~/.claude-projects/<key>`, top is the worktree that asked, and paths holds each of SETTINGS as an absolute path, except three kinds that pages or epics hold instead: `plan` and `goals-and-audience` where they are kept in Jira, and a record kept on a Confluence page."""
key: str
folder: pathlib.Path
top: pathlib.Path
@@ -86,6 +113,10 @@ class ProjectConfig:
goals_epic: Epic | None = None
# The config's `notifier`, or None where it names none.
notifier: Notifier | None = None
# The config's `jira-finish-transition` and `jira-finish-status`, or None where it sets neither.
jira_finish: Finish | None = None
# The Confluence page of each record the config keeps on one, by the record's setting.
pages: dict[str, Page] = dataclasses.field(default_factory=dict)
@property
def plan_file(self) -> pathlib.Path | None:
@@ -99,9 +130,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."""
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 if epics.get(name) or name in self.paths}
"""Where each of SETTINGS is kept, in SETTINGS' order, then TOUCH_PREDICTIONS where the config sets it: a path, or the epic or page as the config spells it."""
spelt = {name: kept.spelling for name, kept in {"plan": self.epic, "goals-and-audience": self.goals_epic, **self.pages}.items() if kept}
return {name: spelt[name] if name in spelt else str(self.paths[name]) for name in (*SETTINGS, TOUCH_PREDICTIONS) if name in spelt or name in self.paths}
@property
def texts(self) -> dict[str, str]:
@@ -138,26 +169,34 @@ 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}
paths = {name: placed(values[name], top, file.parent, home) for name in (*SETTINGS, TOUCH_PREDICTIONS) if name in values}
epics = {name: epic_of(values.get(name)) for name in EPIC_SPELLINGS}
pages = {name: page for name in RECORDS if (page := page_of(values.get(name)))}
env_file = anywhere(values.get(ENV_FILE), home)
misplaced = ENV_FILE in values and (env_file is None or lies_in(env_file, top, main, file.parent))
notifier = next((name for name in NOTIFIERS if name == values.get(NOTIFIER)), None)
waits = values.get(WAIT_FOR_APPROVAL, False)
on_host = values.get(TOOLING_ON_HOST, False)
floor = floor_of(values[READABILITY_FLOOR]) if READABILITY_FLOOR in values else DEFAULT_FLOOR
finish = [name for setting in JIRA_FINISH if (name := name_of(values.get(setting)))]
checks = {LANGUAGE: language_fault, COMMIT_TITLE: templates.title_fault, PULL_REQUEST_TITLE: templates.title_fault, BRANCH: templates.branch_fault}
faults = [
*(f"`{name}` is missing" for name in SETTINGS if name not in values),
*(f"`{name}` is not a setting" for name in values if name not in (*SETTINGS, *OPTIONAL)),
*(f"`{name}` is {values[name]!r}, not {SPELLING}" for name, path in paths.items() if path is None and name not in EPIC_SPELLINGS),
*(f"`{name}` is {values[name]!r}, not {SPELLING}" for name, path in paths.items() if path is None and name not in (*EPIC_SPELLINGS, *RECORDS)),
*(f"`{name}` is {values[name]!r}, not {SPELLING}, or {EPIC_SPELLINGS[name]}" for name in EPIC_SPELLINGS if name in values and paths[name] is None and epics[name] is None),
*(f"`{name}` is {values[name]!r}, not {SPELLING}, or {PAGE_SPELLING}" for name in RECORDS if name in values and paths[name] is None and name not in pages),
*(f"`{name}` names a Jira epic, so `{ENV_FILE}` must name the file that holds its credentials" for name, epic in epics.items() if epic and ENV_FILE not in values),
# rule-hook ranks a plan kept as a file before tool calls, inside the hook's time limit, which a read from Jira mustn't hold up.
*(f"`{name}` names a Confluence page, so `{ENV_FILE}` must name the file that holds its credentials" for name in pages if ENV_FILE not in values),
# rule-hook ranks a plan kept as a file before tool calls, inside the hook's time limit, which a read from Jira or Confluence mustn't hold up.
*(["`goals-and-audience` names a Jira epic, so `plan` must name one too"] if epics["goals-and-audience"] and not epics["plan"] else []),
*(f"`{name}` names a Confluence page, so `plan` must name a Jira epic" for name in RANKED if name in pages and not epics["plan"]),
*([f"`{ENV_FILE}` is {values[ENV_FILE]!r}, not {OUTSIDE}"] if misplaced else []),
*([f"`{NOTIFIER}` is {values[NOTIFIER]!r}, not {' or '.join(NOTIFIERS)}"] if NOTIFIER in values and values[NOTIFIER] not in NOTIFIERS else []),
*([f"`{NOTIFIER}` names a notifier, so `{ENV_FILE}` must name the file that holds its credentials"] if NOTIFIER in values and ENV_FILE not in values else []),
*(f"`{name}` is {values[name]!r}, not the name Jira shows, such as \"{example}\"" for name, example in zip(JIRA_FINISH, ("Mark as done", "Done")) if name in values and not name_of(values[name])),
*(f"`{name}` is set, so `{other}` must be too" for name, other in (JIRA_FINISH, JIRA_FINISH[::-1]) if name in values and other not in values),
*(f"`{name}` is set, so `plan` must name a Jira epic" for name in JIRA_FINISH if name in values and not epics["plan"]),
*(f"`{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]))),
@@ -166,7 +205,12 @@ def load(top: pathlib.Path, main: pathlib.Path, home: pathlib.Path) -> ProjectCo
return Failure(f"{file}: {'; '.join(faults)}. The settings are {', '.join(SETTINGS)}, and optionally {', '.join(OPTIONAL[:-1])} and {OPTIONAL[-1]}.")
# faults names a floor the config misspells.
assert floor is not None
return ProjectConfig(file.parent.name, file.parent, top, {name: path for name, path in paths.items() if path}, env_file, waits is True, on_host is True, floor, **{name.replace("-", "_"): str(values[name]) for name in checks if name in values}, epic=epics["plan"], goals_epic=epics["goals-and-audience"], notifier=notifier)
return ProjectConfig(file.parent.name, file.parent, top, {name: path for name, path in paths.items() if path}, env_file, waits is True, on_host is True, floor, **{name.replace("-", "_"): str(values[name]) for name in checks if name in values}, epic=epics["plan"], goals_epic=epics["goals-and-audience"], notifier=notifier, jira_finish=Finish(*finish) if finish else None, pages=pages)
def name_of(value: object) -> str | None:
"""The name value holds, of a Jira transition or status; None where it holds none."""
return value if isinstance(value, str) and value.strip() else None
def epic_of(value: object) -> Epic | None:
@@ -175,6 +219,12 @@ def epic_of(value: object) -> Epic | None:
return Epic(spelt.group(1), spelt.group(2)) if spelt else None
def page_of(value: object) -> Page | None:
"""The page a setting's value spells; None where it spells none. Only https, as for an epic."""
spelt = isinstance(value, str) and re.fullmatch(rf"{CONFLUENCE}(https://[A-Za-z0-9.-]+(?::[0-9]+)?)/wiki/spaces/[^/?#]+/pages/([0-9]+)(?:/[^/?#]*)?", value)
return Page(spelt.group(1), spelt.group(2), spelt.string) if spelt else None
def floor_of(value: object) -> decimal.Decimal | None:
"""The floor value spells, an integer or a float from 1 to 10; None where it spells none. Not a string, nor a boolean, which Python counts as an integer, nor TOML's nan or inf."""
# An integer too large for a float makes math.isfinite raise, so only a float is checked.
+99 -4
View File
@@ -9,7 +9,7 @@ import unittest.mock
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from project_config.settings import env_files, Epic, held, load, NOTIFIERS, OUTSIDE, ProjectConfig, SETTINGS, Unnamed
from project_config.settings import env_files, Epic, Finish, held, load, NOTIFIERS, OUTSIDE, Page, ProjectConfig, SETTINGS, Unnamed
from failure import Failure
from test_env import isolated_env
from project_config.main import title_templates
@@ -27,10 +27,12 @@ reading-cost = "folder:docs/reading-cost.md"
changelog = "checkout:CHANGELOG.md"
goals-and-audience = "folder:goals.md"
principles = "~/.claude/principles"
standards = "~/.claude/skills/larv-review/standards"
"""
JIRA_PLAN = "jira:https://acme.atlassian.net/browse/ABC-12"
JIRA_CLIENT = CLIENT.replace("folder:todo.md", JIRA_PLAN) + 'env-file = "~/acme.env"\n'
DECISIONS_PAGE = "confluence:https://acme.atlassian.net/wiki/spaces/ENG/pages/2293761/Decisions"
def write_config(home: pathlib.Path, checkout: pathlib.Path, goals: str = "checkout:README.md") -> pathlib.Path:
@@ -85,6 +87,7 @@ class LoadTest(ConfigCase):
self.assertEqual(found.paths["decisions"], folder / "docs" / "decisions.md")
self.assertEqual(found.paths["changelog"], self.checkout / "CHANGELOG.md")
self.assertEqual(found.paths["principles"], self.home / ".claude" / "principles")
self.assertEqual(found.paths["standards"], self.home / ".claude" / "skills" / "larv-review" / "standards")
self.assertEqual(tuple(found.paths), SETTINGS)
def test_a_plan_spelt_as_a_jira_epic_is_no_path(self) -> None:
@@ -153,6 +156,53 @@ class LoadTest(ConfigCase):
self.assertIn("jira:https://<site>/browse/<epic's key>", reason)
self.assertIn("description", reason)
def test_a_record_spelt_as_a_confluence_page_is_no_path_and_prints_as_written(self) -> None:
self.write("acme", JIRA_CLIENT.replace("folder:docs/decisions.md", DECISIONS_PAGE))
found = load(self.checkout, self.checkout, self.home)
assert isinstance(found, ProjectConfig), found
self.assertEqual(found.pages, {"decisions": Page("https://acme.atlassian.net", "2293761", DECISIONS_PAGE)})
self.assertEqual(found.places["decisions"], DECISIONS_PAGE)
self.assertEqual(tuple(found.places), SETTINGS)
self.assertNotIn("decisions", found.paths)
self.assertIsNone(found.tracked("decisions"))
def test_a_confluence_page_may_leave_out_its_title(self) -> None:
for spelled in ("confluence:https://acme.atlassian.net/wiki/spaces/ENG/pages/2293761", "confluence:https://acme.atlassian.net/wiki/spaces/~5b1e/pages/2293761/R%C3%A5d+och+beslut"):
with self.subTest(spelled):
for config in (self.home / ".claude-projects").glob("*/config.toml"):
config.unlink()
config.parent.rmdir()
self.write("acme", CLIENT.replace("checkout:CHANGELOG.md", spelled) + 'env-file = "~/acme.env"\n')
found = load(self.checkout, self.checkout, self.home)
assert isinstance(found, ProjectConfig), found
self.assertEqual(found.pages["changelog"].page_id, "2293761")
def test_a_confluence_record_needs_an_env_file(self) -> None:
self.write("acme", CLIENT.replace("folder:docs/decisions.md", DECISIONS_PAGE))
self.assertIn("`decisions` names a Confluence page, so `env-file` must name the file that holds its credentials", self.failure())
def test_a_record_that_ranking_reads_names_a_page_only_beside_a_plan_in_jira(self) -> None:
self.write("acme", CLIENT.replace("folder:docs/decisions.md", DECISIONS_PAGE).replace("folder:docs/comprehension-history.md", DECISIONS_PAGE) + 'env-file = "~/acme.env"\n')
reason = self.failure()
self.assertIn("`decisions` names a Confluence page, so `plan` must name a Jira epic", reason)
self.assertIn("`comprehension-history` names a Confluence page, so `plan` must name a Jira epic", reason)
def test_a_record_that_spells_no_path_and_no_page_names_both_spellings(self) -> None:
for count, spelled in enumerate(("confluence:http://acme.atlassian.net/wiki/spaces/ENG/pages/2293761", "confluence:https://acme.atlassian.net/wiki/spaces/ENG/pages/Decisions", "confluence:https://acme.atlassian.net@evil.example/wiki/spaces/ENG/pages/2293761", "confluence:2293761", "https://acme.atlassian.net/wiki/spaces/ENG/pages/2293761")):
with self.subTest(spelled):
self.write(f"acme-{count}", CLIENT.replace("folder:docs/decisions.md", spelled) + 'env-file = "~/acme.env"\n')
reason = self.failure()
self.assertIn(f"`decisions` is {spelled!r}, not ", reason)
self.assertIn("confluence:https://<site>/wiki/spaces/<space>/pages/<page ID>", reason)
for config in (self.home / ".claude-projects").glob("*/config.toml"):
config.unlink()
def test_only_a_record_may_name_a_confluence_page(self) -> None:
self.write("acme", CLIENT.replace('"folder:AGENTS.md"', '"' + DECISIONS_PAGE + '"') + 'env-file = "~/acme.env"\n')
reason = self.failure()
self.assertIn("`working-rules` is", reason)
self.assertNotIn("confluence:https://<site>", reason)
def test_a_worktree_finds_the_main_checkouts_config_and_reads_its_own_files(self) -> None:
self.write("acme", CLIENT)
worktree = self.home / "code" / "acme-billing-item-3"
@@ -192,10 +242,10 @@ class LoadTest(ConfigCase):
self.assertIn("~/.claude-projects/<key>/config.toml", reason)
def test_every_missing_setting_is_named(self) -> None:
kept = "".join(line + "\n" for line in CLIENT.splitlines() if not line.startswith(("plan", "changelog", "principles")))
kept = "".join(line + "\n" for line in CLIENT.splitlines() if not line.startswith(("plan", "changelog", "principles", "standards")))
self.write("acme", kept)
reason = self.failure()
for name in ("plan", "changelog", "principles"):
for name in ("plan", "changelog", "principles", "standards"):
with self.subTest(name=name):
self.assertIn(f"`{name}` is missing", reason)
self.assertNotIn("`decisions` is", reason)
@@ -245,6 +295,26 @@ class LoadTest(ConfigCase):
assert isinstance(named, ProjectConfig), named
self.assertEqual(named.notifier, name)
def test_a_jira_plan_may_name_the_transition_and_status_that_finish_an_item(self) -> None:
self.write("acme", JIRA_CLIENT)
left_out = load(self.checkout, self.checkout, self.home)
assert isinstance(left_out, ProjectConfig), left_out
self.assertIsNone(left_out.jira_finish)
(self.home / ".claude-projects" / "acme" / "config.toml").write_text(JIRA_CLIENT + 'jira-finish-transition = "Mark as done"\njira-finish-status = "Done"\n')
named = load(self.checkout, self.checkout, self.home)
assert isinstance(named, ProjectConfig), named
self.assertEqual(named.jira_finish, Finish("Mark as done", "Done"))
def test_a_finish_setting_alone_misspelt_or_beside_a_plan_in_a_file_fails_naming_it(self) -> None:
self.write("acme", JIRA_CLIENT + 'jira-finish-status = "Done"\n')
self.assertIn("`jira-finish-status` is set, so `jira-finish-transition` must be too", self.failure())
(self.home / ".claude-projects" / "acme" / "config.toml").write_text(JIRA_CLIENT + 'jira-finish-transition = "Mark as done"\n')
self.assertIn("`jira-finish-transition` is set, so `jira-finish-status` must be too", self.failure())
(self.home / ".claude-projects" / "acme" / "config.toml").write_text(JIRA_CLIENT + 'jira-finish-transition = 31\njira-finish-status = " "\n')
self.assertIn("`jira-finish-transition` is 31, not the name Jira shows, such as \"Mark as done\"; `jira-finish-status` is ' ', not the name Jira shows, such as \"Done\"", self.failure())
(self.home / ".claude-projects" / "acme" / "config.toml").write_text(CLIENT + 'jira-finish-transition = "Mark as done"\njira-finish-status = "Done"\n')
self.assertIn("`jira-finish-transition` is set, so `plan` must name a Jira epic; `jira-finish-status` is set, so `plan` must name a Jira epic", self.failure())
def test_a_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())
@@ -279,6 +349,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:], ["standards", "touch-predictions"])
self.assertEqual(found.paths["touch-predictions"], folder / "docs/touch-predictions.md")
self.assertIsNone(found.tracked("touch-predictions"))
(folder / "config.toml").write_text(CLIENT + 'touch-predictions = "docs/touch-predictions.md"\n', encoding="utf-8")
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)
@@ -373,7 +457,7 @@ class LoadTest(ConfigCase):
def test_the_failure_for_a_misplaced_env_file_and_a_missing_setting_names_both_and_lists_every_setting(self) -> None:
folder = self.write("acme", "".join(line + "\n" for line in CLIENT.splitlines() if not line.startswith("plan")) + 'env-file = "checkout:.env"\n')
self.assertEqual(self.failure(), f"{folder / 'config.toml'}: `plan` is missing; `env-file` is 'checkout:.env', not {OUTSIDE}. The settings are {', '.join(SETTINGS)}, and optionally branch, commit-title, env-file, language, notifier, pull-request-title, readability-floor, tooling-on-host and wait-for-approval.")
self.assertEqual(self.failure(), f"{folder / 'config.toml'}: `plan` is missing; `env-file` is 'checkout:.env', not {OUTSIDE}. The settings are {', '.join(SETTINGS)}, and optionally branch, commit-title, env-file, jira-finish-status, jira-finish-transition, 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)
@@ -492,6 +576,17 @@ class ToolTest(ConfigCase):
self.assertEqual(self.run_tool("notifier").stdout, "slack\n")
self.assertEqual(self.run_tool().stdout.splitlines()[-1], "notifier: slack")
def test_prints_how_a_jira_item_finishes_where_the_config_says_and_fails_asking_for_it_where_it_does_not(self) -> None:
folder = self.write("acme", JIRA_CLIENT)
for name in ("jira-finish-transition", "jira-finish-status"):
unset = self.run_tool(name)
self.assertEqual((unset.returncode, unset.stdout, unset.stderr), (1, "", f"{folder / 'config.toml'} sets no `{name}`\n"))
self.assertNotIn("jira-finish", self.run_tool().stdout)
(folder / "config.toml").write_text(JIRA_CLIENT + 'jira-finish-transition = "Mark as done"\njira-finish-status = "Done"\n')
self.assertEqual(self.run_tool("jira-finish-transition").stdout, "Mark as done\n")
self.assertEqual(self.run_tool("jira-finish-status").stdout, "Done\n")
self.assertEqual(self.run_tool().stdout.splitlines()[-2:], ["jira-finish-transition: Mark as done", "jira-finish-status: Done"])
def test_prints_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")
+13 -2
View File
@@ -15,9 +15,13 @@ stands, so open it again before each edit. A record that doesn't exist yet has n
create it there.
save stores the file's text in the record, and prints one line saying so. Where the record is kept
as a file there is nothing left to store, and it says that. Run it after every edit, so the same
as a file, there is nothing left to store, and save says so. Run it after every edit, so the same
steps work wherever a project keeps the record.
For a record kept on a Confluence page, save refuses where someone saved the page after open read
it, and the human decides what follows. The copy keeps the unsaved edit until open runs again and
writes the copy afresh.
Exit 2 on bad arguments, and 1, saying why, on any other failure.
"""
import pathlib
@@ -26,6 +30,7 @@ import sys
from failure import Failure
from record_store.stores import FileStore, goals_store, local_file, RECORDS, RecordStore, store, stored
from project_config.main import located
from project_config.settings import ProjectConfig
# Not git's verbs, such as checkout and commit: those read as acting on the repo.
COMMANDS = ("open", "save")
@@ -44,7 +49,7 @@ def main(argv: list[str]) -> int:
return 2
home = pathlib.Path.home()
config = located(None, home)
done = config if isinstance(config, Failure) else act(argv[0], goals_store(config) if argv[1] == GOALS else store(config, argv[1]), home / COPIES / config.key / f"{argv[1]}.md")
done = config if isinstance(config, Failure) else act(argv[0], *opened(config, argv[1], home))
if isinstance(done, Failure):
print(f"project-record: {done.reason}", file=sys.stderr)
return 1
@@ -52,6 +57,12 @@ def main(argv: list[str]) -> int:
return 0
def opened(config: ProjectConfig, name: str, home: pathlib.Path) -> tuple[RecordStore, pathlib.Path]:
"""The store of the record called name, and the copy it gets where it isn't kept as a file. A store that keeps the version it read, for a later save, keeps it beside the copy."""
copy = home / COPIES / config.key / f"{name}.md"
return (goals_store(config) if name == GOALS else store(config, name, copy.with_suffix(".version"))), copy
def act(command: str, record: RecordStore, copy: pathlib.Path) -> str | Failure:
"""What command, one of COMMANDS, prints for record. copy is where a record kept outside files gets its file."""
if command == "open":
+17
View File
@@ -8,13 +8,30 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from project_config.test_project_config import configured
from record_store.confluence_page import ConfluencePage
from failure import Failure
from project_record import main
from record_store.fakes import MemoryStore
from project_config.settings import Page, ProjectConfig
TOOL = pathlib.Path(__file__).resolve().parents[1] / "project-record"
class Opened(unittest.TestCase):
def test_a_record_on_a_confluence_page_keeps_the_version_it_read_beside_its_copy(self):
page = Page("https://acme.atlassian.net", "2293761", "confluence:https://acme.atlassian.net/wiki/spaces/ENG/pages/2293761")
config = ProjectConfig("acme", pathlib.Path("/home/me/.claude-projects/acme"), pathlib.Path("/code/acme"), {}, pathlib.Path("/home/me/acme.env"), pages={"decisions": page})
record, copy = main.opened(config, "decisions", pathlib.Path("/home/me"))
self.assertEqual(copy, pathlib.Path("/home/me/.local/state/project-record/acme/decisions.md"))
assert isinstance(record, ConfluencePage), record
self.assertEqual(record.kept, pathlib.Path("/home/me/.local/state/project-record/acme/decisions.version"))
def test_the_goals_file_opens_through_the_goals_store(self):
config = ProjectConfig("acme", pathlib.Path("/home/me/.claude-projects/acme"), pathlib.Path("/code/acme"), {"goals-and-audience": pathlib.Path("/code/acme/README.md")})
record, copy = main.opened(config, "goals-and-audience", pathlib.Path("/home/me"))
self.assertEqual((record.label, copy), ("/code/acme/README.md", pathlib.Path("/home/me/.local/state/project-record/acme/goals-and-audience.md")))
class Act(unittest.TestCase):
def setUp(self) -> None:
self.copy = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory()), "acme", "decisions.md")
+157
View File
@@ -0,0 +1,157 @@
"""A record kept on one Confluence Cloud page, read and written as markdown over Confluence's REST API version 2, with the credentials of the config's env-file, and converted by the adf-codec shim.
A write never overwrites a teammate's edit: it sends the version it read, and Confluence refuses it where someone saved the page since. The human then decides (lilleman, 2026-11-12)."""
import dataclasses
import json
import pathlib
import typing
from adf_codec.convert import adfs_to_markdown, markdown_to_adf, Refused
from plan_store.jira_epic import basic_auth, Http, TIMEOUT, ToAdf, ToMarkdown
from rest_client.json_request import ErrorAnswer
from failure import Failure
from rest_client import json_request
from project_config.settings import Page
from text_files.file_writes import replace_file
# What Confluence answers to a write whose version isn't the one after the version it holds.
CONFLICT = 409
SHAPE = "not in the shape Confluence Cloud's REST API version 2 documents"
def http_json(method: str, url: str, authorization: str, body: object) -> object:
return json_request.http_json(method, url, authorization, body, TIMEOUT, error_message)
def error_message(answer: object) -> str:
"""Confluence's messages in the JSON of an error answer; empty where it holds none."""
errors = answer.get("errors") if isinstance(answer, dict) else None
found = [error.get("title") for error in errors if isinstance(error, dict)] if isinstance(errors, list) else [answer.get("message")] if isinstance(answer, dict) else []
return "; ".join(text for text in found if isinstance(text, str))
@dataclasses.dataclass(frozen=True)
class Seen:
"""The page's version number and title as the store last read or wrote them. A write needs both."""
version: int
title: str
@dataclasses.dataclass
class ConfluencePage:
"""The text of page as markdown, read and written with the credentials env_file holds.
kept is a file that keeps the version the store read for a later process, such as `project-record save` after `project-record open`; None keeps it only in memory."""
page: Page
env_file: pathlib.Path
kept: pathlib.Path | None = None
http: Http = http_json
to_markdown: ToMarkdown = adfs_to_markdown
to_adf: ToAdf = markdown_to_adf
seen: Seen | None = None
@property
def label(self) -> str:
return self.page.spelling
@property
def tracked(self) -> str | None:
return None
@property
def url(self) -> str:
return f"{self.page.site}/wiki/api/v2/pages/{self.page.page_id}"
def read(self) -> str | Failure:
"""The page's text as markdown; empty where the page is."""
answer = self.fetched("?body-format=atlas_doc_format")
if isinstance(answer, Failure):
return answer
seen, held = answer
if not isinstance(held, str):
return Failure(f"{self.label} is {SHAPE}: it holds no body in atlas_doc_format")
text = self.converted(held)
if isinstance(text, Failure):
return text
# Kept only once the text is in hand: a version kept for a read that failed would let a later write overwrite the save it saw.
unkept = self.keep(seen)
return unkept or text
def converted(self, held: str) -> str | Failure:
"""The markdown of the body held, the JSON of an ADF document; empty where held is."""
if not held:
return ""
try:
document = json.loads(held)
except ValueError:
return Failure(f"{self.label} holds a body that is not JSON")
texts = self.to_markdown([document])
if isinstance(texts, Refused):
return Failure(f"{self.label}: {texts.failure.reason}")
if isinstance(texts, Failure):
return Failure(f"cannot convert {self.label} to markdown: {texts.reason}")
return texts[0]
def write(self, text: str) -> Failure | None:
"""Replaces the page's text with text, as the version after the one the store read. Where the store hasn't read the page, it replaces the page as it stands."""
seen = self.seen or self.recalled()
if seen is None:
fetched = self.fetched("")
if isinstance(fetched, Failure):
return fetched
seen = fetched[0]
if isinstance(seen, Failure):
return seen
document = self.to_adf(text)
if isinstance(document, Failure):
return Failure(f"cannot convert the text for {self.label} to ADF: {document.reason}")
authorization = basic_auth(self.env_file)
if isinstance(authorization, Failure):
return authorization
body = {"id": self.page.page_id, "status": "current", "title": seen.title, "body": {"representation": "atlas_doc_format", "value": json.dumps(document)}, "version": {"number": seen.version + 1}}
answer = self.http("PUT", self.url, authorization, body)
if isinstance(answer, ErrorAnswer) and answer.status == CONFLICT:
return Failure(f"someone saved {self.label} since the loop read version {seen.version} of it, so the loop didn't write it: never overwrite their edit, but ask the human what to do ({answer.reason})")
if isinstance(answer, Failure):
return Failure(f"cannot write {self.label}: {answer.reason}")
return self.keep(Seen(seen.version + 1, seen.title))
def fetched(self, query: str) -> tuple[Seen, object] | Failure:
"""The page's version and title, and the value of its body in atlas_doc_format where query asks for it; None where it doesn't."""
authorization = basic_auth(self.env_file)
if isinstance(authorization, Failure):
return authorization
answer = self.http("GET", self.url + query, authorization, None)
if isinstance(answer, Failure):
return Failure(f"cannot read {self.label}: {answer.reason}")
page = answer if isinstance(answer, dict) else {}
version, title = page.get("version"), page.get("title")
number = version.get("number") if isinstance(version, dict) else None
if not isinstance(number, int) or not isinstance(title, str):
return Failure(f"{self.label} is {SHAPE}: its version number or title is missing")
body = page.get("body")
adf = body.get("atlas_doc_format") if isinstance(body, dict) else None
return Seen(number, title), adf.get("value") if isinstance(adf, dict) else None
def keep(self, seen: Seen) -> Failure | None:
self.seen = seen
if self.kept is None:
return None
try:
self.kept.parent.mkdir(parents=True, exist_ok=True)
except OSError as failure:
return Failure(f"cannot write {self.kept}: {failure.strerror}")
unwritten = replace_file(self.kept, json.dumps(dataclasses.asdict(seen)).encode())
return Failure(f"cannot write {self.kept}: {unwritten.reason}") if unwritten else None
def recalled(self) -> Seen | Failure | None:
"""The version and title the file kept holds; None where kept is None or names no file."""
if self.kept is None:
return None
try:
held: typing.Any = json.loads(self.kept.read_text(encoding="utf-8"))
return Seen(int(held["version"]), str(held["title"]))
except FileNotFoundError:
return None
except (OSError, ValueError, KeyError, TypeError) as failure:
return Failure(f"cannot read the version of {self.label} that {self.kept} keeps: {failure}")
+18 -8
View File
@@ -1,18 +1,15 @@
"""The one way a tool reads or writes a project's records: through the store its config names for each.
Each record has its own setting in the config, so a project may keep one record in its wiki and another as a file. The setting's value names the backend. A path names a markdown file, the only backend of a record so far; the goals file may also be a Jira epic's description, which `goals_store` picks."""
Each record has its own setting in the config, so a project may keep one record in its wiki and another as a file. The setting's value names the backend. A path names a markdown file, and `confluence:` a Confluence Cloud page; the goals file may also be a Jira epic's description, which `goals_store` picks."""
import dataclasses
import pathlib
import typing
from failure import Failure
from git_cli.git_repo import file_at, git, Git
from project_config.settings import ProjectConfig
from project_config.settings import ProjectConfig, RECORDS, TOUCH_PREDICTIONS
from text_files.file_writes import replace_file
# The settings in a project's config that each name a record.
RECORDS = ("decisions", "score-anchors", "comprehension-history", "reading-cost", "changelog")
class RecordStore(typing.Protocol):
"""One record, as text. record_store.contract holds every backend to the same behaviour."""
@@ -61,11 +58,24 @@ class FileStore:
return Failure(f"cannot write {self.path}: {unwritten.reason}") if unwritten else None
def store(config: ProjectConfig, record: str) -> RecordStore:
"""The store config names for record, one of RECORDS."""
def store(config: ProjectConfig, record: str, kept: pathlib.Path | None = None) -> RecordStore:
"""The store config names for record, one of RECORDS. A record on a Confluence page keeps the version it read in the file the parameter kept names, for a later process that writes it; where kept is None, the store keeps the version only in memory."""
if record not in RECORDS:
raise ValueError(f"{record} is not a record; the records are {', '.join(RECORDS)}")
return FileStore(config.paths[record], config.tracked(record))
if record not in config.pages:
return FileStore(config.paths[record], config.tracked(record))
# Imported here, as in goals_store.
from record_store.confluence_page import ConfluencePage
# load refuses a config that names a page and no env-file.
assert config.env_file is not None
return ConfluencePage(config.pages[record], config.env_file, kept)
def touch_predictions_store(config: ProjectConfig) -> RecordStore | None:
"""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:
+202
View File
@@ -0,0 +1,202 @@
import base64
import json
import pathlib
import sys
import tempfile
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from record_store.confluence_page import ConfluencePage, error_message
from rest_client.json_request import ErrorAnswer
from failure import Failure
from project_config.settings import Page
from record_store.contract import RecordStoreContract
from adf_codec.convert import Refused
PAGE = Page("https://acme.atlassian.net", "2293761", "confluence:https://acme.atlassian.net/wiki/spaces/ENG/pages/2293761")
URL = "https://acme.atlassian.net/wiki/api/v2/pages/2293761"
AUTHORIZATION = "Basic " + base64.b64encode(b"me@example.com:s3cret").decode()
class FakeConfluence:
"""One page as Confluence Cloud's REST API version 2 serves it, refusing with 409 a write whose version isn't the current one plus one."""
def __init__(self) -> None:
self.title = "Decisions"
self.version = 1
self.value = ""
self.calls: list[tuple[str, str, str, object]] = []
def http(self, method: str, url: str, authorization: str, body: object) -> object:
self.calls.append((method, url, authorization, body))
if method == "GET":
return {"id": PAGE.page_id, "title": self.title, "version": {"number": self.version}, "body": {"atlas_doc_format": {"representation": "atlas_doc_format", "value": self.value}}}
assert isinstance(body, dict)
if body["version"]["number"] != self.version + 1:
return ErrorAnswer(f"PUT /wiki/api/v2/pages/{PAGE.page_id} answered 409: Version must be incremented on update. Current version is: {self.version}", 409)
self.title, self.version, self.value = body["title"], body["version"]["number"], body["body"]["value"]
return {"id": PAGE.page_id, "version": {"number": self.version}}
def teammate_saves(self, text: str) -> None:
self.version += 1
self.value = json.dumps(to_adf(text))
def to_adf(text: str) -> dict[str, object]:
return {"type": "doc", "version": 1, "content": [{"type": "paragraph", "content": [{"type": "text", "text": text}]}]}
def to_markdown(documents: list[dict[str, object]]) -> list[str]:
return [document["content"][0]["content"][0]["text"] for document in documents] # type: ignore[index]
class ConfluenceCase(unittest.TestCase):
def setUp(self) -> None:
folder = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory()))
self.env = folder / "acme.env"
self.env.write_text("ATLASSIAN_EMAIL=me@example.com\nATLASSIAN_API_TOKEN=s3cret\n")
self.env.chmod(0o600)
self.kept = folder / "state" / "acme" / "decisions.version"
self.confluence = FakeConfluence()
def new_store(self, kept: pathlib.Path | None = None) -> ConfluencePage:
return ConfluencePage(PAGE, self.env, kept, self.confluence.http, to_markdown, to_adf)
class ConfluencePageContract(ConfluenceCase, RecordStoreContract):
pass
class ConfluencePageTest(ConfluenceCase):
def test_reads_the_pages_document_as_markdown(self) -> None:
self.confluence.teammate_saves("# Decisions\n")
self.assertEqual(self.new_store().read(), "# Decisions\n")
self.assertEqual(self.confluence.calls, [("GET", f"{URL}?body-format=atlas_doc_format", AUTHORIZATION, None)])
def test_writes_markdown_as_the_version_it_read_plus_one(self) -> None:
self.confluence.version = 7
store = self.new_store()
store.read()
self.assertIsNone(store.write("- a decision\n"))
self.assertEqual(self.confluence.calls[-1], ("PUT", URL, AUTHORIZATION, {"id": PAGE.page_id, "status": "current", "title": "Decisions", "body": {"representation": "atlas_doc_format", "value": json.dumps(to_adf("- a decision\n"))}, "version": {"number": 8}}))
def test_refuses_to_overwrite_a_teammates_save_since_its_read_and_says_to_ask_the_human(self) -> None:
store = self.new_store()
store.read()
self.confluence.teammate_saves("their edit\n")
written = store.write("my edit\n")
assert isinstance(written, Failure), written
self.assertIn("someone saved", written.reason)
self.assertIn("ask the human", written.reason)
self.assertIn(PAGE.spelling, written.reason)
self.assertEqual(self.new_store().read(), "their edit\n")
def test_keeps_the_version_it_read_in_its_file_for_a_later_process(self) -> None:
self.new_store(self.kept).read()
self.confluence.teammate_saves("their edit\n")
written = self.new_store(self.kept).write("my edit\n")
assert isinstance(written, Failure), written
self.assertIn("someone saved", written.reason)
def test_a_read_that_fails_keeps_the_version_an_earlier_read_kept(self) -> None:
self.new_store(self.kept).read()
self.confluence.teammate_saves("their edit\n")
failing = ConfluencePage(PAGE, self.env, self.kept, self.confluence.http, lambda _: Refused(0, Failure("adf-codec refused the input")), to_adf)
self.assertIsInstance(failing.read(), Failure)
self.confluence.value = "{not json"
self.assertIsInstance(self.new_store(self.kept).read(), Failure)
written = self.new_store(self.kept).write("my edit\n")
assert isinstance(written, Failure), written
self.assertIn("someone saved", written.reason)
self.assertEqual(self.confluence.version, 2)
def test_a_later_process_writes_with_the_version_an_earlier_one_read_or_wrote(self) -> None:
self.new_store(self.kept).read()
self.assertIsNone(self.new_store(self.kept).write("first\n"))
self.assertIsNone(self.new_store(self.kept).write("second\n"))
self.assertEqual(self.new_store().read(), "second\n")
self.assertEqual(self.confluence.title, "Decisions")
def test_a_write_with_no_read_replaces_the_page_as_it_stands(self) -> None:
self.confluence.teammate_saves("earlier\n")
self.assertIsNone(self.new_store().write("replaced\n"))
self.assertEqual(self.confluence.calls[0], ("GET", URL, AUTHORIZATION, None))
self.assertEqual(self.new_store().read(), "replaced\n")
def test_fails_on_an_answer_not_shaped_as_a_page(self) -> None:
for answer in ({}, {"title": "Decisions", "version": {}, "body": {"atlas_doc_format": {"value": ""}}}, {"version": {"number": 3}, "body": {"atlas_doc_format": {"value": ""}}}, ["not", "a", "page"]):
with self.subTest(answer):
store = ConfluencePage(PAGE, self.env, None, lambda *_: answer, to_markdown, to_adf)
read = store.read()
assert isinstance(read, Failure), read
self.assertIn("not in the shape Confluence Cloud's REST API version 2 documents", read.reason)
def test_fails_on_a_page_without_a_body_in_adf(self) -> None:
for body in ({}, "text", {"atlas_doc_format": "text"}, {"atlas_doc_format": {"value": 3}}):
with self.subTest(body):
answer = {"title": "Decisions", "version": {"number": 3}, "body": body}
store = ConfluencePage(PAGE, self.env, None, lambda *_: answer, to_markdown, to_adf)
self.assertEqual(store.read(), Failure(f"{PAGE.spelling} is not in the shape Confluence Cloud's REST API version 2 documents: it holds no body in atlas_doc_format"))
def test_fails_on_a_body_that_is_not_json(self) -> None:
self.confluence.value = "{not json"
self.assertEqual(self.new_store().read(), Failure(f"{PAGE.spelling} holds a body that is not JSON"))
def test_fails_naming_the_page_where_the_text_cannot_be_converted(self) -> None:
self.confluence.teammate_saves("text\n")
store = ConfluencePage(PAGE, self.env, None, self.confluence.http, lambda _: Failure("the shim is down"), lambda _: Failure("the shim is down"))
self.assertEqual(store.read(), Failure(f"cannot convert {PAGE.spelling} to markdown: the shim is down"))
self.assertEqual(store.write("text\n"), Failure(f"cannot convert the text for {PAGE.spelling} to ADF: the shim is down"))
def test_fails_naming_the_page_where_adf_codec_refuses_its_document(self) -> None:
self.confluence.teammate_saves("text\n")
store = ConfluencePage(PAGE, self.env, None, self.confluence.http, lambda _: Refused(0, Failure("adf-codec refused the input")), to_adf)
self.assertEqual(store.read(), Failure(f"{PAGE.spelling}: adf-codec refused the input"))
def test_fails_where_the_folder_of_its_file_cannot_be_made(self) -> None:
self.kept.parent.parent.mkdir(parents=True)
self.kept.parent.write_text("a file, not a folder")
read = self.new_store(self.kept).read()
assert isinstance(read, Failure), read
self.assertTrue(read.reason.startswith(f"cannot write {self.kept}: "), read.reason)
def test_a_write_confluence_refuses_otherwise_fails_naming_the_page_and_not_a_teammate(self) -> None:
answers = iter([{"title": "Decisions", "version": {"number": 3}}, ErrorAnswer("PUT /wiki/api/v2/pages/2293761 answered 403: Forbidden", 403)])
store = ConfluencePage(PAGE, self.env, None, lambda *_: next(answers), to_markdown, to_adf)
self.assertEqual(store.write("text\n"), Failure(f"cannot write {PAGE.spelling}: PUT /wiki/api/v2/pages/2293761 answered 403: Forbidden"))
def test_fails_where_its_file_cannot_keep_the_version(self) -> None:
self.kept.mkdir(parents=True)
read = self.new_store(self.kept).read()
assert isinstance(read, Failure), read
self.assertTrue(read.reason.startswith(f"cannot write {self.kept}: "), read.reason)
def test_fails_on_a_kept_version_it_cannot_read_and_writes_nothing(self) -> None:
self.kept.parent.mkdir(parents=True)
self.kept.write_text("{}")
written = self.new_store(self.kept).write("text\n")
assert isinstance(written, Failure), written
self.assertTrue(written.reason.startswith(f"cannot read the version of {PAGE.spelling} that {self.kept} keeps: "), written.reason)
self.assertEqual(self.confluence.calls, [])
def test_reads_confluences_messages_from_an_error_answer(self) -> None:
self.assertEqual(error_message({"errors": [{"status": 409, "title": "Version must be incremented"}, {"title": "and more"}, "odd"]}), "Version must be incremented; and more")
self.assertEqual(error_message({"message": "Not Found"}), "Not Found")
self.assertEqual(error_message({"errors": "odd"}), "")
self.assertEqual(error_message(["odd"]), "")
def test_fails_naming_the_page_when_confluence_answers_an_error(self) -> None:
store = ConfluencePage(PAGE, self.env, None, lambda *_: ErrorAnswer("GET /wiki/api/v2/pages/2293761 answered 404: Not Found", 404), to_markdown, to_adf)
self.assertEqual(store.read(), Failure(f"cannot read {PAGE.spelling}: GET /wiki/api/v2/pages/2293761 answered 404: Not Found"))
def test_fails_without_credentials_before_any_request(self) -> None:
self.env.unlink()
read = self.new_store().read()
assert isinstance(read, Failure), read
self.assertIn("does not exist", read.reason)
self.assertEqual(self.confluence.calls, [])
if __name__ == "__main__":
unittest.main()
+8 -1
View File
@@ -6,7 +6,8 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from project_config.settings import Epic, ProjectConfig
from record_store.confluence_page import ConfluencePage
from project_config.settings import Epic, Page, ProjectConfig
from record_store.jira_description import EpicDescription
from failure import Failure
from record_store.fakes import MemoryStore
@@ -171,6 +172,12 @@ class Store(unittest.TestCase):
stores.store(self.config(pathlib.Path("/code/acme"), pathlib.Path("/home/me/.claude-projects/acme")), "plan")
self.assertEqual(str(refused.exception), "plan is not a record; the records are decisions, score-anchors, comprehension-history, reading-cost, changelog")
def test_a_record_on_a_confluence_page_is_that_page_keeping_its_version_where_asked(self):
page = Page("https://acme.atlassian.net", "2293761", "confluence:https://acme.atlassian.net/wiki/spaces/ENG/pages/2293761")
config = ProjectConfig("acme", pathlib.Path("/home/me/.claude-projects/acme"), pathlib.Path("/code/acme"), {}, pathlib.Path("/home/me/acme.env"), pages={"decisions": page})
kept = pathlib.Path("/home/me/decisions.version")
self.assertEqual(stores.store(config, "decisions", kept), ConfluencePage(page, pathlib.Path("/home/me/acme.env"), kept))
class GoalsStore(unittest.TestCase):
def test_goals_kept_as_a_file_are_that_file(self):
+13 -5
View File
@@ -6,11 +6,18 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from loop_claude.project.records import HUMAN_RULE_DIRS
from loop_claude.project.records import HUMAN_RULE_DIR
from repo_checks import ROOT
RULE_PATH = rf"(?:{'|'.join(map(re.escape, HUMAN_RULE_DIRS))})/[\w-]+\.md"
CITATION = re.compile(rf'`?(?:~/\.claude/)?(CLAUDE\.md|{RULE_PATH})`? → ("[^"]+"(?:,? (?:and )?"[^"]+")*)')
# The review standards this repo ships. A project's config may name another folder as `standards`.
STANDARDS = "skills/larv-review/standards"
# The folders whose files a citation may name by path. The judge reads both.
RULE_DIRS = (HUMAN_RULE_DIR, STANDARDS)
RULE_PATH = rf"(?:{'|'.join(map(re.escape, RULE_DIRS))})/[\w-]+\.md"
NAMES = r'("[^"]+"(?:,? (?:and )?"[^"]+")*)'
CITATION = re.compile(rf'`?(?:~/\.claude/)?(CLAUDE\.md|{RULE_PATH})`? → {NAMES}')
# A citation of a file in whichever folder the project's config names as `standards`, checked against the folder this repo ships.
STANDARD_CITATION = re.compile(rf"the review standards' `([\w-]+\.md)` → {NAMES}")
HEADING = re.compile(r"^#+ (.+?)(?: \(.*\))?$", re.MULTILINE)
LEAD = re.compile(r"^(?:- )?\*\*(.+?)(?:\*\*|[:.](?=\*\*| )| —)", re.MULTILINE)
DECISION_CITATION = re.compile(r"`?docs/decisions\.md`? → `([^`]+)`")
@@ -27,6 +34,7 @@ class Citations(unittest.TestCase):
texts = [(path, (ROOT / path).read_text()) for path in filter(None, tracked)]
self.assertEqual([f"{path}: {stray}" for path, text in texts for stray in STRAY.findall(text)], [], 'spell a citation `CLAUDE.md` → "Vocabulary"')
cited = [(path, file, NAME.findall(run)) for path, text in texts for file, run in CITATION.findall(text)]
cited += [(path, f"{STANDARDS}/{file}", NAME.findall(run)) for path, text in texts for file, run in STANDARD_CITATION.findall(text)]
self.assertTrue(cited)
unresolved = []
for path, file, names in cited:
@@ -47,8 +55,8 @@ class Citations(unittest.TestCase):
topic_rules = (ROOT / "CLAUDE.md").read_text().split("## Topic rules\n")[1].split("\n## ")[0]
self.assertEqual(sorted(set(RULE_FILE.findall(topic_rules))), sorted(f"rules/{rule.name}" for rule in (ROOT / "rules").glob("*.md")))
def test_every_folder_the_judge_reads_rules_from_exists(self):
self.assertEqual([folder for folder in HUMAN_RULE_DIRS if not (ROOT / folder).is_dir()], [])
def test_the_rules_folder_and_the_review_standards_this_repo_ships_exist(self):
self.assertEqual([folder for folder in RULE_DIRS if not (ROOT / folder).is_dir()], [])
def test_every_decision_title_the_log_lists_at_its_head_is_a_title_in_it(self):
log = (ROOT / "docs/decisions.md").read_text()
+12 -3
View File
@@ -1,4 +1,5 @@
"""Sends one request to a REST API that speaks JSON, with a credential that no redirect may carry elsewhere."""
import dataclasses
import http.client
import json
import typing
@@ -12,6 +13,12 @@ from failure import Failure
MessageOf = typing.Callable[[object], str]
@dataclasses.dataclass(frozen=True)
class ErrorAnswer(Failure):
"""The API answered an HTTP error, whose code is status, such as 409 for a conflict."""
status: int
class NoRedirect(urllib.request.HTTPRedirectHandler):
"""Refuses every redirect, which a REST API doesn't send: urllib would resend the credential to the new location, even one off https."""
@@ -19,14 +26,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, or a Failure saying why there is 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)
@@ -35,12 +42,14 @@ def http_json(method: str, url: str, authorization: str, body: object, seconds:
raw = response.read()
except urllib.error.HTTPError as failure:
with failure:
return Failure(f"{request_name} answered {failure.code}: {error_message(failure, message_of) or failure.reason}")
return ErrorAnswer(f"{request_name} answered {failure.code}: {error_message(failure, message_of) or failure.reason}", failure.code)
except http.client.HTTPException as failure:
return Failure(f"{request_name} got a broken answer: {failure!r}")
except (OSError, ValueError) as failure:
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:
+11 -4
View File
@@ -8,6 +8,7 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from rest_client.json_request import ErrorAnswer
from failure import Failure
from rest_client import json_request
@@ -66,13 +67,19 @@ 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."))
self.assertEqual(send("GET", f"{base}/api/v4/users/me", "bad", None), ErrorAnswer("GET /api/v4/users/me answered 401: Invalid or expired session, please login again.", 401))
def test_follows_no_redirect_so_the_token_goes_only_to_the_server_named(self):
base = self.serve((302, b"{}"))
self.assertEqual(send("GET", f"{base}/api/v4/users/me", "t", None), Failure("GET /api/v4/users/me answered 302: Found"))
self.assertEqual(send("GET", f"{base}/api/v4/users/me", "t", None), ErrorAnswer("GET /api/v4/users/me answered 302: Found", 302))
self.assertEqual(len(self.server.got), 1) # type: ignore[attr-defined]
def test_sends_no_body_with_a_get(self):
@@ -90,7 +97,7 @@ class HttpJson(unittest.TestCase):
def test_names_the_status_of_an_error_whose_body_is_cut_short(self):
base = self.serve((None, b"HTTP/1.1 500 Internal Server Error\r\nContent-Length: 100\r\n\r\n{}"))
self.assertEqual(send("GET", f"{base}/api/v4/users/me", "t", None), Failure("GET /api/v4/users/me answered 500: Internal Server Error"))
self.assertEqual(send("GET", f"{base}/api/v4/users/me", "t", None), ErrorAnswer("GET /api/v4/users/me answered 500: Internal Server Error", 500))
def test_gives_up_on_a_server_that_never_answers_after_the_timeout(self):
silent = socket.socket()
@@ -120,7 +127,7 @@ class HttpJson(unittest.TestCase):
def test_an_error_whose_body_is_not_json_names_the_status_alone(self):
base = self.serve((403, b"<html>"))
self.assertEqual(send("GET", f"{base}/api/v4/users/me", "t", None), Failure("GET /api/v4/users/me answered 403: Forbidden"))
self.assertEqual(send("GET", f"{base}/api/v4/users/me", "t", None), ErrorAnswer("GET /api/v4/users/me answered 403: Forbidden", 403))
if __name__ == "__main__":
+2 -1
View File
@@ -214,7 +214,8 @@ def worse_dimensions(votes: list[str]) -> set[str]:
def table_rows(body: str) -> list[dict[str, list[str]]]:
"""Each table's rows after its header and separator, the cells after the first keyed by the first cell. Tables may touch, so a table starts at the row above a separator."""
lines = [line for line in body.splitlines() if line.startswith("|")]
separators = [index for index, line in enumerate(lines) if line.startswith("|-")]
# entry_text writes a separator as `|---|`, and adf-codec, for a history kept on a Confluence page, as `| --- |`.
separators = [index for index, line in enumerate(lines) if re.fullmatch(r"\|( *-+ *\|)+ *", line)]
ends = [*(index - 1 for index in separators[1:]), len(lines)]
return [dict(row_cells(line) for line in lines[separator + 1:end]) for separator, end in zip(separators, ends)]
+1 -1
View File
@@ -42,7 +42,7 @@ def send(config: Config, message: str, http: Http) -> Failure | None:
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)
+16 -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, add and finish work, and edit and move 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.
@@ -43,9 +48,17 @@ file, where missing. It refuses where that section holds ### subsections: add th
Where CHANGELOG.md holds text, finish needs --changelog or --no-changelog, so no bullet is left out by
mistake. It prints `Finished item <ID> in <plan>.` It doesn't write anything while docs/decisions.md cites the item.
finish <ID> --no-changelog also drops an item no chunk built.
In a Jira epic, finish doesn't remove anything: it moves the item's issue by the transition, and to
the status, that the config's `jira-finish-transition` and `jira-finish-status` name, as
`project-config --help` shows. The --changelog rules hold there too, and docs/decisions.md isn't checked.
It fails, moving no issue, where the config sets neither, where the issue has no such transition
from its present status, or where the transition leads to another status or to one Jira doesn't
count as done. An issue that no chunk built is dropped in Jira, not with finish, which would mark it done.
Exit 2 on bad arguments, and 1, saying why, on any other failure. A message opening `not filed:`,
`not edited:`, `not moved:` or `not finished:` means it didn't write anything.
`not edited:`, `not moved:` or `not finished:` means it didn't write anything. The one exception is an add to, or a
finish in, a Jira epic that Jira didn't answer or answered brokenly: the message then says the issue
may exist, or may have moved.
"""
import argparse
import pathlib
+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()
+44 -9
View File
@@ -17,9 +17,10 @@ Each project principle states one rule that the decisions below apply; their ent
- bin/: the tools support only the latest stable Python, and the tests, written in plain unittest, run on it in four pytest-xdist workers
- deploy: this repo keeps no `AGENTS.md`, since `~/.claude` is its checkout; its principles and decision titles head `docs/decisions.md`, its working rules follow them there, and its `.claude/settings.json` excludes every `.claude/CLAUDE.md`, so a session in the clone loads only the clone's `CLAUDE.md`
- loop-claude: each verdict records the claude-config release and commit that ran it, the raw tokens each thread spent by model and kind since the previous outcome that recorded a spend, and the human's typed answer the judge quotes as reversing a choice the worker took on its own recommendation
- loop-claude: one session per project, its id derived from the checkout's path relative to `~/code`, or to `/` outside it
- loop-claude: one session per running loop of a project, named after the slot the loop holds, its id derived from that name; a chunk's commit in the config's folder takes only the file it changed
- machine load: a heavy command waits for one of the machine's heavy slots, one for every 4 CPUs, which every session shares, and loop-claude starts a worker only while at least a quarter of the machine's memory is available
- principles: about seven things per level, four or five where they act on each other, more where a reader finds them by name; crossing a limit asks for a grouping or a recorded reason
- project config: a record may name a Confluence Cloud page as `confluence:` and its address, the loop reads and writes it as markdown, and a write never overwrites a save made since the loop's read
- project config: a tool that reads a file's commits says where it does not support that file, and the work goes on
- project config: `language` names the prose's language by its English name, and `commit-title`, `pull-request-title` and `branch` are brace templates over `{id}` and `{summary}`
- project config: `plan` may name a Jira Cloud epic as `jira:` and its address, the plan is its open child issues in backlog order, and an issue's number is the item's ID
@@ -38,10 +39,11 @@ 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: 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/`
- worker: a chunk's worker writes the simplest change that solves its item, test first wherever a test can check the change, and reads a technical principle only where the item, a finding or its own record names it; larv-review's reviewers hold the change to the principles and to the project's review standards
- workflow-bench/: the remote may show the bench cases' names and commit SHAs
# Working rules
@@ -118,9 +120,9 @@ Valid while `~/.claude` is a checkout of this repo.
2026-10-03, lilleman. Serves goals 1.2 and 1.4. When the README's premises or those files answer the worker's question, the judge quotes the answer verbatim and the worker resumes with it, so an answer recorded there is not asked again. The judge then sees the quote as a `[loop]` line. The worker asking it again shows the quote did not settle it, and the judge sends it to the human. A backstop of three quoted answers per cycle bounds what the judge misses, such as a reworded repeat or a worker asking without end, so the worker cannot loop unattended: the fourth question that the README's premises or those files answer in one cycle goes to the human with the judge's quote. An interrupt does not reset the count, so every later question they answer in that cycle also goes to the human. Valid while the worker writes records only in a worktree, as `CLAUDE.md` → "Working with the codebase" has it, so the records the judge reads from the checkout root are merged ones.
2026-10-03, lilleman. Serves goal 1.2. The judge reads `~/.claude/CLAUDE.md`, each file under `~/.claude/rules/` and each file under `~/.claude/skills/larv-review/standards/` whole. The worker follows them, so a question they answer should not reach the human. Reading whole is safe, because the judge may quote only words that appear in them, and a list of sections would need keeping current.
2026-10-03, lilleman. Serves goal 1.2. The judge reads `~/.claude/CLAUDE.md`, each file under `~/.claude/rules/` and each file in the project's review standards, the folder its config sets as `standards`, whole. The worker follows them, so a question they answer should not reach the human. Reading whole is safe, because the judge may quote only words that appear in them, and a list of sections would need keeping current.
2026-10-03, lilleman. Serves goal 1.2. The judge rules a chunk finished only once every answer the human typed in it is recorded. A finished chunk's session is deleted, and its answers with it, so an answer recorded nowhere would be asked again in a later chunk. Claude settled two choices lilleman's ruling left open. First, an answer counts as recorded where the files the judge reads hold it, `~/.claude/CLAUDE.md` included, or where the transcript shows the worker writing it into `README.md`'s premises, `AGENTS.md`, `docs/decisions.md`, `todo.md` or a code comment. A worker's write to `~/.claude/CLAUDE.md`, `~/.claude/rules/` or `~/.claude/skills/larv-review/standards/` does not count: the judge reads the live `~/.claude`, which holds the write only once it merges and the checkout is pulled. The judge cannot read a code comment or `todo.md`. Yet `CLAUDE.md` → "Working loop", "Ask, don't guess" puts a standing choice made in one place in a comment there. And the human's approval of a release's items, which "Working loop" requires, is the set of rows `todo.md` names for that release. The judge also reads the records once a cycle from the main checkout. That checkout may not yet hold an answer the worker wrote and merged. A judge that refused any of these would hold the chunk open every cycle. Second, only an answer a later chunk could need must be recorded, so an approval such as "merge it" doesn't hold anything open. The worker's resume prompt states the rule, so a worker whose chunk is held open knows it.
2026-10-03, lilleman. Serves goal 1.2. The judge rules a chunk finished only once every answer the human typed in it is recorded. A finished chunk's session is deleted, and its answers with it, so an answer recorded nowhere would be asked again in a later chunk. Claude settled two choices lilleman's ruling left open. First, an answer counts as recorded where the files the judge reads hold it, `~/.claude/CLAUDE.md` included, or where the transcript shows the worker writing it into `README.md`'s premises, `AGENTS.md`, `docs/decisions.md`, `todo.md` or a code comment. A worker's write to `~/.claude/CLAUDE.md`, `~/.claude/rules/` or the project's review standards does not count: the judge reads those files where they are kept, not in the chunk's worktree, so they hold the write only once it merges and reaches there. The judge cannot read a code comment or `todo.md`. Yet `CLAUDE.md` → "Working loop", "Ask, don't guess" puts a standing choice made in one place in a comment there. And the human's approval of a release's items, which "Working loop" requires, is the set of rows `todo.md` names for that release. The judge also reads the records once a cycle from the main checkout. That checkout may not yet hold an answer the worker wrote and merged. A judge that refused any of these would hold the chunk open every cycle. Second, only an answer a later chunk could need must be recorded, so an approval such as "merge it" doesn't hold anything open. The worker's resume prompt states the rule, so a worker whose chunk is held open knows it.
2026-10-17, lilleman, todo item 168. The human answers an interrupt on loop-claude's terminal, and the worker resumes headless with the answer in a `-p` prompt. The judge reads that answer as a `[human]` line, not a `[loop]` one, so it holds the chunk open until the answer is recorded, as it does for an answer typed in claude.
@@ -140,9 +142,17 @@ Valid while `~/.claude` is a checkout of this repo.
2026-09-30, lilleman. Applies "Always grant explicit access to data": the sandbox `loop-claude` runs in is where access is granted, so the worker and the claude an interrupt opens run with `bypassPermissions`. The worker may read `~/.claude/.credentials.json`: it holds Claude Code's own credentials, which claude reads to run anyway. Its one seam to production is the forge: what it pushes or merges can publish through CI. Valid while `loop-claude` runs only in the sandbox README → Install names.
## loop-claude: one session per project, its id derived from the checkout's path relative to `~/code`, or to `/` outside it
## loop-claude: one session per running loop of a project, named after the slot the loop holds, its id derived from that name; a chunk's commit in the config's folder takes only the file it changed
2026-09-21, lilleman; revised 2026-09-30 by lilleman. Serves goal 1. One fixed id per project keeps the session picker at one entry per project and makes any transcript under that id loop-claude's own to delete. A checkout outside `~/code` mirroring a path inside it shares that id, and a second loop on it is not refused. Once `todo.md` item 5 lands, the id comes from the full path, so no two checkouts share one, and `loop-claude` refuses to start while another session on that id is active. Moving the checkout orphans its open sessions, archive folder and models entry: sessions stay in the picker until the human deletes them, migration code not being worth a one-human audience. Valid while claude takes `--session-id` and resumes by it.
2026-09-21, lilleman; revised 2026-09-30 by lilleman. Serves goal 1. Ids derived from names keep the session picker at one entry per running loop and make any transcript under those ids loop-claude's own to delete. A checkout outside `~/code` mirroring a path inside it shares that id, and a second loop on it is not refused. Once `todo.md` item 5 lands, the id comes from the full path, so no two checkouts share one, and `loop-claude` refuses to start while another session on that id is active. Moving the checkout orphans its open sessions, archive folder and models entry: sessions stay in the picker until the human deletes them, migration code not being worth a one-human audience.
2026-11-15, lilleman's call of 2026-11-13 in item 372, which split item 361: loops of one project, each on its own chunk, run side by side without touching each other's state. The worker's choices, for what the call left open:
- **A slot, not the chunk, names the session.** A loop names its session before it knows its chunk, since a rerun resumes the open session in place of running `chunk-preflight`. So each loop holds a slot, a file it keeps locked with flock under `~/.local/state/loop-claude/<key>/` (`bin/loop_claude/loop/chunk_slot.py`): the lowest free slot whose session is open, so a rerun resumes a chunk left open, or else the lowest free slot. A session lives one chunk, so one slot holds one chunk at a time. Slot 0 keeps the name every loop had before slots, so a chunk left open before slots still resumes. A reload's exec keeps the lock and hands on the slot.
- **The archive and the route needed no change.** The archive keys each chunk by its own transcript's first line, and a rerun's route comes from the latest verdict on that transcript, so both follow the session. The routing figures are measured across all projects, under their own lock.
- **git's own lock serializes the config folder's commits, in place of the file lock the item asked for.** `git commit` holds `.git/index.lock`, so of two commits at once the second fails, and the worker tries again. A wrapper lock would only make it wait, and a command spelled `flock … git commit` would pass rule-hook unchecked, since it reads only a command that starts with `git`. What two chunks could still break is one committing the file the other staged, so each commits only its own file, as `git commit -m <title> -- <file>` (`CLAUDE.md` → "Git, commits, and PRs").
Valid while claude takes `--session-id` and resumes by it, and a loop names its session before it knows its chunk.
## loop-claude: the archive keeps the raw transcript, and a failed archive stops the loop
@@ -267,6 +277,16 @@ Valid while the later fixes per finished chunk, which `score-outcomes` and the r
2026-10-04, lilleman. Serves goal 1.4. In a restructure, each step's scoring run measures code the next step deletes. It costs a run and, below the floor, blocks the step, yet doesn't say anything about what the restructure buys. The scoring run after the last step measures that. 2026-10-08: the paired ruling replaced the scoring run in most chunks, and the suspension covers it too; the ruling after the last step compares with the commit measured before the first step. 2026-10-13, lilleman: the comprehension check doesn't block anything now, so a suspension saves only the runs. Valid while such a decision names its items and the plan item that ends it.
## project config: a record may name a Confluence Cloud page as `confluence:` and its address, the loop reads and writes it as markdown, and a write never overwrites a save made since the loop's read
2026-11-15, larv-review, on lilleman's calls of 2026-11-12. Serves goal 1.6: a client's team keeps its records in its own wiki. Valid while one record fits one page, and while one session per project opens a record's copy, which todo.md's item 375 ends.
- **A bench of readers picked the spelling.** Three fresh readers, seated as the person who writes a client's `config.toml`, each picked `decisions = "confluence:https://<site>/wiki/spaces/<space>/pages/<page ID>"`, pasted from the browser with or without the title at its end, over the bare address, a page ID beside a `confluence-site` key, and a table. Each named the match with `jira:`. Any of the five records may name a page; the goals file, the plan, the working rules and the principles may not.
- **`decisions` and `comprehension-history` may name a page only where `plan` names a Jira epic.** rule-hook ranks a plan kept as a file before tool calls, inside its 30-second limit, and ranking reads those two records. A Confluence read and two adf-codec container runs would hold up every guarded tool call, and fail it while Confluence is down. `load` refuses goals in Jira beside a plan in a file for the same reason.
- **A write sends the version number the store read, plus one, and Confluence refuses it with 409 where someone saved the page since.** The store then fails, saying to ask the human, and doesn't write the page; the loop never overwrites a teammate's edit on its own (lilleman, 2026-11-12). A write with no read before it replaces the page as it stands, as the record contract asks.
- **`project-record` keeps the version `open` read in a file beside its copy**, `~/.local/state/project-record/<key>/<record>.version`, since `save` runs in a later process. The store keeps the version itself, so `write` still takes only the text. Every other tool reads and writes a record in one process, and its store keeps the version in memory, so a read by another tool, such as larv-review's, never moves the version an edit in `project-record` rests on.
- **The page holds ADF, which adf-codec converts both ways**, so a teammate reads the record as Confluence renders it. Where adf-codec cannot convert the markdown, the write fails with adf-codec's error. A node markdown cannot hold reads as text: a mention as its name, a macro as `_(<macro> not included)_`. So the next write replaces it with that text, and a record page should hold only what markdown can.
## project config: a tool that reads a file's commits says where it does not support that file, and the work goes on
2026-11-13, larv-review. Serves goal 1.6: a client's plan and records live in the config's folder, and the loop still runs there. A file the config puts outside the checkout has no commit in the project's history, so a tool that needs the file's commits cannot do its job for it. No such tool blocks the loop or a merge, and each says what it leaves undone:
@@ -301,7 +321,8 @@ 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, files and finishes, and doesn't edit an issue** until todo.md's item 382. It finishes an item with the transition that the config's `jira-finish-transition` names, which must lead to the status `jira-finish-status` names, since each Jira workflow differs (lilleman's call, 2026-11-12); any open child of the epic may move. It refuses a status outside Jira's done status category: the read counts an issue as finished only in that category, so the item would stay in the plan. Where the issue's present status has no direct transition to the status `jira-finish-status` names, `todo-item finish` fails and a person moves the issue in Jira: the store never walks an issue through other statuses to reach it. lilleman answered on 2026-11-15: "If it is possible to move it to done without a transisiont, that should happen. If not, fail." The implementer read "without a transition" as "without a transition in between". `rank_todo.py` refuses to rank a plan in Jira, and its `--check` passes, since Jira's backlog ranks it; rule-hook's rank check skips it. Each read first asks Jira for the epic itself, since a search under an epic the account cannot see answers no issues, as a finished plan does.
## 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
@@ -315,7 +336,7 @@ Messages keep each file's usual name, such as `todo.md`, as its label, since the
2026-10-15, lilleman asked for it through todo item 144, implemented by claude. Serves goal 1.1: a cheap reviewer that finds the work below standard can have a more capable one check that ruling, and work below standard gets a more capable rung to fix it, unless the fix changes only prose.
The work is below standard where systems-architect returns BLOCK, a reviewer reports a finding against larv-review's `standards/quality.md`, or `record-ruling` counts a comprehension seat's vote in a paired ruling as worse. That reviewer or seat may ask, and the worker then relaunches it on the rung loop-claude's prompt names, one above the rung it ran on. `bin/loop_claude/cycle/prompts.py`'s `reruns` names it: the seats run on the project's rung, and the reviewers on the highest of the worker's rung and the one their item's E + I picks. Off the ladder, or for a reviewer or seat already on the top rung, the prompt names none, and its report stands.
The work is below standard where systems-architect returns BLOCK, a reviewer reports a finding against the review standards' `quality.md`, or `record-ruling` counts a comprehension seat's vote in a paired ruling as worse. That reviewer or seat may ask, and the worker then relaunches it on the rung loop-claude's prompt names, one above the rung it ran on. `bin/loop_claude/cycle/prompts.py`'s `reruns` names it: the seats run on the project's rung, and the reviewers on the highest of the worker's rung and the one their item's E + I picks. Off the ladder, or for a reviewer or seat already on the top rung, the prompt names none, and its report stands.
A reviewer's relaunch gets the report that asked and confirms or dismisses each of its findings with a reason, so no finding goes unanswered; a seat's relaunch reads afresh, since a seat reports no findings. The relaunch's report stands in place of the one that asked, in the same round, so it adds no round, and a relaunch cannot ask again. So the round cap still bounds a pass, and one round launches a reviewer at most twice. The ruling that stands is the fourth escalation trigger in `CLAUDE.md`, except where the fix changes only prose: the worker fixes that on its own rung. lilleman ruled that on 2026-11-08 through todo item 276, after PR #432's two quality findings were false claims, one in a docstring and one in a sentence of this file. lilleman also ruled that no ruling raises the judge's rung, which `routing: on a model judge-replay covered` sets.
@@ -652,6 +673,20 @@ 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: 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.
@@ -705,7 +740,7 @@ Four choices the item left open:
`rules/todo-items.md` loads when a session itself reads or writes a `todo.md`, which a session that runs `todo-item` never does, so `CLAUDE.md` → "Topic rules" asks for it before an item is filed, scored, edited or moved. A reviewer without a shell reads the plan from the listing `larv-review reviewer-header` writes, which the header's `Plan:` line names. Valid while `todo-item` is the only command that changes a plan's items.
## worker: a chunk's worker writes the simplest change that solves its item, test first wherever a test can check the change, and reads a technical principle only where the item, a finding or its own record names it; larv-review's reviewers hold the change to the principles and to the standards in `skills/larv-review/standards/`
## worker: a chunk's worker writes the simplest change that solves its item, test first wherever a test can check the change, and reads a technical principle only where the item, a finding or its own record names it; larv-review's reviewers hold the change to the principles and to the project's review standards
2026-10-13, lilleman through todo item 104, implemented by claude. Serves goals 1.4 and 1.5. Like red, green, refactor: the worker makes the item work, and the review passes raise it to the bar. A loop-claude worker loaded `CLAUDE.md` and every file under `rules/`, 4,247 words, and `CLAUDE.md` told it to read `technical-principles.md` too, 2,426 words more. The reviewers read the principles anyway, and a finding against one names it.
+97
View File
@@ -2152,3 +2152,100 @@ Read most (opens and searches):
- `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
## Reading cost, chunk 6cc45aabfc70, finished 2026-11-15T10:19:26Z
81857 new input tokens before the first commit.
Read most (opens and searches):
- `docs/score-anchors.md` 3
- `bin/plan_store/jira_epic.py` 2
- `bin/plan_store/stores.py` 2
- `rules/todo-items.md` 2
- `bin/adf_codec/convert.py` 1
- `bin/plan_store/contract.py` 1
## Reading cost, chunk e42be6f8dd66, finished 2026-11-15T11:13:36Z
175773 new input tokens before the first commit.
Read most (opens and searches):
- `bin/project_config/test_project_config.py` 5
- `bin/record_store/test_stores.py` 5
- `bin/project_config/settings.py` 4
- `bin/rest_client/test_json_request.py` 4
- `README.md` 3
- `bin/plan_store/jira_epic.py` 3
- `bin/project_config/main.py` 3
- `bin/project_record/main.py` 3
- `docs/decisions.md` 3
- `bin/adf_codec/convert.py` 2
## Reading cost, chunk 85cc03e9b3e9, finished 2026-11-15T11:46:29Z
195738 new input tokens before the first commit.
Read most (opens and searches):
- `bin/project_config/test_project_config.py` 8
- `bin/loop_claude/test_loop_claude.py` 7
- `bin/loop_claude/loop/usage.py` 6
- `README.md` 5
- `docs/decisions.md` 5
- `bin/larv_review/test_larv_review.py` 4
- `CLAUDE.md` 3
- `bin/loop_claude/project/records.py` 3
- `bin/project_config/main.py` 3
- `bin/project_config/settings.py` 3
## Reading cost, chunk 09532b58c32b, finished 2026-11-15T13:01:57Z
152048 new input tokens before the first commit.
Read most (opens and searches):
- `README.md` 5
- `bin/project_config/settings.py` 5
- `bin/plan_store/jira_epic.py` 4
- `bin/project_config/main.py` 4
- `bin/todo_item/main.py` 4
- `bin/plan_store/test_jira_epic.py` 3
- `bin/project_config/test_project_config.py` 3
- `bin/plan_store/stores.py` 2
- `docs/decisions.md` 2
- `CHANGELOG.md` 1
+2 -1
View File
@@ -5,7 +5,7 @@ paths:
# Todo items (`todo.md`)
- **A plan is mandatory in every project, and a plan kept as `todo.md` has the shape `rank_todo.py --help` shows**, which `~/.claude/bin/rank_todo.py` checks and ranks; its `--help` shows a valid file. A plan in a Jira epic is read from the epic's open child issues, and `todo-item` can't write one yet. Below, `todo.md` means a plan kept as a file, and "the plan" either kind. `## Scoring` holds the formula and the bar; `## Items` is one table of every item; `## Details` holds each item's detail under its ID. `## Renamed` marks each renamed release with a line such as `- 0.2.1 renamed to 0.3.0`; `rank_todo.py --help` says what a mark does. Cite an item by its ID. The formula and bar are the project's own to tune.
- **A plan is mandatory in every project, and a plan kept as `todo.md` has the shape `rank_todo.py --help` shows**, which `~/.claude/bin/rank_todo.py` checks and ranks; its `--help` shows a valid file. A plan in a Jira epic is read from the epic's open child issues. `todo-item add` files an item there as a new child issue, and `todo-item finish` moves an item's issue to done, and `todo-item` can't edit or move an issue yet. Below, `todo.md` means a plan kept as a file, and "the plan" either kind. `## Scoring` holds the formula and the bar; `## Items` is one table of every item; `## Details` holds each item's detail under its ID. `## Renamed` marks each renamed release with a line such as `- 0.2.1 renamed to 0.3.0`; `rank_todo.py --help` says what a mark does. Cite an item by its ID. The formula and bar are the project's own to tune.
- **File an item with `~/.claude/bin/todo-item add`, and change one with `todo-item edit` or `todo-item move`.** `add` and `edit --detail` read the item's detail from stdin, and all three commands rank the plan; `todo-item --help` shows the flags. `todo-item finish <ID> --no-changelog` drops an item no chunk built. Edit `todo.md` itself only for what `todo-item` has no command for: `## Scoring`, `## Renamed`, and reshaping an old table.
- **Order items only by score and the Blocked by column.** An item's Blocked by cell lists the IDs of the items that must be done before it starts, such as `12, 14`; `rank_todo.py --help` says how it ranks them. No text in `todo.md` outside the table orders items: where an item must go first, score it so, and say why in its detail.
- **Plan only on the project's rung or above.** loop-claude's prompt tells you when you run below it. Below it, never score or re-score an item, move it between releases, split a milestone into items, delete an item under the bar, rewrite a filed item's tagline or detail, or choose or replace an item in `docs/score-anchors.md`. Draft each new item, each change to a filed item, and each change to the anchors, instead. Before your next commit, launch one subagent to apply the drafts, score them and set their release. Launch it on the rung `CLAUDE.md`'s delegation rule gives a subagent that files or scores items. Keep the scores and releases it writes. For a security finding, launch it at once. Any rung may remove a finished item's row and detail, and score a delegated task's L. A subagent launched for another task leaves the plan alone.
@@ -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.
+5 -5
View File
@@ -9,7 +9,7 @@ You orchestrate, fix, and ship; reviewers only report. Run every reviewer in the
**Forge-neutral.** Five PR operations recur below: read a PR's diff, open a draft PR, read check status, mark ready, merge. On GitHub and Gitea, `~/.claude/bin/chunk-pr` opens the draft PR, marks it ready and merges it. Read the diff and the checks with the forge's own CLI, `gh` or `tea` per `~/.claude/CLAUDE.md` → "Git, commits, and PRs". On any other forge, achieve all five through its CLI or API — discover how rather than assuming. A forge without a native draft state gets the closest equivalent (a `WIP:`/`Draft:` title prefix); note any approximation in the summary.
The bar a chunk is reviewed to: ~/.claude/skills/larv-review/standards/quality.md. Words: `~/.claude/CLAUDE.md` → "Vocabulary". What a reviewer reports: ~/.claude/skills/larv-review/review-findings.md; how you resolve it: §3 → "Findings".
The bar a chunk is reviewed to: `quality.md` in the project's review standards, the folder `~/.claude/bin/project-config standards` prints. Words: `~/.claude/CLAUDE.md` → "Vocabulary". What a reviewer reports: ~/.claude/skills/larv-review/review-findings.md; how you resolve it: §3 → "Findings".
**An ask** holds only what it asks about; the rest runs on while it waits. No user reachable (a headless run) → finish the rest, then leave the PR unmerged with the question and your recommendation in the summary, unless the ask's rule names another branch.
@@ -65,7 +65,7 @@ Give a reviewer without Bash `git ls-files`'s output in its prompt, since some h
`~/.claude/bin/larv-review` holds this section's mechanical rules: the chunk's review folder, the round count, the paired ruling's base and vote count, the scoring run's trigger; the history's format, its latest places and its count of how often seats agree; and the header of each reviewer's prompt. Run it in the chunk's worktree; `~/.claude/bin/larv-review --help` states each rule. On exit 1, repair what its message names and run it again; when you cannot, ask the user.
**Reports.** Run `~/.claude/bin/larv-review reviewer-header <pass>` in the chunk's worktree, and open each prompt to an agent under `~/.claude/agents/` with what it prints; then say in a few lines what the change does and which files it touches. The command makes the chunk's review folder and writes the branch diff and the plan's listing into it. The header names that diff, the reviewer's full report, `<pass>-round-<n>.md`, in the folder, the folder of technical principles the project's config sets, the listing, and for architecture and stability the places too. For a reviewer whose definition starts it without `CLAUDE.md`, the header's last line names the file that holds the project principles and decision titles, which the reviewer reads first. For a relaunch one rung up, add `--rerun`: the report becomes `<pass>-round-<n>-rerun.md`, and the header names the report that asked. Before you answer a 🔴 or 🟡, read its entry: Grep the report for the finding's place, with the lines after it, rather than Read the whole report. rule-hook refuses a reviewer's Edit and MultiEdit, and any Write outside `~/.local/state/larv-review/`. Keep the folder after the merge: `review-replay` replays a round from the reports its prompt names.
**Reports.** Run `~/.claude/bin/larv-review reviewer-header <pass>` in the chunk's worktree, and open each prompt to an agent under `~/.claude/agents/` with what it prints; then say in a few lines what the change does and which files it touches. The command makes the chunk's review folder and writes the branch diff and the plan's listing into it. The header names that diff, the reviewer's full report, `<pass>-round-<n>.md`, in the folder, the folders of technical principles and review standards the project's config sets, the listing, and for architecture and stability the places too. For a reviewer whose definition starts it without `CLAUDE.md`, the header's last line names the file that holds the project principles and decision titles, which the reviewer reads first. For a relaunch one rung up, add `--rerun`: the report becomes `<pass>-round-<n>-rerun.md`, and the header names the report that asked. Before you answer a 🔴 or 🟡, read its entry: Grep the report for the finding's place, with the lines after it, rather than Read the whole report. rule-hook refuses a reviewer's Edit and MultiEdit, and any Write outside `~/.local/state/larv-review/`. Keep the folder after the merge: `review-replay` replays a round from the reports its prompt names.
**Precedent, then ask** — for the full scan:
@@ -104,7 +104,7 @@ A fix meets every row it fits. Prose has no row, so a comment or doc edit inside
**What a round reviews.** An agent under `~/.claude/agents/` reviews the branch in round 1. From round 2 it reviews only the answers to its last round's findings, and each fix from another pass that re-entered its pass. Prompt it with the path of its last round's report and each finding's answer: the fix's diff, or the reason it was dismissed. Give it each other pass's fix as `git diff <the commit before that fix> <the fix's commit>`, since the fixes may be unpushed, with the finding it answered. It reports only an answer that is plainly wrong or worse than the change it answered, so its pass converges in its second round. Other reviewers review the branch as their tool does.
**Rung up.** A reviewer rules the work below standard when its report holds systems-architect's BLOCK or a finding against `standards/quality.md`. A comprehension seat does when `record-ruling` counts one of its votes as worse.
**Rung up.** A reviewer rules the work below standard when its report holds systems-architect's BLOCK or a finding against the review standards' `quality.md`. A comprehension seat does when `record-ruling` counts one of its votes as worse.
- **Ask.** Such a reviewer or seat may end its report asking for a rerun one rung up. Relaunch it only on the rung loop-claude's prompt names for it; where the prompt names none, the report stands.
- **Relaunch.** Relaunch a reviewer on that rung with the same prompt, except for its header, made with `--rerun` per "Reports"; its report stands in place of the report that asked, in the same round. Relaunch a seat with the same prompt alone; its line replaces the one that asked in the votes file, before `record-ruling` runs. A relaunch cannot ask again.
@@ -115,7 +115,7 @@ A fix meets every row it fits. Prose has no row, so a comment or doc edit inside
- **Outside the chunk.** A finding outside the chunk's change, whatever its pass or severity, is scored and filed in `todo.md` per `~/.claude/rules/todo-items.md`. A 🔴 is marked `defect`. A 🟡 against a file in the config's principles folder is marked `principle`, its detail naming the principle, where no other reason fits. One under the bar and not exempt is named in the summary with its score. A verified security HIGH is handled per "Security". In the release review the whole project is the chunk's change, so nothing lies outside it; "Release review" → "Findings" says which of its findings are filed.
- **Goal or decision.** A fix that would change a goal, or a `docs/decisions.md` entry the repo held before the chunk began, is asked; no user reachable → filed, marked `question`, the goal or decision left as is.
- **New decision.** Each decision a fix or an answer records in `docs/decisions.md` is checked against the project principles per `~/.claude/rules/decisions.md` → "Decisions: one home, each linked to a goal or a technical principle", "Check each new decision against the project's principles", before the commit that records it.
- **🔴.** A 🔴 is fixed, or shown factually wrong, and what disproved it recorded per `~/.claude/skills/larv-review/standards/comments.md` → "Where a choice goes": in a comment at the code the finding concerns, or in `docs/decisions.md` when it concerns more than one place. Never declined.
- **🔴.** A 🔴 is fixed, or shown factually wrong, and what disproved it recorded per the review standards' `comments.md` → "Where a choice goes": in a comment at the code the finding concerns, or in `docs/decisions.md` when it concerns more than one place. Never declined.
- **🟡.** A 🟡 is fixed, shown factually wrong like a 🔴, or declined. Decline one only where the reason is sound, consistent with the goals and the technical principles, and confidence is very high; the decline and its reason are recorded the same way. A reason neither speaks to is a gap in the goals: fix the finding, or ask per `~/.claude/CLAUDE.md` → "Working loop", "Ask, don't guess"; no user reachable → fix. Never drop one silently, and never decline one for convenience or the size of the fix.
- **🟢 and ❓.** A 🟢 or ❓ is fixed, answered, declined in the summary with its reason, or filed. Answer one where the code, a test, a goal or a decision the repo held before the chunk began settles it, and quote what in the summary. A ❓ only the user can answer is asked; no user reachable → filed, marked `question`.
- **🔀.** A 🔀 runs the named reviewer's pass once the current pass is done.
@@ -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.
+3 -3
View File
@@ -12,7 +12,7 @@ A reviewer reads and reports; it doesn't edit anything. It writes no file but it
- ❓ **question** for the author: a finding you could not confirm goes here, not above.
- 🔀 **escalation** — names the reviewer whose concern it is (`product-owner-reviewer`, `systems-architect` or `/security-review`) and why, in one line.
A finding against a technical principle names it and the file in the config's principles folder it lives in. A finding against `~/.claude/skills/larv-review/standards/quality.md` names that file and the rule it breaks.
A finding against a technical principle names it and the file in the config's principles folder it lives in. A finding against `quality.md`, in the folder your prompt's `Review standards:` line names, names that file and the rule it breaks.
## Misread
@@ -28,14 +28,14 @@ A review's first line, derived from the findings:
## Rung up
Where your report holds a finding against `~/.claude/skills/larv-review/standards/quality.md`, or you are systems-architect and return BLOCK, you may end it with the line `Rerun one rung up` when you want a more capable reviewer to check that ruling.
Where your report holds a finding against `quality.md`, or you are systems-architect and return BLOCK, you may end it with the line `Rerun one rung up` when you want a more capable reviewer to check that ruling.
## Report
Write your full report with the Write tool to the file your prompt names. The file is the worker's input, which it searches for each finding's entry, so write it even where your harness says to return findings directly. It holds the verdict, then every finding with its place, its evidence and its fix, as your agent file shapes them. Then return only:
- the verdict line
- one line per finding, in this order: its severity mark, `[misread]` where you marked the finding so, its place, and what is wrong, in one sentence. Where the finding breaks `standards/quality.md` or a file in the config's principles folder, end the line with that file's name. For a 🔀, end it with the reviewer it names. Example: ``🟡 `bin/example.py:42` `parse`: an empty line raises IndexError (technical-principles.md)``
- one line per finding, in this order: its severity mark, `[misread]` where you marked the finding so, its place, and what is wrong, in one sentence. Where the finding breaks the review standards' `quality.md` or a file in the config's principles folder, end the line with that file's name. For a 🔀, end it with the reviewer it names. Example: ``🟡 `bin/example.py:42` `parse`: an empty line raises IndexError (technical-principles.md)``
- for stability-reviewer, whether the tests passed, and at which commit
- `Rerun one rung up`, where your report ends with it
- the report's path
+1 -1
View File
@@ -2,7 +2,7 @@
**A README covers what a reader needs *before* opening the code**: how it meets its goals, and how to build, test, run, and deploy it. It does **not** narrate an individual symbol, file, or test case — whoever wants to know what a test asserts opens the test, where the answer is exact and cannot drift.
**Refresh `README.md` only to keep it true.** A change that alters a build/test/run/deploy step, a required env var, or a prerequisite makes the README a false claim by omission, fixed per `~/.claude/skills/larv-review/standards/quality.md` → "A false claim is a bug". Otherwise most changes need no README edit at all. GOOD: `run-tests.sh` gained a required `--profile` flag → update the documented command. BANNED: the change added a test case → add a paragraph describing it.
**Refresh `README.md` only to keep it true.** A change that alters a build/test/run/deploy step, a required env var, or a prerequisite makes the README a false claim by omission, fixed per the review standards' `quality.md` → "A false claim is a bug". Otherwise most changes need no README edit at all. GOOD: `run-tests.sh` gained a required `--profile` flag → update the documented command. BANNED: the change added a test case → add a paragraph describing it.
## Package README (what someone finds on npm or GitHub)
- The public API is the contract, so the README documents it: options, results, events, everything exported. The rule against narrating a file or test case still holds.
+51 -40
View File
@@ -6,20 +6,18 @@
`Bar = 0.1`
`Next ID = 381`
`Next ID = 387`
## Items
| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 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 |
| 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 |
| 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 | | decision | **Merge open chunks one at a time: rebase, finish the item in todo.md and CHANGELOG.md, rerun the gate and the paired ruling, and keep a chunk waiting for approval in the queue without blocking the next.** | 4 | 2 | 3 | 7 | 6 | 1.5 by 4, 1.6 by 3 | 1.0 |
| 386 | 0.11.0 | | | **Key project-record's copies per worktree, so two chunks of one project editing the same record kept outside a file don't overwrite each other's unsaved edit.** | 2 | 2 | 2 | 4 | 2 | 1.1 by 2 | 0.8 |
| 359 | 0.11.0 | | | **Tie a project's releases to what its config names: semver tags, Jira Fix Versions, sprints, or none.** | 3 | 2 | 3 | 6 | 4 | 1.6 by 3 | 0.8 |
| 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 |
| 384 | 0.11.0 | | | **Rank an issue the loop files in Jira by its score among the issues the loop filed, a security finding first.** | 3 | 2 | 2 | 5 | 3 | 1.6 by 2 | 0.7 |
| 375 | 0.11.0 | 374 | decision | **Run up to the project's configured number of chunks at once, each in its own window of one tmux session named for the project, mark a window whose chunk waits for the human, and refuse to start without tmux at the needed version.** | 4 | 2 | 3 | 7 | 7 | 1.5 by 7 | 0.6 |
| 319 | 0.12.0 | | | **Start a fresh session with a brief of the chunk when a rung step changes the worker's model, in place of resuming the old session.** | 3 | 2 | 3 | 6 | 4 | 1.1 by 2, 1.4 by 2 | 1.2 |
| 309 | 0.12.0 | | | **Run a scoring run's second pass on one head with two seats in place of four, once `larv-review agreement` shows the seats agree with each other more than a run agrees with its rerun.** | 2 | 2 | 2 | 4 | 2 | 1.4 by 3 | 1.2 |
| 299 | 0.12.0 | | | **Replay the archived judge verdicts through code rules and a classifier trained locally on the archive, and file an item for each verdict kind one of them decides with no missed interrupt.** | 2 | 2 | 2 | 4 | 3 | 1.4 by 3 | 1.0 |
@@ -30,11 +28,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 | | **Have `score-outcomes` read the finished and dropped items of a plan outside the checkout, from the project repo's history or from Jira's issue changelogs.** | 3 | 2 | 2 | 5 | 4 | 1.6 by 2, 1.1 by 2 | 1.2 |
| 368 | 0.13.0 | 382 | | **Call a release review due, call a release ready to cut, and tell whether a chunk owes a scoring run, for a plan outside the checkout, from the project repo's history or from Jira.** | 3 | 2 | 2 | 5 | 4 | 1.6 by 2, 1.1 by 2 | 1.2 |
| 366 | 0.13.0 | 382 | | **Count the chunks of a project whose plan sits outside the checkout in the routing figures, from the project repo's history or from Jira.** | 3 | 2 | 2 | 5 | 4 | 1.6 by 2, 1.4 by 2 | 1.1 |
| 367 | 0.13.0 | 382, 384 | | **Check that every write to a Jira plan leaves it ranked, as rule-hook's `todo-rank-check` checks `todo.md` today.** | 2 | 2 | 3 | 5 | 3 | 1.6 by 2 | 0.7 |
| 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 |
@@ -78,34 +77,6 @@
## Details
### 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.
### 355. Store a record on the Confluence Cloud page its config names, as markdown converted through the adf-codec shim, and interrupt the human when a teammate saved the page since the loop read it.
lilleman's calls, 2026-11-12: one page per record, whose ID the config names. The loop reads the page's ADF as portable markdown and writes markdown back through adf-codec. It writes with the version number it read; where Confluence reports a newer version, the loop asks the human, and never overwrites a teammate's edit on its own. Auth: email plus API token from the project's env file. The page is one more `RecordStore` in `bin/record_store/stores.py`, held to `contract.py`. `store` picks it by the setting's value. `project-config` and `chunk-preflight` print each record's setting as a path, so make both print a page's setting as it is written. `write` takes only the text, so the store itself keeps the version it read.
### 356. Hand reviewers the review standards from the folder a project's config names, in place of `~/.claude/skills/larv-review/standards/`.
lilleman's call, 2026-11-12: the folder replaces the default, as item 347's principles folder does. Readers: the reviewers under `agents/`, the judge's records, larv-review, and the repo check that keeps the standards present.
### 372. Key loop-claude's session, archive, routing state and config-folder commits per chunk, so two chunks of one project run side by side without touching each other's state.
lilleman's call, 2026-11-13, splitting item 361. Items 373 to 375 run several chunks of one project at once. Today a project has one session and one chunk at a time. This item makes two loop-claudes in one project, each on its own chunk, safe to run side by side. It doesn't yet start them; item 375 does that.
Key per chunk, not per project: the worker's session, which `session_named` names after the project, the archive keys and routing's state. Serialize item 345's commits to the config's folder, `~/.claude-projects/<key>/`, with a file lock, since two chunks may commit there at once. Leave `todo.md`'s and `CHANGELOG.md`'s edits to item 374, which moves them to merge time. A test runs two loops in one project and checks that neither reads or overwrites the other's state.
`bin/loop_claude/cycle/run.py:154` `rule` and `run.py:94` `archived` are places the comprehension seats found hard: the archive helpers sit in the cycle runner, and `rule` archives twice in an order only the code states. Make them easier to read where the archive keys change.
### 374. Merge open chunks one at a time: rebase, finish the item in todo.md and CHANGELOG.md, rerun the gate and the paired ruling, and keep a chunk waiting for approval in the queue without blocking the next.
lilleman's call, 2026-11-13, splitting item 361, which also asked that a chunk keep waiting for a human approval while others run. With several chunks open, `chunk-pr merge` merges one pull request at a time. For each it rebases the branch onto the default branch, then writes the item's `todo-item finish` and its changelog bullet, then reruns the gate, then merges. Moving those edits to merge time keeps `todo.md` and `CHANGELOG.md` out of every chunk's conflicts.
@@ -114,10 +85,46 @@ Where the rebase conflicts, the chunk's worker resolves it, and only the review
`bin/chunk_preflight/choices.py:80` `forge_of` is a place the comprehension seats found hard: forge code split across tools. Where this item touches it, build on item 287's forge module if that has shipped.
### 386. Key project-record's copies per worktree, so two chunks of one project editing the same record kept outside a file don't overwrite each other's unsaved edit.
Found in item 372's chunk. `project-record open` writes a record kept on a Confluence page to a copy under `~/.local/state/project-record/<key>/`, keyed by the project alone (`bin/project_record/main.py`, `COPIES`). Two chunks of one project, running side by side as item 375 will run them, share that copy: the second `open` rewrites it, and the first chunk's unsaved edit is lost. Key the copy by the worktree as well as the project.
Touches:
- `bin/project_record/main.py`: `(module)` (small)
- `bin/project_record/test_project_record.py`
### 359. Tie a project's releases to what its config names: semver tags, Jira Fix Versions, sprints, or none.
lilleman's call, 2026-11-12: what a release is differs per client. With none, items name no release, and the architecture and principles passes the release review runs need another trigger, which this item settles and records. Readers: `rank_todo.py`'s release order, chunk-preflight's next release, loop-claude's "release ready to cut", larv-review's release review, `CLAUDE.md` → "Working loop". Cutting a release stays the human's.
### 382. Edit a Jira issue the loop filed, and score an unscored issue a teammate filed with a comment saying why.
Split from item 352 on 2026-11-15; lilleman's calls, 2026-11-12. The loop edits the summary, description and scores of issues it created, which the `Filed by` mark in the `plan-item` property tells apart, and never the summary or description of an issue a person filed. An issue a teammate files without scores gets scored like any item, with a short comment saying it was scored and why; its scope stays as written. The comment reaches the client's team, so it is in the project's `language`, and its reason comes from whoever scores: `PlanStore.edit` and `todo-item edit` gain a way to pass it, whose spelling a bench of readers picks. Say in `docs/decisions.md` whether the loop may re-score or move a person's issue that already holds scores; the calls name neither.
Touches:
- `bin/plan_store/jira_epic.py`: `JiraPlan.edit`
- `bin/plan_store/test_jira_epic.py`: new tests of `edit`
- `bin/plan_store/stores.py`: `PlanStore.edit`, `FilePlan.edit`
- `bin/todo_item/main.py`: the help, `edit`'s flags
### 384. Rank an issue the loop files in Jira by its score among the issues the loop filed, a security finding first.
Split from item 352 on 2026-11-15; lilleman's call, 2026-11-12: an issue the loop files goes into Jira rank by its score among the issues the loop filed, and a security finding ranks first. The team's own rank of every other issue stays as it is.
lilleman's answer, 2026-11-15: a plan in Jira states its score formula and its bar as two settings in the project's `config.toml`. They hold what a `todo.md` states under `## Scoring`: a formula such as `100 * V / (2**S + 8)`, and a bar such as `1`. A bench of readers, seated as the person who writes a client's `config.toml`, picks the two settings' spelling. A config that names an epic as its plan and leaves them out fails to load, saying which to add, since no path setting has a default either.
With the two settings, `JiraPlan.add` scores the new item as `bin/release_plan/ranking.py` scores a row of `todo.md`: it reads the goals file, the decision log and the comprehension history for the weights. It refuses an item under the bar that isn't exempt, and checks that Moves names goals the goals file holds. Then it asks Jira to rank the new issue just before the first issue the loop filed that scores lower. A security finding goes before the first issue the loop filed that isn't one.
Touches:
- `bin/plan_store/jira_epic.py`: `JiraPlan`, `JiraPlan.add`, `Issue`, and a new function that places the issue
- `bin/plan_store/stores.py`: `store`
- `bin/plan_store/test_jira_epic.py`: new tests of the bar and the rank
- `bin/project_config/main.py`: the help
- `bin/project_config/settings.py`: `OPTIONAL`, `ProjectConfig`, `load`
- `bin/release_plan/ranking.py`: `read_scoring`, so a formula and a bar from the config score an item
- `bin/todo_item/main.py`: the help's lines on `add` in a Jira epic
- `docs/decisions.md`: "project config: `plan` may name a Jira Cloud epic …"
### 375. Run up to the project's configured number of chunks at once, each in its own window of one tmux session named for the project, mark a window whose chunk waits for the human, and refuse to start without tmux at the needed version.
lilleman's call, 2026-11-13, splitting item 361. lilleman knows tmux and prefers it. loop-claude runs each chunk in its own window of one tmux session named for the project, such as session `loop-claude-config` with windows `item-372` and `item-373`. It runs up to the number of chunks the project's config allows at once, with 1 as the default, and starts the next chunk item 373's pass allows as each one merges. It uses tmux even at 1, so every project runs the same workflow (goal 1.3). Each window holds a loop-claude for its one chunk, so the interrupt and `/talk` work there as on any terminal. When a chunk waits for the human, loop-claude marks its window, renaming it to end in ` ?` and ringing the bell so tmux's status bar shows it, and clears the mark once it is answered. The DM each interrupt sends names the session and window to answer in, such as `loop-claude-config:item-372`, so the human goes straight to it.
@@ -191,6 +198,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.