From 1a1ee613af02ff992f1e6f4a205ab06d6204303b Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sun, 27 Sep 2026 16:52:46 +0200 Subject: [PATCH] Return every failure to main and exit only there --- bin/loop-claude | 94 ++++++++++++++++++++++++++++++++----------------- 1 file changed, 62 insertions(+), 32 deletions(-) diff --git a/bin/loop-claude b/bin/loop-claude index 5bf42cb5..49bdbc27 100755 --- a/bin/loop-claude +++ b/bin/loop-claude @@ -90,37 +90,64 @@ 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) def run_cycle(root, task, premises, name, session_id, chosen): + """The worker's failure, retried by the caller, or a Stop, or "" once the cycle ran.""" if failure := run_worker(root, worker_args(task, name, session_id, chosen, resuming=session_open(session_id))): return failure path = session_file(session_id) if not path: - sys.exit(f"claude left no transcript for session {session_id}") + return Stop(1, f"claude left no transcript for session {session_id}") verdict = judge(root, task, premises, render(entries(path)), chosen) - while verdict["ask"]: + while not isinstance(verdict, Stop) and verdict["ask"]: 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) + return Stop(2, failure) verdict = judge(root, task, premises, render(entries(path)), chosen) + if isinstance(verdict, Stop): + return verdict 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 ") + return Stop(1, f"the reload cannot read the loop's state from {argv[1:]}; rerun loop-claude ") 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}\": \"\"}} 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}\": \"\"}} 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()