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/30] 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/30] =?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/30] =?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/30] 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 001b3315bfc3439e8bf2d9c1ed00be6625bb820f Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 18 Nov 2026 23:53:03 +0100 Subject: [PATCH 05/30] 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 7d458159cccb341b972004b75123fbe3073a0676 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 19 Nov 2026 00:08:28 +0100 Subject: [PATCH 06/30] =?UTF-8?q?Answer=20product-owner=20round=202:=201?= =?UTF-8?q?=20=F0=9F=94=B4,=201=20=F0=9F=9F=A1=20(0=20misread);=20take=20a?= =?UTF-8?q?=20workflow's=20one=20done=20transition=20whatever=20the=20conf?= =?UTF-8?q?ig=20names,=20move=20a=20split=20item=20to=20done=20with=20its?= =?UTF-8?q?=20last=20sub-task,=20count=20the=20finished=20chunk=20as=20don?= =?UTF-8?q?e=20in=20the=20next=20start,=20and=20read=20a=20parent=20and=20?= =?UTF-8?q?status=20together?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin/do_epic/backend/jira.py | 10 ++++---- bin/do_epic/backend/test_jira.py | 18 +++++++++----- bin/do_epic/main.py | 27 +++++++++++++------- bin/do_epic/test_main.py | 42 ++++++++++++++++++++++++++++++++ 4 files changed, 77 insertions(+), 20 deletions(-) diff --git a/bin/do_epic/backend/jira.py b/bin/do_epic/backend/jira.py index 346db288..e80f063f 100644 --- a/bin/do_epic/backend/jira.py +++ b/bin/do_epic/backend/jira.py @@ -154,15 +154,15 @@ 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") + placed = self.placed(key, authorization, why) 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 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 ".""" + def placed(self, key: str, authorization: str, why: str) -> 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 key's own status is a done one. 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. - answered = self.http("GET", f"{self.epic.site}/rest/api/3/issue/{key}?fields={asked}", authorization, None) + answered = self.http("GET", f"{self.epic.site}/rest/api/3/issue/{key}?fields=parent,status", 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 @@ -217,7 +217,7 @@ def done_transition(offered: object, key: str, named: str | None) -> str | Failu 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] - chosen = [move for move in closing if named is None or move[1] == named] + chosen = closing if len(closing) == 1 else [move for move in closing if 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) diff --git a/bin/do_epic/backend/test_jira.py b/bin/do_epic/backend/test_jira.py index 8ef88099..802833fa 100644 --- a/bin/do_epic/backend/test_jira.py +++ b/bin/do_epic/backend/test_jira.py @@ -207,6 +207,12 @@ class Jira(Case): self.assertEqual(self.jira.calls[-1], ("POST", f"{ISSUES}/{key}/transitions")) self.assertEqual(self.jira.transitioned, ["41"]) + def test_finishes_by_the_one_transition_to_a_done_status_whatever_name_the_config_gives(self) -> None: + key = self.new_store().file("ABC-12", "Count the runs.", "", ()) + self.jira.workflow = [{"id": "31", "name": "Resolve", "to": DONE}] + self.assertIsNone(JiraEpic(EPIC, self.env_file, self.jira, to_markdown, to_adf, "Close").finish(key)) + self.assertEqual(self.jira.transitioned, ["31"]) + 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)): @@ -241,7 +247,7 @@ class Jira(Case): 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.jira.answers[("GET", f"{ISSUES}/{child}?fields=parent,status")] = 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: @@ -314,11 +320,11 @@ class Jira(Case): self.assertEqual(store.read(), Failure("the search for ABC-12's child issues did not end within 1 pages")) def test_refuses_to_file_under_another_epics_child_or_an_issue_it_cannot_read(self) -> None: - self.jira.issues.append({"key": "ABC-5", "fields": {"parent": {"key": "ABC-1"}}}) + self.jira.issues.append({"key": "ABC-5", "fields": {"parent": {"key": "ABC-1"}, "status": TO_DO}}) store = self.new_store() self.assertEqual(store.file("ABC-5", "Count more.", "", ()), Failure("ABC-5 is neither the epic ABC-12 nor one of its child issues, so nothing can be filed under it")) - self.assertEqual(store.file("ABC-77", "Count more.", "", ()), Failure(f"cannot read ABC-77 to file under it: Jira answered 404 for GET {ISSUES}/ABC-77?fields=parent")) - self.jira.answers[("GET", f"{ISSUES}/ABC-78?fields=parent")] = ["ABC-12"] + self.assertEqual(store.file("ABC-77", "Count more.", "", ()), Failure(f"cannot read ABC-77 to file under it: Jira answered 404 for GET {ISSUES}/ABC-77?fields=parent,status")) + self.jira.answers[("GET", f"{ISSUES}/ABC-78?fields=parent,status")] = ["ABC-12"] self.assertEqual(store.file("ABC-78", "Count more.", "", ()), Failure("ABC-78 is neither the epic ABC-12 nor one of its child issues, so nothing can be filed under it")) self.assertEqual([call for call in self.jira.calls if call[0] == "POST" and call[1] == ISSUES], []) @@ -343,14 +349,14 @@ class Jira(Case): def test_an_issue_jira_cannot_read_is_not_commented_on(self) -> None: store = self.new_store() key = store.file("ABC-12", "Count the runs.", "", ()) - self.jira.answers[("GET", f"{ISSUES}/{key}?fields=parent")] = Failure("Jira answered 500") + self.jira.answers[("GET", f"{ISSUES}/{key}?fields=parent,status")] = Failure("Jira answered 500") self.assertEqual(store.comment(str(key), "Hello."), Failure(f"cannot read {key} to comment on it: Jira answered 500")) self.assertNotIn(("POST", f"{ISSUES}/{key}/comment"), self.jira.calls) def test_an_issue_jira_cannot_read_is_not_labelled(self) -> None: store = self.new_store() key = store.file("ABC-12", "Count the runs.", "", ()) - self.jira.answers[("GET", f"{ISSUES}/{key}?fields=parent")] = Failure("Jira answered 500") + self.jira.answers[("GET", f"{ISSUES}/{key}?fields=parent,status")] = Failure("Jira answered 500") self.assertEqual(store.add_label(str(key), "repo:log"), Failure(f"cannot read {key} to label it: Jira answered 500")) self.assertNotIn(("PUT", f"{ISSUES}/{key}"), self.jira.calls) diff --git a/bin/do_epic/main.py b/bin/do_epic/main.py index 0679276f..14c08ee7 100644 --- a/bin/do_epic/main.py +++ b/bin/do_epic/main.py @@ -6,7 +6,7 @@ import pathlib import typing from loop_claude.loop.chunk_start import archived_route, routed -from do_epic import chunk_prompt, scheduler +from do_epic import chunk_prompt, scheduler, split from do_epic.repo_pick import ClaudeWork, HumanTask, recorded, Repo from loop_claude.loop.close import closed_cycle from agent_cycle.run import Cycle, run_cycle @@ -106,7 +106,8 @@ def run(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launcher: def windows_opened(epic: EpicRun) -> Stop: """What the do-epic the human runs does: starts each chunk that may start now, says why each other open issue waits, then puts the epic's session on the terminal until the human detaches.""" - started = chunks_started(epic, None) + issues = epic.store.read() + started = issues if isinstance(issues, Failure) else chunks_started(epic, issues, None) if isinstance(started, Failure): return Stop(1, started.reason) say(f"started {', '.join(started.started)} in the tmux session {epic.session}" if started.started else "started no chunk", epic.effects, stdout=True) @@ -121,11 +122,8 @@ def windows_opened(epic: EpicRun) -> Stop: return Stop(1, f"`tmux {' '.join(shown)}` failed; the chunks go on in the tmux session") if epic.effects.tmux_on_terminal(shown) else Stop(0, "") -def chunks_started(epic: EpicRun, own: str | None) -> scheduler.Started | Failure: - """scheduler.start_chunks on the epic's issues and cap, read afresh; own is the issue of the chunk that asks.""" - issues = epic.store.read() - if isinstance(issues, Failure): - return issues +def chunks_started(epic: EpicRun, issues: list[EpicIssue], own: str | None) -> scheduler.Started | Failure: + """scheduler.start_chunks on the epic's issues, as read, and its cap; own is the issue of the chunk that asks.""" cap = epic.record.parallel_chunks() if isinstance(cap, Failure): return cap @@ -223,11 +221,22 @@ 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. 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.""" + """The stop of a do-epic whose chunk finished. It first moves the chunk's issue to done, and its split item too where that was the last of the item's sub-tasks, so that no finished chunk starts again and what they block 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}; once it is done in Jira, run `do-epic {epic.key}` to start the chunks it blocks") - started = chunks_started(epic, key) + issues = epic.store.read() + if isinstance(issues, Failure): + return Stop(1, f"the chunk finished, but the next could not start: {issues.reason}") + # A search may not show the move yet, so the issue counts as done here whatever the read says. + issues = [dataclasses.replace(each, done=True) if each.key == key else each for each in issues] + above = next((each.parent for each in issues if each.key == key), "") + if not any(each.key == above and each.done for each in issues) and split.finished(issues, above): + moved = epic.store.finish(above) + if isinstance(moved, Failure): + return Stop(1, f"the chunk finished, but its split item {above} could not move to done: {moved.reason}; once it is done in Jira, run `do-epic {epic.key}` to start the chunks it blocks") + issues = [dataclasses.replace(each, done=True) if each.key == above else each for each in issues] + started = chunks_started(epic, issues, key) if isinstance(started, Failure): return Stop(1, f"the chunk finished, but the next could not start: {started.reason}") say(f"the chunk finished; started {', '.join(started.started) or 'no other'}", epic.effects, stdout=True) diff --git a/bin/do_epic/test_main.py b/bin/do_epic/test_main.py index 7524732c..9dcfca53 100644 --- a/bin/do_epic/test_main.py +++ b/bin/do_epic/test_main.py @@ -302,6 +302,48 @@ class AChunksRun(DoEpicTest): 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_finished_chunk_counts_as_done_though_the_search_still_shows_its_issue_open(self) -> None: + issues = [self.issues[0], self.issues[1], issue("ABC-22", "do-epic-claude", blockers=("ABC-21",))] + store = MemoryEpic("ABC-12", issues) + store.read = lambda: list(issues) # 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, 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.assertIn("the chunk finished; started ABC-22\n", out) + + def test_the_last_sub_task_of_a_split_item_to_finish_moves_the_item_to_done_and_starts_what_it_blocks(self) -> None: + parent = issue("ABC-21", "split-by-repo") + tasks = [issue("ABC-23", "do-epic-claude", parent="ABC-21"), issue("ABC-24", "do-epic-claude", parent="ABC-21", done=True)] + store = MemoryEpic("ABC-12", [self.issues[0], parent, *tasks, 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-23\t0\t@9\n") + code, out, err = self.run_main(["--chunk", "ABC-23", "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-23": True, "ABC-24": True, "ABC-22": False}) + self.assertIn("the chunk finished; started ABC-22\n", out) + + def test_a_sub_task_that_leaves_another_open_leaves_its_split_item_open(self) -> None: + parent = issue("ABC-21", "split-by-repo") + store = MemoryEpic("ABC-12", [self.issues[0], parent, issue("ABC-23", "do-epic-claude", parent="ABC-21"), issue("ABC-24", "do-epic-claude", parent="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-23\t0\t@9\n") + code, _, err = self.run_main(["--chunk", "ABC-23", "ABC-12"], fake, MODELS) + self.assertEqual(code, 0, err) + self.assertEqual({each.key: each.done for each in store.issues if each.key in ("ABC-21", "ABC-23", "ABC-24")}, {"ABC-21": False, "ABC-23": True, "ABC-24": False}) + + def test_a_split_item_that_jira_will_not_move_to_done_stops_with_the_reason(self) -> None: + parent = issue("ABC-21", "split-by-repo") + store = MemoryEpic("ABC-12", [self.issues[0], parent, issue("ABC-23", "do-epic-claude", parent="ABC-21")]) + finish = store.finish + store.finish = lambda key: Failure("no way to done") if key == "ABC-21" else finish(key) # 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, windows="ABC-23\t0\t@9\n") + code, out, err = self.run_main(["--chunk", "ABC-23", "ABC-12"], fake, MODELS) + self.assertEqual(code, 1) + self.assertIn("the chunk finished, but its split item ABC-21 could not move to done: no way to done; 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_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] From 8e210eaa099719839b386bc97ffb8ea946a58d6a Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 19 Nov 2026 00:40:16 +0100 Subject: [PATCH 07/30] Print each chunk that asks a question and since when each parked chunk awaits its gate in do-epic --status --- bin/agent_cycle/tmux.py | 4 ++- bin/do_epic/main.py | 12 ++++---- bin/do_epic/scheduler.py | 18 ----------- bin/do_epic/status.py | 46 +++++++++++++++++++++++++++++ bin/do_epic/test_main.py | 17 ++++++++--- bin/do_epic/test_scheduler.py | 2 +- bin/loop_claude/test_loop_claude.py | 2 +- docs/reading-cost.md | 34 +++++++++++++++++++++ 8 files changed, 104 insertions(+), 31 deletions(-) create mode 100644 bin/do_epic/status.py diff --git a/bin/agent_cycle/tmux.py b/bin/agent_cycle/tmux.py index 704caaec..c23f6dc4 100644 --- a/bin/agent_cycle/tmux.py +++ b/bin/agent_cycle/tmux.py @@ -51,6 +51,8 @@ class Listed: dead: bool # What its name says its parked chunk awaits, as the words after PARKED; empty for a chunk that isn't parked. awaits: str = "" + # Whether its name ended in WAITS: its chunk's worker asks the human a question. + asks: bool = False @property def parked(self) -> bool: @@ -90,7 +92,7 @@ def listed(session: str, run: Tmux) -> list[Listed]: def as_listed(shown: str, id: str, pane_dead: str) -> Listed: """The window tmux shows under the name shown, with the ID id and `#{pane_dead}` as pane_dead.""" name, _, awaits = shown.removesuffix(WAITS).partition(PARKED) - return Listed(name, id, pane_dead == "1", awaits) + return Listed(name, id, pane_dead == "1", awaits, shown.endswith(WAITS)) def everywhere(run: Tmux) -> list[Placed]: diff --git a/bin/do_epic/main.py b/bin/do_epic/main.py index 1ab8c919..aa2e16be 100644 --- a/bin/do_epic/main.py +++ b/bin/do_epic/main.py @@ -9,7 +9,7 @@ import sys import typing from loop_claude.loop.chunk_start import archived_route, routed -from do_epic import chunk_prompt, findings, gates, parked, scheduler +from do_epic import chunk_prompt, findings, gates, parked, scheduler, status from do_epic.repo_pick import ClaudeWork, HumanTask, recorded, Repo from loop_claude.loop.close import closed_cycle from loop_claude.project.records import CONSEQUENCE, read_records @@ -52,7 +52,7 @@ A chunk whose worker ends its run while its pull request waits on its checks, an is parked: it frees its place for the next chunk, and its window's name says what it awaits. Its worker goes on once the checks pass, the approval comes or a reviewer comments, and a place is free; until one is, the name says `awaits a slot`. A parked chunk survives a reboot: run do-epic again to go on polling. ---status starts no chunk: it prints each open issue with whether its chunk runs, or why it waits. +--status starts no chunk: it prints each open issue with whether its chunk runs, asks you a question, or why it waits: a parked chunk's gate and since when, a stopped window, a blocker or a human's task. {findings.HELP} The Jira site and its credentials are set in ~/.claude-projects/do-epic/config.toml.""" # Under the home folder, where a chunk's cycles are archived, a folder per epic. It is not loop-claude's archive, since that archive's readers, such as judge-replay and the routing figures, read loop-claude's prompts. @@ -108,8 +108,8 @@ def main(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launcher: def run(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launcher: pathlib.Path, effects: Effects, backend: Backend, stdin: typing.TextIO, forge_at: typing.Callable[[str], Run]) -> Stop: chunk, words = (argv[1], argv[2:]) if len(argv) >= 2 and argv[0] == scheduler.CHUNK_FLAG else (None, argv) - status = chunk is None and words[1:] == [STATUS_FLAG] - words = words[:1] if status else words + status_asked = chunk is None and words[1:] == [STATUS_FLAG] + words = words[:1] if status_asked else words # What the words after the epic's key write into the epic, where they are a filing or a decision. writes = findings.parsed(words[1:]) if chunk is None else None if (len(words) != 1 and not writes) or not ISSUE_KEY.fullmatch(words[0]) or (chunk is not None and not ISSUE_KEY.fullmatch(chunk)): @@ -124,7 +124,7 @@ def run(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launcher: return Stop(1, config.reason) store, record = backend(config, words[0]) epic = EpicRun(words[0], config, store, record, paths, env, launcher, effects, forge_at) - if status: + if status_asked: return status_printed(epic) return windows_opened(epic) if chunk is None else chunk_run(chunk, epic) @@ -132,7 +132,7 @@ def run(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launcher: def status_printed(epic: EpicRun) -> Stop: """What `do-epic --status` does: prints a line per open issue, and doesn't start anything.""" issues = epic.store.read() - lines = issues if isinstance(issues, Failure) else scheduler.status(epic.key, epic.paths.home, issues, epic.effects.tmux) + lines = issues if isinstance(issues, Failure) else status.lines(epic.key, epic.paths.home, issues, epic.effects.tmux) return Stop(1, lines.reason) if isinstance(lines, Failure) else Stop(0, "\n".join(lines) or f"the epic {epic.key} has no open issue") diff --git a/bin/do_epic/scheduler.py b/bin/do_epic/scheduler.py index 7c3dc066..38557080 100644 --- a/bin/do_epic/scheduler.py +++ b/bin/do_epic/scheduler.py @@ -191,21 +191,3 @@ def resume(epic: Epic, repo: str, window: tmux.Window, run: tmux.Tmux) -> str | return None except OSError as failure: return f"cannot lock {failure.filename or epic.folder / LOCK}: {failure.strerror}" - - -def status(key: str, home: pathlib.Path, issues: list[EpicIssue], run: tmux.Tmux) -> list[str] | Failure: - """A line per open issue of the epic called key, in the tracker's rank order: that its chunk runs, or why it waits. It doesn't start anything and checks no limit, so the line of a chunk that has yet to start doesn't say which limit holds it back.""" - found, waits = chunks(issues) - parked = parked_chunks(home / STATE / key) - if isinstance(parked, Failure): - return parked - windows = tmux.listed(tmux.session_name(tmux.EPIC, key), run) - live = {window.name: window for window in windows if not window.dead} - again = f"run `do-epic {key}` to start it again" - reasons = {wait.issue: wait.reason for wait in waits} - for chunk in found: - if chunk.issue in parked: - reasons[chunk.issue] = parked[chunk.issue].waits(live[chunk.issue].awaits) if chunk.issue in live else f"{parked[chunk.issue].waits('')}, and its window stopped; {again}" - elif chunk.issue not in live: - reasons[chunk.issue] = f"its window stopped; {again}" if chunk.issue in {window.name for window in windows} else f"it has not started; `do-epic {key}` starts it once the epic and its repo have room" - return [f"{issue.key} waits: {reasons[issue.key]}" if issue.key in reasons else f"{issue.key} runs" for issue in issues if issue.key in reasons or issue.key in live] diff --git a/bin/do_epic/status.py b/bin/do_epic/status.py new file mode 100644 index 00000000..90c0edb9 --- /dev/null +++ b/bin/do_epic/status.py @@ -0,0 +1,46 @@ +"""What `do-epic --status` prints: each open issue of the epic, with whether its chunk runs, asks the human, is parked on a gate, has stopped or has yet to start (docs/decisions.md → `do-epic: drives one Jira epic …`).""" +import datetime +import pathlib + +from agent_cycle import tmux +from do_epic.backend.protocol import EpicIssue +from do_epic.parked import file_of, Parked, parked_chunks +from do_epic.scheduler import chunks, STATE +from failure import Failure + + +def since(folder: pathlib.Path, chunk: Parked) -> str: + """When the chunk parked on what its file says it awaits, to the minute in the machine's time zone: the file is written once per gate, so its time is when the gate began. Empty where the file cannot be read.""" + try: + return datetime.datetime.fromtimestamp(file_of(folder, chunk.issue).stat().st_mtime).strftime("%Y-%m-%d %H:%M") + except OSError: + return "" + + +def lines(key: str, home: pathlib.Path, issues: list[EpicIssue], run: tmux.Tmux) -> list[str] | Failure: + """A line per open issue of the epic called key, in the tracker's rank order: that its chunk runs or asks the human, or why it waits. It doesn't start anything and checks no limit, so the line of a chunk that has yet to start doesn't say which limit holds it back.""" + found, waits = chunks(issues) + folder = home / STATE / key + parked = parked_chunks(folder) + if isinstance(parked, Failure): + return parked + session = tmux.session_name(tmux.EPIC, key) + windows = tmux.listed(session, run) + live = {window.name: window for window in windows if not window.dead} + again = f"run `do-epic {key}` to start it again" + reasons = {wait.issue: wait.reason for wait in waits} + for chunk in found: + if chunk.issue in parked: + gate = since(folder, parked[chunk.issue]) + when = f", since {gate}" if gate else "" + reasons[chunk.issue] = parked[chunk.issue].waits(live[chunk.issue].awaits) + when if chunk.issue in live else f"{parked[chunk.issue].waits('')}{when}, and its window stopped; {again}" + elif chunk.issue not in live: + reasons[chunk.issue] = f"its window stopped; {again}" if chunk.issue in {window.name for window in windows} else f"it has not started; `do-epic {key}` starts it once the epic and its repo have room" + return [line(issue.key, reasons, live, session) for issue in issues if issue.key in reasons or issue.key in live] + + +def line(issue: str, reasons: dict[str, str], live: dict[str, tmux.Listed], session: str) -> str: + """The status line of issue, whose chunk has a live window or a reason not to run.""" + if issue in reasons: + return f"{issue} waits: {reasons[issue]}" + return f"{issue} asks you: answer its question in the tmux window {session}:{issue}" if live[issue].asks else f"{issue} runs" diff --git a/bin/do_epic/test_main.py b/bin/do_epic/test_main.py index fd02277e..5d027f07 100644 --- a/bin/do_epic/test_main.py +++ b/bin/do_epic/test_main.py @@ -1,7 +1,9 @@ import contextlib import dataclasses +import datetime import io import json +import os import pathlib import shutil import subprocess @@ -41,6 +43,11 @@ class Description: return self.text +# When the parked chunks of the status test were parked, and how the status prints it, in the machine's time zone. +PARKED_SINCE = 1_700_000_000 +PARKED_ON = datetime.datetime.fromtimestamp(PARKED_SINCE).strftime("%Y-%m-%d %H:%M") + + class DoEpicTest(unittest.TestCase): def setUp(self) -> None: made = tempfile.TemporaryDirectory() @@ -614,17 +621,19 @@ class TheStatus(DoEpicTest): parked.park(folder, parked.Parked("ABC-26", "/code/api-ABC-26", "9", "s", "its checks")) parked.park(folder, parked.Parked("ABC-28", "/code/api-ABC-28", "11", "s", "an approval")) self.issues.insert(7, issue("ABC-28", "repo:api")) + for issue_key, when in (("ABC-20", PARKED_SINCE), ("ABC-26", PARKED_SINCE), ("ABC-28", PARKED_SINCE)): + os.utime(parked.file_of(folder, issue_key), (when, when)) fake = FakeEffects(windows="ABC-20 awaits an approval\t0\t@1\nABC-21 ?\t0\t@2\nABC-22\t1\t@3\nABC-28 awaits a slot\t0\t@4\n") code, out, err = self.run_main(["ABC-12", "--status"], fake) self.assertEqual((code, err), (0, "")) self.assertEqual(out.replace("<1790000000> ", "").splitlines(), [ - "ABC-20 waits: it is parked: its pull request #7 awaits an approval", - "ABC-21 runs", + f"ABC-20 waits: it is parked: its pull request #7 awaits an approval, since {PARKED_ON}", + "ABC-21 asks you: answer its question in the tmux window epic-ABC-12:ABC-21", "ABC-22 waits: its window stopped; run `do-epic ABC-12` to start it again", "ABC-23 waits: ABC-20 blocks it", "ABC-24 waits: it has not started; `do-epic ABC-12` starts it once the epic and its repo have room", - "ABC-26 waits: it is parked: its pull request #9 awaits its checks, and its window stopped; run `do-epic ABC-12` to start it again", - "ABC-28 waits: it is parked: its worker has work again on pull request #11 and awaits a slot", + f"ABC-26 waits: it is parked: its pull request #9 awaits its checks, since {PARKED_ON}, and its window stopped; run `do-epic ABC-12` to start it again", + f"ABC-28 waits: it is parked: its worker has work again on pull request #11 and awaits a slot, since {PARKED_ON}", "ABC-27 waits: no label names its repo", ]) self.assertEqual({args[0] for args in fake.tmux_calls}, {"-V", "list-windows"}) diff --git a/bin/do_epic/test_scheduler.py b/bin/do_epic/test_scheduler.py index 97fd1573..70ba18ae 100644 --- a/bin/do_epic/test_scheduler.py +++ b/bin/do_epic/test_scheduler.py @@ -316,7 +316,7 @@ class TheFirstPrompt(unittest.TestCase): class WindowsAcrossSessions(unittest.TestCase): def test_lists_each_window_with_its_session_and_root(self) -> None: run = Tmux(("epic-ABC-12", "ABC-20 ?", False, "/code/api"), ("loop-api", "item-3", True, "")) - self.assertEqual(tmux.everywhere(run), [tmux.Placed("epic-ABC-12", tmux.Listed("ABC-20", "@0", False), "/code/api"), tmux.Placed("loop-api", tmux.Listed("item-3", "@1", True), "")]) + self.assertEqual(tmux.everywhere(run), [tmux.Placed("epic-ABC-12", tmux.Listed("ABC-20", "@0", False, asks=True), "/code/api"), tmux.Placed("loop-api", tmux.Listed("item-3", "@1", True), "")]) self.assertEqual(run.calls, [["list-windows", "-a", "-F", f"#{{session_name}}\t#{{window_name}}\t#{{pane_dead}}\t#{{window_id}}\t#{{{tmux.ROOT}}}"]]) def test_without_a_tmux_server_there_are_none(self) -> None: diff --git a/bin/loop_claude/test_loop_claude.py b/bin/loop_claude/test_loop_claude.py index a3268f58..79c04daf 100644 --- a/bin/loop_claude/test_loop_claude.py +++ b/bin/loop_claude/test_loop_claude.py @@ -1319,7 +1319,7 @@ class TmuxCommands(unittest.TestCase): def test_lists_the_windows_without_the_waiting_mark(self): fake = FakeEffects(windows="item-372 ?\t0\t@1\nitem-380\t1\t@2\nno-item\t0\t@5\n") - self.assertEqual(tmux.listed("loop-proj", fake.tmux), [tmux.Listed("item-372", "@1", False), tmux.Listed("item-380", "@2", True), tmux.Listed("no-item", "@5", False)]) + self.assertEqual(tmux.listed("loop-proj", fake.tmux), [tmux.Listed("item-372", "@1", False, asks=True), tmux.Listed("item-380", "@2", True), tmux.Listed("no-item", "@5", False)]) self.assertEqual(fake.tmux_calls, [["list-windows", "-t", "=loop-proj", "-F", "#{window_name}\t#{pane_dead}\t#{window_id}"]]) self.assertEqual(tmux.listed("loop-proj", FakeEffects().tmux), []) failed = lambda args: subprocess.CompletedProcess(args, 1, "item-1\t0\t@1\n", "no server") diff --git a/docs/reading-cost.md b/docs/reading-cost.md index 2438e973..27a660b4 100644 --- a/docs/reading-cost.md +++ b/docs/reading-cost.md @@ -2910,3 +2910,37 @@ 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 + +## Reading cost, chunk d77b99fcaa22, finished 2026-11-18T23:16:50Z + +112582 new input tokens before the first commit. + +Read most (opens and searches): + +- `bin/do_epic/main.py` 7 +- `bin/forge/pulls.py` 4 +- `bin/chunk_pr/approval.py` 3 +- `bin/chunk_pr/main.py` 3 +- `bin/do_epic/scheduler.py` 3 +- `rules/todo-items.md` 3 +- `README.md` 2 +- `bin/agent_cycle/tmux.py` 1 +- `bin/do_epic/chunk_prompt.py` 1 +- `docs/decisions.md` 1 From e946d71a5e929233e8659cfd050a4cfa7975a84a Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 19 Nov 2026 00:08:28 +0100 Subject: [PATCH 08/30] =?UTF-8?q?Answer=20stability=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=204=20=F0=9F=9F=A1=20(0=20misread);=20answered=20?= =?UTF-8?q?in=20the=20commit=20before?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin/do_epic/test_main.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/bin/do_epic/test_main.py b/bin/do_epic/test_main.py index 9dcfca53..9c39755c 100644 --- a/bin/do_epic/test_main.py +++ b/bin/do_epic/test_main.py @@ -13,10 +13,10 @@ 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 do_epic.backend.protocol import EpicIssue +from do_epic.epic_record import EpicRecord from agent_cycle import escalation_mark, judge, tmux from failure import Failure from loop_claude.test_loop_claude import FakeEffects, judged, Worker From 4cc39b8b20349d85ff476c172a6047dc86973923 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 19 Nov 2026 01:20:30 +0100 Subject: [PATCH 09/30] Kill the surviving mutants of the finish moves: the fake's status and refusal, an unreadable epic, and one more split item per finish --- bin/do_epic/backend/jira.py | 2 +- bin/do_epic/backend/test_fake.py | 14 ++++++++++++++ bin/do_epic/main.py | 22 +++++++++++++++------- bin/do_epic/test_main.py | 8 ++++++++ 4 files changed, 38 insertions(+), 8 deletions(-) diff --git a/bin/do_epic/backend/jira.py b/bin/do_epic/backend/jira.py index e80f063f..bca9c36b 100644 --- a/bin/do_epic/backend/jira.py +++ b/bin/do_epic/backend/jira.py @@ -221,7 +221,7 @@ def done_transition(offered: object, key: str, named: str | None) -> str | Failu 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: + if closing 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 no transition called {named!r} to a done status, only {listed}: correct `{JIRA_FINISH_TRANSITION}`, in ~/.claude-projects/do-epic/config.toml") diff --git a/bin/do_epic/backend/test_fake.py b/bin/do_epic/backend/test_fake.py index 72244f16..5ead58c9 100644 --- a/bin/do_epic/backend/test_fake.py +++ b/bin/do_epic/backend/test_fake.py @@ -51,5 +51,19 @@ class Ranking(unittest.TestCase): self.assertEqual(store.rank(str(child), "ZZZ-1"), Failure(f"ZZZ-1 is not one of the child issues of the epic ABC-12, so {child} is not ranked")) +class Finishing(unittest.TestCase): + def test_finishes_an_issue_to_the_status_done(self) -> None: + store = MemoryEpic("ABC-12") + key = store.file("ABC-12", "Count the runs.", "", ()) + self.assertIsNone(store.finish(str(key))) + self.assertEqual([(issue.status, issue.done) for issue in store.issues], [("Done", True)]) + + def test_refuses_to_finish_an_issue_outside_the_epic_saying_so(self) -> None: + self.assertEqual(MemoryEpic("ABC-12").finish("ZZZ-1"), Failure("ZZZ-1 is not one of the child issues of the epic ABC-12, so it cannot be finished")) + + def test_fails_to_finish_with_the_reason_given(self) -> None: + self.assertEqual(MemoryEpic("ABC-12", fails="Jira is down").finish("ABC-100"), Failure("Jira is down")) + + if __name__ == "__main__": unittest.main() diff --git a/bin/do_epic/main.py b/bin/do_epic/main.py index 14c08ee7..85e17912 100644 --- a/bin/do_epic/main.py +++ b/bin/do_epic/main.py @@ -230,19 +230,27 @@ def handed_on(key: str, epic: EpicRun) -> Stop: return Stop(1, f"the chunk finished, but the next could not start: {issues.reason}") # A search may not show the move yet, so the issue counts as done here whatever the read says. issues = [dataclasses.replace(each, done=True) if each.key == key else each for each in issues] - above = next((each.parent for each in issues if each.key == key), "") - if not any(each.key == above and each.done for each in issues) and split.finished(issues, above): - moved = epic.store.finish(above) - if isinstance(moved, Failure): - return Stop(1, f"the chunk finished, but its split item {above} could not move to done: {moved.reason}; once it is done in Jira, run `do-epic {epic.key}` to start the chunks it blocks") - issues = [dataclasses.replace(each, done=True) if each.key == above else each for each in issues] - started = chunks_started(epic, issues, key) + closed = split_items_closed(epic, issues) + if isinstance(closed, Stop): + return closed + started = chunks_started(epic, closed, key) if isinstance(started, Failure): return Stop(1, f"the chunk finished, but the next could not start: {started.reason}") say(f"the chunk finished; started {', '.join(started.started) or 'no other'}", epic.effects, stdout=True) return Stop(0, "") +def split_items_closed(epic: EpicRun, issues: list[EpicIssue]) -> list[EpicIssue] | Stop: + """The issues, with each item split by repo whose sub-tasks are all done moved to done in the tracker and read as done; the stop where one cannot move. Its last sub-task to finish closes it, and one an earlier run left open closes with it.""" + for item in issues: + if split.SPLIT_LABEL in item.labels and not item.done and split.finished(issues, item.key): + moved = epic.store.finish(item.key) + if isinstance(moved, Failure): + return Stop(1, f"the chunk finished, but its split item {item.key} could not move to done: {moved.reason}; once it is done in Jira, run `do-epic {epic.key}` to start the chunks it blocks") + issues = [dataclasses.replace(each, done=True) if each.key == item.key else each for each in issues] + return issues + + def next_cycle(loop_run: LoopRun, loop: Loop, in_repo: bool, epic: EpicRun) -> Cycle | Stop: """The cycle loop_run runs next, from the issue, the premises, the records, the models and the routing ladder read afresh; the stop where one of them cannot be read. A chunk in a repo routes on that repo's model and ladder, and one without a repo on the machine setting `repoless-model` and the shipped ladder.""" issue = issue_read(loop.window.name, epic) diff --git a/bin/do_epic/test_main.py b/bin/do_epic/test_main.py index 9c39755c..4db7764c 100644 --- a/bin/do_epic/test_main.py +++ b/bin/do_epic/test_main.py @@ -178,6 +178,14 @@ class TheHumansRun(DoEpicTest): code, _, err = self.run_main(["ABC-12"], fake, {"TMUX": "/tmp/tmux"}) self.assertEqual((code, err.split(" ", 1)[1]), (1, "`tmux switch-client -t =epic-ABC-12` failed; the chunks go on in the tmux session\n")) + def test_stops_with_the_reason_where_the_epics_issues_cannot_be_read(self) -> None: + store = MemoryEpic("ABC-12", fails="Jira answered 503") + self.backend = lambda config, key: (store, EpicRecord(Description(self.description))) # type: ignore[method-assign,arg-type] + code, out, err = self.run_main(["ABC-12"], FakeEffects(on_terminal=False)) + self.assertEqual(code, 1) + self.assertIn("Jira answered 503\n", err) + self.assertNotIn("started", out) + def test_off_a_terminal_it_says_how_to_see_the_chunks(self) -> None: code, out, err = self.run_main(["ABC-12"], FakeEffects(on_terminal=False, windows="ABC-21\t0\t@9\n")) self.assertEqual((code, err), (0, "")) From c60ad667da25887856e6ba0633ba54069b6cea6b Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 19 Nov 2026 01:34:01 +0100 Subject: [PATCH 10/30] =?UTF-8?q?Answer=20stability=20round=202:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=200=20=F0=9F=9F=A1=20(0=20misread);=20nothing=20t?= =?UTF-8?q?o=20change?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit From 07ef481c51840761775e5d718b2bd76953142a2c Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 19 Nov 2026 01:35:37 +0100 Subject: [PATCH 11/30] Test do-epic's status lines on their own --- bin/do_epic/test_status.py | 63 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 bin/do_epic/test_status.py diff --git a/bin/do_epic/test_status.py b/bin/do_epic/test_status.py new file mode 100644 index 00000000..3f6faac1 --- /dev/null +++ b/bin/do_epic/test_status.py @@ -0,0 +1,63 @@ +import datetime +import os +import pathlib +import tempfile +import unittest + +from do_epic import parked, status +from do_epic.scheduler import STATE +from do_epic.test_scheduler import issue, Tmux +from failure import Failure + +SINCE = 1_700_000_000 +# How the status prints SINCE, in the machine's time zone. +SINCE_ON = datetime.datetime.fromtimestamp(SINCE).strftime("%Y-%m-%d %H:%M") +EPIC = "epic-ABC-12" + + +class TheStatusLines(unittest.TestCase): + def setUp(self) -> None: + self.home = pathlib.Path(tempfile.mkdtemp()) + self.folder = self.home / STATE / "ABC-12" + + def park(self, key: str, on: str, since: int | None = SINCE) -> None: + parked.park(self.folder, parked.Parked(key, f"/code/api-{key}", "7", "s", on)) + if since is not None: + os.utime(parked.file_of(self.folder, key), (since, since)) + + def lines(self, issues: list, *windows: tuple[str, str, bool, str]) -> list[str] | Failure: + return status.lines("ABC-12", self.home, issues, Tmux(*windows)) + + def test_a_chunk_that_asks_says_where_to_answer_and_one_that_works_runs(self) -> None: + found = self.lines([issue("ABC-20", "repo:api"), issue("ABC-21", "repo:api")], (EPIC, "ABC-20 ?", False, ""), (EPIC, "ABC-21", False, "")) + self.assertEqual(found, ["ABC-20 asks you: answer its question in the tmux window epic-ABC-12:ABC-20", "ABC-21 runs"]) + + def test_a_parked_chunk_says_what_it_awaits_and_since_when(self) -> None: + self.park("ABC-20", "an approval") + self.assertEqual(self.lines([issue("ABC-20", "repo:api")], (EPIC, "ABC-20 awaits its checks", False, "")), [f"ABC-20 waits: it is parked: its pull request #7 awaits its checks, since {SINCE_ON}"]) + + def test_a_parked_chunk_without_a_window_says_since_when_and_how_to_start_it_again(self) -> None: + self.park("ABC-20", "an approval") + self.assertEqual(self.lines([issue("ABC-20", "repo:api")]), [f"ABC-20 waits: it is parked: its pull request #7 awaits an approval, since {SINCE_ON}, and its window stopped; run `do-epic ABC-12` to start it again"]) + + def test_a_stopped_chunk_and_one_not_started_say_so(self) -> None: + found = self.lines([issue("ABC-20", "repo:api"), issue("ABC-21", "repo:api")], (EPIC, "ABC-20", True, "")) + self.assertEqual(found, ["ABC-20 waits: its window stopped; run `do-epic ABC-12` to start it again", "ABC-21 waits: it has not started; `do-epic ABC-12` starts it once the epic and its repo have room"]) + + def test_a_human_task_and_a_blocked_issue_say_why_they_wait(self) -> None: + found = self.lines([issue("ABC-20", "repo:api"), issue("ABC-21", "repo:api", blockers=("ABC-20",)), issue("ABC-22", "do-epic-human")], (EPIC, "ABC-20", False, "")) + self.assertEqual(found, ["ABC-20 runs", "ABC-21 waits: ABC-20 blocks it", "ABC-22 waits: it is a human's task"]) + + def test_a_parked_chunk_that_cannot_be_read_is_a_failure(self) -> None: + (self.folder / parked.FOLDER).mkdir(parents=True) + (self.folder / parked.FOLDER / "ABC-20.json").write_text("{", encoding="utf-8") + self.assertIsInstance(self.lines([issue("ABC-20", "repo:api")]), Failure) + + +class TheTimeSinceParking(unittest.TestCase): + def test_is_empty_where_the_chunks_file_is_gone(self) -> None: + self.assertEqual(status.since(pathlib.Path(tempfile.mkdtemp()), parked.Parked("ABC-20", "/code/api", "7", "s", "an approval")), "") + + +if __name__ == "__main__": + unittest.main() From 3e2e0ae5bf13d598dcb0a6bc2781c0e80538282a Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 19 Nov 2026 01:59:18 +0100 Subject: [PATCH 12/30] Put the since-when suffix in since, so its own test covers it --- bin/do_epic/status.py | 7 +++---- bin/do_epic/test_status.py | 7 +++++++ 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/bin/do_epic/status.py b/bin/do_epic/status.py index 90c0edb9..157636d8 100644 --- a/bin/do_epic/status.py +++ b/bin/do_epic/status.py @@ -10,9 +10,9 @@ from failure import Failure def since(folder: pathlib.Path, chunk: Parked) -> str: - """When the chunk parked on what its file says it awaits, to the minute in the machine's time zone: the file is written once per gate, so its time is when the gate began. Empty where the file cannot be read.""" + """`, since