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
+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(transcript)
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)