End a session with its sibling folder, share the part renderer, and split claude-instances

This commit is contained in:
2026-09-24 20:25:44 +02:00
parent 0bfbfa53c1
commit b5a7a116c2
3 changed files with 108 additions and 72 deletions
+43 -34
View File
@@ -33,42 +33,51 @@ def shown(cwd):
return cwd.replace(HOME, "~", 1) return cwd.replace(HOME, "~", 1)
def rows(found): def is_claude(argv):
wrappers = set() return os.path.basename(argv[0]).startswith("claude") and not any(flag in argv for flag in PLUMBING)
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 wrappers(found):
parents = set()
for argv, ppid, _ in found.values():
parent = found.get(ppid) parent = found.get(ppid)
if parent and os.path.basename(parent[0][0]).startswith("python"): if is_claude(argv) and parent and os.path.basename(parent[0][0]).startswith("python"):
wrappers.add(ppid) 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() listed, claimed = [], set()
for pid in wrappers: for pid in wrappers(found):
status = "Auto" row, children = wrapper_row(found, pid)
for child, (argv, ppid, _) in found.items(): listed.append(row)
if ppid == pid and os.path.basename(argv[0]).startswith("claude"): claimed |= children
claimed.add(child) listed += [("Other", shown(cwd)) for pid, (argv, _, cwd) in found.items() if pid not in claimed and is_claude(argv)]
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])) return sorted(listed, key=lambda row: (row[1], row[0]))
try: def table(listed):
while True: width = max([len(path) for _, path in listed] + [4])
listed = rows(processes()) out = [f"{'STATUS':<6} {'PATH':<{width}}", f"{'-' * 6} {'-' * width}"]
width = max([len(path) for _, path in listed] + [4]) out += [f"{status:<6} {path:<{width}}" for status, path in listed] or ["(none running)"]
out = [f"{'STATUS':<6} {'PATH':<{width}}", f"{'-' * 6} {'-' * width}"] return "\n".join(out)
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() def main():
time.sleep(INTERVAL) try:
except KeyboardInterrupt: while True:
pass sys.stdout.write("\x1b[H\x1b[2J" + table(rows(processes())) + "\n")
sys.stdout.flush()
time.sleep(INTERVAL)
except KeyboardInterrupt:
pass
if __name__ == "__main__":
main()
+47 -38
View File
@@ -20,6 +20,7 @@ file takes effect at the next round boundary.
import glob import glob
import json import json
import os import os
import shutil
import subprocess import subprocess
import sys import sys
import time import time
@@ -28,7 +29,7 @@ import uuid
ARCHIVE = os.path.expanduser(os.environ.get("AUTO_MODE_TRANSCRIPTS", "~/.claude/auto-mode-transcripts")) 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") JUDGE_MODEL = os.environ.get("JUDGE_MODEL", "claude-opus-5-5")
ROUND = "LOOP_CLAUDE_ROUND" 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() SOURCE = open(__file__, encoding="utf-8").read()
WORKER_MODEL = os.environ.get("WORKER_MODEL", "claude-opus-5-5") 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} return {name: "\n".join(body) for name, body in found.items() if body}
def premises(): def gate():
try: try:
found = sections(open("README.md", encoding="utf-8").read()) found = sections(open("README.md", encoding="utf-8").read())
except OSError: except OSError:
@@ -106,11 +107,16 @@ def session_name():
return f"A {cwd} auto-mode" return f"A {cwd} auto-mode"
def session_file(slot): def session_file(session_id):
hit = glob.glob(os.path.expanduser(f"~/.claude/projects/*/{slot}.jsonl")) hit = glob.glob(os.path.expanduser(f"~/.claude/projects/*/{session_id}.jsonl"))
return hit[0] if hit else "" return hit[0] if hit else ""
def end_session(path):
os.remove(path)
shutil.rmtree(path.removesuffix(".jsonl"), ignore_errors=True)
def entries(path): def entries(path):
for raw in open(path, encoding="utf-8"): for raw in open(path, encoding="utf-8"):
try: try:
@@ -121,19 +127,21 @@ def entries(path):
yield entry 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): def render(entries):
said = [] lines = []
for entry in entries: for entry in entries:
if entry.get("type") != "assistant": if entry.get("type") == "assistant":
continue lines += [line for part in entry.get("message", {}).get("content", []) if (line := said(part))]
for part in entry.get("message", {}).get("content", []): return "\n\n".join(lines)
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 human_turns(entries): def human_turns(entries):
@@ -196,11 +204,11 @@ def trust(paths):
print("trusted for the handoff: " + ", ".join(granted), file=sys.stderr) 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: 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: 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 [ return [
*start, *start,
"--output-format", "stream-json", "--output-format", "stream-json",
@@ -213,19 +221,17 @@ def worker_args(task, name, slot, resuming):
def run_worker(args): def run_worker(args):
proc = subprocess.Popen(["claude", *args], stdout=subprocess.PIPE, text=True) proc = subprocess.Popen(["claude", *args], stdout=subprocess.PIPE, text=True)
done = {} done = {}
for line in proc.stdout: for raw in proc.stdout:
try: try:
event = json.loads(line) event = json.loads(raw)
except ValueError: except ValueError:
continue continue
if event.get("type") == "result": if event.get("type") == "result":
done = event done = event
elif event.get("type") == "assistant": elif event.get("type") == "assistant":
for part in event["message"]["content"]: for part in event["message"]["content"]:
if part["type"] == "text" and part["text"].strip(): if line := said(part, 160):
print(part["text"], flush=True) print(line, 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 {} return done if proc.wait() == 0 else {}
@@ -255,7 +261,8 @@ def judge(task, premises, transcript):
for attempt in range(2): for attempt in range(2):
proc = subprocess.run(["claude", *args], capture_output=True, text=True) proc = subprocess.run(["claude", *args], capture_output=True, text=True)
if proc.returncode != 0: 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"] verdict = json.loads(proc.stdout)["structured_output"]
if grounded(verdict, transcript): if grounded(verdict, transcript):
return verdict return verdict
@@ -263,32 +270,34 @@ def judge(task, premises, transcript):
return verdict return verdict
def handoff(slot, path, question): def handoff(session_id, path, question):
print(f"\n{question}", file=sys.stderr) print(f"\n{question}", file=sys.stderr)
if not sys.stdin.isatty(): if not sys.stdin.isatty():
return False return False
trust(checkouts()) trust(checkouts())
before = human_turns(entries(path)) 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 return human_turns(entries(path)) > before
def run_round(task, given, name, slot): def run_round(task, premises, name, session_id):
worked = run_worker(worker_args(task, name, slot, resuming=bool(session_file(slot)))) worked = run_worker(worker_args(task, name, session_id, resuming=bool(session_file(session_id))))
if not worked: if not worked:
return False return False
path = session_file(slot) path = session_file(session_id)
if not path: if not path:
sys.exit(f"claude left no transcript for session {slot}") sys.exit(f"claude left no transcript for session {session_id}")
verdict = judge(task, given, render(entries(path))) verdict = judge(task, premises, render(entries(path)))
while verdict["ask"]: while verdict and verdict["ask"]:
archive(path, f"Task: {task}\n\nVerdict: needs input\n\n{verdict['question']}") 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) 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"]: if verdict["finished"]:
archive(path, f"Task: {task}\n\nVerdict: finished") archive(path, f"Task: {task}\n\nVerdict: finished")
os.remove(path) end_session(path)
return True return True
@@ -315,10 +324,10 @@ def main():
while True: while True:
reload_if_edited(round_number) reload_if_edited(round_number)
round_number += 1 round_number += 1
given = premises() premises = gate()
name = session_name() name = session_name()
print(f"\n=== round {round_number} ===", flush=True) 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 failures = 0
continue continue
failures += 1 failures += 1
+18
View File
@@ -82,6 +82,24 @@ class Archive(unittest.TestCase):
self.assertIn("said", open(copy).read()) 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): class Grounded(unittest.TestCase):
def test_an_interrupt_must_quote_the_transcript(self): def test_an_interrupt_must_quote_the_transcript(self):
self.assertTrue(loop.grounded({"ask": False, "evidence": ""}, "anything")) self.assertTrue(loop.grounded({"ask": False, "evidence": ""}, "anything"))