diff --git a/CHANGELOG.md b/CHANGELOG.md index 6575311f..f14ace06 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,9 @@ ## Unreleased +- 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. +- A chunk that `do-epic` runs files a finding about an epic goal as an issue of the epic, with `do-epic --file`, and records a decision in the epic's description, with `--record-decision`; its judge reads the epic's Scoring and Decisions before the repo's records. - Added `do-epic `: it runs the chunks of one Jira epic, each in its own window of the tmux session `epic-`. As many run at once as the line `**Max parallel chunks:** 2` in the epic's description allows, one without it; a repo takes as many as its `parallel-chunks`, and none while loop-claude runs chunks in it. loop-claude in turn starts no chunk in a checkout where do-epic runs one. - Refuse in rule-hook a Bash or Monitor command that waits forever: a sleeping loop with no time or count cap, and a `pgrep -f` or `pkill -f` whose pattern its own command line matches. - A project's config may list its team's convention files in `coding-conventions`, which larv-review's reviewer agents read beside the principles and the standards, the team's rule winning where they conflict. larv-review opens the pull request after its own review where a push to the branch starts CI, and files an item to add a mutation tool where `mutate-changes` covers none of a language. The technical principles gain rules for tests on a shared environment, "Never mock a service your own team runs" and "Don't loosen a type when refactoring"; stability-reviewer checks a change that stores a value differently; and every finding of an outside reviewer now changes the setup, a deterministic tool first. diff --git a/README.md b/README.md index 682a76ea..c73785fc 100644 --- a/README.md +++ b/README.md @@ -216,8 +216,8 @@ 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, 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`. +- `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`. - `loop_claude` runs `chunk-preflight` as a process of its own. @@ -237,7 +237,7 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a - `routing_figures/` measures loop-claude's archive, and each of its projects' default branches, for loop-claude's routing calls. - `rung_replay/` holds what `judge_replay` and `review_replay` share: the parallel replay runner, the argument reader, the candidate rungs and the exits, and `judge_replay`'s rung search. It reads `agent_cycle`'s retry count and `loop_claude`'s models file, and finds that file through `loop_state`'s paths. Its `archive.py` keeps each replay's runs and its report in a `replays/` folder of loop-claude's archive. - `test_env.py` serves the tests. -- `text_files/` reads a Markdown file's `##` sections, quotes a passage and joins names into a list, stamps times in UTC, replaces a file in one step, private where it is new, and gzips a file beside its plain name, by which it reads it afterwards. +- `text_files/` reads a Markdown file's `##` sections, quotes a passage and joins names into a list, reads the text piped into a command, stamps times in UTC, replaces a file in one step, private where it is new, and gzips a file beside its plain name, by which it reads it afterwards. - `transcript_archive/` stores loop-claude's transcripts. Its `project_key.py` names each project's archive folder, loop-claude session and models-file entry. ## Test diff --git a/bin/agent_cycle/judge.py b/bin/agent_cycle/judge.py index 993ebf85..3591a649 100644 --- a/bin/agent_cycle/judge.py +++ b/bin/agent_cycle/judge.py @@ -141,6 +141,8 @@ class Brief(typing.NamedTuple): task: str premises: str records: str + # What the records are, in their order, as WorkerPrompts.records_named has it. + records_named: str # Where the worker may record an answer the human typed, as the entry point names it. answer_destinations: str entries: list[Entry] @@ -290,7 +292,7 @@ def judge_prompt(brief: Brief) -> tuple[str, Grounds]: """The prompt, and what the judge's quotes are checked against.""" head = ( f"From the goals file, {brief.premises}\n\n" - f"The records: the project's working rules and decisions, then the human's rules for every project:\n{brief.records or 'none'}\n\n" + f"The records: {brief.records_named}:\n{brief.records or 'none'}\n\n" f"{TASK_HEADING}{brief.task}\n\n" f"{transcript_heading(brief.driver)}" ) diff --git a/bin/agent_cycle/run.py b/bin/agent_cycle/run.py index 98bf2bf8..a836cb47 100644 --- a/bin/agent_cycle/run.py +++ b/bin/agent_cycle/run.py @@ -156,6 +156,7 @@ def rule(cycle: Cycle, transcript_path: str, quoted_answers: int) -> Ruled | Sto task=cycle.task, premises=cycle.premises, records=cycle.records, + records_named=cycle.prompts.records_named, answer_destinations=cycle.prompts.answer_destinations, entries=entries, escalated_at=cycle.route.escalated_at, diff --git a/bin/agent_cycle/tmux.py b/bin/agent_cycle/tmux.py index e3b50631..704caaec 100644 --- a/bin/agent_cycle/tmux.py +++ b/bin/agent_cycle/tmux.py @@ -14,6 +14,8 @@ NEEDED = (3, 2) # What a window's name ends in while its chunk waits for the human. tmux's status bar shows the name, and `!` after it once the bell rang. WAITS = " ?" BELL = "\a" +# What follows a window's name while its chunk is parked, before what its pull request waits on, as in `ABC-34 awaits an approval`. A parked chunk takes no running slot (docs/decisions.md → `do-epic: drives one Jira epic …`, "Long gates"). +PARKED = " awaits " # What a session's name opens with: LOOP for a project's chunks under loop-claude, EPIC for an epic's chunks under do-epic. LOOP = "loop" EPIC = "epic" @@ -41,12 +43,18 @@ class Window: @dataclasses.dataclass(frozen=True) class Listed: """A window of the project's session, as tmux lists it.""" - # Without WAITS. + # Without WAITS, and without PARKED and what follows it. name: str # tmux's ID of the window, such as `@3`. id: str # Whether its loop has exited: `remain-on-exit failed` keeps the window of a loop that failed, so its last lines stay readable. 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 = "" + + @property + def parked(self) -> bool: + return bool(self.awaits) @dataclasses.dataclass(frozen=True) @@ -76,14 +84,20 @@ def listed(session: str, run: Tmux) -> list[Listed]: """The windows of session; none where tmux lists none, as while the session doesn't exist or no tmux server runs.""" done = run(["list-windows", "-t", f"={session}", "-F", "#{window_name}\t#{pane_dead}\t#{window_id}"]) rows = [line.split("\t") for line in done.stdout.splitlines()] if done.returncode == 0 else [] - return [Listed(row[0].removesuffix(WAITS), row[2], row[1] == "1") for row in rows if len(row) == 3] + return [as_listed(row[0], row[2], row[1]) for row in rows if len(row) == 3] + + +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) def everywhere(run: Tmux) -> list[Placed]: """The windows of every session; none where no tmux server runs.""" done = run(["list-windows", "-a", "-F", f"#{{session_name}}\t#{{window_name}}\t#{{pane_dead}}\t#{{window_id}}\t#{{{ROOT}}}"]) rows = [line.split("\t") for line in done.stdout.splitlines()] if done.returncode == 0 else [] - return [Placed(row[0], Listed(row[1].removesuffix(WAITS), row[3], row[2] == "1"), row[4]) for row in rows if len(row) == 5] + return [Placed(row[0], as_listed(row[1], row[3], row[2]), row[4]) for row in rows if len(row) == 5] def start_window(window: Window, cwd: str, env: typing.Mapping[str, str], command: list[str], first: bool, owned: bool, run: Tmux) -> Failure | None: @@ -131,6 +145,17 @@ def mark(window: Window, waits: bool, run: Tmux) -> None: run(["rename-window", "-t", window.pane, window.name + (WAITS if waits else "")]) +def park(window: Window, on: str, run: Tmux) -> None: + """Shows window's chunk as parked. on is what the chunk awaits, such as `an approval` or `a slot`: the name says so, and no checkout counts a window so named as a running chunk.""" + run(["rename-window", "-t", window.pane, window.name + PARKED + on]) + + +def unpark(window: Window, root: str, run: Tmux) -> None: + """Shows window's chunk as running again, in the folder root. The window may name another folder: one started again for a parked chunk starts in the epic's folder.""" + run(["rename-window", "-t", window.pane, window.name]) + run(["set-option", "-w", "-t", window.pane, ROOT, root]) + + def show(session: str, inside: bool) -> list[str]: """The tmux arguments that put session on the human's terminal: inside tmux the client switches to it, and outside a new client attaches.""" return ["switch-client" if inside else "attach-session", "-t", f"={session}"] diff --git a/bin/agent_cycle/worker_prompts.py b/bin/agent_cycle/worker_prompts.py index 25f9c931..9c070afb 100644 --- a/bin/agent_cycle/worker_prompts.py +++ b/bin/agent_cycle/worker_prompts.py @@ -45,6 +45,8 @@ class WorkerPrompts: quote_sources: str # Where the worker may record an answer the human typed. answer_destinations: str + # What the records the judge reads are, in the order it reads them. + records_named: str def answered(self, question: str, answer: str, route: Route, project: ProjectRung | None, stepped: bool) -> str: """stepped is whether the answer's ruling stepped the worker up.""" diff --git a/bin/chunk_pr/approval.py b/bin/chunk_pr/approval.py index a33b08e5..61779af0 100644 --- a/bin/chunk_pr/approval.py +++ b/bin/chunk_pr/approval.py @@ -10,6 +10,8 @@ from forge.commands import Forge, Run # A human answers in hours, so merge polls once a minute and gives up after 90 minutes. That leaves half an hour for the queue and the checks inside the 2 hours a background command may run; a run that needs more is killed before the give-up message prints, and its next run goes on from what it pushed. POLL_SECONDS = 60 WAIT_SECONDS = 90 * 60 +# The environment variable do-epic sets to 1 for its chunks' workers. With it, merge doesn't wait for an approval: do-epic parks the chunk and polls the forge itself, so the chunk holds no running slot meanwhile (docs/decisions.md → `do-epic: drives one Jira epic …`, "Long gates"). +PARKS = "CHUNK_PR_PARKS" def awaited(forge: Forge, wait_for_approval: bool) -> bool | Failure: @@ -58,17 +60,29 @@ def approved(number: str, run: Run, sleep: typing.Callable[[float], None] = time return Failure(f"pull request {number} wasn't approved within {WAIT_SECONDS // 60} minutes; run chunk-pr merge again once it is") +def left_to_park(number: str, run: Run) -> Failure: + """Why a merge under PARKS ends at once where pull request number passed its checks and awaits an approval, in place of waiting as `approved` does: a reviewer's comment waits for an answer, which the worker gives first, or else do-epic parks the chunk, so the worker ends its run.""" + return unanswered(number, run) or Failure(f"pull request {number} passed its checks and awaits an approval; end your run now, since do-epic parks the chunk and resumes this session once it is approved or a reviewer comments") + + def unanswered(number: str, run: Run) -> Failure | None: - """A Failure naming the files where a reviewer's comment waits for an answer on pull request number: a review thread nobody resolved, whose last comment someone other than the pull request's author wrote. So a thread the worker answered, as that author, waits for the reviewer again. None where no thread waits.""" - read = run(["gh", "api", "graphql", "-f", f"query={THREADS}", "-F", "owner={owner}", "-F", "repo={repo}", "-F", f"number={number}"]) - try: - pull = read if isinstance(read, Failure) else json.loads(read)["data"]["repository"]["pullRequest"] - if isinstance(pull, Failure): - return pull - author = pull["author"]["login"] - waiting = sorted({thread["path"] for thread in pull["reviewThreads"]["nodes"] if not thread["isResolved"] and any(comment["author"]["login"] != author for comment in thread["comments"]["nodes"])}) - except (ValueError, KeyError, TypeError): - return Failure(f"gh api graphql printed no review threads: {str(read).strip()[:200]}") + """A Failure naming the files where a reviewer's comment waits for an answer on pull request number, as `waiting_threads` finds them, or saying why they cannot be read. None where no thread waits.""" + waiting = waiting_threads(number, run) + if isinstance(waiting, Failure): + return waiting if not waiting: return None return Failure(f"a reviewer's comment on pull request {number} waits for an answer, in {', '.join(waiting)}; answer it in its thread, push any fix, and run chunk-pr merge again") + + +def waiting_threads(number: str, run: Run) -> list[str] | Failure: + """The files where a reviewer's comment waits for an answer on pull request number, read once: those of each review thread nobody resolved, whose last comment someone other than the pull request's author wrote. So a thread the worker answered, as that author, waits for the reviewer again.""" + read = run(["gh", "api", "graphql", "-f", f"query={THREADS}", "-F", "owner={owner}", "-F", "repo={repo}", "-F", f"number={number}"]) + if isinstance(read, Failure): + return read + try: + pull = json.loads(read)["data"]["repository"]["pullRequest"] + author = pull["author"]["login"] + return sorted({thread["path"] for thread in pull["reviewThreads"]["nodes"] if not thread["isResolved"] and any(comment["author"]["login"] != author for comment in thread["comments"]["nodes"])}) + except (ValueError, KeyError, TypeError): + return Failure(f"gh api graphql printed no review threads: {read.strip()[:200]}") diff --git a/bin/chunk_pr/main.py b/bin/chunk_pr/main.py index 0e91ea6a..158011d7 100644 --- a/bin/chunk_pr/main.py +++ b/bin/chunk_pr/main.py @@ -45,7 +45,8 @@ merge merges the pull request in its turn: the chunks of one project on this Where the project's config sets `wait-for-approval = true` (`project-config --help`), it merges only once GitHub reports the pull request approved as its branch protection requires. It waits for that outside its turn, so other chunks merge meanwhile, and takes - a new turn once approved. + a new turn once approved. In a chunk do-epic runs, which sets CHUNK_PR_PARKS=1, it + fails at once instead of waiting: do-epic parks the chunk until the approval comes. It stops, without merging, and says what to do before running it again: - on a merge conflict in step 1, naming the conflicted files, with the merge in progress; - where `larv-review scoring-run-owed` exits 1 after step 3, because the chunk owes a @@ -85,7 +86,7 @@ import sys import time import typing -from chunk_pr.approval import approval, approved, awaited, unanswered +from chunk_pr.approval import approval, approved, awaited, left_to_park, PARKS, unanswered from forge.pulls import checks_passed, merged_pull, open_pull, required_checks from failure import Failure from forge.commands import Forge, forge_of, gitea, Run, runner @@ -119,7 +120,7 @@ def main(argv: list[str]) -> int: if argv[:1] in (["-h"], ["--help"]): print(__doc__.strip()) return 0 - done = step(argv, runner(os.getcwd()), functools.cache(lambda: located(os.getcwd(), pathlib.Path.home()))) + done = step(argv, runner(os.getcwd()), functools.cache(lambda: located(os.getcwd(), pathlib.Path.home())), os.environ.get(PARKS) == "1") if isinstance(done, Failure): print(f"chunk-pr: {done.reason}", file=sys.stderr) return 1 @@ -127,8 +128,8 @@ def main(argv: list[str]) -> int: return 0 -def step(argv: list[str], run: Run, config: Config) -> str | Failure: - """Run the step argv names: the line to print, or a Failure. A malformed argv doesn't run anything.""" +def step(argv: list[str], run: Run, config: Config, parks: bool = False) -> str | Failure: + """Run the step argv names: the line to print, or a Failure. A malformed argv doesn't run anything. parks is whether a merge fails at once where it would wait for an approval (`merged`).""" match argv: case ["open", title, *body] if len(body) <= 1 and not title.startswith("-"): return Failure("give a title of one line") if not one_line(title) else misfit(title, run, config) or opened(title, body[0] if body else "", run) @@ -138,7 +139,7 @@ def step(argv: list[str], run: Run, config: Config) -> str | Failure: return Failure("give a title of one line") if title and not one_line(title[0]) else (misfit(title[0], run, config) if title else None) or marked_ready(run, title[0] if title else None) case ["merge", *given]: finishes = finishes_of(given) - return Failure(USAGE) if finishes is None else merged(run, config, finishes=finishes) + return Failure(USAGE) if finishes is None else merged(run, config, finishes=finishes, parks=parks) case ["clean"]: return cleaned(run) return Failure(USAGE) @@ -304,8 +305,8 @@ def finishes_of(given: list[str]) -> list[list[str]] | None: return finishes -def merged(run: Run, config: Config, sleep: typing.Callable[[float], None] = time.sleep, finishes: typing.Sequence[list[str]] = ()) -> str | Failure: - """Merge the branch's pull request in the project's merge queue. Each pass of the loop is one turn in the queue; a pull request that still wants its approval leaves the queue while it waits, so the next chunk merges meanwhile, and takes a new turn once approved.""" +def merged(run: Run, config: Config, sleep: typing.Callable[[float], None] = time.sleep, finishes: typing.Sequence[list[str]] = (), parks: bool = False) -> str | Failure: + """Merge the branch's pull request in the project's merge queue. Each pass of the loop is one turn in the queue; a pull request that still wants its approval leaves the queue while it waits, so the next chunk merges meanwhile, and takes a new turn once approved. Where parks, it doesn't wait for the approval: it fails at once, as `left_to_park` says.""" found = pull(run) if isinstance(found, Failure): return found @@ -336,6 +337,8 @@ def merged(run: Run, config: Config, sleep: typing.Callable[[float], None] = tim taken = untaken or merge_turn(pull_request, finishes, loaded, run, sleep) if not isinstance(taken, AwaitsApproval): return taken if isinstance(taken, Failure) else taken + absent + if parks: + return left_to_park(number, run) # Out of the queue, so the project's other chunks merge while this one waits. waited = approved(number, run, sleep) if isinstance(waited, Failure): diff --git a/bin/chunk_pr/test_chunk_pr.py b/bin/chunk_pr/test_chunk_pr.py index a8ceafa1..41ca75df 100644 --- a/bin/chunk_pr/test_chunk_pr.py +++ b/bin/chunk_pr/test_chunk_pr.py @@ -377,6 +377,26 @@ class Merge(unittest.TestCase): self.assertEqual(merged(checkout, checkout.config, slept.append), "Merged pull request #12 (merge).") self.assertEqual(slept, [60]) + def test_a_merge_that_parks_returns_at_once_while_the_branch_protection_still_wants_a_review(self): + checkout = self.requiring_approval(GITHUB, "REVIEW_REQUIRED") + failed = merged(checkout, checkout.config, self.fail, parks=True) + self.assertEqual(failed.reason, "pull request 12 passed its checks and awaits an approval; end your run now, since do-epic parks the chunk and resumes this session once it is approved or a reviewer comments") + self.assertEqual(checkout.ran.count(GH_DECISION), 1) + self.assertEqual(step(["merge"], self.requiring_approval(GITHUB, "REVIEW_REQUIRED"), checkout.config, parks=True), failed) + + def test_a_merge_that_parks_reports_a_reviewers_unanswered_comment_before_the_approval_it_awaits(self): + checkout = self.requiring_approval(GITHUB, "REVIEW_REQUIRED") + checkout.threads = [MergeQueue.thread("bin/asked.py", "reviewer")] + failed = merged(checkout, checkout.config, self.fail, parks=True) + self.assertEqual(failed.reason, "a reviewer's comment on pull request 12 waits for an answer, in bin/asked.py; answer it in its thread, push any fix, and run chunk-pr merge again") + checkout = self.requiring_approval(GITHUB, "REVIEW_REQUIRED") + checkout.answers[tuple(GH_THREADS)] = Failure("gh api graphql failed") + self.assertEqual(merged(checkout, checkout.config, self.fail, parks=True), Failure("gh api graphql failed")) + + def test_a_merge_that_parks_merges_an_approved_pull_request(self): + checkout = self.requiring_approval() + self.assertEqual(merged(checkout, checkout.config, self.fail, parks=True), "Merged pull request #12 (merge).") + def test_an_approval_that_never_comes_leaves_it_unmerged_after_90_minutes(self): checkout = self.requiring_approval(GITHUB, "REVIEW_REQUIRED") slept: list[float] = [] diff --git a/bin/do_epic/backend/contract.py b/bin/do_epic/backend/contract.py index d9da553a..9786e2f0 100644 --- a/bin/do_epic/backend/contract.py +++ b/bin/do_epic/backend/contract.py @@ -131,21 +131,21 @@ class EpicStoreContract: 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([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(task)) + 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("ZZZ-1"), Failure) - self.assertIsInstance(store.finish("not a key"), Failure) + 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: @@ -164,6 +164,14 @@ class EpicStoreContract: self.assertIsInstance(store.comment("ZZZ-1", "Hello."), Failure) self.assertEqual([self.comments_on(store, key) for key in (child, task)], [[], []]) + def test_closes_the_epic_once_its_summary_is_posted_and_refuses_a_blank_one(self) -> None: + store = self.new_store() + self.assertEqual(store.closed(), False) + self.assertIsInstance(store.close(" \n"), Failure) + self.assertEqual((store.closed(), self.comments_on(store, "ABC-12")), (False, [])) + self.assertEqual(store.close("## Shipped\n\nThe import.\n"), None) + self.assertEqual((store.closed(), self.comments_on(store, "ABC-12")), (True, ["## Shipped\n\nThe import."])) + def test_reads_an_issue_without_scores_or_blockers_as_one_with_none(self) -> None: store = self.new_store() key = self.filed(store, store.epic_key, "Count the runs.") diff --git a/bin/do_epic/backend/fake.py b/bin/do_epic/backend/fake.py index aed059a9..4d2a3e01 100644 --- a/bin/do_epic/backend/fake.py +++ b/bin/do_epic/backend/fake.py @@ -7,11 +7,12 @@ from failure import Failure @dataclasses.dataclass class MemoryEpic: - """An epic whose issues rank in the order filed, until one is ranked. Where fails is set, every read, filing, label, comment, rank and finish 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, 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) fails: str | None = None + done: bool = False def read(self) -> list[EpicIssue] | Failure: if self.fails: @@ -60,7 +61,19 @@ class MemoryEpic: self.comments.setdefault(key, []).append(text.strip()) return None - def finish(self, key: str) -> None | Failure: + def closed(self) -> bool | Failure: + return Failure(self.fails) if self.fails else self.done + + def close(self, summary: str) -> None | Failure: + if self.fails: + return Failure(self.fails) + if refused := no_words(summary): + return refused + self.comments.setdefault(self.epic_key, []).append(summary.strip()) + self.done = True + return None + + def 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} diff --git a/bin/do_epic/backend/jira.py b/bin/do_epic/backend/jira.py index bca9c36b..33cad807 100644 --- a/bin/do_epic/backend/jira.py +++ b/bin/do_epic/backend/jira.py @@ -5,15 +5,15 @@ 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, JIRA_FINISH_TRANSITION +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 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" +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" @@ -26,14 +26,13 @@ class Found: @dataclasses.dataclass(frozen=True) class JiraEpic: - """The issues of a Jira epic, read and filed with the credentials env_file holds.""" + """The issues of a Jira epic, read and filed with the credentials env_file holds. finish says how the epic itself closes; None where the machine's settings don't say.""" epic: Epic env_file: pathlib.Path http: Http = jira_json to_markdown: ToMarkdown = adfs_to_markdown to_adf: ToAdf = markdown_to_adf - # The name of the transition to finish an issue by, where its status offers several to a done status. - finish_by: str | None = None + finish: Finish | None = None @property def epic_key(self) -> str: @@ -119,7 +118,41 @@ 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: + def closed(self) -> bool | Failure: + authorization = basic_auth(self.env_file) + if isinstance(authorization, Failure): + return authorization + answered = self.http("GET", f"{self.epic.site}/rest/api/3/issue/{self.epic_key}?fields=status", authorization, None) + if isinstance(answered, Failure): + return Failure(f"cannot read {self.epic_key}'s status: {answered.reason}") + try: + category = answered["fields"]["status"]["statusCategory"]["key"] # type: ignore[index] + except (KeyError, TypeError) as failure: + return Failure(f"{self.epic_key}'s status is not in the shape Jira Cloud's REST API version 3 documents: {failure!r}") + return bool(category == "done") + + def close(self, summary: str) -> None | Failure: + if self.finish is None: + return Failure(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 + if refused := no_words(summary): + return refused + body = self.to_adf(summary) + if isinstance(body, Failure): + return Failure(f"cannot convert the summary to a Jira comment: {body.reason}") + # The transition is read before the comment is posted, so an epic that cannot move gets no summary. + transition = finishing_transition(self.epic.site, self.epic_key, self.finish, authorization, self.http) + if isinstance(transition, Failure): + return transition + posted = self.http("POST", f"{self.epic.site}/rest/api/3/issue/{self.epic_key}/comment", authorization, {"body": body}) + if isinstance(posted, Failure): + return Failure(f"cannot comment on {self.epic_key}: {posted.reason}") + refused_move = move_refusal(self.epic.site, self.epic_key, transition, self.finish, authorization, self.http) + return Failure(f"posted the summary on {self.epic_key}, but {refused_move}; close the epic in Jira rather than posting the summary again") if refused_move else None + + def finish_issue(self, key: str) -> None | Failure: authorization = basic_auth(self.env_file) if isinstance(authorization, Failure): return authorization @@ -135,15 +168,13 @@ class JiraEpic: 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, self.finish_by) + 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 - moved = self.http("POST", url, authorization, {"transition": {"id": transition}}) - return Failure(f"cannot move {key} to done: {moved.reason}; {PERHAPS_MOVED.format(key=key)}") if isinstance(moved, Failure) else None + 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.""" @@ -210,25 +241,6 @@ 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, 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] - 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) - 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") - 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 "") + ": 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: """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 a1fe8d39..516b2300 100644 --- a/bin/do_epic/backend/protocol.py +++ b/bin/do_epic/backend/protocol.py @@ -63,10 +63,17 @@ 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: + 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.""" + + def close(self, summary: str) -> None | Failure: + """Posts summary, markdown, as a comment on the epic, then moves the epic to a status the tracker counts as done. Before anything is posted, it refuses a blank summary, and an epic the tracker cannot move to such a status. Where the move fails after the comment is posted, the Failure says so.""" + + def unfit(summary: str, labels: tuple[str, ...]) -> Failure | None: """Why no tracker can file an issue with this summary and these labels; None where a tracker can file it.""" if not summary.strip() or "\n" in summary: diff --git a/bin/do_epic/backend/test_fake.py b/bin/do_epic/backend/test_fake.py index 5ead58c9..46703529 100644 --- a/bin/do_epic/backend/test_fake.py +++ b/bin/do_epic/backend/test_fake.py @@ -55,14 +55,14 @@ 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.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("ZZZ-1"), Failure("ZZZ-1 is not one of the child issues of the epic ABC-12, so it cannot be finished")) + 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("ABC-100"), Failure("Jira is down")) + self.assertEqual(MemoryEpic("ABC-12", fails="Jira is down").finish_issue("ABC-100"), Failure("Jira is down")) if __name__ == "__main__": diff --git a/bin/do_epic/backend/test_jira.py b/bin/do_epic/backend/test_jira.py index 802833fa..762ab246 100644 --- a/bin/do_epic/backend/test_jira.py +++ b/bin/do_epic/backend/test_jira.py @@ -9,7 +9,7 @@ import unittest.mock sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2])) -from project_config.settings import Epic +from project_config.settings import Epic, Finish from do_epic.backend.contract import EpicStoreContract from failure import Failure from plan_store import jira_epic @@ -24,8 +24,11 @@ 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"}} +DONE = {"name": "Done", "statusCategory": {"key": "done"}} +TRANSITIONS = f"{ISSUES}/ABC-12/transitions" +EPIC_COMMENT = f"{ISSUES}/ABC-12/comment" +EPIC_STATUS = f"{ISSUES}/ABC-12?fields=status" TYPES = {"issueTypes": [{"id": "10001", "name": "Task", "subtask": False}, {"id": "10003", "name": "Subtask", "subtask": True}]} @@ -49,6 +52,8 @@ class FakeJira: 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)) def __call__(self, method: str, url: str, authorization: str, body: object) -> object: self.calls.append((method, url)) @@ -58,6 +63,18 @@ class FakeJira: return self.answers[method, url] if method == "GET" and url == EPIC_URL: return {"key": "ABC-12"} + if method == "GET" and url == EPIC_STATUS: + return {"key": "ABC-12", "fields": {"status": self.epic_status}} + if method == "GET" and url == TRANSITIONS: + return {"transitions": [] if self.epic_status == DONE else [{"id": "31", "name": "Mark as done", "to": DONE}, {"id": "21", "name": "Start", "to": {"name": "In Progress", "statusCategory": {"key": "indeterminate"}}}]} + if method == "POST" and url == TRANSITIONS: + assert body == {"transition": {"id": "31"}}, body + self.epic_status = DONE + return None + if method == "POST" and url == EPIC_COMMENT: + assert isinstance(body, dict) + self.comments.setdefault("ABC-12", []).append(body["body"]) + return {"id": "1"} if method == "GET" and url == ISSUE_TYPES: return TYPES if method == "POST" and url == SEARCH: @@ -140,7 +157,7 @@ class Case(unittest.TestCase): self.jira = FakeJira() def new_store(self) -> JiraEpic: - return JiraEpic(EPIC, self.env_file, self.jira, to_markdown, to_adf) + return JiraEpic(EPIC, self.env_file, self.jira, to_markdown, to_adf, Finish("Mark as done", "Done")) class JiraEpicContract(Case, EpicStoreContract): @@ -166,52 +183,73 @@ class JiraEpicContract(Case, EpicStoreContract): class Jira(Case): - def test_finishes_an_issue_by_the_one_transition_that_leads_to_a_done_status(self) -> None: + def test_closes_the_epic_by_the_transition_the_settings_name_after_the_summary(self) -> None: + self.assertEqual(self.new_store().close("Shipped."), None) + self.assertEqual(self.jira.calls[-3:], [("GET", TRANSITIONS), ("POST", EPIC_COMMENT), ("POST", TRANSITIONS)]) + + def test_posts_no_summary_on_an_epic_it_cannot_close(self) -> None: + unnamed = JiraEpic(EPIC, self.env_file, self.jira, to_markdown, to_adf) + wrong_status = JiraEpic(EPIC, self.env_file, self.jira, to_markdown, to_adf, Finish("Start", "Done")) + no_such = JiraEpic(EPIC, self.env_file, self.jira, to_markdown, to_adf, Finish("Close", "Done")) + unconverted = JiraEpic(EPIC, self.env_file, self.jira, to_markdown, lambda markdown: Failure("adf-codec refused it"), Finish("Mark as done", "Done")) + for store, reason in ( + (unnamed, "do-epic's settings name no transition to close an epic by: set `jira-finish-transition` and `jira-finish-status` in ~/.claude-projects/do-epic/config.toml, to the names Jira shows, such as \"Mark as done\" and \"Done\""), + (wrong_status, "ABC-12's transition 'Start' leads to the status 'In Progress', not to 'Done', which `jira-finish-status` names"), + (unconverted, "cannot convert the summary to a Jira comment: adf-codec refused it"), + ): + self.assertEqual(store.close("Shipped."), Failure(reason)) + refused = no_such.close("Shipped.") + assert isinstance(refused, Failure) + self.assertIn("ABC-12 has no transition 'Close' from its status", refused.reason) + self.jira.answers[("GET", TRANSITIONS)] = Failure("Jira answered 503") + self.assertEqual(self.new_store().close("Shipped."), Failure("cannot read ABC-12's transitions: Jira answered 503")) + self.assertEqual((self.jira.comments, self.jira.epic_status), ({}, TO_DO)) + + def test_says_what_was_posted_where_the_comment_or_the_move_fails(self) -> None: + self.jira.answers[("POST", EPIC_COMMENT)] = Failure("Jira answered 503") + self.assertEqual(self.new_store().close("Shipped."), Failure("cannot comment on ABC-12: Jira answered 503")) + self.assertEqual(self.jira.epic_status, TO_DO) + del self.jira.answers[("POST", EPIC_COMMENT)] + self.jira.answers[("POST", TRANSITIONS)] = Failure("Jira answered 503") + self.assertEqual(self.new_store().close("Shipped."), Failure("posted the summary on ABC-12, but cannot move ABC-12 by 'Mark as done': Jira answered 503; close the epic in Jira rather than posting the summary again")) + + def test_says_why_the_epics_status_cannot_be_read(self) -> None: + for answer, reason in ((Failure("Jira answered 503"), "cannot read ABC-12's status: Jira answered 503"), ({"fields": {}}, "ABC-12's status is not in the shape Jira Cloud's REST API version 3 documents: KeyError('status')"), (["ABC-12"], "ABC-12's status is not in the shape Jira Cloud's REST API version 3 documents: TypeError('list indices must be integers or slices, not str')")): + self.jira.answers[("GET", EPIC_STATUS)] = answer + self.assertEqual(self.new_store().closed(), Failure(reason)) + + def test_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(key)) + self.assertIsNone(store.finish_issue(key)) self.assertEqual(self.jira.calls[-1], ("POST", f"{ISSUES}/{key}/transitions")) - self.assertEqual(self.jira.issues[0]["fields"]["status"], DONE) # type: ignore[index] + self.assertEqual((self.jira.transitioned, self.jira.issues[0]["fields"]["status"]), (["31"], 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_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"}}} - 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}"), - (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, named=named): - self.jira.workflow = workflow # type: ignore[assignment] - 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: + 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, "Close").finish(key)) - self.assertEqual(self.jira.calls[-1], ("POST", f"{ISSUES}/{key}/transitions")) + 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_finishes_by_the_one_transition_to_a_done_status_whatever_name_the_config_gives(self) -> None: + 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.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"]) + 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() @@ -220,35 +258,35 @@ class Jira(Case): 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.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(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")) + 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(key), Failure(f"cannot read {key}'s transitions: 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(key), Failure(f"Jira answered {key}'s transitions in a shape other than the one it documents")) + 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(task), Failure(f"cannot read {task} to finish it: 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(task), Failure(f"cannot read {child} to finish its sub-task: 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() diff --git a/bin/do_epic/chunk_prompt.py b/bin/do_epic/chunk_prompt.py index 3de4876d..2d1f08fa 100644 --- a/bin/do_epic/chunk_prompt.py +++ b/bin/do_epic/chunk_prompt.py @@ -1,17 +1,24 @@ -"""What a do-epic cycle's worker is told: its task, from the issue, and its first prompt. The resumed prompt and the rung sentences are the ones loop-claude's cycles use, naming do-epic.""" +"""What a do-epic cycle's worker is told: its task, from the issue, and its first prompt. The resumed prompt and the rung sentences are the ones loop-claude's cycles use, naming do-epic; a chunk that was parked is first told why it resumes, and one whose task follows the epic's state is told that task as it resumes.""" +import dataclasses + from do_epic.backend.protocol import EpicIssue +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 model_routing.ladder import ProjectRung from loop_claude.cycle import prompts from model_routing.route import Route +from agent_cycle.worker_prompts import WorkerPrompts # The entry point's name as the worker, the judge and the human read it. DRIVER = "do-epic" -def task(issue: EpicIssue, epic: str, checkout: str | 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.""" +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.""" 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}. 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}. {findings.instructions(epic, launcher, language)} Its summary: {issue.summary}" + (f"\n\nIts description:\n\n{issue.detail}" if issue.detail else "") CODE_HEALTH = '~/.claude/CLAUDE.md → "Shared goal"' @@ -25,4 +32,24 @@ def fresh(task: str, premises: str, route: Route, project: ProjectRung | None, f # The worker names no plan items: the chunk's one item is its issue. -WORKER = prompts.worker_prompts(DRIVER, fresh, "") +# The epic's records come first, as its goals do; a chunk without a repo is handed only those and the human's rules, so the names that mention a repo's then name nothing it reads. +NAMES = prompts.RecordNames( + quote_sources=listed(("the epic's description", "the repo's goals file's Goals and Audience", *RECORD_FILES, *HUMAN_RULE_NAMES), "or"), + answer_destinations="the epic's description under ## Decisions, the repo's goals file's Goals or Audience, " + ", ".join(RECORD_FILES) + ", the repo's plan or a comment", + records_named="the epic's scoring and decisions, then the repo's working rules and decisions, then the human's rules for every project", +) +WORKER = prompts.worker_prompts(DRIVER, fresh, "", NAMES) + +# What a worker does with a reviewer's feedback, as the decision asks (docs/decisions.md → `do-epic: drives one Jira epic …`, "Long gates"). +FEEDBACK = 'Where a reviewer left feedback, fix what is reasonable and push the fix, answer each other comment in its thread, and change the setup so our review would have caught the finding (~/.claude/CLAUDE.md → "Working loop", "Change the setup for each finding an outside reviewer raises on a PR, deterministic tools first"). Then merge the pull request as before.' + + +def unparked(news: str) -> WorkerPrompts: + """The prompts of the first cycle after a parked chunk resumes: WORKER's, with each prompt that starts a worker opening with news, which says what the chunk waited on and what changed. The fresh prompt opens with it too, since a chunk the judge ruled finished before it parked has no session left to resume.""" + opening = f"{news} {FEEDBACK}\n\n" + return dataclasses.replace(WORKER, fresh=lambda *task: opening + WORKER.fresh(*task), resumed=lambda *evidence: opening + WORKER.resumed(*evidence)) + + +def restating(task: str) -> WorkerPrompts: + """WORKER for a chunk whose task follows the epic's state, as its finishing's does: the prompt that resumes its worker states task, which may not be the one its session began with.""" + return dataclasses.replace(WORKER, resumed=lambda *evidence: f"{WORKER.resumed(*evidence)}\n\nThe task follows the epic's state, so it may have changed since you began. It is now:\n\n{task}") diff --git a/bin/do_epic/config.py b/bin/do_epic/config.py index 94459ab6..f3852832 100644 --- a/bin/do_epic/config.py +++ b/bin/do_epic/config.py @@ -7,21 +7,21 @@ 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. +- `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. - `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, JIRA_FINISH_TRANSITION, LANGUAGE, language_fault, lies_in, name_of, parsed, PROJECTS, SITE +from project_config.settings import anywhere, CONFIG, DO_EPIC, ENV_FILE, Finish, finish_faults, finish_of, JIRA_FINISH, LANGUAGE, language_fault, lies_in, parsed, PROJECTS, SITE from failure import Failure +from text_files.markdown_text import listed from model_routing.ladder_file import read_ladder, SHIPPED REPO_RULE = "repo-rule.md" @@ -30,8 +30,8 @@ JIRA_URL = "jira-url" REPOLESS_MODEL = "repoless-model" CLONE_FOLDER = "clone-folder" SETTINGS = (JIRA_URL, ENV_FILE, REPOLESS_MODEL) -OPTIONAL = (CLONE_FOLDER, LANGUAGE, JIRA_FINISH_TRANSITION) -LISTED = f"The settings are {', '.join(SETTINGS)}, and optionally {' and '.join(OPTIONAL)}." +OPTIONAL = (CLONE_FOLDER, LANGUAGE, *JIRA_FINISH) +LISTED = f"The settings are {', '.join(SETTINGS)}, and optionally {listed(OPTIONAL, 'and')}." @dataclasses.dataclass(frozen=True) @@ -44,8 +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 + # How a finished epic closes; None where the config doesn't say. + finish: Finish | None = None def load(home: pathlib.Path, ladder_file: pathlib.Path = SHIPPED) -> DoEpicConfig | Failure: @@ -67,7 +67,6 @@ 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), @@ -77,12 +76,12 @@ 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 []), + *finish_faults(values), *([rule.reason] if isinstance(rule, Failure) else [f"`{REPO_RULE}` is blank"] if not rule.strip() else []), ] if faults: return Failure(f"{folder}: {'; '.join(faults)}. {LISTED}") # Without a fault, each value above is present and of the type asserted here. assert clone_folder and env_file and isinstance(url, str) and isinstance(model, str) and isinstance(language, str) and isinstance(rule, str) - return DoEpicConfig(folder, url, env_file, clone_folder, language, model, rule, name_of(finish)) + return DoEpicConfig(folder, url, env_file, clone_folder, language, model, rule, finish_of(values)) diff --git a/bin/do_epic/epic_record.py b/bin/do_epic/epic_record.py index fb302034..736e1bc8 100644 --- a/bin/do_epic/epic_record.py +++ b/bin/do_epic/epic_record.py @@ -89,6 +89,19 @@ def with_language(text: str, language: str) -> str | Failure: return line + "\n" + "\n" * bool(text.strip()) + text +def decision_titled(decisions: str, title: str) -> str | None: + """The entry under the ### title heading of decisions, a ## Decisions section's body; None where it has no such heading.""" + found: list[str] | None = None + for line, fenced in fenced_lines(decisions): + if not fenced and line.startswith("### "): + if found is not None: + break + found = [] if line[4:].strip() == title else None + elif found is not None: + found.append(line) + return None if found is None else "\n".join(found).strip() + + @dataclasses.dataclass(frozen=True) class EpicRecord: """One epic's record, kept in its description.""" @@ -110,6 +123,28 @@ class EpicRecord: """Writes body as the ## name section. approved says the human approved the change in an interrupt, which Goals and Audience need.""" return self.written(lambda text: with_section(text, name, body), frozenset({name}) if approved else frozenset()) + def append_decision(self, title: str, entry: str) -> bool | Failure: + """Adds entry under a ### title heading at the end of ## Decisions, leaving the decisions before it as they are. False where the section already holds that entry under that title, so recording a decision twice keeps one; a Failure where it holds another entry under it, so one title names one decision.""" + title, entry = title.strip(), entry.strip() + if not title or "\n" in title: + return Failure("the title must be one line of text") + if not entry: + return Failure("pipe the decision's text in") + held = self.description.held() + if isinstance(held, Failure): + return held + before = read_section(held.text, "Decisions") + if isinstance(before, Failure): + return before + same = decision_titled(before, title) + if same is not None: + return False if same == entry else Failure(f"## Decisions already holds another decision titled {title!r}: give this one a title of its own") + text = with_section(held.text, "Decisions", f"{before}\n\n### {title}\n\n{entry}".strip()) + if isinstance(text, Failure): + return text + wrote = dataclasses.replace(self.description, approved=frozenset()).write(text, held.version) + return wrote if isinstance(wrote, Failure) else True + def write_language(self, language: str) -> Held | Failure: return self.written(lambda text: with_language(text, language), frozenset()) diff --git a/bin/do_epic/findings.py b/bin/do_epic/findings.py new file mode 100644 index 00000000..92336512 --- /dev/null +++ b/bin/do_epic/findings.py @@ -0,0 +1,90 @@ +"""What a chunk's worker writes into its epic: a finding, filed as an issue, and a decision, appended to the description. + +A finding about one of the epic's goals is filed in the epic, and one about a repo's goals by that repo's rules (docs/decisions.md → `do-epic: drives one Jira epic …` → "Findings"). A decision that governs the epic goes under the description's ## Decisions, where the judge of each later chunk reads it.""" +import contextlib +import fcntl +import pathlib +import typing + +from do_epic.repo_pick import CLAUDE_LABEL, HUMAN_LABEL, of_label, REPO_PREFIX, REVIEW_LABEL +from do_epic.epic_record import EpicRecord +from do_epic.backend.protocol import EpicStore +from failure import Failure +from text_files.markdown_text import listed +from text_files.piped_text import piped + +# Three readers, seated as the human and as a chunk's worker, picked each spelling from four: ` --file` over `--file `, `add` and `--finding`, and `--record-decision` over `--decision` and `--decide`. +FILE = "--file" +LABEL = "--label" +RECORD_DECISION = "--record-decision" +# The labels that say where an issue is worked, as do-epic's scheduler reads them. +LABELS = f"`{REPO_PREFIX}` for the repo that works it, `{CLAUDE_LABEL}` for work of Claude's that changes no repo, or `{HUMAN_LABEL}` for a task of the human's" +# Under the epic's folder, the file a do-epic holds locked while it appends a decision. +DECISIONS_LOCK = "decisions.lock" +USAGE = f"""do-epic {FILE} [{LABEL}