Lay out loop-claude as a launcher over the loop_claude package

This commit is contained in:
2026-09-28 11:03:01 +02:00
parent 2ffeb5b4c0
commit 5a681948be
10 changed files with 752 additions and 702 deletions
+108 -129
View File
@@ -1,7 +1,5 @@
import contextlib
import errno
import importlib.machinery
import importlib.util
import io
import json
import os
@@ -14,12 +12,15 @@ import unittest
import unittest.mock
import uuid
SESSION_ID = str(getattr(uuid, "uuid7", uuid.uuid4)())
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
LOADER = importlib.machinery.SourceFileLoader("loop_claude", str(pathlib.Path(__file__).with_name("loop-claude")))
SPEC = importlib.util.spec_from_loader("loop_claude", LOADER)
loop = importlib.util.module_from_spec(SPEC)
LOADER.exec_module(loop)
from loop_claude import checkout, cycle, main, premises
from loop_claude.outcome import Continue, Retry, Stop
from loop_claude.paths import paths_from
LAUNCHER = pathlib.Path(__file__).resolve().with_name("loop-claude")
PATHS = paths_from(pathlib.Path("/h"), {})
SESSION_ID = str(getattr(uuid, "uuid7", uuid.uuid4)())
def assistant(*parts):
@@ -42,12 +43,12 @@ def umask(mask):
class Sections(unittest.TestCase):
def test_keeps_every_headed_section_with_its_bodies(self):
text = "# Title\n\nintro\n\n## Goals\n\n1. one\n```sh\n# not a heading\n```\n### Later\n2. two\n#1 priority\n\n## Empty\n\n## Audience\nme\n## Audience\nagain\n# Appendix\nnot audience\n"
self.assertEqual(loop.sections(text), {"Goals": ["1. one\n```sh\n# not a heading\n```\n### Later\n2. two\n#1 priority"], "Empty": [""], "Audience": ["me", "again"]})
self.assertEqual(premises.sections(text), {"Goals": ["1. one\n```sh\n# not a heading\n```\n### Later\n2. two\n#1 priority"], "Empty": [""], "Audience": ["me", "again"]})
class ReadPremises(unittest.TestCase):
def exit_message(self, root):
stop = loop.read_premises(root)
stop = premises.read_premises(root)
self.assertEqual(stop.code, 1)
self.assertTrue(stop.reason.endswith("no premises."))
return stop.reason
@@ -73,12 +74,12 @@ class ReadPremises(unittest.TestCase):
pathlib.Path(readme).write_text(text)
self.assertIn(missing, self.exit_message(root))
pathlib.Path(readme).write_text("# T\n## Goals\n1. g\n## Audience\nme\n")
self.assertEqual(loop.read_premises(root), "## Goals\n1. g\n\n## Audience\nme")
self.assertEqual(premises.read_premises(root), "## Goals\n1. g\n\n## Audience\nme")
class Render(unittest.TestCase):
def test_joins_assistant_text_and_tool_calls_and_human_turns_and_skips_the_rest(self):
said = loop.render([
said = cycle.render([
human("do it"),
assistant({"type": "text", "text": "Starting."}, {"type": "tool_use", "name": "Bash", "input": {"command": "ls"}}),
assistant({"type": "text", "text": " "}),
@@ -92,7 +93,7 @@ class Render(unittest.TestCase):
class HumanTurns(unittest.TestCase):
def test_counts_typed_turns_and_not_tool_results(self):
self.assertEqual(loop.human_turns([
self.assertEqual(cycle.human_turns([
human("typed"),
human([{"type": "text", "text": "typed as a block"}]),
human([{"type": "tool_result", "content": "not typed"}]),
@@ -109,74 +110,69 @@ class CheckoutRoot(unittest.TestCase):
def test_is_the_checkout_from_any_directory_inside_it_and_exits_outside_one(self):
with tempfile.TemporaryDirectory() as tmp, contextlib.chdir(tmp):
root = os.getcwd()
self.assertEqual(loop.checkout_root().code, 1)
self.assertEqual(checkout.checkout_root().code, 1)
subprocess.run(["git", "init", "-q"], check=True)
os.makedirs("a/b")
with contextlib.chdir("a/b"):
self.assertEqual(loop.checkout_root(), root)
self.assertEqual(checkout.checkout_root(), root)
subprocess.run(["git", "init", "-q", "other"], check=True)
with contextlib.chdir("other"):
self.assertEqual(loop.checkouts(root), [root])
self.assertEqual(checkout.checkouts(root), [root])
class ProjectName(unittest.TestCase):
def test_names_a_checkout_relative_to_code_and_any_other_relative_to_root(self):
with unittest.mock.patch.dict(os.environ, {"HOME": "/h"}):
self.assertEqual(loop.project_name("/h/code/a/b"), "a/b")
self.assertEqual(loop.session_name("/h/code/a/b"), "A a/b loop-claude")
self.assertEqual(loop.project_name("/h/code"), "h/code")
self.assertEqual(loop.project_name("/srv/x"), "srv/x")
self.assertEqual(loop.session_name("/srv/x"), "A srv/x loop-claude")
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(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")
class WorkerArgs(unittest.TestCase):
def test_a_fresh_cycle_names_the_session_and_asks_to_continue_open_work(self):
args = loop.worker_args("the task", "A name", SESSION_ID, "m", resuming=False)
args = cycle.worker_args("the task", "A name", SESSION_ID, "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 = loop.worker_args("paint the fence", "A name", SESSION_ID, "m", resuming=True)
args = cycle.worker_args("paint the fence", "A name", SESSION_ID, "m", {}, resuming=True)
self.assertEqual(args[args.index("--resume") + 1], 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):
with unittest.mock.patch.dict(os.environ):
os.environ.pop("LOOP_CLAUDE_WORKER_MODEL", None)
args = loop.worker_args("t", "n", SESSION_ID, "claude-opus-5-5", resuming=False)
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")
with unittest.mock.patch.dict(os.environ, {"LOOP_CLAUDE_WORKER_MODEL": "claude-fable-5-1"}):
args = loop.worker_args("t", "n", SESSION_ID, "claude-opus-5-5", resuming=False)
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")
class ProjectModel(unittest.TestCase):
def test_asks_once_per_project_from_the_newest_catalog_and_saves_the_answer(self):
with tempfile.TemporaryDirectory() as home, unittest.mock.patch.dict(os.environ, {"HOME": home}), unittest.mock.patch.object(sys, "stderr", io.StringIO()), umask(0o022):
for variable in ("LOOP_CLAUDE_JUDGE_MODEL", "LOOP_CLAUDE_WORKER_MODEL"):
os.environ.pop(variable, None)
with tempfile.TemporaryDirectory() as home, unittest.mock.patch.object(sys, "stderr", io.StringIO()), umask(0o022):
paths = paths_from(pathlib.Path(home), {})
saved = pathlib.Path(home, ".claude", "loop-claude-models.json")
catalog = pathlib.Path(home, ".claude", "cache", "model-catalog")
catalog.mkdir(parents=True)
for name, fetched, ids in (("old.json", 1, ["claude-opus-5"]), ("new.json", 2, ["claude-opus-5-5", "claude-sonnet-5"])):
catalog.joinpath(name).write_text(json.dumps({"fetchedAt": fetched, "catalog": {"config": {"models": [{"id": id, "name": id.upper()} for id in ids]}}}))
with unittest.mock.patch("sys.stdin.isatty", return_value=False):
stop = loop.project_model("/srv/a")
stop = cycle.project_model("/srv/a", paths, {})
self.assertEqual(stop.code, 2)
self.assertIn(f'merge {{"srv/a": "<model>"}} into {saved}', stop.reason)
self.assertFalse(saved.exists())
with unittest.mock.patch.dict(os.environ, {"LOOP_CLAUDE_JUDGE_MODEL": "j", "LOOP_CLAUDE_WORKER_MODEL": "w"}), unittest.mock.patch("sys.stdin.isatty", return_value=False):
self.assertEqual(loop.project_model("/srv/a"), "")
with unittest.mock.patch.dict(os.environ, {"LOOP_CLAUDE_JUDGE_MODEL": "j"}), unittest.mock.patch("sys.stdin.isatty", return_value=False):
self.assertEqual(loop.project_model("/srv/a").code, 2)
with unittest.mock.patch("sys.stdin.isatty", return_value=False):
self.assertEqual(cycle.project_model("/srv/a", paths, {"LOOP_CLAUDE_JUDGE_MODEL": "j", "LOOP_CLAUDE_WORKER_MODEL": "w"}), "")
self.assertEqual(cycle.project_model("/srv/a", paths, {"LOOP_CLAUDE_JUDGE_MODEL": "j"}).code, 2)
with (
unittest.mock.patch("sys.stdin.isatty", return_value=True),
unittest.mock.patch("sys.stdout.isatty", return_value=True),
unittest.mock.patch("builtins.input", side_effect=["", "3", "2"]) as typed,
):
self.assertEqual(loop.project_model("/srv/a"), "claude-sonnet-5")
self.assertEqual(cycle.project_model("/srv/a", paths, {}), "claude-sonnet-5")
self.assertEqual(typed.call_count, 3)
self.assertIn("2. CLAUDE-SONNET-5 (claude-sonnet-5)", sys.stderr.getvalue())
self.assertIn("pick 1 to 2", sys.stderr.getvalue())
@@ -188,33 +184,33 @@ class ProjectModel(unittest.TestCase):
saved.write_text(json.dumps({**json.loads(saved.read_text()), "srv/d": "haiku"}))
return "opus[1m]"
typed.side_effect = saved_elsewhere_while_asking
self.assertEqual(loop.project_model("/srv/b"), "opus[1m]")
self.assertEqual(loop.project_model("/srv/a"), "claude-sonnet-5")
self.assertEqual(cycle.project_model("/srv/b", paths, {}), "opus[1m]")
self.assertEqual(cycle.project_model("/srv/a", paths, {}), "claude-sonnet-5")
self.assertEqual(typed.call_count, 4)
typed.side_effect = EOFError
self.assertEqual(loop.project_model("/srv/c"), loop.Stop(2, "no model picked"))
self.assertEqual(cycle.project_model("/srv/c", paths, {}), Stop(2, "no model picked"))
typed.side_effect = ["sonnet"]
with unittest.mock.patch("os.replace", side_effect=OSError(errno.EACCES, "Permission denied")):
self.assertEqual(loop.project_model("/srv/c"), loop.Stop(1, f"could not save the model in {saved}: Permission denied"))
self.assertEqual(cycle.project_model("/srv/c", paths, {}), Stop(1, f"could not save the model in {saved}: Permission denied"))
self.assertEqual(json.loads(saved.read_text()), {"srv/a": "claude-sonnet-5", "srv/b": "opus[1m]", "srv/d": "haiku"})
self.assertEqual(stat.S_IMODE(saved.stat().st_mode), 0o640)
self.assertEqual(sorted(os.listdir(saved.parent)), ["cache", "loop-claude-models.json"])
for shape in ({"fetchedAt": 3, "catalog": {"config": {"models": []}}}, {"fetchedAt": 3, "catalog": None}, {"fetchedAt": 3, "catalog": {"config": []}}, {"fetchedAt": 3, "catalog": {"config": {"models": "x"}}}):
catalog.joinpath("new.json").write_text(json.dumps(shape))
with self.subTest(shape=shape):
self.assertEqual(loop.catalog(), [])
self.assertEqual(cycle.catalog(catalog), [])
with (
unittest.mock.patch("sys.stdin.isatty", return_value=True),
unittest.mock.patch("sys.stdout.isatty", return_value=True),
unittest.mock.patch("builtins.input", side_effect=["1"]) as typed,
):
self.assertEqual(loop.project_model("/srv/e"), "1")
self.assertEqual(cycle.project_model("/srv/e", paths, {}), "1")
self.assertEqual(typed.call_args.args[0], "A name claude --model takes: ")
self.assertIn("no model catalog cached", sys.stderr.getvalue())
for broken in ("{", "[]", '{"srv/a": 1}'):
saved.write_text(broken)
with self.subTest(broken=broken):
stop = loop.project_model("/srv/a")
stop = cycle.project_model("/srv/a", paths, {})
self.assertEqual(stop.code, 1)
self.assertTrue(stop.reason.startswith(f"could not read {saved}: "))
self.assertEqual(saved.read_text(), broken)
@@ -222,10 +218,10 @@ class ProjectModel(unittest.TestCase):
class JudgePrompt(unittest.TestCase):
def test_hands_the_judge_the_tail_of_a_long_transcript(self):
prompt = loop.judge_prompt("task", "## Goals\n1. g", "early " * 20000 + "LATE")
prompt = cycle.judge_prompt("task", "## Goals\n1. g", "early " * 20000 + "LATE")
self.assertIn("LATE", prompt)
self.assertLess(prompt.count("early"), 20000)
self.assertTrue(prompt.endswith(loop.JUDGE_RULES))
self.assertTrue(prompt.endswith(cycle.JUDGE_RULES))
class Archive(unittest.TestCase):
@@ -233,9 +229,9 @@ class Archive(unittest.TestCase):
with tempfile.TemporaryDirectory() as root:
transcript = os.path.join(root, "session.jsonl")
pathlib.Path(transcript).write_text(json.dumps(assistant({"type": "text", "text": "said"})) + "\n")
loop.ARCHIVE = os.path.join(root, "deep", "archive")
loop.archive("/srv/a/b", transcript, "note")
[copy] = [os.path.join(folder, name) for folder, _, names in os.walk(loop.ARCHIVE) for name in names]
paths = paths_from(pathlib.Path(root), {"LOOP_CLAUDE_TRANSCRIPTS": os.path.join(root, "deep", "archive")})
cycle.archive("/srv/a/b", transcript, "note", paths)
[copy] = [os.path.join(folder, name) for folder, _, names in os.walk(paths.archive) for name in names]
self.assertEqual(stat.S_IMODE(os.stat(copy).st_mode), 0o600)
folder = os.path.dirname(copy)
while folder != root:
@@ -246,26 +242,27 @@ class Archive(unittest.TestCase):
class Said(unittest.TestCase):
def test_renders_text_and_tool_calls_and_nothing_else(self):
self.assertEqual(loop.said({"type": "text", "text": "hi"}), "hi")
self.assertEqual(loop.said({"type": "text", "text": " \n"}), "")
self.assertEqual(loop.said({"type": "tool_use", "name": "Bash", "input": {"command": "x" * 500}}, 20), '[tool Bash] {"command": "xxxxxxx')
self.assertEqual(loop.said("not a part"), "")
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"), "")
class DeleteTranscriptFiles(unittest.TestCase):
def test_deletes_the_transcript_and_its_siblings_so_the_session_is_gone(self):
with tempfile.TemporaryDirectory() as home, unittest.mock.patch.dict(os.environ, {"HOME": home}):
root = os.path.join(home, ".claude", "projects", "p")
with tempfile.TemporaryDirectory() as home:
projects = paths_from(pathlib.Path(home), {}).projects
root = os.path.join(projects, "p")
os.makedirs(root)
transcript = os.path.join(root, f"{SESSION_ID}.jsonl")
pathlib.Path(transcript).write_text("{}\n")
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(loop.session_open(SESSION_ID))
loop.delete_transcript_files(transcript)
self.assertTrue(cycle.session_open(projects, SESSION_ID))
cycle.delete_transcript_files(transcript)
self.assertEqual(os.listdir(root), [])
self.assertFalse(loop.session_open(SESSION_ID))
self.assertFalse(cycle.session_open(projects, SESSION_ID))
class Interrupt(unittest.TestCase):
@@ -274,14 +271,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(loop.interrupt(root, SESSION_ID, "m", transcript, "q?"), "stdin or stdout is not a terminal")
self.assertEqual(cycle.interrupt(root, SESSION_ID, "m", transcript, "q?", paths_from(pathlib.Path(root), {}), {}), "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(loop, checkouts=unittest.mock.DEFAULT, trust=unittest.mock.DEFAULT) as mocks,
unittest.mock.patch.multiple(cycle, checkouts=unittest.mock.DEFAULT, trust=unittest.mock.DEFAULT) as mocks,
unittest.mock.patch("subprocess.run") as run,
):
self.assertEqual(loop.interrupt(root, SESSION_ID, "m", transcript, "q?"), "the interrupt ended without the human typing anything")
self.assertEqual(cycle.interrupt(root, SESSION_ID, "m", transcript, "q?", paths_from(pathlib.Path(root), {}), {}), "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")
@@ -290,35 +287,35 @@ class Interrupt(unittest.TestCase):
handle.write(json.dumps(human("typed")) + "\n")
run.side_effect = type_a_turn
self.assertEqual(loop.interrupt(root, SESSION_ID, "m", transcript, "q?"), "")
self.assertEqual(cycle.interrupt(root, SESSION_ID, "m", transcript, "q?", paths_from(pathlib.Path(root), {}), {}), "")
class Trust(unittest.TestCase):
def test_says_why_the_config_cannot_be_read_and_records_only_what_is_new(self):
with tempfile.TemporaryDirectory() as home, unittest.mock.patch.dict(os.environ, {"HOME": home}), umask(0o022):
with tempfile.TemporaryDirectory() as home, umask(0o022):
config = pathlib.Path(home, ".claude.json")
with contextlib.redirect_stderr(io.StringIO()) as err:
loop.trust(["/a"])
cycle.trust(config, ["/a"])
self.assertEqual(err.getvalue(), f"could not read {config}: No such file or directory\n")
config.write_text("{")
with contextlib.redirect_stderr(io.StringIO()) as err:
loop.trust(["/a"])
cycle.trust(config, ["/a"])
self.assertIn(f"could not read {config}: ", err.getvalue())
for shape in ([], {"projects": []}, {"projects": {"/a": 1}}):
config.write_text(json.dumps(shape))
with contextlib.redirect_stderr(io.StringIO()) as err:
loop.trust(["/a"])
cycle.trust(config, ["/a"])
self.assertEqual(err.getvalue(), f"could not read {config}: not an object whose \"projects\" maps paths to objects\n")
self.assertEqual(json.loads(config.read_text()), shape)
data = {"other": 1, "projects": {"/a": {"hasTrustDialogAccepted": True, "kept": 2}}}
config.write_text(json.dumps(data))
config.chmod(0o600)
with contextlib.redirect_stderr(io.StringIO()) as err:
loop.trust(["/a"])
cycle.trust(config, ["/a"])
self.assertEqual(err.getvalue(), "")
self.assertEqual(json.loads(config.read_text()), data)
with contextlib.redirect_stderr(io.StringIO()) as err:
loop.trust(["/a", "/b"])
cycle.trust(config, ["/a", "/b"])
self.assertEqual(err.getvalue(), "trusted for the interrupt: /b\n")
data["projects"]["/b"] = {"hasTrustDialogAccepted": True}
self.assertEqual(json.loads(config.read_text()), data)
@@ -326,7 +323,7 @@ class Trust(unittest.TestCase):
contextlib.redirect_stderr(io.StringIO()) as err,
unittest.mock.patch("os.replace", side_effect=OSError(errno.EACCES, "Permission denied")),
):
loop.trust(["/c"])
cycle.trust(config, ["/c"])
self.assertEqual(err.getvalue(), f"could not write {config}: Permission denied\n")
self.assertEqual(json.loads(config.read_text()), data)
self.assertEqual(stat.S_IMODE(config.stat().st_mode), 0o600)
@@ -335,25 +332,25 @@ class Trust(unittest.TestCase):
class Parse(unittest.TestCase):
def test_yields_only_json_objects(self):
self.assertEqual(loop.parse('{"type": "user"}'), {"type": "user"})
self.assertIsNone(loop.parse("not json"))
self.assertIsNone(loop.parse("[1, 2]"))
self.assertEqual(cycle.parse('{"type": "user"}'), {"type": "user"})
self.assertIsNone(cycle.parse("not json"))
self.assertIsNone(cycle.parse("[1, 2]"))
class Grounded(unittest.TestCase):
def test_an_interrupt_must_quote_the_transcript(self):
self.assertTrue(loop.grounded({"interrupt": False, "evidence": ""}, "anything"))
self.assertTrue(loop.grounded({"interrupt": True, "evidence": "Needs you: x"}, "so.\n\nNeeds you: x\n"))
self.assertFalse(loop.grounded({"interrupt": True, "evidence": "invented"}, "the transcript"))
self.assertFalse(loop.grounded({"interrupt": True, "evidence": ""}, "the transcript"))
self.assertFalse(loop.grounded({"interrupt": True, "evidence": " "}, "the transcript"))
self.assertTrue(cycle.grounded({"interrupt": False, "evidence": ""}, "anything"))
self.assertTrue(cycle.grounded({"interrupt": True, "evidence": "Needs you: x"}, "so.\n\nNeeds you: x\n"))
self.assertFalse(cycle.grounded({"interrupt": True, "evidence": "invented"}, "the transcript"))
self.assertFalse(cycle.grounded({"interrupt": True, "evidence": ""}, "the transcript"))
self.assertFalse(cycle.grounded({"interrupt": True, "evidence": " "}, "the transcript"))
class Verdict(unittest.TestCase):
def test_needs_every_field_the_schema_requires(self):
self.assertTrue(loop.complete({"interrupt": False, "evidence": "", "finished": True, "question": ""}))
self.assertFalse(loop.complete({"interrupt": False}))
self.assertFalse(loop.complete(None))
self.assertTrue(cycle.complete({"interrupt": False, "evidence": "", "finished": True, "question": ""}))
self.assertFalse(cycle.complete({"interrupt": False}))
self.assertFalse(cycle.complete(None))
STUB_CLAUDE = """#!/usr/bin/env python3
@@ -392,7 +389,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(loop.run_worker(bin, []), failure)
self.assertEqual(cycle.run_worker(bin, []), failure)
class RunCycle(unittest.TestCase):
@@ -402,24 +399,25 @@ 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))
pathlib.Path(verdicts).write_text("fail continue finished unquoted continue")
loop.ARCHIVE = os.path.join(home, "archive")
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}
with unittest.mock.patch.dict(os.environ, environment), unittest.mock.patch("time.sleep") as sleep, unittest.mock.patch("sys.stdin.isatty", return_value=False):
for _ in range(3):
self.assertEqual(loop.run_cycle(home, "task", "premises", "A name", SESSION_ID, "claude-opus-5-5"), "")
self.assertEqual(cycle.run_cycle(home, "task", "premises", "claude-opus-5-5", paths, {}), Continue())
pathlib.Path(verdicts).write_text("interrupt")
with unittest.mock.patch("sys.stderr") as stderr:
self.assertEqual(loop.run_cycle(home, "task", "premises", "A name", SESSION_ID, "claude-opus-5-5"), loop.Stop(2, "stdin or stdout is not a terminal"))
self.assertIn(f"transcript: {loop.ARCHIVE}", "".join(str(call.args[0]) for call in stderr.write.call_args_list))
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(loop, "interrupt", return_value=""):
self.assertEqual(loop.run_cycle(home, "task", "premises", "A name", SESSION_ID, "claude-opus-5-5").code, 1)
with unittest.mock.patch.object(loop, "session_file", return_value=""):
self.assertEqual(loop.run_cycle(home, "task", "premises", "A name", SESSION_ID, "claude-opus-5-5"), loop.Stop(1, f"claude left no transcript for session {SESSION_ID}"))
with unittest.mock.patch("sys.stderr"), unittest.mock.patch.object(cycle, "interrupt", return_value=""):
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=""):
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)
stop = loop.run_cycle(home, "task", "premises", "A name", SESSION_ID, "claude-opus-5-5")
stop = cycle.run_cycle(home, "task", "premises", "claude-opus-5-5", paths, {})
self.assertEqual(stop.code, 1)
self.assertTrue(stop.reason.startswith("the judge "))
if plan.startswith("unquoted"):
@@ -428,74 +426,55 @@ class RunCycle(unittest.TestCase):
self.assertEqual({json.loads(line)[0] for line in pathlib.Path(calls).read_text().splitlines()}, {home})
starts = [args[args.index("-p") + 1:][:3] for args in map(json.loads, pathlib.Path(calls).read_text().splitlines()) if "--json-schema" not in args]
self.assertEqual([start[1] for start in starts], ["--name", "--resume", "--name", "--resume", "--resume", "--name", "--resume", "--resume"])
self.assertEqual(starts[1][2], SESSION_ID)
self.assertEqual(starts[1][2], str(session_id))
self.assertEqual(sleep.call_count, 8)
self.assertEqual({args[args.index("--model") + 1] for args in map(json.loads, pathlib.Path(calls).read_text().splitlines())}, {"claude-opus-5-5"})
class Reload(unittest.TestCase):
def test_runs_the_edited_file_before_trusting_it_and_hands_it_the_state_as_one_json_argument(self):
with tempfile.TemporaryDirectory() as root:
script = os.path.join(root, "loop-claude")
pathlib.Path(script).write_text(loop.RELOAD_BASELINE.replace("import glob\n", "import glob\nimport no_such_module\n"))
with unittest.mock.patch.object(loop, "__file__", script), unittest.mock.patch("os.execv") as execv:
loop.reload_if_edited(loop.LoopState(1, 0, "/r", "do it"))
execv.assert_not_called()
pathlib.Path(script).write_text(loop.RELOAD_BASELINE.replace("RELOAD_FLAG = ", "RELOAD_FLAG = \"x\" or "))
environment = dict(os.environ)
with unittest.mock.patch.object(loop, "__file__", script), unittest.mock.patch("os.execv") as execv:
loop.reload_if_edited(loop.LoopState(1, 2, "/r", "do it"))
execv.assert_called_once_with(sys.executable, [sys.executable, script, loop.RELOAD_FLAG, json.dumps({"cycle_number": 1, "failures": 2, "root": "/r", "task": "do it"})])
self.assertEqual(dict(os.environ), environment)
class Main(unittest.TestCase):
def test_exits_only_here_with_the_stop_the_loop_returned(self):
for argv, code, stream in ((["--help"], 0, "stdout"), ([], 1, "stderr"), ([loop.RELOAD_FLAG, "3"], 1, "stderr")):
with self.subTest(argv=argv), unittest.mock.patch.object(sys, "argv", ["loop-claude", *argv]), contextlib.redirect_stdout(io.StringIO()) as out, contextlib.redirect_stderr(io.StringIO()) as err, self.assertRaises(SystemExit) as stopped:
loop.main()
self.assertEqual(stopped.exception.code, code)
self.assertEqual({"stdout": out, "stderr": err}[stream].getvalue(), loop.run_loop(argv).reason + "\n")
with unittest.mock.patch.object(loop, "run_loop", side_effect=KeyboardInterrupt), self.assertRaises(SystemExit) as stopped:
loop.main()
self.assertEqual(stopped.exception.code, 130)
def test_returns_the_exit_code_of_the_stop_the_loop_returned(self):
for argv, code, stream in ((["--help"], 0, "stdout"), ([], 1, "stderr"), ([main.RELOAD_FLAG, "3"], 1, "stderr")):
with self.subTest(argv=argv), contextlib.redirect_stdout(io.StringIO()) as out, contextlib.redirect_stderr(io.StringIO()) as err:
self.assertEqual(main.main(argv, {}, PATHS, LAUNCHER), code)
self.assertEqual({"stdout": out, "stderr": err}[stream].getvalue(), main.loop_state(argv).reason + "\n")
with unittest.mock.patch.object(main, "run_loop", side_effect=KeyboardInterrupt):
self.assertEqual(main.main(["t"], {}, PATHS, LAUNCHER), 130)
class RunLoop(unittest.TestCase):
def test_stops_naming_the_reload_when_it_hands_over_anything_but_the_state_with_a_task(self):
for handed in (["3", "2", "/r", "do it"], ["3"], ["[1]"], [json.dumps({"cycle_number": 3, "failures": 0, "root": "/r"})], [json.dumps({"cycle_number": 3, "failures": 0, "root": "/r", "task": ""})], [json.dumps({"cycle_number": "3", "failures": 0, "root": "/r", "task": "do it"})], [json.dumps({"cycle_number": 3, "failures": 0, "root": "", "task": "do it"})], [json.dumps({"cycle_number": 3, "failures": 0, "root": "/r", "task": "do it", "turns": 1})]):
with self.subTest(handed=handed):
self.assertEqual(loop.run_loop([loop.RELOAD_FLAG, *handed]), loop.Stop(1, f"the reload cannot read the loop's state from {handed}; rerun loop-claude <task>"))
self.assertEqual(main.loop_state([main.RELOAD_FLAG, *handed]), Stop(1, f"the reload cannot read the loop's state from {handed}; rerun loop-claude <task>"))
def test_resumes_the_root_and_counters_a_reload_handed_over(self):
patches = [unittest.mock.patch.object(loop, name) for name in ("checkout_root", "read_premises", "reload_if_edited", "run_cycle", "project_model")]
stopped = loop.Stop(1, "stopped")
patches = [unittest.mock.patch.object(main, name) for name in ("checkout_root", "read_premises", "reload_if_edited", "run_cycle", "project_model")]
stopped = Stop(1, "stopped")
with contextlib.ExitStack() as stack:
mocks = [stack.enter_context(patch) for patch in patches]
stack.enter_context(unittest.mock.patch.object(sys, "stdout", io.StringIO()))
mocks[3].return_value = stopped
self.assertEqual(loop.run_loop([loop.RELOAD_FLAG, json.dumps({"cycle_number": 3, "failures": 2, "root": "/r", "task": "do it"})]), stopped)
self.assertEqual(main.run_loop([main.RELOAD_FLAG, json.dumps({"cycle_number": 3, "failures": 2, "root": "/r", "task": "do it"})], {}, PATHS, LAUNCHER), stopped)
mocks[0].assert_not_called()
mocks[1].assert_called_once_with("/r")
mocks[2].assert_called_once_with(loop.LoopState(3, 2, "/r", "do it"))
self.assertEqual(mocks[2].call_args.args[2], main.LoopState(3, 2, "/r", "do it"))
self.assertEqual(mocks[3].call_args.args[0], "/r")
mocks[4].assert_called_once_with("/r")
self.assertEqual(mocks[3].call_args.args[-1], mocks[4].return_value)
mocks[4].assert_called_once_with("/r", PATHS, {})
self.assertEqual(mocks[3].call_args.args[3], mocks[4].return_value)
mocks[0].return_value = "/s"
self.assertEqual(loop.run_loop(["do", "it"]), stopped)
self.assertEqual(main.run_loop(["do", "it"], {}, PATHS, LAUNCHER), stopped)
mocks[0].assert_called_once_with()
mocks[1].assert_called_with("/s")
self.assertIn("=== cycle 4 ===", sys.stdout.getvalue())
for leaf in (0, 1, 4):
with self.subTest(leaf=leaf):
mocks[leaf].return_value = loop.Stop(2, f"leaf {leaf}")
self.assertEqual(loop.run_loop(["do it"]), mocks[leaf].return_value)
mocks[leaf].return_value = Stop(2, f"leaf {leaf}")
self.assertEqual(main.run_loop(["do it"], {}, PATHS, LAUNCHER), mocks[leaf].return_value)
mocks[leaf].return_value = "/s"
mocks[3].return_value = None
mocks[3].side_effect = ["claude exited 3"] * 3
mocks[3].side_effect = [Retry("claude exited 3")] * 3
stack.enter_context(unittest.mock.patch.object(sys, "stderr", io.StringIO()))
sleep = stack.enter_context(unittest.mock.patch("time.sleep"))
self.assertEqual(loop.run_loop([loop.RELOAD_FLAG, json.dumps({"cycle_number": 3, "failures": 0, "root": "/r", "task": "do it"})]), loop.Stop(1, "the worker failed three times running: claude exited 3"))
self.assertEqual(main.run_loop([main.RELOAD_FLAG, json.dumps({"cycle_number": 3, "failures": 0, "root": "/r", "task": "do it"})], {}, PATHS, LAUNCHER), Stop(1, "the worker failed three times running: claude exited 3"))
self.assertIn("retrying the worker in a minute: claude exited 3", sys.stderr.getvalue())
self.assertEqual(sleep.call_count, 2)