From 42cff3a8a7de761f71e2a7c5755eef770306707c Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 18 Nov 2026 23:04:34 +0100 Subject: [PATCH 01/26] Move an epic's issue to done in Jira when its chunk finishes --- README.md | 2 +- bin/do_epic/backend/contract.py | 17 +++++++++ bin/do_epic/backend/fake.py | 12 ++++++- bin/do_epic/backend/jira.py | 52 +++++++++++++++++++++++++--- bin/do_epic/backend/protocol.py | 3 ++ bin/do_epic/backend/test_jira.py | 59 ++++++++++++++++++++++++++++++-- bin/do_epic/main.py | 5 ++- bin/do_epic/test_main.py | 19 ++++++++++ docs/reading-cost.md | 22 ++++++++++++ 9 files changed, 182 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 1da63f00..682a76ea 100644 --- a/README.md +++ b/README.md @@ -216,7 +216,7 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a - `branch_chunks/` cuts a default branch into chunks and finds, for each, the items it shipped and the later chunks that fixed its code, for `score_outcomes` and `routing_figures`. It imports `reading_cost`'s record path. - `command_lines/` reads a shell command: its simple commands, and a docker call's subcommand and memory limits, for `command_patterns`, `reading_cost`, `routing_figures`, `rule_hook` and `run_heavy`. - `deploy_release` imports `release_plan`'s `release_standing`. -- `do_epic/` holds `do-epic`, the tool that drives one Jira epic. `main.py` starts the epic's chunks and runs one chunk's cycles in its window, through `agent_cycle`. `scheduler.py` says which issues run now: as many as the epic's cap and each repo's `parallel-chunks` allow, and none in a repo where loop-claude runs chunks. Beside it, `chunk_prompt.py` words what a chunk's worker reads. `config.py` reads its machine-wide settings, importing `project_config`'s settings and `model_routing`'s ladder file, and `epic_record.py` reads and writes an epic's description by section, language line and cap line, through `record_store`'s `EpicDescription`. `repos.py` finds a repo's checkout and project config by its name, and clones a missing checkout from the host and owner of the epic's other repos, through `forge`'s `url_beside`. `repo_pick.py` asks claude, by `repo-rule.md`, where an epic item is worked, and records the answer as a label on the issue. `split.py` has claude predict from the code which repos an item changes, and files a sub-task per repo under it where there are several. `ranking.py` orders an epic's items by score over one chain of goals, the epic's, then code health, then the item's repo's, through `plan`'s ranking, and re-ranks the tracker's backlog to that order through `backend/`. `backend/` reads, files and ranks the epic's issues, adds the labels `repo_pick.py` and `split.py` record, and posts comments. +- `do_epic/` holds `do-epic`, the tool that drives one Jira epic. `main.py` starts the epic's chunks and runs one chunk's cycles in its window, through `agent_cycle`. `scheduler.py` says which issues run now: as many as the epic's cap and each repo's `parallel-chunks` allow, and none in a repo where loop-claude runs chunks. Beside it, `chunk_prompt.py` words what a chunk's worker reads. `config.py` reads its machine-wide settings, importing `project_config`'s settings and `model_routing`'s ladder file, and `epic_record.py` reads and writes an epic's description by section, language line and cap line, through `record_store`'s `EpicDescription`. `repos.py` finds a repo's checkout and project config by its name, and clones a missing checkout from the host and owner of the epic's other repos, through `forge`'s `url_beside`. `repo_pick.py` asks claude, by `repo-rule.md`, where an epic item is worked, and records the answer as a label on the issue. `split.py` has claude predict from the code which repos an item changes, and files a sub-task per repo under it where there are several. `ranking.py` orders an epic's items by score over one chain of goals, the epic's, then code health, then the item's repo's, through `plan`'s ranking, and re-ranks the tracker's backlog to that order through `backend/`. `backend/` reads, files and ranks the epic's issues, adds the labels `repo_pick.py` and `split.py` record, posts comments, and moves a finished chunk's issue to done. - `forge/` tells a GitHub origin from a Gitea one, names a repo beside an origin's and runs that forge's CLI (`commands.py`), and finds a pull request and waits for its checks (`pulls.py`), for `chunk_preflight`, `chunk_pr`, `deploy_release`, `do_epic` and `larv_review`. - `git_cli/` runs git for every tool (`git_repo.py`), and reads the git calls in a shell command (`git_command.py`). - `judge_replay` imports `agent_cycle`'s judge and verdicts, and `loop_claude`'s premises, records and `ANSWER_DESTINATIONS`. diff --git a/bin/do_epic/backend/contract.py b/bin/do_epic/backend/contract.py index 7101e63c..bdadc913 100644 --- a/bin/do_epic/backend/contract.py +++ b/bin/do_epic/backend/contract.py @@ -124,6 +124,23 @@ class EpicStoreContract: self.assertIsInstance(store.add_label("ZZZ-1", "repo:log"), Failure) self.assertEqual([issue.labels for issue in self.issues(store)], [(), ()]) + def test_finishes_a_child_issue_so_it_reads_as_done_and_leaves_one_that_is_done_as_it_is(self) -> None: + store = self.new_store() + key = self.filed(store, store.epic_key, "Count the runs.") + other = self.filed(store, store.epic_key, "Ship the later thing.") + closed = self.filed(store, store.epic_key, "Close the old thing.") + self.close(store, closed, "Done") + self.assertEqual([store.finish(key), store.finish(closed)], [None, None]) + self.assertEqual({issue.key: issue.done for issue in self.issues(store)}, {key: True, other: False, closed: True}) + + def test_refuses_to_finish_a_sub_task_or_an_issue_outside_the_epic(self) -> None: + store = self.new_store() + child = self.filed(store, store.epic_key, "Count the runs.") + task = self.filed(store, child, "Count them in the api.") + self.assertEqual(store.finish(task), Failure(f"{task} is not one of the child issues of the epic {store.epic_key}, so it cannot be finished")) + self.assertIsInstance(store.finish("ZZZ-1"), Failure) + self.assertEqual([issue.done for issue in self.issues(store)], [False, False]) + def test_posts_comments_on_a_child_issue_in_order(self) -> None: store = self.new_store() key = self.filed(store, store.epic_key, "Count the runs.") diff --git a/bin/do_epic/backend/fake.py b/bin/do_epic/backend/fake.py index c6d766bb..94f6f650 100644 --- a/bin/do_epic/backend/fake.py +++ b/bin/do_epic/backend/fake.py @@ -7,7 +7,7 @@ from failure import Failure @dataclasses.dataclass class MemoryEpic: - """An epic whose issues rank in the order filed, until one is ranked. Where fails is set, every read, filing, label, comment and rank fails with it as the reason. comments holds each issue's comments, by key.""" + """An epic whose issues rank in the order filed, until one is ranked. Where fails is set, every read, filing, label, comment, rank and finish fails with it as the reason. comments holds each issue's comments, by key.""" epic_key: str issues: list[EpicIssue] = dataclasses.field(default_factory=list) comments: dict[str, list[str]] = dataclasses.field(default_factory=dict) @@ -60,6 +60,16 @@ class MemoryEpic: self.comments.setdefault(key, []).append(text.strip()) return None + def finish(self, key: str) -> None | Failure: + if self.fails: + return Failure(self.fails) + child = next((issue for issue in self.issues if issue.key == key and issue.parent == self.epic_key), None) + if child is None: + return no_child(self.epic_key, key, "finished") + if not child.done: + self.change(key, status="Done", done=True) + return None + def change(self, key: str, **fields: object) -> None: """Changes the issue named key as a person would in the tracker, such as assignee="Ada Lovelace".""" self.issues = [dataclasses.replace(issue, **fields) if issue.key == key else issue for issue in self.issues] # type: ignore[arg-type] diff --git a/bin/do_epic/backend/jira.py b/bin/do_epic/backend/jira.py index 43813796..2597f34f 100644 --- a/bin/do_epic/backend/jira.py +++ b/bin/do_epic/backend/jira.py @@ -5,7 +5,7 @@ import typing from adf_codec.convert import adfs_to_markdown, markdown_to_adf, Refused from atlassian.client import basic_auth, Http, jira_json, ToAdf, ToMarkdown -from plan_store.jira_epic import blocked_by_links, FILED_BY, ISSUE_KEY, ISSUE_TYPE, project_of, PROPERTY, rank_refusal, scores, searched +from plan_store.jira_epic import blocked_by_links, DONE, FILED_BY, ISSUE_KEY, ISSUE_TYPE, offer_of, project_of, PROPERTY, rank_refusal, scores, searched from project_config.settings import Epic from do_epic.backend.protocol import EpicIssue, no_child, no_parent, no_words, unfit, unfit_label from failure import Failure @@ -116,6 +116,28 @@ class JiraEpic: posted = self.http("POST", f"{self.epic.site}/rest/api/3/issue/{key}/comment", authorization, {"body": body}) return Failure(f"cannot comment on {key}: {posted.reason}") if isinstance(posted, Failure) else None + def finish(self, key: str) -> None | Failure: + authorization = basic_auth(self.env_file) + if isinstance(authorization, Failure): + return authorization + placed = self.placed(key, authorization, "to finish it") + if isinstance(placed, Failure): + return placed + above, done = placed + if above != self.epic_key: + return no_child(self.epic_key, key, "finished") + if done: + return None + url = f"{self.epic.site}/rest/api/3/issue/{key}/transitions" + offered = self.http("GET", url, authorization, None) + if isinstance(offered, Failure): + return Failure(f"cannot read {key}'s transitions: {offered.reason}") + transition = done_transition(offered, key) + if isinstance(transition, Failure): + return transition + moved = self.http("POST", url, authorization, {"transition": {"id": transition}}) + return Failure(f"cannot move {key} to done: {moved.reason}; the issue may have moved all the same: read it in Jira before moving it again") if isinstance(moved, Failure) else None + def not_a_parent(self, parent: str, authorization: str) -> Failure | None: """Why nothing can be filed under parent; None where it is the epic or one of its child issues.""" if parent == self.epic_key: @@ -125,15 +147,22 @@ class JiraEpic: def parent_of(self, key: str, authorization: str, why: str) -> str | None | Failure: """The key of key's parent issue; None where key isn't an issue key or has no parent. A failed read says "cannot read ".""" + placed = self.placed(key, authorization, why, "parent") + return placed if isinstance(placed, Failure) else placed[0] + + def placed(self, key: str, authorization: str, why: str, asked: str = "parent,status") -> tuple[str | None, bool] | Failure: + """The key of key's parent issue, None where key isn't an issue key or has no parent, and whether its status is a done one; asked names the fields to read, and a field it leaves out reads as not done. A failed read says "cannot read ".""" if not ISSUE_KEY.fullmatch(key): - return None + return None, False # A search may not show an issue filed a moment ago, so the issue is asked for by its key. - answered = self.http("GET", f"{self.epic.site}/rest/api/3/issue/{key}?fields=parent", authorization, None) + answered = self.http("GET", f"{self.epic.site}/rest/api/3/issue/{key}?fields={asked}", authorization, None) if isinstance(answered, Failure): return Failure(f"cannot read {key} {why}: {answered.reason}") fields = answered.get("fields") if isinstance(answered, dict) else None above = fields.get("parent") if isinstance(fields, dict) else None - return above.get("key") if isinstance(above, dict) and isinstance(above.get("key"), str) else None + status = fields.get("status") if isinstance(fields, dict) else None + category = status.get("statusCategory") if isinstance(status, dict) else None + return (above.get("key") if isinstance(above, dict) and isinstance(above.get("key"), str) else None), isinstance(category, dict) and category.get("key") == DONE def found(self, authorization: str) -> list[Found] | Failure: """Each child issue, each followed by its sub-tasks.""" @@ -174,6 +203,21 @@ class JiraEpic: return Failure(f"{project} has no sub-task issue type; turn sub-tasks on in Jira") if found is None else {"id": found} +def done_transition(offered: object, key: str) -> str | Failure: + """The ID of the one transition among those Jira offered for the issue named key that leads to a done status; or why no move can finish it. Which of two such moves finishes it is the team's workflow, so none is picked.""" + raw = offered.get("transitions") if isinstance(offered, dict) else None + found = [offer for each in raw if (offer := offer_of(each))] if isinstance(raw, list) else [] + if not isinstance(raw, list) or len(found) != len(raw): + return Failure(f"Jira answered {key}'s transitions in a shape other than the one it documents") + closing = [(id_, name, status) for id_, name, status, category in found if category == DONE] + if len(closing) == 1: + return closing[0][0] + if closing: + return Failure(f"{key}'s status has more than one transition to a done status, {' and '.join(f'{name!r} to {status!r}' for _, name, status in closing)}: move the issue in Jira, or change the workflow so that one move closes it") + others = " and ".join(f"{name!r} to {status!r}" for _, name, status, _ in found) + return Failure(f"{key}'s status has no transition to a done status" + (f", only {others}" if others else "") + ": move the issue in Jira, or change the workflow so that one move closes it") + + def found_of(raw: object) -> Found | Failure: """The issue in one entry of a search's answer, or which issue is not in the shape Jira documents.""" key = raw.get("key") if isinstance(raw, dict) else None diff --git a/bin/do_epic/backend/protocol.py b/bin/do_epic/backend/protocol.py index b48b314c..e1daad98 100644 --- a/bin/do_epic/backend/protocol.py +++ b/bin/do_epic/backend/protocol.py @@ -63,6 +63,9 @@ class EpicStore(typing.Protocol): def comment(self, key: str, text: str) -> None | Failure: """Posts text, markdown, as a comment on the epic's child issue named key, for the people who work the epic to read. A sub-task, an issue outside the epic, or an empty or blank text is refused.""" + def finish(self, key: str) -> None | Failure: + """Moves the epic's child issue named key to a done status, so that read answers it as done; one already done stays as it is. A sub-task, or an issue outside the epic, is refused, and so is a tracker whose workflow offers no one move to a done status.""" + def unfit(summary: str, labels: tuple[str, ...]) -> Failure | None: """Why no tracker can file an issue with this summary and these labels; None where a tracker can file it.""" diff --git a/bin/do_epic/backend/test_jira.py b/bin/do_epic/backend/test_jira.py index 3d3c7cac..8207e6bb 100644 --- a/bin/do_epic/backend/test_jira.py +++ b/bin/do_epic/backend/test_jira.py @@ -24,6 +24,7 @@ ISSUE_TYPES = f"{SITE}/rest/api/3/issue/createmeta/ABC/issuetypes" SEARCH = f"{SITE}/rest/api/3/search/jql" ISSUES = f"{SITE}/rest/api/3/issue" RANK = f"{SITE}/rest/agile/1.0/issue/rank" +DONE = {"name": "Done", "statusCategory": {"key": "done"}} TO_DO = {"name": "To Do", "statusCategory": {"key": "new"}} TYPES = {"issueTypes": [{"id": "10001", "name": "Task", "subtask": False}, {"id": "10003", "name": "Subtask", "subtask": True}]} @@ -44,6 +45,8 @@ class FakeJira: answers: dict[tuple[str, str], object] = dataclasses.field(default_factory=dict) calls: list[tuple[str, str]] = dataclasses.field(default_factory=list) comments: dict[str, list[object]] = dataclasses.field(default_factory=dict) + # The transitions Jira offers an issue that isn't done. + workflow: list[dict[str, object]] = dataclasses.field(default_factory=lambda: [{"id": "31", "name": "Mark as done", "to": DONE}]) def __call__(self, method: str, url: str, authorization: str, body: object) -> object: self.calls.append((method, url)) @@ -57,8 +60,15 @@ class FakeJira: return TYPES if method == "POST" and url == SEARCH: return self.page(body) - if method == "GET" and (held := next((issue for issue in self.issues if url == f"{ISSUES}/{issue['key']}?fields=parent"), None)): - return {"key": held["key"], "fields": {"parent": held["fields"]["parent"]}} # type: ignore[index] + if method == "GET" and (held := next((issue for issue in self.issues if url.startswith(f"{ISSUES}/{issue['key']}?fields=")), None)): + asked = url.partition("?fields=")[2].split(",") + return {"key": held["key"], "fields": {name: held["fields"][name] for name in asked}} # type: ignore[index] + if method == "GET" and (held := next((issue for issue in self.issues if url == f"{ISSUES}/{issue['key']}/transitions"), None)): + return {"transitions": [] if held["fields"]["status"] == DONE else self.workflow} # type: ignore[index] + if method == "POST" and (held := next((issue for issue in self.issues if url == f"{ISSUES}/{issue['key']}/transitions"), None)): + assert isinstance(body, dict) + held["fields"]["status"] = DONE # type: ignore[index] + return None if method == "POST" and url == ISSUES: return self.created(body) if method == "PUT" and url == RANK: @@ -153,6 +163,51 @@ class JiraEpicContract(Case, EpicStoreContract): class Jira(Case): + def test_finishes_an_issue_by_the_one_transition_that_leads_to_a_done_status(self) -> None: + store = self.new_store() + key = store.file("ABC-12", "Count the runs.", "", ()) + self.jira.workflow = [{"id": "11", "name": "Start", "to": {"name": "In Progress", "statusCategory": {"key": "indeterminate"}}}, {"id": "31", "name": "Mark as done", "to": DONE}] + self.assertIsNone(store.finish(key)) + self.assertEqual(self.jira.calls[-1], ("POST", f"{ISSUES}/{key}/transitions")) + self.assertEqual(self.jira.issues[0]["fields"]["status"], DONE) # type: ignore[index] + + def test_leaves_an_issue_that_is_done_without_asking_for_its_transitions(self) -> None: + store = self.new_store() + key = store.file("ABC-12", "Count the runs.", "", ()) + self.jira.change(key, status=DONE) + self.assertIsNone(store.finish(key)) + self.assertNotIn(("GET", f"{ISSUES}/{key}/transitions"), self.jira.calls) + + def test_a_finish_names_why_no_one_move_closes_the_issue(self) -> None: + store = self.new_store() + key = store.file("ABC-12", "Count the runs.", "", ()) + wont = {"name": "Closed", "statusCategory": {"key": "done"}} + start = {"id": "11", "name": "Start", "to": {"name": "In Progress", "statusCategory": {"key": "indeterminate"}}} + for workflow, reason in ( + ([start], f"{key}'s status has no transition to a done status, only 'Start' to 'In Progress'"), + ([], f"{key}'s status has no transition to a done status"), + ([{"id": "31", "name": "Mark as done", "to": DONE}, {"id": "41", "name": "Won't do", "to": wont}], f"{key}'s status has more than one transition to a done status, 'Mark as done' to 'Done' and \"Won't do\" to 'Closed'"), + ): + with self.subTest(workflow=workflow): + self.jira.workflow = workflow # type: ignore[assignment] + self.assertEqual(store.finish(key), Failure(f"{reason}: move the issue in Jira, or change the workflow so that one move closes it")) + self.assertEqual(self.jira.issues[0]["fields"]["status"], TO_DO) # type: ignore[index] + + def test_a_finish_jira_refuses_says_so_and_that_the_issue_may_have_moved(self) -> None: + store = self.new_store() + key = store.file("ABC-12", "Count the runs.", "", ()) + self.jira.answers[("POST", f"{ISSUES}/{key}/transitions")] = Failure("Jira answered 400: Resolution is required") + self.assertEqual(store.finish(key), Failure(f"cannot move {key} to done: Jira answered 400: Resolution is required; the issue may have moved all the same: read it in Jira before moving it again")) + + def test_a_finish_whose_transitions_jira_cannot_give_or_gives_in_another_shape_fails(self) -> None: + store = self.new_store() + key = store.file("ABC-12", "Count the runs.", "", ()) + url = ("GET", f"{ISSUES}/{key}/transitions") + self.jira.answers[url] = Failure("Jira answered 503") + self.assertEqual(store.finish(key), Failure(f"cannot read {key}'s transitions: Jira answered 503")) + self.jira.answers[url] = {"transitions": [{"id": 31}]} + self.assertEqual(store.finish(key), Failure(f"Jira answered {key}'s transitions in a shape other than the one it documents")) + def test_reads_the_sub_tasks_of_more_children_than_one_search_names(self) -> None: store = self.new_store() children = [store.file("ABC-12", f"Item {n}.", "", ()) for n in range(60)] diff --git a/bin/do_epic/main.py b/bin/do_epic/main.py index e11a46cb..ac961759 100644 --- a/bin/do_epic/main.py +++ b/bin/do_epic/main.py @@ -223,7 +223,10 @@ def chunk_root(issue: EpicIssue, epic: EpicRun) -> tuple[str, bool] | Stop: def handed_on(key: str, epic: EpicRun) -> Stop: - """The stop of a do-epic whose chunk finished, once it has started each chunk that may start now. Its window closes as it exits.""" + """The stop of a do-epic whose chunk finished, once its issue is done in the tracker, so that no finished chunk starts again and what it blocks may start, and it has started each chunk that may start now. Its window closes as it exits.""" + moved = epic.store.finish(key) + if isinstance(moved, Failure): + return Stop(1, f"the chunk finished, but its issue could not move to done: {moved.reason}") started = chunks_started(epic, key) if isinstance(started, Failure): return Stop(1, f"the chunk finished, but the next could not start: {started.reason}") diff --git a/bin/do_epic/test_main.py b/bin/do_epic/test_main.py index de1b1e9a..ba8e9dbe 100644 --- a/bin/do_epic/test_main.py +++ b/bin/do_epic/test_main.py @@ -283,6 +283,25 @@ class AChunksRun(DoEpicTest): self.assertEqual(code, 2, out) self.assertIn("the judge ruled it unfinished 6 cycles running; finish the chunk yourself, or rerun do-epic to give it 6 more cycles", err + out) + def test_a_finished_chunk_moves_its_issue_to_done_before_the_chunk_it_blocks_starts(self) -> None: + store = MemoryEpic("ABC-12", [self.issues[0], self.issues[1], issue("ABC-22", "do-epic-claude", blockers=("ABC-21",))]) + self.backend = lambda config, key: (store, EpicRecord(Description(self.description))) # type: ignore[method-assign,arg-type] + fake = FakeEffects(streams=[self.worker()], claude=[judged("finished")], git=UNREAD, windows="ABC-21\t0\t@9\n") + code, out, err = self.run_main(["--chunk", "ABC-21", "ABC-12"], fake, MODELS) + self.assertEqual(code, 0, err) + self.assertEqual({each.key: each.done for each in store.issues}, {"ABC-20": False, "ABC-21": True, "ABC-22": False}) + self.assertIn("the chunk finished; started ABC-22\n", out) + + def test_a_chunk_whose_issue_jira_will_not_move_to_done_stops_with_the_reason_and_starts_no_other(self) -> None: + store = MemoryEpic("ABC-12", list(self.issues)) + store.finish = lambda key: Failure("ABC-21's status has no transition to a done status") # type: ignore[method-assign] + self.backend = lambda config, key: (store, EpicRecord(Description(self.description))) # type: ignore[method-assign,arg-type] + fake = FakeEffects(streams=[self.worker()], claude=[judged("finished")], git=UNREAD) + code, out, err = self.run_main(["--chunk", "ABC-21", "ABC-12"], fake, MODELS) + self.assertEqual(code, 1) + self.assertIn("the chunk finished, but its issue could not move to done: ABC-21's status has no transition to a done status\n", err) + self.assertNotIn("started", out) + def test_a_finished_chunk_says_why_the_next_could_not_start(self) -> None: store = MemoryEpic("ABC-12", list(self.issues)) reads = iter([self.issues, self.issues, Failure("Jira answered 503")]) diff --git a/docs/reading-cost.md b/docs/reading-cost.md index 6525141c..2438e973 100644 --- a/docs/reading-cost.md +++ b/docs/reading-cost.md @@ -2888,3 +2888,25 @@ Read most (opens and searches): - `README.md` 1 - `bin/rule_hook/endless_wait.py` 1 - `bin/rule_hook/env_file.py` 1 + +## Reading cost, chunk c7c9393c2307, finished 2026-11-18T21:50:41Z + +50171 new input tokens before the first commit. + +Read most (opens and searches): + +- `bin/chunk_preflight/test_chunk_preflight.py` 3 +- `bin/chunk_preflight/main.py` 2 + +## Reading cost, chunk b5056eb2a505, finished 2026-11-18T22:01:58Z + +98259 new input tokens before the first commit. + +Read most (opens and searches): + +- `rules/todo-items.md` 3 +- `bin/loop_claude/loop/chunk_windows.py` 2 +- `bin/loop_claude/loop/main.py` 2 +- `docs/decisions.md` 2 +- `bin/agent_cycle/tmux.py` 1 +- `bin/loop-claude` 1 From 720b558bbf7ea081000feee7f42285b7d46121d6 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 18 Nov 2026 23:38:02 +0100 Subject: [PATCH 02/26] =?UTF-8?q?Answer=20product-owner=20round=201:=201?= =?UTF-8?q?=20=F0=9F=94=B4,=203=20=F0=9F=9F=A1=20(1=20misread);=20finish?= =?UTF-8?q?=20a=20sub-task=20too,=20name=20the=20transition=20in=20the=20c?= =?UTF-8?q?onfig=20where=20several=20close=20an=20issue,=20say=20how=20to?= =?UTF-8?q?=20start=20the=20blocked=20chunks=20after=20a=20refused=20move?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin/do_epic/backend/contract.py | 12 ++++++--- bin/do_epic/backend/fake.py | 3 ++- bin/do_epic/backend/jira.py | 33 +++++++++++++++-------- bin/do_epic/backend/protocol.py | 2 +- bin/do_epic/backend/test_jira.py | 45 ++++++++++++++++++++++++-------- bin/do_epic/config.py | 12 ++++++--- bin/do_epic/main.py | 6 ++--- bin/do_epic/test_do_epic.py | 11 ++++++++ bin/do_epic/test_main.py | 2 +- 9 files changed, 92 insertions(+), 34 deletions(-) diff --git a/bin/do_epic/backend/contract.py b/bin/do_epic/backend/contract.py index bdadc913..feaeaad6 100644 --- a/bin/do_epic/backend/contract.py +++ b/bin/do_epic/backend/contract.py @@ -133,13 +133,19 @@ class EpicStoreContract: self.assertEqual([store.finish(key), store.finish(closed)], [None, None]) self.assertEqual({issue.key: issue.done for issue in self.issues(store)}, {key: True, other: False, closed: True}) - def test_refuses_to_finish_a_sub_task_or_an_issue_outside_the_epic(self) -> None: + def test_finishes_a_sub_task_of_a_child_issue_and_leaves_its_parent_open(self) -> None: store = self.new_store() child = self.filed(store, store.epic_key, "Count the runs.") task = self.filed(store, child, "Count them in the api.") - self.assertEqual(store.finish(task), Failure(f"{task} is not one of the child issues of the epic {store.epic_key}, so it cannot be finished")) + self.assertIsNone(store.finish(task)) + self.assertEqual({issue.key: issue.done for issue in self.issues(store)}, {child: False, task: True}) + + def test_refuses_to_finish_an_issue_outside_the_epic(self) -> None: + store = self.new_store() + child = self.filed(store, store.epic_key, "Count the runs.") self.assertIsInstance(store.finish("ZZZ-1"), Failure) - self.assertEqual([issue.done for issue in self.issues(store)], [False, False]) + self.assertIsInstance(store.finish("not a key"), Failure) + self.assertEqual([issue.done for issue in self.issues(store)], [False]) def test_posts_comments_on_a_child_issue_in_order(self) -> None: store = self.new_store() diff --git a/bin/do_epic/backend/fake.py b/bin/do_epic/backend/fake.py index 94f6f650..aed059a9 100644 --- a/bin/do_epic/backend/fake.py +++ b/bin/do_epic/backend/fake.py @@ -63,7 +63,8 @@ class MemoryEpic: def finish(self, key: str) -> None | Failure: if self.fails: return Failure(self.fails) - child = next((issue for issue in self.issues if issue.key == key and issue.parent == self.epic_key), None) + children = {issue.key for issue in self.issues if issue.parent == self.epic_key} + child = next((issue for issue in self.issues if issue.key == key and (issue.parent == self.epic_key or issue.parent in children)), None) if child is None: return no_child(self.epic_key, key, "finished") if not child.done: diff --git a/bin/do_epic/backend/jira.py b/bin/do_epic/backend/jira.py index 2597f34f..346db288 100644 --- a/bin/do_epic/backend/jira.py +++ b/bin/do_epic/backend/jira.py @@ -6,13 +6,14 @@ import typing from adf_codec.convert import adfs_to_markdown, markdown_to_adf, Refused from atlassian.client import basic_auth, Http, jira_json, ToAdf, ToMarkdown from plan_store.jira_epic import blocked_by_links, DONE, FILED_BY, ISSUE_KEY, ISSUE_TYPE, offer_of, project_of, PROPERTY, rank_refusal, scores, searched -from project_config.settings import Epic +from project_config.settings import Epic, JIRA_FINISH_TRANSITION from do_epic.backend.protocol import EpicIssue, no_child, no_parent, no_words, unfit, unfit_label from failure import Failure FIELDS = ["summary", "description", "labels", "assignee", "status", "parent", "issuelinks"] # How many child issues one search for sub-tasks names, which keeps its JQL well inside the length Jira takes. PARENTS_PER_SEARCH = 50 +PERHAPS_MOVED = "unless Jira refused the request, {key} may be done: read it in Jira before moving it again" PERHAPS_FILED = "unless Jira refused the request, the issue may exist: look under {parent} before filing it again" @@ -31,6 +32,8 @@ class JiraEpic: http: Http = jira_json to_markdown: ToMarkdown = adfs_to_markdown to_adf: ToAdf = markdown_to_adf + # The name of the transition to finish an issue by, where its status offers several to a done status. + finish_by: str | None = None @property def epic_key(self) -> str: @@ -124,7 +127,11 @@ class JiraEpic: if isinstance(placed, Failure): return placed above, done = placed - if above != self.epic_key: + # A sub-task is no child of the epic but its parent is, so a sub-task's parent is read too. + grand = self.parent_of(above, authorization, "to finish its sub-task") if above not in (None, self.epic_key) else None + if isinstance(grand, Failure): + return grand + if above is None or (above != self.epic_key and grand != self.epic_key): return no_child(self.epic_key, key, "finished") if done: return None @@ -132,11 +139,11 @@ class JiraEpic: offered = self.http("GET", url, authorization, None) if isinstance(offered, Failure): return Failure(f"cannot read {key}'s transitions: {offered.reason}") - transition = done_transition(offered, key) + transition = done_transition(offered, key, self.finish_by) if isinstance(transition, Failure): return transition moved = self.http("POST", url, authorization, {"transition": {"id": transition}}) - return Failure(f"cannot move {key} to done: {moved.reason}; the issue may have moved all the same: read it in Jira before moving it again") if isinstance(moved, Failure) else None + return Failure(f"cannot move {key} to done: {moved.reason}; {PERHAPS_MOVED.format(key=key)}") if isinstance(moved, Failure) else None def not_a_parent(self, parent: str, authorization: str) -> Failure | None: """Why nothing can be filed under parent; None where it is the epic or one of its child issues.""" @@ -151,7 +158,7 @@ class JiraEpic: return placed if isinstance(placed, Failure) else placed[0] def placed(self, key: str, authorization: str, why: str, asked: str = "parent,status") -> tuple[str | None, bool] | Failure: - """The key of key's parent issue, None where key isn't an issue key or has no parent, and whether its status is a done one; asked names the fields to read, and a field it leaves out reads as not done. A failed read says "cannot read ".""" + """The key of key's parent issue, None where key isn't an issue key or has no parent, and whether key's own status is a done one; asked names the fields to read, and leaving out `status` makes key read as not done. A failed read says "cannot read ".""" if not ISSUE_KEY.fullmatch(key): return None, False # A search may not show an issue filed a moment ago, so the issue is asked for by its key. @@ -203,19 +210,23 @@ class JiraEpic: return Failure(f"{project} has no sub-task issue type; turn sub-tasks on in Jira") if found is None else {"id": found} -def done_transition(offered: object, key: str) -> str | Failure: - """The ID of the one transition among those Jira offered for the issue named key that leads to a done status; or why no move can finish it. Which of two such moves finishes it is the team's workflow, so none is picked.""" +def done_transition(offered: object, key: str, named: str | None) -> str | Failure: + """The ID of the transition that finishes the issue named key, among those Jira offered, which are the ones its status has and the account may make. It is the one that leads to a done status, or where there are several, the one called named; or why Jira offered no such move. Which of several finishes an issue is the team's workflow, so none is picked without a name.""" raw = offered.get("transitions") if isinstance(offered, dict) else None found = [offer for each in raw if (offer := offer_of(each))] if isinstance(raw, list) else [] if not isinstance(raw, list) or len(found) != len(raw): return Failure(f"Jira answered {key}'s transitions in a shape other than the one it documents") closing = [(id_, name, status) for id_, name, status, category in found if category == DONE] - if len(closing) == 1: - return closing[0][0] + chosen = [move for move in closing if named is None or move[1] == named] + if len(chosen) == 1: + return chosen[0][0] + listed = " and ".join(f"{name!r} to {status!r}" for _, name, status in closing) + if len(closing) > 1 and not named: + return Failure(f"{key}'s status has more than one transition to a done status, {listed}: name the one to use in `{JIRA_FINISH_TRANSITION}`, in ~/.claude-projects/do-epic/config.toml") if closing: - return Failure(f"{key}'s status has more than one transition to a done status, {' and '.join(f'{name!r} to {status!r}' for _, name, status in closing)}: move the issue in Jira, or change the workflow so that one move closes it") + return Failure(f"{key}'s status has no transition called {named!r} to a done status, only {listed}: correct `{JIRA_FINISH_TRANSITION}`, in ~/.claude-projects/do-epic/config.toml") others = " and ".join(f"{name!r} to {status!r}" for _, name, status, _ in found) - return Failure(f"{key}'s status has no transition to a done status" + (f", only {others}" if others else "") + ": move the issue in Jira, or change the workflow so that one move closes it") + return Failure(f"{key}'s status has no transition to a done status" + (f", only {others}" if others else "") + ": Jira lists only the transitions the account may make, so move the issue in Jira, or let the account transition issues") def found_of(raw: object) -> Found | Failure: diff --git a/bin/do_epic/backend/protocol.py b/bin/do_epic/backend/protocol.py index e1daad98..a1fe8d39 100644 --- a/bin/do_epic/backend/protocol.py +++ b/bin/do_epic/backend/protocol.py @@ -64,7 +64,7 @@ class EpicStore(typing.Protocol): """Posts text, markdown, as a comment on the epic's child issue named key, for the people who work the epic to read. A sub-task, an issue outside the epic, or an empty or blank text is refused.""" def finish(self, key: str) -> None | Failure: - """Moves the epic's child issue named key to a done status, so that read answers it as done; one already done stays as it is. A sub-task, or an issue outside the epic, is refused, and so is a tracker whose workflow offers no one move to a done status.""" + """Moves the epic's child issue named key, or a sub-task of one, to a done status, so that read answers it as done; one already done stays as it is. An issue outside the epic is refused. A Failure says why the move could not be made: the issue's workflow gives no way to a done status, gives several the backend cannot choose between, or refuses the move.""" def unfit(summary: str, labels: tuple[str, ...]) -> Failure | None: diff --git a/bin/do_epic/backend/test_jira.py b/bin/do_epic/backend/test_jira.py index 8207e6bb..1ecc75a5 100644 --- a/bin/do_epic/backend/test_jira.py +++ b/bin/do_epic/backend/test_jira.py @@ -45,6 +45,8 @@ class FakeJira: answers: dict[tuple[str, str], object] = dataclasses.field(default_factory=dict) calls: list[tuple[str, str]] = dataclasses.field(default_factory=list) comments: dict[str, list[object]] = dataclasses.field(default_factory=dict) + # The ID of each transition made. + transitioned: list[str] = dataclasses.field(default_factory=list) # The transitions Jira offers an issue that isn't done. workflow: list[dict[str, object]] = dataclasses.field(default_factory=lambda: [{"id": "31", "name": "Mark as done", "to": DONE}]) @@ -68,6 +70,7 @@ class FakeJira: if method == "POST" and (held := next((issue for issue in self.issues if url == f"{ISSUES}/{issue['key']}/transitions"), None)): assert isinstance(body, dict) held["fields"]["status"] = DONE # type: ignore[index] + self.transitioned.append(body["transition"]["id"]) return None if method == "POST" and url == ISSUES: return self.created(body) @@ -178,26 +181,46 @@ class Jira(Case): self.assertIsNone(store.finish(key)) self.assertNotIn(("GET", f"{ISSUES}/{key}/transitions"), self.jira.calls) - def test_a_finish_names_why_no_one_move_closes_the_issue(self) -> None: - store = self.new_store() - key = store.file("ABC-12", "Count the runs.", "", ()) - wont = {"name": "Closed", "statusCategory": {"key": "done"}} + def test_a_finish_names_why_no_move_closes_the_issue(self) -> None: + key = self.new_store().file("ABC-12", "Count the runs.", "", ()) + closed = {"name": "Closed", "statusCategory": {"key": "done"}} start = {"id": "11", "name": "Start", "to": {"name": "In Progress", "statusCategory": {"key": "indeterminate"}}} - for workflow, reason in ( - ([start], f"{key}'s status has no transition to a done status, only 'Start' to 'In Progress'"), - ([], f"{key}'s status has no transition to a done status"), - ([{"id": "31", "name": "Mark as done", "to": DONE}, {"id": "41", "name": "Won't do", "to": wont}], f"{key}'s status has more than one transition to a done status, 'Mark as done' to 'Done' and \"Won't do\" to 'Closed'"), + both = [{"id": "31", "name": "Mark as done", "to": DONE}, {"id": "41", "name": "Close", "to": closed}] + config = " in `jira-finish-transition`, in ~/.claude-projects/do-epic/config.toml" + for workflow, named, reason in ( + ([start], None, f"{key}'s status has no transition to a done status, only 'Start' to 'In Progress': Jira lists only the transitions the account may make, so move the issue in Jira, or let the account transition issues"), + ([], None, f"{key}'s status has no transition to a done status: Jira lists only the transitions the account may make, so move the issue in Jira, or let the account transition issues"), + (both, None, f"{key}'s status has more than one transition to a done status, 'Mark as done' to 'Done' and 'Close' to 'Closed': name the one to use{config}"), + (both, "Resolve", f"{key}'s status has no transition called 'Resolve' to a done status, only 'Mark as done' to 'Done' and 'Close' to 'Closed': correct `jira-finish-transition`, in ~/.claude-projects/do-epic/config.toml"), + ([start], "Close", f"{key}'s status has no transition to a done status, only 'Start' to 'In Progress': Jira lists only the transitions the account may make, so move the issue in Jira, or let the account transition issues"), ): - with self.subTest(workflow=workflow): + with self.subTest(workflow=workflow, named=named): self.jira.workflow = workflow # type: ignore[assignment] - self.assertEqual(store.finish(key), Failure(f"{reason}: move the issue in Jira, or change the workflow so that one move closes it")) + self.assertEqual(JiraEpic(EPIC, self.env_file, self.jira, to_markdown, to_adf, named).finish(key), Failure(reason)) self.assertEqual(self.jira.issues[0]["fields"]["status"], TO_DO) # type: ignore[index] + def test_finishes_by_the_transition_the_config_names_where_several_lead_to_a_done_status(self) -> None: + key = self.new_store().file("ABC-12", "Count the runs.", "", ()) + self.jira.workflow = [{"id": "31", "name": "Resolve", "to": DONE}, {"id": "41", "name": "Close", "to": {"name": "Closed", "statusCategory": {"key": "done"}}}] + self.assertIsNone(JiraEpic(EPIC, self.env_file, self.jira, to_markdown, to_adf, "Close").finish(key)) + self.assertEqual(self.jira.calls[-1], ("POST", f"{ISSUES}/{key}/transitions")) + self.assertEqual(self.jira.transitioned, ["41"]) + + def test_refuses_to_finish_a_sub_task_of_an_issue_that_is_no_child_of_the_epic_or_an_issue_without_a_parent(self) -> None: + store = self.new_store() + for key, parent in (("ABC-50", "ABC-60"), ("ABC-60", "ABC-61"), ("ABC-61", None)): + fields = {"summary": "Other.", "description": None, "labels": [], "assignee": None, "status": TO_DO, "parent": {"key": parent} if parent else None, "issuelinks": []} + self.jira.issues.append({"key": key, "fields": fields}) + for key in ("ABC-50", "ABC-61"): + with self.subTest(key=key): + self.assertEqual(store.finish(key), Failure(f"{key} is not one of the child issues of the epic ABC-12, so it cannot be finished")) + self.assertNotIn("POST", [method for method, _ in self.jira.calls]) + def test_a_finish_jira_refuses_says_so_and_that_the_issue_may_have_moved(self) -> None: store = self.new_store() key = store.file("ABC-12", "Count the runs.", "", ()) self.jira.answers[("POST", f"{ISSUES}/{key}/transitions")] = Failure("Jira answered 400: Resolution is required") - self.assertEqual(store.finish(key), Failure(f"cannot move {key} to done: Jira answered 400: Resolution is required; the issue may have moved all the same: read it in Jira before moving it again")) + self.assertEqual(store.finish(key), Failure(f"cannot move {key} to done: Jira answered 400: Resolution is required; unless Jira refused the request, {key} may be done: read it in Jira before moving it again")) def test_a_finish_whose_transitions_jira_cannot_give_or_gives_in_another_shape_fails(self) -> None: store = self.new_store() diff --git a/bin/do_epic/config.py b/bin/do_epic/config.py index 81da5cff..94459ab6 100644 --- a/bin/do_epic/config.py +++ b/bin/do_epic/config.py @@ -7,18 +7,20 @@ One pair per machine, the same for every epic (docs/decisions.md → `do-epic: d repoless-model = "claude-opus-5-5" clone-folder = "~/code" language = "Swedish" + jira-finish-transition = "Mark as done" - `jira-url` is the Jira site's address: https, a host, and no path. - `env-file` is the file of Jira credentials: a path that starts with / or ~/, outside every folder of `~/.claude-projects` and outside the clone folder, which hold git checkouts. `~/.claude-projects/.env` is fine. - `repoless-model` is the model that works an epic item with no repo: a model on the routing ladder, `model_routing/routing-ladder.json`. - `clone-folder` is the folder a missing repo is cloned into: a path that starts with / or ~/. `~/code` where left out. - `language` is the default language of Jira text, by its English name. English where left out. +- `jira-finish-transition` is the name Jira shows of the transition that moves a finished chunk's issue to done. It is needed only where an issue's status offers more than one transition to a done status, such as Resolve and Close. Left out, do-epic takes the one transition that leads to a done status. - `repo-rule.md` is prose that says how to tell an item's repo, and mustn't be blank.""" import dataclasses import pathlib import re -from project_config.settings import anywhere, CONFIG, DO_EPIC, ENV_FILE, LANGUAGE, language_fault, lies_in, parsed, PROJECTS, SITE +from project_config.settings import anywhere, CONFIG, DO_EPIC, ENV_FILE, JIRA_FINISH_TRANSITION, LANGUAGE, language_fault, lies_in, name_of, parsed, PROJECTS, SITE from failure import Failure from model_routing.ladder_file import read_ladder, SHIPPED @@ -28,7 +30,7 @@ JIRA_URL = "jira-url" REPOLESS_MODEL = "repoless-model" CLONE_FOLDER = "clone-folder" SETTINGS = (JIRA_URL, ENV_FILE, REPOLESS_MODEL) -OPTIONAL = (CLONE_FOLDER, LANGUAGE) +OPTIONAL = (CLONE_FOLDER, LANGUAGE, JIRA_FINISH_TRANSITION) LISTED = f"The settings are {', '.join(SETTINGS)}, and optionally {' and '.join(OPTIONAL)}." @@ -42,6 +44,8 @@ class DoEpicConfig: language: str repoless_model: str repo_rule: str + # The name of the transition that finishes an issue where its status offers several to a done status; None where the config names none. + finish_transition: str | None = None def load(home: pathlib.Path, ladder_file: pathlib.Path = SHIPPED) -> DoEpicConfig | Failure: @@ -63,6 +67,7 @@ def load(home: pathlib.Path, ladder_file: pathlib.Path = SHIPPED) -> DoEpicConfi clone_folder = anywhere(values.get(CLONE_FOLDER, "~/code"), home) env_file = anywhere(values.get(ENV_FILE), home) language = values.get(LANGUAGE, "English") + finish = values.get(JIRA_FINISH_TRANSITION) url, model = values.get(JIRA_URL), values.get(REPOLESS_MODEL) faults = [ *(f"`{name}` is missing" for name in SETTINGS if name not in values), @@ -72,6 +77,7 @@ def load(home: pathlib.Path, ladder_file: pathlib.Path = SHIPPED) -> DoEpicConfi *([f"`{ENV_FILE}` is {values[ENV_FILE]!r}, not a path that starts with / or ~/"] if ENV_FILE in values and env_file is None else []), *([f"`{ENV_FILE}` is {values[ENV_FILE]!r}, inside a folder of ~/{PROJECTS} or the clone folder, which hold git checkouts"] if env_file and lies_in(env_file, *config_folders, *([clone_folder] if clone_folder else [])) else []), *([f"`{LANGUAGE}` is {language!r}, {fault}"] if LANGUAGE in values and (fault := language_fault(language)) else []), + *([f"`{JIRA_FINISH_TRANSITION}` is {finish!r}, not the name Jira shows, such as \"Mark as done\""] if JIRA_FINISH_TRANSITION in values and not name_of(finish) else []), *([f"`{REPOLESS_MODEL}` is {model!r}, not a model on the routing ladder: {', '.join(models)}"] if REPOLESS_MODEL in values and model not in models else []), *([rule.reason] if isinstance(rule, Failure) else [f"`{REPO_RULE}` is blank"] if not rule.strip() else []), ] @@ -79,4 +85,4 @@ def load(home: pathlib.Path, ladder_file: pathlib.Path = SHIPPED) -> DoEpicConfi return Failure(f"{folder}: {'; '.join(faults)}. {LISTED}") # Without a fault, each value above is present and of the type asserted here. assert clone_folder and env_file and isinstance(url, str) and isinstance(model, str) and isinstance(language, str) and isinstance(rule, str) - return DoEpicConfig(folder, url, env_file, clone_folder, language, model, rule) + return DoEpicConfig(folder, url, env_file, clone_folder, language, model, rule, name_of(finish)) diff --git a/bin/do_epic/main.py b/bin/do_epic/main.py index ac961759..0679276f 100644 --- a/bin/do_epic/main.py +++ b/bin/do_epic/main.py @@ -53,7 +53,7 @@ Backend = typing.Callable[[DoEpicConfig, str], tuple[EpicStore, EpicRecord]] def jira_backend(config: DoEpicConfig, key: str) -> tuple[EpicStore, EpicRecord]: epic = Epic(config.jira_url, key) - return JiraEpic(epic, config.env_file), EpicRecord(EpicDescription(epic, config.env_file)) + return JiraEpic(epic, config.env_file, finish_by=config.finish_transition), EpicRecord(EpicDescription(epic, config.env_file)) @dataclasses.dataclass(frozen=True) @@ -223,10 +223,10 @@ def chunk_root(issue: EpicIssue, epic: EpicRun) -> tuple[str, bool] | Stop: def handed_on(key: str, epic: EpicRun) -> Stop: - """The stop of a do-epic whose chunk finished, once its issue is done in the tracker, so that no finished chunk starts again and what it blocks may start, and it has started each chunk that may start now. Its window closes as it exits.""" + """The stop of a do-epic whose chunk finished. It first moves the chunk's issue to done, so that no finished chunk starts again and what the issue blocks may start, then starts each chunk that may start now. Its window closes as it exits.""" moved = epic.store.finish(key) if isinstance(moved, Failure): - return Stop(1, f"the chunk finished, but its issue could not move to done: {moved.reason}") + return Stop(1, f"the chunk finished, but its issue could not move to done: {moved.reason}; once it is done in Jira, run `do-epic {epic.key}` to start the chunks it blocks") started = chunks_started(epic, key) if isinstance(started, Failure): return Stop(1, f"the chunk finished, but the next could not start: {started.reason}") diff --git a/bin/do_epic/test_do_epic.py b/bin/do_epic/test_do_epic.py index 2e0cf93a..d5447f2f 100644 --- a/bin/do_epic/test_do_epic.py +++ b/bin/do_epic/test_do_epic.py @@ -43,6 +43,16 @@ class ConfigTest(unittest.TestCase): assert isinstance(found, DoEpicConfig), found self.assertEqual((found.clone_folder, found.language), (pathlib.Path("/srv/repos"), "Brazilian Portuguese")) + def test_reads_the_transition_that_finishes_an_issue_and_has_none_where_the_config_names_none(self) -> None: + self.write() + found = load(self.home) + assert isinstance(found, DoEpicConfig), found + self.assertIsNone(found.finish_transition) + self.write(SETTINGS + 'jira-finish-transition = "Close Issue"\n') + found = load(self.home) + assert isinstance(found, DoEpicConfig), found + self.assertEqual(found.finish_transition, "Close Issue") + def test_refuses_while_the_config_is_missing(self) -> None: self.write(None) self.assertIn(f"cannot read {self.folder / 'config.toml'}", self.failure()) @@ -80,6 +90,7 @@ class ConfigTest(unittest.TestCase): ('env-file = "jira.env"', "env-file"), ('clone-folder = "code"', "clone-folder"), ('language = "sv_SE"', "language"), + ('jira-finish-transition = " "', "jira-finish-transition"), ('repoless-model = "opus"', "repoless-model"), ('repoless-model = "claude-opsu-5-5"', "repoless-model"), ): diff --git a/bin/do_epic/test_main.py b/bin/do_epic/test_main.py index ba8e9dbe..7cf34942 100644 --- a/bin/do_epic/test_main.py +++ b/bin/do_epic/test_main.py @@ -299,7 +299,7 @@ class AChunksRun(DoEpicTest): fake = FakeEffects(streams=[self.worker()], claude=[judged("finished")], git=UNREAD) code, out, err = self.run_main(["--chunk", "ABC-21", "ABC-12"], fake, MODELS) self.assertEqual(code, 1) - self.assertIn("the chunk finished, but its issue could not move to done: ABC-21's status has no transition to a done status\n", err) + self.assertIn("the chunk finished, but its issue could not move to done: ABC-21's status has no transition to a done status; once it is done in Jira, run `do-epic ABC-12` to start the chunks it blocks\n", err) self.assertNotIn("started", out) def test_a_finished_chunk_says_why_the_next_could_not_start(self) -> None: From be67bc66bfdd8ecced9e8183a3f28a0975d3f2fd Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 18 Nov 2026 23:38:02 +0100 Subject: [PATCH 03/26] =?UTF-8?q?Answer=20prose=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=206=20=F0=9F=9F=A1=20(0=20misread);=20reword=20th?= =?UTF-8?q?e=20docstrings=20and=20messages,=20in=20the=20commit=20before?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit From e22711acc21b1dfbb6ee883c233a279800ef27a3 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 18 Nov 2026 23:42:14 +0100 Subject: [PATCH 04/26] Declare assertIsNone on the backend contract --- bin/do_epic/backend/contract.py | 1 + 1 file changed, 1 insertion(+) diff --git a/bin/do_epic/backend/contract.py b/bin/do_epic/backend/contract.py index feaeaad6..d9da553a 100644 --- a/bin/do_epic/backend/contract.py +++ b/bin/do_epic/backend/contract.py @@ -9,6 +9,7 @@ from failure import Failure class EpicStoreContract: assertEqual: typing.Callable[..., None] assertIsInstance: typing.Callable[..., None] + assertIsNone: typing.Callable[..., None] subTest: typing.Callable[..., typing.ContextManager[None]] def new_store(self) -> EpicStore: From 382ac99c4184b04b96de7be420ae85ef32fcb026 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 18 Nov 2026 23:52:15 +0100 Subject: [PATCH 05/26] Re-score item 415 at L 4 and S 6 after reading the code --- docs/reading-cost.md | 17 +++++++++++++++++ todo.md | 2 +- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/docs/reading-cost.md b/docs/reading-cost.md index 2438e973..18b6b9c3 100644 --- a/docs/reading-cost.md +++ b/docs/reading-cost.md @@ -2910,3 +2910,20 @@ Read most (opens and searches): - `docs/decisions.md` 2 - `bin/agent_cycle/tmux.py` 1 - `bin/loop-claude` 1 + +## Reading cost, chunk 43ac6d329242, finished 2026-11-18T22:50:16Z + +104341 new input tokens before the first commit. + +Read most (opens and searches): + +- `bin/agent_cycle/judge.py` 3 +- `rules/todo-items.md` 3 +- `bin/do_epic/main.py` 2 +- `bin/loop_claude/cycle/prompts.py` 2 +- `bin/agent_cycle/run.py` 1 +- `bin/agent_cycle/worker_prompts.py` 1 +- `bin/do_epic/chunk_prompt.py` 1 +- `bin/do_epic/epic_record.py` 1 +- `bin/loop_claude/project/premises.py` 1 +- `bin/loop_claude/project/records.py` 1 diff --git a/todo.md b/todo.md index 647fd824..dd54de6e 100644 --- a/todo.md +++ b/todo.md @@ -14,7 +14,7 @@ |---|---|---|---|---|---|---|---|---|---|---|---| | 441 | 0.12.0 | | | **Move an epic's issue to done in Jira when its chunk finishes, so no finished chunk starts again and what it blocks starts.** | 2 | 2 | 2 | 4 | 3 | 1 by 6 | 2.3 | | 416 | 0.12.0 | | | **Finish an epic's repo item with a bullet under its repo's `CHANGELOG.md` → `## Unreleased`, or with none where the repo's plan is in Jira.** | 1 | 1 | 1 | 1 | 2 | 1 by 5 | 2.1 | -| 415 | 0.12.0 | | | **Finish an epic: run release-review passes on each repo it changed, work what they file, have the human confirm each goal, post a summary comment, and close the epic in Jira last.** | 3 | 2 | 3 | 6 | 5 | 1 by 5 | 1.2 | +| 415 | 0.12.0 | | | **Finish an epic: run release-review passes on each repo it changed, work what they file, have the human confirm each goal, post a summary comment, and close the epic in Jira last.** | 4 | 2 | 3 | 7 | 6 | 1 by 5 | 0.8 | | 418 | 0.12.0 | 415 | | **Describe do-epic in `README.md`'s tools and setup, with its machine settings and `repo-rule.md`.** | 1 | 2 | 1 | 2 | 2 | 1 by 5 | 2.1 | | 420 | 0.12.0 | | | **End a worker that printed its final result and lingers, by killing the background shells it left, after a few minutes, and print each kill with its evidence on loop-claude's terminal.** | 2 | 2 | 2 | 4 | 3 | 1.5 by 6 | 2.0 | | 411 | 0.12.0 | | | **Park a chunk whose PR waits on a long gate, keeping its worktree, PR and session in a state file that survives a reboot, and resume its session when the gate passes or a reviewer comments.** | 3 | 2 | 3 | 6 | 5 | 1 by 5 | 1.2 | From 001b3315bfc3439e8bf2d9c1ed00be6625bb820f Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 18 Nov 2026 23:53:03 +0100 Subject: [PATCH 06/26] Test the backend's wiring, its failing reads and malformed transition answers --- bin/do_epic/backend/test_jira.py | 17 +++++++++++++++-- bin/do_epic/test_main.py | 10 ++++++++++ 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/bin/do_epic/backend/test_jira.py b/bin/do_epic/backend/test_jira.py index 1ecc75a5..8ef88099 100644 --- a/bin/do_epic/backend/test_jira.py +++ b/bin/do_epic/backend/test_jira.py @@ -188,6 +188,7 @@ class Jira(Case): both = [{"id": "31", "name": "Mark as done", "to": DONE}, {"id": "41", "name": "Close", "to": closed}] config = " in `jira-finish-transition`, in ~/.claude-projects/do-epic/config.toml" for workflow, named, reason in ( + ([start, {"id": "12", "name": "Pause", "to": {"name": "On Hold", "statusCategory": {"key": "indeterminate"}}}], None, f"{key}'s status has no transition to a done status, only 'Start' to 'In Progress' and 'Pause' to 'On Hold': Jira lists only the transitions the account may make, so move the issue in Jira, or let the account transition issues"), ([start], None, f"{key}'s status has no transition to a done status, only 'Start' to 'In Progress': Jira lists only the transitions the account may make, so move the issue in Jira, or let the account transition issues"), ([], None, f"{key}'s status has no transition to a done status: Jira lists only the transitions the account may make, so move the issue in Jira, or let the account transition issues"), (both, None, f"{key}'s status has more than one transition to a done status, 'Mark as done' to 'Done' and 'Close' to 'Closed': name the one to use{config}"), @@ -228,8 +229,20 @@ class Jira(Case): url = ("GET", f"{ISSUES}/{key}/transitions") self.jira.answers[url] = Failure("Jira answered 503") self.assertEqual(store.finish(key), Failure(f"cannot read {key}'s transitions: Jira answered 503")) - self.jira.answers[url] = {"transitions": [{"id": 31}]} - self.assertEqual(store.finish(key), Failure(f"Jira answered {key}'s transitions in a shape other than the one it documents")) + for answer in ({"transitions": [{"id": 31}]}, ["Mark as done"], {"transitions": 5}): + with self.subTest(answer=answer): + self.jira.answers[url] = answer + self.assertEqual(store.finish(key), Failure(f"Jira answered {key}'s transitions in a shape other than the one it documents")) + + def test_a_finish_whose_issue_or_parent_jira_cannot_read_says_which(self) -> None: + store = self.new_store() + child = store.file("ABC-12", "Count the runs.", "", ()) + task = store.file(child, "Count them in the api.", "", ()) + self.jira.answers[("GET", f"{ISSUES}/{task}?fields=parent,status")] = Failure("Jira answered 503") + self.assertEqual(store.finish(task), Failure(f"cannot read {task} to finish it: Jira answered 503")) + del self.jira.answers[("GET", f"{ISSUES}/{task}?fields=parent,status")] + self.jira.answers[("GET", f"{ISSUES}/{child}?fields=parent")] = Failure("Jira answered 503") + self.assertEqual(store.finish(task), Failure(f"cannot read {child} to finish its sub-task: Jira answered 503")) def test_reads_the_sub_tasks_of_more_children_than_one_search_names(self) -> None: store = self.new_store() diff --git a/bin/do_epic/test_main.py b/bin/do_epic/test_main.py index 7cf34942..7524732c 100644 --- a/bin/do_epic/test_main.py +++ b/bin/do_epic/test_main.py @@ -14,7 +14,9 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from do_epic import chunk_prompt, main from project_config.test_project_config import configured from do_epic.backend.protocol import EpicIssue +from do_epic.config import DoEpicConfig from do_epic.epic_record import EpicRecord +from project_config.settings import Epic from agent_cycle import escalation_mark, judge, tmux from failure import Failure from loop_claude.test_loop_claude import FakeEffects, judged, Worker @@ -61,6 +63,14 @@ class DoEpicTest(unittest.TestCase): return code, out.getvalue(), err.getvalue() +class TheJiraBackend(unittest.TestCase): + def test_reads_the_epic_with_the_credentials_and_the_finish_transition_the_config_names(self) -> None: + config = DoEpicConfig(pathlib.Path("/c"), "https://acme.atlassian.net", pathlib.Path("/h/jira.env"), pathlib.Path("/h/code"), "English", "claude-opus-5-5", "rule", "Close Issue") + store, record = main.jira_backend(config, "ABC-12") + self.assertEqual((store.epic, store.env_file, store.finish_by), (Epic("https://acme.atlassian.net", "ABC-12"), pathlib.Path("/h/jira.env"), "Close Issue")) # type: ignore[attr-defined] + self.assertEqual((record.description.epic, record.description.env_file), (store.epic, store.env_file)) # type: ignore[attr-defined] + + class TheLauncher(unittest.TestCase): def test_the_repo_ships_a_do_epic_that_prints_its_help(self) -> None: launcher = pathlib.Path(__file__).resolve().parents[1] / "do-epic" From fdb942472d0cdfe3758c32f052ddca77bf0364ee Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 18 Nov 2026 23:59:53 +0100 Subject: [PATCH 07/26] Finish an epic: a finishing chunk files each repo's release review, has the human confirm each goal, and closes the epic with its summary --- README.md | 2 +- bin/do_epic/backend/contract.py | 8 + bin/do_epic/backend/fake.py | 15 +- bin/do_epic/backend/jira.py | 41 ++++- bin/do_epic/backend/protocol.py | 7 + bin/do_epic/backend/test_jira.py | 57 ++++++- bin/do_epic/config.py | 15 +- bin/do_epic/findings.py | 29 ++-- bin/do_epic/finish.py | 88 +++++++++++ bin/do_epic/main.py | 71 ++++++--- bin/do_epic/repo_pick.py | 2 + bin/do_epic/scheduler.py | 14 +- bin/do_epic/test_do_epic.py | 9 ++ bin/do_epic/test_findings.py | 7 + bin/do_epic/test_finish.py | 174 ++++++++++++++++++++++ bin/do_epic/test_main.py | 2 +- bin/do_epic/test_scheduler.py | 4 +- bin/plan_store/jira_epic.py | 24 ++- bin/release_plan/release_standing.py | 4 +- bin/release_plan/test_release_standing.py | 4 + 20 files changed, 514 insertions(+), 63 deletions(-) create mode 100644 bin/do_epic/finish.py create mode 100644 bin/do_epic/test_finish.py diff --git a/README.md b/README.md index d0205e4c..89c8ed21 100644 --- a/README.md +++ b/README.md @@ -216,7 +216,7 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a - `branch_chunks/` cuts a default branch into chunks and finds, for each, the items it shipped and the later chunks that fixed its code, for `score_outcomes` and `routing_figures`. It imports `reading_cost`'s record path. - `command_lines/` reads a shell command: its simple commands, and a docker call's subcommand and memory limits, for `command_patterns`, `reading_cost`, `routing_figures`, `rule_hook` and `run_heavy`. - `deploy_release` imports `release_plan`'s `release_standing`. -- `do_epic/` holds `do-epic`, the tool that drives one Jira epic. `main.py` starts the epic's chunks and runs one chunk's cycles in its window, through `agent_cycle`. `scheduler.py` says which issues run now: as many as the epic's cap and each repo's `parallel-chunks` allow, and none in a repo where loop-claude runs chunks. Beside it, `chunk_prompt.py` words what a chunk's worker reads. Through `findings.py` that worker files a finding as an issue of the epic, with `--file`, and appends a decision to its description, with `--record-decision`. `config.py` reads its machine-wide settings, importing `project_config`'s settings and `model_routing`'s ladder file, and `epic_record.py` reads and writes an epic's description by section, language line and cap line, through `record_store`'s `EpicDescription`. `repos.py` finds a repo's checkout and project config by its name, and clones a missing checkout from the host and owner of the epic's other repos, through `forge`'s `url_beside`. `repo_pick.py` asks claude, by `repo-rule.md`, where an epic item is worked, and records the answer as a label on the issue. `split.py` has claude predict from the code which repos an item changes, and files a sub-task per repo under it where there are several. `ranking.py` orders an epic's items by score over one chain of goals, the epic's, then code health, then the item's repo's, through `plan`'s ranking, and re-ranks the tracker's backlog to that order through `backend/`. `backend/` reads, files and ranks the epic's issues, adds the labels `repo_pick.py` and `split.py` record, and posts comments. +- `do_epic/` holds `do-epic`, the tool that drives one Jira epic. `main.py` starts the epic's chunks and runs one chunk's cycles in its window, through `agent_cycle`. `scheduler.py` says which issues run now: as many as the epic's cap and each repo's `parallel-chunks` allow, and none in a repo where loop-claude runs chunks. Beside it, `chunk_prompt.py` words what a chunk's worker reads. Through `findings.py` that worker files a finding as an issue of the epic, with `--file`, and appends a decision to its description, with `--record-decision`. `finish.py` ends an epic that holds no open issue: its finishing chunk files a release review of each repo the epic changed, has the human confirm each goal, and with `--close-epic` posts the summary on the epic and closes it. `config.py` reads its machine-wide settings, importing `project_config`'s settings and `model_routing`'s ladder file, and `epic_record.py` reads and writes an epic's description by section, language line and cap line, through `record_store`'s `EpicDescription`. `repos.py` finds a repo's checkout and project config by its name, and clones a missing checkout from the host and owner of the epic's other repos, through `forge`'s `url_beside`. `repo_pick.py` asks claude, by `repo-rule.md`, where an epic item is worked, and records the answer as a label on the issue. `split.py` has claude predict from the code which repos an item changes, and files a sub-task per repo under it where there are several. `ranking.py` orders an epic's items by score over one chain of goals, the epic's, then code health, then the item's repo's, through `plan`'s ranking, and re-ranks the tracker's backlog to that order through `backend/`. `backend/` reads, files and ranks the epic's issues, adds the labels `repo_pick.py` and `split.py` record, posts comments, and closes the epic. - `forge/` tells a GitHub origin from a Gitea one, names a repo beside an origin's and runs that forge's CLI (`commands.py`), and finds a pull request and waits for its checks (`pulls.py`), for `chunk_preflight`, `chunk_pr`, `deploy_release`, `do_epic` and `larv_review`. - `git_cli/` runs git for every tool (`git_repo.py`), and reads the git calls in a shell command (`git_command.py`). - `judge_replay` imports `agent_cycle`'s judge and verdicts, and `loop_claude`'s premises, records and `ANSWER_DESTINATIONS`. diff --git a/bin/do_epic/backend/contract.py b/bin/do_epic/backend/contract.py index 7101e63c..4b1c74b3 100644 --- a/bin/do_epic/backend/contract.py +++ b/bin/do_epic/backend/contract.py @@ -140,6 +140,14 @@ class EpicStoreContract: self.assertIsInstance(store.comment("ZZZ-1", "Hello."), Failure) self.assertEqual([self.comments_on(store, key) for key in (child, task)], [[], []]) + def test_closes_the_epic_once_its_summary_is_posted_and_refuses_a_blank_one(self) -> None: + store = self.new_store() + self.assertEqual(store.closed(), False) + self.assertIsInstance(store.close(" \n"), Failure) + self.assertEqual((store.closed(), self.comments_on(store, "ABC-12")), (False, [])) + self.assertEqual(store.close("## Shipped\n\nThe import.\n"), None) + self.assertEqual((store.closed(), self.comments_on(store, "ABC-12")), (True, ["## Shipped\n\nThe import."])) + def test_reads_an_issue_without_scores_or_blockers_as_one_with_none(self) -> None: store = self.new_store() key = self.filed(store, store.epic_key, "Count the runs.") diff --git a/bin/do_epic/backend/fake.py b/bin/do_epic/backend/fake.py index c6d766bb..ea404f51 100644 --- a/bin/do_epic/backend/fake.py +++ b/bin/do_epic/backend/fake.py @@ -7,11 +7,12 @@ from failure import Failure @dataclasses.dataclass class MemoryEpic: - """An epic whose issues rank in the order filed, until one is ranked. Where fails is set, every read, filing, label, comment and rank fails with it as the reason. comments holds each issue's comments, by key.""" + """An epic whose issues rank in the order filed, until one is ranked. Where fails is set, every read, filing, label, comment, rank and closing fails with it as the reason. comments holds each issue's comments, and the epic's, by key. done says whether the epic is closed.""" epic_key: str issues: list[EpicIssue] = dataclasses.field(default_factory=list) comments: dict[str, list[str]] = dataclasses.field(default_factory=dict) fails: str | None = None + done: bool = False def read(self) -> list[EpicIssue] | Failure: if self.fails: @@ -60,6 +61,18 @@ class MemoryEpic: self.comments.setdefault(key, []).append(text.strip()) return None + def closed(self) -> bool | Failure: + return Failure(self.fails) if self.fails else self.done + + def close(self, summary: str) -> None | Failure: + if self.fails: + return Failure(self.fails) + if refused := no_words(summary): + return refused + self.comments.setdefault(self.epic_key, []).append(summary.strip()) + self.done = True + return None + def change(self, key: str, **fields: object) -> None: """Changes the issue named key as a person would in the tracker, such as assignee="Ada Lovelace".""" self.issues = [dataclasses.replace(issue, **fields) if issue.key == key else issue for issue in self.issues] # type: ignore[arg-type] diff --git a/bin/do_epic/backend/jira.py b/bin/do_epic/backend/jira.py index 43813796..3cfdaa31 100644 --- a/bin/do_epic/backend/jira.py +++ b/bin/do_epic/backend/jira.py @@ -5,8 +5,8 @@ import typing from adf_codec.convert import adfs_to_markdown, markdown_to_adf, Refused from atlassian.client import basic_auth, Http, jira_json, ToAdf, ToMarkdown -from plan_store.jira_epic import blocked_by_links, FILED_BY, ISSUE_KEY, ISSUE_TYPE, project_of, PROPERTY, rank_refusal, scores, searched -from project_config.settings import Epic +from plan_store.jira_epic import blocked_by_links, FILED_BY, finishing_transition, ISSUE_KEY, ISSUE_TYPE, move_refusal, project_of, PROPERTY, rank_refusal, scores, searched +from project_config.settings import Epic, Finish, JIRA_FINISH_STATUS, JIRA_FINISH_TRANSITION from do_epic.backend.protocol import EpicIssue, no_child, no_parent, no_words, unfit, unfit_label from failure import Failure @@ -25,12 +25,13 @@ class Found: @dataclasses.dataclass(frozen=True) class JiraEpic: - """The issues of a Jira epic, read and filed with the credentials env_file holds.""" + """The issues of a Jira epic, read and filed with the credentials env_file holds. finish says how the epic itself closes; None where the machine's settings don't say.""" epic: Epic env_file: pathlib.Path http: Http = jira_json to_markdown: ToMarkdown = adfs_to_markdown to_adf: ToAdf = markdown_to_adf + finish: Finish | None = None @property def epic_key(self) -> str: @@ -116,6 +117,40 @@ class JiraEpic: posted = self.http("POST", f"{self.epic.site}/rest/api/3/issue/{key}/comment", authorization, {"body": body}) return Failure(f"cannot comment on {key}: {posted.reason}") if isinstance(posted, Failure) else None + def closed(self) -> bool | Failure: + authorization = basic_auth(self.env_file) + if isinstance(authorization, Failure): + return authorization + answered = self.http("GET", f"{self.epic.site}/rest/api/3/issue/{self.epic_key}?fields=status", authorization, None) + if isinstance(answered, Failure): + return Failure(f"cannot read {self.epic_key}'s status: {answered.reason}") + try: + category = answered["fields"]["status"]["statusCategory"]["key"] # type: ignore[index] + except (KeyError, TypeError) as failure: + return Failure(f"{self.epic_key}'s status is not in the shape Jira Cloud's REST API version 3 documents: {failure!r}") + return bool(category == "done") + + def close(self, summary: str) -> None | Failure: + if self.finish is None: + return Failure(f"do-epic's settings name no transition to close an epic by: set `{JIRA_FINISH_TRANSITION}` and `{JIRA_FINISH_STATUS}`, as config.py's docstring shows") + authorization = basic_auth(self.env_file) + if isinstance(authorization, Failure): + return authorization + if refused := no_words(summary): + return refused + body = self.to_adf(summary) + if isinstance(body, Failure): + return Failure(f"cannot convert the summary to a Jira comment: {body.reason}") + # Read before the comment is posted, so that an epic that cannot move gets no summary, and a second try posts no second one. + transition = finishing_transition(self.epic.site, self.epic_key, self.finish, authorization, self.http) + if isinstance(transition, Failure): + return transition + posted = self.http("POST", f"{self.epic.site}/rest/api/3/issue/{self.epic_key}/comment", authorization, {"body": body}) + if isinstance(posted, Failure): + return Failure(f"cannot comment on {self.epic_key}: {posted.reason}") + refused_move = move_refusal(self.epic.site, self.epic_key, transition, self.finish, authorization, self.http) + return Failure(f"posted the summary on {self.epic_key}, but {refused_move}; close the epic in Jira rather than posting the summary again") if refused_move else None + def not_a_parent(self, parent: str, authorization: str) -> Failure | None: """Why nothing can be filed under parent; None where it is the epic or one of its child issues.""" if parent == self.epic_key: diff --git a/bin/do_epic/backend/protocol.py b/bin/do_epic/backend/protocol.py index b48b314c..ab50bdba 100644 --- a/bin/do_epic/backend/protocol.py +++ b/bin/do_epic/backend/protocol.py @@ -64,6 +64,13 @@ class EpicStore(typing.Protocol): """Posts text, markdown, as a comment on the epic's child issue named key, for the people who work the epic to read. A sub-task, an issue outside the epic, or an empty or blank text is refused.""" + def closed(self) -> bool | Failure: + """Whether the epic itself is in a status the tracker counts as done.""" + + def close(self, summary: str) -> None | Failure: + """Posts summary, markdown, as a comment on the epic, then moves the epic to a status the tracker counts as done. A blank summary is refused, and so is an epic the tracker cannot move so, before anything is posted. Where the move fails after the comment is posted, the Failure says so.""" + + def unfit(summary: str, labels: tuple[str, ...]) -> Failure | None: """Why no tracker can file an issue with this summary and these labels; None where a tracker can file it.""" if not summary.strip() or "\n" in summary: diff --git a/bin/do_epic/backend/test_jira.py b/bin/do_epic/backend/test_jira.py index 3d3c7cac..9253a4b4 100644 --- a/bin/do_epic/backend/test_jira.py +++ b/bin/do_epic/backend/test_jira.py @@ -9,7 +9,7 @@ import unittest.mock sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2])) -from project_config.settings import Epic +from project_config.settings import Epic, Finish from do_epic.backend.contract import EpicStoreContract from failure import Failure from plan_store import jira_epic @@ -25,6 +25,10 @@ SEARCH = f"{SITE}/rest/api/3/search/jql" ISSUES = f"{SITE}/rest/api/3/issue" RANK = f"{SITE}/rest/agile/1.0/issue/rank" TO_DO = {"name": "To Do", "statusCategory": {"key": "new"}} +DONE = {"name": "Done", "statusCategory": {"key": "done"}} +TRANSITIONS = f"{ISSUES}/ABC-12/transitions" +EPIC_COMMENT = f"{ISSUES}/ABC-12/comment" +EPIC_STATUS = f"{ISSUES}/ABC-12?fields=status" TYPES = {"issueTypes": [{"id": "10001", "name": "Task", "subtask": False}, {"id": "10003", "name": "Subtask", "subtask": True}]} @@ -44,6 +48,8 @@ class FakeJira: answers: dict[tuple[str, str], object] = dataclasses.field(default_factory=dict) calls: list[tuple[str, str]] = dataclasses.field(default_factory=list) comments: dict[str, list[object]] = dataclasses.field(default_factory=dict) + # The epic's own status, which the transition "Mark as done" moves to DONE. + epic_status: dict[str, object] = dataclasses.field(default_factory=lambda: dict(TO_DO)) def __call__(self, method: str, url: str, authorization: str, body: object) -> object: self.calls.append((method, url)) @@ -53,6 +59,18 @@ class FakeJira: return self.answers[method, url] if method == "GET" and url == EPIC_URL: return {"key": "ABC-12"} + if method == "GET" and url == EPIC_STATUS: + return {"key": "ABC-12", "fields": {"status": self.epic_status}} + if method == "GET" and url == TRANSITIONS: + return {"transitions": [] if self.epic_status == DONE else [{"id": "31", "name": "Mark as done", "to": DONE}, {"id": "21", "name": "Start", "to": {"name": "In Progress", "statusCategory": {"key": "indeterminate"}}}]} + if method == "POST" and url == TRANSITIONS: + assert body == {"transition": {"id": "31"}}, body + self.epic_status = DONE + return None + if method == "POST" and url == EPIC_COMMENT: + assert isinstance(body, dict) + self.comments.setdefault("ABC-12", []).append(body["body"]) + return {"id": "1"} if method == "GET" and url == ISSUE_TYPES: return TYPES if method == "POST" and url == SEARCH: @@ -127,7 +145,7 @@ class Case(unittest.TestCase): self.jira = FakeJira() def new_store(self) -> JiraEpic: - return JiraEpic(EPIC, self.env_file, self.jira, to_markdown, to_adf) + return JiraEpic(EPIC, self.env_file, self.jira, to_markdown, to_adf, Finish("Mark as done", "Done")) class JiraEpicContract(Case, EpicStoreContract): @@ -153,6 +171,41 @@ class JiraEpicContract(Case, EpicStoreContract): class Jira(Case): + def test_closes_the_epic_by_the_transition_the_settings_name_after_the_summary(self) -> None: + self.assertEqual(self.new_store().close("Shipped."), None) + self.assertEqual(self.jira.calls[-3:], [("GET", TRANSITIONS), ("POST", EPIC_COMMENT), ("POST", TRANSITIONS)]) + + def test_posts_no_summary_on_an_epic_it_cannot_close(self) -> None: + unnamed = JiraEpic(EPIC, self.env_file, self.jira, to_markdown, to_adf) + wrong_status = JiraEpic(EPIC, self.env_file, self.jira, to_markdown, to_adf, Finish("Start", "Done")) + no_such = JiraEpic(EPIC, self.env_file, self.jira, to_markdown, to_adf, Finish("Close", "Done")) + unconverted = JiraEpic(EPIC, self.env_file, self.jira, to_markdown, lambda markdown: Failure("adf-codec refused it"), Finish("Mark as done", "Done")) + for store, reason in ( + (unnamed, "do-epic's settings name no transition to close an epic by: set `jira-finish-transition` and `jira-finish-status`, as config.py's docstring shows"), + (wrong_status, "ABC-12's transition 'Start' leads to the status 'In Progress', not to 'Done', which `jira-finish-status` names"), + (unconverted, "cannot convert the summary to a Jira comment: adf-codec refused it"), + ): + self.assertEqual(store.close("Shipped."), Failure(reason)) + refused = no_such.close("Shipped.") + assert isinstance(refused, Failure) + self.assertIn("ABC-12 has no transition 'Close' from its status", refused.reason) + self.jira.answers[("GET", TRANSITIONS)] = Failure("Jira answered 503") + self.assertEqual(self.new_store().close("Shipped."), Failure("cannot read ABC-12's transitions: Jira answered 503")) + self.assertEqual((self.jira.comments, self.jira.epic_status), ({}, TO_DO)) + + def test_says_what_was_posted_where_the_comment_or_the_move_fails(self) -> None: + self.jira.answers[("POST", EPIC_COMMENT)] = Failure("Jira answered 503") + self.assertEqual(self.new_store().close("Shipped."), Failure("cannot comment on ABC-12: Jira answered 503")) + self.assertEqual(self.jira.epic_status, TO_DO) + del self.jira.answers[("POST", EPIC_COMMENT)] + self.jira.answers[("POST", TRANSITIONS)] = Failure("Jira answered 503") + self.assertEqual(self.new_store().close("Shipped."), Failure("posted the summary on ABC-12, but cannot move ABC-12 by 'Mark as done': Jira answered 503; close the epic in Jira rather than posting the summary again")) + + def test_says_why_the_epics_status_cannot_be_read(self) -> None: + for answer, reason in ((Failure("Jira answered 503"), "cannot read ABC-12's status: Jira answered 503"), ({"fields": {}}, "ABC-12's status is not in the shape Jira Cloud's REST API version 3 documents: KeyError('status')"), (["ABC-12"], "ABC-12's status is not in the shape Jira Cloud's REST API version 3 documents: TypeError('list indices must be integers or slices, not str')")): + self.jira.answers[("GET", EPIC_STATUS)] = answer + self.assertEqual(self.new_store().closed(), Failure(reason)) + def test_reads_the_sub_tasks_of_more_children_than_one_search_names(self) -> None: store = self.new_store() children = [store.file("ABC-12", f"Item {n}.", "", ()) for n in range(60)] diff --git a/bin/do_epic/config.py b/bin/do_epic/config.py index 81da5cff..53b77fbb 100644 --- a/bin/do_epic/config.py +++ b/bin/do_epic/config.py @@ -13,13 +13,15 @@ One pair per machine, the same for every epic (docs/decisions.md → `do-epic: d - `repoless-model` is the model that works an epic item with no repo: a model on the routing ladder, `model_routing/routing-ladder.json`. - `clone-folder` is the folder a missing repo is cloned into: a path that starts with / or ~/. `~/code` where left out. - `language` is the default language of Jira text, by its English name. English where left out. +- `jira-finish-transition` and `jira-finish-status` say how a finished epic closes, as a project's config says it of a plan item: the name of the workflow transition, such as "Mark as done", and of the status it leads to, such as "Done". Set both or neither; without them do-epic closes no epic. - `repo-rule.md` is prose that says how to tell an item's repo, and mustn't be blank.""" import dataclasses import pathlib import re -from project_config.settings import anywhere, CONFIG, DO_EPIC, ENV_FILE, LANGUAGE, language_fault, lies_in, parsed, PROJECTS, SITE +from project_config.settings import anywhere, CONFIG, DO_EPIC, ENV_FILE, Finish, JIRA_FINISH, LANGUAGE, language_fault, lies_in, name_of, parsed, PROJECTS, SITE from failure import Failure +from text_files.markdown_text import listed from model_routing.ladder_file import read_ladder, SHIPPED REPO_RULE = "repo-rule.md" @@ -28,8 +30,8 @@ JIRA_URL = "jira-url" REPOLESS_MODEL = "repoless-model" CLONE_FOLDER = "clone-folder" SETTINGS = (JIRA_URL, ENV_FILE, REPOLESS_MODEL) -OPTIONAL = (CLONE_FOLDER, LANGUAGE) -LISTED = f"The settings are {', '.join(SETTINGS)}, and optionally {' and '.join(OPTIONAL)}." +OPTIONAL = (CLONE_FOLDER, LANGUAGE, *JIRA_FINISH) +LISTED = f"The settings are {', '.join(SETTINGS)}, and optionally {listed(OPTIONAL, 'and')}." @dataclasses.dataclass(frozen=True) @@ -42,6 +44,8 @@ class DoEpicConfig: language: str repoless_model: str repo_rule: str + # How a finished epic closes; None where the config doesn't say. + finish: Finish | None = None def load(home: pathlib.Path, ladder_file: pathlib.Path = SHIPPED) -> DoEpicConfig | Failure: @@ -73,10 +77,13 @@ def load(home: pathlib.Path, ladder_file: pathlib.Path = SHIPPED) -> DoEpicConfi *([f"`{ENV_FILE}` is {values[ENV_FILE]!r}, inside a folder of ~/{PROJECTS} or the clone folder, which hold git checkouts"] if env_file and lies_in(env_file, *config_folders, *([clone_folder] if clone_folder else [])) else []), *([f"`{LANGUAGE}` is {language!r}, {fault}"] if LANGUAGE in values and (fault := language_fault(language)) else []), *([f"`{REPOLESS_MODEL}` is {model!r}, not a model on the routing ladder: {', '.join(models)}"] if REPOLESS_MODEL in values and model not in models else []), + *(f"`{name}` is {values[name]!r}, not the name Jira shows, such as \"{example}\"" for name, example in zip(JIRA_FINISH, ("Mark as done", "Done")) if name in values and not name_of(values[name])), + *(f"`{name}` is set, so `{other}` must be too" for name, other in (JIRA_FINISH, JIRA_FINISH[::-1]) if name in values and other not in values), *([rule.reason] if isinstance(rule, Failure) else [f"`{REPO_RULE}` is blank"] if not rule.strip() else []), ] if faults: return Failure(f"{folder}: {'; '.join(faults)}. {LISTED}") # Without a fault, each value above is present and of the type asserted here. assert clone_folder and env_file and isinstance(url, str) and isinstance(model, str) and isinstance(language, str) and isinstance(rule, str) - return DoEpicConfig(folder, url, env_file, clone_folder, language, model, rule) + finish = [name for setting in JIRA_FINISH if (name := name_of(values.get(setting)))] + return DoEpicConfig(folder, url, env_file, clone_folder, language, model, rule, Finish(*finish) if len(finish) == 2 else None) diff --git a/bin/do_epic/findings.py b/bin/do_epic/findings.py index 9985adc9..d2eefb9d 100644 --- a/bin/do_epic/findings.py +++ b/bin/do_epic/findings.py @@ -6,7 +6,7 @@ import fcntl import pathlib import typing -from do_epic.repo_pick import CLAUDE_LABEL, HUMAN_LABEL, of_label, REPO_PREFIX +from do_epic.repo_pick import CLAUDE_LABEL, HUMAN_LABEL, of_label, REPO_PREFIX, REVIEW_LABEL from do_epic.epic_record import EpicRecord from do_epic.backend.protocol import EpicStore from failure import Failure @@ -20,7 +20,7 @@ RECORD_DECISION = "--record-decision" LABELS = f"`{REPO_PREFIX}` for the repo that works it, `{CLAUDE_LABEL}` for work of Claude's that changes no repo, or `{HUMAN_LABEL}` for a task of the human's" # Under the epic's folder, the file a do-epic holds locked while it appends a decision. DECISIONS_LOCK = "decisions.lock" -USAGE = f"""do-epic {FILE} [{LABEL}