Files

1422 lines
95 KiB
Python

import contextlib
import dataclasses
import io
import json
import pathlib
import shutil
import subprocess
import sys
import tempfile
import typing
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from do_epic import chunk_prompt, main, planning
from chunk_driver.chunk_run import ChunkRun
from project_config.doubles import configured
from do_epic.config import DoEpicConfig
from project_config.settings import Epic, Finish
from do_epic.epic_record import EpicRecord
from agent_cycle import escalation_mark, judge, tmux
from failure import Failure
from loop_effects.doubles import FakeEffects, judged, Worker
from do_epic.test_gates import Forge
from do_epic.test_scheduler import issue
from chunk_driver.this_loop import Loop
from do_epic.backend.fake import MemoryEpic
from do_epic import parked
from loop_state.paths import paths_from
from text_files.file_writes import replace_file
from model_routing.route import Route
from model_routing.ladder import Rung
from do_epic.test_do_epic import SETTINGS
from do_epic.backend.jira_start import Start
DESCRIPTION = "**Max parallel chunks:** 2\n\n## Goals\nShip the import.\n\n## Audience\nThe client's team.\n"
def structured(output: object, key: str | None = "structured_output") -> subprocess.CompletedProcess[str]:
"""claude's reply that holds output as its structured answer. Where key is None, output is the whole result event."""
return subprocess.CompletedProcess([], 0, json.dumps({"type": "result", key: output} if key else output), "")
@dataclasses.dataclass(frozen=True)
class Description:
"""Stands in for an epic's description in Jira."""
text: str | Failure
def read(self) -> str | Failure:
return self.text
class DoEpicTest(unittest.TestCase):
def setUp(self) -> None:
made = tempfile.TemporaryDirectory()
self.addCleanup(made.cleanup)
self.home = pathlib.Path(made.name).resolve()
folder = self.home / ".claude-projects" / "do-epic"
folder.mkdir(parents=True)
(folder / "config.toml").write_text(SETTINGS, encoding="utf-8")
(folder / "repo-rule.md").write_text("A label that equals a repo's name names that repo.\n", encoding="utf-8")
self.issues = [issue("ABC-20", "do-epic-human"), dataclasses.replace(issue("ABC-21", "do-epic-claude"), detail="Tidy the docs.", scores={"L": 3, "E": 2, "I": 3})]
self.description: str | Failure = DESCRIPTION
# What the forge answers each read of a chunk's gate, in turn; the last answers every later read. No worktree has the chunk's branch, so no chunk parks.
self.forges = [Forge(worktrees="worktree /code/api\nbranch refs/heads/main\n")]
self.gate_reads = 0
def forge_at(self, folder: str):
def run(command: list[str]) -> str | Failure:
# A read of a gate opens with the checkout's worktrees.
self.gate_reads += command[:2] == ["git", "worktree"]
return self.forges[min(self.gate_reads, len(self.forges)) - 1].at(folder)(command)
return run
def backend(self, config: object, key: str) -> tuple[MemoryEpic, EpicRecord]:
return MemoryEpic(key, list(self.issues)), EpicRecord(Description(self.description)) # type: ignore[arg-type]
def worker(self) -> Worker:
return Worker(paths_from(self.home).claude_code_transcripts.parent)
def repo_chunk(self) -> pathlib.Path:
"""Makes ABC-20 the one issue, a chunk in the repo api whose checkout holds its premises; the folder of the repo's config."""
checkout = self.home / "code" / "api"
folder = configured(self, checkout, home=self.home)
(checkout / "README.md").write_text("## Goals\nServe the API.\n\n## Audience\nIts callers.\n", encoding="utf-8")
self.issues = [issue("ABC-20", "repo:api")]
return folder
def epic_run(self, fake: FakeEffects, env: dict[str, str] | None = None) -> main.EpicRun:
config = main.load(self.home)
assert not isinstance(config, Failure)
store, record = self.backend(config, "ABC-12")
return main.EpicRun("ABC-12", config, store, record, paths_from(self.home), env or {}, pathlib.Path("/b/do-epic"), fake.effects())
def run_main(self, argv: list[str], fake: FakeEffects, env: dict[str, str] | None = None) -> tuple[int, str, str]:
out, err = io.StringIO(), io.StringIO()
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
code = main.main(argv, env or {}, paths_from(self.home), pathlib.Path("/b/do-epic"), fake.effects(), self.backend, forge_at=self.forge_at)
return code, out.getvalue(), err.getvalue()
class TheJiraBackend(unittest.TestCase):
def test_reads_the_epic_with_the_credentials_and_the_finish_the_config_names(self) -> None:
config = DoEpicConfig(pathlib.Path("/c"), "https://acme.atlassian.net", pathlib.Path("/h/jira.env"), pathlib.Path("/h/code"), "English", "claude-opus-5-5", "rule", Finish("Mark as done", "Done"))
store, record = main.jira_backend(config, "ABC-12")
self.assertEqual((store.epic, store.env_file, store.finish), (Epic("https://acme.atlassian.net", "ABC-12"), pathlib.Path("/h/jira.env"), Finish("Mark as done", "Done"))) # type: ignore[attr-defined]
self.assertEqual((record.description.epic, record.description.env_file), (store.epic, store.env_file)) # type: ignore[attr-defined]
def test_starts_an_issue_as_the_config_says(self) -> None:
config = DoEpicConfig(pathlib.Path("/c"), "https://acme.atlassian.net", pathlib.Path("/h/jira.env"), pathlib.Path("/h/code"), "English", "claude-opus-5-5", "rule", start=Start("In Progress", 6))
store, _ = main.jira_backend(config, "ABC-12")
self.assertEqual(store.start, Start("In Progress", 6)) # type: ignore[attr-defined]
def test_files_the_issue_types_the_config_names(self) -> None:
config = DoEpicConfig(pathlib.Path("/c"), "https://acme.atlassian.net", pathlib.Path("/h/jira.env"), pathlib.Path("/h/code"), "English", "claude-opus-5-5", "rule", finding_type="Feature", review_type="Chore")
store, _ = main.jira_backend(config, "ABC-12")
self.assertEqual((store.finding_type, store.review_type), ("Feature", "Chore")) # type: ignore[attr-defined]
class TheLauncher(unittest.TestCase):
def test_the_repo_ships_a_do_epic_that_prints_its_help(self) -> None:
launcher = pathlib.Path(__file__).resolve().parents[1] / "do-epic"
ran = subprocess.run([str(launcher), "--help"], capture_output=True, text=True, timeout=60)
self.assertEqual((ran.returncode, ran.stdout.split(" ", 2)[2]), (0, main.HELP + "\n"))
tracked = subprocess.run(["git", "ls-files", "--error-unmatch", launcher.name], capture_output=True, cwd=launcher.parent)
self.assertEqual(tracked.returncode, 0, "bin/do-epic is not in the repo; .gitignore lists what it keeps")
class TheCommand(DoEpicTest):
def test_prints_the_help_for_anything_but_one_epic_key(self) -> None:
for argv, code in ((["--help"], 0), (["-h"], 0), ([], 1), (["abc"], 1), (["ABC-12", "ABC-13"], 1), (["--chunk", "x", "ABC-12"], 1), (["--chunk", "ABC-12"], 1)):
with self.subTest(argv=argv):
ran_code, out, err = self.run_main(argv, FakeEffects())
self.assertEqual((ran_code, (err if code else out).split(" ", 1)[1]), (code, main.HELP + "\n"))
def test_refuses_a_tmux_too_old_naming_do_epic(self) -> None:
code, _, err = self.run_main(["ABC-12"], FakeEffects(tmux_version="tmux 3.1"))
self.assertEqual(code, 1)
self.assertIn("do-epic runs each chunk in a tmux window, and needs tmux 3.2 or later; it found tmux 3.1", err)
def test_starts_the_chunks_and_says_why_each_other_issue_waits(self) -> None:
fake = FakeEffects(on_terminal=False)
code, out, _ = self.run_main(["ABC-12"], fake, {"LOOP_CLAUDE_WORKER_MODEL": "m"})
self.assertEqual(code, 0)
self.assertIn("started ABC-21 in the tmux session epic-ABC-12\n", out)
self.assertIn("ABC-20 waits: it is a human's task\n", out)
started = [args for args in fake.tmux_calls if args[0] == "new-session"]
self.assertEqual(started, [["new-session", "-d", "-s", "epic-ABC-12", "-n", "ABC-21", "-c", str(self.home / ".local/state/do-epic/ABC-12"), "-e", "LOOP_CLAUDE_WORKER_MODEL=m", "-e", "CHUNK_PR_PARKS=1", "-P", "-F", "#{window_id}", "--", "/b/do-epic", "--chunk", "ABC-21", "ABC-12"]])
# The session is no checkout's, so nothing marks it as one's.
self.assertNotIn(tmux.OWNER, [args[3] for args in fake.tmux_calls if args[0] == "set-option"])
def test_plans_an_issue_no_label_places_before_it_starts_the_chunks(self) -> None:
self.issues = [issue("ABC-20")]
fake = FakeEffects(on_terminal=False, claude=[structured({"parts": []}), structured({"pick": "claude"})])
code, out, err = self.run_main(["ABC-12"], fake)
self.assertEqual(code, 0, err)
self.assertLess(out.index("ABC-20 is labelled do-epic-claude\n"), out.index("started ABC-20 in the tmux session epic-ABC-12\n"))
def test_starts_no_chunk_where_a_usage_limit_ends_the_planning(self) -> None:
self.issues.append(issue("ABC-22"))
limit = {"type": "result", "is_error": True, "api_error_status": 429, "result": "You've hit your limit"}
fake = FakeEffects(claude=[structured(limit, None)])
code, _, err = self.run_main(["ABC-12"], fake)
self.assertEqual(code, 1)
self.assertIn("the epic is not planned, so no chunk started: You've hit your limit\n", err)
self.assertEqual([args for args in fake.tmux_calls if args[0] == "new-session"], [])
def test_says_why_the_epic_is_not_planned_in_full_and_starts_the_chunks_that_may_start(self) -> None:
self.issues = [dataclasses.replace(issue(key, "do-epic-claude"), scores={"L": 1, "E": 1, "I": 1, "S": 1}, by_loop=True) for key in ("ABC-20", "ABC-21")]
code, out, err = self.run_main(["ABC-12"], FakeEffects())
self.assertEqual(code, 0, err)
self.assertIn("the epic ABC-12 is not planned in full: the epic ABC-12's description states `Score = ...` 0 times under ## Scoring", err)
self.assertTrue(err.endswith("(2**S + 32)`\n"))
self.assertIn("started ABC-20, ABC-21 in the tmux session epic-ABC-12\n", out)
def test_stops_on_an_epic_it_cannot_read(self) -> None:
self.description = Failure("Jira answered 401")
code, _, err = self.run_main(["ABC-12"], FakeEffects())
self.assertEqual(code, 1)
self.assertIn("Jira answered 401\n", err)
def test_a_chunk_outside_a_tmux_window_says_how_to_run_do_epic(self) -> None:
fake = FakeEffects()
code, _, err = self.run_main(["--chunk", "ABC-21", "ABC-12"], fake)
self.assertEqual(code, 1)
self.assertIn("--chunk is how do-epic starts itself in a tmux window; run do-epic <EPIC-KEY>\n", err)
self.assertEqual(fake.dms, ["do-epic --chunk ABC-21 ABC-12 stopped: --chunk is how do-epic starts itself in a tmux window; run do-epic <EPIC-KEY>"])
def test_a_chunk_of_an_issue_the_epic_lacks_stops(self) -> None:
code, _, err = self.run_main(["--chunk", "ABC-99", "ABC-12"], FakeEffects(), {"TMUX_PANE": "%1"})
self.assertEqual(code, 1)
self.assertIn("ABC-99 is no issue of the epic ABC-12\n", err)
class ACycleOfAChunkWithoutARepo(DoEpicTest):
def test_naming_the_chunks_folder_doesnt_make_it(self) -> None:
folder = self.home / ".local/state/do-epic/ABC-12"
self.assertEqual(main.chunk_root("ABC-21", self.issues[1], self.epic_run(FakeEffects())), (str(folder), None))
self.assertFalse(folder.exists())
self.assertIsNone(main.folder_made(str(folder)))
self.assertTrue(folder.is_dir())
def test_a_chunk_whose_folder_cannot_be_made_stops_with_the_reason(self) -> None:
(self.home / ".local/state").mkdir(parents=True, exist_ok=True)
(self.home / ".local/state/do-epic").write_text("", encoding="utf-8")
code, _, err = self.run_main(["--chunk", "ABC-21", "ABC-12"], FakeEffects(), {"TMUX_PANE": "%1"})
self.assertEqual(code, 1)
self.assertRegex(err, f"could not make the chunk's folder {self.home}/.local/state/do-epic/ABC-12: \\w")
def cycle(self, env: dict[str, str] | None = None, run: ChunkRun = ChunkRun(1)) -> main.Cycle:
fake = FakeEffects(git=[Failure("no git"), Failure("no git")])
paths = paths_from(self.home)
epic = self.epic_run(fake, env)
place = main.chunk_root("ABC-21", self.issues[1], epic)
assert isinstance(place, tuple)
root, repo = place
self.assertIsNone(main.folder_made(root))
loop = Loop(root=root, session=main.session_named("A ABC-12 do-epic ABC-21", paths.claude_code_transcripts), window=tmux.Window("epic-ABC-12", "ABC-21", "%1"), paths=paths, env=env or {}, launcher=pathlib.Path("/b/do-epic"), effects=fake.effects())
with contextlib.redirect_stdout(io.StringIO()):
found = main.next_cycle(run, loop, repo is not None, epic)
assert isinstance(found, main.Cycle), found
return found
def test_routes_on_the_repoless_model_by_the_issues_scores(self) -> None:
cycle = self.cycle()
assert cycle.project is not None
self.assertEqual(cycle.project.rung.model, "claude-opus-5-5")
self.assertEqual(cycle.route, Route(cycle.project.worker_rung(3), 21, 3, 5))
self.assertEqual(cycle.judge.model, "claude-opus-5-5")
self.assertEqual(self.cycle({"LOOP_CLAUDE_WORKER_MODEL": "off-the-ladder"}).route, Route(Rung("off-the-ladder")))
self.assertEqual(self.cycle({"LOOP_CLAUDE_JUDGE_MODEL": "claude-fable-5-2"}).judge.model, "claude-fable-5-2")
def test_keeps_the_route_and_the_evidence_its_run_holds(self) -> None:
kept = Route(Rung("claude-opus-5-5", "xhigh"), 21, 3, 5)
cycle = self.cycle(run=ChunkRun(2, unfinished_evidence="the evidence", route=kept))
self.assertEqual((cycle.route, cycle.unfinished_evidence), (kept, "the evidence"))
def test_a_chunk_that_was_not_parked_starts_on_the_drivers_own_prompts_with_no_facts(self) -> None:
cycle = self.cycle()
self.assertIs(cycle.prompts, chunk_prompt.WORKER)
self.assertEqual(cycle.facts, "")
def test_works_in_the_epics_folder_and_archives_apart_from_loop_claude(self) -> None:
cycle = self.cycle()
self.assertEqual((cycle.root, cycle.project_archive, cycle.records), (str(self.home / ".local/state/do-epic/ABC-12"), self.home / ".claude/do-epic-transcripts/ABC-12", ""))
def test_the_records_are_the_epics_scoring_and_decisions_then_the_humans_rules(self) -> None:
self.description = DESCRIPTION + "\n## Scoring\nE + I, bar 4.\n\n## Decisions\n### Merges squash\nAlways.\n"
(self.home / ".claude").mkdir()
(self.home / ".claude/CLAUDE.md").write_text("# Global\n", encoding="utf-8")
self.assertEqual(self.cycle().records, "From the epic ABC-12's description, ## Scoring:\nE + I, bar 4.\n\nFrom the epic ABC-12's description, ## Decisions:\n### Merges squash\nAlways.\n\nFrom ~/.claude/CLAUDE.md:\n# Global")
def test_stops_where_a_section_of_the_epics_records_cannot_be_read(self) -> None:
self.description = DESCRIPTION + "\n## Scoring\nA.\n\n## Scoring\nB.\n"
with self.assertRaises(AssertionError) as raised:
self.cycle()
self.assertIn("the epic ABC-12's description: the epic's description has ## Scoring more than once - the judge cannot read the records.", str(raised.exception))
def test_the_premises_are_the_epics_goals_and_audience(self) -> None:
self.assertEqual(self.cycle().premises, "the epic ABC-12's description:\n## Goals\nShip the import.\n\n## Audience\nThe client's team.")
def test_the_task_is_the_issue(self) -> None:
task = self.cycle().task
self.assertTrue(task.startswith("Work the Jira issue ABC-21 of the epic ABC-12 as one chunk, which changes no repo: work in the folder you start in. File a finding"), task)
self.assertIn('with `/b/do-epic ABC-12 --file "<summary>" --label <label>` and its detail on stdin', task)
self.assertIn("Write the issue and the decision in English, the epic's language.", task)
self.assertTrue(task.endswith(" Its summary: Do ABC-21\n\nIts description:\n\nTidy the docs."), task)
def test_an_issue_without_scores_runs_on_the_projects_rung(self) -> None:
self.issues[1] = dataclasses.replace(self.issues[1], scores={})
cycle = self.cycle()
assert cycle.project is not None
self.assertEqual(cycle.route, Route(cycle.project.rung))
UNREAD = [Failure("no git")] * 20
MODELS = {"LOOP_CLAUDE_JUDGE_MODEL": "claude-opus-5-5", "LOOP_CLAUDE_WORKER_MODEL": "claude-opus-5-5", "TMUX_PANE": "%1"}
class TheHumansRun(DoEpicTest):
def test_shows_the_session_on_a_terminal_and_says_when_tmux_cannot(self) -> None:
fake = FakeEffects(windows="ABC-21\t0\t@9\n")
code, out, err = self.run_main(["ABC-12"], fake)
self.assertEqual((code, err), (0, ""))
self.assertEqual(out, "<1790000000> started no chunk\n<1790000000> ABC-20 waits: it is a human's task\n")
self.assertEqual(fake.tmux_calls[-1], ["attach-session", "-t", "=epic-ABC-12"])
fake.effects = lambda made=fake.effects(): dataclasses.replace(made, tmux_on_terminal=lambda args: 1) # type: ignore[method-assign]
code, _, err = self.run_main(["ABC-12"], fake, {"TMUX": "/tmp/tmux"})
self.assertEqual((code, err.split(" ", 1)[1]), (1, "`tmux switch-client -t =epic-ABC-12` failed; the chunks go on in the tmux session\n"))
def test_stops_with_the_reason_where_the_epics_issues_cannot_be_read(self) -> None:
store = MemoryEpic("ABC-12", fails="Jira answered 503")
self.backend = lambda config, key: (store, EpicRecord(Description(self.description))) # type: ignore[method-assign,arg-type]
code, out, err = self.run_main(["ABC-12"], FakeEffects(on_terminal=False))
self.assertEqual(code, 1)
self.assertIn("Jira answered 503\n", err)
self.assertNotIn("started", out)
def test_off_a_terminal_it_says_how_to_see_the_chunks(self) -> None:
code, out, err = self.run_main(["ABC-12"], FakeEffects(on_terminal=False, windows="ABC-21\t0\t@9\n"))
self.assertEqual((code, err), (0, ""))
self.assertTrue(out.endswith("not on a terminal; see the chunks with `tmux attach -t =epic-ABC-12`\n"))
def test_with_no_window_in_the_session_it_shows_none(self) -> None:
self.issues = self.issues[:1]
fake = FakeEffects()
code, out, _ = self.run_main(["ABC-12"], fake)
self.assertEqual(code, 0)
self.assertEqual(out, "<1790000000> started no chunk\n<1790000000> ABC-20 waits: it is a human's task\n")
self.assertNotIn("attach-session", [args[0] for args in fake.tmux_calls])
def test_stops_without_its_settings_or_on_a_cap_it_cannot_read(self) -> None:
self.description = "**Max parallel chunks:** many\n"
code, _, err = self.run_main(["ABC-12"], FakeEffects())
self.assertEqual(code, 1)
self.assertIn("`**Max parallel chunks:** many`, which is not a whole number of 1 or more", err)
(self.home / ".claude-projects/do-epic/config.toml").unlink()
code, out, err = self.run_main(["ABC-12"], FakeEffects())
self.assertEqual((code, out), (1, ""))
self.assertIn("config.toml", err)
def test_an_interrupt_from_the_keyboard_ends_it_quietly_and_a_crash_is_sent_on(self) -> None:
fake = FakeEffects()
fake.tmux = lambda args: (_ for _ in ()).throw(KeyboardInterrupt()) # type: ignore[method-assign]
self.assertEqual(self.run_main(["ABC-12"], fake), (130, "", ""))
fake.tmux = lambda args: (_ for _ in ()).throw(ValueError("boom")) # type: ignore[method-assign]
with self.assertRaises(ValueError):
self.run_main(["ABC-12"], fake)
self.assertEqual(fake.dms, ["do-epic ABC-12 crashed: ValueError('boom')"])
def test_starts_each_chunk_in_its_repos_checkout(self) -> None:
for name in ("api", "web"):
configured(self, self.home / "code" / name, home=self.home)
self.issues = [issue("ABC-20", "repo:api"), issue("ABC-22", "repo:web")]
fake = FakeEffects(on_terminal=False)
code, out, _ = self.run_main(["ABC-12"], fake)
self.assertEqual(code, 0)
self.assertIn("started ABC-20, ABC-22 in the tmux session epic-ABC-12\n", out)
self.assertEqual([args[args.index("-c") + 1] for args in fake.tmux_calls if args[0] in ("new-session", "new-window")], [str(self.home / "code/api"), str(self.home / "code/web")])
def test_clones_a_missing_repo_from_the_host_of_the_repos_located_before_it(self) -> None:
for name in ("api", "web"):
configured(self, self.home / "code" / name, home=self.home)
shutil.rmtree(self.home / "code/web")
self.issues = [issue("ABC-20", "repo:api"), issue("ABC-22", "repo:web")]
fake = FakeEffects(on_terminal=False, git=["git@host.example:team/api.git", ""])
code, out, err = self.run_main(["ABC-12"], fake)
self.assertEqual(code, 0, err)
self.assertIn("started ABC-20, ABC-22 in the tmux session epic-ABC-12\n", out)
clones = [what for seam, what in fake.calls if seam == "git" and "clone" in what]
self.assertEqual([what[what.index("--") + 1:] for what in clones], [["git@host.example:team/web", str(self.home / "code/web")]])
def test_names_a_checkout_as_loop_claude_does_whatever_way_its_config_spells_it(self) -> None:
real = self.home / "code" / "api"
real.mkdir(parents=True)
(self.home / "work").mkdir()
(self.home / "work/api").symlink_to(real)
configured(self, self.home / "work/api", home=self.home)
self.issues = [issue("ABC-20", "repo:api")]
fake = FakeEffects(on_terminal=False)
code, _, err = self.run_main(["ABC-12"], fake)
self.assertEqual(code, 0, err)
self.assertEqual([args[args.index("-c") + 1] for args in fake.tmux_calls if args[0] == "new-session"], [str(real)])
self.assertEqual([args[-2:] for args in fake.tmux_calls if "@chunk-root" in args], [["@chunk-root", str(real)]])
class AChunksRun(DoEpicTest):
def test_a_finished_chunk_starts_the_next_without_planning_again(self) -> None:
self.issues.append(issue("ABC-22"))
fake = FakeEffects(streams=[self.worker()], claude=[judged("finished")], git=UNREAD, windows="ABC-21\t0\t@9\n")
code, out, err = self.run_main(["--chunk", "ABC-21", "ABC-12"], fake, MODELS)
self.assertEqual(code, 0, err)
self.assertIn("the chunk finished; started no other\n", out)
# The one claude call is the judge's: ABC-22, which no label places, waits for the human's do-epic.
self.assertEqual(len(fake.made("claude")), 1)
def started(self, store: MemoryEpic) -> str:
"""What the chunk of ABC-21 prints as it runs to its end on store."""
self.backend = lambda config, key: (store, EpicRecord(Description(self.description))) # type: ignore[assignment, method-assign, arg-type]
code, out, err = self.run_main(["--chunk", "ABC-21", "ABC-12"], FakeEffects(streams=[self.worker()], claude=[judged("finished")], git=UNREAD, windows="ABC-21\t0\t@9\n"), MODELS)
self.assertEqual(code, 0, err)
return out
def test_a_starting_chunk_starts_its_issue_in_the_tracker_before_its_first_cycle(self) -> None:
store = MemoryEpic("ABC-12", list(self.issues))
out = self.started(store)
self.assertEqual((store.writes[0], store.issues[1].assignee), ("start ABC-21", "do-epic"))
self.assertNotIn("assigned", out.partition("=== cycle 1")[0])
def test_a_starting_chunk_says_who_else_holds_its_issue_and_leaves_it_theirs(self) -> None:
store = MemoryEpic("ABC-12", [self.issues[0], dataclasses.replace(self.issues[1], assignee="Ada Berg")])
self.assertIn("ABC-21 stays assigned to Ada Berg\n", self.started(store).partition("=== cycle 1")[0])
self.assertEqual(store.issues[1].assignee, "Ada Berg")
def test_a_chunk_runs_though_its_issue_could_not_start_in_the_tracker_and_says_why(self) -> None:
class Unstartable(MemoryEpic):
def start_issue(self, key: str) -> str | None | Failure:
return Failure(f"cannot assign {key}: Jira answered 403")
out = self.started(Unstartable("ABC-12", list(self.issues)))
self.assertIn("not every step that starts ABC-21 in the tracker was made, and its chunk runs all the same: cannot assign ABC-21: Jira answered 403\n", out.partition("=== cycle 1")[0])
self.assertIn("the chunk finished", out)
def test_runs_cycles_until_the_judge_rules_it_finished_then_starts_the_next_chunk(self) -> None:
self.issues.append(issue("ABC-22", "do-epic-claude"))
self.description = DESCRIPTION.replace("2", "1")
fake = FakeEffects(streams=[self.worker(), self.worker()], claude=[judged("unfinished"), judged("finished")], git=UNREAD, windows="ABC-21\t0\t@9\n")
code, out, err = self.run_main(["--chunk", "ABC-21", "ABC-12"], fake, MODELS)
self.assertEqual(code, 0, err)
self.assertIn("=== cycle 1, worker on claude-", out)
self.assertIn("=== cycle 2, worker on claude-", out)
self.assertNotIn("=== cycle 3", out)
self.assertIn("the chunk finished; started ABC-22\n", out)
self.assertEqual(fake.dms, [])
archive = self.home / ".claude/do-epic-transcripts/ABC-12"
self.assertTrue(any(archive.iterdir()))
self.assertFalse((self.home / ".claude/loop-claude-transcripts").exists())
streamed = [what for seam, what in fake.calls if seam == "stream_claude"]
self.assertIn("Work the Jira issue ABC-21 of the epic ABC-12 as one chunk", " ".join(streamed[0]))
self.assertNotIn("Work the Jira issue", " ".join(streamed[1]))
def test_every_text_of_a_run_names_do_epic_as_what_drives_it(self) -> None:
fake = FakeEffects(streams=[self.worker()] * 3, claude=[judged("unfinished", escalation="working"), judged("interrupt"), judged("finished")], inputs=["Use B."], git=UNREAD)
code, _, err = self.run_main(["--chunk", "ABC-21", "ABC-12"], fake, MODELS)
self.assertEqual(code, 0, err)
prompts = [" ".join(what) for seam, what in fake.calls if seam == "stream_claude"]
judged_with = [" ".join(what[0]) + (what[1] or "") for seam, what in fake.calls if seam == "claude"]
self.assertEqual((len(prompts), len(judged_with)), (3, 3))
for text in (*prompts, *judged_with, *fake.dms, *[str(what) for seam, what in fake.calls if seam == "input"]):
self.assertNotIn("loop-claude", text)
self.assertNotIn("None", text)
self.assertIn(" do-epic runs you on claude-", prompts[1])
self.assertIn("The human answered your question at do-epic's terminal:\nUse B.", prompts[2])
for text in judged_with:
self.assertIn("what do-epic told it on [loop] lines, latest last:\n", text)
self.assertIn("asking do-epic for a higher rung", text)
self.assertIn("do-epic in ", fake.dms[0])
self.assertNotIn("\n\n[step] ", judged_with[0])
self.assertIn("\n\n[step] do-epic stepped the worker up a rung here", judged_with[1])
def test_stops_for_the_human_after_six_unfinished_cycles_naming_do_epic(self) -> None:
fake = FakeEffects(streams=[self.worker()] * 6, claude=[judged("unfinished")] * 6, git=UNREAD)
code, out, err = self.run_main(["--chunk", "ABC-21", "ABC-12"], fake, MODELS)
self.assertEqual(code, 2, out)
self.assertIn("the judge ruled it unfinished 6 cycles running; finish the chunk yourself, or rerun do-epic to give it 6 more cycles", err + out)
def test_every_archived_transcript_opens_with_the_chunks_task_through_step_ups_and_the_stop_for_the_human(self) -> None:
fake = FakeEffects(streams=[self.worker()] * 6, claude=[judged("unfinished", escalation="working")] + [judged("unfinished")] * 5, git=UNREAD)
code, out, _ = self.run_main(["--chunk", "ABC-21", "ABC-12"], fake, MODELS)
self.assertEqual(code, 2, out)
outcomes = [path.read_text(encoding="utf-8") for path in (self.home / ".claude/do-epic-transcripts/ABC-12").glob("*/*.outcomes.md")]
self.assertTrue(any("Z Stepped up\n" in text for text in outcomes) and any("Z Stopped: " in text for text in outcomes), outcomes)
self.assertEqual([text for text in outcomes if not text.startswith("Task: Work the Jira issue ABC-21 of the epic ABC-12 as one chunk")], [])
def test_a_step_up_archived_beside_a_new_copy_of_the_transcript_opens_with_the_chunks_task(self) -> None:
fake = FakeEffects(streams=[self.worker()] * 6, claude=[judged("unfinished", escalation="working")] + [judged("unfinished")] * 5, git=UNREAD)
def grown_after_each_copy(path: pathlib.Path, data: bytes) -> Failure | None:
"""Writes the file, and adds a line to the worker's transcript after each copy of it, as a worker that still writes does."""
unwritten = replace_file(path, data)
if path.suffix == ".jsonl":
for transcript in (paths_from(self.home).claude_code_transcripts.parent / "projects" / "-fake").glob("*.jsonl"):
with open(transcript, "a", encoding="utf-8") as handle:
handle.write(json.dumps({"type": "queue-operation", "timestamp": str(path)}) + "\n")
return unwritten
fake.replace_file = grown_after_each_copy
code, out, _ = self.run_main(["--chunk", "ABC-21", "ABC-12"], fake, MODELS)
self.assertEqual(code, 2, out)
outcomes = [path.read_text(encoding="utf-8") for path in (self.home / ".claude/do-epic-transcripts/ABC-12").glob("*/*.outcomes.md")]
self.assertTrue(any("Z Stepped up\n" in text for text in outcomes) and any("Z Stopped: " in text for text in outcomes), outcomes)
self.assertEqual([text for text in outcomes if not text.startswith("Task: Work the Jira issue ABC-21 of the epic ABC-12 as one chunk")], [])
def test_a_finished_chunk_moves_its_issue_to_done_before_the_chunk_it_blocks_starts(self) -> None:
store = MemoryEpic("ABC-12", [self.issues[0], self.issues[1], issue("ABC-22", "do-epic-claude", blockers=("ABC-21",))])
self.backend = lambda config, key: (store, EpicRecord(Description(self.description))) # type: ignore[method-assign,arg-type]
fake = FakeEffects(streams=[self.worker()], claude=[judged("finished")], git=UNREAD, windows="ABC-21\t0\t@9\n")
code, out, err = self.run_main(["--chunk", "ABC-21", "ABC-12"], fake, MODELS)
self.assertEqual(code, 0, err)
self.assertEqual({each.key: each.done for each in store.issues}, {"ABC-20": False, "ABC-21": True, "ABC-22": False})
self.assertIn("the chunk finished; started ABC-22\n", out)
def test_a_finished_chunk_counts_as_done_though_the_search_still_shows_its_issue_open(self) -> None:
issues = [self.issues[0], self.issues[1], issue("ABC-22", "do-epic-claude", blockers=("ABC-21",))]
store = MemoryEpic("ABC-12", issues)
store.read = lambda: list(issues) # type: ignore[method-assign]
self.backend = lambda config, key: (store, EpicRecord(Description(self.description))) # type: ignore[method-assign,arg-type]
fake = FakeEffects(streams=[self.worker()], claude=[judged("finished")], git=UNREAD, windows="ABC-21\t0\t@9\n")
code, out, err = self.run_main(["--chunk", "ABC-21", "ABC-12"], fake, MODELS)
self.assertEqual(code, 0, err)
self.assertIn("the chunk finished; started ABC-22\n", out)
def test_where_the_teams_automation_moves_issues_a_finished_chunk_without_a_repo_still_moves_its_own(self) -> None:
(self.home / ".claude-projects" / "do-epic" / "config.toml").write_text(SETTINGS + 'jira-unblocking-statuses = ["Release Ready"]\njira-automation-moves-issues = true\n', encoding="utf-8")
parent = issue("ABC-23", "split-by-repo")
store = MemoryEpic("ABC-12", [self.issues[0], parent, issue("ABC-21", "do-epic-claude", parent="ABC-23"), issue("ABC-22", "do-epic-claude", blockers=("ABC-23",))])
self.backend = lambda config, key: (store, EpicRecord(Description(self.description))) # type: ignore[method-assign,arg-type]
fake = FakeEffects(streams=[self.worker()], claude=[judged("finished")], git=UNREAD, windows="ABC-21\t0\t@9\n")
code, out, err = self.run_main(["--chunk", "ABC-21", "ABC-12"], fake, MODELS)
self.assertEqual(code, 0, err)
# No pull request carries ABC-21, so do-epic moves it; its split item, then all done, closes as ever.
self.assertEqual({each.key: each.done for each in store.issues}, {"ABC-20": False, "ABC-23": True, "ABC-21": True, "ABC-22": False})
self.assertIn("the chunk finished; started ABC-22\n", out)
def test_the_last_sub_task_of_a_split_item_to_finish_moves_the_item_to_done_and_starts_what_it_blocks(self) -> None:
parent = issue("ABC-21", "split-by-repo")
tasks = [issue("ABC-23", "do-epic-claude", parent="ABC-21"), issue("ABC-24", "do-epic-claude", parent="ABC-21", done=True)]
store = MemoryEpic("ABC-12", [self.issues[0], parent, *tasks, issue("ABC-22", "do-epic-claude", blockers=("ABC-21",))])
self.backend = lambda config, key: (store, EpicRecord(Description(self.description))) # type: ignore[method-assign,arg-type]
fake = FakeEffects(streams=[self.worker()], claude=[judged("finished")], git=UNREAD, windows="ABC-23\t0\t@9\n")
code, out, err = self.run_main(["--chunk", "ABC-23", "ABC-12"], fake, MODELS)
self.assertEqual(code, 0, err)
self.assertEqual({each.key: each.done for each in store.issues}, {"ABC-20": False, "ABC-21": True, "ABC-23": True, "ABC-24": True, "ABC-22": False})
self.assertIn("the chunk finished; started ABC-22\n", out)
def test_the_last_sub_task_a_person_filed_to_finish_moves_its_parent_to_done_and_starts_what_it_blocks(self) -> None:
(self.home / ".claude-projects" / "do-epic" / "config.toml").write_text(SETTINGS + 'jira-finish-transition = "Mark as done"\njira-finish-status = "Done"\n', encoding="utf-8")
tasks = [issue("ABC-23", "do-epic-claude", parent="ABC-21"), issue("ABC-24", "do-epic-claude", parent="ABC-21", done=True)]
store = MemoryEpic("ABC-12", [self.issues[0], issue("ABC-21"), *tasks, issue("ABC-22", "do-epic-claude", blockers=("ABC-21",))])
self.backend = lambda config, key: (store, EpicRecord(Description(self.description))) # type: ignore[method-assign,arg-type]
fake = FakeEffects(streams=[self.worker()], claude=[judged("finished")], git=UNREAD, windows="ABC-23\t0\t@9\n")
code, out, err = self.run_main(["--chunk", "ABC-23", "ABC-12"], fake, MODELS)
self.assertEqual(code, 0, err)
self.assertEqual({each.key: each.done for each in store.issues}, {"ABC-20": False, "ABC-21": True, "ABC-23": True, "ABC-24": True, "ABC-22": False})
self.assertIn("the chunk finished; started ABC-22\n", out)
def test_a_parent_jira_will_not_move_is_said_and_the_next_chunk_still_starts(self) -> None:
(self.home / ".claude-projects" / "do-epic" / "config.toml").write_text(SETTINGS + 'jira-finish-transition = "Mark as done"\njira-finish-status = "Done"\n', encoding="utf-8")
store = MemoryEpic("ABC-12", [self.issues[0], issue("ABC-21"), issue("ABC-23", "do-epic-claude", parent="ABC-21"), issue("ABC-22", "do-epic-claude")])
finish = store.finish_issue
store.finish_issue = lambda key: Failure("no way to done") if key == "ABC-21" else finish(key) # type: ignore[method-assign]
self.backend = lambda config, key: (store, EpicRecord(Description(self.description))) # type: ignore[method-assign,arg-type]
fake = FakeEffects(streams=[self.worker()], claude=[judged("finished")], git=UNREAD, windows="ABC-23\t0\t@9\n")
code, out, err = self.run_main(["--chunk", "ABC-23", "ABC-12"], fake, MODELS)
self.assertEqual(code, 0, err)
self.assertIn("ABC-21's sub-tasks are all done, but it did not move to done: no way to done; close it in Jira\n", out)
self.assertIn("the chunk finished; started ABC-22\n", out)
def test_a_sub_task_that_leaves_another_open_leaves_its_split_item_open(self) -> None:
parent = issue("ABC-21", "split-by-repo")
store = MemoryEpic("ABC-12", [self.issues[0], parent, issue("ABC-23", "do-epic-claude", parent="ABC-21"), issue("ABC-24", "do-epic-claude", parent="ABC-21")])
self.backend = lambda config, key: (store, EpicRecord(Description(self.description))) # type: ignore[method-assign,arg-type]
fake = FakeEffects(streams=[self.worker()], claude=[judged("finished")], git=UNREAD, windows="ABC-23\t0\t@9\n")
code, _, err = self.run_main(["--chunk", "ABC-23", "ABC-12"], fake, MODELS)
self.assertEqual(code, 0, err)
self.assertEqual({each.key: each.done for each in store.issues if each.key in ("ABC-21", "ABC-23", "ABC-24")}, {"ABC-21": False, "ABC-23": True, "ABC-24": False})
def test_a_split_item_that_jira_will_not_move_to_done_stops_with_the_reason(self) -> None:
parent = issue("ABC-21", "split-by-repo")
store = MemoryEpic("ABC-12", [self.issues[0], parent, issue("ABC-23", "do-epic-claude", parent="ABC-21")])
finish = store.finish_issue
store.finish_issue = lambda key: Failure("no way to done") if key == "ABC-21" else finish(key) # type: ignore[method-assign]
self.backend = lambda config, key: (store, EpicRecord(Description(self.description))) # type: ignore[method-assign,arg-type]
fake = FakeEffects(streams=[self.worker()], claude=[judged("finished")], git=UNREAD, windows="ABC-23\t0\t@9\n")
code, out, err = self.run_main(["--chunk", "ABC-23", "ABC-12"], fake, MODELS)
self.assertEqual(code, 1)
self.assertIn("the chunk finished, but its split item ABC-21 could not move to done: no way to done; once it is done in Jira, run `do-epic ABC-12` to start the chunks it blocks\n", err)
self.assertNotIn("started", out)
def test_a_chunk_whose_issue_jira_will_not_move_to_done_stops_with_the_reason_and_starts_no_other(self) -> None:
store = MemoryEpic("ABC-12", list(self.issues))
store.finish_issue = lambda key: Failure("ABC-21's status has no transition to a done status") # type: ignore[method-assign]
self.backend = lambda config, key: (store, EpicRecord(Description(self.description))) # type: ignore[method-assign,arg-type]
fake = FakeEffects(streams=[self.worker()], claude=[judged("finished")], git=UNREAD)
code, out, err = self.run_main(["--chunk", "ABC-21", "ABC-12"], fake, MODELS)
self.assertEqual(code, 1)
self.assertIn("the chunk finished, but its issue could not move to done: ABC-21's status has no transition to a done status; once it is done in Jira, run `do-epic ABC-12` to start the chunks it blocks\n", err)
self.assertNotIn("started", out)
def test_a_finished_chunk_says_why_the_next_could_not_start(self) -> None:
store = MemoryEpic("ABC-12", list(self.issues))
reads = iter([self.issues, self.issues, Failure("Jira answered 503")])
store.read = lambda: next(reads) # type: ignore[method-assign]
self.backend = lambda config, key: (store, EpicRecord(Description(self.description))) # type: ignore[method-assign,arg-type]
fake = FakeEffects(streams=[self.worker()], claude=[judged("finished")], git=UNREAD)
code, _, err = self.run_main(["--chunk", "ABC-21", "ABC-12"], fake, MODELS)
self.assertEqual(code, 1)
self.assertIn("the chunk finished, but the next could not start: Jira answered 503\n", err)
def test_a_chunk_in_a_folder_no_project_config_names_stops_with_gits_reason(self) -> None:
stopped = main.chunk_work("ABC-21", str(self.home), "English", self.epic_run(FakeEffects()))
assert isinstance(stopped, main.Stop)
self.assertEqual(stopped.code, 1)
self.assertIn("rev-parse", stopped.reason) # git's reason, since no project config can be found without a checkout
def test_a_chunk_in_a_repo_works_in_its_checkout_on_the_repos_premises_and_records(self) -> None:
checkout = self.home / "code" / "api"
configured(self, checkout, home=self.home)
(checkout / "README.md").write_text("## Goals\nServe the API.\n\n## Audience\nIts callers.\n", encoding="utf-8")
(checkout / "AGENTS.md").write_text("Squash every merge.\n", encoding="utf-8")
self.issues = [dataclasses.replace(issue("ABC-20", "repo:api"), scores={"L": 2, "E": 1, "I": 1})]
self.description = DESCRIPTION + "\n## Decisions\nKeep the v1 endpoints.\n"
fake = FakeEffects(streams=[self.worker()], claude=[judged("finished")], git=UNREAD)
code, out, err = self.run_main(["--chunk", "ABC-20", "ABC-12"], fake, MODELS)
self.assertEqual(code, 0, err)
prompt = " ".join([what for seam, what in fake.calls if seam == "stream_claude"][0])
self.assertIn(f"Work the Jira issue ABC-20 of the epic ABC-12 as one chunk, in the checkout {checkout}, on the branch ABC-20. File a finding", prompt)
self.assertIn("Ship the import.", prompt)
self.assertIn("The repo's goals, which rank after the epic's and after code health, are from", prompt)
self.assertIn("Serve the API.", prompt)
self.assertIn("without `--finish`", prompt)
self.assertIn("add one bullet to `## Unreleased` in `CHANGELOG.md`", prompt)
self.assertIn("the chunk finished; started ABC-12\n", out)
judge_prompt = [what[1] for seam, what in fake.calls if seam == "claude"][0]
self.assertIn("The records: the epic's scoring and decisions, then the repo's working rules and decisions, then the human's rules for every project:\nFrom the epic ABC-12's description, ## Decisions:\nKeep the v1 endpoints.\n\nFrom AGENTS.md:\nSquash every merge.", judge_prompt)
self.assertIn("writing it into the epic's description under ## Decisions, the repo's goals file's Goals or Audience, AGENTS.md, docs/decisions.md, the repo's plan or a comment", judge_prompt)
def test_a_chunk_without_a_repo_reads_no_forge(self) -> None:
fake = FakeEffects(streams=[self.worker()], claude=[judged("finished")], git=UNREAD)
self.assertEqual(self.run_main(["--chunk", "ABC-21", "ABC-12"], fake, MODELS)[0], 0)
self.assertEqual(self.gate_reads, 0)
self.assertTrue(next(what[what.index("-p") + 1] for seam, what in fake.calls if seam == "stream_claude").startswith("Work the Jira issue ABC-21 "))
def test_a_chunk_in_a_repo_routes_on_the_repos_model(self) -> None:
folder = self.repo_chunk()
models = self.home / ".claude/loop-claude-models.json"
models.parent.mkdir(parents=True, exist_ok=True)
models.write_text(json.dumps({folder.name: "claude-fable-5-2", "other": "claude-opus-5-5"}), encoding="utf-8")
fake = FakeEffects(streams=[self.worker()], claude=[judged("finished")], git=UNREAD)
code, out, err = self.run_main(["--chunk", "ABC-20", "ABC-12"], fake, {"TMUX_PANE": "%1"})
self.assertEqual(code, 0, err)
self.assertIn("=== cycle 1, worker on claude-fable-5-2 at low effort ===\n", out)
def test_a_chunk_in_a_repo_without_a_saved_model_stops_off_a_terminal_naming_do_epic_as_what_to_rerun(self) -> None:
self.repo_chunk()
code, out, err = self.run_main(["--chunk", "ABC-20", "ABC-12"], FakeEffects(git=UNREAD, on_terminal=False), {"TMUX_PANE": "%1"})
self.assertEqual((code, out), (2, ""))
self.assertIn("pick api's model", err)
self.assertIn("rerun do-epic on a terminal", err)
def test_a_chunk_in_a_repo_stops_where_the_repos_ladder_or_records_cannot_be_read(self) -> None:
folder = self.repo_chunk()
(folder / "routing-ladder.json").write_text("[", encoding="utf-8")
code, out, err = self.run_main(["--chunk", "ABC-20", "ABC-12"], FakeEffects(git=UNREAD), MODELS)
self.assertEqual((code, out), (1, ""))
self.assertIn(f"{folder / 'routing-ladder.json'}", err.strip().splitlines()[-1])
(folder / "routing-ladder.json").unlink()
(self.home / "code/api/docs/decisions.md").mkdir(parents=True)
fake = FakeEffects(git=UNREAD)
code, out, err = self.run_main(["--chunk", "ABC-20", "ABC-12"], fake, MODELS)
self.assertEqual((code, out), (1, ""))
self.assertIn("decisions.md", err.strip().splitlines()[-1])
self.assertIn("decisions.md", fake.dms[0])
def test_an_issue_that_names_no_repo_is_no_chunk(self) -> None:
self.issues = [issue("ABC-20")]
fake = FakeEffects(git=UNREAD)
code, _, err = self.run_main(["--chunk", "ABC-20", "ABC-12"], fake, MODELS)
self.assertEqual(code, 1)
self.assertIn("ABC-20 is no chunk: no label names its repo\n", err)
self.assertEqual([seam for seam, _ in fake.calls if seam == "stream_claude"], [])
def test_a_chunk_stays_in_its_repo_when_its_labels_change_under_it(self) -> None:
self.repo_chunk()
store = MemoryEpic("ABC-12", list(self.issues))
self.backend = lambda config, key: (store, EpicRecord(Description(self.description))) # type: ignore[method-assign,arg-type]
class Relabelling(Worker):
def __call__(inner, *args: object, **kwargs: object) -> object:
store.issues[:] = [issue("ABC-20", "do-epic-claude")]
return super().__call__(*args, **kwargs)
worker = Relabelling(paths_from(self.home).claude_code_transcripts.parent)
fake = FakeEffects(streams=[worker, self.worker()], claude=[judged("unfinished"), judged("finished")], git=UNREAD)
code, _, err = self.run_main(["--chunk", "ABC-20", "ABC-12"], fake, MODELS)
self.assertEqual(code, 0, err)
self.assertIn("Serve the API.", [what[1] for seam, what in fake.calls if seam == "claude"][1])
def test_a_chunk_in_a_repo_without_premises_stops(self) -> None:
configured(self, self.home / "code" / "api", home=self.home)
self.issues = [issue("ABC-20", "repo:api")]
code, _, err = self.run_main(["--chunk", "ABC-20", "ABC-12"], FakeEffects(git=UNREAD), MODELS)
self.assertEqual(code, 1)
self.assertIn("README.md is missing or empty - no premises.\n", err)
def test_a_chunk_stops_where_the_epics_issues_cannot_be_read(self) -> None:
store = MemoryEpic("ABC-12", [])
store.read = lambda: Failure("Jira answered 503") # type: ignore[method-assign]
self.backend = lambda config, key: (store, EpicRecord(Description(self.description))) # type: ignore[method-assign,arg-type]
code, _, err = self.run_main(["--chunk", "ABC-21", "ABC-12"], FakeEffects(), MODELS)
self.assertEqual(code, 1)
self.assertIn("Jira answered 503\n", err)
def test_a_chunk_whose_repo_or_premises_cannot_be_read_stops(self) -> None:
self.issues = [issue("ABC-20", "repo:api"), issue("ABC-23", "repo:api", "repo:web")]
code, _, err = self.run_main(["--chunk", "ABC-23", "ABC-12"], FakeEffects(), MODELS)
self.assertEqual(code, 1)
self.assertIn("ABC-23 is labelled with 2 picks", err)
self.issues = [self.issues[0]]
code, _, err = self.run_main(["--chunk", "ABC-20", "ABC-12"], FakeEffects(git=UNREAD), MODELS)
self.assertEqual(code, 1)
self.assertIn("api", err)
self.issues = [issue("ABC-21", "do-epic-claude")]
self.description = "## Goals\nShip.\n"
code, _, err = self.run_main(["--chunk", "ABC-21", "ABC-12"], FakeEffects(git=UNREAD), MODELS)
self.assertEqual(code, 1)
self.assertIn("the epic ABC-12's description has no text under a `## Audience` heading - no premises.\n", err)
class WhatAWorkerJudgeAndHumanRead(DoEpicTest):
def test_every_prompt_names_do_epic_and_never_loop_claude(self) -> None:
cycle = ACycleOfAChunkWithoutARepo.cycle(self) # type: ignore[arg-type]
prompts = cycle.prompts
texts = [
prompts.fresh(cycle.task, cycle.premises, cycle.route, cycle.project, ""),
prompts.resumed("the work remaining", cycle.route, cycle.project),
prompts.typed("Which one?", "The first.", cycle.route, cycle.project, True),
judge.judge_rules(prompts.answer_destinations, prompts.driver),
str(judge.judge_schema(prompts.driver)),
]
for text in texts:
self.assertNotIn("loop-claude", text)
self.assertIn(f"do-epic runs you on {cycle.route.rung}, routed by the issue's L of 3. Where a sentence below names item 21, it means the issue.", texts[0])
self.assertRegex(texts[0], r"it means the issue\.( \S|\n\n)")
self.assertNotIn("Chunk items:", texts[1])
# The worker's prompt and the judge's rules word the request for a higher rung alike, from one place.
for text in (texts[0], texts[3]):
self.assertIn("asking do-epic for a higher rung", text)
self.assertEqual(escalation_mark.asks_higher_rung(chunk_prompt.DRIVER), "asking do-epic for a higher rung")
WORKTREE = "worktree /code/api\nbranch refs/heads/main\n\nworktree /code/api-ABC-20\nbranch refs/heads/ABC-20\n"
PARKED_WINDOW = "ABC-20 awaits an approval\t0\t@9\n"
def awaiting(**answers: object) -> Forge:
"""A forge where ABC-20's pull request, #7, passed its checks and still wants its review, but for answers."""
return Forge(worktrees=WORKTREE, **answers) # type: ignore[arg-type]
# A forge whose checkout no longer has ABC-20's worktree, as after `chunk-pr clean`.
CLEANED = Forge(worktrees="worktree /code/api\nHEAD aaa\nbranch refs/heads/main\n")
class AChunkWhosePullRequestWaitsOnAGate(DoEpicTest):
def setUp(self) -> None:
super().setUp()
self.repo_config = self.repo_chunk() / "config.toml"
self.issues.append(issue("ABC-22", "do-epic-claude"))
self.file = parked.file_of(self.home / ".local/state/do-epic/ABC-12", "ABC-20")
self.session = main.session_named("A ABC-12 do-epic ABC-20", paths_from(self.home).claude_code_transcripts)
def parked_run(self, fake: FakeEffects) -> tuple[int, str, str, list[str]]:
"""The chunk's run, as its exit code, what it printed, and each prompt its workers got."""
code, out, err = self.run_main(["--chunk", "ABC-20", "ABC-12"], fake, MODELS)
return code, out.replace("<1790000000> ", ""), err, [what[what.index("-p") + 1] for seam, what in fake.calls if seam == "stream_claude"]
def test_it_parks_frees_its_slot_and_works_again_once_approved(self) -> None:
self.forges = [awaiting(), awaiting(), awaiting(decision="APPROVED")]
fake = FakeEffects(streams=[self.worker(), self.worker()], claude=[judged("finished"), judged("finished")], git=UNREAD, windows=PARKED_WINDOW)
states: list[object] = []
fake.effects = lambda made=fake.effects(): dataclasses.replace(made, sleep=lambda seconds: states.append((seconds, parked.parked_chunks(self.file.parent.parent)))) # type: ignore[method-assign]
checkout = str(self.home / "code/api")
code, out, err, prompts = self.parked_run(fake)
self.assertEqual(code, 0, err)
self.assertEqual(states, [(60, {"ABC-20": parked.Parked("ABC-20", "/code/api-ABC-20", "7", str(self.session.id), "an approval")})] * 2)
self.assertFalse(self.file.exists())
self.assertIn("parked: pull request #7 awaits an approval\nstarted ABC-22\n", out)
self.assertEqual(out.count("parked: "), 1)
self.assertEqual(len(prompts), 2)
self.assertTrue(prompts[0].startswith("Work the Jira issue ABC-20 "), prompts[0])
self.assertEqual(set(self.forges[0].ran[:1] + self.forges[1].ran[:1]), {checkout})
self.assertTrue(prompts[1].startswith(f"do-epic parked the chunk while its pull request awaited an approval. It resumes now: pull request #7 passed its checks and is approved. {chunk_prompt.FEEDBACK}\n\nWork the Jira issue ABC-20 "), prompts[1])
self.assertIn("the chunk finished; ", out)
shown = [args for args in fake.tmux_calls if args[0] == "rename-window" or tmux.ROOT in args and "%1" in args]
self.assertEqual(shown, [["rename-window", "-t", "%1", "ABC-20 awaits an approval"], ["rename-window", "-t", "%1", "ABC-20"], ["set-option", "-w", "-t", "%1", tmux.ROOT, checkout]])
def test_where_a_person_merges_it_parks_on_that_merge_and_works_again_once_merged(self) -> None:
self.repo_config.write_text(self.repo_config.read_text(encoding="utf-8") + 'merge = "human"\n', encoding="utf-8")
self.forges = [awaiting(), awaiting(decision="APPROVED"), awaiting(pulls=""), CLEANED]
fake = FakeEffects(streams=[self.worker(), self.worker()], claude=[judged("unfinished"), judged("finished")], git=UNREAD, windows=PARKED_WINDOW)
code, out, err, prompts = self.parked_run(fake)
self.assertEqual(code, 0, err)
self.assertIn("parked: pull request #7 awaits an approval\nstarted ABC-22\nparked: pull request #7 awaits your merge\n", out)
self.assertEqual(out.count("parked: "), 2)
for fact in ("run `chunk-pr merge` without `--finish`", "leaves the pull request ready for a person to merge"):
self.assertIn(fact, prompts[0])
for fact in ("awaited a person's merge", "no pull request from origin's ABC-20 is open", "chunk-pr clean"):
self.assertIn(fact, prompts[1].split("\n\n")[0])
self.assertEqual([args[3] for args in fake.tmux_calls if args[0] == "rename-window"], ["ABC-20 awaits an approval", "ABC-20 awaits your merge", "ABC-20"])
self.assertFalse(self.file.exists())
def test_stops_where_the_repos_config_cannot_be_read_as_the_cycle_ends(self) -> None:
self.forges = [awaiting()]
fake = FakeEffects(streams=[self.worker()], claude=[judged("unfinished")], git=UNREAD, windows=PARKED_WINDOW)
broken = self.repo_config.read_text(encoding="utf-8") + 'merge = "nobody"\n'
fake.effects = lambda made=fake.effects(): dataclasses.replace(made, stream_claude=lambda *args, **kwargs: (self.repo_config.write_text(broken, encoding="utf-8"), made.stream_claude(*args, **kwargs))[1]) # type: ignore[method-assign]
code, out, err, prompts = self.parked_run(fake)
self.assertEqual((code, len(prompts)), (1, 1))
self.assertIn('`merge` is \'nobody\', not "chunk" or "human"', err)
self.assertNotIn("parked: ", out)
def test_stops_where_the_gate_a_parked_chunk_moved_to_cannot_be_recorded(self) -> None:
self.repo_config.write_text(self.repo_config.read_text(encoding="utf-8") + 'merge = "human"\n', encoding="utf-8")
self.forges = [awaiting(), awaiting(decision="APPROVED")]
fake = FakeEffects(streams=[self.worker()], claude=[judged("unfinished")], git=UNREAD, windows=PARKED_WINDOW)
fake.effects = lambda made=fake.effects(): dataclasses.replace(made, sleep=lambda seconds: self.file.parent.chmod(0o555)) # type: ignore[method-assign]
self.addCleanup(lambda: self.file.parent.chmod(0o755))
code, out, err, prompts = self.parked_run(fake)
self.assertEqual((code, len(prompts), out.count("parked: ")), (1, 1, 1))
self.assertIn("Permission denied", err)
def test_where_a_person_merges_a_finished_chunk_waits_for_a_gate_it_cannot_read(self) -> None:
self.repo_config.write_text(self.repo_config.read_text(encoding="utf-8") + 'merge = "human"\n', encoding="utf-8")
self.forges = [awaiting(decision="APPROVED", fails="gh pr checks"), awaiting(decision="APPROVED"), CLEANED]
fake = FakeEffects(streams=[self.worker(), self.worker()], claude=[judged("finished"), judged("finished")], git=UNREAD, windows=PARKED_WINDOW)
slept: list[object] = []
fake.effects = lambda made=fake.effects(): dataclasses.replace(made, sleep=slept.append) # type: ignore[method-assign]
code, out, err, prompts = self.parked_run(fake)
self.assertEqual((code, len(prompts)), (0, 2), err)
self.assertEqual(slept, [60, 60])
self.assertIn("cannot read the gate of a pull request a person merges: gh pr checks failed", out)
self.assertIn("parked: pull request #7 awaits your merge", out)
def test_where_a_person_merged_before_the_cycle_closed_the_worker_is_told_once_to_remove_its_worktree(self) -> None:
self.repo_config.write_text(self.repo_config.read_text(encoding="utf-8") + 'merge = "human"\n', encoding="utf-8")
self.forges = [awaiting(pulls=""), awaiting(pulls="")]
fake = FakeEffects(streams=[self.worker(), self.worker()], claude=[judged("finished"), judged("finished")], git=UNREAD, windows=PARKED_WINDOW)
code, out, err, prompts = self.parked_run(fake)
self.assertEqual((code, len(prompts)), (0, 2), err)
for fact in ("keeps the chunk open while its worktree stands", "no pull request from origin's ABC-20 is open", "chunk-pr clean"):
self.assertIn(fact, prompts[1].split("\n\n")[0])
self.assertNotIn("parked: ", out)
def test_where_a_person_merges_a_finished_chunk_whose_pull_request_no_longer_merges_is_told_until_it_does(self) -> None:
self.repo_config.write_text(self.repo_config.read_text(encoding="utf-8") + 'merge = "human"\n', encoding="utf-8")
for unmergeable, why in (({"mergeable": "CONFLICTING"}, "conflicts with its base branch"), ({"merge_state": "BEHIND"}, "is behind its base branch")):
with self.subTest(why=why):
self.forges = [awaiting(decision="APPROVED", **unmergeable), awaiting(decision="APPROVED", **unmergeable), CLEANED]
self.gate_reads = 0
fake = FakeEffects(streams=[self.worker(), self.worker(), self.worker()], claude=[judged("finished"), judged("finished"), judged("finished")], git=UNREAD, windows=PARKED_WINDOW)
code, out, err, prompts = self.parked_run(fake)
self.assertEqual((code, len(prompts)), (0, 3), err)
for prompt in prompts[1:]:
for fact in ("keeps the chunk open while its pull request doesn't merge into its base", f"pull request #7 {why}", "run chunk-pr merge again"):
self.assertIn(fact, prompt.split("\n\n")[0])
self.assertNotIn("parked: ", out)
def test_where_a_person_merges_an_unfinished_chunk_goes_on_without_news_or_a_wait(self) -> None:
self.repo_config.write_text(self.repo_config.read_text(encoding="utf-8") + 'merge = "human"\n', encoding="utf-8")
self.forges = [awaiting(pulls=""), awaiting(decision="APPROVED", fails="gh pr checks"), CLEANED]
fake = FakeEffects(streams=[self.worker(), self.worker(), self.worker()], claude=[judged("unfinished"), judged("unfinished"), judged("finished")], git=UNREAD, windows=PARKED_WINDOW)
slept: list[object] = []
fake.effects = lambda made=fake.effects(): dataclasses.replace(made, sleep=slept.append) # type: ignore[method-assign]
code, out, err, prompts = self.parked_run(fake)
self.assertEqual((code, len(prompts), slept), (0, 3, []), err)
self.assertNotIn("keeps the chunk open", "".join(prompts))
self.assertIn("so the chunk isn't parked: gh pr checks failed", out)
def test_where_the_chunk_merges_a_finished_chunk_whose_pull_request_is_no_longer_open_is_handed_on(self) -> None:
self.forges = [awaiting(pulls="")]
fake = FakeEffects(streams=[self.worker()], claude=[judged("finished")], git=UNREAD, windows=PARKED_WINDOW)
code, _, err, prompts = self.parked_run(fake)
self.assertEqual((code, len(prompts)), (0, 1), err)
def test_where_the_teams_automation_moves_issues_a_finished_chunk_in_a_repo_moves_none_and_waits_for_the_move(self) -> None:
(self.home / ".claude-projects" / "do-epic" / "config.toml").write_text(SETTINGS + 'jira-unblocking-statuses = ["Release Ready", "Shipped"]\njira-automation-moves-issues = true\n', encoding="utf-8")
store = MemoryEpic("ABC-12", [*self.issues[:-1], issue("ABC-22", "do-epic-claude", blockers=("ABC-20",))])
self.backend = lambda config, key: (store, EpicRecord(Description(self.description))) # type: ignore[method-assign,arg-type]
self.forges = [awaiting(pulls="")]
fake = FakeEffects(streams=[self.worker()], claude=[judged("finished")], git=UNREAD, windows=PARKED_WINDOW)
slept: list[float] = []
def sleep(seconds: float) -> None:
slept.append(seconds)
store.fails = "Jira answered 503" if len(slept) in (1, 2) else None
if len(slept) == 4:
store.change("ABC-20", status="Release Ready")
fake.effects = lambda made=fake.effects(): dataclasses.replace(made, sleep=sleep) # type: ignore[method-assign]
code, out, err, _ = self.parked_run(fake)
self.assertEqual((code, slept), (0, [60, 60, 60, 60]), err)
self.assertEqual(out.count("cannot read the epic, so cannot tell whether ABC-20 has moved; trying again every 60 seconds: Jira answered 503\n"), 1, out)
self.assertEqual([(each.status, each.done) for each in store.issues if each.key == "ABC-20"], [("Release Ready", False)])
self.assertEqual(out.count("ABC-20 is To Do: it waits for the team's automation to move it to Release Ready or Shipped; move it in Jira if the automation doesn't\n"), 1, out)
self.assertIn("the chunk finished; started ABC-22\n", out)
def test_where_the_chunk_merges_an_approved_pull_request_parks_no_chunk(self) -> None:
self.forges = [awaiting(decision="APPROVED")]
fake = FakeEffects(streams=[self.worker()], claude=[judged("finished")], git=UNREAD, windows=PARKED_WINDOW)
code, out, err, prompts = self.parked_run(fake)
self.assertEqual(code, 0, err)
self.assertNotIn("parked: ", out)
def test_an_unfinished_chunk_parks_too_and_a_reviewers_comment_resumes_it(self) -> None:
self.forges = [awaiting(buckets=("pending",)), awaiting(), awaiting(threads=({"isResolved": False, "path": "a.py", "comments": {"nodes": [{"author": {"login": "reviewer"}}]}},))]
fake = FakeEffects(streams=[self.worker(), self.worker()], claude=[judged("unfinished"), judged("finished")], git=UNREAD, windows=PARKED_WINDOW + "ABC-22\t1\t@10\n")
code, out, err, prompts = self.parked_run(fake)
self.assertEqual(code, 0, err)
self.assertIn("parked: pull request #7 awaits its checks\nstarted no other\nparked: pull request #7 awaits an approval\n", out)
self.assertIn("its pull request awaited an approval. It resumes now: a reviewer's comment on pull request #7 waits for an answer, in a.py. Where a reviewer left feedback, fix what is reasonable", prompts[1])
self.assertEqual([args[3] for args in fake.tmux_calls if args[0] == "rename-window"], ["ABC-20 awaits its checks", "ABC-20 awaits an approval", "ABC-20"])
def test_a_chunk_parked_when_its_window_ended_polls_before_any_cycle_and_resumes_its_session(self) -> None:
parked.park(self.file.parent.parent, parked.Parked("ABC-20", "/code/api-ABC-20", "7", str(self.session.id), "an approval"))
self.worker()(["--session-id", str(self.session.id)])
self.forges = [awaiting(fails="gh pr list"), awaiting(decision="CHANGES_REQUESTED")]
fake = FakeEffects(streams=[self.worker()], claude=[judged("finished")], git=UNREAD, windows=PARKED_WINDOW)
code, out, err, prompts = self.parked_run(fake)
self.assertEqual(code, 0, err)
self.assertNotIn("parked: ", out)
self.assertEqual([args[3] for args in fake.tmux_calls if args[0] == "rename-window"], ["ABC-20 awaits an approval", "ABC-20"])
self.assertEqual(len(prompts), 1)
self.assertTrue(prompts[0].startswith("do-epic parked the chunk while its pull request awaited an approval. It resumes now: a reviewer requested changes on pull request #7. "), prompts[0])
self.assertFalse(self.file.exists())
def test_a_chunk_with_work_again_stays_parked_until_a_slot_is_free(self) -> None:
self.description = DESCRIPTION.replace("2", "1")
self.forges = [awaiting(), awaiting(decision="APPROVED")]
fake = FakeEffects(streams=[self.worker(), self.worker()], claude=[judged("finished"), judged("finished")], git=UNREAD, windows=PARKED_WINDOW + "ABC-22\t0\t@10\n")
slept: list[bool] = []
def sleep(seconds: float) -> None:
slept.append(self.file.exists())
if len(slept) == 3:
fake.windows = PARKED_WINDOW
fake.effects = lambda made=fake.effects(): dataclasses.replace(made, sleep=sleep) # type: ignore[method-assign]
code, out, err, prompts = self.parked_run(fake)
self.assertEqual(code, 0, err)
self.assertEqual(slept, [True] * 3)
self.assertEqual(out.count("pull request #7 passed its checks and is approved, but the chunk stays parked: the epic runs as many chunks as its `**Max parallel chunks:**` line allows: 1; trying again every 60 seconds\n"), 1)
self.assertEqual([args[3] for args in fake.tmux_calls if args[0] == "rename-window"], ["ABC-20 awaits an approval", "ABC-20 awaits a slot", "ABC-20"])
self.assertEqual(len(prompts), 2)
def test_a_chunk_parks_and_resumes_though_the_next_chunk_cannot_start(self) -> None:
self.forges = [awaiting(), awaiting(decision="APPROVED")]
worker = self.worker()
def unreadable_after(*args: object) -> object:
self.description = Failure("Jira answered 503")
return worker(*args) # type: ignore[arg-type]
fake = FakeEffects(streams=[unreadable_after, self.worker()], claude=[judged("finished"), judged("finished")], git=UNREAD, windows=PARKED_WINDOW)
slept: list[bool] = []
# The epic's description cannot be read from the first worker's run until the parked chunk first sleeps.
description = Description("")
object.__setattr__(description, "read", lambda: self.description)
self.backend = lambda config, key: (MemoryEpic(key, list(self.issues)), EpicRecord(description)) # type: ignore[method-assign,arg-type]
def sleep(seconds: float) -> None:
slept.append(self.file.exists())
self.description = DESCRIPTION
fake.effects = lambda made=fake.effects(): dataclasses.replace(made, sleep=sleep) # type: ignore[method-assign]
code, out, err, prompts = self.parked_run(fake)
self.assertEqual(code, 0, err)
self.assertIn("parked: pull request #7 awaits an approval\ncould not start the next chunk: Jira answered 503\n", out)
self.assertEqual(slept, [True])
self.assertFalse(self.file.exists())
self.assertEqual(len(prompts), 2)
def test_a_chunk_parks_and_resumes_though_the_epics_issues_cannot_be_read(self) -> None:
self.forges = [awaiting(), awaiting(decision="APPROVED")]
store = MemoryEpic("ABC-12", list(self.issues))
read = store.read
unreadable = [False]
worker = self.worker()
def unreadable_after(*args: object) -> object:
unreadable[0] = True
return worker(*args) # type: ignore[arg-type]
store.read = lambda: Failure("Jira answered 502") if unreadable[0] else read() # type: ignore[method-assign]
self.backend = lambda config, key: (store, EpicRecord(Description(self.description))) # type: ignore[method-assign,arg-type]
fake = FakeEffects(streams=[unreadable_after, self.worker()], claude=[judged("finished"), judged("finished")], git=UNREAD, windows=PARKED_WINDOW)
fake.effects = lambda made=fake.effects(): dataclasses.replace(made, sleep=lambda seconds: unreadable.__setitem__(0, False)) # type: ignore[method-assign]
code, out, err, prompts = self.parked_run(fake)
self.assertEqual(code, 0, err)
self.assertIn("parked: pull request #7 awaits an approval\ncould not start the next chunk: Jira answered 502\n", out)
self.assertFalse(self.file.exists())
self.assertEqual(len(prompts), 2)
def test_a_forge_that_cannot_be_read_parks_no_chunk_and_unparks_none(self) -> None:
self.forges = [awaiting(fails="gh pr checks")]
fake = FakeEffects(streams=[self.worker()], claude=[judged("finished")], git=UNREAD)
code, out, err, _ = self.parked_run(fake)
self.assertEqual(code, 0, err)
self.assertIn("cannot tell whether the chunk's pull request waits on a gate, so the chunk isn't parked: gh pr checks failed\nthe chunk finished; ", out)
self.assertFalse(self.file.exists())
self.forges = [awaiting(), awaiting(fails="gh pr list"), awaiting(fails="gh pr list"), awaiting(decision="APPROVED")]
self.gate_reads = 0
fake = FakeEffects(streams=[self.worker(), self.worker()], claude=[judged("finished"), judged("finished")], git=UNREAD, windows=PARKED_WINDOW)
code, out, err, prompts = self.parked_run(fake)
self.assertEqual(code, 0, err)
self.assertEqual(out.count("cannot read the gate: gh pr list failed; trying again every 60 seconds\n"), 1)
self.assertEqual([args[3] for args in fake.tmux_calls if args[0] == "rename-window"], ["ABC-20 awaits an approval", "ABC-20"])
self.assertEqual(len(prompts), 2)
def test_stops_where_the_chunk_cannot_be_recorded_as_parked_or_the_record_cannot_be_read(self) -> None:
self.forges = [awaiting()]
self.file.parent.parent.mkdir(parents=True)
self.file.parent.write_text("a file")
fake = FakeEffects(streams=[self.worker()], claude=[judged("finished")], git=UNREAD)
code, _, err, _ = self.parked_run(fake)
self.assertEqual(code, 1)
self.assertIn(f"cannot record the parked chunk in {self.file}: ", err)
self.file.parent.unlink()
parked.park(self.file.parent.parent, parked.Parked("ABC-20", "/w", "7", "s", "an approval"))
self.file.write_text("{")
code, _, err, prompts = self.parked_run(FakeEffects(git=UNREAD))
self.assertEqual((code, prompts), (1, []))
self.assertIn(f"cannot read the parked chunk in {self.file}: ", err)
def test_stops_where_the_chunk_cannot_be_recorded_as_parked_no_longer(self) -> None:
self.forges = [awaiting(), awaiting(decision="APPROVED")]
fake = FakeEffects(streams=[self.worker()], claude=[judged("finished")], git=UNREAD, windows=PARKED_WINDOW)
fake.effects = lambda made=fake.effects(): dataclasses.replace(made, sleep=lambda seconds: self.file.parent.chmod(0o555)) # type: ignore[method-assign]
self.addCleanup(lambda: self.file.parent.chmod(0o755))
code, _, err, prompts = self.parked_run(fake)
self.assertEqual((code, len(prompts)), (1, 1))
self.assertIn(f"cannot remove {self.file}: Permission denied", err)
class StepwiseStore:
"""A store whose workflow reaches each status in `after` only from the status it names there; every other call is the wrapped store's."""
def __init__(self, store: typing.Any, after: dict[str, str]) -> None:
self.store, self.after = store, after
def __getattr__(self, name: str) -> typing.Any:
return getattr(self.store, name)
def move_issue(self, key: str, status: str) -> None | Failure:
now = self.store.within(key).status
if status in self.after and now not in (status, self.after[status]):
return Failure(f"{key} has no transition to {status!r} from its status {now!r}")
return self.store.move_issue(key, status)
class LaggingStore:
"""A store whose every read answers `read`, as a search that doesn't show the latest move yet; every other call is the wrapped store's."""
def __init__(self, store: typing.Any, read: typing.Any) -> None:
self.store, self.answer = store, read
def __getattr__(self, name: str) -> typing.Any:
return getattr(self.store, name)
def read(self) -> typing.Any:
return self.answer
class AnEpicsWorkingBranch(DoEpicTest):
"""A chunk in a repo whose config sets `epic-branch`, so its pull request goes into the branch ABC-12."""
def setUp(self) -> None:
super().setUp()
self.repo_config = self.repo_chunk() / "config.toml"
self.repo_config.write_text(self.repo_config.read_text(encoding="utf-8") + 'epic-branch = "{epic}"\nmerge = "human"\n', encoding="utf-8")
self.checkout = str(self.home / "code/api")
self.store = MemoryEpic("ABC-12", [self.issues[0], issue("ABC-22", "do-epic-claude", blockers=("ABC-20",))])
self.backend = lambda config, key: (self.store, EpicRecord(Description(self.description))) # type: ignore[method-assign,arg-type]
self.git_calls: list[tuple[tuple[str, ...], str | None]] = []
self.git_timeouts: list[tuple[str, object]] = []
def settings(self, more: str) -> None:
(self.home / ".claude-projects" / "do-epic" / "config.toml").write_text(SETTINGS + more, encoding="utf-8")
def with_git(self, fake: FakeEffects, **answers: str | Failure) -> FakeEffects:
"""fake, whose git answers each command by its first word: as answers has it, else as a checkout whose origin has the branch ABC-12, which holds origin/main."""
answered = {"symbolic-ref": "origin/main\n", "fetch": "", "ls-remote": "aaa\trefs/heads/ABC-12\n", "rev-parse": "aaa\n", "rev-list": "0\n", "config": ""} | {name.replace("_", "-"): answer for name, answer in answers.items()}
def git(*args: str, cwd: str | None = None, **more: object) -> str | Failure:
self.git_calls.append((args, cwd))
self.git_timeouts.append((args[0], more.get("timeout")))
return answered.get(args[0], Failure("no git"))
fake.effects = lambda made=fake.effects(): dataclasses.replace(made, git=git) # type: ignore[method-assign]
return fake
def recorded(self, **answers: object) -> Forge:
"""A forge like `awaiting`'s, in a checkout that records ABC-12 as the base of ABC-20's branch."""
forge = awaiting(**answers)
forge.answers["git config"] = "ABC-12\n"
return forge
def test_a_chunk_that_starts_levels_the_branch_and_records_it_as_the_chunks_base(self) -> None:
fake = self.with_git(FakeEffects())
out = io.StringIO()
with contextlib.redirect_stdout(out):
self.assertEqual(main.epic_based("ABC-20", self.checkout, self.epic_run(fake)), "ABC-12")
self.assertEqual(self.git_calls, [(args, self.checkout) for args in (("symbolic-ref", "--short", "refs/remotes/origin/HEAD"), ("ls-remote", "--heads", "origin", "refs/heads/ABC-12"), ("fetch", "--quiet", "origin"), ("rev-list", "--count", "origin/ABC-12..origin/main"), ("config", "branch.ABC-20.chunk-base", "ABC-12"))])
self.assertIn("origin/ABC-12 already holds origin/main; ABC-20's pull request goes into ABC-12\n", out.getvalue())
def test_a_call_to_origin_that_levels_the_branch_is_stopped_after_a_minute_so_no_window_hangs_before_its_first_cycle(self) -> None:
main.epic_based("ABC-20", self.checkout, self.epic_run(self.with_git(FakeEffects(), ls_remote="", push="")))
self.assertEqual([timed for timed in self.git_timeouts if timed[0] in ("fetch", "ls-remote", "push")], [("ls-remote", 60), ("fetch", 60), ("push", 60), ("fetch", 60)])
def test_says_the_default_branchs_whole_name_however_it_ends(self) -> None:
out = io.StringIO()
with contextlib.redirect_stdout(out):
main.epic_based("ABC-20", self.checkout, self.epic_run(self.with_git(FakeEffects(), symbolic_ref="origin/BOX\n")))
self.assertIn("origin/ABC-12 already holds origin/BOX; ABC-20's pull request goes into ABC-12\n", out.getvalue())
def test_a_folder_no_checkout_holds_stops_with_the_reason_its_config_cannot_be_found(self) -> None:
elsewhere = self.home / "elsewhere"
elsewhere.mkdir()
unnamed = main.config_located(str(elsewhere), self.home)
assert isinstance(unnamed, Failure), unnamed
self.assertEqual(main.epic_based("ABC-20", str(elsewhere), self.epic_run(self.with_git(FakeEffects()))), main.Stop(1, unnamed.reason))
def test_a_repo_whose_config_sets_no_epic_branch_has_none_and_runs_no_git(self) -> None:
self.repo_config.write_text(self.repo_config.read_text(encoding="utf-8").replace('epic-branch = "{epic}"\n', ""), encoding="utf-8")
self.assertIsNone(main.epic_based("ABC-20", self.checkout, self.epic_run(self.with_git(FakeEffects()))))
self.assertEqual(self.git_calls, [])
def test_a_default_branch_that_conflicts_stops_the_loop_for_a_person_and_records_no_base(self) -> None:
stop = main.epic_based("ABC-20", self.checkout, self.epic_run(self.with_git(FakeEffects(), rev_list="1\n", merge_tree=Failure("git merge-tree --write-tree origin/ABC-12 origin/main: "))))
self.assertEqual(stop, main.Stop(1, f"cannot ready the epic's working branch ABC-12 in {self.checkout} for ABC-20: origin/main doesn't merge into origin/ABC-12 cleanly, so a person merges it: check ABC-12 out, run `git merge origin/main`, resolve the conflicts and push; once that is settled, run `do-epic ABC-12` to start the chunk again"))
self.assertNotIn("config", [args[0] for args, _ in self.git_calls])
def test_a_checkout_that_names_no_default_branch_stops_before_the_branch_is_touched(self) -> None:
stop = main.epic_based("ABC-20", self.checkout, self.epic_run(self.with_git(FakeEffects(), symbolic_ref=Failure("no origin/HEAD"))))
self.assertIsInstance(stop, main.Stop)
self.assertIn("no origin/HEAD", stop.reason)
self.assertEqual(len(self.git_calls), 1)
def test_a_chunk_whose_working_branch_cannot_be_readied_leaves_its_issue_unstarted(self) -> None:
code, _, err = self.run_main(["--chunk", "ABC-20", "ABC-12"], self.with_git(FakeEffects(), rev_list="1\n", merge_tree=Failure("git merge-tree --write-tree origin/ABC-12 origin/main: ")), MODELS)
self.assertEqual(code, 1)
self.assertIn("cannot ready the epic's working branch ABC-12", err)
self.assertEqual(self.store.writes, [])
def test_its_issue_moves_as_the_pull_request_opens_and_merges_and_no_person_merges_it(self) -> None:
self.settings('jira-unblocking-statuses = ["Release Ready"]\njira-automation-moves-issues = true\njira-pull-request-open-status = "Code Review"\njira-pull-request-merged-status = "Release Ready"\n')
self.forges = [self.recorded(base="ABC-12"), self.recorded(base="ABC-12"), self.recorded(base="ABC-12", decision="APPROVED")]
fake = self.with_git(FakeEffects(streams=[self.worker(), self.worker()], claude=[judged("finished"), judged("finished")], windows=PARKED_WINDOW))
code, out, err = self.run_main(["--chunk", "ABC-20", "ABC-12"], fake, MODELS)
prompts = [what[what.index("-p") + 1] for seam, what in fake.calls if seam == "stream_claude"]
self.assertEqual(code, 0, err)
self.assertEqual([write for write in self.store.writes if write.startswith("move ")], ["move ABC-20 to Code Review", "move ABC-20 to Release Ready"])
self.assertEqual({each.key: (each.status, each.done) for each in self.store.issues}["ABC-20"], ("Release Ready", False))
# Approved, the pull request awaits no person's merge, though the repo's config says `merge = "human"`.
self.assertEqual(out.count("parked: "), 1)
self.assertIn("parked: pull request #7 awaits an approval\n", out)
self.assertIn("the chunk finished; started ABC-22\n", out)
self.assertIn("The chunk's pull request goes into the epic's working branch `ABC-12`", prompts[0])
self.assertIn(("config", "branch.ABC-20.chunk-base", "ABC-12"), [args for args, _ in self.git_calls])
def test_a_chunk_parked_on_a_persons_merge_into_the_default_branch_stays_parked_until_its_pull_request_goes_into_the_branch(self) -> None:
self.settings('jira-unblocking-statuses = ["Release Ready"]\njira-pull-request-merged-status = "Release Ready"\n')
session = main.session_named("A ABC-12 do-epic ABC-20", paths_from(self.home).claude_code_transcripts)
parked.park(self.home / ".local/state/do-epic/ABC-12", parked.Parked("ABC-20", "/code/api-ABC-20", "7", str(session.id), "your merge"))
self.worker()(["--session-id", str(session.id)])
# The pull request was opened into main before the setting was on; a person then changes its base to ABC-12.
self.forges = [self.recorded(decision="APPROVED"), self.recorded(decision="APPROVED"), self.recorded(base="ABC-12", decision="APPROVED")]
fake = self.with_git(FakeEffects(streams=[self.worker()], claude=[judged("finished")], windows="ABC-20 awaits your merge\t0\t@9\n"))
code, out, err = self.run_main(["--chunk", "ABC-20", "ABC-12"], fake, MODELS)
prompts = [what[what.index("-p") + 1] for seam, what in fake.calls if seam == "stream_claude"]
self.assertEqual(code, 0, err)
self.assertEqual(out.count("cannot read the gate: pull request #7 merges into main on the forge, but this checkout takes ABC-12 as the base of its branch; a person settles which holds, and changes the pull request's base on the forge or the branch's `chunk-base` in git's config; trying again every 60 seconds\n"), 1)
self.assertEqual(len(prompts), 1)
self.assertTrue(prompts[0].startswith("do-epic parked the chunk while its pull request awaited a person's merge. It resumes now: pull request #7 passed its checks and is approved. "), prompts[0])
def test_a_chunk_that_started_before_the_setting_was_on_keeps_its_merge_for_a_person(self) -> None:
self.settings('jira-unblocking-statuses = ["Release Ready"]\njira-pull-request-open-status = "Code Review"\njira-pull-request-merged-status = "Release Ready"\n')
set_on = self.repo_config.read_text(encoding="utf-8")
self.repo_config.write_text(set_on.replace('epic-branch = "{epic}"\n', ""), encoding="utf-8")
worker = self.worker()
def turns_the_setting_on(args: list[str]) -> object:
self.repo_config.write_text(set_on, encoding="utf-8")
return worker(args)
self.forges = [awaiting(decision="APPROVED"), awaiting(decision="APPROVED"), awaiting(pulls=""), CLEANED]
fake = self.with_git(FakeEffects(streams=[turns_the_setting_on, self.worker()], claude=[judged("unfinished"), judged("finished")], windows="ABC-20 awaits your merge\t0\t@9\n"))
code, out, err = self.run_main(["--chunk", "ABC-20", "ABC-12"], fake, MODELS)
self.assertEqual(code, 0, err)
self.assertNotIn("config", [args[0] for args, _ in self.git_calls], "no base recorded, so the pull request goes into the default branch")
self.assertIn("parked: pull request #7 awaits your merge\n", out)
self.assertNotIn("move ABC-20 to Code Review", self.store.writes)
def test_an_issue_that_cannot_move_to_the_open_status_says_so_and_its_chunk_goes_on(self) -> None:
self.settings('jira-unblocking-statuses = ["Release Ready"]\njira-pull-request-open-status = "Code Review"\njira-pull-request-merged-status = "Release Ready"\n')
self.backend = lambda config, key: (StepwiseStore(self.store, {"Code Review": "QA"}), EpicRecord(Description(self.description))) # type: ignore[method-assign,arg-type]
self.forges = [self.recorded(base="ABC-12"), self.recorded(base="ABC-12"), self.recorded(base="ABC-12", decision="APPROVED")]
fake = self.with_git(FakeEffects(streams=[self.worker(), self.worker()], claude=[judged("finished"), judged("finished")], windows=PARKED_WINDOW))
code, out, err = self.run_main(["--chunk", "ABC-20", "ABC-12"], fake, MODELS)
self.assertEqual(code, 0, err)
self.assertIn("ABC-20 did not move to 'Code Review' though its pull request is open: ABC-20 has no transition to 'Code Review' from its status 'To Do'\n", out)
def test_a_finished_chunk_whose_issue_has_no_pull_request_into_the_epic_branch_moves_it_to_done(self) -> None:
self.settings('jira-unblocking-statuses = ["Release Ready"]\njira-pull-request-merged-status = "Release Ready"\n')
with contextlib.redirect_stdout(io.StringIO()):
self.assertEqual(main.handed_on("ABC-20", self.epic_run(FakeEffects(windows="")), main.Landed.WITH_A_HUMAN).code, 0)
self.assertEqual((self.store.issues[0].status, self.store.issues[0].done), ("Done", True))
# A chunk not marked as in a repo moves its issue to done itself, even where the automation moves issues.
self.settings('jira-unblocking-statuses = ["Release Ready"]\njira-automation-moves-issues = true\n')
self.store.change("ABC-22", status="Release Ready")
with contextlib.redirect_stdout(io.StringIO()):
self.assertEqual(main.handed_on("ABC-22", self.epic_run(FakeEffects(windows=""))).code, 0)
self.assertEqual((self.store.issues[1].status, self.store.issues[1].done), ("Done", True))
def test_a_read_that_does_not_show_the_move_yet_still_counts_the_issue_moved(self) -> None:
self.settings('jira-unblocking-statuses = ["Release Ready"]\njira-pull-request-merged-status = "Release Ready"\n')
before = self.store.read()
lagging = LaggingStore(self.store, before)
out = io.StringIO()
with contextlib.redirect_stdout(out):
stop = main.handed_on("ABC-20", dataclasses.replace(self.epic_run(FakeEffects(windows="")), store=lagging), main.Landed.ON_EPIC_BRANCH)
self.assertEqual(stop.code, 0, stop.reason)
self.assertIn("the chunk finished; started ABC-22\n", out.getvalue())
unread = LaggingStore(self.store, Failure("Jira answered 503"))
stop = main.handed_on("ABC-22", dataclasses.replace(self.epic_run(FakeEffects(windows="")), store=unread), main.Landed.ON_EPIC_BRANCH)
self.assertEqual(stop, main.Stop(1, "the chunk finished, but the next could not start: Jira answered 503"))
def test_the_epics_finishing_is_due_once_every_issue_has_the_merged_status(self) -> None:
self.settings('jira-unblocking-statuses = ["Release Ready"]\njira-pull-request-merged-status = "Release Ready"\n')
for each in ("ABC-20", "ABC-22"):
self.store.change(each, status="Release Ready")
self.assertIsInstance(main.chunk_work("ABC-12", None, "English", self.epic_run(FakeEffects())), tuple)
def test_without_a_merged_status_a_finished_chunk_stops_where_automation_moves_issues_and_is_done_where_it_doesnt(self) -> None:
self.settings('jira-unblocking-statuses = ["Release Ready"]\njira-automation-moves-issues = true\n')
stop = main.handed_on("ABC-20", self.epic_run(FakeEffects()), main.Landed.ON_EPIC_BRANCH)
self.assertEqual(stop, main.Stop(1, "the chunk finished, but its issue stays as it is: its pull request merged into the epic's working branch, where the team's automation moves no issue, and do-epic's config names no `jira-pull-request-merged-status` to move it to. Move ABC-20 in Jira, then run `do-epic ABC-12` to start the chunks it blocks"))
self.assertEqual(self.store.writes, [])
self.settings("")
out = io.StringIO()
with contextlib.redirect_stdout(out):
self.assertEqual(main.handed_on("ABC-20", self.epic_run(FakeEffects(windows="")), main.Landed.ON_EPIC_BRANCH).code, 0)
self.assertTrue(self.store.issues[0].done)
def test_an_issue_whose_workflow_reaches_the_merged_status_only_through_the_open_status_moves_through_it(self) -> None:
self.settings('jira-unblocking-statuses = ["Release Ready"]\njira-pull-request-open-status = "Code Review"\njira-pull-request-merged-status = "Release Ready"\n')
epic = self.epic_run(FakeEffects(windows=""))
stepwise = StepwiseStore(self.store, {"Release Ready": "Code Review"})
with contextlib.redirect_stdout(io.StringIO()):
stop = main.handed_on("ABC-20", dataclasses.replace(epic, store=stepwise), main.Landed.ON_EPIC_BRANCH)
self.assertEqual(stop.code, 0, stop.reason)
self.assertEqual(self.store.writes, ["move ABC-20 to Code Review", "move ABC-20 to Release Ready"])
# An issue the open status doesn't lead on from stops on the move it asked for.
stuck = StepwiseStore(self.store, {"Release Ready": "QA", "Code Review": "QA"})
stop = main.handed_on("ABC-22", dataclasses.replace(epic, store=stuck), main.Landed.ON_EPIC_BRANCH)
self.assertTrue(stop.reason.startswith("the chunk finished, but its issue could not move to 'Release Ready': ABC-22 has no transition to 'Release Ready'"), stop.reason)
def test_an_issue_that_cannot_move_to_the_merged_status_stops_and_says_what_to_do(self) -> None:
self.settings('jira-unblocking-statuses = ["Release Ready"]\njira-pull-request-merged-status = "Release Ready"\n')
self.store.fails = "Jira answered 503"
stop = main.handed_on("ABC-20", self.epic_run(FakeEffects()), main.Landed.ON_EPIC_BRANCH)
self.assertEqual(stop.code, 1)
self.assertTrue(stop.reason.startswith("the chunk finished, but its issue could not move to 'Release Ready': "), stop.reason)
self.assertTrue(stop.reason.endswith("once it has that status in Jira, run `do-epic ABC-12` to start the chunks it blocks"), stop.reason)
class TheStatus(DoEpicTest):
def test_prints_what_each_open_issue_does_and_starts_nothing(self) -> None:
self.issues = [issue("ABC-21", "repo:api"), issue("ABC-24", "repo:api"), issue("ABC-27")]
fake = FakeEffects(windows="ABC-21 ?\t0\t@2\n")
code, out, err = self.run_main(["ABC-12", "--status"], fake)
self.assertEqual((code, err), (0, ""))
self.assertEqual(out.replace("<1790000000> ", "").splitlines(), [
"ABC-21 asks you: answer its question in the tmux window epic-ABC-12:ABC-21",
"ABC-24 waits: it has not started; `do-epic ABC-12` starts it once the epic and its repo have room",
"ABC-27 waits: no label names its repo",
])
self.assertEqual({args[0] for args in fake.tmux_calls}, {"-V", "list-windows"})
self.assertTrue(all("epic-ABC-12" in " ".join(args) for args in fake.tmux_calls if args[0] == "list-windows"), fake.tmux_calls)
def test_says_which_issue_starts_after_those_that_start_by_score(self) -> None:
self.issues = [issue("ABC-21", "do-epic-claude"), dataclasses.replace(issue("ABC-24", "do-epic-claude"), scores={"L": 1, "E": 1, "I": 1, "S": 1})]
room = "it has not started; `do-epic ABC-12` starts it once the epic and its repo have room"
out = self.run_main(["ABC-12", "--status"], FakeEffects())[1]
self.assertEqual(out.replace("<1790000000> ", "").splitlines(), [f"ABC-21 waits: {room}, after each issue that holds every score, since it doesn't", f"ABC-24 waits: {room}"])
def test_clones_no_missing_repo_to_print_the_status(self) -> None:
for repo in ("api", "web"):
configured(self, self.home / "code" / repo, home=self.home)
(self.home / "code" / repo / "README.md").write_text("## Goals\nServe the API.\n\n## Audience\nIts callers.\n", encoding="utf-8")
shutil.rmtree(self.home / "code/web")
self.description = DESCRIPTION + "\n## Scoring\n`Score = V`\n"
self.issues = [dataclasses.replace(issue(key, label), scores={"L": 1, "E": 1, "I": 1, "S": 1}) for key, label in (("ABC-20", "repo:api"), ("ABC-22", "repo:web"))]
fake = FakeEffects(git=["git@host.example:team/api.git"] * 3)
code, out, _ = self.run_main(["ABC-12", "--status"], fake)
self.assertEqual(code, 0)
self.assertIn("ABC-20 waits: it has not started", out)
self.assertEqual([what for seam, what in fake.calls if seam == "git" and "clone" in what], [])
def test_says_so_where_no_issue_is_open_or_the_epic_cannot_be_read(self) -> None:
self.issues = [issue("ABC-20", "repo:api", done=True)]
self.assertIn("the epic ABC-12 has no open issue\n", self.run_main(["ABC-12", "--status"], FakeEffects())[1])
store = MemoryEpic("ABC-12", [])
store.read = lambda: Failure("Jira answered 503") # type: ignore[method-assign]
self.backend = lambda config, key: (store, EpicRecord(Description(self.description))) # type: ignore[method-assign,arg-type]
code, _, err = self.run_main(["ABC-12", "--status"], FakeEffects())
self.assertEqual(code, 1)
self.assertIn("Jira answered 503\n", err)
BANNER = "dry run: nothing is written to Jira and no window starts, so a line below that says an issue is labelled, split or scored shows what a real run would do. A real run would also start in Jira the issue of each chunk it starts: assign it and, where config.toml says so, move it and add it to a sprint"
class TheDryRun(DoEpicTest):
def setUp(self) -> None:
super().setUp()
for repo in ("api", "web"):
configured(self, self.home / "code" / repo, home=self.home)
(self.home / "code" / repo / "README.md").write_text("## Goals\nServe the API.\n\n## Audience\nIts callers.\n", encoding="utf-8")
self.stores: list[MemoryEpic] = []
made = self.backend
self.backend = lambda config, key: (self.stores.append(made(config, key)[0]) or self.stores[-1], EpicRecord(Description(self.description))) # type: ignore[method-assign,assignment]
def test_prints_each_write_and_each_chunk_it_would_start_and_makes_none_of_them(self) -> None:
self.issues = [issue("ABC-20"), issue("ABC-21", "do-epic-claude")]
parts = structured({"parts": [{"repo": "api", "change": "Add the endpoint."}, {"repo": "web", "change": "Call it."}], "comment": "Split by repo: api and web."})
fake = FakeEffects(on_terminal=True, claude=[parts])
code, out, err = self.run_main(["ABC-12", "--dry-run"], fake)
self.assertEqual((code, err), (0, ""))
shown = out.replace("<1790000000> ", "")
self.assertIn("planning would write to Jira:\n- file ABC-new1 under ABC-20: [api] Do ABC-20, labelled repo:api\n- file ABC-new2 under ABC-20: [web] Do ABC-20, labelled repo:web\n- comment on ABC-20: Split by repo: api and web.\n", shown)
self.assertIn("would start ABC-new1, ABC-new2\nABC-21 waits: the epic runs as many chunks as its `**Max parallel chunks:**` line allows: 2\n", shown)
self.assertEqual(self.stores[0].writes, [])
self.assertEqual([each.key for each in self.stores[0].issues], ["ABC-20", "ABC-21"])
changing = {"new-session", "new-window", "kill-window", "set-option", "rename-window"}
self.assertEqual([args for args in fake.tmux_calls if args[0] in changing], [])
def test_prints_each_move_of_a_parent_whose_sub_tasks_a_person_filed(self) -> None:
(self.home / ".claude-projects" / "do-epic" / "config.toml").write_text(SETTINGS + 'jira-unblocking-statuses = ["Release Ready"]\njira-sub-tasks-landed-transition = "Release Ready"\njira-finish-transition = "Mark as done"\njira-finish-status = "Done"\n', encoding="utf-8")
self.issues = [issue("ABC-20", status="In Progress"), issue("ABC-30", "do-epic-claude", parent="ABC-20", status="Release Ready"), issue("ABC-21"), issue("ABC-31", "do-epic-claude", parent="ABC-21", done=True), issue("ABC-22", "do-epic-claude", blockers=("ABC-20",))]
code, out, err = self.run_main(["ABC-12", "--dry-run"], FakeEffects())
self.assertEqual((code, err), (0, ""))
self.assertIn("planning would write to Jira:\n- move ABC-20 by Release Ready\n- finish ABC-21\nwould start ABC-22\n", out.replace("<1790000000> ", ""))
self.assertEqual(self.stores[0].writes, [])
def test_prints_the_label_a_pick_would_give_an_issue(self) -> None:
self.issues = [issue("ABC-20")]
code, out, _ = self.run_main(["ABC-12", "--dry-run"], FakeEffects(claude=[structured({"parts": []}), structured({"pick": "claude"})]))
self.assertEqual(code, 0)
self.assertIn("planning would write to Jira:\n- label ABC-20 with do-epic-claude\nwould start ABC-20\n", out.replace("<1790000000> ", ""))
def test_counts_the_chunks_it_would_start_against_the_epics_cap_and_a_repos_limit(self) -> None:
self.issues = [issue("ABC-21", "do-epic-claude"), issue("ABC-22", "do-epic-claude"), issue("ABC-23", "do-epic-claude")]
self.description = DESCRIPTION.replace("2", "1")
code, out, _ = self.run_main(["ABC-12", "--dry-run"], FakeEffects(on_terminal=True))
self.assertEqual(code, 0)
shown = out.replace("<1790000000> ", "")
self.assertIn("planning wouldn't write anything to Jira\nwould start ABC-21\n", shown)
self.assertIn("ABC-22 waits: the epic runs as many chunks as its `**Max parallel chunks:**` line allows: 1\n", shown)
def test_prints_the_question_planning_would_ask_and_asks_none(self) -> None:
self.issues = [issue("ABC-20")]
unclear = structured({"pick": "unclear", "question": "Is the importer in api or in web?"})
fake = FakeEffects(on_terminal=True, claude=[structured({"parts": []}), unclear], inputs=["api"])
code, out, _ = self.run_main(["ABC-12", "--dry-run"], fake)
self.assertEqual(code, 0)
self.assertIn("ABC-20 waits for your answer: Is the importer in api or in web?", out)
self.assertEqual([seam for seam, _ in fake.calls if seam == "input"], [])
self.assertIn("planning wouldn't write anything to Jira\n", out)
def test_works_without_tmux_and_a_chunk_in_a_missing_repo_waits(self) -> None:
self.issues = [issue("ABC-20", "repo:missing"), issue("ABC-21", "do-epic-claude")]
fake = FakeEffects(on_terminal=False, tmux_version="")
code, out, _ = self.run_main(["ABC-12", "--dry-run"], fake)
self.assertEqual(code, 0)
self.assertIn("would start ABC-21\n", out)
self.assertIn("ABC-20 waits: missing is missing", out)
self.assertEqual([what for seam, what in fake.calls if seam == "git" and "clone" in what], [])
def test_prints_the_scores_it_would_write_and_the_order_the_issues_would_start_in(self) -> None:
(self.home / planning.RULE).parent.mkdir(parents=True, exist_ok=True)
(self.home / planning.RULE).write_text("L is how much the item changes.\n", encoding="utf-8")
self.description = DESCRIPTION.replace("Ship the import.", "1. **Achieve:** Ship the import.") + "\n## Scoring\n`Score = V`\n"
self.issues = [issue("ABC-20", "do-epic-claude"), issue("ABC-21", "do-epic-claude")]
answer = {"L": 2, "E": 1, "I": 2, "S": 3, "comment": "Scored to decide what starts first."}
fake = FakeEffects(on_terminal=False, claude=[structured(answer | {"moves": "epic 1 by 2"}), structured(answer | {"moves": "epic 1 by 9"})])
code, out, err = self.run_main(["ABC-12", "--dry-run"], fake)
self.assertEqual((code, err), (0, ""))
shown = out.replace("<1790000000> ", "")
self.assertIn("by score, the issues of ABC-12 start in the order ABC-21, ABC-20\n", shown)
self.assertIn("planning would write to Jira:\n- score ABC-20 L 2, E 1, I 2, S 3, Moves epic 1 by 2, with the comment: Scored to decide what starts first.\n- score ABC-21 L 2, E 1, I 2, S 3, Moves epic 1 by 9, with the comment: Scored to decide what starts first.\n", shown)
self.assertIn("would start ABC-21, ABC-20\n", shown)
self.assertEqual(self.stores[0].writes, [])
def test_says_why_the_issues_start_in_backlog_order_and_names_no_order_of_one_issue(self) -> None:
self.issues = [dataclasses.replace(issue(key, "do-epic-claude"), scores={"L": 1, "E": 1, "I": 1, "S": 1}) for key in ("ABC-20", "ABC-21")]
out = io.StringIO()
with contextlib.redirect_stdout(out):
main.chunks_started(self.epic_run(FakeEffects(on_terminal=False)), self.issues, None)
self.assertIn("the issues of ABC-12 start in Jira's backlog order, since they cannot be put in order of score: the epic ABC-12's description states `Score = ...` 0 times under ## Scoring", out.getvalue())
self.description = DESCRIPTION.replace("Ship the import.", "1. **Achieve:** Ship the import.") + "\n## Scoring\n`Score = V`\n"
self.issues = self.issues[:1]
code, out, err = self.run_main(["ABC-12", "--dry-run"], FakeEffects(on_terminal=False))
self.assertEqual((code, err), (0, ""))
self.assertNotIn("by score", out)
def test_clones_no_missing_repo_and_says_so(self) -> None:
shutil.rmtree(self.home / "code/web")
self.description = DESCRIPTION + "\n## Scoring\n`Score = V`\n"
self.issues = [dataclasses.replace(issue(key, label), scores={"L": 1, "E": 1, "I": 1, "S": 1}) for key, label in (("ABC-20", "repo:api"), ("ABC-22", "repo:web"))]
fake = FakeEffects(on_terminal=False, git=["git@host.example:team/api.git"] * 3)
code, out, err = self.run_main(["ABC-12", "--dry-run"], fake)
self.assertEqual((code, err), (0, ""))
missing = f"cannot clone git@host.example:team/web to {self.home / 'code/web'}: a dry run doesn't clone a repo, but a real run would. Where does web live?"
# The reason the order of score is missing is said once, by the planning.
self.assertEqual(out.replace("<1790000000> ", ""), f"{BANNER}\nthe epic ABC-12 is not planned in full, so the writes below are those it made before it stopped: {missing}\nthe issues of ABC-12 start in Jira's backlog order, since they cannot be put in order of score\nplanning wouldn't write anything to Jira\nwould start ABC-20\nABC-22 waits: {missing}\n")
self.assertEqual([what for seam, what in fake.calls if seam == "git" and "clone" in what], [])
def test_says_on_stdout_that_planning_stopped_at_a_missing_repo_and_what_the_writes_are(self) -> None:
shutil.rmtree(self.home / "code/web")
self.issues = [issue("ABC-20"), issue("ABC-22", "repo:api"), issue("ABC-23", "repo:web")]
fake = FakeEffects(on_terminal=False, git=["git@host.example:team/api.git", ""])
code, out, err = self.run_main(["ABC-12", "--dry-run"], fake)
self.assertEqual((code, err), (0, ""))
stopped = f"the epic ABC-12 is not planned in full, so the writes below are those it made before it stopped: cannot clone git@host.example:team/web to {self.home / 'code/web'}: a dry run doesn't clone a repo, but a real run would. Where does web live?\n"
self.assertIn(stopped, out.replace("<1790000000> ", ""))
self.assertIn("planning wouldn't write anything to Jira\n", out)
def test_indents_the_lines_after_the_first_of_a_comment_under_its_bullet(self) -> None:
self.issues = [issue("ABC-20")]
parts = structured({"parts": [{"repo": "api", "change": "Add it."}, {"repo": "web", "change": "Call it."}], "comment": "Split by repo.\nSecond line."})
code, out, _ = self.run_main(["ABC-12", "--dry-run"], FakeEffects(claude=[parts]))
self.assertEqual(code, 0)
self.assertIn("\n- comment on ABC-20: Split by repo.\n Second line.\n", out)
def test_stops_where_the_epic_cannot_be_read(self) -> None:
store = MemoryEpic("ABC-12", [], fails="Jira answered 503")
self.backend = lambda config, key: (store, EpicRecord(Description(self.description))) # type: ignore[method-assign,arg-type]
code, _, err = self.run_main(["ABC-12", "--dry-run"], FakeEffects())
self.assertEqual((code, "Jira answered 503\n" in err), (1, True))
def test_is_in_the_help(self) -> None:
self.assertIn("--dry-run", main.HELP)
self.assertEqual(self.run_main(["ABC-12", "--dry-run", "--status"], FakeEffects())[0], 1)
if __name__ == "__main__":
unittest.main()