Files
claude-config/bin/test_loop_claude.py
T

345 lines
16 KiB
Python

import contextlib
import errno
import importlib.machinery
import importlib.util
import io
import json
import os
import pathlib
import stat
import subprocess
import sys
import tempfile
import unittest
import unittest.mock
import uuid
SESSION_ID = str(getattr(uuid, "uuid7", uuid.uuid4)())
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)
def assistant(*parts):
return {"type": "assistant", "message": {"content": list(parts)}}
def human(content):
return {"type": "user", "message": {"content": content}}
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"]})
class ReadPremises(unittest.TestCase):
def exit_message(self):
with self.assertRaises(SystemExit) as stopped:
loop.read_premises()
self.assertTrue(stopped.exception.code.endswith("no premises."))
return stopped.exception.code
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, contextlib.chdir(root):
self.assertIn(f"README.md in {os.getcwd()}: No such file or directory", self.exit_message())
os.mkdir("README.md")
self.assertIn("Is a directory", self.exit_message())
os.rmdir("README.md")
for text, missing in texts.items():
with self.subTest(missing=missing):
open("README.md", "w").write(text)
self.assertIn(missing, self.exit_message())
open("README.md", "w").write("# T\n## Goals\n1. g\n## Audience\nme\n")
self.assertEqual(loop.read_premises(), "## Goals\n1. g\n\n## Audience\nme")
class Render(unittest.TestCase):
def test_joins_assistant_text_and_tool_calls_and_skips_the_rest(self):
said = loop.render([
human("do it"),
assistant({"type": "text", "text": "Starting."}, {"type": "tool_use", "name": "Bash", "input": {"command": "ls"}}),
assistant({"type": "text", "text": " "}),
])
self.assertEqual(said, 'Starting.\n\n[tool Bash] {"command": "ls"}')
class HumanTurns(unittest.TestCase):
def test_counts_typed_turns_and_not_tool_results(self):
self.assertEqual(loop.human_turns([
human("typed"),
human([{"type": "text", "text": "typed as a block"}]),
human([{"type": "tool_result", "content": "not typed"}]),
human("<command-name>/model</command-name>"),
{**human("peer message"), "isMeta": True},
human([{"type": "text", "text": "[Request interrupted by user]"}]),
human([]),
assistant({"type": "text", "text": "said"}),
]), 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()
with self.assertRaises(SystemExit) as stopped:
loop.checkout_root()
self.assertTrue(stopped.exception.code)
subprocess.run(["git", "init", "-q"], check=True)
os.makedirs("a/b")
with contextlib.chdir("a/b"):
self.assertEqual(loop.checkout_root(), root)
class Project(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"}):
with unittest.mock.patch("os.getcwd", return_value="/h/code/a/b"):
self.assertEqual(loop.project(), "a/b")
self.assertEqual(loop.session_name(), "A a/b loop-claude")
with unittest.mock.patch("os.getcwd", return_value="/h/code"):
self.assertEqual(loop.project(), "h/code")
with unittest.mock.patch("os.getcwd", return_value="/srv/x"):
self.assertEqual(loop.project(), "srv/x")
self.assertEqual(loop.session_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 = loop.worker_args("the task", "A name", SESSION_ID, 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, 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_settings_pick_the_model_unless_the_environment_names_one(self):
with unittest.mock.patch.dict(os.environ):
os.environ.pop("LOOP_CLAUDE_WORKER_MODEL", None)
self.assertNotIn("--model", loop.worker_args("t", "n", SESSION_ID, resuming=False))
with unittest.mock.patch.dict(os.environ, {"LOOP_CLAUDE_WORKER_MODEL": "claude-fable-5-1"}):
args = loop.worker_args("t", "n", SESSION_ID, resuming=False)
self.assertEqual(args[args.index("--model") + 1], "claude-fable-5-1")
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")
self.assertIn("LATE", prompt)
self.assertLess(prompt.count("early"), 20000)
self.assertTrue(prompt.endswith(loop.JUDGE_RULES))
class Archive(unittest.TestCase):
def test_keeps_the_copy_and_every_folder_it_creates_as_private_as_the_transcript(self):
with tempfile.TemporaryDirectory() as root, unittest.mock.patch("os.getcwd", return_value="/srv/a/b"):
transcript = os.path.join(root, "session.jsonl")
open(transcript, "w").write(json.dumps(assistant({"type": "text", "text": "said"})) + "\n")
loop.ARCHIVE = os.path.join(root, "deep", "archive")
loop.archive(transcript, "note")
[copy] = [os.path.join(folder, name) for folder, _, names in os.walk(loop.ARCHIVE) for name in names]
self.assertEqual(stat.S_IMODE(os.stat(copy).st_mode), 0o600)
folder = os.path.dirname(copy)
while folder != root:
self.assertEqual(stat.S_IMODE(os.stat(folder).st_mode), 0o700, folder)
folder = os.path.dirname(folder)
self.assertIn("said", open(copy).read())
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"), "")
class EndSession(unittest.TestCase):
def test_removes_the_transcript_and_its_siblings_and_closes_the_session(self):
with tempfile.TemporaryDirectory() as home, unittest.mock.patch.dict(os.environ, {"HOME": home}):
root = os.path.join(home, ".claude", "projects", "p")
os.makedirs(root)
transcript = os.path.join(root, f"{SESSION_ID}.jsonl")
open(transcript, "w").write("{}\n")
os.makedirs(os.path.join(root, SESSION_ID, "subagents"))
os.makedirs(os.path.join(root, f"{SESSION_ID}.superseded-1", "tool-results"))
open(os.path.join(root, f"{SESSION_ID}.orphaned-1-ab.jsonl"), "w").write("{}\n")
self.assertTrue(loop.session_open(SESSION_ID))
loop.end_session(transcript)
self.assertEqual(os.listdir(root), [])
self.assertFalse(loop.session_open(SESSION_ID))
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")
open(transcript, "w").write("{}\n")
with unittest.mock.patch("sys.stdin.isatty", return_value=False):
self.assertEqual(loop.interrupt(SESSION_ID, transcript, "q?"), "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),
unittest.mock.patch("subprocess.run") as run,
):
self.assertEqual(loop.interrupt(SESSION_ID, transcript, "q?"), "the interrupt ended without the human typing anything")
run.side_effect = lambda *args, **kwargs: open(transcript, "a").write(json.dumps(human("typed")) + "\n")
self.assertEqual(loop.interrupt(SESSION_ID, transcript, "q?"), "")
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}):
config = pathlib.Path(home, ".claude.json")
with contextlib.redirect_stderr(io.StringIO()) as err:
loop.trust(["/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"])
self.assertIn(f"could not read {config}: ", err.getvalue())
data = {"other": 1, "projects": {"/a": {"hasTrustDialogAccepted": True, "kept": 2}}}
config.write_text(json.dumps(data))
with contextlib.redirect_stderr(io.StringIO()) as err:
loop.trust(["/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"])
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")),
):
loop.trust(["/c"])
self.assertEqual(err.getvalue(), f"could not write {config}: Permission denied\n")
self.assertEqual(json.loads(config.read_text()), data)
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]"))
class Grounded(unittest.TestCase):
def test_an_interrupt_must_quote_the_transcript(self):
self.assertTrue(loop.grounded({"ask": False, "evidence": ""}, "anything"))
self.assertTrue(loop.grounded({"ask": True, "evidence": "Needs you: x"}, "so.\n\nNeeds you: x\n"))
self.assertFalse(loop.grounded({"ask": True, "evidence": "invented"}, "the transcript"))
self.assertFalse(loop.grounded({"ask": True, "evidence": ""}, "the transcript"))
class Verdict(unittest.TestCase):
def test_needs_every_field_the_schema_requires(self):
self.assertTrue(loop.complete({"ask": False, "evidence": "", "finished": True, "question": ""}))
self.assertFalse(loop.complete({"ask": False}))
self.assertFalse(loop.complete(None))
STUB_CLAUDE = """#!/usr/bin/env python3
import json, os, sys
args = sys.argv[1:]
open(os.environ["STUB_CALLS"], "a").write(json.dumps(args) + "\\n")
if "--json-schema" in args:
plan = open(os.environ["STUB_VERDICTS"]).read().split()
open(os.environ["STUB_VERDICTS"], "w").write(" ".join(plan[1:]))
if plan[0] == "fail":
sys.exit(1)
ask = plan[0] in ("ask", "unquoted")
print(json.dumps({"structured_output": {"ask": ask, "evidence": {"ask": "worked", "unquoted": "invented"}.get(plan[0], ""), "finished": plan[0] == "finished", "question": "q?" if ask 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)
open(os.path.join(folder, args[args.index(flag) + 1] + ".jsonl"), "a").write(json.dumps({"type": "assistant", "message": {"content": [{"type": "text", "text": "worked"}]}}) + "\\n")
print(json.dumps({"type": "result"}))
"""
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")
open(stub, "w").write(STUB_CLAUDE)
os.chmod(stub, 0o700)
calls, verdicts = os.path.join(home, "calls"), os.path.join(home, "verdicts")
open(verdicts, "w").write("fail continue finished unquoted continue")
loop.ARCHIVE = 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.assertTrue(loop.run_cycle("task", "premises", "A name", SESSION_ID))
open(verdicts, "w").write("ask")
with self.assertRaises(SystemExit) as stopped, unittest.mock.patch("sys.stderr") as stderr:
loop.run_cycle("task", "premises", "A name", SESSION_ID)
self.assertEqual(stopped.exception.code, 2)
said = "".join(str(call.args[0]) for call in stderr.write.call_args_list)
self.assertIn(f"transcript: {loop.ARCHIVE}", said)
self.assertIn("not a terminal", said)
for plan in ("fail fail fail", "unquoted unquoted unquoted"):
open(verdicts, "w").write(plan)
with self.assertRaises(SystemExit) as stopped:
loop.run_cycle("task", "premises", "A name", SESSION_ID)
self.assertTrue(stopped.exception.code.startswith("the judge "))
if plan.startswith("unquoted"):
self.assertIn("asking: q?", stopped.exception.code)
self.assertEqual(open(verdicts).read(), "")
starts = [args[args.index("-p") + 1:][:3] for args in map(json.loads, open(calls)) if "--json-schema" not in args]
self.assertEqual([start[1] for start in starts], ["--name", "--resume", "--name", "--resume", "--resume", "--resume"])
self.assertEqual(starts[1][2], SESSION_ID)
self.assertEqual(sleep.call_count, 6)
class Reload(unittest.TestCase):
def test_runs_the_edited_file_before_trusting_it_and_hands_it_the_counters_on_argv(self):
with tempfile.TemporaryDirectory() as root:
script = os.path.join(root, "loop-claude")
open(script, "w").write(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("do it", cycle_number=1, failures=0)
execv.assert_not_called()
open(script, "w").write(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("do it", cycle_number=1, failures=2)
execv.assert_called_once_with(sys.executable, [sys.executable, script, loop.RELOAD_FLAG, "1", "2", "do it"])
self.assertEqual(dict(os.environ), environment)
class Main(unittest.TestCase):
def test_resumes_the_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")]
with contextlib.ExitStack() as stack:
mocks = [stack.enter_context(patch) for patch in patches]
stack.enter_context(unittest.mock.patch.object(sys, "argv", ["loop-claude", loop.RELOAD_FLAG, "3", "2", "do it"]))
stack.enter_context(unittest.mock.patch.object(sys, "stdout", io.StringIO()))
mocks[0].return_value = os.getcwd()
mocks[3].side_effect = SystemExit(0)
with self.assertRaises(SystemExit):
loop.main()
mocks[2].assert_called_once_with("do it", 3, 2)
self.assertIn("=== cycle 4 ===", sys.stdout.getvalue())
if __name__ == "__main__":
unittest.main()