Move the transcript, the session and the worker into their own modules

This commit is contained in:
2026-09-28 16:24:26 +02:00
parent 60c949b732
commit dfb7ae294c
10 changed files with 245 additions and 178 deletions
+36 -141
View File
@@ -1,18 +1,16 @@
import glob
import itertools
import json
import os
import shutil
import subprocess
import sys
import time
import uuid
from loop_claude.checkout import checkouts, project_name
from loop_claude.outcome import Continue, Retry, Stop
from loop_claude.outcome import Continue, Failure, Retry, Stop
from loop_claude.session import delete_session, session_for, transcript_file
from loop_claude.strike import strike
SESSION_NAMESPACE = uuid.UUID("64fb586b-d926-4bb3-a44c-c903e86d3eec")
from loop_claude.transcript import human_turns, parse, read, render
from loop_claude.worker import run_worker, worker_args
JUDGE_RULES = (
"Decide whether the human must now be interrupted. interrupt=true when any of these appear:\n"
@@ -47,34 +45,32 @@ JUDGE_SCHEMA = {
def run_cycle(root, task, premises, chosen, paths, env):
name = session_name(root, paths.code)
session_id = uuid.uuid5(SESSION_NAMESPACE, name)
if failure := run_worker(root, worker_args(task, name, session_id, chosen, env, resuming=session_open(paths.projects, session_id))):
return Retry(failure)
path = session_file(paths.projects, session_id)
session = session_for(root, paths)
resuming = bool(transcript_file(session))
if failure := run_worker(root, worker_args(task, session, model_for(env, "LOOP_CLAUDE_WORKER_MODEL", chosen), resuming)):
return Retry(failure.reason)
path = transcript_file(session)
if not path:
return Stop(1, f"claude left no transcript for session {session_id}")
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:
verdict = judge(root, task, premises, render(entries(path)), chosen, env)
entries = read(path)
if isinstance(entries, Failure):
return Stop(1, entries.reason)
verdict = judge(root, task, premises, render(entries), chosen, env)
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 failure := interrupt(root, session_id, chosen, path, verdict["question"], paths, env):
return Stop(2, failure)
if stop := interrupt(root, session.id, chosen, path, verdict["question"], paths, env):
return stop
if verdict["finished"]:
archive(root, path, f"Task: {task}\n\nVerdict: finished", paths)
delete_transcript_files(path)
delete_session(path)
return Continue()
def session_name(root, code):
# "A " is the human's cue in the session picker that the session is the loop's.
return f"A {project_name(root, code)} loop-claude"
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)
@@ -84,8 +80,12 @@ def archive(root, path, note, paths):
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(path))}\n")
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)
@@ -114,8 +114,8 @@ def replace_json(path, data, **dump):
return None
def model_args(env, variable, chosen):
return ["--model", env.get(variable) or chosen]
def model_for(env, variable, chosen):
return env.get(variable) or chosen
# ~/.claude/loop-claude-models.json
@@ -197,118 +197,6 @@ def catalog(folder):
return [(entry["id"], entry.get("name", entry["id"])) for entry in models if isinstance(entry, dict) and isinstance(entry.get("id"), str)] if isinstance(models, list) else []
# The transcript file
def session_open(projects, session_id):
return bool(session_file(projects, session_id))
def session_file(projects, session_id):
hit = glob.glob(os.path.join(glob.escape(str(projects)), "*", f"{session_id}.jsonl"))
return hit[0] if hit else ""
def delete_transcript_files(path):
for sibling in glob.glob(glob.escape(path.removesuffix(".jsonl")) + "*"):
try:
shutil.rmtree(sibling) if os.path.isdir(sibling) else os.remove(sibling)
except OSError as failure:
print(f"could not remove {sibling}: {failure}", file=sys.stderr)
def entries(path):
with open(path, encoding="utf-8") as handle:
for raw in handle:
if entry := parse(raw):
yield entry
def parse(raw):
try:
entry = json.loads(raw)
except ValueError:
return None
return entry if isinstance(entry, dict) else None
# "user" entries
def human_turns(entries):
return sum(1 for entry in entries if typed(entry))
def typed(entry):
if entry.get("type") != "user":
return False
content = entry.get("message", {}).get("content")
parts = content if isinstance(content, list) else []
meta = entry.get("isMeta")
loop_prompt = entry.get("promptSource") == "sdk"
command = isinstance(content, str) and content.startswith("<")
no_content = not isinstance(content, str) and not parts
non_text = any(not isinstance(part, dict) or part.get("type") != "text" for part in parts)
interruption = not non_text and any(part.get("text", "").startswith("[Request interrupted") for part in parts)
return not (meta or loop_prompt or command or no_content or non_text or interruption)
# "assistant" entries and stream-json
def run_worker(root, args):
with subprocess.Popen(["claude", *args], cwd=root, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, text=True) as proc:
done = False
for raw in proc.stdout:
event = parse(raw) or {}
if event.get("type") == "result":
done = True
elif event.get("type") == "assistant":
for part in event.get("message", {}).get("content", []):
if line := said(part, 160):
print(line, flush=True)
code = proc.wait()
if code < 0:
return f"claude killed by signal {-code}"
if code:
return f"claude exited {code}"
return "" if done else "claude exited 0 without a result event"
def worker_args(task, name, session_id, chosen, env, resuming):
if resuming:
start = ["-p", "Continue the task; the previous run stopped before it was finished.", "--resume", str(session_id)]
else:
start = ["-p", f"{task}\n\nContinue any open draft PR or worktree for the item before creating a new one.", "--name", name, "--session-id", str(session_id)]
return [
*start,
"--output-format", "stream-json",
"--permission-mode", "bypassPermissions",
"--verbose",
*model_args(env, "LOOP_CLAUDE_WORKER_MODEL", chosen),
]
def render(entries):
lines = []
for entry in entries:
if entry.get("type") == "assistant":
lines += [line for part in entry.get("message", {}).get("content", []) if (line := said(part))]
elif typed(entry):
content = entry["message"]["content"]
lines.append("[human] " + (content if isinstance(content, str) else "".join(part.get("text", "") for part in content)))
return "\n\n".join(lines)
def said(part, limit=400):
kind = part.get("type") if isinstance(part, dict) else None
if kind == "text" and part.get("text", "").strip():
return part["text"]
if kind == "tool_use":
return f"[tool {part.get('name')}] {json.dumps(part.get('input'))[:limit]}"
return ""
# --json-schema verdicts
@@ -317,7 +205,7 @@ def judge(root, task, premises, transcript, chosen, env):
args = [
"-p",
"--json-schema", json.dumps(JUDGE_SCHEMA),
*model_args(env, "LOOP_CLAUDE_JUDGE_MODEL", chosen),
"--model", model_for(env, "LOOP_CLAUDE_JUDGE_MODEL", chosen),
"--no-session-persistence",
"--output-format", "json",
"--permission-mode", "bypassPermissions",
@@ -364,11 +252,18 @@ def grounded(verdict, transcript):
def interrupt(root, session_id, chosen, path, question, paths, env):
print(f"\n{question}", file=sys.stderr)
if not (sys.stdin.isatty() and sys.stdout.isatty()):
return "stdin or stdout is not a terminal"
return Stop(2, "stdin or stdout is not a terminal")
trust(paths.claude_json, checkouts(root))
before = human_turns(entries(path))
subprocess.run(["claude", *model_args(env, "LOOP_CLAUDE_WORKER_MODEL", chosen), "--permission-mode", "bypassPermissions", "--resume", str(session_id)], cwd=root)
return "" if human_turns(entries(path)) > before else "the interrupt ended without the human typing anything"
before = read(path)
if isinstance(before, Failure):
return Stop(1, before.reason)
subprocess.run(["claude", "--model", model_for(env, "LOOP_CLAUDE_WORKER_MODEL", chosen), "--permission-mode", "bypassPermissions", "--resume", str(session_id)], cwd=root)
after = read(path)
if isinstance(after, Failure):
return Stop(1, f"could not tell whether you typed anything: {after.reason}")
if human_turns(after) <= human_turns(before):
return Stop(2, "the interrupt ended without the human typing anything")
return None
def trust(config, roots):