diff --git a/bin/loop-claude b/bin/loop-claude index 4a060d5d..4afdffda 100755 --- a/bin/loop-claude +++ b/bin/loop-claude @@ -82,267 +82,35 @@ JUDGE_SCHEMA = { } -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 read_premises(root): - try: - found = sections(open(os.path.join(root, "README.md"), encoding="utf-8").read()) - except OSError as failure: - sys.exit(f"README.md in {root}: {failure.strerror} - no premises.") - for name in ("Goals", "Audience"): - bodies = found.get(name, []) - if not bodies: - sys.exit(f"README.md has no ## {name} heading - no premises.") - if len(bodies) > 1: - sys.exit(f"README.md has ## {name} more than once - no premises.") - if not bodies[0]: - sys.exit(f"README.md has nothing under ## {name} - no premises.") - return f"## Goals\n{found['Goals'][0]}\n\n## Audience\n{found['Audience'][0]}" - - -def checkout_root(): - found = subprocess.run(["git", "rev-parse", "--show-toplevel"], capture_output=True, text=True) - if found.returncode != 0: - sys.exit(found.stderr.strip()) - return found.stdout.strip() - - -def project(root): - return root.removeprefix(os.path.expanduser("~/code/")).lstrip("/") - - -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(root)} loop-claude" - - -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 session_open(session_id): - return bool(session_file(session_id)) - - -def parse(raw): - try: - entry = json.loads(raw) - except ValueError: - return None - return entry if isinstance(entry, dict) else None - - -def entries(path): - for raw in open(path, encoding="utf-8"): - if entry := parse(raw): - yield entry - - -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 "" - - -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 typed(entry): - """A human turn: a "user" entry, not isMeta, not promptSource "sdk" (the loop's own prompts), whose message.content is a string not starting with "<" ( and its kind) or one or more text parts, none starting with "[Request interrupted".""" - if entry.get("type") != "user" or entry.get("isMeta") or entry.get("promptSource") == "sdk": - return False - content = entry.get("message", {}).get("content") - if isinstance(content, str): - return not content.startswith("<") - parts = content if isinstance(content, list) else [] - return bool(parts) and all(isinstance(part, dict) and part.get("type") == "text" and not part.get("text", "").startswith("[Request interrupted") for part in parts) - - -def human_turns(entries): - return sum(1 for entry in entries if typed(entry)) - - -def make_private(folder): - mask = os.umask(0o077) - try: - os.makedirs(folder, exist_ok=True) - finally: - os.umask(mask) - - -def archive(root, path, note): - folder = os.path.join(ARCHIVE, project(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(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 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", {}) - granted = [path for path in paths if not projects.get(path, {}).get("hasTrustDialogAccepted")] - if not granted: - return - for path in granted: - projects.setdefault(path, {})["hasTrustDialogAccepted"] = True - staged = f"{config}.loop-claude" - try: - with open(staged, "w", encoding="utf-8") as handle: - json.dump(data, handle, indent=2) - os.replace(staged, config) - except OSError as failure: - print(f"could not write {config}: {failure.strerror}", file=sys.stderr) - return - print("trusted for the interrupt: " + ", ".join(granted), file=sys.stderr) - - -def model(variable): - return ["--model", os.environ[variable]] if os.environ.get(variable) else [] - - -def worker_args(task, name, session_id, resuming): - if resuming: - start = ["-p", "Continue the task; the previous run stopped before it was finished.", "--resume", str(session_id)] +def main(): + argv = sys.argv[1:] + if argv[:1] == [RELOAD_FLAG]: + state = reloaded_state(argv[1:]) 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("LOOP_CLAUDE_WORKER_MODEL"), - ] - - -def run_worker(root, args): - proc = subprocess.Popen(["claude", *args], cwd=root, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, text=True) - 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 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 ask 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["ask"]: - return True - evidence = verdict["evidence"] - return evidence.strip() != "" and evidence in transcript - - -def judge(root, task, premises, transcript): - args = [ - "-p", - "--json-schema", json.dumps(JUDGE_SCHEMA), - *model("LOOP_CLAUDE_JUDGE_MODEL"), - "--no-session-persistence", - "--output-format", "json", - "--permission-mode", "bypassPermissions", - "--tools", "", - ] - prompt = judge_prompt(task, premises, transcript) - for attempt in range(3): - 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, asking: {verdict['question']}" - else: - return verdict - if attempt == 2: - sys.exit(f"the judge failed three times running: {failure}") - print(f"retrying the judge in a minute: {failure}", file=sys.stderr) + state = {"cycle_number": 0, "failures": 0, "root": "", "task": " ".join(argv)} + if state["task"] in ("", "-h", "--help"): + print(__doc__.strip()) + sys.exit(0 if state["task"] else 1) + task = state["task"] + root = state["root"] or checkout_root() + cycle_number, failures = state["cycle_number"], state["failures"] + while True: + reload_if_edited(root, task, cycle_number, failures) + cycle_number += 1 + premises = read_premises(root) + name = session_name(root) + print(f"\n=== cycle {cycle_number} ===", flush=True) + failure = run_cycle(root, task, premises, name, uuid.uuid5(SESSION_NAMESPACE, name)) + if not failure: + failures = 0 + continue + failures += 1 + if failures == 3: + sys.exit(f"the worker failed three times running: {failure}") + print(f"retrying the worker in a minute: {failure}", file=sys.stderr) time.sleep(60) -def interrupt(root, session_id, 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", "--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 run_cycle(root, task, premises, name, session_id): if failure := run_worker(root, worker_args(task, name, session_id, resuming=session_open(session_id))): return failure @@ -385,35 +153,282 @@ def reloaded_state(handed): return state -def main(): - argv = sys.argv[1:] - if argv[:1] == [RELOAD_FLAG]: - state = reloaded_state(argv[1:]) +def checkout_root(): + found = subprocess.run(["git", "rev-parse", "--show-toplevel"], capture_output=True, text=True) + if found.returncode != 0: + sys.exit(found.stderr.strip()) + return found.stdout.strip() + + +def read_premises(root): + try: + found = sections(open(os.path.join(root, "README.md"), encoding="utf-8").read()) + except OSError as failure: + sys.exit(f"README.md in {root}: {failure.strerror} - no premises.") + for name in ("Goals", "Audience"): + bodies = found.get(name, []) + if not bodies: + sys.exit(f"README.md has no ## {name} heading - no premises.") + if len(bodies) > 1: + sys.exit(f"README.md has ## {name} more than once - no premises.") + if not bodies[0]: + sys.exit(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(root)} loop-claude" + + +def archive(root, path, note): + folder = os.path.join(ARCHIVE, project(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(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 model(variable): + return ["--model", os.environ[variable]] if os.environ.get(variable) else [] + + +def project(root): + return root.removeprefix(os.path.expanduser("~/code/")).lstrip("/") + + +# 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): + for raw in open(path, encoding="utf-8"): + 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): + """A human turn: a "user" entry, not isMeta, not promptSource "sdk" (the loop's own prompts), whose message.content is a string not starting with "<" ( and its kind) or one or more text parts, none starting with "[Request interrupted".""" + if entry.get("type") != "user" or entry.get("isMeta") or entry.get("promptSource") == "sdk": + return False + content = entry.get("message", {}).get("content") + if isinstance(content, str): + return not content.startswith("<") + parts = content if isinstance(content, list) else [] + return bool(parts) and all(isinstance(part, dict) and part.get("type") == "text" and not part.get("text", "").startswith("[Request interrupted") for part in parts) + + +# "assistant" entries and stream-json + + +def run_worker(root, args): + proc = subprocess.Popen(["claude", *args], cwd=root, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, text=True) + 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, resuming): + if resuming: + start = ["-p", "Continue the task; the previous run stopped before it was finished.", "--resume", str(session_id)] else: - state = {"cycle_number": 0, "failures": 0, "root": "", "task": " ".join(argv)} - if state["task"] in ("", "-h", "--help"): - print(__doc__.strip()) - sys.exit(0 if state["task"] else 1) - task = state["task"] - root = state["root"] or checkout_root() - cycle_number, failures = state["cycle_number"], state["failures"] - while True: - reload_if_edited(root, task, cycle_number, failures) - cycle_number += 1 - premises = read_premises(root) - name = session_name(root) - print(f"\n=== cycle {cycle_number} ===", flush=True) - failure = run_cycle(root, task, premises, name, uuid.uuid5(SESSION_NAMESPACE, name)) - if not failure: - failures = 0 - continue - failures += 1 - if failures == 3: - sys.exit(f"the worker failed three times running: {failure}") - print(f"retrying the worker in a minute: {failure}", file=sys.stderr) + 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("LOOP_CLAUDE_WORKER_MODEL"), + ] + + +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): + args = [ + "-p", + "--json-schema", json.dumps(JUDGE_SCHEMA), + *model("LOOP_CLAUDE_JUDGE_MODEL"), + "--no-session-persistence", + "--output-format", "json", + "--permission-mode", "bypassPermissions", + "--tools", "", + ] + prompt = judge_prompt(task, premises, transcript) + for attempt in range(3): + 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, asking: {verdict['question']}" + else: + return verdict + if attempt == 2: + sys.exit(f"the judge failed three times running: {failure}") + print(f"retrying the judge in a minute: {failure}", file=sys.stderr) time.sleep(60) +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 ask 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["ask"]: + return True + evidence = verdict["evidence"] + return evidence.strip() != "" and evidence in transcript + + +# ~/.claude.json + + +def interrupt(root, session_id, 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", "--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", {}) + granted = [path for path in paths if not projects.get(path, {}).get("hasTrustDialogAccepted")] + if not granted: + return + for path in granted: + projects.setdefault(path, {})["hasTrustDialogAccepted"] = True + staged = f"{config}.loop-claude" + try: + with open(staged, "w", encoding="utf-8") as handle: + json.dump(data, handle, indent=2) + os.replace(staged, config) + except OSError as failure: + print(f"could not write {config}: {failure.strerror}", file=sys.stderr) + return + print("trusted for the interrupt: " + ", ".join(granted), file=sys.stderr) + + if __name__ == "__main__": try: main() diff --git a/todo.md b/todo.md index 427fa67a..ee8aea46 100644 --- a/todo.md +++ b/todo.md @@ -4,7 +4,6 @@ Ordered by how many seats of the 2026-09-25 scoring panel (`docs/decisions.md`) named the place; each is one chunk. -- Group `bin/loop-claude` by the Claude Code internals it rests on, in the docstring's order, with `main` and `run_cycle` above what they call, today 36 flat names with the adapter scattered. - Exit `loop-claude` with a message, today a traceback, when `README.md` is not UTF-8. - Say under `CLAUDE.md` → "One spelling per goal" that one spelling in two places is the same case, and what its rejection names. - Say `could not read` when `~/.claude.json` parses to anything but an object whose `projects` maps paths to objects, today a traceback before the interrupt.