From fa9d487afd14674ef7332922eae888a062778215 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 16 Nov 2026 12:46:07 +0100 Subject: [PATCH] =?UTF-8?q?Answer=20stability=20round=201:=201=20?= =?UTF-8?q?=F0=9F=94=B4,=204=20=F0=9F=9F=A1=20(0=20misread);=20check=20a?= =?UTF-8?q?=20new=20chunk's=20Touches=20against=20every=20held=20item,=20k?= =?UTF-8?q?eep=20a=20stopped=20chunk's=20items,=20test=20the=20fetch=20and?= =?UTF-8?q?=20fold=20the=20slot=20loop=20back?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin/loop_claude/cycle/prompts.py | 4 +- bin/loop_claude/loop/chunk_start.py | 7 +-- bin/loop_claude/loop/chunk_windows.py | 49 ++++++++++------ bin/loop_claude/loop/main.py | 10 ++-- bin/loop_claude/test_black_box.py | 37 +++++++++--- bin/loop_claude/test_loop_claude.py | 81 +++++++++++++++++++++------ bin/loop_claude/tmux.py | 11 +++- bin/machine_load/slots.py | 7 +-- 8 files changed, 148 insertions(+), 58 deletions(-) diff --git a/bin/loop_claude/cycle/prompts.py b/bin/loop_claude/cycle/prompts.py index f78d2c20..3010ac93 100644 --- a/bin/loop_claude/cycle/prompts.py +++ b/bin/loop_claude/cycle/prompts.py @@ -54,8 +54,8 @@ def preflight_facts(printed: str) -> str: def held_by_others(items: list[int]) -> str: - """Keeps a fresh worker off the plan items the project's other running chunks hold.""" - return f"\n\nOther chunks of this project run now, and hold {'items ' if len(items) > 1 else 'item '}{', '.join(map(str, items))}. Leave those out of this chunk, whatever else may join it." + """Keeps a fresh worker off the plan items the project's other chunks hold, running or stopped.""" + return f"\n\nOther chunks of this project, running or stopped, hold {'items ' if len(items) > 1 else 'item '}{', '.join(map(str, items))}. Leave those items out of this chunk, even where the facts above list them as items that may join it." def preflight_failed(reason: str) -> str: diff --git a/bin/loop_claude/loop/chunk_start.py b/bin/loop_claude/loop/chunk_start.py index 3b8415ec..c58c70ae 100644 --- a/bin/loop_claude/loop/chunk_start.py +++ b/bin/loop_claude/loop/chunk_start.py @@ -67,13 +67,12 @@ def chunk_start(loop: Loop) -> tuple[str, typing.Callable[[], Item | None]]: def chunk_facts(loop: Loop) -> str: - """What `chunk-preflight --worktree` printed at the checkout root, for a fresh worker's prompt, or why it could not run. The chunk of a window named for an item starts from that item, and the facts end with the items the project's other running chunks hold.""" + """What `chunk-preflight --worktree` printed at the checkout root, for a fresh worker's prompt, or why it could not run. The chunk of a window named for an item starts from that item, and either ends with the items the project's other chunks hold.""" item = item_of(loop.window.name) done = loop.effects.python([str(loop.launcher.with_name("chunk-preflight")), "--worktree", *([] if item is None else [ITEM, str(item)])], loop.root) - if done.returncode: - return prompts.preflight_failed(done.stderr.strip() or f"it exited {done.returncode}") + facts = prompts.preflight_failed(done.stderr.strip() or f"it exited {done.returncode}") if done.returncode else prompts.preflight_facts(done.stdout.strip()) held = held_beside(loop.window.name, loop.root, loop.paths, loop.effects) - return prompts.preflight_facts(done.stdout.strip()) + (prompts.held_by_others(held) if held else "") + return facts + (prompts.held_by_others(held) if held else "") def fetched_plan(loop: Loop) -> DefaultPlan | Failure: diff --git a/bin/loop_claude/loop/chunk_windows.py b/bin/loop_claude/loop/chunk_windows.py index 36d214c5..c2d148fb 100644 --- a/bin/loop_claude/loop/chunk_windows.py +++ b/bin/loop_claude/loop/chunk_windows.py @@ -13,6 +13,7 @@ from failure import Failure from project_config.main import located from loop_claude.loop.reload import LoopRun from chunk_preflight.gathered import NoItem, Plan +from touch_predictions.prediction import overlaps, predicted, Touches from loop_state.paths import Paths from chunk_preflight.choices import planned from transcript_archive.project_key import project_key @@ -23,15 +24,15 @@ from loop_claude import tmux # Under the home folder, a folder per project key holds LOCK. STATE = ".local/state/loop-claude" -# The file a loop keeps locked with flock while it lists the project's windows and starts new ones, so two loops whose chunks finish together start no chunk twice. +# The file a loop keeps locked with flock while it lists the project's windows and starts new ones, so two loops whose chunks finish together don't start a chunk twice. LOCK = "starting" -# loop-claude's own flag: the loop it starts in a window is told its chunk by it, as `--chunk item-372`. Nobody types it, so no panel picked it. +# The flag that tells the loop in a window its chunk, as `--chunk item-372`. Nobody types it, so no panel picked it. CHUNK_FLAG = "--chunk" # The chunk of a plan that names no item for the next chunk: a release to plan, a release review, or a task outside the plan. NO_ITEM = "no-item" # Seconds a fetch of origin may take before a chunk starts; past them, the plan reads as last fetched. FETCH_TIMEOUT = 60 -# The variables loop-claude reads. A window gets the tmux server's environment, not the starting terminal's, so they are handed to each window by name. +# The prefix of the variables loop-claude reads. A window gets the tmux server's environment, not the starting terminal's, so they are handed to each window by name. HANDED = "LOOP_CLAUDE_" @@ -72,12 +73,21 @@ def held_items(chunks: typing.Iterable[str], key: str, claude_code_transcripts: def may_start(plan: Plan | NoItem, running: list[str], held: set[int], limit: int) -> list[str]: - """The chunks to start now, beside those running, whose items are held: the plan's next item and the items touch_predictions picks to run beside it, in the plan's order, less each a running chunk holds, up to limit chunks at once. A plan without an item starts NO_ITEM, and only alone.""" + """The chunks to start now beside the running ones, whose chunks hold the items in held: the plan's next item and the items touch_predictions picks to run beside it, in the plan's order, up to limit chunks running at once. Each leaves out an item in held, and one whose `Touches:` prediction overlaps a held item's, or where either has none. A plan without an item starts NO_ITEM, and only alone.""" if isinstance(plan, NoItem): return [] if running else [NO_ITEM] beside = chunks_beside(plan.items, plan.first) picked = [plan.first.id, *(beside.picked if isinstance(beside, Beside) else [])] - return [window_name(item_id) for item_id in picked if item_id not in held][: max(limit - len(running), 0)] + details = {item.id: item.detail for item in plan.items} + # chunks_beside checks overlaps against the plan's next item only, and a running chunk's item may no longer be that one once an item merged. A held item that left the plan overlaps nothing. + theirs = [predicted(details[item_id]) for item_id in sorted(held) if item_id in details] + free = [item_id for item_id in picked if item_id not in held and clear_of(predicted(details[item_id]), theirs)] + return [window_name(item_id) for item_id in free][: max(limit - len(running), 0)] + + +def clear_of(ours: Touches | Failure | None, theirs: list[Touches | Failure | None]) -> bool: + """Whether a prediction overlaps none of theirs; not where one of them is missing or unreadable, unless theirs is empty.""" + return not theirs or (isinstance(ours, dict) and all(isinstance(touches, dict) and not overlaps(ours, touches) for touches in theirs)) def next_plan(root: str, home: pathlib.Path, effects: Effects) -> Plan | NoItem | Failure: @@ -95,7 +105,7 @@ def next_plan(root: str, home: pathlib.Path, effects: Effects) -> Plan | NoItem def start_chunks(loop_run: LoopRun, leaving: bool, paths: Paths, env: typing.Mapping[str, str], launcher: pathlib.Path, effects: Effects) -> list[str] | Failure: - """Starts a loop-claude in a new window for each chunk of loop_run's project that may start now, and returns the chunks started. leaving says that loop_run's own chunk finished, so its window no longer counts as running. A plan that cannot be read starts NO_ITEM, as a plan without an item does. A Failure says why none could start.""" + """Starts a loop-claude in a new window for each chunk of loop_run's project that may start now, and returns the chunks started. leaving says that loop_run's own chunk finished, so its window no longer counts as running; without it, the human started loop-claude. A plan that cannot be read starts NO_ITEM, as a plan without an item does. A Failure says why a chunk could not start; those before it run.""" config = located(loop_run.root, paths.home) if isinstance(config, Failure): return config @@ -105,17 +115,24 @@ def start_chunks(loop_run: LoopRun, leaving: bool, paths: Paths, env: typing.Map try: with starting(paths.home, key): windows = tmux.listed(session, effects.tmux) + if windows and (owned := tmux.owner(session, effects.tmux)) != loop_run.root: + return Failure(f"the tmux session {session} runs the chunks of {owned or 'another checkout'}, whose key maps to the same session name; rename one of the two checkouts' folders") running = [window.name for window in windows if not window.dead and not (leaving and window.name == loop_run.chunk)] - if len(running) >= config.parallel_chunks: + room = config.parallel_chunks - len(running) + if room <= 0: return [] - plan = next_plan(loop_run.root, paths.home, effects) - if isinstance(plan, Failure): - # As in a checkout without a default branch. The chunk's worker is told why its preflight failed, and finds the facts itself. - say(f"starting a chunk without a plan item, since the plan cannot be read: {plan.reason}", effects) - plan = NoItem(plan.reason) - chunks = may_start(plan, running, held_items(running, key, paths.claude_code_transcripts), config.parallel_chunks) + # A loop that the human stopped, or that failed, keeps its window, dead, with its last lines and its items. Only the human's loop-claude starts it again, before any other chunk. + stopped = [window.name for window in windows if window.dead] + chunks = [] if leaving else stopped[:room] + if len(chunks) < room: + plan = next_plan(loop_run.root, paths.home, effects) + if isinstance(plan, Failure): + # Such as in a checkout without a default branch, where chunk-preflight fails too: the worker is told why and finds the facts itself. + say(f"starting a chunk without a plan item, since the plan cannot be read: {plan.reason}", effects) + plan = NoItem(plan.reason) + held = held_items(running + stopped, key, paths.claude_code_transcripts) + chunks += [chunk for chunk in may_start(plan, running + chunks, held, config.parallel_chunks) if chunk not in stopped] for chunk in chunks: - # The window of a loop that failed stays, dead, until its chunk starts again. stale = [window for window in windows if window.name == chunk and window.dead] for window in stale: tmux.close(window, effects.tmux) @@ -130,9 +147,9 @@ def start_chunks(loop_run: LoopRun, leaving: bool, paths: Paths, env: typing.Map def held_beside(chunk: str, root: str, paths: Paths, effects: Effects) -> list[int]: - """The plan items that the project's other running chunks hold now, which a chunk starting as `chunk` leaves to them. It waits for a loop that is starting windows, so chunks started together see each other. Where the lock cannot be taken, it reads the windows without it.""" + """The plan items that the project's other chunks hold now, running or stopped, which a chunk starting as `chunk` leaves to them. It waits for a loop that is starting windows, so chunks started together see each other. Where the lock cannot be taken, it reads the windows without it.""" key = project_key(root, paths.home) with contextlib.suppress(OSError), starting(paths.home, key): pass - others = [window.name for window in tmux.listed(tmux.session_name(key), effects.tmux) if not window.dead and window.name != chunk] + others = [window.name for window in tmux.listed(tmux.session_name(key), effects.tmux) if window.name != chunk] return sorted(held_items(others, key, paths.claude_code_transcripts)) diff --git a/bin/loop_claude/loop/main.py b/bin/loop_claude/loop/main.py index 7feefb26..6843a8e8 100644 --- a/bin/loop_claude/loop/main.py +++ b/bin/loop_claude/loop/main.py @@ -37,7 +37,7 @@ def main(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launcher: raise if stop.reason: say(stop.reason, effects, stdout=not stop.code) - # Every stop with a reason, but the help, is DMed where the project's config can be read and sets `env-file`, so a loop left overnight never ends unseen. A loop given no task prints the help. Ctrl-C stops without a reason. So does a loop that started the project's windows, or whose chunk finished and handed on to the next, since the project's chunks go on. + # Every stop with a reason, but the help, is DMed where the project's config can be read and sets `env-file`, so a loop left overnight never ends unseen. A loop given no task prints the help. Ctrl-C stops without a reason. So does the loop that started the project's windows once it attaches or prints how to, and a loop whose chunk finished once it started the next chunks, since the project's chunks go on. if stop.reason not in ("", HELP): tell(f"loop-claude in {cwd} stopped: {stop.reason}", effects) return stop.code @@ -47,7 +47,7 @@ def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launc loop_run = loop_run_from(argv, cwd, effects) if isinstance(loop_run, Stop): return loop_run - # Before anything starts: a worktree, a session or a window. + # Before anything starts: a worktree, a claude session or a tmux window. if reason := tmux.unusable(effects.tmux): return Stop(1, reason) if loop_run.chunk is None: @@ -86,12 +86,12 @@ def windows_opened(loop_run: LoopRun, env: typing.Mapping[str, str], paths: Path if isinstance(started, Failure): return Stop(1, started.reason) session = tmux.session_name(project_key(loop_run.root, paths.home)) - say(f"started {', '.join(started)} in the tmux session {session}" if started else f"the tmux session {session} runs every chunk that may run now", effects, stdout=True) + say(f"started {', '.join(started)} in the tmux session {session}" if started else f"the tmux session {session} runs every chunk that may run now, so `{loop_run.task}` started in no new window", effects, stdout=True) if not effects.on_terminal(): say(f"not on a terminal; see the chunks with `tmux attach -t ={session}`", effects, stdout=True) return Stop(0, "") shown = tmux.show(session, "TMUX" in env) - return Stop(1, f"`tmux {' '.join(shown)}` failed; the chunks go on in the session") if effects.tmux_on_terminal(shown) else Stop(0, "") + return Stop(1, f"`tmux {' '.join(shown)}` failed; the chunks go on in the tmux session") if effects.tmux_on_terminal(shown) else Stop(0, "") def handed_on(loop_run: LoopRun, loop: Loop) -> Stop: @@ -129,7 +129,7 @@ def next_cycle(loop_run: LoopRun, loop: Loop) -> Cycle | Stop: if ladder_file != SHIPPED: say(own_ladder(ladder_file, models.worker, project is None), loop.effects) todo = fetched_todo(loop) - return Cycle(config=setup_version(loop.paths.claude_dir, loop.effects.git), effects=loop.effects, facts=facts, judge_model=models.judge, ladder=ladder, premises=premises, project=project, project_archive=archive_folder, records=records, root=loop.root, route=route, session=loop.session, task=loop_run.task, window=loop.window, todo=todo, unfinished_evidence=loop_run.unfinished_evidence) + return Cycle(config=setup_version(loop.paths.claude_dir, loop.effects.git), effects=loop.effects, facts=facts, judge_model=models.judge, ladder=ladder, premises=premises, project=project, project_archive=archive_folder, records=records, root=loop.root, route=route, session=loop.session, task=loop_run.task, todo=todo, unfinished_evidence=loop_run.unfinished_evidence, window=loop.window) def own_ladder(file: pathlib.Path, model: str, unrouted: bool) -> str: diff --git a/bin/loop_claude/test_black_box.py b/bin/loop_claude/test_black_box.py index 5c31843a..a167edb9 100644 --- a/bin/loop_claude/test_black_box.py +++ b/bin/loop_claude/test_black_box.py @@ -29,9 +29,7 @@ OFF_LADDER = '{"model": "worker-model"}' OFF_LADDER_ROUTE = {"rung": {"model": "worker-model", "effort": ""}, "item": 0, "likelihood": 0, "escape_and_impact": 0, "unfinished": 0, "escape_and_impact_taken_in": 0, "escalated_at": 0} -# Plays claude from FAKE_CLAUDE_SCENARIO, one step per call, logging each call; a step for another role, -# or none left, is Ctrl-C to loop-claude, which otherwise loops forever. -# A tmux that logs each command. It prints $FAKE_TMUX_VERSION for -V and the file $FAKE_TMUX_WINDOWS for list-windows, where it finds no session without the file, and for any other command the ID of a new window. +# A tmux that logs each command. It prints $FAKE_TMUX_VERSION for -V, $FAKE_TMUX_OWNER for show-options, and the file $FAKE_TMUX_WINDOWS for list-windows, where it finds no session without the file, and for any other command the ID of a new window. FAKE_TMUX = """#!{python} import json, os, pathlib, sys @@ -41,6 +39,8 @@ with open(os.environ["FAKE_TMUX_LOG"], "a") as log: windows = pathlib.Path(os.environ["FAKE_TMUX_WINDOWS"]) if argv[0] == "-V": print(os.environ.get("FAKE_TMUX_VERSION", "tmux 3.2")) +elif argv[0] == "show-options": + print(os.environ["FAKE_TMUX_OWNER"]) elif argv[0] == "list-windows": if not windows.exists(): sys.exit("no server running") @@ -49,6 +49,8 @@ else: print("@7") """ +# Plays claude from FAKE_CLAUDE_SCENARIO, one step per call, logging each call; a step for another role, +# or none left, is Ctrl-C to loop-claude, which otherwise loops forever. FAKE_CLAUDE = """#!{python} import json, os, pathlib, signal, sys, time @@ -227,6 +229,7 @@ class Checkout: "FAKE_MEMINFO": str(self.temp / "meminfo"), "FAKE_TMUX_LOG": str(self.temp / "tmux.jsonl"), "FAKE_TMUX_WINDOWS": str(self.temp / "tmux-windows"), + "FAKE_TMUX_OWNER": str(self.root), # The pane of the window the loop under test runs in. "TMUX_PANE": "%3", "FAKE_CLAUDE_SCENARIO": str(self.temp / "scenario.json"), @@ -827,6 +830,7 @@ class Windows(unittest.TestCase): ["-V"], ["list-windows", "-t", "=loop-proj", "-F", "#{window_name}\t#{pane_dead}\t#{window_id}"], ["new-session", "-d", "-s", "loop-proj", "-n", "item-4", "-c", str(checkout.root), "-e", "LOOP_CLAUDE_JUDGE_MODEL=judge-model", "-e", "LOOP_CLAUDE_WORKER_MODEL=worker-model", "-P", "-F", "#{window_id}", "--", str(checkout.script), "--chunk", "item-4", "ship it"], + ["set-option", "-t", "=loop-proj", "@loop-root", str(checkout.root)], ["set-option", "-w", "-t", "@7", "remain-on-exit", "failed"], ]) self.assertEqual(run.stdout, "started item-4 in the tmux session loop-proj\nnot on a terminal; see the chunks with `tmux attach -t =loop-proj`\n") @@ -846,7 +850,7 @@ class Windows(unittest.TestCase): pathlib.Path(checkout.env["FAKE_TMUX_WINDOWS"]).write_text("item-4\t0\t@1\nitem-9\t0\t@2\n") run = checkout.run([], argv=[TASK]) self.assertEqual((self.started(run), run.code), ([], 0)) - self.assertIn("the tmux session loop-proj runs every chunk that may run now\n", run.stdout) + self.assertIn(f"the tmux session loop-proj runs every chunk that may run now, so `{TASK}` started in no new window\n", run.stdout) def test_a_finished_chunk_starts_the_next_one_its_window_leaves_room_for(self): checkout = self.checkout(parallel=2) @@ -857,6 +861,25 @@ class Windows(unittest.TestCase): self.assertEqual(self.started(run), [("new-window", "item-9", [str(checkout.script), "--chunk", "item-9", TASK])]) self.assertIn("the chunk finished; started item-9\n", run.stdout) + def test_a_finished_chunk_starts_the_next_item_from_the_plan_its_merge_left_on_origin(self): + checkout = Checkout(self) + origin = checkout.temp / "origin.git" + checkout.git("init", "--quiet", "--bare", "--initial-branch=main", str(origin)) + checkout.git("symbolic-ref", "HEAD", "refs/heads/main") + checkout.commit_plan(TODO) + checkout.git("remote", "add", "origin", str(origin)) + checkout.git("push", "--quiet", "--set-upstream", "origin", "main") + # Item 4's chunk runs a cycle and stays open, so the rerun below resumes it and runs no chunk-preflight, which would fetch. + self.assertEqual(checkout.run([worker(), judge()], chunk="item-4").code, 130) + # Item 4's chunk merges, which leaves item 6 next on origin; the checkout fetched before it. + elsewhere = checkout.temp / "elsewhere" + checkout.git("clone", "--quiet", str(origin), str(elsewhere)) + (elsewhere / "todo.md").write_text(TODO.replace("| 4 | 0.1.0 |", "| 6 | 0.1.0 |")) + checkout.git("-C", str(elsewhere), "commit", "--quiet", "--all", "-m", "Finish item 4") + checkout.git("-C", str(elsewhere), "push", "--quiet", "origin", "main") + run = checkout.run([worker(say="merged"), judge(finished=True, evidence="merged")], chunk="item-4") + self.assertEqual(self.started(run), [("new-session", "item-6", [str(checkout.script), "--chunk", "item-6", TASK])]) + def test_tells_a_fresh_worker_the_items_the_other_running_chunks_hold_and_starts_from_its_windows_item(self): checkout = self.checkout(parallel=2) checkout.env["LOOP_CLAUDE_WORKER_MODEL"] = "claude-opus-5-5" @@ -864,7 +887,7 @@ class Windows(unittest.TestCase): run = checkout.run([worker()], chunk="item-9") prompt = argument(run.calls[0], "-p") self.assertIn("The item this chunk starts from, named with --item: item 9, L 4, E + I 3.", prompt) - self.assertIn("Other chunks of this project run now, and hold item 4. Leave those out of this chunk, whatever else may join it.", prompt) + self.assertIn("Other chunks of this project, running or stopped, hold item 4. Leave those items out of this chunk, even where the facts above list them as items that may join it.", prompt) self.assertIn("routed by item 9's L of 4", prompt) def test_refuses_to_start_on_a_tmux_older_than_needed_or_without_one(self): @@ -1097,12 +1120,12 @@ class Reload(unittest.TestCase): self.assertEqual(run.calls[0]["cwd"], str(checkout.root)) self.assertIn("=== cycle 4,", run.stdout) - def test_a_loop_started_before_chunks_ran_in_windows_reloads_by_moving_its_chunk_into_one(self): + def test_a_loop_started_before_chunks_ran_in_windows_reloads_into_starting_the_projects_windows(self): checkout = Checkout(self) state = {"cycle_number": 3, "root": str(checkout.root), "task": TASK, "unfinished_evidence": "", "route": None, "slot": 0} run = checkout.run([worker()], argv=["--reloaded", json.dumps(state)]) self.assertEqual((run.code, run.calls), (0, [])) - self.assertEqual([command[0] for command in run.tmux], ["-V", "list-windows", "new-session", "set-option"]) + self.assertEqual([command[0] for command in run.tmux], ["-V", "list-windows", "new-session", "set-option", "set-option"]) self.assertIn("started no-item in the tmux session loop-proj\n", run.stdout) def test_stops_where_a_reload_hands_no_state(self): diff --git a/bin/loop_claude/test_loop_claude.py b/bin/loop_claude/test_loop_claude.py index 46e1a908..f800d203 100644 --- a/bin/loop_claude/test_loop_claude.py +++ b/bin/loop_claude/test_loop_claude.py @@ -93,12 +93,14 @@ def a_loop(effects, **fields): 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=(), tmux_version="tmux 3.2", windows=None): + 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, owner="/r"): 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 + # The checkout the session's @loop-root option names. + self.owner = owner # 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) @@ -134,7 +136,7 @@ class FakeEffects: 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"), "") + return subprocess.CompletedProcess(args, 0, {"-V": self.tmux_version + "\n", "show-options": self.owner + "\n"}.get(args[0], "@9\n"), "") def dm(self, text): self.dms.append(text) @@ -1293,6 +1295,7 @@ class TmuxCommands(unittest.TestCase): 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", "-t", "=loop-proj", "@loop-root", "/r"], ["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"], @@ -1305,6 +1308,11 @@ class TmuxCommands(unittest.TestCase): 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_reads_the_checkout_the_session_names(self): + fake = FakeEffects(owner="/c/proj") + self.assertEqual(tmux.owner("loop-proj", fake.tmux), "/c/proj") + self.assertEqual(fake.tmux_calls, [["show-options", "-qv", "-t", "=loop-proj", "@loop-root"]]) + def test_marks_a_waiting_window_by_its_pane_and_clears_the_mark(self): fake = FakeEffects() tmux.mark(WINDOW, True, fake.tmux) @@ -1338,6 +1346,17 @@ class ChunkWindows(unittest.TestCase): 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_starts_no_item_that_overlaps_a_running_chunks_items(self): + # Item 1 merged, so 2 is the plan's next item; it overlaps item 3, which still runs, at c.py. + items = touch_plan((2, "1.0.0", "", "- `a.py`\n- `c.py`"), (3, "1.0.0", "", "- `c.py`"), (4, "1.0.0", "", "- `d.py`")) + plan = gathered.Plan(items=items, first=items[0], text="", branch_template="") + self.assertEqual(chunk_windows.may_start(plan, ["item-3"], {3}, 3), ["item-4"]) + # A running chunk's item without a prediction leaves no other item free to start beside it. + unpredicted = touch_plan((2, "1.0.0", "", "- `a.py`"), (3, "1.0.0", "", None)) + self.assertEqual(chunk_windows.may_start(gathered.Plan(items=unpredicted, first=unpredicted[0], text="", branch_template=""), ["item-3"], {3}, 3), []) + # A held item that left the plan, as once it merged, overlaps nothing. + self.assertEqual(chunk_windows.may_start(plan, ["item-9"], {9}, 3), ["item-2", "item-4"]) + 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"]) @@ -1370,9 +1389,9 @@ class ChunkWindows(unittest.TestCase): folder.mkdir(parents=True) lines = [assistant({"type": "text", "text": "Chunk items: 8 (L 1, E + I 2), 11 (L 2, E + I 3)"})] (folder / f"{chunk_windows.chunk_session('r', 'item-8', held.claude_code_transcripts).id}.jsonl").write_text("".join(json.dumps(line) + "\n" for line in lines)) - # Its own window, item-7, and item-9's dead one hold nothing for it. + # Its own window, item-7, holds nothing for it; item-9's stopped chunk holds its item. fake = FakeEffects(windows="item-7\t0\t@1\nitem-8 ?\t0\t@2\nitem-9\t1\t@3\nitem-10\t0\t@4\n") - self.assertEqual(chunk_windows.held_beside("item-7", "/r", held, fake.effects()), [8, 10, 11]) + self.assertEqual(chunk_windows.held_beside("item-7", "/r", held, fake.effects()), [8, 9, 10, 11]) self.assertEqual(fake.tmux_calls, [["list-windows", "-t", "=loop-r", "-F", "#{window_name}\t#{pane_dead}\t#{window_id}"]]) @@ -1393,7 +1412,9 @@ class StartChunks(unittest.TestCase): config = self.home / ".claude-projects" / self.root.name / "config.toml" config.write_text(config.read_text() + f"parallel-chunks = {chunks}\n") - def start(self, fake, chunk=None, leaving=False, plan=None, env=None): + def start(self, fake, chunk=None, leaving=False, plan=None, env=None, owner=None): + """start_chunks' answer, for a session whose @loop-root names owner, by default this checkout.""" + fake.owner = str(self.root) if owner is None else owner run = main.LoopRun(0, str(self.root), "ship it", "", chunk=chunk) with unittest.mock.patch.object(chunk_windows, "next_plan", return_value=plan or self.plan) as planned, contextlib.redirect_stderr(io.StringIO()) as said: effects = fake.effects() @@ -1418,6 +1439,15 @@ class StartChunks(unittest.TestCase): # Only loop-claude's own variables are handed on, since a window gets the tmux server's environment. self.assertEqual([word for word in first if "=" in word], ["LOOP_CLAUDE_WORKER_MODEL=m"]) self.assertEqual(fake.tmux_calls[0], ["list-windows", "-t", f"={self.session}", "-F", "#{window_name}\t#{pane_dead}\t#{window_id}"]) + # The session names the checkout whose chunks it runs. + self.assertIn(["set-option", "-t", f"={self.session}", "@loop-root", str(self.root)], fake.tmux_calls) + + def test_refuses_a_session_that_runs_another_checkouts_chunks(self): + for owner, named in (("/c/acme.api", "/c/acme.api"), ("", "another checkout")): + with self.subTest(owner=owner): + fake = FakeEffects(windows="item-5\t0\t@1\n") + self.assertEqual(self.start(fake, owner=owner), Failure(f"the tmux session {self.session} runs the chunks of {named}, whose key maps to the same session name; rename one of the two checkouts' folders")) + self.assertEqual(self.starts(fake), []) def test_leaves_out_the_items_a_running_chunk_names_on_its_chunk_items_line(self): self.limit(2) @@ -1445,23 +1475,36 @@ class StartChunks(unittest.TestCase): # The session exists, since the finishing loop's window is still in it. self.assertEqual(self.starts(fake)[0][0], "new-window") - def test_closes_the_dead_window_of_a_chunk_before_starting_it_again(self): - fake = FakeEffects(windows="item-1\t1\t@3\n") - self.assertEqual(self.start(fake), ["item-1"]) + def test_the_humans_loop_claude_starts_a_stopped_chunk_again_first_closing_its_dead_window(self): + fake = FakeEffects(windows="item-5\t1\t@3\n") + self.assertEqual((self.start(fake), self.planned), (["item-5"], 0)) self.assertIn(["kill-window", "-t", "@3"], fake.tmux_calls) # Its dead window was the session's last, so the session is made again. self.assertEqual(self.starts(fake)[0][0], "new-session") - # Another chunk's dead window stays, with its last lines, until that chunk starts again. - fake = FakeEffects(windows="item-5\t1\t@7\n") - self.assertEqual(self.start(fake), ["item-1"]) + self.limit(2) + fake = FakeEffects(windows="item-5\t1\t@3\n") + self.assertEqual(self.start(fake), ["item-5", "item-1"]) + + def test_a_finishing_chunk_leaves_a_stopped_chunk_and_its_items_to_the_human(self): + self.limit(2) + transcripts = paths.paths_from(self.home).claude_code_transcripts + folder = transcripts / "-r" + folder.mkdir(parents=True) + opened = chunk_windows.chunk_session(str(self.root).lstrip("/"), "item-5", transcripts) + (folder / f"{opened.id}.jsonl").write_text(json.dumps(assistant({"type": "text", "text": "Chunk items: 5 (L 1, E + I 2), 1 (L 1, E + I 2)"})) + "\n") + fake = FakeEffects(windows="item-7\t0\t@1\nitem-5\t1\t@3\n") + # Item 1 is the stopped chunk's, so item 3 starts; the stopped one doesn't count against parallel-chunks. + self.assertEqual(self.start(fake, chunk="item-7", leaving=True), ["item-3"]) self.assertEqual([call for call in fake.tmux_calls if call[0] == "kill-window"], []) + fake = FakeEffects(windows="item-7\t0\t@1\nno-item\t1\t@3\n") + self.assertEqual(self.start(fake, chunk="item-7", leaving=True, plan=gathered.NoItem("release 1.0.0 has no items")), []) def test_starts_the_chunk_without_a_plan_item_where_the_plan_cannot_be_read(self): fake = FakeEffects() self.assertEqual(self.start(fake, plan=Failure("no origin/main")), ["no-item"]) self.assertIn("starting a chunk without a plan item, since the plan cannot be read: no origin/main", self.said) - def test_says_why_no_window_could_start(self): + def test_says_why_a_window_could_not_start(self): with unittest.mock.patch.object(tmux, "start_window", return_value=Failure("tmux could not start the window")): self.assertEqual(self.start(FakeEffects()), Failure("tmux could not start the window")) @@ -1564,11 +1607,15 @@ class ChunkFacts(unittest.TestCase): 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. + # The loop's own window, a stopped 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.") + self.assertTrue(said.endswith("- A fact.\n\nOther chunks of this project, running or stopped, hold items 5, 9, 12. Leave those items out of this chunk, even where the facts above list them as items that may join it."), said) + self.assertEqual(prompts.held_by_others([9]), "\n\nOther chunks of this project, running or stopped, hold item 9. Leave those items out of this chunk, even where the facts above list them as items that may join it.") + # A worker whose preflight failed is told them too. + fake = FakeEffects(python=[ran(code=1, stderr="git could not start\n")], windows="item-9\t0\t@4\n") + said = chunk_start.chunk_facts(a_loop(fake.effects(), launcher=self.LAUNCHER)) + self.assertTrue(said.endswith("Other chunks of this project, running or stopped, hold item 9. Leave those items out of this chunk, even where the facts above list them as items that may join it."), said) 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")): @@ -2226,7 +2273,7 @@ class WindowStarts(unittest.TestCase): self.assertIsInstance(main.loop_run_from(["--chunk", "item-3", "do it"], CWD, FakeEffects(git=[Failure("git cannot start")]).effects()), Stop) 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") + 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, so `do it` started in no new window\n") def test_off_a_terminal_it_prints_how_to_attach(self): fake = FakeEffects(git=["/r\n"], on_terminal=False) @@ -2243,7 +2290,7 @@ class WindowStarts(unittest.TestCase): 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")) + self.assertEqual(stop, Stop(1, "`tmux attach-session -t =loop-r` failed; the chunks go on in the tmux session")) def test_a_window_loop_outside_tmux_stops(self): fake = FakeEffects(git=["/r\n"]) diff --git a/bin/loop_claude/tmux.py b/bin/loop_claude/tmux.py index b2bed7f8..d5992c78 100644 --- a/bin/loop_claude/tmux.py +++ b/bin/loop_claude/tmux.py @@ -14,6 +14,8 @@ NEEDED = (3, 2) # What a window's name ends in while its chunk waits for the human. tmux's status bar shows the name, and `!` after it once the bell rang. WAITS = " ?" BELL = "\a" +# The session option that names the checkout whose chunks the session runs, since two checkouts' keys may map to one session name. +OWNER = "@loop-root" @dataclasses.dataclass(frozen=True) @@ -72,11 +74,18 @@ def start_window(window: Window, cwd: str, env: typing.Mapping[str, str], comman done = run([*make, "-n", window.name, "-c", cwd, *variables, "-P", "-F", "#{window_id}", "--", *words]) if done.returncode: return Failure(f"tmux could not start the window {window.target}: {done.stderr.strip() or f'it exited {done.returncode}'}") - # By the ID, since a window of the same name may still be closing. A loop that fails before this lands closes its window, and its stop is still sent as a DM. + if first: + run(["set-option", "-t", f"={window.session}", OWNER, cwd]) + # By the ID, since a window of the same name may still be closing. A loop that fails before the option is set closes its window, and its stop is still sent as a DM. run(["set-option", "-w", "-t", done.stdout.strip(), "remain-on-exit", "failed"]) return None +def owner(session: str, run: Tmux) -> str: + """The checkout whose chunks session runs, as OWNER names it; empty where it names none.""" + return run(["show-options", "-qv", "-t", f"={session}", OWNER]).stdout.strip() + + def close(window: Listed, run: Tmux) -> None: run(["kill-window", "-t", window.id]) diff --git a/bin/machine_load/slots.py b/bin/machine_load/slots.py index 0ad47408..9b2e9d64 100644 --- a/bin/machine_load/slots.py +++ b/bin/machine_load/slots.py @@ -28,12 +28,7 @@ def slot_folder(env: typing.Mapping[str, str], home: pathlib.Path) -> pathlib.Pa def taken_slot(folder: pathlib.Path, slots: int) -> tuple[int, int] | None: """The number and open file of the lowest slot this call locked; None while every slot is held. Raises OSError where a slot file cannot be opened or locked.""" - return first_free_slot(folder, range(slots)) - - -def first_free_slot(folder: pathlib.Path, order: typing.Iterable[int]) -> tuple[int, int] | None: - """The number and open file of the first slot in order that this call locked; None while every slot in order is held. Raises OSError where a slot file cannot be opened or locked.""" - for slot in order: + for slot in range(slots): fd = os.open(folder / f"slot-{slot}", os.O_RDWR | os.O_CREAT, 0o644) try: fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)