Fix the round loop's judge retry, reload and archive modes in loop-claude

This commit is contained in:
2026-09-24 22:12:53 +02:00
parent ed469ff874
commit 42f649bf70
3 changed files with 133 additions and 47 deletions
+55 -41
View File
@@ -9,15 +9,16 @@ or a release ready to cut, hands the session over: `claude --resume` on the term
chunk resumes the same session next round; a finished one starts a fresh session. Rounds continue
until Ctrl-C or that handoff.
Exit 1: no task, the README gate blocks, claude leaves no transcript, or claude fails three rounds
running. Exit 2: the human is needed and no terminal is attached, or the handoff ended without them
typing anything. Before a handoff every worktree is marked trusted in ~/.claude.json.
Exit 1: no task, the README gate blocks, claude leaves no transcript, or the worker or the judge fails
three times running. Exit 2: the human is needed and no terminal is attached, or the handoff ended
without them typing anything. Before a handoff every worktree is marked trusted in ~/.claude.json.
Each project has one session, "A ~/code/<path> auto-mode" (the absolute path outside ~/code),
resumed while present and deleted when the chunk finishes. Its transcript is archived under
$AUTO_MODE_TRANSCRIPTS (default ~/.claude/auto-mode-transcripts/<path>/) whenever the human is asked
and when the chunk finishes. JUDGE_MODEL and WORKER_MODEL override the model the project's
Claude Code settings pick. A change to this file takes effect at the next round boundary.
Claude Code settings pick. A change to this file takes effect at the next round boundary, once the
new file answers --help.
Claude Code internals this rests on, observed on 2.1.282:
- The transcript is ~/.claude/projects/*/<session-id>.jsonl, one JSON object per line. A <session-id>/
@@ -39,6 +40,7 @@ import time
import uuid
ARCHIVE = os.path.expanduser(os.environ.get("AUTO_MODE_TRANSCRIPTS", "~/.claude/auto-mode-transcripts"))
FAILURES = "LOOP_CLAUDE_FAILURES"
ROUND = "LOOP_CLAUDE_ROUND"
SESSION_NAMESPACE = uuid.UUID("64fb586b-d926-4bb3-a44c-c903e86d3eec")
SOURCE = open(__file__, encoding="utf-8").read()
@@ -82,6 +84,8 @@ def sections(text):
if line.startswith("## "):
current = line.strip()[3:]
found[current] = []
elif line.startswith("#"):
current = None
elif current and line.strip():
found[current].append(line)
return {name: "\n".join(body) for name, body in found.items() if body}
@@ -97,24 +101,20 @@ def gate():
return f"## Goals\n{found['Goals']}\n\n## Audience\n{found['Audience']}"
def project_path():
def project():
root = os.path.expanduser("~/code")
cwd = os.getcwd()
if cwd == root:
return "code"
if cwd.startswith(f"{root}/"):
return os.path.relpath(cwd, root)
return cwd.lstrip("/")
if cwd == root or cwd.startswith(f"{root}/"):
return "~/" + os.path.relpath(cwd, os.path.dirname(root))
return cwd
def project_path():
return project().removeprefix("~").lstrip("/")
def session_name():
root = os.path.expanduser("~/code")
cwd = os.getcwd()
if cwd == root:
return "A ~/code auto-mode"
if cwd.startswith(f"{root}/"):
return f"A ~/code/{os.path.relpath(cwd, root)} auto-mode"
return f"A {cwd} auto-mode"
return f"A {project()} auto-mode"
def session_file(session_id):
@@ -161,25 +161,28 @@ def render(entries):
return "\n\n".join(lines)
def typed(content):
if isinstance(content, str):
return not content.startswith("<")
parts = content if isinstance(content, list) else []
return bool(parts) and all(isinstance(part, dict) and part.get("type") == "text" and not part.get("text", "").startswith("[Request interrupted") for part in parts)
def human_turns(entries):
spoken = 0
for entry in entries:
if entry.get("type") != "user" or entry.get("isMeta"):
continue
content = entry.get("message", {}).get("content")
if isinstance(content, str) and not content.startswith("<"):
spoken += 1
elif isinstance(content, list) and not any(said(part) == "" or said(part).startswith("[Request interrupted") for part in content):
spoken += 1
return spoken
return sum(1 for entry in entries if entry.get("type") == "user" and not entry.get("isMeta") and typed(entry.get("message", {}).get("content")))
def make_private(folder):
if folder and not os.path.isdir(folder):
make_private(os.path.dirname(folder))
os.mkdir(folder, 0o700)
def archive(path, note):
folder = os.path.join(ARCHIVE, project_path())
try:
stamp = time.strftime("%Y-%m-%dT%H-%M-%SZ", time.gmtime(os.path.getmtime(path)))
os.makedirs(folder, mode=0o700, exist_ok=True)
os.chmod(ARCHIVE, 0o700)
make_private(folder)
dest = os.path.join(folder, f"{stamp}.md")
if not os.path.exists(dest):
with open(os.open(dest, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), "w", encoding="utf-8") as copy:
@@ -291,6 +294,15 @@ def judge(task, premises, transcript):
return verdict
def verdict_on(task, premises, path):
for attempt in range(3):
if verdict := judge(task, premises, render(entries(path))):
return verdict
print("the judge failed - retrying in a minute", file=sys.stderr)
time.sleep(60)
sys.exit("the judge failed three times running")
def handoff(session_id, path, question):
print(f"\n{question}", file=sys.stderr)
if not (sys.stdin.isatty() and sys.stdout.isatty()):
@@ -308,29 +320,31 @@ def run_round(task, premises, name, session_id):
path = session_file(session_id)
if not path:
sys.exit(f"claude left no transcript for session {session_id}")
verdict = judge(task, premises, render(entries(path)))
while verdict and verdict["ask"]:
verdict = verdict_on(task, premises, path)
while verdict["ask"]:
archive(path, f"Task: {task}\n\nVerdict: needs input\n\n{verdict['question']}")
if not handoff(session_id, path, verdict["question"]):
sys.exit(2)
verdict = judge(task, premises, render(entries(path)))
if not verdict:
return False
verdict = verdict_on(task, premises, path)
if verdict["finished"]:
archive(path, f"Task: {task}\n\nVerdict: finished")
end_session(path)
return True
def reload_if_edited(round_number):
def reload_if_edited(round_number, failures):
try:
source = open(__file__, encoding="utf-8").read()
compile(source, __file__, "exec")
except (OSError, SyntaxError) as failure:
except OSError as failure:
print(f"keeping the running script: {failure}", file=sys.stderr)
return
if source == SOURCE:
return
trial = subprocess.run([sys.executable, __file__, "--help"], capture_output=True, text=True)
if trial.returncode != 0:
print(f"keeping the running script: {trial.stderr.strip()}", file=sys.stderr)
return
os.environ[FAILURES] = str(failures)
os.environ[ROUND] = str(round_number)
os.execv(sys.executable, [sys.executable, __file__, *sys.argv[1:]])
@@ -340,10 +354,10 @@ def main():
if task in ("", "-h", "--help"):
print(__doc__.strip())
sys.exit(0 if task else 1)
failures = int(os.environ.pop(FAILURES, 0))
round_number = int(os.environ.pop(ROUND, 0))
failures = 0
while True:
reload_if_edited(round_number)
reload_if_edited(round_number, failures)
round_number += 1
premises = gate()
name = session_name()
@@ -353,8 +367,8 @@ def main():
continue
failures += 1
if failures == 3:
sys.exit("claude failed three rounds running")
print("claude failed - retrying in a minute", file=sys.stderr)
sys.exit("the worker failed three times running")
print("the worker failed - retrying in a minute", file=sys.stderr)
time.sleep(60)