"""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 touch_predictions.beside import Beside, chunks_beside from loop_claude.cycle import chunk_items from git_cli.git_repo import default_ref from loop_effects.effects import Effects, say from failure import Failure from project_config.main import located from loop_claude.loop.reload import LoopRun from chunk_preflight.gathered import NoItem, Plan from loop_state.paths import Paths from chunk_preflight.choices import planned from transcript_archive.project_key import project_key from release_plan.release_standing import project_plan from claude_code.transcript import read_transcript from claude_code.session import Session, session_named, transcript_file from loop_claude import tmux # Under the home folder, a folder per project key holds LOCK. STATE = ".local/state/loop-claude" # The file a loop keeps locked with flock while it lists the project's windows and starts new ones, so two loops whose chunks finish together start no chunk twice. 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[int] = 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))