Files
claude-config/bin/do_epic/test_main.py
T

656 lines
39 KiB
Python

import contextlib
import dataclasses
import datetime
import io
import json
import os
import pathlib
import shutil
import subprocess
import sys
import tempfile
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from do_epic import chunk_prompt, main
from project_config.test_project_config import configured
from do_epic.backend.protocol import EpicIssue
from do_epic.epic_record import EpicRecord
from agent_cycle import escalation_mark, judge, tmux
from failure import Failure
from loop_claude.test_loop_claude import FakeEffects, judged, Worker
from do_epic.test_gates import Forge
from do_epic.test_scheduler import issue
from loop_claude.loop.this_loop import Loop
from loop_claude.loop.reload import LoopRun
from do_epic.backend.fake import MemoryEpic
from do_epic import parked
from loop_state.paths import paths_from
from model_routing.route import Route
from model_routing.ladder import Rung
from do_epic.test_do_epic import SETTINGS
DESCRIPTION = "**Max parallel chunks:** 2\n\n## Goals\nShip the import.\n\n## Audience\nThe client's team.\n"
@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
# When the parked chunks of the status test were parked, and how the status prints it, in the machine's time zone.
PARKED_SINCE = 1_700_000_000
PARKED_ON = datetime.datetime.fromtimestamp(PARKED_SINCE).strftime("%Y-%m-%d %H:%M")
class DoEpicTest(unittest.TestCase):
def setUp(self) -> None:
made = tempfile.TemporaryDirectory()
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"), 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 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 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: no label names its repo\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_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 cycle(self, env: dict[str, str] | None = None) -> main.Cycle:
fake = FakeEffects(git=[Failure("no git"), Failure("no git")])
paths = paths_from(self.home)
config = main.load(self.home)
assert not isinstance(config, Failure)
store, record = self.backend(config, "ABC-12")
epic = main.EpicRun("ABC-12", config, store, record, paths, env or {}, pathlib.Path("/b/do-epic"), fake.effects())
place = main.chunk_root(self.issues[1], epic)
assert isinstance(place, tuple)
root, repo = place
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(LoopRun(1, root, "", "", chunk="ABC-21"), 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_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")
self.assertEqual(self.run_main(["ABC-12"], fake)[0], 0)
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_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.assertIn("not on a terminal; see the chunks with `tmux attach -t =epic-ABC-12`\n", out)
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.assertIn("started no chunk\n", out)
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_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_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_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("the chunk finished; started no other\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_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_is_a_humans_or_names_no_repo_is_no_chunk(self) -> None:
for labels, why in ((("do-epic-human",), "it is a human's task"), ((), "no label names its repo")):
with self.subTest(labels):
self.issues = [issue("ABC-20", *labels)]
fake = FakeEffects(git=UNREAD)
code, _, err = self.run_main(["--chunk", "ABC-20", "ABC-12"], fake, MODELS)
self.assertEqual(code, 1)
self.assertIn(f"ABC-20 is no chunk: {why}\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]
class AChunkWhosePullRequestWaitsOnAGate(DoEpicTest):
def setUp(self) -> None:
super().setUp()
self.repo_chunk()
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(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_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_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 TheStatus(DoEpicTest):
def test_prints_what_each_open_issue_does_and_starts_nothing(self) -> None:
self.issues = [issue("ABC-20", "repo:api"), issue("ABC-21", "repo:api"), issue("ABC-22", "repo:api"), issue("ABC-23", "repo:api", blockers=("ABC-20",)), issue("ABC-24", "repo:api"), issue("ABC-25", "repo:api", done=True), issue("ABC-26", "repo:api"), issue("ABC-27")]
folder = self.home / ".local/state/do-epic/ABC-12"
parked.park(folder, parked.Parked("ABC-20", "/code/api-ABC-20", "7", "s", "an approval"))
parked.park(folder, parked.Parked("ABC-26", "/code/api-ABC-26", "9", "s", "its checks"))
parked.park(folder, parked.Parked("ABC-28", "/code/api-ABC-28", "11", "s", "an approval"))
self.issues.insert(7, issue("ABC-28", "repo:api"))
for issue_key, when in (("ABC-20", PARKED_SINCE), ("ABC-26", PARKED_SINCE), ("ABC-28", PARKED_SINCE)):
os.utime(parked.file_of(folder, issue_key), (when, when))
fake = FakeEffects(windows="ABC-20 awaits an approval\t0\t@1\nABC-21 ?\t0\t@2\nABC-22\t1\t@3\nABC-28 awaits a slot\t0\t@4\n")
code, out, err = self.run_main(["ABC-12", "--status"], fake)
self.assertEqual((code, err), (0, ""))
self.assertEqual(out.replace("<1790000000> ", "").splitlines(), [
f"ABC-20 waits: it is parked: its pull request #7 awaits an approval, since {PARKED_ON}",
"ABC-21 asks you: answer its question in the tmux window epic-ABC-12:ABC-21",
"ABC-22 waits: its window stopped; run `do-epic ABC-12` to start it again",
"ABC-23 waits: ABC-20 blocks it",
"ABC-24 waits: it has not started; `do-epic ABC-12` starts it once the epic and its repo have room",
f"ABC-26 waits: it is parked: its pull request #9 awaits its checks, since {PARKED_ON}, and its window stopped; run `do-epic ABC-12` to start it again",
f"ABC-28 waits: it is parked: its worker has work again on pull request #11 and awaits a slot, since {PARKED_ON}",
"ABC-27 waits: no label names its repo",
])
self.assertEqual({args[0] for args in fake.tmux_calls}, {"-V", "list-windows"})
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_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)
if __name__ == "__main__":
unittest.main()