Answer stability round 1: 1 🔴, 11 🟡 (0 misread); drop keys typed ahead on leaving an answer, wrap every line to the drawn width, list the routing calls, test the paths mutants survived

This commit is contained in:
2026-10-29 01:27:23 +01:00
parent 192b36fada
commit e3cd8ae0cf
15 changed files with 413 additions and 151 deletions
+6 -6
View File
@@ -15,7 +15,7 @@ from claude_code.trust import trust
from loop_claude.project.checkout import worktrees
ANSWER_QUESTION = "answer the question above"
# TALK and ASK_ANSWER were picked on 2026-10-17 by a bench of three readers seated as the README's audience, as ~/.claude/CLAUDE.md → "Working loop" → "Bench a syntax with the people who write it." has it.
# ASK_ANSWER was picked on 2026-10-17 by a bench of three readers seated as the README's audience, as ~/.claude/CLAUDE.md → "Working loop" → "Bench a syntax with the people who write it." has it.
ASK_ANSWER = f"Answer ({TALK} opens claude, Enter stops the loop): "
@@ -26,7 +26,7 @@ class WorkerSession:
id: uuid.UUID
rung: Rung
transcript_path: str
# What the worker's claude adds to its environment, as the claude /talk opens does.
# Added to the environment of the worker's claude, and of the claude /talk opens.
env: dict[str, str]
def claude_command(self) -> ClaudeCommand:
@@ -76,7 +76,7 @@ def first_answer(ask: Ask, paths: Paths, effects: Effects) -> str | Talk | Stop:
def shown(paths: Paths, ask: Ask, effects: Effects) -> None:
"""Shows ask in loop-inbox. A failure only warns: the question is still answered on the terminal."""
"""Shows ask in loop-inbox. A failure only warns. The question is then still answered on the terminal, unless claude was to open in loop-inbox: loop-inbox then gives up, and the loop stops."""
if unshown := publish(paths.waiting, ask):
say(f"loop-inbox cannot show this question: {unshown.reason}", effects)
@@ -88,7 +88,7 @@ def withdrawn(paths: Paths, ask: Ask, effects: Effects) -> None:
def talk(chosen: Talk, session: WorkerSession, paths: Paths, effects: Effects) -> Stop | None:
"""Holds the loop while the human answers in the worker's claude session, listed in loop-inbox as open where it is; the human must type something there."""
"""Holds the loop while the human answers in the worker's claude session, which loop-inbox lists as open on loop-claude's terminal or in loop-inbox. A Stop where they type nothing there."""
try:
return human_typed(session.transcript_path, lambda: opened(chosen, session, paths, effects))
finally:
@@ -97,7 +97,7 @@ def talk(chosen: Talk, session: WorkerSession, paths: Paths, effects: Effects) -
def opened(chosen: Talk, session: WorkerSession, paths: Paths, effects: Effects) -> Stop | None:
"""Returns once the claude the human answers in has ended: the one it opens on the terminal, or the one loop-inbox opened."""
# For loop-inbox, this shows that the loop has stopped reading its terminal, so it may open claude.
# Tells loop-inbox where claude is open; for OpenInInbox, it is the go-ahead claim_talk waits for.
shown(paths, dataclasses.replace(chosen.ask, state=chosen.where), effects)
match chosen.where:
case OpenOnTerminal():
@@ -127,7 +127,7 @@ def human_typed(transcript_path: str, held_open: typing.Callable[[], Stop | None
def hand_over(command: ClaudeCommand, paths: Paths, effects: Effects) -> Failure | None:
"""Marks the checkout command runs in, and each of its worktrees, trusted, then runs claude on the terminal as command says; the failure is why claude could not start."""
"""Marks trusted the checkout that command runs in, and each of its worktrees, then runs claude on the terminal as command says; the failure is why claude could not start."""
trust(paths.claude_json, worktrees(command.cwd, effects), lambda text: say(text, effects))
try:
effects.claude_on_terminal(command.args, command.cwd, command.env)
-2
View File
@@ -42,11 +42,9 @@ class Effects:
local_time: typing.Callable[[float], str]
# The machine's memory; None where it cannot be read.
memory: typing.Callable[[], Memory | None]
# A new random id.
new_id: typing.Callable[[], str]
now: typing.Callable[[], float]
on_terminal: typing.Callable[[], bool]
# This process's pid.
pid: typing.Callable[[], int]
# Runs a Python script in a directory, as run_python does.
python: typing.Callable[[list[str], str], subprocess.CompletedProcess[str]]
+12 -11
View File
@@ -22,12 +22,12 @@ is shown the passage the judge quoted as the work remaining. The next chunk star
Cycles continue until an exit below or Ctrl-C. Words: ~/.claude/CLAUDE.md → "Vocabulary".
A question only the human can answer is an interrupt (bin/loop_claude/cycle/interrupt.py).
loop-claude prints the question on its terminal and lists it in loop-inbox, which shows every
loop on the machine that waits for the human. The first answer counts, from either place:
loop-claude prints the question on its terminal and lists it in loop-inbox, which shows the
interrupts of every loop on the machine. The first answer counts, from either place:
- A line of text: the worker resumes headless with it. The judge reads it as the human's, so the
chunk stays unfinished until the answer is recorded.
- /talk: opens the worker's session with `claude --resume`, to read the diff or discuss first. Once
that claude exits, the judge rules on what was typed there.
- /talk: opens the worker's session with `claude --resume` where it was typed, to read the diff or
discuss first. Once that claude exits, the judge rules on what was typed there.
- Enter alone, on loop-claude's terminal: stops the loop.
A release ready to cut opens that session on the terminal at once, since only the human may cut it;
loop-inbox lists it too. Before claude opens, the checkout and each of its worktrees are marked
@@ -57,9 +57,9 @@ compacts its context at about 170k tokens.
Every claude loop-claude starts runs the project's model, saved per <key> in
~/.claude/loop-claude-models.json and read each cycle, unless routing, below, puts the worker,
the session /talk opens and the judge on another rung, a model at an effort. A project without an
entry, as on its first run, is asked for one. LOOP_CLAUDE_JUDGE_MODEL overrides the model for the
judge, LOOP_CLAUDE_WORKER_MODEL for the worker and the session /talk opens; with both set, nothing
is asked.
entry, as on its first run, is asked for one on the terminal; loop-inbox doesn't list that
question. LOOP_CLAUDE_JUDGE_MODEL overrides the model for the judge, LOOP_CLAUDE_WORKER_MODEL for
the worker and the session /talk opens; with both set, nothing is asked.
Where the project's model is on the routing ladder (bin/model_routing/ladder.py), the worker and the
session /talk opens run on the rung that the chunk's todo.md item picks, and the judge of some
@@ -78,9 +78,10 @@ Once 20 cycles have closed across all projects in the archive since the last mea
loop to close one measures every finished chunk there, with no model run, and writes
routing-figures.md at the archive's root (bin/routing_figures/measure.py). Each call the figures
make for a routing change, unless raised before, is an interrupt: claude, on the project's model,
on the terminal in ~/.claude, asked to put the calls to the human. Once that claude ends, the calls
are listed in routing-calls-raised.md beside the figures, and not raised again. Off a terminal, the
calls are said on stderr, the loop goes on, and they are raised again at the next measurement.
on the terminal in ~/.claude, asked to put the calls to the human; loop-inbox lists it too. Once
that claude ends, the calls are listed in routing-calls-raised.md beside the figures, and not
raised again. Off a terminal, the calls are said on stderr, the loop goes on, and they are raised
again at the next measurement.
A change to bin/loop-claude or any bin/**/*.py takes effect at the next cycle boundary, once
loop-claude --help succeeds: the loop reloads into the edited script.
@@ -199,7 +200,7 @@ def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launc
if isinstance(closed, Stop):
return closed
loop_run = closed
if stop := check_routing(archive_root(paths.home, env), project or Rung(models.worker), paths, effects):
if stop := check_routing(archive_root(paths.home, env), loop_run.root, project or Rung(models.worker), paths, effects):
return stop
+18 -9
View File
@@ -2,9 +2,9 @@
import pathlib
from routing_figures import archive
from loop_claude.waiting import Ask, ClaudeCommand, OpenOnTerminal
from routing_figures.measure import calls, due, render, totals
from loop_claude.cycle.interrupt import claude_args, hand_over
from loop_claude.waiting import ClaudeCommand
from loop_claude.cycle.interrupt import claude_args, hand_over, shown, withdrawn
from loop_claude.effects import Effects, say
from failure import Failure
from loop_claude.paths import Paths
@@ -13,14 +13,14 @@ from loop_claude.stop import Stop
from utc_stamp import utc
def check_routing(root: pathlib.Path, rung: Rung, paths: Paths, effects: Effects) -> Stop | None:
"""Stops only when claude cannot start for the calls; a figure it cannot measure or keep is said on stderr, and the loop goes on. rung is the rung of the claude that puts the calls to the human."""
def check_routing(root: pathlib.Path, checkout: str, rung: Rung, paths: Paths, effects: Effects) -> Stop | None:
"""Stops only when claude cannot start for the calls; a figure it cannot measure or keep is said on stderr, and the loop goes on. checkout is the loop's, and rung is the rung of the claude that puts the calls to the human."""
with archive.locked(root) as held:
new = new_calls(root, paths, effects) if held else []
if isinstance(new, Failure):
say(f"routing figures: {new.reason}", effects)
return None
return raise_calls(root, new, rung, paths, effects) if new else None
return raise_calls(root, checkout, new, rung, paths, effects) if new else None
def new_calls(root: pathlib.Path, paths: Paths, effects: Effects) -> list[str] | Failure:
@@ -43,15 +43,24 @@ def new_calls(root: pathlib.Path, paths: Paths, effects: Effects) -> list[str] |
return [call for call in found if call not in kept.calls]
def raise_calls(root: pathlib.Path, new: list[str], rung: Rung, paths: Paths, effects: Effects) -> Stop | None:
"""Puts the calls to the human through a claude in this setup's checkout, where the routing decision lives. Off a terminal they are only said, and stay in the figures, raised at the next measurement on a terminal."""
def raise_calls(root: pathlib.Path, checkout: str, new: list[str], rung: Rung, paths: Paths, effects: Effects) -> Stop | None:
"""Puts the calls to the human through a claude in this setup's checkout, where the routing decision lives; loop-inbox lists them under the loop's checkout while that claude is open. Off a terminal they are only said, and stay in the figures, raised at the next measurement on a terminal."""
listed = "".join(f"- {call}\n" for call in new)
say(f"\nloop-claude's routing figures call for a routing change:\n{listed}The figures: {root / archive.FIGURES}", effects)
question = f"loop-claude's routing figures call for a routing change:\n{listed}The figures: {root / archive.FIGURES}"
say(f"\n{question}", effects)
if not effects.on_terminal():
say("Not on a terminal: the calls are raised again at the next measurement.", effects)
return None
prompt = f"Put these calls for a routing change from loop-claude's figures to the human, and change nothing until they answer:\n{listed}The figures are in {root / archive.FIGURES}. The ladder, its steps and the delegation rule are docs/decisions.md → `routing:`, and a change to them is the human's. Record what they decide as ~/.claude/CLAUDE.md says; the next chunk of this repo files the plan item for these calls."
if unstarted := hand_over(ClaudeCommand(claude_args(rung, [prompt]), str(paths.claude_dir), {}), paths, effects):
# No worker session answers the calls, so the ask is filed under its own id.
ask_id = effects.new_id()
ask = Ask(ask_id, ask_id, checkout, question, effects.now(), effects.pid(), OpenOnTerminal())
shown(paths, ask, effects)
try:
unstarted = hand_over(ClaudeCommand(claude_args(rung, [prompt]), str(paths.claude_dir), {}), paths, effects)
finally:
withdrawn(paths, ask, effects)
if unstarted:
return Stop(1, f"could not start claude for the routing calls: {unstarted.reason}")
# Raised once the human has seen them, answered or not: an unanswered call reaches the plan through AGENTS.md, so it is not asked twice.
if unmarked := archive.mark_raised(root, new, utc(effects.now())):
+1 -1
View File
@@ -10,7 +10,7 @@ class Paths:
home: pathlib.Path
model_catalog: pathlib.Path
models_file: pathlib.Path
# Where a loop that waits for the human shows its question to loop-inbox (bin/loop_claude/waiting.py).
# Where a loop shows its interrupt to loop-inbox (bin/loop_claude/waiting.py).
waiting: pathlib.Path
+1 -2
View File
@@ -100,9 +100,8 @@ elif role == "judge":
print(step.get("stderr", ""), file=sys.stderr)
else:
if step.get("ctrl_c"):
# A Ctrl-C on the terminal reaches every process in its foreground, loop-claude too.
# A Ctrl-C on the terminal reaches every process in its foreground, loop-claude too. kill returns once the signal is pending in loop-claude, before this process exits and loop-claude stops waiting for it.
os.kill(os.getppid(), signal.SIGINT)
time.sleep(0.5)
if "type" in step:
append({{"type": "user", "message": {{"content": step["type"]}}}})
if step.get("unreadable"):
+57 -14
View File
@@ -6,6 +6,7 @@ import json
import os
import pathlib
import shutil
import signal
import stat
import subprocess
import sys
@@ -66,10 +67,8 @@ def human(content):
class FakeEffects:
"""Effects that record each call and answer from a script, one answer per call."""
def __init__(self, claude=(), on_terminal_claude=(), git=(), inputs=(), python=(), streams=(), on_terminal=True, free_memory=(), gone=()):
def __init__(self, claude=(), on_terminal_claude=(), git=(), inputs=(), python=(), streams=(), on_terminal=True, free_memory=()):
self.calls = []
# The pids of processes that no longer run.
self.gone = set(gone)
self.scripts = {"claude": list(claude), "claude_on_terminal": list(on_terminal_claude), "git": list(git), "input": list(inputs), "python": list(python), "stream_claude": list(streams)}
# Without a script, every read finds all memory available.
self.free_memory = list(free_memory)
@@ -79,7 +78,7 @@ class FakeEffects:
def effects(self):
return Effects(
alive=lambda pid: pid not in self.gone,
alive=lambda pid: True,
claude=lambda args, cwd, stdin: self.answer("claude", (args, stdin)),
claude_on_terminal=self.on_terminal_claude,
discard_typed=lambda: self.calls.append(("discard_typed", None)),
@@ -103,7 +102,7 @@ class FakeEffects:
return self.free_memory.pop(0) if self.free_memory else memory.Memory(available=16, total=16)
def input_or(self, prompt, other):
"""Answers from the input script as input does, but hands a callable in it other, which loop-inbox's answer comes from."""
"""Answers from the input script as input does; a callable in the script gets other, the source of loop-inbox's answer."""
self.calls.append(("input", prompt))
answer = self.scripts["input"].pop(0)
if isinstance(answer, BaseException):
@@ -752,15 +751,26 @@ class Interrupts(unittest.TestCase):
self.assertEqual(self.talk(states.Talk(self.ask(), waiting.OpenInInbox(inbox)), effects), (None, f"{STAMP} claude is open for this question in loop-inbox; waiting for it to end\n"))
self.assertEqual((fake.made("claude_on_terminal"), list(self.paths.waiting.iterdir())), ([], []))
def test_stops_when_loop_inbox_ends_its_claude_or_is_gone_with_nothing_typed(self):
inbox = 4343
def ended(_):
def test_stops_when_loop_inbox_ends_its_claude_with_nothing_typed(self):
inbox, looked, slept = 4343, [], []
def alive(pid):
looked.append(pid)
return pid == inbox
def ended(seconds):
slept.append(seconds)
waiting.send(self.paths.waiting, self.ask(), waiting.ClaudeEnded())
# loop-inbox's claude ends while the loop waits, or loop-inbox is gone before the loop looks.
for gone in ((), (inbox,)):
with self.subTest(gone=gone):
stop, _ = self.talk(states.Talk(self.ask(), waiting.OpenInInbox(inbox)), dataclasses.replace(FakeEffects(gone=gone).effects(), sleep=ended))
self.assertEqual(stop, Stop(2, "the human is needed to answer the question above, but the interrupt ended with nothing typed"))
stop, _ = self.talk(states.Talk(self.ask(), waiting.OpenInInbox(inbox)), dataclasses.replace(FakeEffects().effects(), alive=alive, sleep=ended))
self.assertEqual((stop, looked, slept), (Stop(2, "the human is needed to answer the question above, but the interrupt ended with nothing typed"), [inbox], [waiting.POLL_SECONDS]))
def test_stops_when_loop_inbox_is_gone_with_nothing_typed(self):
inbox, looked = 4343, []
def alive(pid):
looked.append(pid)
# loop-inbox's process ends while the loop waits for its claude.
return pid == inbox and len(looked) == 1
fake = FakeEffects()
stop, _ = self.talk(states.Talk(self.ask(), waiting.OpenInInbox(inbox)), dataclasses.replace(fake.effects(), alive=alive))
self.assertEqual((stop, looked, fake.made("sleep")), (Stop(2, "the human is needed to answer the question above, but the interrupt ended with nothing typed"), [inbox, inbox], [waiting.POLL_SECONDS]))
def test_lists_the_claude_open_on_its_terminal_in_loop_inbox_while_it_runs(self):
def ran(args):
@@ -805,10 +815,20 @@ class RoutingCheck(unittest.TestCase):
(subagents / "agent-a.meta.json").write_text(json.dumps({"agentType": "Explore", "toolUseId": "a"}))
def check(self, fake):
"""What check_routing returns and says for a loop in /code/log."""
with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()) as said:
stop = routing_check.check_routing(self.root, Rung("m", "high"), self.paths, fake.effects())
stop = routing_check.check_routing(self.root, "/code/log", Rung("m", "high"), self.paths, fake.effects())
return stop, said.getvalue()
def test_lists_the_calls_in_loop_inbox_while_their_claude_is_open(self):
self.chunks(5, 4)
question = f"loop-claude's routing figures call for a routing change:\n- Explore subagents' reports took more of the worker's context than their searches would have.\nThe figures: {self.root / 'routing-figures.md'}"
def ran(args):
self.assertEqual(waiting.waiting(self.paths.waiting, lambda pid: True), [waiting.Ask(ASK_ID, ASK_ID, "/code/log", question, NOW, PID, waiting.OpenOnTerminal())])
return 0
self.check(FakeEffects(on_terminal_claude=[ran], git=[UNREAD, ""]))
self.assertEqual(list(self.paths.waiting.iterdir()), [])
def test_measures_once_20_cycles_have_closed_since_the_last_measurement(self):
self.chunks(5, 3)
self.assertEqual(self.check(FakeEffects()), (None, ""))
@@ -871,6 +891,7 @@ class RoutingCheck(unittest.TestCase):
self.chunks(5, 4)
stop, _ = self.check(FakeEffects(on_terminal_claude=[OSError(2, "No such file or directory")], git=[UNREAD, ""]))
self.assertEqual(stop, Stop(1, "could not start claude for the routing calls: No such file or directory"))
self.assertEqual(list(self.paths.waiting.iterdir()), [])
@unittest.skipIf(os.geteuid() == 0, "root writes into a read-only directory")
def test_says_a_figure_it_cannot_write_and_goes_on(self):
@@ -1243,6 +1264,28 @@ class LocalTime(unittest.TestCase):
self.assertEqual(system_effects().local_time(NOW), "2026-09-21 16:13:20")
class Alive(unittest.TestCase):
def test_a_process_that_runs_is_alive_and_one_that_ended_is_not(self):
ended = subprocess.Popen([sys.executable, "-c", "pass"])
ended.wait()
# Unless this process runs as root, it may not signal pid 1, which still runs.
self.assertEqual([system_effects().alive(pid) for pid in (os.getpid(), ended.pid, 1)], [True, False, True])
class ClaudeOnTerminal(unittest.TestCase):
def test_leaves_ctrl_c_to_claude_while_it_runs_and_returns_its_exit_code(self):
caught = []
self.addCleanup(signal.signal, signal.SIGINT, signal.signal(signal.SIGINT, lambda number, frame: caught.append(number)))
before = signal.getsignal(signal.SIGINT)
with tempfile.TemporaryDirectory() as folder:
claude = pathlib.Path(folder, "claude")
# A Ctrl-C on the terminal reaches every process in its foreground. kill returns once the signal is pending in the test's process, before claude exits and claude_on_terminal returns.
claude.write_text(f"#!{sys.executable}\nimport os, signal, sys\nos.kill(os.getppid(), signal.SIGINT)\nsys.exit(3)\n")
claude.chmod(0o755)
code = system_effects().claude_on_terminal([], folder, {"PATH": folder})
self.assertEqual((code, caught, signal.getsignal(signal.SIGINT)), (3, [], before))
class PythonEffect(unittest.TestCase):
def test_runs_a_script_in_the_given_directory(self):
with tempfile.TemporaryDirectory() as cwd:
+11 -9
View File
@@ -1,9 +1,11 @@
"""The files by which a loop-claude that waits for the human shows its question in loop-inbox, and takes an answer typed there.
"""The files by which a loop-claude shows its interrupt in loop-inbox, and takes an answer typed there.
A waiting loop keeps one file per session, <session id>.json, in Paths.waiting, and removes it once answered or stopped.
Its state says whether it waits for an answer, or has claude open for it, on the loop's own terminal or in loop-inbox.
loop-inbox answers by replacing <session id>.answer. The answer names the ask it answers by its id, so an answer
meant for an earlier question, or sent as the loop took an answer on its terminal, never answers a later one.
A waiting loop keeps its ask in <session>.json in Paths.waiting: the question, with an id new for each question.
<session> is the worker's session id, or the ask's own id for the routing calls, which have no worker session.
The loop removes the file once the question is answered or the loop stops. The ask's state says whether the loop
waits for an answer, or has claude open for it, on the loop's own terminal or in loop-inbox. loop-inbox answers by
replacing <session>.answer, which names the ask's id. So an answer meant for an earlier question, or sent as the
loop took an answer on its terminal, never answers a later one.
/talk from loop-inbox goes in three steps, so that only one claude ever holds the worker's session:
1. loop-inbox's claim_talk sends ClaudeOpening, with its pid.
@@ -24,7 +26,7 @@ from file_writes import make_private, replace_json
POLL_SECONDS = 0.5
# Seconds loop-inbox waits for a loop to make way for its claude: ten of the loop's looks, so a loop slow for a moment still makes way.
MAKE_WAY_SECONDS = 10 * POLL_SECONDS
# What the human types, on the loop's terminal or in loop-inbox, to open claude for the ask; interrupt.py says who picked it.
# What the human types, on the loop's terminal or in loop-inbox, to open claude for the ask; picked on 2026-10-17 by a bench of three readers seated as the README's audience.
TALK = "/talk"
@@ -44,7 +46,7 @@ class Asking:
@dataclasses.dataclass(frozen=True)
class OpenOnTerminal:
"""claude is open for the ask on the loop's own terminal, and takes no answer from loop-inbox."""
"""claude is open for the ask on the loop's own terminal; the loop takes no answer from loop-inbox."""
@dataclasses.dataclass(frozen=True)
@@ -118,7 +120,7 @@ def withdraw(folder: pathlib.Path, session: str) -> Failure | None:
def waiting(folder: pathlib.Path, alive: typing.Callable[[int], bool]) -> list[Ask]:
"""The asks of loops still running, oldest first. A file that cannot be read or parsed is left out, as is one being replaced."""
"""The asks of loops still running, oldest first. A file that cannot be read or parsed is left out."""
try:
paths = sorted(folder.glob("*.json"))
except OSError:
@@ -188,7 +190,7 @@ def received(folder: pathlib.Path, ask: Ask) -> Message | None:
def claim_talk(folder: pathlib.Path, ask: Ask, pid: int, now: typing.Callable[[], float], sleep: typing.Callable[[float], None]) -> bool | Failure:
"""loop-inbox's side of /talk: asks the loop to make way for a claude that the loop-inbox whose process is pid opens for ask. True once the loop shows it has stopped reading its terminal, within MAKE_WAY_SECONDS; False where it was answered first, or stopped, or didn't make way in time."""
"""loop-inbox's side of /talk, where pid is loop-inbox's process: asks the loop to make way for the claude loop-inbox opens for ask. True once the loop shows it has stopped reading its terminal, within MAKE_WAY_SECONDS; False where it was answered first, stopped, made way for another loop-inbox, or didn't make way in time."""
if unsent := send(folder, ask, ClaudeOpening(pid)):
return unsent
deadline = now() + MAKE_WAY_SECONDS