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

Merged
lilleman merged 7 commits from rebuild-transcript-session-worker into rebuild 2026-09-28 16:31:15 +02:00
12 changed files with 302 additions and 183 deletions
+1
View File
@@ -26,3 +26,4 @@ Decisions live in `docs/decisions.md`:
- loop-claude: the archive keeps the raw transcript, and a failed archive stops the loop
- loop-claude: the rebuild keeps main's `--reloaded` state
- rebuild: a chunk into `rebuild` takes no comprehension scoring run
- loop-claude: a `claude` that cannot start is a failed worker run, retried
+1
View File
@@ -6,4 +6,5 @@
- `settings.json`, the agents and the status line run on any machine unedited; the status line shows reset times in the machine's own time zone.
- `loop-claude`'s no-premises exit names what is wrong: `README.md` unopenable or not UTF-8, a `## Goals` or `## Audience` heading missing or repeated, or nothing under one.
- `loop-claude` says why when it cannot read or write `~/.claude.json` before an interrupt, and the interrupt then lands in Claude Code's trust dialog.
- `loop-claude` skips a transcript line it cannot parse, exits 1 naming a transcript it cannot read, and counts a `claude` it cannot start as a failed worker run.
- `loop-claude` keeps the mode of `~/.claude.json` and of its models file when it rewrites them, and creates the models file 0600.
+37 -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(session)
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,19 @@ 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"
entries = read(path)
if isinstance(entries, Failure):
return Stop(1, entries.reason)
before = human_turns(entries)
subprocess.run(["claude", "--model", model_for(env, "LOOP_CLAUDE_WORKER_MODEL", chosen), "--permission-mode", "bypassPermissions", "--resume", str(session_id)], cwd=root)
entries = read(path)
if isinstance(entries, Failure):
return Stop(1, f"could not tell whether you typed anything: {entries.reason}")
if human_turns(entries) <= 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
+42
View File
@@ -0,0 +1,42 @@
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(session):
path = transcript_file(session)
if not path:
return
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."""
COMMAND = enum.auto()
CTRL_C = enum.auto()
EMPTY = enum.auto()
HUMAN = enum.auto()
META = enum.auto()
NON_TEXT = enum.auto()
SDK_PROMPT = enum.auto()
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, encoding="utf-8", errors="replace", stdin=subprocess.DEVNULL, stdout=subprocess.PIPE)
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,
]
+31 -31
View File
@@ -15,14 +15,15 @@ import uuid
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
from loop_claude import checkout, cycle, main, premises, reload
from loop_claude.outcome import Continue, Retry, Stop
from loop_claude import checkout, cycle, main, premises, reload, session, transcript, worker
from loop_claude.outcome import Continue, Failure, Retry, Stop
from loop_claude.paths import paths_from
CWD = pathlib.Path("/c")
LAUNCHER = pathlib.Path(__file__).resolve().with_name("loop-claude")
PATHS = paths_from(pathlib.Path("/h"), {})
SESSION_ID = str(getattr(uuid, "uuid7", uuid.uuid4)())
SESSION = session.Session(uuid.UUID(SESSION_ID), "A name", PATHS.projects)
def assistant(*parts):
@@ -81,7 +82,7 @@ class ReadPremises(unittest.TestCase):
class Render(unittest.TestCase):
def test_joins_assistant_text_and_tool_calls_and_human_turns_and_skips_the_rest(self):
said = cycle.render([
said = transcript.render([
human("do it"),
assistant({"type": "text", "text": "Starting."}, {"type": "tool_use", "name": "Bash", "input": {"command": "ls"}}),
assistant({"type": "text", "text": " "}),
@@ -95,7 +96,7 @@ class Render(unittest.TestCase):
class HumanTurns(unittest.TestCase):
def test_counts_typed_turns_and_not_tool_results(self):
self.assertEqual(cycle.human_turns([
self.assertEqual(transcript.human_turns([
human("typed"),
human([{"type": "text", "text": "typed as a block"}]),
human([{"type": "tool_result", "content": "not typed"}]),
@@ -126,30 +127,28 @@ class ProjectName(unittest.TestCase):
def test_names_a_checkout_relative_to_code_and_any_other_relative_to_root(self):
code = pathlib.Path("/h/code")
self.assertEqual(checkout.project_name("/h/code/a/b", code), "a/b")
self.assertEqual(cycle.session_name("/h/code/a/b", code), "A a/b loop-claude")
self.assertEqual(session.session_for("/h/code/a/b", PATHS).name, "A a/b loop-claude")
self.assertEqual(checkout.project_name("/h/code", code), "h/code")
self.assertEqual(checkout.project_name("/srv/x", code), "srv/x")
self.assertEqual(cycle.session_name("/srv/x", code), "A srv/x loop-claude")
self.assertEqual(session.session_for("/srv/x", PATHS).name, "A srv/x loop-claude")
class WorkerArgs(unittest.TestCase):
def test_a_fresh_cycle_names_the_session_and_asks_to_continue_open_work(self):
args = cycle.worker_args("the task", "A name", SESSION_ID, "m", {}, resuming=False)
args = worker.worker_args("the task", SESSION, "m", resuming=False)
self.assertIn("--session-id", args)
self.assertEqual(args[args.index("--name") + 1], "A name")
self.assertTrue(args[1].startswith("the task\n\nContinue any open draft PR"))
def test_a_resumed_cycle_reuses_the_session(self):
args = cycle.worker_args("paint the fence", "A name", SESSION_ID, "m", {}, resuming=True)
self.assertEqual(args[args.index("--resume") + 1], SESSION_ID)
args = worker.worker_args("paint the fence", SESSION, "m", resuming=True)
self.assertEqual(args[args.index("--resume") + 1], str(SESSION.id))
self.assertNotIn("--name", args)
self.assertNotIn("paint the fence", args[1])
def test_the_project_model_runs_unless_the_environment_names_one(self):
args = cycle.worker_args("t", "n", SESSION_ID, "claude-opus-5-5", {}, resuming=False)
self.assertEqual(args[args.index("--model") + 1], "claude-opus-5-5")
args = cycle.worker_args("t", "n", SESSION_ID, "claude-opus-5-5", {"LOOP_CLAUDE_WORKER_MODEL": "claude-fable-5-1"}, resuming=False)
self.assertEqual(args[args.index("--model") + 1], "claude-fable-5-1")
self.assertEqual(cycle.model_for({}, "LOOP_CLAUDE_WORKER_MODEL", "claude-opus-5-5"), "claude-opus-5-5")
self.assertEqual(cycle.model_for({"LOOP_CLAUDE_WORKER_MODEL": "claude-fable-5-1"}, "LOOP_CLAUDE_WORKER_MODEL", "claude-opus-5-5"), "claude-fable-5-1")
class ProjectModel(unittest.TestCase):
@@ -244,10 +243,10 @@ class Archive(unittest.TestCase):
class Said(unittest.TestCase):
def test_renders_text_and_tool_calls_and_nothing_else(self):
self.assertEqual(cycle.said({"type": "text", "text": "hi"}), "hi")
self.assertEqual(cycle.said({"type": "text", "text": " \n"}), "")
self.assertEqual(cycle.said({"type": "tool_use", "name": "Bash", "input": {"command": "x" * 500}}, 20), '[tool Bash] {"command": "xxxxxxx')
self.assertEqual(cycle.said("not a part"), "")
self.assertEqual(transcript.said({"type": "text", "text": "hi"}), "hi")
self.assertEqual(transcript.said({"type": "text", "text": " \n"}), "")
self.assertEqual(transcript.said({"type": "tool_use", "name": "Bash", "input": {"command": "x" * 500}}, 20), '[tool Bash] {"command": "xxxxxxx')
self.assertEqual(transcript.said("not a part"), "")
class DeleteTranscriptFiles(unittest.TestCase):
@@ -261,10 +260,11 @@ class DeleteTranscriptFiles(unittest.TestCase):
os.makedirs(os.path.join(root, SESSION_ID, "subagents"))
os.makedirs(os.path.join(root, f"{SESSION_ID}.superseded-1", "tool-results"))
pathlib.Path(root, f"{SESSION_ID}.orphaned-1-ab.jsonl").write_text("{}\n")
self.assertTrue(cycle.session_open(projects, SESSION_ID))
cycle.delete_transcript_files(transcript)
located = session.Session(uuid.UUID(SESSION_ID), "A name", projects)
self.assertEqual(session.transcript_file(located), transcript)
session.delete_session(located)
self.assertEqual(os.listdir(root), [])
self.assertFalse(cycle.session_open(projects, SESSION_ID))
self.assertEqual(session.transcript_file(located), "")
class Interrupt(unittest.TestCase):
@@ -273,14 +273,14 @@ class Interrupt(unittest.TestCase):
transcript = os.path.join(root, "session.jsonl")
pathlib.Path(transcript).write_text("{}\n")
with unittest.mock.patch("sys.stdin.isatty", return_value=False):
self.assertEqual(cycle.interrupt(root, SESSION_ID, "m", transcript, "q?", paths_from(pathlib.Path(root), {}), {}), "stdin or stdout is not a terminal")
self.assertEqual(cycle.interrupt(root, SESSION_ID, "m", transcript, "q?", paths_from(pathlib.Path(root), {}), {}), Stop(2, "stdin or stdout is not a terminal"))
with (
unittest.mock.patch("sys.stdin.isatty", return_value=True),
unittest.mock.patch("sys.stdout.isatty", return_value=True),
unittest.mock.patch.multiple(cycle, checkouts=unittest.mock.DEFAULT, trust=unittest.mock.DEFAULT) as mocks,
unittest.mock.patch("subprocess.run") as run,
):
self.assertEqual(cycle.interrupt(root, SESSION_ID, "m", transcript, "q?", paths_from(pathlib.Path(root), {}), {}), "the interrupt ended without the human typing anything")
self.assertEqual(cycle.interrupt(root, SESSION_ID, "m", transcript, "q?", paths_from(pathlib.Path(root), {}), {}), Stop(2, "the interrupt ended without the human typing anything"))
mocks["checkouts"].assert_called_with(root)
self.assertEqual(run.call_args.kwargs["cwd"], root)
self.assertEqual(run.call_args.args[0][run.call_args.args[0].index("--model") + 1], "m")
@@ -289,7 +289,7 @@ class Interrupt(unittest.TestCase):
handle.write(json.dumps(human("typed")) + "\n")
run.side_effect = type_a_turn
self.assertEqual(cycle.interrupt(root, SESSION_ID, "m", transcript, "q?", paths_from(pathlib.Path(root), {}), {}), "")
self.assertIsNone(cycle.interrupt(root, SESSION_ID, "m", transcript, "q?", paths_from(pathlib.Path(root), {}), {}))
class Trust(unittest.TestCase):
@@ -334,9 +334,9 @@ class Trust(unittest.TestCase):
class Parse(unittest.TestCase):
def test_yields_only_json_objects(self):
self.assertEqual(cycle.parse('{"type": "user"}'), {"type": "user"})
self.assertIsNone(cycle.parse("not json"))
self.assertIsNone(cycle.parse("[1, 2]"))
self.assertEqual(transcript.parse('{"type": "user"}'), {"type": "user"})
self.assertIsNone(transcript.parse("not json"))
self.assertIsNone(transcript.parse("[1, 2]"))
class Grounded(unittest.TestCase):
@@ -382,7 +382,7 @@ class RunWorker(unittest.TestCase):
with tempfile.TemporaryDirectory() as bin:
stub = os.path.join(bin, "claude")
scripts = {
"": 'print(json.dumps({"type": "result"}))',
None: 'print(json.dumps({"type": "result"}))',
"claude exited 0 without a result event": 'print(json.dumps({"type": "assistant", "message": {"content": [{"type": "text", "text": "worked"}]}}))',
"claude exited 3": "sys.exit(3)",
"claude killed by signal 9": "os.kill(os.getpid(), 9)",
@@ -391,7 +391,7 @@ class RunWorker(unittest.TestCase):
for failure, script in scripts.items():
pathlib.Path(stub).write_text(f"#!/usr/bin/env python3\nimport json\nimport os\nimport sys\n{script}\n")
os.chmod(stub, 0o700)
self.assertEqual(cycle.run_worker(bin, []), failure)
self.assertEqual(worker.run_worker(bin, []), failure and Failure(failure))
class RunCycle(unittest.TestCase):
@@ -401,7 +401,7 @@ class RunCycle(unittest.TestCase):
pathlib.Path(stub).write_text(STUB_CLAUDE)
os.chmod(stub, 0o700)
calls, verdicts = os.path.join(home, "calls"), os.path.join(home, "verdicts")
session_id = cycle.uuid.uuid5(cycle.SESSION_NAMESPACE, cycle.session_name(home, paths_from(pathlib.Path(home), {}).code))
session_id = session.session_for(home, paths_from(pathlib.Path(home), {})).id
pathlib.Path(verdicts).write_text("fail continue finished unquoted continue")
paths = paths_from(pathlib.Path(home), {"LOOP_CLAUDE_TRANSCRIPTS": os.path.join(home, "archive")})
environment = {"HOME": home, "PATH": f"{home}:{os.environ['PATH']}", "STUB_CALLS": calls, "STUB_VERDICTS": verdicts}
@@ -413,9 +413,9 @@ class RunCycle(unittest.TestCase):
self.assertEqual(cycle.run_cycle(home, "task", "premises", "claude-opus-5-5", paths, {}), Stop(2, "stdin or stdout is not a terminal"))
self.assertIn(f"transcript: {paths.archive}", "".join(str(call.args[0]) for call in stderr.write.call_args_list))
pathlib.Path(verdicts).write_text("interrupt fail fail fail")
with unittest.mock.patch("sys.stderr"), unittest.mock.patch.object(cycle, "interrupt", return_value=""):
with unittest.mock.patch("sys.stderr"), unittest.mock.patch.object(cycle, "interrupt", return_value=None):
self.assertEqual(cycle.run_cycle(home, "task", "premises", "claude-opus-5-5", paths, {}).code, 1)
with unittest.mock.patch.object(cycle, "session_file", return_value=""):
with unittest.mock.patch.object(cycle, "transcript_file", return_value=""):
self.assertEqual(cycle.run_cycle(home, "task", "premises", "claude-opus-5-5", paths, {}), Stop(1, f"claude left no transcript for session {session_id}"))
for plan in ("fail fail fail", "unquoted unquoted unquoted"):
pathlib.Path(verdicts).write_text(plan)
+48 -5
View File
@@ -44,23 +44,31 @@ def session():
return argv[argv.index(flag) + 1]
def transcript():
return pathlib.Path.home() / ".claude" / "projects" / "-fake" / f"{{session()}}.jsonl"
def append(*entries):
path = pathlib.Path.home() / ".claude" / "projects" / "-fake" / f"{{session()}}.jsonl"
path.parent.mkdir(parents=True, exist_ok=True)
with open(path, "a") as transcript:
transcript.writelines(json.dumps(entry) + "\\n" for entry in entries)
transcript().parent.mkdir(parents=True, exist_ok=True)
with open(transcript(), "a") as handle:
handle.writelines(json.dumps(entry) + "\\n" for entry in entries)
if role == "worker":
said = {{"type": "assistant", "message": {{"content": [{{"type": "text", "text": step.get("say", "working")}}]}}}}
if step.get("transcript", True):
append({{"type": "user", "promptSource": "sdk", "message": {{"content": argv[argv.index("-p") + 1]}}}}, said)
append({{"type": "user", "promptSource": "sdk", "message": {{"content": argv[argv.index("-p") + 1]}}}})
with open(transcript(), "ab") as handle:
handle.write(step.get("raw", "").encode("latin-1"))
append(said)
if "append" in step:
with open(os.environ["FAKE_CLAUDE_EDIT"], "a") as script:
script.write(step["append"])
if "replace" in step:
script = pathlib.Path(os.environ["FAKE_CLAUDE_EDIT"])
script.write_text(script.read_text().replace(*step["replace"]))
sys.stdout.flush()
sys.stdout.buffer.write(step.get("stream", "").encode("latin-1"))
print(json.dumps(said))
if step.get("result", True):
print(json.dumps({{"type": "result"}}))
@@ -71,6 +79,8 @@ elif role == "judge":
print(step.get("stderr", ""), file=sys.stderr)
elif "type" in step:
append({{"type": "user", "message": {{"content": step["type"]}}}})
if step.get("unreadable"):
transcript().chmod(0)
sys.exit(step.get("exit", 0))
"""
@@ -311,6 +321,32 @@ class Cycles(unittest.TestCase):
self.assertEqual(run.roles(), ["worker", "judge", "judge", "worker"])
self.assertIn("the judge quoted 'never said', nothing in the transcript, for the question: A or B?", run.stderr)
def test_skips_a_malformed_transcript_or_stream_line(self):
checkout = Checkout(self)
raw = "\xff not UTF-8\nnot JSON\n[1]\n" + json.dumps({"type": "assistant", "message": "not an object"}) + "\n" + json.dumps({"type": "user", "message": None}) + "\n"
run = checkout.run([worker(raw=raw, say="past the noise", stream="\xff not UTF-8\n"), judge()])
self.assertEqual((run.code, run.roles()), (130, ["worker", "judge", "worker"]))
self.assertIn("past the noise", run.stdout)
self.assertIn("past the noise", run.calls[1]["stdin"])
@unittest.skipIf(os.geteuid() == 0, "root reads an unreadable file")
def test_exits_1_when_the_transcript_cannot_be_read(self):
checkout = Checkout(self)
run = checkout.run([worker(unreadable=True)])
self.assertEqual((run.code, run.roles()), (1, ["worker"]))
self.assertRegex(run.stderr.strip().splitlines()[-1], r"^could not read the transcript .*\.jsonl: Permission denied$")
def test_retries_a_worker_claude_cannot_start(self):
checkout = Checkout(self)
only_git = checkout.temp / "only-git"
only_git.mkdir()
(only_git / "git").symlink_to(shutil.which("git"))
checkout.env["PATH"] = str(only_git)
run = checkout.run([])
self.assertEqual((run.code, run.calls), (1, []))
self.assertEqual(run.sleeps, [60, 60])
self.assertEqual(run.stderr.strip().splitlines()[-1], "the worker failed three times running: could not start claude: No such file or directory")
def test_exits_1_when_claude_leaves_no_transcript(self):
checkout = Checkout(self)
run = checkout.run([worker(transcript=False)])
@@ -359,6 +395,13 @@ class Interrupt(unittest.TestCase):
self.assertEqual((run.code, run.roles()), (2, ["worker", "judge", "interrupt"]))
self.assertEqual(run.stderr.strip().splitlines()[-1], "the interrupt ended without the human typing anything")
@unittest.skipIf(os.geteuid() == 0, "root reads an unreadable file")
def test_exits_1_when_the_transcript_cannot_be_read_after_the_interrupt(self):
checkout = Checkout(self)
run = checkout.run([worker(say="A or B?"), judge(interrupt=True, evidence="A or B?", question="A or B?"), interrupt(type="B", unreadable=True)], terminal_input="")
self.assertEqual((run.code, run.roles()), (1, ["worker", "judge", "interrupt"]))
self.assertRegex(run.stderr.strip().splitlines()[-1], r"^could not tell whether you typed anything: could not read the transcript .*\.jsonl: Permission denied$")
class Models(unittest.TestCase):
def catalog(self, checkout):
+5 -1
View File
@@ -38,7 +38,7 @@
## loop-claude: the section headers stay
2026-09-26, larv-review, declining a prose-pass deletion under `CLAUDE.md` → "Comments and documentation". Serves goal 4. Two seats of the 2026-09-26 panel credit Navigation 8 to `# The transcript file` and its siblings, now in `bin/loop_claude/cycle.py`, indexing it by the file or format each group touches. Valid until the modules the rebuild splits out of `cycle.py` take over that index.
2026-09-26, larv-review, declining a prose-pass deletion under `CLAUDE.md` → "Comments and documentation". Serves goal 4. Two seats of the 2026-09-26 panel credit Navigation 8 to the headers in what is now `bin/loop_claude/cycle.py`, which index it by the file or format each group touches. Valid while `cycle.py` holds more than one group; a header leaves with its group, as `# The transcript file` did into `transcript.py`.
## vocabulary: the concept words are defined under `CLAUDE.md` → "Vocabulary" and cited by a bare link
@@ -87,3 +87,7 @@
## rebuild: a chunk into `rebuild` takes no comprehension scoring run
2026-09-28, lilleman, confirming larv-review's reading of the rebuild decision above. Serves goal 4. The floor and its ratchet gate `rebuild` into main, scored by the plan's last item; the chunks before it pass through half-moved states a per-chunk run would block. Valid until the rebuild merges.
## loop-claude: a `claude` that cannot start is a failed worker run, retried
2026-09-28, larv-review, declining a product-owner nit to exit at once when `claude` is missing. Serves goal 4. Claude Code's updater repoints `~/.local/bin/claude` at each new version under running loops, and a start that meets it mid-update fails with the same error as a broken install; the retry costs two minutes on the second and saves an unattended loop on the first. Valid while Claude Code updates by repointing its link.
-1
View File
@@ -6,7 +6,6 @@
The rebuild lifts every dimension: each item below is one chunk on a worktree based on `origin/rebuild`, its PR into `rebuild`, until the last item merges `rebuild` into main. The sketches, the judges' verdicts and what to take from each: `~/code/claude-handoffs/claude-config_2026-09-28.md`.
- **Move the transcript, the session and the worker into their own modules.** `UserEntryKind` names each entry Claude Code writes; a malformed line is skipped; an unreadable transcript is its own error, never "typed nothing"; `session` states the lifecycle once, where the id is made; `run_worker` returns a failure its caller maps, never `""` for success.
- **Move the judge, the interrupt, trust and model resolution into their own modules.** The judge is retried alone and checks evidence on every verdict against the rendered transcript; `models` owns the whole resolution, env overrides included, with no sentinel; `trust` names a `projects` entry that is not an object; `input()` at end of file is exit 2. `ask_model` and `interrupt` spell "the human is needed" one way; `replace_json` and `make_private` get one module shared by `models`, `trust` and the archive.
- **Move each Claude Code internal `--help` lists beside the module relying on it.** Or `docs/decisions.md` says why `--help` keeps it.
- **Archive the raw transcript, deduplicated by content hash, with the verdict beside it, and stop on a failed archive.** Tests first; the changelog line says what the archive now holds.