Run each chunk in its own tmux window, up to parallel-chunks at once, and mark a window that waits
CI / tests (pull_request) Failing after 2m56s

This commit is contained in:
2026-11-16 11:59:45 +01:00
parent 7fc64d860a
commit eecb0387ca
28 changed files with 883 additions and 209 deletions
+235 -67
View File
@@ -21,7 +21,10 @@ from routing_figures import archive, state
from routing_figures.calls import Call
from loop_claude.project import checkout, model_choice, records
from loop_claude.cycle import chunk_items
from loop_claude.loop import chunk_slot, chunk_start, close
from loop_claude.loop import chunk_start, chunk_windows, close
from loop_claude import tmux
from chunk_preflight import gathered
from touch_predictions.test_touch_predictions import plan as touch_plan
from project_config.test_project_config import configured
from release_plan.release_standing import DefaultPlan, LastCut, UNSEEN_RELEASES
from loop_effects.effects import Effects, PYTHON_TIMEOUT
@@ -76,18 +79,26 @@ def human(content):
return {"type": "user", "message": {"content": content}}
# The window the loops under test run in.
WINDOW = tmux.Window("loop-proj", "item-7", "%4")
def a_loop(effects, **fields):
"""A loop in /r on effects, with fields in place of its defaults."""
home = pathlib.Path("/h")
defaults = {"root": "/r", "session": session.session_named("A proj loop-claude", home / ".claude" / "projects"), "paths": paths.paths_from(home), "env": {}, "launcher": pathlib.Path("/b/loop-claude")}
defaults = {"root": "/r", "session": session.session_named("A proj loop-claude", home / ".claude" / "projects"), "paths": paths.paths_from(home), "env": {}, "launcher": pathlib.Path("/b/loop-claude"), "window": WINDOW}
return this_loop.Loop(**{**defaults, **fields}, effects=effects)
class FakeEffects:
"""Effects that record each call and answer from a script, one answer per call."""
def __init__(self, claude=(), on_terminal_claude=(), git=(), inputs=(), python=(), streams=(), on_terminal=True, free_memory=(), dm_failures=()):
def __init__(self, claude=(), on_terminal_claude=(), git=(), inputs=(), python=(), streams=(), on_terminal=True, free_memory=(), dm_failures=(), tmux_version="tmux 3.2", windows=None):
self.calls = []
# Each tmux command run. They stay out of self.calls, as the DMs do. tmux prints `windows` for list-windows, or without them finds no session.
self.tmux_calls = []
self.tmux_version = tmux_version
self.windows = windows
# Each direct message sent. They stay out of self.calls, so a test that lists every call doesn't list them. Without a script, each is sent.
self.dms = []
self.dm_failures = list(dm_failures)
@@ -115,8 +126,16 @@ class FakeEffects:
python=lambda args, cwd: self.answer("python", (args, cwd)),
sleep=lambda seconds: self.calls.append(("sleep", seconds)),
stream_claude=self.stream,
tmux=self.tmux,
tmux_on_terminal=lambda args: self.tmux(args).returncode,
)
def tmux(self, args):
self.tmux_calls.append(args)
if args[0] == "list-windows":
return subprocess.CompletedProcess(args, 1 if self.windows is None else 0, self.windows or "", "no server")
return subprocess.CompletedProcess(args, 0, {"-V": self.tmux_version + "\n"}.get(args[0], "@9\n"), "")
def dm(self, text):
self.dms.append(text)
return self.dm_failures.pop(0) if self.dm_failures else None
@@ -265,7 +284,7 @@ class Cycles(unittest.TestCase):
self.archive = project_archive(str(self.home / "code" / "proj"), self.home, {})
def cycle(self, fake, records="", unfinished_evidence="", facts="- A preflight fact."):
return run.Cycle(config=CONFIG, effects=fake.effects(), facts=facts, judge_model="judge-model", ladder=LADDER, premises="## Goals", project=None, project_archive=self.archive, records=records, root=str(self.home), route=Route(Rung("worker-model")), session=self.session, task="Do it.", todo=plan_of(""), unfinished_evidence=unfinished_evidence)
return run.Cycle(config=CONFIG, window=WINDOW, effects=fake.effects(), facts=facts, judge_model="judge-model", ladder=LADDER, premises="## Goals", project=None, project_archive=self.archive, records=records, root=str(self.home), route=Route(Rung("worker-model")), session=self.session, task="Do it.", todo=plan_of(""), unfinished_evidence=unfinished_evidence)
def archived_outcomes(self):
return sorted(path.read_text() for path in self.archive.glob("*/*.outcomes.md"))
@@ -560,7 +579,7 @@ Spent since 2026-09-21T14:13:20Z, in tokens of input, cache write 5m, cache writ
fake = FakeEffects(streams=[worker, worker], claude=[judged("interrupt"), judged("unfinished")], inputs=["Use B."])
with contextlib.redirect_stderr(io.StringIO()) as said:
self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Unfinished("working", entries_read=6))
self.assertIn(f"\n{STAMP} Which one?\n", said.getvalue())
self.assertIn(f"\n{STAMP} Which one?\a\n", said.getvalue())
self.assertEqual(fake.made("claude_on_terminal"), [])
resumed = fake.made("stream_claude")[1]
self.assertEqual(resumed[resumed.index("--resume") + 1], str(self.session.id))
@@ -627,7 +646,7 @@ Spent since 2026-09-21T14:13:20Z, in tokens of input, cache write 5m, cache writ
with contextlib.redirect_stderr(io.StringIO()) as said:
self.assertEqual(run.run_cycle(self.cycle(fake, records="From AGENTS.md:\nUse B. Use A.")), Stop(2, "the human is needed to answer the question above, but nothing was typed"))
self.assertEqual(len(fake.made("stream_claude")), 1)
self.assertIn(f"\n{STAMP} Which one?\n", said.getvalue())
self.assertIn(f"\n{STAMP} Which one?\a\n", said.getvalue())
self.assertNotIn("Use ... A.", said.getvalue())
@unittest.skipIf(os.geteuid() == 0, "root writes into a read-only directory")
@@ -733,10 +752,11 @@ class Interrupts(unittest.TestCase):
self.session = interrupt.WorkerSession(str(self.home), uuid.uuid7(), Rung("m", "high"), str(self.transcript), {"LOOP_CLAUDE_WORKER_RUNG": "m at high effort"})
def put(self, fake, answer_here=True, effects=None, question="Which one?"):
"""interrupt's answer and what it said."""
"""interrupt's answer and what it said, without the bell it rang, which self.bells counts."""
with contextlib.redirect_stderr(io.StringIO()) as said:
answer = interrupt.interrupt(question, answer_here, self.session, effects or fake.effects())
return answer, said.getvalue()
answer = interrupt.interrupt(question, answer_here, self.session, WINDOW, effects or fake.effects())
self.bells = said.getvalue().count(tmux.BELL)
return answer, said.getvalue().replace(tmux.BELL, "")
def typed_there(self, args):
"""The claude opened on the terminal: the human types a line in the worker's session, and it ends."""
@@ -754,7 +774,19 @@ class Interrupts(unittest.TestCase):
with self.subTest(on_terminal=on_terminal):
fake = FakeEffects(inputs=["Use B."], on_terminal=on_terminal)
self.put(fake)
self.assertEqual(fake.dms, [f"loop-claude in {self.home} asks:\n\nWhich one?"])
self.assertEqual(fake.dms, [f"loop-claude in {self.home} asks, in the tmux window loop-proj:item-7:\n\nWhich one?"])
def test_marks_its_window_and_rings_the_bell_while_it_waits_and_clears_the_mark_once_answered(self):
fake = FakeEffects(inputs=["Use B."])
answer, said = self.put(fake)
self.assertEqual(answer, "Use B.")
self.assertEqual(self.bells, 1)
self.assertEqual(fake.tmux_calls, [["rename-window", "-t", "%4", "item-7 ?"], ["rename-window", "-t", "%4", "item-7"]])
def test_a_loop_that_stops_unanswered_leaves_its_window_marked(self):
fake = FakeEffects(on_terminal=False)
self.put(fake)
self.assertEqual(fake.tmux_calls, [["rename-window", "-t", "%4", "item-7 ?"]])
def test_drops_the_keys_typed_before_the_question_ahead_of_the_dm_so_an_answer_typed_while_it_sends_counts(self):
fake = FakeEffects(inputs=["Use B."])
@@ -1125,14 +1157,21 @@ class Routing(unittest.TestCase):
class RouteSources(unittest.TestCase):
def test_routes_on_the_plan_item_and_says_why_it_routes_on_the_projects_rung(self):
self.assertIsNone(chunk_start.plan_item(DefaultPlan(plan_of(""), NO_CUT), FakeEffects().effects()))
self.assertEqual(chunk_start.plan_item(DefaultPlan(plan_of(TODO), LastCut("v0.1.0", "", 3, [TODO])), FakeEffects().effects()).id, 3)
self.assertIsNone(chunk_start.plan_item(DefaultPlan(plan_of(TODO), LastCut("v0.3.0", "", 3, [TODO])), FakeEffects().effects()))
self.assertIsNone(chunk_start.plan_item(DefaultPlan(plan_of(""), NO_CUT), None, FakeEffects().effects()))
self.assertEqual(chunk_start.plan_item(DefaultPlan(plan_of(TODO), LastCut("v0.1.0", "", 3, [TODO])), None, FakeEffects().effects()).id, 3)
self.assertIsNone(chunk_start.plan_item(DefaultPlan(plan_of(TODO), LastCut("v0.3.0", "", 3, [TODO])), None, FakeEffects().effects()))
def test_routes_a_window_named_for_an_item_on_that_item_whatever_the_plan_takes_next(self):
plan = DefaultPlan(plan_of(TODO), LastCut("v0.1.0", "", 3, [TODO]))
later = next(item.id for item in plan.todo.items if item.id != 3)
self.assertEqual(chunk_start.plan_item(plan, later, FakeEffects().effects()).id, later)
# An item that left the plan, as once it shipped.
self.assertIsNone(chunk_start.plan_item(plan, 999, FakeEffects().effects()))
unreadable = Failure("git show origin/main:todo.md printed text that is not UTF-8")
for plan, said in ((DefaultPlan(plan_of(TODO.replace("| 4 | 2 | 3 |", "| x | 2 | 3 |")), NO_CUT), "routing on the project's rung: item 3's L 'x' is not a whole number from 1 to 4\n"), (DefaultPlan(unreadable, NO_CUT), f"routing on the project's rung: {unreadable.reason}\n"), (Failure("no origin remote"), "routing on the project's rung: no origin remote\n")):
with self.subTest(said=said):
with contextlib.redirect_stderr(io.StringIO()) as stderr:
self.assertIsNone(chunk_start.plan_item(plan, FakeEffects().effects()))
self.assertIsNone(chunk_start.plan_item(plan, None, FakeEffects().effects()))
self.assertTrue(stderr.getvalue().startswith(f"{STAMP} {said}"), stderr.getvalue())
def test_says_why_the_items_the_worker_names_lift_no_rung(self):
@@ -1210,61 +1249,99 @@ class RouteSources(unittest.TestCase):
self.assertTrue(stderr.getvalue().startswith(f"{STAMP} routing the chunk afresh: could not read the archive"), stderr.getvalue())
class ChunkSlots(unittest.TestCase):
def setUp(self):
temp = tempfile.TemporaryDirectory()
self.addCleanup(temp.cleanup)
self.home = pathlib.Path(temp.name)
self.paths = paths.paths_from(self.home)
self.addCleanup(self.release)
class TmuxCommands(unittest.TestCase):
def test_refuses_a_tmux_older_than_needed_naming_both_versions(self):
for found, reason in (("tmux 3.2", None), ("tmux 3.8", None), ("tmux next-3.4", None), ("tmux 10.0", None),
("tmux 3.1c", "loop-claude runs each chunk in a tmux window, and needs tmux 3.2 or later; it found tmux 3.1c"),
("tmux 2.9a", "loop-claude runs each chunk in a tmux window, and needs tmux 3.2 or later; it found tmux 2.9a"),
("", "loop-claude runs each chunk in a tmux window, and needs tmux 3.2 or later; it found no tmux")):
with self.subTest(found=found):
fake = FakeEffects(tmux_version=found)
self.assertEqual(tmux.unusable(fake.tmux), reason)
self.assertEqual(fake.tmux_calls, [["-V"]])
def held(self):
"""This process's open files on a slot, each with whether an exec keeps it."""
folder = self.home / chunk_slot.SLOTS
found = {}
for fd in os.listdir("/proc/self/fd"):
with contextlib.suppress(OSError):
if pathlib.Path(os.readlink(f"/proc/self/fd/{fd}")).is_relative_to(folder):
found[os.readlink(f"/proc/self/fd/{fd}")] = os.get_inheritable(int(fd))
return found
def test_names_the_session_for_the_project(self):
self.assertEqual(tmux.session_name("claude-config"), "loop-claude-config")
# tmux reads `.` and `:` in a target as separators.
self.assertEqual(tmux.session_name("my.site:2 x"), "loop-my-site-2-x")
def release(self):
folder = str(self.home / chunk_slot.SLOTS)
for fd in os.listdir("/proc/self/fd"):
with contextlib.suppress(OSError):
if os.readlink(f"/proc/self/fd/{fd}").startswith(folder):
os.close(int(fd))
def test_lists_the_windows_without_the_waiting_mark(self):
fake = FakeEffects(windows="item-372 ?\t0\t@1\nitem-380\t1\t@2\nno-item\t0\t@5\n")
self.assertEqual(tmux.listed("loop-proj", fake.tmux), [tmux.Listed("item-372", "@1", False), tmux.Listed("item-380", "@2", True), tmux.Listed("no-item", "@5", False)])
self.assertEqual(fake.tmux_calls, [["list-windows", "-t", "=loop-proj", "-F", "#{window_name}\t#{pane_dead}\t#{window_id}"]])
self.assertEqual(tmux.listed("loop-proj", FakeEffects().tmux), [])
def test_each_loop_takes_the_lowest_free_slot_and_names_its_session_after_it(self):
loop_run = main.LoopRun(cycle_number=0, root=str(self.home / "code" / "proj"), task="do it", unfinished_evidence="")
first, second = chunk_slot.slotted(loop_run, self.paths), chunk_slot.slotted(loop_run, self.paths)
self.assertEqual((first[0], first[1].name), (dataclasses.replace(loop_run, slot=0), "A proj loop-claude"))
self.assertEqual((second[0].slot, second[1].name), (1, "A proj loop-claude 2"))
self.assertEqual(second[1], session.session_named("A proj loop-claude 2", self.paths.claude_code_transcripts))
folder = self.home / ".local" / "state" / "loop-claude" / "proj"
self.assertEqual(self.held(), {str(folder / "slot-0"): True, str(folder / "slot-1"): True})
def test_the_first_window_makes_the_session_and_each_later_one_joins_it(self):
fake = FakeEffects()
window = tmux.Window("loop-proj", "item-7", "")
self.assertIsNone(tmux.start_window(window, "/r", {"LOOP_CLAUDE_X": "1"}, ["/b/loop-claude", "--chunk", "item-7", "ship it;"], True, fake.tmux))
self.assertIsNone(tmux.start_window(window, "/r", {}, ["/b/loop-claude"], False, fake.tmux))
self.assertEqual(fake.tmux_calls, [
["new-session", "-d", "-s", "loop-proj", "-n", "item-7", "-c", "/r", "-e", "LOOP_CLAUDE_X=1", "-P", "-F", "#{window_id}", "--", "/b/loop-claude", "--chunk", "item-7", "ship it\;"],
["set-option", "-w", "-t", "@9", "remain-on-exit", "failed"],
["new-window", "-d", "-t", "=loop-proj:", "-n", "item-7", "-c", "/r", "-P", "-F", "#{window_id}", "--", "/b/loop-claude"],
["set-option", "-w", "-t", "@9", "remain-on-exit", "failed"],
])
def test_a_rerun_takes_the_lowest_free_slot_whose_session_is_open_before_a_lower_closed_one(self):
loop_run = main.LoopRun(cycle_number=0, root=str(self.home / "code" / "proj"), task="do it", unfinished_evidence="")
for name in ("A proj loop-claude 3", "A proj loop-claude 4"):
transcript = self.paths.claude_code_transcripts / "-home-proj" / f"{session.session_named(name, self.paths.claude_code_transcripts).id}.jsonl"
transcript.parent.mkdir(parents=True, exist_ok=True)
transcript.write_text("")
self.assertEqual([chunk_slot.slotted(loop_run, self.paths)[0].slot for _ in range(4)], [2, 3, 0, 1])
def test_says_why_tmux_started_no_window(self):
failed = lambda args: subprocess.CompletedProcess(args, 1, "", "duplicate session: loop-proj\n")
silent = lambda args: subprocess.CompletedProcess(args, 2, "", "")
window = tmux.Window("loop-proj", "item-7", "")
self.assertEqual(tmux.start_window(window, "/r", {}, ["x"], True, failed), Failure("tmux could not start the window loop-proj:item-7: duplicate session: loop-proj"))
self.assertEqual(tmux.start_window(window, "/r", {}, ["x"], True, silent), Failure("tmux could not start the window loop-proj:item-7: it exited 2"))
def test_a_reload_keeps_the_slot_it_is_handed_and_takes_no_other(self):
loop_run = main.LoopRun(cycle_number=3, root="/srv/proj", task="do it", unfinished_evidence="", slot=2)
self.assertEqual(chunk_slot.slotted(loop_run, self.paths), (loop_run, session.session_named("A srv/proj loop-claude 3", self.paths.claude_code_transcripts)))
self.assertEqual(self.held(), {})
def test_marks_a_waiting_window_by_its_pane_and_clears_the_mark(self):
fake = FakeEffects()
tmux.mark(WINDOW, True, fake.tmux)
tmux.mark(WINDOW, False, fake.tmux)
tmux.close(tmux.Listed("item-7", "@3", True), fake.tmux)
self.assertEqual(fake.tmux_calls, [["rename-window", "-t", "%4", "item-7 ?"], ["rename-window", "-t", "%4", "item-7"], ["kill-window", "-t", "@3"]])
self.assertEqual(WINDOW.target, "loop-proj:item-7")
def test_says_why_it_takes_no_slot(self):
loop_run = main.LoopRun(cycle_number=0, root="/srv/proj", task="do it", unfinished_evidence="")
with unittest.mock.patch.object(chunk_slot, "MOST", 1):
chunk_slot.slotted(loop_run, self.paths)
self.assertEqual(chunk_slot.slotted(loop_run, self.paths), Failure(f"1 loops of this project are running already; `fuser {self.home}/.local/state/loop-claude/srv/proj/slot-*` names them"))
(self.home / ".local" / "state" / "loop-claude").mkdir(parents=True, exist_ok=True)
(self.home / ".local" / "state" / "loop-claude" / "other").write_text("")
self.assertEqual(chunk_slot.slotted(dataclasses.replace(loop_run, root="/other"), self.paths), Failure(f"cannot take a slot in {self.home}/.local/state/loop-claude/other: File exists"))
def test_shows_the_session_by_attaching_or_inside_tmux_by_switching(self):
self.assertEqual(tmux.show("loop-proj", False), ["attach-session", "-t", "=loop-proj"])
self.assertEqual(tmux.show("loop-proj", True), ["switch-client", "-t", "=loop-proj"])
class ChunkWindows(unittest.TestCase):
def plan(self, *touched):
"""A plan of items 1, 2 and on, each predicted to touch the path given for it."""
items = touch_plan(*((number, "1.0.0", "", f"- `{path}`") for number, path in enumerate(touched, 1)))
return gathered.Plan(items=items, first=items[0], text="", branch_template="")
def test_starts_the_next_item_and_those_picked_beside_it_up_to_the_limit(self):
# Item 2 overlaps item 1, so it waits for it; items 3 and 4 run beside it.
plan = self.plan("a.py", "a.py", "c.py", "d.py")
self.assertEqual(chunk_windows.may_start(plan, [], set(), 1), ["item-1"])
self.assertEqual(chunk_windows.may_start(plan, [], set(), 2), ["item-1", "item-3"])
self.assertEqual(chunk_windows.may_start(plan, [], set(), 9), ["item-1", "item-3", "item-4"])
def test_leaves_the_items_running_chunks_hold_and_counts_them_against_the_limit(self):
plan = self.plan("a.py", "a.py", "c.py", "d.py")
self.assertEqual(chunk_windows.may_start(plan, ["item-1"], {1, 3}, 2), ["item-4"])
self.assertEqual(chunk_windows.may_start(plan, ["item-1"], {1}, 3), ["item-3", "item-4"])
self.assertEqual(chunk_windows.may_start(plan, ["item-1", "item-3"], {1, 3}, 2), [])
self.assertEqual(chunk_windows.may_start(plan, ["item-1", "item-3", "item-4"], {1, 3, 4}, 2), [])
def test_a_plan_without_an_item_starts_one_chunk_and_only_alone(self):
none = gathered.NoItem("release 1.0.0 has no items")
self.assertEqual(chunk_windows.may_start(none, [], set(), 3), ["no-item"])
self.assertEqual(chunk_windows.may_start(none, ["item-1"], {1}, 3), [])
def test_names_a_window_for_its_item_and_reads_the_item_back(self):
self.assertEqual(chunk_windows.window_name(372), "item-372")
self.assertEqual([chunk_windows.item_of(chunk) for chunk in ("item-372", "no-item", "item-", "item-3x", "xitem-3")], [372, None, None, None, None])
def test_a_chunk_holds_its_own_item_and_those_on_its_latest_chunk_items_line(self):
with tempfile.TemporaryDirectory() as temp:
transcripts = pathlib.Path(temp)
opened = chunk_windows.chunk_session("proj", "item-7", transcripts)
self.assertEqual(opened.name, "A proj loop-claude item-7")
folder = transcripts / "-r"
folder.mkdir()
lines = [assistant({"type": "text", "text": "Chunk items: 7 (L 1, E + I 2)"}), assistant({"type": "text", "text": "Chunk items: 7 (L 1, E + I 2), 9 (L 2, E + I 3)"})]
(folder / f"{opened.id}.jsonl").write_text("".join(json.dumps(line) + "\n" for line in lines))
self.assertEqual(chunk_windows.held_items(["item-7", "item-8", "no-item"], "proj", transcripts), {7, 8, 9})
class Steps(unittest.TestCase):
@@ -1337,10 +1414,22 @@ class ChunkFacts(unittest.TestCase):
def test_runs_the_preflight_at_the_checkout_root_and_quotes_what_it_printed(self):
fake = FakeEffects(python=[ran("- A fact.\n")])
said = chunk_start.chunk_facts(a_loop(fake.effects(), launcher=self.LAUNCHER))
self.assertEqual(fake.made("python"), [(["/b/chunk-preflight", "--worktree"], "/r")])
self.assertIn("\n\n- A fact.", said)
self.assertEqual(fake.made("python"), [(["/b/chunk-preflight", "--worktree", "--item", "7"], "/r")])
self.assertTrue(said.endswith("\n\n- A fact."), said)
self.assertNotIn("yourself", said)
def test_a_chunk_without_an_item_runs_the_preflight_without_naming_one(self):
fake = FakeEffects(python=[ran("- A fact.\n")])
chunk_start.chunk_facts(a_loop(fake.effects(), launcher=self.LAUNCHER, window=tmux.Window("loop-proj", "no-item", "%4")))
self.assertEqual(fake.made("python"), [(["/b/chunk-preflight", "--worktree"], "/r")])
def test_the_facts_end_with_the_items_the_projects_other_running_chunks_hold(self):
# The loop's own window, a dead one and two that run, one of them waiting for the human.
fake = FakeEffects(python=[ran("- A fact.\n")], windows="item-7\t0\t@1\nitem-5\t1\t@2\nitem-12 ?\t0\t@3\nitem-9\t0\t@4\n")
said = chunk_start.chunk_facts(a_loop(fake.effects(), launcher=self.LAUNCHER))
self.assertTrue(said.endswith("- A fact.\n\nOther chunks of this project run now, and hold items 9, 12. Leave those out of this chunk, whatever else may join it."), said)
self.assertEqual(prompts.held_by_others([9]), "\n\nOther chunks of this project run now, and hold item 9. Leave those out of this chunk, whatever else may join it.")
def test_has_the_worker_find_the_facts_itself_where_the_preflight_failed(self):
for failed, why in ((ran(code=1, stderr="git could not start\n"), "git could not start"), (ran(code=1), "exited 1")):
with self.subTest(why=why):
@@ -1353,7 +1442,7 @@ class ChunkFacts(unittest.TestCase):
opened = session.session_named("A proj loop-claude", pathlib.Path(home, "projects"))
fresh = FakeEffects(python=[ran("- A fact.\n")])
facts, _ = chunk_start.chunk_start(a_loop(fresh.effects(), session=opened, launcher=self.LAUNCHER))
self.assertEqual((fresh.made("python"), "- A fact." in facts), ([(["/b/chunk-preflight", "--worktree"], "/r")], True))
self.assertEqual((fresh.made("python"), "- A fact." in facts), ([(["/b/chunk-preflight", "--worktree", "--item", "7"], "/r")], True))
transcript = pathlib.Path(home, "projects", "-fake", f"{opened.id}.jsonl")
transcript.parent.mkdir(parents=True)
transcript.write_text("")
@@ -1932,6 +2021,75 @@ class LoopRuns(unittest.TestCase):
self.assertEqual(reload.exec_if_edited(a_loop(fake.effects(), launcher=launcher), "stale", main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="")), Stop(1, "could not reload loop-claude: No such file or directory; rerun loop-claude <task>"))
class WindowStarts(unittest.TestCase):
"""The loop-claude the human runs, which starts the windows, and the stop of a window's loop whose chunk finished."""
HOME = pathlib.Path("/h")
def run_loop(self, argv, fake, env=None, started=("item-3", "item-4")):
"""run_loop's stop and what it said on stdout, with start_chunks answering `started`; self.asked holds what start_chunks was asked."""
with unittest.mock.patch.object(main, "start_chunks", return_value=list(started) if isinstance(started, tuple) else started) as start, contextlib.redirect_stdout(io.StringIO()) as said:
stop = main.run_loop(argv, env or {}, paths.paths_from(self.HOME), pathlib.Path("/b/loop-claude"), CWD, fake.effects())
self.asked = [call.args[:2] for call in start.call_args_list]
return stop, said.getvalue()
def test_refuses_to_start_anything_on_a_tmux_older_than_needed(self):
fake = FakeEffects(git=["/r\n"], tmux_version="tmux 3.1c")
self.assertEqual(self.run_loop(["do it"], fake), (Stop(1, "loop-claude runs each chunk in a tmux window, and needs tmux 3.2 or later; it found tmux 3.1c"), ""))
self.assertEqual((fake.tmux_calls, self.asked), ([["-V"]], []))
def test_prints_the_help_without_tmux(self):
fake = FakeEffects(tmux_version="")
self.assertEqual(self.run_loop(["--help"], fake)[0], Stop(0, usage.HELP))
self.assertEqual(fake.tmux_calls, [])
def test_starts_the_chunks_then_attaches_to_the_session_or_inside_tmux_switches_to_it(self):
for env, shown in (({}, ["attach-session", "-t", "=loop-r"]), ({"TMUX": "/tmp/tmux-1000/default,1,0"}, ["switch-client", "-t", "=loop-r"])):
with self.subTest(shown=shown):
fake = FakeEffects(git=["/r\n"])
stop, said = self.run_loop(["do", "it"], fake, env)
self.assertEqual((stop, said), (Stop(0, ""), f"{STAMP} started item-3, item-4 in the tmux session loop-r\n"))
self.assertEqual(fake.tmux_calls, [["-V"], shown])
self.assertEqual(self.asked, [(main.LoopRun(0, "/r", "do it", ""), False)])
def test_says_that_nothing_started_where_the_session_already_runs_every_chunk_that_may(self):
self.assertEqual(self.run_loop(["do it"], FakeEffects(git=["/r\n"]), started=())[1], f"{STAMP} the tmux session loop-r runs every chunk that may run now\n")
def test_off_a_terminal_it_prints_how_to_attach(self):
fake = FakeEffects(git=["/r\n"], on_terminal=False)
stop, said = self.run_loop(["do it"], fake)
self.assertEqual(stop, Stop(0, ""))
self.assertTrue(said.endswith(f"{STAMP} not on a terminal; see the chunks with `tmux attach -t =loop-r`\n"), said)
self.assertEqual(fake.tmux_calls, [["-V"]])
def test_stops_where_no_chunk_could_start(self):
self.assertEqual(self.run_loop(["do it"], FakeEffects(git=["/r\n"]), started=Failure("no plan"))[0], Stop(1, "no plan"))
def test_stops_where_tmux_cannot_show_the_session(self):
fake = FakeEffects(git=["/r\n"])
effects = dataclasses.replace(fake.effects(), tmux_on_terminal=lambda args: 1)
with unittest.mock.patch.object(main, "start_chunks", return_value=["item-3"]), contextlib.redirect_stdout(io.StringIO()):
stop = main.run_loop(["do it"], {}, paths.paths_from(self.HOME), pathlib.Path("/b/loop-claude"), CWD, effects)
self.assertEqual(stop, Stop(1, "`tmux attach-session -t =loop-r` failed; the chunks go on in the session"))
def test_a_window_loop_outside_tmux_stops(self):
fake = FakeEffects(git=["/r\n"])
self.assertEqual(self.run_loop(["--chunk", "item-3", "do it"], fake)[0], Stop(1, "--chunk is how loop-claude starts itself in a tmux window; run loop-claude <task>"))
self.assertEqual(self.asked, [])
def test_reads_the_chunk_a_window_loop_is_started_with(self):
self.assertEqual(main.loop_run_from(["--chunk", "item-3", "do", "it"], CWD, FakeEffects(git=["/r\n"]).effects()), main.LoopRun(0, "/r", "do it", "", chunk="item-3"))
self.assertEqual(main.loop_run_from(["do", "it"], CWD, FakeEffects(git=["/r\n"]).effects()), main.LoopRun(0, "/r", "do it", ""))
def test_a_finished_chunk_starts_each_chunk_that_may_start_and_stops_without_a_reason(self):
loop_run = main.LoopRun(4, "/r", "do it", "", chunk="item-7")
for started, said, stop in ((["item-9"], "the chunk finished; started item-9", Stop(0, "")), ([], "the chunk finished; started no other, since the chunks running fill what may run now", Stop(0, "")),
(Failure("no plan"), "", Stop(1, "the chunk finished, but the next could not start: no plan"))):
with self.subTest(started=started), unittest.mock.patch.object(main, "start_chunks", return_value=started) as start, contextlib.redirect_stdout(io.StringIO()) as printed:
self.assertEqual(main.handed_on(loop_run, a_loop(FakeEffects().effects())), stop)
self.assertEqual(printed.getvalue(), f"{STAMP} {said}\n" if said else "")
self.assertEqual(start.call_args.args[:2], (loop_run, True))
class StopDms(unittest.TestCase):
def run_main(self, argv, fake):
with tempfile.TemporaryDirectory() as home, contextlib.redirect_stderr(io.StringIO()) as said, contextlib.redirect_stdout(io.StringIO()):
@@ -1944,6 +2102,12 @@ class StopDms(unittest.TestCase):
self.assertEqual(self.run_main(["do it"], fake)[0], 2)
self.assertEqual(fake.dms, [f"loop-claude in {CWD} stopped: the human is needed to look at the chunk, but it stayed unfinished"])
def test_skips_the_dm_of_a_stop_without_a_reason_as_once_the_windows_started(self):
fake = FakeEffects()
with unittest.mock.patch.object(main, "run_loop", return_value=Stop(0, "")):
self.assertEqual(self.run_main(["do it"], fake), (0, ""))
self.assertEqual(fake.dms, [])
def test_skips_the_dm_where_ctrl_c_stopped_the_loop(self):
fake = FakeEffects()
with unittest.mock.patch.object(main, "run_loop", side_effect=KeyboardInterrupt):
@@ -2021,7 +2185,11 @@ class ExitContract(unittest.TestCase):
("cycle/run.py", "close", "1", "failure.reason", read),
("cycle/run.py", "close", "1", "failure.reason", "a finished chunk's session cannot be deleted"),
("loop/close.py", "closed_cycle", "1", "failure.reason", read),
("loop/main.py", "run_loop", "1", "held.reason", "its slot in the project cannot be taken"),
("loop/main.py", "run_loop", "1", "reason", "tmux is missing or older than 3.2"),
("loop/main.py", "run_loop", "1", "f'{CHUNK_FLAG} is how loop-claude starts itself", "--chunk is given outside a tmux window"),
("loop/main.py", "windows_opened", "1", "started.reason", "a chunk's window cannot be started"),
("loop/main.py", "windows_opened", "1", "f\"`tmux {' '.join(shown)}` failed", "the tmux session cannot be put on the terminal"),
("loop/main.py", "handed_on", "1", "f'the chunk finished, but the next could not start", "a chunk's window cannot be started"),
("loop/main.py", "next_cycle", "1", "premises.reason", premises_),
("loop/main.py", "next_cycle", "1", "records.reason", unreadable),
("loop/main.py", "next_cycle", "1", "ladder_file.reason", premises_),