import dataclasses 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 loop_claude.transcript_archive import archive, FINISHED, UNFINISHED from loop_claude.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_reply import Finished, Interrupt, QUOTE_SOURCES, QuotedAnswer, Unfinished from loop_claude.cycle.interrupt import interrupt from loop_claude.cycle.judge import judge from loop_claude.project.model_choice import Models from loop_claude.paths import Paths from loop_claude.claude_code.transcript import read_transcript, render from loop_claude.cycle.retry import retried from loop_claude.cycle.worker import run_worker, worker_args from loop_claude.stop import Stop @dataclasses.dataclass(frozen=True) class Cycle: effects: Effects models: Models paths: Paths premises: str project_key: str records: str # The evidence of the previous cycle's unfinished verdict, empty after any other. remaining: str root: str session: Session task: 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_key, path, cycle.task, f"Stopped: {why}", cycle.effects.now(), cycle.paths) 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 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=== {QUOTE_SOURCES} answered: {answered.question} ===\n{answered.answer}", flush=True) if stop := keep_answer(cycle, answered): return stop # session_open runs inside the lambda: a failed attempt may have opened the session. if stop := retried("worker", lambda: run_worker(cycle.root, worker_args(cycle.task, cycle.session, cycle.models.worker, session_open(cycle.session), answered, quoted(cycle.remaining)), 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 keep_answer(cycle: Cycle, answered: QuotedAnswer) -> Stop | None: path = transcript_file(cycle.session) if path and (failure := archive(cycle.project_key, path, cycle.task, f"Verdict: quoted answer\n\n{answered.question}\n\n{QUOTE_SOURCES} says:\n{quoted(answered.answer)}\n\nEvidence:\n{quoted(answered.evidence)}", cycle.effects.now(), cycle.paths)): 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), cycle.models.judge, 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_key, transcript_path, cycle.task, f"Verdict: interrupt\n\n{question}\n\nEvidence:\n{quoted(ruling.evidence)}", cycle.effects.now(), cycle.paths): return Stop(1, failure.reason) return interrupt(cycle.root, cycle.session.id, cycle.models.worker, transcript_path, question, cycle.paths, cycle.effects) or HumanAnswered() def question_for(ruling: Interrupt | QuotedAnswer) -> str: if isinstance(ruling, Interrupt): return ruling.question return f"{ruling.question}\n\n{QUOTE_SOURCES} says:\n{ruling.answer}\n\nThose files have answered {QUOTED_ANSWERS_PER_CYCLE} questions this cycle, the most allowed, so this one comes to you." def close(cycle: Cycle, transcript_path: str, verdict: Finished | Unfinished) -> Archived | Stop: finished = isinstance(verdict, Finished) if failure := archive(cycle.project_key, transcript_path, cycle.task, f"{FINISHED if finished else UNFINISHED}\n\nEvidence:\n{quoted(verdict.evidence)}", cycle.effects.now(), cycle.paths): return Stop(1, failure.reason) if finished and (failure := delete_session(cycle.session)): return Stop(1, failure.reason) return Archived() # Blockquoted, so evidence holding blank lines still ends visibly where the text after it starts. def quoted(passage: str) -> str: return "\n".join(f"> {line}" for line in passage.splitlines())