Derive the round's state from the session file, name the steps, and test the pure core

This commit is contained in:
2026-09-24 20:21:06 +02:00
parent 8f647f8596
commit 839804f47e
8 changed files with 390 additions and 177 deletions
+187 -169
View File
@@ -1,4 +1,22 @@
#!/usr/bin/env python3
"""Run a task as headless claude rounds; a judge stops the loop only when a decision is the human's.
usage: loop-claude <task>
Run it in a project checkout whose README.md has ## Goals and ## Audience. Each round a worker runs
the task; a judge then reads the transcript against the README. A question only the human can answer
opens `claude --resume` on the terminal. An unfinished chunk resumes the same session next round; a
finished one starts a fresh session. Rounds continue until Ctrl-C.
Exit 1: the README gate blocks, 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.
Each project has one session, "A ~/code/<path> auto-mode", at an id derived from that name; it is
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 models. A change to this
file takes effect at the next round boundary.
"""
import glob
import json
import os
@@ -9,11 +27,32 @@ import uuid
ARCHIVE = os.path.expanduser(os.environ.get("AUTO_MODE_TRANSCRIPTS", "~/.claude/auto-mode-transcripts"))
JUDGE_MODEL = os.environ.get("JUDGE_MODEL", "claude-opus-5-5")
ROUND = "LOOP_CLAUDE_ROUND"
SLOT_NAMESPACE = uuid.UUID("64fb586b-d926-4bb3-a44c-c903e86d3eec")
SOURCE = open(__file__, encoding="utf-8").read()
STATE = "LOOP_CLAUDE_STATE"
WORKER_MODEL = os.environ.get("WORKER_MODEL", "claude-opus-5-5")
JUDGE_RULES = (
"Decide whether the human must now be interrupted. ask=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 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"
"ask=false otherwise. A sensible preference is not a derivation. 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: judge only what is still open, "
"never a question they already answered there.\n"
"The question must be one the agent itself raised. Never construct a question from facts the agent "
"stated. When ask=true, quote the agent's own wording where it already framed the question.\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": {
"ask": {"type": "boolean"},
@@ -26,41 +65,9 @@ JUDGE_SCHEMA = {
}
def claude(args):
proc = subprocess.run(["claude", *args], capture_output=True, text=True)
if proc.returncode != 0:
sys.exit(proc.stderr.strip() or "claude failed")
return json.loads(proc.stdout)
def work(args):
proc = subprocess.Popen(["claude", *args], stdout=subprocess.PIPE, text=True)
done = {}
for line in proc.stdout:
try:
event = json.loads(line)
except ValueError:
continue
if event.get("type") == "result":
done = event
elif event.get("type") == "assistant":
for part in event["message"]["content"]:
if part["type"] == "text" and part["text"].strip():
print(part["text"], flush=True)
elif part["type"] == "tool_use":
print(f"· {part['name']} {json.dumps(part['input'])[:160]}", flush=True)
if proc.wait() != 0 or not done:
sys.exit("claude failed")
return done
def sections():
try:
lines = open("README.md", encoding="utf-8").read().splitlines()
except OSError:
return {}
def sections(text):
found, current = {}, None
for line in lines:
for line in text.splitlines():
if line.startswith("## "):
current = line.strip()[3:]
found[current] = []
@@ -69,6 +76,16 @@ def sections():
return {name: "\n".join(body) for name, body in found.items() if body}
def premises():
try:
found = sections(open("README.md", encoding="utf-8").read())
except OSError:
found = {}
if not found.get("Goals") or not found.get("Audience"):
sys.exit("README.md needs ## Goals and ## Audience - the gate blocks.")
return f"## Goals\n{found['Goals']}\n\n## Audience\n{found['Audience']}"
def project_path():
root = os.path.expanduser("~/code")
cwd = os.getcwd()
@@ -89,14 +106,12 @@ def session_name():
return f"A {cwd} auto-mode"
def slot_file(session_id):
hit = glob.glob(os.path.expanduser(f"~/.claude/projects/*/{session_id}.jsonl"))
def session_file(slot):
hit = glob.glob(os.path.expanduser(f"~/.claude/projects/*/{slot}.jsonl"))
return hit[0] if hit else ""
def entries(path):
if not path:
return
for raw in open(path, encoding="utf-8"):
try:
entry = json.loads(raw)
@@ -106,36 +121,9 @@ def entries(path):
yield entry
def clear_slot(name, slot):
path = slot_file(slot)
if not path:
return True
for entry in entries(path):
if "agentName" in entry:
if entry["agentName"] != name:
return False
archive(path, "Archived when a later run cleared the slot.")
os.remove(path)
return True
return False
def typed(path):
spoken = 0
for entry in entries(path):
if entry.get("type") != "user":
continue
content = entry.get("message", {}).get("content")
if isinstance(content, str):
spoken += 1
elif isinstance(content, list) and not any(part.get("type") == "tool_result" for part in content if isinstance(part, dict)):
spoken += 1
return spoken
def render(path):
def render(entries):
said = []
for entry in entries(path):
for entry in entries:
if entry.get("type") != "assistant":
continue
for part in entry.get("message", {}).get("content", []):
@@ -148,21 +136,30 @@ def render(path):
return "\n\n".join(said)
def human_turns(entries):
spoken = 0
for entry in entries:
if entry.get("type") != "user":
continue
content = entry.get("message", {}).get("content")
if isinstance(content, str):
spoken += 1
elif isinstance(content, list) and not any(part.get("type") == "tool_result" for part in content if isinstance(part, dict)):
spoken += 1
return spoken
def archive(path, note):
if not path:
return ""
folder = os.path.join(ARCHIVE, project_path())
try:
stamp = time.strftime("%Y-%m-%dT%H-%M-%S", time.localtime(os.path.getmtime(path)))
stamp = time.strftime("%Y-%m-%dT%H-%M-%SZ", time.gmtime(os.path.getmtime(path)))
os.makedirs(folder, exist_ok=True)
dest = os.path.join(folder, f"{stamp}.md")
if os.path.exists(dest):
return dest
open(dest, "w", encoding="utf-8").write(f"# {stamp} {project_path()}\n\n{note}\n\n{render(path)}\n")
if not os.path.exists(dest):
open(dest, "w", encoding="utf-8").write(f"# {stamp} {project_path()}\n\n{note}\n\n{render(entries(path))}\n")
print(f"transcript: {dest}", file=sys.stderr)
except OSError as failure:
print(f"could not archive the transcript: {failure}", file=sys.stderr)
return ""
return dest
def checkouts():
@@ -174,15 +171,16 @@ def checkouts():
def trust(paths):
# No CLI flag skips the trust dialog, and the interactive resume would stall on it in every worktree the round created.
config = os.path.expanduser("~/.claude.json")
try:
data = json.load(open(config, encoding="utf-8"))
except (OSError, ValueError):
return []
return
projects = data.setdefault("projects", {})
granted = [path for path in paths if not projects.setdefault(path, {}).get("hasTrustDialogAccepted")]
if not granted:
return []
return
for path in granted:
projects[path]["hasTrustDialogAccepted"] = True
staged = f"{config}.loop-claude"
@@ -192,49 +190,107 @@ def trust(paths):
os.replace(staged, config)
except OSError as failure:
print(f"could not record trust: {failure}", file=sys.stderr)
return []
return granted
return
print("trusted for the handoff: " + ", ".join(granted), file=sys.stderr)
def interrupt(task, premises, work):
verdict = claude([
"-p",
def worker_args(task, name, slot, resuming):
if resuming:
start = ["-p", "Continue the task; the previous run stopped before it was finished.", "--resume", str(slot)]
else:
start = ["-p", f"{task}\n\nContinue any open draft PR or worktree for the item before creating a new one.", "--name", name, "--session-id", str(slot)]
return [
*start,
"--output-format", "stream-json",
"--permission-mode", "bypassPermissions",
"--verbose",
*(["--model", WORKER_MODEL] if WORKER_MODEL else []),
]
def run_worker(args):
proc = subprocess.Popen(["claude", *args], stdout=subprocess.PIPE, text=True)
done = {}
for line in proc.stdout:
try:
event = json.loads(line)
except ValueError:
continue
if event.get("type") == "result":
done = event
elif event.get("type") == "assistant":
for part in event["message"]["content"]:
if part["type"] == "text" and part["text"].strip():
print(part["text"], flush=True)
elif part["type"] == "tool_use":
print(f"· {part['name']} {json.dumps(part['input'])[:160]}", flush=True)
return done if proc.wait() == 0 else {}
def judge_prompt(task, premises, transcript):
return (
f"README.md, verbatim:\n{premises}\n\n"
f"The task an agent was given:\n{task}\n\n"
f"What the agent then did and said:\n{work[:40000]}\n\n"
"Decide whether the human must now be interrupted. ask=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 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"
"ask=false otherwise. A sensible preference is not a derivation. 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: judge only what is still open, "
"never a question they already answered there.\n"
"The question must be one the agent itself raised. Never construct a question from facts the agent "
"stated. When ask=true, quote the agent's own wording where it already framed the question.\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.",
f"What the agent then did and said, latest last:\n{transcript[-40000:]}\n\n"
f"{JUDGE_RULES}"
)
def grounded(verdict, transcript):
return not verdict["ask"] or verdict["evidence"] in transcript
def judge(task, premises, transcript):
args = [
"-p", judge_prompt(task, premises, transcript),
"--json-schema", json.dumps(JUDGE_SCHEMA),
"--model", JUDGE_MODEL,
"--no-session-persistence",
"--output-format", "json",
"--permission-mode", "bypassPermissions",
"--tools", "",
])
verdict = verdict["structured_output"]
if verdict["ask"] and verdict["evidence"] not in work:
print("judge quoted nothing in the transcript - treating as done", file=sys.stderr)
verdict["ask"] = False
]
for attempt in range(2):
proc = subprocess.run(["claude", *args], capture_output=True, text=True)
if proc.returncode != 0:
sys.exit(proc.stderr.strip() or "the judge failed")
verdict = json.loads(proc.stdout)["structured_output"]
if grounded(verdict, transcript):
return verdict
print("the judge quoted nothing in the transcript twice - interrupting anyway", file=sys.stderr)
return verdict
def reload(state):
def handoff(slot, path, question):
print(f"\n{question}", file=sys.stderr)
if not sys.stdin.isatty():
return False
trust(checkouts())
before = human_turns(entries(path))
subprocess.run(["claude", "--permission-mode", "bypassPermissions", "--resume", str(slot)])
return human_turns(entries(path)) > before
def run_round(task, given, name, slot):
worked = run_worker(worker_args(task, name, slot, resuming=bool(session_file(slot))))
if not worked:
return False
path = session_file(slot)
if not path:
sys.exit(f"claude left no transcript for session {slot}")
verdict = judge(task, given, render(entries(path)))
while verdict["ask"]:
archive(path, f"Task: {task}\n\nVerdict: needs input\n\n{verdict['question']}")
if not handoff(slot, path, verdict["question"]):
sys.exit(2)
verdict = judge(task, given, render(entries(path)))
if verdict["finished"]:
archive(path, f"Task: {task}\n\nVerdict: finished")
os.remove(path)
return True
def reload_if_edited(round_number):
try:
source = open(__file__, encoding="utf-8").read()
compile(source, __file__, "exec")
@@ -243,70 +299,32 @@ def reload(state):
return
if source == SOURCE:
return
os.environ[STATE] = json.dumps(state)
os.environ[ROUND] = str(round_number)
os.execv(sys.executable, [sys.executable, __file__, *sys.argv[1:]])
task = " ".join(sys.argv[1:])
if not task:
sys.exit("usage: loop-claude <task>")
state = json.loads(os.environ.pop(STATE, "{}"))
round_number = state.get("round", 0)
resume = state.get("resume", "")
while True:
reload({"round": round_number, "resume": resume})
round_number += 1
found = sections()
if not found.get("Goals") or not found.get("Audience"):
sys.exit("README.md needs ## Goals and ## Audience - the gate blocks.")
premises = f"## Goals\n{found['Goals']}\n\n## Audience\n{found['Audience']}"
name = session_name()
print(f"\n=== round {round_number} ===", flush=True)
if resume:
start = ["-p", "Continue the task; the previous run stopped before it was finished.", "--resume", resume]
else:
slot = uuid.uuid5(SLOT_NAMESPACE, name)
sticky = clear_slot(name, slot)
if not sticky:
print(f"session {slot} is not this tool's - running without the slot", file=sys.stderr)
start = [
"-p", f"{task}\n\nContinue any open draft PR or worktree for the item before creating a new one.",
"--name", name,
*(["--session-id", str(slot)] if sticky else []),
]
worked = work([
*start,
"--output-format", "stream-json",
"--permission-mode", "bypassPermissions",
"--verbose",
*(["--model", WORKER_MODEL] if WORKER_MODEL else []),
])
path = slot_file(worked["session_id"])
verdict = interrupt(task, premises, render(path) or worked["result"])
def main():
task = " ".join(sys.argv[1:])
if task in ("", "-h", "--help"):
print(__doc__.strip())
sys.exit(0 if task else 1)
round_number = int(os.environ.pop(ROUND, 0))
failures = 0
while True:
kept = archive(path, f"Task: {task}\n\nVerdict: {'needs input' if verdict['ask'] else 'finished' if verdict['finished'] else 'continues'}\n\n{verdict['question']}".rstrip())
if kept:
print(f"transcript: {kept}", file=sys.stderr)
if not verdict["ask"]:
break
reload_if_edited(round_number)
round_number += 1
given = premises()
name = session_name()
print(f"\n=== round {round_number} ===", flush=True)
if run_round(task, given, name, uuid.uuid5(SLOT_NAMESPACE, name)):
failures = 0
continue
failures += 1
if failures == 3:
sys.exit("claude failed three rounds running")
print("claude failed - retrying in a minute", file=sys.stderr)
time.sleep(60)
print(f"\n{verdict['question']}", file=sys.stderr)
if not sys.stdin.isatty():
sys.exit(2)
granted = trust(checkouts())
if granted:
print("trusted for the handoff: " + ", ".join(granted), file=sys.stderr)
answered = typed(path)
subprocess.run(["claude", "--permission-mode", "bypassPermissions", "--resume", worked["session_id"]])
path = slot_file(worked["session_id"])
if typed(path) <= answered:
sys.exit(2)
verdict = interrupt(task, premises, render(path))
resume = "" if verdict["finished"] else worked["session_id"]
if __name__ == "__main__":
main()