Lay out loop-claude as a launcher over the loop_claude package
This commit is contained in:
@@ -0,0 +1,141 @@
|
||||
"""Run a task as headless claude cycles; a judge interrupts only when a decision is the human's.
|
||||
|
||||
usage: loop-claude <task>
|
||||
|
||||
Run it anywhere inside a project checkout whose README.md has ## Goals and ## Audience, the
|
||||
premises; the task runs at the checkout root. Each cycle a worker runs the task; a judge then reads
|
||||
the transcript against them and rules whether the chunk, the smallest PR-able change, is finished.
|
||||
A question only the human can answer, or a release ready to cut, is an interrupt: `claude --resume`
|
||||
on the terminal, every worktree first marked trusted in ~/.claude.json. An unfinished chunk resumes
|
||||
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, a reload with unreadable state, or the worker or 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, 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.
|
||||
|
||||
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
|
||||
$LOOP_CLAUDE_TRANSCRIPTS/<path>/ (default ~/.claude/loop-claude-transcripts) at every interrupt and
|
||||
when the chunk finishes.
|
||||
|
||||
Every claude it starts runs the project's model, saved per <path> in ~/.claude/loop-claude-models.json
|
||||
and read each cycle; a project without an entry, as on its first run, is asked for one.
|
||||
LOOP_CLAUDE_JUDGE_MODEL overrides it for the judge, LOOP_CLAUDE_WORKER_MODEL for the worker and the
|
||||
interrupt; with both set, nothing is asked.
|
||||
|
||||
A change to loop-claude's files takes effect at the next cycle boundary, once they answer --help.
|
||||
|
||||
Claude Code internals this rests on, observed on 2.1.282, the model catalog on 2.1.283:
|
||||
- The transcript is ~/.claude/projects/*/<session-id>.jsonl, one JSON object per line. A <session-id>/
|
||||
folder and <session-id>.superseded-*/ and .orphaned-*.jsonl siblings belong to the same session.
|
||||
- Claude Code writes "user" entries of its own into the transcript, and a `claude -p` prompt lands as one
|
||||
with promptSource "sdk"; typed() tells a human's from them.
|
||||
- An "assistant" entry, in the transcript and in --output-format stream-json, carries message.content
|
||||
parts of type "text" (text) and "tool_use" (name, input); stream-json ends with a "result" event.
|
||||
- `claude -p --output-format json --json-schema` returns the verdict under "structured_output".
|
||||
- `claude -p` without --bare loads the project's and ~/.claude's CLAUDE.md, so the judge reads the words.
|
||||
- ~/.claude.json holds projects.<path>.hasTrustDialogAccepted per checkout.
|
||||
- ~/.claude/cache/model-catalog/*.json holds catalog.config.models, each with an id and a name; the newest
|
||||
file has the highest fetchedAt.
|
||||
"""
|
||||
import dataclasses
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
from loop_claude.checkout import checkout_root
|
||||
from loop_claude.cycle import parse, project_model, run_cycle, strike
|
||||
from loop_claude.outcome import Continue, Retry, Stop
|
||||
from loop_claude.premises import read_premises
|
||||
|
||||
RELOAD_FLAG = "--reloaded"
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class LoopState:
|
||||
cycle_number: int
|
||||
failures: int
|
||||
root: str
|
||||
task: str
|
||||
|
||||
|
||||
def main(argv, env, paths, launcher):
|
||||
try:
|
||||
stop = run_loop(argv, env, paths, launcher)
|
||||
except KeyboardInterrupt:
|
||||
stop = Stop(130, "")
|
||||
if stop.reason:
|
||||
print(stop.reason, file=sys.stderr if stop.code else sys.stdout)
|
||||
return stop.code
|
||||
|
||||
|
||||
def run_loop(argv, env, paths, launcher):
|
||||
state = loop_state(argv)
|
||||
if isinstance(state, Stop):
|
||||
return state
|
||||
baseline = fingerprint(launcher)
|
||||
while True:
|
||||
reload_if_edited(launcher, baseline, state)
|
||||
state = dataclasses.replace(state, cycle_number=state.cycle_number + 1)
|
||||
premises = read_premises(state.root)
|
||||
if isinstance(premises, Stop):
|
||||
return premises
|
||||
chosen = project_model(state.root, paths, env)
|
||||
if isinstance(chosen, Stop):
|
||||
return chosen
|
||||
print(f"\n=== cycle {state.cycle_number} ===", flush=True)
|
||||
match run_cycle(state.root, state.task, premises, chosen, paths, env):
|
||||
case Stop() as stop:
|
||||
return stop
|
||||
case Retry(failure):
|
||||
state = dataclasses.replace(state, failures=state.failures + 1)
|
||||
if stop := strike("worker", state.failures, failure):
|
||||
return stop
|
||||
case Continue():
|
||||
state = dataclasses.replace(state, failures=0)
|
||||
|
||||
|
||||
# The reload
|
||||
|
||||
|
||||
def loop_state(argv):
|
||||
if argv[:1] != [RELOAD_FLAG]:
|
||||
task = " ".join(argv)
|
||||
if task in ("", "-h", "--help"):
|
||||
return Stop(0 if task else 1, __doc__.strip())
|
||||
root = checkout_root()
|
||||
return root if isinstance(root, Stop) else LoopState(0, 0, root, task)
|
||||
handed = parse(argv[1]) if len(argv) == 2 else None
|
||||
shape = {field.name: field.type for field in dataclasses.fields(LoopState)}
|
||||
if not handed or handed.keys() != shape.keys() or any(type(handed[name]) is not kind for name, kind in shape.items()) or not (handed["root"] and handed["task"]):
|
||||
return Stop(1, f"the reload cannot read the loop's state from {argv[1:]}; rerun loop-claude <task>")
|
||||
return LoopState(**handed)
|
||||
|
||||
|
||||
def fingerprint(launcher):
|
||||
# An unreadable file hashes its error, and the --help trial judges it.
|
||||
digest = hashlib.sha256()
|
||||
for path in [launcher, *sorted(pathlib.Path(__file__).parent.glob("*.py"))]:
|
||||
try:
|
||||
content = path.read_bytes()
|
||||
except OSError as failure:
|
||||
content = str(failure).encode()
|
||||
digest.update(f"{path.name}\0{len(content)}\0".encode() + content)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def reload_if_edited(launcher, baseline, state):
|
||||
if fingerprint(launcher) == baseline:
|
||||
return
|
||||
trial = subprocess.run([sys.executable, launcher, "--help"], capture_output=True, text=True)
|
||||
if trial.returncode != 0:
|
||||
print(f"keeping the running script: {trial.stderr.strip() or f'exit {trial.returncode}'}", file=sys.stderr)
|
||||
return
|
||||
os.execv(sys.executable, [sys.executable, str(launcher), RELOAD_FLAG, json.dumps(dataclasses.asdict(state))])
|
||||
Reference in New Issue
Block a user