Name the session invariant run_cycle resumes on, and say which outcome ended an interrupt #22

Merged
lilleman merged 5 commits from session-open into main 2026-09-24 23:36:30 +02:00
4 changed files with 50 additions and 16 deletions
+1
View File
@@ -5,6 +5,7 @@
- Track the authored configuration: `CLAUDE.md`, `AGENTS.md`, `settings.json`, `statusline.sh`, agents, skills and principles. Credentials, transcripts and memory files stay untracked.
- `loop-claude <task>` runs a project's next chunk cycle after cycle, interrupting only for a decision that is yours or a release ready to cut.
- `loop-claude` exits 1 when the judge fails three times running; a verdict missing a field or quoting nothing in the transcript is a failure.
- `loop-claude` exits 2 when an interrupt gets no answer, saying why: stdin or stdout is not a terminal, or nothing was typed. Rerunning resumes the session.
- `loop-claude --help` names the Claude Code version its transcript, session and trust handling were observed on; check it first when an upgrade breaks a cycle.
- `loop-claude` runs the model each project's settings pick; `WORKER_MODEL` and `JUDGE_MODEL` override it. This repo runs on Fable 5.1.
- Reviewers share one protocol for verdicts, severities, rounds and declines: `agents/review-protocol.md`.
+13 -8
View File
@@ -10,10 +10,10 @@ unfinished chunk resumes the same session next cycle; a finished one starts a fr
continue until that interrupt or Ctrl-C.
Exit 1: no task, no premises, claude leaves no transcript, or the worker or the judge fails three
times running, a verdict missing a field or quoting nothing in the transcript being a judge failure;
rerunning resumes the session. Exit 2: the human is needed and no terminal is attached, or the
interrupt ended without them typing anything. Before an interrupt every worktree is marked trusted in
~/.claude.json.
times running, a verdict missing a field or quoting nothing in the transcript being a judge failure.
Exit 2: the human is needed and stdin or stdout is not a terminal, or the interrupt ended without
them typing anything. Rerunning resumes the session after either exit. Before an interrupt every
worktree is marked trusted in ~/.claude.json.
Each project has one session, "A ~/code/<path> auto-mode" (the absolute path outside ~/code),
deleted when the chunk finishes. Its transcript is archived under $AUTO_MODE_TRANSCRIPTS (default
@@ -133,6 +133,10 @@ def end_session(path):
print(f"could not remove {sibling}: {failure}", file=sys.stderr)
def session_open(session_id):
return bool(session_file(session_id))
def parse(raw):
try:
entry = json.loads(raw)
@@ -306,15 +310,15 @@ def judge(task, premises, transcript):
def interrupt(session_id, path, question):
print(f"\n{question}", file=sys.stderr)
if not (sys.stdin.isatty() and sys.stdout.isatty()):
return False
return "stdin or stdout is not a terminal"
trust(checkouts())
before = human_turns(entries(path))
subprocess.run(["claude", "--permission-mode", "bypassPermissions", "--resume", str(session_id)])
return human_turns(entries(path)) > before
return "" if human_turns(entries(path)) > before else "the interrupt ended without the human typing anything"
def run_cycle(task, premises, name, session_id):
worked = run_worker(worker_args(task, name, session_id, resuming=bool(session_file(session_id))))
worked = run_worker(worker_args(task, name, session_id, resuming=session_open(session_id)))
if not worked:
return False
path = session_file(session_id)
@@ -323,7 +327,8 @@ def run_cycle(task, premises, name, session_id):
verdict = judge(task, premises, render(entries(path)))
while verdict["ask"]:
archive(path, f"Task: {task}\n\nVerdict: needs input\n\n{verdict['question']}")
if not interrupt(session_id, path, verdict["question"]):
if failure := interrupt(session_id, path, verdict["question"]):
print(failure, file=sys.stderr)
sys.exit(2)
verdict = judge(task, premises, render(entries(path)))
if verdict["finished"]:
+35 -7
View File
@@ -124,15 +124,37 @@ class Said(unittest.TestCase):
class EndSession(unittest.TestCase):
def test_removes_the_transcript_and_its_sibling_folder(self):
with tempfile.TemporaryDirectory() as root:
def test_removes_the_transcript_and_its_siblings_and_closes_the_session(self):
with tempfile.TemporaryDirectory() as home, unittest.mock.patch.dict(os.environ, {"HOME": home}):
root = os.path.join(home, ".claude", "projects", "p")
os.makedirs(root)
transcript = os.path.join(root, f"{SESSION_ID}.jsonl")
open(transcript, "w").write("{}\n")
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")
self.assertTrue(loop.session_open(SESSION_ID))
loop.end_session(transcript)
self.assertEqual(os.listdir(root), [])
self.assertFalse(loop.session_open(SESSION_ID))
class Interrupt(unittest.TestCase):
def test_says_whether_no_terminal_or_nothing_typed_ended_it(self):
with tempfile.TemporaryDirectory() as root:
transcript = os.path.join(root, "session.jsonl")
open(transcript, "w").write("{}\n")
with unittest.mock.patch("sys.stdin.isatty", return_value=False):
self.assertEqual(loop.interrupt(SESSION_ID, transcript, "q?"), "stdin or stdout is not a terminal")
with (
unittest.mock.patch("sys.stdin.isatty", return_value=True),
unittest.mock.patch("sys.stdout.isatty", return_value=True),
unittest.mock.patch.multiple(loop, checkouts=unittest.mock.DEFAULT, trust=unittest.mock.DEFAULT),
unittest.mock.patch("subprocess.run") as run,
):
self.assertEqual(loop.interrupt(SESSION_ID, transcript, "q?"), "the interrupt ended without the human typing anything")
run.side_effect = lambda *args, **kwargs: open(transcript, "a").write(json.dumps(human("typed")) + "\n")
self.assertEqual(loop.interrupt(SESSION_ID, transcript, "q?"), "")
class Parse(unittest.TestCase):
@@ -166,8 +188,8 @@ if "--json-schema" in args:
open(os.environ["STUB_VERDICTS"], "w").write(" ".join(plan[1:]))
if plan[0] == "fail":
sys.exit(1)
unquoted = plan[0] == "unquoted"
print(json.dumps({"structured_output": {"ask": unquoted, "evidence": "invented" if unquoted else "", "finished": plan[0] == "finished", "question": "q?" if unquoted else ""}}))
ask = plan[0] in ("ask", "unquoted")
print(json.dumps({"structured_output": {"ask": ask, "evidence": {"ask": "worked", "unquoted": "invented"}.get(plan[0], ""), "finished": plan[0] == "finished", "question": "q?" if ask else ""}}))
else:
flag = "--session-id" if "--session-id" in args else "--resume"
folder = os.path.expanduser("~/.claude/projects/p")
@@ -187,9 +209,16 @@ class RunCycle(unittest.TestCase):
open(verdicts, "w").write("fail continue finished unquoted continue")
loop.ARCHIVE = os.path.join(home, "archive")
environment = {"HOME": home, "PATH": f"{home}:{os.environ['PATH']}", "STUB_CALLS": calls, "STUB_VERDICTS": verdicts}
with unittest.mock.patch.dict(os.environ, environment), unittest.mock.patch("time.sleep") as sleep:
with unittest.mock.patch.dict(os.environ, environment), unittest.mock.patch("time.sleep") as sleep, unittest.mock.patch("sys.stdin.isatty", return_value=False):
for _ in range(3):
self.assertTrue(loop.run_cycle("task", "premises", "A name", SESSION_ID))
open(verdicts, "w").write("ask")
with self.assertRaises(SystemExit) as stopped, unittest.mock.patch("sys.stderr") as stderr:
loop.run_cycle("task", "premises", "A name", SESSION_ID)
self.assertEqual(stopped.exception.code, 2)
said = "".join(str(call.args[0]) for call in stderr.write.call_args_list)
self.assertIn(f"transcript: {loop.ARCHIVE}", said)
self.assertIn("not a terminal", said)
for plan in ("fail fail fail", "unquoted unquoted unquoted"):
open(verdicts, "w").write(plan)
with self.assertRaises(SystemExit) as stopped:
@@ -199,10 +228,9 @@ class RunCycle(unittest.TestCase):
self.assertIn("asking: q?", stopped.exception.code)
self.assertEqual(open(verdicts).read(), "")
starts = [args[args.index("-p") + 1:][:3] for args in map(json.loads, open(calls)) if "--json-schema" not in args]
self.assertEqual([start[1] for start in starts], ["--name", "--resume", "--name", "--resume", "--resume"])
self.assertEqual([start[1] for start in starts], ["--name", "--resume", "--name", "--resume", "--resume", "--resume"])
self.assertEqual(starts[1][2], SESSION_ID)
self.assertEqual(sleep.call_count, 6)
[copy] = [name for _, _, names in os.walk(loop.ARCHIVE) for name in names]
class Reload(unittest.TestCase):
+1 -1
View File
@@ -4,7 +4,6 @@
Ordered by how many seats of the 2026-09-24 scoring panel (`docs/decisions.md`) named the place; each is one chunk.
- Decide resume-or-fresh in `run_cycle` from state it owns, and give `interrupt`'s no-tty and nothing-typed outcomes two distinct results.
- Give the concept words one definition a reader lands on, cited from where they are used; today three seats found them only in `CHANGELOG.md`'s one-word-per-concept entry.
- Keep `###` sub-headings inside their `##` section in `sections`, pinned by a test; today a sub-heading under `## Goals` silently drops the rest of the goals.
- Merge `project` and `project_path` into one name and one shape for the project's path.
@@ -12,4 +11,5 @@ Ordered by how many seats of the 2026-09-24 scoring panel (`docs/decisions.md`)
- Pin every `CLAUDE.md` heading the agents and skills cite with a test that resolves each citation.
- Define chunk, plan and release inside `JUDGE_RULES`; the judge reads nothing else.
- Name the `set -u` empty-array idiom and the `@sh` eval in `statusline.sh`, one line each.
- Make `CLAUDE.md`'s comment rules say an invariant earns a line only where the code cannot show it, state the one-line rule once, and scope the docstring exemption to what a tool consumes; today a reviewer finds two sentences saying keep and one saying delete.
- Re-run the four-seat scoring panel and record the score in `docs/decisions.md`; the target is every dimension at 7.0 or above.