import dataclasses import pathlib import typing from transcript_archive.location import archive_root, project_archive from loop_claude.loop.chunk_start import archived_route, chunk_start, fetched_todo, routed from loop_claude.loop.routing_check import check_routing from loop_claude.project.checkout import checkout_root from loop_claude.loop.close import closed_cycle from loop_claude.cycle.run import 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 loop_claude.project.model_choice import get_or_ask_models from git_cli.git_repo import Git from loop_claude.loop.usage import HELP from loop_claude.loop.this_loop import Loop from loop_state.paths import Paths from transcript_archive.project_key import project_key from model_routing.ladder import project_rung 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.stop import Stop from loop_claude.direct_message import tell def main(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launcher: pathlib.Path, cwd: pathlib.Path, effects: Effects) -> int: try: stop = run_loop(argv, env, paths, launcher, cwd, effects) 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 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: 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) -> Stop: loop_run = loop_run_from(argv, cwd, effects) if isinstance(loop_run, Stop): return loop_run 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) while True: if stop := exec_if_edited(loop, baseline, loop_run): return stop loop_run = dataclasses.replace(loop_run, cycle_number=loop_run.cycle_number + 1) cycle = next_cycle(loop_run, loop) if isinstance(cycle, Stop): return cycle concluded = run_cycle(cycle) if isinstance(concluded, Stop): return concluded closed = closed_cycle(loop_run, cycle.project, concluded, cycle.project_archive, 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 := check_routing(archive_root(paths.home, env), cycle.project or cycle.route.rung, loop): return stop def next_cycle(loop_run: LoopRun, loop: Loop) -> Cycle | Stop: """The cycle loop_run runs next, from the premises, the records and the project's models 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) models = get_or_ask_models(project_key(loop.root, loop.paths.home), loop.paths, loop.env, loop.effects) if isinstance(models, Stop): return models 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, item = chunk_start(loop) project = project_rung(models.worker) route = routed(loop_run.route, project, models.worker, lambda: archived_route(archive_folder, loop), item) say(f"\n=== cycle {loop_run.cycle_number}, worker on {route.rung} ===", loop.effects, stdout=True) 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, 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) def loop_run_from(argv: list[str], cwd: pathlib.Path, effects: Effects) -> LoopRun | Stop: if argv[:1] != [RELOAD_FLAG]: task = " ".join(argv) 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, "") 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 def setup_version(claude_dir: pathlib.Path, git: Git) -> str: """The release and commit of this setup that the worker's claude reads, as `v0.8.0 ()`; a commit past the latest release reads as git describe gives it, such as `v0.8.0-3-g1a2b3c4 ()`. Where git can't tell, `unknown` and why.""" described = git("describe", "--tags", "--match", "v*", "--always", cwd=str(claude_dir)) commit = git("rev-parse", "HEAD", cwd=str(claude_dir)) if isinstance(described, Failure): return unknown_version(described) if isinstance(commit, Failure): return unknown_version(commit) return f"{described.strip()} ({commit.strip()})" def unknown_version(failure: Failure) -> str: # One line, since the archive reads the line after it as the judge's. return f"unknown: {' '.join(failure.reason.split())}"