From 520e0e9aa5a9b359b167f7f9b5e6f7603518f9f2 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sat, 14 Nov 2026 17:05:57 +0100 Subject: [PATCH 01/14] Re-score item 351 at L 4 and S 6, and keep item IDs as ints for a Jira plan --- docs/reading-cost.md | 17 +++++++++++++++++ todo.md | 4 +++- 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/docs/reading-cost.md b/docs/reading-cost.md index 49d354d2..1cf0f40f 100644 --- a/docs/reading-cost.md +++ b/docs/reading-cost.md @@ -2033,3 +2033,20 @@ 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 diff --git a/todo.md b/todo.md index 087b5b90..beacbb58 100644 --- a/todo.md +++ b/todo.md @@ -12,7 +12,7 @@ | 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 | +| 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.** | 4 | 2 | 3 | 7 | 6 | 1.6 by 6 | 0.8 | | 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 | @@ -89,6 +89,8 @@ lilleman's calls, 2026-11-12. One epic is one project's plan. An item is a child 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`. +Item IDs stay `int`: the store holds the Jira project key from the config, and an issue's number is the item's ID, so the 30 or so modules that read an ID as an int stay as they are. A branch template `ABC-{id}` and a commit-title template `ABC-{id} - {summary}` give the ticket-style names. The store refuses a child issue from another Jira project. Re-scored 2026-11-14 at L 4 and S 6: a new pattern, HTTP to Jira Cloud with entity properties, rank and ADF, across plan_store, project_config, larv_review and the reviewer prompts, about 900 to 1,200 lines. + ### 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. -- 2.52.0 From c19f097ecd327fc111089a77a683be2c64f606f5 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sat, 14 Nov 2026 19:01:08 +0100 Subject: [PATCH 02/14] Split items 377 and 378 out of item 351 --- todo.md | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/todo.md b/todo.md index beacbb58..bd3cb3f2 100644 --- a/todo.md +++ b/todo.md @@ -6,17 +6,19 @@ `Bar = 0.1` -`Next ID = 377` +`Next ID = 379` ## 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.** | 4 | 2 | 3 | 7 | 6 | 1.6 by 6 | 0.8 | +| 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.** | 4 | 2 | 3 | 7 | 5 | 1.6 by 6 | 1.2 | +| 378 | 0.11.0 | 351 | | **Name the branches, worktrees and commit and PR titles of a Jira plan's chunks by the issue key, as in `ABC-123` and `ABC-123 - ...`.** | 2 | 2 | 3 | 5 | 2 | 1.6 by 4 | 1.4 | | 353 | 0.11.0 | 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 | | 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 | @@ -87,9 +89,11 @@ 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`. +Item IDs stay `int`: the store holds the Jira project key from the config, and an issue's number is the item's ID, so the 30 or so modules that read an ID as an int stay as they are. The store refuses a child issue from another Jira project. This item only reads: `add`, `edit` and `finish` fail, saying item 352 builds them. lilleman's call, 2026-11-14: item 377 hands the plan to a reviewer without a shell, and item 378 names branches and titles by the issue key. Re-scored 2026-11-14 at L 4: a new pattern, HTTP to Jira Cloud with entity properties, rank and ADF, across plan_store and project_config. -Item IDs stay `int`: the store holds the Jira project key from the config, and an issue's number is the item's ID, so the 30 or so modules that read an ID as an int stay as they are. A branch template `ABC-{id}` and a commit-title template `ABC-{id} - {summary}` give the ticket-style names. The store refuses a child issue from another Jira project. Re-scored 2026-11-14 at L 4 and S 6: a new pattern, HTTP to Jira Cloud with entity properties, rank and ADF, across plan_store, project_config, larv_review and the reviewer prompts, about 900 to 1,200 lines. +### 378. Name the branches, worktrees and commit and PR titles of a Jira plan's chunks by the issue key, as in `ABC-123` and `ABC-123 - ...`. + +lilleman's call, 2026-11-14: split from item 351. Item IDs stay `int`: the Jira store holds the project key and an issue's number is the item's ID. A branch template `ABC-{id}` and a commit-title template `ABC-{id} - {summary}` already give the ticket-style names `CLAUDE.md`'s ticket rules ask for. Make a project with a Jira plan get them without spelling its key twice, or document the two templates where the plan setting is documented, whichever is simpler, and check `chunk-preflight` names the worktree the same way. ### 353. Let a project's config take its goals and audience from a Jira epic's description, under the same two headings. @@ -107,6 +111,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. -- 2.52.0 From 59d972cc82325ada751e406570e2ba7b2c3630b9 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sat, 14 Nov 2026 19:12:25 +0100 Subject: [PATCH 03/14] Read a plan from the child issues of a Jira Cloud epic --- README.md | 4 +- bin/branch_chunks/read.py | 2 +- bin/chunk_preflight/choices.py | 8 +- bin/chunk_preflight/facts.py | 2 +- bin/chunk_preflight/gathered.py | 2 +- bin/chunk_preflight/main.py | 4 +- bin/larv_review/history_commands.py | 5 +- bin/larv_review/owed.py | 2 +- bin/larv_review/plan.py | 2 +- bin/larv_review/test_larv_review.py | 16 +- bin/plan_store/jira_epic.py | 213 ++++++++++++++++++++++ bin/plan_store/stores.py | 10 +- bin/plan_store/test_jira_epic.py | 165 +++++++++++++++++ bin/plan_store/test_stores.py | 18 ++ bin/project_config/main.py | 7 +- bin/project_config/settings.py | 51 +++++- bin/project_config/test_project_config.py | 40 +++- bin/rank_todo.py | 8 +- bin/rule_hook/test_rule_hook.py | 8 + bin/rule_hook/todo_check.py | 10 +- bin/test_rank_todo.py | 11 ++ docs/decisions.md | 12 ++ 22 files changed, 570 insertions(+), 30 deletions(-) create mode 100644 bin/plan_store/jira_epic.py create mode 100644 bin/plan_store/test_jira_epic.py diff --git a/README.md b/README.md index 776fbafa..19adb62b 100644 --- a/README.md +++ b/README.md @@ -100,6 +100,8 @@ A project's config may set four more things, each optional, as `project-config - A project whose pull requests need a human's approval sets `wait-for-approval = true` in its config. `chunk-pr merge` then waits, once the checks have passed, until GitHub reports the pull request approved as its branch protection requires, and merges it. It refuses on Gitea, where a reviewer requested changes and where the protection requires no review. It gives up after 90 minutes without an approval; run it again once the pull request is approved. Left out, the setting is false. +A client that plans in Jira Cloud names an epic as the plan, as `plan = "jira:https://acme.atlassian.net/browse/ABC-12"`: `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. An issue's number is the item's ID, so every child lies in the epic's own Jira project, and a read fails naming one that doesn't. The summary is the tagline, the description the detail, the earliest Fix Version named as a semver version the release, and an "is blocked by" link to another open child a blocker. The scores sit in 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. The config's `env-file` must hold `ATLASSIAN_EMAIL` and `ATLASSIAN_API_TOKEN`, an API token of that Atlassian account. The loop only reads such a plan so far: `todo-item add`, `edit`, `move` and `finish` fail saying so, `rank_todo.py` refuses it, and rule-hook's rank check skips it. What isn't supported for a plan outside the checkout, below, isn't for a plan in Jira either. + 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:`, 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. ```sh @@ -178,7 +180,7 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a - `machine_load/` takes the machine's heavy slots, its shared lock files, for `run_heavy`, and 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` and the reader of a Jira epic's child issues in `jira_epic.py`. `contract.py` holds the tests every backend must pass, 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`. diff --git a/bin/branch_chunks/read.py b/bin/branch_chunks/read.py index 91412fc0..ae2874f7 100644 --- a/bin/branch_chunks/read.py +++ b/bin/branch_chunks/read.py @@ -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 diff --git a/bin/chunk_preflight/choices.py b/bin/chunk_preflight/choices.py index 92256e6c..b8ec48a1 100644 --- a/bin/chunk_preflight/choices.py +++ b/bin/chunk_preflight/choices.py @@ -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): diff --git a/bin/chunk_preflight/facts.py b/bin/chunk_preflight/facts.py index 07774477..470bbb23 100644 --- a/bin/chunk_preflight/facts.py +++ b/bin/chunk_preflight/facts.py @@ -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 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] diff --git a/bin/chunk_preflight/gathered.py b/bin/chunk_preflight/gathered.py index 153bfa2c..07cab36d 100644 --- a/bin/chunk_preflight/gathered.py +++ b/bin/chunk_preflight/gathered.py @@ -82,7 +82,7 @@ class Gathered: # 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] + 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. diff --git a/bin/chunk_preflight/main.py b/bin/chunk_preflight/main.py index ca070a6d..6ab9ad89 100644 --- a/bin/chunk_preflight/main.py +++ b/bin/chunk_preflight/main.py @@ -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: diff --git a/bin/larv_review/history_commands.py b/bin/larv_review/history_commands.py index 08bbe733..9aa017ce 100644 --- a/bin/larv_review/history_commands.py +++ b/bin/larv_review/history_commands.py @@ -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") diff --git a/bin/larv_review/owed.py b/bin/larv_review/owed.py index 7a65fc70..ec1ad8da 100644 --- a/bin/larv_review/owed.py +++ b/bin/larv_review/owed.py @@ -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) diff --git a/bin/larv_review/plan.py b/bin/larv_review/plan.py index 4cb1cd4d..e4269e74 100644 --- a/bin/larv_review/plan.py +++ b/bin/larv_review/plan.py @@ -100,7 +100,7 @@ def plan_reasons(ref: str, ids: list[int] | None, home: pathlib.Path) -> list[st 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 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.plan_label}") return scoring_run_due(planned, chunk, ids, landed_release, renamed, unmeasured) diff --git a/bin/larv_review/test_larv_review.py b/bin/larv_review/test_larv_review.py index 23d490e1..187de198 100644 --- a/bin/larv_review/test_larv_review.py +++ b/bin/larv_review/test_larv_review.py @@ -1,3 +1,4 @@ +import contextlib import decimal import itertools import json @@ -16,8 +17,9 @@ 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 failure import Failure from plan_store.stores import FilePlan from larv_review.scoring import floor_step, means, under_floor @@ -942,6 +944,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() diff --git a/bin/plan_store/jira_epic.py b/bin/plan_store/jira_epic.py new file mode 100644 index 00000000..df1e74c2 --- /dev/null +++ b/bin/plan_store/jira_epic.py @@ -0,0 +1,213 @@ +"""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 the epic's children all lie 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 concurrent.futures +import dataclasses +import http.client +import json +import pathlib +import re +import typing +import urllib.error +import urllib.parse +import urllib.request + +from adf_codec.convert import adf_to_markdown +from failure import Failure +from mattermost_dm.dm import parse_env +from plan_store.markdown_edits import bold_cell +from plan_store.stores import Plan, Written +from project_config.settings import Epic +from release_plan.release import parsed, Release, tagged +from release_plan.todo_table import is_exempt, Item, MOVES, parse_moves, parse_scores, SHAPE + +# One pair of keys for Jira and Confluence, which 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" +# 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 +# The adf-codec containers run at once: each description is one run. +CONVERSIONS = 8 +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, and returns the JSON answer, or a Failure saying why there is none. +Http = typing.Callable[[str, str, str, object], object] +ToMarkdown = typing.Callable[[dict[str, typing.Any]], str | Failure] + + +class NoRedirect(urllib.request.HTTPRedirectHandler): + """Refuses every redirect, which Jira's API never sends: urllib would resend the credentials 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) -> object: + """The JSON that url answers; a Failure naming the request where it answers an error, breaks HTTP or answers something other than JSON, and saying so where the site cannot be reached.""" + request_name = f"{method} {urllib.parse.urlsplit(url).path}" + request = urllib.request.Request(url, json.dumps(body).encode(), {"Authorization": authorization, "Content-Type": "application/json", "Accept": "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}: {failure.reason}") + except http.client.HTTPException as failure: + return Failure(f"{request_name} got a broken answer: {failure!r}") + except (OSError, ValueError) as failure: + return Failure(f"cannot be reached: {getattr(failure, 'reason', failure)}") + try: + return json.loads(raw) + except ValueError: + return Failure(f"{request_name} answered with something other than JSON") + + +@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 = adf_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 + issues = children(self.epic, authorization, self.http) + if isinstance(issues, Failure): + return Failure(f"{self.epic.site}: {issues.reason}") + try: + return plan_of(issues, self.epic, self.to_markdown) + except (AttributeError, KeyError, TypeError): + return Failure(f"{self.epic.site} answered issues in another shape than Jira Cloud's REST API version 3 documents") + + 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's KEY=value lines hold.""" + try: + mode = env_file.stat().st_mode + text = env_file.read_text(encoding="utf-8") + except FileNotFoundError: + return Failure(f"{env_file} does not exist; it needs {' and '.join(KEYS)}") + except (OSError, UnicodeDecodeError) as failure: + return Failure(f"cannot read {env_file}: {failure}") + if mode & 0o077: + return Failure(f"{env_file} holds an API token, so only its owner may read it; run chmod 600 {env_file}") + values = parse_env(text) + if missing := [key for key in KEYS if not values.get(key)]: + return Failure(f"{env_file} lacks {' and '.join(missing)}") + return "Basic " + base64.b64encode(":".join(values[key] for key in KEYS).encode()).decode() + + +def children(epic: Epic, authorization: str, http: Http) -> list[dict[str, typing.Any]] | 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.""" + 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[dict[str, typing.Any]] = [] + 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 plan_of(issues: list[dict[str, typing.Any]], epic: Epic, to_markdown: ToMarkdown) -> Plan | Failure: + """The plan the issues hold, in their order. Raises AttributeError, KeyError or TypeError where an issue is not in the shape Jira documents.""" + project = epic.key.rpartition("-")[0] + if strangers := [issue["key"] for issue in issues if not re.fullmatch(rf"{re.escape(project)}-[0-9]+", issue["key"])]: + 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 = {number(issue["key"]) for issue in issues} + with concurrent.futures.ThreadPoolExecutor(CONVERSIONS) as pool: + details = list(pool.map(lambda issue: detail(issue, to_markdown), issues)) + items = [item(issue, ids, text) for issue, text in zip(issues, details)] + return next((found for found in items if isinstance(found, Failure)), None) or Plan([found for found in items if isinstance(found, Item)]) + + +def number(key: str) -> int: + return int(key.rpartition("-")[2]) + + +def detail(issue: dict[str, typing.Any], to_markdown: ToMarkdown) -> str | Failure: + """The issue's description as markdown; empty where it has none.""" + description = issue["fields"]["description"] + if description is None: + return "" + text = to_markdown(description) + return Failure(f"{issue['key']}'s description: {text.reason}") if isinstance(text, Failure) else text.strip() + + +def item(issue: dict[str, typing.Any], ids: set[int], text: str | Failure) -> Item | Failure: + """The item an issue holds, 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.""" + if isinstance(text, Failure): + return text + key, fields = issue["key"], issue["fields"] + release = earliest_release([version["name"] for version in fields["fixVersions"]]) + 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"{key} names no Fix Version that is a semver version, such as 1.2.0; set one in Jira") + blockers = [number(link["inwardIssue"]["key"]) for link in fields["issuelinks"] if link["type"]["inward"] == "is blocked by" and "inwardIssue" in link and link["inwardIssue"]["key"].rpartition("-")[0] == key.rpartition("-")[0]] + scored = scores(key, issue.get("properties", {}).get(PROPERTY, {})) + if isinstance(scored, Failure): + return scored + return Item(number(key), release, scored[2], bold_cell(fields["summary"].strip()), scored[0], scored[1], tuple(sorted(set(blockers) & ids)), text) + + +def earliest_release(names: list[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"item {key}'s Exempt {exempt!r} is not one a todo.md's items table takes") + return levels, moves, exempt diff --git a/bin/plan_store/stores.py b/bin/plan_store/stores.py index 9144cd35..fdca6a5f 100644 --- a/bin/plan_store/stores.py +++ b/bin/plan_store/stores.py @@ -1,6 +1,6 @@ """The one way a tool reads or writes a project's plan: through the store its config names. -The config's `plan` setting names the backend. A path names a markdown file, todo.md, 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. A Jira epic names its child issues, which `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 @@ -144,7 +144,13 @@ 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: diff --git a/bin/plan_store/test_jira_epic.py b/bin/plan_store/test_jira_epic.py new file mode 100644 index 00000000..f3cc98a3 --- /dev/null +++ b/bin/plan_store/test_jira_epic.py @@ -0,0 +1,165 @@ +import base64 +import pathlib +import sys +import tempfile +import unittest + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) + +from failure import Failure +from plan_store import jira_epic +from plan_store.stores import Plan +from project_config.settings import Epic +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" + + +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]] = [] + + def http(self, method: str, url: str, authorization: str, body: object) -> object: + self.calls.append((method, url, authorization, body)) + return self.pages[len(self.calls) - 1] + + def store(self) -> jira_epic.JiraPlan: + return jira_epic.JiraPlan(EPIC, self.env, self.http, text_of) + + 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, "Basic " + base64.b64encode(b"me@example.com:s3cret").decode()) + self.assertEqual(body["jql"], 'parent = "ABC-12" AND statusCategory != Done ORDER BY Rank ASC') # type: ignore[index] + self.assertEqual(body["properties"], [jira_epic.PROPERTY]) # type: ignore[index] + + 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): + item, = self.items(issue("ABC-34")) + 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): + item, = self.items(issue("ABC-34", versions=("v1.2.0", "0.9.1", "Later"))) + 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",)): + failure = self.read(issue("ABC-34", versions=versions)) + self.assertIsInstance(failure, Failure) + self.assertIn("ABC-34", failure.reason) # type: ignore[union-attr] + self.assertIn("Fix Version", failure.reason) # type: ignore[union-attr] + + 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"): + failure = self.read(issue("ABC-34", scores=scores)) # type: ignore[arg-type] + self.assertIsInstance(failure, Failure, scores) + self.assertIn("ABC-34", failure.reason) # type: ignore[union-attr] + + 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("https://acme.atlassian.net: POST /rest/api/3/search/jql answered 401: no")) + + def test_an_answer_in_another_shape_fails_the_read(self): + for page in ([], {"issues": "none"}, {"issues": [{"key": "ABC-1"}]}, {"issues": [{"key": 7, "fields": {}}]}, {"issues": [issue("ABC-1", summary=None)]}): # type: ignore[arg-type] + self.pages, self.calls = [page], [] + self.assertIsInstance(self.store().read(), Failure, page) + + def test_a_description_the_codec_refuses_fails_the_read_naming_the_issue(self): + store = jira_epic.JiraPlan(EPIC, self.env, self.http, lambda document: Failure("adf-codec refused")) + self.pages = [{"issues": [issue("ABC-34", description=adf("x"))]}] + self.assertEqual(store.read(), Failure("ABC-34's description: adf-codec refused")) + + 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, []) + + def test_an_env_file_others_may_read_fails_before_any_request(self): + self.env.chmod(0o644) + self.assertIsInstance(self.read(), Failure) + self.assertEqual(self.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)): + self.assertIsInstance(written, Failure) + self.assertEqual(self.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)) + + +if __name__ == "__main__": + unittest.main() diff --git a/bin/plan_store/test_stores.py b/bin/plan_store/test_stores.py index 8da5c2f2..8397fd1e 100644 --- a/bin/plan_store/test_stores.py +++ b/bin/plan_store/test_stores.py @@ -7,8 +7,10 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) +from project_config.settings import Epic, ProjectConfig, SETTINGS from failure import Failure from plan_store.contract import FIRST, 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 @@ -176,5 +178,21 @@ 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_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() diff --git a/bin/project_config/main.py b/bin/project_config/main.py index 42ca1401..25a525be 100644 --- a/bin/project_config/main.py +++ b/bin/project_config/main.py @@ -21,6 +21,11 @@ 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 it is printed as the config spells it. Such a config must set `env-file`, +and that file hold ATLASSIAN_EMAIL and ATLASSIAN_API_TOKEN. + `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 @@ -81,7 +86,7 @@ def main(argv: list[str]) -> int: 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 diff --git a/bin/project_config/settings.py b/bin/project_config/settings.py index a21d4521..6ec86f74 100644 --- a/bin/project_config/settings.py +++ b/bin/project_config/settings.py @@ -25,6 +25,9 @@ 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) +# The one setting that may name something other than a path: a plan kept as the child issues of a Jira Cloud epic, spelt as `jira:` and the epic's address as the browser shows it. Three readers, seated as the human who writes the config, picked that spelling from four candidates, and one ATLASSIAN_ pair of env-file keys for Jira and Confluence over a pair for each. +JIRA = "jira:" +EPIC_SPELLING = '"jira:https:///browse/" 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 +36,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's `plan` setting spells it.""" + return f"{JIRA}{self.site}/browse/{self.key}" + + @dataclasses.dataclass(frozen=True) class ProjectConfig: - """folder is `~/.claude-projects/`, top is the worktree that asked, and paths holds each of SETTINGS as an absolute path.""" + """folder is `~/.claude-projects/`, top is the worktree that asked, and paths holds each of SETTINGS as an absolute path, but for a plan kept in Jira, which epic holds.""" key: str folder: pathlib.Path top: pathlib.Path @@ -47,6 +62,23 @@ class ProjectConfig: 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; paths then holds no "plan". + 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.""" + return {name: self.plan_label if name == "plan" else str(self.paths[name]) for name in SETTINGS if name == "plan" or name in self.paths} @property def texts(self) -> dict[str, str]: @@ -59,7 +91,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,6 +116,7 @@ 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} + epic = epic_of(values.get("plan")) 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) @@ -89,14 +124,22 @@ def load(top: pathlib.Path, main: pathlib.Path, home: pathlib.Path) -> ProjectCo 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 != "plan"), + *([f"`plan` is {values['plan']!r}, not {SPELLING}, or {EPIC_SPELLING}"] if "plan" in values and paths["plan"] is None and epic is None else []), + *([f"`plan` names a Jira epic, so `{ENV_FILE}` must name the file that holds its credentials"] if epic and ENV_FILE not in values else []), *([f"`{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 {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}) + return ProjectConfig(file.parent.name, file.parent, top, {name: path for name, path in paths.items() if path}, env_file, waits is True, **{name.replace("-", "_"): str(values[name]) for name in checks if name in values}, epic=epic) + + +def epic_of(value: object) -> Epic | None: + """The epic a `plan` setting's value spells; None where it spells none. Only https, so the credentials are never sent in the clear.""" + 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 language_fault(value: object) -> str | None: diff --git a/bin/project_config/test_project_config.py b/bin/project_config/test_project_config.py index cc39c44f..d6f8c13d 100644 --- a/bin/project_config/test_project_config.py +++ b/bin/project_config/test_project_config.py @@ -8,7 +8,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 +28,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 +86,36 @@ 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 spelled in ("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-{len(spelled)}-{hash(spelled) % 1000}", 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:///browse/", reason) + for config in (self.home / ".claude-projects").glob("*/config.toml"): + config.unlink() + 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" @@ -325,6 +358,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) diff --git a/bin/rank_todo.py b/bin/rank_todo.py index 1bc6b6f0..ff2ee2e1 100755 --- a/bin/rank_todo.py +++ b/bin/rank_todo.py @@ -106,10 +106,12 @@ 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: + 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: diff --git a/bin/rule_hook/test_rule_hook.py b/bin/rule_hook/test_rule_hook.py index 3e003f8f..13682da1 100644 --- a/bin/rule_hook/test_rule_hook.py +++ b/bin/rule_hook/test_rule_hook.py @@ -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) diff --git a/bin/rule_hook/todo_check.py b/bin/rule_hook/todo_check.py index c7947911..43edc10c 100644 --- a/bin/rule_hook/todo_check.py +++ b/bin/rule_hook/todo_check.py @@ -32,9 +32,9 @@ 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") - # 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)): + todo, tracked = config.plan_file, config.tracked("plan") + # A plan outside the checkout has no commit in the checkout to differ from, so it is checked on every call. A plan in Jira is no file, and Jira's backlog ranks it. + if todo is None or not todo.is_file() or (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 +43,9 @@ 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): + todo = None if isinstance(config, Failure) else config.plan_file + if isinstance(config, Failure) or 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)] diff --git a/bin/test_rank_todo.py b/bin/test_rank_todo.py index 2d1787e3..13f2a5d2 100644 --- a/bin/test_rank_todo.py +++ b/bin/test_rank_todo.py @@ -57,6 +57,17 @@ 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 ((), ("--check",), (str(todo),)): + 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(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)) diff --git a/docs/decisions.md b/docs/decisions.md index fc4abb06..bd1bd8d4 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -21,6 +21,7 @@ Each project principle states one rule that the decisions below apply; their ent - machine load: a heavy command waits for one of the machine's heavy slots, one for every 4 CPUs, which every session shares, and loop-claude starts a worker only while at least a quarter of the machine's memory is available - principles: about seven things per level, four or five where they act on each other, more where a reader finds them by name; crossing a limit asks for a grouping or a recorded reason - project config: a tool that reads a file's commits says where it does not support that file, and the work goes on +- project config: `plan` names 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: `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}` - 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 @@ -277,6 +278,17 @@ Valid while the later fixes per finished chunk, which `score-outcomes` and the r Messages keep each file's usual name, such as `todo.md`, as its label, since the config keeps the names. Revisit at 0.13.0, which plans the support for `score-outcomes`, the routing figures, the release standing and the owed scoring run. +## project config: `plan` names 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:///browse/"` over the bare address, a `jira:` 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. A tool that works on the file, such as `rank_todo.py` or rule-hook's rank check, refuses or skips a plan in Jira. + ## 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}` 2026-11-14, larv-review. Serves goal 1.6: a client's team reads its docs, Jira text, commits and pull requests in its own language and format. Valid while one language and one template per title serve a project. -- 2.52.0 From 543d85238ac7636a22bc4787ccc5bd17b43de4c3 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sat, 14 Nov 2026 19:14:12 +0100 Subject: [PATCH 04/14] =?UTF-8?q?Answer=20security=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=200=20=F0=9F=9F=A1=20(0=20misread);=20the=20revie?= =?UTF-8?q?w=20found=20nothing?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit -- 2.52.0 From 728c7b004a13fa05f79d678b031df8f14d3a8ecc Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sat, 14 Nov 2026 19:18:02 +0100 Subject: [PATCH 05/14] Test the search's whole body, an issue without properties and a v-named earliest version --- bin/plan_store/test_jira_epic.py | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/bin/plan_store/test_jira_epic.py b/bin/plan_store/test_jira_epic.py index f3cc98a3..0a44813d 100644 --- a/bin/plan_store/test_jira_epic.py +++ b/bin/plan_store/test_jira_epic.py @@ -67,8 +67,12 @@ class JiraPlan(unittest.TestCase): method, url, authorization, body = self.calls[0] self.assertEqual((method, url), ("POST", SEARCH)) self.assertEqual(authorization, "Basic " + base64.b64encode(b"me@example.com:s3cret").decode()) - self.assertEqual(body["jql"], 'parent = "ABC-12" AND statusCategory != Done ORDER BY Rank ASC') # type: ignore[index] - self.assertEqual(body["properties"], [jira_epic.PROPERTY]) # type: ignore[index] + 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_issue_reads_as_an_item_under_its_number(self): scores = {"L": 1, "E": 2, "I": 3, "S": 1, "Moves": "1 by 9", "Exempt": "owner"} @@ -81,16 +85,19 @@ class JiraPlan(unittest.TestCase): self.assertEqual([item.id for item in found], [40, 7, 21]) def test_an_issue_nobody_scored_reads_without_scores(self): - item, = self.items(issue("ABC-34")) - self.assertEqual((item.scores, item.moves, item.exempt, item.detail, item.likelihood), ({}, (), "", "", 0)) + bare = issue("ABC-35") + del bare["properties"] + for item in self.items(issue("ABC-34"), bare): + 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): - item, = self.items(issue("ABC-34", versions=("v1.2.0", "0.9.1", "Later"))) - self.assertEqual(item.release, release_of("0.9.1")) + for versions in (("v1.2.0", "0.9.1", "Later"), ("1.2.0", "v0.9.1")): + item, = self.items(issue("ABC-34", versions=versions)) + self.assertEqual(item.release, release_of("0.9.1"), versions) def test_an_issue_with_no_semver_fix_version_fails_the_read_naming_it(self): for versions in ((), ("Sprint 4",)): -- 2.52.0 From d008dc09f2d9b5870ddb1e2460646d1d29f315c1 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sat, 14 Nov 2026 19:26:04 +0100 Subject: [PATCH 06/14] Sort the Jira store's imports --- bin/plan_store/jira_epic.py | 8 ++++---- bin/plan_store/test_jira_epic.py | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/bin/plan_store/jira_epic.py b/bin/plan_store/jira_epic.py index df1e74c2..ddc057d7 100644 --- a/bin/plan_store/jira_epic.py +++ b/bin/plan_store/jira_epic.py @@ -16,13 +16,13 @@ import urllib.parse import urllib.request from adf_codec.convert import adf_to_markdown -from failure import Failure -from mattermost_dm.dm import parse_env from plan_store.markdown_edits import bold_cell -from plan_store.stores import Plan, Written from project_config.settings import Epic -from release_plan.release import parsed, Release, tagged +from failure import Failure from release_plan.todo_table import is_exempt, Item, MOVES, parse_moves, parse_scores, SHAPE +from mattermost_dm.dm import parse_env +from release_plan.release import parsed, Release, tagged +from plan_store.stores import Plan, Written # One pair of keys for Jira and Confluence, which one Atlassian account's API token opens both. KEYS = ("ATLASSIAN_EMAIL", "ATLASSIAN_API_TOKEN") diff --git a/bin/plan_store/test_jira_epic.py b/bin/plan_store/test_jira_epic.py index 0a44813d..61380c07 100644 --- a/bin/plan_store/test_jira_epic.py +++ b/bin/plan_store/test_jira_epic.py @@ -6,10 +6,10 @@ import unittest 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 project_config.settings import Epic from release_plan.release import release_of EPIC = Epic("https://acme.atlassian.net", "ABC-12") -- 2.52.0 From 8ee67ed2b711d5f47d1a2d21b402b3781f50d9be Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sat, 14 Nov 2026 19:40:36 +0100 Subject: [PATCH 07/14] =?UTF-8?q?Answer=20stability=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=2010=20=F0=9F=9F=A1=20(0=20misread);=20share=20on?= =?UTF-8?q?e=20REST=20client=20and=20env-file=20reader,=20read=20each=20is?= =?UTF-8?q?sue=20into=20a=20checked=20value,=20convert=20descriptions=20la?= =?UTF-8?q?st,=20and=20simplify=20the=20hard=20places=20the=20change=20tou?= =?UTF-8?q?ched?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 2 + README.md | 16 +- bin/larv_review/plan.py | 13 +- bin/larv_review/test_larv_review.py | 2 +- bin/mattermost_dm/dm.py | 73 ++------- bin/mattermost_dm/test_mattermost_dm.py | 102 ++----------- bin/plan_store/jira_epic.py | 189 +++++++++++++----------- bin/plan_store/stores.py | 4 +- bin/plan_store/test_jira_epic.py | 105 ++++++++++--- bin/rest_client/__init__.py | 0 bin/rest_client/env_file.py | 34 +++++ bin/rest_client/json_request.py | 52 +++++++ bin/rest_client/test_env_file.py | 50 +++++++ bin/rest_client/test_json_request.py | 120 +++++++++++++++ bin/rule_hook/todo_check.py | 13 +- bin/todo_item/main.py | 9 +- 16 files changed, 501 insertions(+), 283 deletions(-) create mode 100644 bin/rest_client/__init__.py create mode 100644 bin/rest_client/env_file.py create mode 100644 bin/rest_client/json_request.py create mode 100644 bin/rest_client/test_env_file.py create mode 100644 bin/rest_client/test_json_request.py diff --git a/.gitignore b/.gitignore index 39346409..2094a65b 100644 --- a/.gitignore +++ b/.gitignore @@ -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 diff --git a/README.md b/README.md index 19adb62b..301fc28d 100644 --- a/README.md +++ b/README.md @@ -100,10 +100,19 @@ A project's config may set four more things, each optional, as `project-config - A project whose pull requests need a human's approval sets `wait-for-approval = true` in its config. `chunk-pr merge` then waits, once the checks have passed, until GitHub reports the pull request approved as its branch protection requires, and merges it. It refuses on Gitea, where a reviewer requested changes and where the protection requires no review. It gives up after 90 minutes without an approval; run it again once the pull request is approved. Left out, the setting is false. -A client that plans in Jira Cloud names an epic as the plan, as `plan = "jira:https://acme.atlassian.net/browse/ABC-12"`: `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. An issue's number is the item's ID, so every child lies in the epic's own Jira project, and a read fails naming one that doesn't. The summary is the tagline, the description the detail, the earliest Fix Version named as a semver version the release, and an "is blocked by" link to another open child a blocker. The scores sit in 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. The config's `env-file` must hold `ATLASSIAN_EMAIL` and `ATLASSIAN_API_TOKEN`, an API token of that Atlassian account. The loop only reads such a plan so far: `todo-item add`, `edit`, `move` and `finish` fail saying so, `rank_todo.py` refuses it, and rule-hook's rank check skips it. What isn't supported for a plan outside the checkout, below, isn't for a plan in Jira either. - 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:`, 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. + ```sh mkdir -p ~/.claude-projects/acme && cd ~/.claude-projects/acme git init @@ -180,11 +189,12 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a - `machine_load/` takes the machine's heavy slots, its shared lock files, for `run_heavy`, and 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` and the reader of a Jira epic's child issues in `jira_epic.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. diff --git a/bin/larv_review/plan.py b/bin/larv_review/plan.py index e4269e74..d858c620 100644 --- a/bin/larv_review/plan.py +++ b/bin/larv_review/plan.py @@ -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.plan_label}") - 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: diff --git a/bin/larv_review/test_larv_review.py b/bin/larv_review/test_larv_review.py index 187de198..2657aad3 100644 --- a/bin/larv_review/test_larv_review.py +++ b/bin/larv_review/test_larv_review.py @@ -590,7 +590,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 diff --git a/bin/mattermost_dm/dm.py b/bin/mattermost_dm/dm.py index 068df948..f3ac085f 100644 --- a/bin/mattermost_dm/dm.py +++ b/bin/mattermost_dm/dm.py @@ -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 "" diff --git a/bin/mattermost_dm/test_mattermost_dm.py b/bin/mattermost_dm/test_mattermost_dm.py index ffa5ca6e..0427cbac 100644 --- a/bin/mattermost_dm/test_mattermost_dm.py +++ b/bin/mattermost_dm/test_mattermost_dm.py @@ -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"")) - 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): diff --git a/bin/plan_store/jira_epic.py b/bin/plan_store/jira_epic.py index ddc057d7..d6e6a995 100644 --- a/bin/plan_store/jira_epic.py +++ b/bin/plan_store/jira_epic.py @@ -1,75 +1,72 @@ """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 the epic's children all lie in the epic's own Jira project: ABC-34 is item 34 of the plan under ABC-12. The summary is the tagline, the description the detail, the earliest Fix Version the release, and an "is blocked by" link a blocker. L, E, I, S, Moves and Exempt sit in one issue property, PROPERTY, which needs no Jira admin to set up; an issue a teammate filed holds none, and reads as an item without scores. +An item is an open child issue. Its ID is the issue's number, so every child must be in the epic's own Jira project: ABC-34 is item 34 of the plan under ABC-12. The summary is the tagline, the description the detail, the earliest Fix Version the release, and an "is blocked by" link a blocker. L, E, I, S, Moves and Exempt sit in one issue property, PROPERTY, which needs no Jira admin to set up; an issue a 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 concurrent.futures import dataclasses -import http.client -import json import pathlib import re import typing -import urllib.error -import urllib.parse -import urllib.request from adf_codec.convert import adf_to_markdown 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 release_plan.todo_table import is_exempt, Item, MOVES, parse_moves, parse_scores, SHAPE -from mattermost_dm.dm import parse_env +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, which one Atlassian account's API token opens both. +# 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 -# The adf-codec containers run at once: each description is one run. -CONVERSIONS = 8 +# The adf-codec containers run at once, each converting one description: one heavy slot's CPUs. +CONVERSIONS = 4 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, and returns the JSON answer, or a Failure saying why there is none. +# Sends a request with the Authorization header given, the body as JSON where there is one, and returns the JSON answer, or a Failure saying why there is none. Http = typing.Callable[[str, str, str, object], object] ToMarkdown = typing.Callable[[dict[str, typing.Any]], str | Failure] -class NoRedirect(urllib.request.HTTPRedirectHandler): - """Refuses every redirect, which Jira's API never sends: urllib would resend the credentials 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) -> object: - """The JSON that url answers; a Failure naming the request where it answers an error, breaks HTTP or answers something other than JSON, and saying so where the site cannot be reached.""" - request_name = f"{method} {urllib.parse.urlsplit(url).path}" - request = urllib.request.Request(url, json.dumps(body).encode(), {"Authorization": authorization, "Content-Type": "application/json", "Accept": "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}: {failure.reason}") - except http.client.HTTPException as failure: - return Failure(f"{request_name} got a broken answer: {failure!r}") - except (OSError, ValueError) as failure: - return Failure(f"cannot be reached: {getattr(failure, 'reason', failure)}") - try: - return json.loads(raw) - except ValueError: - return Failure(f"{request_name} answered with something other than JSON") + 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) @@ -92,13 +89,11 @@ class JiraPlan: authorization = basic_auth(self.env_file) if isinstance(authorization, Failure): return authorization - issues = children(self.epic, authorization, self.http) - if isinstance(issues, Failure): - return Failure(f"{self.epic.site}: {issues.reason}") - try: - return plan_of(issues, self.epic, self.to_markdown) - except (AttributeError, KeyError, TypeError): - return Failure(f"{self.epic.site} answered issues in another shape than Jira Cloud's REST API version 3 documents") + 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) @@ -111,31 +106,26 @@ class JiraPlan: def basic_auth(env_file: pathlib.Path) -> str | Failure: - """The Authorization header for the email and API token that env_file's KEY=value lines hold.""" - try: - mode = env_file.stat().st_mode - text = env_file.read_text(encoding="utf-8") - except FileNotFoundError: - return Failure(f"{env_file} does not exist; it needs {' and '.join(KEYS)}") - except (OSError, UnicodeDecodeError) as failure: - return Failure(f"cannot read {env_file}: {failure}") - if mode & 0o077: - return Failure(f"{env_file} holds an API token, so only its owner may read it; run chmod 600 {env_file}") - values = parse_env(text) - if missing := [key for key in KEYS if not values.get(key)]: - return Failure(f"{env_file} lacks {' and '.join(missing)}") + """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[dict[str, typing.Any]] | Failure: +def children(epic: Epic, authorization: str, http: Http) -> list[object] | Failure: """The epic's open child issues in backlog order, which is the order the team ranks them in. An issue in a done status is a finished item, so it is no longer in the plan.""" + # The 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[dict[str, typing.Any]] = [] + 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): @@ -149,48 +139,71 @@ def children(epic: Epic, authorization: str, http: Http) -> list[dict[str, typin return Failure(f"the search for {epic.key}'s children did not end within {MAX_PAGES} pages") -def plan_of(issues: list[dict[str, typing.Any]], epic: Epic, to_markdown: ToMarkdown) -> Plan | Failure: - """The plan the issues hold, in their order. Raises AttributeError, KeyError or TypeError where an issue is not in the shape Jira documents.""" +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): + 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 is of another type") + 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 not re.fullmatch(rf"{re.escape(project)}-[0-9]+", issue["key"])]: + 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 = {number(issue["key"]) for issue in issues} - with concurrent.futures.ThreadPoolExecutor(CONVERSIONS) as pool: - details = list(pool.map(lambda issue: detail(issue, to_markdown), issues)) - items = [item(issue, ids, text) for issue, text in zip(issues, details)] - return next((found for found in items if isinstance(found, Failure)), None) or Plan([found for found in items if isinstance(found, Item)]) + 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 each costs a container run, which a read that fails doesn't need. + texts = details(issues, 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 detail(issue: dict[str, typing.Any], to_markdown: ToMarkdown) -> str | Failure: - """The issue's description as markdown; empty where it has none.""" - description = issue["fields"]["description"] - if description is None: - return "" - text = to_markdown(description) - return Failure(f"{issue['key']}'s description: {text.reason}") if isinstance(text, Failure) else text.strip() +def details(issues: list[Issue], to_markdown: ToMarkdown) -> dict[int, str] | Failure: + """Each described issue's description as markdown, under the issue's number. The first converts alone, since that run builds the codec's image where the machine has none; the rest convert CONVERSIONS at a time.""" + described = [(issue, issue.description) for issue in issues if issue.description is not None] + texts: list[str | Failure] = [to_markdown(description) for _, description in described[:1]] + if not any(isinstance(text, Failure) for text in texts): + with concurrent.futures.ThreadPoolExecutor(CONVERSIONS) as pool: + texts += pool.map(to_markdown, [description for _, description in described[1:]]) + found = {} + for (issue, _), text in zip(described, texts): + if isinstance(text, Failure): + return Failure(f"{issue.key}'s description: {text.reason}") + found[issue.number] = text.strip() + return found -def item(issue: dict[str, typing.Any], ids: set[int], text: str | Failure) -> Item | Failure: - """The item an issue holds, 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.""" - if isinstance(text, Failure): - return text - key, fields = issue["key"], issue["fields"] - release = earliest_release([version["name"] for version in fields["fixVersions"]]) +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"{key} names no Fix Version that is a semver version, such as 1.2.0; set one in Jira") - blockers = [number(link["inwardIssue"]["key"]) for link in fields["issuelinks"] if link["type"]["inward"] == "is blocked by" and "inwardIssue" in link and link["inwardIssue"]["key"].rpartition("-")[0] == key.rpartition("-")[0]] - scored = scores(key, issue.get("properties", {}).get(PROPERTY, {})) + 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 - return Item(number(key), release, scored[2], bold_cell(fields["summary"].strip()), scored[0], scored[1], tuple(sorted(set(blockers) & ids)), text) + 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: list[str]) -> Release | None: +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) @@ -209,5 +222,5 @@ def scores(key: str, held: object) -> tuple[dict[str, int], typing.Any, typing.A return moves exempt = named.get("Exempt", "") if not is_exempt(exempt): - return Failure(f"item {key}'s Exempt {exempt!r} is not one a todo.md's items table takes") + 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 diff --git a/bin/plan_store/stores.py b/bin/plan_store/stores.py index fdca6a5f..3c0c8d36 100644 --- a/bin/plan_store/stores.py +++ b/bin/plan_store/stores.py @@ -1,6 +1,6 @@ """The one way a tool reads or writes a project's plan: through the store its config names. -The config's `plan` setting names the backend. A path names a markdown file, todo.md. A Jira epic names its child issues, which `jira_epic` reads and nothing writes yet. An agent reads and changes the plan with `todo-item`, which works through the same store. +The config's `plan` setting names the backend. A path names a markdown file, todo.md. `jira:` and an epic's address name a Jira epic, whose open child issues `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 @@ -44,7 +44,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: diff --git a/bin/plan_store/test_jira_epic.py b/bin/plan_store/test_jira_epic.py index 61380c07..7c6d57b1 100644 --- a/bin/plan_store/test_jira_epic.py +++ b/bin/plan_store/test_jira_epic.py @@ -3,6 +3,7 @@ import pathlib import sys import tempfile import unittest +import unittest.mock sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) @@ -14,6 +15,7 @@ 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]: @@ -42,13 +44,24 @@ class JiraPlan(unittest.TestCase): 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[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, document: dict[str, object]) -> str | Failure: + self.converted.append(document) + return text_of(document) + def store(self) -> jira_epic.JiraPlan: - return jira_epic.JiraPlan(EPIC, self.env, self.http, text_of) + 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)}], [] @@ -66,7 +79,7 @@ class JiraPlan(unittest.TestCase): self.read() method, url, authorization, body = self.calls[0] self.assertEqual((method, url), ("POST", SEARCH)) - self.assertEqual(authorization, "Basic " + base64.b64encode(b"me@example.com:s3cret").decode()) + self.assertEqual(authorization, AUTHORIZATION) self.assertEqual(body, { "jql": 'parent = "ABC-12" AND statusCategory != Done ORDER BY Rank ASC', "fields": ["summary", "description", "fixVersions", "issuelinks"], @@ -74,6 +87,12 @@ class JiraPlan(unittest.TestCase): "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."))) @@ -96,15 +115,16 @@ class JiraPlan(unittest.TestCase): 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")): - item, = self.items(issue("ABC-34", versions=versions)) - self.assertEqual(item.release, release_of("0.9.1"), versions) + 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",)): - failure = self.read(issue("ABC-34", versions=versions)) - self.assertIsInstance(failure, Failure) - self.assertIn("ABC-34", failure.reason) # type: ignore[union-attr] - self.assertIn("Fix Version", failure.reason) # type: ignore[union-attr] + 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")) @@ -113,9 +133,13 @@ class JiraPlan(unittest.TestCase): 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"): - failure = self.read(issue("ABC-34", scores=scores)) # type: ignore[arg-type] - self.assertIsInstance(failure, Failure, scores) - self.assertIn("ABC-34", failure.reason) # type: ignore[union-attr] + 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")]}] @@ -126,12 +150,33 @@ class JiraPlan(unittest.TestCase): 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("https://acme.atlassian.net: 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): - for page in ([], {"issues": "none"}, {"issues": [{"key": "ABC-1"}]}, {"issues": [{"key": 7, "fields": {}}]}, {"issues": [issue("ABC-1", summary=None)]}): # type: ignore[arg-type] - self.pages, self.calls = [page], [] - self.assertIsInstance(self.store().read(), Failure, page) + for page in ([], {"issues": "none"}, {"issues": ["ABC-1"]}, {"issues": [{"key": 7, "fields": {}}]}, {"issues": [{"key": "abc", "fields": {}}]}): + with self.subTest(page=page): + self.pages, self.calls = [page], [] + self.assertIsInstance(self.store().read(), Failure) + + 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 | {"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_each_description_once_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(len(self.converted), 3) + + def test_a_first_description_the_codec_refuses_converts_no_other(self): + calls: list[object] = [] + store = jira_epic.JiraPlan(EPIC, self.env, self.http, lambda document: calls.append(document) or Failure("no docker")) # type: ignore[func-returns-value] + self.pages = [{"issues": [issue("ABC-1", description=adf("One.")), issue("ABC-2", description=adf("Two."))]}] + self.assertEqual(store.read(), Failure("ABC-1's description: no docker")) + self.assertEqual(len(calls), 1) def test_a_description_the_codec_refuses_fails_the_read_naming_the_issue(self): store = jira_epic.JiraPlan(EPIC, self.env, self.http, lambda document: Failure("adf-codec refused")) @@ -143,12 +188,12 @@ class JiraPlan(unittest.TestCase): failure = self.read() self.assertIsInstance(failure, Failure) self.assertIn("ATLASSIAN_API_TOKEN", failure.reason) # type: ignore[union-attr] - self.assertEqual(self.calls, []) + 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.assertIsInstance(self.read(), Failure) - self.assertEqual(self.calls, []) + 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() @@ -161,12 +206,32 @@ class JiraPlan(unittest.TestCase): 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)): - self.assertIsInstance(written, Failure) - self.assertEqual(self.calls, []) + 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() diff --git a/bin/rest_client/__init__.py b/bin/rest_client/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/bin/rest_client/env_file.py b/bin/rest_client/env_file.py new file mode 100644 index 00000000..ddf1831a --- /dev/null +++ b/bin/rest_client/env_file.py @@ -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 diff --git a/bin/rest_client/json_request.py b/bin/rest_client/json_request.py new file mode 100644 index 00000000..e6c517e3 --- /dev/null +++ b/bin/rest_client/json_request.py @@ -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 "" diff --git a/bin/rest_client/test_env_file.py b/bin/rest_client/test_env_file.py new file mode 100644 index 00000000..56ff934a --- /dev/null +++ b/bin/rest_client/test_env_file.py @@ -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\n"), {"A": "1", "B": "two words", "C": "3", "E": "a=b"}) + + +if __name__ == "__main__": + unittest.main() diff --git a/bin/rest_client/test_json_request.py b/bin/rest_client/test_json_request.py new file mode 100644 index 00000000..d017329f --- /dev/null +++ b/bin/rest_client/test_json_request.py @@ -0,0 +1,120 @@ +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"")) + 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_an_error_whose_body_is_not_json_names_the_status_alone(self): + base = self.serve((403, b"")) + 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() diff --git a/bin/rule_hook/todo_check.py b/bin/rule_hook/todo_check.py index 43edc10c..a06468ab 100644 --- a/bin/rule_hook/todo_check.py +++ b/bin/rule_hook/todo_check.py @@ -33,8 +33,11 @@ def todo_breaches(directory: str, home: pathlib.Path, own: pathlib.Path = OWN) - 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.plan_file, config.tracked("plan") - # A plan outside the checkout has no commit in the checkout to differ from, so it is checked on every call. A plan in Jira is no file, and Jira's backlog ranks it. - if todo is None or not todo.is_file() or (tracked is not None and not changed(top, todo, tracked)): + # 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 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,8 +46,10 @@ 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.""" - todo = None if isinstance(config, Failure) else config.plan_file - if isinstance(config, Failure) or todo is None or not todo.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 [] if not todo.is_file() or not changed(str(config.folder), todo, todo.relative_to(config.folder).as_posix()): return [] diff --git a/bin/todo_item/main.py b/bin/todo_item/main.py index 0a7b5a9e..c373369c 100644 --- a/bin/todo_item/main.py +++ b/bin/todo_item/main.py @@ -10,14 +10,15 @@ usage: todo-item list [--release ] todo-item finish [--changelog | --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 , 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 ` holds no item.` show prints `From :`, then the table's header and divider, item 's row, and its detail under -- 2.52.0 From 9ac89c3d503b3c57aeb7df9b0d9f2a63c461afb8 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sat, 14 Nov 2026 19:40:36 +0100 Subject: [PATCH 08/14] =?UTF-8?q?Answer=20product-owner=20round=201:=201?= =?UTF-8?q?=20=F0=9F=94=B4,=202=20=F0=9F=9F=A1=20(1=20misread);=20list=20a?= =?UTF-8?q?n=20unscored=20joining=20item,=20and=20pass=20rank=5Ftodo.py=20?= =?UTF-8?q?--check=20for=20a=20plan=20in=20Jira?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin/chunk_preflight/facts.py | 4 ++-- bin/chunk_preflight/test_chunk_preflight.py | 11 +++++++++-- bin/rank_todo.py | 3 +++ bin/test_rank_todo.py | 6 ++++-- 4 files changed, 18 insertions(+), 6 deletions(-) diff --git a/bin/chunk_preflight/facts.py b/bin/chunk_preflight/facts.py index 470bbb23..cd7cdb4d 100644 --- a/bin/chunk_preflight/facts.py +++ b/bin/chunk_preflight/facts.py @@ -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.places.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] diff --git a/bin/chunk_preflight/test_chunk_preflight.py b/bin/chunk_preflight/test_chunk_preflight.py index e6e42ac7..511692cc 100644 --- a/bin/chunk_preflight/test_chunk_preflight.py +++ b/bin/chunk_preflight/test_chunk_preflight.py @@ -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) diff --git a/bin/rank_todo.py b/bin/rank_todo.py index ff2ee2e1..14130d0f 100755 --- a/bin/rank_todo.py +++ b/bin/rank_todo.py @@ -106,6 +106,9 @@ def main(argv: list[str]) -> int: config = located(None, pathlib.Path.home()) if isinstance(config, Failure): return fail(config) + 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 diff --git a/bin/test_rank_todo.py b/bin/test_rank_todo.py index 13f2a5d2..3fc726de 100644 --- a/bin/test_rank_todo.py +++ b/bin/test_rank_todo.py @@ -64,8 +64,10 @@ class Main(unittest.TestCase): 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 ((), ("--check",), (str(todo),)): - 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")) + 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): -- 2.52.0 From 0f142f8da5bd8cfabbc254002d2860dc8cc8bdc5 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sat, 14 Nov 2026 19:40:36 +0100 Subject: [PATCH 09/14] =?UTF-8?q?Answer=20prose=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=207=20=F0=9F=9F=A1=20(0=20misread);=20reword=20th?= =?UTF-8?q?e=20help=20text=20and=20comments,=20and=20sort=20the=20decision?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin/chunk_preflight/gathered.py | 2 +- bin/project_config/main.py | 4 ++-- bin/project_config/settings.py | 6 +++--- docs/decisions.md | 24 ++++++++++++------------ 4 files changed, 18 insertions(+), 18 deletions(-) diff --git a/bin/chunk_preflight/gathered.py b/bin/chunk_preflight/gathered.py index 07cab36d..bdc18fef 100644 --- a/bin/chunk_preflight/gathered.py +++ b/bin/chunk_preflight/gathered.py @@ -81,7 +81,7 @@ 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. + # 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 diff --git a/bin/project_config/main.py b/bin/project_config/main.py index 25a525be..a3f236bf 100644 --- a/bin/project_config/main.py +++ b/bin/project_config/main.py @@ -23,8 +23,8 @@ starts with / or ~/. In a worktree, a "checkout:" path is the worktree's own fil `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 it is printed as the config spells it. Such a config must set `env-file`, -and that file hold ATLASSIAN_EMAIL and ATLASSIAN_API_TOKEN. +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. `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 diff --git a/bin/project_config/settings.py b/bin/project_config/settings.py index 6ec86f74..37797991 100644 --- a/bin/project_config/settings.py +++ b/bin/project_config/settings.py @@ -25,7 +25,7 @@ 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) -# The one setting that may name something other than a path: a plan kept as the child issues of a Jira Cloud epic, spelt as `jira:` and the epic's address as the browser shows it. Three readers, seated as the human who writes the config, picked that spelling from four candidates, and one ATLASSIAN_ pair of env-file keys for Jira and Confluence over a pair for each. +# What opens a `plan` setting that names a Jira Cloud epic in place of a path: `jira:`, then the epic's address as the browser shows it. `plan` is the one setting that may name something other than a path. JIRA = "jira:" EPIC_SPELLING = '"jira:https:///browse/" 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" @@ -50,7 +50,7 @@ class Epic: @dataclasses.dataclass(frozen=True) class ProjectConfig: - """folder is `~/.claude-projects/`, top is the worktree that asked, and paths holds each of SETTINGS as an absolute path, but for a plan kept in Jira, which epic holds.""" + """folder is `~/.claude-projects/`, top is the worktree that asked, and paths holds each of SETTINGS as an absolute path, except `plan` where the plan is kept in Jira.""" key: str folder: pathlib.Path top: pathlib.Path @@ -62,7 +62,7 @@ class ProjectConfig: 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; paths then holds no "plan". + # The epic whose child issues are the plan, where the config's `plan` names one. epic: Epic | None = None @property diff --git a/docs/decisions.md b/docs/decisions.md index bd1bd8d4..d8e23dbb 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -21,8 +21,8 @@ Each project principle states one rule that the decisions below apply; their ent - machine load: a heavy command waits for one of the machine's heavy slots, one for every 4 CPUs, which every session shares, and loop-claude starts a worker only while at least a quarter of the machine's memory is available - principles: about seven things per level, four or five where they act on each other, more where a reader finds them by name; crossing a limit asks for a grouping or a recorded reason - project config: a tool that reads a file's commits says where it does not support that file, and the work goes on -- project config: `plan` names 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: `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 - 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 @@ -278,17 +278,6 @@ Valid while the later fixes per finished chunk, which `score-outcomes` and the r Messages keep each file's usual name, such as `todo.md`, as its label, since the config keeps the names. Revisit at 0.13.0, which plans the support for `score-outcomes`, the routing figures, the release standing and the owed scoring run. -## project config: `plan` names 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:///browse/"` over the bare address, a `jira:` 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. A tool that works on the file, such as `rank_todo.py` or rule-hook's rank check, refuses or skips a plan in Jira. - ## 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}` 2026-11-14, larv-review. Serves goal 1.6: a client's team reads its docs, Jira text, commits and pull requests in its own language and format. Valid while one language and one template per title serve a project. @@ -302,6 +291,17 @@ 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 ` 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:///browse/"` over the bare address, a `jira:` 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. + ## 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. -- 2.52.0 From 4e0e7e655d0452d0db9258840995f2be600757cb Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sat, 14 Nov 2026 19:44:51 +0100 Subject: [PATCH 10/14] =?UTF-8?q?Answer=20architecture=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=202=20=F0=9F=9F=A1=20(0=20misread);=20file=20item?= =?UTF-8?q?=20379=20for=20one=20container=20per=20plan=20read=20and=20a=20?= =?UTF-8?q?heavy=20slot=20around=20the=20codec's=20build?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- todo.md | 30 ++++++++++++++++++++++++++++-- 1 file changed, 28 insertions(+), 2 deletions(-) diff --git a/todo.md b/todo.md index bd3cb3f2..092647e3 100644 --- a/todo.md +++ b/todo.md @@ -6,13 +6,14 @@ `Bar = 0.1` -`Next ID = 379` +`Next ID = 380` ## 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.** | 4 | 2 | 3 | 7 | 5 | 1.6 by 6 | 1.2 | +| 379 | 0.11.0 | 351 | | **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.** | 3 | 2 | 3 | 6 | 4 | code health by 2, 1.5 by 2 | 3.2 | | 378 | 0.11.0 | 351 | | **Name the branches, worktrees and commit and PR titles of a Jira plan's chunks by the issue key, as in `ABC-123` and `ABC-123 - ...`.** | 2 | 2 | 3 | 5 | 2 | 1.6 by 4 | 1.4 | | 353 | 0.11.0 | 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 | @@ -20,7 +21,7 @@ | 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 | 351, 379 | | **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 | @@ -91,6 +92,31 @@ lilleman's calls, 2026-11-12. One epic is one project's plan. An item is a child Item IDs stay `int`: the store holds the Jira project key from the config, and an issue's number is the item's ID, so the 30 or so modules that read an ID as an int stay as they are. The store refuses a child issue from another Jira project. This item only reads: `add`, `edit` and `finish` fail, saying item 352 builds them. lilleman's call, 2026-11-14: item 377 hands the plan to a reviewer without a shell, and item 378 names branches and titles by the issue key. Re-scored 2026-11-14 at L 4: a new pattern, HTTP to Jira Cloud with entity properties, rank and ADF, across plan_store and project_config. +### 379. 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. + +Two changes in `bin/adf_codec/`, in one item since both change the codec and its tests. Item 352 waits for this one. It waits for item 351, which adds `bin/plan_store/jira_epic.py`. + +**One container per read.** Today a read of a Jira epic with N described issues starts N containers, four at a time: `details` in `bin/plan_store/jira_epic.py` calls `adf_to_markdown` in `bin/adf_codec/convert.py` once per description. `todo-item show ` converts all N to print one, and `larv-review needs-scoring-run` converts all N twice, since it reads a plan outside the checkout twice. To keep that bearable, `details` carries a thread pool, the constant `CONVERSIONS` and a rule that the first description converts alone. Two later items get harder while this stands: + +- Item 352 scores each issue a teammate filed, and its worker reads an issue's scope with `todo-item show `. Scoring M unscored issues of an epic with N described ones is M ร— N container runs: 20 unscored issues in an epic of 40 is 800 runs. Item 352 would otherwise have to add a way to read one item past `PlanStore.read()`, which changes the protocol, `FilePlan`, the fakes, the contract and four readers. +- Item 375 runs several chunks at once. `CONVERSIONS = 4` is commented as one heavy slot's CPUs, but no slot is taken, so K chunks that read the plan at once run 4 ร— K containers. + +Items 353 and 355 add a conversion to each read of the goals and of each record in Confluence, each with a container start of its own. + +The smallest change leaves `Plan` as it is, a plain value holding every detail: + +- `bin/adf_codec/node_shim/shim.mjs` gets a mode that takes a JSON array of ADF documents on stdin and prints a JSON array of markdown texts. A refused document answers with its index, so the Failure still names the issue. +- `convert.py` gets one function beside `adf_to_markdown` that takes the documents and returns the texts, or a Failure naming the index. +- `JiraPlan.to_markdown` takes that function, and `details` becomes one call. The thread pool, `CONVERSIONS`, the `concurrent.futures` import and the first-converts-alone rule go. + +A read then costs one container whatever the epic's size: `show` one, `needs-scoring-run` two, and item 352's scoring M runs. The price: one container of 256m holds every description of the epic at once, and one 60-second limit covers them all. A hundred descriptions are a few megabytes of JSON, so neither should bind; if one does, raise that one constant. + +**A heavy slot around the image build.** Today `ensure_image` in `convert.py` runs `docker build` from Python, so rule-hook's `run-heavy` rule, which sees only a session's Bash commands, doesn't make it wait. The decision "machine load: a heavy command waits for one of the machine's heavy slots" names `docker build` as heavy. `chunk-preflight` reaches the build through `JiraPlan.read()`, in process and outside its per-tool timeout. One read builds once, but two processes each inspect, find no image, and build. Item 375 starts several chunks of one project at once: on a new machine, or after a release that bumps the shim or adf-codec, each chunk's `chunk-preflight` builds, each with 1 GiB and up to 300 seconds, all outside the slots. + +In `ensure_image`, where the inspect finds no image, take a slot with `machine_load.slots.waited_slot`, inspect again, build only if the image is still missing, and free the slot. A second process then waits and finds the first one's image, and the codec stays the one place that knows it builds. The one `docker run` a read keeps is short and carries its limits, so it takes no slot. + +Scores: L 3, since the change spans the Node shim, its image, `convert.py` and `jira_epic.py`. I 3, since every reader of a plan in Jira runs it. R is above 5, so this item ships alone. + ### 378. Name the branches, worktrees and commit and PR titles of a Jira plan's chunks by the issue key, as in `ABC-123` and `ABC-123 - ...`. lilleman's call, 2026-11-14: split from item 351. Item IDs stay `int`: the Jira store holds the project key and an issue's number is the item's ID. A branch template `ABC-{id}` and a commit-title template `ABC-{id} - {summary}` already give the ticket-style names `CLAUDE.md`'s ticket rules ask for. Make a project with a Jira plan get them without spelling its key twice, or document the two templates where the plan setting is documented, whichever is simpler, and check `chunk-preflight` names the worktree the same way. -- 2.52.0 From 98c28cc244a54466a223eb450913c53c4700ee2e Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sat, 14 Nov 2026 19:50:47 +0100 Subject: [PATCH 11/14] =?UTF-8?q?Answer=20stability=20round=202:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=201=20=F0=9F=9F=A1=20(0=20misread);=20run=20two?= =?UTF-8?q?=20looped=20tests=20under=20subTest,=20refuse=20a=20blocker=20t?= =?UTF-8?q?hat=20is=20no=20issue=20key,=20and=20test=20the=20page=20cap,?= =?UTF-8?q?=20the=20four=20conversions=20at=20once=20and=20the=20search's?= =?UTF-8?q?=20failure=20messages?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin/plan_store/jira_epic.py | 4 +-- bin/plan_store/test_jira_epic.py | 33 ++++++++++++++++++++--- bin/project_config/test_project_config.py | 4 +-- bin/rest_client/test_env_file.py | 2 +- bin/rest_client/test_json_request.py | 4 ++- 5 files changed, 37 insertions(+), 10 deletions(-) diff --git a/bin/plan_store/jira_epic.py b/bin/plan_store/jira_epic.py index d6e6a995..470dff78 100644 --- a/bin/plan_store/jira_epic.py +++ b/bin/plan_store/jira_epic.py @@ -150,8 +150,8 @@ def issue_of(raw: object) -> Issue | Failure: 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): - 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 is of another type") + 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 diff --git a/bin/plan_store/test_jira_epic.py b/bin/plan_store/test_jira_epic.py index 7c6d57b1..f05e009a 100644 --- a/bin/plan_store/test_jira_epic.py +++ b/bin/plan_store/test_jira_epic.py @@ -2,6 +2,8 @@ import base64 import pathlib import sys import tempfile +import threading +import time import unittest import unittest.mock @@ -107,7 +109,8 @@ class JiraPlan(unittest.TestCase): bare = issue("ABC-35") del bare["properties"] for item in self.items(issue("ABC-34"), bare): - self.assertEqual((item.scores, item.moves, item.exempt, item.detail, item.likelihood), ({}, (), "", "", 0)) + 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",))) @@ -153,14 +156,36 @@ class JiraPlan(unittest.TestCase): 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): - for page in ([], {"issues": "none"}, {"issues": ["ABC-1"]}, {"issues": [{"key": 7, "fields": {}}]}, {"issues": [{"key": "abc", "fields": {}}]}): + 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.assertIsInstance(self.store().read(), Failure) + 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_converts_at_most_four_descriptions_at_once(self): + lock, running, most = threading.Lock(), [0], [0] + + def slow(document: dict[str, object]) -> str: + with lock: + running[0] += 1 + most[0] = max(most[0], running[0]) + time.sleep(0.02) + with lock: + running[0] -= 1 + return "text" + + self.pages = [{"issues": [issue(f"ABC-{number}", description=adf("Why.")) for number in range(1, 41)]}] + self.assertIsInstance(jira_epic.JiraPlan(EPIC, self.env, self.http, slow).read(), Plan) + self.assertLessEqual(most[0], 4) 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 | {"properties": None}): # type: ignore[arg-type, operator] + 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) diff --git a/bin/project_config/test_project_config.py b/bin/project_config/test_project_config.py index d6f8c13d..d3631fd7 100644 --- a/bin/project_config/test_project_config.py +++ b/bin/project_config/test_project_config.py @@ -107,9 +107,9 @@ class LoadTest(ConfigCase): 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 spelled in ("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"): + 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-{len(spelled)}-{hash(spelled) % 1000}", CLIENT.replace("folder:todo.md", spelled) + 'env-file = "~/acme.env"\n') + 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:///browse/", reason) diff --git a/bin/rest_client/test_env_file.py b/bin/rest_client/test_env_file.py index 56ff934a..a9283752 100644 --- a/bin/rest_client/test_env_file.py +++ b/bin/rest_client/test_env_file.py @@ -43,7 +43,7 @@ class ReadEnv(unittest.TestCase): 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\n"), {"A": "1", "B": "two words", "C": "3", "E": "a=b"}) + self.assertEqual(parse_env("# note\nA = 1 \nB=\"two words\"\nC='3'\nnot a pair\n#D=4\nE=a=b\nF=\"\"\nG='\n"), {"A": "1", "B": "two words", "C": "3", "E": "a=b", "F": "", "G": "'"}) if __name__ == "__main__": diff --git a/bin/rest_client/test_json_request.py b/bin/rest_client/test_json_request.py index d017329f..4df5887c 100644 --- a/bin/rest_client/test_json_request.py +++ b/bin/rest_client/test_json_request.py @@ -109,7 +109,9 @@ class HttpJson(unittest.TestCase): 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) + reason = str(getattr(failed, "reason", "")) + self.assertTrue(reason.startswith(f"cannot reach {base}: "), failed) + self.assertNotIn("urlopen", reason) def test_an_error_whose_body_is_not_json_names_the_status_alone(self): base = self.serve((403, b"")) -- 2.52.0 From 8e6b2f1f12b15f94f8821c3ff5e18c8e9764955c Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sat, 14 Nov 2026 19:50:47 +0100 Subject: [PATCH 12/14] =?UTF-8?q?Answer=20product-owner=20round=202:=200?= =?UTF-8?q?=20=F0=9F=94=B4,=200=20=F0=9F=9F=A1=20(0=20misread);=20every=20?= =?UTF-8?q?answer=20holds?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit -- 2.52.0 From 3931eef4519f566ccda3fc56058072f17689d6ff Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sat, 14 Nov 2026 19:59:07 +0100 Subject: [PATCH 13/14] Test a refused connection's reason, an indented comment and a value between letters --- bin/rest_client/test_env_file.py | 2 +- bin/rest_client/test_json_request.py | 11 ++++++++--- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/bin/rest_client/test_env_file.py b/bin/rest_client/test_env_file.py index a9283752..37be5535 100644 --- a/bin/rest_client/test_env_file.py +++ b/bin/rest_client/test_env_file.py @@ -43,7 +43,7 @@ class ReadEnv(unittest.TestCase): 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"), {"A": "1", "B": "two words", "C": "3", "E": "a=b", "F": "", "G": "'"}) + 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__": diff --git a/bin/rest_client/test_json_request.py b/bin/rest_client/test_json_request.py index 4df5887c..845747d3 100644 --- a/bin/rest_client/test_json_request.py +++ b/bin/rest_client/test_json_request.py @@ -109,9 +109,14 @@ class HttpJson(unittest.TestCase): self.server.server_close() failed = send("GET", f"{base}/api/v4/users/me", "t", None) self.assertIsInstance(failed, Failure) - reason = str(getattr(failed, "reason", "")) - self.assertTrue(reason.startswith(f"cannot reach {base}: "), failed) - self.assertNotIn("urlopen", reason) + 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"")) -- 2.52.0 From c51c246c3634507a6e73d46376e978461a832dfe Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sat, 14 Nov 2026 19:59:23 +0100 Subject: [PATCH 14/14] Finish item 351: a plan read from a Jira Cloud epic --- CHANGELOG.md | 1 + todo.md | 15 ++++----------- 2 files changed, 5 insertions(+), 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bd805987..bcbb8cc8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## Unreleased +- A project config may name its plan as `jira:https:///browse/`: 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 ]` prints the plan's items in the plan's order, `todo-item edit ` sets an item's cells or detail, and `todo-item move --release ` 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 --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. diff --git a/todo.md b/todo.md index 092647e3..742eee63 100644 --- a/todo.md +++ b/todo.md @@ -12,16 +12,15 @@ | 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.** | 4 | 2 | 3 | 7 | 5 | 1.6 by 6 | 1.2 | -| 379 | 0.11.0 | 351 | | **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.** | 3 | 2 | 3 | 6 | 4 | code health by 2, 1.5 by 2 | 3.2 | -| 378 | 0.11.0 | 351 | | **Name the branches, worktrees and commit and PR titles of a Jira plan's chunks by the issue key, as in `ABC-123` and `ABC-123 - ...`.** | 2 | 2 | 3 | 5 | 2 | 1.6 by 4 | 1.4 | -| 353 | 0.11.0 | 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 | +| 379 | 0.11.0 | | | **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.** | 3 | 2 | 3 | 6 | 4 | code health by 2, 1.5 by 2 | 3.2 | +| 378 | 0.11.0 | | | **Name the branches, worktrees and commit and PR titles of a Jira plan's chunks by the issue key, as in `ABC-123` and `ABC-123 - ...`.** | 2 | 2 | 3 | 5 | 2 | 1.6 by 4 | 1.4 | +| 353 | 0.11.0 | | | **Let a project's config take its goals and audience from a Jira epic's description, under the same two headings.** | 2 | 2 | 3 | 5 | 3 | 1.6 by 4 | 1.3 | | 358 | 0.11.0 | | | **Let a project's config allow its runtime and tests on the host, and set the comprehension score under which code health is very important.** | 2 | 2 | 3 | 5 | 3 | 1.6 by 4 | 1.3 | | 362 | 0.11.0 | | | **Send loop-claude's notices through the notifier a project's config names, with Mattermost as the first backend.** | 2 | 1 | 2 | 3 | 3 | 1.6 by 3 | 1.0 | | 363 | 0.11.0 | 362 | | **Add a Slack backend to the notifier, sending each notice as a DM from a bot.** | 2 | 1 | 2 | 3 | 3 | 1.6 by 4 | 1.3 | | 377 | 0.11.0 | | | **Hand a reviewer without a shell the plan as a listing `larv-review` writes into the review folder, whatever store holds the plan.** | 2 | 2 | 3 | 5 | 3 | 1.6 by 4 | 1.3 | | 373 | 0.11.0 | | | **Pick the next release's chunks that may run at once by the files and the parts of files each is predicted to touch, and record the prediction beside what each merged chunk touched.** | 3 | 2 | 2 | 5 | 5 | 1.5 by 4, 1.4 by 2 | 1.3 | -| 352 | 0.11.0 | 351, 379 | | **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 | 379 | | **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 | @@ -86,12 +85,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. - -Item IDs stay `int`: the store holds the Jira project key from the config, and an issue's number is the item's ID, so the 30 or so modules that read an ID as an int stay as they are. The store refuses a child issue from another Jira project. This item only reads: `add`, `edit` and `finish` fail, saying item 352 builds them. lilleman's call, 2026-11-14: item 377 hands the plan to a reviewer without a shell, and item 378 names branches and titles by the issue key. Re-scored 2026-11-14 at L 4: a new pattern, HTTP to Jira Cloud with entity properties, rank and ADF, across plan_store and project_config. - ### 379. 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. Two changes in `bin/adf_codec/`, in one item since both change the codec and its tests. Item 352 waits for this one. It waits for item 351, which adds `bin/plan_store/jira_epic.py`. -- 2.52.0