import dataclasses import pathlib import typing from chunk_driver.cycle_start import announced_route, cycle_of, project_routing from transcript_archive.location import archive_root, project_archive from loop_claude.loop.routing_check import check_routing from loop_claude.loop.checkout import checkout_root from chunk_driver.claims import CHUNK_FLAG, loop_session from loop_claude.chunk import chunk_items, fresh_prompt from loop_claude.loop.chunk_windows import chunk_session, item_of, start_chunks from loop_claude.loop.chunk_start import chunk_start, plan_item, scored_plan from chunk_driver.chunk_run import closed_cycle from agent_cycle.run import Concluded, Cycle, run_cycle from loop_claude.loop.reload import decode_handed, exec_if_edited, fingerprint, LoopRun, RELOAD_FLAG from loop_effects.effects import Effects, say from failure import Failure from agent_cycle.verdicts import Finished from loop_claude.loop.usage import HELP from chunk_driver.this_loop import Loop from loop_state.paths import Paths from transcript_archive.project_key import project_key from model_routing.ladder import ProjectRung, Rung from chunk_driver.project.premises import read_premises from chunk_driver.project.records import read_records from model_routing.ladder_file import SHIPPED from agent_cycle.stop import Stop from agent_cycle.direct_message import tell from agent_cycle import tmux # Starts the chunks that may start now, as chunk_windows.start_chunks does. StartChunks = typing.Callable[[LoopRun, bool, Paths, typing.Mapping[str, str], pathlib.Path, Effects], list[str] | Failure] @dataclasses.dataclass(frozen=True) class Steps: """The steps a loop takes, each the function of its name, which main binds.""" start_chunks: StartChunks fingerprint: typing.Callable[[pathlib.Path], str] exec_if_edited: typing.Callable[[Loop, str, LoopRun], Stop | None] next_cycle: typing.Callable[[LoopRun, Loop], Cycle | Stop] run_cycle: typing.Callable[[Cycle], Stop | Concluded] closed_cycle: typing.Callable[[LoopRun, ProjectRung | None, Concluded, pathlib.Path, str, Loop], LoopRun | Stop] check_routing: typing.Callable[[pathlib.Path, Rung, Loop], Stop | None] def main(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launcher: pathlib.Path, cwd: pathlib.Path, effects: Effects) -> int: steps = Steps(start_chunks, fingerprint, exec_if_edited, next_cycle, run_cycle, closed_cycle, check_routing) return exit_code(lambda: run_loop(argv, env, paths, launcher, cwd, effects, steps), cwd, effects) def exit_code(run: typing.Callable[[], Stop], cwd: pathlib.Path, effects: Effects) -> int: """The exit code of the loop that run runs in cwd, once its stop is said and sent as a DM.""" try: stop = run() except KeyboardInterrupt: stop = Stop(130, "") except Exception as crash: tell(f"loop-claude in {cwd} crashed: {crash!r}", effects) raise if stop.reason: say(stop.reason, effects, stdout=not stop.code) # Every stop with a reason, but the help, is DMed where the project's config can be read and sets `env-file`, so a loop left overnight never ends unseen. A loop given no task prints the help. Ctrl-C stops without a reason. So does the loop that started the project's windows once it attaches or prints how to, and a loop whose chunk finished once it started the next chunks, since the project's chunks go on. if stop.reason not in ("", HELP): tell(f"loop-claude in {cwd} stopped: {stop.reason}", effects) return stop.code def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launcher: pathlib.Path, cwd: pathlib.Path, effects: Effects, steps: Steps) -> Stop: loop_run = loop_run_from(argv, cwd, effects) if isinstance(loop_run, Stop): return loop_run # Before anything starts: a worktree, a claude session or a tmux window. if reason := tmux.unusable(effects.tmux, fresh_prompt.DRIVER): return Stop(1, reason) if loop_run.chunk is None: return windows_opened(loop_run, env, paths, launcher, effects, steps.start_chunks) 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 ") baseline = steps.fingerprint(launcher) key = project_key(loop_run.root, paths.home) window = tmux.Window(loop_session(loop_run.root, paths.home), 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 := steps.exec_if_edited(loop, baseline, loop_run): return stop loop_run = dataclasses.replace(loop_run, cycle_number=loop_run.cycle_number + 1) cycle = steps.next_cycle(loop_run, loop) if isinstance(cycle, Stop): return cycle concluded = steps.run_cycle(cycle) if isinstance(concluded, Stop): return concluded closed = steps.closed_cycle(loop_run, cycle.project, concluded, cycle.project_archive, fresh_prompt.DRIVER, loop) if isinstance(closed, Stop): return closed loop_run = closed # Off the ladder the worker runs on the project's model itself, which its route names. if stop := steps.check_routing(archive_root(paths.home, env), cycle.project.rung if cycle.project else cycle.route.rung, loop): return stop if isinstance(concluded.verdict, Finished): return handed_on(loop_run, loop, steps.start_chunks) def windows_opened(loop_run: LoopRun, env: typing.Mapping[str, str], paths: Paths, launcher: pathlib.Path, effects: Effects, start: StartChunks) -> Stop: """What the loop-claude the human runs does: starts, through start, 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(loop_run, False, paths, env, launcher, effects) if isinstance(started, Failure): return Stop(1, started.reason) session = loop_session(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, so `{loop_run.task}` started in no new window", effects, stdout=True) if not effects.on_terminal(): say(f"not on a terminal; see the chunks with `tmux attach -t ={session}`", effects, stdout=True) return Stop(0, "") shown = tmux.show(session, "TMUX" in env) return Stop(1, f"`tmux {' '.join(shown)}` failed; the chunks go on in the tmux session") if effects.tmux_on_terminal(shown) else Stop(0, "") def handed_on(loop_run: LoopRun, loop: Loop, start: StartChunks) -> Stop: """The stop of a loop whose chunk finished, once it has started, through start, each chunk that may start now. Its window closes as it exits.""" started = start(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: """The cycle loop_run runs next, from the premises, the records, the project's models and its routing ladder read afresh, and the route the chunk runs on; the stop where one of them cannot be read.""" premises = read_premises(loop.root, loop.paths.home) if isinstance(premises, Failure): return Stop(1, premises.reason) records = read_records(loop.root, loop.paths.home, loop.paths.claude_dir) if isinstance(records, Failure): return Stop(1, records.reason) routing = project_routing(loop, fresh_prompt.DRIVER) if isinstance(routing, Stop): return routing archive_folder = project_archive(loop.root, loop.paths.home, loop.env) # After the reads above, so a loop that stops on one makes no worktree. facts, default = chunk_start(loop) route = announced_route(loop_run.cycle_number, loop_run.route, routing, archive_folder, lambda: plan_item(default, item_of(loop.window.name), loop.effects), loop) if routing.ladder_file != SHIPPED: say(own_ladder(routing.ladder_file, routing.models.worker, routing.project is None), loop.effects) plan = scored_plan(default, loop.effects) return cycle_of(loop, routing, route, archive_folder, task=loop_run.task, facts=facts, premises=premises, records=records, unfinished_evidence=loop_run.unfinished_evidence, prompts=fresh_prompt.WORKER, taken_in=lambda entries: chunk_items.taken_in(entries, plan)) def own_ladder(file: pathlib.Path, model: str, unrouted: bool) -> str: """What a cycle says of a project that runs on a ladder of its own, so that a file left in place after its reason passed doesn't go unseen, nor one that leaves out the project's model, whose work the ladder then doesn't route.""" routes = f" {model} is not on it, so the worker runs on {model} unrouted; LOOP_CLAUDE_WORKER_MODEL and LOOP_CLAUDE_JUDGE_MODEL name other models for a run." if unrouted else "" return f"routing on the project's own ladder, {file}.{routes}" def loop_run_from(argv: list[str], cwd: pathlib.Path, effects: Effects) -> LoopRun | Stop: if argv[:1] != [RELOAD_FLAG]: 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, "", 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 . Handed: {' '.join(argv[1:])}") return loop_run