diff --git a/CHANGELOG.md b/CHANGELOG.md index d8787a3d..997c1d97 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,9 @@ ## Unreleased +- do-epic tells an epic chunk's worker how its repo ships the change: a bullet under the repo's changelog where the repo publishes something, none where its plan is in Jira, and no `--finish` for `chunk-pr merge`. +- `do-epic --status` says which chunk asks you a question, and since when each parked chunk has awaited its gate. +- do-epic moves a chunk's issue to done in Jira when the chunk finishes, and the split item it belongs to once its last sub-task is done, so no finished chunk starts again and the chunks it blocks start. It moves them by the transition `jira-finish-transition` and `jira-finish-status` name, so set both; without them a finishing chunk stops with that reason. - Describe do-epic in the README: its entry under Tools, and its machine settings and `repo-rule.md` under Set up a project. - do-epic finishes an epic: once none of its issues is open, a finishing chunk files a release review of each repo the epic changed, as an issue labelled `do-epic-release-review`, and asks you to confirm each goal. `do-epic --close-epic` then posts the summary piped in as a comment on the epic and closes it in Jira, by the transition `jira-finish-transition` names, to the status `jira-finish-status` names. - do-epic parks a chunk whose pull request waits on its checks, an approval or a new review: the chunk frees its place for the next one, its tmux window says what it awaits, and its worker goes on when the gate opens or a reviewer comments, even after a reboot. `do-epic --status` prints what each open issue does. diff --git a/README.md b/README.md index 309b2862..3446b6cf 100644 --- a/README.md +++ b/README.md @@ -152,7 +152,7 @@ The last line prints each setting's path once the config is complete. `do-epic` keeps its settings per machine, not per project, in `~/.claude-projects/do-epic/`, two files for every epic: -- `config.toml` sets `jira-url`, the site, such as `https://acme.atlassian.net`; `env-file`, the file holding `ATLASSIAN_EMAIL` and `ATLASSIAN_API_TOKEN`, a path that starts with `/` or `~/`, outside the clone folder and every folder of `~/.claude-projects`; and `repoless-model`, the model that works an item with no repo. It may also set `clone-folder`, where a missing repo is cloned, `~/code` if left out; `language`, the language of Jira text, English if left out; and `jira-finish-transition` with `jira-finish-status`, which name the workflow transition that closes a finished epic and the status it leads to, such as `"Mark as done"` and `"Done"`. Set both or neither: without them do-epic closes no epic. +- `config.toml` sets `jira-url`, the site, such as `https://acme.atlassian.net`; `env-file`, the file holding `ATLASSIAN_EMAIL` and `ATLASSIAN_API_TOKEN`, a path that starts with `/` or `~/`, outside the clone folder and every folder of `~/.claude-projects`; and `repoless-model`, the model that works an item with no repo. It may also set `clone-folder`, where a missing repo is cloned, `~/code` if left out; `language`, the language of Jira text, English if left out; and `jira-finish-transition` with `jira-finish-status`, which name the workflow transition that moves a finished chunk's issue, and closes a finished epic, and the status it leads to, such as `"Mark as done"` and `"Done"`. Set both or neither: without them do-epic moves no issue to done and closes no epic, and a chunk that finishes stops with that reason. - `repo-rule.md` is prose that says how to tell an item's repo, such as "a label that equals a repo's name names that repo". It may not be blank. do-epic doesn't read it yet: until it picks each item's repo from the rule, an issue runs once a label `repo:` records its repo, `do-epic-claude` marks work of Claude's that changes no repo, and `do-epic-human` a task of yours. Each repo an epic changes has a project config of its own, as in the rest of this section. `do-epic` fails and names each setting or file that is missing or invalid. @@ -224,7 +224,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. `gates.py` reads once whether a chunk's pull request waits on its checks, an approval or a new review, and `parked.py` keeps each chunk that does in a state file, so it takes no running slot while it waits and goes on waiting after a reboot. `chunk_prompt.py` words what a chunk's worker reads. Through `findings.py` that worker files a finding as an issue of the epic, with `--file`, and appends a decision to its description, with `--record-decision`. `finish.py` ends an epic that holds no open issue: its finishing chunk files a release review of each repo the epic changed, has the human confirm each goal, and with `--close-epic` posts the summary on the epic and closes it. `config.py` reads its machine-wide settings, importing `project_config`'s settings and `model_routing`'s ladder file, and `epic_record.py` reads and writes an epic's description by section, language line and cap line, through `record_store`'s `EpicDescription`. `repos.py` finds a repo's checkout and project config by its name, and clones a missing checkout from the host and owner of the epic's other repos, through `forge`'s `url_beside`. `repo_pick.py` asks claude, by `repo-rule.md`, where an epic item is worked, and records the answer as a label on the issue. `split.py` has claude predict from the code which repos an item changes, and files a sub-task per repo under it where there are several. `ranking.py` orders an epic's items by score over one chain of goals, the epic's, then code health, then the item's repo's, through `plan`'s ranking, and re-ranks the tracker's backlog to that order through `backend/`. `backend/` reads, files and ranks the epic's issues, adds the labels `repo_pick.py` and `split.py` record, posts comments, and closes the epic. +- `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. `gates.py` reads once whether a chunk's pull request waits on its checks, an approval or a new review, and `parked.py` keeps each chunk that does in a state file, so it takes no running slot while it waits and goes on waiting after a reboot. `chunk_prompt.py` words what a chunk's worker reads. Through `findings.py` that worker files a finding as an issue of the epic, with `--file`, and appends a decision to its description, with `--record-decision`. `finish.py` ends an epic that holds no open issue: its finishing chunk files a release review of each repo the epic changed, has the human confirm each goal, and with `--close-epic` posts the summary on the epic and closes it. `config.py` reads its machine-wide settings, importing `project_config`'s settings and `model_routing`'s ladder file, and `epic_record.py` reads and writes an epic's description by section, language line and cap line, through `record_store`'s `EpicDescription`. `repos.py` finds a repo's checkout and project config by its name, and clones a missing checkout from the host and owner of the epic's other repos, through `forge`'s `url_beside`. `repo_pick.py` asks claude, by `repo-rule.md`, where an epic item is worked, and records the answer as a label on the issue. `split.py` has claude predict from the code which repos an item changes, and files a sub-task per repo under it where there are several. `ranking.py` orders an epic's items by score over one chain of goals, the epic's, then code health, then the item's repo's, through `plan`'s ranking, and re-ranks the tracker's backlog to that order through `backend/`. `backend/` reads, files and ranks the epic's issues, adds the labels `repo_pick.py` and `split.py` record, posts comments, moves a finished chunk's issue to done, and closes the epic. - `forge/` tells a GitHub origin from a Gitea one, names a repo beside an origin's and runs that forge's CLI (`commands.py`), and finds a pull request and reads its checks, once or until they settle (`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/agent_cycle/tmux.py b/bin/agent_cycle/tmux.py index 704caaec..0af21917 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 loop asks the human something. + 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/backend/contract.py b/bin/do_epic/backend/contract.py index 4b1c74b3..9786e2f0 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: @@ -124,6 +125,29 @@ 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_issue(key), store.finish_issue(closed)], [None, None]) + self.assertEqual({issue.key: issue.done for issue in self.issues(store)}, {key: True, other: False, closed: True}) + + 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.assertIsNone(store.finish_issue(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_issue("ZZZ-1"), Failure) + self.assertIsInstance(store.finish_issue("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() 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 ea404f51..4d2a3e01 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, rank and closing fails with it as the reason. comments holds each issue's comments, and the epic's, by key. done says whether the epic is closed.""" + """An epic whose issues rank in the order filed, until one is ranked. Where fails is set, every read, filing, label, comment, rank, issue finish and closing fails with it as the reason. comments holds each issue's comments, and the epic's, by key. done says whether the epic is closed.""" epic_key: str issues: list[EpicIssue] = dataclasses.field(default_factory=list) comments: dict[str, list[str]] = dataclasses.field(default_factory=dict) @@ -73,6 +73,17 @@ class MemoryEpic: self.done = True return None + def finish_issue(self, key: str) -> None | Failure: + if self.fails: + return Failure(self.fails) + 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: + 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 f9a6d1c3..33cad807 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, finishing_transition, ISSUE_KEY, ISSUE_TYPE, move_refusal, project_of, PROPERTY, rank_refusal, scores, searched +from plan_store.jira_epic import blocked_by_links, DONE, FILED_BY, finishing_transition, ISSUE_KEY, ISSUE_TYPE, move_refusal, PERHAPS_MOVED, project_of, PROPERTY, rank_refusal, scores, searched from project_config.settings import Epic, Finish, JIRA_FINISH_STATUS, JIRA_FINISH_TRANSITION from do_epic.backend.protocol import EpicIssue, no_child, no_parent, no_words, unfit, unfit_label from failure import Failure @@ -13,6 +13,7 @@ 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 +NO_FINISH = "do-epic's settings name no transition to {to} by: set `{transition}` and `{status}` in ~/.claude-projects/do-epic/config.toml, to the names Jira shows, such as \"Mark as done\" and \"Done\"" PERHAPS_FILED = "unless Jira refused the request, the issue may exist: look under {parent} before filing it again" @@ -132,7 +133,7 @@ class JiraEpic: def close(self, summary: str) -> None | Failure: if self.finish is None: - return Failure(f"do-epic's settings name no transition to close an epic by: set `{JIRA_FINISH_TRANSITION}` and `{JIRA_FINISH_STATUS}` in ~/.claude-projects/do-epic/config.toml, to the names Jira shows, such as \"Mark as done\" and \"Done\"") + return Failure(NO_FINISH.format(to="close an epic", transition=JIRA_FINISH_TRANSITION, status=JIRA_FINISH_STATUS)) authorization = basic_auth(self.env_file) if isinstance(authorization, Failure): return authorization @@ -151,6 +152,30 @@ class JiraEpic: refused_move = move_refusal(self.epic.site, self.epic_key, transition, self.finish, authorization, self.http) return Failure(f"posted the summary on {self.epic_key}, but {refused_move}; close the epic in Jira rather than posting the summary again") if refused_move else None + def finish_issue(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 + # 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 + if self.finish is None: + return Failure(NO_FINISH.format(to="finish an issue", transition=JIRA_FINISH_TRANSITION, status=JIRA_FINISH_STATUS)) + transition = finishing_transition(self.epic.site, key, self.finish, authorization, self.http) + if isinstance(transition, Failure): + return transition + refused = move_refusal(self.epic.site, key, transition, self.finish, authorization, self.http) + return Failure(f"{refused}; {PERHAPS_MOVED.format(key=key)}") if refused 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: @@ -160,15 +185,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) + return placed if isinstance(placed, Failure) else placed[0] + + 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 + 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=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 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.""" diff --git a/bin/do_epic/backend/protocol.py b/bin/do_epic/backend/protocol.py index 94b4e7bc..516b2300 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_issue(self, key: str) -> None | Failure: + """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 closed(self) -> bool | Failure: """Whether the epic itself is in a status the tracker counts as done.""" diff --git a/bin/do_epic/backend/test_fake.py b/bin/do_epic/backend/test_fake.py index 72244f16..46703529 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_issue(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_issue("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_issue("ABC-100"), Failure("Jira is down")) + + if __name__ == "__main__": unittest.main() diff --git a/bin/do_epic/backend/test_jira.py b/bin/do_epic/backend/test_jira.py index af2db03d..762ab246 100644 --- a/bin/do_epic/backend/test_jira.py +++ b/bin/do_epic/backend/test_jira.py @@ -48,6 +48,10 @@ 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}]) # The epic's own status, which the transition "Mark as done" moves to DONE. epic_status: dict[str, object] = dataclasses.field(default_factory=lambda: dict(TO_DO)) @@ -75,8 +79,16 @@ 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] + self.transitioned.append(body["transition"]["id"]) + return None if method == "POST" and url == ISSUES: return self.created(body) if method == "PUT" and url == RANK: @@ -206,6 +218,76 @@ class Jira(Case): self.jira.answers[("GET", EPIC_STATUS)] = answer self.assertEqual(self.new_store().closed(), Failure(reason)) + def test_finishes_an_issue_by_the_transition_the_settings_name(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_issue(key)) + self.assertEqual(self.jira.calls[-1], ("POST", f"{ISSUES}/{key}/transitions")) + self.assertEqual((self.jira.transitioned, self.jira.issues[0]["fields"]["status"]), (["31"], DONE)) # type: ignore[index] + + def test_finishes_by_the_named_transition_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, Finish("Close", "Closed")).finish_issue(key)) + self.assertEqual(self.jira.transitioned, ["41"]) + + def test_leaves_an_issue_that_is_done_without_asking_for_its_transitions(self) -> None: + store = JiraEpic(EPIC, self.env_file, self.jira, to_markdown, to_adf) + key = self.new_store().file("ABC-12", "Count the runs.", "", ()) + self.jira.change(key, status=DONE) + self.assertIsNone(store.finish_issue(key)) + self.assertNotIn(("GET", f"{ISSUES}/{key}/transitions"), self.jira.calls) + + def test_a_finish_names_why_no_move_finishes_the_issue(self) -> None: + key = self.new_store().file("ABC-12", "Count the runs.", "", ()) + unnamed = JiraEpic(EPIC, self.env_file, self.jira, to_markdown, to_adf) + wrong_status = JiraEpic(EPIC, self.env_file, self.jira, to_markdown, to_adf, Finish("Mark as done", "Closed")) + no_such = JiraEpic(EPIC, self.env_file, self.jira, to_markdown, to_adf, Finish("Close", "Done")) + self.assertEqual(unnamed.finish_issue(key), Failure("do-epic's settings name no transition to finish an issue by: set `jira-finish-transition` and `jira-finish-status` in ~/.claude-projects/do-epic/config.toml, to the names Jira shows, such as \"Mark as done\" and \"Done\"")) + self.assertEqual(wrong_status.finish_issue(key), Failure(f"{key}'s transition 'Mark as done' leads to the status 'Done', not to 'Closed', which `jira-finish-status` names")) + refused = no_such.finish_issue(key) + assert isinstance(refused, Failure) + self.assertIn(f"{key} has no transition 'Close' from its status", refused.reason) + self.assertEqual((self.jira.transitioned, self.jira.issues[0]["fields"]["status"]), ([], TO_DO)) # type: ignore[index] + + 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_issue(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_issue(key), Failure(f"cannot move {key} by 'Mark as done': Jira answered 400: Resolution is required; unless Jira refused the request, the issue may have moved: look at {key} before finishing the item 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_issue(key), Failure(f"cannot read {key}'s transitions: Jira answered 503")) + 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_issue(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_issue(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,status")] = Failure("Jira answered 503") + self.assertEqual(store.finish_issue(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() children = [store.file("ABC-12", f"Item {n}.", "", ()) for n in range(60)] @@ -276,11 +358,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], []) @@ -305,14 +387,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/chunk_prompt.py b/bin/do_epic/chunk_prompt.py index 2d1f08fa..cea698dc 100644 --- a/bin/do_epic/chunk_prompt.py +++ b/bin/do_epic/chunk_prompt.py @@ -6,6 +6,7 @@ from do_epic import findings from loop_claude.project.records import HUMAN_RULE_NAMES, RECORD_FILES from text_files.markdown_text import listed import pathlib +from project_config.settings import ProjectConfig from model_routing.ladder import ProjectRung from loop_claude.cycle import prompts from model_routing.route import Route @@ -15,10 +16,20 @@ from agent_cycle.worker_prompts import WorkerPrompts DRIVER = "do-epic" -def task(issue: EpicIssue, epic: str, checkout: str | None, launcher: pathlib.Path, language: str) -> str: - """The task of the chunk that works issue, of the epic with the key epic: in checkout, or without a repo where it is None. launcher is the do-epic that runs the chunk, and language the one the epic's Jira text is in.""" +def shipping(config: ProjectConfig) -> str: + """How a chunk in the repo that config names ships its change. An epic's issue isn't an item of the repo's plan, so `chunk-pr merge --finish`, which adds a finished item's changelog bullet, doesn't apply: the worker writes the bullet itself, where the repo publishes something others consume (docs/decisions.md → `do-epic: drives one Jira epic …`, "Releases").""" + opening = "The issue isn't an item of the repo's plan, so run `chunk-pr merge` without `--finish`." + if config.epic: + return f"{opening} The repo's plan is a Jira epic, and the history of its issues serves as the changelog, so leave the changelog as it is." + changelog = config.paths["changelog"].relative_to(config.top) if "changelog" in config.paths and config.paths["changelog"].is_relative_to(config.top) else config.places["changelog"] + return f"{opening} Where the repo publishes something others consume, add one bullet to `## Unreleased` in `{changelog}` that tells the repo's consumers what changed; otherwise leave the changelog as it is." + + +def task(issue: EpicIssue, epic: str, checkout: str | None, launcher: pathlib.Path, language: str, config: ProjectConfig | None) -> str: + """The task of the chunk that works issue, of the epic with the key epic: in checkout, or without a repo where it is None. launcher is the do-epic that runs the chunk, language the one the epic's Jira text is in, and config the project config of the repo's checkout, None without a repo.""" + shipped = shipping(config) if config else "" where = f"in the checkout {checkout}, on the branch {issue.key}" if checkout else "which changes no repo: work in the folder you start in" - return f"Work the Jira issue {issue.key} of the epic {epic} as one chunk, {where}. {findings.instructions(epic, launcher, language)} Its summary: {issue.summary}" + (f"\n\nIts description:\n\n{issue.detail}" if issue.detail else "") + return f"Work the Jira issue {issue.key} of the epic {epic} as one chunk, {where}. {" ".join(filter(None, [findings.instructions(epic, launcher, language), shipped]))} Its summary: {issue.summary}" + (f"\n\nIts description:\n\n{issue.detail}" if issue.detail else "") CODE_HEALTH = '~/.claude/CLAUDE.md → "Shared goal"' diff --git a/bin/do_epic/config.py b/bin/do_epic/config.py index f3852832..04f4ed74 100644 --- a/bin/do_epic/config.py +++ b/bin/do_epic/config.py @@ -13,7 +13,7 @@ One pair per machine, the same for every epic (docs/decisions.md → `do-epic: d - `repoless-model` is the model that works an epic item with no repo: a model on the routing ladder, `model_routing/routing-ladder.json`. - `clone-folder` is the folder a missing repo is cloned into: a path that starts with / or ~/. `~/code` where left out. - `language` is the default language of Jira text, by its English name. English where left out. -- `jira-finish-transition` and `jira-finish-status` name the workflow transition that closes a finished epic, such as "Mark as done", and the status it leads to, such as "Done". A project's config names a plan item's the same way. Set both or neither; without them do-epic closes no epic. +- `jira-finish-transition` and `jira-finish-status` name the workflow transition that moves a finished chunk's issue and closes a finished epic, such as "Mark as done", and the status it leads to, such as "Done". A project's config names a plan item's the same way. Set both or neither; without them do-epic moves no issue to done and closes no epic. - `repo-rule.md` is prose that says how to tell an item's repo, and mustn't be blank.""" import dataclasses import pathlib diff --git a/bin/do_epic/main.py b/bin/do_epic/main.py index 5db12731..18748cfe 100644 --- a/bin/do_epic/main.py +++ b/bin/do_epic/main.py @@ -9,9 +9,10 @@ import sys import typing from loop_claude.loop.chunk_start import archived_route, routed -from do_epic import chunk_prompt, findings, finish, gates, human_tasks, parked, scheduler +from do_epic import chunk_prompt, findings, finish, gates, human_tasks, parked, scheduler, split, status from do_epic.repo_pick import ClaudeWork, HumanTask, recorded, Repo from loop_claude.loop.close import closed_cycle +from project_config.main import located as config_located from loop_claude.project.records import CONSEQUENCE, read_records from agent_cycle.run import Cycle, run_cycle from do_epic.config import DoEpicConfig, load @@ -54,7 +55,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 doesn't start any chunk. It prints a line per open issue: that its chunk runs or asks you a question, or why it waits, such as the gate a parked chunk awaits and since when. {findings.HELP} {finish.HELP} The Jira site and its credentials are set in ~/.claude-projects/do-epic/config.toml.""" @@ -111,8 +112,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 closes = chunk is None and words[1:] == [finish.CLOSE] @@ -128,7 +129,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) @@ -136,7 +137,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") @@ -152,7 +153,8 @@ def epic_written(key: str, writes: tuple[str, str, tuple[str, ...]] | None, path 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) @@ -169,11 +171,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. Where no issue is open, the chunk to start is the epic's finishing, unless the epic is closed.""" - 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, read afresh; own is the issue of the chunk that asks. Where no issue is open, the chunk to start is the epic's finishing, unless the epic is closed.""" closed = finish.due(issues) and epic.store.closed() if isinstance(closed, Failure): return closed @@ -309,7 +308,8 @@ def parked_through(repo: str, loop: Loop, epic: EpicRun, starts: bool) -> str | shown = awaits if on is None: # Once the window shows as parked, so the chunks that start count it as running nowhere. - started = chunks_started(epic, key) + issues = epic.store.read() + started = issues if isinstance(issues, Failure) else chunks_started(epic, issues, key) say(f"could not start the next chunk: {started.reason}" if isinstance(started, Failure) else f"started {', '.join(started.started) or 'no other'}", epic.effects, stdout=True) on = now.on if isinstance(now, gates.Gate) else on if stays is not None and stays != said: @@ -355,14 +355,37 @@ def chunk_root(key: str, issue: EpicIssue | None, epic: EpicRun) -> tuple[str, s 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.""" - started = chunks_started(epic, key) + """The stop of a do-epic whose chunk finished. It first moves the chunk's issue to done (the epic's finishing has none), 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.""" + # The epic's finishing has no issue to move: the epic is closed by `--close-epic`. + moved = None if key == epic.key else epic.store.finish_issue(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") + 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] + 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_issue(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, news: str = "") -> 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. news is what `parked_through` tells the worker of a chunk that was parked, and opens its prompt. 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.""" premises = premises_read(loop.root if in_repo else None, epic) @@ -400,7 +423,10 @@ def chunk_work(key: str, checkout: str | None, language: str, epic: EpicRun) -> issue = issue_read(key, epic) if isinstance(issue, Stop): return issue - return chunk_prompt.task(issue, epic.key, checkout, epic.launcher, language), RoutingIssue(issue) if "L" in issue.scores else None + config = config_located(checkout, epic.paths.home) if checkout else None + if isinstance(config, Failure): + return Stop(1, config.reason) + return chunk_prompt.task(issue, epic.key, checkout, epic.launcher, language, config), RoutingIssue(issue) if "L" in issue.scores else None issues = epic.store.read() if isinstance(issues, Failure): return Stop(1, issues.reason) diff --git a/bin/do_epic/scheduler.py b/bin/do_epic/scheduler.py index bae47b19..a8a42647 100644 --- a/bin/do_epic/scheduler.py +++ b/bin/do_epic/scheduler.py @@ -223,23 +223,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.human and chunk.issue in live: - reasons[chunk.issue] = HUMAN_WAIT - 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" + ("" if chunk.human else " 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..be8bfe01 --- /dev/null +++ b/bin/do_epic/status.py @@ -0,0 +1,50 @@ +"""What `do-epic --status` prints: a line per open issue of the epic (docs/decisions.md → `do-epic: drives one Jira epic …`).""" +import datetime +import pathlib + +from do_epic.scheduler import chunks, HUMAN_WAIT, STATE +from do_epic.backend.protocol import EpicIssue +from failure import Failure +from do_epic.parked import file_of, Parked, parked_chunks, SLOT +from agent_cycle import tmux + + +def since(folder: pathlib.Path, chunk: Parked) -> str: + """`, since