Return every failure to main and exit only there #71

Merged
lilleman merged 5 commits from failures-to-main into main 2026-09-27 16:55:21 +02:00
3 changed files with 122 additions and 85 deletions
+64 -34
View File
@@ -90,20 +90,45 @@ JUDGE_SCHEMA = {
}
@dataclasses.dataclass(frozen=True)
class Stop:
code: int
reason: str
def main():
state = loop_state(sys.argv[1:])
try:
stop = run_loop(sys.argv[1:])
except KeyboardInterrupt:
stop = Stop(130, "")
if stop.reason:
print(stop.reason, file=sys.stderr if stop.code else sys.stdout)
sys.exit(stop.code)
def run_loop(argv):
state = loop_state(argv)
if isinstance(state, Stop):
return state
while True:
reload_if_edited(state)
state = dataclasses.replace(state, cycle_number=state.cycle_number + 1)
premises = read_premises(state.root)
if isinstance(premises, Stop):
return premises
chosen = project_model(state.root)
if isinstance(chosen, Stop):
return chosen
name = session_name(state.root)
print(f"\n=== cycle {state.cycle_number} ===", flush=True)
failure = run_cycle(state.root, state.task, premises, name, uuid.uuid5(SESSION_NAMESPACE, name), project_model(state.root))
failure = run_cycle(state.root, state.task, premises, name, uuid.uuid5(SESSION_NAMESPACE, name), chosen)
if isinstance(failure, Stop):
return failure
state = dataclasses.replace(state, failures=state.failures + 1 if failure else 0)
if not failure:
continue
if state.failures == 3:
sys.exit(f"the worker failed three times running: {failure}")
return Stop(1, f"the worker failed three times running: {failure}")
print(f"retrying the worker in a minute: {failure}", file=sys.stderr)
time.sleep(60)
@@ -113,14 +138,16 @@ def run_cycle(root, task, premises, name, session_id, chosen):
return failure
path = session_file(session_id)
if not path:
sys.exit(f"claude left no transcript for session {session_id}")
verdict = judge(root, task, premises, render(entries(path)), chosen)
while verdict["ask"]:
return Stop(1, f"claude left no transcript for session {session_id}")
while True:
verdict = judge(root, task, premises, render(entries(path)), chosen)
if isinstance(verdict, Stop):
return verdict
if not verdict["ask"]:
break
archive(root, path, f"Task: {task}\n\nVerdict: needs input\n\n{verdict['question']}")
if failure := interrupt(root, session_id, chosen, path, verdict["question"]):
print(failure, file=sys.stderr)
sys.exit(2)
verdict = judge(root, task, premises, render(entries(path)), chosen)
return Stop(2, failure)
if verdict["finished"]:
archive(root, path, f"Task: {task}\n\nVerdict: finished")
delete_transcript_files(path)
@@ -130,7 +157,7 @@ def run_cycle(root, task, premises, name, session_id, chosen):
def checkout_root():
found = subprocess.run(["git", "rev-parse", "--show-toplevel"], capture_output=True, text=True)
if found.returncode != 0:
sys.exit(found.stderr.strip())
return Stop(1, found.stderr.strip())
return found.stdout.strip()
@@ -138,18 +165,18 @@ def read_premises(root):
try:
found = sections(open(os.path.join(root, "README.md"), encoding="utf-8").read())
except OSError as failure:
sys.exit(f"README.md in {root}: {failure.strerror} - no premises.")
return Stop(1, f"README.md in {root}: {failure.strerror} - no premises.")
except UnicodeDecodeError as failure:
line = failure.object.count(b"\n", 0, failure.start) + 1
sys.exit(f"README.md is not UTF-8 on line {line} - no premises.")
return Stop(1, f"README.md is not UTF-8 on line {line} - no premises.")
for name in ("Goals", "Audience"):
bodies = found.get(name, [])
if not bodies:
sys.exit(f"README.md has no ## {name} heading - no premises.")
return Stop(1, f"README.md has no ## {name} heading - no premises.")
if len(bodies) > 1:
sys.exit(f"README.md has ## {name} more than once - no premises.")
return Stop(1, f"README.md has ## {name} more than once - no premises.")
if not bodies[0]:
sys.exit(f"README.md has nothing under ## {name} - no premises.")
return Stop(1, f"README.md has nothing under ## {name} - no premises.")
return f"## Goals\n{found['Goals'][0]}\n\n## Audience\n{found['Audience'][0]}"
@@ -232,13 +259,13 @@ def loop_state(argv):
if argv[:1] != [RELOAD_FLAG]:
task = " ".join(argv)
if task in ("", "-h", "--help"):
print(__doc__.strip())
sys.exit(0 if task else 1)
return LoopState(0, 0, checkout_root(), task)
return Stop(0 if task else 1, __doc__.strip())
root = checkout_root()
return root if isinstance(root, Stop) else LoopState(0, 0, root, task)
handed = parse(argv[1]) if len(argv) == 2 else None
shape = {field.name: field.type for field in dataclasses.fields(LoopState)}
if not handed or handed.keys() != shape.keys() or any(type(handed[name]) is not kind for name, kind in shape.items()) or not (handed["root"] and handed["task"]):
sys.exit(f"the reload cannot read the loop's state from {argv[1:]}; rerun loop-claude <task>")
return Stop(1, f"the reload cannot read the loop's state from {argv[1:]}; rerun loop-claude <task>")
return LoopState(**handed)
@@ -265,13 +292,20 @@ def project_model(root):
return ""
saved = os.path.expanduser("~/.claude/loop-claude-models.json")
name = project(root)
if chosen := read_models(saved).get(name):
models = read_models(saved)
if isinstance(models, Stop):
return models
if chosen := models.get(name):
return chosen
chosen = ask_model(name, saved)
if isinstance(chosen, Stop):
return chosen
# Reread: another loop may have saved its project while this one waited on the human.
models = {**read_models(saved), name: chosen}
if failure := replace_json(saved, models, indent="\t", sort_keys=True):
sys.exit(f"could not save the model in {saved}: {failure.strerror}")
models = read_models(saved)
if isinstance(models, Stop):
return models
if failure := replace_json(saved, {**models, name: chosen}, indent="\t", sort_keys=True):
return Stop(1, f"could not save the model in {saved}: {failure.strerror}")
print(f"{name} runs on {chosen}", file=sys.stderr)
return chosen
@@ -283,16 +317,15 @@ def read_models(saved):
except FileNotFoundError:
return {}
except (OSError, ValueError) as failure:
sys.exit(f"could not read {saved}: {getattr(failure, 'strerror', None) or failure}")
return Stop(1, f"could not read {saved}: {getattr(failure, 'strerror', None) or failure}")
if not isinstance(models, dict) or not all(isinstance(chosen, str) and chosen for chosen in models.values()):
sys.exit(f"could not read {saved}: not an object mapping projects to model names")
return Stop(1, f"could not read {saved}: not an object mapping projects to model names")
return models
def ask_model(name, saved):
if not (sys.stdin.isatty() and sys.stdout.isatty()):
print(f"{name} has no model in {saved}, and stdin or stdout is not a terminal to ask on; run it on a terminal or merge {{\"{name}\": \"<model>\"}} into {saved}", file=sys.stderr)
sys.exit(2)
return Stop(2, f"{name} has no model in {saved}, and stdin or stdout is not a terminal to ask on; run it on a terminal or merge {{\"{name}\": \"<model>\"}} into {saved}")
offered = catalog()
print(f"\nThe model to run {name} on, saved in {saved}:", file=sys.stderr)
for number, (model_id, label) in enumerate(offered, 1):
@@ -303,8 +336,8 @@ def ask_model(name, saved):
try:
answer = input(f"{'A number, or any' if offered else 'A'} name claude --model takes: ").strip()
except EOFError:
print("\nno model picked", file=sys.stderr)
sys.exit(2)
print(file=sys.stderr)
return Stop(2, "no model picked")
if not answer:
continue
if not (offered and answer.isdecimal()):
@@ -462,7 +495,7 @@ def judge(root, task, premises, transcript, chosen):
else:
return verdict
if attempt == 2:
sys.exit(f"the judge failed three times running: {failure}")
return Stop(1, f"the judge failed three times running: {failure}")
print(f"retrying the judge in a minute: {failure}", file=sys.stderr)
time.sleep(60)
@@ -533,7 +566,4 @@ def trust(paths):
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
sys.exit(130)
main()
+58 -50
View File
@@ -47,10 +47,10 @@ class Sections(unittest.TestCase):
class ReadPremises(unittest.TestCase):
def exit_message(self, root):
with self.assertRaises(SystemExit) as stopped:
loop.read_premises(root)
self.assertTrue(stopped.exception.code.endswith("no premises."))
return stopped.exception.code
stop = loop.read_premises(root)
self.assertEqual(stop.code, 1)
self.assertTrue(stop.reason.endswith("no premises."))
return stop.reason
def test_names_what_is_missing(self):
texts = {
@@ -109,9 +109,7 @@ 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)
self.assertEqual(loop.checkout_root().code, 1)
subprocess.run(["git", "init", "-q"], check=True)
os.makedirs("a/b")
with contextlib.chdir("a/b"):
@@ -164,16 +162,15 @@ class ProjectModel(unittest.TestCase):
catalog.mkdir(parents=True)
for name, fetched, ids in (("old.json", 1, ["claude-opus-5"]), ("new.json", 2, ["claude-opus-5-5", "claude-sonnet-5"])):
catalog.joinpath(name).write_text(json.dumps({"fetchedAt": fetched, "catalog": {"config": {"models": [{"id": id, "name": id.upper()} for id in ids]}}}))
with unittest.mock.patch("sys.stdin.isatty", return_value=False), self.assertRaises(SystemExit) as stopped:
loop.project_model("/srv/a")
self.assertEqual(stopped.exception.code, 2)
self.assertIn(f'merge {{"srv/a": "<model>"}} into {saved}', sys.stderr.getvalue())
with unittest.mock.patch("sys.stdin.isatty", return_value=False):
stop = loop.project_model("/srv/a")
self.assertEqual(stop.code, 2)
self.assertIn(f'merge {{"srv/a": "<model>"}} into {saved}', stop.reason)
self.assertFalse(saved.exists())
with unittest.mock.patch.dict(os.environ, {"LOOP_CLAUDE_JUDGE_MODEL": "j", "LOOP_CLAUDE_WORKER_MODEL": "w"}), unittest.mock.patch("sys.stdin.isatty", return_value=False):
self.assertEqual(loop.project_model("/srv/a"), "")
with unittest.mock.patch.dict(os.environ, {"LOOP_CLAUDE_JUDGE_MODEL": "j"}), unittest.mock.patch("sys.stdin.isatty", return_value=False), self.assertRaises(SystemExit) as stopped:
loop.project_model("/srv/a")
self.assertEqual(stopped.exception.code, 2)
with unittest.mock.patch.dict(os.environ, {"LOOP_CLAUDE_JUDGE_MODEL": "j"}), unittest.mock.patch("sys.stdin.isatty", return_value=False):
self.assertEqual(loop.project_model("/srv/a").code, 2)
with (
unittest.mock.patch("sys.stdin.isatty", return_value=True),
unittest.mock.patch("sys.stdout.isatty", return_value=True),
@@ -195,13 +192,10 @@ class ProjectModel(unittest.TestCase):
self.assertEqual(loop.project_model("/srv/a"), "claude-sonnet-5")
self.assertEqual(typed.call_count, 4)
typed.side_effect = EOFError
with self.assertRaises(SystemExit) as stopped:
loop.project_model("/srv/c")
self.assertEqual(stopped.exception.code, 2)
self.assertEqual(loop.project_model("/srv/c"), loop.Stop(2, "no model picked"))
typed.side_effect = ["sonnet"]
with unittest.mock.patch("os.replace", side_effect=OSError(errno.EACCES, "Permission denied")), self.assertRaises(SystemExit) as stopped:
loop.project_model("/srv/c")
self.assertEqual(stopped.exception.code, f"could not save the model in {saved}: Permission denied")
with unittest.mock.patch("os.replace", side_effect=OSError(errno.EACCES, "Permission denied")):
self.assertEqual(loop.project_model("/srv/c"), loop.Stop(1, f"could not save the model in {saved}: Permission denied"))
self.assertEqual(json.loads(saved.read_text()), {"srv/a": "claude-sonnet-5", "srv/b": "opus[1m]", "srv/d": "haiku"})
self.assertEqual(stat.S_IMODE(saved.stat().st_mode), 0o640)
self.assertEqual(sorted(os.listdir(saved.parent)), ["cache", "loop-claude-models.json"])
@@ -219,9 +213,10 @@ class ProjectModel(unittest.TestCase):
self.assertIn("no model catalog cached", sys.stderr.getvalue())
for broken in ("{", "[]", '{"srv/a": 1}'):
saved.write_text(broken)
with self.subTest(broken=broken), self.assertRaises(SystemExit) as stopped:
loop.project_model("/srv/a")
self.assertTrue(stopped.exception.code.startswith(f"could not read {saved}: "))
with self.subTest(broken=broken):
stop = loop.project_model("/srv/a")
self.assertEqual(stop.code, 1)
self.assertTrue(stop.reason.startswith(f"could not read {saved}: "))
self.assertEqual(saved.read_text(), broken)
@@ -408,25 +403,27 @@ class RunCycle(unittest.TestCase):
for _ in range(3):
self.assertEqual(loop.run_cycle(home, "task", "premises", "A name", SESSION_ID, "claude-opus-5-5"), "")
open(verdicts, "w").write("ask")
with self.assertRaises(SystemExit) as stopped, unittest.mock.patch("sys.stderr") as stderr:
loop.run_cycle(home, "task", "premises", "A name", SESSION_ID, "claude-opus-5-5")
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)
with unittest.mock.patch("sys.stderr") as stderr:
self.assertEqual(loop.run_cycle(home, "task", "premises", "A name", SESSION_ID, "claude-opus-5-5"), loop.Stop(2, "stdin or stdout is not a terminal"))
self.assertIn(f"transcript: {loop.ARCHIVE}", "".join(str(call.args[0]) for call in stderr.write.call_args_list))
open(verdicts, "w").write("ask fail fail fail")
with unittest.mock.patch("sys.stderr"), unittest.mock.patch.object(loop, "interrupt", return_value=""):
self.assertEqual(loop.run_cycle(home, "task", "premises", "A name", SESSION_ID, "claude-opus-5-5").code, 1)
with unittest.mock.patch.object(loop, "session_file", return_value=""):
self.assertEqual(loop.run_cycle(home, "task", "premises", "A name", SESSION_ID, "claude-opus-5-5"), loop.Stop(1, f"claude left no transcript for session {SESSION_ID}"))
for plan in ("fail fail fail", "unquoted unquoted unquoted"):
open(verdicts, "w").write(plan)
with self.assertRaises(SystemExit) as stopped:
loop.run_cycle(home, "task", "premises", "A name", SESSION_ID, "claude-opus-5-5")
self.assertTrue(stopped.exception.code.startswith("the judge "))
stop = loop.run_cycle(home, "task", "premises", "A name", SESSION_ID, "claude-opus-5-5")
self.assertEqual(stop.code, 1)
self.assertTrue(stop.reason.startswith("the judge "))
if plan.startswith("unquoted"):
self.assertIn("asking: q?", stopped.exception.code)
self.assertIn("asking: q?", stop.reason)
self.assertEqual(open(verdicts).read(), "")
self.assertEqual({json.loads(line)[0] for line in open(calls)}, {home})
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([start[1] for start in starts], ["--name", "--resume", "--name", "--resume", "--resume", "--name", "--resume", "--resume"])
self.assertEqual(starts[1][2], SESSION_ID)
self.assertEqual(sleep.call_count, 6)
self.assertEqual(sleep.call_count, 8)
self.assertEqual({args[args.index("--model") + 1] for args in map(json.loads, open(calls))}, {"claude-opus-5-5"})
@@ -447,43 +444,54 @@ class Reload(unittest.TestCase):
class Main(unittest.TestCase):
def test_exits_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), unittest.mock.patch.object(sys, "argv", ["loop-claude", loop.RELOAD_FLAG, *handed]), self.assertRaises(SystemExit) as stopped:
def test_exits_only_here_with_the_stop_the_loop_returned(self):
for argv, code, stream in ((["--help"], 0, "stdout"), ([], 1, "stderr"), ([loop.RELOAD_FLAG, "3"], 1, "stderr")):
with self.subTest(argv=argv), unittest.mock.patch.object(sys, "argv", ["loop-claude", *argv]), contextlib.redirect_stdout(io.StringIO()) as out, contextlib.redirect_stderr(io.StringIO()) as err, self.assertRaises(SystemExit) as stopped:
loop.main()
self.assertEqual(stopped.exception.code, f"the reload cannot read the loop's state from {handed}; rerun loop-claude <task>")
self.assertEqual(stopped.exception.code, code)
self.assertEqual({"stdout": out, "stderr": err}[stream].getvalue(), loop.run_loop(argv).reason + "\n")
with unittest.mock.patch.object(loop, "run_loop", side_effect=KeyboardInterrupt), self.assertRaises(SystemExit) as stopped:
loop.main()
self.assertEqual(stopped.exception.code, 130)
class RunLoop(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(loop.run_loop([loop.RELOAD_FLAG, *handed]), loop.Stop(1, f"the reload cannot read the loop's state from {handed}; rerun loop-claude <task>"))
def test_resumes_the_root_and_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", "project_model")]
stopped = loop.Stop(1, "stopped")
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, json.dumps({"cycle_number": 3, "failures": 2, "root": "/r", "task": "do it"})]))
stack.enter_context(unittest.mock.patch.object(sys, "stdout", io.StringIO()))
mocks[3].side_effect = SystemExit(0)
with self.assertRaises(SystemExit):
loop.main()
mocks[3].return_value = stopped
self.assertEqual(loop.run_loop([loop.RELOAD_FLAG, json.dumps({"cycle_number": 3, "failures": 2, "root": "/r", "task": "do it"})]), stopped)
mocks[0].assert_not_called()
mocks[1].assert_called_once_with("/r")
mocks[2].assert_called_once_with(loop.LoopState(3, 2, "/r", "do it"))
self.assertEqual(mocks[3].call_args.args[0], "/r")
mocks[4].assert_called_once_with("/r")
self.assertEqual(mocks[3].call_args.args[-1], mocks[4].return_value)
stack.enter_context(unittest.mock.patch.object(sys, "argv", ["loop-claude", "do it"]))
mocks[0].return_value = "/s"
with self.assertRaises(SystemExit):
loop.main()
self.assertEqual(loop.run_loop(["do", "it"]), stopped)
mocks[0].assert_called_once_with()
mocks[1].assert_called_with("/s")
self.assertIn("=== cycle 4 ===", sys.stdout.getvalue())
for leaf in (0, 1, 4):
with self.subTest(leaf=leaf):
mocks[leaf].return_value = loop.Stop(2, f"leaf {leaf}")
self.assertEqual(loop.run_loop(["do it"]), mocks[leaf].return_value)
mocks[leaf].return_value = "/s"
mocks[3].return_value = None
mocks[3].side_effect = ["claude exited 3"] * 3
stack.enter_context(unittest.mock.patch.object(sys, "argv", ["loop-claude", loop.RELOAD_FLAG, json.dumps({"cycle_number": 3, "failures": 0, "root": "/r", "task": "do it"})]))
stack.enter_context(unittest.mock.patch.object(sys, "stderr", io.StringIO()))
sleep = stack.enter_context(unittest.mock.patch("time.sleep"))
with self.assertRaises(SystemExit) as stopped:
loop.main()
self.assertEqual(loop.run_loop([loop.RELOAD_FLAG, json.dumps({"cycle_number": 3, "failures": 0, "root": "/r", "task": "do it"})]), loop.Stop(1, "the worker failed three times running: claude exited 3"))
self.assertIn("retrying the worker in a minute: claude exited 3", sys.stderr.getvalue())
self.assertEqual(sleep.call_count, 2)
self.assertEqual(stopped.exception.code, "the worker failed three times running: claude exited 3")
if __name__ == "__main__":
-1
View File
@@ -6,7 +6,6 @@ Ships when a four-seat scoring run puts every dimension and the overall at 7.0 o
Locality, 6.25:
- Return every failure to `main` and exit only there, today `run_cycle`, `loop_state`, `checkout_root`, `read_premises`, `judge`, `ask_model` and the models file exit from leaves.
- Put the three-strikes rule in one place, today `main` for the worker and `judge` for the judge.
- Say in `run_cycle` that the interrupt appends to the transcript under the loop and that `archive` skips a stamp already written, today inferred from `archive`.
- Name each clause of `typed` for the entry kind it drops, so one edit cannot silently change what both `human_turns` and `render` see.