Compare commits

...

45 Commits

Author SHA1 Message Date
lilleman f648f4235a Sort the floor's imports where the default left them
CI / tests (pull_request) Successful in 2m0s
2026-11-14 22:15:34 +01:00
lilleman 0a664ae889 Answer prose round 1: 0 🔴, 7 🟡 (0 misread); untangle the floor's help, comments and changelog, and list what tooling-on-host covers one way 2026-11-14 22:12:07 +01:00
lilleman 6862420b51 Answer product-owner round 1: 0 🔴, 0 🟡 (0 misread); say the floor may be set either way, and ask for a bare number 2026-11-14 22:12:07 +01:00
lilleman ea0910d60d Answer stability round 1: 0 🔴, 2 🟡 (0 misread); test the config's floor in record-scoring's Floor and Next lines, make ranking ask for the floor, fail a huge integer floor by name 2026-11-14 22:12:07 +01:00
lilleman 68f867e74b Test that the plan store ranks every write with the config's floor 2026-11-14 21:57:06 +01:00
lilleman f8958fbfe0 Test that ranking reads the floor the config sets, and name the project's floor throughout the Floor item 2026-11-14 21:50:00 +01:00
lilleman 9dba8e97be Answer security round 1: 0 🔴, 0 🟡 (0 misread); no findings 2026-11-14 21:44:45 +01:00
lilleman c97e4ad21b Let a project's config allow its tooling on the host and set its readability floor
CI / tests (pull_request) Successful in 3m3s
2026-11-14 21:43:51 +01:00
lilleman fc5e78ba88 Finish item 353: take a project's goals and audience from a Jira epic's description
CI / tests (pull_request) Successful in 2m8s
2026-11-14 21:30:36 +01:00
lilleman 5c05520f1d Name the goals file among what project-record opens in the README 2026-11-14 21:27:37 +01:00
lilleman 68808e7eee Answer prose round 1: 0 🔴, 8 🟡 (0 misread); reword the README paragraph, help, docstrings and messages 2026-11-14 21:27:23 +01:00
lilleman b514dcfe85 Answer product-owner round 1: 0 🔴, 2 🟡 (1 misread); open the goals file with project-record, and say in the help where it prints 2026-11-14 21:27:23 +01:00
lilleman 3a2d72a007 Answer stability round 1: 0 🔴, 4 🟡 (0 misread); keep goals in Jira to projects whose plan is there, test the reviewer header's Jira read, drop the repeated premises tests 2026-11-14 21:27:23 +01:00
lilleman e38e45579f Answer security round 1: 0 🔴, 0 🟡 (0 misread) 2026-11-14 21:09:49 +01:00
lilleman 0d16290e38 Test each message read_premises fails with 2026-11-14 21:08:44 +01:00
lilleman 55967b5fa6 Take a project's goals and audience from a Jira epic's description where its config names one
CI / tests (pull_request) Successful in 2m1s
2026-11-14 21:01:50 +01:00
lilleman 8363514fe9 Record the reading cost before item 353's first commit 2026-11-14 21:01:47 +01:00
lilleman 415d1dc704 Re-score item 353 at L 3 and S 5, since it reaches six components 2026-11-14 20:47:02 +01:00
lilleman c99c53202d Answer product-owner round 1: 0 🔴, 0 🟡 (0 misread)
CI / tests (pull_request) Successful in 2m56s
2026-11-14 20:40:07 +01:00
lilleman 22265462e0 Answer prose round 1: 0 🔴, 2 🟡 (0 misread); reword the Jira template paragraph, README sentence and changelog bullet 2026-11-14 20:40:07 +01:00
lilleman 20f8ba29da Answer stability round 1: 0 🔴, 1 🟡 (0 misread); delete the test that repeats the PAY-{id} cases 2026-11-14 20:40:07 +01:00
lilleman 2b4c8b4cab Finish item 378: name a Jira plan's chunks by the issue key through the branch and title templates
CI / tests (pull_request) Successful in 2m7s
2026-11-14 20:37:30 +01:00
lilleman 93bad95bfd Name the machine's heavy slots in item 379's changelog bullet
CI / tests (pull_request) Successful in 2m56s
2026-11-14 20:28:51 +01:00
lilleman c4499f3db0 Finish item 379: one adf-codec run per plan read, and a heavy slot around its image build
CI / tests (pull_request) Successful in 2m4s
2026-11-14 20:28:46 +01:00
lilleman 4d5abf3bd1 Answer prose round 1: 0 🔴, 4 🟡 (0 misread); reword HELD, Refused, heavy_slot, ensure_image and the past-the-documents refusal
CI / tests (pull_request) Successful in 2m4s
2026-11-14 20:26:59 +01:00
lilleman d443cf1ee3 Answer product-owner round 1: 0 🔴, 0 🟡 (0 misread); name the codec's heavy slot in README and the slot folder and fuser hint in its wait line 2026-11-14 20:26:59 +01:00
lilleman 53a754a1d7 Answer stability round 1: 0 🔴, 2 🟡 (0 misread); parametrize the looped tests, split the heavy-slot test and close its slot file on failure 2026-11-14 20:26:59 +01:00
lilleman 62c67af820 Answer security round 1: 0 🔴, 0 🟡 (0 misread); no finding 2026-11-14 20:11:56 +01:00
lilleman 9b1a45a993 Convert every description of a plan read in one adf-codec container run, and take a heavy slot around the build of the codec's image
CI / tests (pull_request) Successful in 2m57s
2026-11-14 20:11:11 +01:00
lilleman 9b145d488f Record the reading cost before item 379 2026-11-14 20:11:11 +01:00
lilleman ed67d052aa File item 380: define the plan in Vocabulary whatever holds it
CI / tests (pull_request) Successful in 2m0s
2026-11-14 20:03:43 +01:00
lilleman c51c246c36 Finish item 351: a plan read from a Jira Cloud epic
CI / tests (pull_request) Successful in 2m2s
2026-11-14 19:59:23 +01:00
lilleman 3931eef451 Test a refused connection's reason, an indented comment and a value between letters 2026-11-14 19:59:07 +01:00
lilleman 8e6b2f1f12 Answer product-owner round 2: 0 🔴, 0 🟡 (0 misread); every answer holds 2026-11-14 19:50:47 +01:00
lilleman 98c28cc244 Answer stability round 2: 0 🔴, 1 🟡 (0 misread); run two looped tests under subTest, refuse a blocker that is no issue key, and test the page cap, the four conversions at once and the search's failure messages 2026-11-14 19:50:47 +01:00
lilleman 4e0e7e655d Answer architecture round 1: 0 🔴, 2 🟡 (0 misread); file item 379 for one container per plan read and a heavy slot around the codec's build 2026-11-14 19:44:51 +01:00
lilleman 0f142f8da5 Answer prose round 1: 0 🔴, 7 🟡 (0 misread); reword the help text and comments, and sort the decision 2026-11-14 19:40:36 +01:00
lilleman 9ac89c3d50 Answer product-owner round 1: 1 🔴, 2 🟡 (1 misread); list an unscored joining item, and pass rank_todo.py --check for a plan in Jira 2026-11-14 19:40:36 +01:00
lilleman 8ee67ed2b7 Answer stability round 1: 0 🔴, 10 🟡 (0 misread); share one REST client and env-file reader, read each issue into a checked value, convert descriptions last, and simplify the hard places the change touched 2026-11-14 19:40:36 +01:00
lilleman d008dc09f2 Sort the Jira store's imports 2026-11-14 19:26:04 +01:00
lilleman 728c7b004a Test the search's whole body, an issue without properties and a v-named earliest version 2026-11-14 19:18:02 +01:00
lilleman 543d85238a Answer security round 1: 0 🔴, 0 🟡 (0 misread); the review found nothing 2026-11-14 19:14:12 +01:00
lilleman 59d972cc82 Read a plan from the child issues of a Jira Cloud epic
CI / tests (pull_request) Failing after 2m6s
2026-11-14 19:12:25 +01:00
lilleman c19f097ecd Split items 377 and 378 out of item 351 2026-11-14 19:01:08 +01:00
lilleman 520e0e9aa5 Re-score item 351 at L 4 and S 6, and keep item IDs as ints for a Jira plan 2026-11-14 17:05:57 +01:00
66 changed files with 1903 additions and 415 deletions
+2
View File
@@ -96,6 +96,8 @@
!bin/release_plan/*.py
!bin/repo_checks/
!bin/repo_checks/*.py
!bin/rest_client/
!bin/rest_client/*.py
!bin/review-replay
!bin/review_replay/
!bin/review_replay/*.py
+6
View File
@@ -2,6 +2,12 @@
## Unreleased
- A project's config may set `tooling-on-host = true`, so the loop runs a legacy project's language runtime, package manager, tests and task runner directly on the host.
- A project's config may set `readability-floor` to a number from 1 to 10: the comprehension score under which code health is very important. It is 7.0 where left out.
- A project whose plan is a Jira epic can keep its goals and audience in an epic's description too: set `goals-and-audience = "jira:https://<site>/browse/<KEY>"`. The loop only reads it, and `project-record open goals-and-audience` prints a file holding its text.
- A project with a Jira plan can name each chunk's branch, worktree, commits and pull request by the issue key, as in `ABC-123` and `ABC-123 - …`. The README shows the three templates to set.
- A read of a plan in a Jira epic converts every issue description in one `adf_codec` container run, however many issues the epic holds. The codec builds its image inside one of the machine's heavy slots that `run-heavy` shares, so sessions reading at once build it once.
- A project config may name its plan as `jira:https://<site>/browse/<KEY>`: the plan is then read from the open child issues of that Jira Cloud epic, in backlog order, with the credentials in the config's `env-file`. Such a plan is only read so far: file, edit and finish its issues in Jira.
- A new `adf_codec` package converts markdown to ADF, the rich text of Jira Cloud and Confluence, and back with `@larvit/adf-codec` 0.3.1. It runs in a pinned Node container with a memory limit and no network, and returns adf-codec's error codes as a `Failure`. No tool calls it yet.
- The new `todo-item list [--release <version>]` prints the plan's items in the plan's order, `todo-item edit <ID>` sets an item's cells or detail, and `todo-item move <ID> --release <version>` moves it to another release; each change ranks the plan. Agents now read and change the plan's items only with `todo-item`, and the tools read the plan as it stands through one store, `bin/plan_store`, so a later backend can keep a plan outside `todo.md`. `todo-item list --release` with a bad version exits 2, and `finish <ID> --no-changelog` also drops an item no chunk built.
- A project's config may name the language its prose is written in (`language`) and templates for its commit titles, pull request titles and branch names (`commit-title`, `pull-request-title`, `branch`), in which `{id}` stands for the plan item's ID and `{summary}` for the one-line summary. The tools and the prose reviewer follow them. On a branch that fits the `branch` template, rule-hook's new `commit-title` rule refuses a commit title that doesn't fit, and `chunk-pr` such a pull request title. While a project's config holds a fault, rule-hook refuses every commit there.
+3 -3
View File
@@ -27,7 +27,7 @@ How work proceeds in any repo, unless the repo's `AGENTS.md` says otherwise. The
Every project pursues the achieve goal below, ranked above every achieve goal its goals file states. A project whose code nobody will maintain voids it with one line under `## Goals`, before the numbered goals: `**Void:** code health, since <reason>.` So does a project that opts out of the comprehension check, since the goal then has no signal. An item's Moves cell names it as in `code health by 6`, and `rank_todo.py --help` says how much it weighs.
**Achieve:** Code health: the code stays easy to read, change safely and debug, tomorrow and after seven years of development.
- Signal: the comprehension panel's overall score rises, always. Under 7.0 it is very important.
- Signal: the comprehension panel's overall score rises, always. Under the project's readability floor it is very important. The floor is 7.0, unless the project's config sets `readability-floor`.
- Counter-signal: defects keep reappearing in functionality that already shipped, or reviewers raise blockers because the implementer misunderstood the current system.
- Why: a score that rises while changes still misread the code measures the wrong thing.
@@ -65,7 +65,7 @@ The rules only reviewers apply, for quality, comments, READMEs and prose, live i
## Working with the codebase
- Always start a new git worktree when doing something in a codebase, and clean it up when done. Unless told otherwise, branch it off a freshly-updated default branch (`git fetch origin`, then base on `origin/main`), not whatever happens to be checked out.
- Keep the project's main checkout (e.g. `~/code/log`, never a worktree) current: when it is behind `origin` — a merge landed, or a fetch shows it — run `git pull --ff-only` there instead of reporting the lag, never with `--autostash`: a dirty checkout is a finding to report, not to carry along.
- Run a project's language runtime, package manager, and task runner through its container/tooling setup, never directly on the host unless a decision puts them there. Example: `docker compose run --rm app <tool> …`.
- Run a project's language runtime, package manager, and task runner through its container/tooling setup, never directly on the host, unless the project's config sets `tooling-on-host = true` or a decision puts them there. Example: `docker compose run --rm app <tool> …`.
- Tear down test containers after a run.
- Give every container you start a memory limit and a swap limit, as large as its work needs: `--memory 4g --memory-swap 4g` on `docker run`, or `mem_limit` and `memswap_limit` in a compose file, scripts included. rule-hook checks only the `docker run` and `docker create` in your Bash commands.
- A heavy command loads the machine for minutes: a full gate, mutation tests, an e2e run, a `docker build`. Run each one under `~/.claude/bin/run-heavy`, as in `~/.claude/bin/run-heavy ./ci.sh`. run-heavy waits for one of the heavy slots that every session on the machine shares. It also caps each container the command makes at the slot's share of memory, where the container sets no limits; give a container that needs more its own. Run the command in the background, since run-heavy's wait can outlast the Bash tool's timeout; `~/.claude/bin/wait-for <file> [<pattern>]` waits for a line in a log the command writes.
@@ -127,7 +127,7 @@ Claude Code reads this section by its heading when it compacts a conversation. K
- **chunk** — the unit of work, shipped as one PR; "Working loop" says what it holds.
- **cycle** — in `loop-claude`, worker runs and the judge's verdict on each, until the chunk closes or is left for the next cycle. In between, the human answers any interrupt, or the worker resumes with an answer the judge quoted from the premises or the judge's records.
- **gate** — the merge gate: the checks a PR passes before it merges.
- **goals file** — the file holding a project's `## Goals` and `## Audience`: the one its config names as `goals-and-audience`, which `~/.claude/bin/project-config goals-and-audience` prints. It is `README.md`, unless a client's project keeps it in the config's folder.
- **goals file** — the file holding a project's `## Goals` and `## Audience`: the one its config names as `goals-and-audience`. Read it in the file `~/.claude/bin/project-record open goals-and-audience` prints. It is `README.md`, unless a client's project keeps it in the config's folder, or in a Jira epic's description, which the loop only reads.
- **interrupt** — `loop-claude` asking the human, on its terminal, for a decision that is theirs. They type a one-line answer there, or `/talk` to open the worker's session there with `claude --resume`. A release ready to cut opens that session at once. A routing call opens claude on that terminal too, in `~/code/claude-config`, the checkout where this setup is developed.
- **judge** — the headless claude that reads a worker's transcript each cycle and decides whether to interrupt and whether the chunk is finished.
- **judge's records** — the files the judge reads beside the premises: the project's `AGENTS.md` and `docs/decisions.md`, then the human's `~/.claude/CLAUDE.md` and the `.md` files in `~/.claude/rules/` and `~/.claude/skills/larv-review/standards/`.
+22 -4
View File
@@ -98,10 +98,27 @@ A project may also set `env-file`, the file of `KEY=value` credentials its tools
A project's config may set four more things, each optional, as `project-config --help` describes. `language` names the language its owners write in, where that isn't English: the worker writes the project's prose in it, and the prose reviewer judges the prose in it. `commit-title`, `pull-request-title` and `branch` are templates for a project that titles and names these in another way than `CLAUDE.md` → "Git, commits, and PRs" says. `chunk-preflight` names the branch and the worktree by the `branch` template. On a branch that fits it, rule-hook refuses a commit, and `chunk-pr` a pull request, whose title doesn't fit its template; on any other branch, such as a release review's, a title is the summary alone. A tool that reads a commit title, such as a round's `Answer <pass> round <n>:`, reads the template's `{summary}`: it tries `commit-title`, then `pull-request-title`, since a squash merge titles the commit as the pull request, then takes the title whole. While a project's config holds a fault, rule-hook refuses every commit there, and the tools that read its titles fail naming the fault.
A legacy project with no container setup sets `tooling-on-host = true`, so the loop runs its language runtime, package manager, tests and task runner directly on the host. One whose code the comprehension panel scores low may lower `readability-floor` from 7.0: under it, the ranking weighs code health 4 times as much, and a scoring run asks for a floor item.
A project whose pull requests need a human's approval sets `wait-for-approval = true` in its config. `chunk-pr merge` then waits, once the checks have passed, until GitHub reports the pull request approved as its branch protection requires, and merges it. It refuses on Gitea, where a reviewer requested changes and where the protection requires no review. It gives up after 90 minutes without an approval; run it again once the pull request is approved. Left out, the setting is false.
For a client's project, use one sandbox VM per client, so that one client's code, transcripts and credentials never share a machine with another's. What the client's repo should not hold lives in the config's folder, at paths written as `folder:<path>`, as `project-config --help` shows: the plan, the working rules in an `AGENTS.md` I write for the agents, the records, and the goals and audience, as `goals-and-audience = "folder:goals.md"`. Name that file `goals.md`, so the rules for goals and audience load when an agent writes it. A file outside the checkout has no commits in the checkout's history, so four things are not supported for it yet. `score-outcomes` and loop-claude's routing figures count a project's chunks only where `todo.md`, `docs/comprehension-history.md` and `docs/reading-cost.md` are at those paths in the checkout; otherwise each says so, and the loop goes on. For a plan or a comprehension history outside the checkout, `larv-review` says it cannot tell whether a scoring run is owed, and for such a history it cannot find a paired ruling's base. For a plan outside the checkout, chunk-preflight and loop-claude don't see a release whose last item has shipped, and say that its release review and its cut are yours to call. And rule-hook checks a plan outside the checkout on every call, not only when it changed.
A client that plans in Jira Cloud names an epic as its project's plan: `plan = "jira:https://acme.atlassian.net/browse/ABC-12"`, which is `jira:` and the epic's address as the browser shows it. The plan is then the epic's open child issues, in Jira's backlog order, which the team sets. An issue in a done status is a finished item. Each part of an item comes from one part of its issue:
- The ID is the issue's number, so every child must be in the epic's own Jira project.
- The tagline is the summary.
- The detail is the description, which a docker container converts to markdown.
- The release is the earliest Fix Version named as a semver version, such as `1.2.0`. Every open child needs one.
- 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 client that keeps its goals and audience in an epic's description names that epic as the goals file: `goals-and-audience = "jira:https://acme.atlassian.net/browse/ABC-12"`, which may be the plan's own epic. Such a config keeps its plan in Jira too, and reads both with the same `env-file`. The description needs `## Goals` and `## Audience` as headings, level-2 headings in Jira's editor. The loop only reads the description, so edit it in Jira; `project-record open goals-and-audience` prints a file holding its text. Whoever may edit that description sets the premises every worker and judge follows, so keep its edit rights to the people who own the project's goals.
To name a chunk's branch, worktree, commits and pull request by the issue key, as in `ABC-123` and `ABC-123 - …`, set these three templates, with your Jira project's key in place of `ABC`: `branch = "ABC-{id}"`, `commit-title = "ABC-{id} - {summary}"` and `pull-request-title = "ABC-{id} - {summary}"`. `project-config --help` says how the templates work.
```sh
mkdir -p ~/.claude-projects/acme && cd ~/.claude-projects/acme
git init
@@ -149,7 +166,7 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a
- `metric-bench [history]` benches cheap static metrics of a project's Python against the places its comprehension history names as hardest; `metric-bench --help` states the metrics and the scores.
- `mutate-changes [--base <ref>] [--prefix <shell text>] [--jobs <n>]` mutation-tests the lines a branch changes and prints each mutant its tests don't kill; `mutate-changes --help` says which tool it runs for each language.
- `project-config [<setting>]` prints the paths a project's config sets, or the one asked for, and fails naming each setting the config leaves out; Install → "Set up a project" shows a config.
- `project-record open <record>` prints the path of a file holding one of a project's records, for an agent to read and edit, and `project-record save <record>` stores the edit; for a record kept as a file, that file is the record.
- `project-record open <record>` prints the path of a file holding one of a project's records, for an agent to read and edit, and `project-record save <record>` stores the edit; for a record kept as a file, that file is the record. `goals-and-audience` opens the goals file the same way.
- `rank_todo.py [--check] [todo.md]` scores and ranks a project's `todo.md`, by default the one its config names; `rank_todo.py --help` states the format.
- `reading-cost [--reset] [record]` appends a figure for each chunk `loop-claude` finished to a project's `docs/reading-cost.md`, and says whether the figures rise; `reading-cost --help` states the measure.
- `review-replay <pass> <model>` replays a review pass's archived rounds from the projects run on the model, on the code each reviewed, and prints the lowest rung below the project's that, like each rung above it, qualifies: it finds no less of the 🔴 and 🟡 findings than two replays on the project's rung find, within a margin, and misses no 🔴 that both found. `review-replay --help` states the replay. With `--omit-claude-md` it tests instead whether the pass's reviewer may start without `CLAUDE.md`: it replays each round three times as archived and once without the instruction files, and prints whether the reviewer passes: whether the last replay missed no more findings than the most an unchanged replay missed, with each count and each finding it missed. Each replayed reviewer skips every permission prompt, stability-reviewer has Bash, and an archived prompt may name paths on the host.
@@ -165,7 +182,7 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a
`bin/` is the import root: each launcher puts it on `sys.path`, so a module imports another by its path under `bin/`, such as `from claude_code.entries import parse_entry`. Each tool's package holds its tests. Beside the packages, `bin/`'s root holds only the launchers, the tools of one file with their tests, `test_env.py`, `failure.py` and `setup.cfg`. `failure.py`'s `Failure`, which modules across `bin/` return for a failed step, belongs to no single package. `branch_chunks/`, `claude_code/`, `command_lines/`, `git_cli/`, `loop_effects/`, `loop_state/`, `machine_load/`, `mattermost_dm/`, `model_routing/`, `plan_store/`, `record_store/`, `release_plan/`, `review_rules/`, `rung_replay/`, `text_files/` and `transcript_archive/` serve more than one tool.
- `adf_codec/` converts markdown to ADF, the rich text of Jira Cloud and Confluence, and back, in a throwaway container running a pinned `@larvit/adf-codec`.
- `adf_codec/` converts markdown to ADF, the rich text of Jira Cloud and Confluence, and back, in a throwaway container running a pinned `@larvit/adf-codec`. It builds the container's image inside a heavy slot.
- `branch_chunks/` cuts a default branch into chunks and finds, for each, the items it shipped and the later chunks that fixed its code, for `score_outcomes` and `routing_figures`. It imports `reading_cost`'s record path.
- `command_lines/` reads a shell command: its simple commands, and a docker call's subcommand and memory limits, for `command_patterns`, `reading_cost`, `routing_figures`, `rule_hook` and `run_heavy`.
- `chunk_pr` imports `deploy_release`'s forge calls, and `forge_of` as `deploy_release` does.
@@ -175,14 +192,15 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a
- `loop_claude` runs `chunk-preflight` as a process of its own.
- `loop_effects/` holds `Effects`: the processes, terminal, clock and git a tool reaches, injected so its tests can script them. loop-claude, both replay tools and `reviewer-merge-trials`' driver use it.
- `loop_state/` holds where loop-claude keeps its files (`paths.py`), which `rung_replay` reads too.
- `machine_load/` takes the machine's heavy slots, its shared lock files, for `run_heavy`, and reads the memory share that loop-claude waits for. It also gives `mutate_changes` a slot's CPU count.
- `machine_load/` takes the machine's heavy slots, its shared lock files, for `run_heavy` and `adf_codec`, and reads the memory share that loop-claude waits for. It also gives `mutate_changes` a slot's CPU count.
- `mattermost_dm/` sends the human a Mattermost DM, for `mattermost-dm` and for loop-claude through `loop_effects`.
- `model_routing/` holds the routing ladder, which loop-claude, `rule_hook`, both replay tools and `subagent-rung` read, and the list prices, which `routing_figures` and `transcript_archive` read.
- `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 must pass, and `fakes.py` a plan in memory.
- `plan_store/` reads and writes a project's plan through the store the project's config names (`stores.py`), with the markdown file's edits in `markdown_edits.py`. `contract.py` holds the tests every backend that writes must pass, which `jira_epic.py` doesn't yet, and `fakes.py` a plan in memory.
- `rank_todo.py`, `settings_filter.py` and `statusline.py` are tools of one file each, tested beside them.
- `record_store/` reads and writes a project's records, each through the store the project's config names (`stores.py`). `contract.py` holds the tests every backend must pass, and `fakes.py` a store in memory that the tests of other tools use.
- `release_plan/` reads `todo.md`'s items table and release versions, says which release is next and whether it is ready to cut (`release_standing.py`), and ranks the plan (`ranking.py`, with its score formula in `formula.py` and its blocker order in `blockers.py`). `goals_file.py` reads the goals file's sections, goals and goal weights, for the ranking and for `loop_claude`'s premises, and `citations.py` holds `todo.md` and `docs/decisions.md` to each other. `plan_file.py` ranks, checks and writes a `todo.md`, for `larv_review`, `rank_todo.py` and `rule_hook`.
- `repo_checks/` tests the repo itself.
- `rest_client/` sends a JSON request to a REST API and reads its credentials from an env file, for `mattermost_dm` and `plan_store`.
- `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.
+1 -1
View File
@@ -13,7 +13,7 @@ You are an elite stability-focused code reviewer with deep expertise in defensiv
1. **Scope the change.** You review every PR; a fresh invocation has no prior context, so determine the diff yourself. Diff the PR branch against its base (`gh pr diff`, or `git merge-base <base> HEAD` then `git diff`), and review the changed lines **plus enough surrounding code and callers** to judge correctness — read the whole changed file when practical; a diff alone hides whether a caller breaks. Read the PR description and, when the project uses an issue tracker (project-specific — check its docs) and the change references a ticket, that ticket: the diff is judged against its stated intent, and a scope mismatch in either direction is a finding — claimed-but-unimplemented, and implemented-but-unasked (#2).
2. **Read every file in the folder your prompt's `Technical principles:` line names**, and `~/.claude/skills/larv-review/standards/quality.md`. These are mandatory guidelines; all code MUST comply with each that applies. A file's `Applies to` line says what it covers; one without the line covers every change. Re-read each time — they change. Flag violations prominently. Where your prompt has no such line, without one, open your report by saying so.
3. **Read README.md, AGENTS.md and `docs/decisions.md`** in the current project for project-specific conventions, build instructions, tooling, and the accepted trade-offs a reviewer should honor rather than re-flag. Note the documented test, lint, and static-analysis commands — you run them unless your prompt hands you a passing run on the head (step 4).
4. **Verify, don't just read.** Where your prompt hands you the commit on which the worker's run of the test suite and static analysis last passed, and it is the head, don't run them again, and say so in Coverage & Verification. Otherwise run the test suite and static analysis/linters through the project's container tooling, unless a decision puts them on the host; tear down test containers afterwards. Run the full suite under `~/.claude/bin/run-heavy`. Run it in the background or with the Bash tool's longest timeout: that timeout includes the wait for a slot. A full-suite run catches broken callers that diff-reading misses. When a suspected bug is cheap to confirm, reproduce it — a scratch script, a targeted test run — before reporting it. Make scratch work with Bash, since Write is for your report alone. Put it in a directory you create for this run, and delete it when done; don't delete anything else, since a directory the prompt names may hold other agents' files. Leave the working tree exactly as you found it. Anything you could not run goes in Coverage & Verification, never silently skipped.
4. **Verify, don't just read.** Where your prompt hands you the commit on which the worker's run of the test suite and static analysis last passed, and it is the head, don't run them again, and say so in Coverage & Verification. Otherwise run the test suite and static analysis/linters through the project's container tooling, unless `~/.claude/bin/project-config tooling-on-host` prints true or a decision puts them on the host; tear down test containers afterwards. Run the full suite under `~/.claude/bin/run-heavy`. Run it in the background or with the Bash tool's longest timeout: that timeout includes the wait for a slot. A full-suite run catches broken callers that diff-reading misses. When a suspected bug is cheap to confirm, reproduce it — a scratch script, a targeted test run — before reporting it. Make scratch work with Bash, since Write is for your report alone. Put it in a directory you create for this run, and delete it when done; don't delete anything else, since a directory the prompt names may hold other agents' files. Leave the working tree exactly as you found it. Anything you could not run goes in Coverage & Verification, never silently skipped.
5. **Judge the surviving mutants.** Your prompt hands you what the project's mutation command printed on the change, with the commit it ran on: the mutants of changed lines that no test kills, or the message of a run that failed. Ignore a surviving mutant that leaves behaviour unchanged, or changes only message or log text no caller or user depends on. Report one 🟡 per test to add or strengthen, naming the surviving mutants it would catch. Where the prompt doesn't hand you any output, or names a commit other than the head, run the command yourself in the change's checkout, through run-heavy as in step 4: the one the project's README documents, else `~/.claude/bin/run-heavy ~/.claude/bin/mutate-changes --prefix '<how the project runs its tools>'`. `~/.claude/bin/mutate-changes --help` says which tool it runs for each language, how to set `--jobs`, and what it prints. Mutation-test the changed code that no run mutated, in a language mutate-changes doesn't cover or where a run failed, with a widely deployed mutation tool limited to the changed lines, else with mutants you make by hand. Report the wall time and mutant count in Coverage & Verification, or why nothing was mutated.
6. **Two passes minimum, then hunt absences.**
- *Breadth:* every hunk in every changed file, no skimming. Track which files you have covered; batch large diffs, never truncate the review.
+91 -16
View File
@@ -2,14 +2,18 @@
It runs @larvit/adf-codec, a Node package, in a throwaway container that holds node_shim/shim.mjs; the shim's header says what its exit status means.
"""
import contextlib
import dataclasses
import hashlib
import json
import os
import pathlib
import subprocess
import sys
import typing
from failure import Failure
from machine_load.slots import HELD, slot_count, slot_folder, usable_cpus, waited_slot
SHIM = pathlib.Path(__file__).resolve().parent / "node_shim"
SHIM_FILES = ("Dockerfile", "package.json", "package-lock.json", "shim.mjs")
@@ -31,6 +35,15 @@ class Ran:
Run = typing.Callable[[str, str], Ran | Failure]
# Runs a docker command line on a text, in at most the given seconds, or fails to run it.
Docker = typing.Callable[[list[str], str, int], Ran | Failure]
# Holds one of the machine's heavy slots for a with block, or yields why none could be taken.
Slot = typing.Callable[[], typing.ContextManager[Failure | None]]
@dataclasses.dataclass(frozen=True)
class Refused:
"""Why adf-codec refused one of the documents handed to adfs_to_markdown, and that document's index among them."""
index: int
failure: Failure
def image_tag(shim: pathlib.Path) -> str:
@@ -55,17 +68,54 @@ def docker(args: list[str], text: str, seconds: int, call: typing.Callable[...,
return Ran(done.returncode, done.stdout, done.stderr)
def ensure_image(shim: pathlib.Path, run_docker: Docker = docker) -> str | Failure:
"""The tag of the image for the shim folder, built from that folder first where this machine has no image under that tag."""
@contextlib.contextmanager
def heavy_slot(env: typing.Mapping[str, str] = os.environ, slots: int | None = None) -> typing.Iterator[Failure | None]:
"""Holds one of the machine's heavy slots, which run-heavy shares, for the with block. Under run-heavy the process already holds one, so it doesn't wait."""
if HELD in env:
yield None
return
folder = slot_folder(env, pathlib.Path.home())
count = slot_count(usable_cpus()) if slots is None else slots
try:
folder.mkdir(parents=True, exist_ok=True)
_, fd = waited_slot(folder, count, lambda: print(f"adf-codec: waiting for a heavy slot, of {count} on this machine, in {folder}, to build the shim's image; `fuser {folder}/slot-*` names the processes that hold them", file=sys.stderr, flush=True))
except OSError as failure:
yield Failure(f"cannot take a heavy slot in {folder}: {failure.strerror}")
return
try:
yield None
finally:
os.close(fd)
def ensure_image(shim: pathlib.Path, run_docker: Docker = docker, slot: Slot = heavy_slot) -> str | Failure:
"""The tag of the image for the shim folder, built from that folder first where this machine has no image under that tag.
The build waits for a heavy slot. Once this process holds the slot, it inspects again, as another process may have built the image meanwhile."""
tag = image_tag(shim)
found = image_found(tag, run_docker)
if found is not False:
return tag if found is True else found
with slot() as refused:
if refused is not None:
return refused
found = image_found(tag, run_docker)
if found is not False:
return tag if found is True else found
return build_image(shim, tag, run_docker)
def image_found(tag: str, run_docker: Docker) -> bool | Failure:
found = run_docker(["docker", "image", "inspect", tag], "", RUN_SECONDS)
if isinstance(found, Failure) or found.status == 0:
return found if isinstance(found, Failure) else tag
built = run_docker(["docker", "build", "--quiet", "--memory", "1g", "--memory-swap", "1g", "--tag", tag, str(shim)], "", BUILD_SECONDS)
if isinstance(built, Failure):
return built
if built.status != 0:
return Failure(f"building the adf-codec shim's image failed with exit {built.status}: {built.err.strip()}")
return found if isinstance(found, Failure) else found.status == 0
def build_image(shim: pathlib.Path, tag: str, run_docker: Docker) -> str | Failure:
ran = run_docker(["docker", "build", "--quiet", "--memory", "1g", "--memory-swap", "1g", "--tag", tag, str(shim)], "", BUILD_SECONDS)
if isinstance(ran, Failure):
return ran
if ran.status != 0:
return Failure(f"building the adf-codec shim's image failed with exit {ran.status}: {ran.err.strip()}")
return tag
@@ -76,8 +126,8 @@ def container_run(mode: str, text: str, run_docker: Docker = docker, shim: pathl
return run_docker(docker_args(image, mode), text, RUN_SECONDS)
def answer(mode: str, text: str, run: Run) -> str | Failure:
"""What the shim printed for text, or a Failure saying why it gave no answer."""
def answer(mode: str, text: str, run: Run) -> str | Refused | Failure:
"""What the shim printed for text, or why it gave no answer: a Refused where it named the refused document's index."""
ran = run(mode, text)
if isinstance(ran, Failure):
return ran
@@ -88,18 +138,22 @@ def answer(mode: str, text: str, run: Run) -> str | Failure:
return Failure(f"the adf-codec shim failed with exit {ran.status}: {ran.err.strip()}")
def refusal(out: str) -> Failure:
def refusal(out: str) -> Refused | Failure:
try:
error = json.loads(out)["error"]
refused = json.loads(out)
error = refused["error"]
where = f"line {error['position']['line']}" if "position" in error else ".".join(str(step) for step in error["path"]) or "the document"
return Failure(f"adf-codec refused the input with {error['code']}: {error['message']} (at {where})")
except (ValueError, KeyError, TypeError):
failure = Failure(f"adf-codec refused the input with {error['code']}: {error['message']} (at {where})")
return Refused(refused["index"], failure) if isinstance(refused.get("index"), int) else failure
except (ValueError, KeyError, TypeError, AttributeError):
return Failure(f"the adf-codec shim refused with output that is not an error: {out.strip()}")
def markdown_to_adf(markdown: str, run: Run = container_run) -> dict[str, typing.Any] | Failure:
"""The ADF document for the markdown."""
out = answer("to-adf", markdown, run)
if isinstance(out, Refused):
return out.failure
if isinstance(out, Failure):
return out
try:
@@ -109,6 +163,27 @@ def markdown_to_adf(markdown: str, run: Run = container_run) -> dict[str, typing
return document
def adfs_to_markdown(documents: list[dict[str, typing.Any]], run: Run = container_run) -> list[str] | Refused | Failure:
"""The markdown for each ADF document, in their order, from one container run, so a caller with many documents pays one container start."""
if not documents:
return []
out = answer("to-markdown", json.dumps(documents), run)
if isinstance(out, Refused) and not 0 <= out.index < len(documents):
return Failure(f"the adf-codec shim refused a document at index {out.index}, past the {len(documents)} it was handed")
if isinstance(out, Refused | Failure):
return out
try:
texts = json.loads(out)
except ValueError:
texts = None
if not isinstance(texts, list) or len(texts) != len(documents) or not all(isinstance(text, str) for text in texts):
return Failure(f"the adf-codec shim printed output that is not a JSON array of {len(documents)} texts: {out.strip()}")
return texts
def adf_to_markdown(document: dict[str, typing.Any], run: Run = container_run) -> str | Failure:
"""The markdown for the ADF document."""
return answer("to-markdown", json.dumps(document), run)
texts = adfs_to_markdown([document], run)
if isinstance(texts, Refused):
return texts.failure
return texts if isinstance(texts, Failure) else texts[0]
+25 -10
View File
@@ -1,7 +1,8 @@
// Converts between markdown and ADF with @larvit/adf-codec's portable calls. The mode is the one argument:
// to-adf stdin is markdown, stdout is the ADF document as JSON
// to-markdown stdin is an ADF document as JSON, stdout is markdown
// Exit 0: stdout holds the answer. Exit 2: adf-codec refused the input, and stdout holds {"error": {code, message, path, position?}}.
// to-markdown stdin is a JSON array of ADF documents, stdout a JSON array of their markdown texts, in their order
// Exit 0: stdout holds the answer. Exit 2: adf-codec refused the input, and stdout holds {"error": {code, message, path, position?}},
// with "index", the refused document's place in the array, beside "error" in to-markdown.
// Exit 1: the shim could not run, and stderr says why.
import { adfToPortableMarkdown, portableMarkdownToAdf } from '@larvit/adf-codec'
@@ -13,19 +14,33 @@ async function readStdin() {
return Buffer.concat(chunks).toString('utf8')
}
function finish(result, render) {
if (result.ok) {
process.stdout.write(render(result.value))
return 0
}
process.stdout.write(JSON.stringify({ error: result.error }))
function refuse(refusal) {
process.stdout.write(JSON.stringify(refusal))
return REFUSED
}
function toAdf(markdown) {
const result = portableMarkdownToAdf(markdown)
if (!result.ok) return refuse({ error: result.error })
process.stdout.write(JSON.stringify(result.value))
return 0
}
function toMarkdown(documents) {
const texts = []
for (const [index, document] of documents.entries()) {
const result = adfToPortableMarkdown(document)
if (!result.ok) return refuse({ index, error: result.error })
texts.push(result.value)
}
process.stdout.write(JSON.stringify(texts))
return 0
}
async function main(mode) {
const input = await readStdin()
if (mode === 'to-adf') return finish(portableMarkdownToAdf(input), (doc) => JSON.stringify(doc))
if (mode === 'to-markdown') return finish(adfToPortableMarkdown(JSON.parse(input)), (markdown) => markdown)
if (mode === 'to-adf') return toAdf(input)
if (mode === 'to-markdown') return toMarkdown(JSON.parse(input))
throw new Error(`mode must be to-adf or to-markdown, not ${mode}`)
}
+109 -14
View File
@@ -1,4 +1,6 @@
import contextlib
import json
import os
import shutil
import subprocess
@@ -6,6 +8,7 @@ import pytest
from adf_codec import convert
from failure import Failure
from machine_load import slots
DOC = {"type": "doc", "version": 1, "content": [{"type": "paragraph", "content": [{"type": "text", "text": "Hi"}]}]}
@@ -27,10 +30,40 @@ def test_markdown_to_adf_returns_the_document_the_shim_printed():
assert run.calls == [("to-adf", "Hi\n")]
def test_adf_to_markdown_sends_the_document_as_json_and_returns_the_text():
run = fake(0, "Hi\n")
def test_adfs_to_markdown_sends_every_document_in_one_run_and_returns_the_texts_in_order():
run = fake(0, json.dumps(["Hi\n", "Yo\n"]))
assert convert.adfs_to_markdown([DOC, DOC], run) == ["Hi\n", "Yo\n"]
assert run.calls == [("to-markdown", json.dumps([DOC, DOC]))]
def test_adfs_to_markdown_of_no_documents_runs_no_container():
run = fake(1)
assert convert.adfs_to_markdown([], run) == []
assert run.calls == []
def test_a_refused_document_names_its_index():
refusal = {"index": 1, "error": {"code": "not-an-adf-document", "message": "no type", "path": []}}
refused = convert.adfs_to_markdown([DOC, DOC], fake(2, json.dumps(refusal)))
assert refused == convert.Refused(1, Failure("adf-codec refused the input with not-an-adf-document: no type (at the document)"))
def test_a_refusal_whose_index_is_past_the_documents_becomes_a_failure():
refusal = {"index": 2, "error": {"code": "not-an-adf-document", "message": "no type", "path": []}}
failure = convert.adfs_to_markdown([DOC, DOC], fake(2, json.dumps(refusal)))
assert failure == Failure("the adf-codec shim refused a document at index 2, past the 2 it was handed")
@pytest.mark.parametrize("out", ["not json", json.dumps(["Hi\n"]), json.dumps({"0": "Hi\n"}), json.dumps(["Hi\n", 7])])
def test_texts_that_do_not_match_the_documents_become_a_failure(out):
failure = convert.adfs_to_markdown([DOC, DOC], fake(0, out))
assert failure == Failure(f"the adf-codec shim printed output that is not a JSON array of 2 texts: {out}")
def test_adf_to_markdown_returns_the_text_of_its_one_document():
run = fake(0, json.dumps(["Hi\n"]))
assert convert.adf_to_markdown(DOC, run) == "Hi\n"
assert run.calls == [("to-markdown", json.dumps(DOC))]
assert run.calls == [("to-markdown", json.dumps([DOC]))]
def test_a_refusal_becomes_a_failure_with_adf_codecs_code_and_message():
@@ -40,7 +73,7 @@ def test_a_refusal_becomes_a_failure_with_adf_codecs_code_and_message():
def test_a_refusal_without_a_position_names_the_path():
refusal = {"error": {"code": "unsupported-node-shape", "message": "bad node", "path": ["content", 0]}}
refusal = {"index": 0, "error": {"code": "unsupported-node-shape", "message": "bad node", "path": ["content", 0]}}
failure = convert.adf_to_markdown(DOC, fake(2, json.dumps(refusal)))
assert failure == Failure("adf-codec refused the input with unsupported-node-shape: bad node (at content.0)")
@@ -87,7 +120,7 @@ def test_the_container_command_line_is_exactly_this():
def test_a_refusal_at_the_root_says_the_document():
refusal = {"error": {"code": "not-an-adf-document", "message": "no type", "path": []}}
refusal = {"index": 0, "error": {"code": "not-an-adf-document", "message": "no type", "path": []}}
failure = convert.adf_to_markdown(DOC, fake(2, json.dumps(refusal)))
assert failure == Failure("adf-codec refused the input with not-an-adf-document: no type (at the document)")
@@ -143,24 +176,83 @@ def test_an_image_that_exists_is_not_built(tmp_path):
assert run_docker.lines == [(["docker", "image", "inspect", tag], "", convert.RUN_SECONDS)]
def test_a_missing_image_is_built_from_the_shim_folder_with_a_memory_limit(tmp_path):
class Slot:
"""Stands in for a heavy slot: records the docker lines run while it is held, or yields the given Failure."""
def __init__(self, run_docker, failure: Failure | None = None):
self.run_docker, self.failure, self.held_lines = run_docker, failure, None
@contextlib.contextmanager
def __call__(self):
before = len(self.run_docker.lines)
yield self.failure
self.held_lines = self.run_docker.lines[before:]
def test_a_missing_image_is_built_from_the_shim_folder_with_a_memory_limit_inside_a_heavy_slot(tmp_path):
missing = convert.Ran(1, "", "")
run_docker = scripted(missing, missing, convert.Ran(0, "", ""))
slot = Slot(run_docker)
tag = convert.image_tag(shim_dir(tmp_path))
assert convert.ensure_image(tmp_path, run_docker, slot) == tag
inspect = (["docker", "image", "inspect", tag], "", convert.RUN_SECONDS)
build = (["docker", "build", "--quiet", "--memory", "1g", "--memory-swap", "1g", "--tag", tag, str(tmp_path)], "", convert.BUILD_SECONDS)
assert run_docker.lines == [inspect, inspect, build]
assert slot.held_lines == [inspect, build]
def test_an_image_another_process_built_while_this_one_waited_for_a_slot_is_not_built_again(tmp_path):
run_docker = scripted(convert.Ran(1, "", ""), convert.Ran(0, "", ""))
tag = convert.image_tag(shim_dir(tmp_path))
assert convert.ensure_image(tmp_path, run_docker) == tag
assert run_docker.lines[1] == (["docker", "build", "--quiet", "--memory", "1g", "--memory-swap", "1g", "--tag", tag, str(tmp_path)], "", convert.BUILD_SECONDS)
assert convert.ensure_image(tmp_path, run_docker, Slot(run_docker)) == tag
assert len(run_docker.lines) == 2
def test_a_heavy_slot_that_cannot_be_taken_fails_before_the_build(tmp_path):
run_docker = scripted(convert.Ran(1, "", ""))
shim_dir(tmp_path)
down = Failure("cannot take a heavy slot in /x: Permission denied")
assert convert.ensure_image(tmp_path, run_docker, Slot(run_docker, down)) == down
assert len(run_docker.lines) == 1
def test_a_failed_build_becomes_a_failure_with_its_stderr(tmp_path):
run_docker = scripted(convert.Ran(1, "", ""), convert.Ran(5, "", "no network\n"))
run_docker = scripted(convert.Ran(1, "", ""), convert.Ran(1, "", ""), convert.Ran(5, "", "no network\n"))
shim_dir(tmp_path)
assert convert.ensure_image(tmp_path, run_docker) == Failure("building the adf-codec shim's image failed with exit 5: no network")
assert convert.ensure_image(tmp_path, run_docker, Slot(run_docker)) == Failure("building the adf-codec shim's image failed with exit 5: no network")
def test_a_failure_to_start_docker_passes_through_inspect_and_build(tmp_path):
DOWN, MISSING = Failure("docker is not installed"), convert.Ran(1, "", "")
@pytest.mark.parametrize("answers", [(DOWN,), (MISSING, DOWN), (MISSING, MISSING, DOWN)], ids=["first inspect", "second inspect", "build"])
def test_a_failure_to_start_docker_passes_through_inspect_and_build(tmp_path, answers):
shim_dir(tmp_path)
down = Failure("docker is not installed")
assert convert.ensure_image(tmp_path, scripted(down)) == down
assert convert.ensure_image(tmp_path, scripted(convert.Ran(1, "", ""), down)) == down
run_docker = scripted(*answers)
assert convert.ensure_image(tmp_path, run_docker, Slot(run_docker)) == DOWN
def test_a_heavy_slot_is_held_until_the_block_ends(tmp_path):
with convert.heavy_slot({"XDG_STATE_HOME": str(tmp_path)}, 1) as held:
assert held is None
assert slots.taken_slot(tmp_path / "run-heavy", 1) is None
slot, fd = slots.taken_slot(tmp_path / "run-heavy", 1)
os.close(fd)
def test_a_process_under_run_heavy_takes_no_second_slot(tmp_path):
(tmp_path / "run-heavy").mkdir()
slot, fd = slots.taken_slot(tmp_path / "run-heavy", 1)
try:
with convert.heavy_slot({"XDG_STATE_HOME": str(tmp_path), slots.HELD: "0"}, 1) as held:
assert held is None
finally:
os.close(fd)
def test_a_heavy_slot_folder_that_cannot_be_made_yields_a_failure(tmp_path):
(tmp_path / "run-heavy").write_text("a file where the folder goes")
with convert.heavy_slot({"XDG_STATE_HOME": str(tmp_path)}, 1) as held:
assert isinstance(held, Failure) and held.reason.startswith(f"cannot take a heavy slot in {tmp_path / 'run-heavy'}: ")
def test_container_run_runs_the_image_on_the_text(tmp_path):
@@ -182,5 +274,8 @@ def test_round_trip_through_the_real_container():
assert isinstance(markdown, str) and markdown.startswith("# Title") and "**bold**" in markdown
refused = convert.adf_to_markdown({"type": "nope"})
assert isinstance(refused, Failure) and "not-an-adf-document" in refused.reason
assert convert.adfs_to_markdown([doc, doc]) == [markdown, markdown]
second = convert.adfs_to_markdown([doc, {"type": "nope"}])
assert isinstance(second, convert.Refused) and second.index == 1 and "not-an-adf-document" in second.failure.reason
crashed = convert.answer("to-markdown", "not json", convert.container_run)
assert isinstance(crashed, Failure) and crashed.reason.startswith("the adf-codec shim failed with exit 1: ")
+1 -1
View File
@@ -28,7 +28,7 @@ def unsupported(checkout: str | None, home: pathlib.Path, run: Git = git) -> str
def held(config: ProjectConfig, name: str) -> tuple[str, str | None]:
"""What a message calls the plan or the record that setting name names in config, and its path from the checkout's top, None where it is kept elsewhere."""
if name == "plan":
return str(config.paths[name]), config.tracked(name)
return config.plan_label, config.tracked(name)
record = store(config, name)
return record.label, record.tracked
+4 -4
View File
@@ -20,12 +20,12 @@ def cut_name(cut: LastCut) -> str | None:
return None if headed is None else f"{version(headed)} (dated in CHANGELOG.md)"
def plan_name(default: str, outside: pathlib.Path | None) -> str:
"""How the preflight names the plan it read: the default branch's todo.md, or the file, where the project's config puts it outside the checkout."""
return str(outside) if outside else f"{default}'s todo.md"
def plan_name(default: str, outside: str | None) -> str:
"""How the preflight names the plan it read: the default branch's todo.md, or the file or Jira epic, where the project's config puts it outside the checkout."""
return outside if outside else f"{default}'s todo.md"
def planned(todo: plan_stores.Plan | Failure, cut: LastCut, default: str, branch: str, outside: pathlib.Path | None = None) -> Plan | NoItem:
def planned(todo: plan_stores.Plan | Failure, cut: LastCut, default: str, branch: str, outside: str | None = None) -> Plan | NoItem:
"""todo, which is the project's plan as its store read it and which plan_name names, with the item the next chunk takes first, release_standing.chunk_item's pick; else why there is none. branch is the project's `branch` template."""
where = plan_name(default, outside)
if isinstance(todo, NoItemsTable):
+2 -2
View File
@@ -17,7 +17,7 @@ def render(found: Gathered) -> list[str]:
note = [f"- {found.note}"] if found.note else []
unseen = [f"- {UNSEEN_RELEASES}"] if found.plan_outside else []
head = [*note, f"- {last_release(found.default, found.cut)}", *unseen]
paths = f"- The project's config puts its files at: {'; '.join(f'{setting} {path}' for setting, path in found.paths.items())}."
paths = f"- The project's config puts its files and plan at: {'; '.join(f'{setting} {path}' for setting, path in found.places.items())}."
texts = f"- The project's config sets: {'; '.join(f'{setting} {text}' for setting, text in found.texts.items())}."
if isinstance(found.item, NoItem):
return [*head, f"- No plan item: {found.item.why} No worktree was made.", paths, texts]
@@ -94,7 +94,7 @@ def bundled(plan: Plan) -> list[str]:
return [f"- Item {first.id} has R above {BUNDLE_MAX_R}, so it ships alone."]
if not candidates:
return [f"- No other item of release {version(first.release)} may join item {first.id}'s chunk."]
listed = [f" - item {item.id}, {levels(item)}, S {item.scores['S']}: {item.tagline}" for item in candidates]
listed = [f" - item {item.id}, {levels(item)}, S {item.scores.get('S', 'unscored')}: {item.tagline}" for item in candidates]
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]
+2 -2
View File
@@ -81,8 +81,8 @@ class Gathered:
item: ItemFacts | NoItem
# The plan that was read, as choices.plan_name names it.
plan: str
# Each path the project's config sets, by its setting: in the item's worktree where one was made or continued, else in the checkout.
paths: dict[str, pathlib.Path]
# Each path the project's config sets, and the epic of a plan kept in Jira, by its setting: in the item's worktree where one was made or continued, else in the checkout.
places: dict[str, str]
# Whether the project's config puts the plan outside the checkout, where a release whose items are all done is not seen.
plan_outside: bool
# The language and the templates the project's config names, by their settings.
+2 -2
View File
@@ -127,13 +127,13 @@ def preflight(root: pathlib.Path, timeout: float, make: bool) -> list[str] | Fai
config = located(str(root), pathlib.Path.home())
if isinstance(config, Failure):
return config
outside = None if config.tracked("plan") else config.paths["plan"]
outside = None if config.tracked("plan") else config.plan_label
held = project_plan(config, ref, str(root))
plan = planned(held.todo, held.cut, ref, config.branch, outside)
item = plan if isinstance(plan, NoItem) else item_facts(root, ref, plan, timeout, make)
# A `checkout:` path lands in the worktree the chunk works in.
made = located(str(item.worktree.path), pathlib.Path.home()) if isinstance(item, ItemFacts) and isinstance(item.worktree, Worktree) else config
return render(Gathered(ref, note, held.cut, item, plan_name(ref, outside), (config if isinstance(made, Failure) else made).paths, outside is not None, config.texts))
return render(Gathered(ref, note, held.cut, item, plan_name(ref, outside), (config if isinstance(made, Failure) else made).places, outside is not None, config.texts))
def item_facts(root: pathlib.Path, default: str, plan: Plan, timeout: float, make: bool) -> ItemFacts:
+9 -2
View File
@@ -1,3 +1,4 @@
import dataclasses
import os
import pathlib
import shutil
@@ -139,7 +140,7 @@ class ChunkPreflightTool(unittest.TestCase):
self.assertEqual(done.returncode, 0, done.stderr)
worktree = repo.temp / "proj-item-7"
self.assertIn("item 7, L 1, E + I 2", done.stdout, "origin's todo.md still holds item 3, which the plan in the config's folder does not")
self.assertIn(f"- The project's config puts its files at: plan {folder}/todo.md; working-rules {worktree}/AGENTS.md; decisions {worktree}/docs/decisions.md; ", done.stdout)
self.assertIn(f"- The project's config puts its files and plan at: plan {folder}/todo.md; working-rules {worktree}/AGENTS.md; decisions {worktree}/docs/decisions.md; ", done.stdout)
self.assertIn("`rank_todo.py --check` exited 0", done.stdout)
self.assertIn(f"- {UNSEEN_RELEASES}\n", done.stdout)
config.unlink()
@@ -388,7 +389,7 @@ class Render(unittest.TestCase):
def test_states_each_fact_once_with_the_paths_between_the_worktree_and_the_open_pull_requests(self):
lines = render(gathered(item_facts()))
self.assertEqual([line.partition(":")[0] for line in lines[:6]], ["- Last version cut", "- The earliest release in origin/main's todo.md", "- Worktree", "- The project's config puts its files at", "- The project's config sets", "- Open pull requests from item-3"])
self.assertEqual([line.partition(":")[0] for line in lines[:6]], ["- Last version cut", "- The earliest release in origin/main's todo.md", "- Worktree", "- The project's config puts its files and plan at", "- The project's config sets", "- Open pull requests from item-3"])
self.assertEqual([line for line in lines[6:] if line.startswith("- Open pull requests")], [])
def test_says_that_a_plan_outside_the_checkout_hides_a_release_whose_items_are_all_done(self):
@@ -404,6 +405,12 @@ class Render(unittest.TestCase):
self.assertIn("Item 7's detail:\n\n> Touch `src/other.py`.\n> \n> Run the e2e leg.", said)
self.assertNotIn("Not quoted", said)
def test_lists_a_joining_item_nobody_scored_as_unscored(self):
plan = item_facts().plan
unscored = [dataclasses.replace(item, scores={}) if item.id == 7 else item for item in plan.items]
said = rendered(item_facts(plan=dataclasses.replace(plan, items=unscored)))
self.assertIn(" - item 7, L unscored, E + I unscored, S unscored: ", said)
def test_states_that_a_joining_item_has_no_detail(self):
said = rendered(item_facts())
self.assertIn("Item 7 has no detail.", said)
+4 -3
View File
@@ -9,6 +9,7 @@ import sys
import tempfile
from release_plan.release_standing import chunk_item, Cut, default_plan, Next, ReadyToCut, ReviewDue, Unplanned
from project_config.settings import DEFAULT_FLOOR
from git_cli.git_repo import default_ref, git
from deploy_release.deploy import deploy
from failure import Failure
@@ -109,9 +110,9 @@ def same_origin(clone: str, checkout: str) -> Failure | None:
def clone_plan(clone: str) -> FilePlan:
"""The clone's plan, at the path this repo keeps it. ready_release only reads it; FilePlan also takes the files a write would rank it against."""
decisions, history = (FileStore(pathlib.Path(clone, path), path) for path in ("docs/decisions.md", "docs/comprehension-history.md"))
return FilePlan(pathlib.Path(clone, "todo.md"), "todo.md", pathlib.Path(clone, "README.md"), decisions, history)
"""The clone's plan, at the path this repo keeps it. ready_release only reads it; FilePlan also takes the files and the floor a write would rank it against, and the clone has no config to set the floor."""
goals, decisions, history = (FileStore(pathlib.Path(clone, path), path) for path in ("README.md", "docs/decisions.md", "docs/comprehension-history.md"))
return FilePlan(pathlib.Path(clone, "todo.md"), "todo.md", goals, decisions, history, DEFAULT_FLOOR)
def ready_release(clone: str, ref: str) -> Release | Failure:
+8 -5
View File
@@ -2,7 +2,7 @@ import pathlib
import typing
from larv_review.agreement import agreement_report
from review_rules.comprehension_history import appended, DIMENSIONS, FLOOR, heading, Heading, latest_places, recorded, ruling_entry, scoring_entry, ScoringRun, vote_text
from review_rules.comprehension_history import appended, DIMENSIONS, heading, Heading, latest_places, recorded, ruling_entry, scoring_entry, ScoringRun, vote_text
from larv_review.plan import checkout_plan, plan_reasons
from git_cli.git_repo import commit_exists
from larv_review.ruling import counted, overall, ruling, split, surplus, votes
@@ -66,9 +66,9 @@ def record_scoring(default: str, scores_file: pathlib.Path, ids: list[int], home
return appended_to
say(appended_to)
say(f"Means: {', '.join(f'{name} {value}' for name, value in zip(DIMENSIONS, scoring.means))}.")
if under := under_floor(scoring.means):
say(f"Floor: {', '.join(under)} under the floor of {FLOOR}.")
if step := floor_step(scoring.means, plan, ids):
if under := under_floor(scoring.means, config.readability_floor):
say(f"Floor: {', '.join(under)} under the floor of {config.readability_floor}.")
if step := floor_step(scoring.means, plan, ids, config.readability_floor):
say(step)
reranked = rerank(home, warn)
removed = removed_setup(checkout, home)
@@ -80,7 +80,10 @@ def rerank(home: pathlib.Path, warn: Say) -> Failure | None:
config = located(None, home)
if isinstance(config, Failure):
return config
todo = config.paths["plan"]
todo = config.plan_file
if todo is None:
# A plan in Jira is ranked by Jira's backlog, which no score moves.
return None
ranked = plan_file.rank_file(todo, config)
if isinstance(ranked, Failure):
return Failure(f"recorded the run, but rank_todo.py cannot rank {todo}: {ranked.reason}. Fix what that names, then run rank_todo.py on {todo}, not record-scoring again")
+4 -3
View File
@@ -101,7 +101,8 @@ record-scoring never removed is still there, it removes it first and says so.
record-scoring takes the scores file of a run needs-scoring-run calls, whose first line names no
`, against`, and the same item IDs, and exits 1 when they call no run. It appends the seats' scores
and their means, rounded half up to two decimals, prints the means and, when a mean is under the
floor of {floor}, a line opening `Floor:` naming each one. A line opening `Next:` follows it. It
project's readability floor, a line opening `Floor:` naming each one and the floor. The config sets
the floor as `readability-floor`, {floor} where left out. A line opening `Next:` follows it. It
says to file a floor item aimed at the lowest of the four dimensions, and names the tagline's opening
`Reach the comprehension floor:`. Where the project's todo.md holds such an item other than those given, it says to
refresh that item instead. Then it ranks the project's todo.md as rank_todo.py does, since the
@@ -161,8 +162,8 @@ import typing
from git_cli.git_repo import branch_titles, default_branch, git, top
from review_rules.round_titles import cap, CAP, RELEASE_REVIEW_CAP, round_counts
from project_config.settings import DEFAULT_FLOOR
from failure import Failure
from review_rules.comprehension_history import FLOOR
from larv_review.history_changes import history_changes
from review_rules.reviewer_context import hook_reply
from review_rules.review_folder import made_review_folder
@@ -237,7 +238,7 @@ USAGE = f"usage: larv-review {SHAPES}"
def main(argv: list[str]) -> int:
if argv in (["-h"], ["--help"]):
print(__doc__.strip().format(commands=SHAPES, cap=CAP, release_cap=RELEASE_REVIEW_CAP, floor=FLOOR, pairs=MIN_PAIRS))
print(__doc__.strip().format(commands=SHAPES, cap=CAP, release_cap=RELEASE_REVIEW_CAP, floor=DEFAULT_FLOOR, pairs=MIN_PAIRS))
return 0
if not argv:
print(USAGE, file=sys.stderr)
+1 -1
View File
@@ -26,7 +26,7 @@ def owed_scoring_run(default: str, home: pathlib.Path, warn: typing.Callable[[st
record = store(config, "comprehension-history")
plan, history = config.tracked("plan"), record.tracked
if plan is None or history is None:
name, where = ("plan", str(config.paths["plan"])) if plan is None else ("comprehension history", record.label)
name, where = ("plan", config.plan_label) if plan is None else ("comprehension history", record.label)
warn(f"larv-review doesn't support a {name} outside the checkout, so it cannot tell whether the chunk owes a scoring run: {where}")
return None
base = git("merge-base", default, "HEAD", cwd=checkout)
+9 -4
View File
@@ -8,6 +8,7 @@ from project_config.main import located
from release_plan.goals_file import OPTED_OUT
from plan_store.stores import Plan, PlanStore
from plan_store import stores as plan_stores
from project_config.settings import ProjectConfig
from release_plan.release import Release, version
from record_store import stores
from larv_review.unmeasured import unmeasured_cut
@@ -66,6 +67,13 @@ def emptied(before: list[Item], after: list[Item], shipped: list[Item], renamed:
return sorted(named - {item.release for item in kept} - renamed)
def finished_unseen(config: ProjectConfig, ids: list[int], chunk: list[Item]) -> Failure | None:
"""Why the items under ids cannot all be read, where the plan lies outside the checkout: such a plan is read as it stands for both plans, so a finished item is in neither."""
if config.tracked("plan") is None and (gone := sorted(set(ids) - {item.id for item in chunk})):
return Failure(f"the plan as it stands holds no item {', '.join(map(str, gone))}, and larv-review doesn't support a plan outside the checkout, so it cannot read the plan as it stood before the item was finished: {config.plan_label}")
return None
def plan_reasons(ref: str, ids: list[int] | None, home: pathlib.Path) -> list[str] | Failure:
"""Why the plan calls a scoring run, from todo.md at ref and the checkout's, each file where the project's config puts it; empty where the project opts out of the comprehension check. ref is the default branch, or the commit where the chunk began. Where ids is None, the chunk ships each item the plan at ref holds and the checkout's does not."""
config = located(None, home)
@@ -98,10 +106,7 @@ def plan_reasons(ref: str, ids: list[int] | None, home: pathlib.Path) -> list[st
return unmeasured
if ids is None:
ids = sorted({item.id for item in planned} - {item.id for item in chunk})
# A plan outside the checkout is read as it stands for both plans, so a finished item is in neither.
if config.tracked("plan") is None and (gone := sorted(set(ids) - {item.id for item in chunk})):
return Failure(f"todo.md as it stands holds no item {', '.join(map(str, gone))}, and larv-review doesn't support a plan outside the checkout, so it cannot read the plan as it stood before the item was finished: {config.paths['plan']}")
return scoring_run_due(planned, chunk, ids, landed_release, renamed, unmeasured)
return finished_unseen(config, ids, chunk) or scoring_run_due(planned, chunk, ids, landed_release, renamed, unmeasured)
def checkout_plan(plan: PlanStore) -> Plan | Failure:
+6 -2
View File
@@ -6,8 +6,8 @@ from git_cli.git_repo import branch_titles, git, top
from review_rules.round_titles import cap, round_counts
from failure import Failure
from chunk_preflight.choices import forge_of
from record_store.stores import goals_store, local_file, store
from larv_review.history_commands import history_file, places_report
from record_store.stores import local_file, store
from project_config.main import located, title_templates
from review_rules.review_folder import made_review_folder
from deploy_release.forge import open_pull, runner
@@ -99,7 +99,11 @@ def reviewer_header(default: str, pass_: str, rerun: bool, home: pathlib.Path) -
decisions = local_file(store(config, "decisions"), folder / "decisions.md")
if isinstance(decisions, Failure):
return decisions
launch = Launch(pass_, round_, rerun, pull_named(worktree, branch), worktree, branch, base, default, folder, folder / f"branch-{head}.diff", principles, config.paths["goals-and-audience"], starts_bare(next((agent for name, agent in REVIEWERS.items() if name == pass_), ""), home), config.paths["working-rules"], decisions, config.language)
# A reviewer reads files, so goals kept in a Jira epic's description are copied into the review folder.
goals = local_file(goals_store(config), folder / "goals.md")
if isinstance(goals, Failure):
return goals
launch = Launch(pass_, round_, rerun, pull_named(worktree, branch), worktree, branch, base, default, folder, folder / f"branch-{head}.diff", principles, goals, 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)
+7 -6
View File
@@ -1,6 +1,6 @@
import decimal
from review_rules.comprehension_history import DIMENSIONS, FLOOR
from review_rules.comprehension_history import DIMENSIONS
from release_plan.todo_table import Item
# A floor item's tagline opens with this phrase, which a tagline quoting or mentioning the floor never does; a floor item's chunk runs a scoring run.
@@ -21,16 +21,17 @@ def mean(values: list[decimal.Decimal]) -> decimal.Decimal:
return (sum(values, decimal.Decimal(0)) / len(values)).quantize(decimal.Decimal("0.01"), decimal.ROUND_HALF_UP)
def under_floor(found: list[decimal.Decimal]) -> list[str]:
return [f"{name} {value}" for name, value in zip(DIMENSIONS, found) if value < FLOOR]
def under_floor(found: list[decimal.Decimal], floor: decimal.Decimal) -> list[str]:
"""Each mean in found under floor, the project's readability floor, with its dimension's name."""
return [f"{name} {value}" for name, value in zip(DIMENSIONS, found) if value < floor]
def floor_step(found: list[decimal.Decimal], plan: list[Item], ships: list[int]) -> str | None:
def floor_step(found: list[decimal.Decimal], plan: list[Item], ships: list[int], floor: decimal.Decimal) -> str | None:
"""The `Next:` line of a scoring run with a mean under the floor, None when no mean is under it (SKILL.md → "Floor item").
The line aims at the lowest of the four dimensions, or at each where they tie, since the lowest caps the overall. A floor item in plan is open unless ships holds its ID, so a chunk that ships one still files the next.
"""
if not under_floor(found):
if not under_floor(found, floor):
return None
dimensions = dict(zip(DIMENSIONS[:-1], found))
lowest = [name for name, value in dimensions.items() if value == min(dimensions.values())]
@@ -39,4 +40,4 @@ def floor_step(found: list[decimal.Decimal], plan: list[Item], ships: list[int])
rule = 'as larv-review §3 → "Floor item" says.'
if open_items := [item for item in plan if is_floor_item(item) and item.id not in ships]:
return f"Next: refresh floor item {open_items[0].id} to lift {aim}, with this run's places, and file no other, {rule}"
return f"Next: file one floor item, a refactor lifting {aim}, with a tagline that opens with `{FLOOR_ITEM}`, until every mean reaches {FLOOR}, {rule}"
return f"Next: file one floor item, a refactor lifting {aim}, with a tagline that opens with `{FLOOR_ITEM}`, until every mean reaches {floor}, {rule}"
+62 -14
View File
@@ -1,3 +1,4 @@
import contextlib
import decimal
import itertools
import json
@@ -16,17 +17,19 @@ from larv_review.agreement import agreement_report, ruling_agreement, run_agreem
from review_rules.comprehension_history import appended, entries, HistoryChange, latest_places, Place, recorded, ruling_entry, scoring_entry, ScoringRun, Seat
from larv_review.plan import checkout_plan, EMPTIED_WORDS, landed_towards, plan_reasons, scoring_run_due
from review_rules import comprehension_history
from project_config.test_project_config import configured
from larv_review.ruling import counted, ruling, split, surplus, votes
from larv_review.history_commands import decided
from larv_review.history_commands import decided, rerank
from project_config.settings import DEFAULT_FLOOR
from failure import Failure
from plan_store.stores import FilePlan
from record_store.stores import FileStore
from larv_review.scoring import floor_step, means, under_floor
from test_env import isolated_env
from release_plan.todo_table import Item, items, NoItemsTable
from release_plan.release_standing import LastCut
from larv_review.ruling_base import measured_commit
from record_store.fakes import MemoryStore
from record_store.fakes import MemoryStore
from larv_review.seats import score_line, scores, seats_file, SeatsFile
from larv_review.owed import shortfall
@@ -117,42 +120,49 @@ class Seats(unittest.TestCase):
def test_rounds_each_mean_half_up_and_names_each_under_the_floor(self):
found = means([["7.5", "6.5", "7", "7", "7"], ["7.5", "7", "7", "6.5", "7"], ["7", "6.5", "7", "6.5", "6.5"], ["7.5", "6.5", "7", "6.5", "7"]])
self.assertEqual([str(mean) for mean in found], ["7.38", "6.63", "7.00", "6.63", "6.88"])
self.assertEqual(under_floor(found), ["Locality 6.63", "Self-sufficiency 6.63", "Overall 6.88"])
self.assertEqual(under_floor([decimal.Decimal("7.00")] * 5), [])
self.assertEqual(under_floor(found, DEFAULT_FLOOR), ["Locality 6.63", "Self-sufficiency 6.63", "Overall 6.88"])
self.assertEqual(under_floor([decimal.Decimal("7.00")] * 5, DEFAULT_FLOOR), [])
def test_names_only_the_means_under_the_floor_it_is_given_and_aims_the_next_item_at_it(self):
found = [decimal.Decimal(mean) for mean in ("6.50", "5.75", "6.00", "5.50", "5.94")]
self.assertEqual(under_floor(found, decimal.Decimal("6")), ["Locality 5.75", "Self-sufficiency 5.50", "Overall 5.94"])
self.assertEqual(under_floor(found, decimal.Decimal("5.5")), [])
self.assertIsNone(floor_step(found, [], [], decimal.Decimal("5.5")))
self.assertIn("until every mean reaches 6, ", floor_step(found, [], [], decimal.Decimal("6")))
def test_floor_step_files_one_item_at_the_lowest_dimension_unless_one_is_open(self):
found = [decimal.Decimal(mean) for mean in ("7.38", "6.63", "7.00", "6.50", "6.88")]
floor_item = item(5, (0, 2, 0), "**Reach the comprehension floor: restructure the reload, lifting Locality.**")
with self.subTest("none open"):
step = floor_step(found, [item(1, (0, 1, 0))], [])
step = floor_step(found, [item(1, (0, 1, 0))], [], DEFAULT_FLOOR)
self.assertTrue(step.startswith("Next: file one floor item"), step)
self.assertIn("with a tagline that opens with `Reach the comprehension floor:`,", step)
self.assertIn(" Self-sufficiency, the lowest dimension,", step)
self.assertIn('"Floor item"', step)
with self.subTest("one open"):
step = floor_step(found, [item(1, (0, 1, 0)), floor_item], [])
step = floor_step(found, [item(1, (0, 1, 0)), floor_item], [], DEFAULT_FLOOR)
self.assertTrue(step.startswith("Next: refresh floor item 5 "), step)
self.assertIn(" Self-sufficiency, the lowest dimension,", step)
self.assertIn("file no other", step)
with self.subTest("the shipped one is not open"):
self.assertTrue(floor_step(found, [floor_item], [5]).startswith("Next: file one floor item"))
self.assertTrue(floor_step(found, [floor_item], [5], DEFAULT_FLOOR).startswith("Next: file one floor item"))
with self.subTest("a tie names both"):
tied = [decimal.Decimal(mean) for mean in ("7.38", "6.50", "7.00", "6.50", "6.88")]
self.assertIn(" Locality and Self-sufficiency, the lowest dimensions,", floor_step(tied, [], []))
self.assertIn(" Locality and Self-sufficiency, the lowest dimensions,", floor_step(tied, [], [], DEFAULT_FLOOR))
with self.subTest("a tagline that only mentions the floor is no floor item"):
quoting = item(6, (0, 2, 0), "**Rename the decision `comprehension floor: …` in the log.**")
self.assertTrue(floor_step(found, [quoting], []).startswith("Next: file one floor item"))
self.assertTrue(floor_step(found, [quoting], [], DEFAULT_FLOOR).startswith("Next: file one floor item"))
with self.subTest("none under the floor"):
self.assertIsNone(floor_step([decimal.Decimal("7.00")] * 5, [floor_item], []))
self.assertIsNone(floor_step([decimal.Decimal("7.00")] * 5, [floor_item], [], DEFAULT_FLOOR))
with self.subTest("only the overall under the floor"):
step = floor_step([decimal.Decimal("7.00")] * 4 + [decimal.Decimal("6.75")], [], [])
step = floor_step([decimal.Decimal("7.00")] * 4 + [decimal.Decimal("6.75")], [], [], DEFAULT_FLOOR)
self.assertIn(" Navigation, Locality, Shape and Self-sufficiency, the lowest dimensions,", step)
self.assertIn("until every mean reaches 7.0", step)
def test_checkout_plan_fails_on_a_missing_or_tableless_todo(self):
with tempfile.TemporaryDirectory() as checkout:
path = pathlib.Path(checkout, "todo.md")
plan = FilePlan(path, "todo.md", pathlib.Path(checkout, "README.md"), MemoryStore(), MemoryStore())
plan = FilePlan(path, "todo.md", FileStore(pathlib.Path(checkout, "README.md"), None), MemoryStore(), MemoryStore(), DEFAULT_FLOOR)
with self.subTest("missing"):
self.assertEqual(checkout_plan(plan).reason, f"the project's plan: {path}: not found; every project keeps a todo.md, and rank_todo.py --help shows one")
with self.subTest("no items table"):
@@ -588,7 +598,7 @@ class LarvReviewTool(unittest.TestCase):
(self.config.parent / "decisions.md").unlink()
gone = plan_reasons("origin/main", [1, 7], pathlib.Path.home())
assert isinstance(gone, Failure), gone
self.assertEqual(gone.reason, f"todo.md as it stands holds no item 7, and larv-review doesn't support a plan outside the checkout, so it cannot read the plan as it stood before the item was finished: {self.config.parent}/todo.md")
self.assertEqual(gone.reason, f"the plan as it stands holds no item 7, and larv-review doesn't support a plan outside the checkout, so it cannot read the plan as it stood before the item was finished: {self.config.parent}/todo.md")
(self.config.parent / "todo.md").write_bytes(b"\xff")
unreadable = plan_reasons("origin/main", [2], pathlib.Path.home())
assert isinstance(unreadable, Failure), unreadable
@@ -825,6 +835,21 @@ class LarvReviewTool(unittest.TestCase):
self.assertIn(f"cannot read {history}: not UTF-8 on line 2", ran.stderr)
self.assertEqual(history.read_bytes(), b"# Comprehension history\n\xff\n")
def test_holds_a_scoring_run_to_the_readability_floor_the_config_sets(self):
line = "Navigation 7, Locality 6.5, Shape 7, Self-sufficiency 6.5, Overall 7"
seats = "".join(f"\n{seat}: {line}\n\n- `bin/a.py:3` `f`: long\n" for seat in ("Junior A", "Mid A", "Maintainability senior", "Inherited architect"))
self.plan()
self.config.write_text(PROJECT_CONFIG + "readability-floor = 6.5\n")
ran = self.run_tool("record-scoring", self.seats_file(f"PR #2 at {self.start}\n" + seats), "1")
self.assertEqual(ran.returncode, 0, ran.stderr)
self.assertIn("\nMeans: ", ran.stdout)
self.assertNotIn("Floor:", ran.stdout)
self.config.write_text(PROJECT_CONFIG + "readability-floor = 6.8\n")
ran = self.run_tool("record-scoring", self.seats_file(f"PR #3 at {self.start}\n" + seats), "1")
self.assertEqual(ran.returncode, 0, ran.stderr)
self.assertIn("\nFloor: Locality 6.50, Self-sufficiency 6.50 under the floor of 6.8.\nNext: file one floor item,", ran.stdout)
self.assertIn("until every mean reaches 6.8,", ran.stdout)
def test_records_a_scoring_run_with_its_means(self):
line = "Navigation 7, Locality 6.5, Shape 7, Self-sufficiency 6.5, Overall 7"
seats = "".join(f"\n{seat}: {line}\n\n- `bin/a.py:3` `f`: long\n" for seat in ("Junior A", "Mid A", "Maintainability senior", "Inherited architect"))
@@ -930,7 +955,7 @@ class LarvReviewTool(unittest.TestCase):
# This checkout has no README.md beside its todo.md.
ran = self.record_sevens()
self.assertEqual(ran.returncode, 1)
self.assertIn(f"recorded the run, but rank_todo.py cannot rank {self.checkout / 'todo.md'}: {self.checkout / 'README.md'}: not found", ran.stderr)
self.assertIn(f"recorded the run, but rank_todo.py cannot rank {self.checkout / 'todo.md'}: {self.checkout / 'README.md'}: missing or empty", ran.stderr)
self.assertIn("not record-scoring again", ran.stderr)
self.assertEqual(len(entries((self.checkout / "docs" / "comprehension-history.md").read_text())), 1)
@@ -942,6 +967,18 @@ class LarvReviewTool(unittest.TestCase):
self.assertIn("not record-scoring again", ran.stderr)
self.assertEqual(len(entries((self.checkout / "docs" / "comprehension-history.md").read_text())), 1)
def test_a_plan_in_jira_is_not_reranked(self):
with tempfile.TemporaryDirectory() as temp:
checkout = pathlib.Path(temp, "acme")
checkout.mkdir()
config = configured(self, checkout) / "config.toml"
config.write_text(config.read_text().replace('"checkout:todo.md"', '"jira:https://acme.atlassian.net/browse/ABC-12"') + 'env-file = "~/acme.env"\n')
(checkout / "todo.md").write_text("the owners' own notes\n")
self.enterContext(contextlib.chdir(checkout))
said: list[str] = []
self.assertIsNone(rerank(pathlib.Path.home(), said.append))
self.assertEqual((said, (checkout / "todo.md").read_text()), ([], "the owners' own notes\n"))
def test_reranks_todo_md_by_the_overall_it_records(self):
self.plan()
ran = self.record_sevens()
@@ -1185,6 +1222,17 @@ class LarvReviewTool(unittest.TestCase):
self.config.write_text(PROJECT_CONFIG.replace('"checkout:README.md"', '"folder:goals.md"'))
self.assertEqual(self.header_line("Goals and audience:", "principles"), f"Goals and audience: {self.config.parent}/goals.md")
def test_reviewer_header_fails_naming_the_epic_where_it_cannot_read_goals_kept_in_jira(self):
# Port 1 on the loopback refuses the connection, so the read fails without leaving the machine.
epic = "jira:https://127.0.0.1:1/browse/ABC-12"
credentials = self.config.parents[2] / "acme.env"
credentials.write_text("ATLASSIAN_EMAIL=me@example.com\nATLASSIAN_API_TOKEN=s3cret\n")
credentials.chmod(0o600)
self.config.write_text(PROJECT_CONFIG.replace('"checkout:todo.md"', f'"{epic}"').replace('"checkout:README.md"', f'"{epic}"') + 'env-file = "~/acme.env"\n')
ran = self.run_tool("reviewer-header", "prose")
self.assertEqual((ran.returncode, ran.stdout), (1, ""))
self.assertIn("cannot read the epic ABC-12", ran.stderr)
def test_reviewer_header_fails_with_the_configs_message_where_it_sets_no_principles_folder(self):
self.config.write_text(PROJECT_CONFIG.replace('principles = "~/principles"\n', ""))
ran = self.run_tool("reviewer-header", "prose")
+20 -19
View File
@@ -4,25 +4,26 @@ usage: loop-claude <task>
Run it anywhere inside a project checkout whose goals file has ## Goals and ## Audience, the
premises. The goals file is the one the project's config, ~/.claude-projects/<key>/config.toml, sets
as goals-and-audience; `project-config goals-and-audience` prints it. The task runs at the checkout
root. Each cycle a worker runs the task. A chunk's first worker prompt also quotes the premises.
They, with code health (~/.claude/CLAUDE.md → "Shared goal") ranked first unless the goals file
voids it, choose between ways to deliver the chunk's todo.md items, or else the task, and never
widen them. A judge then reads the transcript's end, the premises, and the records: the project's
AGENTS.md and docs/decisions.md, and the human's ~/.claude/CLAUDE.md, ~/.claude/rules/*.md and
~/.claude/skills/larv-review/standards/*.md, where they exist. It rules whether the chunk, the work
of one PR, is finished. A chunk stays unfinished until each answer the human typed in it that a
later chunk could need is recorded: the premises or the records hold it, or the transcript shows the
worker writing it into the premises, AGENTS.md, docs/decisions.md, todo.md or a code comment. A
choice the worker made that the premises or the records settle is not asked about. When the worker
asks a question they answer, the judge quotes the answer, loop-claude prints it, and the worker
resumes with it. A quote they do not hold word for word is dropped, and the question goes to the
human. So does a question asked again after its answer. A question the human answered earlier in the
chunk goes back to the worker with that answer, unless the question quotes the words of the answer
that leave it open. The fourth question they answer in one cycle goes to the human too, with the
quote. An unfinished chunk resumes its session next cycle, and the worker is shown the passage the
judge quoted as the work remaining. The next chunk starts a fresh session. Cycles continue until an
exit below or Ctrl-C. Words: ~/.claude/CLAUDE.md → "Vocabulary".
as goals-and-audience: a file, or a Jira epic's description. `project-config goals-and-audience`
prints where it is. The task runs at the checkout root. Each cycle a worker runs the task. A chunk's
first worker prompt also quotes the premises. They, with code health (~/.claude/CLAUDE.md →
"Shared goal") ranked first unless the goals file voids it, choose between ways to deliver the
chunk's todo.md items, or else the task, and never widen them. A judge then reads the transcript's
end, the premises, and the records: the project's AGENTS.md and docs/decisions.md, and the human's
~/.claude/CLAUDE.md, ~/.claude/rules/*.md and ~/.claude/skills/larv-review/standards/*.md, where
they exist. It rules whether the chunk, the work of one PR, is finished. A chunk stays unfinished
until each answer the human typed in it that a later chunk could need is recorded: the premises or
the records hold it, or the transcript shows the worker writing it into the premises, AGENTS.md,
docs/decisions.md, todo.md or a code comment. A choice the worker made that the premises or the
records settle is not asked about. When the worker asks a question they answer, the judge quotes the
answer, loop-claude prints it, and the worker resumes with it. A quote they do not hold word for
word is dropped, and the question goes to the human. So does a question asked again after its
answer. A question the human answered earlier in the chunk goes back to the worker with that answer,
unless the question quotes the words of the answer that leave it open. The fourth question they
answer in one cycle goes to the human too, with the quote. An unfinished chunk resumes its session
next cycle, and the worker is shown the passage the judge quoted as the work remaining. The next
chunk starts a fresh session. Cycles continue until an exit below or Ctrl-C. Words:
~/.claude/CLAUDE.md → "Vocabulary".
A question only the human can answer is an interrupt (bin/loop_claude/cycle/interrupt.py).
loop-claude prints the question on its terminal, where the human answers it:
+13 -10
View File
@@ -1,23 +1,26 @@
import pathlib
from failure import Failure
from project_config.main import goals_file
from loop_claude.project.text_file import read_utf8
from record_store.stores import goals_store
from project_config.main import located
from release_plan.goals_file import section
def read_premises(root: str, home: pathlib.Path) -> str | Failure:
"""The goals file's path, then its ## Goals and ## Audience; the goals file is the one that the config under home of root's project names. A Failure where no config names root's checkout, the file cannot be read, or the file lacks a section, holds one twice or leaves one empty."""
path = goals_file(root, home)
if isinstance(path, Failure):
return Failure(f"{path.reason} - no premises.")
text = read_utf8(str(path.parent), path.name, "no premises")
"""Where the goals file is kept, then its ## Goals and ## Audience. The goals file is the one that the config of root's checkout, under home, names: a file or a Jira epic's description. A Failure where no config names the checkout, or the goals file cannot be read, is missing or empty, lacks a section, holds one twice or leaves one empty."""
config = located(root, home)
if isinstance(config, Failure):
return Failure(f"{config.reason} - no premises.")
goals = goals_store(config)
text = goals.read()
if isinstance(text, Failure):
return text
return Failure(f"{text.reason} - no premises.")
if not text:
return Failure(f"{goals.label} is missing or empty - no premises.")
bodies: list[str] = []
for name in ("Goals", "Audience"):
body = section(text, name)
if isinstance(body, Failure):
return Failure(f"{path} {body.reason} - no premises.")
return Failure(f"{goals.label} {body.reason} - no premises.")
bodies.append(body)
return f"{path}:\n## Goals\n{bodies[0]}\n\n## Audience\n{bodies[1]}"
return f"{goals.label}:\n## Goals\n{bodies[0]}\n\n## Audience\n{bodies[1]}"
+3 -3
View File
@@ -335,8 +335,8 @@ class Premises(unittest.TestCase):
self.assertEqual((run.code, run.calls), (1, []))
self.assertRegex(run.raw_stderr, rf"(?m)^{STAMP} .*not a git repository")
readmes = {
None: "README.md in {root}: No such file or directory - no premises.",
b"# P\n## Goals\n1. g\xff\n## Audience\nme\n": "README.md in {root} is not UTF-8 on line 3 - no premises.",
None: "{root}/README.md is missing or empty - no premises.",
b"# P\n## Goals\n1. g\xff\n## Audience\nme\n": "cannot read {root}/README.md: not UTF-8 on line 3 - no premises.",
b"# P\n## Audience\nme\n": "{root}/README.md has no ## Goals heading - no premises.",
b"# P\n## Goals\n1. g\n": "{root}/README.md has no ## Audience heading - no premises.",
b"# P\n## Goals\n\n## Audience\nme\n": "{root}/README.md has no text under ## Goals - no premises.",
@@ -356,7 +356,7 @@ class Premises(unittest.TestCase):
(checkout.root / "README.md").mkdir()
run = checkout.run([worker()])
self.assertEqual((run.code, run.calls), (1, []))
self.assertEqual(run.stderr.strip(), f"README.md in {checkout.root}: Is a directory - no premises.")
self.assertEqual(run.stderr.strip(), f"cannot read {checkout.root}/README.md: Is a directory - no premises.")
(checkout.home / ".claude-projects" / "proj" / "config.toml").unlink()
run = checkout.run([worker()])
self.assertEqual((run.code, run.calls), (1, []))
+2
View File
@@ -8,6 +8,8 @@ import typing
CPUS_PER_SLOT = 4
# Seconds between tries while every slot is held; a slot frees as its command exits.
POLL_SECONDS = 1
# Names the environment variable run-heavy sets for the command it runs. A process that finds it set already holds a slot, and takes no second one.
HELD = "RUN_HEAVY_SLOT"
def usable_cpus() -> int | None:
+9 -64
View File
@@ -1,15 +1,13 @@
"""Sends a direct message from a Mattermost bot to one user, through Mattermost's REST API v4."""
import dataclasses
import http.client
import json
import pathlib
import typing
import urllib.error
import urllib.parse
import urllib.request
from failure import Failure
from rest_client import json_request
from project_config.main import located
from rest_client.env_file import read_env
KEYS = ("MATTERMOST_URL", "MATTERMOST_TOKEN", "MATTERMOST_RECIPIENT")
# Seconds each connect and each read may wait, so an unreachable server holds loop-claude's interrupt only briefly.
@@ -19,16 +17,6 @@ TIMEOUT = 10
Http = typing.Callable[[str, str, str, object], object]
class NoRedirect(urllib.request.HTTPRedirectHandler):
"""Refuses every redirect, which Mattermost's API never sends: urllib would resend the token to the new location, even one off https."""
def redirect_request(self, *args: typing.Any, **kwargs: typing.Any) -> None:
return None
OPENER = urllib.request.build_opener(NoRedirect)
@dataclasses.dataclass(frozen=True)
class Config:
url: str
@@ -38,37 +26,15 @@ class Config:
def read_config(path: pathlib.Path) -> Config | Failure:
"""The server, bot token and recipient that path's KEY=value lines hold."""
try:
mode = path.stat().st_mode
text = path.read_text(encoding="utf-8")
except FileNotFoundError:
return Failure(f"{path} does not exist; it needs {', '.join(KEYS[:-1])} and {KEYS[-1]}")
except (OSError, UnicodeDecodeError) as failure:
return Failure(f"cannot read {path}: {failure}")
if mode & 0o077:
return Failure(f"{path} holds the bot's token, so only its owner may read it; run chmod 600 {path}")
values = parse_env(text)
if missing := [key for key in KEYS if not values.get(key)]:
return Failure(f"{path} lacks {' and '.join(missing)}")
values = read_env(path, KEYS, "the bot's token")
if isinstance(values, Failure):
return values
url, token, recipient = (values[key] for key in KEYS)
if not url.startswith("https://"):
return Failure(f"{path} → MATTERMOST_URL must start with https://, so the token is never sent in the clear")
return Config(url.rstrip("/"), token, recipient)
def parse_env(text: str) -> dict[str, str]:
values = {}
for line in text.splitlines():
key, equals, value = line.partition("=")
if not equals or key.lstrip().startswith("#"):
continue
value = value.strip()
if len(value) >= 2 and value[0] == value[-1] and value[0] in "'\"":
value = value[1:-1]
values[key.strip()] = value
return values
def send(config: Config, message: str, http: Http) -> Failure | None:
api = f"{config.url}/api/v4"
bot = id_of(http("GET", f"{api}/users/me", config.token, None), "GET /api/v4/users/me")
@@ -92,33 +58,12 @@ 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; a Failure naming the server where it cannot be reached, and the request where it answers an error, breaks HTTP or answers something other than JSON."""
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": f"Bearer {token}", "Content-Type": "application/json"}, method=method)
try:
with OPENER.open(request, timeout=TIMEOUT) as response:
raw = response.read()
except urllib.error.HTTPError as failure:
with failure:
return Failure(f"{request_name} answered {failure.code}: {error_message(failure) or failure.reason}")
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)}")
try:
return json.loads(raw)
except ValueError:
return Failure(f"{request_name} answered with something other than JSON")
"""The JSON that url answers to the bot's request, or a Failure saying why there is none."""
return json_request.http_json(method, url, f"Bearer {token}", body, TIMEOUT, error_message)
def error_message(failure: urllib.error.HTTPError) -> str:
"""Mattermost's message in an error answer; empty where the body is cut short, breaks HTTP or holds none."""
try:
answer = json.loads(failure.read())
except (http.client.HTTPException, OSError, ValueError):
return ""
def error_message(answer: object) -> str:
"""Mattermost's message in the JSON of an error answer; empty where it holds none."""
message = answer.get("message") if isinstance(answer, dict) else None
return message if isinstance(message, str) else ""
+9 -93
View File
@@ -1,13 +1,9 @@
import contextlib
import http.server
import io
import json
import pathlib
import socket
import subprocess
import sys
import tempfile
import threading
import unittest
import unittest.mock
@@ -111,97 +107,17 @@ class Send(unittest.TestCase):
self.assertEqual(dm.send(CONFIG, "Which one?", server), Failure("POST /api/v4/posts answered 403: You do not have the appropriate permissions."))
class Recorded(http.server.BaseHTTPRequestHandler):
"""Answers each request with the server's next scripted status and body, recording what it got."""
def do_GET(self) -> None:
self.answer()
def do_POST(self) -> None:
self.answer()
def answer(self) -> None:
length = int(self.headers.get("Content-Length") or 0)
self.server.got.append((self.command, self.path, dict(self.headers), self.rfile.read(length))) # type: ignore[attr-defined]
status, body = self.server.script.pop(0) # type: ignore[attr-defined]
if status is None:
# Raw bytes, as a server that breaks HTTP sends them.
self.wfile.write(body)
self.close_connection = True
return
self.send_response(status)
if 300 <= status < 400:
self.send_header("Location", "/elsewhere")
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfile.write(body)
def log_message(self, format: str, *args: object) -> None:
pass
class HttpJson(unittest.TestCase):
def serve(self, *script: tuple[int, bytes]) -> str:
server = http.server.HTTPServer(("127.0.0.1", 0), Recorded)
server.script = list(script) # type: ignore[attr-defined]
server.got = [] # type: ignore[attr-defined]
threading.Thread(target=server.serve_forever, daemon=True).start()
self.addCleanup(server.server_close)
self.addCleanup(server.shutdown)
self.server = server
return f"http://127.0.0.1:{server.server_port}"
def test_sends_the_token_as_a_bearer_and_reads_mattermosts_message_from_an_error(self):
with unittest.mock.patch.object(dm.json_request, "http_json", return_value={"id": "post-id"}) as sent:
self.assertEqual(dm.http_json("POST", "https://chat.example/api/v4/posts", "secret-token", {"message": "hi"}), {"id": "post-id"})
sent.assert_called_once_with("POST", "https://chat.example/api/v4/posts", "Bearer secret-token", {"message": "hi"}, dm.TIMEOUT, dm.error_message)
self.assertEqual(dm.TIMEOUT, 10)
def test_sends_the_token_as_a_bearer_and_the_body_as_json_and_reads_the_json_answer(self):
base = self.serve((201, b'{"id": "post-id"}'))
self.assertEqual(dm.http_json("POST", f"{base}/api/v4/posts", "secret-token", {"message": "hi"}), {"id": "post-id"})
[(method, path, headers, body)] = self.server.got # type: ignore[attr-defined]
self.assertEqual((method, path, headers["Authorization"], headers["Content-Type"], json.loads(body)), ("POST", "/api/v4/posts", "Bearer secret-token", "application/json", {"message": "hi"}))
def test_names_the_request_the_status_and_mattermosts_message_on_an_error(self):
base = self.serve((401, b'{"message": "Invalid or expired session, please login again."}'))
self.assertEqual(dm.http_json("GET", f"{base}/api/v4/users/me", "bad", None), Failure("GET /api/v4/users/me answered 401: Invalid or expired session, please login again."))
def test_follows_no_redirect_so_the_token_goes_only_to_the_server_named(self):
base = self.serve((302, b"{}"))
self.assertEqual(dm.http_json("GET", f"{base}/api/v4/users/me", "t", None), Failure("GET /api/v4/users/me answered 302: Found"))
self.assertEqual(len(self.server.got), 1) # type: ignore[attr-defined]
def test_sends_no_body_with_a_get(self):
base = self.serve((200, b'{"id": "bot-id"}'))
dm.http_json("GET", f"{base}/api/v4/users/me", "t", None)
[(_, _, headers, body)] = self.server.got # type: ignore[attr-defined]
self.assertEqual((headers.get("Content-Length"), body), (None, b""))
def test_fails_on_an_answer_that_breaks_http(self):
for raw in (b"garbage\r\n\r\n", b"HTTP/1.1 200 OK\r\nContent-Length: 100\r\n\r\n{}"):
with self.subTest(raw=raw):
base = self.serve((None, raw))
failed = dm.http_json("GET", f"{base}/api/v4/users/me", "t", None)
self.assertTrue(isinstance(failed, Failure) and failed.reason.startswith("GET /api/v4/users/me got a broken answer: "), failed)
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(dm.http_json("GET", f"{base}/api/v4/users/me", "t", None), Failure("GET /api/v4/users/me answered 500: Internal Server Error"))
def test_gives_up_on_a_server_that_never_answers_after_the_timeout(self):
silent = socket.socket()
self.addCleanup(silent.close)
silent.bind(("127.0.0.1", 0))
silent.listen(1)
base = f"http://127.0.0.1:{silent.getsockname()[1]}"
with unittest.mock.patch.object(dm, "TIMEOUT", 0.2):
self.assertEqual(dm.http_json("GET", f"{base}/api/v4/users/me", "t", None), Failure(f"cannot reach {base}: timed out"))
def test_fails_on_an_answer_that_is_not_json(self):
base = self.serve((200, b"<html>"))
self.assertEqual(dm.http_json("GET", f"{base}/api/v4/users/me", "t", None), Failure("GET /api/v4/users/me answered with something other than JSON"))
def test_fails_naming_the_server_it_cannot_reach(self):
base = self.serve()
self.server.server_close()
failed = dm.http_json("GET", f"{base}/api/v4/users/me", "t", None)
self.assertIsInstance(failed, Failure)
self.assertTrue(str(getattr(failed, "reason", "")).startswith(f"cannot reach {base}: "), failed)
def test_reads_mattermosts_message_from_an_error_answer(self):
for answer, message in (({"message": "Invalid or expired session."}, "Invalid or expired session."), ({"message": 7}, ""), ({}, ""), (["message"], "")):
with self.subTest(answer=answer):
self.assertEqual(dm.error_message(answer), message)
class Project(unittest.TestCase):
+219
View File
@@ -0,0 +1,219 @@
"""A plan kept as the child issues of one Jira Cloud epic, read 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."""
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 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.
KEYS = ("ATLASSIAN_EMAIL", "ATLASSIAN_API_TOKEN")
# The issue property that holds an item's scores, as a JSON object such as {"L": 2, "E": 2, "I": 3, "S": 3, "Moves": "1.6 by 4", "Exempt": ""}.
PROPERTY = "plan-item"
ISSUE_KEY = re.compile(r"([A-Z][A-Z0-9_]*)-([0-9]+)")
# Seconds each connect and each read may wait.
TIMEOUT = 30
PAGE = 100
# The pages one read asks for at most, so an answer that never names a last page ends the read.
MAX_PAGES = 100
READ_ONLY = "a plan in Jira is only read so far: file, edit and finish its issues in Jira"
# 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.
Http = typing.Callable[[str, str, str, object], object]
ToMarkdown = typing.Callable[[list[dict[str, typing.Any]]], list[str] | Refused | Failure]
def http_json(method: str, url: str, authorization: str, body: object) -> object:
return json_request.http_json(method, url, authorization, body, TIMEOUT, error_message)
def error_message(answer: object) -> str:
"""Jira's messages in the JSON of an error answer; empty where it holds none."""
if not isinstance(answer, dict):
return ""
messages, errors = answer.get("errorMessages"), answer.get("errors")
found = [*(messages if isinstance(messages, list) else []), *(errors.values() if isinstance(errors, dict) else [])]
return "; ".join(text for text in found if isinstance(text, str))
@dataclasses.dataclass(frozen=True)
class Issue:
"""A child issue as Jira answered it, checked to hold what an item is read from."""
key: str
summary: str
description: dict[str, typing.Any] | None
fix_versions: tuple[str, ...]
# The key of each issue this one "is blocked by".
blockers: tuple[str, ...]
# PROPERTY's value; an empty object where the issue holds none.
scores: object
@property
def number(self) -> int:
return number(self.key)
@dataclasses.dataclass(frozen=True)
class JiraPlan:
"""The plan under epic, read with the credentials env_file holds."""
epic: Epic
env_file: pathlib.Path
http: Http = http_json
to_markdown: ToMarkdown = adfs_to_markdown
@property
def label(self) -> str:
return self.epic.spelling
@property
def tracked(self) -> str | None:
return None
def read(self) -> Plan | Failure:
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
issues = [issue_of(raw) for raw in answered]
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)
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)
def basic_auth(env_file: pathlib.Path) -> str | Failure:
"""The Authorization header for the email and API token that env_file holds."""
values = read_env(env_file, KEYS, "an API token")
if isinstance(values, Failure):
return values
return "Basic " + base64.b64encode(":".join(values[key] for key in KEYS).encode()).decode()
def children(epic: Epic, authorization: str, http: Http) -> list[object] | Failure:
"""The epic's open child issues in backlog order, which is the order the team ranks them in. An issue in a done status is a finished item, so it is no longer in the plan."""
# The search answers no issues for an epic the account cannot see, as for one whose children are all done; asking for the epic itself tells them apart.
seen = http("GET", f"{epic.site}/rest/api/3/issue/{epic.key}?fields=summary", authorization, None)
if isinstance(seen, Failure):
return Failure(f"cannot read the epic {epic.key}: {seen.reason}")
body: dict[str, object] = {
"jql": f'parent = "{epic.key}" AND statusCategory != Done ORDER BY Rank ASC',
"fields": ["summary", "description", "fixVersions", "issuelinks"],
"properties": [PROPERTY],
"maxResults": PAGE,
}
found: list[object] = []
for _ in range(MAX_PAGES):
page = http("POST", f"{epic.site}/rest/api/3/search/jql", authorization, body)
if isinstance(page, Failure):
return page
if not isinstance(page, dict) or not isinstance(page.get("issues"), list):
return Failure("the search answered something other than a page of issues")
found += page["issues"]
if not page.get("nextPageToken"):
return found
body = body | {"nextPageToken": page["nextPageToken"]}
return Failure(f"the search for {epic.key}'s children did not end within {MAX_PAGES} pages")
def issue_of(raw: object) -> Issue | Failure:
"""The issue in one entry of the search's answer, or which issue is not in the shape Jira documents, and how."""
key = raw.get("key") if isinstance(raw, dict) else None
if not isinstance(key, str) or not ISSUE_KEY.fullmatch(key):
return Failure("the search answered an issue without an issue key")
try:
fields = typing.cast(dict[str, typing.Any], raw)["fields"]
blockers = tuple(link["inwardIssue"]["key"] for link in fields["issuelinks"] if "inwardIssue" in link and link["type"]["inward"] == "is blocked by")
issue = Issue(key, fields["summary"].strip(), fields["description"], tuple(version["name"] for version in fields["fixVersions"]), blockers, typing.cast(dict[str, typing.Any], raw).get("properties", {}).get(PROPERTY, {}))
except (AttributeError, KeyError, TypeError) as failure:
return Failure(f"{key} is not in the shape Jira Cloud's REST API version 3 documents: {failure!r}")
if not isinstance(issue.description, dict | None) or not all(isinstance(name, str) for name in issue.fix_versions + issue.blockers) or not all(ISSUE_KEY.fullmatch(blocker) for blocker in issue.blockers):
return Failure(f"{key} is not in the shape Jira Cloud's REST API version 3 documents: its description, a Fix Version's name or a linked issue's key holds another kind of value")
return issue
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]:
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]
if failed := next((found for found in items if isinstance(found, Failure)), None):
return failed
# The descriptions convert last, since that costs a container run, which a read that fails doesn't need.
texts = details(issues, epic, to_markdown)
if isinstance(texts, Failure):
return texts
return Plan([dataclasses.replace(found, detail=texts.get(found.id, "")) for found in items if isinstance(found, Item)])
def number(key: str) -> int:
return int(key.rpartition("-")[2])
def details(issues: list[Issue], epic: Epic, to_markdown: ToMarkdown) -> dict[int, str] | Failure:
"""Each described issue's description as markdown, under the issue's number, all converted at once."""
described = [(issue, issue.description) for issue in issues if issue.description is not None]
texts = to_markdown([description for _, description in described])
if isinstance(texts, Refused):
return Failure(f"{described[texts.index][0].key}'s description: {texts.failure.reason}")
if isinstance(texts, Failure):
return Failure(f"cannot convert the descriptions of {epic.key}'s children to markdown: {texts.reason}")
return {issue.number: text.strip() for (issue, _), text in zip(described, texts)}
def item(issue: Issue, project: str, ids: set[int]) -> Item | Failure:
"""The item an issue holds, without its detail. It is blocked by each of its blockers among ids, the plan's items: a blocker that is done or lies outside the epic doesn't make the item wait."""
release = earliest_release(issue.fix_versions)
if release is None:
# Until a project can tie its releases to something other than semver versions, an item with no release cannot be placed in the plan.
return Failure(f"{issue.key} names no Fix Version that is a semver version, such as 1.2.0; set one in Jira")
scored = scores(issue.key, issue.scores)
if isinstance(scored, Failure):
return scored
blockers = {number(key) for key in issue.blockers if key.rpartition("-")[0] == project}
return Item(issue.number, release, scored[2], bold_cell(issue.summary), scored[0], scored[1], tuple(sorted(blockers & ids)), "")
def earliest_release(names: tuple[str, ...]) -> Release | None:
"""The earliest release among Fix Versions named as a semver version, with a leading v or without; None where none is."""
releases = [release for name in names if (release := parsed(name) or tagged(name))]
return min(releases, default=None)
def scores(key: str, held: object) -> tuple[dict[str, int], typing.Any, typing.Any] | Failure:
"""The scores, Moves and Exempt that an issue's PROPERTY value holds, each in the format the items table of a todo.md takes."""
if not isinstance(held, dict):
return Failure(f"{key}'s issue property {PROPERTY} is not a JSON object")
named = {name: str(value) for name, value in held.items()}
levels = parse_scores(key, named, SHAPE.score_columns)
if isinstance(levels, Failure):
return levels
moves = parse_moves(key, named.get(MOVES, ""))
if isinstance(moves, Failure):
return moves
exempt = named.get("Exempt", "")
if not is_exempt(exempt):
return Failure(f"{key}'s issue property {PROPERTY} holds the Exempt {exempt!r}, which is not empty or one of {', '.join(EXEMPTIONS[1:])}")
return levels, moves, exempt
+25 -12
View File
@@ -1,19 +1,20 @@
"""The one way a tool reads or writes a project's plan: through the store its config names.
The config's `plan` setting names the backend. A path names a markdown file, todo.md, the only backend so far. 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 `jira_epic` reads and nothing writes yet. An agent reads and changes the plan with `todo-item`, which works through the same store.
A tool that reads what a past commit held, such as `score-outcomes`, still parses that commit's todo.md itself, with `release_plan.todo_table`: only the markdown backend has commits, and todo.md's items 365, 366 and 368 port those tools to the other backends."""
import dataclasses
import decimal
import pathlib
import typing
from release_plan.todo_table import BLOCKED_BY, Item, item_details, items, MOVES, NoItemsTable, renames
from failure import Failure
from git_cli.git_repo import file_at, git, Git
from record_store.stores import goals_store, store as record_store, RecordStore
from plan_store import markdown_edits
from project_config.settings import ProjectConfig
from release_plan import ranking
from record_store.stores import store as record_store, RecordStore
from release_plan.release import Release
from text_files.file_writes import replace_file
@@ -22,8 +23,10 @@ TAGLINE = "Tagline"
FIELDS = ("Release", BLOCKED_BY, "Exempt", TAGLINE, "L", "E", "I", "S", MOVES)
# What a missing todo.md's reader is told.
# What the reader of a missing todo.md is told.
MISSING = "every project keeps a todo.md, and rank_todo.py --help shows one"
# What the reader of a missing or empty goals file is told.
GOALS_HINT = "rank_todo.py weighs goals from the goals file the project's config names as goals-and-audience"
@dataclasses.dataclass(frozen=True)
@@ -44,7 +47,7 @@ class Written:
class PlanStore(typing.Protocol):
"""A project's plan. plan_store.contract holds every backend to the same behaviour. 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` only reads until todo.md's item 352. A write that fails leaves the plan as it was."""
@property
def label(self) -> str:
@@ -69,12 +72,14 @@ class PlanStore(typing.Protocol):
@dataclasses.dataclass(frozen=True)
class FilePlan:
"""A plan kept as a markdown file at path, in the shape `rank_todo.py --help` shows. Every write ranks the file, reading the goals file at goals, the decision log and the comprehension history."""
"""A plan kept as a markdown file at path, in the shape `rank_todo.py --help` shows. Every write ranks the file, reading the goals file from goals, the decision log and the comprehension history."""
path: pathlib.Path
tracked: str | None
goals: pathlib.Path
goals: RecordStore
decisions: RecordStore
history: RecordStore
# The project's readability floor: while the comprehension overall is under it, ranking weighs code health 4 times as much.
floor: decimal.Decimal
@property
def label(self) -> str:
@@ -102,7 +107,7 @@ class FilePlan:
def kept(self, id_: int, text: str, texts: tuple[str, str, str, str]) -> Written | Failure:
"""Ranks text, the file with item id_ filed or edited, and writes it where the item scores at the bar or above."""
ranked = ranking.rank(text, *texts[1:])
ranked = ranking.rank(text, *texts[1:], self.floor)
if isinstance(ranked, Failure):
return ranked
# The write may lower another item under the bar, which the notes then say; the write is refused only where the written item itself scores under the bar.
@@ -117,7 +122,7 @@ class FilePlan:
text = markdown_edits.finished(texts[0], id_, self.label)
if isinstance(text, Failure):
return text
ranked = ranking.rank(text, *texts[1:])
ranked = ranking.rank(text, *texts[1:], self.floor)
return ranked if isinstance(ranked, Failure) else self.written(id_, ranked)
def written(self, id_: int, ranked: ranking.Ranked) -> Written | Failure:
@@ -128,13 +133,15 @@ class FilePlan:
return Written(id_, tuple(f"{self.path}: {line}" for line in ranked.notes + ranked.under_bar))
def texts(self) -> tuple[str, str, str, str] | Failure:
"""What ranking reads: the file, the goals file, the decision log and the comprehension history. The last two are empty when missing; a missing plan or goals file is a Failure."""
"""What ranking reads: the file, the goals file, the decision log and the comprehension history. The last two are empty when missing; a missing plan, or a goals file that is missing or empty, is a Failure."""
plan = read_text(self.path, MISSING)
if isinstance(plan, Failure):
return plan
goals = read_text(self.goals, "rank_todo.py weighs goals from the file the project's config names as goals-and-audience")
goals = self.goals.read()
if isinstance(goals, Failure):
return goals
if not goals:
return Failure(f"{self.goals.label}: missing or empty; {GOALS_HINT}")
decisions = self.decisions.read()
if isinstance(decisions, Failure):
return decisions
@@ -144,12 +151,18 @@ class FilePlan:
def store(config: ProjectConfig) -> PlanStore:
"""The store config names for the plan."""
return file_plan(config)
if config.epic is None:
return file_plan(config)
# Imported here, since jira_epic builds on this module's Plan and Written.
from plan_store.jira_epic import JiraPlan
# load refuses a config that names an epic and no env-file.
assert config.env_file is not None
return JiraPlan(config.epic, config.env_file)
def file_plan(config: ProjectConfig, path: pathlib.Path | None = None) -> FilePlan:
"""The markdown file config names as its plan, for a tool that works on the file itself, as ranking does. path stands in for the configured one where given."""
return FilePlan(path or config.paths["plan"], config.tracked("plan"), config.paths["goals-and-audience"], record_store(config, "decisions"), record_store(config, "comprehension-history"))
return FilePlan(path or config.paths["plan"], config.tracked("plan"), goals_store(config), record_store(config, "decisions"), record_store(config, "comprehension-history"), config.readability_floor)
def held_at(revision: str, plan: PlanStore, cwd: str, run: Git = git) -> Plan | Failure:
+243
View File
@@ -0,0 +1,243 @@
import base64
import pathlib
import sys
import tempfile
import unittest
import unittest.mock
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from project_config.settings import Epic
from failure import Failure
from plan_store import jira_epic
from plan_store.stores import Plan
from adf_codec.convert import Refused
from release_plan.release import release_of
EPIC = Epic("https://acme.atlassian.net", "ABC-12")
SEARCH = "https://acme.atlassian.net/rest/api/3/search/jql"
AUTHORIZATION = "Basic " + base64.b64encode(b"me@example.com:s3cret").decode()
def issue(key: str, summary: str = "Count the runs.", versions: tuple[str, ...] = ("0.1.0",), scores: dict[str, object] | None = None, blocked_by: tuple[str, ...] = (), description: object = None, blocks: tuple[str, ...] = ()) -> dict[str, object]:
links = [{"type": {"inward": "is blocked by", "outward": "blocks"}, "inwardIssue": {"key": blocker}} for blocker in blocked_by]
links += [{"type": {"inward": "is blocked by", "outward": "blocks"}, "outwardIssue": {"key": blocked}} for blocked in blocks]
return {
"key": key,
"fields": {"summary": summary, "description": description, "fixVersions": [{"name": name} for name in versions], "issuelinks": links},
"properties": {} if scores is None else {jira_epic.PROPERTY: scores},
}
def adf(text: str) -> dict[str, object]:
return {"type": "doc", "version": 1, "content": [{"type": "paragraph", "content": [{"type": "text", "text": text}]}]}
def text_of(document: dict[str, object]) -> str | Failure:
"""Stands in for the adf-codec shim: the text of the one paragraph adf builds."""
return document["content"][0]["content"][0]["text"] + "\n" # type: ignore[index]
class JiraPlan(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.pages: list[object] = []
self.calls: list[tuple[str, str, str, object]] = []
self.epic: object = {"key": "ABC-12"}
self.epic_calls: list[tuple[str, str, str, object]] = []
self.converted: list[list[dict[str, object]]] = []
def http(self, method: str, url: str, authorization: str, body: object) -> object:
"""Stands in for Jira: answers self.epic to the request for the epic, and the next of self.pages to each search."""
if method == "GET":
self.epic_calls.append((method, url, authorization, body))
return self.epic
self.calls.append((method, url, authorization, body))
return self.pages[len(self.calls) - 1]
def to_markdown(self, documents: list[dict[str, object]]) -> list[str] | Refused | Failure:
self.converted.append(documents)
return [text_of(document) for document in documents]
def store(self) -> jira_epic.JiraPlan:
return jira_epic.JiraPlan(EPIC, self.env, self.http, self.to_markdown)
def read(self, *issues: dict[str, object]) -> Plan | Failure:
self.pages, self.calls = [{"issues": list(issues)}], []
return self.store().read()
def items(self, *issues: dict[str, object]):
plan = self.read(*issues)
assert isinstance(plan, Plan), plan
return plan.items
def test_an_epic_with_no_open_child_reads_as_an_empty_plan(self):
self.assertEqual(self.read(), Plan([]))
def test_asks_for_the_epics_open_children_in_backlog_order_with_basic_auth(self):
self.read()
method, url, authorization, body = self.calls[0]
self.assertEqual((method, url), ("POST", SEARCH))
self.assertEqual(authorization, AUTHORIZATION)
self.assertEqual(body, {
"jql": 'parent = "ABC-12" AND statusCategory != Done ORDER BY Rank ASC',
"fields": ["summary", "description", "fixVersions", "issuelinks"],
"properties": ["plan-item"],
"maxResults": 100,
})
def test_an_epic_that_cannot_be_read_fails_the_read_before_any_search(self):
self.epic = Failure("GET /rest/api/3/issue/ABC-12 answered 404: Issue does not exist or you do not have permission to see it.")
self.assertEqual(self.read(), Failure("cannot read the epic ABC-12: GET /rest/api/3/issue/ABC-12 answered 404: Issue does not exist or you do not have permission to see it."))
self.assertEqual(self.epic_calls, [("GET", "https://acme.atlassian.net/rest/api/3/issue/ABC-12?fields=summary", AUTHORIZATION, None)])
self.assertEqual(self.calls, [])
def test_an_issue_reads_as_an_item_under_its_number(self):
scores = {"L": 1, "E": 2, "I": 3, "S": 1, "Moves": "1 by 9", "Exempt": "owner"}
item, = self.items(issue("ABC-34", "Count the runs.", ("0.1.0",), scores, description=adf("Why it counts.")))
self.assertEqual((item.id, item.release, item.tagline, item.detail), (34, release_of("0.1.0"), "**Count the runs.**", "Why it counts."))
self.assertEqual((item.scores, item.moves, item.exempt, item.blocked_by), ({"L": 1, "E": 2, "I": 3, "S": 1}, (("1", 9),), "owner", ()))
def test_keeps_jiras_order_whatever_the_releases_and_scores(self):
found = self.items(issue("ABC-40", versions=("0.2.0",)), issue("ABC-7", versions=("0.1.0",)), issue("ABC-21", versions=("0.3.0",)))
self.assertEqual([item.id for item in found], [40, 7, 21])
def test_an_issue_nobody_scored_reads_without_scores(self):
bare = issue("ABC-35")
del bare["properties"]
for item in self.items(issue("ABC-34"), bare):
with self.subTest(item=item.id):
self.assertEqual((item.scores, item.moves, item.exempt, item.detail, item.likelihood), ({}, (), "", "", 0))
def test_an_issue_is_blocked_by_each_blocker_still_in_the_plan(self):
blocked, _ = self.items(issue("ABC-34", blocked_by=("ABC-35", "ABC-2", "OTHER-9"), blocks=("ABC-35",)), issue("ABC-35", blocks=("ABC-34",)))
self.assertEqual(blocked.blocked_by, (35,))
def test_the_release_is_the_earliest_fix_version_with_or_without_a_v(self):
for versions in (("v1.2.0", "0.9.1", "Later"), ("1.2.0", "v0.9.1")):
with self.subTest(versions=versions):
item, = self.items(issue("ABC-34", versions=versions))
self.assertEqual(item.release, release_of("0.9.1"))
def test_an_issue_with_no_semver_fix_version_fails_the_read_naming_it(self):
for versions in ((), ("Sprint 4",)):
with self.subTest(versions=versions):
failure = self.read(issue("ABC-33", description=adf("Why.")), issue("ABC-34", versions=versions))
self.assertEqual(failure, Failure("ABC-34 names no Fix Version that is a semver version, such as 1.2.0; set one in Jira"))
self.assertEqual(self.converted, [])
def test_a_child_in_another_jira_project_fails_the_read_naming_it(self):
failure = self.read(issue("ABC-34"), issue("OTHER-5"))
self.assertIsInstance(failure, Failure)
self.assertIn("OTHER-5", failure.reason) # type: ignore[union-attr]
def test_scores_out_of_format_fail_the_read_naming_the_issue(self):
for scores in ({"L": 9}, {"L": "high"}, {"Moves": "everything"}, {"Exempt": "because"}, "L 3"):
with self.subTest(scores=scores):
failure = self.read(issue("ABC-34", scores=scores)) # type: ignore[arg-type]
self.assertIsInstance(failure, Failure)
self.assertIn("ABC-34", failure.reason) # type: ignore[union-attr]
def test_an_exempt_out_of_format_fails_naming_the_reasons_it_may_hold(self):
self.assertEqual(self.read(issue("ABC-34", scores={"Exempt": "because"})), Failure("ABC-34's issue property plan-item holds the Exempt 'because', which is not empty or one of decision, defect, owner, principle, question, security"))
def test_reads_every_page(self):
self.pages = [{"issues": [issue("ABC-1")], "nextPageToken": "t1"}, {"issues": [issue("ABC-2")]}]
plan = self.store().read()
self.assertEqual([item.id for item in plan.items], [1, 2]) # type: ignore[union-attr]
self.assertNotIn("nextPageToken", self.calls[0][3]) # type: ignore[operator]
self.assertEqual(self.calls[1][3]["nextPageToken"], "t1") # type: ignore[index]
def test_a_failing_request_fails_the_read(self):
self.pages = [Failure("POST /rest/api/3/search/jql answered 401: no")]
self.assertEqual(self.store().read(), Failure("POST /rest/api/3/search/jql answered 401: no"))
def test_an_answer_in_another_shape_fails_the_read(self):
no_page, no_key = "the search answered something other than a page of issues", "the search answered an issue without an issue key"
for page, reason in (([], no_page), ({"issues": "none"}, no_page), ({"issues": ["ABC-1"]}, no_key), ({"issues": [{"key": 7, "fields": {}}]}, no_key), ({"issues": [{"key": "abc", "fields": {}}]}, no_key)):
with self.subTest(page=page):
self.pages, self.calls = [page], []
self.assertEqual(self.store().read(), Failure(reason))
def test_a_search_that_never_names_a_last_page_fails_the_read(self):
self.pages = [{"issues": [], "nextPageToken": "more"}] * 2
with unittest.mock.patch.object(jira_epic, "MAX_PAGES", 2):
self.assertEqual(self.store().read(), Failure("the search for ABC-12's children did not end within 2 pages"))
def test_an_issue_in_another_shape_fails_the_read_naming_it(self):
good = issue("ABC-1")
for wrong in ({"key": "ABC-1"}, issue("ABC-1", summary=None), issue("ABC-1", description="text"), good | {"fields": good["fields"] | {"fixVersions": [{"name": 7}]}}, good | {"fields": good["fields"] | {"issuelinks": [{"type": {"inward": "is blocked by"}, "inwardIssue": {"key": 7}}]}}, good | {"fields": good["fields"] | {"issuelinks": [{"type": {"inward": "is blocked by"}, "inwardIssue": {"key": "ABC-x"}}]}}, good | {"properties": None}): # type: ignore[arg-type, operator]
with self.subTest(wrong=wrong):
failure = self.read(wrong) # type: ignore[arg-type]
self.assertIsInstance(failure, Failure)
self.assertTrue(failure.reason.startswith("ABC-1 is not in the shape Jira Cloud's REST API version 3 documents: "), failure) # type: ignore[union-attr]
def test_converts_every_description_in_one_run_and_none_for_an_issue_without_one(self):
found = self.items(issue("ABC-1", description=adf("One.")), issue("ABC-2"), issue("ABC-3", description=adf("Three.")), issue("ABC-4", description=adf("Four.")))
self.assertEqual([item.detail for item in found], ["One.", "", "Three.", "Four."])
self.assertEqual(self.converted, [[adf("One."), adf("Three."), adf("Four.")]])
def test_a_description_the_codec_refuses_fails_the_read_naming_the_issue(self):
store = jira_epic.JiraPlan(EPIC, self.env, self.http, lambda documents: Refused(1, Failure("adf-codec refused")))
self.pages = [{"issues": [issue("ABC-33", description=adf("x")), issue("ABC-34"), issue("ABC-35", description=adf("y"))]}]
self.assertEqual(store.read(), Failure("ABC-35's description: adf-codec refused"))
def test_a_codec_that_cannot_run_fails_the_read(self):
store = jira_epic.JiraPlan(EPIC, self.env, self.http, lambda documents: Failure("docker is not installed"))
self.pages = [{"issues": [issue("ABC-34", description=adf("x"))]}]
self.assertEqual(store.read(), Failure("cannot convert the descriptions of ABC-12's children to markdown: docker is not installed"))
def test_an_env_file_without_the_credentials_fails_before_any_request(self):
self.env.write_text("ATLASSIAN_EMAIL=me@example.com\n")
failure = self.read()
self.assertIsInstance(failure, Failure)
self.assertIn("ATLASSIAN_API_TOKEN", failure.reason) # type: ignore[union-attr]
self.assertEqual(self.calls + self.epic_calls, [])
def test_an_env_file_others_may_read_fails_before_any_request(self):
self.env.chmod(0o644)
self.assertEqual(self.read(), Failure(f"{self.env} holds an API token, so only its owner may read it; run chmod 600 {self.env}"))
self.assertEqual(self.calls + self.epic_calls, [])
def test_a_missing_env_file_fails(self):
self.env.unlink()
self.assertIsInstance(self.read(), Failure)
def test_no_failure_holds_the_token(self):
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"))
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))
class Requests(unittest.TestCase):
def test_sends_each_request_through_the_shared_client_with_jiras_error_messages(self):
with unittest.mock.patch.object(jira_epic.json_request, "http_json", return_value={"issues": []}) as sent:
self.assertEqual(jira_epic.http_json("POST", SEARCH, AUTHORIZATION, {"jql": "x"}), {"issues": []})
sent.assert_called_once_with("POST", SEARCH, AUTHORIZATION, {"jql": "x"}, 30, jira_epic.error_message)
def test_reads_jiras_messages_from_an_error_answer(self):
cases = (
({"errorMessages": ["Issue does not exist or you do not have permission to see it."], "errors": {}}, "Issue does not exist or you do not have permission to see it."),
({"errorMessages": ["One."], "errors": {"jql": "Two."}}, "One.; Two."),
({"errorMessages": "One.", "errors": ["Two."]}, ""),
({"errorMessages": [7, "One."]}, "One."),
(["One."], ""),
)
for answer, message in cases:
with self.subTest(answer=answer):
self.assertEqual(jira_epic.error_message(answer), message)
if __name__ == "__main__":
unittest.main()
+38 -3
View File
@@ -1,4 +1,5 @@
import dataclasses
import decimal
import os
import pathlib
import sys
@@ -7,12 +8,15 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from project_config.settings import DEFAULT_FLOOR, Epic, ProjectConfig, SETTINGS
from failure import Failure
from plan_store.contract import FIRST, PlanStoreContract, SECOND
from record_store.stores import FileStore
from plan_store.contract import FIRST, MOVES, PlanStoreContract, SECOND
from plan_store.jira_epic import JiraPlan
from plan_store.fakes import MemoryPlan
from record_store.fakes import MemoryStore
from release_plan.todo_table import NoItemsTable
from release_plan.test_ranking import README
from release_plan.test_ranking import README, SCORED, VOID
from release_plan.release import release_of
from plan_store import stores
@@ -31,7 +35,7 @@ class FilePlanContract(PlanStoreContract, unittest.TestCase):
def new_store(self) -> stores.FilePlan:
(self.folder / "todo.md").write_text(EMPTY)
(self.folder / "README.md").write_text(README)
return stores.FilePlan(self.folder / "todo.md", "todo.md", self.folder / "README.md", MemoryStore(), MemoryStore())
return stores.FilePlan(self.folder / "todo.md", "todo.md", FileStore(self.folder / "README.md", None), MemoryStore(), MemoryStore(), DEFAULT_FLOOR)
class FilePlan(FilePlanContract):
@@ -146,6 +150,18 @@ class FilePlan(FilePlanContract):
self.assertEqual(store.add(FIRST, ""), Failure("no history"))
def test_ranks_every_write_with_its_floor(self):
# At an overall of 6.50 code health weighs 4 times under the default floor of 7.0, and once at a floor of 6.0.
def health_row(floor):
store = dataclasses.replace(self.new_store(), history=MemoryStore(SCORED.format(overall="6.50")), floor=decimal.Decimal(floor))
(self.folder / "README.md").write_text(README.replace(VOID, ""))
kept, finished = self.filed(store, FIRST | {MOVES: "code health by 1"}), self.filed(store, SECOND)
row = [line for line in (self.folder / "todo.md").read_text().splitlines() if line.startswith(f"| {kept} ")]
self.assertIsInstance(store.finish(finished), stores.Written)
self.assertIn(row[0], (self.folder / "todo.md").read_text())
return row[0]
self.assertNotEqual(health_row("6.0"), health_row("7.0"))
class HeldAt(unittest.TestCase):
def test_reads_the_revisions_file_where_commits_hold_the_plan(self):
shown = []
@@ -176,5 +192,24 @@ class HeldAt(unittest.TestCase):
self.assertEqual(stores.held_at("origin/main", MemoryPlan(tracked="todo.md"), "/checkout", run), Failure("no git"))
class Store(unittest.TestCase):
def config(self, **named) -> ProjectConfig:
paths = {name: pathlib.Path("/checkout", name) for name in SETTINGS[1:]}
return ProjectConfig("acme", pathlib.Path("/folder"), pathlib.Path("/checkout"), paths, **named)
def test_a_path_picks_the_markdown_file(self):
config = self.config()
picked = stores.store(dataclasses.replace(config, paths=config.paths | {"plan": pathlib.Path("/checkout/todo.md")}))
self.assertEqual((type(picked), picked.label, picked.tracked), (stores.FilePlan, "/checkout/todo.md", "todo.md"))
def test_the_markdown_file_ranks_with_the_configs_floor(self):
self.assertEqual(stores.file_plan(self.config(readability_floor=decimal.Decimal("6.5")), pathlib.Path("/checkout/todo.md")).floor, decimal.Decimal("6.5"))
def test_an_epic_picks_jira_with_the_env_files_credentials(self):
epic = Epic("https://acme.atlassian.net", "ABC-12")
picked = stores.store(self.config(epic=epic, env_file=pathlib.Path("/secrets/acme.env")))
self.assertEqual(picked, JiraPlan(epic, pathlib.Path("/secrets/acme.env"), picked.http))
if __name__ == "__main__":
unittest.main()
+44 -12
View File
@@ -21,6 +21,16 @@ starts with / or ~/. In a worktree, a "checkout:" path is the worktree's own fil
goals-and-audience = "folder:goals.md"
principles = "folder:principles"
`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.
`goals-and-audience` may name a Jira Cloud epic the same way, where `plan` names one too. The
epic's description is then the goals file, with ## Goals and ## Audience as headings, and
`project-config goals-and-audience` prints the setting as the config spells it. The description is
only read: edit it in Jira.
`env-file` is an optional setting: the file of KEY=value credentials the project's tools read,
a path that starts with / or ~/ and lies outside the checkout and the config's folder, such as
"~/.claude-projects/acme-billing.env". Where it is left out, the project has no credentials file, and
@@ -31,6 +41,18 @@ approval of the pull request, as its branch protection requires on GitHub, befor
false. `project-config wait-for-approval` prints true or false; the full listing shows the setting only where
it is true.
`tooling-on-host` is an optional setting, true or false: whether the loop may run the project's language
runtime, package manager, tests and task runner directly on the host, for a project with no container
setup. Left out, it is false, and they run through the project's container setup.
`readability-floor` is an optional setting, a number from 1 to 10: the comprehension score a project
aims for. While the panel's overall score is under it, code health weighs 4 times as much in the plan's
ranking, and a scoring run with a mean under it asks for a floor item. A legacy project, whose code
scores low, may lower it. Left out, it is 7.0.
`project-config tooling-on-host` and `project-config readability-floor` print their values; the full
listing shows each only where the config changes it from what it is when left out.
Four optional settings say how the project writes, for a project whose owners don't write as
~/.claude/CLAUDE.md does:
@@ -51,14 +73,25 @@ a title for its summary tries `commit-title`, then `pull-request-title`, then ta
`project-config <setting>` prints each one's value, and the full listing shows it only where the
config changes it from what it is when left out.
In a Jira plan an item's ID is its issue's number. To name a chunk by its issue key, write the
Jira project's key before {id}, as here for the key ABC:
branch = "ABC-{id}"
commit-title = "ABC-{id} - {summary}"
pull-request-title = "ABC-{id} - {summary}"
The chunk for the issue ABC-123 is then on the branch ABC-123, in the worktree <checkout>-ABC-123,
and its commits and pull request are titled "ABC-123 - …".
Exit 1, naming each fault on stderr, where no config names the checkout, or its config leaves out a
setting, names an unknown one, misspells a path, a language or a template, or sets `wait-for-approval` to anything but true or
false, and where `env-file` is asked for and not set. No path setting has a default.
setting, names an unknown one, misspells a path, a language or a template, sets `wait-for-approval` or
`tooling-on-host` to anything but true or false, or sets `readability-floor` to anything but a number
from 1 to 10, and where `env-file` is asked for and not set. No path setting has a default.
"""
import pathlib
import sys
from project_config.settings import CONFIG, ENV_FILE, load, OPTIONAL, ProjectConfig, SETTINGS, Unnamed, WAIT_FOR_APPROVAL
from project_config.settings import CONFIG, DEFAULT_FLOOR, ENV_FILE, load, 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
@@ -75,18 +108,22 @@ def main(argv: list[str]) -> int:
if isinstance(config, Failure):
print(config.reason, file=sys.stderr)
return 1
if argv == [WAIT_FOR_APPROVAL]:
print("true" if config.wait_for_approval else "false")
switches = {WAIT_FOR_APPROVAL: config.wait_for_approval, TOOLING_ON_HOST: config.tooling_on_host}
if argv and argv[0] in switches:
print("true" if switches[argv[0]] else "false")
return 0
if argv == [READABILITY_FLOOR]:
print(config.readability_floor)
return 0
if argv and argv[0] in config.texts:
print(config.texts[argv[0]])
return 0
paths = {**config.paths, **({ENV_FILE: config.env_file} if config.env_file else {})}
paths = {**config.places, **({ENV_FILE: str(config.env_file)} if config.env_file else {})}
if argv and argv[0] not in paths:
print(f"{config.folder / CONFIG} sets no `{ENV_FILE}`", file=sys.stderr)
return 1
defaults = ProjectConfig(config.key, config.folder, config.top, {}).texts
listed = [f"{name}: {path}" for name, path in paths.items()] + ([f"{WAIT_FOR_APPROVAL}: true"] if config.wait_for_approval else []) + [f"{name}: {text}" for name, text in config.texts.items() if text != defaults[name]]
listed = [f"{name}: {path}" for name, path in paths.items()] + [f"{name}: true" for name, on in switches.items() if on] + ([f"{READABILITY_FLOOR}: {config.readability_floor}"] if config.readability_floor != DEFAULT_FLOOR else []) + [f"{name}: {text}" for name, text in config.texts.items() if text != defaults[name]]
print(paths[argv[0]] if argv else "\n".join(listed))
return 0
@@ -114,8 +151,3 @@ def project() -> ProjectConfig | Failure:
"""The config of the project whose checkout holds the current directory, under the user's home."""
return located(None, pathlib.Path.home())
def goals_file(directory: str, home: pathlib.Path) -> pathlib.Path | Failure:
"""The file holding the premises, `## Goals` and `## Audience`, of the project whose checkout holds directory, as its config under home names it."""
config = located(directory, home)
return config if isinstance(config, Failure) else config.paths["goals-and-audience"]
+82 -7
View File
@@ -2,6 +2,8 @@
No path setting has a default, so that a client's project never runs on another project's files: a missing config or setting is a Failure that names it."""
import dataclasses
import decimal
import math
import pathlib
import re
import tomllib
@@ -17,14 +19,26 @@ SETTINGS = ("plan", "working-rules", "decisions", "score-anchors", "comprehensio
SPELLING = '"checkout:<path>" for a path in the checkout, "folder:<path>" for one in the config\'s folder, or a path that starts with / or ~/'
# A path setting a project may leave out: the file of KEY=value credentials its tools read. It has no default either: a project without it asks for no credentials, and never reads another project's.
ENV_FILE = "env-file"
# The optional boolean setting: whether `chunk-pr merge` waits for a human's approval of the pull request. False where left out.
# An optional boolean setting: whether `chunk-pr merge` waits for a human's approval of the pull request. False where left out.
WAIT_FOR_APPROVAL = "wait-for-approval"
# An optional boolean setting: whether the loop may run the project's language runtime, package manager, tests and task runner on the host, for a project with no container setup. False where left out.
TOOLING_ON_HOST = "tooling-on-host"
# An optional number setting: the comprehension score under which code health is very important. A legacy project, whose code scores low, may lower it.
READABILITY_FLOOR = "readability-floor"
# The floor where the config leaves it out, which every dimension and the overall should reach; docs/decisions.md → "comprehension floor" says it doesn't block anything.
DEFAULT_FLOOR = decimal.Decimal("7.0")
# The optional text settings. `language` is the language the project's prose is written in, by its English name. The others are templates, as `templates` says.
LANGUAGE = "language"
COMMIT_TITLE = "commit-title"
PULL_REQUEST_TITLE = "pull-request-title"
BRANCH = "branch"
OPTIONAL = (BRANCH, COMMIT_TITLE, ENV_FILE, LANGUAGE, PULL_REQUEST_TITLE, WAIT_FOR_APPROVAL)
OPTIONAL = (BRANCH, COMMIT_TITLE, ENV_FILE, LANGUAGE, PULL_REQUEST_TITLE, READABILITY_FLOOR, TOOLING_ON_HOST, 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',
}
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"
@@ -33,9 +47,21 @@ class Unnamed(Failure):
"""No config names a checkout here: none names the one asked for, or git finds no checkout. A reader of titles takes them bare there, as in a third party's clone; a config that is faulty or cannot be read is a plain Failure."""
@dataclasses.dataclass(frozen=True)
class Epic:
"""A Jira Cloud epic: site is its site's address, such as https://acme.atlassian.net, and key its issue key, such as ABC-12."""
site: str
key: str
@property
def spelling(self) -> str:
"""The epic as a config spells it."""
return f"{JIRA}{self.site}/browse/{self.key}"
@dataclasses.dataclass(frozen=True)
class ProjectConfig:
"""folder is `~/.claude-projects/<key>`, top is the worktree that asked, and paths holds each of SETTINGS as an absolute path."""
"""folder is `~/.claude-projects/<key>`, top is the worktree that asked, and paths holds each of SETTINGS as an absolute path, except `plan` and `goals-and-audience` where they are kept in Jira."""
key: str
folder: pathlib.Path
top: pathlib.Path
@@ -43,10 +69,32 @@ class ProjectConfig:
# The config's `env-file`, or None where it sets none.
env_file: pathlib.Path | None = None
wait_for_approval: bool = False
tooling_on_host: bool = False
readability_floor: decimal.Decimal = DEFAULT_FLOOR
language: str = "English"
commit_title: str = templates.TITLE
pull_request_title: str = templates.TITLE
branch: str = templates.BRANCH
# The epic whose child issues are the plan, where the config's `plan` names one.
epic: Epic | None = None
# The epic whose description holds the goals and audience, where the config's `goals-and-audience` names one.
goals_epic: Epic | None = None
@property
def plan_file(self) -> pathlib.Path | None:
"""The plan's file; None where the plan is kept in Jira."""
return self.paths.get("plan")
@property
def plan_label(self) -> str:
"""What a message calls the plan: its path, or the epic as the config spells it."""
return self.epic.spelling if self.epic else str(self.paths["plan"])
@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}
@property
def texts(self) -> dict[str, str]:
@@ -59,7 +107,9 @@ class ProjectConfig:
def tracked(self, setting: str) -> str | None:
"""setting's path from top, as git names a file in a commit; None where the config puts it outside the checkout, whose commits hold no version of it."""
path = self.paths[setting]
path = self.paths.get(setting)
if path is None:
return None
return path.relative_to(self.top).as_posix() if path.is_relative_to(self.top) else None
@@ -82,21 +132,46 @@ def load(top: pathlib.Path, main: pathlib.Path, home: pathlib.Path) -> ProjectCo
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}
epics = {name: epic_of(values.get(name)) for name in EPIC_SPELLINGS}
env_file = anywhere(values.get(ENV_FILE), home)
misplaced = ENV_FILE in values and (env_file is None or lies_in(env_file, top, main, file.parent))
waits = values.get(WAIT_FOR_APPROVAL, False)
on_host = values.get(TOOLING_ON_HOST, False)
floor = floor_of(values[READABILITY_FLOOR]) if READABILITY_FLOOR in values else DEFAULT_FLOOR
checks = {LANGUAGE: language_fault, COMMIT_TITLE: templates.title_fault, PULL_REQUEST_TITLE: templates.title_fault, BRANCH: templates.branch_fault}
faults = [
*(f"`{name}` is missing" for name in SETTINGS if name not in values),
*(f"`{name}` is not a setting" for name in values if name not in (*SETTINGS, *OPTIONAL)),
*(f"`{name}` is {values[name]!r}, not {SPELLING}" for name, path in paths.items() if path is None),
*(f"`{name}` is {values[name]!r}, not {SPELLING}" for name, path in paths.items() if path is None and name not in EPIC_SPELLINGS),
*(f"`{name}` is {values[name]!r}, not {SPELLING}, or {EPIC_SPELLINGS[name]}" for name in EPIC_SPELLINGS if name in values and paths[name] is None and epics[name] is None),
*(f"`{name}` names a Jira epic, so `{ENV_FILE}` must name the file that holds its credentials" for name, epic in epics.items() if epic and ENV_FILE not in values),
# rule-hook ranks a plan kept as a file before tool calls, inside the hook's time limit, which a read from Jira mustn't hold up.
*(["`goals-and-audience` names a Jira epic, so `plan` must name one too"] if epics["goals-and-audience"] and not epics["plan"] else []),
*([f"`{ENV_FILE}` is {values[ENV_FILE]!r}, not {OUTSIDE}"] if misplaced else []),
*([f"`{WAIT_FOR_APPROVAL}` is {waits!r}, not true or false"] if not isinstance(waits, bool) else []),
*(f"`{name}` is {value!r}, not true or false" for name, value in ((WAIT_FOR_APPROVAL, waits), (TOOLING_ON_HOST, on_host)) if not isinstance(value, bool)),
*([f"`{READABILITY_FLOOR}` is {values[READABILITY_FLOOR]!r}, not a number from 1 to 10; write a bare number, such as `{READABILITY_FLOOR} = 7.0`"] if floor is None else []),
*(f"`{name}` is {values[name]!r}, {fault}" for name, check in checks.items() if name in values and (fault := check(values[name]))),
]
if faults:
return Failure(f"{file}: {'; '.join(faults)}. The settings are {', '.join(SETTINGS)}, and optionally {', '.join(OPTIONAL[:-1])} and {OPTIONAL[-1]}.")
return ProjectConfig(file.parent.name, file.parent, top, {name: path for name, path in paths.items() if path}, env_file, waits is True, **{name.replace("-", "_"): str(values[name]) for name in checks if name in values})
# 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"])
def epic_of(value: object) -> Epic | None:
"""The epic a setting's value spells; None where it spells none. Only https, so the credentials are never sent in the clear."""
spelt = isinstance(value, str) and re.fullmatch(rf"{JIRA}(https://[A-Za-z0-9.-]+(?::[0-9]+)?)/browse/([A-Z][A-Z0-9_]*-[0-9]+)", value)
return Epic(spelt.group(1), spelt.group(2)) if spelt else None
def floor_of(value: object) -> decimal.Decimal | None:
"""The floor value spells, an integer or a float from 1 to 10; None where it spells none. Not a string, nor a boolean, which Python counts as an integer, nor TOML's nan or inf."""
# An integer too large for a float makes math.isfinite raise, so only a float is checked.
if isinstance(value, bool) or not isinstance(value, int | float) or (isinstance(value, float) and not math.isfinite(value)):
return None
floor = decimal.Decimal(str(value))
return floor if 1 <= floor <= 10 else None
def language_fault(value: object) -> str | None:
+126 -2
View File
@@ -1,3 +1,4 @@
import decimal
import os
import pathlib
import subprocess
@@ -8,7 +9,7 @@ import unittest.mock
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from project_config.settings import env_files, held, load, OUTSIDE, ProjectConfig, SETTINGS, Unnamed
from project_config.settings import env_files, Epic, held, load, OUTSIDE, ProjectConfig, SETTINGS, Unnamed
from failure import Failure
from test_env import isolated_env
from project_config.main import title_templates
@@ -28,6 +29,9 @@ goals-and-audience = "folder:goals.md"
principles = "~/.claude/principles"
"""
JIRA_PLAN = "jira:https://acme.atlassian.net/browse/ABC-12"
JIRA_CLIENT = CLIENT.replace("folder:todo.md", JIRA_PLAN) + 'env-file = "~/acme.env"\n'
def write_config(home: pathlib.Path, checkout: pathlib.Path, goals: str = "checkout:README.md") -> pathlib.Path:
"""A config under home that names checkout, every setting inside it but goals-and-audience; for the tests of each tool that reads the config."""
@@ -83,6 +87,72 @@ class LoadTest(ConfigCase):
self.assertEqual(found.paths["principles"], self.home / ".claude" / "principles")
self.assertEqual(tuple(found.paths), SETTINGS)
def test_a_plan_spelt_as_a_jira_epic_is_no_path(self) -> None:
self.write("acme", JIRA_CLIENT)
found = load(self.checkout, self.checkout, self.home)
assert isinstance(found, ProjectConfig), found
self.assertEqual(found.epic, Epic("https://acme.atlassian.net", "ABC-12"))
self.assertEqual((found.plan_file, found.tracked("plan"), found.plan_label), (None, None, JIRA_PLAN))
self.assertEqual(tuple(found.places), SETTINGS)
self.assertEqual(found.places["plan"], JIRA_PLAN)
self.assertEqual(tuple(found.paths), SETTINGS[1:])
def test_a_plan_kept_as_a_file_has_no_epic(self) -> None:
folder = self.write("acme", CLIENT)
found = load(self.checkout, self.checkout, self.home)
assert isinstance(found, ProjectConfig), found
self.assertEqual((found.epic, found.plan_file, found.plan_label, found.places["plan"]), (None, folder / "todo.md", str(folder / "todo.md"), str(folder / "todo.md")))
def test_a_jira_plan_needs_an_env_file(self) -> None:
self.write("acme", JIRA_CLIENT.replace('env-file = "~/acme.env"\n', ""))
self.assertIn("`plan` names a Jira epic, so `env-file` must name the file that holds its credentials", self.failure())
def test_a_plan_that_spells_no_path_and_no_epic_names_both_spellings(self) -> None:
for count, spelled in enumerate(("jira:http://acme.atlassian.net/browse/ABC-12", "jira:https://acme.atlassian.net/browse/abc-12", "jira:https://acme.atlassian.net/browse/ABC-12/x", "jira:https://acme.atlassian.net@evil.example/browse/ABC-12", "jira:ABC-12", "https://acme.atlassian.net/browse/ABC-12")):
with self.subTest(spelled):
self.write(f"acme-{count}", CLIENT.replace("folder:todo.md", spelled) + 'env-file = "~/acme.env"\n')
reason = self.failure()
self.assertIn(f"`plan` is {spelled!r}, not ", reason)
self.assertIn("jira:https://<site>/browse/<epic's key>", reason)
for config in (self.home / ".claude-projects").glob("*/config.toml"):
config.unlink()
def test_goals_and_audience_spelt_as_a_jira_epic_is_no_path(self) -> None:
self.write("acme", JIRA_CLIENT.replace("folder:goals.md", "jira:https://acme.atlassian.net/browse/ABC-7"))
found = load(self.checkout, self.checkout, self.home)
assert isinstance(found, ProjectConfig), found
self.assertEqual(found.goals_epic, Epic("https://acme.atlassian.net", "ABC-7"))
self.assertEqual(found.places["goals-and-audience"], "jira:https://acme.atlassian.net/browse/ABC-7")
self.assertEqual(tuple(found.places), SETTINGS)
self.assertNotIn("goals-and-audience", found.paths)
def test_goals_and_the_plan_may_name_the_same_epic(self) -> None:
self.write("acme", JIRA_CLIENT.replace("folder:goals.md", JIRA_PLAN))
found = load(self.checkout, self.checkout, self.home)
assert isinstance(found, ProjectConfig), found
self.assertEqual(found.goals_epic, found.epic)
def test_goals_in_jira_need_the_plan_in_jira(self) -> None:
self.write("acme", CLIENT.replace("folder:goals.md", JIRA_PLAN) + 'env-file = "~/acme.env"\n')
self.assertIn("`goals-and-audience` names a Jira epic, so `plan` must name one too", self.failure())
def test_goals_kept_as_a_file_have_no_epic(self) -> None:
folder = self.write("acme", CLIENT)
found = load(self.checkout, self.checkout, self.home)
assert isinstance(found, ProjectConfig), found
self.assertEqual((found.goals_epic, found.places["goals-and-audience"]), (None, str(folder / "goals.md")))
def test_goals_in_jira_need_an_env_file(self) -> None:
self.write("acme", CLIENT.replace("folder:goals.md", JIRA_PLAN))
self.assertIn("`goals-and-audience` names a Jira epic, so `env-file` must name the file that holds its credentials", self.failure())
def test_goals_that_spell_no_path_and_no_epic_name_both_spellings(self) -> None:
self.write("acme", CLIENT.replace("folder:goals.md", "jira:http://acme.atlassian.net/browse/ABC-12") + 'env-file = "~/acme.env"\n')
reason = self.failure()
self.assertIn("`goals-and-audience` is 'jira:http://acme.atlassian.net/browse/ABC-12', not ", reason)
self.assertIn("jira:https://<site>/browse/<epic's key>", reason)
self.assertIn("description", reason)
def test_a_worktree_finds_the_main_checkouts_config_and_reads_its_own_files(self) -> None:
self.write("acme", CLIENT)
worktree = self.home / "code" / "acme-billing-item-3"
@@ -212,6 +282,44 @@ class LoadTest(ConfigCase):
assert isinstance(found, Failure), found
self.assertIn(f"`wait-for-approval` is {eval(spelled)!r}, not true or false", found.reason)
def test_tooling_on_host_is_an_optional_boolean_that_is_false_where_left_out(self) -> None:
folder = self.write("acme", CLIENT)
left_out = load(self.checkout, self.checkout, self.home)
assert isinstance(left_out, ProjectConfig), left_out
self.assertFalse(left_out.tooling_on_host)
for spelled, expected in (("true", True), ("false", False)):
with self.subTest(spelled):
(folder / "config.toml").write_text(CLIENT + f"tooling-on-host = {spelled}\n")
found = load(self.checkout, self.checkout, self.home)
assert isinstance(found, ProjectConfig), found
self.assertEqual(found.tooling_on_host, expected)
(folder / "config.toml").write_text(CLIENT + 'tooling-on-host = "yes"\n')
found = load(self.checkout, self.checkout, self.home)
assert isinstance(found, Failure), found
self.assertIn("`tooling-on-host` is 'yes', not true or false", found.reason)
def test_the_readability_floor_is_an_optional_number_from_1_to_10_that_is_7_where_left_out(self) -> None:
folder = self.write("acme", CLIENT)
left_out = load(self.checkout, self.checkout, self.home)
assert isinstance(left_out, ProjectConfig), left_out
self.assertEqual(left_out.readability_floor, decimal.Decimal("7.0"))
for spelled, expected in (("5", "5"), ("6.5", "6.5"), ("1", "1"), ("10.0", "10.0")):
with self.subTest(spelled):
(folder / "config.toml").write_text(CLIENT + f"readability-floor = {spelled}\n")
found = load(self.checkout, self.checkout, self.home)
assert isinstance(found, ProjectConfig), found
self.assertEqual(found.readability_floor, decimal.Decimal(expected))
def test_a_readability_floor_that_is_no_number_from_1_to_10_fails_naming_it(self) -> None:
folder = self.write("acme", CLIENT)
for spelled in ('"7.0"', "0.5", "11", "true", "nan", "inf", "1" + "0" * 400):
with self.subTest(spelled):
(folder / "config.toml").write_text(CLIENT + f"readability-floor = {spelled}\n")
found = load(self.checkout, self.checkout, self.home)
assert isinstance(found, Failure), found
self.assertIn("`readability-floor` is ", found.reason)
self.assertIn(", not a number from 1 to 10; write a bare number, such as `readability-floor = 7.0`", found.reason)
def test_the_language_and_the_templates_are_optional_and_default_to_english_bare_summaries_and_item_branches(self) -> None:
folder = self.write("acme", CLIENT)
left_out = load(self.checkout, self.checkout, self.home)
@@ -247,7 +355,7 @@ class LoadTest(ConfigCase):
def test_the_failure_for_a_misplaced_env_file_and_a_missing_setting_names_both_and_lists_every_setting(self) -> None:
folder = self.write("acme", "".join(line + "\n" for line in CLIENT.splitlines() if not line.startswith("plan")) + 'env-file = "checkout:.env"\n')
self.assertEqual(self.failure(), f"{folder / 'config.toml'}: `plan` is missing; `env-file` is 'checkout:.env', not {OUTSIDE}. The settings are {', '.join(SETTINGS)}, and optionally branch, commit-title, env-file, language, pull-request-title and wait-for-approval.")
self.assertEqual(self.failure(), f"{folder / 'config.toml'}: `plan` is missing; `env-file` is 'checkout:.env', not {OUTSIDE}. The settings are {', '.join(SETTINGS)}, and optionally branch, commit-title, env-file, language, pull-request-title, readability-floor, tooling-on-host and wait-for-approval.")
def test_two_configs_naming_one_checkout_fail_naming_both(self) -> None:
self.write("acme", CLIENT)
@@ -325,6 +433,11 @@ class EnvFilesTest(ConfigCase):
class ToolTest(ConfigCase):
def test_prints_a_jira_plan_as_the_config_spells_it(self) -> None:
self.write("acme", JIRA_CLIENT)
self.assertEqual(self.run_tool("plan").stdout, JIRA_PLAN + "\n")
self.assertEqual(self.run_tool().stdout.splitlines()[0], f"plan: {JIRA_PLAN}")
def run_tool(self, *args: str, cwd: pathlib.Path | None = None) -> subprocess.CompletedProcess[str]:
return subprocess.run([sys.executable, str(TOOL), *args], cwd=cwd or self.checkout, env={**isolated_env(), "HOME": str(self.home)}, capture_output=True, text=True)
@@ -361,6 +474,17 @@ class ToolTest(ConfigCase):
self.assertEqual(self.run_tool("wait-for-approval").stdout, "true\n")
self.assertEqual(self.run_tool().stdout.splitlines()[-1], "wait-for-approval: true")
def test_prints_tooling_on_host_and_the_readability_floor_and_lists_them_only_where_the_config_changes_them(self) -> None:
folder = self.write("acme", CLIENT)
for setting, value in (("tooling-on-host", "false"), ("readability-floor", "7.0")):
with self.subTest(setting):
left_out = self.run_tool(setting)
self.assertEqual((left_out.returncode, left_out.stdout, left_out.stderr), (0, f"{value}\n", ""))
self.assertNotIn(setting, self.run_tool().stdout)
(folder / "config.toml").write_text(CLIENT + "tooling-on-host = true\nreadability-floor = 5\n")
self.assertEqual((self.run_tool("tooling-on-host").stdout, self.run_tool("readability-floor").stdout), ("true\n", "5\n"))
self.assertEqual(self.run_tool().stdout.splitlines()[-2:], ["tooling-on-host: true", "readability-floor: 5"])
def test_prints_the_language_and_each_template_and_lists_them_only_where_the_config_sets_them(self) -> None:
folder = self.write("acme", CLIENT)
defaults = {"language": "English", "commit-title": "{summary}", "pull-request-title": "{summary}", "branch": "item-{id}"}
+9 -5
View File
@@ -4,7 +4,9 @@ usage: project-record open <record>
project-record save <record>
Run inside a checkout, or a worktree of one. <record> is one of decisions, score-anchors,
comprehension-history, reading-cost and changelog, each kept where the project's config names it.
comprehension-history, reading-cost and changelog, each kept where the project's config names it,
or goals-and-audience, the goals file. Goals kept in a Jira epic's description are only read, so
save refuses them: edit the epic in Jira.
open prints the path of a file holding the record's text, and nothing else. Read and edit that
file. Where the record is kept as a file, the path is that file. Where it is kept elsewhere, the
@@ -22,25 +24,27 @@ import pathlib
import sys
from failure import Failure
from record_store.stores import FileStore, local_file, RECORDS, RecordStore, store, stored
from record_store.stores import FileStore, goals_store, local_file, RECORDS, RecordStore, store, stored
from project_config.main import located
# Not git's verbs, such as checkout and commit: those read as acting on the repo.
COMMANDS = ("open", "save")
# Where the copy of a record kept outside files goes, under the user's home, in a folder per project.
COPIES = ".local/state/project-record"
# The goals file opens like a record, though it is a setting of its own.
GOALS = "goals-and-audience"
def main(argv: list[str]) -> int:
if argv[:1] in (["-h"], ["--help"]):
print(__doc__.strip())
return 0
if len(argv) != 2 or argv[0] not in COMMANDS or argv[1] not in RECORDS:
print(f"usage: project-record {'|'.join(COMMANDS)} <record>, where <record> is one of {', '.join(RECORDS)}", file=sys.stderr)
if len(argv) != 2 or argv[0] not in COMMANDS or argv[1] not in (*RECORDS, GOALS):
print(f"usage: project-record {'|'.join(COMMANDS)} <record>, where <record> is one of {', '.join((*RECORDS, GOALS))}", file=sys.stderr)
return 2
home = pathlib.Path.home()
config = located(None, home)
done = config if isinstance(config, Failure) else act(argv[0], store(config, argv[1]), home / COPIES / config.key / f"{argv[1]}.md")
done = config if isinstance(config, Failure) else act(argv[0], goals_store(config) if argv[1] == GOALS else store(config, argv[1]), home / COPIES / config.key / f"{argv[1]}.md")
if isinstance(done, Failure):
print(f"project-record: {done.reason}", file=sys.stderr)
return 1
+5 -1
View File
@@ -53,11 +53,15 @@ class BlackBox(unittest.TestCase):
self.assertEqual((saved.returncode, saved.stdout, saved.stderr), (0, f"{self.top}/docs/decisions.md is the record itself, so nothing is left to store.\n", ""))
self.assertFalse((pathlib.Path(os.environ["HOME"]) / ".local").exists(), "a file record gets no copy")
def test_the_goals_file_opens_as_the_config_names_it(self):
opened = self.run_tool("open", "goals-and-audience")
self.assertEqual((opened.returncode, opened.stdout, opened.stderr), (0, f"{self.top}/README.md\n", ""))
def test_exits_2_with_the_usage_on_an_unknown_command_or_record(self):
for args in ([], ["open"], ["open", "plan"], ["close", "decisions"], ["open", "decisions", "changelog"]):
ran = self.run_tool(*args)
self.assertEqual((ran.returncode, ran.stdout), (2, ""), args)
self.assertIn("usage: project-record open|save <record>, where <record> is one of decisions, score-anchors, comprehension-history, reading-cost, changelog", ran.stderr)
self.assertIn("usage: project-record open|save <record>, where <record> is one of decisions, score-anchors, comprehension-history, reading-cost, changelog, goals-and-audience", ran.stderr)
def test_exits_1_saying_why_where_no_config_names_the_checkout(self):
(pathlib.Path(os.environ["HOME"]) / ".claude-projects" / self.top.name / "config.toml").unlink()
+12 -6
View File
@@ -44,9 +44,10 @@ A valid todo.md; ## Details and each item's detail are optional:
file's achieve goals follow in reading order, a sub-goal such as 1.1 included. Each weighs 0.97 times the one
before, and the weights sum to 1. With 5 achieve goals the first weighs 0.212 and the last 0.188.
With 15 they weigh 0.082 and 0.053. The overall is the mean of the overall means of every scoring
run on docs/comprehension-history.md's newest scored commit. While it is under 7.0, or the history
holds no scoring run, code health weighs 4 times its weight by position, and the other goals keep
theirs. A line `**Void:** code health, since <reason>.` in the goals file's ## Goals drops code
run on docs/comprehension-history.md's newest scored commit. While it is under the project's
readability floor, or the history holds no scoring run, code health weighs 4 times its weight by
position, and the other goals keep theirs. The config sets the floor as `readability-floor`, 7.0
where left out. A line `**Void:** code health, since <reason>.` in the goals file's ## Goals drops code
health, and an item may not name it. A project must void it where its docs/decisions.md has a
`## review opt-out:` title naming the comprehension check. An item that adds a test,
a gate leg or a probe that fails where a maintain goal breaks may name that goal, by how much
@@ -106,10 +107,15 @@ def main(argv: list[str]) -> int:
config = located(None, pathlib.Path.home())
if isinstance(config, Failure):
return fail(config)
check, todo = args[0], args[1] or config.paths["plan"]
if config.plan_file is None and args == (True, None):
# Jira's backlog ranks a plan kept there, so the check passes, as silently as on a ranked todo.md: chunk-preflight runs it on every project.
return 0
if config.plan_file is None:
return fail(Failure(f"rank_todo.py ranks a todo.md, and this checkout's config keeps the plan in Jira, whose backlog ranks it: {config.plan_label}"))
check, todo = args[0], args[1] or config.plan_file
# The goals, decisions and history are this checkout's project's, so another project's plan would be ranked by them.
if todo.resolve() != config.paths["plan"].resolve():
return fail(Failure(f"rank_todo.py: {todo} is not the plan this checkout's config names, {config.paths['plan'].resolve()}; run rank_todo.py in the checkout of the project whose plan it is"))
if todo.resolve() != config.plan_file.resolve():
return fail(Failure(f"rank_todo.py: {todo} is not the plan this checkout's config names, {config.plan_file.resolve()}; run rank_todo.py in the checkout of the project whose plan it is"))
if check:
failures = plan_file.check_failures(todo, config)
for line in failures:
+53
View File
@@ -0,0 +1,53 @@
"""A project's goals and audience kept as the description of one Jira Cloud epic, read over Jira's REST API with the credentials of the config's env-file, and converted by the adf-codec shim.
The store only reads: a write, such as `project-record save goals-and-audience`, fails, saying to edit the epic in Jira."""
import dataclasses
import pathlib
from adf_codec.convert import adfs_to_markdown, Refused
from plan_store.jira_epic import basic_auth, Http, http_json, ToMarkdown
from project_config.settings import Epic
from failure import Failure
READ_ONLY = "goals and audience kept in Jira are only read: edit the epic's description in Jira"
@dataclasses.dataclass(frozen=True)
class EpicDescription:
"""The description of epic as markdown, read with the credentials env_file holds."""
epic: Epic
env_file: pathlib.Path
http: Http = http_json
to_markdown: ToMarkdown = adfs_to_markdown
@property
def label(self) -> str:
return self.epic.spelling
@property
def tracked(self) -> str | None:
return None
def read(self) -> str | Failure:
"""The description as markdown; empty where the epic has none."""
authorization = basic_auth(self.env_file)
if isinstance(authorization, Failure):
return authorization
key = self.epic.key
answer = self.http("GET", f"{self.epic.site}/rest/api/3/issue/{key}?fields=description", authorization, None)
if isinstance(answer, Failure):
return Failure(f"cannot read the epic {key}: {answer.reason}")
fields = answer.get("fields") if isinstance(answer, dict) else None
if not isinstance(fields, dict) or "description" not in fields or not isinstance(fields["description"], dict | None):
return Failure(f"the epic {key} is not in the shape Jira Cloud's REST API version 3 documents: its description field is missing, or neither a document nor null")
if fields["description"] is None:
return ""
texts = self.to_markdown([fields["description"]])
if isinstance(texts, Refused):
return Failure(f"{key}'s description: {texts.failure.reason}")
if isinstance(texts, Failure):
return Failure(f"cannot convert {key}'s description to markdown: {texts.reason}")
return texts[0]
def write(self, text: str) -> Failure | None:
return Failure(READ_ONLY)
+12 -1
View File
@@ -1,6 +1,6 @@
"""The one way a tool reads or writes a project's records: through the store its config names for each.
Each record has its own setting in the config, so a project may keep one record in its wiki and another as a file. The setting's value names the backend. A path names a markdown file, the only backend so far."""
Each record has its own setting in the config, so a project may keep one record in its wiki and another as a file. The setting's value names the backend. A path names a markdown file, the only backend of a record so far; the goals file may also be a Jira epic's description, which `goals_store` picks."""
import dataclasses
import pathlib
import typing
@@ -68,6 +68,17 @@ def store(config: ProjectConfig, record: str) -> RecordStore:
return FileStore(config.paths[record], config.tracked(record))
def goals_store(config: ProjectConfig) -> RecordStore:
"""The store config names for the goals file, which holds ## Goals and ## Audience: a markdown file, or a Jira epic's description, which the store only reads."""
if config.goals_epic is None:
return FileStore(config.paths["goals-and-audience"], config.tracked("goals-and-audience"))
# Imported here, since the Jira store builds on plan_store, which builds on this module.
from record_store.jira_description import EpicDescription
# load refuses a config that names an epic and no env-file.
assert config.env_file is not None
return EpicDescription(config.goals_epic, config.env_file)
def held_at(revision: str, record: RecordStore, cwd: str, run: Git = git) -> str | Failure:
"""record's text at revision, read in the checkout at cwd, where its commits hold the record; else as it stands. Empty where there is no such record."""
return record.read() if record.tracked is None else file_at(revision, record.tracked, cwd, run)
+89
View File
@@ -0,0 +1,89 @@
import base64
import pathlib
import sys
import tempfile
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from project_config.settings import Epic
from record_store.jira_description import EpicDescription
from failure import Failure
from adf_codec.convert import Refused
EPIC = Epic("https://acme.atlassian.net", "ABC-12")
AUTHORIZATION = "Basic " + base64.b64encode(b"me@example.com:s3cret").decode()
GOALS = {"type": "doc", "version": 1, "content": [{"type": "heading", "attrs": {"level": 2}, "content": [{"type": "text", "text": "Goals"}]}]}
class EpicDescriptionTest(unittest.TestCase):
def setUp(self) -> None:
self.env = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory())) / "acme.env"
self.env.write_text("ATLASSIAN_EMAIL=me@example.com\nATLASSIAN_API_TOKEN=s3cret\n")
self.env.chmod(0o600)
self.answer: object = {"key": "ABC-12", "fields": {"description": GOALS}}
self.calls: list[tuple[str, str, str, object]] = []
self.converted: list[list[dict[str, object]]] = []
self.markdown: list[str] | Refused | Failure = ["## Goals\n1. **Achieve:** Ship.\n"]
def http(self, method: str, url: str, authorization: str, body: object) -> object:
self.calls.append((method, url, authorization, body))
return self.answer
def to_markdown(self, documents: list[dict[str, object]]) -> list[str] | Refused | Failure:
self.converted.append(documents)
return self.markdown
def store(self) -> EpicDescription:
return EpicDescription(EPIC, self.env, self.http, self.to_markdown)
def test_reads_the_epics_description_as_markdown(self) -> None:
self.assertEqual(self.store().read(), "## Goals\n1. **Achieve:** Ship.\n")
self.assertEqual(self.calls, [("GET", "https://acme.atlassian.net/rest/api/3/issue/ABC-12?fields=description", AUTHORIZATION, None)])
self.assertEqual(self.converted, [[GOALS]])
def test_is_named_as_the_config_spells_it_and_held_in_no_commit(self) -> None:
self.assertEqual((self.store().label, self.store().tracked), ("jira:https://acme.atlassian.net/browse/ABC-12", None))
def test_an_epic_without_a_description_reads_empty(self) -> None:
self.answer = {"key": "ABC-12", "fields": {"description": None}}
self.assertEqual(self.store().read(), "")
self.assertEqual(self.converted, [])
def test_an_unreadable_epic_fails_naming_it(self) -> None:
self.answer = Failure("HTTP 404: Issue does not exist")
found = self.store().read()
assert isinstance(found, Failure), found
self.assertIn("ABC-12", found.reason)
self.assertIn("HTTP 404", found.reason)
def test_an_answer_in_another_shape_fails(self) -> None:
for answer in ({"key": "ABC-12"}, {"fields": {"description": "text"}}, ["ABC-12"]):
with self.subTest(answer):
self.answer = answer
found = self.store().read()
assert isinstance(found, Failure), found
self.assertIn("ABC-12", found.reason)
def test_a_description_the_shim_refuses_fails(self) -> None:
for markdown in (Refused(0, Failure("an unsupported node")), Failure("docker is not running")):
with self.subTest(markdown):
self.markdown = markdown
found = self.store().read()
assert isinstance(found, Failure), found
self.assertIn("ABC-12", found.reason)
def test_missing_credentials_fail(self) -> None:
self.env.unlink()
self.assertIsInstance(self.store().read(), Failure)
self.assertEqual(self.calls, [])
def test_writing_fails_since_the_store_only_reads(self) -> None:
found = self.store().write("## Goals\n")
assert isinstance(found, Failure), found
self.assertIn("Jira", found.reason)
self.assertEqual(self.calls, [])
if __name__ == "__main__":
unittest.main()
+14 -1
View File
@@ -6,9 +6,10 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from project_config.settings import Epic, ProjectConfig
from record_store.jira_description import EpicDescription
from failure import Failure
from record_store.fakes import MemoryStore
from project_config.settings import ProjectConfig
from record_store.contract import RecordStoreContract
from record_store import stores
@@ -171,5 +172,17 @@ class Store(unittest.TestCase):
self.assertEqual(str(refused.exception), "plan is not a record; the records are decisions, score-anchors, comprehension-history, reading-cost, changelog")
class GoalsStore(unittest.TestCase):
def test_goals_kept_as_a_file_are_that_file(self):
top = pathlib.Path("/code/acme")
store = stores.goals_store(ProjectConfig("acme", pathlib.Path("/home/me/.claude-projects/acme"), top, {"goals-and-audience": top / "README.md"}))
self.assertEqual((store.label, store.tracked), ("/code/acme/README.md", "README.md"))
def test_goals_kept_in_jira_are_the_epics_description(self):
epic = Epic("https://acme.atlassian.net", "ABC-12")
store = stores.goals_store(ProjectConfig("acme", pathlib.Path("/home/me/.claude-projects/acme"), pathlib.Path("/code/acme"), {}, pathlib.Path("/home/me/acme.env"), goals_epic=epic))
self.assertEqual(store, EpicDescription(epic, pathlib.Path("/home/me/acme.env")))
if __name__ == "__main__":
unittest.main()
+4 -5
View File
@@ -6,12 +6,11 @@ import typing
from release_plan.todo_table import CODE_HEALTH
from failure import Failure
from review_rules.comprehension_history import FLOOR
from text_files.markdown_text import sections
# What each achieve goal weighs of the one above it; docs/decisions.md records the choice.
GOAL_STEP = 0.97
# Code health weighs this many times its weight by position while the comprehension panel's overall is under FLOOR, or unmeasured; lilleman's choice, which docs/decisions.md records.
# Code health weighs this many times its weight by position while the comprehension panel's overall is under the project's readability floor, or unmeasured; lilleman's choice, which docs/decisions.md records.
UNDER_FLOOR = 4
# Any **Void:** line of the goals file's ## Goals; ranked_goals accepts only `**Void:** code health, since <reason>.`, as ~/.claude/CLAUDE.md → "Shared goal" spells it.
VOID = re.compile(r"^\*\*Void:\*\* (.*)$", re.M)
@@ -72,13 +71,13 @@ def numbered(body: str) -> list[tuple[str, Mark]] | Failure:
return goals
def goal_weights(goals: list[tuple[str, Mark]], overall: decimal.Decimal | None) -> dict[str, float] | Failure:
"""Each achieve goal's weight: the one ranked k of n weighs GOAL_STEP ** (k - 1) / (1 + GOAL_STEP + ... + GOAL_STEP ** (n - 1)), so the weights sum to 1. Code health, where goals holds it, then weighs UNDER_FLOOR times that while the overall is under FLOOR or None, and the other goals keep their weights. Every weight is 0 where goals holds no achieve goal, as where the goals file voids code health and marks no goal **Achieve:**; an item then scores V 0 unless it names a maintain goal, and only an exempt one passes the bar. A maintain goal has no weight here: weight_of weighs it per item."""
def goal_weights(goals: list[tuple[str, Mark]], overall: decimal.Decimal | None, floor: decimal.Decimal) -> dict[str, float] | Failure:
"""Each achieve goal's weight: the one ranked k of n weighs GOAL_STEP ** (k - 1) / (1 + GOAL_STEP + ... + GOAL_STEP ** (n - 1)), so the weights sum to 1. Code health, where goals holds it, then weighs UNDER_FLOOR times that while the overall is None or under floor, the project's readability floor, and the other goals keep their weights. Every weight is 0 where goals holds no achieve goal, as where the goals file voids code health and marks no goal **Achieve:**; an item then scores V 0 unless it names a maintain goal, and only an exempt one passes the bar. A maintain goal has no weight here: weight_of weighs it per item."""
if unmarked := [number for number, mark in goals if mark is None]:
return Failure(f"the goals file's goal {unmarked[0]} is marked neither **Maintain:** nor **Achieve:**; mark it, as ~/.claude/rules/goals-and-audience.md says, so rank_todo.py knows which goals score")
achieve = [number for number, mark in goals if mark == "Achieve"]
total = sum(GOAL_STEP**rank for rank in range(len(achieve)))
weights = {number: GOAL_STEP**rank / total for rank, number in enumerate(achieve)}
if CODE_HEALTH in weights and (overall is None or overall < FLOOR):
if CODE_HEALTH in weights and (overall is None or overall < floor):
weights[CODE_HEALTH] *= UNDER_FLOOR
return weights
+2 -2
View File
@@ -13,7 +13,7 @@ def rank_file(todo: pathlib.Path, config: ProjectConfig) -> Ranked | Failure:
texts = file_plan(config, todo).texts()
if isinstance(texts, Failure):
return texts
ranked = rank(*texts)
ranked = rank(*texts, config.readability_floor)
if isinstance(ranked, Failure):
return ranked
if ranked.text != texts[0] and (unwritten := write(todo, ranked.text)):
@@ -31,7 +31,7 @@ def check_failures(todo: pathlib.Path, config: ProjectConfig) -> list[str]:
texts = file_plan(config, todo).texts()
if isinstance(texts, Failure):
return [texts.reason]
ranked = rank(*texts)
ranked = rank(*texts, config.readability_floor)
if isinstance(ranked, Failure):
return [ranked.reason]
unranked = [] if ranked.text == texts[0] else [f"{todo}: not ranked; run rank_todo.py on it"]
+8 -6
View File
@@ -2,6 +2,7 @@
"""
import ast
import dataclasses
import decimal
import math
import re
import typing
@@ -44,13 +45,14 @@ class Ranked:
notes: list[str]
def rank(text: str, goals_text: str, decisions: str, history: str) -> Ranked | Failure:
def rank(text: str, goals_text: str, decisions: str, history: str, floor: decimal.Decimal) -> Ranked | Failure:
"""floor is the project's readability floor, which its config sets."""
lines = text.split("\n")
table = read_table(lines)
if isinstance(table, Failure):
return table
shape = shape_of(table.columns)
scoring = read_scoring(text, lines, goals_text, decisions, history, shape)
scoring = read_scoring(text, lines, goals_text, decisions, history, shape, floor)
if isinstance(scoring, Failure):
return scoring
items = read_items(table, scoring)
@@ -112,7 +114,7 @@ def under_the_bar(item: Item, value: float, bar: float, items: list[Item]) -> st
return f"item {item.id} scores {value:.1f}, under the bar {bar:g}; delete it{blocked}, or mark it with a reason the bar does not apply"
def read_scoring(text: str, lines: list[str], goals_text: str, decisions: str, history: str, shape: Shape) -> Scoring | Failure:
def read_scoring(text: str, lines: list[str], goals_text: str, decisions: str, history: str, shape: Shape, floor: decimal.Decimal) -> Scoring | Failure:
goals = ranked_goals(goals_text, decisions)
if isinstance(goals, Failure):
return goals
@@ -125,13 +127,13 @@ def read_scoring(text: str, lines: list[str], goals_text: str, decisions: str, h
next_id = stated(text, "Next ID")
if isinstance(next_id, Failure) or not re.fullmatch(r"[0-9]+", next_id):
return next_id if isinstance(next_id, Failure) else Failure(f"Next ID {next_id!r} is not a whole number")
weights = weigh(lines, history, goals, shape)
weights = weigh(lines, history, goals, shape, floor)
if isinstance(weights, Failure):
return weights
return Scoring(shape, formula, bar, int(next_id), dict(goals), weights)
def weigh(lines: list[str], history: str, goals: list[tuple[str, Mark]], shape: Shape) -> dict[str, float] | Failure:
def weigh(lines: list[str], history: str, goals: list[tuple[str, Mark]], shape: Shape, floor: decimal.Decimal) -> dict[str, float] | Failure:
"""Each goal's weight. In OLD_SHAPE, the goals file's goals weigh what todo.md states, and code health has no weight, so no item may name it. Otherwise goal_weights gives each its weight, at the overall latest_overall reads where the goals hold code health."""
if shape is OLD_SHAPE:
return parse_weights(lines, [number for number, _ in goals if number != CODE_HEALTH])
@@ -140,7 +142,7 @@ def weigh(lines: list[str], history: str, goals: list[tuple[str, Mark]], shape:
overall = latest_overall(history) if CODE_HEALTH in dict(goals) else None
if isinstance(overall, Failure):
return overall
return goal_weights(goals, overall)
return goal_weights(goals, overall, floor)
def read_table(lines: list[str]) -> Table | Failure:
+2 -1
View File
@@ -6,13 +6,14 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from release_plan.test_ranking import DECISIONS, README, TODO
from project_config.settings import DEFAULT_FLOOR
from failure import Failure
from release_plan import ranking, todo_table
class Blockers(unittest.TestCase):
def ranked(self, todo):
return ranking.rank(todo, README, DECISIONS, "")
return ranking.rank(todo, README, DECISIONS, "", DEFAULT_FLOOR)
def test_ranks_each_blocker_just_above_the_first_item_it_blocks(self):
ranked = self.ranked(TODO.replace("| 3 | 0.1.0 | |", "| 3 | 0.1.0 | 5, 2 |"))
+2 -1
View File
@@ -5,13 +5,14 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from release_plan.test_ranking import DECISIONS, README, TODO
from project_config.settings import DEFAULT_FLOOR
from failure import Failure
from release_plan import ranking
class Formula(unittest.TestCase):
def ranked(self, todo):
return ranking.rank(todo, README, DECISIONS, "")
return ranking.rank(todo, README, DECISIONS, "", DEFAULT_FLOOR)
def test_refuses_a_formula_that_is_more_than_arithmetic_over_the_scores(self):
for formula in ("__import__('os')", "R.real", "X + 1", "C + 1", "A + V", "G + V", "W * V", "R ^ 2", "R +", "R / (S - 2)", "R\x00", "1" * 400, " + ".join(["R"] * 300), "-" * 100000 + "R", "10 ** 10 ** 10", "(-8) ** (1 / 3)", "0 ** -1"):
+44 -18
View File
@@ -1,4 +1,5 @@
import contextlib
import decimal
import io
import pathlib
import re
@@ -9,6 +10,7 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from project_config.test_project_config import configured
from project_config.settings import DEFAULT_FLOOR
from failure import Failure
from release_plan import goals_file, plan_file, ranking
from project_config.main import located
@@ -107,7 +109,7 @@ def numbered_goals(goals_text):
class Rank(unittest.TestCase):
def ranked(self, todo=TODO, readme=README, decisions=DECISIONS):
return ranking.rank(todo, readme, decisions, "")
return ranking.rank(todo, readme, decisions, "", DEFAULT_FLOOR)
def test_scores_and_sorts_by_release_then_security_then_score_and_orders_the_details_to_match(self):
ranked = self.ranked()
@@ -128,13 +130,13 @@ class Rank(unittest.TestCase):
def test_weighs_each_achieve_goal_97_percent_of_the_one_above_and_no_maintain_goal(self):
readme = "## Goals\n\n1. **Achieve:** A.\n 1. **Maintain:** B.\n 2. **Achieve:** C.\n2. **Achieve:** D.\n"
self.assertEqual({goal: round(weight, 4) for goal, weight in goals_file.goal_weights(numbered_goals(readme), None).items()}, {"1": 0.3435, "1.2": 0.3332, "2": 0.3232})
self.assertEqual({goal: round(weight, 4) for goal, weight in goals_file.goal_weights(numbered_goals(readme), None, DEFAULT_FLOOR).items()}, {"1": 0.3435, "1.2": 0.3332, "2": 0.3232})
def test_weighs_5_achieve_goals_from_0212_to_0188_and_15_from_0082_to_0053(self):
for count, first, last in ((5, 0.212, 0.188), (15, 0.082, 0.053)):
with self.subTest(count=count):
goals = numbered_goals("## Goals\n\n" + "".join(f"{number}. **Achieve:** G.\n" for number in range(1, count + 1)))
weights = list(goals_file.goal_weights(goals, None).values())
weights = list(goals_file.goal_weights(goals, None, DEFAULT_FLOOR).values())
self.assertEqual((round(weights[0], 3), round(weights[-1], 3), round(sum(weights), 6)), (first, last, 1))
def test_scores_an_item_by_the_weights_of_the_goals_it_moves(self):
@@ -262,7 +264,7 @@ class CodeHealth(unittest.TestCase):
todo = TODO.split("| 1 | 0.2.0", 1)[0].replace("`Bar = 2`", "`Bar = 0.1`") + "| 1 | 0.1.0 | | | **Read easier.** | 1 | 1 | 1 | 1 | 1 | code health by 1 | 0 |\n| 2 | 0.1.0 | | | **Do A.** | 1 | 1 | 1 | 1 | 1 | 1 by 1 | 0 |\n"
def scores(self, history, readme=readme):
ranked = ranking.rank(self.todo, readme, "", history)
ranked = ranking.rank(self.todo, readme, "", history, DEFAULT_FLOOR)
return ranked if isinstance(ranked, Failure) else {line.split(" | ")[0]: line.rsplit(" | ", 1)[1].rstrip(" |") for line in ranked.text.splitlines() if line.startswith("| ") and " 0.1.0 " in line}
def entry(self, overall, at="2026-10-08T12", read="PR #1 at aaaaaaa"):
@@ -278,6 +280,13 @@ class CodeHealth(unittest.TestCase):
with self.subTest(history=history):
self.assertEqual(self.scores(history), {"| 1": "101.5", "| 2": "24.6"})
def test_weighs_code_health_four_times_as_much_only_under_the_floor_it_is_given(self):
for floor, value in (("6.0", "25.4"), ("6.5", "101.5")):
with self.subTest(floor=floor):
ranked = ranking.rank(self.todo, self.readme, "", SCORED.format(overall="6.25"), decimal.Decimal(floor))
assert isinstance(ranked, ranking.Ranked), ranked
self.assertIn(f"| **Read easier.** | 1 | 1 | 1 | 1 | 1 | code health by 1 | {value} |", ranked.text)
def test_weighs_by_the_newest_scored_commit_wherever_the_file_holds_it(self):
older = self.entry("6.50")
newer = self.entry("7.25", "2026-10-10T12", "PR #1 at bbbbbbb")
@@ -313,7 +322,7 @@ class CodeHealth(unittest.TestCase):
def test_drops_code_health_where_readme_voids_it(self):
voided = "## Goals\n\n**Void:** code health, since it is a one-off script.\n\n1. **Achieve:** A.\n"
self.assertEqual(self.scores("", voided), Failure("item 1 names code health, which the goals file voids; drop it from the item's Moves, or the void from the goals file"))
ranked = ranking.rank(self.todo.replace("code health by 1", "1 by 2"), voided, "", "")
ranked = ranking.rank(self.todo.replace("code health by 1", "1 by 2"), voided, "", "", DEFAULT_FLOOR)
self.assertIn("| **Read easier.** | 1 | 1 | 1 | 1 | 1 | 1 by 2 | 100.0 |", ranked.text)
def test_weighs_a_defects_maintain_goal_as_code_health_four_times_over_under_an_overall_of_7(self):
@@ -321,18 +330,18 @@ class CodeHealth(unittest.TestCase):
todo = self.todo.replace("| 2 | 0.1.0 | | | **Do A.** | 1 | 1 | 1 | 1 | 1 | 1 by 1 |", "| 2 | 0.1.0 | | defect | **Restore B.** | 1 | 1 | 1 | 1 | 1 | 2 by 1 |")
for history, value in (("", "101.5"), (SCORED.format(overall="7.00"), "25.4")):
with self.subTest(history=history):
self.assertIn(f"| **Restore B.** | 1 | 1 | 1 | 1 | 1 | 2 by 1 | {value} |", ranking.rank(todo, readme, "", history).text)
self.assertIn(f"| **Restore B.** | 1 | 1 | 1 | 1 | 1 | 2 by 1 | {value} |", ranking.rank(todo, readme, "", history, DEFAULT_FLOOR).text)
def test_refuses_a_plan_whose_project_opts_out_of_the_comprehension_check_yet_keeps_code_health(self):
opted_out = "## review opt-out: the architect and the comprehension check\n\nCosts rounds.\n"
self.assertEqual(ranking.rank(self.todo, self.readme, opted_out, ""), Failure("docs/decisions.md opts out of the comprehension check, so code health has no signal; void it in the goals file's ## Goals with `**Void:** code health, since <reason>.`, as ~/.claude/CLAUDE.md → 'Shared goal' says"))
self.assertIsInstance(ranking.rank(self.todo, self.readme, opted_out.replace(" and the comprehension check", ""), ""), ranking.Ranked)
self.assertEqual(ranking.rank(self.todo, self.readme, opted_out, "", DEFAULT_FLOOR), Failure("docs/decisions.md opts out of the comprehension check, so code health has no signal; void it in the goals file's ## Goals with `**Void:** code health, since <reason>.`, as ~/.claude/CLAUDE.md → 'Shared goal' says"))
self.assertIsInstance(ranking.rank(self.todo, self.readme, opted_out.replace(" and the comprehension check", ""), "", DEFAULT_FLOOR), ranking.Ranked)
voided = "## Goals\n\n**Void:** code health, since nobody reads the probes.\n\n1. **Achieve:** A.\n"
self.assertIsInstance(ranking.rank(self.todo.replace("code health by 1", "1 by 2"), voided, opted_out, ""), ranking.Ranked)
self.assertIsInstance(ranking.rank(self.todo.replace("code health by 1", "1 by 2"), voided, opted_out, "", DEFAULT_FLOOR), ranking.Ranked)
def test_ranks_a_project_that_voids_code_health_whatever_its_history_holds(self):
voided = "## Goals\n\n**Void:** code health, since it is a one-off script.\n\n1. **Achieve:** A.\n"
self.assertIsInstance(ranking.rank(self.todo.replace("code health by 1", "1 by 2"), voided, "", SCORED.format(overall="high")), ranking.Ranked)
self.assertIsInstance(ranking.rank(self.todo.replace("code health by 1", "1 by 2"), voided, "", SCORED.format(overall="high"), DEFAULT_FLOOR), ranking.Ranked)
def test_refuses_a_void_of_anything_but_code_health(self):
self.assertEqual(self.scores("", "## Goals\n\n**Void:** speed, since nobody waits.\n\n1. **Achieve:** A.\n"), Failure("the goals file's ## Goals voids `speed, since nobody waits.`; only code health may be voided, as `**Void:** code health, since <reason>.`"))
@@ -361,11 +370,28 @@ class CodeHealth(unittest.TestCase):
self.assertEqual(ranked.under_bar, [])
self.assertIn("| code health by 1 | 25.4 |", todo.read_text())
def test_ranks_and_checks_with_the_floor_the_config_sets(self):
# At an overall of 6.50, code health weighs 4 times under the default floor of 7.0, and once at a floor of 6.0.
with tempfile.TemporaryDirectory() as temp:
todo = pathlib.Path(temp, "todo.md")
todo.write_text(self.todo)
folder = configured(self, pathlib.Path(temp), goals="folder:goals.md")
(folder / "goals.md").write_text(self.readme)
with (folder / "config.toml").open("a") as config:
config.write("readability-floor = 6.0\n")
pathlib.Path(temp, "docs").mkdir()
pathlib.Path(temp, "docs", "comprehension-history.md").write_text(SCORED.format(overall="6.50"))
with contextlib.redirect_stderr(io.StringIO()):
ranked = plan_file.rank_file(todo, located(temp, pathlib.Path.home()))
self.assertIsInstance(ranked, ranking.Ranked)
self.assertIn("| code health by 1 | 25.4 |", todo.read_text())
self.assertEqual(plan_file.check_failures(todo, located(temp, pathlib.Path.home())), [])
class Risk(unittest.TestCase):
"""R is L + E + I - 2, which rank_todo.py writes, at least 7 when I is 5 and at least 5 when I is 4."""
def ranked(self, todo):
return ranking.rank(todo, README, DECISIONS, "")
return ranking.rank(todo, README, DECISIONS, "", DEFAULT_FLOOR)
def test_writes_r_from_l_e_and_i_over_a_stale_or_missing_r(self):
ranked = self.ranked(TODO).text
@@ -414,7 +440,7 @@ class Risk(unittest.TestCase):
class OldShape(unittest.TestCase):
"""A table with A, G and Goals, from before the Moves column, ranks by the formula and goal weights it states until its project reshapes it."""
def ranked(self, todo=OLD_SHAPE, readme=README):
return ranking.rank(todo, readme, DECISIONS, "")
return ranking.rank(todo, readme, DECISIONS, "", DEFAULT_FLOOR)
def test_scores_by_the_stated_weights_and_says_to_reshape(self):
ranked = self.ranked()
@@ -441,7 +467,7 @@ class OldShape(unittest.TestCase):
def test_ranks_a_table_from_before_c_joined_and_says_to_reshape_it(self):
legacy = OLD_SHAPE.split("## Items")[0] + "## Items\n\n| ID | Release | Exempt | Item | R | S | A | G | Goals | Score |\n|---|---|---|---|---|---|---|---|---|---|\n| 2 | 0.1.0 | | **Tighten the tests.** | 2 | 4 | 5 | 5 | 2.1 | 0 |\n"
self.assertEqual(ranking.rank(legacy, README, "", "").notes, [ranking.RESHAPE])
self.assertEqual(ranking.rank(legacy, README, "", "", DEFAULT_FLOOR).notes, [ranking.RESHAPE])
def test_refuses_a_table_with_both_moves_and_goals(self):
both = OLD_SHAPE.replace("| Goals | Score |\n|---|", "| Goals | Moves | Score |\n|---|---|").replace(" | 0 |\n", " | 1 by 1 | 0 |\n")
@@ -451,7 +477,7 @@ class OldShape(unittest.TestCase):
def test_names_the_goals_column_a_table_misspells_by_its_shape(self):
misspelt = TODO.replace("| S | Moves |", "| S | Move |")
self.assertEqual(ranking.rank(misspelt, README, DECISIONS, ""), Failure("todo.md's items table has no Moves column; rank_todo.py --help shows a valid one"))
self.assertEqual(ranking.rank(misspelt, README, DECISIONS, "", DEFAULT_FLOOR), Failure("todo.md's items table has no Moves column; rank_todo.py --help shows a valid one"))
self.assertEqual(todo_table.items(misspelt), Failure("todo.md's items table has no Moves column; rank_todo.py --help shows a valid one"))
self.assertEqual(self.ranked(OLD_SHAPE.replace("| G | Goals |", "| G | Goal |")), Failure("todo.md's items table has no Goals column; rank_todo.py --help shows a valid one"))
@@ -466,15 +492,15 @@ class Renamed(unittest.TestCase):
self.assertIsInstance(todo_table.renames(f"## Renamed\n\n{bad}\n"), Failure)
def test_fails_on_a_renamed_section_that_does_not_parse(self):
failed = ranking.rank(TODO + "\n## Renamed\n\nsoon\n", README, DECISIONS, "")
failed = ranking.rank(TODO + "\n## Renamed\n\nsoon\n", README, DECISIONS, "", DEFAULT_FLOOR)
self.assertIsInstance(failed, Failure)
self.assertIn("## Renamed", failed.reason)
def test_ranks_a_plan_with_a_valid_renamed_section(self):
self.assertIsInstance(ranking.rank(TODO + "\n## Renamed\n\n- 0.3.0 renamed to 0.4.0\n", README, DECISIONS, ""), ranking.Ranked)
self.assertIsInstance(ranking.rank(TODO + "\n## Renamed\n\n- 0.3.0 renamed to 0.4.0\n", README, DECISIONS, "", DEFAULT_FLOOR), ranking.Ranked)
def test_fails_on_an_item_filed_under_a_release_the_plan_marks_renamed(self):
live = ranking.rank(TODO + "\n## Renamed\n\n- 0.2.0 renamed to 0.3.0\n", README, DECISIONS, "")
live = ranking.rank(TODO + "\n## Renamed\n\n- 0.2.0 renamed to 0.3.0\n", README, DECISIONS, "", DEFAULT_FLOOR)
self.assertIsInstance(live, Failure)
self.assertIn("marks release 0.2.0 renamed but files item 1 under it", live.reason)
@@ -483,5 +509,5 @@ class Renamed(unittest.TestCase):
class ThisRepo(unittest.TestCase):
def test_todo_md_is_ranked_with_nothing_under_the_bar(self):
text = (ROOT / "todo.md").read_text(encoding="utf-8")
ranked = ranking.rank(text, *((ROOT / name).read_text(encoding="utf-8") for name in ("README.md", "docs/decisions.md", "docs/comprehension-history.md")))
ranked = ranking.rank(text, *((ROOT / name).read_text(encoding="utf-8") for name in ("README.md", "docs/decisions.md", "docs/comprehension-history.md")), DEFAULT_FLOOR)
self.assertEqual(ranked, ranking.Ranked(text, [], []))
+2 -2
View File
@@ -8,13 +8,13 @@ import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from project_config.templates import BARE, Titles
from project_config.settings import DEFAULT_FLOOR, ProjectConfig, SETTINGS
from failure import Failure
from plan_store.stores import FilePlan, plan_of
from record_store.stores import FileStore
from test_env import isolated_env
from record_store.fakes import MemoryStore
from release_plan.todo_table import NoItemsTable
from project_config.settings import ProjectConfig, SETTINGS
from release_plan import release_standing
from release_plan import todo_table
from release_plan.release import version
@@ -26,7 +26,7 @@ ROW = "| {id} | {release} | | | **Do {id}.** | 1 | 1 | 1 | 1 | 1 | 1 by 1 | 10
def plan_at(path: pathlib.Path, tracked: str | None) -> FilePlan:
"""The markdown plan at path, which these tests only read."""
return FilePlan(path, tracked, path.parent / "README.md", MemoryStore(), MemoryStore())
return FilePlan(path, tracked, FileStore(path.parent / "README.md", None), MemoryStore(), MemoryStore(), DEFAULT_FLOOR)
def plan_in(repo: str) -> FilePlan:
View File
+34
View File
@@ -0,0 +1,34 @@
"""Reads the credentials a tool needs from an env file: KEY=value lines that only the file's owner may read."""
import pathlib
from failure import Failure
def read_env(path: pathlib.Path, keys: tuple[str, ...], secret: str) -> dict[str, str] | Failure:
"""The value of each of keys in path. secret names what the file holds, such as `an API token`, for the Failure that says who may read it."""
try:
mode = path.stat().st_mode
text = path.read_text(encoding="utf-8")
except FileNotFoundError:
return Failure(f"{path} does not exist; it needs {', '.join(keys[:-1])} and {keys[-1]}")
except (OSError, UnicodeDecodeError) as failure:
return Failure(f"cannot read {path}: {failure}")
if mode & 0o077:
return Failure(f"{path} holds {secret}, so only its owner may read it; run chmod 600 {path}")
values = parse_env(text)
if missing := [key for key in keys if not values.get(key)]:
return Failure(f"{path} lacks {' and '.join(missing)}")
return {key: values[key] for key in keys}
def parse_env(text: str) -> dict[str, str]:
values = {}
for line in text.splitlines():
key, equals, value = line.partition("=")
if not equals or key.lstrip().startswith("#"):
continue
value = value.strip()
if len(value) >= 2 and value[0] == value[-1] and value[0] in "'\"":
value = value[1:-1]
values[key.strip()] = value
return values
+52
View File
@@ -0,0 +1,52 @@
"""Sends one request to a REST API that speaks JSON, with a credential that no redirect may carry elsewhere."""
import http.client
import json
import typing
import urllib.error
import urllib.parse
import urllib.request
from failure import Failure
# The API's own message in the JSON of an error answer; empty where it holds none.
MessageOf = typing.Callable[[object], str]
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."""
def redirect_request(self, *args: typing.Any, **kwargs: typing.Any) -> None:
return None
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."""
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)
try:
with OPENER.open(request, timeout=seconds) as response:
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}")
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)}")
try:
return json.loads(raw)
except ValueError:
return Failure(f"{request_name} answered with something other than JSON")
def error_message(failure: urllib.error.HTTPError, message_of: MessageOf) -> str:
"""The API's message in an error answer; empty where the body is cut short, breaks HTTP or holds none."""
try:
return message_of(json.loads(failure.read()))
except (http.client.HTTPException, OSError, ValueError):
return ""
+50
View File
@@ -0,0 +1,50 @@
import pathlib
import sys
import tempfile
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from failure import Failure
from rest_client.env_file import parse_env, read_env
KEYS = ("SITE", "USER", "TOKEN")
class ReadEnv(unittest.TestCase):
def setUp(self) -> None:
self.path = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory())) / ".env"
def write(self, text: str, mode: int = 0o600) -> None:
self.path.write_text(text)
self.path.chmod(mode)
def test_reads_the_keys_asked_for_and_no_other(self):
self.write("SITE=https://a.example\nUSER=me\nTOKEN=s3cret\nOTHER=x\n")
self.assertEqual(read_env(self.path, KEYS, "a token"), {"SITE": "https://a.example", "USER": "me", "TOKEN": "s3cret"})
def test_a_missing_file_fails_naming_every_key_it_needs(self):
self.assertEqual(read_env(self.path, KEYS, "a token"), Failure(f"{self.path} does not exist; it needs SITE, USER and TOKEN"))
def test_a_file_lacking_keys_or_holding_empty_ones_fails_naming_them(self):
self.write("SITE=https://a.example\nUSER=\n")
self.assertEqual(read_env(self.path, KEYS, "a token"), Failure(f"{self.path} lacks USER and TOKEN"))
def test_a_file_that_group_or_others_may_read_fails_naming_the_secret(self):
for mode in (0o640, 0o604, 0o610):
with self.subTest(mode=oct(mode)):
self.write("SITE=a\nUSER=b\nTOKEN=c\n", mode)
self.assertEqual(read_env(self.path, KEYS, "a token"), Failure(f"{self.path} holds a token, so only its owner may read it; run chmod 600 {self.path}"))
def test_a_file_that_cannot_be_read_as_text_fails(self):
self.path.write_bytes(b"TOKEN=\xff\n")
self.path.chmod(0o600)
failed = read_env(self.path, KEYS, "a token")
self.assertTrue(isinstance(failed, Failure) and failed.reason.startswith(f"cannot read {self.path}: "), failed)
def test_parses_quotes_comments_and_spaces(self):
self.assertEqual(parse_env("# note\nA = 1 \nB=\"two words\"\nC='3'\nnot a pair\n#D=4\nE=a=b\nF=\"\"\nG='\n # H=5\nI=XaX\n"), {"A": "1", "B": "two words", "C": "3", "E": "a=b", "F": "", "G": "'", "I": "XaX"})
if __name__ == "__main__":
unittest.main()
+127
View File
@@ -0,0 +1,127 @@
import http.server
import json
import pathlib
import socket
import sys
import threading
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from failure import Failure
from rest_client import json_request
def message(answer: object) -> str:
return answer.get("message", "") if isinstance(answer, dict) else ""
def send(method: str, url: str, token: str, body: object, seconds: float = 5) -> object:
return json_request.http_json(method, url, f"Bearer {token}", body, seconds, message) # type: ignore[arg-type]
class Recorded(http.server.BaseHTTPRequestHandler):
"""Answers each request with the server's next scripted status and body, recording what it got."""
def do_GET(self) -> None:
self.answer()
def do_POST(self) -> None:
self.answer()
def answer(self) -> None:
length = int(self.headers.get("Content-Length") or 0)
self.server.got.append((self.command, self.path, dict(self.headers), self.rfile.read(length))) # type: ignore[attr-defined]
status, body = self.server.script.pop(0) # type: ignore[attr-defined]
if status is None:
# Raw bytes, as a server that breaks HTTP sends them.
self.wfile.write(body)
self.close_connection = True
return
self.send_response(status)
if 300 <= status < 400:
self.send_header("Location", "/elsewhere")
self.send_header("Content-Type", "application/json")
self.end_headers()
self.wfile.write(body)
def log_message(self, format: str, *args: object) -> None:
pass
class HttpJson(unittest.TestCase):
def serve(self, *script: tuple[int, bytes]) -> str:
server = http.server.HTTPServer(("127.0.0.1", 0), Recorded)
server.script = list(script) # type: ignore[attr-defined]
server.got = [] # type: ignore[attr-defined]
threading.Thread(target=server.serve_forever, daemon=True).start()
self.addCleanup(server.server_close)
self.addCleanup(server.shutdown)
self.server = server
return f"http://127.0.0.1:{server.server_port}"
def test_sends_the_authorization_and_the_body_as_json_and_reads_the_json_answer(self):
base = self.serve((201, b'{"id": "post-id"}'))
self.assertEqual(send("POST", f"{base}/api/v4/posts", "secret-token", {"message": "hi"}), {"id": "post-id"})
[(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_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."))
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(len(self.server.got), 1) # type: ignore[attr-defined]
def test_sends_no_body_with_a_get(self):
base = self.serve((200, b'{"id": "bot-id"}'))
send("GET", f"{base}/api/v4/users/me", "t", None)
[(_, _, headers, body)] = self.server.got # type: ignore[attr-defined]
self.assertEqual((headers.get("Content-Length"), body), (None, b""))
def test_fails_on_an_answer_that_breaks_http(self):
for raw in (b"garbage\r\n\r\n", b"HTTP/1.1 200 OK\r\nContent-Length: 100\r\n\r\n{}"):
with self.subTest(raw=raw):
base = self.serve((None, raw))
failed = send("GET", f"{base}/api/v4/users/me", "t", None)
self.assertTrue(isinstance(failed, Failure) and failed.reason.startswith("GET /api/v4/users/me got a broken answer: "), failed)
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"))
def test_gives_up_on_a_server_that_never_answers_after_the_timeout(self):
silent = socket.socket()
self.addCleanup(silent.close)
silent.bind(("127.0.0.1", 0))
silent.listen(1)
base = f"http://127.0.0.1:{silent.getsockname()[1]}"
self.assertEqual(send("GET", f"{base}/api/v4/users/me", "t", None, 0.2), Failure(f"cannot reach {base}: timed out"))
def test_fails_on_an_answer_that_is_not_json(self):
base = self.serve((200, b"<html>"))
self.assertEqual(send("GET", f"{base}/api/v4/users/me", "t", None), Failure("GET /api/v4/users/me answered with something other than JSON"))
def test_fails_naming_the_server_it_cannot_reach(self):
base = self.serve()
self.server.server_close()
failed = send("GET", f"{base}/api/v4/users/me", "t", None)
self.assertIsInstance(failed, Failure)
self.assertTrue(str(getattr(failed, "reason", "")).startswith(f"cannot reach {base}: "), failed)
def test_names_why_a_server_refuses_the_connection(self):
with socket.socket() as taken:
taken.bind(("127.0.0.1", 0))
port = taken.getsockname()[1]
failed = send("GET", f"http://127.0.0.1:{port}/api", "t", None)
self.assertEqual(failed, Failure(f"cannot reach http://127.0.0.1:{port}: [Errno 111] Connection refused"))
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"))
if __name__ == "__main__":
unittest.main()
@@ -9,8 +9,6 @@ from text_files.utc_stamp import utc
ARCHITECT = "Inherited architect"
DECIDED_BY = "decided by"
DIMENSIONS = ("Navigation", "Locality", "Shape", "Self-sufficiency", "Overall")
# The comprehension floor, which every dimension and the overall should reach; docs/decisions.md → "comprehension floor" says it doesn't block anything.
FLOOR = decimal.Decimal("7.0")
HARDEST_FIRST = "hardest first"
HEADING = re.compile(r"^([^,]+), (.+) at ([0-9a-f]{7,40})(?:, against ([0-9a-f]{7,40}))?$")
HISTORY = "docs/comprehension-history.md"
+8
View File
@@ -1217,6 +1217,14 @@ class TodoRankCheck(unittest.TestCase):
(self.config.parent / "todo.md").write_text("# todo\n")
self.assertEqual(self.details(checkout), [f"own script checked {self.config.parent}/todo.md"])
def test_a_plan_in_jira_is_not_checked_in_the_checkout_or_the_configs_folder(self):
checkout = self.changed_plan(f"{self.folder}/clone", self.STUB)
self.config.write_text(self.config.read_text().replace('"checkout:todo.md"', '"jira:https://acme.atlassian.net/browse/ABC-12"') + 'env-file = "~/acme.env"\n')
folder = str(self.config.parent)
git(folder, "init", "-q")
(self.config.parent / "todo.md").write_text("# todo\n")
self.assertEqual((self.details(checkout), self.details(folder)), ([], []))
def test_a_commit_in_the_configs_folder_checks_the_plan_it_keeps_there_once_it_changes(self):
checkout = self.changed_plan(f"{self.folder}/clone", self.STUB)
folder = str(self.config.parent)
+9 -4
View File
@@ -32,9 +32,12 @@ def todo_breaches(directory: str, home: pathlib.Path, own: pathlib.Path = OWN) -
# A checkout whose todo.md changes with no config is one whose config is still to write. An unchanged todo.md may be a third party's, whose clone needs no config.
unconfigured = pathlib.Path(top) / "todo.md"
return [Breach("todo-rank-check", config.reason, top)] if unconfigured.is_file() and changed(top, unconfigured, "todo.md") else []
todo, tracked = config.paths["plan"], config.tracked("plan")
todo, tracked = config.plan_file, config.tracked("plan")
# A plan in Jira is no file, and Jira's backlog ranks it.
if todo is None or not todo.is_file():
return []
# A plan outside the checkout has no commit in the checkout to differ from, so it is checked on every call.
if not todo.is_file() or (tracked is not None and not changed(top, todo, tracked)):
if tracked is not None and not changed(top, todo, tracked):
return []
return [Breach("todo-rank-check", line, top) for line in check_failures(top, todo, config, own)]
@@ -43,9 +46,11 @@ def folder_breaches(top: str, config: ProjectConfig | Failure, own: pathlib.Path
"""Why the plan kept in top, a config's folder, is not ranked, where the plan has changed in that folder's repo; ranked as for a commit in the project's checkout.
A config that fails to load doesn't block anything here, so that the commit that fixes it goes through."""
if isinstance(config, Failure) or not config.paths["plan"].is_relative_to(config.folder):
if isinstance(config, Failure):
return []
todo = config.plan_file
if todo is None or not todo.is_relative_to(config.folder):
return []
todo = config.paths["plan"]
if not todo.is_file() or not changed(str(config.folder), todo, todo.relative_to(config.folder).as_posix()):
return []
return [Breach("todo-rank-check", line, top) for line in check_failures(str(config.top), todo, config, own)]
+1 -2
View File
@@ -36,11 +36,10 @@ import typing
from run_heavy.capped_docker import CANNOT_RUN, NOT_FOUND, PATH_ENTRY, SHARE_VARIABLE, without_path_entry
from failure import Failure
from machine_load.slots import HELD, slot_count, slot_folder, waited_slot
from machine_load.memory import Memory
from machine_load.slots import slot_count, slot_folder, waited_slot
OWN_FAILURE = 125
HELD = "RUN_HEAVY_SLOT"
USAGE = "usage: run-heavy <command> [<arg>...]"
+18 -4
View File
@@ -9,6 +9,7 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from project_config.test_project_config import configured
from release_plan.test_ranking import DECISIONS, OLD_SHAPE, README, TODO
from project_config.settings import DEFAULT_FLOOR
from release_plan import goals_file, ranking
import rank_todo
@@ -33,9 +34,9 @@ class Main(unittest.TestCase):
self.assertEqual(self.run_main(str(todo)), (0, ""))
self.assertEqual(self.run_main("--check", str(todo)), (0, ""))
pathlib.Path(temp, "README.md").write_bytes(b"\xff")
self.assertEqual(self.run_main(str(todo)), (1, f"{temp}/README.md: not UTF-8\n"))
self.assertEqual(self.run_main(str(todo)), (1, f"cannot read {temp}/README.md: not UTF-8 on line 1\n"))
pathlib.Path(temp, "README.md").unlink()
self.assertEqual(self.run_main(str(todo)), (1, f"{temp}/README.md: not found; rank_todo.py weighs goals from the file the project's config names as goals-and-audience\n"))
self.assertEqual(self.run_main(str(todo)), (1, f"{temp}/README.md: missing or empty; rank_todo.py weighs goals from the goals file the project's config names as goals-and-audience\n"))
todo.unlink()
self.assertEqual(self.run_main(str(todo)), (1, f"{todo}: not found; every project keeps a todo.md, and rank_todo.py --help shows one\n"))
@@ -57,6 +58,19 @@ class Main(unittest.TestCase):
(folder / "decisions.md").write_bytes(b"\xff")
self.assertEqual(self.run_main(), (1, f"cannot read {folder}/decisions.md: not UTF-8 on line 1\n"))
def test_refuses_a_project_whose_plan_is_in_jira_and_writes_no_file(self):
with tempfile.TemporaryDirectory() as temp:
config = configured(self, pathlib.Path(temp)) / "config.toml"
self.enterContext(contextlib.chdir(temp))
config.write_text(config.read_text().replace('"checkout:todo.md"', '"jira:https://acme.atlassian.net/browse/ABC-12"') + 'env-file = "~/acme.env"\n')
todo = pathlib.Path(temp, "todo.md")
todo.write_text(TODO)
for args in ((), (str(todo),), ("--check", str(todo))):
with self.subTest(args=args):
self.assertEqual(self.run_main(*args), (1, "rank_todo.py ranks a todo.md, and this checkout's config keeps the plan in Jira, whose backlog ranks it: jira:https://acme.atlassian.net/browse/ABC-12\n"))
self.assertEqual(self.run_main("--check"), (0, ""))
self.assertEqual(todo.read_text(), TODO)
def test_refuses_a_file_that_is_not_the_plan_the_config_names_and_a_checkout_no_config_names(self):
with tempfile.TemporaryDirectory() as temp:
folder = configured(self, pathlib.Path(temp))
@@ -103,7 +117,7 @@ class Main(unittest.TestCase):
def test_shows_a_valid_file_in_help_and_names_arguments_it_cannot_read(self):
self.assertEqual(self.run_main("--help")[0], 0)
skeleton = "\n".join(line[4:] for line in rank_todo.__doc__.split("\n") if line.startswith(" "))
ranked = ranking.rank(skeleton, "## Goals\n\n1. **Achieve:** Work.\n", "", "")
ranked = ranking.rank(skeleton, "## Goals\n\n1. **Achieve:** Work.\n", "", "", DEFAULT_FLOOR)
self.assertIsInstance(ranked, ranking.Ranked)
self.assertEqual((ranked.under_bar, ranked.notes), ([], []))
self.assertEqual(self.run_main("--fix"), (1, "rank_todo.py: cannot read the arguments --fix; usage: rank_todo.py [--check] [todo.md]\n"))
@@ -111,4 +125,4 @@ class Main(unittest.TestCase):
def test_states_the_goal_weights_the_ranking_computes(self):
for figure in (goals_file.GOAL_STEP, 0.212, 0.188, 0.082, 0.053):
self.assertIn(str(figure), rank_todo.__doc__)
self.assertIn(f"While it is under {goals_file.FLOOR}, or the history holds no scoring run, code health weighs {goals_file.UNDER_FLOOR} times its weight by position, and the other goals keep theirs.", " ".join(rank_todo.__doc__.split()))
self.assertIn(f"While it is under the project's readability floor, or the history holds no scoring run, code health weighs {goals_file.UNDER_FLOOR} times its weight by position, and the other goals keep theirs. The config sets the floor as `readability-floor`, {DEFAULT_FLOOR} where left out.", " ".join(rank_todo.__doc__.split()))
+5 -4
View File
@@ -10,14 +10,15 @@ 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. The commands work the same whatever holds the plan.
Today a markdown file, todo.md, holds it. Each command that changes the file 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.
`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
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.
list prints `From <plan>, in its order:`, then the table's header and divider and one row per item,
without details: first the earliest release, and within a release the item to take first.
A plan in a Jira epic lists in Jira's backlog order instead.
--release prints one release's items. Where no item fits, it prints `<plan> holds no item.`
show prints `From <plan>:`, then the table's header and divider, item <ID>'s row, and its detail under
+2 -1
View File
@@ -9,6 +9,7 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent.parent))
from project_config.test_project_config import configured
from release_plan.test_ranking import DECISIONS, README, TODO
from project_config.settings import DEFAULT_FLOOR
from todo_item import edits, main
from failure import Failure
from project_config.main import located
@@ -41,7 +42,7 @@ class TodoItem(unittest.TestCase):
(self.folder / "README.md").write_text(README)
(self.folder / "docs").mkdir()
(self.folder / "docs" / "decisions.md").write_text(DECISIONS)
ranked = ranking.rank(TODO, README, DECISIONS, "")
ranked = ranking.rank(TODO, README, DECISIONS, "", DEFAULT_FLOOR)
assert not isinstance(ranked, ranking.Failure)
self.todo.write_text(ranked.text)
+21 -4
View File
@@ -22,6 +22,8 @@ Each project principle states one rule that the decisions below apply; their ent
- 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 tool that reads a file's commits says where it does not support that file, and the work goes on
- project config: `language` names the prose's language by its English name, and `commit-title`, `pull-request-title` and `branch` are brace templates over `{id}` and `{summary}`
- project config: `plan` may name a Jira Cloud epic as `jira:` and its address, the plan is its open child issues in backlog order, and an issue's number is the item's ID
- project config: `tooling-on-host = true` lets a project with no container setup run its language runtime, package manager, tests and task runner on the host
- review: a release review fixes its findings in the release it reviews, and files under that release only a finding that needs a human answer, adds a feature or outlasts its five rounds
- review: a reviewer or comprehension seat that rules the work below standard may ask to rerun once, one rung up, in the same round; the ruling that stands is an escalation trigger for the worker unless the fix changes only prose, and never for the judge
- review: a reviewer under `agents/` marks a 🔴 or 🟡 `[misread]` where the implementer misread code that had already shipped, each round title counts the marked findings, and `score-outcomes` lists them per chunk
@@ -36,7 +38,7 @@ Each project principle states one rule that the decisions below apply; their ent
- routing: the worker changes rung only as a chunk starts, after every second unfinished verdict, when it names a chunk item that picks a higher rung, or when it cites an escalation trigger the judge finds
- tests: each test earns its keep as the technical principles' test bullet says, and the worker takes a test's expected values from its item, never from the code
- the repo may name bender, bender-infra and ai-sandbox
- todo.md: one table of items, scored by the formula it states, held to its bar and ranked by `bin/rank_todo.py`, which ranks each blocker above the items it blocks; each achieve goal weighs by its position, code health first and four times as heavy while the comprehension panel's overall is under 7.0 or unmeasured, then the goals file's goals, and a maintain goal weighs 0.5 per point of the confidence an item's test, gate leg or probe adds to it; the table's order is the plan's only order
- todo.md: 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/`
@@ -80,9 +82,9 @@ Valid while the archive's file names, the Vocabulary and the panel keep these wo
The cap is 5, `bin/release_plan/todo_table.py`'s `BUNDLE_MAX_R`, from the same chunks: by the highest R among a chunk's items, the median was 0.9M to 1.5M tokens at R 1 to 5, and 2.7M at R 6, where the 90th percentile was 8.8M. A risky item that runs long re-runs review over every item bundled with it. R 5 is also the least R an I 4 item gets, so an item that could take everything down shares a chunk only where its L + E is 3 or less, and an irreversible I 5 item, at R 7 or more, never does. Valid while a review's cost is mostly fixed per chunk; revisit once 30 chunks have shipped bundles under it.
## comprehension floor: every dimension and the overall at 7.0 or above is the target, and no score blocks a merge or release
## comprehension floor: every dimension and the overall at the project's readability floor or above is the target, and no score blocks a merge or release
2026-09-27, lilleman, restating the 2026-09-24 target and extending it to the overall. Serves goal 1. 2026-10-13, lilleman: the floor doesn't block anything, and `review: the comprehension check records …` says why. Valid while the scoring run keeps its four seats.
2026-09-27, lilleman, restating the 2026-09-24 target and extending it to the overall. Serves goal 1. 2026-10-13, lilleman: the floor doesn't block anything, and `review: the comprehension check records …` says why. Valid while the scoring run keeps its four seats. 2026-11-12, lilleman, through todo item 358: a project's config sets this floor as `readability-floor`, its readability floor, since legacy code scores low. It is 7.0 where left out, and the signal stays that the score rises. Readers seated as the person who writes the config picked the key, 2 of 3.
## deploy: `~/.claude` holds only a release, which `deploy-release` moves it to; this repo is developed in `~/code/claude-config`, where loop-claude runs its chunks like any project's
@@ -290,6 +292,21 @@ Messages keep each file's usual name, such as `todo.md`, as its label, since the
- **The language covers what the project's readers read**: docs, comments, tickets, and the summary a title carries. `CLAUDE.md` → "Prose" lists what stays English.
- **`deploy-release` titles its commit `Cut release <version>` whatever the template**, since a release has no plan item to give `{id}`, and the tool finds that commit again by its exact title. It reads its clone's other titles whole, as no project's config names the clone.
## 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
2026-11-14, larv-review, on lilleman's calls of 2026-11-12 and 2026-11-14. Serves goal 1.6: a client's team keeps planning in its own Jira. Valid while a client's plan fits one epic in one Jira project.
- **One epic is one project's plan, and Jira's backlog rank orders it.** The team sets the rank, so the loop's score doesn't break ties and the loop doesn't reorder anything (lilleman, 2026-11-12). An item is an open child issue; one in a done status category is finished.
- **A bench of readers picked the spelling.** Three fresh readers, seated as the person who writes a client's `config.toml`, each picked `plan = "jira:https://<site>/browse/<key>"` over the bare address, a `jira:<key>` beside a `jira-site` key, and a `[plan]` table. Each also picked one pair of env-file keys, `ATLASSIAN_EMAIL` and `ATLASSIAN_API_TOKEN`, for Jira and Confluence over a pair for each, since one account's token opens both.
- **An item's ID stays a whole number: the issue's number in the epic's Jira project.** About 30 modules read an ID as an int, and the `branch` and title templates already spell a ticket's name, as `ABC-{id}`. So the store refuses a child issue from another Jira project, and counts a blocker only among the plan's own items (`bin/plan_store/jira_epic.py`).
- **The scores sit in one issue property, `plan-item`**, which needs no Jira admin (lilleman, 2026-11-12). An issue without it reads as an item nobody scored.
- **The release is the earliest Fix Version named as a semver version**, and an issue with none fails the read, naming it, until todo.md's item 359 ties releases to something else.
- **The 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.
## project config: `tooling-on-host = true` lets a project with no container setup run its language runtime, package manager, tests and task runner on the host
2026-11-12, lilleman, through todo item 358. Serves goal 1.6: a legacy product may have no container setup, and the loop works in it without its owners adding one. `CLAUDE.md`'s container rule and the stability reviewer follow the setting. rule-hook checks only how a container starts, its memory limits and its image's pin, never where a runtime runs, so it needs no change. A decision may still put one tool on the host where the project has containers, as this repo's `bin/` decision does. Readers seated as the person who writes the config picked the key, 2 of 3. Valid while the loop runs on the machine that holds the checkout.
## review: a release review fixes its findings in the release it reviews, and files under that release only a finding that needs a human answer, adds a feature or outlasts its five rounds
2026-10-30, lilleman through todo item 258. Serves goal 1.1. fejkdata.dev's release review of 0.1.0 filed the architect's findings as items 28 to 36, in releases after 0.1.0, so the release the human was about to cut still held the drift the review had found. A release review's branch opens with an empty commit, so under `larv-review` §3 → "Findings" → "Outside the chunk" every finding lay outside its change and was filed. The review's whole point is to leave the release without the drift the release's small changes made, so the whole project is its chunk and the passes fix within their five rounds. Three kinds of finding are still filed, each under the release being reviewed, or under the earliest release `rules/todo-items.md` allows where that release's semver bump forbids it, such as a feature in a patch release: one whose fix needs a human answer, marked `question`; one whose fix adds a feature; and one whose fix the five rounds cannot finish. The release isn't ready to cut while one is open, so `CLAUDE.md` → "Working loop" calls a release finished only once its review has merged and it holds no item. Valid while a release review's rounds can fix what they find.
@@ -635,7 +652,7 @@ Valid while the worker writes the tests that larv-review's reviewers hold to the
2026-10-04, lilleman, answering the principles audit of PR #215. Serves goal 4, which keeps credentials, transcripts and memory files off the remote; the names of the host, its infrastructure project and the sandbox VM are none of those. Valid while the repo names them without their addresses or credentials.
## todo.md: one table of items, scored by the formula it states, held to its bar and ranked by `bin/rank_todo.py`, which ranks each blocker above the items it blocks; each achieve goal weighs by its position, code health first and four times as heavy while the comprehension panel's overall is under 7.0 or unmeasured, then the goals file's goals, and a maintain goal weighs 0.5 per point of the confidence an item's test, gate leg or probe adds to it; the table's order is the plan's only order
## todo.md: 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.
+85
View File
@@ -2033,3 +2033,88 @@ Read most (opens and searches):
- `bin/release_plan/plan_file.py` 5
- `bin/release_plan/ranking.py` 5
- `bin/larv_review/owed.py` 4
## Reading cost, chunk 7932529d6b61, finished 2026-11-14T16:03:27Z
63976 new input tokens before the first commit.
Read most (opens and searches):
- `README.md` 2
- `CHANGELOG.md` 1
- `bin/adf_codec/node_shim/package-lock.json` 1
- `bin/failure.py` 1
- `bin/mattermost-dm` 1
- `bin/mattermost_dm/dm.py` 1
- `bin/mutate_changes/tool_process.py` 1
- `bin/run-tests` 1
- `bin/run_tests/main.py` 1
- `ci.sh` 1
## Reading cost, chunk 2c4de5662b08, finished 2026-11-14T19:06:19Z
84663 new input tokens before the first commit.
Read most (opens and searches):
- `bin/plan_store/stores.py` 5
- `todo.md` 3
- `bin/project_config/templates.py` 2
- `CLAUDE.md` 1
- `README.md` 1
- `bin/larv_review/plan.py` 1
- `bin/loop_claude/cycle/chunk_items.py` 1
- `bin/plan_store/contract.py` 1
- `bin/release_plan/todo_table.py` 1
- `bin/todo_item/main.py` 1
## Reading cost, chunk ca7c9a18d77d, finished 2026-11-14T19:36:20Z
87192 new input tokens before the first commit.
Read most (opens and searches):
- `bin/plan_store/test_jira_epic.py` 11
- `bin/adf_codec/convert.py` 3
- `bin/adf_codec/test_adf_codec.py` 3
- `bin/plan_store/jira_epic.py` 3
- `bin/run_heavy/main.py` 3
- `README.md` 2
- `bin/adf_codec/__init__.py` 2
- `bin/machine_load/slots.py` 2
- `docs/decisions.md` 2
- `bin/adf_codec/node_shim/Dockerfile` 1
## Reading cost, chunk 514c7381359c, finished 2026-11-14T19:43:45Z
60112 new input tokens before the first commit.
Read most (opens and searches):
- `README.md` 6
- `bin/chunk_preflight/main.py` 2
- `bin/chunk_preflight/test_chunk_preflight.py` 2
- `bin/project_config/main.py` 2
- `bin/chunk_preflight/choices.py` 1
- `bin/project_config/templates.py` 1
- `bin/project_config/test_templates.py` 1
- `ci.sh` 1
- `docs/decisions.md` 1
- `todo.md` 1
## Reading cost, chunk c1c3ab1d8e14, finished 2026-11-14T20:33:37Z
135080 new input tokens before the first commit.
Read most (opens and searches):
- `bin/plan_store/stores.py` 4
- `bin/project_config/settings.py` 4
- `bin/project_config/test_project_config.py` 4
- `bin/larv_review/reviewer_header.py` 3
- `bin/plan_store/jira_epic.py` 3
- `bin/project_config/main.py` 3
- `bin/release_plan/goals_file.py` 2
- `skills/larv-review/SKILL.md` 2
- `bin/adf_codec/convert.py` 1
- `bin/loop_claude/loop/usage.py` 1
+1 -1
View File
@@ -6,7 +6,7 @@ paths:
# Goals and Audience
A project's goals and audience live in its goals file (`~/.claude/CLAUDE.md` → "Vocabulary"): `README.md`, or a client project's `goals.md` in its config's folder.
A project's goals and audience live in its goals file (`~/.claude/CLAUDE.md` → "Vocabulary"): `README.md`, or a client project's `goals.md` in its config's folder or its plan epic's description in Jira.
- **Goals** state the project's aim and intent, not promises: one numbered line each, like slogans, in priority order; a sub-goal is indented under its goal — "1. Blazing fast performance. 2. Correctness is more important than many features." A goal names no step of the work, such as a check to run first, and rarely an implementation. How a goal is met goes in a method section further down the goals file and names the goal it serves. BANNED as a goal: `Kill weak candidates early, with the cheap checks first.` GOOD: the goal `Keep research on a budget, so it scales in both time and cost.`, with the cheap checks moved to the method section, naming that goal.
- **Mark each goal `**Maintain:**` or `**Achieve:**`.** A maintain goal is a state to hold: a change that breaks it is redesigned or dropped, whatever its value to other goals. An achieve goal is a direction to pursue, weighed against the other achieve goals. Under each achieve goal, three indented bullets: `Signal:` what moving towards it looks like, `Counter-signal:` what shows it is bought at a wrong price, and `Why:` one line on how the two connect. A goal with sub-goals states its own signal. A maintain goal has no bullets. BANNED: an unmarked goal; an achieve goal with no signal; `**Achieve:** Delivery speed.` with the signal `faster`. GOOD: `**Achieve:** Delivery speed.` with `Signal: hours from a chunk's start to its merge fall.`, `Counter-signal: 🔴 findings per chunk rise.` and `Why: speed bought by skipping review shows up as defects.`
+1 -1
View File
@@ -156,7 +156,7 @@ The comprehension check records how hard the project is for its contributor to r
**Scoring run**, when `~/.claude/bin/larv-review needs-scoring-run <the IDs of the items the chunk ships, if any>` prints `Scoring run due:`. Run `needs-scoring-run` before removing the chunk's items from `todo.md`. `chunk-pr merge` refuses until the branch's committed history records every run the plan calls, which `larv-review scoring-run-owed` counts at merge time from the merge base; an earlier due line is only a snapshot.
- **Seats.** Junior A, Mid A, the maintainability senior and the inherited architect each score the project at the head from 1 to 10 overall and on four dimensions: Navigation, Locality, Shape and Self-sufficiency. Run `~/.claude/bin/larv-review prepare-scoring`, adding `--preloaded <text>` only where its default list of pre-loaded files is wrong. It makes the worktree the seats read and prints each seat's prompt file; launch each seat with its file's text as its prompt. Write their lines into a scores file and run `~/.claude/bin/larv-review record-scoring <scores file> <the same item IDs>`, which appends the run to the history and prints the four seats' means.
- **Floor item.** Where `record-scoring` prints `Floor:`, a `Next:` line follows: file one floor item, or refresh the open one. A floor item is a plan item meant to bring every mean to 7.0. File it as one ambitious refactor, not touch-ups. It restructures the area behind the places `larv-review places` prints for this run, chosen where they bear on the lowest dimension, sized to bring every mean to 7.0, and quotes those places. Its tagline opens with `Reach the comprehension floor:`, so its own chunk runs a scoring run; while a mean stays under 7.0, that run's `Next:` line asks for the next floor item. Mark it `owner`, since the human asked that such a project always hold one, so no score deletes it. Put it in the earliest release the plan names after the one the chunk ships into, or else in the next version after that one that `~/.claude/rules/todo-items.md` allows, so the floor doesn't hold up any release. While one is open, refresh its places and aim from the newest run instead of filing another; the item the chunk ships doesn't count as open. Commit it with the run, as "Record" says.
- **Floor item.** Where `record-scoring` prints `Floor:`, a `Next:` line follows: file one floor item, or refresh the open one. A floor item is a plan item meant to bring every mean to the project's readability floor, which `record-scoring`'s `Floor:` line names. File it as one ambitious refactor, not touch-ups. It restructures the area behind the places `larv-review places` prints for this run, chosen where they bear on the lowest dimension, sized to bring every mean to that floor, and quotes those places. Its tagline opens with `Reach the comprehension floor:`, so its own chunk runs a scoring run; while a mean stays under the floor, that run's `Next:` line asks for the next floor item. Mark it `owner`, since the human asked that such a project always hold one, so no score deletes it. Put it in the earliest release the plan names after the one the chunk ships into, or else in the next version after that one that `~/.claude/rules/todo-items.md` allows, so the floor doesn't hold up any release. While one is open, refresh its places and aim from the newest run instead of filing another; the item the chunk ships doesn't count as open. Commit it with the run, as "Record" says.
- **Second run.** Where `needs-scoring-run` printed that the chunk `leaves release … with no plan item`, run `prepare-scoring` again and launch the same four seats afresh on the same head. Their scores file's first line is `<PR or branch> rerun at <commit>`. Record it with the same `record-scoring` command.
- **Agreement.** After the second run, run `~/.claude/bin/larv-review agreement` and put its counts in the summary. On `Assumption fails:`, ask the user whether to keep the paired ruling or change the decision `review: the comprehension check records …`. Record the answer as a decision in the repo whose history was counted, with the counts that led to the ask. A later run asks again only when the rulings' rate falls, or the runs' rate rises, against the recorded counts.
+18 -19
View File
@@ -6,24 +6,23 @@
`Bar = 0.1`
`Next ID = 377`
`Next ID = 381`
## Items
| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 351 | 0.11.0 | | | **Read a project's plan from the child issues of a Jira Cloud epic its config names, ranked in Jira's backlog order.** | 3 | 2 | 3 | 6 | 5 | 1.6 by 6 | 1.2 |
| 353 | 0.11.0 | 351 | | **Let a project's config take its goals and audience from a Jira epic's description, under the same two headings.** | 2 | 2 | 3 | 5 | 3 | 1.6 by 4 | 1.3 |
| 358 | 0.11.0 | | | **Let a project's config allow its runtime and tests on the host, and set the comprehension score under which code health is very important.** | 2 | 2 | 3 | 5 | 3 | 1.6 by 4 | 1.3 |
| 362 | 0.11.0 | | | **Send loop-claude's notices through the notifier a project's config names, with Mattermost as the first backend.** | 2 | 1 | 2 | 3 | 3 | 1.6 by 3 | 1.0 |
| 363 | 0.11.0 | 362 | | **Add a Slack backend to the notifier, sending each notice as a DM from a bot.** | 2 | 1 | 2 | 3 | 3 | 1.6 by 4 | 1.3 |
| 377 | 0.11.0 | | | **Hand a reviewer without a shell the plan as a listing `larv-review` writes into the review folder, whatever store holds the plan.** | 2 | 2 | 3 | 5 | 3 | 1.6 by 4 | 1.3 |
| 373 | 0.11.0 | | | **Pick the next release's chunks that may run at once by the files and the parts of files each is predicted to touch, and record the prediction beside what each merged chunk touched.** | 3 | 2 | 2 | 5 | 5 | 1.5 by 4, 1.4 by 2 | 1.3 |
| 352 | 0.11.0 | 351 | | **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 |
| 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 |
| 359 | 0.11.0 | | | **Tie a project's releases to what its config names: semver tags, Jira Fix Versions, sprints, or none.** | 3 | 2 | 3 | 6 | 4 | 1.6 by 3 | 0.8 |
| 380 | 0.11.0 | | | **Define "plan" in `CLAUDE.md` → "Vocabulary" as the store a project's config names as `plan`, a `todo.md` or a Jira epic, and reword each line of `CLAUDE.md` and `rules/todo-items.md` that says `todo.md` where it is false for a plan in Jira.** | 1 | 2 | 3 | 4 | 2 | 1.6 by 2 | 0.7 |
| 375 | 0.11.0 | 372, 373, 374 | | **Run up to the project's configured number of chunks at once, each in its own window of one tmux session named for the project, mark a window whose chunk waits for the human, and refuse to start without tmux at the needed version.** | 4 | 2 | 3 | 7 | 7 | 1.5 by 7 | 0.6 |
| 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 |
@@ -83,20 +82,6 @@
## Details
### 351. Read a project's plan from the child issues of a Jira Cloud epic its config names, ranked in Jira's backlog order.
lilleman's calls, 2026-11-12. One epic is one project's plan. An item is a child issue: its key is the item's ID, so branches, worktrees and commit and PR titles follow `CLAUDE.md`'s ticket rules (`ABC-123`, `ABC-123 - ...`). Summary is the tagline, description the detail (ADF, read through the adf-codec shim). Release is the Fix Version, or what item 359 configures. Blocked by is the "is blocked by" link. L, E, I, S, Moves and Exempt are issue entity properties, so no Jira admin is needed; the computed score also shows as a label such as `score-2.4`. Jira's backlog rank decides the order, since the team sets it; the loop's score doesn't break ties, and the loop doesn't reorder anything others filed. Auth: email plus API token from the project's env file.
A reviewer without a shell reads the plan with the Read tool today, as `todo.md` (the agents under `agents/` and `skills/larv-review/review-findings.md` say so). Hand it a Jira plan another way, such as a listing `larv-review` writes into the review folder beside `places.md`.
### 353. Let a project's config take its goals and audience from a Jira epic's description, under the same two headings.
lilleman's call, 2026-11-12: this client keeps its goals and audience in the plan epic's description. The source is a config setting, never hard-coded; item 346 builds the file source this one adds to. Read through the adf-codec shim.
### 358. Let a project's config allow its runtime and tests on the host, and set the comprehension score under which code health is very important.
lilleman's calls, 2026-11-12. Legacy products may have no container setup, so the config may allow host tooling; `CLAUDE.md`'s container rule and rule-hook then follow it. In 0.10.0 a decision in the project's records can put tooling on the host instead. The comprehension panel will score legacy code low, and today code health under 7.0 is very important. The config sets that floor, 7.0 in the configs of the projects under `~/code`; the signal stays that the score rises.
### 362. Send loop-claude's notices through the notifier a project's config names, with Mattermost as the first backend.
lilleman's call, 2026-11-12: each project names its notifier, server and recipient, so client notices can go to a client's workspace. Today `bin/mattermost-dm` reads one server from `~/.claude/.env` for every project.
@@ -105,6 +90,10 @@ lilleman's call, 2026-11-12: each project names its notifier, server and recipie
lilleman asked for a Slack driver on 2026-11-12, for clients on Slack. The bot token comes from the project's env file.
### 377. Hand a reviewer without a shell the plan as a listing `larv-review` writes into the review folder, whatever store holds the plan.
lilleman's call, 2026-11-14: split from item 351. A reviewer without a shell reads the plan with the Read tool today, as `todo.md`; the agents under `agents/` and `skills/larv-review/review-findings.md` say so. A plan in Jira has no file to read. Write the listing through the plan's store, beside `places.md`, and point the agents and `review-findings.md` at it. Where the change touches `bin/larv_review/plan.py` `plan_reasons`, which the comprehension seats found hard, make it easier to read.
### 373. Pick the next release's chunks that may run at once by the files and the parts of files each is predicted to touch, and record the prediction beside what each merged chunk touched.
lilleman's call, 2026-11-13, splitting item 361. A planning pass, on the project's rung or above, predicts for each item of the next release the files it will touch and, within each file, the parts: a function, a class, a section heading, a table row. It writes the prediction into the item's detail, where `chunk-preflight` reads it. Two chunks may run together where their predicted parts don't overlap, even in one file. `todo.md` and `CHANGELOG.md` don't count, since item 374 writes them at merge time.
@@ -145,6 +134,16 @@ Where the rebase conflicts, the chunk's worker resolves it, and only the review
lilleman's call, 2026-11-12: what a release is differs per client. With none, items name no release, and the architecture and principles passes the release review runs need another trigger, which this item settles and records. Readers: `rank_todo.py`'s release order, chunk-preflight's next release, loop-claude's "release ready to cut", larv-review's release review, `CLAUDE.md` → "Working loop". Cutting a release stays the human's.
### 380. Define "plan" in `CLAUDE.md` → "Vocabulary" as the store a project's config names as `plan`, a `todo.md` or a Jira epic, and reword each line of `CLAUDE.md` and `rules/todo-items.md` that says `todo.md` where it is false for a plan in Jira.
Since item 351 a project's config may name its plan as `jira:https://<site>/browse/<KEY>`, read from the epic's open child issues; `bin/todo-item --help` and `project-config --help` describe it. `CLAUDE.md` → "Vocabulary" still defines **plan** as "the project's `todo.md`, at the path its config names as `plan`", which is false for such a project.
Start with the definition, then read every line that says `todo.md` in `CLAUDE.md` and `rules/todo-items.md`. Reword a line only where it is false for a plan in Jira, such as "`todo.md` is mandatory in every project" and "Plan `todo.md` as one scored table"; prefer the word "plan", which the definition then covers. Leave a line that is about the file itself: the table's shape, `## Scoring`, `## Renamed`, `rank_todo.py`, and the `paths:` frontmatter that loads the rule. "Working loop" already says a rule names a project's files by their usual paths, so a line that only names the plan as `todo.md` may stay where that sentence covers it; say there that the plan may be no file at all.
A plan in Jira is only read today, until item 352 writes one. Don't describe filing, scoring or finishing an item in Jira as working; say what holds now, and leave the rest to item 352.
Both files load into every session of every project, hence I 3. Keep the change to prose: it adds no rule and removes none.
### 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.