import dataclasses import pathlib import typing from loop_claude.cycle.states import Active, Archived, Closing, Ended, Event, HumanAnswered, Interrupting, Judging, QUOTED_ANSWERS_PER_CYCLE, Ruled, State, transition, WorkerRan, Working from transcript_archive.write import archive from claude_code.session import delete_session, Session, session_open, transcript_file from loop_claude.effects import Effects from failure import Failure from loop_claude.cycle.judge import Finished, Interrupt, judge, QuotedAnswer, Unfinished from loop_claude.cycle.interrupt import interrupt from loop_claude.routing import judge_rung from transcript_archive import outcomes from loop_claude.paths import Paths from loop_claude.cycle import prompts from claude_code.transcript import read_transcript, render from loop_claude.cycle.retry import retried from model_routing.route import Route from loop_claude.cycle.worker import run_worker, worker_args from model_routing.ladder import Rung from loop_claude.stop import Stop @dataclasses.dataclass(frozen=True) class Cycle: effects: Effects judge_model: str paths: Paths premises: str project_archive: pathlib.Path records: str root: str session: Session task: str route: Route # The project's rung; None for a model off the ladder. anchor: Rung | None # Empty when the previous cycle's verdict was not Unfinished. unfinished_evidence: str def run_cycle(cycle: Cycle) -> Stop | Finished | Unfinished: state: State = Working() try: while not isinstance(state, Ended): event = step(cycle, state) if isinstance(event, Stop): return stopped(cycle, event, event.reason) state = transition(state, event) except KeyboardInterrupt: return stopped(cycle, Stop(130, ""), "Ctrl-C") return state.verdict def stopped(cycle: Cycle, stop: Stop, why: str) -> Stop: path = transcript_file(cycle.session) failure = archive(cycle.project_archive, path, cycle.task, outcomes.stopped(str(cycle.route), why), cycle.effects.now()) if path else None # A failed archive exits 1 whatever the stop; when the stop was this archive failing, its reason is said once. return Stop(1, f"{failure.reason}\n{stop.reason}".rstrip()) if failure and failure.reason != stop.reason else stop def judge_of(cycle: Cycle) -> Rung: """The judge's rung, which the archive names beside each verdict.""" return judge_rung(cycle.judge_model, cycle.route) def step(cycle: Cycle, state: Active) -> Event | Stop: match state: case Working(answered, _): return work(cycle, answered) case Judging(transcript_path, _): return rule(cycle, transcript_path) case Interrupting(transcript_path, ruling, _): return ask(cycle, transcript_path, ruling) case Closing(transcript_path, verdict): return close(cycle, transcript_path, verdict) case _: typing.assert_never(state) def work(cycle: Cycle, answered: QuotedAnswer | None) -> WorkerRan | Stop: if answered is not None: print(f"\n=== {prompts.QUOTE_SOURCES} answered: {answered.question} ===\n{answered.answer}", flush=True) if stop := keep_answer(cycle, answered): return stop # worker_start runs inside the lambda: a failed attempt may have opened the session. if stop := retried("worker", lambda: run_worker(cycle.root, worker_start(cycle, answered), cycle.effects), cycle.effects): return stop path = transcript_file(cycle.session) return WorkerRan(path) if path is not None else Stop(1, f"claude left no transcript for session {cycle.session.id}") def worker_start(cycle: Cycle, answered: QuotedAnswer | None) -> list[str]: if answered is not None: return worker_args(cycle.session, cycle.route.rung, prompts.answered(answered.question, answered.answer), resume=True) if session_open(cycle.session): return worker_args(cycle.session, cycle.route.rung, prompts.resumed(cycle.unfinished_evidence, cycle.route, cycle.anchor), resume=True) return worker_args(cycle.session, cycle.route.rung, prompts.fresh(cycle.task, cycle.premises, cycle.route, cycle.anchor), resume=False) def keep_answer(cycle: Cycle, answered: QuotedAnswer) -> Stop | None: path = transcript_file(cycle.session) if path and (failure := archive(cycle.project_archive, path, cycle.task, outcomes.answered(answered.question, prompts.QUOTE_SOURCES, answered.answer, answered.evidence, str(judge_of(cycle))), cycle.effects.now())): return Stop(1, failure.reason) return None def rule(cycle: Cycle, transcript_path: str) -> Ruled | Stop: entries = read_transcript(transcript_path) if isinstance(entries, Failure): return Stop(1, entries.reason) verdict = judge(cycle.root, cycle.task, cycle.premises, cycle.records, render(entries), judge_of(cycle), cycle.effects) return verdict if isinstance(verdict, Stop) else Ruled(verdict) def ask(cycle: Cycle, transcript_path: str, ruling: Interrupt | QuotedAnswer) -> HumanAnswered | Stop: question = question_for(ruling) # Archived now, so the transcript the question was asked on is kept with it; the human's answer then grows the transcript. if failure := archive(cycle.project_archive, transcript_path, cycle.task, outcomes.interrupted(question, ruling.evidence, str(judge_of(cycle))), cycle.effects.now()): return Stop(1, failure.reason) return interrupt(cycle.root, cycle.session.id, cycle.route.rung, transcript_path, question, cycle.paths, cycle.effects) or HumanAnswered() def question_for(ruling: Interrupt | QuotedAnswer) -> str: if isinstance(ruling, Interrupt): return ruling.question return prompts.past_the_cap(ruling.question, ruling.answer, QUOTED_ANSWERS_PER_CYCLE) def close(cycle: Cycle, transcript_path: str, verdict: Finished | Unfinished) -> Archived | Stop: outcome = outcomes.finished(str(cycle.route), verdict.evidence, str(judge_of(cycle))) if isinstance(verdict, Finished) else outcomes.unfinished(str(cycle.route), verdict.evidence, str(judge_of(cycle)), verdict.escalation) if failure := archive(cycle.project_archive, transcript_path, cycle.task, outcome, cycle.effects.now()): return Stop(1, failure.reason) if isinstance(verdict, Finished) and (failure := delete_session(cycle.session)): return Stop(1, failure.reason) return Archived()