import dataclasses import json import os import pathlib import sys import tempfile import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) from loop_claude import file_writes, main, reload from loop_claude.claude_code import formats, transcript from loop_claude.claude_runs import judge from loop_claude.outcome import Failure, Stop from loop_claude.project import 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 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("/exit"), 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("/model"), {**human("<3 merge it"), "promptSource": "typed"}, {**human("done"), "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("done", "task-notification"), {"type": "attachment", "attachment": {"type": "queued_command", "commandMode": "task-notification", "prompt": "done"}}, 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): def verdict(evidence): return judge.Verdict(evidence=evidence, finished=False, interrupt=False, question="") self.assertTrue(judge.grounded(verdict("Needs you: x"), "so.\n\nNeeds you: x\n")) self.assertFalse(judge.grounded(verdict("invented"), "the transcript")) self.assertFalse(judge.grounded(verdict(""), "the transcript")) self.assertFalse(judge.grounded(verdict(" "), "the transcript")) class Verdict(unittest.TestCase): def test_needs_every_field_the_schema_requires(self): self.assertEqual(judge.verdict_from({"interrupt": False, "evidence": "", "finished": True, "question": ""}), judge.Verdict(evidence="", finished=True, interrupt=False, question="")) 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 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 ")) def test_decodes_a_state_whose_annotations_are_strings(self): @dataclasses.dataclass(frozen=True) class Stringly: count: "int" name: "str" self.assertEqual(reload.decode_state('{"count": 1, "name": "n"}', Stringly), Stringly(1, "n")) self.assertIsNone(reload.decode_state('{"count": "1", "name": "n"}', Stringly)) 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(os.path.join(root, "in-the-way"), b"data"), Failure("Is a directory")) self.assertEqual(os.listdir(root), ["in-the-way"]) if __name__ == "__main__": unittest.main()