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
CI / tests (pull_request) Failing after 2m56s
This commit is contained in:
@@ -10,6 +10,7 @@ from claude_code.transcript import human_turns, read_transcript
|
||||
from loop_claude.stop import needs_human, needs_terminal, Stop
|
||||
from model_routing.ladder import Rung
|
||||
from loop_claude.direct_message import tell
|
||||
from loop_claude import tmux
|
||||
|
||||
ANSWER_QUESTION = "answer the question above"
|
||||
# TALK, what the human types at loop-claude's terminal to open claude for the question, and ASK_ANSWER were picked on 2026-10-17 by a bench of three readers seated as the README's audience, as ~/.claude/CLAUDE.md → "Working loop" → "Bench a syntax with the people who write it." has it.
|
||||
@@ -36,17 +37,26 @@ class Talked:
|
||||
"""The human typed in the worker's claude session."""
|
||||
|
||||
|
||||
def interrupt(question: str, answer_here: bool, session: WorkerSession, effects: Effects) -> str | Talked | Stop:
|
||||
"""Prints question for the human and returns their answer: where answer_here, the first line typed at loop-claude's terminal, stripped, or Talked once they typed in the worker's claude session, which TALK opens; else Talked once they typed in that session, which opens at once on the terminal. A Stop where loop-claude is off a terminal, or they type no answer, or the input ends."""
|
||||
say(f"\n{question}", effects)
|
||||
def interrupt(question: str, answer_here: bool, session: WorkerSession, window: tmux.Window, effects: Effects) -> str | Talked | Stop:
|
||||
"""Prints question for the human, in window, and returns their answer. While it waits, the window's name ends in tmux.WAITS, and the bell it rings shows in tmux's status bar. The answer: where answer_here, the first line typed at loop-claude's terminal, stripped, or Talked once they typed in the worker's claude session, which TALK opens; else Talked once they typed in that session, which opens at once on the terminal. A Stop where loop-claude is off a terminal, or they type no answer, or the input ends."""
|
||||
# The bell ends the question's line, so it rings once the question can be read.
|
||||
say(f"\n{question}{tmux.BELL}", effects)
|
||||
on_terminal = effects.on_terminal()
|
||||
if on_terminal:
|
||||
# Keys typed while the worker ran wait on the terminal, and would answer a question no one has read, here or in claude's session, which reads them too. Of a pasted answer, the first line answers; the rest wait, and the next question drops them. A longer answer goes through TALK.
|
||||
effects.discard_typed()
|
||||
tmux.mark(window, True, effects.tmux)
|
||||
# After the discard, so an answer typed while the DM sends counts; before the terminal check, so a loop that cannot ask still tells the human what it would have asked.
|
||||
tell(f"loop-claude in {session.root} asks:\n\n{question}", effects)
|
||||
if stop := needs_terminal(ANSWER_QUESTION, on_terminal):
|
||||
return stop
|
||||
tell(f"loop-claude in {session.root} asks, in the tmux window {window.target}:\n\n{question}", effects)
|
||||
answer = needs_terminal(ANSWER_QUESTION, on_terminal) or answered(answer_here, session, effects)
|
||||
# A loop that stops unanswered leaves the mark on its window.
|
||||
if not isinstance(answer, Stop):
|
||||
tmux.mark(window, False, effects.tmux)
|
||||
return answer
|
||||
|
||||
|
||||
def answered(answer_here: bool, session: WorkerSession, effects: Effects) -> str | Talked | Stop:
|
||||
"""The human's answer, as interrupt returns it."""
|
||||
answer = typed_answer(effects) if answer_here else TALK
|
||||
if answer != TALK:
|
||||
return answer
|
||||
|
||||
@@ -53,6 +53,11 @@ def preflight_facts(printed: str) -> str:
|
||||
return f"loop-claude ran `~/.claude/bin/chunk-preflight` at the checkout root just before this run. Take what it printed as found rather than finding it again:\n\n{printed}"
|
||||
|
||||
|
||||
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."
|
||||
|
||||
|
||||
def preflight_failed(reason: str) -> str:
|
||||
"""Has the worker find the facts chunk-preflight would have, its worktree among them."""
|
||||
return f"loop-claude could not run `~/.claude/bin/chunk-preflight`, so find the chunk's facts yourself. Why it could not run: {reason}"
|
||||
|
||||
@@ -24,6 +24,7 @@ from loop_claude.cycle.retry import retried
|
||||
from model_routing.route import Route
|
||||
from loop_claude.cycle import spend
|
||||
from loop_claude.stop import Stop
|
||||
from loop_claude.tmux import Window
|
||||
from model_routing import worker_rungs
|
||||
|
||||
|
||||
@@ -54,6 +55,8 @@ class Cycle:
|
||||
todo: Plan | Failure
|
||||
# Empty when the previous cycle's verdict was not Unfinished.
|
||||
unfinished_evidence: str
|
||||
# The tmux window the loop runs in, which an interrupt marks.
|
||||
window: Window
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
@@ -198,7 +201,7 @@ def keep_rejection(cycle: Cycle, transcript_path: str, rejected: Rejected) -> St
|
||||
def ask(cycle: Cycle, transcript_path: str, ruling: Interrupt | QuotedAnswer) -> HumanTyped | HumanTalked | Stop:
|
||||
"""The human's answer to a ruling that rule archived as it ruled; the human's answer then grows the transcript."""
|
||||
# Only the human may cut a release, so a release ready to cut opens claude's session at once.
|
||||
answer = interrupt(question_for(ruling), not (isinstance(ruling, Interrupt) and ruling.release_ready), worker_session(cycle, transcript_path), cycle.effects)
|
||||
answer = interrupt(question_for(ruling), not (isinstance(ruling, Interrupt) and ruling.release_ready), worker_session(cycle, transcript_path), cycle.window, cycle.effects)
|
||||
match answer:
|
||||
case Stop():
|
||||
return answer
|
||||
|
||||
@@ -1,46 +0,0 @@
|
||||
"""The slot a loop holds in its project, so that loops of one project, each on its own chunk, run side by side, each in a session named after its slot."""
|
||||
import dataclasses
|
||||
import os
|
||||
import pathlib
|
||||
|
||||
from failure import Failure
|
||||
from machine_load.slots import first_free_slot
|
||||
from loop_claude.loop.reload import LoopRun
|
||||
from loop_state.paths import Paths
|
||||
from transcript_archive.project_key import project_key
|
||||
from claude_code.session import Session, session_named, session_open
|
||||
|
||||
# Under the home folder, a folder per project key holds a file per slot, which a running loop keeps locked with flock.
|
||||
SLOTS = ".local/state/loop-claude"
|
||||
# A bound no project reaches. Once todo.md item 375 lands, the project's config sets how many loops run at once.
|
||||
MOST = 64
|
||||
|
||||
|
||||
def held_slot(home: pathlib.Path, key: str, claude_code_transcripts: pathlib.Path) -> int | Failure:
|
||||
"""The slot this loop takes, or why it could take none: the lowest free slot whose session is open, so that a rerun resumes a chunk left open, or else the lowest free slot. The loop holds it until it exits; a reload's exec keeps the lock."""
|
||||
folder = home / SLOTS / key
|
||||
order = sorted(range(MOST), key=lambda slot: not session_open(session_named(session_name(key, slot), claude_code_transcripts)))
|
||||
try:
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
taken = first_free_slot(folder, order)
|
||||
except OSError as failure:
|
||||
return Failure(f"cannot take a slot in {folder}: {failure.strerror}")
|
||||
if taken is None:
|
||||
return Failure(f"{MOST} loops of this project are running already; `fuser {folder}/slot-*` names them")
|
||||
slot, fd = taken
|
||||
os.set_inheritable(fd, True)
|
||||
return slot
|
||||
|
||||
|
||||
def session_name(key: str, slot: int) -> str:
|
||||
""""A " is the human's cue in the session picker that the session is the loop's. Slot 0 keeps the name every loop had before slots, so a chunk left open before slots resumes in it."""
|
||||
return f"A {key} loop-claude" if slot == 0 else f"A {key} loop-claude {slot + 1}"
|
||||
|
||||
|
||||
def slotted(loop_run: LoopRun, paths: Paths) -> tuple[LoopRun, Session] | Failure:
|
||||
"""loop_run holding its slot, and the worker's session, named after the slot. A reloaded script keeps the slot it is handed."""
|
||||
key = project_key(loop_run.root, paths.home)
|
||||
slot = held_slot(paths.home, key, paths.claude_code_transcripts) if loop_run.slot is None else loop_run.slot
|
||||
if isinstance(slot, Failure):
|
||||
return slot
|
||||
return dataclasses.replace(loop_run, slot=slot), session_named(session_name(key, slot), paths.claude_code_transcripts)
|
||||
@@ -7,6 +7,8 @@ from release_plan.release_standing import DefaultPlan, project_plan, UNSEEN_RELE
|
||||
from loop_effects.effects import Effects, say
|
||||
from failure import Failure
|
||||
from loop_claude.routing import first_route, kept, routed_item
|
||||
from loop_claude.loop.chunk_windows import held_beside, item_of
|
||||
from chunk_preflight.main import ITEM
|
||||
from plan_store.stores import held_at, Plan, store as plan_store
|
||||
from release_plan.todo_table import Item
|
||||
from model_routing.ladder import Ladder, Rung
|
||||
@@ -61,15 +63,17 @@ def archived_route(archive_folder: pathlib.Path, loop: Loop) -> Route | None:
|
||||
def chunk_start(loop: Loop) -> tuple[str, typing.Callable[[], Item | None]]:
|
||||
"""The facts for a fresh worker's prompt, empty where the session is open, and the reader of the item that routes the chunk. The reader reads the default branch as last fetched: for a fresh chunk, by the preflight that runs first; for an open session, which runs none, by whatever fetched last."""
|
||||
facts = "" if session_open(loop.session) else chunk_facts(loop)
|
||||
return facts, lambda: plan_item(fetched_plan(loop), loop.effects)
|
||||
return facts, lambda: plan_item(fetched_plan(loop), item_of(loop.window.name), loop.effects)
|
||||
|
||||
|
||||
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."""
|
||||
done = loop.effects.python([str(loop.launcher.with_name("chunk-preflight")), "--worktree"], loop.root)
|
||||
"""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."""
|
||||
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}")
|
||||
return 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 "")
|
||||
|
||||
|
||||
def fetched_plan(loop: Loop) -> DefaultPlan | Failure:
|
||||
@@ -83,13 +87,13 @@ def fetched_plan(loop: Loop) -> DefaultPlan | Failure:
|
||||
return ref if isinstance(ref, Failure) else project_plan(config, ref, loop.root, loop.effects.git)
|
||||
|
||||
|
||||
def plan_item(plan: DefaultPlan | Failure, effects: Effects) -> Item | None:
|
||||
"""The item that routes a chunk, release_standing.chunk_item's pick from the default branch; None without one, so the chunk runs on the project's rung."""
|
||||
def plan_item(plan: DefaultPlan | Failure, window_item: int | None, effects: Effects) -> Item | None:
|
||||
"""The item that routes a chunk: the one its window is named for, or else release_standing.chunk_item's pick from the default branch; None without one, so the chunk runs on the project's rung."""
|
||||
# It prints the reason itself, through effects, like the other loop-claude functions that print. todo.md item 51 moves them all to one injected effect, so changing this one alone would be undone.
|
||||
if isinstance(plan, Failure):
|
||||
item: Item | Failure | None = plan
|
||||
else:
|
||||
item = routed_item(plan.todo, plan.cut)
|
||||
item = routed_item(plan.todo, plan.cut, window_item)
|
||||
if isinstance(item, Failure):
|
||||
say(f"routing on the project's rung: {item.reason}", effects)
|
||||
return None
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
"""The chunks of one project that run at once, each in its own tmux window: which may start now, and how each starts (docs/decisions.md → `loop-claude: each chunk runs in its own tmux window`)."""
|
||||
import contextlib
|
||||
import fcntl
|
||||
import pathlib
|
||||
import re
|
||||
import typing
|
||||
|
||||
from chunk_preflight.choices import planned
|
||||
from chunk_preflight.gathered import NoItem, Plan
|
||||
from claude_code.session import Session, session_named, transcript_file
|
||||
from claude_code.transcript import read_transcript
|
||||
from failure import Failure
|
||||
from git_cli.git_repo import default_ref
|
||||
from loop_claude import tmux
|
||||
from loop_claude.cycle import chunk_items
|
||||
from loop_claude.loop.reload import LoopRun
|
||||
from loop_effects.effects import Effects, say
|
||||
from loop_state.paths import Paths
|
||||
from project_config.main import located
|
||||
from release_plan.release_standing import project_plan
|
||||
from touch_predictions.beside import Beside, chunks_beside
|
||||
from transcript_archive.project_key import project_key
|
||||
|
||||
# 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.
|
||||
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.
|
||||
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.
|
||||
HANDED = "LOOP_CLAUDE_"
|
||||
|
||||
|
||||
def window_name(item_id: int) -> str:
|
||||
return f"item-{item_id}"
|
||||
|
||||
|
||||
def item_of(chunk: str) -> int | None:
|
||||
"""The ID of the plan item a chunk starts from; None for NO_ITEM."""
|
||||
named = re.fullmatch(r"item-([0-9]+)", chunk, re.ASCII)
|
||||
return int(named[1]) if named else None
|
||||
|
||||
|
||||
def chunk_session(key: str, chunk: str, claude_code_transcripts: pathlib.Path) -> Session:
|
||||
"""The worker's session for a chunk. A rerun finds a chunk left open by this name. "A " is the human's cue in the session picker that the session is the loop's."""
|
||||
return session_named(f"A {key} loop-claude {chunk}", claude_code_transcripts)
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def starting(home: pathlib.Path, key: str) -> typing.Iterator[None]:
|
||||
"""Holds the project's LOCK. Raises OSError where the file cannot be opened or locked."""
|
||||
folder = home / STATE / key
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
with open(folder / LOCK, "a") as lock:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX)
|
||||
yield
|
||||
|
||||
|
||||
def held_items(chunks: typing.Iterable[str], key: str, claude_code_transcripts: pathlib.Path) -> set[int]:
|
||||
"""The plan items these chunks hold: the one each started from, and those its worker names on its latest `Chunk items:` line so far. A chunk whose transcript cannot be read holds the item it started from."""
|
||||
held = set()
|
||||
for chunk in chunks:
|
||||
held.update(filter(None, [item_of(chunk)]))
|
||||
transcript = transcript_file(chunk_session(key, chunk, claude_code_transcripts))
|
||||
entries = read_transcript(transcript) if transcript else []
|
||||
held.update([] if isinstance(entries, Failure) else chunk_items.named(entries))
|
||||
return held
|
||||
|
||||
|
||||
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."""
|
||||
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)]
|
||||
|
||||
|
||||
def next_plan(root: str, home: pathlib.Path, effects: Effects) -> Plan | NoItem | Failure:
|
||||
"""The plan on the default branch, fetched now where origin answers, with its next item, as chunk-preflight reads it."""
|
||||
config = located(root, home)
|
||||
if isinstance(config, Failure):
|
||||
return config
|
||||
# A chunk that just merged left the plan on origin. A fetch that fails leaves the plan as last fetched, which chunk-preflight then reads too.
|
||||
effects.git("fetch", "--quiet", "origin", cwd=root, timeout=FETCH_TIMEOUT)
|
||||
ref = default_ref(root, FETCH_TIMEOUT, run=effects.git)
|
||||
if isinstance(ref, Failure):
|
||||
return ref
|
||||
held = project_plan(config, ref, root, effects.git)
|
||||
return planned(held.todo, held.cut, ref, config.branch, None if config.tracked("plan") else config.plan_label)
|
||||
|
||||
|
||||
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."""
|
||||
config = located(loop_run.root, paths.home)
|
||||
if isinstance(config, Failure):
|
||||
return config
|
||||
key = project_key(loop_run.root, paths.home)
|
||||
session = tmux.session_name(key)
|
||||
handed = {name: value for name, value in env.items() if name.startswith(HANDED)}
|
||||
try:
|
||||
with starting(paths.home, key):
|
||||
windows = tmux.listed(session, effects.tmux)
|
||||
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:
|
||||
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)
|
||||
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)
|
||||
windows = [window for window in windows if window not in stale]
|
||||
command = [str(launcher), CHUNK_FLAG, chunk, loop_run.task]
|
||||
if failed := tmux.start_window(tmux.Window(session, chunk, ""), loop_run.root, handed, command, not windows, effects.tmux):
|
||||
return failed
|
||||
windows.append(tmux.Listed(chunk, "", False))
|
||||
return chunks
|
||||
except OSError as failure:
|
||||
return Failure(f"cannot lock {paths.home / STATE / key / LOCK}: {failure.strerror}")
|
||||
|
||||
|
||||
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."""
|
||||
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]
|
||||
return sorted(held_items(others, key, paths.claude_code_transcripts))
|
||||
@@ -20,7 +20,9 @@ from transcript_archive.project_key import project_key
|
||||
from model_routing.ladder_file import project_ladder_file, read_ladder, SHIPPED
|
||||
from loop_claude.project.premises import read_premises
|
||||
from loop_claude.project.records import read_records
|
||||
from loop_claude.loop.chunk_slot import slotted
|
||||
from loop_claude.loop.chunk_windows import CHUNK_FLAG, chunk_session, start_chunks
|
||||
from loop_claude import tmux
|
||||
from loop_claude.verdicts import Finished
|
||||
from loop_claude.stop import Stop
|
||||
from loop_claude.direct_message import tell
|
||||
|
||||
@@ -35,8 +37,8 @@ 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 but the human's own Ctrl-C and 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.
|
||||
if stop.code != 130 and stop.reason != HELP:
|
||||
# Every stop with a reason, but the human's own Ctrl-C and 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. One that started the project's windows, or whose chunk finished and handed on to the next, stops without a reason: the project's chunks go on.
|
||||
if stop.code != 130 and stop.reason not in ("", HELP):
|
||||
tell(f"loop-claude in {cwd} stopped: {stop.reason}", effects)
|
||||
return stop.code
|
||||
|
||||
@@ -45,12 +47,18 @@ 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.
|
||||
if reason := tmux.unusable(effects.tmux):
|
||||
return Stop(1, reason)
|
||||
if loop_run.chunk is None:
|
||||
return windows_opened(loop_run, env, paths, launcher, effects)
|
||||
pane = env.get("TMUX_PANE")
|
||||
if not pane:
|
||||
return Stop(1, f"{CHUNK_FLAG} is how loop-claude starts itself in a tmux window; run loop-claude <task>")
|
||||
baseline = fingerprint(launcher)
|
||||
held = slotted(loop_run, paths)
|
||||
if isinstance(held, Failure):
|
||||
return Stop(1, held.reason)
|
||||
loop_run, session = held
|
||||
loop = Loop(root=loop_run.root, session=session, paths=paths, env=env, launcher=launcher, effects=effects)
|
||||
key = project_key(loop_run.root, paths.home)
|
||||
window = tmux.Window(tmux.session_name(key), loop_run.chunk, pane)
|
||||
loop = Loop(root=loop_run.root, session=chunk_session(key, loop_run.chunk, paths.claude_code_transcripts), window=window, paths=paths, env=env, launcher=launcher, effects=effects)
|
||||
while True:
|
||||
if stop := exec_if_edited(loop, baseline, loop_run):
|
||||
return stop
|
||||
@@ -68,6 +76,31 @@ def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launc
|
||||
# Off the ladder the worker runs on the project's model itself, which its route names.
|
||||
if stop := check_routing(archive_root(paths.home, env), cycle.project or cycle.route.rung, loop):
|
||||
return stop
|
||||
if isinstance(concluded.verdict, Finished):
|
||||
return handed_on(loop_run, loop)
|
||||
|
||||
|
||||
def windows_opened(loop_run: LoopRun, env: typing.Mapping[str, str], paths: Paths, launcher: pathlib.Path, effects: Effects) -> Stop:
|
||||
"""What the loop-claude the human runs does: starts each chunk that may start now in a window of the project's tmux session, then puts that session on the terminal until the human detaches."""
|
||||
started = start_chunks(loop_run, False, paths, env, launcher, effects)
|
||||
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)
|
||||
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, "")
|
||||
|
||||
|
||||
def handed_on(loop_run: LoopRun, loop: Loop) -> Stop:
|
||||
"""The stop of a loop whose chunk finished, once it has started each chunk that may start now. Its window closes as it exits."""
|
||||
started = start_chunks(loop_run, True, loop.paths, loop.env, loop.launcher, loop.effects)
|
||||
if isinstance(started, Failure):
|
||||
return Stop(1, f"the chunk finished, but the next could not start: {started.reason}")
|
||||
say(f"the chunk finished; started {', '.join(started) or 'no other, since the chunks running fill what may run now'}", loop.effects, stdout=True)
|
||||
return Stop(0, "")
|
||||
|
||||
|
||||
def next_cycle(loop_run: LoopRun, loop: Loop) -> Cycle | Stop:
|
||||
@@ -96,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, 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, window=loop.window, todo=todo, unfinished_evidence=loop_run.unfinished_evidence)
|
||||
|
||||
|
||||
def own_ladder(file: pathlib.Path, model: str, unrouted: bool) -> str:
|
||||
@@ -107,11 +140,12 @@ def own_ladder(file: pathlib.Path, model: str, unrouted: bool) -> str:
|
||||
|
||||
def loop_run_from(argv: list[str], cwd: pathlib.Path, effects: Effects) -> LoopRun | Stop:
|
||||
if argv[:1] != [RELOAD_FLAG]:
|
||||
task = " ".join(argv)
|
||||
chunk, words = (argv[1], argv[2:]) if len(argv) > 2 and argv[0] == CHUNK_FLAG else (None, argv)
|
||||
task = " ".join(words)
|
||||
if task in ("", "-h", "--help"):
|
||||
return Stop(0 if task else 1, HELP)
|
||||
root = checkout_root(cwd, effects)
|
||||
return root if isinstance(root, Stop) else LoopRun(0, root, task, "")
|
||||
return root if isinstance(root, Stop) else LoopRun(0, root, task, "", chunk=chunk)
|
||||
loop_run = decode_handed(argv[1]) if len(argv) == 2 else None
|
||||
if not (loop_run and loop_run.root and loop_run.task):
|
||||
return Stop(1, f"the edited loop-claude cannot read the state the running one handed it, likely because the edit changed that handover; rerun loop-claude <task>. Handed: {' '.join(argv[1:])}")
|
||||
|
||||
@@ -25,8 +25,8 @@ class LoopRun:
|
||||
route: Route | None = None
|
||||
# How many unfinished verdicts the chunk has had running; a finished chunk and a rerun each set it to 0. It stays apart from route and unfinished_evidence, though all three change together at each verdict: merging or renaming a field stops a running loop at its next reload.
|
||||
unfinished_run: int = 0
|
||||
# The project's slot this loop holds (chunk_slot.py); None until it takes one. A loop started before slots reloads with None, and so takes a slot then.
|
||||
slot: int | None = None
|
||||
# The chunk this loop runs in its tmux window, as chunk_windows names it: `item-372`, or `no-item`. None for the loop-claude the human started, which starts the windows; a loop started before chunks ran in windows reloads with None too, and so moves its chunk into one.
|
||||
chunk: str | None = None
|
||||
|
||||
|
||||
class Unreadable(Exception):
|
||||
@@ -40,8 +40,10 @@ def decode_handed(handed: str) -> LoopRun | None:
|
||||
except ValueError:
|
||||
return None
|
||||
# A loop started before 0.11.0 hands the items loop-inbox listed; dropping them keeps it running across its reload.
|
||||
# One started before chunks ran in tmux windows hands the slot it held.
|
||||
if isinstance(fields, dict):
|
||||
fields.pop("items_taken_in", None)
|
||||
fields.pop("slot", None)
|
||||
try:
|
||||
return LoopRun(**decoded_fields(fields, LOOP_RUN_FIELDS, "cycle_number", "root", "task", "unfinished_evidence"))
|
||||
except Unreadable:
|
||||
@@ -77,7 +79,7 @@ def decoded_route(value: object) -> Route | None:
|
||||
|
||||
|
||||
# One decoder per field of LoopRun, which a test holds to the dataclass's fields: a field missing here stops a loop at the reload after it joined.
|
||||
LOOP_RUN_FIELDS = {"cycle_number": exactly(int), "root": exactly(str), "task": exactly(str), "unfinished_evidence": exactly(str), "route": decoded_route, "unfinished_run": exactly(int), "slot": lambda value: None if value is None else exactly(int)(value)}
|
||||
LOOP_RUN_FIELDS = {"cycle_number": exactly(int), "root": exactly(str), "task": exactly(str), "unfinished_evidence": exactly(str), "route": decoded_route, "unfinished_run": exactly(int), "chunk": lambda value: None if value is None else exactly(str)(value)}
|
||||
|
||||
|
||||
def fingerprint(launcher: pathlib.Path) -> str:
|
||||
|
||||
@@ -5,6 +5,7 @@ import typing
|
||||
from loop_effects.effects import Effects
|
||||
from loop_state.paths import Paths
|
||||
from claude_code.session import Session
|
||||
from loop_claude.tmux import Window
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
@@ -14,6 +15,8 @@ class Loop:
|
||||
root: str
|
||||
# The worker's session.
|
||||
session: Session
|
||||
# The tmux window the loop runs in.
|
||||
window: Window
|
||||
paths: Paths
|
||||
env: typing.Mapping[str, str]
|
||||
# The loop-claude script, whose edits reload the loop and beside which chunk-preflight lies.
|
||||
|
||||
@@ -26,7 +26,9 @@ remaining. The next chunk starts a fresh session. Cycles continue until an exit
|
||||
Words: ~/.claude/CLAUDE.md → "Vocabulary".
|
||||
|
||||
A question only the human can answer is an interrupt (bin/loop_claude/cycle/interrupt.py).
|
||||
loop-claude prints the question on its terminal, where the human answers it:
|
||||
loop-claude prints the question in the chunk's window and rings its bell. Until it is answered the
|
||||
window's name ends in " ?", as in "item-372 ?", which tmux's status bar shows. The human answers
|
||||
it there:
|
||||
- A line of text: the worker resumes headless with it. The judge reads it as the human's, so the
|
||||
chunk stays unfinished until the answer is recorded.
|
||||
- /talk: opens the worker's session with `claude --resume` on the terminal, to read the diff or
|
||||
@@ -34,20 +36,33 @@ loop-claude prints the question on its terminal, where the human answers it:
|
||||
- Enter alone: stops the loop.
|
||||
A release ready to cut opens that session on the terminal at once, since only the human may cut it.
|
||||
While claude is open, Ctrl-C reaches it alone, and the loop goes on.
|
||||
Where the project's config sets notifier, loop-claude also sends the human each question, each
|
||||
release ready to cut and each stop as a DM, as bin/notify sends it. Two stops are
|
||||
left out: Ctrl-C, and printing this help. A DM that fails is said on stderr, and the loop goes on.
|
||||
Where the project's config sets notifier, loop-claude also sends the human each question, naming
|
||||
its window as <session>:<window>, each release ready to cut and each stop as a DM, as bin/notify
|
||||
sends it. Four stops are left out: Ctrl-C, printing this help, the loop-claude that started the
|
||||
windows, and a loop whose chunk finished. A DM that fails is said on stderr, and the loop goes on.
|
||||
|
||||
As a chunk starts, before it is routed, loop-claude runs bin/chunk-preflight --worktree and quotes
|
||||
what it prints in the first prompt (prompts.preflight_facts in bin/loop_claude/cycle/prompts.py);
|
||||
chunk-preflight --help says what it finds and makes. A preflight that fails, or is still running
|
||||
chunk-preflight --help says what it finds and makes. For a window named for an item it adds
|
||||
--item <ID>. A preflight that fails, or is still running
|
||||
after 600 s and is stopped, leaves the worker to find the facts itself.
|
||||
|
||||
Loops of one project run side by side, each on one chunk at a time. Each holds a slot of the
|
||||
project, the file slot-<n> under ~/.local/state/loop-claude/<key>/, locked while the loop runs.
|
||||
<key> is the checkout's path relative to ~/code, or to / outside it. A loop takes the lowest free
|
||||
slot whose session is open, so a rerun resumes a chunk left open, or else the lowest free slot.
|
||||
slot-0's session is named "A <key> loop-claude", and slot-<n>'s "A <key> loop-claude <n+1>".
|
||||
Each chunk runs in its own window of one tmux session per project, named loop-<key>, such as
|
||||
loop-claude-config. <key> is the checkout's path relative to ~/code, or to / outside it, with a
|
||||
dash for each character tmux reads as a separator. loop-claude <task> starts the chunks that may
|
||||
start now, then attaches to the session, or switches to it inside tmux; detaching leaves the chunks
|
||||
running. Off a terminal it prints the command that attaches. Up to parallel-chunks chunks run at
|
||||
once, a whole number the project's config sets, 1 by default. The first starts from the plan's next
|
||||
item, and each other from an item whose `Touches:` prediction overlaps none before it
|
||||
(touch-predictions --help). A window is named for the item its chunk starts from, as item-372; a
|
||||
chunk without a plan item, such as planning a release or its release review, runs alone in the
|
||||
window no-item. Each window runs a loop-claude for that one chunk, started with --chunk <window>,
|
||||
which nobody types. As a chunk finishes, its loop starts each chunk that may start then and exits,
|
||||
which closes its window. The window of a loop that failed stays, with its last lines, until its
|
||||
chunk starts again. A chunk's session is named "A <key> loop-claude <window>", so a rerun resumes a
|
||||
chunk left open. A fresh worker is told the items the other running chunks hold, each chunk's own
|
||||
and those on its latest `Chunk items:` line, and leaves them out. loop-claude needs tmux 3.2 or
|
||||
later, and checks it before it starts anything.
|
||||
The session is deleted when its chunk finishes. At every
|
||||
interrupt, and as every cycle ends, Ctrl-C and a failure included, the session's transcript is
|
||||
copied into a folder per chunk under $LOOP_CLAUDE_TRANSCRIPTS/<key> (default root
|
||||
@@ -116,7 +131,10 @@ loop-claude --help succeeds: the loop reloads into the edited script.
|
||||
Exit 1, saying why, when:
|
||||
- no task is given
|
||||
- git cannot start or finds no checkout
|
||||
- its slot in the project cannot be taken
|
||||
- tmux is missing or older than 3.2
|
||||
- --chunk is given outside a tmux window
|
||||
- a chunk's window cannot be started, as when the plan or the project's config cannot be read
|
||||
- the tmux session cannot be put on the terminal
|
||||
- the goals file, or AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/*.md or
|
||||
the project's review standards where they exist, cannot be read or is not UTF-8
|
||||
- no config names the checkout, its config cannot be read, or the goals file holds no premises
|
||||
|
||||
@@ -45,14 +45,17 @@ ESCALATION_CAP = 2
|
||||
JUDGE_REPLAYED = ("claude-opus-5-5",)
|
||||
|
||||
|
||||
def routed_item(plan: Plan | Failure, cut: LastCut) -> Item | Failure | None:
|
||||
"""The item release_standing.chunk_item picks from plan, weighed against the last cut; None when there is none, or it lacks L, E or I."""
|
||||
def routed_item(plan: Plan | Failure, cut: LastCut, item_id: int | None = None) -> Item | Failure | None:
|
||||
"""The plan's item item_id, or without one the item release_standing.chunk_item picks from plan, weighed against the last cut; None when there is none, or it lacks L, E or I."""
|
||||
if isinstance(plan, NoItemsTable):
|
||||
return None
|
||||
if isinstance(plan, Failure):
|
||||
return plan
|
||||
pick = chunk_item(plan.items, cut)
|
||||
takes = pick.item if isinstance(pick, Next) else None
|
||||
if item_id is None:
|
||||
pick = chunk_item(plan.items, cut)
|
||||
takes = pick.item if isinstance(pick, Next) else None
|
||||
else:
|
||||
takes = next((item for item in plan.items if item.id == item_id), None)
|
||||
return takes if takes and takes.likelihood and takes.escape_and_impact else None
|
||||
|
||||
|
||||
|
||||
@@ -31,6 +31,24 @@ OFF_LADDER_ROUTE = {"rung": {"model": "worker-model", "effort": ""}, "item": 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.
|
||||
FAKE_TMUX = """#!{python}
|
||||
import json, os, pathlib, sys
|
||||
|
||||
argv = sys.argv[1:]
|
||||
with open(os.environ["FAKE_TMUX_LOG"], "a") as log:
|
||||
log.write(json.dumps(argv) + "\\n")
|
||||
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] == "list-windows":
|
||||
if not windows.exists():
|
||||
sys.exit("no server running")
|
||||
print(windows.read_text(), end="")
|
||||
else:
|
||||
print("@7")
|
||||
"""
|
||||
|
||||
FAKE_CLAUDE = """#!{python}
|
||||
import json, os, pathlib, signal, sys, time
|
||||
|
||||
@@ -166,9 +184,11 @@ class Run:
|
||||
code: int
|
||||
sleeps: list
|
||||
starts: list
|
||||
# stderr and stdout are without the local time that opens each message loop-claude prints; raw_stderr and raw_stdout keep it.
|
||||
# stderr and stdout are without the local time that opens each message loop-claude prints, and stderr without the bell an interrupt rings; raw_stderr and raw_stdout keep them.
|
||||
stderr: str
|
||||
stdout: str
|
||||
# Each tmux command run, as its arguments.
|
||||
tmux: list
|
||||
raw_stderr: str
|
||||
raw_stdout: str
|
||||
|
||||
@@ -195,6 +215,8 @@ class Checkout:
|
||||
fake.mkdir()
|
||||
(fake / "claude").write_text(FAKE_CLAUDE.format(python=sys.executable))
|
||||
(fake / "claude").chmod(0o755)
|
||||
(fake / "tmux").write_text(FAKE_TMUX.format(python=sys.executable))
|
||||
(fake / "tmux").chmod(0o755)
|
||||
(fake / "git").symlink_to(shutil.which("git"))
|
||||
site = self.temp / "site"
|
||||
site.mkdir()
|
||||
@@ -203,6 +225,10 @@ class Checkout:
|
||||
self.env.update({
|
||||
"FAKE_CLAUDE_LOG": str(self.temp / "calls.jsonl"),
|
||||
"FAKE_MEMINFO": str(self.temp / "meminfo"),
|
||||
"FAKE_TMUX_LOG": str(self.temp / "tmux.jsonl"),
|
||||
"FAKE_TMUX_WINDOWS": str(self.temp / "tmux-windows"),
|
||||
# The pane of the window the loop under test runs in.
|
||||
"TMUX_PANE": "%3",
|
||||
"FAKE_CLAUDE_SCENARIO": str(self.temp / "scenario.json"),
|
||||
"GIT_CONFIG_GLOBAL": os.devnull,
|
||||
"GIT_CONFIG_NOSYSTEM": "1",
|
||||
@@ -224,15 +250,20 @@ class Checkout:
|
||||
self.git("add", "todo.md")
|
||||
self.git("commit", "--quiet", "-m", "plan")
|
||||
|
||||
def run(self, steps, argv=(TASK,), cwd=None, terminal_input=None, stdout_on_terminal=True, before_typing=None, typed_early=""):
|
||||
for name in ("FAKE_CLAUDE_LOG", "LOOP_TEST_LOG"):
|
||||
def run(self, steps, argv=None, cwd=None, terminal_input=None, stdout_on_terminal=True, before_typing=None, typed_early="", chunk="no-item"):
|
||||
"""Runs loop-claude with argv, or without one as the loop of the window `chunk`, on TASK. Off a terminal, a window's loop whose chunk finished is run again while steps remain, as the window it starts for the next chunk would."""
|
||||
for name in ("FAKE_CLAUDE_LOG", "LOOP_TEST_LOG", "FAKE_TMUX_LOG"):
|
||||
pathlib.Path(self.env[name]).unlink(missing_ok=True)
|
||||
pathlib.Path(self.env["FAKE_CLAUDE_SCENARIO"]).write_text(json.dumps(steps))
|
||||
command = [sys.executable, str(self.script), *argv]
|
||||
command = [sys.executable, str(self.script), *(("--chunk", chunk, TASK) if argv is None else argv)]
|
||||
cwd = cwd or self.root
|
||||
if terminal_input is None:
|
||||
done = subprocess.run(command, capture_output=True, cwd=cwd, env=self.env, stdin=subprocess.DEVNULL, text=True, timeout=60)
|
||||
code, stdout, stderr = done.returncode, done.stdout, done.stderr
|
||||
code, stdout, stderr = 0, "", ""
|
||||
runs = 0
|
||||
while code == 0 and (runs == 0 or (argv is None and json.loads(pathlib.Path(self.env["FAKE_CLAUDE_SCENARIO"]).read_text()))):
|
||||
runs += 1
|
||||
done = subprocess.run(command, capture_output=True, cwd=cwd, env=self.env, stdin=subprocess.DEVNULL, text=True, timeout=60)
|
||||
code, stdout, stderr = done.returncode, stdout + done.stdout, stderr + done.stderr
|
||||
else:
|
||||
code, stdout, stderr = self.run_on_terminal(command, cwd, terminal_input, stdout_on_terminal, before_typing, typed_early)
|
||||
started = lines(pathlib.Path(self.env["LOOP_TEST_LOG"]))
|
||||
@@ -241,8 +272,9 @@ class Checkout:
|
||||
code=code,
|
||||
sleeps=[event["sleep"] for event in started if "sleep" in event],
|
||||
starts=[event["argv"] for event in started if "argv" in event],
|
||||
stderr=unstamped(stderr),
|
||||
stderr=unstamped(stderr).replace("\a", ""),
|
||||
stdout=unstamped(stdout),
|
||||
tmux=lines(pathlib.Path(self.env["FAKE_TMUX_LOG"])),
|
||||
raw_stderr=stderr,
|
||||
raw_stdout=stdout,
|
||||
)
|
||||
@@ -394,7 +426,7 @@ class Premises(unittest.TestCase):
|
||||
write_config(checkout.home, root)
|
||||
checkout.git("init", "--quiet", str(root))
|
||||
run = checkout.run([worker()], cwd=root)
|
||||
self.assertEqual(argument(run.calls[0], "--name"), f"A {str(root).lstrip('/')} loop-claude")
|
||||
self.assertEqual(argument(run.calls[0], "--name"), f"A {str(root).lstrip('/')} loop-claude no-item")
|
||||
|
||||
|
||||
class Cycles(unittest.TestCase):
|
||||
@@ -414,7 +446,7 @@ class Cycles(unittest.TestCase):
|
||||
self.assertEqual(run.roles(), ["worker", "judge", "worker", "judge", "worker", "judge"])
|
||||
workers = [call for call in run.calls if call["role"] == "worker"]
|
||||
session = argument(workers[0], "--session-id")
|
||||
self.assertEqual(argument(workers[0], "--name"), "A proj loop-claude")
|
||||
self.assertEqual(argument(workers[0], "--name"), "A proj loop-claude no-item")
|
||||
self.assertEqual(argument(workers[1], "--resume"), session)
|
||||
self.assertIsNone(argument(workers[1], "--session-id"))
|
||||
self.assertIsNone(argument(workers[1], "--name"))
|
||||
@@ -433,8 +465,10 @@ class Cycles(unittest.TestCase):
|
||||
self.assertIn("landed-it", run.calls[3]["stdin"])
|
||||
self.assertNotIn("landed-it", run.calls[5]["stdin"])
|
||||
self.assertEqual([path.name for path in checkout.transcripts()[0].parent.iterdir()], [checkout.transcripts()[0].name])
|
||||
self.assertIn("=== cycle 3, worker on worker-model ===", run.stdout)
|
||||
self.assertEqual(len(re.findall(rf"(?m)^{STAMP} === cycle 3, worker on worker-model ===$", run.raw_stdout)), 1)
|
||||
self.assertIn("=== cycle 2, worker on worker-model ===", run.stdout)
|
||||
self.assertEqual(len(re.findall(rf"(?m)^{STAMP} === cycle 2, worker on worker-model ===$", run.raw_stdout)), 1)
|
||||
# The finished chunk's loop started the next chunk's window and ended; the checkout has no default branch to read a plan from.
|
||||
self.assertIn("landed-it\nthe chunk finished; started no-item\n\n=== cycle 1, worker on worker-model ===\nnext chunk\n", run.stdout)
|
||||
copies = {verdict.removeprefix(f"Task: {TASK}\n\n"): copy for copy, verdict in checkout.archived().items()}
|
||||
self.assertEqual(sorted(copies), [f"<UTC> Stopped: Ctrl-C\n\nWorker: {OFF_LADDER}\n", f"<UTC> Verdict: finished\n\nEvidence:\n> landed-it\n\nConfig: <config>\nJudge: judge-model\nWorker: {OFF_LADDER}\n", f"<UTC> Verdict: unfinished\n\nEvidence:\n> started\n\nConfig: <config>\nJudge: judge-model\nWorker: {OFF_LADDER}\n"])
|
||||
self.assertIn('"text": "landed-it"', copies[f"<UTC> Verdict: finished\n\nEvidence:\n> landed-it\n\nConfig: <config>\nJudge: judge-model\nWorker: {OFF_LADDER}\n"])
|
||||
@@ -608,19 +642,15 @@ class Cycles(unittest.TestCase):
|
||||
self.assertIsNotNone(argument(run.calls[0], "--resume"))
|
||||
self.assertEqual((argument(run.calls[0], "--model"), argument(run.calls[0], "--effort")), ("claude-fable-5-2", "medium"))
|
||||
|
||||
def test_a_second_loop_in_the_project_runs_its_own_session_and_leaves_the_first_loops_open_chunk_alone(self):
|
||||
def test_a_second_window_of_the_project_runs_its_own_session_and_leaves_the_first_ones_open_chunk_alone(self):
|
||||
checkout = Checkout(self)
|
||||
first = checkout.run([worker(say="first chunk"), judge(evidence="first chunk")])
|
||||
session = argument(first.calls[0], "--session-id")
|
||||
transcript = checkout.transcripts()[0]
|
||||
kept, archived = transcript.read_bytes(), checkout.archived()
|
||||
slot = checkout.home / ".local" / "state" / "loop-claude" / "proj" / "slot-0"
|
||||
slot.parent.mkdir(parents=True, exist_ok=True)
|
||||
# The test holds the first loop's slot, as the first loop does while it runs.
|
||||
with open(slot, "a") as running:
|
||||
fcntl.flock(running, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
second = checkout.run([worker(say="second chunk"), judge(evidence="second chunk")])
|
||||
self.assertEqual(argument(second.calls[0], "--name"), "A proj loop-claude 2")
|
||||
self.assertEqual(argument(first.calls[0], "--name"), "A proj loop-claude no-item")
|
||||
second = checkout.run([worker(say="second chunk"), judge(evidence="second chunk")], chunk="item-2")
|
||||
self.assertEqual(argument(second.calls[0], "--name"), "A proj loop-claude item-2")
|
||||
self.assertNotIn(session, [argument(call, "--session-id") or argument(call, "--resume") for call in second.calls if call["role"] == "worker"])
|
||||
self.assertNotIn("first chunk", second.calls[1]["stdin"])
|
||||
self.assertEqual(transcript.read_bytes(), kept)
|
||||
@@ -771,6 +801,91 @@ class Cycles(unittest.TestCase):
|
||||
self.assertEqual((run.code, run.roles()), (130, ["worker", "judge"] * 12))
|
||||
|
||||
|
||||
# Items 4 and 9 with predictions that do not overlap, so both may run at once, and item 12, which overlaps item 4.
|
||||
BESIDE = TAKEN_IN_AT_L_4 + "| 12 | 0.1.0 | | **Do most.** | 2 | 1 | 2 | 3 | 2 | 1 by 9 | 10 |\n\n## Details\n\n### 4. Do it.\n\nTouches:\n\n- `a.py`\n\n### 9. Do more.\n\nTouches:\n\n- `b.py`\n\n### 12. Do most.\n\nTouches:\n\n- `a.py`\n"
|
||||
|
||||
|
||||
class Windows(unittest.TestCase):
|
||||
def checkout(self, parallel=None):
|
||||
"""A checkout whose plan is BESIDE, with parallel-chunks set where given."""
|
||||
checkout = Checkout(self)
|
||||
checkout.commit_plan(BESIDE)
|
||||
if parallel:
|
||||
config = checkout.home / ".claude-projects" / "proj" / "config.toml"
|
||||
config.write_text(f"parallel-chunks = {parallel}\n" + config.read_text())
|
||||
return checkout
|
||||
|
||||
def started(self, run):
|
||||
"""The window each new-session or new-window made, with the command it runs."""
|
||||
return [(command[0], command[command.index("-n") + 1], command[command.index("--") + 1:]) for command in run.tmux if command[0] in ("new-session", "new-window")]
|
||||
|
||||
def test_starts_one_chunk_in_a_window_of_the_projects_session_by_default(self):
|
||||
checkout = self.checkout()
|
||||
run = checkout.run([], argv=["ship", "it"])
|
||||
self.assertEqual((run.code, run.calls, run.stderr), (0, [], ""))
|
||||
self.assertEqual(run.tmux, [
|
||||
["-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", "-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")
|
||||
|
||||
def test_starts_up_to_the_configured_number_of_chunks_whose_predictions_do_not_overlap(self):
|
||||
run = self.checkout(parallel=3).run([], argv=[TASK])
|
||||
self.assertEqual([(made, window) for made, window, _ in self.started(run)], [("new-session", "item-4"), ("new-window", "item-9")])
|
||||
self.assertIn("started item-4, item-9 in the tmux session loop-proj\n", run.stdout)
|
||||
|
||||
def test_starts_only_what_the_running_windows_leave_room_for(self):
|
||||
checkout = self.checkout(parallel=2)
|
||||
# Item 4's chunk runs and waits for the human; item 9's loop failed, so its window stays, dead.
|
||||
pathlib.Path(checkout.env["FAKE_TMUX_WINDOWS"]).write_text("item-4 ?\t0\t@1\nitem-9\t1\t@2\n")
|
||||
run = checkout.run([], argv=[TASK])
|
||||
self.assertEqual([command for command in run.tmux if command[0] == "kill-window"], [["kill-window", "-t", "@2"]])
|
||||
self.assertEqual([(made, window) for made, window, _ in self.started(run)], [("new-window", "item-9")])
|
||||
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)
|
||||
|
||||
def test_a_finished_chunk_starts_the_next_one_its_window_leaves_room_for(self):
|
||||
checkout = self.checkout(parallel=2)
|
||||
pathlib.Path(checkout.env["FAKE_TMUX_WINDOWS"]).write_text("item-4\t0\t@1\nitem-9\t0\t@2\n")
|
||||
run = checkout.run([worker(say="merged"), judge(finished=True, evidence="merged")], chunk="item-9")
|
||||
self.assertEqual((run.code, run.roles()), (0, ["worker", "judge"]))
|
||||
# Item 9 is still in the checkout's plan, since nothing merged here; the window that leaves holds it no longer, and item 4's chunk still runs.
|
||||
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_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"
|
||||
pathlib.Path(checkout.env["FAKE_TMUX_WINDOWS"]).write_text("item-4\t0\t@1\nitem-9\t0\t@2\n")
|
||||
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("routed by item 9's L of 4", prompt)
|
||||
|
||||
def test_refuses_to_start_on_a_tmux_older_than_needed_or_without_one(self):
|
||||
checkout = self.checkout()
|
||||
checkout.env["FAKE_TMUX_VERSION"] = "tmux 3.1c"
|
||||
run = checkout.run([], argv=[TASK])
|
||||
self.assertEqual((run.code, run.stderr, run.tmux), (1, "loop-claude runs each chunk in a tmux window, and needs tmux 3.2 or later; it found tmux 3.1c\n", [["-V"]]))
|
||||
(pathlib.Path(checkout.env["PATH"]) / "tmux").unlink()
|
||||
run = checkout.run([], argv=[TASK])
|
||||
self.assertEqual((run.code, run.stderr), (1, "loop-claude runs each chunk in a tmux window, and needs tmux 3.2 or later; it found no tmux\n"))
|
||||
|
||||
def test_marks_the_window_while_an_interrupt_waits_and_rings_its_bell(self):
|
||||
checkout = self.checkout()
|
||||
run = checkout.run([worker(say="A or B?"), judge(interrupt=True, question="A or B?")], chunk="item-4")
|
||||
self.assertEqual(run.code, 2)
|
||||
self.assertEqual([command for command in run.tmux if command[0] == "rename-window"], [["rename-window", "-t", "%3", "item-4 ?"]])
|
||||
self.assertEqual(run.raw_stderr.count("\a"), 1)
|
||||
run = checkout.run([worker(say="A or B?"), judge(interrupt=True, question="A or B?"), worker()], chunk="item-4", terminal_input="B\n", before_typing=ANSWERING)
|
||||
self.assertEqual([command for command in run.tmux if command[0] == "rename-window"], [["rename-window", "-t", "%3", "item-4 ?"], ["rename-window", "-t", "%3", "item-4"]])
|
||||
|
||||
|
||||
class Interrupt(unittest.TestCase):
|
||||
def test_exits_2_off_a_terminal_and_resumes_on_the_next_run(self):
|
||||
checkout = Checkout(self)
|
||||
@@ -971,17 +1086,28 @@ class Reload(unittest.TestCase):
|
||||
self.assertEqual(run.roles(), ["worker", "judge"] * 5)
|
||||
self.assertIn("keeping the running script", run.stderr)
|
||||
reloads = [json.loads(argv[1]) for argv in run.starts if argv[:1] == ["--reloaded"]]
|
||||
self.assertEqual(reloads, [{"cycle_number": cycle, "root": str(checkout.root), "task": TASK, "unfinished_evidence": "working", "route": OFF_LADDER_ROUTE, "unfinished_run": cycle, "slot": 0} for cycle in (2, 3, 4)])
|
||||
self.assertEqual(reloads, [{"cycle_number": cycle, "root": str(checkout.root), "task": TASK, "unfinished_evidence": "working", "route": OFF_LADDER_ROUTE, "unfinished_run": cycle, "chunk": "no-item"} for cycle in (2, 3, 4)])
|
||||
self.assertIn("=== cycle 5,", run.stdout)
|
||||
|
||||
outside = checkout.temp / "outside"
|
||||
outside.mkdir()
|
||||
state = {"cycle_number": 3, "root": str(checkout.root), "task": TASK, "unfinished_evidence": "", "route": None}
|
||||
state = {"cycle_number": 3, "root": str(checkout.root), "task": TASK, "unfinished_evidence": "", "route": None, "chunk": "no-item"}
|
||||
run = checkout.run([worker()], argv=["--reloaded", json.dumps(state)], cwd=outside)
|
||||
self.assertEqual((run.code, run.roles()), (130, ["worker", "judge"]))
|
||||
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):
|
||||
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.assertIn("started no-item in the tmux session loop-proj\n", run.stdout)
|
||||
|
||||
def test_stops_where_a_reload_hands_no_state(self):
|
||||
checkout = Checkout(self)
|
||||
|
||||
run = checkout.run([], argv=["--reloaded", "{}"])
|
||||
self.assertEqual((run.code, run.calls), (1, []))
|
||||
self.assertIn("rerun loop-claude <task>", run.stderr)
|
||||
|
||||
@@ -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_),
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
"""The tmux commands loop-claude runs: each chunk's loop runs in its own window of one tmux session named for the project (docs/decisions.md → `loop-claude: each chunk runs in its own tmux window`)."""
|
||||
import dataclasses
|
||||
import re
|
||||
import subprocess
|
||||
import typing
|
||||
|
||||
from failure import Failure
|
||||
|
||||
# Runs tmux with these arguments and returns what it printed; exit 127 where tmux cannot start.
|
||||
Tmux = typing.Callable[[list[str]], subprocess.CompletedProcess[str]]
|
||||
|
||||
# The oldest tmux that has every command and option used here. Its CHANGES file dates the newest two to 3.2: `remain-on-exit failed` and `new-session -e`.
|
||||
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"
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Window:
|
||||
"""The tmux window a chunk's loop runs in."""
|
||||
session: str
|
||||
# Without WAITS.
|
||||
name: str
|
||||
# The ID of the loop's pane, which $TMUX_PANE holds. It targets the window whatever its name is.
|
||||
pane: str
|
||||
|
||||
@property
|
||||
def target(self) -> str:
|
||||
"""What `tmux attach -t` and `tmux select-window -t` take to reach the window."""
|
||||
return f"{self.session}:{self.name}"
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Listed:
|
||||
"""A window of the project's session, as tmux lists it."""
|
||||
# Without WAITS.
|
||||
name: str
|
||||
# tmux's ID of the window, such as `@3`.
|
||||
id: str
|
||||
# Whether its loop has exited: `remain-on-exit failed` keeps the window of a loop that failed, so its last lines stay readable.
|
||||
dead: bool
|
||||
|
||||
|
||||
def unusable(run: Tmux) -> str | None:
|
||||
"""Why loop-claude cannot use this machine's tmux, naming the version found and the one needed; None where it is NEEDED or later."""
|
||||
found = run(["-V"]).stdout.strip()
|
||||
version = re.search(r"([0-9]+)\.([0-9]+)", found)
|
||||
if version and (int(version[1]), int(version[2])) >= NEEDED:
|
||||
return None
|
||||
return f"loop-claude runs each chunk in a tmux window, and needs tmux {NEEDED[0]}.{NEEDED[1]} or later; it found {found or 'no tmux'}"
|
||||
|
||||
|
||||
def session_name(key: str) -> str:
|
||||
"""The tmux session of the project with this key, such as `loop-claude-config`. tmux reads `.` and `:` in a target as separators, so every character but a letter, a digit, `_` and `-` becomes a dash."""
|
||||
return "loop-" + re.sub(r"[^A-Za-z0-9_-]", "-", key)
|
||||
|
||||
|
||||
def listed(session: str, run: Tmux) -> list[Listed]:
|
||||
"""The windows of session; none where tmux lists none, as while the session doesn't exist or no tmux server runs."""
|
||||
done = run(["list-windows", "-t", f"={session}", "-F", "#{window_name}\t#{pane_dead}\t#{window_id}"])
|
||||
rows = [line.split("\t") for line in done.stdout.splitlines()] if done.returncode == 0 else []
|
||||
return [Listed(row[0].removesuffix(WAITS), row[2], row[1] == "1") for row in rows if len(row) == 3]
|
||||
|
||||
|
||||
def start_window(window: Window, cwd: str, env: typing.Mapping[str, str], command: list[str], first: bool, run: Tmux) -> Failure | None:
|
||||
"""Starts command in a new window of window's session, in cwd with env added to its environment, and leaves the client where it is. first makes the session too. A Failure says why tmux started none."""
|
||||
make = ["new-session", "-d", "-s", window.session] if first else ["new-window", "-d", "-t", f"={window.session}:"]
|
||||
variables = [flag for name, value in env.items() for flag in ("-e", f"{name}={value}")]
|
||||
# tmux reads a `;` that ends an argument as the end of the command, unless a backslash precedes it.
|
||||
words = [re.sub(r";$", r"\\;", word) for word in command]
|
||||
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.
|
||||
run(["set-option", "-w", "-t", done.stdout.strip(), "remain-on-exit", "failed"])
|
||||
return None
|
||||
|
||||
|
||||
def close(window: Listed, run: Tmux) -> None:
|
||||
run(["kill-window", "-t", window.id])
|
||||
|
||||
|
||||
def mark(window: Window, waits: bool, run: Tmux) -> None:
|
||||
"""Renames window to end in WAITS while its chunk waits for the human, and back once it doesn't."""
|
||||
run(["rename-window", "-t", window.pane, window.name + (WAITS if waits else "")])
|
||||
|
||||
|
||||
def show(session: str, inside: bool) -> list[str]:
|
||||
"""The tmux arguments that put session on the human's terminal: inside tmux the client switches to it, and outside a new client attaches."""
|
||||
return ["switch-client" if inside else "attach-session", "-t", f"={session}"]
|
||||
Reference in New Issue
Block a user