From 24ae33a580bf251486c343669e9b76690be41610 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sat, 26 Sep 2026 14:53:40 +0200 Subject: [PATCH 1/3] Group bin/loop-claude by the Claude Code internals it rests on, main and run_cycle first --- bin/loop-claude | 647 +++++++++++++++++++++++++----------------------- 1 file changed, 344 insertions(+), 303 deletions(-) diff --git a/bin/loop-claude b/bin/loop-claude index 4a060d5d..803829ea 100755 --- a/bin/loop-claude +++ b/bin/loop-claude @@ -82,309 +82,6 @@ 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)] - 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) - 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 - path = session_file(session_id) - if not path: - sys.exit(f"claude left no transcript for session {session_id}") - verdict = judge(root, task, premises, render(entries(path))) - while verdict["ask"]: - archive(root, path, f"Task: {task}\n\nVerdict: needs input\n\n{verdict['question']}") - if failure := interrupt(root, session_id, path, verdict["question"]): - print(failure, file=sys.stderr) - sys.exit(2) - verdict = judge(root, task, premises, render(entries(path))) - if verdict["finished"]: - archive(root, path, f"Task: {task}\n\nVerdict: finished") - delete_transcript_files(path) - return "" - - -def reload_if_edited(root, task, cycle_number, failures): - try: - source = open(__file__, encoding="utf-8").read() - 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 - state = {"cycle_number": cycle_number, "failures": failures, "root": root, "task": task} - os.execv(sys.executable, [sys.executable, __file__, RELOAD_FLAG, json.dumps(state)]) - - -def reloaded_state(handed): - state = parse(handed[0]) if len(handed) == 1 else None - if not state or {"cycle_number", "failures", "root"} - state.keys() or not isinstance(state.get("task"), str) or not state["task"]: - sys.exit(f"the reload cannot read the loop's state from {handed}; rerun loop-claude ") - return state - - def main(): argv = sys.argv[1:] if argv[:1] == [RELOAD_FLAG]: @@ -414,6 +111,350 @@ def main(): time.sleep(60) + +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 + path = session_file(session_id) + if not path: + sys.exit(f"claude left no transcript for session {session_id}") + verdict = judge(root, task, premises, render(entries(path))) + while verdict["ask"]: + archive(root, path, f"Task: {task}\n\nVerdict: needs input\n\n{verdict['question']}") + if failure := interrupt(root, session_id, path, verdict["question"]): + print(failure, file=sys.stderr) + sys.exit(2) + verdict = judge(root, task, premises, render(entries(path))) + if verdict["finished"]: + archive(root, path, f"Task: {task}\n\nVerdict: finished") + delete_transcript_files(path) + return "" + + + +def reload_if_edited(root, task, cycle_number, failures): + try: + source = open(__file__, encoding="utf-8").read() + 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 + state = {"cycle_number": cycle_number, "failures": failures, "root": root, "task": task} + os.execv(sys.executable, [sys.executable, __file__, RELOAD_FLAG, json.dumps(state)]) + + + +def reloaded_state(handed): + state = parse(handed[0]) if len(handed) == 1 else None + if not state or {"cycle_number", "failures", "root"} - state.keys() or not isinstance(state.get("task"), str) or not state["task"]: + sys.exit(f"the reload cannot read the loop's state from {handed}; rerun loop-claude ") + return state + + + +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 project(root): + return root.removeprefix(os.path.expanduser("~/code/")).lstrip("/") + + + +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) + + +# The transcript file + + +def session_file(session_id): + hit = glob.glob(os.path.expanduser(f"~/.claude/projects/*/{session_id}.jsonl")) + return hit[0] if hit else "" + + + +def session_open(session_id): + return bool(session_file(session_id)) + + + +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 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)) + + +# "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: + 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 model(variable): + return ["--model", os.environ[variable]] if os.environ.get(variable) else [] + + + +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) + + +# --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() -- 2.52.0 From 1eb715354c742663f226a3fd94696a79507d4f1c Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sat, 26 Sep 2026 14:57:42 +0200 Subject: [PATCH 2/3] Two blank lines throughout, callers above callees in each group, model with the loop's own --- bin/loop-claude | 76 ++++++++++++++++--------------------------------- 1 file changed, 25 insertions(+), 51 deletions(-) diff --git a/bin/loop-claude b/bin/loop-claude index 803829ea..4afdffda 100755 --- a/bin/loop-claude +++ b/bin/loop-claude @@ -111,7 +111,6 @@ def main(): time.sleep(60) - 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 @@ -131,7 +130,6 @@ def run_cycle(root, task, premises, name, session_id): return "" - def reload_if_edited(root, task, cycle_number, failures): try: source = open(__file__, encoding="utf-8").read() @@ -148,7 +146,6 @@ def reload_if_edited(root, task, cycle_number, failures): os.execv(sys.executable, [sys.executable, __file__, RELOAD_FLAG, json.dumps(state)]) - def reloaded_state(handed): state = parse(handed[0]) if len(handed) == 1 else None if not state or {"cycle_number", "failures", "root"} - state.keys() or not isinstance(state.get("task"), str) or not state["task"]: @@ -156,7 +153,6 @@ def reloaded_state(handed): return state - def checkout_root(): found = subprocess.run(["git", "rev-parse", "--show-toplevel"], capture_output=True, text=True) if found.returncode != 0: @@ -164,7 +160,6 @@ def checkout_root(): return found.stdout.strip() - def read_premises(root): try: found = sections(open(os.path.join(root, "README.md"), encoding="utf-8").read()) @@ -181,7 +176,6 @@ def read_premises(root): 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(): @@ -196,18 +190,11 @@ def sections(text): 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 project(root): - return root.removeprefix(os.path.expanduser("~/code/")).lstrip("/") - - - def archive(root, path, note): folder = os.path.join(ARCHIVE, project(root)) try: @@ -222,7 +209,6 @@ def archive(root, path, note): print(f"could not archive the transcript: {failure}", file=sys.stderr) - def make_private(folder): mask = os.umask(0o077) try: @@ -231,19 +217,25 @@ def make_private(folder): 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_file(session_id): - hit = glob.glob(os.path.expanduser(f"~/.claude/projects/*/{session_id}.jsonl")) - return hit[0] if hit else "" - - - 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")) + "*"): @@ -253,14 +245,12 @@ def delete_transcript_files(path): 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) @@ -272,6 +262,10 @@ def parse(raw): # "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": @@ -283,11 +277,6 @@ def typed(entry): 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)) - - # "assistant" entries and stream-json @@ -310,7 +299,6 @@ def run_worker(root, args): 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)] @@ -325,22 +313,6 @@ def worker_args(task, name, session_id, resuming): ] - -def model(variable): - return ["--model", os.environ[variable]] if os.environ.get(variable) else [] - - - -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: @@ -352,6 +324,15 @@ def render(entries): 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 @@ -381,7 +362,6 @@ def judge(root, task, premises, transcript): time.sleep(60) - def judge_prompt(task, premises, transcript): return ( f"From README.md:\n{premises}\n\n" @@ -392,12 +372,10 @@ def judge_prompt(task, premises, transcript): ) - def complete(verdict): return isinstance(verdict, dict) and set(JUDGE_SCHEMA["required"]) <= verdict.keys() - def grounded(verdict, transcript): if not verdict["ask"]: return True @@ -418,7 +396,6 @@ def interrupt(root, session_id, path, question): 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) @@ -427,7 +404,6 @@ def checkouts(root): return sorted(set(found)) - def trust(paths): config = os.path.expanduser("~/.claude.json") try: @@ -453,8 +429,6 @@ def trust(paths): print("trusted for the interrupt: " + ", ".join(granted), file=sys.stderr) - - if __name__ == "__main__": try: main() -- 2.52.0 From 9af9745b7a471bd1cbaa281cef79e1c74901a28e Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sat, 26 Sep 2026 14:58:02 +0200 Subject: [PATCH 3/3] Drop the shipped grouping item from the plan --- todo.md | 1 - 1 file changed, 1 deletion(-) 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. -- 2.52.0