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/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/README.md b/README.md index 776fbafa..301fc28d 100644 --- a/README.md +++ b/README.md @@ -102,6 +102,17 @@ A project whose pull requests need a human's approval sets `wait-for-approval = 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 @@ -178,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`. `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/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..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.paths.items())}." + paths = f"- The project's config puts its files and plan at: {'; '.join(f'{setting} {path}' for setting, path in found.places.items())}." texts = f"- The project's config sets: {'; '.join(f'{setting} {text}' for setting, text in found.texts.items())}." if isinstance(found.item, NoItem): return [*head, f"- No plan item: {found.item.why} No worktree was made.", paths, texts] @@ -94,7 +94,7 @@ def bundled(plan: Plan) -> list[str]: return [f"- Item {first.id} has R above {BUNDLE_MAX_R}, so it ships alone."] if not candidates: return [f"- No other item of release {version(first.release)} may join item {first.id}'s chunk."] - listed = [f" - item {item.id}, {levels(item)}, S {item.scores['S']}: {item.tagline}" for item in candidates] + listed = [f" - item {item.id}, {levels(item)}, S {item.scores.get('S', 'unscored')}: {item.tagline}" for item in candidates] return [f'- The items of release {version(first.release)} that may join the chunk of item {first.id}, where `~/.claude/CLAUDE.md` โ†’ "Working loop" lets them share it:', *listed] diff --git a/bin/chunk_preflight/gathered.py b/bin/chunk_preflight/gathered.py index 153bfa2c..bdc18fef 100644 --- a/bin/chunk_preflight/gathered.py +++ b/bin/chunk_preflight/gathered.py @@ -81,8 +81,8 @@ class Gathered: item: ItemFacts | NoItem # The plan that was read, as choices.plan_name names it. plan: str - # Each path the project's config sets, by its setting: in the item's worktree where one was made or continued, else in the checkout. - paths: dict[str, pathlib.Path] + # Each path the project's config sets, and the epic of a plan kept in Jira, by its setting: in the item's worktree where one was made or continued, else in the checkout. + places: dict[str, str] # Whether the project's config puts the plan outside the checkout, where a release whose items are all done is not seen. plan_outside: bool # The language and the templates the project's config names, by their settings. 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/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/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..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.paths['plan']}") - return scoring_run_due(planned, chunk, ids, landed_release, renamed, unmeasured) + return finished_unseen(config, ids, chunk) or scoring_run_due(planned, chunk, ids, landed_release, renamed, unmeasured) def checkout_plan(plan: PlanStore) -> Plan | Failure: diff --git a/bin/larv_review/test_larv_review.py b/bin/larv_review/test_larv_review.py index 23d490e1..2657aad3 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 @@ -588,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 @@ -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/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 new file mode 100644 index 00000000..470dff78 --- /dev/null +++ b/bin/plan_store/jira_epic.py @@ -0,0 +1,226 @@ +"""A plan kept as the child issues of one Jira Cloud epic, read over Jira's REST API. + +An item is an open child issue. Its ID is the issue's number, so every child must be in the epic's own Jira project: ABC-34 is item 34 of the plan under ABC-12. The summary is the tagline, the description the detail, the earliest Fix Version the release, and an "is blocked by" link a blocker. L, E, I, S, Moves and Exempt sit in one issue property, PROPERTY, which needs no Jira admin to set up; an issue a teammate filed holds none, and reads as an item without scores. + +The store only reads so far: every write is a Failure.""" +import base64 +import concurrent.futures +import dataclasses +import pathlib +import re +import typing + +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 rest_client import json_request +from release_plan.release import parsed, Release, tagged +from plan_store.stores import Plan, Written +from rest_client.env_file import read_env + +# One pair of keys for Jira and Confluence: one Atlassian account's API token opens both. +KEYS = ("ATLASSIAN_EMAIL", "ATLASSIAN_API_TOKEN") +# The issue property that holds an item's scores, as a JSON object such as {"L": 2, "E": 2, "I": 3, "S": 3, "Moves": "1.6 by 4", "Exempt": ""}. +PROPERTY = "plan-item" +ISSUE_KEY = re.compile(r"([A-Z][A-Z0-9_]*)-([0-9]+)") +# Seconds each connect and each read may wait. +TIMEOUT = 30 +PAGE = 100 +# The pages one read asks for at most, so an answer that never names a last page ends the read. +MAX_PAGES = 100 +# 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 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] + + +def http_json(method: str, url: str, authorization: str, body: object) -> object: + return json_request.http_json(method, url, authorization, body, TIMEOUT, error_message) + + +def error_message(answer: object) -> str: + """Jira's messages in the JSON of an error answer; empty where it holds none.""" + if not isinstance(answer, dict): + return "" + messages, errors = answer.get("errorMessages"), answer.get("errors") + found = [*(messages if isinstance(messages, list) else []), *(errors.values() if isinstance(errors, dict) else [])] + return "; ".join(text for text in found if isinstance(text, str)) + + +@dataclasses.dataclass(frozen=True) +class Issue: + """A child issue as Jira answered it, checked to hold what an item is read from.""" + key: str + summary: str + description: dict[str, typing.Any] | None + fix_versions: tuple[str, ...] + # The key of each issue this one "is blocked by". + blockers: tuple[str, ...] + # PROPERTY's value; an empty object where the issue holds none. + scores: object + + @property + def number(self) -> int: + return number(self.key) + + +@dataclasses.dataclass(frozen=True) +class JiraPlan: + """The plan under epic, read with the credentials env_file holds.""" + epic: Epic + env_file: pathlib.Path + http: Http = http_json + to_markdown: ToMarkdown = 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 + answered = children(self.epic, authorization, self.http) + if isinstance(answered, Failure): + return answered + issues = [issue_of(raw) for raw in answered] + return next((issue for issue in issues if isinstance(issue, Failure)), None) or plan_of([issue for issue in issues if isinstance(issue, Issue)], self.epic, self.to_markdown) + + def add(self, fields: dict[str, str], detail: str) -> Written | Failure: + return Failure(READ_ONLY) + + def edit(self, id_: int, fields: dict[str, str], detail: str | None) -> Written | Failure: + return Failure(READ_ONLY) + + def finish(self, id_: int) -> Written | Failure: + return Failure(READ_ONLY) + + +def basic_auth(env_file: pathlib.Path) -> str | Failure: + """The Authorization header for the email and API token that env_file holds.""" + values = read_env(env_file, KEYS, "an API token") + if isinstance(values, Failure): + return values + return "Basic " + base64.b64encode(":".join(values[key] for key in KEYS).encode()).decode() + + +def children(epic: Epic, authorization: str, http: Http) -> list[object] | Failure: + """The epic's open child issues in backlog order, which is the order the team ranks them in. An issue in a done status is a finished item, so it is no longer in the plan.""" + # The search answers no issues for an epic the account cannot see, as for one whose children are all done; asking for the epic itself tells them apart. + seen = http("GET", f"{epic.site}/rest/api/3/issue/{epic.key}?fields=summary", authorization, None) + if isinstance(seen, Failure): + return Failure(f"cannot read the epic {epic.key}: {seen.reason}") + body: dict[str, object] = { + "jql": f'parent = "{epic.key}" AND statusCategory != Done ORDER BY Rank ASC', + "fields": ["summary", "description", "fixVersions", "issuelinks"], + "properties": [PROPERTY], + "maxResults": PAGE, + } + found: list[object] = [] + for _ in range(MAX_PAGES): + page = http("POST", f"{epic.site}/rest/api/3/search/jql", authorization, body) + if isinstance(page, Failure): + return page + if not isinstance(page, dict) or not isinstance(page.get("issues"), list): + return Failure("the search answered something other than a page of issues") + found += page["issues"] + if not page.get("nextPageToken"): + return found + body = body | {"nextPageToken": page["nextPageToken"]} + return Failure(f"the search for {epic.key}'s children did not end within {MAX_PAGES} pages") + + +def issue_of(raw: object) -> Issue | Failure: + """The issue in one entry of the search's answer, or which issue is not in the shape Jira documents, and how.""" + key = raw.get("key") if isinstance(raw, dict) else None + if not isinstance(key, str) or not ISSUE_KEY.fullmatch(key): + return Failure("the search answered an issue without an issue key") + try: + fields = typing.cast(dict[str, typing.Any], raw)["fields"] + blockers = tuple(link["inwardIssue"]["key"] for link in fields["issuelinks"] if "inwardIssue" in link and link["type"]["inward"] == "is blocked by") + issue = Issue(key, fields["summary"].strip(), fields["description"], tuple(version["name"] for version in fields["fixVersions"]), blockers, typing.cast(dict[str, typing.Any], raw).get("properties", {}).get(PROPERTY, {})) + except (AttributeError, KeyError, TypeError) as failure: + return Failure(f"{key} is not in the shape Jira Cloud's REST API version 3 documents: {failure!r}") + if not isinstance(issue.description, dict | None) or not all(isinstance(name, str) for name in issue.fix_versions + issue.blockers) or not all(ISSUE_KEY.fullmatch(blocker) for blocker in issue.blockers): + return Failure(f"{key} is not in the shape Jira Cloud's REST API version 3 documents: its description, a Fix Version's name or a linked issue's key holds another kind of value") + return issue + + +def plan_of(issues: list[Issue], epic: Epic, to_markdown: ToMarkdown) -> Plan | Failure: + """The plan the issues hold, in their order.""" + project = epic.key.rpartition("-")[0] + if strangers := [issue.key for issue in issues if issue.key.rpartition("-")[0] != project]: + return Failure(f"{strangers[0]} is a child of {epic.key} in another Jira project, and an item's ID is its number in {project}; move it into {project} or out of the epic") + ids = {issue.number for issue in issues} + items = [item(issue, project, ids) for issue in issues] + if failed := next((found for found in items if isinstance(found, Failure)), None): + return failed + # The descriptions convert last, since 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 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: Issue, project: str, ids: set[int]) -> Item | Failure: + """The item an issue holds, without its detail. It is blocked by each of its blockers among ids, the plan's items: a blocker that is done or lies outside the epic doesn't make the item wait.""" + release = earliest_release(issue.fix_versions) + if release is None: + # Until a project can tie its releases to something other than semver versions, an item with no release cannot be placed in the plan. + return Failure(f"{issue.key} names no Fix Version that is a semver version, such as 1.2.0; set one in Jira") + scored = scores(issue.key, issue.scores) + if isinstance(scored, Failure): + return scored + blockers = {number(key) for key in issue.blockers if key.rpartition("-")[0] == project} + return Item(issue.number, release, scored[2], bold_cell(issue.summary), scored[0], scored[1], tuple(sorted(blockers & ids)), "") + + +def earliest_release(names: tuple[str, ...]) -> Release | None: + """The earliest release among Fix Versions named as a semver version, with a leading v or without; None where none is.""" + releases = [release for name in names if (release := parsed(name) or tagged(name))] + return min(releases, default=None) + + +def scores(key: str, held: object) -> tuple[dict[str, int], typing.Any, typing.Any] | Failure: + """The scores, Moves and Exempt that an issue's PROPERTY value holds, each in the format the items table of a todo.md takes.""" + if not isinstance(held, dict): + return Failure(f"{key}'s issue property {PROPERTY} is not a JSON object") + named = {name: str(value) for name, value in held.items()} + levels = parse_scores(key, named, SHAPE.score_columns) + if isinstance(levels, Failure): + return levels + moves = parse_moves(key, named.get(MOVES, "")) + if isinstance(moves, Failure): + return moves + exempt = named.get("Exempt", "") + if not is_exempt(exempt): + return Failure(f"{key}'s issue property {PROPERTY} holds the Exempt {exempt!r}, which is not empty or one of {', '.join(EXEMPTIONS[1:])}") + return levels, moves, exempt diff --git a/bin/plan_store/stores.py b/bin/plan_store/stores.py index 9144cd35..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, the only backend so far. An agent reads and changes the plan with `todo-item`, which works through the same store. +The config's `plan` setting names the backend. A path names a markdown file, todo.md. `jira:` and an epic's address name a Jira epic, whose open child issues `jira_epic` reads and nothing writes yet. An agent reads and changes the plan with `todo-item`, which works through the same store. A tool that reads what a past commit held, such as `score-outcomes`, still parses that commit's todo.md itself, with `release_plan.todo_table`: only the markdown backend has commits, and todo.md's items 365, 366 and 368 port those tools to the other backends.""" import dataclasses @@ -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: @@ -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..f05e009a --- /dev/null +++ b/bin/plan_store/test_jira_epic.py @@ -0,0 +1,262 @@ +import base64 +import pathlib +import sys +import tempfile +import threading +import time +import unittest +import unittest.mock + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) + +from project_config.settings import Epic +from failure import Failure +from plan_store import jira_epic +from plan_store.stores import Plan +from release_plan.release import release_of + +EPIC = Epic("https://acme.atlassian.net", "ABC-12") +SEARCH = "https://acme.atlassian.net/rest/api/3/search/jql" +AUTHORIZATION = "Basic " + base64.b64encode(b"me@example.com:s3cret").decode() + + +def issue(key: str, summary: str = "Count the runs.", versions: tuple[str, ...] = ("0.1.0",), scores: dict[str, object] | None = None, blocked_by: tuple[str, ...] = (), description: object = None, blocks: tuple[str, ...] = ()) -> dict[str, object]: + links = [{"type": {"inward": "is blocked by", "outward": "blocks"}, "inwardIssue": {"key": blocker}} for blocker in blocked_by] + links += [{"type": {"inward": "is blocked by", "outward": "blocks"}, "outwardIssue": {"key": blocked}} for blocked in blocks] + return { + "key": key, + "fields": {"summary": summary, "description": description, "fixVersions": [{"name": name} for name in versions], "issuelinks": links}, + "properties": {} if scores is None else {jira_epic.PROPERTY: scores}, + } + + +def adf(text: str) -> dict[str, object]: + return {"type": "doc", "version": 1, "content": [{"type": "paragraph", "content": [{"type": "text", "text": text}]}]} + + +def text_of(document: dict[str, object]) -> str | Failure: + """Stands in for the adf-codec shim: the text of the one paragraph adf builds.""" + return document["content"][0]["content"][0]["text"] + "\n" # type: ignore[index] + + +class JiraPlan(unittest.TestCase): + def setUp(self) -> None: + self.env = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory())) / "acme.env" + self.env.write_text("ATLASSIAN_EMAIL=me@example.com\nATLASSIAN_API_TOKEN=s3cret\n") + self.env.chmod(0o600) + self.pages: list[object] = [] + self.calls: list[tuple[str, str, str, object]] = [] + self.epic: object = {"key": "ABC-12"} + self.epic_calls: list[tuple[str, str, str, object]] = [] + self.converted: list[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, self.to_markdown) + + def read(self, *issues: dict[str, object]) -> Plan | Failure: + self.pages, self.calls = [{"issues": list(issues)}], [] + return self.store().read() + + def items(self, *issues: dict[str, object]): + plan = self.read(*issues) + assert isinstance(plan, Plan), plan + return plan.items + + def test_an_epic_with_no_open_child_reads_as_an_empty_plan(self): + self.assertEqual(self.read(), Plan([])) + + def test_asks_for_the_epics_open_children_in_backlog_order_with_basic_auth(self): + self.read() + method, url, authorization, body = self.calls[0] + self.assertEqual((method, url), ("POST", SEARCH)) + self.assertEqual(authorization, AUTHORIZATION) + self.assertEqual(body, { + "jql": 'parent = "ABC-12" AND statusCategory != Done ORDER BY Rank ASC', + "fields": ["summary", "description", "fixVersions", "issuelinks"], + "properties": ["plan-item"], + "maxResults": 100, + }) + + def test_an_epic_that_cannot_be_read_fails_the_read_before_any_search(self): + self.epic = Failure("GET /rest/api/3/issue/ABC-12 answered 404: Issue does not exist or you do not have permission to see it.") + self.assertEqual(self.read(), Failure("cannot read the epic ABC-12: GET /rest/api/3/issue/ABC-12 answered 404: Issue does not exist or you do not have permission to see it.")) + self.assertEqual(self.epic_calls, [("GET", "https://acme.atlassian.net/rest/api/3/issue/ABC-12?fields=summary", AUTHORIZATION, None)]) + self.assertEqual(self.calls, []) + + def test_an_issue_reads_as_an_item_under_its_number(self): + scores = {"L": 1, "E": 2, "I": 3, "S": 1, "Moves": "1 by 9", "Exempt": "owner"} + item, = self.items(issue("ABC-34", "Count the runs.", ("0.1.0",), scores, description=adf("Why it counts."))) + self.assertEqual((item.id, item.release, item.tagline, item.detail), (34, release_of("0.1.0"), "**Count the runs.**", "Why it counts.")) + self.assertEqual((item.scores, item.moves, item.exempt, item.blocked_by), ({"L": 1, "E": 2, "I": 3, "S": 1}, (("1", 9),), "owner", ())) + + def test_keeps_jiras_order_whatever_the_releases_and_scores(self): + found = self.items(issue("ABC-40", versions=("0.2.0",)), issue("ABC-7", versions=("0.1.0",)), issue("ABC-21", versions=("0.3.0",))) + self.assertEqual([item.id for item in found], [40, 7, 21]) + + def test_an_issue_nobody_scored_reads_without_scores(self): + bare = issue("ABC-35") + del bare["properties"] + for item in self.items(issue("ABC-34"), bare): + with self.subTest(item=item.id): + self.assertEqual((item.scores, item.moves, item.exempt, item.detail, item.likelihood), ({}, (), "", "", 0)) + + def test_an_issue_is_blocked_by_each_blocker_still_in_the_plan(self): + blocked, _ = self.items(issue("ABC-34", blocked_by=("ABC-35", "ABC-2", "OTHER-9"), blocks=("ABC-35",)), issue("ABC-35", blocks=("ABC-34",))) + self.assertEqual(blocked.blocked_by, (35,)) + + def test_the_release_is_the_earliest_fix_version_with_or_without_a_v(self): + for versions in (("v1.2.0", "0.9.1", "Later"), ("1.2.0", "v0.9.1")): + with self.subTest(versions=versions): + item, = self.items(issue("ABC-34", versions=versions)) + self.assertEqual(item.release, release_of("0.9.1")) + + def test_an_issue_with_no_semver_fix_version_fails_the_read_naming_it(self): + for versions in ((), ("Sprint 4",)): + with self.subTest(versions=versions): + failure = self.read(issue("ABC-33", description=adf("Why.")), issue("ABC-34", versions=versions)) + self.assertEqual(failure, Failure("ABC-34 names no Fix Version that is a semver version, such as 1.2.0; set one in Jira")) + self.assertEqual(self.converted, []) + + def test_a_child_in_another_jira_project_fails_the_read_naming_it(self): + failure = self.read(issue("ABC-34"), issue("OTHER-5")) + self.assertIsInstance(failure, Failure) + self.assertIn("OTHER-5", failure.reason) # type: ignore[union-attr] + + def test_scores_out_of_format_fail_the_read_naming_the_issue(self): + for scores in ({"L": 9}, {"L": "high"}, {"Moves": "everything"}, {"Exempt": "because"}, "L 3"): + with self.subTest(scores=scores): + failure = self.read(issue("ABC-34", scores=scores)) # type: ignore[arg-type] + self.assertIsInstance(failure, Failure) + self.assertIn("ABC-34", failure.reason) # type: ignore[union-attr] + + def test_an_exempt_out_of_format_fails_naming_the_reasons_it_may_hold(self): + self.assertEqual(self.read(issue("ABC-34", scores={"Exempt": "because"})), Failure("ABC-34's issue property plan-item holds the Exempt 'because', which is not empty or one of decision, defect, owner, principle, question, security")) + + def test_reads_every_page(self): + self.pages = [{"issues": [issue("ABC-1")], "nextPageToken": "t1"}, {"issues": [issue("ABC-2")]}] + plan = self.store().read() + self.assertEqual([item.id for item in plan.items], [1, 2]) # type: ignore[union-attr] + self.assertNotIn("nextPageToken", self.calls[0][3]) # type: ignore[operator] + self.assertEqual(self.calls[1][3]["nextPageToken"], "t1") # type: ignore[index] + + def test_a_failing_request_fails_the_read(self): + self.pages = [Failure("POST /rest/api/3/search/jql answered 401: no")] + self.assertEqual(self.store().read(), Failure("POST /rest/api/3/search/jql answered 401: no")) + + def test_an_answer_in_another_shape_fails_the_read(self): + no_page, no_key = "the search answered something other than a page of issues", "the search answered an issue without an issue key" + for page, reason in (([], no_page), ({"issues": "none"}, no_page), ({"issues": ["ABC-1"]}, no_key), ({"issues": [{"key": 7, "fields": {}}]}, no_key), ({"issues": [{"key": "abc", "fields": {}}]}, no_key)): + with self.subTest(page=page): + self.pages, self.calls = [page], [] + self.assertEqual(self.store().read(), Failure(reason)) + + def test_a_search_that_never_names_a_last_page_fails_the_read(self): + self.pages = [{"issues": [], "nextPageToken": "more"}] * 2 + with unittest.mock.patch.object(jira_epic, "MAX_PAGES", 2): + self.assertEqual(self.store().read(), Failure("the search for ABC-12's children did not end within 2 pages")) + + def test_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 | {"fields": good["fields"] | {"issuelinks": [{"type": {"inward": "is blocked by"}, "inwardIssue": {"key": "ABC-x"}}]}}, good | {"properties": None}): # type: ignore[arg-type, operator] + with self.subTest(wrong=wrong): + failure = self.read(wrong) # type: ignore[arg-type] + self.assertIsInstance(failure, Failure) + self.assertTrue(failure.reason.startswith("ABC-1 is not in the shape Jira Cloud's REST API version 3 documents: "), failure) # type: ignore[union-attr] + + def test_converts_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")) + 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 + self.epic_calls, []) + + def test_an_env_file_others_may_read_fails_before_any_request(self): + self.env.chmod(0o644) + self.assertEqual(self.read(), Failure(f"{self.env} holds an API token, so only its owner may read it; run chmod 600 {self.env}")) + self.assertEqual(self.calls + self.epic_calls, []) + + def test_a_missing_env_file_fails(self): + self.env.unlink() + self.assertIsInstance(self.read(), Failure) + + def test_no_failure_holds_the_token(self): + self.pages = [{"issues": [issue("OTHER-5")]}] + self.assertNotIn("s3cret", self.store().read().reason) # type: ignore[union-attr] + + def test_every_write_fails_since_the_store_only_reads(self): + store = self.store() + for written in (store.add({}, ""), store.edit(34, {"L": "2"}, None), store.finish(34)): + with self.subTest(written=written): + self.assertEqual(written, Failure("a plan in Jira is only read so far: file, edit and finish its issues in Jira")) + self.assertEqual(self.calls + self.epic_calls, []) + + def test_names_itself_by_the_configs_spelling_and_no_commit_holds_it(self): + self.assertEqual((self.store().label, self.store().tracked), ("jira:https://acme.atlassian.net/browse/ABC-12", None)) + + +class Requests(unittest.TestCase): + def test_sends_each_request_through_the_shared_client_with_jiras_error_messages(self): + with unittest.mock.patch.object(jira_epic.json_request, "http_json", return_value={"issues": []}) as sent: + self.assertEqual(jira_epic.http_json("POST", SEARCH, AUTHORIZATION, {"jql": "x"}), {"issues": []}) + sent.assert_called_once_with("POST", SEARCH, AUTHORIZATION, {"jql": "x"}, 30, jira_epic.error_message) + + def test_reads_jiras_messages_from_an_error_answer(self): + cases = ( + ({"errorMessages": ["Issue does not exist or you do not have permission to see it."], "errors": {}}, "Issue does not exist or you do not have permission to see it."), + ({"errorMessages": ["One."], "errors": {"jql": "Two."}}, "One.; Two."), + ({"errorMessages": "One.", "errors": ["Two."]}, ""), + ({"errorMessages": [7, "One."]}, "One."), + (["One."], ""), + ) + for answer, message in cases: + with self.subTest(answer=answer): + self.assertEqual(jira_epic.error_message(answer), message) + + +if __name__ == "__main__": + unittest.main() 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..a3f236bf 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 `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 "~/.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..37797991 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) +# 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" @@ -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, except `plan` where the plan is kept in Jira.""" 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. + 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..d3631fd7 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 count, spelled in enumerate(("jira:http://acme.atlassian.net/browse/ABC-12", "jira:https://acme.atlassian.net/browse/abc-12", "jira:https://acme.atlassian.net/browse/ABC-12/x", "jira:https://acme.atlassian.net@evil.example/browse/ABC-12", "jira:ABC-12", "https://acme.atlassian.net/browse/ABC-12")): + with self.subTest(spelled): + self.write(f"acme-{count}", CLIENT.replace("folder:todo.md", spelled) + 'env-file = "~/acme.env"\n') + reason = self.failure() + self.assertIn(f"`plan` is {spelled!r}, not ", reason) + self.assertIn("jira:https:///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..14130d0f 100755 --- a/bin/rank_todo.py +++ b/bin/rank_todo.py @@ -106,10 +106,15 @@ def main(argv: list[str]) -> int: config = located(None, pathlib.Path.home()) if isinstance(config, Failure): return fail(config) - check, todo = args[0], args[1] or config.paths["plan"] + if config.plan_file is None and args == (True, None): + # Jira's backlog ranks a plan kept there, so the check passes, as silently as on a ranked todo.md: chunk-preflight runs it on every project. + return 0 + if config.plan_file is None: + return fail(Failure(f"rank_todo.py ranks a todo.md, and this checkout's config keeps the plan in Jira, whose backlog ranks it: {config.plan_label}")) + check, todo = args[0], args[1] or config.plan_file # The goals, decisions and history are this checkout's project's, so another project's plan would be ranked by them. - if todo.resolve() != config.paths["plan"].resolve(): - return fail(Failure(f"rank_todo.py: {todo} is not the plan this checkout's config names, {config.paths['plan'].resolve()}; run rank_todo.py in the checkout of the project whose plan it is")) + if todo.resolve() != config.plan_file.resolve(): + return fail(Failure(f"rank_todo.py: {todo} is not the plan this checkout's config names, {config.plan_file.resolve()}; run rank_todo.py in the checkout of the project whose plan it is")) if check: failures = plan_file.check_failures(todo, config) for line in failures: 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..37be5535 --- /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\nF=\"\"\nG='\n # H=5\nI=XaX\n"), {"A": "1", "B": "two words", "C": "3", "E": "a=b", "F": "", "G": "'", "I": "XaX"}) + + +if __name__ == "__main__": + unittest.main() diff --git a/bin/rest_client/test_json_request.py b/bin/rest_client/test_json_request.py new file mode 100644 index 00000000..845747d3 --- /dev/null +++ b/bin/rest_client/test_json_request.py @@ -0,0 +1,127 @@ +import http.server +import json +import pathlib +import socket +import sys +import threading +import unittest + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) + +from failure import Failure +from rest_client import json_request + + +def message(answer: object) -> str: + return answer.get("message", "") if isinstance(answer, dict) else "" + + +def send(method: str, url: str, token: str, body: object, seconds: float = 5) -> object: + return json_request.http_json(method, url, f"Bearer {token}", body, seconds, message) # type: ignore[arg-type] + + +class Recorded(http.server.BaseHTTPRequestHandler): + """Answers each request with the server's next scripted status and body, recording what it got.""" + + def do_GET(self) -> None: + self.answer() + + def do_POST(self) -> None: + self.answer() + + def answer(self) -> None: + length = int(self.headers.get("Content-Length") or 0) + self.server.got.append((self.command, self.path, dict(self.headers), self.rfile.read(length))) # type: ignore[attr-defined] + status, body = self.server.script.pop(0) # type: ignore[attr-defined] + if status is None: + # Raw bytes, as a server that breaks HTTP sends them. + self.wfile.write(body) + self.close_connection = True + return + self.send_response(status) + if 300 <= status < 400: + self.send_header("Location", "/elsewhere") + self.send_header("Content-Type", "application/json") + self.end_headers() + self.wfile.write(body) + + def log_message(self, format: str, *args: object) -> None: + pass + + +class HttpJson(unittest.TestCase): + def serve(self, *script: tuple[int, bytes]) -> str: + server = http.server.HTTPServer(("127.0.0.1", 0), Recorded) + server.script = list(script) # type: ignore[attr-defined] + server.got = [] # type: ignore[attr-defined] + threading.Thread(target=server.serve_forever, daemon=True).start() + self.addCleanup(server.server_close) + self.addCleanup(server.shutdown) + self.server = server + return f"http://127.0.0.1:{server.server_port}" + + def test_sends_the_authorization_and_the_body_as_json_and_reads_the_json_answer(self): + base = self.serve((201, b'{"id": "post-id"}')) + self.assertEqual(send("POST", f"{base}/api/v4/posts", "secret-token", {"message": "hi"}), {"id": "post-id"}) + [(method, path, headers, body)] = self.server.got # type: ignore[attr-defined] + self.assertEqual((method, path, headers["Authorization"], headers["Content-Type"], headers["Accept"], json.loads(body)), ("POST", "/api/v4/posts", "Bearer secret-token", "application/json", "application/json", {"message": "hi"})) + + def test_names_the_request_the_status_and_the_apis_message_on_an_error(self): + base = self.serve((401, b'{"message": "Invalid or expired session, please login again."}')) + self.assertEqual(send("GET", f"{base}/api/v4/users/me", "bad", None), Failure("GET /api/v4/users/me answered 401: Invalid or expired session, please login again.")) + + def test_follows_no_redirect_so_the_token_goes_only_to_the_server_named(self): + base = self.serve((302, b"{}")) + self.assertEqual(send("GET", f"{base}/api/v4/users/me", "t", None), Failure("GET /api/v4/users/me answered 302: Found")) + self.assertEqual(len(self.server.got), 1) # type: ignore[attr-defined] + + def test_sends_no_body_with_a_get(self): + base = self.serve((200, b'{"id": "bot-id"}')) + send("GET", f"{base}/api/v4/users/me", "t", None) + [(_, _, headers, body)] = self.server.got # type: ignore[attr-defined] + self.assertEqual((headers.get("Content-Length"), body), (None, b"")) + + def test_fails_on_an_answer_that_breaks_http(self): + for raw in (b"garbage\r\n\r\n", b"HTTP/1.1 200 OK\r\nContent-Length: 100\r\n\r\n{}"): + with self.subTest(raw=raw): + base = self.serve((None, raw)) + failed = send("GET", f"{base}/api/v4/users/me", "t", None) + self.assertTrue(isinstance(failed, Failure) and failed.reason.startswith("GET /api/v4/users/me got a broken answer: "), failed) + + def test_names_the_status_of_an_error_whose_body_is_cut_short(self): + base = self.serve((None, b"HTTP/1.1 500 Internal Server Error\r\nContent-Length: 100\r\n\r\n{}")) + self.assertEqual(send("GET", f"{base}/api/v4/users/me", "t", None), Failure("GET /api/v4/users/me answered 500: Internal Server Error")) + + def test_gives_up_on_a_server_that_never_answers_after_the_timeout(self): + silent = socket.socket() + self.addCleanup(silent.close) + silent.bind(("127.0.0.1", 0)) + silent.listen(1) + base = f"http://127.0.0.1:{silent.getsockname()[1]}" + self.assertEqual(send("GET", f"{base}/api/v4/users/me", "t", None, 0.2), Failure(f"cannot reach {base}: timed out")) + + def test_fails_on_an_answer_that_is_not_json(self): + base = self.serve((200, b"")) + self.assertEqual(send("GET", f"{base}/api/v4/users/me", "t", None), Failure("GET /api/v4/users/me answered with something other than JSON")) + + def test_fails_naming_the_server_it_cannot_reach(self): + base = self.serve() + self.server.server_close() + failed = send("GET", f"{base}/api/v4/users/me", "t", None) + self.assertIsInstance(failed, Failure) + self.assertTrue(str(getattr(failed, "reason", "")).startswith(f"cannot reach {base}: "), failed) + + def test_names_why_a_server_refuses_the_connection(self): + with socket.socket() as taken: + taken.bind(("127.0.0.1", 0)) + port = taken.getsockname()[1] + failed = send("GET", f"http://127.0.0.1:{port}/api", "t", None) + self.assertEqual(failed, Failure(f"cannot reach http://127.0.0.1:{port}: [Errno 111] Connection refused")) + + def test_an_error_whose_body_is_not_json_names_the_status_alone(self): + base = self.serve((403, b"")) + 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/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..a06468ab 100644 --- a/bin/rule_hook/todo_check.py +++ b/bin/rule_hook/todo_check.py @@ -32,9 +32,12 @@ def todo_breaches(directory: str, home: pathlib.Path, own: pathlib.Path = OWN) - # A checkout whose todo.md changes with no config is one whose config is still to write. An unchanged todo.md may be a third party's, whose clone needs no config. unconfigured = pathlib.Path(top) / "todo.md" return [Breach("todo-rank-check", config.reason, top)] if unconfigured.is_file() and changed(top, unconfigured, "todo.md") else [] - todo, tracked = config.paths["plan"], config.tracked("plan") + todo, tracked = config.plan_file, config.tracked("plan") + # A plan in Jira is no file, and Jira's backlog ranks it. + if todo is None or not todo.is_file(): + return [] # A plan outside the checkout has no commit in the checkout to differ from, so it is checked on every call. - if not todo.is_file() or (tracked is not None and not changed(top, todo, tracked)): + if tracked is not None and not changed(top, todo, tracked): return [] return [Breach("todo-rank-check", line, top) for line in check_failures(top, todo, config, own)] @@ -43,9 +46,11 @@ def folder_breaches(top: str, config: ProjectConfig | Failure, own: pathlib.Path """Why the plan kept in top, a config's folder, is not ranked, where the plan has changed in that folder's repo; ranked as for a commit in the project's checkout. A config that fails to load doesn't block anything here, so that the commit that fixes it goes through.""" - if isinstance(config, Failure) or not config.paths["plan"].is_relative_to(config.folder): + if isinstance(config, Failure): + return [] + todo = config.plan_file + if todo is None or not todo.is_relative_to(config.folder): return [] - todo = config.paths["plan"] if not todo.is_file() or not changed(str(config.folder), todo, todo.relative_to(config.folder).as_posix()): return [] return [Breach("todo-rank-check", line, top) for line in check_failures(str(config.top), todo, config, own)] diff --git a/bin/test_rank_todo.py b/bin/test_rank_todo.py index 2d1787e3..3fc726de 100644 --- a/bin/test_rank_todo.py +++ b/bin/test_rank_todo.py @@ -57,6 +57,19 @@ class Main(unittest.TestCase): (folder / "decisions.md").write_bytes(b"\xff") self.assertEqual(self.run_main(), (1, f"cannot read {folder}/decisions.md: not UTF-8 on line 1\n")) + def test_refuses_a_project_whose_plan_is_in_jira_and_writes_no_file(self): + with tempfile.TemporaryDirectory() as temp: + config = configured(self, pathlib.Path(temp)) / "config.toml" + self.enterContext(contextlib.chdir(temp)) + config.write_text(config.read_text().replace('"checkout:todo.md"', '"jira:https://acme.atlassian.net/browse/ABC-12"') + 'env-file = "~/acme.env"\n') + todo = pathlib.Path(temp, "todo.md") + todo.write_text(TODO) + for args in ((), (str(todo),), ("--check", str(todo))): + with self.subTest(args=args): + self.assertEqual(self.run_main(*args), (1, "rank_todo.py ranks a todo.md, and this checkout's config keeps the plan in Jira, whose backlog ranks it: jira:https://acme.atlassian.net/browse/ABC-12\n")) + self.assertEqual(self.run_main("--check"), (0, "")) + self.assertEqual(todo.read_text(), TODO) + def test_refuses_a_file_that_is_not_the_plan_the_config_names_and_a_checkout_no_config_names(self): with tempfile.TemporaryDirectory() as temp: folder = configured(self, pathlib.Path(temp)) 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 diff --git a/docs/decisions.md b/docs/decisions.md index fc4abb06..d8e23dbb 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -22,6 +22,7 @@ Each project principle states one rule that the decisions below apply; their ent - principles: about seven things per level, four or five where they act on each other, more where a reader finds them by name; crossing a limit asks for a grouping or a recorded reason - project config: a tool that reads a file's commits says where it does not support that file, and the work goes on - project config: `language` names the prose's language by its English name, and `commit-title`, `pull-request-title` and `branch` are brace templates over `{id}` and `{summary}` +- project config: `plan` may name a Jira Cloud epic as `jira:` and its address, the plan is its open child issues in backlog order, and an issue's number is the item's ID - 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 @@ -290,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. 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..742eee63 100644 --- a/todo.md +++ b/todo.md @@ -6,19 +6,21 @@ `Bar = 0.1` -`Next ID = 377` +`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.** | 3 | 2 | 3 | 6 | 5 | 1.6 by 6 | 1.2 | -| 353 | 0.11.0 | 351 | | **Let a project's config take its goals and audience from a Jira epic's description, under the same two headings.** | 2 | 2 | 3 | 5 | 3 | 1.6 by 4 | 1.3 | +| 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 | | **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 | @@ -83,11 +85,34 @@ ## 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. +### 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. -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. +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`. -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`. +**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. ### 353. Let a project's config take its goals and audience from a Jira epic's description, under the same two headings. @@ -105,6 +130,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.