Files
claude-config/bin/loop_claude/cycle.py
T

60 lines
2.4 KiB
Python

import os
import sys
import time
from loop_claude.checkout import project_name
from loop_claude.file_writes import make_private
from loop_claude.interrupt import interrupt
from loop_claude.judge import judge
from loop_claude.outcome import Continue, Failure, Retry, Stop
from loop_claude.session import delete_session, session_for, transcript_file
from loop_claude.transcript import read, render
from loop_claude.worker import run_worker, worker_args
def run_cycle(root, task, premises, models, paths):
session = session_for(root, paths)
resuming = bool(transcript_file(session))
if failure := run_worker(root, worker_args(task, session, models.worker, resuming)):
return Retry(failure.reason)
path = transcript_file(session)
if not path:
return Stop(1, f"claude left no transcript for session {session.id}")
# The interrupt appends to this transcript, so each pass judges and archives it anew; archive skips a stamp it already wrote.
while True:
entries = read(path)
if isinstance(entries, Failure):
return Stop(1, entries.reason)
verdict = judge(root, task, premises, render(entries), models.judge)
if isinstance(verdict, Stop):
return verdict
if not verdict["interrupt"]:
break
archive(root, path, f"Task: {task}\n\nVerdict: interrupt\n\n{verdict['question']}", paths)
if stop := interrupt(root, session.id, models.worker, path, verdict["question"], paths):
return stop
if verdict["finished"]:
archive(root, path, f"Task: {task}\n\nVerdict: finished", paths)
delete_session(session)
return Continue()
def archive(root, path, note, paths):
# Stamped by mtime, so a transcript unchanged since its last archive maps to the file already written.
name = project_name(root, paths.code)
folder = paths.archive / name
try:
stamp = time.strftime("%Y-%m-%dT%H-%M-%SZ", time.gmtime(os.path.getmtime(path)))
make_private(folder)
dest = folder / f"{stamp}.md"
if not os.path.exists(dest):
entries = read(path)
if isinstance(entries, Failure):
print(f"could not archive the transcript: {entries.reason}", file=sys.stderr)
return
with open(os.open(dest, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), "w", encoding="utf-8") as copy:
copy.write(f"# {stamp} {name}\n\n{note}\n\n{render(entries)}\n")
print(f"transcript: {dest}", file=sys.stderr)
except OSError as failure:
print(f"could not archive the transcript: {failure}", file=sys.stderr)