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)
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()
+47 -38
View File
@@ -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
+18
View File
@@ -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"))