One word per concept: premises, trigger, gate, reviewer, cycle, interrupt, chunk, memory file
This commit is contained in:
+25
-25
@@ -1,23 +1,23 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run a task as headless claude rounds; a judge interrupts only when a decision is the human's.
|
||||
"""Run a task as headless claude cycles; a judge interrupts 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,
|
||||
or a release ready to cut, hands the session over: `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 or that handoff.
|
||||
Run it in a project checkout whose README.md has ## Goals and ## Audience, the premises. Each cycle a
|
||||
worker runs the task; a judge then reads the transcript against the premises. A question only the
|
||||
human can answer, or a release ready to cut, is an interrupt: `claude --resume` on the terminal. An
|
||||
unfinished chunk resumes the same session next cycle; a finished one starts a fresh session. Cycles
|
||||
continue until Ctrl-C or that interrupt.
|
||||
|
||||
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.
|
||||
Exit 1: no task, no premises, 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 interrupt ended
|
||||
without them typing anything. Before an interrupt every worktree is marked trusted in ~/.claude.json.
|
||||
|
||||
Each project has one session, "A ~/code/<path> auto-mode" (the absolute path outside ~/code),
|
||||
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, once the new file answers --help.
|
||||
this file takes effect at the next cycle 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>/
|
||||
@@ -41,7 +41,7 @@ import uuid
|
||||
|
||||
ARCHIVE = os.path.expanduser(os.environ.get("AUTO_MODE_TRANSCRIPTS", "~/.claude/auto-mode-transcripts"))
|
||||
FAILURES = "LOOP_CLAUDE_FAILURES"
|
||||
ROUND = "LOOP_CLAUDE_ROUND"
|
||||
CYCLE = "LOOP_CLAUDE_CYCLE"
|
||||
SESSION_NAMESPACE = uuid.UUID("64fb586b-d926-4bb3-a44c-c903e86d3eec")
|
||||
SOURCE = open(__file__, encoding="utf-8").read()
|
||||
|
||||
@@ -92,13 +92,13 @@ def sections(text):
|
||||
return {name: "\n".join(body) for name, body in found.items() if body}
|
||||
|
||||
|
||||
def gate():
|
||||
def read_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.")
|
||||
sys.exit("README.md needs ## Goals and ## Audience - no premises.")
|
||||
return f"## Goals\n{found['Goals']}\n\n## Audience\n{found['Audience']}"
|
||||
|
||||
|
||||
@@ -223,7 +223,7 @@ def trust(paths):
|
||||
except OSError as failure:
|
||||
print(f"could not record trust: {failure}", file=sys.stderr)
|
||||
return
|
||||
print("trusted for the handoff: " + ", ".join(granted), file=sys.stderr)
|
||||
print("trusted for the interrupt: " + ", ".join(granted), file=sys.stderr)
|
||||
|
||||
|
||||
def model(variable):
|
||||
@@ -307,7 +307,7 @@ def verdict_on(task, premises, path):
|
||||
time.sleep(60)
|
||||
|
||||
|
||||
def handoff(session_id, path, question):
|
||||
def interrupt(session_id, path, question):
|
||||
print(f"\n{question}", file=sys.stderr)
|
||||
if not (sys.stdin.isatty() and sys.stdout.isatty()):
|
||||
return False
|
||||
@@ -317,7 +317,7 @@ def handoff(session_id, path, question):
|
||||
return human_turns(entries(path)) > before
|
||||
|
||||
|
||||
def run_round(task, premises, name, session_id):
|
||||
def run_cycle(task, premises, name, session_id):
|
||||
worked = run_worker(worker_args(task, name, session_id, resuming=bool(session_file(session_id))))
|
||||
if not worked:
|
||||
return False
|
||||
@@ -327,7 +327,7 @@ def run_round(task, premises, name, session_id):
|
||||
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"]):
|
||||
if not interrupt(session_id, path, verdict["question"]):
|
||||
sys.exit(2)
|
||||
verdict = verdict_on(task, premises, path)
|
||||
if verdict["finished"]:
|
||||
@@ -336,7 +336,7 @@ def run_round(task, premises, name, session_id):
|
||||
return True
|
||||
|
||||
|
||||
def reload_if_edited(round_number, failures):
|
||||
def reload_if_edited(cycle_number, failures):
|
||||
try:
|
||||
source = open(__file__, encoding="utf-8").read()
|
||||
except OSError as failure:
|
||||
@@ -349,7 +349,7 @@ def reload_if_edited(round_number, failures):
|
||||
print(f"keeping the running script: {trial.stderr.strip() or f'exit {trial.returncode}'}", file=sys.stderr)
|
||||
return
|
||||
os.environ[FAILURES] = str(failures)
|
||||
os.environ[ROUND] = str(round_number)
|
||||
os.environ[CYCLE] = str(cycle_number)
|
||||
os.execv(sys.executable, [sys.executable, __file__, *sys.argv[1:]])
|
||||
|
||||
|
||||
@@ -359,14 +359,14 @@ def main():
|
||||
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))
|
||||
cycle_number = int(os.environ.pop(CYCLE, 0))
|
||||
while True:
|
||||
reload_if_edited(round_number, failures)
|
||||
round_number += 1
|
||||
premises = gate()
|
||||
reload_if_edited(cycle_number, failures)
|
||||
cycle_number += 1
|
||||
premises = read_premises()
|
||||
name = session_name()
|
||||
print(f"\n=== round {round_number} ===", flush=True)
|
||||
if run_round(task, premises, name, uuid.uuid5(SESSION_NAMESPACE, name)):
|
||||
print(f"\n=== cycle {cycle_number} ===", flush=True)
|
||||
if run_cycle(task, premises, name, uuid.uuid5(SESSION_NAMESPACE, name)):
|
||||
failures = 0
|
||||
continue
|
||||
failures += 1
|
||||
|
||||
@@ -70,13 +70,13 @@ class Project(unittest.TestCase):
|
||||
|
||||
|
||||
class WorkerArgs(unittest.TestCase):
|
||||
def test_a_fresh_round_names_the_session_and_asks_to_continue_open_work(self):
|
||||
def test_a_fresh_cycle_names_the_session_and_asks_to_continue_open_work(self):
|
||||
args = loop.worker_args("the task", "A name", SESSION_ID, resuming=False)
|
||||
self.assertIn("--session-id", args)
|
||||
self.assertEqual(args[args.index("--name") + 1], "A name")
|
||||
self.assertTrue(args[1].startswith("the task\n\nContinue any open draft PR"))
|
||||
|
||||
def test_a_resumed_round_reuses_the_session(self):
|
||||
def test_a_resumed_cycle_reuses_the_session(self):
|
||||
args = loop.worker_args("paint the fence", "A name", SESSION_ID, resuming=True)
|
||||
self.assertEqual(args[args.index("--resume") + 1], SESSION_ID)
|
||||
self.assertNotIn("--name", args)
|
||||
@@ -188,10 +188,10 @@ class RunRound(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:
|
||||
for _ in range(3):
|
||||
self.assertTrue(loop.run_round("task", "premises", "A name", SESSION_ID))
|
||||
self.assertTrue(loop.run_cycle("task", "premises", "A name", SESSION_ID))
|
||||
open(verdicts, "w").write("fail fail fail")
|
||||
with self.assertRaises(SystemExit):
|
||||
loop.run_round("task", "premises", "A name", SESSION_ID)
|
||||
loop.run_cycle("task", "premises", "A name", SESSION_ID)
|
||||
starts = [args[args.index("-p") + 1:][:3] for args in map(json.loads, open(calls)) if "--json-schema" not in args]
|
||||
self.assertEqual([start[1] for start in starts], ["--name", "--resume", "--name", "--resume"])
|
||||
self.assertEqual(starts[1][2], SESSION_ID)
|
||||
@@ -206,13 +206,13 @@ class Reload(unittest.TestCase):
|
||||
script = os.path.join(root, "loop-claude")
|
||||
open(script, "w").write(loop.SOURCE.replace("import glob\n", "import glob\nimport no_such_module\n"))
|
||||
with unittest.mock.patch.object(loop, "__file__", script), unittest.mock.patch("os.execv") as execv:
|
||||
loop.reload_if_edited(round_number=1, failures=0)
|
||||
loop.reload_if_edited(cycle_number=1, failures=0)
|
||||
execv.assert_not_called()
|
||||
open(script, "w").write(loop.SOURCE.replace("ROUND = ", "ROUND = \"x\" or "))
|
||||
open(script, "w").write(loop.SOURCE.replace("CYCLE = ", "CYCLE = \"x\" or "))
|
||||
with unittest.mock.patch.object(loop, "__file__", script), unittest.mock.patch("os.execv") as execv:
|
||||
loop.reload_if_edited(round_number=1, failures=2)
|
||||
loop.reload_if_edited(cycle_number=1, failures=2)
|
||||
execv.assert_called_once()
|
||||
self.assertEqual((os.environ.pop(loop.ROUND), os.environ.pop(loop.FAILURES)), ("1", "2"))
|
||||
self.assertEqual((os.environ.pop(loop.CYCLE), os.environ.pop(loop.FAILURES)), ("1", "2"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
Reference in New Issue
Block a user