168 lines
9.5 KiB
Python
168 lines
9.5 KiB
Python
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, plan_item, routed, scored_plan
|
|
from loop_claude.loop.routing_check import check_routing
|
|
from loop_claude.project.checkout import checkout_root
|
|
from loop_claude.loop.chunk_windows import CHUNK_FLAG, chunk_session, item_of, start_chunks
|
|
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.verdicts import Finished
|
|
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_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.stop import Stop
|
|
from loop_claude.direct_message import tell
|
|
from loop_claude import tmux
|
|
|
|
|
|
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 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) -> 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):
|
|
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)
|
|
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
|
|
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.ladder, 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
|
|
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, 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) -> 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:
|
|
"""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)
|
|
models = get_or_ask_models(project_key(loop.root, loop.paths.home), loop.paths, loop.env, loop.effects)
|
|
if isinstance(models, Stop):
|
|
return models
|
|
ladder_file = project_ladder_file(loop.root, loop.paths.home)
|
|
if isinstance(ladder_file, Failure):
|
|
return Stop(1, ladder_file.reason)
|
|
ladder = read_ladder(ladder_file)
|
|
if isinstance(ladder, Failure):
|
|
return Stop(1, ladder.reason)
|
|
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)
|
|
project = ladder.project_rung(models.worker)
|
|
route = routed(loop_run.route, ladder, project, models.worker, lambda: archived_route(archive_folder, loop), lambda: plan_item(default, item_of(loop.window.name), loop.effects))
|
|
say(f"\n=== cycle {loop_run.cycle_number}, worker on {route.rung} ===", loop.effects, stdout=True)
|
|
if ladder_file != SHIPPED:
|
|
say(own_ladder(ladder_file, models.worker, project is None), loop.effects)
|
|
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, plan=scored_plan(default, loop.effects), unfinished_evidence=loop_run.unfinished_evidence, window=loop.window)
|
|
|
|
|
|
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 <task>. 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 (<sha>)`; a commit past the latest release reads as git describe gives it, such as `v0.8.0-3-g1a2b3c4 (<sha>)`. 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())}"
|