372 lines
18 KiB
Python
372 lines
18 KiB
Python
import dataclasses
|
|
import json
|
|
import os
|
|
import pathlib
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
import time
|
|
import unittest
|
|
import uuid
|
|
|
|
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
|
|
|
|
from loop_claude import file_writes, paths
|
|
from loop_claude.claude_code import formats, session, transcript
|
|
from loop_claude.cycle import interrupt, judge, retry, states, steps, worker
|
|
from loop_claude.cycle.verdicts import Finished, Interrupt, Unfinished
|
|
from loop_claude.effects import Effects
|
|
from loop_claude.loop import main, reload
|
|
from loop_claude.outcome import Failure, Stop
|
|
from loop_claude.project import checkout, models, premises
|
|
|
|
CWD = pathlib.Path("/c")
|
|
|
|
|
|
def assistant(*parts):
|
|
return {"type": "assistant", "message": {"content": list(parts)}}
|
|
|
|
|
|
def human(content):
|
|
return {"type": "user", "message": {"content": content}}
|
|
|
|
|
|
def queued(prompt, kind):
|
|
return {"type": "attachment", "attachment": {"type": "queued_command", "commandMode": "prompt", "origin": {"kind": kind}, "prompt": prompt}}
|
|
|
|
|
|
class FakeEffects:
|
|
"""Effects that record each call and answer from a script, one answer per call."""
|
|
|
|
def __init__(self, claude=(), on_terminal_claude=(), git=(), inputs=(), python=(), streams=(), on_terminal=True):
|
|
self.calls = []
|
|
self.scripts = {"claude": list(claude), "claude_on_terminal": list(on_terminal_claude), "git": list(git), "input": list(inputs), "python": list(python), "stream_claude": list(streams)}
|
|
self.terminal = on_terminal
|
|
|
|
def effects(self):
|
|
return Effects(
|
|
claude=lambda args, cwd, stdin: self.answer("claude", (args, stdin)),
|
|
claude_on_terminal=lambda args, cwd: self.answer("claude_on_terminal", args),
|
|
execv=self.execv,
|
|
git=lambda args, cwd: self.answer("git", args),
|
|
input=lambda prompt: self.answer("input", prompt),
|
|
on_terminal=lambda: self.terminal,
|
|
python=lambda args: self.answer("python", args),
|
|
sleep=lambda seconds: self.calls.append(("sleep", seconds)),
|
|
stream_claude=lambda args, cwd: self.answer("stream_claude", args),
|
|
)
|
|
|
|
def answer(self, seam, what):
|
|
self.calls.append((seam, what))
|
|
answer = self.scripts[seam].pop(0)
|
|
if isinstance(answer, BaseException):
|
|
raise answer
|
|
return answer(what) if callable(answer) else answer
|
|
|
|
def execv(self, path, args):
|
|
self.calls.append(("execv", args))
|
|
raise OSError(2, "No such file or directory")
|
|
|
|
def made(self, seam):
|
|
return [what for called, what in self.calls if called == seam]
|
|
|
|
|
|
def uuid7():
|
|
# Python 3.11, the floor, has no uuid.uuid7.
|
|
random = int.from_bytes(os.urandom(10))
|
|
return uuid.UUID(int=int(time.time() * 1000) << 80 | 7 << 76 | (random >> 62 & 0xFFF) << 64 | 2 << 62 | random & (1 << 62) - 1)
|
|
|
|
|
|
def ran(stdout="", code=0, stderr=""):
|
|
return subprocess.CompletedProcess([], code, stdout, stderr)
|
|
|
|
|
|
def judged(verdict, evidence="working"):
|
|
reply = {"evidence": evidence, "finished": verdict == "finished", "interrupt": verdict == "interrupt", "question": "Which one?" if verdict == "interrupt" else ""}
|
|
return ran(json.dumps({"structured_output": reply}))
|
|
|
|
|
|
class Worker:
|
|
"""A worker claude: writes a line to the session's transcript, then streams a result."""
|
|
|
|
def __init__(self, home):
|
|
self.home = home
|
|
|
|
def __call__(self, args):
|
|
flag = "--session-id" if "--session-id" in args else "--resume"
|
|
path = self.home / "projects" / "-fake" / f"{args[args.index(flag) + 1]}.jsonl"
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
with open(path, "a") as handle:
|
|
handle.write(json.dumps(assistant({"type": "text", "text": "working"})) + "\n")
|
|
return Streamed(0)
|
|
|
|
|
|
class Streamed:
|
|
def __init__(self, code):
|
|
self.code = code
|
|
|
|
def lines(self):
|
|
return [json.dumps({"type": "result"}) + "\n"]
|
|
|
|
def wait(self):
|
|
return self.code
|
|
|
|
|
|
class Transitions(unittest.TestCase):
|
|
def test_each_state_moves_on_its_events_and_only_on_them(self):
|
|
legal = (
|
|
(states.Working(), states.WorkerRan("/t"), states.Judging("/t")),
|
|
(states.Judging("/t"), states.Ruled(Interrupt("e", "Which one?")), states.Interrupting("/t", "Which one?")),
|
|
(states.Judging("/t"), states.Ruled(Finished("e")), states.Finishing("/t")),
|
|
(states.Judging("/t"), states.Ruled(Unfinished("e")), states.Ended()),
|
|
(states.Interrupting("/t", "q"), states.Answered(), states.Judging("/t")),
|
|
(states.Finishing("/t"), states.Archived(), states.Ended()),
|
|
)
|
|
for state, event, after in legal:
|
|
with self.subTest(state=state, event=event):
|
|
self.assertEqual(states.transition(state, event), after)
|
|
every_state = (states.Working(), states.Judging("/t"), states.Interrupting("/t", "q"), states.Finishing("/t"), states.Ended())
|
|
every_event = (states.WorkerRan("/t"), states.Ruled(Interrupt("e", "Which one?")), states.Ruled(Finished("e")), states.Ruled(Unfinished("e")), states.Answered(), states.Archived())
|
|
for state in every_state:
|
|
for event in every_event:
|
|
if (state, event) not in [(state, event) for state, event, _ in legal]:
|
|
with self.subTest(state=state, event=event), self.assertRaises(ValueError):
|
|
states.transition(state, event)
|
|
|
|
|
|
class Cycles(unittest.TestCase):
|
|
def setUp(self):
|
|
temp = tempfile.TemporaryDirectory()
|
|
self.addCleanup(temp.cleanup)
|
|
self.home = pathlib.Path(temp.name)
|
|
self.paths = paths.paths_from(self.home, {})
|
|
self.session = session.session_for("proj", self.paths)
|
|
|
|
def cycle(self, fake):
|
|
return steps.Cycle(effects=fake.effects(), models=models.Models("judge-model", "worker-model"), paths=self.paths, premises="## Goals", project="proj", root=str(self.home), session=self.session, task="Do it.")
|
|
|
|
def archived_verdicts(self):
|
|
return sorted(path.read_text() for path in (self.paths.archive / "proj").glob("*.verdict.md"))
|
|
|
|
def test_a_finished_chunk_is_archived_and_its_session_deleted(self):
|
|
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("finished")])
|
|
self.assertIsNone(steps.run_cycle(self.cycle(fake)))
|
|
self.assertEqual(self.archived_verdicts(), ["Task: Do it.\n\nVerdict: finished\n"])
|
|
self.assertEqual(session.transcript_file(self.session), "")
|
|
|
|
def test_an_unfinished_chunk_keeps_its_session_and_the_next_cycle_resumes_it(self):
|
|
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 2, claude=[judged("unfinished")] * 2)
|
|
self.assertIsNone(steps.run_cycle(self.cycle(fake)))
|
|
self.assertTrue(session.transcript_file(self.session))
|
|
self.assertIsNone(steps.run_cycle(self.cycle(fake)))
|
|
workers = fake.made("stream_claude")
|
|
self.assertIn("--session-id", workers[0])
|
|
self.assertIn("--resume", workers[1])
|
|
self.assertFalse((self.paths.archive / "proj").exists())
|
|
|
|
def test_an_interrupt_is_archived_answered_and_judged_again(self):
|
|
def answer(args):
|
|
with open(session.transcript_file(self.session), "a") as handle:
|
|
handle.write(json.dumps(human("the second")) + "\n")
|
|
return 0
|
|
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("interrupt"), judged("unfinished")], on_terminal_claude=[answer], git=[ran()])
|
|
self.assertIsNone(steps.run_cycle(self.cycle(fake)))
|
|
self.assertEqual(self.archived_verdicts(), ["Task: Do it.\n\nVerdict: interrupt\n\nWhich one?\n"])
|
|
self.assertIn(str(self.session.id), fake.made("claude_on_terminal")[0])
|
|
prompts = [stdin for args, stdin in fake.made("claude")]
|
|
self.assertEqual(len(prompts), 2)
|
|
self.assertNotIn("the second", prompts[0])
|
|
self.assertIn("[human] the second", prompts[1])
|
|
|
|
def test_stops_when_the_worker_leaves_no_transcript(self):
|
|
fake = FakeEffects(streams=[Streamed(0)])
|
|
self.assertEqual(steps.run_cycle(self.cycle(fake)), Stop(1, f"claude left no transcript for session {self.session.id}"))
|
|
|
|
|
|
class Retried(unittest.TestCase):
|
|
def test_retries_a_minute_apart_and_stops_on_the_third_failure(self):
|
|
fake = FakeEffects()
|
|
results = [Failure("one"), "done"]
|
|
self.assertEqual(retry.retried("worker", lambda: results.pop(0), fake.effects()), "done")
|
|
self.assertEqual(fake.calls, [("sleep", 60)])
|
|
fake = FakeEffects()
|
|
self.assertEqual(retry.retried("judge", lambda: Failure("no"), fake.effects()), Stop(1, "the judge failed three times running: no"))
|
|
self.assertEqual(fake.calls, [("sleep", 60), ("sleep", 60)])
|
|
|
|
|
|
class Interrupts(unittest.TestCase):
|
|
def test_stops_off_a_terminal_before_starting_claude(self):
|
|
fake = FakeEffects(on_terminal=False)
|
|
stop = interrupt.interrupt("/r", uuid7(), "m", "/t", "Which one?", paths.paths_from(pathlib.Path("/h"), {}), fake.effects())
|
|
self.assertEqual(stop, 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.assertEqual(fake.calls, [])
|
|
|
|
def test_stops_when_nothing_was_typed_in_the_handover(self):
|
|
with tempfile.TemporaryDirectory() as home:
|
|
path = pathlib.Path(home, "t.jsonl")
|
|
path.write_text(json.dumps(human("a")) + "\n")
|
|
fake = FakeEffects(on_terminal_claude=[0], git=[ran()])
|
|
stop = interrupt.interrupt(home, uuid7(), "m", str(path), "Which one?", paths.paths_from(pathlib.Path(home), {}), fake.effects())
|
|
self.assertEqual(stop, Stop(2, "the human is needed to answer the question above, but the interrupt ended with nothing typed"))
|
|
|
|
|
|
class ModelPrompt(unittest.TestCase):
|
|
OFFERED = [("claude-opus-5-5", "Opus 5.5"), ("claude-haiku-4-5", "Haiku 4.5")]
|
|
|
|
def test_reads_a_number_as_the_offered_model_and_anything_else_as_a_name(self):
|
|
self.assertEqual(models.model_picked(" 2 ", self.OFFERED), "claude-haiku-4-5")
|
|
self.assertEqual(models.model_picked("opus", self.OFFERED), "opus")
|
|
self.assertEqual(models.model_picked("3", []), "3")
|
|
self.assertEqual(models.model_picked("3", self.OFFERED), Failure("pick 1 to 2"))
|
|
self.assertIsNone(models.model_picked(" ", self.OFFERED))
|
|
|
|
def test_asks_again_until_an_answer_picks_a_model(self):
|
|
with tempfile.TemporaryDirectory() as empty:
|
|
fake = FakeEffects(inputs=["", "my-model"])
|
|
self.assertEqual(models.ask_model("proj", pathlib.Path("/m.json"), pathlib.Path(empty), fake.effects()), "my-model")
|
|
self.assertEqual(len(fake.made("input")), 2)
|
|
fake = FakeEffects(inputs=[EOFError()])
|
|
self.assertEqual(models.ask_model("proj", pathlib.Path("/m.json"), pathlib.Path(empty), fake.effects()), Stop(2, "the human is needed to pick proj's model, but the input ended"))
|
|
|
|
|
|
class WorkerArgs(unittest.TestCase):
|
|
def test_opens_a_fresh_session_by_name_and_resumes_an_open_one(self):
|
|
opened = session.session_for("proj", paths.paths_from(pathlib.Path("/h"), {}))
|
|
fresh = worker.worker_args("Do it.", opened, "m", False)
|
|
self.assertEqual(fresh[fresh.index("--session-id") + 1], str(opened.id))
|
|
self.assertEqual(fresh[fresh.index("--name") + 1], "A proj loop-claude")
|
|
resumed = worker.worker_args("Do it.", opened, "m", True)
|
|
self.assertEqual(resumed[resumed.index("--resume") + 1], str(opened.id))
|
|
self.assertNotIn("Do it.", " ".join(resumed))
|
|
|
|
|
|
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 Render(unittest.TestCase):
|
|
def test_joins_assistant_text_and_tool_calls_and_human_turns_and_skips_the_rest(self):
|
|
said = transcript.render([
|
|
human("do it"),
|
|
assistant({"type": "text", "text": "Starting."}, {"type": "tool_use", "name": "Bash", "input": {"command": "ls"}}),
|
|
assistant({"type": "text", "text": " "}),
|
|
human([{"type": "tool_result", "content": "not typed"}]),
|
|
human("<command-name>/exit</command-name>"),
|
|
human([{"type": "text", "text": "yes, "}, {"type": "text", "text": "merge it"}]),
|
|
queued("B, while you work", "human"),
|
|
queued("origin/main moved", "coordinator"),
|
|
{**human("Continue the task; the previous run stopped before it was finished."), "promptSource": "sdk"},
|
|
])
|
|
self.assertEqual(said, '[human] do it\n\nStarting.\n\n[tool Bash] {"command": "ls"}\n\n[human] yes, merge it\n\n[human] B, while you work')
|
|
|
|
|
|
class HumanTurns(unittest.TestCase):
|
|
def test_counts_typed_turns_and_not_tool_results(self):
|
|
self.assertEqual(transcript.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("<3 merge it"), "promptSource": "typed"},
|
|
{**human("<task-notification>done</task-notification>"), "promptSource": "system"},
|
|
{**human([{"type": "text", "text": "<task-notification>done</task-notification>"}]), "promptSource": "system"},
|
|
{**human("peer message"), "isMeta": True},
|
|
{**human("the loop's own prompt"), "promptSource": "sdk"},
|
|
human([{"type": "text", "text": "[Request interrupted by user]"}]),
|
|
human([]),
|
|
queued("typed while claude worked", "human"),
|
|
queued("<task-notification>done</task-notification>", "task-notification"),
|
|
{"type": "attachment", "attachment": {"type": "queued_command", "commandMode": "task-notification", "prompt": "<task-notification>done</task-notification>"}},
|
|
assistant({"type": "text", "text": "said"}),
|
|
]), 4)
|
|
|
|
|
|
class PartLine(unittest.TestCase):
|
|
def test_renders_text_and_tool_calls_and_nothing_else(self):
|
|
self.assertEqual(transcript.part_line({"type": "text", "text": "hi"}), "hi")
|
|
self.assertEqual(transcript.part_line({"type": "text", "text": " \n"}), "")
|
|
self.assertEqual(transcript.part_line({"type": "tool_use", "name": "Bash", "input": {"command": "x" * 500}}, 20), '[tool Bash] {"command": "xxxxxxx')
|
|
self.assertEqual(transcript.part_line("not a part"), "")
|
|
|
|
|
|
class Parse(unittest.TestCase):
|
|
def test_yields_only_json_objects(self):
|
|
self.assertEqual(formats.parse('{"type": "user"}'), {"type": "user"})
|
|
self.assertIsNone(formats.parse("not json"))
|
|
self.assertIsNone(formats.parse("[1, 2]"))
|
|
|
|
|
|
class MarkTrusted(unittest.TestCase):
|
|
def test_returns_the_updated_config_and_leaves_the_one_it_was_handed(self):
|
|
config = {"other": 1, "projects": {"/a": {"hasTrustDialogAccepted": True}, "/b": {"kept": True}}}
|
|
handed = json.dumps(config)
|
|
self.assertEqual(formats.mark_trusted(config, ["/a", "/b", "/c"]), ({"other": 1, "projects": {"/a": {"hasTrustDialogAccepted": True}, "/b": {"hasTrustDialogAccepted": True, "kept": True}, "/c": {"hasTrustDialogAccepted": True}}}, ["/b", "/c"]))
|
|
self.assertEqual(json.dumps(config), handed)
|
|
self.assertEqual(formats.mark_trusted({}, ["/a"]), ({"projects": {"/a": {"hasTrustDialogAccepted": True}}}, ["/a"]))
|
|
|
|
|
|
class Grounded(unittest.TestCase):
|
|
def test_every_verdict_must_quote_the_transcript(self):
|
|
self.assertTrue(judge.grounded("Needs you: x", "so.\n\nNeeds you: x\n"))
|
|
self.assertFalse(judge.grounded("invented", "the transcript"))
|
|
self.assertFalse(judge.grounded("", "the transcript"))
|
|
self.assertFalse(judge.grounded(" ", "the transcript"))
|
|
transcript = "done.\n\n**Your step:**\n```\n./run.sh\n```\nRun it."
|
|
self.assertTrue(judge.grounded("Your step:\n```\n./run.sh\n```\nRun it.", transcript))
|
|
self.assertTrue(judge.grounded("Your step: ``` ./run.sh ``` Run it.", transcript))
|
|
self.assertFalse(judge.grounded("**", transcript))
|
|
|
|
|
|
class Verdict(unittest.TestCase):
|
|
def test_needs_every_field_the_schema_requires(self):
|
|
self.assertEqual(judge.verdict_from({"interrupt": False, "evidence": "e", "finished": True, "question": ""}), Finished("e"))
|
|
self.assertEqual(judge.verdict_from({"interrupt": False, "evidence": "e", "finished": False, "question": "ignored"}), Unfinished("e"))
|
|
self.assertEqual(judge.verdict_from({"interrupt": True, "evidence": "e", "finished": True, "question": "Which one?"}), Interrupt("e", "Which one?"))
|
|
self.assertEqual(judge.verdict_from({"interrupt": "no", "evidence": "", "finished": True, "question": ""}), Failure("the judge's verdict has no interrupt of type boolean"))
|
|
self.assertEqual(judge.verdict_from({"interrupt": False, "evidence": None, "finished": True, "question": ""}), Failure("the judge's verdict has no evidence of type string"))
|
|
self.assertEqual(judge.verdict_from({"interrupt": True, "evidence": "x", "finished": False, "question": " "}), Failure("the judge interrupted without a question"))
|
|
self.assertEqual(judge.verdict_from(None), Failure("the judge returned no verdict"))
|
|
|
|
|
|
class LoopRuns(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, "root": "/r"})], [json.dumps({"cycle_number": 3, "root": "/r", "task": ""})], [json.dumps({"cycle_number": "3", "root": "/r", "task": "do it"})], [json.dumps({"cycle_number": 3, "root": "", "task": "do it"})], [json.dumps({"cycle_number": 3, "root": "/r", "task": "do it", "turns": 1})], [json.dumps({"cycle_number": 3, "failures": 0, "root": "/r", "task": "do it"})]):
|
|
with self.subTest(handed=handed):
|
|
self.assertEqual(main.loop_run_from([main.RELOAD_FLAG, *handed], CWD, FakeEffects().effects()), Stop(1, f"the reload cannot read the loop run from {handed}; rerun loop-claude <task>"))
|
|
|
|
def test_decodes_a_state_whose_annotations_are_strings(self):
|
|
@dataclasses.dataclass(frozen=True)
|
|
class Stringly:
|
|
count: "int"
|
|
name: "str"
|
|
self.assertEqual(reload.decode_handed('{"count": 1, "name": "n"}', Stringly), Stringly(1, "n"))
|
|
self.assertIsNone(reload.decode_handed('{"count": "1", "name": "n"}', Stringly))
|
|
|
|
def test_stops_when_the_reload_cannot_start_python(self):
|
|
with tempfile.TemporaryDirectory() as root:
|
|
launcher = pathlib.Path(root, "loop-claude")
|
|
launcher.write_text("")
|
|
fake = FakeEffects(python=[ran()])
|
|
self.assertEqual(reload.exec_if_edited(launcher, "stale", main.LoopRun(1, "/r", "do it"), fake.effects()), Stop(1, "could not reload loop-claude: No such file or directory; rerun loop-claude <task>"))
|
|
|
|
|
|
class Checkouts(unittest.TestCase):
|
|
def test_lists_the_root_alone_when_git_cannot_start(self):
|
|
fake = FakeEffects(git=[FileNotFoundError(2, "No such file or directory")])
|
|
self.assertEqual(checkout.checkouts("/r", fake.effects()), ["/r"])
|
|
|
|
|
|
|
|
class ReplaceFile(unittest.TestCase):
|
|
def test_removes_what_it_staged_when_the_replace_fails(self):
|
|
with tempfile.TemporaryDirectory() as root:
|
|
os.mkdir(os.path.join(root, "in-the-way"))
|
|
self.assertEqual(file_writes.replace_file(pathlib.Path(root, "in-the-way"), b"data"), Failure("Is a directory"))
|
|
self.assertEqual(os.listdir(root), ["in-the-way"])
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|