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 claude_code, file_writes, judge, main, premises, transcript from loop_claude.outcome import Stop CWD = pathlib.Path("/c") 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(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"}]), {**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') 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("peer message"), "isMeta": True}, {**human("the loop's own prompt"), "promptSource": "sdk"}, human([{"type": "text", "text": "[Request interrupted by user]"}]), human([]), assistant({"type": "text", "text": "said"}), ]), 2) class Said(unittest.TestCase): def test_renders_text_and_tool_calls_and_nothing_else(self): self.assertEqual(transcript.said({"type": "text", "text": "hi"}), "hi") self.assertEqual(transcript.said({"type": "text", "text": " \n"}), "") self.assertEqual(transcript.said({"type": "tool_use", "name": "Bash", "input": {"command": "x" * 500}}, 20), '[tool Bash] {"command": "xxxxxxx') self.assertEqual(transcript.said("not a part"), "") class Parse(unittest.TestCase): def test_yields_only_json_objects(self): self.assertEqual(claude_code.parse('{"type": "user"}'), {"type": "user"}) self.assertIsNone(claude_code.parse("not json")) self.assertIsNone(claude_code.parse("[1, 2]")) class Grounded(unittest.TestCase): def test_every_verdict_must_quote_the_transcript(self): for interrupting in (False, True): self.assertTrue(judge.grounded({"interrupt": interrupting, "evidence": "Needs you: x"}, "so.\n\nNeeds you: x\n")) self.assertFalse(judge.grounded({"interrupt": interrupting, "evidence": "invented"}, "the transcript")) self.assertFalse(judge.grounded({"interrupt": interrupting, "evidence": ""}, "the transcript")) self.assertFalse(judge.grounded({"interrupt": interrupting, "evidence": " "}, "the transcript")) class Verdict(unittest.TestCase): def test_needs_every_field_the_schema_requires(self): self.assertIsNone(judge.incomplete({"interrupt": False, "evidence": "", "finished": True, "question": ""})) self.assertEqual(judge.incomplete({"interrupt": "no", "evidence": "", "finished": True, "question": ""}), "the judge's verdict has no interrupt of type boolean") self.assertEqual(judge.incomplete({"interrupt": False, "evidence": None, "finished": True, "question": ""}), "the judge's verdict has no evidence of type string") self.assertEqual(judge.incomplete({"interrupt": True, "evidence": "x", "finished": False, "question": " "}), "the judge interrupted without a question") self.assertEqual(judge.incomplete(None), "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 ")) 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.assertIsInstance(file_writes.replace_file(os.path.join(root, "in-the-way"), b"data"), IsADirectoryError) self.assertEqual(os.listdir(root), ["in-the-way"]) if __name__ == "__main__": unittest.main()