Answer principles round 1: 1 🔴, 7 🟡 (0 misread); every effect is handed in as an argument, no test patches a global, and the traces principle scopes tools that run on their user's machine
CI / tests (pull_request) Successful in 3m43s

This commit is contained in:
2026-11-19 12:42:03 +01:00
parent 8ca612b7a4
commit cb3135bc8c
124 changed files with 1437 additions and 793 deletions
+4 -2
View File
@@ -5,7 +5,7 @@ import typing
from adf_codec.convert import adfs_to_markdown, markdown_to_adf, Refused
from atlassian.client import basic_auth, Http, jira_json, ToAdf, ToMarkdown
from atlassian.jira import DONE, entry_of, finishing_transition, ISSUE_KEY, move_refusal, PERHAPS_FILED, PERHAPS_MOVED, project_of, rank_refusal, searched, unshaped
from atlassian.jira import DONE, entry_of, finishing_transition, ISSUE_KEY, MAX_PAGES, move_refusal, PERHAPS_FILED, PERHAPS_MOVED, project_of, rank_refusal, searched, unshaped
from project_config.settings import Epic, Finish, JIRA_FINISH_STATUS, JIRA_FINISH_TRANSITION
from do_epic.backend.protocol import EpicIssue, no_child, no_parent, no_words, unfit, unfit_label
from failure import Failure
@@ -33,6 +33,8 @@ class JiraEpic:
to_markdown: ToMarkdown = adfs_to_markdown
to_adf: ToAdf = markdown_to_adf
finish: Finish | None = None
# The pages a search may take before the read fails.
max_pages: int = MAX_PAGES
@property
def epic_key(self) -> str:
@@ -223,7 +225,7 @@ class JiraEpic:
def searched(self, what: str, parents: tuple[str, ...], authorization: str) -> list[Found] | Failure:
"""The issues whose parent is one of parents, in rank order."""
named = ", ".join(f'"{key}"' for key in parents)
answered = searched(self.epic.site, what, f"parent in ({named}) ORDER BY Rank ASC", {"fields": FIELDS, "properties": [PROPERTY]}, authorization, self.http)
answered = searched(self.epic.site, what, f"parent in ({named}) ORDER BY Rank ASC", {"fields": FIELDS, "properties": [PROPERTY]}, authorization, self.http, self.max_pages)
if isinstance(answered, Failure):
return answered
found = [found_of(raw) for raw in answered]
+8 -9
View File
@@ -5,7 +5,6 @@ import re
import sys
import tempfile
import unittest
import unittest.mock
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2]))
@@ -329,12 +328,13 @@ class Jira(Case):
({"key": "abc-34", "fields": valid}, "the search answered an issue without an issue key"),
({"key": "ABC-34", "fields": {"summary": "Count the runs.", "parent": {"key": "ABC-12"}, "issuelinks": []}}, shape + ": KeyError('labels')"),
*((({"key": "ABC-34", "fields": valid | changed}, shape + ": its summary, labels, assignee, status, parent, description or a linked issue's key holds another kind of value") for changed in (
{"summary": 3}, {"labels": "api"}, {"labels": [3]}, {"assignee": {"displayName": 0}}, {"status": {"name": 0, "statusCategory": {"key": "new"}}}, {"parent": {"key": "ABC"}}, {"parent": {"key": 12}}, {"description": "text"}, {"issuelinks": [linked | {"inwardIssue": {"key": 7}}]}, {"issuelinks": [linked | {"inwardIssue": {"key": "ABC-x"}}]},
{"summary": 3}, {"labels": "api"}, {"labels": [3]}, {"assignee": {"displayName": 0}}, {"status": {"name": 0, "statusCategory": {"key": "new"}}}, {"parent": {"key": "ABC"}}, {"parent": {"key": 12}}, {"description": "text"}, {"issuelinks": [linked | {"inwardIssue": {"key": "ABC-x"}}]},
))),
({"key": "ABC-34", "fields": {key: value for key, value in valid.items() if key != "issuelinks"}}, shape + ": KeyError('issuelinks')"),
({"key": "ABC-34", "fields": {key: value for key, value in valid.items() if key != "issuelinks"}}, shape + ": its issuelinks are no list"),
({"key": "ABC-34", "fields": valid, "properties": {"plan-item": "L 2"}}, "ABC-34's issue property plan-item is not a JSON object"),
({"key": "ABC-34", "fields": valid, "properties": {"plan-item": {"L": "many"}}}, "item ABC-34's L 'many' is not a whole number from 1 to 4; ABC-34 holds it in its issue property plan-item"),
({"key": "ABC-34", "fields": valid, "properties": None}, shape + ": AttributeError(\"'NoneType' object has no attribute 'get'\")"),
({"key": "ABC-34", "fields": valid, "properties": None}, shape + ": its properties are no object"),
({"key": "ABC-34", "fields": valid | {"issuelinks": [linked | {"inwardIssue": {"key": 7}}]}}, shape + ": its issuelinks hold a link whose id or whose linked issue's key is no text"),
):
with self.subTest(raw=raw):
self.jira.answers[("POST", SEARCH)] = {"issues": [raw]}
@@ -347,14 +347,13 @@ class Jira(Case):
self.assertEqual(JiraEpic(EPIC, self.env_file, self.jira, lambda documents: converted, to_adf).read(), Failure(reason))
def test_a_search_that_does_not_end_names_the_issues_it_sought(self) -> None:
store = self.new_store()
store = dataclasses.replace(self.new_store(), max_pages=1)
children = [store.file("ABC-12", "Count the runs.", "", ()) for _ in range(2)]
for _ in range(3):
store.file(str(children[0]), "A task.", "", ())
with unittest.mock.patch("atlassian.jira.MAX_PAGES", 1):
self.assertEqual(store.read(), Failure("the search for the sub-tasks of ABC-12's child issues did not end within 1 pages"))
store.file("ABC-12", "Count the runs.", "", ())
self.assertEqual(store.read(), Failure("the search for ABC-12's child issues did not end within 1 pages"))
self.assertEqual(store.read(), Failure("the search for the sub-tasks of ABC-12's child issues did not end within 1 pages"))
store.file("ABC-12", "Count the runs.", "", ())
self.assertEqual(store.read(), Failure("the search for ABC-12's child issues did not end within 1 pages"))
def test_refuses_to_file_under_another_epics_child_or_an_issue_it_cannot_read(self) -> None:
self.jira.issues.append({"key": "ABC-5", "fields": {"parent": {"key": "ABC-1"}, "status": TO_DO}})
+7 -3
View File
@@ -13,8 +13,12 @@ It reads three environment variables and fails, naming each that is missing:
{chr(10).join(f' {name}: {meaning}' for name, meaning in settings.MEANING.items())}
It prints a line per check, and exits 0 only where every check held."""
EpicMade = typing.Callable[[settings.Sandbox, str], typing.ContextManager[str | Failure]]
Run = typing.Callable[[settings.Sandbox, str, pathlib.Path, typing.Mapping[str, str]], scenario.Report]
def main(argv: list[str], env: typing.Mapping[str, str], launcher: pathlib.Path) -> int:
def main(argv: list[str], env: typing.Mapping[str, str], launcher: pathlib.Path, epic_made: EpicMade, run: Run) -> int:
"""Runs do-epic-e2e: epic_made makes the sandbox epic, as sandbox.epic_made does, and run drives do-epic against it, as scenario.run does."""
if argv:
print(HELP, file=sys.stdout if argv in (["-h"], ["--help"]) else sys.stderr)
return 0 if argv in (["-h"], ["--help"]) else 1
@@ -25,12 +29,12 @@ def main(argv: list[str], env: typing.Mapping[str, str], launcher: pathlib.Path)
report = scenario.Report()
left: sandbox.Leftover | None = None
try:
with sandbox.epic_made(found, "do-epic e2e sandbox epic") as key:
with epic_made(found, "do-epic e2e sandbox epic") as key:
if isinstance(key, Failure):
print(f"do-epic-e2e: {key.reason}", file=sys.stderr)
return 1
print(f"Sandbox epic {key} in {found.jira_url}")
report = scenario.run(found, key, launcher, env)
report = run(found, key, launcher, env)
except sandbox.Leftover as failure:
left = failure
# The checks are printed even where the epic could not be deleted.
+9 -6
View File
@@ -1,6 +1,5 @@
import contextlib
import io
from unittest import mock
import pathlib
import sys
import tempfile
@@ -18,7 +17,7 @@ class MainTest(unittest.TestCase):
def run_main(self, argv: list[str]) -> tuple[int, str, str]:
out, err = io.StringIO(), io.StringIO()
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
code = main.main(argv, {}, pathlib.Path("do-epic"))
code = main.main(argv, {}, pathlib.Path("do-epic"), sandbox.epic_made, scenario.run)
return code, out.getvalue(), err.getvalue()
def test_fails_naming_each_missing_setting_before_it_touches_anything(self) -> None:
@@ -56,10 +55,14 @@ class ReportedTest(unittest.TestCase):
out, err = io.StringIO(), io.StringIO()
report = report or scenario.Report(["a check held"], ["a check broke"])
with mock.patch.object(sandbox, "epic_made", epic_made), mock.patch.object(scenario, "run", return_value=report) as ran:
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
code = main.main([], self.env, pathlib.Path("do-epic"))
self.ran_with = ran.call_args.args if ran.called else None
self.ran_with = None
def ran(*args: object) -> scenario.Report:
self.ran_with = args
return report
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
code = main.main([], self.env, pathlib.Path("do-epic"), epic_made, ran)
return code, out.getvalue(), err.getvalue()
def test_prints_each_check_and_fails_where_one_broke(self) -> None:
+26 -10
View File
@@ -251,6 +251,8 @@ def chunk_run(key: str, epic: EpicRun) -> Stop:
if isinstance(place, Stop):
return place
root, repo = place
if unmade := folder_made(root):
return Stop(1, unmade.reason)
session = session_named(f"A {epic.key} do-epic {key}", epic.paths.claude_code_transcripts)
loop = Loop(root=root, session=session, window=tmux.Window(epic.session, key, pane), paths=epic.paths, env=epic.env, launcher=epic.launcher, effects=epic.effects)
run = ChunkRun()
@@ -263,6 +265,9 @@ def chunk_run(key: str, epic: EpicRun) -> Stop:
cycle = next_cycle(run, loop, repo is not None, epic, news)
if isinstance(cycle, Stop):
return cycle
if isinstance(cycle, EpicReopened):
say(f"the epic {epic.key} holds an open issue again, so its finishing chunk ends until none is open", epic.effects, stdout=True)
return handed_on(key, epic)
run = dataclasses.replace(run, task=cycle.task)
concluded = run_cycle(cycle)
if isinstance(concluded, Stop):
@@ -355,15 +360,22 @@ def chunk_root(key: str, issue: EpicIssue | None, epic: EpicRun) -> tuple[str, s
if isinstance(pick, Failure):
return Stop(1, pick.reason)
if isinstance(pick, ClaudeWork):
folder = epic.paths.home / scheduler.STATE / epic.key
folder.mkdir(parents=True, exist_ok=True)
return str(folder), None
return str(epic.paths.home / scheduler.STATE / epic.key), None
if not isinstance(pick, Repo):
return Stop(1, f"{key} is no chunk: no label names its repo")
found = locate(pick.name, [], epic.config, epic.paths.home, epic.effects.git)
return Stop(1, found.reason) if isinstance(found, Failure) else (str(real(found.checkout)), pick.name)
def folder_made(root: str) -> Failure | None:
"""Makes the folder a chunk works in where it is missing, as the epic's folder is before its first chunk without a repo."""
try:
pathlib.Path(root).mkdir(parents=True, exist_ok=True)
except OSError as failure:
return Failure(f"could not make the chunk's folder {root}: {failure.strerror}")
return None
def handed_on(key: str, epic: EpicRun) -> Stop:
"""The stop of a do-epic whose chunk finished. It first moves the chunk's issue to done (the epic's finishing has none), and its split item too where that was the last of the item's sub-tasks, so that no finished chunk starts again and what they block may start, then starts each chunk that may start now. Its window closes as it exits."""
# The epic's finishing has no issue to move: the epic is closed by `--close-epic`.
@@ -396,8 +408,8 @@ def split_items_closed(epic: EpicRun, issues: list[EpicIssue]) -> list[EpicIssue
return issues
def next_cycle(run: ChunkRun, loop: Loop, in_repo: bool, epic: EpicRun, news: str = "") -> Cycle | Stop:
"""The cycle run runs next, from the issue, the premises, the records, the models and the routing ladder read afresh; the stop where one of them cannot be read. news is what `parked_through` tells the worker of a chunk that was parked, and opens its prompt. A chunk in a repo routes on that repo's model and ladder, and one without a repo on the machine setting `repoless-model` and the shipped ladder."""
def next_cycle(run: ChunkRun, loop: Loop, in_repo: bool, epic: EpicRun, news: str = "") -> Cycle | EpicReopened | Stop:
"""The cycle run runs next, from the issue, the premises, the records, the models and the routing ladder read afresh; the stop where one of them cannot be read, and EpicReopened where the epic's finishing has no cycle to run. news is what `parked_through` tells the worker of a chunk that was parked, and opens its prompt. A chunk in a repo routes on that repo's model and ladder, and one without a repo on the machine setting `repoless-model` and the shipped ladder."""
premises = premises_read(loop.root if in_repo else None, epic)
if isinstance(premises, Failure):
return Stop(1, premises.reason)
@@ -408,7 +420,7 @@ def next_cycle(run: ChunkRun, loop: Loop, in_repo: bool, epic: EpicRun, news: st
if isinstance(records, Failure):
return Stop(1, records.reason)
work = chunk_work(loop.window.name, loop.root if in_repo else None, language or epic.config.language, epic)
if isinstance(work, Stop):
if isinstance(work, (Stop, EpicReopened)):
return work
task, issue = work
routing = project_routing(loop, chunk_prompt.DRIVER) if in_repo else routing_on(repoless_models(epic), SHIPPED)
@@ -420,8 +432,13 @@ def next_cycle(run: ChunkRun, loop: Loop, in_repo: bool, epic: EpicRun, news: st
return cycle_of(loop, routing, route, archive_folder, task=task, facts="", premises=premises, records=records, unfinished_evidence=run.unfinished_evidence, prompts=prompts, taken_in=lambda entries: TakenIn())
def chunk_work(key: str, checkout: str | None, language: str, epic: EpicRun) -> tuple[str, RoutingIssue | None] | Stop:
"""The task of the chunk called key, and the issue that routes it, or None where that issue has no scores: both from the epic's issues, read afresh. The epic's finishing has no issue, and it ends here once the epic holds an open issue again, since working that issue comes first."""
@dataclasses.dataclass(frozen=True)
class EpicReopened:
"""The epic holds an open issue again, so its finishing chunk has no work until none is open: working that issue comes first."""
def chunk_work(key: str, checkout: str | None, language: str, epic: EpicRun) -> tuple[str, RoutingIssue | None] | EpicReopened | Stop:
"""The task of the chunk called key, and the issue that routes it, or None where that issue has no scores: both from the epic's issues, read afresh. The epic's finishing has no issue, and its work is EpicReopened once the epic holds an open issue again."""
if key != epic.key:
issue = issue_read(key, epic)
if isinstance(issue, Stop):
@@ -434,8 +451,7 @@ def chunk_work(key: str, checkout: str | None, language: str, epic: EpicRun) ->
if isinstance(issues, Failure):
return Stop(1, issues.reason)
if not finish.due(issues):
say(f"the epic {epic.key} holds an open issue again, so its finishing chunk ends until none is open", epic.effects, stdout=True)
return handed_on(key, epic)
return EpicReopened()
return finish.task(epic.key, issues, epic.launcher, language), None
+51 -49
View File
@@ -140,45 +140,44 @@ def start_chunks(epic: Epic, issues: list[EpicIssue], finishing: bool, own: str
parked = parked_chunks(epic.folder)
if isinstance(parked, Failure):
return parked
try:
with starting(epic.folder):
windows = tmux.listed(session, run)
live = {window.name: window for window in windows if not window.dead and window.name != own}
running = {window.name for window in windows if not window.dead and not window.parked} - {own}
stopped = {window.name for window in windows if window.dead} - set(live)
# The windows this call started that take a running slot.
taken = 0
for chunk in found:
if chunk.issue in running or chunk.issue == own:
continue
slot = chunk.issue not in parked and not chunk.human
if chunk.human and chunk.issue in live:
waits.append(Waits(chunk.issue, HUMAN_WAIT))
elif chunk.issue in parked and chunk.issue in live:
waits.append(Waits(chunk.issue, parked[chunk.issue].waits(live[chunk.issue].awaits)))
elif own and (chunk.issue in stopped or chunk.issue in parked):
waits.append(Waits(chunk.issue, f"its window stopped; run `do-epic {epic.key}` to start it again"))
elif slot and len(running) + taken >= epic.cap:
waits.append(Waits(chunk.issue, f"the epic runs as many chunks as its `{CAP}` line allows: {epic.cap}"))
with starting(epic.folder) as unlocked:
if unlocked:
return unlocked
windows = tmux.listed(session, run)
live = {window.name: window for window in windows if not window.dead and window.name != own}
running = {window.name for window in windows if not window.dead and not window.parked} - {own}
stopped = {window.name for window in windows if window.dead} - set(live)
# The windows this call started that take a running slot.
taken = 0
for chunk in found:
if chunk.issue in running or chunk.issue == own:
continue
slot = chunk.issue not in parked and not chunk.human
if chunk.human and chunk.issue in live:
waits.append(Waits(chunk.issue, HUMAN_WAIT))
elif chunk.issue in parked and chunk.issue in live:
waits.append(Waits(chunk.issue, parked[chunk.issue].waits(live[chunk.issue].awaits)))
elif own and (chunk.issue in stopped or chunk.issue in parked):
waits.append(Waits(chunk.issue, f"its window stopped; run `do-epic {epic.key}` to start it again"))
elif slot and len(running) + taken >= epic.cap:
waits.append(Waits(chunk.issue, f"the epic runs as many chunks as its `{CAP}` line allows: {epic.cap}"))
else:
now = start_chunk(epic, chunk if chunk.issue not in parked else Chunk(chunk.issue, None), own, windows, run)
if isinstance(now, Failure):
return now
if isinstance(now, str):
waits.append(Waits(chunk.issue, now))
else:
now = start_chunk(epic, chunk if chunk.issue not in parked else Chunk(chunk.issue, None), own, windows, run)
if isinstance(now, Failure):
return now
if isinstance(now, str):
waits.append(Waits(chunk.issue, now))
else:
windows = now
started.append(chunk.issue)
taken += slot
except OSError as failure:
return Failure(f"cannot lock {failure.filename or epic.folder / LOCK}: {failure.strerror}")
windows = now
started.append(chunk.issue)
taken += slot
# The epic's finishing is no issue: its wait is listed after every issue's.
order = [*(issue.key for issue in issues), epic.key]
return Started(started, sorted(waits, key=lambda wait: order.index(wait.issue)))
def start_chunk(epic: Epic, chunk: Chunk, own: str | None, windows: list[tmux.Listed], run: tmux.Tmux) -> list[tmux.Listed] | str | Failure:
"""Starts chunk's window beside windows, the epic's session's, and returns the session's windows afterwards; the reason where its repo takes no chunk now, and a Failure where tmux started none. It holds the repo's lock from the check to the start. Raises OSError where that lock cannot be taken. A chunk without a repo starts in the epic's folder. So does a parked chunk, since it takes no room in its repo."""
"""Starts chunk's window beside windows, the epic's session's, and returns the session's windows afterwards; the reason where its repo takes no chunk now, and a Failure where tmux started none, or where the repo's lock cannot be taken. It holds that lock from the check to the start. A chunk without a repo starts in the epic's folder. So does a parked chunk, since it takes no room in its repo."""
session = tmux.session_name(tmux.EPIC, epic.key)
handed = {**{name: value for name, value in epic.env.items() if name.startswith(HANDED)}, PARKS: "1"}
command = [str(epic.launcher), CHUNK_FLAG, chunk.issue, epic.key]
@@ -188,7 +187,9 @@ def start_chunk(epic: Epic, chunk: Chunk, own: str | None, windows: list[tmux.Li
if isinstance(located, Failure):
return located.reason
checkout, limit = located
with starting(project_lock(str(checkout), epic.home)):
with starting(project_lock(str(checkout), epic.home)) as unlocked:
if unlocked:
return unlocked
if reason := refusal(chunk.repo, room_in(str(checkout), limit, (session, own), epic.home, run)):
return reason
return tmux.start_chunk(tmux.Window(session, chunk.issue, ""), str(checkout), handed, command, windows, False, run)
@@ -202,19 +203,20 @@ def room_in(checkout: str, limit: int, leaving: tuple[str, str | None], home: pa
def resume(epic: Epic, repo: str, window: tmux.Window, run: tmux.Tmux) -> str | None:
"""Takes a running slot for the parked chunk in window, whose worker has something to do again in the repo called repo: None once the window counts as a running chunk, else why the chunk still waits. The limits are those a starting chunk meets, checked under the same locks. The window itself never counts against them: one started again for a parked chunk, as after a reboot, isn't named as parked until its first read of the gate."""
try:
with starting(epic.folder):
running = [listed for listed in tmux.listed(window.session, run) if not listed.dead and not listed.parked and listed.name != window.name]
if len(running) >= epic.cap:
return f"the epic runs as many chunks as its `{CAP}` line allows: {epic.cap}"
located = epic.locate(repo)
if isinstance(located, Failure):
return located.reason
checkout, limit = located
with starting(project_lock(str(checkout), epic.home)):
if reason := refusal(repo, room_in(str(checkout), limit, (window.session, window.name), epic.home, run)):
return reason
tmux.unpark(window, str(checkout), run)
return None
except OSError as failure:
return f"cannot lock {failure.filename or epic.folder / LOCK}: {failure.strerror}"
with starting(epic.folder) as unlocked:
if unlocked:
return unlocked.reason
running = [listed for listed in tmux.listed(window.session, run) if not listed.dead and not listed.parked and listed.name != window.name]
if len(running) >= epic.cap:
return f"the epic runs as many chunks as its `{CAP}` line allows: {epic.cap}"
located = epic.locate(repo)
if isinstance(located, Failure):
return located.reason
checkout, limit = located
with starting(project_lock(str(checkout), epic.home)) as unlocked:
if unlocked:
return unlocked.reason
if reason := refusal(repo, room_in(str(checkout), limit, (window.session, window.name), epic.home, run)):
return reason
tmux.unpark(window, str(checkout), run)
return None
+8
View File
@@ -233,3 +233,11 @@ class TheFinishingChunk(DoEpicTest):
self.assertIn("the epic ABC-12 holds an open issue again, so its finishing chunk ends until none is open\n", out)
self.assertIn("the chunk finished; started ABC-31\n", out)
self.assertEqual([seam for seam, _ in fake.calls if seam == "stream_claude"], [])
def test_asking_for_the_finishing_chunks_work_names_a_reopened_epic_and_doesnt_start_any_window(self) -> None:
self.issues = [*REVIEWED, issue("ABC-31", "do-epic-claude")]
fake = FakeEffects(windows="ABC-12\t0\t@9\n")
out = io.StringIO()
with contextlib.redirect_stdout(out):
self.assertEqual(main.chunk_work("ABC-12", None, "English", self.epic_run(fake)), main.EpicReopened())
self.assertEqual((out.getvalue(), fake.tmux_calls), ("", []))
+15
View File
@@ -179,6 +179,20 @@ class TheCommand(DoEpicTest):
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) -> main.Cycle:
fake = FakeEffects(git=[Failure("no git"), Failure("no git")])
paths = paths_from(self.home)
@@ -186,6 +200,7 @@ class ACycleOfAChunkWithoutARepo(DoEpicTest):
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(ChunkRun(1), loop, repo is not None, epic)
+11 -6
View File
@@ -2,10 +2,10 @@ import pathlib
import sys
import tempfile
import unittest
import unittest.mock
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from test_env import assert_not_root
from do_epic.config import DoEpicConfig
from failure import Failure
from do_epic.repos import locate, Located, Unsure
@@ -14,9 +14,9 @@ from project_config.doubles import write_config
class FakeGit:
"""git as locate calls it: origins maps a checkout to its origin URL, cloned holds each `clone` that worked, and refused names a URL whose clone fails after it made the checkout's `.git`, as a stopped git does."""
def __init__(self, origins: dict[str, str | Failure], refused: str | None = None) -> None:
self.origins, self.refused = origins, refused
"""git as locate calls it: origins maps a checkout to its origin URL, cloned holds each `clone` that worked, and refused names a URL whose clone fails after it made the checkout's `.git`, as a stopped git does. Where locked, that clone also takes away the right to remove what it made."""
def __init__(self, origins: dict[str, str | Failure], refused: str | None = None, locked: bool = False) -> None:
self.origins, self.refused, self.locked = origins, refused, locked
self.cloned: list[tuple[str, str]] = []
self.clone_timeouts: list[float | None] = []
self.clone_options: list[tuple[str, ...]] = []
@@ -30,6 +30,8 @@ class FakeGit:
url, destination = args[clone + 2:clone + 4]
pathlib.Path(destination, ".git").mkdir(parents=True)
if url == self.refused:
if self.locked:
pathlib.Path(destination).chmod(0o500)
return Failure("git clone: repository not found")
self.cloned.append((url, destination))
self.clone_timeouts.append(timeout)
@@ -110,9 +112,12 @@ class LocateTest(unittest.TestCase):
self.assertIn(f"{self.billing} has an origin, billing, with no host and owner to put another repo under", self.unsure(FakeGit(self.origins)))
def test_asks_all_the_same_where_the_leftovers_of_a_failed_clone_cannot_be_removed(self) -> None:
assert_not_root(self)
self.configure()
with unittest.mock.patch("do_epic.repos.shutil.rmtree", side_effect=lambda path, ignore_errors: None if ignore_errors is True else self.fail("rmtree must ignore errors")):
self.assertIn("cannot clone", self.unsure(FakeGit(self.origins, refused="git@github.com:acme/ledger")))
left = self.home / "code" / "ledger"
self.addCleanup(lambda: left.chmod(0o700))
self.assertIn("cannot clone", self.unsure(FakeGit(self.origins, refused="git@github.com:acme/ledger", locked=True)))
self.assertTrue((left / ".git").is_dir())
def test_asks_where_the_clone_fails_naming_the_url_and_the_reason(self) -> None:
self.configure()
+16
View File
@@ -315,6 +315,22 @@ class StartingAnEpicsChunks(unittest.TestCase):
assert isinstance(found, Failure)
self.assertRegex(found.reason, f"^cannot lock {self.home}/.local/state/do-epic/ABC-12: \\w")
def test_says_which_repos_lock_it_could_not_take(self) -> None:
(self.home / ".local/state").mkdir(parents=True)
(self.home / ".local/state/loop-claude").write_text("", encoding="utf-8")
found = start_chunks(self.epic(1, api=1), [issue("ABC-20", "repo:api")], False, None, Tmux())
assert isinstance(found, Failure)
self.assertRegex(found.reason, f"^cannot lock {self.home}/.local/state/loop-claude/\\S+: \\w")
self.assertRegex(self.resumed(self.epic(1, api=1), Tmux()) or "", f"^cannot lock {self.home}/.local/state/loop-claude/\\S+: \\w")
def test_an_error_raised_under_the_lock_is_not_reported_as_the_locks(self) -> None:
def failing(args: list[str]) -> subprocess.CompletedProcess[str]:
raise OSError("tmux is gone")
with self.assertRaisesRegex(OSError, "tmux is gone"):
start_chunks(self.epic(1, api=1), [issue("ABC-20", "repo:api")], False, None, failing)
with self.assertRaisesRegex(OSError, "tmux is gone"):
resume(self.epic(1, api=1), "api", tmux.Window("epic-ABC-12", "ABC-20", "%0"), failing)
CONFIG = settings.ProjectConfig("api", pathlib.Path("/c/api"), pathlib.Path("/code/api"), {"changelog": pathlib.Path("/code/api/CHANGELOG.md")}, epic=settings.Epic("https://acme.atlassian.net", "API-1"))