Name the cycle's module steps.py, and group main and reload under loop/
This commit is contained in:
@@ -0,0 +1,89 @@
|
||||
"""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 an exit below 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 or one it cannot read or archive, claude cannot start for an interrupt, a
|
||||
reload with unreadable state, or the worker or the judge fails three times running, retried a minute
|
||||
apart within the cycle. A worker fails when claude cannot start, exits non-zero, is killed, or ends
|
||||
without a result event; a judge when claude cannot start or exits non-zero, or its verdict misses or
|
||||
mistypes a field, interrupts without a question, 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, the input ends, or the interrupt ended with nothing typed. 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. At every interrupt and when the chunk finishes
|
||||
its transcript is copied to $LOOP_CLAUDE_TRANSCRIPTS/<path>/<sha256>.jsonl (default
|
||||
~/.claude/loop-claude-transcripts), the verdict beside it in <sha256>.verdict.md.
|
||||
|
||||
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 bin/loop-claude or bin/loop_claude/**/*.py takes effect at the next cycle boundary, once
|
||||
loop-claude --help succeeds.
|
||||
"""
|
||||
import dataclasses
|
||||
import sys
|
||||
|
||||
from loop_claude.claude_code.session import session_for
|
||||
from loop_claude.cycle.steps import Cycle, run_cycle
|
||||
from loop_claude.outcome import Stop
|
||||
from loop_claude.project.checkout import checkout_root, project_name
|
||||
from loop_claude.project.models import project_models
|
||||
from loop_claude.project.premises import read_premises
|
||||
from loop_claude.loop.reload import RELOAD_FLAG, LoopState, decode_state, exec_if_edited, fingerprint
|
||||
|
||||
|
||||
def main(argv, env, paths, launcher, cwd):
|
||||
try:
|
||||
stop = run_loop(argv, env, paths, launcher, cwd)
|
||||
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, cwd):
|
||||
state = loop_state(argv, cwd)
|
||||
if isinstance(state, Stop):
|
||||
return state
|
||||
baseline = fingerprint(launcher)
|
||||
project = project_name(state.root, paths.code)
|
||||
session = session_for(project, paths)
|
||||
while True:
|
||||
exec_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
|
||||
models = project_models(project, paths, env)
|
||||
if isinstance(models, Stop):
|
||||
return models
|
||||
print(f"\n=== cycle {state.cycle_number} ===", flush=True)
|
||||
if stop := run_cycle(Cycle(models=models, paths=paths, premises=premises, project=project, root=state.root, session=session, task=state.task)):
|
||||
return stop
|
||||
|
||||
|
||||
def loop_state(argv, cwd):
|
||||
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(cwd)
|
||||
return root if isinstance(root, Stop) else LoopState(0, root, task)
|
||||
state = decode_state(argv[1], LoopState) if len(argv) == 2 else None
|
||||
if not (state and state.root and state.task):
|
||||
return Stop(1, f"the reload cannot read the loop's state from {argv[1:]}; rerun loop-claude <task>")
|
||||
return state
|
||||
@@ -0,0 +1,51 @@
|
||||
import dataclasses
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import typing
|
||||
|
||||
RELOAD_FLAG = "--reloaded"
|
||||
|
||||
|
||||
# A field change stops a running loop at its next reload: the new script rejects the old fields.
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class LoopState:
|
||||
cycle_number: int
|
||||
root: str
|
||||
task: str
|
||||
|
||||
|
||||
def decode_state(handed, kind):
|
||||
try:
|
||||
fields = json.loads(handed)
|
||||
except ValueError:
|
||||
return None
|
||||
shape = typing.get_type_hints(kind)
|
||||
if not isinstance(fields, dict) or fields.keys() != shape.keys():
|
||||
return None
|
||||
if any(type(fields[name]) is not type_ for name, type_ in shape.items()):
|
||||
return None
|
||||
return kind(**fields)
|
||||
|
||||
|
||||
def fingerprint(launcher):
|
||||
digest = hashlib.sha256()
|
||||
for path in [launcher, *sorted((launcher.parent / "loop_claude").rglob("*.py"))]:
|
||||
try:
|
||||
content = path.read_bytes()
|
||||
except OSError as failure:
|
||||
content = str(failure).encode()
|
||||
digest.update(f"{path.relative_to(launcher.parent)}\0{len(content)}\0".encode() + content)
|
||||
return digest.hexdigest()
|
||||
|
||||
|
||||
def exec_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