Say why the worker failed: the exit code, or exit 0 without a result event #45

Merged
lilleman merged 4 commits from worker-failure into main 2026-09-25 18:03:28 +02:00
4 changed files with 47 additions and 15 deletions
+1
View File
@@ -5,6 +5,7 @@
- Track the authored configuration: `CLAUDE.md`, `AGENTS.md`, `settings.json`, `statusline.sh`, agents, skills and principles. Credentials, transcripts and memory files stay untracked.
- `loop-claude <task>` runs a project's next chunk cycle after cycle, interrupting only for a decision that is yours or a release ready to cut.
- `loop-claude` exits 1 when the judge fails three times running; a verdict missing a field or quoting nothing in the transcript is a failure.
- `loop-claude` says why the worker failed: the exit code, the signal that killed it, or an exit 0 without a result event.
- `loop-claude` exits 2 when an interrupt gets no answer, saying why: stdin or stdout is not a terminal, or nothing was typed. Rerunning resumes the session.
- `loop-claude` archives each session's transcript under `~/.claude/loop-claude-transcripts/`, one folder per project; `LOOP_CLAUDE_TRANSCRIPTS` overrides the root.
- `loop-claude` runs at the checkout root wherever inside the checkout it is started.
+19 -13
View File
@@ -11,9 +11,10 @@ An unfinished chunk resumes the same session next cycle; a finished one starts a
Cycles continue until that interrupt or Ctrl-C. Words: ~/.claude/CLAUDE.md → "Vocabulary".
Exit 1: no task, not inside a checkout, no premises, claude leaves no transcript, or the worker or
the judge fails three times running. A judge fails when its verdict misses a field or quotes nothing
in the transcript. Exit 2: the human is needed and stdin or stdout is not a terminal, or the
interrupt ended without them typing anything. Rerunning resumes any open session.
the judge fails three times running. A worker fails when claude 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.
Exit 2: the human is needed and stdin or stdout is not a terminal, or the interrupt ended without
them typing anything. Rerunning resumes any open session.
Each project has one session, "A <path> loop-claude", <path> being the checkout relative to ~/code,
or to / outside it, deleted when the chunk finishes. Its transcript is archived under
@@ -262,16 +263,21 @@ def worker_args(task, name, session_id, resuming):
def run_worker(args):
proc = subprocess.Popen(["claude", *args], stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, text=True)
done = {}
done = False
for raw in proc.stdout:
event = parse(raw) or {}
if event.get("type") == "result":
done = event
done = True
elif event.get("type") == "assistant":
for part in event.get("message", {}).get("content", []):
if line := said(part, 160):
print(line, flush=True)
return done if proc.wait() == 0 else {}
code = proc.wait()
if code < 0:
return f"claude killed by signal {-code}"
if code:
return f"claude exited {code}"
return "" if done else "claude exited 0 without a result event"
def judge_prompt(task, premises, transcript):
@@ -328,9 +334,8 @@ def interrupt(session_id, path, question):
def run_cycle(task, premises, name, session_id):
worked = run_worker(worker_args(task, name, session_id, resuming=session_open(session_id)))
if not worked:
return False
if failure := run_worker(worker_args(task, name, session_id, 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}")
@@ -344,7 +349,7 @@ def run_cycle(task, premises, name, session_id):
if verdict["finished"]:
archive(path, f"Task: {task}\n\nVerdict: finished")
end_session(path)
return True
return ""
def reload_if_edited(task, cycle_number, failures):
@@ -378,13 +383,14 @@ def main():
premises = read_premises()
name = session_name()
print(f"\n=== cycle {cycle_number} ===", flush=True)
if run_cycle(task, premises, name, uuid.uuid5(SESSION_NAMESPACE, name)):
failure = run_cycle(task, premises, name, uuid.uuid5(SESSION_NAMESPACE, name))
if not failure:
failures = 0
continue
failures += 1
if failures == 3:
sys.exit("the worker failed three times running")
print("the worker failed - retrying in a minute", file=sys.stderr)
sys.exit(f"the worker failed three times running: {failure}")
print(f"retrying the worker in a minute: {failure}", file=sys.stderr)
time.sleep(60)
+27 -1
View File
@@ -275,6 +275,23 @@ else:
"""
class RunWorker(unittest.TestCase):
def test_says_whether_a_non_zero_exit_or_a_missing_result_event_failed_it(self):
with tempfile.TemporaryDirectory() as bin:
stub = os.path.join(bin, "claude")
scripts = {
"": 'print(json.dumps({"type": "result"}))',
"claude exited 0 without a result event": 'print(json.dumps({"type": "assistant", "message": {"content": [{"type": "text", "text": "worked"}]}}))',
"claude exited 3": "sys.exit(3)",
"claude killed by signal 9": "os.kill(os.getpid(), 9)",
}
with unittest.mock.patch.dict(os.environ, {"PATH": f"{bin}:{os.environ['PATH']}"}), unittest.mock.patch.object(sys, "stdout", io.StringIO()):
for failure, script in scripts.items():
open(stub, "w").write(f"#!/usr/bin/env python3\nimport json\nimport os\nimport sys\n{script}\n")
os.chmod(stub, 0o700)
self.assertEqual(loop.run_worker([]), failure)
class RunCycle(unittest.TestCase):
def test_resumes_until_the_judge_calls_the_chunk_finished_and_rejudges_a_failed_or_unquoted_verdict(self):
with tempfile.TemporaryDirectory() as home:
@@ -287,7 +304,7 @@ 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.assertTrue(loop.run_cycle("task", "premises", "A name", SESSION_ID))
self.assertEqual(loop.run_cycle("task", "premises", "A name", SESSION_ID), "")
open(verdicts, "w").write("ask")
with self.assertRaises(SystemExit) as stopped, unittest.mock.patch("sys.stderr") as stderr:
loop.run_cycle("task", "premises", "A name", SESSION_ID)
@@ -338,6 +355,15 @@ class Main(unittest.TestCase):
loop.main()
mocks[2].assert_called_once_with("do it", 3, 2)
self.assertIn("=== cycle 4 ===", sys.stdout.getvalue())
mocks[3].side_effect = ["claude exited 3"] * 3
stack.enter_context(unittest.mock.patch.object(sys, "argv", ["loop-claude", loop.RELOAD_FLAG, "3", "0", "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.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
@@ -4,7 +4,6 @@
Ordered by how many seats of the 2026-09-25 scoring panel (`docs/decisions.md`) named the place; each is one chunk.
- Say why the worker failed when `claude` exits 0 without a result event, today `run_worker` returns `{}` for that and for a non-zero exit and prints nothing.
- Pass the checkout root to `project`, `read_premises` and `checkouts`, today each reads the cwd `main` set once.
- Reject empty evidence in `grounded` by name, today `bool(evidence) and evidence in transcript`, where a tidy-up drops the guard and `"" in transcript` is always true.
- Split `CLAUDE.md`'s release bullet under "Working loop" so the plan-it and stop predicates each stand alone, today six rules in one paragraph differing by one clause.