Lay out loop-claude as a launcher over the loop_claude package
This commit is contained in:
@@ -0,0 +1,22 @@
|
||||
import subprocess
|
||||
|
||||
from loop_claude.outcome import Stop
|
||||
|
||||
|
||||
def checkout_root():
|
||||
found = subprocess.run(["git", "rev-parse", "--show-toplevel"], capture_output=True, text=True)
|
||||
if found.returncode != 0:
|
||||
return Stop(1, found.stderr.strip())
|
||||
return found.stdout.strip()
|
||||
|
||||
|
||||
def checkouts(root):
|
||||
found = [root]
|
||||
listing = subprocess.run(["git", "worktree", "list", "--porcelain"], capture_output=True, cwd=root, text=True)
|
||||
if listing.returncode == 0:
|
||||
found += [line.split(" ", 1)[1] for line in listing.stdout.splitlines() if line.startswith("worktree ")]
|
||||
return sorted(set(found))
|
||||
|
||||
|
||||
def project_name(root, code):
|
||||
return root.removeprefix(f"{code}/").lstrip("/")
|
||||
@@ -0,0 +1,399 @@
|
||||
import glob
|
||||
import itertools
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from loop_claude.checkout import checkouts, project_name
|
||||
from loop_claude.outcome import Continue, Retry, Stop
|
||||
|
||||
SESSION_NAMESPACE = uuid.UUID("64fb586b-d926-4bb3-a44c-c903e86d3eec")
|
||||
|
||||
JUDGE_RULES = (
|
||||
"Decide whether the human must now be interrupted. interrupt=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 release "
|
||||
"ready to cut, 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"
|
||||
"interrupt=false otherwise. 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, on a [human] line: judge only what "
|
||||
"is still open, never a question they already answered there.\n"
|
||||
"Where the agent asked or flagged something itself, the question is that one, in the agent's own "
|
||||
"wording; never construct another from facts it stated.\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": {
|
||||
"evidence": {"description": "A verbatim quote of the transcript line that triggers the interrupt. Empty when interrupt is false.", "type": "string"},
|
||||
"finished": {"type": "boolean"},
|
||||
"interrupt": {"type": "boolean"},
|
||||
"question": {"description": "The single question to put to the human. Empty when interrupt is false.", "type": "string"},
|
||||
},
|
||||
"required": ["evidence", "finished", "interrupt", "question"],
|
||||
"type": "object",
|
||||
}
|
||||
|
||||
|
||||
def strike(who, failures, failure):
|
||||
if failures == 3:
|
||||
return Stop(1, f"the {who} failed three times running: {failure}")
|
||||
print(f"retrying the {who} in a minute: {failure}", file=sys.stderr)
|
||||
time.sleep(60)
|
||||
|
||||
|
||||
def run_cycle(root, task, premises, chosen, paths, env):
|
||||
name = session_name(root, paths.code)
|
||||
session_id = uuid.uuid5(SESSION_NAMESPACE, name)
|
||||
if failure := run_worker(root, worker_args(task, name, session_id, chosen, env, resuming=session_open(paths.projects, session_id))):
|
||||
return Retry(failure)
|
||||
path = session_file(paths.projects, session_id)
|
||||
if not path:
|
||||
return Stop(1, f"claude left no transcript for session {session_id}")
|
||||
# The interrupt appends to this transcript, so each pass judges and archives it anew; archive skips a stamp it already wrote.
|
||||
while True:
|
||||
verdict = judge(root, task, premises, render(entries(path)), chosen, env)
|
||||
if isinstance(verdict, Stop):
|
||||
return verdict
|
||||
if not verdict["interrupt"]:
|
||||
break
|
||||
archive(root, path, f"Task: {task}\n\nVerdict: interrupt\n\n{verdict['question']}", paths)
|
||||
if failure := interrupt(root, session_id, chosen, path, verdict["question"], paths, env):
|
||||
return Stop(2, failure)
|
||||
if verdict["finished"]:
|
||||
archive(root, path, f"Task: {task}\n\nVerdict: finished", paths)
|
||||
delete_transcript_files(path)
|
||||
return Continue()
|
||||
|
||||
|
||||
def session_name(root, code):
|
||||
# "A " is the human's cue in the session picker that the session is the loop's.
|
||||
return f"A {project_name(root, code)} loop-claude"
|
||||
|
||||
|
||||
def archive(root, path, note, paths):
|
||||
# Stamped by mtime, so a transcript unchanged since its last archive maps to the file already written.
|
||||
name = project_name(root, paths.code)
|
||||
folder = paths.archive / name
|
||||
try:
|
||||
stamp = time.strftime("%Y-%m-%dT%H-%M-%SZ", time.gmtime(os.path.getmtime(path)))
|
||||
make_private(folder)
|
||||
dest = 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:
|
||||
copy.write(f"# {stamp} {name}\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)
|
||||
|
||||
|
||||
def make_private(folder):
|
||||
mask = os.umask(0o077)
|
||||
try:
|
||||
os.makedirs(folder, exist_ok=True)
|
||||
finally:
|
||||
os.umask(mask)
|
||||
|
||||
|
||||
def replace_json(path, data, **dump):
|
||||
staged = f"{path}.{os.getpid()}"
|
||||
try:
|
||||
mode = os.stat(path).st_mode & 0o7777 if os.path.exists(path) else 0o600
|
||||
with open(os.open(staged, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), "w", encoding="utf-8") as handle:
|
||||
os.fchmod(handle.fileno(), mode)
|
||||
json.dump(data, handle, **dump)
|
||||
os.replace(staged, path)
|
||||
except OSError as failure:
|
||||
if os.path.exists(staged):
|
||||
os.remove(staged)
|
||||
return failure
|
||||
return None
|
||||
|
||||
|
||||
def model_args(env, variable, chosen):
|
||||
return ["--model", env.get(variable) or chosen]
|
||||
|
||||
|
||||
# ~/.claude/loop-claude-models.json
|
||||
|
||||
|
||||
def project_model(root, paths, env):
|
||||
if env.get("LOOP_CLAUDE_JUDGE_MODEL") and env.get("LOOP_CLAUDE_WORKER_MODEL"):
|
||||
return ""
|
||||
saved = paths.models_file
|
||||
name = project_name(root, paths.code)
|
||||
models = read_models(saved)
|
||||
if isinstance(models, Stop):
|
||||
return models
|
||||
if chosen := models.get(name):
|
||||
return chosen
|
||||
chosen = ask_model(name, saved, paths.model_catalog)
|
||||
if isinstance(chosen, Stop):
|
||||
return chosen
|
||||
# Reread: another loop may have saved its project while this one waited on the human.
|
||||
models = read_models(saved)
|
||||
if isinstance(models, Stop):
|
||||
return models
|
||||
if failure := replace_json(saved, {**models, name: chosen}, indent="\t", sort_keys=True):
|
||||
return Stop(1, f"could not save the model in {saved}: {failure.strerror}")
|
||||
print(f"{name} runs on {chosen}", file=sys.stderr)
|
||||
return chosen
|
||||
|
||||
|
||||
def read_models(saved):
|
||||
try:
|
||||
with open(saved, encoding="utf-8") as handle:
|
||||
models = json.load(handle)
|
||||
except FileNotFoundError:
|
||||
return {}
|
||||
except (OSError, ValueError) as failure:
|
||||
return Stop(1, f"could not read {saved}: {getattr(failure, 'strerror', None) or failure}")
|
||||
if not isinstance(models, dict) or not all(isinstance(chosen, str) and chosen for chosen in models.values()):
|
||||
return Stop(1, f"could not read {saved}: not an object mapping projects to model names")
|
||||
return models
|
||||
|
||||
|
||||
def ask_model(name, saved, folder):
|
||||
if not (sys.stdin.isatty() and sys.stdout.isatty()):
|
||||
return Stop(2, f"{name} has no model in {saved}, and stdin or stdout is not a terminal to ask on; run it on a terminal or merge {{\"{name}\": \"<model>\"}} into {saved}")
|
||||
offered = catalog(folder)
|
||||
print(f"\nThe model to run {name} on, saved in {saved}:", file=sys.stderr)
|
||||
for number, (model_id, label) in enumerate(offered, 1):
|
||||
print(f" {number}. {label} ({model_id})", file=sys.stderr)
|
||||
if not offered:
|
||||
print(f" no model catalog cached in {folder}", file=sys.stderr)
|
||||
while True:
|
||||
try:
|
||||
answer = input(f"{'A number, or any' if offered else 'A'} name claude --model takes: ").strip()
|
||||
except EOFError:
|
||||
print(file=sys.stderr)
|
||||
return Stop(2, "no model picked")
|
||||
if not answer:
|
||||
continue
|
||||
if not (offered and answer.isdecimal()):
|
||||
return answer
|
||||
if 1 <= int(answer) <= len(offered):
|
||||
return offered[int(answer) - 1][0]
|
||||
print(f"pick 1 to {len(offered)}", file=sys.stderr)
|
||||
|
||||
|
||||
def catalog(folder):
|
||||
newest = {}
|
||||
for path in folder.glob("*.json"):
|
||||
try:
|
||||
with open(path, encoding="utf-8") as handle:
|
||||
data = json.load(handle)
|
||||
except (OSError, ValueError):
|
||||
continue
|
||||
if isinstance(data, dict) and isinstance(data.get("fetchedAt"), (int, float)) and data["fetchedAt"] > newest.get("fetchedAt", -1):
|
||||
newest = data
|
||||
models = newest
|
||||
for key in ("catalog", "config", "models"):
|
||||
models = models.get(key) if isinstance(models, dict) else None
|
||||
return [(entry["id"], entry.get("name", entry["id"])) for entry in models if isinstance(entry, dict) and isinstance(entry.get("id"), str)] if isinstance(models, list) else []
|
||||
|
||||
|
||||
# The transcript file
|
||||
|
||||
|
||||
def session_open(projects, session_id):
|
||||
return bool(session_file(projects, session_id))
|
||||
|
||||
|
||||
def session_file(projects, session_id):
|
||||
hit = glob.glob(os.path.join(glob.escape(str(projects)), "*", f"{session_id}.jsonl"))
|
||||
return hit[0] if hit else ""
|
||||
|
||||
|
||||
def delete_transcript_files(path):
|
||||
for sibling in glob.glob(glob.escape(path.removesuffix(".jsonl")) + "*"):
|
||||
try:
|
||||
shutil.rmtree(sibling) if os.path.isdir(sibling) else os.remove(sibling)
|
||||
except OSError as failure:
|
||||
print(f"could not remove {sibling}: {failure}", file=sys.stderr)
|
||||
|
||||
|
||||
def entries(path):
|
||||
with open(path, encoding="utf-8") as handle:
|
||||
for raw in handle:
|
||||
if entry := parse(raw):
|
||||
yield entry
|
||||
|
||||
|
||||
def parse(raw):
|
||||
try:
|
||||
entry = json.loads(raw)
|
||||
except ValueError:
|
||||
return None
|
||||
return entry if isinstance(entry, dict) else None
|
||||
|
||||
|
||||
# "user" entries
|
||||
|
||||
|
||||
def human_turns(entries):
|
||||
return sum(1 for entry in entries if typed(entry))
|
||||
|
||||
|
||||
def typed(entry):
|
||||
if entry.get("type") != "user":
|
||||
return False
|
||||
content = entry.get("message", {}).get("content")
|
||||
parts = content if isinstance(content, list) else []
|
||||
meta = entry.get("isMeta")
|
||||
loop_prompt = entry.get("promptSource") == "sdk"
|
||||
command = isinstance(content, str) and content.startswith("<")
|
||||
no_content = not isinstance(content, str) and not parts
|
||||
non_text = any(not isinstance(part, dict) or part.get("type") != "text" for part in parts)
|
||||
interruption = not non_text and any(part.get("text", "").startswith("[Request interrupted") for part in parts)
|
||||
return not (meta or loop_prompt or command or no_content or non_text or interruption)
|
||||
|
||||
|
||||
# "assistant" entries and stream-json
|
||||
|
||||
|
||||
def run_worker(root, args):
|
||||
with subprocess.Popen(["claude", *args], cwd=root, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, text=True) as proc:
|
||||
done = False
|
||||
for raw in proc.stdout:
|
||||
event = parse(raw) or {}
|
||||
if event.get("type") == "result":
|
||||
done = True
|
||||
elif event.get("type") == "assistant":
|
||||
for part in event.get("message", {}).get("content", []):
|
||||
if line := said(part, 160):
|
||||
print(line, flush=True)
|
||||
code = proc.wait()
|
||||
if code < 0:
|
||||
return f"claude killed by signal {-code}"
|
||||
if code:
|
||||
return f"claude exited {code}"
|
||||
return "" if done else "claude exited 0 without a result event"
|
||||
|
||||
|
||||
def worker_args(task, name, session_id, chosen, env, resuming):
|
||||
if resuming:
|
||||
start = ["-p", "Continue the task; the previous run stopped before it was finished.", "--resume", str(session_id)]
|
||||
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(session_id)]
|
||||
return [
|
||||
*start,
|
||||
"--output-format", "stream-json",
|
||||
"--permission-mode", "bypassPermissions",
|
||||
"--verbose",
|
||||
*model_args(env, "LOOP_CLAUDE_WORKER_MODEL", chosen),
|
||||
]
|
||||
|
||||
|
||||
def render(entries):
|
||||
lines = []
|
||||
for entry in entries:
|
||||
if entry.get("type") == "assistant":
|
||||
lines += [line for part in entry.get("message", {}).get("content", []) if (line := said(part))]
|
||||
elif typed(entry):
|
||||
content = entry["message"]["content"]
|
||||
lines.append("[human] " + (content if isinstance(content, str) else "".join(part.get("text", "") for part in content)))
|
||||
return "\n\n".join(lines)
|
||||
|
||||
|
||||
def said(part, limit=400):
|
||||
kind = part.get("type") if isinstance(part, dict) else None
|
||||
if kind == "text" and part.get("text", "").strip():
|
||||
return part["text"]
|
||||
if kind == "tool_use":
|
||||
return f"[tool {part.get('name')}] {json.dumps(part.get('input'))[:limit]}"
|
||||
return ""
|
||||
|
||||
|
||||
# --json-schema verdicts
|
||||
|
||||
|
||||
def judge(root, task, premises, transcript, chosen, env):
|
||||
# No tools, so the verdict rests on the transcript grounded() checks it against; no persistence, so its runs stay out of the session picker.
|
||||
args = [
|
||||
"-p",
|
||||
"--json-schema", json.dumps(JUDGE_SCHEMA),
|
||||
*model_args(env, "LOOP_CLAUDE_JUDGE_MODEL", chosen),
|
||||
"--no-session-persistence",
|
||||
"--output-format", "json",
|
||||
"--permission-mode", "bypassPermissions",
|
||||
"--tools", "",
|
||||
]
|
||||
prompt = judge_prompt(task, premises, transcript)
|
||||
for failures in itertools.count(1):
|
||||
proc = subprocess.run(["claude", *args], capture_output=True, cwd=root, input=prompt, text=True)
|
||||
verdict = (parse(proc.stdout) or {}).get("structured_output") if proc.returncode == 0 else None
|
||||
if not complete(verdict):
|
||||
failure = proc.stderr.strip() or "the judge returned no verdict"
|
||||
elif not grounded(verdict, transcript):
|
||||
failure = f"the judge quoted {verdict['evidence']!r}, nothing in the transcript, for the question: {verdict['question']}"
|
||||
else:
|
||||
return verdict
|
||||
if stop := strike("judge", failures, failure):
|
||||
return stop
|
||||
|
||||
|
||||
def judge_prompt(task, premises, transcript):
|
||||
return (
|
||||
f"From README.md:\n{premises}\n\n"
|
||||
f"The task an agent was given:\n{task}\n\n"
|
||||
# The tail, where an interrupt or a finish lands; the session's transcript grows cycle over cycle.
|
||||
f"What the agent did and said, and what the human typed on [human] lines, latest last:\n{transcript[-40000:]}\n\n"
|
||||
f"{JUDGE_RULES}"
|
||||
)
|
||||
|
||||
|
||||
def complete(verdict):
|
||||
return isinstance(verdict, dict) and set(JUDGE_SCHEMA["required"]) <= verdict.keys()
|
||||
|
||||
|
||||
def grounded(verdict, transcript):
|
||||
if not verdict["interrupt"]:
|
||||
return True
|
||||
evidence = verdict["evidence"]
|
||||
return evidence.strip() != "" and evidence in transcript
|
||||
|
||||
|
||||
# ~/.claude.json
|
||||
|
||||
|
||||
def interrupt(root, session_id, chosen, path, question, paths, env):
|
||||
print(f"\n{question}", file=sys.stderr)
|
||||
if not (sys.stdin.isatty() and sys.stdout.isatty()):
|
||||
return "stdin or stdout is not a terminal"
|
||||
trust(paths.claude_json, checkouts(root))
|
||||
before = human_turns(entries(path))
|
||||
subprocess.run(["claude", *model_args(env, "LOOP_CLAUDE_WORKER_MODEL", chosen), "--permission-mode", "bypassPermissions", "--resume", str(session_id)], cwd=root)
|
||||
return "" if human_turns(entries(path)) > before else "the interrupt ended without the human typing anything"
|
||||
|
||||
|
||||
def trust(config, roots):
|
||||
try:
|
||||
with open(config, encoding="utf-8") as handle:
|
||||
data = json.load(handle)
|
||||
except (OSError, ValueError) as failure:
|
||||
print(f"could not read {config}: {getattr(failure, 'strerror', failure)}", file=sys.stderr)
|
||||
return
|
||||
projects = data.setdefault("projects", {}) if isinstance(data, dict) else None
|
||||
if not isinstance(projects, dict) or not all(isinstance(record, dict) for record in projects.values()):
|
||||
print(f"could not read {config}: not an object whose \"projects\" maps paths to objects", file=sys.stderr)
|
||||
return
|
||||
untrusted = [path for path in roots if not projects.get(path, {}).get("hasTrustDialogAccepted")]
|
||||
if not untrusted:
|
||||
return
|
||||
for path in untrusted:
|
||||
projects.setdefault(path, {})["hasTrustDialogAccepted"] = True
|
||||
if failure := replace_json(config, data, indent=2):
|
||||
print(f"could not write {config}: {failure.strerror}", file=sys.stderr)
|
||||
return
|
||||
print("trusted for the interrupt: " + ", ".join(untrusted), file=sys.stderr)
|
||||
@@ -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))])
|
||||
@@ -0,0 +1,17 @@
|
||||
import dataclasses
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Continue:
|
||||
pass
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Retry:
|
||||
failure: str
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Stop:
|
||||
code: int
|
||||
reason: str
|
||||
@@ -0,0 +1,24 @@
|
||||
import dataclasses
|
||||
import pathlib
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Paths:
|
||||
archive: pathlib.Path
|
||||
claude_json: pathlib.Path
|
||||
code: pathlib.Path
|
||||
model_catalog: pathlib.Path
|
||||
models_file: pathlib.Path
|
||||
projects: pathlib.Path
|
||||
|
||||
|
||||
def paths_from(home, env):
|
||||
claude = home / ".claude"
|
||||
return Paths(
|
||||
archive=pathlib.Path(env["LOOP_CLAUDE_TRANSCRIPTS"]).expanduser() if env.get("LOOP_CLAUDE_TRANSCRIPTS") else claude / "loop-claude-transcripts",
|
||||
claude_json=home / ".claude.json",
|
||||
code=home / "code",
|
||||
model_catalog=claude / "cache" / "model-catalog",
|
||||
models_file=claude / "loop-claude-models.json",
|
||||
projects=claude / "projects",
|
||||
)
|
||||
@@ -0,0 +1,36 @@
|
||||
import pathlib
|
||||
|
||||
from loop_claude.outcome import Stop
|
||||
|
||||
|
||||
def read_premises(root):
|
||||
try:
|
||||
found = sections(pathlib.Path(root, "README.md").read_text(encoding="utf-8"))
|
||||
except OSError as failure:
|
||||
return Stop(1, f"README.md in {root}: {failure.strerror} - no premises.")
|
||||
except UnicodeDecodeError as failure:
|
||||
line = failure.object.count(b"\n", 0, failure.start) + 1
|
||||
return Stop(1, f"README.md is not UTF-8 on line {line} - no premises.")
|
||||
for name in ("Goals", "Audience"):
|
||||
bodies = found.get(name, [])
|
||||
if not bodies:
|
||||
return Stop(1, f"README.md has no ## {name} heading - no premises.")
|
||||
if len(bodies) > 1:
|
||||
return Stop(1, f"README.md has ## {name} more than once - no premises.")
|
||||
if not bodies[0]:
|
||||
return Stop(1, f"README.md has nothing under ## {name} - no premises.")
|
||||
return f"## Goals\n{found['Goals'][0]}\n\n## Audience\n{found['Audience'][0]}"
|
||||
|
||||
|
||||
def sections(text):
|
||||
found, current, fenced = {}, None, False
|
||||
for line in text.splitlines():
|
||||
fenced ^= line.startswith("```")
|
||||
if not fenced and line.startswith("## "):
|
||||
current = []
|
||||
found.setdefault(line.strip()[3:], []).append(current)
|
||||
elif not fenced and line.startswith("# "):
|
||||
current = None
|
||||
elif current is not None and line.strip():
|
||||
current.append(line)
|
||||
return {name: ["\n".join(body) for body in bodies] for name, bodies in found.items()}
|
||||
Reference in New Issue
Block a user