From 8f647f859682861072e167d11dab2e7fe148aa30 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 24 Sep 2026 20:10:37 +0200 Subject: [PATCH 1/9] Track loop-claude; continue an unfinished chunk in its session and reload the script each round --- .gitignore | 2 + README.md | 4 + bin/loop-claude | 312 ++++++++++++++++++++++++++++++++++++ skills/larv-review/SKILL.md | 2 +- 4 files changed, 319 insertions(+), 1 deletion(-) create mode 100755 bin/loop-claude diff --git a/.gitignore b/.gitignore index 3519548d..9ea767a7 100644 --- a/.gitignore +++ b/.gitignore @@ -14,6 +14,8 @@ !agent-shared/** !agents/ !agents/*.md +!bin/ +!bin/* !principles/ !principles/*.md !skills/ diff --git a/README.md b/README.md index 12124b42..c2d13d3d 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,10 @@ My personal `~/.claude`, version controlled. Instructions, agents, skills, princ Me, on my own machines. Private repo, nobody else depends on it. +## Install + +Link `bin/` onto `PATH`: `ln -s ~/.claude/bin/loop-claude ~/.local/bin/loop-claude`. + ## Tracking a new file `.gitignore` is an allowlist: everything is ignored, and a file is tracked only by being named. Add it as a negation, with its parent directories un-ignored too, then confirm with `git check-ignore -v `: diff --git a/bin/loop-claude b/bin/loop-claude new file mode 100755 index 00000000..d30932b7 --- /dev/null +++ b/bin/loop-claude @@ -0,0 +1,312 @@ +#!/usr/bin/env python3 +import glob +import json +import os +import subprocess +import sys +import time +import uuid + +ARCHIVE = os.path.expanduser(os.environ.get("AUTO_MODE_TRANSCRIPTS", "~/.claude/auto-mode-transcripts")) +JUDGE_MODEL = os.environ.get("JUDGE_MODEL", "claude-opus-5-5") +SLOT_NAMESPACE = uuid.UUID("64fb586b-d926-4bb3-a44c-c903e86d3eec") +SOURCE = open(__file__, encoding="utf-8").read() +STATE = "LOOP_CLAUDE_STATE" +WORKER_MODEL = os.environ.get("WORKER_MODEL", "claude-opus-5-5") + +JUDGE_SCHEMA = { + "properties": { + "ask": {"type": "boolean"}, + "evidence": {"description": "A verbatim quote from the transcript of the line that raises the question. Empty when ask is false.", "type": "string"}, + "finished": {"description": "True when the chunk is complete: merged, or nothing remains that the agent could do on its own.", "type": "boolean"}, + "question": {"description": "The single question to put to the human. Empty when ask is false.", "type": "string"}, + }, + "required": ["ask", "evidence", "finished", "question"], + "type": "object", +} + + +def claude(args): + proc = subprocess.run(["claude", *args], capture_output=True, text=True) + if proc.returncode != 0: + sys.exit(proc.stderr.strip() or "claude failed") + return json.loads(proc.stdout) + + +def work(args): + proc = subprocess.Popen(["claude", *args], stdout=subprocess.PIPE, text=True) + done = {} + for line in proc.stdout: + try: + event = json.loads(line) + except ValueError: + continue + if event.get("type") == "result": + done = event + elif event.get("type") == "assistant": + for part in event["message"]["content"]: + if part["type"] == "text" and part["text"].strip(): + print(part["text"], flush=True) + elif part["type"] == "tool_use": + print(f"· {part['name']} {json.dumps(part['input'])[:160]}", flush=True) + if proc.wait() != 0 or not done: + sys.exit("claude failed") + return done + + +def sections(): + try: + lines = open("README.md", encoding="utf-8").read().splitlines() + except OSError: + return {} + found, current = {}, None + for line in lines: + if line.startswith("## "): + current = line.strip()[3:] + found[current] = [] + elif current and line.strip(): + found[current].append(line) + return {name: "\n".join(body) for name, body in found.items() if body} + + +def project_path(): + root = os.path.expanduser("~/code") + cwd = os.getcwd() + if cwd == root: + return "code" + if cwd.startswith(f"{root}/"): + return os.path.relpath(cwd, root) + return cwd.lstrip("/") + + +def session_name(): + root = os.path.expanduser("~/code") + cwd = os.getcwd() + if cwd == root: + return "A ~/code auto-mode" + if cwd.startswith(f"{root}/"): + return f"A ~/code/{os.path.relpath(cwd, root)} auto-mode" + return f"A {cwd} auto-mode" + + +def slot_file(session_id): + hit = glob.glob(os.path.expanduser(f"~/.claude/projects/*/{session_id}.jsonl")) + return hit[0] if hit else "" + + +def entries(path): + if not path: + return + for raw in open(path, encoding="utf-8"): + try: + entry = json.loads(raw) + except ValueError: + continue + if isinstance(entry, dict): + yield entry + + +def clear_slot(name, slot): + path = slot_file(slot) + if not path: + return True + for entry in entries(path): + if "agentName" in entry: + if entry["agentName"] != name: + return False + archive(path, "Archived when a later run cleared the slot.") + os.remove(path) + return True + return False + + +def typed(path): + spoken = 0 + for entry in entries(path): + if entry.get("type") != "user": + continue + content = entry.get("message", {}).get("content") + if isinstance(content, str): + spoken += 1 + elif isinstance(content, list) and not any(part.get("type") == "tool_result" for part in content if isinstance(part, dict)): + spoken += 1 + return spoken + + +def render(path): + said = [] + for entry in entries(path): + if entry.get("type") != "assistant": + continue + for part in entry.get("message", {}).get("content", []): + if not isinstance(part, dict): + continue + if part.get("type") == "text" and part.get("text", "").strip(): + said.append(part["text"]) + elif part.get("type") == "tool_use": + said.append(f"[tool {part.get('name')}] {json.dumps(part.get('input'))[:400]}") + return "\n\n".join(said) + + +def archive(path, note): + if not path: + return "" + folder = os.path.join(ARCHIVE, project_path()) + try: + stamp = time.strftime("%Y-%m-%dT%H-%M-%S", time.localtime(os.path.getmtime(path))) + os.makedirs(folder, exist_ok=True) + dest = os.path.join(folder, f"{stamp}.md") + if os.path.exists(dest): + return dest + open(dest, "w", encoding="utf-8").write(f"# {stamp} {project_path()}\n\n{note}\n\n{render(path)}\n") + except OSError as failure: + print(f"could not archive the transcript: {failure}", file=sys.stderr) + return "" + return dest + + +def checkouts(): + found = [os.getcwd()] + listing = subprocess.run(["git", "worktree", "list", "--porcelain"], capture_output=True, 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: + data = json.load(open(config, encoding="utf-8")) + except (OSError, ValueError): + return [] + projects = data.setdefault("projects", {}) + granted = [path for path in paths if not projects.setdefault(path, {}).get("hasTrustDialogAccepted")] + if not granted: + return [] + for path in granted: + projects[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 record trust: {failure}", file=sys.stderr) + return [] + return granted + + +def interrupt(task, premises, work): + verdict = claude([ + "-p", + f"README.md, verbatim:\n{premises}\n\n" + f"The task an agent was given:\n{task}\n\n" + f"What the agent then did and said:\n{work[:40000]}\n\n" + "Decide whether the human must now be interrupted. ask=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 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" + "ask=false otherwise. A sensible preference is not a derivation. 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: judge only what is still open, " + "never a question they already answered there.\n" + "The question must be one the agent itself raised. Never construct a question from facts the agent " + "stated. When ask=true, quote the agent's own wording where it already framed the question.\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.", + "--json-schema", json.dumps(JUDGE_SCHEMA), + "--model", JUDGE_MODEL, + "--no-session-persistence", + "--output-format", "json", + "--permission-mode", "bypassPermissions", + "--tools", "", + ]) + verdict = verdict["structured_output"] + if verdict["ask"] and verdict["evidence"] not in work: + print("judge quoted nothing in the transcript - treating as done", file=sys.stderr) + verdict["ask"] = False + return verdict + + +def reload(state): + try: + source = open(__file__, encoding="utf-8").read() + compile(source, __file__, "exec") + except (OSError, SyntaxError) as failure: + print(f"keeping the running script: {failure}", file=sys.stderr) + return + if source == SOURCE: + return + os.environ[STATE] = json.dumps(state) + os.execv(sys.executable, [sys.executable, __file__, *sys.argv[1:]]) + + +task = " ".join(sys.argv[1:]) +if not task: + sys.exit("usage: loop-claude ") + +state = json.loads(os.environ.pop(STATE, "{}")) +round_number = state.get("round", 0) +resume = state.get("resume", "") +while True: + reload({"round": round_number, "resume": resume}) + round_number += 1 + found = sections() + if not found.get("Goals") or not found.get("Audience"): + sys.exit("README.md needs ## Goals and ## Audience - the gate blocks.") + premises = f"## Goals\n{found['Goals']}\n\n## Audience\n{found['Audience']}" + + name = session_name() + print(f"\n=== round {round_number} ===", flush=True) + if resume: + start = ["-p", "Continue the task; the previous run stopped before it was finished.", "--resume", resume] + else: + slot = uuid.uuid5(SLOT_NAMESPACE, name) + sticky = clear_slot(name, slot) + if not sticky: + print(f"session {slot} is not this tool's - running without the slot", 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(slot)] if sticky else []), + ] + worked = work([ + *start, + "--output-format", "stream-json", + "--permission-mode", "bypassPermissions", + "--verbose", + *(["--model", WORKER_MODEL] if WORKER_MODEL else []), + ]) + + path = slot_file(worked["session_id"]) + verdict = interrupt(task, premises, render(path) or worked["result"]) + + while True: + kept = archive(path, f"Task: {task}\n\nVerdict: {'needs input' if verdict['ask'] else 'finished' if verdict['finished'] else 'continues'}\n\n{verdict['question']}".rstrip()) + if kept: + print(f"transcript: {kept}", file=sys.stderr) + if not verdict["ask"]: + break + + print(f"\n{verdict['question']}", file=sys.stderr) + if not sys.stdin.isatty(): + sys.exit(2) + + granted = trust(checkouts()) + if granted: + print("trusted for the handoff: " + ", ".join(granted), file=sys.stderr) + + answered = typed(path) + subprocess.run(["claude", "--permission-mode", "bypassPermissions", "--resume", worked["session_id"]]) + path = slot_file(worked["session_id"]) + if typed(path) <= answered: + sys.exit(2) + verdict = interrupt(task, premises, render(path)) + + resume = "" if verdict["finished"] else worked["session_id"] diff --git a/skills/larv-review/SKILL.md b/skills/larv-review/SKILL.md index ca995659..f35cbfca 100644 --- a/skills/larv-review/SKILL.md +++ b/skills/larv-review/SKILL.md @@ -5,7 +5,7 @@ description: One-stop shipping pipeline for a work chunk - branch, commit, push, # larv-review — ship the chunk, review until clean, gate green, merge -You orchestrate, fix, and ship; the reviewer agents only report. Run every reviewer synchronously (`run_in_background: false`) — each step depends on the previous result. Architecture strictly before security, security before stability: line-level polish on code the architect wants restructured, or on a call the security pass will rewrite, is wasted work. The full order is architecture → security → stability → product-owner when escalated → a closing stability round over what that changed. +You orchestrate, fix, and ship; the reviewer agents only report. Run every reviewer synchronously (`run_in_background: false`) — each step depends on the previous result. Watch CI in the foreground too: a headless run exits when the turn ends, and a background watcher or a scheduled wakeup dies with it. A reviewer's report is input to the next step; the turn runs on until §12. Architecture strictly before security, security before stability: line-level polish on code the architect wants restructured, or on a call the security pass will rewrite, is wasted work. The full order is architecture → security → stability → product-owner when escalated → a closing stability round over what that changed. **Forge-neutral.** Five PR operations recur below: read a PR's diff, open a draft PR, read check status, mark ready, merge. Resolve the tooling from the remote per the global git rules (`gh` on GitHub, `tea` on Gitea); on any other forge, achieve the same intents through its CLI or API — discover how rather than assuming. A forge without a native draft state gets the closest equivalent (a `WIP:`/`Draft:` title prefix); note any approximation in the summary. -- 2.52.0 From 839804f47e14623d19b6ab844398a2e1049f06ae Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 24 Sep 2026 20:21:06 +0200 Subject: [PATCH 2/9] Derive the round's state from the session file, name the steps, and test the pure core --- .gitignore | 10 +- AGENTS.md | 8 + README.md | 16 +- bin/claude-instances | 74 +++++++++ bin/loop-claude | 356 +++++++++++++++++++++------------------- bin/test_loop_claude.py | 76 +++++++++ docs/decisions.md | 17 ++ todo.md | 10 ++ 8 files changed, 390 insertions(+), 177 deletions(-) create mode 100644 AGENTS.md create mode 100755 bin/claude-instances create mode 100644 bin/test_loop_claude.py create mode 100644 docs/decisions.md create mode 100644 todo.md diff --git a/.gitignore b/.gitignore index 9ea767a7..63f77ba8 100644 --- a/.gitignore +++ b/.gitignore @@ -5,10 +5,12 @@ * !.gitignore +!AGENTS.md !CLAUDE.md !README.md !settings.json !statusline.sh +!todo.md !agent-shared/ !agent-shared/** @@ -16,10 +18,10 @@ !agents/*.md !bin/ !bin/* +!docs/ +!docs/*.md !principles/ !principles/*.md !skills/ -!skills/comprehension-panel/ -!skills/comprehension-panel/** -!skills/larv-review/ -!skills/larv-review/** +!skills/*/ +!skills/*/** diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 00000000..1fd3b832 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,8 @@ +# Working here + +Decisions live in `docs/decisions.md`: + +- loop-claude: a judge decides interrupts, not the worker's self-report +- loop-claude: one session per project, at a fixed id +- loop-claude: the trust file is rewritten before a handoff +- bin/: host python, no container diff --git a/README.md b/README.md index c2d13d3d..aa85fa67 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,13 @@ # Claude Code configuration -My personal `~/.claude`, version controlled. Instructions, agents, skills, principles and settings. +My personal `~/.claude`, version controlled. Instructions, agents, skills, principles, settings and the tools in `bin/`. ## Goals 1. Share this configuration between my computers. 2. Keep it backed up. 3. Leak nothing — no credentials, no session transcripts, no memory. +4. Run work chunks unattended, interrupting me only when a decision is mine. ## Audience @@ -14,13 +15,20 @@ Me, on my own machines. Private repo, nobody else depends on it. ## Install -Link `bin/` onto `PATH`: `ln -s ~/.claude/bin/loop-claude ~/.local/bin/loop-claude`. +Link the tools onto `PATH`: `ln -s ~/.claude/bin/loop-claude ~/.local/bin/loop-claude`, and the same for `claude-instances`. + +## Tools + +- `loop-claude ` runs a project's next chunk round after round; `loop-claude --help` states its contract. +- `claude-instances` redraws a table of the running claude sessions by project. + +Test: `python3 -m unittest bin/test_loop_claude.py` ## Tracking a new file `.gitignore` is an allowlist: everything is ignored, and a file is tracked only by being named. Add it as a negation, with its parent directories un-ignored too, then confirm with `git check-ignore -v `: ``` -!commands/ -!commands/*.md +!docs/ +!docs/*.md ``` diff --git a/bin/claude-instances b/bin/claude-instances new file mode 100755 index 00000000..f8835234 --- /dev/null +++ b/bin/claude-instances @@ -0,0 +1,74 @@ +#!/usr/bin/env python3 +import os +import sys +import time + +CODE = os.path.expanduser("~/code") +HOME = os.path.expanduser("~") +INTERVAL = float(os.environ.get("INTERVAL", "2")) +PLUMBING = ("--bg-pty-host", "--bg-spare", "--json-path", "--spawned-by") + + +def processes(): + found = {} + for pid in os.listdir("/proc"): + if not pid.isdigit(): + continue + try: + argv = open(f"/proc/{pid}/cmdline", "rb").read().decode("utf-8", "replace").split("\0")[:-1] + cwd = os.readlink(f"/proc/{pid}/cwd") + ppid = next(int(line.split()[1]) for line in open(f"/proc/{pid}/status") if line.startswith("PPid:")) + except (OSError, StopIteration, ValueError): + continue + if argv: + found[int(pid)] = (argv, ppid, cwd.removesuffix(" (deleted)")) + return found + + +def shown(cwd): + if cwd == CODE: + return "code" + if cwd.startswith(f"{CODE}/"): + return os.path.relpath(cwd, CODE) + return cwd.replace(HOME, "~", 1) + + +def rows(found): + wrappers = set() + for pid, (argv, ppid, _) in found.items(): + if not os.path.basename(argv[0]).startswith("claude") or any(flag in argv for flag in PLUMBING): + continue + parent = found.get(ppid) + if parent and os.path.basename(parent[0][0]).startswith("python"): + wrappers.add(ppid) + listed, claimed = [], set() + for pid in wrappers: + status = "Auto" + for child, (argv, ppid, _) in found.items(): + if ppid == pid and os.path.basename(argv[0]).startswith("claude"): + claimed.add(child) + if "--resume" in argv: + status = "Inter" + listed.append((status, shown(found[pid][2]))) + for pid, (argv, _, cwd) in found.items(): + if pid in claimed or pid in wrappers: + continue + if not os.path.basename(argv[0]).startswith("claude"): + continue + if any(flag in argv for flag in PLUMBING): + continue + listed.append(("Other", shown(cwd))) + return sorted(listed, key=lambda row: (row[1], row[0])) + + +try: + while True: + listed = rows(processes()) + width = max([len(path) for _, path in listed] + [4]) + out = [f"{'STATUS':<6} {'PATH':<{width}}", f"{'-' * 6} {'-' * width}"] + out += [f"{status:<6} {path:<{width}}" for status, path in listed] or ["(none running)"] + sys.stdout.write("\x1b[H\x1b[2J" + "\n".join(out) + "\n") + sys.stdout.flush() + time.sleep(INTERVAL) +except KeyboardInterrupt: + pass diff --git a/bin/loop-claude b/bin/loop-claude index d30932b7..9be3f0c2 100755 --- a/bin/loop-claude +++ b/bin/loop-claude @@ -1,4 +1,22 @@ #!/usr/bin/env python3 +"""Run a task as headless claude rounds; a judge stops the loop only when a decision is the human's. + +usage: loop-claude + +Run it in a project checkout whose README.md has ## Goals and ## Audience. Each round a worker runs +the task; a judge then reads the transcript against the README. A question only the human can answer +opens `claude --resume` on the terminal. An unfinished chunk resumes the same session next round; a +finished one starts a fresh session. Rounds continue until Ctrl-C. + +Exit 1: the README gate blocks, or claude fails three rounds running. Exit 2: the human is needed and +no terminal is attached, or the handoff ended without them typing anything. + +Each project has one session, "A ~/code/ auto-mode", at an id derived from that name; it is +resumed while present and deleted when the chunk finishes. Its transcript is archived under +$AUTO_MODE_TRANSCRIPTS (default ~/.claude/auto-mode-transcripts//) whenever the human is asked +and when the chunk finishes. JUDGE_MODEL and WORKER_MODEL override the models. A change to this +file takes effect at the next round boundary. +""" import glob import json import os @@ -9,11 +27,32 @@ import uuid ARCHIVE = os.path.expanduser(os.environ.get("AUTO_MODE_TRANSCRIPTS", "~/.claude/auto-mode-transcripts")) JUDGE_MODEL = os.environ.get("JUDGE_MODEL", "claude-opus-5-5") +ROUND = "LOOP_CLAUDE_ROUND" SLOT_NAMESPACE = uuid.UUID("64fb586b-d926-4bb3-a44c-c903e86d3eec") SOURCE = open(__file__, encoding="utf-8").read() -STATE = "LOOP_CLAUDE_STATE" WORKER_MODEL = os.environ.get("WORKER_MODEL", "claude-opus-5-5") +JUDGE_RULES = ( + "Decide whether the human must now be interrupted. ask=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 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" + "ask=false otherwise. A sensible preference is not a derivation. 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: judge only what is still open, " + "never a question they already answered there.\n" + "The question must be one the agent itself raised. Never construct a question from facts the agent " + "stated. When ask=true, quote the agent's own wording where it already framed the question.\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": { "ask": {"type": "boolean"}, @@ -26,41 +65,9 @@ JUDGE_SCHEMA = { } -def claude(args): - proc = subprocess.run(["claude", *args], capture_output=True, text=True) - if proc.returncode != 0: - sys.exit(proc.stderr.strip() or "claude failed") - return json.loads(proc.stdout) - - -def work(args): - proc = subprocess.Popen(["claude", *args], stdout=subprocess.PIPE, text=True) - done = {} - for line in proc.stdout: - try: - event = json.loads(line) - except ValueError: - continue - if event.get("type") == "result": - done = event - elif event.get("type") == "assistant": - for part in event["message"]["content"]: - if part["type"] == "text" and part["text"].strip(): - print(part["text"], flush=True) - elif part["type"] == "tool_use": - print(f"· {part['name']} {json.dumps(part['input'])[:160]}", flush=True) - if proc.wait() != 0 or not done: - sys.exit("claude failed") - return done - - -def sections(): - try: - lines = open("README.md", encoding="utf-8").read().splitlines() - except OSError: - return {} +def sections(text): found, current = {}, None - for line in lines: + for line in text.splitlines(): if line.startswith("## "): current = line.strip()[3:] found[current] = [] @@ -69,6 +76,16 @@ def sections(): return {name: "\n".join(body) for name, body in found.items() if body} +def premises(): + try: + found = sections(open("README.md", encoding="utf-8").read()) + except OSError: + found = {} + if not found.get("Goals") or not found.get("Audience"): + sys.exit("README.md needs ## Goals and ## Audience - the gate blocks.") + return f"## Goals\n{found['Goals']}\n\n## Audience\n{found['Audience']}" + + def project_path(): root = os.path.expanduser("~/code") cwd = os.getcwd() @@ -89,14 +106,12 @@ def session_name(): return f"A {cwd} auto-mode" -def slot_file(session_id): - hit = glob.glob(os.path.expanduser(f"~/.claude/projects/*/{session_id}.jsonl")) +def session_file(slot): + hit = glob.glob(os.path.expanduser(f"~/.claude/projects/*/{slot}.jsonl")) return hit[0] if hit else "" def entries(path): - if not path: - return for raw in open(path, encoding="utf-8"): try: entry = json.loads(raw) @@ -106,36 +121,9 @@ def entries(path): yield entry -def clear_slot(name, slot): - path = slot_file(slot) - if not path: - return True - for entry in entries(path): - if "agentName" in entry: - if entry["agentName"] != name: - return False - archive(path, "Archived when a later run cleared the slot.") - os.remove(path) - return True - return False - - -def typed(path): - spoken = 0 - for entry in entries(path): - if entry.get("type") != "user": - continue - content = entry.get("message", {}).get("content") - if isinstance(content, str): - spoken += 1 - elif isinstance(content, list) and not any(part.get("type") == "tool_result" for part in content if isinstance(part, dict)): - spoken += 1 - return spoken - - -def render(path): +def render(entries): said = [] - for entry in entries(path): + for entry in entries: if entry.get("type") != "assistant": continue for part in entry.get("message", {}).get("content", []): @@ -148,21 +136,30 @@ def render(path): return "\n\n".join(said) +def human_turns(entries): + spoken = 0 + for entry in entries: + if entry.get("type") != "user": + continue + content = entry.get("message", {}).get("content") + if isinstance(content, str): + spoken += 1 + elif isinstance(content, list) and not any(part.get("type") == "tool_result" for part in content if isinstance(part, dict)): + spoken += 1 + return spoken + + def archive(path, note): - if not path: - return "" folder = os.path.join(ARCHIVE, project_path()) try: - stamp = time.strftime("%Y-%m-%dT%H-%M-%S", time.localtime(os.path.getmtime(path))) + stamp = time.strftime("%Y-%m-%dT%H-%M-%SZ", time.gmtime(os.path.getmtime(path))) os.makedirs(folder, exist_ok=True) dest = os.path.join(folder, f"{stamp}.md") - if os.path.exists(dest): - return dest - open(dest, "w", encoding="utf-8").write(f"# {stamp} {project_path()}\n\n{note}\n\n{render(path)}\n") + if not os.path.exists(dest): + open(dest, "w", encoding="utf-8").write(f"# {stamp} {project_path()}\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) - return "" - return dest def checkouts(): @@ -174,15 +171,16 @@ def checkouts(): def trust(paths): + # No CLI flag skips the trust dialog, and the interactive resume would stall on it in every worktree the round created. config = os.path.expanduser("~/.claude.json") try: data = json.load(open(config, encoding="utf-8")) except (OSError, ValueError): - return [] + return projects = data.setdefault("projects", {}) granted = [path for path in paths if not projects.setdefault(path, {}).get("hasTrustDialogAccepted")] if not granted: - return [] + return for path in granted: projects[path]["hasTrustDialogAccepted"] = True staged = f"{config}.loop-claude" @@ -192,49 +190,107 @@ def trust(paths): os.replace(staged, config) except OSError as failure: print(f"could not record trust: {failure}", file=sys.stderr) - return [] - return granted + return + print("trusted for the handoff: " + ", ".join(granted), file=sys.stderr) -def interrupt(task, premises, work): - verdict = claude([ - "-p", +def worker_args(task, name, slot, resuming): + if resuming: + start = ["-p", "Continue the task; the previous run stopped before it was finished.", "--resume", str(slot)] + 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(slot)] + return [ + *start, + "--output-format", "stream-json", + "--permission-mode", "bypassPermissions", + "--verbose", + *(["--model", WORKER_MODEL] if WORKER_MODEL else []), + ] + + +def run_worker(args): + proc = subprocess.Popen(["claude", *args], stdout=subprocess.PIPE, text=True) + done = {} + for line in proc.stdout: + try: + event = json.loads(line) + except ValueError: + continue + if event.get("type") == "result": + done = event + elif event.get("type") == "assistant": + for part in event["message"]["content"]: + if part["type"] == "text" and part["text"].strip(): + print(part["text"], flush=True) + elif part["type"] == "tool_use": + print(f"· {part['name']} {json.dumps(part['input'])[:160]}", flush=True) + return done if proc.wait() == 0 else {} + + +def judge_prompt(task, premises, transcript): + return ( f"README.md, verbatim:\n{premises}\n\n" f"The task an agent was given:\n{task}\n\n" - f"What the agent then did and said:\n{work[:40000]}\n\n" - "Decide whether the human must now be interrupted. ask=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 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" - "ask=false otherwise. A sensible preference is not a derivation. 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: judge only what is still open, " - "never a question they already answered there.\n" - "The question must be one the agent itself raised. Never construct a question from facts the agent " - "stated. When ask=true, quote the agent's own wording where it already framed the question.\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.", + f"What the agent then did and said, latest last:\n{transcript[-40000:]}\n\n" + f"{JUDGE_RULES}" + ) + + +def grounded(verdict, transcript): + return not verdict["ask"] or verdict["evidence"] in transcript + + +def judge(task, premises, transcript): + args = [ + "-p", judge_prompt(task, premises, transcript), "--json-schema", json.dumps(JUDGE_SCHEMA), "--model", JUDGE_MODEL, "--no-session-persistence", "--output-format", "json", "--permission-mode", "bypassPermissions", "--tools", "", - ]) - verdict = verdict["structured_output"] - if verdict["ask"] and verdict["evidence"] not in work: - print("judge quoted nothing in the transcript - treating as done", file=sys.stderr) - verdict["ask"] = False + ] + for attempt in range(2): + proc = subprocess.run(["claude", *args], capture_output=True, text=True) + if proc.returncode != 0: + sys.exit(proc.stderr.strip() or "the judge failed") + verdict = json.loads(proc.stdout)["structured_output"] + if grounded(verdict, transcript): + return verdict + print("the judge quoted nothing in the transcript twice - interrupting anyway", file=sys.stderr) return verdict -def reload(state): +def handoff(slot, path, question): + print(f"\n{question}", file=sys.stderr) + if not sys.stdin.isatty(): + return False + trust(checkouts()) + before = human_turns(entries(path)) + subprocess.run(["claude", "--permission-mode", "bypassPermissions", "--resume", str(slot)]) + return human_turns(entries(path)) > before + + +def run_round(task, given, name, slot): + worked = run_worker(worker_args(task, name, slot, resuming=bool(session_file(slot)))) + if not worked: + return False + path = session_file(slot) + if not path: + sys.exit(f"claude left no transcript for session {slot}") + verdict = judge(task, given, render(entries(path))) + while verdict["ask"]: + archive(path, f"Task: {task}\n\nVerdict: needs input\n\n{verdict['question']}") + if not handoff(slot, path, verdict["question"]): + sys.exit(2) + verdict = judge(task, given, render(entries(path))) + if verdict["finished"]: + archive(path, f"Task: {task}\n\nVerdict: finished") + os.remove(path) + return True + + +def reload_if_edited(round_number): try: source = open(__file__, encoding="utf-8").read() compile(source, __file__, "exec") @@ -243,70 +299,32 @@ def reload(state): return if source == SOURCE: return - os.environ[STATE] = json.dumps(state) + os.environ[ROUND] = str(round_number) os.execv(sys.executable, [sys.executable, __file__, *sys.argv[1:]]) -task = " ".join(sys.argv[1:]) -if not task: - sys.exit("usage: loop-claude ") - -state = json.loads(os.environ.pop(STATE, "{}")) -round_number = state.get("round", 0) -resume = state.get("resume", "") -while True: - reload({"round": round_number, "resume": resume}) - round_number += 1 - found = sections() - if not found.get("Goals") or not found.get("Audience"): - sys.exit("README.md needs ## Goals and ## Audience - the gate blocks.") - premises = f"## Goals\n{found['Goals']}\n\n## Audience\n{found['Audience']}" - - name = session_name() - print(f"\n=== round {round_number} ===", flush=True) - if resume: - start = ["-p", "Continue the task; the previous run stopped before it was finished.", "--resume", resume] - else: - slot = uuid.uuid5(SLOT_NAMESPACE, name) - sticky = clear_slot(name, slot) - if not sticky: - print(f"session {slot} is not this tool's - running without the slot", 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(slot)] if sticky else []), - ] - worked = work([ - *start, - "--output-format", "stream-json", - "--permission-mode", "bypassPermissions", - "--verbose", - *(["--model", WORKER_MODEL] if WORKER_MODEL else []), - ]) - - path = slot_file(worked["session_id"]) - verdict = interrupt(task, premises, render(path) or worked["result"]) - +def main(): + task = " ".join(sys.argv[1:]) + if task in ("", "-h", "--help"): + print(__doc__.strip()) + sys.exit(0 if task else 1) + round_number = int(os.environ.pop(ROUND, 0)) + failures = 0 while True: - kept = archive(path, f"Task: {task}\n\nVerdict: {'needs input' if verdict['ask'] else 'finished' if verdict['finished'] else 'continues'}\n\n{verdict['question']}".rstrip()) - if kept: - print(f"transcript: {kept}", file=sys.stderr) - if not verdict["ask"]: - break + reload_if_edited(round_number) + round_number += 1 + given = premises() + name = session_name() + print(f"\n=== round {round_number} ===", flush=True) + if run_round(task, given, name, uuid.uuid5(SLOT_NAMESPACE, name)): + failures = 0 + continue + failures += 1 + if failures == 3: + sys.exit("claude failed three rounds running") + print("claude failed - retrying in a minute", file=sys.stderr) + time.sleep(60) - print(f"\n{verdict['question']}", file=sys.stderr) - if not sys.stdin.isatty(): - sys.exit(2) - granted = trust(checkouts()) - if granted: - print("trusted for the handoff: " + ", ".join(granted), file=sys.stderr) - - answered = typed(path) - subprocess.run(["claude", "--permission-mode", "bypassPermissions", "--resume", worked["session_id"]]) - path = slot_file(worked["session_id"]) - if typed(path) <= answered: - sys.exit(2) - verdict = interrupt(task, premises, render(path)) - - resume = "" if verdict["finished"] else worked["session_id"] +if __name__ == "__main__": + main() diff --git a/bin/test_loop_claude.py b/bin/test_loop_claude.py new file mode 100644 index 00000000..c7d756d3 --- /dev/null +++ b/bin/test_loop_claude.py @@ -0,0 +1,76 @@ +import importlib.machinery +import importlib.util +import pathlib +import unittest + +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) + + +def assistant(*parts): + return {"type": "assistant", "message": {"content": list(parts)}} + + +def human(content): + return {"type": "user", "message": {"content": content}} + + +class Sections(unittest.TestCase): + def test_keeps_only_headed_sections_with_a_body(self): + text = "# Title\n\nintro\n\n## Goals\n\n1. one\n2. two\n\n## Empty\n\n## Audience\nme\n" + self.assertEqual(loop.sections(text), {"Goals": "1. one\n2. two", "Audience": "me"}) + + +class Render(unittest.TestCase): + def test_joins_assistant_text_and_tool_calls_and_skips_the_rest(self): + said = loop.render([ + human("do it"), + assistant({"type": "text", "text": "Starting."}, {"type": "tool_use", "name": "Bash", "input": {"command": "ls"}}), + assistant({"type": "text", "text": " "}), + ]) + self.assertEqual(said, 'Starting.\n\n[tool Bash] {"command": "ls"}') + + +class HumanTurns(unittest.TestCase): + def test_counts_typed_turns_and_not_tool_results(self): + self.assertEqual(loop.human_turns([ + human("typed"), + human([{"type": "text", "text": "typed as a block"}]), + human([{"type": "tool_result", "content": "not typed"}]), + assistant({"type": "text", "text": "said"}), + ]), 2) + + +class WorkerArgs(unittest.TestCase): + def test_a_fresh_round_names_the_session_and_asks_to_continue_open_work(self): + args = loop.worker_args("the task", "A name", "slot-id", 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_round_reuses_the_session(self): + args = loop.worker_args("paint the fence", "A name", "slot-id", resuming=True) + self.assertEqual(args[args.index("--resume") + 1], "slot-id") + self.assertNotIn("--name", args) + self.assertNotIn("paint the fence", args[1]) + + +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") + self.assertIn("LATE", prompt) + self.assertLess(prompt.count("early"), 20000) + self.assertTrue(prompt.endswith(loop.JUDGE_RULES)) + + +class Grounded(unittest.TestCase): + def test_an_interrupt_must_quote_the_transcript(self): + self.assertTrue(loop.grounded({"ask": False, "evidence": ""}, "anything")) + self.assertTrue(loop.grounded({"ask": True, "evidence": "Needs you: x"}, "so.\n\nNeeds you: x\n")) + self.assertFalse(loop.grounded({"ask": True, "evidence": "invented"}, "the transcript")) + + +if __name__ == "__main__": + unittest.main() diff --git a/docs/decisions.md b/docs/decisions.md new file mode 100644 index 00000000..af97a5ae --- /dev/null +++ b/docs/decisions.md @@ -0,0 +1,17 @@ +# Decisions + +## loop-claude: a judge decides interrupts, not the worker's self-report + +2026-09-21, lilleman. Serves goal 4. Asked to name the goal behind each choice, the worker cites a real goal for a choice that goal does not settle, and under-reports its own decisions; the judge's bar is whether the README discriminates between the alternatives. Valid while the worker's self-report stays unreliable. + +## loop-claude: one session per project, at a fixed id + +2026-09-21, lilleman. Serves goal 4. The id is uuid5 of the session name under the script's own namespace, so the session picker holds one entry per project and any transcript under that id is the script's own: resumed while present, deleted when the chunk finishes. Valid while the picker lists sessions by id. + +## loop-claude: the trust file is rewritten before a handoff + +2026-09-21, lilleman; the lost-write risk accepted 2026-09-24 by larv-review. Serves goal 4. No CLI flag skips the trust dialog, so `~/.claude.json` gets `hasTrustDialogAccepted` for every checkout before `claude --resume`. A write by another claude inside that read-modify-write window is lost. Valid while no flag skips the dialog. + +## bin/: host python, no container + +2026-09-24, larv-review. Serves goals 1 and 4. The tools drive the host's claude CLI and read the host's session files, which a container cannot see; the tests run the same way. Valid while claude runs on the host. diff --git a/todo.md b/todo.md new file mode 100644 index 00000000..5b52b61f --- /dev/null +++ b/todo.md @@ -0,0 +1,10 @@ +# todo + +## 0.1.0 + +- Delete `agent-shared/`: no agent carries its markers, and its memory system contradicts the agents' own no-private-memory rule. +- Keep the comment and prose bar in `CLAUDE.md` only, and point `agents/stability-reviewer.md` §10 and `skills/larv-review/SKILL.md` §7 at it. +- Replace `/home/lilleman/…` in `agents/*.md` and `settings.json` with a path that holds on another machine. +- Give the `CLAUDE.md` sections `skills/larv-review/SKILL.md` cites headings it can name. +- Give the README gate, the architecture gate, the merge gate and the stability reviewer four different words; today all four are "gate". +- Raise the comprehension panel above the 7.0 floor: the 2026-09-24 four-seat run scored 5 overall, capped at 4 by Locality and Self-sufficiency, on the items above. -- 2.52.0 From 0bfbfa53c1c4acad6fd4cd00a675771ce7819e1e Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 24 Sep 2026 20:23:53 +0200 Subject: [PATCH 3/9] Archive transcripts as private as their session files --- bin/loop-claude | 6 ++++-- bin/test_loop_claude.py | 17 +++++++++++++++++ 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/bin/loop-claude b/bin/loop-claude index 9be3f0c2..262511fd 100755 --- a/bin/loop-claude +++ b/bin/loop-claude @@ -153,10 +153,12 @@ def archive(path, note): folder = os.path.join(ARCHIVE, project_path()) try: stamp = time.strftime("%Y-%m-%dT%H-%M-%SZ", time.gmtime(os.path.getmtime(path))) - os.makedirs(folder, exist_ok=True) + os.makedirs(folder, mode=0o700, exist_ok=True) + os.chmod(ARCHIVE, 0o700) dest = os.path.join(folder, f"{stamp}.md") if not os.path.exists(dest): - open(dest, "w", encoding="utf-8").write(f"# {stamp} {project_path()}\n\n{note}\n\n{render(entries(path))}\n") + 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_path()}\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) diff --git a/bin/test_loop_claude.py b/bin/test_loop_claude.py index c7d756d3..89b32abc 100644 --- a/bin/test_loop_claude.py +++ b/bin/test_loop_claude.py @@ -1,6 +1,10 @@ import importlib.machinery import importlib.util +import json +import os import pathlib +import stat +import tempfile import unittest LOADER = importlib.machinery.SourceFileLoader("loop_claude", str(pathlib.Path(__file__).with_name("loop-claude"))) @@ -65,6 +69,19 @@ class JudgePrompt(unittest.TestCase): self.assertTrue(prompt.endswith(loop.JUDGE_RULES)) +class Archive(unittest.TestCase): + def test_keeps_the_copy_as_private_as_the_transcript(self): + with tempfile.TemporaryDirectory() as root: + transcript = os.path.join(root, "session.jsonl") + open(transcript, "w").write(json.dumps(assistant({"type": "text", "text": "said"})) + "\n") + loop.ARCHIVE = os.path.join(root, "archive") + loop.archive(transcript, "note") + [copy] = [os.path.join(folder, name) for folder, _, names in os.walk(loop.ARCHIVE) for name in names] + self.assertEqual(stat.S_IMODE(os.stat(copy).st_mode), 0o600) + self.assertEqual(stat.S_IMODE(os.stat(os.path.dirname(copy)).st_mode), 0o700) + self.assertIn("said", open(copy).read()) + + class Grounded(unittest.TestCase): def test_an_interrupt_must_quote_the_transcript(self): self.assertTrue(loop.grounded({"ask": False, "evidence": ""}, "anything")) -- 2.52.0 From b5a7a116c25fbb4834741d8adb45541172ba5a93 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 24 Sep 2026 20:25:44 +0200 Subject: [PATCH 4/9] End a session with its sibling folder, share the part renderer, and split claude-instances --- bin/claude-instances | 77 ++++++++++++++++++++----------------- bin/loop-claude | 85 +++++++++++++++++++++++------------------ bin/test_loop_claude.py | 18 +++++++++ 3 files changed, 108 insertions(+), 72 deletions(-) diff --git a/bin/claude-instances b/bin/claude-instances index f8835234..6dcb13d3 100755 --- a/bin/claude-instances +++ b/bin/claude-instances @@ -33,42 +33,51 @@ def shown(cwd): return cwd.replace(HOME, "~", 1) -def rows(found): - wrappers = set() - for pid, (argv, ppid, _) in found.items(): - if not os.path.basename(argv[0]).startswith("claude") or any(flag in argv for flag in PLUMBING): - continue +def is_claude(argv): + return os.path.basename(argv[0]).startswith("claude") and not any(flag in argv for flag in PLUMBING) + + +def wrappers(found): + parents = set() + for argv, ppid, _ in found.values(): parent = found.get(ppid) - if parent and os.path.basename(parent[0][0]).startswith("python"): - wrappers.add(ppid) + if is_claude(argv) and parent and os.path.basename(parent[0][0]).startswith("python"): + parents.add(ppid) + return parents + + +def wrapper_row(found, pid): + children = {child for child, (argv, ppid, _) in found.items() if ppid == pid and is_claude(argv)} + status = "Inter" if any("--resume" in found[child][0] for child in children) else "Auto" + return (status, shown(found[pid][2])), children + + +def rows(found): listed, claimed = [], set() - for pid in wrappers: - status = "Auto" - for child, (argv, ppid, _) in found.items(): - if ppid == pid and os.path.basename(argv[0]).startswith("claude"): - claimed.add(child) - if "--resume" in argv: - status = "Inter" - listed.append((status, shown(found[pid][2]))) - for pid, (argv, _, cwd) in found.items(): - if pid in claimed or pid in wrappers: - continue - if not os.path.basename(argv[0]).startswith("claude"): - continue - if any(flag in argv for flag in PLUMBING): - continue - listed.append(("Other", shown(cwd))) + for pid in wrappers(found): + row, children = wrapper_row(found, pid) + listed.append(row) + claimed |= children + listed += [("Other", shown(cwd)) for pid, (argv, _, cwd) in found.items() if pid not in claimed and is_claude(argv)] return sorted(listed, key=lambda row: (row[1], row[0])) -try: - while True: - listed = rows(processes()) - width = max([len(path) for _, path in listed] + [4]) - out = [f"{'STATUS':<6} {'PATH':<{width}}", f"{'-' * 6} {'-' * width}"] - out += [f"{status:<6} {path:<{width}}" for status, path in listed] or ["(none running)"] - sys.stdout.write("\x1b[H\x1b[2J" + "\n".join(out) + "\n") - sys.stdout.flush() - time.sleep(INTERVAL) -except KeyboardInterrupt: - pass +def table(listed): + width = max([len(path) for _, path in listed] + [4]) + out = [f"{'STATUS':<6} {'PATH':<{width}}", f"{'-' * 6} {'-' * width}"] + out += [f"{status:<6} {path:<{width}}" for status, path in listed] or ["(none running)"] + return "\n".join(out) + + +def main(): + try: + while True: + sys.stdout.write("\x1b[H\x1b[2J" + table(rows(processes())) + "\n") + sys.stdout.flush() + time.sleep(INTERVAL) + except KeyboardInterrupt: + pass + + +if __name__ == "__main__": + main() diff --git a/bin/loop-claude b/bin/loop-claude index 262511fd..87799627 100755 --- a/bin/loop-claude +++ b/bin/loop-claude @@ -20,6 +20,7 @@ file takes effect at the next round boundary. import glob import json import os +import shutil import subprocess import sys import time @@ -28,7 +29,7 @@ import uuid ARCHIVE = os.path.expanduser(os.environ.get("AUTO_MODE_TRANSCRIPTS", "~/.claude/auto-mode-transcripts")) JUDGE_MODEL = os.environ.get("JUDGE_MODEL", "claude-opus-5-5") ROUND = "LOOP_CLAUDE_ROUND" -SLOT_NAMESPACE = uuid.UUID("64fb586b-d926-4bb3-a44c-c903e86d3eec") +SESSION_NAMESPACE = uuid.UUID("64fb586b-d926-4bb3-a44c-c903e86d3eec") SOURCE = open(__file__, encoding="utf-8").read() WORKER_MODEL = os.environ.get("WORKER_MODEL", "claude-opus-5-5") @@ -76,7 +77,7 @@ def sections(text): return {name: "\n".join(body) for name, body in found.items() if body} -def premises(): +def gate(): try: found = sections(open("README.md", encoding="utf-8").read()) except OSError: @@ -106,11 +107,16 @@ def session_name(): return f"A {cwd} auto-mode" -def session_file(slot): - hit = glob.glob(os.path.expanduser(f"~/.claude/projects/*/{slot}.jsonl")) +def session_file(session_id): + hit = glob.glob(os.path.expanduser(f"~/.claude/projects/*/{session_id}.jsonl")) return hit[0] if hit else "" +def end_session(path): + os.remove(path) + shutil.rmtree(path.removesuffix(".jsonl"), ignore_errors=True) + + def entries(path): for raw in open(path, encoding="utf-8"): try: @@ -121,19 +127,21 @@ def entries(path): 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): - said = [] + lines = [] for entry in entries: - if entry.get("type") != "assistant": - continue - for part in entry.get("message", {}).get("content", []): - if not isinstance(part, dict): - continue - if part.get("type") == "text" and part.get("text", "").strip(): - said.append(part["text"]) - elif part.get("type") == "tool_use": - said.append(f"[tool {part.get('name')}] {json.dumps(part.get('input'))[:400]}") - return "\n\n".join(said) + if entry.get("type") == "assistant": + lines += [line for part in entry.get("message", {}).get("content", []) if (line := said(part))] + return "\n\n".join(lines) def human_turns(entries): @@ -196,11 +204,11 @@ def trust(paths): print("trusted for the handoff: " + ", ".join(granted), file=sys.stderr) -def worker_args(task, name, slot, resuming): +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(slot)] + 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(slot)] + 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", @@ -213,19 +221,17 @@ def worker_args(task, name, slot, resuming): def run_worker(args): proc = subprocess.Popen(["claude", *args], stdout=subprocess.PIPE, text=True) done = {} - for line in proc.stdout: + for raw in proc.stdout: try: - event = json.loads(line) + event = json.loads(raw) except ValueError: continue if event.get("type") == "result": done = event elif event.get("type") == "assistant": for part in event["message"]["content"]: - if part["type"] == "text" and part["text"].strip(): - print(part["text"], flush=True) - elif part["type"] == "tool_use": - print(f"· {part['name']} {json.dumps(part['input'])[:160]}", flush=True) + if line := said(part, 160): + print(line, flush=True) return done if proc.wait() == 0 else {} @@ -255,7 +261,8 @@ def judge(task, premises, transcript): for attempt in range(2): proc = subprocess.run(["claude", *args], capture_output=True, text=True) if proc.returncode != 0: - sys.exit(proc.stderr.strip() or "the judge failed") + print(proc.stderr.strip() or "the judge failed", file=sys.stderr) + return {} verdict = json.loads(proc.stdout)["structured_output"] if grounded(verdict, transcript): return verdict @@ -263,32 +270,34 @@ def judge(task, premises, transcript): return verdict -def handoff(slot, path, question): +def handoff(session_id, path, question): print(f"\n{question}", file=sys.stderr) if not sys.stdin.isatty(): return False trust(checkouts()) before = human_turns(entries(path)) - subprocess.run(["claude", "--permission-mode", "bypassPermissions", "--resume", str(slot)]) + subprocess.run(["claude", "--permission-mode", "bypassPermissions", "--resume", str(session_id)]) return human_turns(entries(path)) > before -def run_round(task, given, name, slot): - worked = run_worker(worker_args(task, name, slot, resuming=bool(session_file(slot)))) +def run_round(task, premises, name, session_id): + worked = run_worker(worker_args(task, name, session_id, resuming=bool(session_file(session_id)))) if not worked: return False - path = session_file(slot) + path = session_file(session_id) if not path: - sys.exit(f"claude left no transcript for session {slot}") - verdict = judge(task, given, render(entries(path))) - while verdict["ask"]: + sys.exit(f"claude left no transcript for session {session_id}") + verdict = judge(task, premises, render(entries(path))) + while verdict and verdict["ask"]: archive(path, f"Task: {task}\n\nVerdict: needs input\n\n{verdict['question']}") - if not handoff(slot, path, verdict["question"]): + if not handoff(session_id, path, verdict["question"]): sys.exit(2) - verdict = judge(task, given, render(entries(path))) + verdict = judge(task, premises, render(entries(path))) + if not verdict: + return False if verdict["finished"]: archive(path, f"Task: {task}\n\nVerdict: finished") - os.remove(path) + end_session(path) return True @@ -315,10 +324,10 @@ def main(): while True: reload_if_edited(round_number) round_number += 1 - given = premises() + premises = gate() name = session_name() print(f"\n=== round {round_number} ===", flush=True) - if run_round(task, given, name, uuid.uuid5(SLOT_NAMESPACE, name)): + if run_round(task, premises, name, uuid.uuid5(SESSION_NAMESPACE, name)): failures = 0 continue failures += 1 diff --git a/bin/test_loop_claude.py b/bin/test_loop_claude.py index 89b32abc..ed5afbe0 100644 --- a/bin/test_loop_claude.py +++ b/bin/test_loop_claude.py @@ -82,6 +82,24 @@ class Archive(unittest.TestCase): self.assertIn("said", open(copy).read()) +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"), "") + + +class EndSession(unittest.TestCase): + def test_removes_the_transcript_and_its_sibling_folder(self): + with tempfile.TemporaryDirectory() as root: + transcript = os.path.join(root, "abc.jsonl") + open(transcript, "w").write("{}\n") + os.makedirs(os.path.join(root, "abc", "subagents")) + loop.end_session(transcript) + self.assertEqual(os.listdir(root), []) + + class Grounded(unittest.TestCase): def test_an_interrupt_must_quote_the_transcript(self): self.assertTrue(loop.grounded({"ask": False, "evidence": ""}, "anything")) -- 2.52.0 From 15bbae8a4eec9e8464781fea1c485d2c366eaa3b Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 24 Sep 2026 20:38:42 +0200 Subject: [PATCH 5/9] Close stdin on the worker, pipe the judge its prompt, ground empty evidence, and skip meta turns in the handoff count --- .gitignore | 6 +++-- bin/claude-instances | 2 +- bin/loop-claude | 53 +++++++++++++++++++++++------------------ bin/test_loop_claude.py | 25 +++++++++++++++---- 4 files changed, 55 insertions(+), 31 deletions(-) diff --git a/.gitignore b/.gitignore index 63f77ba8..9bfb5bcf 100644 --- a/.gitignore +++ b/.gitignore @@ -23,5 +23,7 @@ !principles/ !principles/*.md !skills/ -!skills/*/ -!skills/*/** +!skills/comprehension-panel/ +!skills/comprehension-panel/** +!skills/larv-review/ +!skills/larv-review/** diff --git a/bin/claude-instances b/bin/claude-instances index 6dcb13d3..69c009b8 100755 --- a/bin/claude-instances +++ b/bin/claude-instances @@ -48,7 +48,7 @@ def wrappers(found): def wrapper_row(found, pid): children = {child for child, (argv, ppid, _) in found.items() if ppid == pid and is_claude(argv)} - status = "Inter" if any("--resume" in found[child][0] for child in children) else "Auto" + status = "Inter" if any("-p" not in found[child][0] for child in children) else "Auto" return (status, shown(found[pid][2])), children diff --git a/bin/loop-claude b/bin/loop-claude index 87799627..02e1db83 100755 --- a/bin/loop-claude +++ b/bin/loop-claude @@ -113,17 +113,24 @@ def session_file(session_id): def end_session(path): - os.remove(path) - shutil.rmtree(path.removesuffix(".jsonl"), ignore_errors=True) + 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 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"): - try: - entry = json.loads(raw) - except ValueError: - continue - if isinstance(entry, dict): + if entry := parse(raw): yield entry @@ -147,10 +154,10 @@ def render(entries): def human_turns(entries): spoken = 0 for entry in entries: - if entry.get("type") != "user": + if entry.get("type") != "user" or entry.get("isMeta"): continue content = entry.get("message", {}).get("content") - if isinstance(content, str): + if isinstance(content, str) and not content.startswith("<"): spoken += 1 elif isinstance(content, list) and not any(part.get("type") == "tool_result" for part in content if isinstance(part, dict)): spoken += 1 @@ -219,17 +226,14 @@ def worker_args(task, name, session_id, resuming): def run_worker(args): - proc = subprocess.Popen(["claude", *args], stdout=subprocess.PIPE, text=True) + proc = subprocess.Popen(["claude", *args], stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, text=True) done = {} for raw in proc.stdout: - try: - event = json.loads(raw) - except ValueError: - continue + event = parse(raw) or {} if event.get("type") == "result": done = event elif event.get("type") == "assistant": - for part in event["message"]["content"]: + for part in event.get("message", {}).get("content", []): if line := said(part, 160): print(line, flush=True) return done if proc.wait() == 0 else {} @@ -245,12 +249,12 @@ def judge_prompt(task, premises, transcript): def grounded(verdict, transcript): - return not verdict["ask"] or verdict["evidence"] in transcript + return not verdict["ask"] or bool(verdict["evidence"]) and verdict["evidence"] in transcript def judge(task, premises, transcript): args = [ - "-p", judge_prompt(task, premises, transcript), + "-p", "--json-schema", json.dumps(JUDGE_SCHEMA), "--model", JUDGE_MODEL, "--no-session-persistence", @@ -259,11 +263,11 @@ def judge(task, premises, transcript): "--tools", "", ] for attempt in range(2): - proc = subprocess.run(["claude", *args], capture_output=True, text=True) - if proc.returncode != 0: - print(proc.stderr.strip() or "the judge failed", file=sys.stderr) + proc = subprocess.run(["claude", *args], capture_output=True, input=judge_prompt(task, premises, transcript), text=True) + verdict = (parse(proc.stdout) or {}).get("structured_output") if proc.returncode == 0 else None + if not isinstance(verdict, dict) or "ask" not in verdict: + print(proc.stderr.strip() or "the judge returned no verdict", file=sys.stderr) return {} - verdict = json.loads(proc.stdout)["structured_output"] if grounded(verdict, transcript): return verdict print("the judge quoted nothing in the transcript twice - interrupting anyway", file=sys.stderr) @@ -272,7 +276,7 @@ def judge(task, premises, transcript): def handoff(session_id, path, question): print(f"\n{question}", file=sys.stderr) - if not sys.stdin.isatty(): + if not (sys.stdin.isatty() and sys.stdout.isatty()): return False trust(checkouts()) before = human_turns(entries(path)) @@ -338,4 +342,7 @@ def main(): if __name__ == "__main__": - main() + try: + main() + except KeyboardInterrupt: + sys.exit(130) diff --git a/bin/test_loop_claude.py b/bin/test_loop_claude.py index ed5afbe0..cc99ef04 100644 --- a/bin/test_loop_claude.py +++ b/bin/test_loop_claude.py @@ -6,6 +6,9 @@ import pathlib import stat import tempfile import unittest +import uuid + +SESSION_ID = str(getattr(uuid, "uuid7", uuid.uuid4)()) LOADER = importlib.machinery.SourceFileLoader("loop_claude", str(pathlib.Path(__file__).with_name("loop-claude"))) SPEC = importlib.util.spec_from_loader("loop_claude", LOADER) @@ -43,20 +46,22 @@ class HumanTurns(unittest.TestCase): human("typed"), human([{"type": "text", "text": "typed as a block"}]), human([{"type": "tool_result", "content": "not typed"}]), + human("/model"), + {**human("peer message"), "isMeta": True}, assistant({"type": "text", "text": "said"}), ]), 2) class WorkerArgs(unittest.TestCase): def test_a_fresh_round_names_the_session_and_asks_to_continue_open_work(self): - args = loop.worker_args("the task", "A name", "slot-id", resuming=False) + args = loop.worker_args("the task", "A name", SESSION_ID, 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_round_reuses_the_session(self): - args = loop.worker_args("paint the fence", "A name", "slot-id", resuming=True) - self.assertEqual(args[args.index("--resume") + 1], "slot-id") + args = loop.worker_args("paint the fence", "A name", SESSION_ID, resuming=True) + self.assertEqual(args[args.index("--resume") + 1], SESSION_ID) self.assertNotIn("--name", args) self.assertNotIn("paint the fence", args[1]) @@ -93,18 +98,28 @@ class Said(unittest.TestCase): class EndSession(unittest.TestCase): def test_removes_the_transcript_and_its_sibling_folder(self): with tempfile.TemporaryDirectory() as root: - transcript = os.path.join(root, "abc.jsonl") + transcript = os.path.join(root, f"{SESSION_ID}.jsonl") open(transcript, "w").write("{}\n") - os.makedirs(os.path.join(root, "abc", "subagents")) + os.makedirs(os.path.join(root, SESSION_ID, "subagents")) + os.makedirs(os.path.join(root, f"{SESSION_ID}.superseded-1", "tool-results")) + open(os.path.join(root, f"{SESSION_ID}.orphaned-1-ab.jsonl"), "w").write("{}\n") loop.end_session(transcript) self.assertEqual(os.listdir(root), []) +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]")) + + class Grounded(unittest.TestCase): def test_an_interrupt_must_quote_the_transcript(self): self.assertTrue(loop.grounded({"ask": False, "evidence": ""}, "anything")) self.assertTrue(loop.grounded({"ask": True, "evidence": "Needs you: x"}, "so.\n\nNeeds you: x\n")) self.assertFalse(loop.grounded({"ask": True, "evidence": "invented"}, "the transcript")) + self.assertFalse(loop.grounded({"ask": True, "evidence": ""}, "the transcript")) if __name__ == "__main__": -- 2.52.0 From 09339f694b182859dd6e5ba0044c5c7782d4e0f2 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 24 Sep 2026 20:42:51 +0200 Subject: [PATCH 6/9] Require every verdict field, treat an interrupted handoff as unanswered, and tighten the --help contract --- README.md | 2 +- bin/loop-claude | 24 ++++++++++++++---------- bin/test_loop_claude.py | 8 ++++++++ docs/decisions.md | 2 +- 4 files changed, 24 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index aa85fa67..2cb79aaf 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,7 @@ Test: `python3 -m unittest bin/test_loop_claude.py` ## Tracking a new file -`.gitignore` is an allowlist: everything is ignored, and a file is tracked only by being named. Add it as a negation, with its parent directories un-ignored too, then confirm with `git check-ignore -v `: +`.gitignore` is an allowlist. Track a file by negating it and its parent directories, then confirm with `git check-ignore -v `: ``` !docs/ diff --git a/bin/loop-claude b/bin/loop-claude index 02e1db83..71d6d56f 100755 --- a/bin/loop-claude +++ b/bin/loop-claude @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Run a task as headless claude rounds; a judge stops the loop only when a decision is the human's. +"""Run a task as headless claude rounds; a judge interrupts only when a decision is the human's. usage: loop-claude @@ -8,14 +8,15 @@ the task; a judge then reads the transcript against the README. A question only opens `claude --resume` on the terminal. An unfinished chunk resumes the same session next round; a finished one starts a fresh session. Rounds continue until Ctrl-C. -Exit 1: the README gate blocks, or claude fails three rounds running. Exit 2: the human is needed and -no terminal is attached, or the handoff ended without them typing anything. +Exit 1: no task, the README gate blocks, claude leaves no transcript, or claude fails three rounds +running. Exit 2: the human is needed and no terminal is attached, or the handoff ended without them +typing anything. Before a handoff every worktree is marked trusted in ~/.claude.json. -Each project has one session, "A ~/code/ auto-mode", at an id derived from that name; it is +Each project has one session, "A ~/code/ auto-mode" (the absolute path outside ~/code), resumed while present and deleted when the chunk finishes. Its transcript is archived under $AUTO_MODE_TRANSCRIPTS (default ~/.claude/auto-mode-transcripts//) whenever the human is asked -and when the chunk finishes. JUDGE_MODEL and WORKER_MODEL override the models. A change to this -file takes effect at the next round boundary. +and when the chunk finishes. JUDGE_MODEL and WORKER_MODEL override the models (default +claude-opus-5-5). A change to this file takes effect at the next round boundary. """ import glob import json @@ -159,7 +160,7 @@ def human_turns(entries): content = entry.get("message", {}).get("content") if isinstance(content, str) and not content.startswith("<"): spoken += 1 - elif isinstance(content, list) and not any(part.get("type") == "tool_result" for part in content if isinstance(part, dict)): + elif isinstance(content, list) and not any(said(part) == "" or said(part).startswith("[Request interrupted") for part in content): spoken += 1 return spoken @@ -188,7 +189,6 @@ def checkouts(): def trust(paths): - # No CLI flag skips the trust dialog, and the interactive resume would stall on it in every worktree the round created. config = os.path.expanduser("~/.claude.json") try: data = json.load(open(config, encoding="utf-8")) @@ -221,7 +221,7 @@ def worker_args(task, name, session_id, resuming): "--output-format", "stream-json", "--permission-mode", "bypassPermissions", "--verbose", - *(["--model", WORKER_MODEL] if WORKER_MODEL else []), + "--model", WORKER_MODEL, ] @@ -248,6 +248,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): return not verdict["ask"] or bool(verdict["evidence"]) and verdict["evidence"] in transcript @@ -265,7 +269,7 @@ def judge(task, premises, transcript): for attempt in range(2): proc = subprocess.run(["claude", *args], capture_output=True, input=judge_prompt(task, premises, transcript), text=True) verdict = (parse(proc.stdout) or {}).get("structured_output") if proc.returncode == 0 else None - if not isinstance(verdict, dict) or "ask" not in verdict: + if not complete(verdict): print(proc.stderr.strip() or "the judge returned no verdict", file=sys.stderr) return {} if grounded(verdict, transcript): diff --git a/bin/test_loop_claude.py b/bin/test_loop_claude.py index cc99ef04..53acfc58 100644 --- a/bin/test_loop_claude.py +++ b/bin/test_loop_claude.py @@ -48,6 +48,7 @@ class HumanTurns(unittest.TestCase): human([{"type": "tool_result", "content": "not typed"}]), human("/model"), {**human("peer message"), "isMeta": True}, + human([{"type": "text", "text": "[Request interrupted by user]"}]), assistant({"type": "text", "text": "said"}), ]), 2) @@ -122,5 +123,12 @@ class Grounded(unittest.TestCase): self.assertFalse(loop.grounded({"ask": True, "evidence": ""}, "the transcript")) +class Verdict(unittest.TestCase): + def test_needs_every_field_the_schema_requires(self): + self.assertTrue(loop.complete({"ask": False, "evidence": "", "finished": True, "question": ""})) + self.assertFalse(loop.complete({"ask": False})) + self.assertFalse(loop.complete(None)) + + if __name__ == "__main__": unittest.main() diff --git a/docs/decisions.md b/docs/decisions.md index af97a5ae..9f300058 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -6,7 +6,7 @@ ## loop-claude: one session per project, at a fixed id -2026-09-21, lilleman. Serves goal 4. The id is uuid5 of the session name under the script's own namespace, so the session picker holds one entry per project and any transcript under that id is the script's own: resumed while present, deleted when the chunk finishes. Valid while the picker lists sessions by id. +2026-09-21, lilleman. 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. Valid while the picker lists sessions by id. ## loop-claude: the trust file is rewritten before a handoff -- 2.52.0 From 3d419f56661e06277826d7c7d05a37a78336086b Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 24 Sep 2026 20:46:45 +0200 Subject: [PATCH 7/9] Drop claude-instances --- README.md | 3 +- bin/claude-instances | 83 -------------------------------------------- 2 files changed, 1 insertion(+), 85 deletions(-) delete mode 100755 bin/claude-instances diff --git a/README.md b/README.md index 2cb79aaf..f52279b3 100644 --- a/README.md +++ b/README.md @@ -15,12 +15,11 @@ Me, on my own machines. Private repo, nobody else depends on it. ## Install -Link the tools onto `PATH`: `ln -s ~/.claude/bin/loop-claude ~/.local/bin/loop-claude`, and the same for `claude-instances`. +Link the tool onto `PATH`: `ln -s ~/.claude/bin/loop-claude ~/.local/bin/loop-claude`. ## Tools - `loop-claude ` runs a project's next chunk round after round; `loop-claude --help` states its contract. -- `claude-instances` redraws a table of the running claude sessions by project. Test: `python3 -m unittest bin/test_loop_claude.py` diff --git a/bin/claude-instances b/bin/claude-instances deleted file mode 100755 index 69c009b8..00000000 --- a/bin/claude-instances +++ /dev/null @@ -1,83 +0,0 @@ -#!/usr/bin/env python3 -import os -import sys -import time - -CODE = os.path.expanduser("~/code") -HOME = os.path.expanduser("~") -INTERVAL = float(os.environ.get("INTERVAL", "2")) -PLUMBING = ("--bg-pty-host", "--bg-spare", "--json-path", "--spawned-by") - - -def processes(): - found = {} - for pid in os.listdir("/proc"): - if not pid.isdigit(): - continue - try: - argv = open(f"/proc/{pid}/cmdline", "rb").read().decode("utf-8", "replace").split("\0")[:-1] - cwd = os.readlink(f"/proc/{pid}/cwd") - ppid = next(int(line.split()[1]) for line in open(f"/proc/{pid}/status") if line.startswith("PPid:")) - except (OSError, StopIteration, ValueError): - continue - if argv: - found[int(pid)] = (argv, ppid, cwd.removesuffix(" (deleted)")) - return found - - -def shown(cwd): - if cwd == CODE: - return "code" - if cwd.startswith(f"{CODE}/"): - return os.path.relpath(cwd, CODE) - return cwd.replace(HOME, "~", 1) - - -def is_claude(argv): - return os.path.basename(argv[0]).startswith("claude") and not any(flag in argv for flag in PLUMBING) - - -def wrappers(found): - parents = set() - for argv, ppid, _ in found.values(): - parent = found.get(ppid) - if is_claude(argv) and parent and os.path.basename(parent[0][0]).startswith("python"): - parents.add(ppid) - return parents - - -def wrapper_row(found, pid): - children = {child for child, (argv, ppid, _) in found.items() if ppid == pid and is_claude(argv)} - status = "Inter" if any("-p" not in found[child][0] for child in children) else "Auto" - return (status, shown(found[pid][2])), children - - -def rows(found): - listed, claimed = [], set() - for pid in wrappers(found): - row, children = wrapper_row(found, pid) - listed.append(row) - claimed |= children - listed += [("Other", shown(cwd)) for pid, (argv, _, cwd) in found.items() if pid not in claimed and is_claude(argv)] - return sorted(listed, key=lambda row: (row[1], row[0])) - - -def table(listed): - width = max([len(path) for _, path in listed] + [4]) - out = [f"{'STATUS':<6} {'PATH':<{width}}", f"{'-' * 6} {'-' * width}"] - out += [f"{status:<6} {path:<{width}}" for status, path in listed] or ["(none running)"] - return "\n".join(out) - - -def main(): - try: - while True: - sys.stdout.write("\x1b[H\x1b[2J" + table(rows(processes())) + "\n") - sys.stdout.flush() - time.sleep(INTERVAL) - except KeyboardInterrupt: - pass - - -if __name__ == "__main__": - main() -- 2.52.0 From f9d37f4a14d2e5ed1a406283965b1487ed5d84a2 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 24 Sep 2026 20:49:49 +0200 Subject: [PATCH 8/9] Name a release ready to cut as a handoff in the contract and the judge rules --- bin/loop-claude | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/bin/loop-claude b/bin/loop-claude index 71d6d56f..6aa21a50 100755 --- a/bin/loop-claude +++ b/bin/loop-claude @@ -4,9 +4,10 @@ usage: loop-claude Run it in a project checkout whose README.md has ## Goals and ## Audience. Each round a worker runs -the task; a judge then reads the transcript against the README. A question only the human can answer -opens `claude --resume` on the terminal. An unfinished chunk resumes the same session next round; a -finished one starts a fresh session. Rounds continue until Ctrl-C. +the task; a judge then reads the transcript against the README. A question only the human can answer, +or a release ready to cut, hands the session over: `claude --resume` on the terminal. An unfinished +chunk resumes the same session next round; a finished one starts a fresh session. Rounds continue +until Ctrl-C or that handoff. Exit 1: no task, the README gate blocks, claude leaves no transcript, or claude fails three rounds running. Exit 2: the human is needed and no terminal is attached, or the handoff ended without them @@ -39,8 +40,8 @@ JUDGE_RULES = ( "- 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 choice " - "outside the repo\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" -- 2.52.0 From 9a2eff3005b209388cb51417853799559f5f4085 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 24 Sep 2026 20:52:18 +0200 Subject: [PATCH 9/9] Record the merge under the comprehension floor --- AGENTS.md | 1 + docs/decisions.md | 4 ++++ 2 files changed, 5 insertions(+) diff --git a/AGENTS.md b/AGENTS.md index 1fd3b832..4c951f08 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -6,3 +6,4 @@ Decisions live in `docs/decisions.md`: - loop-claude: one session per project, at a fixed id - loop-claude: the trust file is rewritten before a handoff - bin/: host python, no container +- Merged under the comprehension floor diff --git a/docs/decisions.md b/docs/decisions.md index 9f300058..38886b24 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -15,3 +15,7 @@ ## bin/: host python, no container 2026-09-24, larv-review. Serves goals 1 and 4. The tools drive the host's claude CLI and read the host's session files, which a container cannot see; the tests run the same way. Valid while claude runs on the host. + +## Merged under the comprehension floor + +2026-09-24, lilleman. Serves goal 4. The 2026-09-24 four-seat panel scored 5 overall, capped at 4 by Locality and Self-sufficiency, on items outside the loop-claude chunk; the chunk merged and the items sit in `todo.md`. Valid until that todo item closes. -- 2.52.0