Move loop-claude's internal-function tests into the black-box tests, keeping unit tests of the pure parsers
This commit is contained in:
+3
-410
@@ -1,30 +1,14 @@
|
||||
import contextlib
|
||||
import errno
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import shutil
|
||||
import stat
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
import unittest.mock
|
||||
import uuid
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
|
||||
|
||||
from loop_claude import checkout, cycle, interrupt, judge, main, models, premises, reload, session, transcript, trust, worker
|
||||
from loop_claude.outcome import Continue, Failure, Retry, Stop
|
||||
from loop_claude.paths import paths_from
|
||||
from loop_claude import judge, main, premises, transcript
|
||||
from loop_claude.outcome import Stop
|
||||
|
||||
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)
|
||||
OPUS = models.Models("claude-opus-5-5", "claude-opus-5-5")
|
||||
|
||||
|
||||
def assistant(*parts):
|
||||
@@ -35,52 +19,12 @@ def human(content):
|
||||
return {"type": "user", "message": {"content": content}}
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def umask(mask):
|
||||
previous = os.umask(mask)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
os.umask(previous)
|
||||
|
||||
|
||||
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(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 = premises.read_premises(root)
|
||||
self.assertEqual(stop.code, 1)
|
||||
self.assertTrue(stop.reason.endswith("no premises."))
|
||||
return stop.reason
|
||||
|
||||
def test_names_what_is_missing(self):
|
||||
texts = {
|
||||
"# T\n## Audience\nme\n": "no ## Goals heading",
|
||||
"# T\n## Goals\n\n## Audience\nme\n": "nothing under ## Goals",
|
||||
"# T\n## Goals\n1. g\n": "no ## Audience heading",
|
||||
"# T\n## Goals\n1. g\n## Audience\n": "nothing under ## Audience",
|
||||
"# T\n## Goals\n1. g\n## Audience\nme\n## Goals\n": "## Goals more than once",
|
||||
}
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
readme = os.path.join(root, "README.md")
|
||||
self.assertIn(f"README.md in {root}: No such file or directory", self.exit_message(root))
|
||||
os.mkdir(readme)
|
||||
self.assertIn("Is a directory", self.exit_message(root))
|
||||
os.rmdir(readme)
|
||||
pathlib.Path(readme).write_bytes(b"# T\n## Goals\n1. g\xff\n## Audience\nme\n")
|
||||
self.assertIn("README.md is not UTF-8 on line 3", self.exit_message(root))
|
||||
for text, missing in texts.items():
|
||||
with self.subTest(missing=missing):
|
||||
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(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 = transcript.render([
|
||||
@@ -110,138 +54,6 @@ class HumanTurns(unittest.TestCase):
|
||||
]), 2)
|
||||
|
||||
|
||||
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(checkout.checkout_root(os.getcwd()).code, 1)
|
||||
subprocess.run(["git", "init", "-q"], check=True)
|
||||
os.makedirs("a/b")
|
||||
with contextlib.chdir("a/b"):
|
||||
self.assertEqual(checkout.checkout_root(os.getcwd()), root)
|
||||
subprocess.run(["git", "init", "-q", "other"], check=True)
|
||||
with contextlib.chdir("other"):
|
||||
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):
|
||||
code = pathlib.Path("/h/code")
|
||||
self.assertEqual(checkout.project_name("/h/code/a/b", code), "a/b")
|
||||
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(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 = 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 = 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])
|
||||
|
||||
|
||||
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.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 = models.project_models("/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("sys.stdin.isatty", return_value=False):
|
||||
self.assertEqual(models.project_models("/srv/a", paths, {"LOOP_CLAUDE_JUDGE_MODEL": "j", "LOOP_CLAUDE_WORKER_MODEL": "w"}), models.Models("j", "w"))
|
||||
self.assertEqual(models.project_models("/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(models.project_models("/srv/a", paths, {}), models.Models("claude-sonnet-5", "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())
|
||||
self.assertIn("srv/a runs on claude-sonnet-5", sys.stderr.getvalue())
|
||||
self.assertNotIn("claude-opus-5)", sys.stderr.getvalue())
|
||||
self.assertEqual(stat.S_IMODE(saved.stat().st_mode), 0o600)
|
||||
saved.chmod(0o640)
|
||||
def saved_elsewhere_while_asking(prompt):
|
||||
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(models.project_models("/srv/b", paths, {}), models.Models("opus[1m]", "opus[1m]"))
|
||||
self.assertEqual(models.project_models("/srv/a", paths, {}), models.Models("claude-sonnet-5", "claude-sonnet-5"))
|
||||
self.assertEqual(models.project_models("/srv/a", paths, {"LOOP_CLAUDE_WORKER_MODEL": "w"}), models.Models("claude-sonnet-5", "w"))
|
||||
self.assertEqual(typed.call_count, 4)
|
||||
typed.side_effect = EOFError
|
||||
self.assertEqual(models.project_models("/srv/c", paths, {}), Stop(2, "the human is needed to pick srv/c's model, but the input ended"))
|
||||
typed.side_effect = ["sonnet"]
|
||||
with unittest.mock.patch("os.replace", side_effect=OSError(errno.EACCES, "Permission denied")):
|
||||
self.assertEqual(models.project_models("/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(models.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(models.project_models("/srv/e", paths, {}), models.Models("1", "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 = models.project_models("/srv/a", paths, {})
|
||||
self.assertEqual(stop.code, 1)
|
||||
self.assertTrue(stop.reason.startswith(f"could not read {saved}: "))
|
||||
self.assertEqual(saved.read_text(), broken)
|
||||
|
||||
|
||||
class JudgePrompt(unittest.TestCase):
|
||||
def test_hands_the_judge_the_tail_of_a_long_transcript(self):
|
||||
prompt = judge.judge_prompt("task", "## Goals\n1. g", "early " * 20000 + "LATE")
|
||||
self.assertIn("LATE", prompt)
|
||||
self.assertLess(prompt.count("early"), 20000)
|
||||
self.assertTrue(prompt.endswith(judge.JUDGE_RULES))
|
||||
|
||||
|
||||
class Archive(unittest.TestCase):
|
||||
def test_keeps_one_copy_per_content_and_every_folder_it_creates_as_private_as_the_transcript(self):
|
||||
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")
|
||||
paths = paths_from(pathlib.Path(root), {"LOOP_CLAUDE_TRANSCRIPTS": os.path.join(root, "deep", "archive")})
|
||||
with unittest.mock.patch("sys.stderr"):
|
||||
for _ in range(2):
|
||||
self.assertIsNone(cycle.archive("/srv/a/b", transcript, "note", paths))
|
||||
copies = [os.path.join(folder, name) for folder, _, names in os.walk(paths.archive) for name in names]
|
||||
self.assertEqual(len(copies), 2)
|
||||
for copy in copies:
|
||||
self.assertEqual(stat.S_IMODE(os.stat(copy).st_mode), 0o600)
|
||||
folder = os.path.dirname(copies[0])
|
||||
while folder != root:
|
||||
self.assertEqual(stat.S_IMODE(os.stat(folder).st_mode), 0o700, folder)
|
||||
folder = os.path.dirname(folder)
|
||||
|
||||
|
||||
class Said(unittest.TestCase):
|
||||
def test_renders_text_and_tool_calls_and_nothing_else(self):
|
||||
self.assertEqual(transcript.said({"type": "text", "text": "hi"}), "hi")
|
||||
@@ -250,89 +62,6 @@ class Said(unittest.TestCase):
|
||||
self.assertEqual(transcript.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:
|
||||
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")
|
||||
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.assertEqual(session.transcript_file(located), "")
|
||||
|
||||
|
||||
class Interrupt(unittest.TestCase):
|
||||
def test_says_whether_no_terminal_or_nothing_typed_ended_it(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
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(interrupt.interrupt(root, SESSION_ID, "m", transcript, "q?", paths_from(pathlib.Path(root), {})), Stop(2, "the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun loop-claude on 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(interrupt, checkouts=unittest.mock.DEFAULT, trust=unittest.mock.DEFAULT) as mocks,
|
||||
unittest.mock.patch("subprocess.run") as run,
|
||||
):
|
||||
self.assertEqual(interrupt.interrupt(root, SESSION_ID, "m", transcript, "q?", paths_from(pathlib.Path(root), {})), Stop(2, "the human is needed to answer the question above, but the interrupt ended with nothing typed"))
|
||||
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")
|
||||
def type_a_turn(*args, **kwargs):
|
||||
with open(transcript, "a") as handle:
|
||||
handle.write(json.dumps(human("typed")) + "\n")
|
||||
|
||||
run.side_effect = type_a_turn
|
||||
self.assertIsNone(interrupt.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, umask(0o022):
|
||||
config = pathlib.Path(home, ".claude.json")
|
||||
with contextlib.redirect_stderr(io.StringIO()) as err:
|
||||
trust.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:
|
||||
trust.trust(config, ["/a"])
|
||||
self.assertIn(f"could not read {config}: ", err.getvalue())
|
||||
for shape, said in (([], 'not an object whose "projects" is an object'), ({"projects": []}, 'not an object whose "projects" is an object'), ({"projects": {"/a": 1}}, 'projects["/a"] is not an object')):
|
||||
config.write_text(json.dumps(shape))
|
||||
with contextlib.redirect_stderr(io.StringIO()) as err:
|
||||
trust.trust(config, ["/a"])
|
||||
self.assertEqual(err.getvalue(), f"could not read {config}: {said}\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:
|
||||
trust.trust(config, ["/a"])
|
||||
self.assertEqual(err.getvalue(), "")
|
||||
self.assertEqual(json.loads(config.read_text()), data)
|
||||
with contextlib.redirect_stderr(io.StringIO()) as err:
|
||||
trust.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)
|
||||
with (
|
||||
contextlib.redirect_stderr(io.StringIO()) as err,
|
||||
unittest.mock.patch("os.replace", side_effect=OSError(errno.EACCES, "Permission denied")),
|
||||
):
|
||||
trust.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)
|
||||
self.assertEqual(os.listdir(home), [".claude.json"])
|
||||
|
||||
|
||||
class Parse(unittest.TestCase):
|
||||
def test_yields_only_json_objects(self):
|
||||
self.assertEqual(transcript.parse('{"type": "user"}'), {"type": "user"})
|
||||
@@ -358,148 +87,12 @@ class Verdict(unittest.TestCase):
|
||||
self.assertEqual(judge.incomplete(None), "the judge returned no verdict")
|
||||
|
||||
|
||||
STUB_CLAUDE = """#!/usr/bin/env python3
|
||||
import json, os, pathlib, sys
|
||||
args = sys.argv[1:]
|
||||
with open(os.environ["STUB_CALLS"], "a") as calls:
|
||||
calls.write(json.dumps([os.getcwd(), *args]) + "\\n")
|
||||
if "--json-schema" in args:
|
||||
plan = pathlib.Path(os.environ["STUB_VERDICTS"]).read_text().split()
|
||||
pathlib.Path(os.environ["STUB_VERDICTS"]).write_text(" ".join(plan[1:]))
|
||||
if plan[0] == "fail":
|
||||
sys.exit(1)
|
||||
interrupt = plan[0] in ("interrupt", "unquoted")
|
||||
print(json.dumps({"structured_output": {"interrupt": interrupt, "evidence": {"interrupt": "worked", "unquoted": "invented"}.get(plan[0], "worked"), "finished": plan[0] == "finished", "question": "q?" if interrupt else ""}}))
|
||||
else:
|
||||
flag = "--session-id" if "--session-id" in args else "--resume"
|
||||
folder = os.path.expanduser("~/.claude/projects/p")
|
||||
os.makedirs(folder, exist_ok=True)
|
||||
with open(os.path.join(folder, args[args.index(flag) + 1] + ".jsonl"), "a") as transcript:
|
||||
transcript.write(json.dumps({"type": "assistant", "message": {"content": [{"type": "text", "text": "worked"}]}}) + "\\n")
|
||||
print(json.dumps({"type": "result"}))
|
||||
"""
|
||||
|
||||
|
||||
class RunWorker(unittest.TestCase):
|
||||
def test_says_whether_a_non_zero_exit_or_a_missing_result_event_failed_it(self):
|
||||
with tempfile.TemporaryDirectory() as bin:
|
||||
stub = os.path.join(bin, "claude")
|
||||
scripts = {
|
||||
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)",
|
||||
}
|
||||
with unittest.mock.patch.dict(os.environ, {"PATH": f"{bin}:{os.environ['PATH']}"}), unittest.mock.patch.object(sys, "stdout", io.StringIO()):
|
||||
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(worker.run_worker(bin, []), failure and Failure(failure))
|
||||
|
||||
|
||||
class RunCycle(unittest.TestCase):
|
||||
def test_resumes_until_the_judge_calls_the_chunk_finished_and_rejudges_a_failed_or_unquoted_verdict(self):
|
||||
with tempfile.TemporaryDirectory() as home:
|
||||
stub = os.path.join(home, "claude")
|
||||
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 = 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}
|
||||
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(cycle.run_cycle(home, "task", "premises", OPUS, paths), Continue())
|
||||
pathlib.Path(verdicts).write_text("interrupt")
|
||||
with unittest.mock.patch("sys.stderr") as stderr:
|
||||
self.assertEqual(cycle.run_cycle(home, "task", "premises", OPUS, paths), Stop(2, "the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun loop-claude on 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=None):
|
||||
self.assertEqual(cycle.run_cycle(home, "task", "premises", OPUS, paths).code, 1)
|
||||
with unittest.mock.patch.object(cycle, "transcript_file", return_value=""):
|
||||
self.assertEqual(cycle.run_cycle(home, "task", "premises", OPUS, 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 = cycle.run_cycle(home, "task", "premises", OPUS, paths)
|
||||
self.assertEqual(stop.code, 1)
|
||||
self.assertTrue(stop.reason.startswith("the judge "))
|
||||
if plan.startswith("unquoted"):
|
||||
self.assertIn("for the question: q?", stop.reason)
|
||||
self.assertEqual(pathlib.Path(verdicts).read_text(), "")
|
||||
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], 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_an_edited_package_file_reloads_once_the_launcher_answers_help(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
copy = pathlib.Path(root, "bin")
|
||||
shutil.copytree(LAUNCHER.parent, copy, ignore=shutil.ignore_patterns("__pycache__", "test_*"))
|
||||
launcher, edited = copy / "loop-claude", copy / "loop_claude" / "cycle.py"
|
||||
state = main.LoopState(1, 2, "/r", "do it")
|
||||
with unittest.mock.patch("os.execv") as execv, contextlib.redirect_stderr(io.StringIO()) as err:
|
||||
baseline = reload.fingerprint(launcher)
|
||||
edited.write_text(edited.read_text() + "\ndef\n")
|
||||
reload.reload_if_edited(launcher, baseline, state)
|
||||
execv.assert_not_called()
|
||||
self.assertIn("keeping the running script", err.getvalue())
|
||||
edited.write_text(edited.read_text().replace("\ndef\n", "\n# edited\n"))
|
||||
reload.reload_if_edited(launcher, baseline, state)
|
||||
execv.assert_called_once_with(sys.executable, [sys.executable, str(launcher), main.RELOAD_FLAG, json.dumps({"cycle_number": 1, "failures": 2, "root": "/r", "task": "do it"})])
|
||||
|
||||
|
||||
class Main(unittest.TestCase):
|
||||
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, CWD), code)
|
||||
self.assertEqual({"stdout": out, "stderr": err}[stream].getvalue(), main.loop_state(argv, CWD).reason + "\n")
|
||||
with unittest.mock.patch.object(main, "run_loop", side_effect=KeyboardInterrupt):
|
||||
self.assertEqual(main.main(["t"], {}, PATHS, LAUNCHER, CWD), 130)
|
||||
|
||||
|
||||
class RunLoop(unittest.TestCase):
|
||||
class LoopState(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(main.loop_state([main.RELOAD_FLAG, *handed], CWD), 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(main, name) for name in ("checkout_root", "read_premises", "reload_if_edited", "run_cycle", "project_models")]
|
||||
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(main.run_loop([main.RELOAD_FLAG, json.dumps({"cycle_number": 3, "failures": 2, "root": "/r", "task": "do it"})], {}, PATHS, LAUNCHER, CWD), stopped)
|
||||
mocks[0].assert_not_called()
|
||||
mocks[1].assert_called_once_with("/r")
|
||||
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", PATHS, {})
|
||||
self.assertEqual(mocks[3].call_args.args[3], mocks[4].return_value)
|
||||
mocks[0].return_value = "/s"
|
||||
self.assertEqual(main.run_loop(["do", "it"], {}, PATHS, LAUNCHER, CWD), stopped)
|
||||
mocks[0].assert_called_once_with(CWD)
|
||||
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 = Stop(2, f"leaf {leaf}")
|
||||
self.assertEqual(main.run_loop(["do it"], {}, PATHS, LAUNCHER, CWD), mocks[leaf].return_value)
|
||||
mocks[leaf].return_value = "/s"
|
||||
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(main.run_loop([main.RELOAD_FLAG, json.dumps({"cycle_number": 3, "failures": 0, "root": "/r", "task": "do it"})], {}, PATHS, LAUNCHER, CWD), 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)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -25,7 +25,7 @@ argv = sys.argv[1:]
|
||||
role = "judge" if "--json-schema" in argv else "worker" if "-p" in argv else "interrupt"
|
||||
scenario = pathlib.Path(os.environ["FAKE_CLAUDE_SCENARIO"])
|
||||
steps = json.loads(scenario.read_text())
|
||||
call = {{"argv": argv, "role": role}}
|
||||
call = {{"argv": argv, "cwd": os.getcwd(), "role": role}}
|
||||
if role == "judge":
|
||||
call["stdin"] = sys.stdin.read()
|
||||
with open(os.environ["FAKE_CLAUDE_LOG"], "a") as log:
|
||||
@@ -62,6 +62,10 @@ if role == "worker":
|
||||
with open(transcript(), "ab") as handle:
|
||||
handle.write(step.get("raw", "").encode("latin-1"))
|
||||
append(said)
|
||||
if step.get("siblings"):
|
||||
for sibling in (f"{{session()}}/subagents", f"{{session()}}.superseded-1/tool-results"):
|
||||
(transcript().parent / sibling).mkdir(parents=True, exist_ok=True)
|
||||
(transcript().parent / f"{{session()}}.orphaned-1-ab.jsonl").write_text("{{}}\\n")
|
||||
if "append" in step:
|
||||
with open(os.environ["FAKE_CLAUDE_EDIT"], "a") as script:
|
||||
script.write(step["append"])
|
||||
@@ -171,7 +175,7 @@ class Checkout:
|
||||
def git(self, *args):
|
||||
subprocess.run(["git", "-c", "user.name=t", "-c", "user.email=t@example.com", *args], capture_output=True, check=True, cwd=self.root, env=self.env)
|
||||
|
||||
def run(self, steps, argv=(TASK,), cwd=None, terminal_input=None, stdout_on_terminal=True):
|
||||
def run(self, steps, argv=(TASK,), cwd=None, terminal_input=None, stdout_on_terminal=True, before_typing=None):
|
||||
for name in ("FAKE_CLAUDE_LOG", "LOOP_TEST_LOG"):
|
||||
pathlib.Path(self.env[name]).unlink(missing_ok=True)
|
||||
pathlib.Path(self.env["FAKE_CLAUDE_SCENARIO"]).write_text(json.dumps(steps))
|
||||
@@ -181,7 +185,7 @@ class Checkout:
|
||||
done = subprocess.run(command, capture_output=True, cwd=cwd, env=self.env, stdin=subprocess.DEVNULL, text=True, timeout=60)
|
||||
code, stdout, stderr = done.returncode, done.stdout, done.stderr
|
||||
else:
|
||||
code, stdout, stderr = self.run_on_terminal(command, cwd, terminal_input, stdout_on_terminal)
|
||||
code, stdout, stderr = self.run_on_terminal(command, cwd, terminal_input, stdout_on_terminal, before_typing)
|
||||
started = lines(pathlib.Path(self.env["LOOP_TEST_LOG"]))
|
||||
return Run(
|
||||
calls=lines(pathlib.Path(self.env["FAKE_CLAUDE_LOG"])),
|
||||
@@ -192,7 +196,8 @@ class Checkout:
|
||||
stdout=stdout,
|
||||
)
|
||||
|
||||
def run_on_terminal(self, command, cwd, typed, stdout_on_terminal):
|
||||
def run_on_terminal(self, command, cwd, typed, stdout_on_terminal, before_typing):
|
||||
"""Types the input at once, or once stderr shows before_typing's prompt and its callback has run."""
|
||||
controller, terminal = pty.openpty()
|
||||
with tempfile.TemporaryFile() as stderr, tempfile.TemporaryFile() as stdout:
|
||||
try:
|
||||
@@ -200,7 +205,9 @@ class Checkout:
|
||||
finally:
|
||||
os.close(terminal)
|
||||
try:
|
||||
os.write(controller, typed.encode())
|
||||
prompt, callback = before_typing or (None, None)
|
||||
if prompt is None:
|
||||
os.write(controller, typed.encode())
|
||||
output, deadline = b"", time.monotonic() + 60
|
||||
while time.monotonic() < deadline:
|
||||
if select.select([controller], [], [], 1)[0]:
|
||||
@@ -211,6 +218,10 @@ class Checkout:
|
||||
if not chunk:
|
||||
break
|
||||
output += chunk
|
||||
if prompt is not None and prompt.encode() in os.pread(stderr.fileno(), 1 << 20, 0):
|
||||
callback()
|
||||
os.write(controller, typed.encode())
|
||||
prompt = None
|
||||
code = proc.wait(timeout=10)
|
||||
finally:
|
||||
os.close(controller)
|
||||
@@ -231,11 +242,13 @@ class Checkout:
|
||||
return sorted((self.home / ".claude" / "projects").glob("*/*.jsonl"))
|
||||
|
||||
def archive(self):
|
||||
return self.home / ".claude" / "loop-claude-transcripts"
|
||||
return pathlib.Path(self.env.get("LOOP_CLAUDE_TRANSCRIPTS", self.home / ".claude" / "loop-claude-transcripts"))
|
||||
|
||||
def archived(self):
|
||||
"""Each archived transcript's verdict, after checking the copy is named by its content hash."""
|
||||
verdicts = {}
|
||||
for folder in (self.archive(), self.archive() / "proj"):
|
||||
self.test.assertEqual(stat.S_IMODE(folder.stat().st_mode), 0o700, folder)
|
||||
for copy in sorted((self.archive() / "proj").glob("*.jsonl")):
|
||||
self.test.assertEqual(copy.stem, hashlib.sha256(copy.read_bytes()).hexdigest())
|
||||
verdict = copy.with_suffix(".verdict.md")
|
||||
@@ -280,16 +293,32 @@ class Premises(unittest.TestCase):
|
||||
run = checkout.run([worker()], cwd=checkout.root / "sub")
|
||||
self.assertEqual((run.code, run.calls), (1, []))
|
||||
self.assertEqual(run.stderr.strip(), said.format(root=checkout.root))
|
||||
(checkout.root / "README.md").unlink()
|
||||
(checkout.root / "README.md").mkdir()
|
||||
run = checkout.run([worker()])
|
||||
self.assertEqual((run.code, run.calls), (1, []))
|
||||
self.assertEqual(run.stderr.strip(), f"README.md in {checkout.root}: Is a directory - no premises.")
|
||||
|
||||
def test_names_the_session_by_the_checkout_relative_to_code_or_else_to_the_root(self):
|
||||
checkout = Checkout(self)
|
||||
for root in (checkout.temp / "elsewhere", checkout.home / "code"):
|
||||
with self.subTest(root=root):
|
||||
root.mkdir(exist_ok=True)
|
||||
(root / "README.md").write_text(PREMISES)
|
||||
checkout.git("init", "--quiet", str(root))
|
||||
run = checkout.run([worker()], cwd=root)
|
||||
self.assertEqual(argument(run.calls[0], "--name"), f"A {str(root).lstrip('/')} loop-claude")
|
||||
|
||||
|
||||
class Cycles(unittest.TestCase):
|
||||
def test_resumes_the_session_while_unfinished_and_starts_it_fresh_after_finishing(self):
|
||||
checkout = Checkout(self)
|
||||
(checkout.root / "sub").mkdir()
|
||||
run = checkout.run([
|
||||
worker(say="started"), judge(evidence="started"),
|
||||
worker(say="landed-it"), judge(finished=True, evidence="landed-it"),
|
||||
worker(say="landed-it", siblings=True), judge(finished=True, evidence="landed-it"),
|
||||
worker(say="next chunk"),
|
||||
])
|
||||
], cwd=checkout.root / "sub")
|
||||
self.assertEqual(run.code, 130)
|
||||
self.assertEqual(run.roles(), ["worker", "judge", "worker", "judge", "worker", "judge"])
|
||||
workers = [call for call in run.calls if call["role"] == "worker"]
|
||||
@@ -298,11 +327,15 @@ class Cycles(unittest.TestCase):
|
||||
self.assertEqual(argument(workers[1], "--resume"), session)
|
||||
self.assertIsNone(argument(workers[1], "--session-id"))
|
||||
self.assertEqual(argument(workers[2], "--session-id"), session)
|
||||
self.assertTrue(argument(workers[0], "-p").startswith(TASK))
|
||||
self.assertTrue(argument(workers[0], "-p").startswith(f"{TASK}\n\nContinue any open draft PR"))
|
||||
self.assertNotIn(TASK, argument(workers[1], "-p"))
|
||||
self.assertEqual({call["cwd"] for call in run.calls}, {str(checkout.root)})
|
||||
self.assertIn("1. Work.", run.calls[1]["stdin"])
|
||||
self.assertEqual({argument(call, "--model") for call in workers}, {"worker-model"})
|
||||
self.assertEqual({argument(call, "--model") for call in run.calls if call["role"] == "judge"}, {"judge-model"})
|
||||
self.assertIn("landed-it", run.calls[3]["stdin"])
|
||||
self.assertNotIn("landed-it", run.calls[5]["stdin"])
|
||||
self.assertEqual([path.name for path in checkout.transcripts()[0].parent.iterdir()], [checkout.transcripts()[0].name])
|
||||
self.assertIn("=== cycle 3 ===", run.stdout)
|
||||
[(copy, verdict)] = checkout.archived().items()
|
||||
self.assertIn('"text": "landed-it"', copy)
|
||||
@@ -365,6 +398,12 @@ class Cycles(unittest.TestCase):
|
||||
self.assertEqual(run.sleeps, [60, 60])
|
||||
self.assertEqual(run.stderr.strip().splitlines()[-1], "the judge failed three times running: could not start claude: No such file or directory")
|
||||
|
||||
def test_hands_the_judge_the_tail_of_a_long_transcript(self):
|
||||
checkout = Checkout(self)
|
||||
run = checkout.run([worker(say="early " * 20000 + "LATE")])
|
||||
self.assertIn("LATE", run.calls[1]["stdin"])
|
||||
self.assertLess(run.calls[1]["stdin"].count("early"), 20000)
|
||||
|
||||
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"
|
||||
@@ -398,6 +437,7 @@ class Cycles(unittest.TestCase):
|
||||
class Interrupt(unittest.TestCase):
|
||||
def test_exits_2_off_a_terminal_and_resumes_on_the_next_run(self):
|
||||
checkout = Checkout(self)
|
||||
checkout.env["LOOP_CLAUDE_TRANSCRIPTS"] = str(checkout.temp / "deep" / "archive")
|
||||
steps = [worker(say="Shall I use A or B?"), judge(interrupt=True, evidence="Shall I use A or B?", question="A or B?")]
|
||||
run = checkout.run(steps)
|
||||
self.assertEqual((run.code, run.roles()), (2, ["worker", "judge"]))
|
||||
@@ -405,12 +445,17 @@ class Interrupt(unittest.TestCase):
|
||||
[(copy, verdict)] = checkout.archived().items()
|
||||
self.assertEqual(copy, (checkout.transcripts()[0]).read_text())
|
||||
self.assertEqual(verdict, f"Task: {TASK}\n\nVerdict: interrupt\n\nA or B?\n")
|
||||
self.assertEqual(stat.S_IMODE((checkout.temp / "deep").stat().st_mode), 0o700)
|
||||
self.assertIn(f"transcript: {checkout.archive() / 'proj'}/", run.stderr)
|
||||
session = argument(run.calls[0], "--session-id")
|
||||
run = checkout.run(steps, terminal_input="", stdout_on_terminal=False)
|
||||
self.assertEqual((run.code, run.roles()), (2, ["worker", "judge"]))
|
||||
self.assertEqual(argument(run.calls[0], "--resume"), session)
|
||||
self.assertEqual(len(checkout.archived()), 2)
|
||||
self.assertEqual(run.stderr.strip().splitlines()[-1], "the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun loop-claude on a terminal")
|
||||
run = checkout.run([worker(transcript=False), steps[1]])
|
||||
self.assertEqual(run.code, 2)
|
||||
self.assertEqual(len(checkout.archived()), 2)
|
||||
|
||||
def test_hands_the_terminal_over_and_exits_2_when_nothing_is_typed(self):
|
||||
checkout = Checkout(self)
|
||||
@@ -432,6 +477,7 @@ class Interrupt(unittest.TestCase):
|
||||
self.assertEqual(trusted["projects"][str(checkout.root)], {"hasTrustDialogAccepted": True, "kept": True})
|
||||
self.assertEqual(trusted["projects"][str(checkout.home / "code" / "proj-wt")], {"hasTrustDialogAccepted": True})
|
||||
self.assertEqual(stat.S_IMODE(checkout.claude_json().stat().st_mode), 0o644)
|
||||
self.assertIn(f"trusted for the interrupt: {checkout.root}, {checkout.home / 'code' / 'proj-wt'}\n", run.stderr)
|
||||
|
||||
for transcript in checkout.transcripts():
|
||||
transcript.unlink()
|
||||
@@ -443,6 +489,47 @@ class Interrupt(unittest.TestCase):
|
||||
self.assertEqual((run.code, run.roles()), (1, ["worker", "judge"]))
|
||||
self.assertEqual(run.stderr.strip().splitlines()[-1], "could not start claude for the interrupt: No such file or directory")
|
||||
|
||||
def test_says_why_the_trust_file_cannot_be_read_and_leaves_it_as_it_was(self):
|
||||
checkout = Checkout(self)
|
||||
asked = [worker(say="A or B?"), judge(interrupt=True, evidence="A or B?", question="A or B?"), interrupt()]
|
||||
root = json.dumps(str(checkout.root))
|
||||
shapes = {
|
||||
None: "No such file or directory",
|
||||
"{": "Expecting property name enclosed in double quotes: line 1 column 2 (char 1)",
|
||||
"[]": 'not an object whose "projects" is an object',
|
||||
'{"projects": []}': 'not an object whose "projects" is an object',
|
||||
f'{{"projects": {{{root}: 1}}}}': f"projects[{root}] is not an object",
|
||||
}
|
||||
for text, said in shapes.items():
|
||||
with self.subTest(said=said):
|
||||
checkout.claude_json().unlink(missing_ok=True)
|
||||
if text is not None:
|
||||
checkout.claude_json().write_text(text)
|
||||
run = checkout.run(asked, terminal_input="")
|
||||
self.assertEqual(run.code, 2)
|
||||
self.assertIn(f"could not read {checkout.claude_json()}: {said}\n", run.stderr)
|
||||
self.assertEqual(checkout.claude_json().read_text() if checkout.claude_json().exists() else None, text)
|
||||
|
||||
trusted = json.dumps({"projects": {str(checkout.root): {"hasTrustDialogAccepted": True}}})
|
||||
checkout.claude_json().write_text(trusted)
|
||||
run = checkout.run(asked, terminal_input="")
|
||||
self.assertNotIn(str(checkout.claude_json()), run.stderr)
|
||||
self.assertNotIn("trusted for the interrupt", run.stderr)
|
||||
self.assertEqual(checkout.claude_json().read_text(), trusted)
|
||||
|
||||
@unittest.skipIf(os.geteuid() == 0, "root writes into a read-only directory")
|
||||
def test_says_why_the_trust_file_cannot_be_written(self):
|
||||
checkout = Checkout(self)
|
||||
checkout.claude_json().write_text("{}")
|
||||
asked = [worker(say="A or B?"), judge(interrupt=True, evidence="A or B?", question="A or B?"), interrupt()]
|
||||
checkout.run(asked[:2])
|
||||
checkout.home.chmod(0o500)
|
||||
self.addCleanup(checkout.home.chmod, 0o700)
|
||||
run = checkout.run([worker(), *asked[1:]], terminal_input="")
|
||||
self.assertEqual(run.code, 2)
|
||||
self.assertIn(f"could not write {checkout.claude_json()}: Permission denied\n", run.stderr)
|
||||
self.assertEqual(checkout.claude_json().read_text(), "{}")
|
||||
|
||||
@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)
|
||||
@@ -470,8 +557,13 @@ class Models(unittest.TestCase):
|
||||
self.assertEqual((run.code, run.calls), (2, []))
|
||||
self.assertEqual(run.stderr.strip().splitlines()[-1], "the human is needed to pick proj's model, but the input ended")
|
||||
|
||||
run = checkout.run([worker(), judge()], terminal_input="9\n2\n")
|
||||
checkout.env["LOOP_CLAUDE_JUDGE_MODEL"] = "judge-model"
|
||||
run = checkout.run([worker()])
|
||||
self.assertEqual((run.code, run.calls), (2, []))
|
||||
del checkout.env["LOOP_CLAUDE_JUDGE_MODEL"]
|
||||
run = checkout.run([worker(), judge()], terminal_input="\n9\n2\n")
|
||||
self.assertEqual(run.code, 130)
|
||||
self.assertIn("proj runs on model-b", run.stderr)
|
||||
self.assertIn("1. A (model-a)", run.stderr)
|
||||
self.assertNotIn("old-model", run.stderr)
|
||||
self.assertIn("pick 1 to 2", run.stderr)
|
||||
@@ -489,16 +581,36 @@ class Models(unittest.TestCase):
|
||||
checkout.models_file().parent.mkdir(parents=True)
|
||||
checkout.models_file().write_text(json.dumps({"other": "model-x"}))
|
||||
checkout.models_file().chmod(0o640)
|
||||
run = checkout.run([worker()], terminal_input="custom-model\n")
|
||||
def saved_elsewhere():
|
||||
checkout.models_file().write_text(json.dumps({"late": "model-y", "other": "model-x"}))
|
||||
|
||||
run = checkout.run([worker()], terminal_input="custom-model\n", before_typing=("claude --model takes: ", saved_elsewhere))
|
||||
self.assertEqual(run.code, 130)
|
||||
self.assertIn("no model catalog cached", run.stderr)
|
||||
self.assertEqual(json.loads(checkout.models_file().read_text()), {"other": "model-x", "proj": "custom-model"})
|
||||
self.assertIn("A name claude --model takes: ", run.stderr)
|
||||
self.assertEqual(json.loads(checkout.models_file().read_text()), {"late": "model-y", "other": "model-x", "proj": "custom-model"})
|
||||
self.assertEqual(stat.S_IMODE(checkout.models_file().stat().st_mode), 0o640)
|
||||
|
||||
checkout.models_file().write_text("[]")
|
||||
run = checkout.run([worker()])
|
||||
self.assertEqual((run.code, run.calls), (1, []))
|
||||
self.assertIn(f"could not read {checkout.models_file()}", run.stderr)
|
||||
for broken in ("{", "[]", '{"proj": 1}'):
|
||||
with self.subTest(broken=broken):
|
||||
checkout.models_file().write_text(broken)
|
||||
run = checkout.run([worker()])
|
||||
self.assertEqual((run.code, run.calls), (1, []))
|
||||
self.assertTrue(run.stderr.startswith(f"could not read {checkout.models_file()}: "))
|
||||
self.assertEqual(checkout.models_file().read_text(), broken)
|
||||
|
||||
def test_offers_no_catalog_whose_models_are_not_a_list(self):
|
||||
checkout = Checkout(self)
|
||||
del checkout.env["LOOP_CLAUDE_JUDGE_MODEL"], checkout.env["LOOP_CLAUDE_WORKER_MODEL"]
|
||||
self.catalog(checkout)
|
||||
catalog = checkout.home / ".claude" / "cache" / "model-catalog" / "new.json"
|
||||
for shape in ({"catalog": {"config": {"models": []}}}, {"catalog": None}, {"catalog": {"config": []}}, {"catalog": {"config": {"models": "x"}}}):
|
||||
with self.subTest(shape=shape):
|
||||
catalog.write_text(json.dumps({**shape, "fetchedAt": 3}))
|
||||
checkout.models_file().unlink(missing_ok=True)
|
||||
run = checkout.run([worker()], terminal_input="1\n")
|
||||
self.assertIn("no model catalog cached", run.stderr)
|
||||
self.assertEqual(argument(run.calls[0], "--model"), "1")
|
||||
|
||||
@unittest.skipIf(os.geteuid() == 0, "root writes into a read-only directory")
|
||||
def test_exits_1_when_the_models_file_cannot_be_written(self):
|
||||
@@ -531,6 +643,15 @@ class Reload(unittest.TestCase):
|
||||
self.assertEqual(json.loads(reloads[0][1]), {"cycle_number": 2, "failures": 0, "root": str(checkout.root), "task": TASK})
|
||||
self.assertIn("=== cycle 3 ===", run.stdout)
|
||||
|
||||
outside = checkout.temp / "outside"
|
||||
outside.mkdir()
|
||||
state = {"cycle_number": 3, "failures": 2, "root": str(checkout.root), "task": TASK}
|
||||
run = checkout.run([worker(exit=1)], argv=["--reloaded", json.dumps(state)], cwd=outside)
|
||||
self.assertEqual((run.code, run.sleeps), (1, []))
|
||||
self.assertEqual(run.calls[0]["cwd"], str(checkout.root))
|
||||
self.assertIn("=== cycle 4 ===", run.stdout)
|
||||
self.assertEqual(run.stderr.strip().splitlines()[-1], "the worker failed three times running: claude exited 1")
|
||||
|
||||
run = checkout.run([], argv=["--reloaded", "{}"])
|
||||
self.assertEqual((run.code, run.calls), (1, []))
|
||||
self.assertIn("rerun loop-claude <task>", run.stderr)
|
||||
|
||||
@@ -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`.
|
||||
|
||||
- **Replace `bin/test_loop_claude.py`'s internal-function tests with the black-box tests plus unit tests of the pure parsers.**
|
||||
- **Hold every reviewer to one findings document, `principles/review-findings.md`.** Severity, verdict, rounds with round 2 verifying each earlier finding, the per-chunk round cap, declining, and `/security-review`'s HIGH/MEDIUM/LOW mapped onto the scale; it replaces `principles/review-protocol.md`.
|
||||
- **Rewrite larv-review around one pass table and one re-entry rule.** A trigger per pass, each stated only there; the re-entry paragraph classifies a fix by the widest thing it touches; forge neutrality, the draft PR, CI watched in the foreground, the comprehension floor, the auto-reviewer's waits and the goal-alignment check carried over.
|
||||
- **Make the three reviewer agents pure reporters in the findings document's vocabulary.** Keep their names and checklists; remove every README- and decision-writing duty and every private severity or verdict scale.
|
||||
|
||||
Reference in New Issue
Block a user