From a1c5e8a16b05a95cb6e224a55fd10b0e5d3d4843 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 16:37:55 +0200 Subject: [PATCH 1/8] Pin evidence on every verdict, a named non-object trust entry, one spelling of the human being needed, and a claude the judge or interrupt cannot start --- bin/test_loop_claude.py | 92 +++++++++++++++---------------- bin/test_loop_claude_black_box.py | 49 ++++++++++++---- 2 files changed, 83 insertions(+), 58 deletions(-) diff --git a/bin/test_loop_claude.py b/bin/test_loop_claude.py index 1d478b00..a25565ea 100644 --- a/bin/test_loop_claude.py +++ b/bin/test_loop_claude.py @@ -15,7 +15,7 @@ import uuid sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) -from loop_claude import checkout, cycle, main, premises, reload, session, transcript, worker +from loop_claude import checkout, cycle, interrupt, judge, main, models, premises, reload, session, transcript, trust, worker from loop_claude.outcome import Continue, Failure, Retry, Stop from loop_claude.paths import paths_from @@ -24,6 +24,7 @@ LAUNCHER = pathlib.Path(__file__).resolve().with_name("loop-claude") PATHS = paths_from(pathlib.Path("/h"), {}) SESSION_ID = str(getattr(uuid, "uuid7", uuid.uuid4)()) SESSION = session.Session(uuid.UUID(SESSION_ID), "A name", PATHS.projects) +OPUS = models.Models("claude-opus-5-5", "claude-opus-5-5") def assistant(*parts): @@ -146,10 +147,6 @@ class WorkerArgs(unittest.TestCase): self.assertNotIn("--name", args) self.assertNotIn("paint the fence", args[1]) - def test_the_project_model_runs_unless_the_environment_names_one(self): - self.assertEqual(cycle.model_for({}, "LOOP_CLAUDE_WORKER_MODEL", "claude-opus-5-5"), "claude-opus-5-5") - self.assertEqual(cycle.model_for({"LOOP_CLAUDE_WORKER_MODEL": "claude-fable-5-1"}, "LOOP_CLAUDE_WORKER_MODEL", "claude-opus-5-5"), "claude-fable-5-1") - class ProjectModel(unittest.TestCase): def test_asks_once_per_project_from_the_newest_catalog_and_saves_the_answer(self): @@ -161,19 +158,19 @@ class ProjectModel(unittest.TestCase): 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): - stop = cycle.project_model("/srv/a", paths, {}) + stop = models.project_models("/srv/a", paths, {}) self.assertEqual(stop.code, 2) self.assertIn(f'merge {{"srv/a": ""}} into {saved}', stop.reason) self.assertFalse(saved.exists()) with unittest.mock.patch("sys.stdin.isatty", return_value=False): - self.assertEqual(cycle.project_model("/srv/a", paths, {"LOOP_CLAUDE_JUDGE_MODEL": "j", "LOOP_CLAUDE_WORKER_MODEL": "w"}), "") - self.assertEqual(cycle.project_model("/srv/a", paths, {"LOOP_CLAUDE_JUDGE_MODEL": "j"}).code, 2) + self.assertEqual(models.project_models("/srv/a", paths, {"LOOP_CLAUDE_JUDGE_MODEL": "j", "LOOP_CLAUDE_WORKER_MODEL": "w"}), models.Models("j", "w")) + self.assertEqual(models.project_models("/srv/a", paths, {"LOOP_CLAUDE_JUDGE_MODEL": "j"}).code, 2) with ( unittest.mock.patch("sys.stdin.isatty", return_value=True), unittest.mock.patch("sys.stdout.isatty", return_value=True), unittest.mock.patch("builtins.input", side_effect=["", "3", "2"]) as typed, ): - self.assertEqual(cycle.project_model("/srv/a", paths, {}), "claude-sonnet-5") + self.assertEqual(models.project_models("/srv/a", paths, {}), models.Models("claude-sonnet-5", "claude-sonnet-5")) self.assertEqual(typed.call_count, 3) self.assertIn("2. CLAUDE-SONNET-5 (claude-sonnet-5)", sys.stderr.getvalue()) self.assertIn("pick 1 to 2", sys.stderr.getvalue()) @@ -185,33 +182,34 @@ class ProjectModel(unittest.TestCase): saved.write_text(json.dumps({**json.loads(saved.read_text()), "srv/d": "haiku"})) return "opus[1m]" typed.side_effect = saved_elsewhere_while_asking - self.assertEqual(cycle.project_model("/srv/b", paths, {}), "opus[1m]") - self.assertEqual(cycle.project_model("/srv/a", paths, {}), "claude-sonnet-5") + self.assertEqual(models.project_models("/srv/b", paths, {}), models.Models("opus[1m]", "opus[1m]")) + self.assertEqual(models.project_models("/srv/a", paths, {}), models.Models("claude-sonnet-5", "claude-sonnet-5")) + self.assertEqual(models.project_models("/srv/a", paths, {"LOOP_CLAUDE_WORKER_MODEL": "w"}), models.Models("claude-sonnet-5", "w")) self.assertEqual(typed.call_count, 4) typed.side_effect = EOFError - self.assertEqual(cycle.project_model("/srv/c", paths, {}), Stop(2, "no model picked")) + self.assertEqual(models.project_models("/srv/c", paths, {}), Stop(2, "the human is needed to pick srv/c's model, but the input ended")) typed.side_effect = ["sonnet"] with unittest.mock.patch("os.replace", side_effect=OSError(errno.EACCES, "Permission denied")): - self.assertEqual(cycle.project_model("/srv/c", paths, {}), Stop(1, f"could not save the model in {saved}: Permission denied")) + self.assertEqual(models.project_models("/srv/c", paths, {}), 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"]) for shape in ({"fetchedAt": 3, "catalog": {"config": {"models": []}}}, {"fetchedAt": 3, "catalog": None}, {"fetchedAt": 3, "catalog": {"config": []}}, {"fetchedAt": 3, "catalog": {"config": {"models": "x"}}}): catalog.joinpath("new.json").write_text(json.dumps(shape)) with self.subTest(shape=shape): - self.assertEqual(cycle.catalog(catalog), []) + self.assertEqual(models.catalog(catalog), []) with ( unittest.mock.patch("sys.stdin.isatty", return_value=True), unittest.mock.patch("sys.stdout.isatty", return_value=True), unittest.mock.patch("builtins.input", side_effect=["1"]) as typed, ): - self.assertEqual(cycle.project_model("/srv/e", paths, {}), "1") + self.assertEqual(models.project_models("/srv/e", paths, {}), models.Models("1", "1")) self.assertEqual(typed.call_args.args[0], "A name claude --model takes: ") self.assertIn("no model catalog cached", sys.stderr.getvalue()) for broken in ("{", "[]", '{"srv/a": 1}'): saved.write_text(broken) with self.subTest(broken=broken): - stop = cycle.project_model("/srv/a", paths, {}) + stop = models.project_models("/srv/a", paths, {}) self.assertEqual(stop.code, 1) self.assertTrue(stop.reason.startswith(f"could not read {saved}: ")) self.assertEqual(saved.read_text(), broken) @@ -219,10 +217,10 @@ class ProjectModel(unittest.TestCase): class JudgePrompt(unittest.TestCase): def test_hands_the_judge_the_tail_of_a_long_transcript(self): - prompt = cycle.judge_prompt("task", "## Goals\n1. g", "early " * 20000 + "LATE") + prompt = judge.judge_prompt("task", "## Goals\n1. g", "early " * 20000 + "LATE") self.assertIn("LATE", prompt) self.assertLess(prompt.count("early"), 20000) - self.assertTrue(prompt.endswith(cycle.JUDGE_RULES)) + self.assertTrue(prompt.endswith(judge.JUDGE_RULES)) class Archive(unittest.TestCase): @@ -273,14 +271,14 @@ class Interrupt(unittest.TestCase): transcript = os.path.join(root, "session.jsonl") pathlib.Path(transcript).write_text("{}\n") with unittest.mock.patch("sys.stdin.isatty", return_value=False): - self.assertEqual(cycle.interrupt(root, SESSION_ID, "m", transcript, "q?", paths_from(pathlib.Path(root), {}), {}), Stop(2, "stdin or stdout is not a terminal")) + self.assertEqual(interrupt.interrupt(root, SESSION_ID, "m", transcript, "q?", paths_from(pathlib.Path(root), {})), Stop(2, "the human is needed to answer the question above, but stdin or stdout is not a terminal")) with ( unittest.mock.patch("sys.stdin.isatty", return_value=True), unittest.mock.patch("sys.stdout.isatty", return_value=True), - unittest.mock.patch.multiple(cycle, checkouts=unittest.mock.DEFAULT, trust=unittest.mock.DEFAULT) as mocks, + unittest.mock.patch.multiple(interrupt, checkouts=unittest.mock.DEFAULT, trust=unittest.mock.DEFAULT) as mocks, unittest.mock.patch("subprocess.run") as run, ): - self.assertEqual(cycle.interrupt(root, SESSION_ID, "m", transcript, "q?", paths_from(pathlib.Path(root), {}), {}), Stop(2, "the interrupt ended without the human typing anything")) + self.assertEqual(interrupt.interrupt(root, SESSION_ID, "m", transcript, "q?", paths_from(pathlib.Path(root), {})), Stop(2, "the human is needed to answer the question above, but the interrupt ended without you typing anything")) mocks["checkouts"].assert_called_with(root) self.assertEqual(run.call_args.kwargs["cwd"], root) self.assertEqual(run.call_args.args[0][run.call_args.args[0].index("--model") + 1], "m") @@ -289,7 +287,7 @@ class Interrupt(unittest.TestCase): handle.write(json.dumps(human("typed")) + "\n") run.side_effect = type_a_turn - self.assertIsNone(cycle.interrupt(root, SESSION_ID, "m", transcript, "q?", paths_from(pathlib.Path(root), {}), {})) + self.assertIsNone(interrupt.interrupt(root, SESSION_ID, "m", transcript, "q?", paths_from(pathlib.Path(root), {}))) class Trust(unittest.TestCase): @@ -297,27 +295,27 @@ class Trust(unittest.TestCase): with tempfile.TemporaryDirectory() as home, umask(0o022): config = pathlib.Path(home, ".claude.json") with contextlib.redirect_stderr(io.StringIO()) as err: - cycle.trust(config, ["/a"]) + trust.trust(config, ["/a"]) self.assertEqual(err.getvalue(), f"could not read {config}: No such file or directory\n") config.write_text("{") with contextlib.redirect_stderr(io.StringIO()) as err: - cycle.trust(config, ["/a"]) + trust.trust(config, ["/a"]) self.assertIn(f"could not read {config}: ", err.getvalue()) - for shape in ([], {"projects": []}, {"projects": {"/a": 1}}): + for shape, said in (([], 'not an object whose "projects" is an object'), ({"projects": []}, 'not an object whose "projects" is an object'), ({"projects": {"/a": 1}}, 'projects["/a"] is not an object')): config.write_text(json.dumps(shape)) with contextlib.redirect_stderr(io.StringIO()) as err: - cycle.trust(config, ["/a"]) - self.assertEqual(err.getvalue(), f"could not read {config}: not an object whose \"projects\" maps paths to objects\n") + trust.trust(config, ["/a"]) + self.assertEqual(err.getvalue(), f"could not read {config}: {said}\n") self.assertEqual(json.loads(config.read_text()), shape) data = {"other": 1, "projects": {"/a": {"hasTrustDialogAccepted": True, "kept": 2}}} config.write_text(json.dumps(data)) config.chmod(0o600) with contextlib.redirect_stderr(io.StringIO()) as err: - cycle.trust(config, ["/a"]) + trust.trust(config, ["/a"]) self.assertEqual(err.getvalue(), "") self.assertEqual(json.loads(config.read_text()), data) with contextlib.redirect_stderr(io.StringIO()) as err: - cycle.trust(config, ["/a", "/b"]) + trust.trust(config, ["/a", "/b"]) self.assertEqual(err.getvalue(), "trusted for the interrupt: /b\n") data["projects"]["/b"] = {"hasTrustDialogAccepted": True} self.assertEqual(json.loads(config.read_text()), data) @@ -325,7 +323,7 @@ class Trust(unittest.TestCase): contextlib.redirect_stderr(io.StringIO()) as err, unittest.mock.patch("os.replace", side_effect=OSError(errno.EACCES, "Permission denied")), ): - cycle.trust(config, ["/c"]) + trust.trust(config, ["/c"]) self.assertEqual(err.getvalue(), f"could not write {config}: Permission denied\n") self.assertEqual(json.loads(config.read_text()), data) self.assertEqual(stat.S_IMODE(config.stat().st_mode), 0o600) @@ -340,19 +338,21 @@ class Parse(unittest.TestCase): class Grounded(unittest.TestCase): - def test_an_interrupt_must_quote_the_transcript(self): - self.assertTrue(cycle.grounded({"interrupt": False, "evidence": ""}, "anything")) - self.assertTrue(cycle.grounded({"interrupt": True, "evidence": "Needs you: x"}, "so.\n\nNeeds you: x\n")) - self.assertFalse(cycle.grounded({"interrupt": True, "evidence": "invented"}, "the transcript")) - self.assertFalse(cycle.grounded({"interrupt": True, "evidence": ""}, "the transcript")) - self.assertFalse(cycle.grounded({"interrupt": True, "evidence": " "}, "the transcript")) + 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.assertTrue(cycle.complete({"interrupt": False, "evidence": "", "finished": True, "question": ""})) - self.assertFalse(cycle.complete({"interrupt": False})) - self.assertFalse(cycle.complete(None)) + self.assertTrue(judge.complete({"interrupt": False, "evidence": "", "finished": True, "question": ""})) + self.assertFalse(judge.complete({"interrupt": "no", "evidence": "", "finished": True, "question": ""})) + self.assertFalse(judge.complete({"interrupt": False, "evidence": None, "finished": True, "question": ""})) + self.assertFalse(judge.complete({"interrupt": False})) + self.assertFalse(judge.complete(None)) STUB_CLAUDE = """#!/usr/bin/env python3 @@ -366,7 +366,7 @@ if "--json-schema" in args: if plan[0] == "fail": sys.exit(1) interrupt = plan[0] in ("interrupt", "unquoted") - print(json.dumps({"structured_output": {"interrupt": interrupt, "evidence": {"interrupt": "worked", "unquoted": "invented"}.get(plan[0], ""), "finished": plan[0] == "finished", "question": "q?" if interrupt else ""}})) + print(json.dumps({"structured_output": {"interrupt": interrupt, "evidence": {"interrupt": "worked", "unquoted": "invented"}.get(plan[0], "worked"), "finished": plan[0] == "finished", "question": "q?" if interrupt else ""}})) else: flag = "--session-id" if "--session-id" in args else "--resume" folder = os.path.expanduser("~/.claude/projects/p") @@ -407,19 +407,19 @@ class RunCycle(unittest.TestCase): environment = {"HOME": home, "PATH": f"{home}:{os.environ['PATH']}", "STUB_CALLS": calls, "STUB_VERDICTS": verdicts} with unittest.mock.patch.dict(os.environ, environment), unittest.mock.patch("time.sleep") as sleep, unittest.mock.patch("sys.stdin.isatty", return_value=False): for _ in range(3): - self.assertEqual(cycle.run_cycle(home, "task", "premises", "claude-opus-5-5", paths, {}), Continue()) + self.assertEqual(cycle.run_cycle(home, "task", "premises", OPUS, paths), Continue()) pathlib.Path(verdicts).write_text("interrupt") with unittest.mock.patch("sys.stderr") as stderr: - self.assertEqual(cycle.run_cycle(home, "task", "premises", "claude-opus-5-5", paths, {}), Stop(2, "stdin or stdout is not a terminal")) + self.assertEqual(cycle.run_cycle(home, "task", "premises", OPUS, paths), Stop(2, "the human is needed to answer the question above, but stdin or stdout is not a terminal")) self.assertIn(f"transcript: {paths.archive}", "".join(str(call.args[0]) for call in stderr.write.call_args_list)) pathlib.Path(verdicts).write_text("interrupt fail fail fail") with unittest.mock.patch("sys.stderr"), unittest.mock.patch.object(cycle, "interrupt", return_value=None): - self.assertEqual(cycle.run_cycle(home, "task", "premises", "claude-opus-5-5", paths, {}).code, 1) + self.assertEqual(cycle.run_cycle(home, "task", "premises", OPUS, paths).code, 1) with unittest.mock.patch.object(cycle, "transcript_file", return_value=""): - self.assertEqual(cycle.run_cycle(home, "task", "premises", "claude-opus-5-5", paths, {}), Stop(1, f"claude left no transcript for session {session_id}")) + self.assertEqual(cycle.run_cycle(home, "task", "premises", OPUS, paths), Stop(1, f"claude left no transcript for session {session_id}")) for plan in ("fail fail fail", "unquoted unquoted unquoted"): pathlib.Path(verdicts).write_text(plan) - stop = cycle.run_cycle(home, "task", "premises", "claude-opus-5-5", paths, {}) + stop = cycle.run_cycle(home, "task", "premises", OPUS, paths) self.assertEqual(stop.code, 1) self.assertTrue(stop.reason.startswith("the judge ")) if plan.startswith("unquoted"): @@ -468,7 +468,7 @@ class RunLoop(unittest.TestCase): 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_resumes_the_root_and_counters_a_reload_handed_over(self): - patches = [unittest.mock.patch.object(main, name) for name in ("checkout_root", "read_premises", "reload_if_edited", "run_cycle", "project_model")] + patches = [unittest.mock.patch.object(main, name) for name in ("checkout_root", "read_premises", "reload_if_edited", "run_cycle", "project_models")] stopped = Stop(1, "stopped") with contextlib.ExitStack() as stack: mocks = [stack.enter_context(patch) for patch in patches] diff --git a/bin/test_loop_claude_black_box.py b/bin/test_loop_claude_black_box.py index 56a5ccf8..6f26acf5 100644 --- a/bin/test_loop_claude_black_box.py +++ b/bin/test_loop_claude_black_box.py @@ -81,6 +81,8 @@ elif "type" in step: append({{"type": "user", "message": {{"content": step["type"]}}}}) if step.get("unreadable"): transcript().chmod(0) +if step.get("vanish"): + os.remove(__file__) sys.exit(step.get("exit", 0)) """ @@ -103,7 +105,7 @@ def worker(**step): return {"role": "worker", **step} -def judge(interrupt=False, finished=False, evidence="", question="", **step): +def judge(interrupt=False, finished=False, evidence="working", question="", **step): verdict = {"evidence": evidence, "finished": finished, "interrupt": interrupt, "question": question} return {"role": "judge", "verdict": verdict, **step} @@ -271,8 +273,8 @@ class Cycles(unittest.TestCase): def test_resumes_the_session_while_unfinished_and_starts_it_fresh_after_finishing(self): checkout = Checkout(self) run = checkout.run([ - worker(say="started"), judge(), - worker(say="landed-it"), judge(finished=True), + worker(say="started"), judge(evidence="started"), + worker(say="landed-it"), judge(finished=True, evidence="landed-it"), worker(say="next chunk"), ]) self.assertEqual(run.code, 130) @@ -314,17 +316,32 @@ class Cycles(unittest.TestCase): self.assertIn("retrying the judge in a minute: judge down", run.stderr) self.assertEqual(run.stderr.strip().splitlines()[-1], "the judge failed three times running: the judge returned no verdict") - def test_retries_the_judge_alone_when_its_interrupt_quotes_nothing_in_the_transcript(self): + def test_retries_the_judge_alone_when_its_verdict_quotes_nothing_in_the_transcript(self): checkout = Checkout(self) - run = checkout.run([worker(say="Shall I use A or B?"), judge(interrupt=True, evidence="never said", question="A or B?"), judge()]) + run = checkout.run([ + worker(say="Shall I use A or B?"), + judge(interrupt=True, evidence="never said", question="A or B?"), + judge(finished=True, evidence=""), + judge(evidence="A or B"), + worker(), + ]) self.assertEqual(run.code, 130) - self.assertEqual(run.roles(), ["worker", "judge", "judge", "worker"]) + self.assertEqual(run.roles(), ["worker", "judge", "judge", "judge", "worker", "judge"]) + self.assertEqual(run.sleeps, [60, 60]) self.assertIn("the judge quoted 'never said', nothing in the transcript, for the question: A or B?", run.stderr) + self.assertIn("retrying the judge in a minute: the judge quoted '', nothing in the transcript\n", run.stderr) + + def test_retries_a_judge_claude_cannot_start(self): + checkout = Checkout(self) + run = checkout.run([worker(vanish=True)]) + self.assertEqual((run.code, run.roles()), (1, ["worker"])) + self.assertEqual(run.sleeps, [60, 60]) + self.assertEqual(run.stderr.strip().splitlines()[-1], "the judge failed three times running: could not start claude: No such file or directory") def test_skips_a_malformed_transcript_or_stream_line(self): checkout = Checkout(self) raw = "\xff not UTF-8\nnot JSON\n[1]\n" + json.dumps({"type": "assistant", "message": "not an object"}) + "\n" + json.dumps({"type": "user", "message": None}) + "\n" - run = checkout.run([worker(raw=raw, say="past the noise", stream="\xff not UTF-8\n"), judge()]) + run = checkout.run([worker(raw=raw, say="past the noise", stream="\xff not UTF-8\n"), judge(evidence="past the noise")]) self.assertEqual((run.code, run.roles()), (130, ["worker", "judge", "worker"])) self.assertIn("past the noise", run.stdout) self.assertIn("past the noise", run.calls[1]["stdin"]) @@ -360,13 +377,13 @@ class Interrupt(unittest.TestCase): steps = [worker(say="Shall I use A or B?"), judge(interrupt=True, evidence="Shall I use A or B?", question="A or B?")] run = checkout.run(steps) self.assertEqual((run.code, run.roles()), (2, ["worker", "judge"])) - self.assertEqual(run.stderr.strip().splitlines()[-2:], ["A or B?", "stdin or stdout is not a terminal"]) + self.assertEqual(run.stderr.strip().splitlines()[-2:], ["A or B?", "the human is needed to answer the question above, but stdin or stdout is not a terminal"]) self.assertTrue(checkout.archived()) session = argument(run.calls[0], "--session-id") run = checkout.run(steps, terminal_input="", stdout_on_terminal=False) self.assertEqual((run.code, run.roles()), (2, ["worker", "judge"])) self.assertEqual(argument(run.calls[0], "--resume"), session) - self.assertEqual(run.stderr.strip().splitlines()[-1], "stdin or stdout is not a terminal") + self.assertEqual(run.stderr.strip().splitlines()[-1], "the human is needed to answer the question above, but stdin or stdout is not a terminal") def test_hands_the_terminal_over_and_exits_2_when_nothing_is_typed(self): checkout = Checkout(self) @@ -375,7 +392,7 @@ class Interrupt(unittest.TestCase): checkout.claude_json().write_text(json.dumps({"other": 1, "projects": {str(checkout.root): {"kept": True}}})) checkout.claude_json().chmod(0o644) asked = [worker(say="Shall I use A or B?"), judge(interrupt=True, evidence="Shall I use A or B?", question="A or B?")] - run = checkout.run([*asked, interrupt(type="B"), judge(), worker()], terminal_input="") + run = checkout.run([*asked, interrupt(type="B"), judge(evidence="B"), worker()], terminal_input="") self.assertEqual(run.code, 130) self.assertEqual(run.roles(), ["worker", "judge", "interrupt", "judge", "worker", "judge"]) handed = run.calls[2]["argv"] @@ -393,7 +410,11 @@ class Interrupt(unittest.TestCase): transcript.unlink() run = checkout.run([*asked, interrupt()], terminal_input="") self.assertEqual((run.code, run.roles()), (2, ["worker", "judge", "interrupt"])) - self.assertEqual(run.stderr.strip().splitlines()[-1], "the interrupt ended without the human typing anything") + self.assertEqual(run.stderr.strip().splitlines()[-1], "the human is needed to answer the question above, but the interrupt ended without you typing anything") + + run = checkout.run([worker(say="A or B?"), judge(interrupt=True, evidence="A or B?", question="A or B?", vanish=True)], terminal_input="") + self.assertEqual((run.code, run.roles()), (1, ["worker", "judge"])) + self.assertEqual(run.stderr.strip().splitlines()[-1], "could not start claude: No such file or directory") @unittest.skipIf(os.geteuid() == 0, "root reads an unreadable file") def test_exits_1_when_the_transcript_cannot_be_read_after_the_interrupt(self): @@ -416,7 +437,11 @@ class Models(unittest.TestCase): self.catalog(checkout) run = checkout.run([worker()]) self.assertEqual((run.code, run.calls), (2, [])) - self.assertIn(f"proj has no model in {checkout.models_file()}", run.stderr) + self.assertEqual(run.stderr.strip(), f'the human is needed to pick proj\'s model, or merge {{"proj": ""}} into {checkout.models_file()}, but stdin or stdout is not a terminal') + + run = checkout.run([worker()], terminal_input="\x04") + self.assertEqual((run.code, run.calls), (2, [])) + self.assertEqual(run.stderr.strip().splitlines()[-1], "the human is needed to pick proj's model, but the input ended") run = checkout.run([worker(), judge()], terminal_input="9\n2\n") self.assertEqual(run.code, 130) -- 2.52.0 From 5e773f8460aa543d9c27cfe18ccefd4e61900b92 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 16:42:32 +0200 Subject: [PATCH 2/8] Keep the host's claude off the black-box tests' PATH --- bin/test_loop_claude_black_box.py | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/bin/test_loop_claude_black_box.py b/bin/test_loop_claude_black_box.py index 6f26acf5..67e52a00 100644 --- a/bin/test_loop_claude_black_box.py +++ b/bin/test_loop_claude_black_box.py @@ -149,6 +149,7 @@ class Checkout: fake.mkdir() (fake / "claude").write_text(FAKE_CLAUDE.format(python=sys.executable)) (fake / "claude").chmod(0o755) + (fake / "git").symlink_to(shutil.which("git")) site = self.temp / "site" site.mkdir() (site / "sitecustomize.py").write_text(SITECUSTOMIZE) @@ -161,7 +162,7 @@ class Checkout: "LOOP_CLAUDE_JUDGE_MODEL": "judge-model", "LOOP_CLAUDE_WORKER_MODEL": "worker-model", "LOOP_TEST_LOG": str(self.temp / "starts.jsonl"), - "PATH": f"{fake}{os.pathsep}{os.environ['PATH']}", + "PATH": str(fake), "PYTHONPATH": str(site), }) self.git("init", "--quiet") @@ -355,10 +356,7 @@ class Cycles(unittest.TestCase): def test_retries_a_worker_claude_cannot_start(self): checkout = Checkout(self) - only_git = checkout.temp / "only-git" - only_git.mkdir() - (only_git / "git").symlink_to(shutil.which("git")) - checkout.env["PATH"] = str(only_git) + (checkout.temp / "fake-bin" / "claude").unlink() run = checkout.run([]) self.assertEqual((run.code, run.calls), (1, [])) self.assertEqual(run.sleeps, [60, 60]) -- 2.52.0 From b0afcfab57214362146235a9f81cdcfa1a4c4512 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 16:42:32 +0200 Subject: [PATCH 3/8] Move the judge, the interrupt, trust and model resolution into their own modules --- AGENTS.md | 1 - CHANGELOG.md | 4 +- bin/loop_claude/cycle.py | 248 ++------------------------------ bin/loop_claude/human.py | 13 ++ bin/loop_claude/interrupt.py | 31 ++++ bin/loop_claude/judge.py | 95 ++++++++++++ bin/loop_claude/main.py | 22 +-- bin/loop_claude/models.py | 98 +++++++++++++ bin/loop_claude/private_file.py | 25 ++++ bin/loop_claude/trust.py | 29 ++++ docs/decisions.md | 4 - todo.md | 1 - 12 files changed, 315 insertions(+), 256 deletions(-) create mode 100644 bin/loop_claude/human.py create mode 100644 bin/loop_claude/interrupt.py create mode 100644 bin/loop_claude/judge.py create mode 100644 bin/loop_claude/models.py create mode 100644 bin/loop_claude/private_file.py create mode 100644 bin/loop_claude/trust.py diff --git a/AGENTS.md b/AGENTS.md index ddcdcb39..4f7aa2eb 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -9,7 +9,6 @@ Decisions live in `docs/decisions.md`: - loop-claude: one session per project, at a fixed id - loop-claude: the trust file is rewritten before an interrupt - loop-claude: every worktree of the checkout is trusted before an interrupt -- loop-claude: a wrong-shape trust file gets one message, naming the shape - bin/: the Python floor is README's Install prerequisite - bin/: host python, no container - comprehension floor: every dimension and the overall at 7.0 or above, and 0.1.0 waits on it diff --git a/CHANGELOG.md b/CHANGELOG.md index 360bafc3..c2b87599 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,8 @@ - First release: `README.md` states what the checkout holds and needs, `loop-claude --help` what `loop-claude` does. - `settings.json`, the agents and the status line run on any machine unedited; the status line shows reset times in the machine's own time zone. - `loop-claude`'s no-premises exit names what is wrong: `README.md` unopenable or not UTF-8, a `## Goals` or `## Audience` heading missing or repeated, or nothing under one. -- `loop-claude` says why when it cannot read or write `~/.claude.json` before an interrupt, and the interrupt then lands in Claude Code's trust dialog. +- `loop-claude` says why when it cannot read or write `~/.claude.json` before an interrupt, naming a `projects` entry that is not an object, and the interrupt then lands in Claude Code's trust dialog. - `loop-claude` skips a transcript line it cannot parse, exits 1 naming a transcript it cannot read, and counts a `claude` it cannot start as a failed worker run. +- `loop-claude`'s judge quotes the transcript for every verdict, and a verdict quoting nothing, or a `claude` the judge cannot start, is a failed judge run; a `claude` that cannot start for an interrupt exits 1. +- `loop-claude`'s exit-2 message says what the human is needed for. - `loop-claude` keeps the mode of `~/.claude.json` and of its models file when it rewrites them, and creates the models file 0600. diff --git a/bin/loop_claude/cycle.py b/bin/loop_claude/cycle.py index 1f4e368b..b9d11697 100644 --- a/bin/loop_claude/cycle.py +++ b/bin/loop_claude/cycle.py @@ -1,53 +1,21 @@ -import itertools -import json import os -import subprocess import sys import time -from loop_claude.checkout import checkouts, project_name +from loop_claude.checkout import project_name +from loop_claude.interrupt import interrupt +from loop_claude.judge import judge from loop_claude.outcome import Continue, Failure, Retry, Stop +from loop_claude.private_file import make_private from loop_claude.session import delete_session, session_for, transcript_file -from loop_claude.strike import strike -from loop_claude.transcript import human_turns, parse, read, render +from loop_claude.transcript import read, render from loop_claude.worker import run_worker, worker_args -JUDGE_RULES = ( - "Decide whether the human must now be interrupted. interrupt=true when any of these appear:\n" - "- the agent asks the human anything, seeks approval, or says a decision is the human's\n" - "- it carried on under an assumption that decides the deliverable and that the human could " - "reasonably reject; a caveat about transient state it then handled is not one\n" - "- it is blocked on something only the human can supply: a credential, a version bump, a release " - "ready to cut, a choice outside the repo\n" - "- it flags that the goals, the plan or the task itself is unclear, missing or in need of change\n" - "- it chose between alternatives the README text does not discriminate between - it does not " - "rule the rejected one out - and the choice materially changes the deliverable\n" - "interrupt=false otherwise. Bookkeeping the agent settled silently - what to document, wording, " - "where a note goes - is not on its own a reason to interrupt. The human may have replied inside the transcript, on a [human] line: judge only what " - "is still open, never a question they already answered there.\n" - "Where the agent asked or flagged something itself, the question is that one, in the agent's own " - "wording; never construct another from facts it stated.\n" - "finished=true when the chunk is complete: merged, or nothing remains that the agent could do on " - "its own. finished=false when work remains that a further run can continue: an open PR, a review " - "not yet run, CI not yet reported." -) -JUDGE_SCHEMA = { - "properties": { - "evidence": {"description": "A verbatim quote of the transcript line that triggers the interrupt. Empty when interrupt is false.", "type": "string"}, - "finished": {"type": "boolean"}, - "interrupt": {"type": "boolean"}, - "question": {"description": "The single question to put to the human. Empty when interrupt is false.", "type": "string"}, - }, - "required": ["evidence", "finished", "interrupt", "question"], - "type": "object", -} - - -def run_cycle(root, task, premises, chosen, paths, env): +def run_cycle(root, task, premises, models, paths): session = session_for(root, paths) resuming = bool(transcript_file(session)) - if failure := run_worker(root, worker_args(task, session, model_for(env, "LOOP_CLAUDE_WORKER_MODEL", chosen), resuming)): + if failure := run_worker(root, worker_args(task, session, models.worker, resuming)): return Retry(failure.reason) path = transcript_file(session) if not path: @@ -57,13 +25,13 @@ def run_cycle(root, task, premises, chosen, paths, env): entries = read(path) if isinstance(entries, Failure): return Stop(1, entries.reason) - verdict = judge(root, task, premises, render(entries), chosen, env) + verdict = judge(root, task, premises, render(entries), models.judge) if isinstance(verdict, Stop): return verdict if not verdict["interrupt"]: break archive(root, path, f"Task: {task}\n\nVerdict: interrupt\n\n{verdict['question']}", paths) - if stop := interrupt(root, session.id, chosen, path, verdict["question"], paths, env): + if stop := interrupt(root, session.id, models.worker, path, verdict["question"], paths): return stop if verdict["finished"]: archive(root, path, f"Task: {task}\n\nVerdict: finished", paths) @@ -89,201 +57,3 @@ def archive(root, path, note, paths): print(f"transcript: {dest}", file=sys.stderr) except OSError as failure: print(f"could not archive the transcript: {failure}", file=sys.stderr) - - -def make_private(folder): - mask = os.umask(0o077) - try: - os.makedirs(folder, exist_ok=True) - finally: - os.umask(mask) - - -def replace_json(path, data, **dump): - staged = f"{path}.{os.getpid()}" - try: - mode = os.stat(path).st_mode & 0o7777 if os.path.exists(path) else 0o600 - with open(os.open(staged, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), "w", encoding="utf-8") as handle: - os.fchmod(handle.fileno(), mode) - json.dump(data, handle, **dump) - os.replace(staged, path) - except OSError as failure: - if os.path.exists(staged): - os.remove(staged) - return failure - return None - - -def model_for(env, variable, chosen): - return env.get(variable) or chosen - - -# ~/.claude/loop-claude-models.json - - -def project_model(root, paths, env): - if env.get("LOOP_CLAUDE_JUDGE_MODEL") and env.get("LOOP_CLAUDE_WORKER_MODEL"): - return "" - saved = paths.models_file - name = project_name(root, paths.code) - models = read_models(saved) - if isinstance(models, Stop): - return models - if chosen := models.get(name): - return chosen - chosen = ask_model(name, saved, paths.model_catalog) - 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) - 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 - - -def read_models(saved): - try: - with open(saved, encoding="utf-8") as handle: - models = json.load(handle) - except FileNotFoundError: - return {} - except (OSError, ValueError) as 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()): - return Stop(1, f"could not read {saved}: not an object mapping projects to model names") - return models - - -def ask_model(name, saved, folder): - if not (sys.stdin.isatty() and sys.stdout.isatty()): - 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(folder) - print(f"\nThe model to run {name} on, saved in {saved}:", file=sys.stderr) - for number, (model_id, label) in enumerate(offered, 1): - print(f" {number}. {label} ({model_id})", file=sys.stderr) - if not offered: - print(f" no model catalog cached in {folder}", file=sys.stderr) - while True: - try: - answer = input(f"{'A number, or any' if offered else 'A'} name claude --model takes: ").strip() - except EOFError: - print(file=sys.stderr) - return Stop(2, "no model picked") - if not answer: - continue - if not (offered and answer.isdecimal()): - return answer - if 1 <= int(answer) <= len(offered): - return offered[int(answer) - 1][0] - print(f"pick 1 to {len(offered)}", file=sys.stderr) - - -def catalog(folder): - newest = {} - for path in folder.glob("*.json"): - try: - with open(path, encoding="utf-8") as handle: - data = json.load(handle) - except (OSError, ValueError): - continue - if isinstance(data, dict) and isinstance(data.get("fetchedAt"), (int, float)) and data["fetchedAt"] > newest.get("fetchedAt", -1): - newest = data - models = newest - for key in ("catalog", "config", "models"): - models = models.get(key) if isinstance(models, dict) else None - return [(entry["id"], entry.get("name", entry["id"])) for entry in models if isinstance(entry, dict) and isinstance(entry.get("id"), str)] if isinstance(models, list) else [] - - -# --json-schema verdicts - - -def judge(root, task, premises, transcript, chosen, env): - # No tools, so the verdict rests on the transcript grounded() checks it against; no persistence, so its runs stay out of the session picker. - args = [ - "-p", - "--json-schema", json.dumps(JUDGE_SCHEMA), - "--model", model_for(env, "LOOP_CLAUDE_JUDGE_MODEL", chosen), - "--no-session-persistence", - "--output-format", "json", - "--permission-mode", "bypassPermissions", - "--tools", "", - ] - prompt = judge_prompt(task, premises, transcript) - for failures in itertools.count(1): - proc = subprocess.run(["claude", *args], capture_output=True, cwd=root, input=prompt, text=True) - verdict = (parse(proc.stdout) or {}).get("structured_output") if proc.returncode == 0 else None - if not complete(verdict): - failure = proc.stderr.strip() or "the judge returned no verdict" - elif not grounded(verdict, transcript): - failure = f"the judge quoted {verdict['evidence']!r}, nothing in the transcript, for the question: {verdict['question']}" - else: - return verdict - if stop := strike("judge", failures, failure): - return stop - - -def judge_prompt(task, premises, transcript): - return ( - f"From README.md:\n{premises}\n\n" - f"The task an agent was given:\n{task}\n\n" - # The tail, where an interrupt or a finish lands; the session's transcript grows cycle over cycle. - f"What the agent did and said, and what the human typed on [human] lines, latest last:\n{transcript[-40000:]}\n\n" - f"{JUDGE_RULES}" - ) - - -def complete(verdict): - return isinstance(verdict, dict) and set(JUDGE_SCHEMA["required"]) <= verdict.keys() - - -def grounded(verdict, transcript): - if not verdict["interrupt"]: - return True - evidence = verdict["evidence"] - return evidence.strip() != "" and evidence in transcript - - -# ~/.claude.json - - -def interrupt(root, session_id, chosen, path, question, paths, env): - print(f"\n{question}", file=sys.stderr) - if not (sys.stdin.isatty() and sys.stdout.isatty()): - return Stop(2, "stdin or stdout is not a terminal") - trust(paths.claude_json, checkouts(root)) - entries = read(path) - if isinstance(entries, Failure): - return Stop(1, entries.reason) - before = human_turns(entries) - subprocess.run(["claude", "--model", model_for(env, "LOOP_CLAUDE_WORKER_MODEL", chosen), "--permission-mode", "bypassPermissions", "--resume", str(session_id)], cwd=root) - entries = read(path) - if isinstance(entries, Failure): - return Stop(1, f"could not tell whether you typed anything: {entries.reason}") - if human_turns(entries) <= before: - return Stop(2, "the interrupt ended without the human typing anything") - return None - - -def trust(config, roots): - try: - with open(config, encoding="utf-8") as handle: - data = json.load(handle) - except (OSError, ValueError) as failure: - print(f"could not read {config}: {getattr(failure, 'strerror', failure)}", file=sys.stderr) - return - projects = data.setdefault("projects", {}) if isinstance(data, dict) else None - if not isinstance(projects, dict) or not all(isinstance(record, dict) for record in projects.values()): - print(f"could not read {config}: not an object whose \"projects\" maps paths to objects", file=sys.stderr) - return - untrusted = [path for path in roots if not projects.get(path, {}).get("hasTrustDialogAccepted")] - if not untrusted: - return - for path in untrusted: - projects.setdefault(path, {})["hasTrustDialogAccepted"] = True - if failure := replace_json(config, data, indent=2): - print(f"could not write {config}: {failure.strerror}", file=sys.stderr) - return - print("trusted for the interrupt: " + ", ".join(untrusted), file=sys.stderr) diff --git a/bin/loop_claude/human.py b/bin/loop_claude/human.py new file mode 100644 index 00000000..0850fc90 --- /dev/null +++ b/bin/loop_claude/human.py @@ -0,0 +1,13 @@ +import sys + +from loop_claude.outcome import Stop + + +def needed(to, but): + return Stop(2, f"the human is needed to {to}, but {but}") + + +def off_terminal(to): + if sys.stdin.isatty() and sys.stdout.isatty(): + return None + return needed(to, "stdin or stdout is not a terminal") diff --git a/bin/loop_claude/interrupt.py b/bin/loop_claude/interrupt.py new file mode 100644 index 00000000..fbe7e7d3 --- /dev/null +++ b/bin/loop_claude/interrupt.py @@ -0,0 +1,31 @@ +import subprocess +import sys + +from loop_claude import human +from loop_claude.checkout import checkouts +from loop_claude.outcome import Failure, Stop +from loop_claude.transcript import human_turns, read +from loop_claude.trust import trust + +TO = "answer the question above" + + +def interrupt(root, session_id, model, path, question, paths): + print(f"\n{question}", file=sys.stderr) + if stop := human.off_terminal(TO): + return stop + trust(paths.claude_json, checkouts(root)) + entries = read(path) + if isinstance(entries, Failure): + return Stop(1, entries.reason) + before = human_turns(entries) + try: + subprocess.run(["claude", "--model", model, "--permission-mode", "bypassPermissions", "--resume", str(session_id)], cwd=root) + except OSError as failure: + return Stop(1, f"could not start claude: {failure.strerror}") + entries = read(path) + if isinstance(entries, Failure): + return Stop(1, f"could not tell whether you typed anything: {entries.reason}") + if human_turns(entries) <= before: + return human.needed(TO, "the interrupt ended without you typing anything") + return None diff --git a/bin/loop_claude/judge.py b/bin/loop_claude/judge.py new file mode 100644 index 00000000..4140ccda --- /dev/null +++ b/bin/loop_claude/judge.py @@ -0,0 +1,95 @@ +import itertools +import json +import subprocess + +from loop_claude.outcome import Failure +from loop_claude.strike import strike +from loop_claude.transcript import parse + +JUDGE_RULES = ( + "Decide whether the human must now be interrupted. interrupt=true when any of these appear:\n" + "- the agent asks the human anything, seeks approval, or says a decision is the human's\n" + "- it carried on under an assumption that decides the deliverable and that the human could " + "reasonably reject; a caveat about transient state it then handled is not one\n" + "- it is blocked on something only the human can supply: a credential, a version bump, a release " + "ready to cut, a choice outside the repo\n" + "- it flags that the goals, the plan or the task itself is unclear, missing or in need of change\n" + "- it chose between alternatives the README text does not discriminate between - it does not " + "rule the rejected one out - and the choice materially changes the deliverable\n" + "interrupt=false otherwise. Bookkeeping the agent settled silently - what to document, wording, " + "where a note goes - is not on its own a reason to interrupt. The human may have replied inside the transcript, on a [human] line: judge only what " + "is still open, never a question they already answered there.\n" + "Where the agent asked or flagged something itself, the question is that one, in the agent's own " + "wording; never construct another from facts it stated.\n" + "finished=true when the chunk is complete: merged, or nothing remains that the agent could do on " + "its own. finished=false when work remains that a further run can continue: an open PR, a review " + "not yet run, CI not yet reported." +) + +JUDGE_SCHEMA = { + "properties": { + "evidence": {"description": "A verbatim quote of the transcript line the verdict rests on: what triggers the interrupt, else what shows the chunk finished or the work remaining.", "type": "string"}, + "finished": {"type": "boolean"}, + "interrupt": {"type": "boolean"}, + "question": {"description": "The single question to put to the human. Empty when interrupt is false.", "type": "string"}, + }, + "required": ["evidence", "finished", "interrupt", "question"], + "type": "object", +} + + +def judge(root, task, premises, transcript, model): + # No tools, so the verdict rests on the transcript grounded() checks it against; no persistence, so its runs stay out of the session picker. + args = [ + "-p", + "--json-schema", json.dumps(JUDGE_SCHEMA), + "--model", model, + "--no-session-persistence", + "--output-format", "json", + "--permission-mode", "bypassPermissions", + "--tools", "", + ] + prompt = judge_prompt(task, premises, transcript) + for failures in itertools.count(1): + verdict = run_judge(root, args, prompt) + if isinstance(verdict, Failure): + failure = verdict.reason + elif not complete(verdict): + failure = "the judge returned no verdict" + elif not grounded(verdict, transcript): + failure = f"the judge quoted {verdict['evidence']!r}, nothing in the transcript" + (f", for the question: {verdict['question']}" if verdict["interrupt"] else "") + else: + return verdict + if stop := strike("judge", failures, failure): + return stop + + +def run_judge(root, args, prompt): + try: + proc = subprocess.run(["claude", *args], capture_output=True, cwd=root, input=prompt, text=True) + except OSError as failure: + return Failure(f"could not start claude: {failure.strerror}") + if proc.returncode != 0: + return Failure(proc.stderr.strip() or f"the judge exited {proc.returncode}") + return (parse(proc.stdout) or {}).get("structured_output") + + +def judge_prompt(task, premises, transcript): + return ( + f"From README.md:\n{premises}\n\n" + f"The task an agent was given:\n{task}\n\n" + # The tail, where an interrupt or a finish lands; the session's transcript grows cycle over cycle. + f"What the agent did and said, and what the human typed on [human] lines, latest last:\n{transcript[-40000:]}\n\n" + f"{JUDGE_RULES}" + ) + + +def complete(verdict): + return isinstance(verdict, dict) and all( + isinstance(verdict.get(name), bool if JUDGE_SCHEMA["properties"][name]["type"] == "boolean" else str) for name in JUDGE_SCHEMA["required"] + ) + + +def grounded(verdict, transcript): + evidence = verdict["evidence"] + return evidence.strip() != "" and evidence in transcript diff --git a/bin/loop_claude/main.py b/bin/loop_claude/main.py index 0789bc58..432d208c 100644 --- a/bin/loop_claude/main.py +++ b/bin/loop_claude/main.py @@ -11,12 +11,13 @@ its session next cycle; the next chunk starts a fresh session. Cycles continue until that interrupt or Ctrl-C. Words: ~/.claude/CLAUDE.md → "Vocabulary". Exit 1: no task, not inside a checkout, no premises, a models file it cannot read or write, claude -leaves no transcript or one it cannot read, a reload with unreadable state, or the worker or the -judge fails three times running. A worker fails when claude cannot start, exits non-zero, is killed, -or ends without a result event; a judge when its verdict misses a field or quotes nothing in the -transcript. +leaves no transcript or one it cannot read, claude cannot start for an interrupt, a reload with +unreadable state, or the worker or the judge fails three times running. A worker fails when claude +cannot start, exits non-zero, is killed, or ends without a result event; a judge when claude cannot +start or exits non-zero, or its verdict misses a field or quotes nothing in the transcript. Exit 2: the human is needed, to pick the model or answer an interrupt, and stdin or stdout is not a -terminal, or the interrupt ended without them typing anything. Rerunning resumes any open session. +terminal, the input ends, or the interrupt ended without them typing anything. Rerunning resumes any +open session. Each project has one session, "A loop-claude", being the checkout relative to ~/code, or to / outside it, deleted when the chunk finishes. Its transcript is archived under @@ -48,7 +49,8 @@ import dataclasses import sys from loop_claude.checkout import checkout_root -from loop_claude.cycle import project_model, run_cycle +from loop_claude.cycle import run_cycle +from loop_claude.models import project_models from loop_claude.outcome import Continue, Retry, Stop from loop_claude.premises import read_premises from loop_claude.reload import RELOAD_FLAG, decode_state, fingerprint, reload_if_edited @@ -84,11 +86,11 @@ def run_loop(argv, env, paths, launcher, cwd): premises = read_premises(state.root) if isinstance(premises, Stop): return premises - chosen = project_model(state.root, paths, env) - if isinstance(chosen, Stop): - return chosen + models = project_models(state.root, paths, env) + if isinstance(models, Stop): + return models print(f"\n=== cycle {state.cycle_number} ===", flush=True) - match run_cycle(state.root, state.task, premises, chosen, paths, env): + match run_cycle(state.root, state.task, premises, models, paths): case Stop() as stop: return stop case Retry(failure): diff --git a/bin/loop_claude/models.py b/bin/loop_claude/models.py new file mode 100644 index 00000000..851bd0ba --- /dev/null +++ b/bin/loop_claude/models.py @@ -0,0 +1,98 @@ +import dataclasses +import json +import sys + +from loop_claude import human +from loop_claude.checkout import project_name +from loop_claude.outcome import Stop +from loop_claude.private_file import replace_json + + +@dataclasses.dataclass(frozen=True) +class Models: + judge: str + worker: str + + +def project_models(root, paths, env): + """LOOP_CLAUDE_JUDGE_MODEL and LOOP_CLAUDE_WORKER_MODEL, each falling back to the project's saved model.""" + judge, worker = env.get("LOOP_CLAUDE_JUDGE_MODEL"), env.get("LOOP_CLAUDE_WORKER_MODEL") + if judge and worker: + return Models(judge, worker) + chosen = project_model(project_name(root, paths.code), paths) + if isinstance(chosen, Stop): + return chosen + return Models(judge or chosen, worker or chosen) + + +def project_model(name, paths): + saved = paths.models_file + models = read_models(saved) + if isinstance(models, Stop): + return models + if chosen := models.get(name): + return chosen + chosen = ask_model(name, saved, paths.model_catalog) + 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) + 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 + + +def read_models(saved): + try: + with open(saved, encoding="utf-8") as handle: + models = json.load(handle) + except FileNotFoundError: + return {} + except (OSError, ValueError) as 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()): + return Stop(1, f"could not read {saved}: not an object mapping projects to model names") + return models + + +def ask_model(name, saved, folder): + if stop := human.off_terminal(f"pick {name}'s model, or merge {{\"{name}\": \"\"}} into {saved}"): + return stop + offered = catalog(folder) + print(f"\nThe model to run {name} on, saved in {saved}:", file=sys.stderr) + for number, (model_id, label) in enumerate(offered, 1): + print(f" {number}. {label} ({model_id})", file=sys.stderr) + if not offered: + print(f" no model catalog cached in {folder}", file=sys.stderr) + while True: + try: + answer = input(f"{'A number, or any' if offered else 'A'} name claude --model takes: ").strip() + except EOFError: + print(file=sys.stderr) + return human.needed(f"pick {name}'s model", "the input ended") + if not answer: + continue + if not (offered and answer.isdecimal()): + return answer + if 1 <= int(answer) <= len(offered): + return offered[int(answer) - 1][0] + print(f"pick 1 to {len(offered)}", file=sys.stderr) + + +def catalog(folder): + newest = {} + for path in folder.glob("*.json"): + try: + with open(path, encoding="utf-8") as handle: + data = json.load(handle) + except (OSError, ValueError): + continue + if isinstance(data, dict) and isinstance(data.get("fetchedAt"), (int, float)) and data["fetchedAt"] > newest.get("fetchedAt", -1): + newest = data + models = newest + for key in ("catalog", "config", "models"): + models = models.get(key) if isinstance(models, dict) else None + return [(entry["id"], entry.get("name", entry["id"])) for entry in models if isinstance(entry, dict) and isinstance(entry.get("id"), str)] if isinstance(models, list) else [] diff --git a/bin/loop_claude/private_file.py b/bin/loop_claude/private_file.py new file mode 100644 index 00000000..44cf070e --- /dev/null +++ b/bin/loop_claude/private_file.py @@ -0,0 +1,25 @@ +import json +import os + + +def make_private(folder): + mask = os.umask(0o077) + try: + os.makedirs(folder, exist_ok=True) + finally: + os.umask(mask) + + +def replace_json(path, data, **dump): + staged = f"{path}.{os.getpid()}" + try: + mode = os.stat(path).st_mode & 0o7777 if os.path.exists(path) else 0o600 + with open(os.open(staged, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), "w", encoding="utf-8") as handle: + os.fchmod(handle.fileno(), mode) + json.dump(data, handle, **dump) + os.replace(staged, path) + except OSError as failure: + if os.path.exists(staged): + os.remove(staged) + return failure + return None diff --git a/bin/loop_claude/trust.py b/bin/loop_claude/trust.py new file mode 100644 index 00000000..299201cb --- /dev/null +++ b/bin/loop_claude/trust.py @@ -0,0 +1,29 @@ +import json +import sys + +from loop_claude.private_file import replace_json + + +def trust(config, roots): + try: + with open(config, encoding="utf-8") as handle: + data = json.load(handle) + except (OSError, ValueError) as failure: + print(f"could not read {config}: {getattr(failure, 'strerror', failure)}", file=sys.stderr) + return + projects = data.setdefault("projects", {}) if isinstance(data, dict) else None + if not isinstance(projects, dict): + print(f"could not read {config}: not an object whose \"projects\" is an object", file=sys.stderr) + return + if wrong := next((path for path, record in projects.items() if not isinstance(record, dict)), None): + print(f"could not read {config}: projects[{json.dumps(wrong)}] is not an object", file=sys.stderr) + return + untrusted = [path for path in roots if not projects.get(path, {}).get("hasTrustDialogAccepted")] + if not untrusted: + return + for path in untrusted: + projects.setdefault(path, {})["hasTrustDialogAccepted"] = True + if failure := replace_json(config, data, indent=2): + print(f"could not write {config}: {failure.strerror}", file=sys.stderr) + return + print("trusted for the interrupt: " + ", ".join(untrusted), file=sys.stderr) diff --git a/docs/decisions.md b/docs/decisions.md index b99a1749..148c4a48 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -20,10 +20,6 @@ 2026-09-24, lilleman. Serves goal 4. `claude --resume` re-enters the worktree the worker last entered, recorded in the transcript's `worktree-state` entry, and Claude Code asks trust per path, so trusting the checkout alone still lands the human in the dialog; trusting every worktree `git worktree list` names spares reading which one from the transcript. Valid while resume re-enters a recorded worktree and trust is kept per path. -## loop-claude: a wrong-shape trust file gets one message, naming the shape - -2026-09-26, larv-review, declining a product-owner nit. Serves goal 4. `trust` says `not an object whose "projects" maps paths to objects` for every wrong shape; naming the failing path would add a branch to `trust`, and the interrupt still lands in Claude Code's own dialog, which shows the path. The 2026-09-25 panel's `trust` as the unit least wanted to modify was the first reason; the 2026-09-26 panel named `typed`, so the entry rests on the dialog. Valid while the interrupt lands in that dialog. - ## bin/: the Python floor is README's Install prerequisite 2026-09-26, larv-review, carrying the floor the 2026-09-26 stability round assumed and verified its f-string fix under. Serves goal 1. The suite reruns itself on a `uv`-fetched interpreter of the version Install names: `ast.parse(feature_version=)` on the host's Python accepts the nested f-string 186181a fixed, a compile check passes a 3.11-only call like `contextlib.chdir`, and a `python3.N` on `PATH` is installed by hand on every machine and again at each bump. Valid while no machine taking the checkout ships an older Python. diff --git a/todo.md b/todo.md index 9cf5980f..81b4af98 100644 --- a/todo.md +++ b/todo.md @@ -6,7 +6,6 @@ The rebuild lifts every dimension: each item below is one chunk on a worktree based on `origin/rebuild`, its PR into `rebuild`, until the last item merges `rebuild` into main. The sketches, the judges' verdicts and what to take from each: `~/code/claude-handoffs/claude-config_2026-09-28.md`. -- **Move the judge, the interrupt, trust and model resolution into their own modules.** The judge is retried alone and checks evidence on every verdict against the rendered transcript; `models` owns the whole resolution, env overrides included, with no sentinel; `trust` names a `projects` entry that is not an object; `input()` at end of file is exit 2. `ask_model` and `interrupt` spell "the human is needed" one way; `replace_json` and `make_private` get one module shared by `models`, `trust` and the archive. - **Move each Claude Code internal `--help` lists beside the module relying on it.** Or `docs/decisions.md` says why `--help` keeps it. - **Archive the raw transcript, deduplicated by content hash, with the verdict beside it, and stop on a failed archive.** Tests first; the changelog line says what the archive now holds. - **Replace `bin/test_loop_claude.py`'s internal-function tests with the black-box tests plus unit tests of the pure parsers.** -- 2.52.0 From 9bfb2fe173b6fb71421413cbc3c8b43bb0b20290 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 16:45:46 +0200 Subject: [PATCH 4/8] Pin an interrupt verdict without a question as incomplete, and one person in the empty-interrupt message --- bin/test_loop_claude.py | 3 ++- bin/test_loop_claude_black_box.py | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/bin/test_loop_claude.py b/bin/test_loop_claude.py index a25565ea..a42fc5b1 100644 --- a/bin/test_loop_claude.py +++ b/bin/test_loop_claude.py @@ -278,7 +278,7 @@ class Interrupt(unittest.TestCase): unittest.mock.patch.multiple(interrupt, checkouts=unittest.mock.DEFAULT, trust=unittest.mock.DEFAULT) as mocks, unittest.mock.patch("subprocess.run") as run, ): - self.assertEqual(interrupt.interrupt(root, SESSION_ID, "m", transcript, "q?", paths_from(pathlib.Path(root), {})), Stop(2, "the human is needed to answer the question above, but the interrupt ended without you typing anything")) + self.assertEqual(interrupt.interrupt(root, SESSION_ID, "m", transcript, "q?", paths_from(pathlib.Path(root), {})), Stop(2, "the human is needed to answer the question above, but the interrupt ended with nothing typed")) mocks["checkouts"].assert_called_with(root) self.assertEqual(run.call_args.kwargs["cwd"], root) self.assertEqual(run.call_args.args[0][run.call_args.args[0].index("--model") + 1], "m") @@ -352,6 +352,7 @@ class Verdict(unittest.TestCase): self.assertFalse(judge.complete({"interrupt": "no", "evidence": "", "finished": True, "question": ""})) self.assertFalse(judge.complete({"interrupt": False, "evidence": None, "finished": True, "question": ""})) self.assertFalse(judge.complete({"interrupt": False})) + self.assertFalse(judge.complete({"interrupt": True, "evidence": "x", "finished": False, "question": " "})) self.assertFalse(judge.complete(None)) diff --git a/bin/test_loop_claude_black_box.py b/bin/test_loop_claude_black_box.py index 67e52a00..c46572a0 100644 --- a/bin/test_loop_claude_black_box.py +++ b/bin/test_loop_claude_black_box.py @@ -408,7 +408,7 @@ class Interrupt(unittest.TestCase): transcript.unlink() run = checkout.run([*asked, interrupt()], terminal_input="") self.assertEqual((run.code, run.roles()), (2, ["worker", "judge", "interrupt"])) - self.assertEqual(run.stderr.strip().splitlines()[-1], "the human is needed to answer the question above, but the interrupt ended without you typing anything") + self.assertEqual(run.stderr.strip().splitlines()[-1], "the human is needed to answer the question above, but the interrupt ended with nothing typed") run = checkout.run([worker(say="A or B?"), judge(interrupt=True, evidence="A or B?", question="A or B?", vanish=True)], terminal_input="") self.assertEqual((run.code, run.roles()), (1, ["worker", "judge"])) -- 2.52.0 From b40893bc70742b84e5118b963ddadaaeec5c7713 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 16:46:18 +0200 Subject: [PATCH 5/8] Retire the section-headers decision, reject an interrupt without a question, and name file_writes by what it does --- AGENTS.md | 1 - bin/loop_claude/cycle.py | 2 +- bin/loop_claude/{private_file.py => file_writes.py} | 0 bin/loop_claude/interrupt.py | 2 +- bin/loop_claude/judge.py | 3 ++- bin/loop_claude/main.py | 5 +++-- bin/loop_claude/models.py | 2 +- bin/loop_claude/trust.py | 4 ++-- docs/decisions.md | 4 ---- 9 files changed, 10 insertions(+), 13 deletions(-) rename bin/loop_claude/{private_file.py => file_writes.py} (100%) diff --git a/AGENTS.md b/AGENTS.md index 4f7aa2eb..e6eb6094 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -12,7 +12,6 @@ Decisions live in `docs/decisions.md`: - bin/: the Python floor is README's Install prerequisite - bin/: host python, no container - comprehension floor: every dimension and the overall at 7.0 or above, and 0.1.0 waits on it -- loop-claude: the section headers stay - vocabulary: the concept words are defined under `CLAUDE.md` → "Vocabulary" and cited by a bare link - larv-review: a re-entered loop takes a fresh round cap - loop-claude: a reload into an older file is unsupported diff --git a/bin/loop_claude/cycle.py b/bin/loop_claude/cycle.py index b9d11697..247c8011 100644 --- a/bin/loop_claude/cycle.py +++ b/bin/loop_claude/cycle.py @@ -6,7 +6,7 @@ from loop_claude.checkout import project_name from loop_claude.interrupt import interrupt from loop_claude.judge import judge from loop_claude.outcome import Continue, Failure, Retry, Stop -from loop_claude.private_file import make_private +from loop_claude.file_writes import make_private from loop_claude.session import delete_session, session_for, transcript_file from loop_claude.transcript import read, render from loop_claude.worker import run_worker, worker_args diff --git a/bin/loop_claude/private_file.py b/bin/loop_claude/file_writes.py similarity index 100% rename from bin/loop_claude/private_file.py rename to bin/loop_claude/file_writes.py diff --git a/bin/loop_claude/interrupt.py b/bin/loop_claude/interrupt.py index fbe7e7d3..31145aad 100644 --- a/bin/loop_claude/interrupt.py +++ b/bin/loop_claude/interrupt.py @@ -27,5 +27,5 @@ def interrupt(root, session_id, model, path, question, paths): if isinstance(entries, Failure): return Stop(1, f"could not tell whether you typed anything: {entries.reason}") if human_turns(entries) <= before: - return human.needed(TO, "the interrupt ended without you typing anything") + return human.needed(TO, "the interrupt ended with nothing typed") return None diff --git a/bin/loop_claude/judge.py b/bin/loop_claude/judge.py index 4140ccda..39617957 100644 --- a/bin/loop_claude/judge.py +++ b/bin/loop_claude/judge.py @@ -85,9 +85,10 @@ def judge_prompt(task, premises, transcript): def complete(verdict): - return isinstance(verdict, dict) and all( + typed = isinstance(verdict, dict) and all( isinstance(verdict.get(name), bool if JUDGE_SCHEMA["properties"][name]["type"] == "boolean" else str) for name in JUDGE_SCHEMA["required"] ) + return typed and not (verdict["interrupt"] and not verdict["question"].strip()) def grounded(verdict, transcript): diff --git a/bin/loop_claude/main.py b/bin/loop_claude/main.py index 432d208c..3802c6ba 100644 --- a/bin/loop_claude/main.py +++ b/bin/loop_claude/main.py @@ -14,9 +14,10 @@ Exit 1: no task, not inside a checkout, no premises, a models file it cannot rea leaves no transcript or one it cannot read, claude cannot start for an interrupt, a reload with unreadable state, or the worker or the judge fails three times running. A worker fails when claude cannot start, exits non-zero, is killed, or ends without a result event; a judge when claude cannot -start or exits non-zero, or its verdict misses a field or quotes nothing in the transcript. +start or exits non-zero, or its verdict misses or mistypes a field, interrupts without a question, +or quotes nothing in the transcript. Exit 2: the human is needed, to pick the model or answer an interrupt, and stdin or stdout is not a -terminal, the input ends, or the interrupt ended without them typing anything. Rerunning resumes any +terminal, the input ends, or the interrupt ended with nothing typed. Rerunning resumes any open session. Each project has one session, "A loop-claude", being the checkout relative to ~/code, diff --git a/bin/loop_claude/models.py b/bin/loop_claude/models.py index 851bd0ba..ae1bb6f7 100644 --- a/bin/loop_claude/models.py +++ b/bin/loop_claude/models.py @@ -5,7 +5,7 @@ import sys from loop_claude import human from loop_claude.checkout import project_name from loop_claude.outcome import Stop -from loop_claude.private_file import replace_json +from loop_claude.file_writes import replace_json @dataclasses.dataclass(frozen=True) diff --git a/bin/loop_claude/trust.py b/bin/loop_claude/trust.py index 299201cb..ab73f25b 100644 --- a/bin/loop_claude/trust.py +++ b/bin/loop_claude/trust.py @@ -1,7 +1,7 @@ import json import sys -from loop_claude.private_file import replace_json +from loop_claude.file_writes import replace_json def trust(config, roots): @@ -15,7 +15,7 @@ def trust(config, roots): if not isinstance(projects, dict): print(f"could not read {config}: not an object whose \"projects\" is an object", file=sys.stderr) return - if wrong := next((path for path, record in projects.items() if not isinstance(record, dict)), None): + if (wrong := next((path for path, record in projects.items() if not isinstance(record, dict)), None)) is not None: print(f"could not read {config}: projects[{json.dumps(wrong)}] is not an object", file=sys.stderr) return untrusted = [path for path in roots if not projects.get(path, {}).get("hasTrustDialogAccepted")] diff --git a/docs/decisions.md b/docs/decisions.md index 148c4a48..598eb123 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -32,10 +32,6 @@ 2026-09-27, lilleman, restating the 2026-09-24 target and extending it to the overall. Serves goal 4. The 2026-09-28 run, Junior A, Mid A, the maintainability senior and the inherited architect at depth 1 over every non-test file, blind to `todo.md` and this log, scored Navigation 7.25, Locality 6.0, Shape 6.5, Self-sufficiency 6.25, overall 6.25; on 2026-09-26 they were 7.75, 6.25, 7.0, 6.75, 6.75. Every seat scored Locality 6, and three of four named `run_cycle`'s three-way return and larv-review's re-entry rules, split across the passes on 2026-09-28. The rebuild planned in `todo.md` under 0.1.0 answers the places named, and a later chunk may not lower any dimension. Valid until the next scoring run, which uses the same four seats. -## loop-claude: the section headers stay - -2026-09-26, larv-review, declining a prose-pass deletion under `CLAUDE.md` → "Comments and documentation". Serves goal 4. Two seats of the 2026-09-26 panel credit Navigation 8 to the headers in what is now `bin/loop_claude/cycle.py`, which index it by the file or format each group touches. Valid while `cycle.py` holds more than one group; a header leaves with its group, as `# The transcript file` did into `transcript.py`. - ## vocabulary: the concept words are defined under `CLAUDE.md` → "Vocabulary" and cited by a bare link 2026-09-24, larv-review. Serves goal 4. Three seats of the 2026-09-24 panel found the words only in the changelog; a definition at each rule lands one reader and misses the next, so the section is the one landing place and each file using the words links it once, and `bin/test_citations.py` fails on a citation no heading or bold lead answers, so the pointer's rot is visible. `loop-claude --help` restates chunk, cycle, interrupt and premises, since a terminal reader has no link to follow. Valid until the next scoring run. -- 2.52.0 From cd9c0fe4a6acf197cfe3287272a32aa90c9672fd Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 16:47:36 +0200 Subject: [PATCH 6/8] Sort the file_writes imports and drop a docstring restating project_models --- bin/loop_claude/cycle.py | 2 +- bin/loop_claude/models.py | 3 +-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/bin/loop_claude/cycle.py b/bin/loop_claude/cycle.py index 247c8011..c5b5e163 100644 --- a/bin/loop_claude/cycle.py +++ b/bin/loop_claude/cycle.py @@ -3,10 +3,10 @@ import sys import time from loop_claude.checkout import project_name +from loop_claude.file_writes import make_private from loop_claude.interrupt import interrupt from loop_claude.judge import judge from loop_claude.outcome import Continue, Failure, Retry, Stop -from loop_claude.file_writes import make_private from loop_claude.session import delete_session, session_for, transcript_file from loop_claude.transcript import read, render from loop_claude.worker import run_worker, worker_args diff --git a/bin/loop_claude/models.py b/bin/loop_claude/models.py index ae1bb6f7..808ad18d 100644 --- a/bin/loop_claude/models.py +++ b/bin/loop_claude/models.py @@ -4,8 +4,8 @@ import sys from loop_claude import human from loop_claude.checkout import project_name -from loop_claude.outcome import Stop from loop_claude.file_writes import replace_json +from loop_claude.outcome import Stop @dataclasses.dataclass(frozen=True) @@ -15,7 +15,6 @@ class Models: def project_models(root, paths, env): - """LOOP_CLAUDE_JUDGE_MODEL and LOOP_CLAUDE_WORKER_MODEL, each falling back to the project's saved model.""" judge, worker = env.get("LOOP_CLAUDE_JUDGE_MODEL"), env.get("LOOP_CLAUDE_WORKER_MODEL") if judge and worker: return Models(judge, worker) -- 2.52.0 From 7b1ee20c7c3b3d5be23bd2f9af338ab55f3e4ae6 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 16:48:46 +0200 Subject: [PATCH 7/8] Pin a reason per incomplete verdict, the rerun hint off a terminal, and which claude could not start --- bin/test_loop_claude.py | 15 +++++++-------- bin/test_loop_claude_black_box.py | 11 ++++++----- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/bin/test_loop_claude.py b/bin/test_loop_claude.py index a42fc5b1..432645f9 100644 --- a/bin/test_loop_claude.py +++ b/bin/test_loop_claude.py @@ -271,7 +271,7 @@ class Interrupt(unittest.TestCase): transcript = os.path.join(root, "session.jsonl") pathlib.Path(transcript).write_text("{}\n") with unittest.mock.patch("sys.stdin.isatty", return_value=False): - self.assertEqual(interrupt.interrupt(root, SESSION_ID, "m", transcript, "q?", paths_from(pathlib.Path(root), {})), Stop(2, "the human is needed to answer the question above, but stdin or stdout is not a terminal")) + self.assertEqual(interrupt.interrupt(root, SESSION_ID, "m", transcript, "q?", paths_from(pathlib.Path(root), {})), Stop(2, "the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun loop-claude on a terminal")) with ( unittest.mock.patch("sys.stdin.isatty", return_value=True), unittest.mock.patch("sys.stdout.isatty", return_value=True), @@ -348,12 +348,11 @@ class Grounded(unittest.TestCase): class Verdict(unittest.TestCase): def test_needs_every_field_the_schema_requires(self): - self.assertTrue(judge.complete({"interrupt": False, "evidence": "", "finished": True, "question": ""})) - self.assertFalse(judge.complete({"interrupt": "no", "evidence": "", "finished": True, "question": ""})) - self.assertFalse(judge.complete({"interrupt": False, "evidence": None, "finished": True, "question": ""})) - self.assertFalse(judge.complete({"interrupt": False})) - self.assertFalse(judge.complete({"interrupt": True, "evidence": "x", "finished": False, "question": " "})) - self.assertFalse(judge.complete(None)) + 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") STUB_CLAUDE = """#!/usr/bin/env python3 @@ -411,7 +410,7 @@ class RunCycle(unittest.TestCase): self.assertEqual(cycle.run_cycle(home, "task", "premises", OPUS, paths), Continue()) pathlib.Path(verdicts).write_text("interrupt") with unittest.mock.patch("sys.stderr") as stderr: - self.assertEqual(cycle.run_cycle(home, "task", "premises", OPUS, paths), Stop(2, "the human is needed to answer the question above, but stdin or stdout is not a terminal")) + self.assertEqual(cycle.run_cycle(home, "task", "premises", OPUS, paths), Stop(2, "the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun loop-claude on a terminal")) self.assertIn(f"transcript: {paths.archive}", "".join(str(call.args[0]) for call in stderr.write.call_args_list)) pathlib.Path(verdicts).write_text("interrupt fail fail fail") with unittest.mock.patch("sys.stderr"), unittest.mock.patch.object(cycle, "interrupt", return_value=None): diff --git a/bin/test_loop_claude_black_box.py b/bin/test_loop_claude_black_box.py index c46572a0..51f84aff 100644 --- a/bin/test_loop_claude_black_box.py +++ b/bin/test_loop_claude_black_box.py @@ -315,7 +315,8 @@ class Cycles(unittest.TestCase): self.assertEqual(run.roles(), ["worker", "judge", "judge", "judge"]) self.assertEqual(run.sleeps, [60, 60]) self.assertIn("retrying the judge in a minute: judge down", run.stderr) - self.assertEqual(run.stderr.strip().splitlines()[-1], "the judge failed three times running: the judge returned no verdict") + self.assertIn("retrying the judge in a minute: the judge returned no verdict", run.stderr) + self.assertEqual(run.stderr.strip().splitlines()[-1], "the judge failed three times running: the judge's verdict has no evidence of type string") def test_retries_the_judge_alone_when_its_verdict_quotes_nothing_in_the_transcript(self): checkout = Checkout(self) @@ -375,13 +376,13 @@ class Interrupt(unittest.TestCase): steps = [worker(say="Shall I use A or B?"), judge(interrupt=True, evidence="Shall I use A or B?", question="A or B?")] run = checkout.run(steps) self.assertEqual((run.code, run.roles()), (2, ["worker", "judge"])) - self.assertEqual(run.stderr.strip().splitlines()[-2:], ["A or B?", "the human is needed to answer the question above, but stdin or stdout is not a terminal"]) + self.assertEqual(run.stderr.strip().splitlines()[-2:], ["A or B?", "the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun loop-claude on a terminal"]) self.assertTrue(checkout.archived()) session = argument(run.calls[0], "--session-id") run = checkout.run(steps, terminal_input="", stdout_on_terminal=False) self.assertEqual((run.code, run.roles()), (2, ["worker", "judge"])) self.assertEqual(argument(run.calls[0], "--resume"), session) - self.assertEqual(run.stderr.strip().splitlines()[-1], "the human is needed to answer the question above, but stdin or stdout is not a terminal") + self.assertEqual(run.stderr.strip().splitlines()[-1], "the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun loop-claude on a terminal") def test_hands_the_terminal_over_and_exits_2_when_nothing_is_typed(self): checkout = Checkout(self) @@ -412,7 +413,7 @@ class Interrupt(unittest.TestCase): run = checkout.run([worker(say="A or B?"), judge(interrupt=True, evidence="A or B?", question="A or B?", vanish=True)], terminal_input="") self.assertEqual((run.code, run.roles()), (1, ["worker", "judge"])) - self.assertEqual(run.stderr.strip().splitlines()[-1], "could not start claude: No such file or directory") + self.assertEqual(run.stderr.strip().splitlines()[-1], "could not start claude for the interrupt: No such file or directory") @unittest.skipIf(os.geteuid() == 0, "root reads an unreadable file") def test_exits_1_when_the_transcript_cannot_be_read_after_the_interrupt(self): @@ -435,7 +436,7 @@ class Models(unittest.TestCase): self.catalog(checkout) run = checkout.run([worker()]) self.assertEqual((run.code, run.calls), (2, [])) - self.assertEqual(run.stderr.strip(), f'the human is needed to pick proj\'s model, or merge {{"proj": ""}} into {checkout.models_file()}, but stdin or stdout is not a terminal') + self.assertEqual(run.stderr.strip(), f'the human is needed to pick proj\'s model, or merge {{"proj": ""}} into {checkout.models_file()}, but stdin or stdout is not a terminal; rerun loop-claude on a terminal') run = checkout.run([worker()], terminal_input="\x04") self.assertEqual((run.code, run.calls), (2, [])) -- 2.52.0 From 1be6ae818775efb0f14a7b939feeefd89e958654 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Mon, 28 Sep 2026 16:49:17 +0200 Subject: [PATCH 8/8] Name why a verdict is incomplete, say how to proceed off a terminal, and which claude could not start --- CHANGELOG.md | 2 +- bin/loop_claude/human.py | 2 +- bin/loop_claude/interrupt.py | 2 +- bin/loop_claude/judge.py | 19 ++++++++++++------- 4 files changed, 15 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c2b87599..66b2b001 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,6 @@ - `loop-claude`'s no-premises exit names what is wrong: `README.md` unopenable or not UTF-8, a `## Goals` or `## Audience` heading missing or repeated, or nothing under one. - `loop-claude` says why when it cannot read or write `~/.claude.json` before an interrupt, naming a `projects` entry that is not an object, and the interrupt then lands in Claude Code's trust dialog. - `loop-claude` skips a transcript line it cannot parse, exits 1 naming a transcript it cannot read, and counts a `claude` it cannot start as a failed worker run. -- `loop-claude`'s judge quotes the transcript for every verdict, and a verdict quoting nothing, or a `claude` the judge cannot start, is a failed judge run; a `claude` that cannot start for an interrupt exits 1. +- `loop-claude`'s judge quotes the transcript for every verdict, and a verdict quoting nothing or interrupting without a question, or a `claude` the judge cannot start, is a failed judge run; a `claude` that cannot start for an interrupt exits 1. - `loop-claude`'s exit-2 message says what the human is needed for. - `loop-claude` keeps the mode of `~/.claude.json` and of its models file when it rewrites them, and creates the models file 0600. diff --git a/bin/loop_claude/human.py b/bin/loop_claude/human.py index 0850fc90..2d87aa2f 100644 --- a/bin/loop_claude/human.py +++ b/bin/loop_claude/human.py @@ -10,4 +10,4 @@ def needed(to, but): def off_terminal(to): if sys.stdin.isatty() and sys.stdout.isatty(): return None - return needed(to, "stdin or stdout is not a terminal") + return needed(to, "stdin or stdout is not a terminal; rerun loop-claude on a terminal") diff --git a/bin/loop_claude/interrupt.py b/bin/loop_claude/interrupt.py index 31145aad..5a965f7d 100644 --- a/bin/loop_claude/interrupt.py +++ b/bin/loop_claude/interrupt.py @@ -22,7 +22,7 @@ def interrupt(root, session_id, model, path, question, paths): try: subprocess.run(["claude", "--model", model, "--permission-mode", "bypassPermissions", "--resume", str(session_id)], cwd=root) except OSError as failure: - return Stop(1, f"could not start claude: {failure.strerror}") + return Stop(1, f"could not start claude for the interrupt: {failure.strerror}") entries = read(path) if isinstance(entries, Failure): return Stop(1, f"could not tell whether you typed anything: {entries.reason}") diff --git a/bin/loop_claude/judge.py b/bin/loop_claude/judge.py index 39617957..28a9cbda 100644 --- a/bin/loop_claude/judge.py +++ b/bin/loop_claude/judge.py @@ -54,8 +54,8 @@ def judge(root, task, premises, transcript, model): verdict = run_judge(root, args, prompt) if isinstance(verdict, Failure): failure = verdict.reason - elif not complete(verdict): - failure = "the judge returned no verdict" + elif reason := incomplete(verdict): + failure = reason elif not grounded(verdict, transcript): failure = f"the judge quoted {verdict['evidence']!r}, nothing in the transcript" + (f", for the question: {verdict['question']}" if verdict["interrupt"] else "") else: @@ -84,11 +84,16 @@ def judge_prompt(task, premises, transcript): ) -def complete(verdict): - typed = isinstance(verdict, dict) and all( - isinstance(verdict.get(name), bool if JUDGE_SCHEMA["properties"][name]["type"] == "boolean" else str) for name in JUDGE_SCHEMA["required"] - ) - return typed and not (verdict["interrupt"] and not verdict["question"].strip()) +def incomplete(verdict): + if not isinstance(verdict, dict): + return "the judge returned no verdict" + for name in JUDGE_SCHEMA["required"]: + kind = JUDGE_SCHEMA["properties"][name]["type"] + if not isinstance(verdict.get(name), bool if kind == "boolean" else str): + return f"the judge's verdict has no {name} of type {kind}" + if verdict["interrupt"] and not verdict["question"].strip(): + return "the judge interrupted without a question" + return None def grounded(verdict, transcript): -- 2.52.0