Name loop_claude's modules and words by what each holds, explain the reload, and tie each exit-1 clause of --help to its Stop
This commit is contained in:
+60
-26
@@ -1,3 +1,4 @@
|
||||
import ast
|
||||
import dataclasses
|
||||
import json
|
||||
import os
|
||||
@@ -12,13 +13,14 @@ 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.claude_code import entries, session, transcript, trust
|
||||
from loop_claude.cycle import interrupt, judge, retry, run, states, worker
|
||||
from loop_claude.cycle.verdicts import Finished, Interrupt, Unfinished
|
||||
from loop_claude.effects import Effects
|
||||
from loop_claude.failure import Failure
|
||||
from loop_claude.loop import main, reload
|
||||
from loop_claude.outcome import Failure, Stop
|
||||
from loop_claude.project import checkout, models, premises
|
||||
from loop_claude.stop import Stop
|
||||
|
||||
CWD = pathlib.Path("/c")
|
||||
|
||||
@@ -143,26 +145,26 @@ class Cycles(unittest.TestCase):
|
||||
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.")
|
||||
return run.Cycle(effects=fake.effects(), models=models.Models("judge-model", "worker-model"), paths=self.paths, premises="## Goals", project_key="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"))
|
||||
return sorted(path.read_text() for path in (self.paths.transcript_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.assertIsNone(run.run_cycle(self.cycle(fake)))
|
||||
self.assertEqual(self.archived_verdicts(), ["Task: Do it.\n\nVerdict: finished\n"])
|
||||
self.assertIsNone(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.assertIsNone(run.run_cycle(self.cycle(fake)))
|
||||
self.assertTrue(session.transcript_file(self.session))
|
||||
self.assertIsNone(steps.run_cycle(self.cycle(fake)))
|
||||
self.assertIsNone(run.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())
|
||||
self.assertFalse((self.paths.transcript_archive / "proj").exists())
|
||||
|
||||
def test_an_interrupt_is_archived_answered_and_judged_again(self):
|
||||
def answer(args):
|
||||
@@ -170,7 +172,7 @@ class Cycles(unittest.TestCase):
|
||||
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.assertIsNone(run.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")]
|
||||
@@ -185,14 +187,14 @@ class Cycles(unittest.TestCase):
|
||||
folder.chmod(0o500)
|
||||
self.addCleanup(folder.chmod, 0o700)
|
||||
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("finished")])
|
||||
stop = steps.run_cycle(self.cycle(fake))
|
||||
stop = run.run_cycle(self.cycle(fake))
|
||||
self.assertEqual(stop, Stop(1, f"could not delete {folder}: Permission denied; delete every file and folder matching {folder}*, then rerun loop-claude; a rerun before that resumes the finished chunk's session"))
|
||||
self.assertTrue(session.session_open(self.session))
|
||||
self.assertEqual(self.archived_verdicts(), ["Task: Do it.\n\nVerdict: finished\n"])
|
||||
|
||||
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}"))
|
||||
self.assertEqual(run.run_cycle(self.cycle(fake)), Stop(1, f"claude left no transcript for session {self.session.id}"))
|
||||
|
||||
|
||||
class Retried(unittest.TestCase):
|
||||
@@ -235,10 +237,10 @@ class ModelPrompt(unittest.TestCase):
|
||||
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(models.ask_for_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"))
|
||||
self.assertEqual(models.ask_for_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):
|
||||
@@ -297,26 +299,26 @@ class HumanTurns(unittest.TestCase):
|
||||
|
||||
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": "text", "text": "hi"}, 20), "hi")
|
||||
self.assertEqual(transcript.part_line({"type": "text", "text": " \n"}, 20), "")
|
||||
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"), "")
|
||||
self.assertEqual(transcript.part_line("not a part", 20), "")
|
||||
|
||||
|
||||
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]"))
|
||||
self.assertEqual(entries.parse('{"type": "user"}'), {"type": "user"})
|
||||
self.assertIsNone(entries.parse("not json"))
|
||||
self.assertIsNone(entries.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(trust.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"]))
|
||||
self.assertEqual(trust.mark_trusted({}, ["/a"]), ({"projects": {"/a": {"hasTrustDialogAccepted": True}}}, ["/a"]))
|
||||
|
||||
|
||||
class Grounded(unittest.TestCase):
|
||||
@@ -336,17 +338,17 @@ class Verdict(unittest.TestCase):
|
||||
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": "no", "evidence": "", "finished": True, "question": ""}), Failure("the judge's reply has no interrupt of type boolean"))
|
||||
self.assertEqual(judge.verdict_from({"interrupt": False, "evidence": None, "finished": True, "question": ""}), Failure("the judge's reply 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"))
|
||||
self.assertEqual(judge.verdict_from(None), Failure("the judge returned no reply"))
|
||||
|
||||
|
||||
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>"))
|
||||
self.assertEqual(main.loop_run_from([main.RELOAD_FLAG, *handed], CWD, FakeEffects().effects()), Stop(1, f"the reload cannot read the cycle number, checkout root and task the edited script was handed in {handed}, as when the edit changed what one script hands the next; rerun loop-claude <task>"))
|
||||
|
||||
def test_decodes_a_state_whose_annotations_are_strings(self):
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
@@ -364,6 +366,38 @@ class LoopRuns(unittest.TestCase):
|
||||
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 ExitContract(unittest.TestCase):
|
||||
def test_every_exit_1_stop_has_its_clause_in_help(self):
|
||||
read, task, git, premises_ = "a transcript cannot be read or archived", "no task is given", "git cannot start or finds no checkout", "README.md holds no premises"
|
||||
models_, retries = "the models file cannot be read or written", "the worker or the judge fails three times running"
|
||||
# Per function, the --help clause of each Stop it returns with an exit code other than 0, 2 or 130, in source order.
|
||||
clauses = {
|
||||
("cycle/interrupt.py", "interrupt"): (read, read, "claude cannot start for an interrupt"),
|
||||
("cycle/retry.py", "retried"): (retries,),
|
||||
("cycle/run.py", "ask"): (read,),
|
||||
("cycle/run.py", "close"): (read, "a finished chunk's session cannot be deleted"),
|
||||
("cycle/run.py", "rule"): (read,),
|
||||
("cycle/run.py", "work"): ("claude leaves no transcript",),
|
||||
("loop/main.py", "loop_run_from"): (task, "a reload cannot read the cycle number, checkout root and task"),
|
||||
("loop/reload.py", "exec_if_edited"): ("python cannot start for a reload",),
|
||||
("project/checkout.py", "checkout_root"): (git, git),
|
||||
("project/models.py", "read_models_file"): (models_, models_),
|
||||
("project/models.py", "saved_model"): (models_,),
|
||||
("project/premises.py", "read_premises"): (premises_,) * 5,
|
||||
}
|
||||
root = pathlib.Path(main.__file__).parents[1]
|
||||
found = {}
|
||||
for path in sorted(root.rglob("*.py")):
|
||||
for function in ast.walk(ast.parse(path.read_text())):
|
||||
if isinstance(function, ast.FunctionDef):
|
||||
stops = [call for call in ast.walk(function) if isinstance(call, ast.Call) and getattr(call.func, "id", None) == "Stop" and not (isinstance(call.args[0], ast.Constant) and call.args[0].value in (0, 2, 130))]
|
||||
if stops:
|
||||
found[(str(path.relative_to(root)), function.name)] = len(stops)
|
||||
self.assertEqual(found, {site: len(said) for site, said in clauses.items()})
|
||||
help_exit_1 = main.__doc__[main.__doc__.index("Exit 1"):main.__doc__.index("Exit 2")]
|
||||
self.assertEqual([clause for said in clauses.values() for clause in said if f"- {clause}" not in help_exit_1], [])
|
||||
|
||||
|
||||
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")])
|
||||
|
||||
Reference in New Issue
Block a user