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):
+5 -4
View File
@@ -11,9 +11,10 @@ its session next cycle; the next chunk starts a fresh session.
Cycles continue until that interrupt or Ctrl-C. Words: ~/.claude/CLAUDE.md → "Vocabulary".
Exit 1: no task, not inside a checkout, no premises, a models file it cannot read or write, claude
leaves no transcript, a reload with unreadable state, or the worker or the judge fails three times
running. A worker fails when claude exits non-zero, is killed, or ends without a result event; a
judge when its verdict misses a field or quotes nothing in the transcript.
leaves no transcript or one it cannot read, a reload with unreadable state, or the worker or the
judge fails three times running. A worker fails when claude cannot start, exits non-zero, is killed,
or ends without a result event; a judge when its verdict misses a field or quotes nothing in the
transcript.
Exit 2: the human is needed, to pick the model or answer an interrupt, and stdin or stdout is not a
terminal, or the interrupt ended without them typing anything. Rerunning resumes any open session.
@@ -34,7 +35,7 @@ Claude Code internals this rests on, observed on 2.1.282, the model catalog on 2
- The transcript is ~/.claude/projects/*/<session-id>.jsonl, one JSON object per line. A <session-id>/
folder and <session-id>.superseded-*/ and .orphaned-*.jsonl siblings belong to the same session.
- Claude Code writes "user" entries of its own into the transcript, and a `claude -p` prompt lands as one
with promptSource "sdk"; typed() tells a human's from them.
with promptSource "sdk"; UserEntryKind in transcript.py tells a human's from them.
- An "assistant" entry, in the transcript and in --output-format stream-json, carries message.content
parts of type "text" (text) and "tool_use" (name, input); stream-json ends with a "result" event.
- `claude -p --output-format json --json-schema` returns the verdict under "structured_output".
+5
View File
@@ -6,6 +6,11 @@ class Continue:
pass
@dataclasses.dataclass(frozen=True)
class Failure:
reason: str
@dataclasses.dataclass(frozen=True)
class Retry:
failure: str
+39
View File
@@ -0,0 +1,39 @@
import dataclasses
import glob
import os
import pathlib
import shutil
import sys
import uuid
from loop_claude.checkout import project_name
NAMESPACE = uuid.UUID("64fb586b-d926-4bb3-a44c-c903e86d3eec")
@dataclasses.dataclass(frozen=True)
class Session:
id: uuid.UUID
name: str
projects: pathlib.Path
def session_for(root, paths):
"""The project's one session, at an id fixed by its name. It exists while its transcript does: a chunk's first
cycle starts it, each later cycle of the chunk resumes it, and the finished chunk deletes it."""
# "A " is the human's cue in the session picker that the session is the loop's.
name = f"A {project_name(root, paths.code)} loop-claude"
return Session(uuid.uuid5(NAMESPACE, name), name, paths.projects)
def transcript_file(session):
hit = glob.glob(os.path.join(glob.escape(str(session.projects)), "*", f"{session.id}.jsonl"))
return hit[0] if hit else ""
def delete_session(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)
+86
View File
@@ -0,0 +1,86 @@
import enum
import json
from loop_claude.outcome import Failure
class UserEntryKind(enum.Enum):
"""Who wrote a "user" entry: the human wrote HUMAN, Claude Code every other kind; the value is the tell."""
COMMAND = "string content starting with <"
CTRL_C = "a text part starting with [Request interrupted"
EMPTY = "no content"
HUMAN = "typed by the human"
META = "isMeta"
NON_TEXT = "a part that is not text, such as a tool result"
SDK_PROMPT = "promptSource sdk: the claude -p prompt"
def read(path):
try:
with open(path, "rb") as handle:
return [entry for raw in handle if (entry := parse(raw))]
except OSError as failure:
return Failure(f"could not read the transcript {path}: {failure.strerror}")
def parse(raw):
try:
entry = json.loads(raw)
except ValueError:
return None
return entry if isinstance(entry, dict) else None
def content(entry):
message = entry.get("message")
return message.get("content") if isinstance(message, dict) else None
def parts(entry):
found = content(entry)
return found if isinstance(found, list) else []
def user_entry_kind(entry):
if entry.get("isMeta"):
return UserEntryKind.META
if entry.get("promptSource") == "sdk":
return UserEntryKind.SDK_PROMPT
if isinstance(text := content(entry), str):
return UserEntryKind.COMMAND if text.startswith("<") else UserEntryKind.HUMAN
if not parts(entry):
return UserEntryKind.EMPTY
if any(not isinstance(part, dict) or part.get("type") != "text" or not isinstance(part.get("text"), str) for part in parts(entry)):
return UserEntryKind.NON_TEXT
if any(part["text"].startswith("[Request interrupted") for part in parts(entry)):
return UserEntryKind.CTRL_C
return UserEntryKind.HUMAN
def typed(entry):
return entry.get("type") == "user" and user_entry_kind(entry) is UserEntryKind.HUMAN
def human_turns(entries):
return sum(1 for entry in entries if typed(entry))
def render(entries):
lines = []
for entry in entries:
if entry.get("type") == "assistant":
lines += [line for part in parts(entry) if (line := said(part))]
elif typed(entry):
text = content(entry)
lines.append("[human] " + (text if isinstance(text, str) else "".join(part["text"] for part in text)))
return "\n\n".join(lines)
def said(part, limit=400):
kind = part.get("type") if isinstance(part, dict) else None
if kind == "text" and isinstance(part.get("text"), str) and part["text"].strip():
return part["text"]
if kind == "tool_use":
return f"[tool {part.get('name')}] {json.dumps(part.get('input'))[:limit]}"
return ""
+41
View File
@@ -0,0 +1,41 @@
import subprocess
from loop_claude.outcome import Failure
from loop_claude.transcript import parse, parts, said
def run_worker(root, args):
try:
proc = subprocess.Popen(["claude", *args], cwd=root, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, text=True)
except OSError as failure:
return Failure(f"could not start claude: {failure.strerror}")
with 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 parts(event):
if line := said(part, 160):
print(line, flush=True)
code = proc.wait()
if code < 0:
return Failure(f"claude killed by signal {-code}")
if code:
return Failure(f"claude exited {code}")
return None if done else Failure("claude exited 0 without a result event")
def worker_args(task, session, model, 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", session.name, "--session-id", str(session.id)]
return [
*start,
"--output-format", "stream-json",
"--permission-mode", "bypassPermissions",
"--verbose",
"--model", model,
]