From 59d972cc82325ada751e406570e2ba7b2c3630b9 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sat, 14 Nov 2026 19:12:25 +0100 Subject: [PATCH] Read a plan from the child issues of a Jira Cloud epic --- README.md | 4 +- bin/branch_chunks/read.py | 2 +- bin/chunk_preflight/choices.py | 8 +- bin/chunk_preflight/facts.py | 2 +- bin/chunk_preflight/gathered.py | 2 +- bin/chunk_preflight/main.py | 4 +- bin/larv_review/history_commands.py | 5 +- bin/larv_review/owed.py | 2 +- bin/larv_review/plan.py | 2 +- bin/larv_review/test_larv_review.py | 16 +- bin/plan_store/jira_epic.py | 213 ++++++++++++++++++++++ bin/plan_store/stores.py | 10 +- bin/plan_store/test_jira_epic.py | 165 +++++++++++++++++ bin/plan_store/test_stores.py | 18 ++ bin/project_config/main.py | 7 +- bin/project_config/settings.py | 51 +++++- bin/project_config/test_project_config.py | 40 +++- bin/rank_todo.py | 8 +- bin/rule_hook/test_rule_hook.py | 8 + bin/rule_hook/todo_check.py | 10 +- bin/test_rank_todo.py | 11 ++ docs/decisions.md | 12 ++ 22 files changed, 570 insertions(+), 30 deletions(-) create mode 100644 bin/plan_store/jira_epic.py create mode 100644 bin/plan_store/test_jira_epic.py diff --git a/README.md b/README.md index 776fbafa..19adb62b 100644 --- a/README.md +++ b/README.md @@ -100,6 +100,8 @@ A project's config may set four more things, each optional, as `project-config - A project whose pull requests need a human's approval sets `wait-for-approval = true` in its config. `chunk-pr merge` then waits, once the checks have passed, until GitHub reports the pull request approved as its branch protection requires, and merges it. It refuses on Gitea, where a reviewer requested changes and where the protection requires no review. It gives up after 90 minutes without an approval; run it again once the pull request is approved. Left out, the setting is false. +A client that plans in Jira Cloud names an epic as the plan, as `plan = "jira:https://acme.atlassian.net/browse/ABC-12"`: `jira:` and the epic's address as the browser shows it. The plan is then the epic's open child issues in Jira's backlog order, which the team sets; an issue in a done status is a finished item. An issue's number is the item's ID, so every child lies in the epic's own Jira project, and a read fails naming one that doesn't. The summary is the tagline, the description the detail, the earliest Fix Version named as a semver version the release, and an "is blocked by" link to another open child a blocker. The scores sit in the issue property `plan-item`, a JSON object such as `{"L": 2, "E": 2, "I": 3, "S": 3, "Moves": "1.6 by 4", "Exempt": ""}`; an issue without it reads as an item nobody scored yet. The config's `env-file` must hold `ATLASSIAN_EMAIL` and `ATLASSIAN_API_TOKEN`, an API token of that Atlassian account. The loop only reads such a plan so far: `todo-item add`, `edit`, `move` and `finish` fail saying so, `rank_todo.py` refuses it, and rule-hook's rank check skips it. What isn't supported for a plan outside the checkout, below, isn't for a plan in Jira either. + For a client's project, use one sandbox VM per client, so that one client's code, transcripts and credentials never share a machine with another's. What the client's repo should not hold lives in the config's folder, at paths written as `folder:`, as `project-config --help` shows: the plan, the working rules in an `AGENTS.md` I write for the agents, the records, and the goals and audience, as `goals-and-audience = "folder:goals.md"`. Name that file `goals.md`, so the rules for goals and audience load when an agent writes it. A file outside the checkout has no commits in the checkout's history, so four things are not supported for it yet. `score-outcomes` and loop-claude's routing figures count a project's chunks only where `todo.md`, `docs/comprehension-history.md` and `docs/reading-cost.md` are at those paths in the checkout; otherwise each says so, and the loop goes on. For a plan or a comprehension history outside the checkout, `larv-review` says it cannot tell whether a scoring run is owed, and for such a history it cannot find a paired ruling's base. For a plan outside the checkout, chunk-preflight and loop-claude don't see a release whose last item has shipped, and say that its release review and its cut are yours to call. And rule-hook checks a plan outside the checkout on every call, not only when it changed. ```sh @@ -178,7 +180,7 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a - `machine_load/` takes the machine's heavy slots, its shared lock files, for `run_heavy`, and reads the memory share that loop-claude waits for. It also gives `mutate_changes` a slot's CPU count. - `mattermost_dm/` sends the human a Mattermost DM, for `mattermost-dm` and for loop-claude through `loop_effects`. - `model_routing/` holds the routing ladder, which loop-claude, `rule_hook`, both replay tools and `subagent-rung` read, and the list prices, which `routing_figures` and `transcript_archive` read. -- `plan_store/` reads and writes a project's plan through the store the project's config names (`stores.py`), with the markdown file's edits in `markdown_edits.py`. `contract.py` holds the tests every backend must pass, and `fakes.py` a plan in memory. +- `plan_store/` reads and writes a project's plan through the store the project's config names (`stores.py`), with the markdown file's edits in `markdown_edits.py` and the reader of a Jira epic's child issues in `jira_epic.py`. `contract.py` holds the tests every backend must pass, and `fakes.py` a plan in memory. - `rank_todo.py`, `settings_filter.py` and `statusline.py` are tools of one file each, tested beside them. - `record_store/` reads and writes a project's records, each through the store the project's config names (`stores.py`). `contract.py` holds the tests every backend must pass, and `fakes.py` a store in memory that the tests of other tools use. - `release_plan/` reads `todo.md`'s items table and release versions, says which release is next and whether it is ready to cut (`release_standing.py`), and ranks the plan (`ranking.py`, with its score formula in `formula.py` and its blocker order in `blockers.py`). `goals_file.py` reads the goals file's sections, goals and goal weights, for the ranking and for `loop_claude`'s premises, and `citations.py` holds `todo.md` and `docs/decisions.md` to each other. `plan_file.py` ranks, checks and writes a `todo.md`, for `larv_review`, `rank_todo.py` and `rule_hook`. diff --git a/bin/branch_chunks/read.py b/bin/branch_chunks/read.py index 91412fc0..ae2874f7 100644 --- a/bin/branch_chunks/read.py +++ b/bin/branch_chunks/read.py @@ -28,7 +28,7 @@ def unsupported(checkout: str | None, home: pathlib.Path, run: Git = git) -> str def held(config: ProjectConfig, name: str) -> tuple[str, str | None]: """What a message calls the plan or the record that setting name names in config, and its path from the checkout's top, None where it is kept elsewhere.""" if name == "plan": - return str(config.paths[name]), config.tracked(name) + return config.plan_label, config.tracked(name) record = store(config, name) return record.label, record.tracked diff --git a/bin/chunk_preflight/choices.py b/bin/chunk_preflight/choices.py index 92256e6c..b8ec48a1 100644 --- a/bin/chunk_preflight/choices.py +++ b/bin/chunk_preflight/choices.py @@ -20,12 +20,12 @@ def cut_name(cut: LastCut) -> str | None: return None if headed is None else f"{version(headed)} (dated in CHANGELOG.md)" -def plan_name(default: str, outside: pathlib.Path | None) -> str: - """How the preflight names the plan it read: the default branch's todo.md, or the file, where the project's config puts it outside the checkout.""" - return str(outside) if outside else f"{default}'s todo.md" +def plan_name(default: str, outside: str | None) -> str: + """How the preflight names the plan it read: the default branch's todo.md, or the file or Jira epic, where the project's config puts it outside the checkout.""" + return outside if outside else f"{default}'s todo.md" -def planned(todo: plan_stores.Plan | Failure, cut: LastCut, default: str, branch: str, outside: pathlib.Path | None = None) -> Plan | NoItem: +def planned(todo: plan_stores.Plan | Failure, cut: LastCut, default: str, branch: str, outside: str | None = None) -> Plan | NoItem: """todo, which is the project's plan as its store read it and which plan_name names, with the item the next chunk takes first, release_standing.chunk_item's pick; else why there is none. branch is the project's `branch` template.""" where = plan_name(default, outside) if isinstance(todo, NoItemsTable): diff --git a/bin/chunk_preflight/facts.py b/bin/chunk_preflight/facts.py index 07774477..470bbb23 100644 --- a/bin/chunk_preflight/facts.py +++ b/bin/chunk_preflight/facts.py @@ -17,7 +17,7 @@ def render(found: Gathered) -> list[str]: note = [f"- {found.note}"] if found.note else [] unseen = [f"- {UNSEEN_RELEASES}"] if found.plan_outside else [] head = [*note, f"- {last_release(found.default, found.cut)}", *unseen] - paths = f"- The project's config puts its files at: {'; '.join(f'{setting} {path}' for setting, path in found.paths.items())}." + paths = f"- The project's config puts its files at: {'; '.join(f'{setting} {path}' for setting, path in found.places.items())}." texts = f"- The project's config sets: {'; '.join(f'{setting} {text}' for setting, text in found.texts.items())}." if isinstance(found.item, NoItem): return [*head, f"- No plan item: {found.item.why} No worktree was made.", paths, texts] diff --git a/bin/chunk_preflight/gathered.py b/bin/chunk_preflight/gathered.py index 153bfa2c..07cab36d 100644 --- a/bin/chunk_preflight/gathered.py +++ b/bin/chunk_preflight/gathered.py @@ -82,7 +82,7 @@ class Gathered: # The plan that was read, as choices.plan_name names it. plan: str # Each path the project's config sets, by its setting: in the item's worktree where one was made or continued, else in the checkout. - paths: dict[str, pathlib.Path] + places: dict[str, str] # Whether the project's config puts the plan outside the checkout, where a release whose items are all done is not seen. plan_outside: bool # The language and the templates the project's config names, by their settings. diff --git a/bin/chunk_preflight/main.py b/bin/chunk_preflight/main.py index ca070a6d..6ab9ad89 100644 --- a/bin/chunk_preflight/main.py +++ b/bin/chunk_preflight/main.py @@ -127,13 +127,13 @@ def preflight(root: pathlib.Path, timeout: float, make: bool) -> list[str] | Fai config = located(str(root), pathlib.Path.home()) if isinstance(config, Failure): return config - outside = None if config.tracked("plan") else config.paths["plan"] + outside = None if config.tracked("plan") else config.plan_label held = project_plan(config, ref, str(root)) plan = planned(held.todo, held.cut, ref, config.branch, outside) item = plan if isinstance(plan, NoItem) else item_facts(root, ref, plan, timeout, make) # A `checkout:` path lands in the worktree the chunk works in. made = located(str(item.worktree.path), pathlib.Path.home()) if isinstance(item, ItemFacts) and isinstance(item.worktree, Worktree) else config - return render(Gathered(ref, note, held.cut, item, plan_name(ref, outside), (config if isinstance(made, Failure) else made).paths, outside is not None, config.texts)) + return render(Gathered(ref, note, held.cut, item, plan_name(ref, outside), (config if isinstance(made, Failure) else made).places, outside is not None, config.texts)) def item_facts(root: pathlib.Path, default: str, plan: Plan, timeout: float, make: bool) -> ItemFacts: diff --git a/bin/larv_review/history_commands.py b/bin/larv_review/history_commands.py index 08bbe733..9aa017ce 100644 --- a/bin/larv_review/history_commands.py +++ b/bin/larv_review/history_commands.py @@ -80,7 +80,10 @@ def rerank(home: pathlib.Path, warn: Say) -> Failure | None: config = located(None, home) if isinstance(config, Failure): return config - todo = config.paths["plan"] + todo = config.plan_file + if todo is None: + # A plan in Jira is ranked by Jira's backlog, which no score moves. + return None ranked = plan_file.rank_file(todo, config) if isinstance(ranked, Failure): return Failure(f"recorded the run, but rank_todo.py cannot rank {todo}: {ranked.reason}. Fix what that names, then run rank_todo.py on {todo}, not record-scoring again") diff --git a/bin/larv_review/owed.py b/bin/larv_review/owed.py index 7a65fc70..ec1ad8da 100644 --- a/bin/larv_review/owed.py +++ b/bin/larv_review/owed.py @@ -26,7 +26,7 @@ def owed_scoring_run(default: str, home: pathlib.Path, warn: typing.Callable[[st record = store(config, "comprehension-history") plan, history = config.tracked("plan"), record.tracked if plan is None or history is None: - name, where = ("plan", str(config.paths["plan"])) if plan is None else ("comprehension history", record.label) + name, where = ("plan", config.plan_label) if plan is None else ("comprehension history", record.label) warn(f"larv-review doesn't support a {name} outside the checkout, so it cannot tell whether the chunk owes a scoring run: {where}") return None base = git("merge-base", default, "HEAD", cwd=checkout) diff --git a/bin/larv_review/plan.py b/bin/larv_review/plan.py index 4cb1cd4d..e4269e74 100644 --- a/bin/larv_review/plan.py +++ b/bin/larv_review/plan.py @@ -100,7 +100,7 @@ def plan_reasons(ref: str, ids: list[int] | None, home: pathlib.Path) -> list[st ids = sorted({item.id for item in planned} - {item.id for item in chunk}) # A plan outside the checkout is read as it stands for both plans, so a finished item is in neither. if config.tracked("plan") is None and (gone := sorted(set(ids) - {item.id for item in chunk})): - return Failure(f"todo.md as it stands holds no item {', '.join(map(str, gone))}, and larv-review doesn't support a plan outside the checkout, so it cannot read the plan as it stood before the item was finished: {config.paths['plan']}") + return Failure(f"todo.md as it stands holds no item {', '.join(map(str, gone))}, and larv-review doesn't support a plan outside the checkout, so it cannot read the plan as it stood before the item was finished: {config.plan_label}") return scoring_run_due(planned, chunk, ids, landed_release, renamed, unmeasured) diff --git a/bin/larv_review/test_larv_review.py b/bin/larv_review/test_larv_review.py index 23d490e1..187de198 100644 --- a/bin/larv_review/test_larv_review.py +++ b/bin/larv_review/test_larv_review.py @@ -1,3 +1,4 @@ +import contextlib import decimal import itertools import json @@ -16,8 +17,9 @@ from larv_review.agreement import agreement_report, ruling_agreement, run_agreem from review_rules.comprehension_history import appended, entries, HistoryChange, latest_places, Place, recorded, ruling_entry, scoring_entry, ScoringRun, Seat from larv_review.plan import checkout_plan, EMPTIED_WORDS, landed_towards, plan_reasons, scoring_run_due from review_rules import comprehension_history +from project_config.test_project_config import configured from larv_review.ruling import counted, ruling, split, surplus, votes -from larv_review.history_commands import decided +from larv_review.history_commands import decided, rerank from failure import Failure from plan_store.stores import FilePlan from larv_review.scoring import floor_step, means, under_floor @@ -942,6 +944,18 @@ class LarvReviewTool(unittest.TestCase): self.assertIn("not record-scoring again", ran.stderr) self.assertEqual(len(entries((self.checkout / "docs" / "comprehension-history.md").read_text())), 1) + def test_a_plan_in_jira_is_not_reranked(self): + with tempfile.TemporaryDirectory() as temp: + checkout = pathlib.Path(temp, "acme") + checkout.mkdir() + config = configured(self, checkout) / "config.toml" + config.write_text(config.read_text().replace('"checkout:todo.md"', '"jira:https://acme.atlassian.net/browse/ABC-12"') + 'env-file = "~/acme.env"\n') + (checkout / "todo.md").write_text("the owners' own notes\n") + self.enterContext(contextlib.chdir(checkout)) + said: list[str] = [] + self.assertIsNone(rerank(pathlib.Path.home(), said.append)) + self.assertEqual((said, (checkout / "todo.md").read_text()), ([], "the owners' own notes\n")) + def test_reranks_todo_md_by_the_overall_it_records(self): self.plan() ran = self.record_sevens() diff --git a/bin/plan_store/jira_epic.py b/bin/plan_store/jira_epic.py new file mode 100644 index 00000000..df1e74c2 --- /dev/null +++ b/bin/plan_store/jira_epic.py @@ -0,0 +1,213 @@ +"""A plan kept as the child issues of one Jira Cloud epic, read over Jira's REST API. + +An item is an open child issue. Its ID is the issue's number, so the epic's children all lie in the epic's own Jira project: ABC-34 is item 34 of the plan under ABC-12. The summary is the tagline, the description the detail, the earliest Fix Version the release, and an "is blocked by" link a blocker. L, E, I, S, Moves and Exempt sit in one issue property, PROPERTY, which needs no Jira admin to set up; an issue a teammate filed holds none, and reads as an item without scores. + +The store only reads so far: every write is a Failure.""" +import base64 +import concurrent.futures +import dataclasses +import http.client +import json +import pathlib +import re +import typing +import urllib.error +import urllib.parse +import urllib.request + +from adf_codec.convert import adf_to_markdown +from failure import Failure +from mattermost_dm.dm import parse_env +from plan_store.markdown_edits import bold_cell +from plan_store.stores import Plan, Written +from project_config.settings import Epic +from release_plan.release import parsed, Release, tagged +from release_plan.todo_table import is_exempt, Item, MOVES, parse_moves, parse_scores, SHAPE + +# One pair of keys for Jira and Confluence, which one Atlassian account's API token opens both. +KEYS = ("ATLASSIAN_EMAIL", "ATLASSIAN_API_TOKEN") +# The issue property that holds an item's scores, as a JSON object such as {"L": 2, "E": 2, "I": 3, "S": 3, "Moves": "1.6 by 4", "Exempt": ""}. +PROPERTY = "plan-item" +# Seconds each connect and each read may wait. +TIMEOUT = 30 +PAGE = 100 +# The pages one read asks for at most, so an answer that never names a last page ends the read. +MAX_PAGES = 100 +# The adf-codec containers run at once: each description is one run. +CONVERSIONS = 8 +READ_ONLY = "a plan in Jira is only read so far: file, edit and finish its issues in Jira" + +# Sends a request with the Authorization header given, the body as JSON, and returns the JSON answer, or a Failure saying why there is none. +Http = typing.Callable[[str, str, str, object], object] +ToMarkdown = typing.Callable[[dict[str, typing.Any]], str | Failure] + + +class NoRedirect(urllib.request.HTTPRedirectHandler): + """Refuses every redirect, which Jira's API never sends: urllib would resend the credentials to the new location, even one off https.""" + + def redirect_request(self, *args: typing.Any, **kwargs: typing.Any) -> None: + return None + + +OPENER = urllib.request.build_opener(NoRedirect) + + +def http_json(method: str, url: str, authorization: str, body: object) -> object: + """The JSON that url answers; a Failure naming the request where it answers an error, breaks HTTP or answers something other than JSON, and saying so where the site cannot be reached.""" + request_name = f"{method} {urllib.parse.urlsplit(url).path}" + request = urllib.request.Request(url, json.dumps(body).encode(), {"Authorization": authorization, "Content-Type": "application/json", "Accept": "application/json"}, method=method) + try: + with OPENER.open(request, timeout=TIMEOUT) as response: + raw = response.read() + except urllib.error.HTTPError as failure: + with failure: + return Failure(f"{request_name} answered {failure.code}: {failure.reason}") + except http.client.HTTPException as failure: + return Failure(f"{request_name} got a broken answer: {failure!r}") + except (OSError, ValueError) as failure: + return Failure(f"cannot be reached: {getattr(failure, 'reason', failure)}") + try: + return json.loads(raw) + except ValueError: + return Failure(f"{request_name} answered with something other than JSON") + + +@dataclasses.dataclass(frozen=True) +class JiraPlan: + """The plan under epic, read with the credentials env_file holds.""" + epic: Epic + env_file: pathlib.Path + http: Http = http_json + to_markdown: ToMarkdown = adf_to_markdown + + @property + def label(self) -> str: + return self.epic.spelling + + @property + def tracked(self) -> str | None: + return None + + def read(self) -> Plan | Failure: + authorization = basic_auth(self.env_file) + if isinstance(authorization, Failure): + return authorization + issues = children(self.epic, authorization, self.http) + if isinstance(issues, Failure): + return Failure(f"{self.epic.site}: {issues.reason}") + try: + return plan_of(issues, self.epic, self.to_markdown) + except (AttributeError, KeyError, TypeError): + return Failure(f"{self.epic.site} answered issues in another shape than Jira Cloud's REST API version 3 documents") + + def add(self, fields: dict[str, str], detail: str) -> Written | Failure: + return Failure(READ_ONLY) + + def edit(self, id_: int, fields: dict[str, str], detail: str | None) -> Written | Failure: + return Failure(READ_ONLY) + + def finish(self, id_: int) -> Written | Failure: + return Failure(READ_ONLY) + + +def basic_auth(env_file: pathlib.Path) -> str | Failure: + """The Authorization header for the email and API token that env_file's KEY=value lines hold.""" + try: + mode = env_file.stat().st_mode + text = env_file.read_text(encoding="utf-8") + except FileNotFoundError: + return Failure(f"{env_file} does not exist; it needs {' and '.join(KEYS)}") + except (OSError, UnicodeDecodeError) as failure: + return Failure(f"cannot read {env_file}: {failure}") + if mode & 0o077: + return Failure(f"{env_file} holds an API token, so only its owner may read it; run chmod 600 {env_file}") + values = parse_env(text) + if missing := [key for key in KEYS if not values.get(key)]: + return Failure(f"{env_file} lacks {' and '.join(missing)}") + return "Basic " + base64.b64encode(":".join(values[key] for key in KEYS).encode()).decode() + + +def children(epic: Epic, authorization: str, http: Http) -> list[dict[str, typing.Any]] | Failure: + """The epic's open child issues in backlog order, which is the order the team ranks them in. An issue in a done status is a finished item, so it is no longer in the plan.""" + body: dict[str, object] = { + "jql": f'parent = "{epic.key}" AND statusCategory != Done ORDER BY Rank ASC', + "fields": ["summary", "description", "fixVersions", "issuelinks"], + "properties": [PROPERTY], + "maxResults": PAGE, + } + found: list[dict[str, typing.Any]] = [] + for _ in range(MAX_PAGES): + page = http("POST", f"{epic.site}/rest/api/3/search/jql", authorization, body) + if isinstance(page, Failure): + return page + if not isinstance(page, dict) or not isinstance(page.get("issues"), list): + return Failure("the search answered something other than a page of issues") + found += page["issues"] + if not page.get("nextPageToken"): + return found + body = body | {"nextPageToken": page["nextPageToken"]} + return Failure(f"the search for {epic.key}'s children did not end within {MAX_PAGES} pages") + + +def plan_of(issues: list[dict[str, typing.Any]], epic: Epic, to_markdown: ToMarkdown) -> Plan | Failure: + """The plan the issues hold, in their order. Raises AttributeError, KeyError or TypeError where an issue is not in the shape Jira documents.""" + project = epic.key.rpartition("-")[0] + if strangers := [issue["key"] for issue in issues if not re.fullmatch(rf"{re.escape(project)}-[0-9]+", issue["key"])]: + return Failure(f"{strangers[0]} is a child of {epic.key} in another Jira project, and an item's ID is its number in {project}; move it into {project} or out of the epic") + ids = {number(issue["key"]) for issue in issues} + with concurrent.futures.ThreadPoolExecutor(CONVERSIONS) as pool: + details = list(pool.map(lambda issue: detail(issue, to_markdown), issues)) + items = [item(issue, ids, text) for issue, text in zip(issues, details)] + return next((found for found in items if isinstance(found, Failure)), None) or Plan([found for found in items if isinstance(found, Item)]) + + +def number(key: str) -> int: + return int(key.rpartition("-")[2]) + + +def detail(issue: dict[str, typing.Any], to_markdown: ToMarkdown) -> str | Failure: + """The issue's description as markdown; empty where it has none.""" + description = issue["fields"]["description"] + if description is None: + return "" + text = to_markdown(description) + return Failure(f"{issue['key']}'s description: {text.reason}") if isinstance(text, Failure) else text.strip() + + +def item(issue: dict[str, typing.Any], ids: set[int], text: str | Failure) -> Item | Failure: + """The item an issue holds, blocked by each of its blockers among ids, the plan's items: a blocker that is done or lies outside the epic doesn't make the item wait.""" + if isinstance(text, Failure): + return text + key, fields = issue["key"], issue["fields"] + release = earliest_release([version["name"] for version in fields["fixVersions"]]) + if release is None: + # Until a project can tie its releases to something other than semver versions, an item with no release cannot be placed in the plan. + return Failure(f"{key} names no Fix Version that is a semver version, such as 1.2.0; set one in Jira") + blockers = [number(link["inwardIssue"]["key"]) for link in fields["issuelinks"] if link["type"]["inward"] == "is blocked by" and "inwardIssue" in link and link["inwardIssue"]["key"].rpartition("-")[0] == key.rpartition("-")[0]] + scored = scores(key, issue.get("properties", {}).get(PROPERTY, {})) + if isinstance(scored, Failure): + return scored + return Item(number(key), release, scored[2], bold_cell(fields["summary"].strip()), scored[0], scored[1], tuple(sorted(set(blockers) & ids)), text) + + +def earliest_release(names: list[str]) -> Release | None: + """The earliest release among Fix Versions named as a semver version, with a leading v or without; None where none is.""" + releases = [release for name in names if (release := parsed(name) or tagged(name))] + return min(releases, default=None) + + +def scores(key: str, held: object) -> tuple[dict[str, int], typing.Any, typing.Any] | Failure: + """The scores, Moves and Exempt that an issue's PROPERTY value holds, each in the format the items table of a todo.md takes.""" + if not isinstance(held, dict): + return Failure(f"{key}'s issue property {PROPERTY} is not a JSON object") + named = {name: str(value) for name, value in held.items()} + levels = parse_scores(key, named, SHAPE.score_columns) + if isinstance(levels, Failure): + return levels + moves = parse_moves(key, named.get(MOVES, "")) + if isinstance(moves, Failure): + return moves + exempt = named.get("Exempt", "") + if not is_exempt(exempt): + return Failure(f"item {key}'s Exempt {exempt!r} is not one a todo.md's items table takes") + return levels, moves, exempt diff --git a/bin/plan_store/stores.py b/bin/plan_store/stores.py index 9144cd35..fdca6a5f 100644 --- a/bin/plan_store/stores.py +++ b/bin/plan_store/stores.py @@ -1,6 +1,6 @@ """The one way a tool reads or writes a project's plan: through the store its config names. -The config's `plan` setting names the backend. A path names a markdown file, todo.md, the only backend so far. An agent reads and changes the plan with `todo-item`, which works through the same store. +The config's `plan` setting names the backend. A path names a markdown file, todo.md. A Jira epic names its child issues, which `jira_epic` reads and nothing writes yet. An agent reads and changes the plan with `todo-item`, which works through the same store. A tool that reads what a past commit held, such as `score-outcomes`, still parses that commit's todo.md itself, with `release_plan.todo_table`: only the markdown backend has commits, and todo.md's items 365, 366 and 368 port those tools to the other backends.""" import dataclasses @@ -144,7 +144,13 @@ class FilePlan: def store(config: ProjectConfig) -> PlanStore: """The store config names for the plan.""" - return file_plan(config) + if config.epic is None: + return file_plan(config) + # Imported here, since jira_epic builds on this module's Plan and Written. + from plan_store.jira_epic import JiraPlan + # load refuses a config that names an epic and no env-file. + assert config.env_file is not None + return JiraPlan(config.epic, config.env_file) def file_plan(config: ProjectConfig, path: pathlib.Path | None = None) -> FilePlan: diff --git a/bin/plan_store/test_jira_epic.py b/bin/plan_store/test_jira_epic.py new file mode 100644 index 00000000..f3cc98a3 --- /dev/null +++ b/bin/plan_store/test_jira_epic.py @@ -0,0 +1,165 @@ +import base64 +import pathlib +import sys +import tempfile +import unittest + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) + +from failure import Failure +from plan_store import jira_epic +from plan_store.stores import Plan +from project_config.settings import Epic +from release_plan.release import release_of + +EPIC = Epic("https://acme.atlassian.net", "ABC-12") +SEARCH = "https://acme.atlassian.net/rest/api/3/search/jql" + + +def issue(key: str, summary: str = "Count the runs.", versions: tuple[str, ...] = ("0.1.0",), scores: dict[str, object] | None = None, blocked_by: tuple[str, ...] = (), description: object = None, blocks: tuple[str, ...] = ()) -> dict[str, object]: + links = [{"type": {"inward": "is blocked by", "outward": "blocks"}, "inwardIssue": {"key": blocker}} for blocker in blocked_by] + links += [{"type": {"inward": "is blocked by", "outward": "blocks"}, "outwardIssue": {"key": blocked}} for blocked in blocks] + return { + "key": key, + "fields": {"summary": summary, "description": description, "fixVersions": [{"name": name} for name in versions], "issuelinks": links}, + "properties": {} if scores is None else {jira_epic.PROPERTY: scores}, + } + + +def adf(text: str) -> dict[str, object]: + return {"type": "doc", "version": 1, "content": [{"type": "paragraph", "content": [{"type": "text", "text": text}]}]} + + +def text_of(document: dict[str, object]) -> str | Failure: + """Stands in for the adf-codec shim: the text of the one paragraph adf builds.""" + return document["content"][0]["content"][0]["text"] + "\n" # type: ignore[index] + + +class JiraPlan(unittest.TestCase): + def setUp(self) -> None: + self.env = pathlib.Path(self.enterContext(tempfile.TemporaryDirectory())) / "acme.env" + self.env.write_text("ATLASSIAN_EMAIL=me@example.com\nATLASSIAN_API_TOKEN=s3cret\n") + self.env.chmod(0o600) + self.pages: list[object] = [] + self.calls: list[tuple[str, str, str, object]] = [] + + def http(self, method: str, url: str, authorization: str, body: object) -> object: + self.calls.append((method, url, authorization, body)) + return self.pages[len(self.calls) - 1] + + def store(self) -> jira_epic.JiraPlan: + return jira_epic.JiraPlan(EPIC, self.env, self.http, text_of) + + def read(self, *issues: dict[str, object]) -> Plan | Failure: + self.pages, self.calls = [{"issues": list(issues)}], [] + return self.store().read() + + def items(self, *issues: dict[str, object]): + plan = self.read(*issues) + assert isinstance(plan, Plan), plan + return plan.items + + def test_an_epic_with_no_open_child_reads_as_an_empty_plan(self): + self.assertEqual(self.read(), Plan([])) + + def test_asks_for_the_epics_open_children_in_backlog_order_with_basic_auth(self): + self.read() + method, url, authorization, body = self.calls[0] + self.assertEqual((method, url), ("POST", SEARCH)) + self.assertEqual(authorization, "Basic " + base64.b64encode(b"me@example.com:s3cret").decode()) + self.assertEqual(body["jql"], 'parent = "ABC-12" AND statusCategory != Done ORDER BY Rank ASC') # type: ignore[index] + self.assertEqual(body["properties"], [jira_epic.PROPERTY]) # type: ignore[index] + + def test_an_issue_reads_as_an_item_under_its_number(self): + scores = {"L": 1, "E": 2, "I": 3, "S": 1, "Moves": "1 by 9", "Exempt": "owner"} + item, = self.items(issue("ABC-34", "Count the runs.", ("0.1.0",), scores, description=adf("Why it counts."))) + self.assertEqual((item.id, item.release, item.tagline, item.detail), (34, release_of("0.1.0"), "**Count the runs.**", "Why it counts.")) + self.assertEqual((item.scores, item.moves, item.exempt, item.blocked_by), ({"L": 1, "E": 2, "I": 3, "S": 1}, (("1", 9),), "owner", ())) + + def test_keeps_jiras_order_whatever_the_releases_and_scores(self): + found = self.items(issue("ABC-40", versions=("0.2.0",)), issue("ABC-7", versions=("0.1.0",)), issue("ABC-21", versions=("0.3.0",))) + self.assertEqual([item.id for item in found], [40, 7, 21]) + + def test_an_issue_nobody_scored_reads_without_scores(self): + item, = self.items(issue("ABC-34")) + self.assertEqual((item.scores, item.moves, item.exempt, item.detail, item.likelihood), ({}, (), "", "", 0)) + + def test_an_issue_is_blocked_by_each_blocker_still_in_the_plan(self): + blocked, _ = self.items(issue("ABC-34", blocked_by=("ABC-35", "ABC-2", "OTHER-9"), blocks=("ABC-35",)), issue("ABC-35", blocks=("ABC-34",))) + self.assertEqual(blocked.blocked_by, (35,)) + + def test_the_release_is_the_earliest_fix_version_with_or_without_a_v(self): + item, = self.items(issue("ABC-34", versions=("v1.2.0", "0.9.1", "Later"))) + self.assertEqual(item.release, release_of("0.9.1")) + + def test_an_issue_with_no_semver_fix_version_fails_the_read_naming_it(self): + for versions in ((), ("Sprint 4",)): + failure = self.read(issue("ABC-34", versions=versions)) + self.assertIsInstance(failure, Failure) + self.assertIn("ABC-34", failure.reason) # type: ignore[union-attr] + self.assertIn("Fix Version", failure.reason) # type: ignore[union-attr] + + def test_a_child_in_another_jira_project_fails_the_read_naming_it(self): + failure = self.read(issue("ABC-34"), issue("OTHER-5")) + self.assertIsInstance(failure, Failure) + self.assertIn("OTHER-5", failure.reason) # type: ignore[union-attr] + + def test_scores_out_of_format_fail_the_read_naming_the_issue(self): + for scores in ({"L": 9}, {"L": "high"}, {"Moves": "everything"}, {"Exempt": "because"}, "L 3"): + failure = self.read(issue("ABC-34", scores=scores)) # type: ignore[arg-type] + self.assertIsInstance(failure, Failure, scores) + self.assertIn("ABC-34", failure.reason) # type: ignore[union-attr] + + def test_reads_every_page(self): + self.pages = [{"issues": [issue("ABC-1")], "nextPageToken": "t1"}, {"issues": [issue("ABC-2")]}] + plan = self.store().read() + self.assertEqual([item.id for item in plan.items], [1, 2]) # type: ignore[union-attr] + self.assertNotIn("nextPageToken", self.calls[0][3]) # type: ignore[operator] + self.assertEqual(self.calls[1][3]["nextPageToken"], "t1") # type: ignore[index] + + def test_a_failing_request_fails_the_read(self): + self.pages = [Failure("POST /rest/api/3/search/jql answered 401: no")] + self.assertEqual(self.store().read(), Failure("https://acme.atlassian.net: POST /rest/api/3/search/jql answered 401: no")) + + def test_an_answer_in_another_shape_fails_the_read(self): + for page in ([], {"issues": "none"}, {"issues": [{"key": "ABC-1"}]}, {"issues": [{"key": 7, "fields": {}}]}, {"issues": [issue("ABC-1", summary=None)]}): # type: ignore[arg-type] + self.pages, self.calls = [page], [] + self.assertIsInstance(self.store().read(), Failure, page) + + def test_a_description_the_codec_refuses_fails_the_read_naming_the_issue(self): + store = jira_epic.JiraPlan(EPIC, self.env, self.http, lambda document: Failure("adf-codec refused")) + self.pages = [{"issues": [issue("ABC-34", description=adf("x"))]}] + self.assertEqual(store.read(), Failure("ABC-34's description: adf-codec refused")) + + def test_an_env_file_without_the_credentials_fails_before_any_request(self): + self.env.write_text("ATLASSIAN_EMAIL=me@example.com\n") + failure = self.read() + self.assertIsInstance(failure, Failure) + self.assertIn("ATLASSIAN_API_TOKEN", failure.reason) # type: ignore[union-attr] + self.assertEqual(self.calls, []) + + def test_an_env_file_others_may_read_fails_before_any_request(self): + self.env.chmod(0o644) + self.assertIsInstance(self.read(), Failure) + self.assertEqual(self.calls, []) + + def test_a_missing_env_file_fails(self): + self.env.unlink() + self.assertIsInstance(self.read(), Failure) + + def test_no_failure_holds_the_token(self): + self.pages = [{"issues": [issue("OTHER-5")]}] + self.assertNotIn("s3cret", self.store().read().reason) # type: ignore[union-attr] + + def test_every_write_fails_since_the_store_only_reads(self): + store = self.store() + for written in (store.add({}, ""), store.edit(34, {"L": "2"}, None), store.finish(34)): + self.assertIsInstance(written, Failure) + self.assertEqual(self.calls, []) + + def test_names_itself_by_the_configs_spelling_and_no_commit_holds_it(self): + self.assertEqual((self.store().label, self.store().tracked), ("jira:https://acme.atlassian.net/browse/ABC-12", None)) + + +if __name__ == "__main__": + unittest.main() diff --git a/bin/plan_store/test_stores.py b/bin/plan_store/test_stores.py index 8da5c2f2..8397fd1e 100644 --- a/bin/plan_store/test_stores.py +++ b/bin/plan_store/test_stores.py @@ -7,8 +7,10 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) +from project_config.settings import Epic, ProjectConfig, SETTINGS from failure import Failure from plan_store.contract import FIRST, PlanStoreContract, SECOND +from plan_store.jira_epic import JiraPlan from plan_store.fakes import MemoryPlan from record_store.fakes import MemoryStore from release_plan.todo_table import NoItemsTable @@ -176,5 +178,21 @@ class HeldAt(unittest.TestCase): self.assertEqual(stores.held_at("origin/main", MemoryPlan(tracked="todo.md"), "/checkout", run), Failure("no git")) +class Store(unittest.TestCase): + def config(self, **named) -> ProjectConfig: + paths = {name: pathlib.Path("/checkout", name) for name in SETTINGS[1:]} + return ProjectConfig("acme", pathlib.Path("/folder"), pathlib.Path("/checkout"), paths, **named) + + def test_a_path_picks_the_markdown_file(self): + config = self.config() + picked = stores.store(dataclasses.replace(config, paths=config.paths | {"plan": pathlib.Path("/checkout/todo.md")})) + self.assertEqual((type(picked), picked.label, picked.tracked), (stores.FilePlan, "/checkout/todo.md", "todo.md")) + + def test_an_epic_picks_jira_with_the_env_files_credentials(self): + epic = Epic("https://acme.atlassian.net", "ABC-12") + picked = stores.store(self.config(epic=epic, env_file=pathlib.Path("/secrets/acme.env"))) + self.assertEqual(picked, JiraPlan(epic, pathlib.Path("/secrets/acme.env"), picked.http)) + + if __name__ == "__main__": unittest.main() diff --git a/bin/project_config/main.py b/bin/project_config/main.py index 42ca1401..25a525be 100644 --- a/bin/project_config/main.py +++ b/bin/project_config/main.py @@ -21,6 +21,11 @@ starts with / or ~/. In a worktree, a "checkout:" path is the worktree's own fil goals-and-audience = "folder:goals.md" principles = "folder:principles" +`plan` may name a Jira Cloud epic in place of a path, as "jira:" and the epic's address: +"jira:https://acme.atlassian.net/browse/ABC-12". The plan is then the epic's open child issues, in +Jira's backlog order, and it is printed as the config spells it. Such a config must set `env-file`, +and that file hold ATLASSIAN_EMAIL and ATLASSIAN_API_TOKEN. + `env-file` is an optional setting: the file of KEY=value credentials the project's tools read, a path that starts with / or ~/ and lies outside the checkout and the config's folder, such as "~/.claude-projects/acme-billing.env". Where it is left out, the project has no credentials file, and @@ -81,7 +86,7 @@ def main(argv: list[str]) -> int: if argv and argv[0] in config.texts: print(config.texts[argv[0]]) return 0 - paths = {**config.paths, **({ENV_FILE: config.env_file} if config.env_file else {})} + paths = {**config.places, **({ENV_FILE: str(config.env_file)} if config.env_file else {})} if argv and argv[0] not in paths: print(f"{config.folder / CONFIG} sets no `{ENV_FILE}`", file=sys.stderr) return 1 diff --git a/bin/project_config/settings.py b/bin/project_config/settings.py index a21d4521..6ec86f74 100644 --- a/bin/project_config/settings.py +++ b/bin/project_config/settings.py @@ -25,6 +25,9 @@ COMMIT_TITLE = "commit-title" PULL_REQUEST_TITLE = "pull-request-title" BRANCH = "branch" OPTIONAL = (BRANCH, COMMIT_TITLE, ENV_FILE, LANGUAGE, PULL_REQUEST_TITLE, WAIT_FOR_APPROVAL) +# The one setting that may name something other than a path: a plan kept as the child issues of a Jira Cloud epic, spelt as `jira:` and the epic's address as the browser shows it. Three readers, seated as the human who writes the config, picked that spelling from four candidates, and one ATLASSIAN_ pair of env-file keys for Jira and Confluence over a pair for each. +JIRA = "jira:" +EPIC_SPELLING = '"jira:https:///browse/" for a plan kept as a Jira Cloud epic\'s child issues' OUTSIDE = "a path that starts with / or ~/ and lies outside the checkout and the config's folder, so that no git remote receives the credentials" @@ -33,9 +36,21 @@ class Unnamed(Failure): """No config names a checkout here: none names the one asked for, or git finds no checkout. A reader of titles takes them bare there, as in a third party's clone; a config that is faulty or cannot be read is a plain Failure.""" +@dataclasses.dataclass(frozen=True) +class Epic: + """A Jira Cloud epic: site is its site's address, such as https://acme.atlassian.net, and key its issue key, such as ABC-12.""" + site: str + key: str + + @property + def spelling(self) -> str: + """The epic as a config's `plan` setting spells it.""" + return f"{JIRA}{self.site}/browse/{self.key}" + + @dataclasses.dataclass(frozen=True) class ProjectConfig: - """folder is `~/.claude-projects/`, top is the worktree that asked, and paths holds each of SETTINGS as an absolute path.""" + """folder is `~/.claude-projects/`, top is the worktree that asked, and paths holds each of SETTINGS as an absolute path, but for a plan kept in Jira, which epic holds.""" key: str folder: pathlib.Path top: pathlib.Path @@ -47,6 +62,23 @@ class ProjectConfig: commit_title: str = templates.TITLE pull_request_title: str = templates.TITLE branch: str = templates.BRANCH + # The epic whose child issues are the plan, where the config's `plan` names one; paths then holds no "plan". + epic: Epic | None = None + + @property + def plan_file(self) -> pathlib.Path | None: + """The plan's file; None where the plan is kept in Jira.""" + return self.paths.get("plan") + + @property + def plan_label(self) -> str: + """What a message calls the plan: its path, or the epic as the config spells it.""" + return self.epic.spelling if self.epic else str(self.paths["plan"]) + + @property + def places(self) -> dict[str, str]: + """Where each of SETTINGS is kept, in SETTINGS' order: a path, or the epic as the config spells it.""" + return {name: self.plan_label if name == "plan" else str(self.paths[name]) for name in SETTINGS if name == "plan" or name in self.paths} @property def texts(self) -> dict[str, str]: @@ -59,7 +91,9 @@ class ProjectConfig: def tracked(self, setting: str) -> str | None: """setting's path from top, as git names a file in a commit; None where the config puts it outside the checkout, whose commits hold no version of it.""" - path = self.paths[setting] + path = self.paths.get(setting) + if path is None: + return None return path.relative_to(self.top).as_posix() if path.is_relative_to(self.top) else None @@ -82,6 +116,7 @@ def load(top: pathlib.Path, main: pathlib.Path, home: pathlib.Path) -> ProjectCo return Failure(f"{' and '.join(str(file) for file, _ in named)} each name the checkout {main}; only one config may") file, values = named[0] paths = {name: placed(values[name], top, file.parent, home) for name in SETTINGS if name in values} + epic = epic_of(values.get("plan")) env_file = anywhere(values.get(ENV_FILE), home) misplaced = ENV_FILE in values and (env_file is None or lies_in(env_file, top, main, file.parent)) waits = values.get(WAIT_FOR_APPROVAL, False) @@ -89,14 +124,22 @@ def load(top: pathlib.Path, main: pathlib.Path, home: pathlib.Path) -> ProjectCo faults = [ *(f"`{name}` is missing" for name in SETTINGS if name not in values), *(f"`{name}` is not a setting" for name in values if name not in (*SETTINGS, *OPTIONAL)), - *(f"`{name}` is {values[name]!r}, not {SPELLING}" for name, path in paths.items() if path is None), + *(f"`{name}` is {values[name]!r}, not {SPELLING}" for name, path in paths.items() if path is None and name != "plan"), + *([f"`plan` is {values['plan']!r}, not {SPELLING}, or {EPIC_SPELLING}"] if "plan" in values and paths["plan"] is None and epic is None else []), + *([f"`plan` names a Jira epic, so `{ENV_FILE}` must name the file that holds its credentials"] if epic and ENV_FILE not in values else []), *([f"`{ENV_FILE}` is {values[ENV_FILE]!r}, not {OUTSIDE}"] if misplaced else []), *([f"`{WAIT_FOR_APPROVAL}` is {waits!r}, not true or false"] if not isinstance(waits, bool) else []), *(f"`{name}` is {values[name]!r}, {fault}" for name, check in checks.items() if name in values and (fault := check(values[name]))), ] if faults: return Failure(f"{file}: {'; '.join(faults)}. The settings are {', '.join(SETTINGS)}, and optionally {', '.join(OPTIONAL[:-1])} and {OPTIONAL[-1]}.") - return ProjectConfig(file.parent.name, file.parent, top, {name: path for name, path in paths.items() if path}, env_file, waits is True, **{name.replace("-", "_"): str(values[name]) for name in checks if name in values}) + return ProjectConfig(file.parent.name, file.parent, top, {name: path for name, path in paths.items() if path}, env_file, waits is True, **{name.replace("-", "_"): str(values[name]) for name in checks if name in values}, epic=epic) + + +def epic_of(value: object) -> Epic | None: + """The epic a `plan` setting's value spells; None where it spells none. Only https, so the credentials are never sent in the clear.""" + spelt = isinstance(value, str) and re.fullmatch(rf"{JIRA}(https://[A-Za-z0-9.-]+(?::[0-9]+)?)/browse/([A-Z][A-Z0-9_]*-[0-9]+)", value) + return Epic(spelt.group(1), spelt.group(2)) if spelt else None def language_fault(value: object) -> str | None: diff --git a/bin/project_config/test_project_config.py b/bin/project_config/test_project_config.py index cc39c44f..d6f8c13d 100644 --- a/bin/project_config/test_project_config.py +++ b/bin/project_config/test_project_config.py @@ -8,7 +8,7 @@ import unittest.mock sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) -from project_config.settings import env_files, held, load, OUTSIDE, ProjectConfig, SETTINGS, Unnamed +from project_config.settings import env_files, Epic, held, load, OUTSIDE, ProjectConfig, SETTINGS, Unnamed from failure import Failure from test_env import isolated_env from project_config.main import title_templates @@ -28,6 +28,9 @@ goals-and-audience = "folder:goals.md" principles = "~/.claude/principles" """ +JIRA_PLAN = "jira:https://acme.atlassian.net/browse/ABC-12" +JIRA_CLIENT = CLIENT.replace("folder:todo.md", JIRA_PLAN) + 'env-file = "~/acme.env"\n' + def write_config(home: pathlib.Path, checkout: pathlib.Path, goals: str = "checkout:README.md") -> pathlib.Path: """A config under home that names checkout, every setting inside it but goals-and-audience; for the tests of each tool that reads the config.""" @@ -83,6 +86,36 @@ class LoadTest(ConfigCase): self.assertEqual(found.paths["principles"], self.home / ".claude" / "principles") self.assertEqual(tuple(found.paths), SETTINGS) + def test_a_plan_spelt_as_a_jira_epic_is_no_path(self) -> None: + self.write("acme", JIRA_CLIENT) + found = load(self.checkout, self.checkout, self.home) + assert isinstance(found, ProjectConfig), found + self.assertEqual(found.epic, Epic("https://acme.atlassian.net", "ABC-12")) + self.assertEqual((found.plan_file, found.tracked("plan"), found.plan_label), (None, None, JIRA_PLAN)) + self.assertEqual(tuple(found.places), SETTINGS) + self.assertEqual(found.places["plan"], JIRA_PLAN) + self.assertEqual(tuple(found.paths), SETTINGS[1:]) + + def test_a_plan_kept_as_a_file_has_no_epic(self) -> None: + folder = self.write("acme", CLIENT) + found = load(self.checkout, self.checkout, self.home) + assert isinstance(found, ProjectConfig), found + self.assertEqual((found.epic, found.plan_file, found.plan_label, found.places["plan"]), (None, folder / "todo.md", str(folder / "todo.md"), str(folder / "todo.md"))) + + def test_a_jira_plan_needs_an_env_file(self) -> None: + self.write("acme", JIRA_CLIENT.replace('env-file = "~/acme.env"\n', "")) + self.assertIn("`plan` names a Jira epic, so `env-file` must name the file that holds its credentials", self.failure()) + + def test_a_plan_that_spells_no_path_and_no_epic_names_both_spellings(self) -> None: + for spelled in ("jira:http://acme.atlassian.net/browse/ABC-12", "jira:https://acme.atlassian.net/browse/abc-12", "jira:https://acme.atlassian.net/browse/ABC-12/x", "jira:https://acme.atlassian.net@evil.example/browse/ABC-12", "jira:ABC-12", "https://acme.atlassian.net/browse/ABC-12"): + with self.subTest(spelled): + self.write(f"acme-{len(spelled)}-{hash(spelled) % 1000}", CLIENT.replace("folder:todo.md", spelled) + 'env-file = "~/acme.env"\n') + reason = self.failure() + self.assertIn(f"`plan` is {spelled!r}, not ", reason) + self.assertIn("jira:https:///browse/", reason) + for config in (self.home / ".claude-projects").glob("*/config.toml"): + config.unlink() + def test_a_worktree_finds_the_main_checkouts_config_and_reads_its_own_files(self) -> None: self.write("acme", CLIENT) worktree = self.home / "code" / "acme-billing-item-3" @@ -325,6 +358,11 @@ class EnvFilesTest(ConfigCase): class ToolTest(ConfigCase): + def test_prints_a_jira_plan_as_the_config_spells_it(self) -> None: + self.write("acme", JIRA_CLIENT) + self.assertEqual(self.run_tool("plan").stdout, JIRA_PLAN + "\n") + self.assertEqual(self.run_tool().stdout.splitlines()[0], f"plan: {JIRA_PLAN}") + def run_tool(self, *args: str, cwd: pathlib.Path | None = None) -> subprocess.CompletedProcess[str]: return subprocess.run([sys.executable, str(TOOL), *args], cwd=cwd or self.checkout, env={**isolated_env(), "HOME": str(self.home)}, capture_output=True, text=True) diff --git a/bin/rank_todo.py b/bin/rank_todo.py index 1bc6b6f0..ff2ee2e1 100755 --- a/bin/rank_todo.py +++ b/bin/rank_todo.py @@ -106,10 +106,12 @@ def main(argv: list[str]) -> int: config = located(None, pathlib.Path.home()) if isinstance(config, Failure): return fail(config) - check, todo = args[0], args[1] or config.paths["plan"] + if config.plan_file is None: + return fail(Failure(f"rank_todo.py ranks a todo.md, and this checkout's config keeps the plan in Jira, whose backlog ranks it: {config.plan_label}")) + check, todo = args[0], args[1] or config.plan_file # The goals, decisions and history are this checkout's project's, so another project's plan would be ranked by them. - if todo.resolve() != config.paths["plan"].resolve(): - return fail(Failure(f"rank_todo.py: {todo} is not the plan this checkout's config names, {config.paths['plan'].resolve()}; run rank_todo.py in the checkout of the project whose plan it is")) + if todo.resolve() != config.plan_file.resolve(): + return fail(Failure(f"rank_todo.py: {todo} is not the plan this checkout's config names, {config.plan_file.resolve()}; run rank_todo.py in the checkout of the project whose plan it is")) if check: failures = plan_file.check_failures(todo, config) for line in failures: diff --git a/bin/rule_hook/test_rule_hook.py b/bin/rule_hook/test_rule_hook.py index 3e003f8f..13682da1 100644 --- a/bin/rule_hook/test_rule_hook.py +++ b/bin/rule_hook/test_rule_hook.py @@ -1217,6 +1217,14 @@ class TodoRankCheck(unittest.TestCase): (self.config.parent / "todo.md").write_text("# todo\n") self.assertEqual(self.details(checkout), [f"own script checked {self.config.parent}/todo.md"]) + def test_a_plan_in_jira_is_not_checked_in_the_checkout_or_the_configs_folder(self): + checkout = self.changed_plan(f"{self.folder}/clone", self.STUB) + self.config.write_text(self.config.read_text().replace('"checkout:todo.md"', '"jira:https://acme.atlassian.net/browse/ABC-12"') + 'env-file = "~/acme.env"\n') + folder = str(self.config.parent) + git(folder, "init", "-q") + (self.config.parent / "todo.md").write_text("# todo\n") + self.assertEqual((self.details(checkout), self.details(folder)), ([], [])) + def test_a_commit_in_the_configs_folder_checks_the_plan_it_keeps_there_once_it_changes(self): checkout = self.changed_plan(f"{self.folder}/clone", self.STUB) folder = str(self.config.parent) diff --git a/bin/rule_hook/todo_check.py b/bin/rule_hook/todo_check.py index c7947911..43edc10c 100644 --- a/bin/rule_hook/todo_check.py +++ b/bin/rule_hook/todo_check.py @@ -32,9 +32,9 @@ def todo_breaches(directory: str, home: pathlib.Path, own: pathlib.Path = OWN) - # A checkout whose todo.md changes with no config is one whose config is still to write. An unchanged todo.md may be a third party's, whose clone needs no config. unconfigured = pathlib.Path(top) / "todo.md" return [Breach("todo-rank-check", config.reason, top)] if unconfigured.is_file() and changed(top, unconfigured, "todo.md") else [] - todo, tracked = config.paths["plan"], config.tracked("plan") - # A plan outside the checkout has no commit in the checkout to differ from, so it is checked on every call. - if not todo.is_file() or (tracked is not None and not changed(top, todo, tracked)): + todo, tracked = config.plan_file, config.tracked("plan") + # A plan outside the checkout has no commit in the checkout to differ from, so it is checked on every call. A plan in Jira is no file, and Jira's backlog ranks it. + if todo is None or not todo.is_file() or (tracked is not None and not changed(top, todo, tracked)): return [] return [Breach("todo-rank-check", line, top) for line in check_failures(top, todo, config, own)] @@ -43,9 +43,9 @@ def folder_breaches(top: str, config: ProjectConfig | Failure, own: pathlib.Path """Why the plan kept in top, a config's folder, is not ranked, where the plan has changed in that folder's repo; ranked as for a commit in the project's checkout. A config that fails to load doesn't block anything here, so that the commit that fixes it goes through.""" - if isinstance(config, Failure) or not config.paths["plan"].is_relative_to(config.folder): + todo = None if isinstance(config, Failure) else config.plan_file + if isinstance(config, Failure) or todo is None or not todo.is_relative_to(config.folder): return [] - todo = config.paths["plan"] if not todo.is_file() or not changed(str(config.folder), todo, todo.relative_to(config.folder).as_posix()): return [] return [Breach("todo-rank-check", line, top) for line in check_failures(str(config.top), todo, config, own)] diff --git a/bin/test_rank_todo.py b/bin/test_rank_todo.py index 2d1787e3..13f2a5d2 100644 --- a/bin/test_rank_todo.py +++ b/bin/test_rank_todo.py @@ -57,6 +57,17 @@ class Main(unittest.TestCase): (folder / "decisions.md").write_bytes(b"\xff") self.assertEqual(self.run_main(), (1, f"cannot read {folder}/decisions.md: not UTF-8 on line 1\n")) + def test_refuses_a_project_whose_plan_is_in_jira_and_writes_no_file(self): + with tempfile.TemporaryDirectory() as temp: + config = configured(self, pathlib.Path(temp)) / "config.toml" + self.enterContext(contextlib.chdir(temp)) + config.write_text(config.read_text().replace('"checkout:todo.md"', '"jira:https://acme.atlassian.net/browse/ABC-12"') + 'env-file = "~/acme.env"\n') + todo = pathlib.Path(temp, "todo.md") + todo.write_text(TODO) + for args in ((), ("--check",), (str(todo),)): + self.assertEqual(self.run_main(*args), (1, "rank_todo.py ranks a todo.md, and this checkout's config keeps the plan in Jira, whose backlog ranks it: jira:https://acme.atlassian.net/browse/ABC-12\n")) + self.assertEqual(todo.read_text(), TODO) + def test_refuses_a_file_that_is_not_the_plan_the_config_names_and_a_checkout_no_config_names(self): with tempfile.TemporaryDirectory() as temp: folder = configured(self, pathlib.Path(temp)) diff --git a/docs/decisions.md b/docs/decisions.md index fc4abb06..bd1bd8d4 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -21,6 +21,7 @@ Each project principle states one rule that the decisions below apply; their ent - machine load: a heavy command waits for one of the machine's heavy slots, one for every 4 CPUs, which every session shares, and loop-claude starts a worker only while at least a quarter of the machine's memory is available - principles: about seven things per level, four or five where they act on each other, more where a reader finds them by name; crossing a limit asks for a grouping or a recorded reason - project config: a tool that reads a file's commits says where it does not support that file, and the work goes on +- project config: `plan` names a Jira Cloud epic as `jira:` and its address, the plan is its open child issues in backlog order, and an issue's number is the item's ID - project config: `language` names the prose's language by its English name, and `commit-title`, `pull-request-title` and `branch` are brace templates over `{id}` and `{summary}` - review: a release review fixes its findings in the release it reviews, and files under that release only a finding that needs a human answer, adds a feature or outlasts its five rounds - review: a reviewer or comprehension seat that rules the work below standard may ask to rerun once, one rung up, in the same round; the ruling that stands is an escalation trigger for the worker unless the fix changes only prose, and never for the judge @@ -277,6 +278,17 @@ Valid while the later fixes per finished chunk, which `score-outcomes` and the r Messages keep each file's usual name, such as `todo.md`, as its label, since the config keeps the names. Revisit at 0.13.0, which plans the support for `score-outcomes`, the routing figures, the release standing and the owed scoring run. +## project config: `plan` names a Jira Cloud epic as `jira:` and its address, the plan is its open child issues in backlog order, and an issue's number is the item's ID + +2026-11-14, larv-review, on lilleman's calls of 2026-11-12 and 2026-11-14. Serves goal 1.6: a client's team keeps planning in its own Jira. Valid while a client's plan fits one epic in one Jira project. + +- **One epic is one project's plan, and Jira's backlog rank orders it.** The team sets the rank, so the loop's score doesn't break ties and the loop doesn't reorder anything (lilleman, 2026-11-12). An item is an open child issue; one in a done status category is finished. +- **A bench of readers picked the spelling.** Three fresh readers, seated as the person who writes a client's `config.toml`, each picked `plan = "jira:https:///browse/"` over the bare address, a `jira:` beside a `jira-site` key, and a `[plan]` table. Each also picked one pair of env-file keys, `ATLASSIAN_EMAIL` and `ATLASSIAN_API_TOKEN`, for Jira and Confluence over a pair for each, since one account's token opens both. +- **An item's ID stays a whole number: the issue's number in the epic's Jira project.** About 30 modules read an ID as an int, and the `branch` and title templates already spell a ticket's name, as `ABC-{id}`. So the store refuses a child issue from another Jira project, and counts a blocker only among the plan's own items (`bin/plan_store/jira_epic.py`). +- **The scores sit in one issue property, `plan-item`**, which needs no Jira admin (lilleman, 2026-11-12). An issue without it reads as an item nobody scored. +- **The release is the earliest Fix Version named as a semver version**, and an issue with none fails the read, naming it, until todo.md's item 359 ties releases to something else. +- **The store only reads**, until todo.md's item 352 writes. A tool that works on the file, such as `rank_todo.py` or rule-hook's rank check, refuses or skips a plan in Jira. + ## project config: `language` names the prose's language by its English name, and `commit-title`, `pull-request-title` and `branch` are brace templates over `{id}` and `{summary}` 2026-11-14, larv-review. Serves goal 1.6: a client's team reads its docs, Jira text, commits and pull requests in its own language and format. Valid while one language and one template per title serve a project.