diff --git a/.gitignore b/.gitignore index 01dedfeb..abba4dcf 100644 --- a/.gitignore +++ b/.gitignore @@ -19,6 +19,7 @@ !agents/*.md !bin/ !bin/* +!bin/loop_claude/*.py !docs/ !docs/*.md !principles/ diff --git a/AGENTS.md b/AGENTS.md index 1f7171a9..9f231cdd 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -13,7 +13,7 @@ Decisions live in `docs/decisions.md`: - bin/: the Python floor is README's Install prerequisite - bin/: host python, no container - comprehension floor: every dimension and the overall at 7.0 or above, and 0.1.0 waits on it -- loop-claude: the five section headers stay +- loop-claude: the section headers stay - vocabulary: the concept words are defined under `CLAUDE.md` → "Vocabulary" and cited by a bare link - larv-review: a re-entered loop takes a fresh round cap - loop-claude: a reload into an older file is unsupported @@ -25,3 +25,4 @@ Decisions live in `docs/decisions.md`: - loop-claude: the judge loads `CLAUDE.md` - loop-claude: the archive keeps the raw transcript, and a failed archive stops the loop - loop-claude: the rebuild keeps main's `--reloaded` state +- rebuild: a chunk into `rebuild` takes no comprehension scoring run diff --git a/bin/loop-claude b/bin/loop-claude index f4d4d6e2..faeda406 100755 --- a/bin/loop-claude +++ b/bin/loop-claude @@ -1,579 +1,11 @@ #!/usr/bin/env python3 -"""Run a task as headless claude cycles; a judge interrupts only when a decision is the human's. - -usage: loop-claude - -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 loop-claude", being the checkout relative to ~/code, -or to / outside it, deleted when the chunk finishes. Its transcript is archived under -$LOOP_CLAUDE_TRANSCRIPTS// (default ~/.claude/loop-claude-transcripts) at every interrupt and -when the chunk finishes. - -Every claude it starts runs the project's model, saved per 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 this script takes effect at the next cycle boundary, once the new script answers --help. - -Claude Code internals this rests on, observed on 2.1.282, the model catalog on 2.1.283: -- The transcript is ~/.claude/projects/*/.jsonl, one JSON object per line. A / - folder and .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..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 glob -import itertools -import json import os import pathlib -import shutil -import subprocess import sys -import time -import uuid -ARCHIVE = os.path.expanduser(os.environ.get("LOOP_CLAUDE_TRANSCRIPTS", "~/.claude/loop-claude-transcripts")) -RELOAD_BASELINE = pathlib.Path(__file__).read_text(encoding="utf-8") -RELOAD_FLAG = "--reloaded" -SESSION_NAMESPACE = uuid.UUID("64fb586b-d926-4bb3-a44c-c903e86d3eec") +LAUNCHER = pathlib.Path(__file__).resolve() +sys.path.insert(0, str(LAUNCHER.parent)) -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." -) +from loop_claude import main, paths -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", -} - - -@dataclasses.dataclass(frozen=True) -class Stop: - code: int - reason: str - - -def main(): - try: - stop = run_loop(sys.argv[1:]) - except KeyboardInterrupt: - stop = Stop(130, "") - if stop.reason: - print(stop.reason, file=sys.stderr if stop.code else sys.stdout) - sys.exit(stop.code) - - -def run_loop(argv): - state = loop_state(argv) - if isinstance(state, Stop): - return state - while True: - reload_if_edited(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) - if isinstance(chosen, Stop): - return chosen - name = session_name(state.root) - print(f"\n=== cycle {state.cycle_number} ===", flush=True) - failure = run_cycle(state.root, state.task, premises, name, uuid.uuid5(SESSION_NAMESPACE, name), chosen) - if isinstance(failure, Stop): - return failure - state = dataclasses.replace(state, failures=state.failures + 1 if failure else 0) - if failure and (stop := strike("worker", state.failures, failure)): - return stop - - -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, name, session_id, chosen): - if failure := run_worker(root, worker_args(task, name, session_id, chosen, resuming=session_open(session_id))): - return failure - path = session_file(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) - if isinstance(verdict, Stop): - return verdict - if not verdict["interrupt"]: - break - archive(root, path, f"Task: {task}\n\nVerdict: interrupt\n\n{verdict['question']}") - if failure := interrupt(root, session_id, chosen, path, verdict["question"]): - return Stop(2, failure) - if verdict["finished"]: - archive(root, path, f"Task: {task}\n\nVerdict: finished") - delete_transcript_files(path) - return "" - - -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 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()} - - -def session_name(root): - # "A " is the human's cue in the session picker that the session is the loop's. - return f"A {project_name(root)} loop-claude" - - -def archive(root, path, note): - # Stamped by mtime, so a transcript unchanged since its last archive maps to the file already written. - folder = os.path.join(ARCHIVE, project_name(root)) - try: - stamp = time.strftime("%Y-%m-%dT%H-%M-%SZ", time.gmtime(os.path.getmtime(path))) - make_private(folder) - dest = os.path.join(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} {project_name(root)}\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(variable, chosen): - return ["--model", os.environ.get(variable) or chosen] - - -def project_name(root): - return root.removeprefix(os.path.expanduser("~/code/")).lstrip("/") - - -# The reload - - -@dataclasses.dataclass(frozen=True) -class LoopState: - cycle_number: int - failures: int - root: str - task: str - - -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 ") - return LoopState(**handed) - - -def reload_if_edited(state): - try: - source = pathlib.Path(__file__).read_text(encoding="utf-8") - except OSError as failure: - print(f"keeping the running script: {failure}", file=sys.stderr) - return - if source == RELOAD_BASELINE: - return - trial = subprocess.run([sys.executable, __file__, "--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, __file__, RELOAD_FLAG, json.dumps(dataclasses.asdict(state))]) - - -# ~/.claude/loop-claude-models.json - - -def project_model(root): - if os.environ.get("LOOP_CLAUDE_JUDGE_MODEL") and os.environ.get("LOOP_CLAUDE_WORKER_MODEL"): - return "" - saved = os.path.expanduser("~/.claude/loop-claude-models.json") - name = project_name(root) - models = read_models(saved) - if isinstance(models, Stop): - return models - if chosen := models.get(name): - return chosen - chosen = ask_model(name, saved) - 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): - 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}\": \"\"}} into {saved}") - offered = catalog() - 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(" no model catalog cached in ~/.claude/cache/model-catalog", 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(): - newest = {} - for path in glob.glob(os.path.expanduser("~/.claude/cache/model-catalog/*.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(session_id): - return bool(session_file(session_id)) - - -def session_file(session_id): - hit = glob.glob(os.path.expanduser(f"~/.claude/projects/*/{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, 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("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): - # 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("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): - 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(checkouts(root)) - before = human_turns(entries(path)) - subprocess.run(["claude", *model_args("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 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 trust(paths): - config = os.path.expanduser("~/.claude.json") - 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 paths 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) - - -if __name__ == "__main__": - main() +sys.exit(main.main(sys.argv[1:], os.environ, paths.paths_from(pathlib.Path.home(), os.environ), LAUNCHER, pathlib.Path.cwd())) diff --git a/bin/loop_claude/__init__.py b/bin/loop_claude/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/bin/loop_claude/checkout.py b/bin/loop_claude/checkout.py new file mode 100644 index 00000000..8d56d06d --- /dev/null +++ b/bin/loop_claude/checkout.py @@ -0,0 +1,22 @@ +import subprocess + +from loop_claude.outcome import Stop + + +def checkout_root(cwd): + found = subprocess.run(["git", "rev-parse", "--show-toplevel"], capture_output=True, cwd=cwd, 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("/") diff --git a/bin/loop_claude/cycle.py b/bin/loop_claude/cycle.py new file mode 100644 index 00000000..e0284026 --- /dev/null +++ b/bin/loop_claude/cycle.py @@ -0,0 +1,393 @@ +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 +from loop_claude.strike import strike + +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 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}\": \"\"}} 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) diff --git a/bin/loop_claude/main.py b/bin/loop_claude/main.py new file mode 100644 index 00000000..66d646be --- /dev/null +++ b/bin/loop_claude/main.py @@ -0,0 +1,111 @@ +"""Run a task as headless claude cycles; a judge interrupts only when a decision is the human's. + +usage: loop-claude + +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 loop-claude", being the checkout relative to ~/code, +or to / outside it, deleted when the chunk finishes. Its transcript is archived under +$LOOP_CLAUDE_TRANSCRIPTS// (default ~/.claude/loop-claude-transcripts) at every interrupt and +when the chunk finishes. + +Every claude it starts runs the project's model, saved per 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. + +Claude Code internals this rests on, observed on 2.1.282, the model catalog on 2.1.283: +- The transcript is ~/.claude/projects/*/.jsonl, one JSON object per line. A / + folder and .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..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 sys + +from loop_claude.checkout import checkout_root +from loop_claude.cycle import project_model, run_cycle +from loop_claude.outcome import Continue, Retry, Stop +from loop_claude.premises import read_premises +from loop_claude.reload import RELOAD_FLAG, decode_state, fingerprint, reload_if_edited +from loop_claude.strike import strike + + +@dataclasses.dataclass(frozen=True) +class LoopState: + cycle_number: int + failures: int + root: str + task: str + + +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) + 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) + + +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, 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 ") + return state diff --git a/bin/loop_claude/outcome.py b/bin/loop_claude/outcome.py new file mode 100644 index 00000000..acd5df0b --- /dev/null +++ b/bin/loop_claude/outcome.py @@ -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 diff --git a/bin/loop_claude/paths.py b/bin/loop_claude/paths.py new file mode 100644 index 00000000..cdf05a48 --- /dev/null +++ b/bin/loop_claude/paths.py @@ -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", + ) diff --git a/bin/loop_claude/premises.py b/bin/loop_claude/premises.py new file mode 100644 index 00000000..a23fc24f --- /dev/null +++ b/bin/loop_claude/premises.py @@ -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()} diff --git a/bin/loop_claude/reload.py b/bin/loop_claude/reload.py new file mode 100644 index 00000000..a3c75177 --- /dev/null +++ b/bin/loop_claude/reload.py @@ -0,0 +1,42 @@ +import dataclasses +import hashlib +import json +import os +import subprocess +import sys + +RELOAD_FLAG = "--reloaded" + + +def decode_state(handed, kind): + try: + fields = json.loads(handed) + except ValueError: + return None + shape = {field.name: field.type for field in dataclasses.fields(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").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))]) diff --git a/bin/loop_claude/strike.py b/bin/loop_claude/strike.py new file mode 100644 index 00000000..72105153 --- /dev/null +++ b/bin/loop_claude/strike.py @@ -0,0 +1,11 @@ +import sys +import time + +from loop_claude.outcome import Stop + + +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) diff --git a/bin/test_loop_claude.py b/bin/test_loop_claude.py index c031435d..3d532a24 100644 --- a/bin/test_loop_claude.py +++ b/bin/test_loop_claude.py @@ -1,11 +1,10 @@ import contextlib import errno -import importlib.machinery -import importlib.util import io import json import os import pathlib +import shutil import stat import subprocess import sys @@ -14,12 +13,16 @@ import unittest import unittest.mock import uuid -SESSION_ID = str(getattr(uuid, "uuid7", uuid.uuid4)()) +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) -LOADER = importlib.machinery.SourceFileLoader("loop_claude", str(pathlib.Path(__file__).with_name("loop-claude"))) -SPEC = importlib.util.spec_from_loader("loop_claude", LOADER) -loop = importlib.util.module_from_spec(SPEC) -LOADER.exec_module(loop) +from loop_claude import checkout, cycle, main, premises, reload +from loop_claude.outcome import Continue, Retry, Stop +from loop_claude.paths import paths_from + +CWD = pathlib.Path("/c") +LAUNCHER = pathlib.Path(__file__).resolve().with_name("loop-claude") +PATHS = paths_from(pathlib.Path("/h"), {}) +SESSION_ID = str(getattr(uuid, "uuid7", uuid.uuid4)()) def assistant(*parts): @@ -42,12 +45,12 @@ def umask(mask): class Sections(unittest.TestCase): def test_keeps_every_headed_section_with_its_bodies(self): text = "# Title\n\nintro\n\n## Goals\n\n1. one\n```sh\n# not a heading\n```\n### Later\n2. two\n#1 priority\n\n## Empty\n\n## Audience\nme\n## Audience\nagain\n# Appendix\nnot audience\n" - self.assertEqual(loop.sections(text), {"Goals": ["1. one\n```sh\n# not a heading\n```\n### Later\n2. two\n#1 priority"], "Empty": [""], "Audience": ["me", "again"]}) + self.assertEqual(premises.sections(text), {"Goals": ["1. one\n```sh\n# not a heading\n```\n### Later\n2. two\n#1 priority"], "Empty": [""], "Audience": ["me", "again"]}) class ReadPremises(unittest.TestCase): def exit_message(self, root): - stop = loop.read_premises(root) + stop = premises.read_premises(root) self.assertEqual(stop.code, 1) self.assertTrue(stop.reason.endswith("no premises.")) return stop.reason @@ -73,12 +76,12 @@ class ReadPremises(unittest.TestCase): pathlib.Path(readme).write_text(text) self.assertIn(missing, self.exit_message(root)) pathlib.Path(readme).write_text("# T\n## Goals\n1. g\n## Audience\nme\n") - self.assertEqual(loop.read_premises(root), "## Goals\n1. g\n\n## Audience\nme") + self.assertEqual(premises.read_premises(root), "## Goals\n1. g\n\n## Audience\nme") class Render(unittest.TestCase): def test_joins_assistant_text_and_tool_calls_and_human_turns_and_skips_the_rest(self): - said = loop.render([ + said = cycle.render([ human("do it"), assistant({"type": "text", "text": "Starting."}, {"type": "tool_use", "name": "Bash", "input": {"command": "ls"}}), assistant({"type": "text", "text": " "}), @@ -92,7 +95,7 @@ class Render(unittest.TestCase): class HumanTurns(unittest.TestCase): def test_counts_typed_turns_and_not_tool_results(self): - self.assertEqual(loop.human_turns([ + self.assertEqual(cycle.human_turns([ human("typed"), human([{"type": "text", "text": "typed as a block"}]), human([{"type": "tool_result", "content": "not typed"}]), @@ -109,74 +112,69 @@ class CheckoutRoot(unittest.TestCase): def test_is_the_checkout_from_any_directory_inside_it_and_exits_outside_one(self): with tempfile.TemporaryDirectory() as tmp, contextlib.chdir(tmp): root = os.getcwd() - self.assertEqual(loop.checkout_root().code, 1) + self.assertEqual(checkout.checkout_root(os.getcwd()).code, 1) subprocess.run(["git", "init", "-q"], check=True) os.makedirs("a/b") with contextlib.chdir("a/b"): - self.assertEqual(loop.checkout_root(), root) + self.assertEqual(checkout.checkout_root(os.getcwd()), root) subprocess.run(["git", "init", "-q", "other"], check=True) with contextlib.chdir("other"): - self.assertEqual(loop.checkouts(root), [root]) + self.assertEqual(checkout.checkouts(root), [root]) class ProjectName(unittest.TestCase): def test_names_a_checkout_relative_to_code_and_any_other_relative_to_root(self): - with unittest.mock.patch.dict(os.environ, {"HOME": "/h"}): - self.assertEqual(loop.project_name("/h/code/a/b"), "a/b") - self.assertEqual(loop.session_name("/h/code/a/b"), "A a/b loop-claude") - self.assertEqual(loop.project_name("/h/code"), "h/code") - self.assertEqual(loop.project_name("/srv/x"), "srv/x") - self.assertEqual(loop.session_name("/srv/x"), "A srv/x loop-claude") + code = pathlib.Path("/h/code") + self.assertEqual(checkout.project_name("/h/code/a/b", code), "a/b") + self.assertEqual(cycle.session_name("/h/code/a/b", code), "A a/b loop-claude") + self.assertEqual(checkout.project_name("/h/code", code), "h/code") + self.assertEqual(checkout.project_name("/srv/x", code), "srv/x") + self.assertEqual(cycle.session_name("/srv/x", code), "A srv/x loop-claude") class WorkerArgs(unittest.TestCase): 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, "m", resuming=False) + args = cycle.worker_args("the task", "A name", SESSION_ID, "m", {}, 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_cycle_reuses_the_session(self): - args = loop.worker_args("paint the fence", "A name", SESSION_ID, "m", resuming=True) + args = cycle.worker_args("paint the fence", "A name", SESSION_ID, "m", {}, resuming=True) self.assertEqual(args[args.index("--resume") + 1], SESSION_ID) self.assertNotIn("--name", args) self.assertNotIn("paint the fence", args[1]) def test_the_project_model_runs_unless_the_environment_names_one(self): - with unittest.mock.patch.dict(os.environ): - os.environ.pop("LOOP_CLAUDE_WORKER_MODEL", None) - args = loop.worker_args("t", "n", SESSION_ID, "claude-opus-5-5", resuming=False) + args = cycle.worker_args("t", "n", SESSION_ID, "claude-opus-5-5", {}, resuming=False) self.assertEqual(args[args.index("--model") + 1], "claude-opus-5-5") - with unittest.mock.patch.dict(os.environ, {"LOOP_CLAUDE_WORKER_MODEL": "claude-fable-5-1"}): - args = loop.worker_args("t", "n", SESSION_ID, "claude-opus-5-5", resuming=False) + args = cycle.worker_args("t", "n", SESSION_ID, "claude-opus-5-5", {"LOOP_CLAUDE_WORKER_MODEL": "claude-fable-5-1"}, resuming=False) self.assertEqual(args[args.index("--model") + 1], "claude-fable-5-1") class ProjectModel(unittest.TestCase): def test_asks_once_per_project_from_the_newest_catalog_and_saves_the_answer(self): - with tempfile.TemporaryDirectory() as home, unittest.mock.patch.dict(os.environ, {"HOME": home}), unittest.mock.patch.object(sys, "stderr", io.StringIO()), umask(0o022): - for variable in ("LOOP_CLAUDE_JUDGE_MODEL", "LOOP_CLAUDE_WORKER_MODEL"): - os.environ.pop(variable, None) + with tempfile.TemporaryDirectory() as home, unittest.mock.patch.object(sys, "stderr", io.StringIO()), umask(0o022): + paths = paths_from(pathlib.Path(home), {}) saved = pathlib.Path(home, ".claude", "loop-claude-models.json") catalog = pathlib.Path(home, ".claude", "cache", "model-catalog") catalog.mkdir(parents=True) for name, fetched, ids in (("old.json", 1, ["claude-opus-5"]), ("new.json", 2, ["claude-opus-5-5", "claude-sonnet-5"])): catalog.joinpath(name).write_text(json.dumps({"fetchedAt": fetched, "catalog": {"config": {"models": [{"id": id, "name": id.upper()} for id in ids]}}})) with unittest.mock.patch("sys.stdin.isatty", return_value=False): - stop = loop.project_model("/srv/a") + stop = cycle.project_model("/srv/a", paths, {}) self.assertEqual(stop.code, 2) self.assertIn(f'merge {{"srv/a": ""}} into {saved}', stop.reason) self.assertFalse(saved.exists()) - with unittest.mock.patch.dict(os.environ, {"LOOP_CLAUDE_JUDGE_MODEL": "j", "LOOP_CLAUDE_WORKER_MODEL": "w"}), unittest.mock.patch("sys.stdin.isatty", return_value=False): - self.assertEqual(loop.project_model("/srv/a"), "") - with unittest.mock.patch.dict(os.environ, {"LOOP_CLAUDE_JUDGE_MODEL": "j"}), unittest.mock.patch("sys.stdin.isatty", return_value=False): - self.assertEqual(loop.project_model("/srv/a").code, 2) + with unittest.mock.patch("sys.stdin.isatty", return_value=False): + self.assertEqual(cycle.project_model("/srv/a", paths, {"LOOP_CLAUDE_JUDGE_MODEL": "j", "LOOP_CLAUDE_WORKER_MODEL": "w"}), "") + self.assertEqual(cycle.project_model("/srv/a", paths, {"LOOP_CLAUDE_JUDGE_MODEL": "j"}).code, 2) with ( unittest.mock.patch("sys.stdin.isatty", return_value=True), unittest.mock.patch("sys.stdout.isatty", return_value=True), unittest.mock.patch("builtins.input", side_effect=["", "3", "2"]) as typed, ): - self.assertEqual(loop.project_model("/srv/a"), "claude-sonnet-5") + self.assertEqual(cycle.project_model("/srv/a", paths, {}), "claude-sonnet-5") self.assertEqual(typed.call_count, 3) self.assertIn("2. CLAUDE-SONNET-5 (claude-sonnet-5)", sys.stderr.getvalue()) self.assertIn("pick 1 to 2", sys.stderr.getvalue()) @@ -188,33 +186,33 @@ class ProjectModel(unittest.TestCase): saved.write_text(json.dumps({**json.loads(saved.read_text()), "srv/d": "haiku"})) return "opus[1m]" typed.side_effect = saved_elsewhere_while_asking - self.assertEqual(loop.project_model("/srv/b"), "opus[1m]") - self.assertEqual(loop.project_model("/srv/a"), "claude-sonnet-5") + self.assertEqual(cycle.project_model("/srv/b", paths, {}), "opus[1m]") + self.assertEqual(cycle.project_model("/srv/a", paths, {}), "claude-sonnet-5") self.assertEqual(typed.call_count, 4) typed.side_effect = EOFError - self.assertEqual(loop.project_model("/srv/c"), loop.Stop(2, "no model picked")) + self.assertEqual(cycle.project_model("/srv/c", paths, {}), Stop(2, "no model picked")) typed.side_effect = ["sonnet"] with unittest.mock.patch("os.replace", side_effect=OSError(errno.EACCES, "Permission denied")): - self.assertEqual(loop.project_model("/srv/c"), loop.Stop(1, f"could not save the model in {saved}: Permission denied")) + self.assertEqual(cycle.project_model("/srv/c", paths, {}), Stop(1, f"could not save the model in {saved}: Permission denied")) self.assertEqual(json.loads(saved.read_text()), {"srv/a": "claude-sonnet-5", "srv/b": "opus[1m]", "srv/d": "haiku"}) self.assertEqual(stat.S_IMODE(saved.stat().st_mode), 0o640) self.assertEqual(sorted(os.listdir(saved.parent)), ["cache", "loop-claude-models.json"]) for shape in ({"fetchedAt": 3, "catalog": {"config": {"models": []}}}, {"fetchedAt": 3, "catalog": None}, {"fetchedAt": 3, "catalog": {"config": []}}, {"fetchedAt": 3, "catalog": {"config": {"models": "x"}}}): catalog.joinpath("new.json").write_text(json.dumps(shape)) with self.subTest(shape=shape): - self.assertEqual(loop.catalog(), []) + self.assertEqual(cycle.catalog(catalog), []) with ( unittest.mock.patch("sys.stdin.isatty", return_value=True), unittest.mock.patch("sys.stdout.isatty", return_value=True), unittest.mock.patch("builtins.input", side_effect=["1"]) as typed, ): - self.assertEqual(loop.project_model("/srv/e"), "1") + self.assertEqual(cycle.project_model("/srv/e", paths, {}), "1") self.assertEqual(typed.call_args.args[0], "A name claude --model takes: ") self.assertIn("no model catalog cached", sys.stderr.getvalue()) for broken in ("{", "[]", '{"srv/a": 1}'): saved.write_text(broken) with self.subTest(broken=broken): - stop = loop.project_model("/srv/a") + stop = cycle.project_model("/srv/a", paths, {}) self.assertEqual(stop.code, 1) self.assertTrue(stop.reason.startswith(f"could not read {saved}: ")) self.assertEqual(saved.read_text(), broken) @@ -222,10 +220,10 @@ class ProjectModel(unittest.TestCase): class JudgePrompt(unittest.TestCase): def test_hands_the_judge_the_tail_of_a_long_transcript(self): - prompt = loop.judge_prompt("task", "## Goals\n1. g", "early " * 20000 + "LATE") + prompt = cycle.judge_prompt("task", "## Goals\n1. g", "early " * 20000 + "LATE") self.assertIn("LATE", prompt) self.assertLess(prompt.count("early"), 20000) - self.assertTrue(prompt.endswith(loop.JUDGE_RULES)) + self.assertTrue(prompt.endswith(cycle.JUDGE_RULES)) class Archive(unittest.TestCase): @@ -233,9 +231,9 @@ class Archive(unittest.TestCase): with tempfile.TemporaryDirectory() as root: transcript = os.path.join(root, "session.jsonl") pathlib.Path(transcript).write_text(json.dumps(assistant({"type": "text", "text": "said"})) + "\n") - loop.ARCHIVE = os.path.join(root, "deep", "archive") - loop.archive("/srv/a/b", transcript, "note") - [copy] = [os.path.join(folder, name) for folder, _, names in os.walk(loop.ARCHIVE) for name in names] + paths = paths_from(pathlib.Path(root), {"LOOP_CLAUDE_TRANSCRIPTS": os.path.join(root, "deep", "archive")}) + cycle.archive("/srv/a/b", transcript, "note", paths) + [copy] = [os.path.join(folder, name) for folder, _, names in os.walk(paths.archive) for name in names] self.assertEqual(stat.S_IMODE(os.stat(copy).st_mode), 0o600) folder = os.path.dirname(copy) while folder != root: @@ -246,26 +244,27 @@ class Archive(unittest.TestCase): class Said(unittest.TestCase): def test_renders_text_and_tool_calls_and_nothing_else(self): - self.assertEqual(loop.said({"type": "text", "text": "hi"}), "hi") - self.assertEqual(loop.said({"type": "text", "text": " \n"}), "") - self.assertEqual(loop.said({"type": "tool_use", "name": "Bash", "input": {"command": "x" * 500}}, 20), '[tool Bash] {"command": "xxxxxxx') - self.assertEqual(loop.said("not a part"), "") + self.assertEqual(cycle.said({"type": "text", "text": "hi"}), "hi") + self.assertEqual(cycle.said({"type": "text", "text": " \n"}), "") + self.assertEqual(cycle.said({"type": "tool_use", "name": "Bash", "input": {"command": "x" * 500}}, 20), '[tool Bash] {"command": "xxxxxxx') + self.assertEqual(cycle.said("not a part"), "") class DeleteTranscriptFiles(unittest.TestCase): def test_deletes_the_transcript_and_its_siblings_so_the_session_is_gone(self): - with tempfile.TemporaryDirectory() as home, unittest.mock.patch.dict(os.environ, {"HOME": home}): - root = os.path.join(home, ".claude", "projects", "p") + with tempfile.TemporaryDirectory() as home: + projects = paths_from(pathlib.Path(home), {}).projects + root = os.path.join(projects, "p") os.makedirs(root) transcript = os.path.join(root, f"{SESSION_ID}.jsonl") pathlib.Path(transcript).write_text("{}\n") os.makedirs(os.path.join(root, SESSION_ID, "subagents")) os.makedirs(os.path.join(root, f"{SESSION_ID}.superseded-1", "tool-results")) pathlib.Path(root, f"{SESSION_ID}.orphaned-1-ab.jsonl").write_text("{}\n") - self.assertTrue(loop.session_open(SESSION_ID)) - loop.delete_transcript_files(transcript) + self.assertTrue(cycle.session_open(projects, SESSION_ID)) + cycle.delete_transcript_files(transcript) self.assertEqual(os.listdir(root), []) - self.assertFalse(loop.session_open(SESSION_ID)) + self.assertFalse(cycle.session_open(projects, SESSION_ID)) class Interrupt(unittest.TestCase): @@ -274,14 +273,14 @@ class Interrupt(unittest.TestCase): transcript = os.path.join(root, "session.jsonl") pathlib.Path(transcript).write_text("{}\n") with unittest.mock.patch("sys.stdin.isatty", return_value=False): - self.assertEqual(loop.interrupt(root, SESSION_ID, "m", transcript, "q?"), "stdin or stdout is not a terminal") + self.assertEqual(cycle.interrupt(root, SESSION_ID, "m", transcript, "q?", paths_from(pathlib.Path(root), {}), {}), "stdin or stdout is not a terminal") with ( unittest.mock.patch("sys.stdin.isatty", return_value=True), unittest.mock.patch("sys.stdout.isatty", return_value=True), - unittest.mock.patch.multiple(loop, checkouts=unittest.mock.DEFAULT, trust=unittest.mock.DEFAULT) as mocks, + unittest.mock.patch.multiple(cycle, checkouts=unittest.mock.DEFAULT, trust=unittest.mock.DEFAULT) as mocks, unittest.mock.patch("subprocess.run") as run, ): - self.assertEqual(loop.interrupt(root, SESSION_ID, "m", transcript, "q?"), "the interrupt ended without the human typing anything") + self.assertEqual(cycle.interrupt(root, SESSION_ID, "m", transcript, "q?", paths_from(pathlib.Path(root), {}), {}), "the interrupt ended without the human typing anything") mocks["checkouts"].assert_called_with(root) self.assertEqual(run.call_args.kwargs["cwd"], root) self.assertEqual(run.call_args.args[0][run.call_args.args[0].index("--model") + 1], "m") @@ -290,35 +289,35 @@ class Interrupt(unittest.TestCase): handle.write(json.dumps(human("typed")) + "\n") run.side_effect = type_a_turn - self.assertEqual(loop.interrupt(root, SESSION_ID, "m", transcript, "q?"), "") + self.assertEqual(cycle.interrupt(root, SESSION_ID, "m", transcript, "q?", paths_from(pathlib.Path(root), {}), {}), "") class Trust(unittest.TestCase): def test_says_why_the_config_cannot_be_read_and_records_only_what_is_new(self): - with tempfile.TemporaryDirectory() as home, unittest.mock.patch.dict(os.environ, {"HOME": home}), umask(0o022): + with tempfile.TemporaryDirectory() as home, umask(0o022): config = pathlib.Path(home, ".claude.json") with contextlib.redirect_stderr(io.StringIO()) as err: - loop.trust(["/a"]) + cycle.trust(config, ["/a"]) self.assertEqual(err.getvalue(), f"could not read {config}: No such file or directory\n") config.write_text("{") with contextlib.redirect_stderr(io.StringIO()) as err: - loop.trust(["/a"]) + cycle.trust(config, ["/a"]) self.assertIn(f"could not read {config}: ", err.getvalue()) for shape in ([], {"projects": []}, {"projects": {"/a": 1}}): config.write_text(json.dumps(shape)) with contextlib.redirect_stderr(io.StringIO()) as err: - loop.trust(["/a"]) + cycle.trust(config, ["/a"]) self.assertEqual(err.getvalue(), f"could not read {config}: not an object whose \"projects\" maps paths to objects\n") self.assertEqual(json.loads(config.read_text()), shape) data = {"other": 1, "projects": {"/a": {"hasTrustDialogAccepted": True, "kept": 2}}} config.write_text(json.dumps(data)) config.chmod(0o600) with contextlib.redirect_stderr(io.StringIO()) as err: - loop.trust(["/a"]) + cycle.trust(config, ["/a"]) self.assertEqual(err.getvalue(), "") self.assertEqual(json.loads(config.read_text()), data) with contextlib.redirect_stderr(io.StringIO()) as err: - loop.trust(["/a", "/b"]) + cycle.trust(config, ["/a", "/b"]) self.assertEqual(err.getvalue(), "trusted for the interrupt: /b\n") data["projects"]["/b"] = {"hasTrustDialogAccepted": True} self.assertEqual(json.loads(config.read_text()), data) @@ -326,7 +325,7 @@ class Trust(unittest.TestCase): contextlib.redirect_stderr(io.StringIO()) as err, unittest.mock.patch("os.replace", side_effect=OSError(errno.EACCES, "Permission denied")), ): - loop.trust(["/c"]) + cycle.trust(config, ["/c"]) self.assertEqual(err.getvalue(), f"could not write {config}: Permission denied\n") self.assertEqual(json.loads(config.read_text()), data) self.assertEqual(stat.S_IMODE(config.stat().st_mode), 0o600) @@ -335,25 +334,25 @@ class Trust(unittest.TestCase): class Parse(unittest.TestCase): def test_yields_only_json_objects(self): - self.assertEqual(loop.parse('{"type": "user"}'), {"type": "user"}) - self.assertIsNone(loop.parse("not json")) - self.assertIsNone(loop.parse("[1, 2]")) + self.assertEqual(cycle.parse('{"type": "user"}'), {"type": "user"}) + self.assertIsNone(cycle.parse("not json")) + self.assertIsNone(cycle.parse("[1, 2]")) class Grounded(unittest.TestCase): def test_an_interrupt_must_quote_the_transcript(self): - self.assertTrue(loop.grounded({"interrupt": False, "evidence": ""}, "anything")) - self.assertTrue(loop.grounded({"interrupt": True, "evidence": "Needs you: x"}, "so.\n\nNeeds you: x\n")) - self.assertFalse(loop.grounded({"interrupt": True, "evidence": "invented"}, "the transcript")) - self.assertFalse(loop.grounded({"interrupt": True, "evidence": ""}, "the transcript")) - self.assertFalse(loop.grounded({"interrupt": True, "evidence": " "}, "the transcript")) + self.assertTrue(cycle.grounded({"interrupt": False, "evidence": ""}, "anything")) + self.assertTrue(cycle.grounded({"interrupt": True, "evidence": "Needs you: x"}, "so.\n\nNeeds you: x\n")) + self.assertFalse(cycle.grounded({"interrupt": True, "evidence": "invented"}, "the transcript")) + self.assertFalse(cycle.grounded({"interrupt": True, "evidence": ""}, "the transcript")) + self.assertFalse(cycle.grounded({"interrupt": True, "evidence": " "}, "the transcript")) class Verdict(unittest.TestCase): def test_needs_every_field_the_schema_requires(self): - self.assertTrue(loop.complete({"interrupt": False, "evidence": "", "finished": True, "question": ""})) - self.assertFalse(loop.complete({"interrupt": False})) - self.assertFalse(loop.complete(None)) + self.assertTrue(cycle.complete({"interrupt": False, "evidence": "", "finished": True, "question": ""})) + self.assertFalse(cycle.complete({"interrupt": False})) + self.assertFalse(cycle.complete(None)) STUB_CLAUDE = """#!/usr/bin/env python3 @@ -392,7 +391,7 @@ class RunWorker(unittest.TestCase): for failure, script in scripts.items(): pathlib.Path(stub).write_text(f"#!/usr/bin/env python3\nimport json\nimport os\nimport sys\n{script}\n") os.chmod(stub, 0o700) - self.assertEqual(loop.run_worker(bin, []), failure) + self.assertEqual(cycle.run_worker(bin, []), failure) class RunCycle(unittest.TestCase): @@ -402,24 +401,25 @@ class RunCycle(unittest.TestCase): pathlib.Path(stub).write_text(STUB_CLAUDE) os.chmod(stub, 0o700) calls, verdicts = os.path.join(home, "calls"), os.path.join(home, "verdicts") + session_id = cycle.uuid.uuid5(cycle.SESSION_NAMESPACE, cycle.session_name(home, paths_from(pathlib.Path(home), {}).code)) pathlib.Path(verdicts).write_text("fail continue finished unquoted continue") - loop.ARCHIVE = os.path.join(home, "archive") + paths = paths_from(pathlib.Path(home), {"LOOP_CLAUDE_TRANSCRIPTS": os.path.join(home, "archive")}) 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, unittest.mock.patch("sys.stdin.isatty", return_value=False): for _ in range(3): - self.assertEqual(loop.run_cycle(home, "task", "premises", "A name", SESSION_ID, "claude-opus-5-5"), "") + self.assertEqual(cycle.run_cycle(home, "task", "premises", "claude-opus-5-5", paths, {}), Continue()) pathlib.Path(verdicts).write_text("interrupt") with unittest.mock.patch("sys.stderr") as stderr: - self.assertEqual(loop.run_cycle(home, "task", "premises", "A name", SESSION_ID, "claude-opus-5-5"), loop.Stop(2, "stdin or stdout is not a terminal")) - self.assertIn(f"transcript: {loop.ARCHIVE}", "".join(str(call.args[0]) for call in stderr.write.call_args_list)) + self.assertEqual(cycle.run_cycle(home, "task", "premises", "claude-opus-5-5", paths, {}), Stop(2, "stdin or stdout is not a terminal")) + self.assertIn(f"transcript: {paths.archive}", "".join(str(call.args[0]) for call in stderr.write.call_args_list)) pathlib.Path(verdicts).write_text("interrupt fail fail fail") - with unittest.mock.patch("sys.stderr"), unittest.mock.patch.object(loop, "interrupt", return_value=""): - self.assertEqual(loop.run_cycle(home, "task", "premises", "A name", SESSION_ID, "claude-opus-5-5").code, 1) - with unittest.mock.patch.object(loop, "session_file", return_value=""): - self.assertEqual(loop.run_cycle(home, "task", "premises", "A name", SESSION_ID, "claude-opus-5-5"), loop.Stop(1, f"claude left no transcript for session {SESSION_ID}")) + with unittest.mock.patch("sys.stderr"), unittest.mock.patch.object(cycle, "interrupt", return_value=""): + self.assertEqual(cycle.run_cycle(home, "task", "premises", "claude-opus-5-5", paths, {}).code, 1) + with unittest.mock.patch.object(cycle, "session_file", return_value=""): + self.assertEqual(cycle.run_cycle(home, "task", "premises", "claude-opus-5-5", paths, {}), Stop(1, f"claude left no transcript for session {session_id}")) for plan in ("fail fail fail", "unquoted unquoted unquoted"): pathlib.Path(verdicts).write_text(plan) - stop = loop.run_cycle(home, "task", "premises", "A name", SESSION_ID, "claude-opus-5-5") + stop = cycle.run_cycle(home, "task", "premises", "claude-opus-5-5", paths, {}) self.assertEqual(stop.code, 1) self.assertTrue(stop.reason.startswith("the judge ")) if plan.startswith("unquoted"): @@ -428,74 +428,73 @@ class RunCycle(unittest.TestCase): self.assertEqual({json.loads(line)[0] for line in pathlib.Path(calls).read_text().splitlines()}, {home}) starts = [args[args.index("-p") + 1:][:3] for args in map(json.loads, pathlib.Path(calls).read_text().splitlines()) if "--json-schema" not in args] self.assertEqual([start[1] for start in starts], ["--name", "--resume", "--name", "--resume", "--resume", "--name", "--resume", "--resume"]) - self.assertEqual(starts[1][2], SESSION_ID) + self.assertEqual(starts[1][2], str(session_id)) self.assertEqual(sleep.call_count, 8) self.assertEqual({args[args.index("--model") + 1] for args in map(json.loads, pathlib.Path(calls).read_text().splitlines())}, {"claude-opus-5-5"}) class Reload(unittest.TestCase): - def test_runs_the_edited_file_before_trusting_it_and_hands_it_the_state_as_one_json_argument(self): + def test_an_edited_package_file_reloads_once_the_launcher_answers_help(self): with tempfile.TemporaryDirectory() as root: - script = os.path.join(root, "loop-claude") - pathlib.Path(script).write_text(loop.RELOAD_BASELINE.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(loop.LoopState(1, 0, "/r", "do it")) - execv.assert_not_called() - pathlib.Path(script).write_text(loop.RELOAD_BASELINE.replace("RELOAD_FLAG = ", "RELOAD_FLAG = \"x\" or ")) - environment = dict(os.environ) - with unittest.mock.patch.object(loop, "__file__", script), unittest.mock.patch("os.execv") as execv: - loop.reload_if_edited(loop.LoopState(1, 2, "/r", "do it")) - execv.assert_called_once_with(sys.executable, [sys.executable, script, loop.RELOAD_FLAG, json.dumps({"cycle_number": 1, "failures": 2, "root": "/r", "task": "do it"})]) - self.assertEqual(dict(os.environ), environment) + copy = pathlib.Path(root, "bin") + shutil.copytree(LAUNCHER.parent, copy, ignore=shutil.ignore_patterns("__pycache__", "test_*")) + launcher, edited = copy / "loop-claude", copy / "loop_claude" / "cycle.py" + state = main.LoopState(1, 2, "/r", "do it") + with unittest.mock.patch("os.execv") as execv, contextlib.redirect_stderr(io.StringIO()) as err: + baseline = reload.fingerprint(launcher) + edited.write_text(edited.read_text() + "\ndef\n") + reload.reload_if_edited(launcher, baseline, state) + execv.assert_not_called() + self.assertIn("keeping the running script", err.getvalue()) + edited.write_text(edited.read_text().replace("\ndef\n", "\n# edited\n")) + reload.reload_if_edited(launcher, baseline, state) + execv.assert_called_once_with(sys.executable, [sys.executable, str(launcher), main.RELOAD_FLAG, json.dumps({"cycle_number": 1, "failures": 2, "root": "/r", "task": "do it"})]) class Main(unittest.TestCase): - def test_exits_only_here_with_the_stop_the_loop_returned(self): - for argv, code, stream in ((["--help"], 0, "stdout"), ([], 1, "stderr"), ([loop.RELOAD_FLAG, "3"], 1, "stderr")): - with self.subTest(argv=argv), unittest.mock.patch.object(sys, "argv", ["loop-claude", *argv]), contextlib.redirect_stdout(io.StringIO()) as out, contextlib.redirect_stderr(io.StringIO()) as err, self.assertRaises(SystemExit) as stopped: - loop.main() - self.assertEqual(stopped.exception.code, code) - self.assertEqual({"stdout": out, "stderr": err}[stream].getvalue(), loop.run_loop(argv).reason + "\n") - with unittest.mock.patch.object(loop, "run_loop", side_effect=KeyboardInterrupt), self.assertRaises(SystemExit) as stopped: - loop.main() - self.assertEqual(stopped.exception.code, 130) + def test_returns_the_exit_code_of_the_stop_the_loop_returned(self): + for argv, code, stream in ((["--help"], 0, "stdout"), ([], 1, "stderr"), ([main.RELOAD_FLAG, "3"], 1, "stderr")): + with self.subTest(argv=argv), contextlib.redirect_stdout(io.StringIO()) as out, contextlib.redirect_stderr(io.StringIO()) as err: + self.assertEqual(main.main(argv, {}, PATHS, LAUNCHER, CWD), code) + self.assertEqual({"stdout": out, "stderr": err}[stream].getvalue(), main.loop_state(argv, CWD).reason + "\n") + with unittest.mock.patch.object(main, "run_loop", side_effect=KeyboardInterrupt): + self.assertEqual(main.main(["t"], {}, PATHS, LAUNCHER, CWD), 130) class RunLoop(unittest.TestCase): def test_stops_naming_the_reload_when_it_hands_over_anything_but_the_state_with_a_task(self): for handed in (["3", "2", "/r", "do it"], ["3"], ["[1]"], [json.dumps({"cycle_number": 3, "failures": 0, "root": "/r"})], [json.dumps({"cycle_number": 3, "failures": 0, "root": "/r", "task": ""})], [json.dumps({"cycle_number": "3", "failures": 0, "root": "/r", "task": "do it"})], [json.dumps({"cycle_number": 3, "failures": 0, "root": "", "task": "do it"})], [json.dumps({"cycle_number": 3, "failures": 0, "root": "/r", "task": "do it", "turns": 1})]): with self.subTest(handed=handed): - self.assertEqual(loop.run_loop([loop.RELOAD_FLAG, *handed]), loop.Stop(1, f"the reload cannot read the loop's state from {handed}; rerun loop-claude ")) + self.assertEqual(main.loop_state([main.RELOAD_FLAG, *handed], CWD), Stop(1, f"the reload cannot read the loop's state from {handed}; rerun loop-claude ")) def test_resumes_the_root_and_counters_a_reload_handed_over(self): - patches = [unittest.mock.patch.object(loop, name) for name in ("checkout_root", "read_premises", "reload_if_edited", "run_cycle", "project_model")] - stopped = loop.Stop(1, "stopped") + patches = [unittest.mock.patch.object(main, name) for name in ("checkout_root", "read_premises", "reload_if_edited", "run_cycle", "project_model")] + stopped = Stop(1, "stopped") with contextlib.ExitStack() as stack: mocks = [stack.enter_context(patch) for patch in patches] stack.enter_context(unittest.mock.patch.object(sys, "stdout", io.StringIO())) mocks[3].return_value = stopped - self.assertEqual(loop.run_loop([loop.RELOAD_FLAG, json.dumps({"cycle_number": 3, "failures": 2, "root": "/r", "task": "do it"})]), stopped) + self.assertEqual(main.run_loop([main.RELOAD_FLAG, json.dumps({"cycle_number": 3, "failures": 2, "root": "/r", "task": "do it"})], {}, PATHS, LAUNCHER, CWD), stopped) mocks[0].assert_not_called() mocks[1].assert_called_once_with("/r") - mocks[2].assert_called_once_with(loop.LoopState(3, 2, "/r", "do it")) + self.assertEqual(mocks[2].call_args.args[2], main.LoopState(3, 2, "/r", "do it")) self.assertEqual(mocks[3].call_args.args[0], "/r") - mocks[4].assert_called_once_with("/r") - self.assertEqual(mocks[3].call_args.args[-1], mocks[4].return_value) + mocks[4].assert_called_once_with("/r", PATHS, {}) + self.assertEqual(mocks[3].call_args.args[3], mocks[4].return_value) mocks[0].return_value = "/s" - self.assertEqual(loop.run_loop(["do", "it"]), stopped) - mocks[0].assert_called_once_with() + self.assertEqual(main.run_loop(["do", "it"], {}, PATHS, LAUNCHER, CWD), stopped) + mocks[0].assert_called_once_with(CWD) mocks[1].assert_called_with("/s") self.assertIn("=== cycle 4 ===", sys.stdout.getvalue()) for leaf in (0, 1, 4): with self.subTest(leaf=leaf): - mocks[leaf].return_value = loop.Stop(2, f"leaf {leaf}") - self.assertEqual(loop.run_loop(["do it"]), mocks[leaf].return_value) + mocks[leaf].return_value = Stop(2, f"leaf {leaf}") + self.assertEqual(main.run_loop(["do it"], {}, PATHS, LAUNCHER, CWD), mocks[leaf].return_value) mocks[leaf].return_value = "/s" - mocks[3].return_value = None - mocks[3].side_effect = ["claude exited 3"] * 3 + mocks[3].side_effect = [Retry("claude exited 3")] * 3 stack.enter_context(unittest.mock.patch.object(sys, "stderr", io.StringIO())) sleep = stack.enter_context(unittest.mock.patch("time.sleep")) - self.assertEqual(loop.run_loop([loop.RELOAD_FLAG, json.dumps({"cycle_number": 3, "failures": 0, "root": "/r", "task": "do it"})]), loop.Stop(1, "the worker failed three times running: claude exited 3")) + self.assertEqual(main.run_loop([main.RELOAD_FLAG, json.dumps({"cycle_number": 3, "failures": 0, "root": "/r", "task": "do it"})], {}, PATHS, LAUNCHER, CWD), Stop(1, "the worker failed three times running: claude exited 3")) self.assertIn("retrying the worker in a minute: claude exited 3", sys.stderr.getvalue()) self.assertEqual(sleep.call_count, 2) diff --git a/docs/decisions.md b/docs/decisions.md index c9fa0a0e..d1e1fcec 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -10,7 +10,7 @@ ## loop-claude: one session per project, at a fixed id -2026-09-21, lilleman; the rename and mirrored-path costs accepted 2026-09-25 by larv-review. Serves goal 4. One fixed id per project keeps the session picker at one entry per project and makes any transcript under that id the script's own to delete. The id derives from the session name, so moving the checkout or changing that name orphans open sessions: they stay in the picker until the human deletes them, migration code not being worth a one-human audience. A checkout outside `~/code` mirroring a path inside it would share its id. Valid while claude takes `--session-id` and resumes by it, and no checkout outside `~/code` mirrors a path inside it. +2026-09-21, lilleman; the rename and mirrored-path costs accepted 2026-09-25 by larv-review. Serves goal 4. One fixed id per project keeps the session picker at one entry per project and makes any transcript under that id loop-claude's own to delete. The id derives from the session name, so moving the checkout or changing that name orphans open sessions: they stay in the picker until the human deletes them, migration code not being worth a one-human audience. A checkout outside `~/code` mirroring a path inside it would share its id. Valid while claude takes `--session-id` and resumes by it, and no checkout outside `~/code` mirrors a path inside it. ## loop-claude: the trust file is rewritten before an interrupt @@ -36,9 +36,9 @@ 2026-09-27, lilleman, restating the 2026-09-24 target and extending it to the overall. Serves goal 4. The 2026-09-28 run, Junior A, Mid A, the maintainability senior and the inherited architect at depth 1 over every non-test file, blind to `todo.md` and this log, scored Navigation 7.25, Locality 6.0, Shape 6.5, Self-sufficiency 6.25, overall 6.25; on 2026-09-26 they were 7.75, 6.25, 7.0, 6.75, 6.75. Every seat scored Locality 6, and three of four named `run_cycle`'s three-way return and larv-review's re-entry rules, split across the passes on 2026-09-28. The rebuild planned in `todo.md` under 0.1.0 answers the places named, and a later chunk may not lower any dimension. Valid until the next scoring run, which uses the same four seats. -## loop-claude: the five section headers stay +## loop-claude: the section headers stay -2026-09-26, larv-review, declining a prose-pass deletion under `CLAUDE.md` → "Comments and documentation". Serves goal 4. Two seats of the 2026-09-26 panel credit Navigation 8 to `# The transcript file` and its four siblings indexing the script by the Claude Code internal each group touches. Valid until a scoring run scores Navigation without them. +2026-09-26, larv-review, declining a prose-pass deletion under `CLAUDE.md` → "Comments and documentation". Serves goal 4. Two seats of the 2026-09-26 panel credit Navigation 8 to `# The transcript file` and its siblings, now in `bin/loop_claude/cycle.py`, indexing it by the file or format each group touches. Valid until the modules the rebuild splits out of `cycle.py` take over that index. ## vocabulary: the concept words are defined under `CLAUDE.md` → "Vocabulary" and cited by a bare link @@ -50,7 +50,7 @@ ## loop-claude: a reload into an older file is unsupported -2026-09-26, lilleman. Serves goal 4. A running loop whose `bin/loop-claude` on disk is rolled back to a version with an older handover fails in that older file, or, older than the handover itself, runs `--reloaded ` as its task; this version cannot change either; the human who rolled it back reruns `loop-claude `. Valid while nobody but the developer runs it: other team members running it while it is still developed reopens this. +2026-09-26, lilleman. Serves goal 4. A running loop whose `bin/loop-claude` or `bin/loop_claude/` on disk is rolled back to a version with an older handover fails in that older file, or, older than the handover itself, runs `--reloaded ` as its task; this version cannot change either; the human who rolled it back reruns `loop-claude `. Valid while nobody but the developer runs it: other team members running it while it is still developed reopens this. ## loop-claude: a CR-only README.md is reported at line 1 @@ -83,3 +83,7 @@ ## loop-claude: the rebuild keeps main's `--reloaded` state 2026-09-28, lilleman, for the rebuild. Serves goal 4. A loop running main's script reloads into the rebuilt one at its next cycle boundary and carries on; the state keeps main's four fields, `cycle_number`, `failures`, `root` and `task`, so no code exists only for the cut-over. Valid until the rebuild merges. + +## rebuild: a chunk into `rebuild` takes no comprehension scoring run + +2026-09-28, larv-review, reading the rebuild decision above. Serves goal 4. The floor and its ratchet gate `rebuild` into main, scored by the plan's last item; the chunks before it pass through half-moved states a per-chunk run would block. Valid until the rebuild merges. diff --git a/todo.md b/todo.md index b6fc7eb9..299f539b 100644 --- a/todo.md +++ b/todo.md @@ -2,13 +2,13 @@ ## 0.1.0 -**⚠️ THE REBUILD NEVER MERGES INTO MAIN WITHOUT THE HUMAN'S EXPLICIT APPROVAL.** Every rebuild chunk is a worktree based on `origin/rebuild` with its PR into `rebuild`, never into main. What remains of the rebuild is `rebuild`'s `todo.md` (`git show origin/rebuild:todo.md`), where each chunk ticks its item off; this copy stays as planned until the merge. Other sessions run on `~/.claude` main throughout; only the human merges `rebuild` into main, once they have approved the finished whole. +**⚠️ THE REBUILD NEVER MERGES INTO MAIN WITHOUT THE HUMAN'S EXPLICIT APPROVAL.** Every rebuild chunk is a worktree based on `origin/rebuild` with its PR into `rebuild`, never into main. Other sessions run on `~/.claude` main throughout; only the human merges `rebuild` into main, once they have approved the finished whole. -Ships when a four-seat scoring run puts every dimension and the overall at 7.0 or above (`docs/decisions.md`). The rebuild lifts every dimension: each item below is one chunk on a worktree based on `origin/rebuild`, its PR into `rebuild`, until the last item merges `rebuild` into main. The sketches, the judges' verdicts and what to take from each: `~/code/claude-handoffs/claude-config_2026-09-28.md`. +The rebuild lifts every dimension: each item below is one chunk on a worktree based on `origin/rebuild`, its PR into `rebuild`, until the last item merges `rebuild` into main. The sketches, the judges' verdicts and what to take from each: `~/code/claude-handoffs/claude-config_2026-09-28.md`. -- **Lay out `bin/loop-claude` as a launcher over a `bin/loop_claude/` package, with the loop, checkout and premises moved in.** The launcher resolves its own symlink, injects `Paths` and the environment, and is the only thing that exits; `main` owns the loop state, carries it across a reload on argv, and maps `Stop | Retry | Continue`. The black-box tests pass unchanged. -- **Move the transcript, the session and the worker into their own modules.** `UserEntryKind` names each entry Claude Code writes; a malformed line is skipped; an unreadable transcript is its own error, never "typed nothing"; `session` states the lifecycle once, where the id is made. -- **Move the judge, the interrupt, trust and model resolution into their own modules.** The judge is retried alone and checks evidence on every verdict against the rendered transcript; `models` owns the whole resolution, env overrides included, with no sentinel; `trust` names a `projects` entry that is not an object; `input()` at end of file is exit 2. +- **Move the transcript, the session and the worker into their own modules.** `UserEntryKind` names each entry Claude Code writes; a malformed line is skipped; an unreadable transcript is its own error, never "typed nothing"; `session` states the lifecycle once, where the id is made; `run_worker` returns a failure its caller maps, never `""` for success. +- **Move the judge, the interrupt, trust and model resolution into their own modules.** The judge is retried alone and checks evidence on every verdict against the rendered transcript; `models` owns the whole resolution, env overrides included, with no sentinel; `trust` names a `projects` entry that is not an object; `input()` at end of file is exit 2. `ask_model` and `interrupt` spell "the human is needed" one way; `replace_json` and `make_private` get one module shared by `models`, `trust` and the archive. +- **Move each Claude Code internal `--help` lists beside the module relying on it.** Or `docs/decisions.md` says why `--help` keeps it. - **Archive the raw transcript, deduplicated by content hash, with the verdict beside it, and stop on a failed archive.** Tests first; the changelog line says what the archive now holds. - **Replace `bin/test_loop_claude.py`'s internal-function tests with the black-box tests plus unit tests of the pure parsers.** - **Hold every reviewer to one findings document, `principles/review-findings.md`.** Severity, verdict, rounds with round 2 verifying each earlier finding, the per-chunk round cap, declining, and `/security-review`'s HIGH/MEDIUM/LOW mapped onto the scale; it replaces `principles/review-protocol.md`.