List a loop's question in loop-inbox only while the loop holds the session's lock #396

Merged
lilleman merged 8 commits from item-252 into main 2026-10-29 18:40:24 +01:00
11 changed files with 252 additions and 63 deletions
+1 -1
View File
@@ -2,7 +2,7 @@
## Unreleased
- New tool `loop-inbox` lists the interrupts of every loop-claude on the machine, oldest first, in one terminal. Each entry shows the loop's checkout, how long it has waited and the question's first lines. Pick one to answer the question as on the loop's terminal, except that Enter alone goes back; `/talk` opens claude in loop-inbox's terminal. Of a pasted answer, only the first line is sent, and the rest is dropped. The loop takes the first answer, from its terminal or loop-inbox, so it works as before with no loop-inbox running. A loop whose claude is already open, such as for a release ready to cut or the routing calls, is listed but answered in that claude. A loop asking for its project's model, as on a project's first run, asks on its own terminal only. Link it onto `PATH` as README → Install shows.
- New tool `loop-inbox` lists the interrupts of every loop-claude on the machine, oldest first, in one terminal. Each entry shows the loop's checkout, how long it has waited and the question's first lines. Pick one to answer the question as on the loop's terminal, except that Enter alone goes back; `/talk` opens claude in loop-inbox's terminal. Of a pasted answer, only the first line is sent, and the rest is dropped. The loop takes the first answer, from its terminal or loop-inbox, so it works as before with no loop-inbox running. A loop that ends drops off the list, even one killed outright. A loop whose claude is already open, such as for a release ready to cut or the routing calls, is listed but answered in that claude. A loop asking for its project's model, as on a project's first run, asks on its own terminal only. Link it onto `PATH` as README → Install shows.
- Ctrl-C in a claude that `loop-claude` opens on its terminal, for `/talk`, a release ready to cut or the routing calls, now reaches only that claude. Before, it also stopped `loop-claude`, which closed that claude a quarter second later.
- `reading-cost` now lists the files a chunk read in the worktree `chunk-preflight` made, `<checkout>-item-<ID>`. It listed none, since no transcript command names that worktree.
- `larv-review ruling-base` now finds the last measured commit when run in a subfolder of a checkout. Before, it found no change to the comprehension history there and fell back to the merge base.
+1 -1
View File
@@ -43,7 +43,7 @@ def interrupt(question: str, answer_here: bool, session: WorkerSession, paths: P
return stop
# Keys typed while the worker ran wait on the terminal, and would answer a question no one has read, here or in claude's session, which reads them too. Of a pasted answer, the first line answers; the rest wait, and the next question drops them. A longer answer goes through TALK.
effects.discard_typed()
ask = Ask(effects.new_id(), str(session.id), session.root, question, effects.now(), effects.pid(), Asking(session.claude_command()) if answer_here else OpenOnTerminal())
ask = Ask(effects.new_id(), str(session.id), session.root, question, effects.now(), Asking(session.claude_command()) if answer_here else OpenOnTerminal())
with listed(paths.waiting, ask, effects):
answer = first_answer(ask, paths, effects) if answer_here else OpenOnTerminal()
if isinstance(answer, OpenOnTerminal | OpenInInbox):
+1 -1
View File
@@ -52,7 +52,7 @@ def raise_calls(root: pathlib.Path, checkout: str, session: str, new: list[str],
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{bullets}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."
ask = Ask(effects.new_id(), session, checkout, question, effects.now(), effects.pid(), OpenOnTerminal())
ask = Ask(effects.new_id(), session, checkout, question, effects.now(), OpenOnTerminal())
with listed(paths.waiting, ask, effects):
unstarted = hand_over(ClaudeCommand(claude_args(rung, [prompt]), str(paths.claude_dir), {}), paths, effects)
if unstarted:
+54
View File
@@ -0,0 +1,54 @@
"""The lock a loop-claude holds on its worker's session while loop-inbox lists the session's question. loop-inbox reads a held lock as a loop that still runs.
The lock is <session>.lock, held with flock, which the kernel frees however the loop ends, killed included. The lock
file stays once the loop ends: docs/decisions.md → `loop-inbox: …` says why.
"""
import contextlib
import fcntl
import pathlib
import typing
from failure import Failure
from file_writes import make_private
def lock_file(folder: pathlib.Path, session: str) -> pathlib.Path:
return folder / f"{session}.lock"
@contextlib.contextmanager
def locked(folder: pathlib.Path, session: str) -> typing.Iterator[Failure | None]:
"""Holds the session's lock while the with block runs, or yields a Failure where it cannot. loop-inbox's drop_ended takes the lock for a moment on each ask still on disk, so a loop may find it held."""
try:
make_private(folder)
except OSError as failure:
yield Failure(f"cannot make {folder}: {failure.strerror}")
return
path = lock_file(folder, session)
try:
handle = open(path, "a")
except OSError as failure:
yield Failure(f"cannot open {path}: {failure.strerror}")
return
with handle:
try:
fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
yield Failure(f"another process holds {path}")
return
except OSError as failure:
yield Failure(f"cannot lock {path}: {failure.strerror}")
return
yield None
def running(folder: pathlib.Path, session: str) -> bool:
"""Whether a loop holds the session's lock; False also where the lock file cannot be opened or locked."""
try:
with open(lock_file(folder, session)) as handle:
fcntl.flock(handle, fcntl.LOCK_SH | fcntl.LOCK_NB)
except BlockingIOError:
return True
except OSError:
return False
return False
+2 -2
View File
@@ -735,7 +735,7 @@ class Interrupt(unittest.TestCase):
checkout = Checkout(self)
folder = checkout.home / ".local" / "state" / "loop-claude"
def answered_in_inbox():
[ask] = waiting.waiting(folder, lambda pid: True)
[ask] = waiting.waiting(folder)
waiting.send(folder, ask, waiting.Typed("B"))
asked = [worker(say="Shall I use A or B?"), judge(interrupt=True, evidence="Shall I use A or B?", question="A or B?")]
run = checkout.run([*asked, worker(say="Using B."), judge(evidence="Using B.")], terminal_input="", before_typing=("Answer (", answered_in_inbox))
@@ -743,7 +743,7 @@ class Interrupt(unittest.TestCase):
self.assertEqual(run.roles(), ["worker", "judge", "worker", "judge", "worker"])
self.assertIn("Answer (/talk opens claude, Enter stops the loop): \nAnswered in loop-inbox: B\n", run.stderr)
self.assertIn("[human] B\n\nUsing B.", run.calls[3]["stdin"])
self.assertEqual(list(folder.iterdir()), [])
self.assertEqual([path for path in folder.iterdir() if path.suffix != ".lock"], [])
def test_hands_the_terminal_over_and_exits_2_when_nothing_is_typed(self):
checkout = Checkout(self)
+56 -12
View File
@@ -1,6 +1,7 @@
import ast
import contextlib
import dataclasses
import errno
import io
import json
import os
@@ -23,7 +24,7 @@ from loop_claude.project import checkout, model_choice, records
from chunk_pick import DefaultPlan, LastCut
from loop_claude.effects import Effects, POLL_SECONDS, PYTHON_TIMEOUT, run_python, say, system_effects
from claude_code import entries, reply, session
from loop_claude import escalation_mark, hand_over, paths, routing, waiting
from loop_claude import escalation_mark, hand_over, paths, routing, session_lock, waiting
from failure import Failure
from loop_claude.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished
from loop_claude.cycle import interrupt, judge, prompts, retry, run, states, worker
@@ -66,6 +67,11 @@ def human(content):
return {"type": "user", "message": {"content": content}}
def asks_and_answers(folder):
"""folder's files but the session's lock file, which stays once the loop lets go of the lock."""
return [path for path in sorted(folder.iterdir()) if path.suffix != ".lock"]
class FakeEffects:
"""Effects that record each call and answer from a script, one answer per call."""
@@ -667,12 +673,12 @@ class Interrupts(unittest.TestCase):
return answer, said.getvalue()
def asked(self):
return waiting.waiting(self.paths.waiting, lambda pid: True)
return waiting.waiting(self.paths.waiting)
def ask(self, question="Which one?", state=None):
"""The ask interrupt makes for question, in state; by default it waits for an answer, and /talk resumes the worker's session."""
resumed = hand_over.ClaudeCommand(["--model", "m", "--effort", "high", "--permission-mode", "bypassPermissions", "--resume", str(self.session.id)], str(self.home), {"LOOP_CLAUDE_WORKER_RUNG": "m at high effort"})
return waiting.Ask(ASK_ID, str(self.session.id), str(self.home), question, NOW, PID, state or waiting.Asking(resumed))
return waiting.Ask(ASK_ID, str(self.session.id), str(self.home), question, NOW, state or waiting.Asking(resumed))
def opening(self, other):
"""loop-inbox's /talk, as the loop's input sees it: loop-inbox claims the one ask listed, and the claim is the first answer."""
@@ -708,14 +714,14 @@ class Interrupts(unittest.TestCase):
for typed, why, said in ((" ", "nothing was typed", ""), (EOFError(), "the input ended", "\n")):
with self.subTest(why=why):
self.assertEqual(self.put(FakeEffects(inputs=[typed])), (Stop(2, f"the human is needed to answer the question above, but {why}"), f"\n{STAMP} Which one?\n{said}"))
self.assertEqual(list(self.paths.waiting.iterdir()), [])
self.assertEqual(asks_and_answers(self.paths.waiting), [])
def test_shows_the_question_in_loop_inbox_while_it_waits_and_only_then(self):
def typed(_):
self.assertEqual(self.asked(), [self.ask()])
return "Use B."
self.assertEqual(self.put(FakeEffects(inputs=[typed]))[0], "Use B.")
self.assertEqual(list(self.paths.waiting.iterdir()), [])
self.assertEqual(asks_and_answers(self.paths.waiting), [])
def test_takes_a_line_typed_in_loop_inbox_for_this_question_and_no_other(self):
def answered(_, other):
@@ -727,17 +733,26 @@ class Interrupts(unittest.TestCase):
fake = FakeEffects()
effects = dataclasses.replace(fake.effects(), input_or=answered)
self.assertEqual(self.put(fake, effects=effects), ("Use C.", f"\n{STAMP} Which one?\n{STAMP} Answered in loop-inbox: Use C. \n"))
self.assertEqual(list(self.paths.waiting.iterdir()), [])
self.assertEqual(asks_and_answers(self.paths.waiting), [])
def test_takes_the_answer_typed_on_its_terminal_where_loop_inbox_cannot_list_the_question(self):
self.paths.waiting.parent.mkdir(parents=True)
self.paths.waiting.write_text("")
answer, said = self.put(FakeEffects(inputs=["Use B."]))
self.assertEqual(answer, "Use B.")
self.assertIn(f"loop-inbox may still list this question: cannot remove {self.paths.waiting / f'{self.session.id}.json'}: Not a directory", said)
self.assertIn(f"loop-inbox cannot show this question: cannot make {self.paths.waiting}: File exists", said)
stop, _ = self.put(FakeEffects(inputs=["/talk"], on_terminal_claude=[0], git=[""]))
self.assertEqual(stop, Stop(2, "the human is needed to answer the question above, but the interrupt ended with nothing typed"))
def test_leaves_the_question_another_loop_lists_for_the_session_where_that_loop_holds_its_lock(self):
theirs = self.ask(question="Theirs?")
self.enterContext(session_lock.locked(self.paths.waiting, theirs.session))
waiting.publish(self.paths.waiting, theirs)
answer, said = self.put(FakeEffects(inputs=["Use B."]))
self.assertEqual(answer, "Use B.")
self.assertIn(f"loop-inbox cannot show this question: another process holds {session_lock.lock_file(self.paths.waiting, theirs.session)}", said)
self.assertEqual(self.asked(), [theirs])
def test_makes_way_for_the_claude_loop_inbox_opens_and_goes_on_once_the_human_typed_there(self):
def claude_ran(_):
# loop-inbox opens claude only once the loop lists it as open there.
@@ -747,7 +762,7 @@ class Interrupts(unittest.TestCase):
waiting.send(self.paths.waiting, self.ask(), waiting.ClaudeEnded())
fake = FakeEffects(inputs=[self.opening])
self.assertEqual(self.put(fake, effects=dataclasses.replace(fake.effects(), sleep=claude_ran)), (interrupt.Talked(), f"\n{STAMP} Which one?\n{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())), ([], []))
self.assertEqual((fake.made("claude_on_terminal"), asks_and_answers(self.paths.waiting)), ([], []))
def test_stops_when_loop_inbox_ends_its_claude_with_nothing_typed(self):
looked, slept = [], []
@@ -780,7 +795,7 @@ class Interrupts(unittest.TestCase):
fake = FakeEffects(inputs=typed, on_terminal_claude=[ran], git=[""])
self.put(fake, answer_here, question="Cut 0.4.0?")
self.assertEqual(len(fake.made("claude_on_terminal")), 1)
self.assertEqual(list(self.paths.waiting.iterdir()), [])
self.assertEqual(asks_and_answers(self.paths.waiting), [])
def test_stops_when_nothing_was_typed_in_the_session(self):
fake = FakeEffects(inputs=["/talk"], on_terminal_claude=[0], git=[""])
@@ -825,10 +840,10 @@ class RoutingCheck(unittest.TestCase):
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, "s1", "/code/log", question, NOW, PID, waiting.OpenOnTerminal())])
self.assertEqual(waiting.waiting(self.paths.waiting), [waiting.Ask(ASK_ID, "s1", "/code/log", question, NOW, waiting.OpenOnTerminal())])
return 0
self.check(FakeEffects(on_terminal_claude=[ran], git=[UNREAD, ""]))
self.assertEqual(list(self.paths.waiting.iterdir()), [])
self.assertEqual(asks_and_answers(self.paths.waiting), [])
def test_measures_once_20_cycles_have_closed_since_the_last_measurement(self):
self.chunks(5, 3)
@@ -892,7 +907,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()), [])
self.assertEqual(asks_and_answers(self.paths.waiting), [])
@unittest.skipIf(os.geteuid() == 0, "root writes into a read-only directory")
def test_says_a_figure_it_cannot_write_and_goes_on(self):
@@ -1273,6 +1288,35 @@ class Alive(unittest.TestCase):
self.assertEqual([system_effects().alive(pid) for pid in (os.getpid(), ended.pid, 1)], [True, False, True])
class SessionLock(unittest.TestCase):
def setUp(self):
self.folder = pathlib.Path(tempfile.mkdtemp())
self.addCleanup(shutil.rmtree, self.folder)
self.path = session_lock.lock_file(self.folder, "s1")
def test_a_held_lock_refuses_a_second_taker_and_reads_as_running_until_let_go(self):
self.assertFalse(session_lock.running(self.folder, "s1"))
with session_lock.locked(self.folder, "s1") as first:
self.assertIsNone(first)
with session_lock.locked(self.folder, "s1") as second:
self.assertEqual(second, Failure(f"another process holds {self.path}"))
self.assertTrue(session_lock.running(self.folder, "s1"))
self.assertFalse(session_lock.running(self.folder, "s1"))
def test_a_lock_that_cannot_be_opened_is_a_failure_and_no_loop_running(self):
self.path.mkdir()
with session_lock.locked(self.folder, "s1") as unlocked:
self.assertEqual(unlocked, Failure(f"cannot open {self.path}: Is a directory"))
self.assertFalse(session_lock.running(self.folder, "s1"))
def test_a_lock_the_kernel_refuses_is_a_failure_and_no_loop_running(self):
self.path.touch()
with unittest.mock.patch("fcntl.flock", side_effect=OSError(errno.ENOLCK, "No locks available")):
with session_lock.locked(self.folder, "s1") as unlocked:
self.assertEqual(unlocked, Failure(f"cannot lock {self.path}: No locks available"))
self.assertFalse(session_lock.running(self.folder, "s1"))
class ClaudeOnTerminal(unittest.TestCase):
def test_leaves_ctrl_c_to_claude_while_it_runs_and_returns_its_exit_code(self):
caught = []
+34 -16
View File
@@ -1,9 +1,10 @@
"""The files by which a loop-claude shows its interrupt in loop-inbox, and takes an answer typed there.
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, so a loop lists one question at a time. 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
<session> is the worker's session id, so a loop lists one question at a time. The loop holds the session's lock while it
lists the ask, and removes the ask once the question is answered or the loop stops. loop-inbox lists an ask only while
its lock is held, and removes one whose lock is free. 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.
@@ -23,6 +24,7 @@ import typing
from loop_claude.hand_over import ClaudeCommand
from loop_claude.effects import Effects, POLL_SECONDS, say
from failure import Failure
from loop_claude.session_lock import locked, running
from file_writes import make_private, replace_json
# 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.
@@ -61,7 +63,6 @@ class Ask:
question: str
# When the loop asked, in seconds since the epoch.
asked: float
pid: int
state: AskState
@@ -120,25 +121,42 @@ def shown(folder: pathlib.Path, ask: Ask, effects: Effects) -> None:
@contextlib.contextmanager
def listed(folder: pathlib.Path, ask: Ask, effects: Effects) -> typing.Iterator[None]:
"""Lists ask in loop-inbox while the with block runs, then takes it out, with any answer. A failure to take it out only warns: loop-inbox drops the ask once the loop's process ends."""
shown(folder, ask, effects)
try:
yield
finally:
if unwithdrawn := withdraw(folder, ask.session):
say(f"loop-inbox may still list this question: {unwithdrawn.reason}", effects)
"""Lists ask in loop-inbox while the with block runs, then takes it out, with any answer. A failure to list it only warns: the question is still answered on the loop's terminal."""
with locked(folder, ask.session) as unlocked:
if unlocked:
say(f"loop-inbox cannot show this question: {unlocked.reason}", effects)
yield
return
shown(folder, ask, effects)
try:
yield
finally:
# An ask this fails to remove is left to loop-inbox, which stops listing it once the lock is let go, and removes it.
withdraw(folder, ask.session)
def waiting(folder: pathlib.Path, alive: typing.Callable[[int], bool]) -> list[Ask]:
def waiting(folder: pathlib.Path) -> list[Ask]:
"""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:
return []
asks = [ask for path in paths if (ask := read_ask(path)) and alive(ask.pid)]
asks = [ask for path in paths if (ask := read_ask(path)) and running(folder, ask.session)]
return sorted(asks, key=lambda ask: ask.asked)
def drop_ended(folder: pathlib.Path) -> None:
"""Removes each ask, with any answer, whose session's lock no loop holds: a loop that was killed leaves its ask behind. It removes one while holding the lock, so a loop that lists a new ask meanwhile keeps it. An ask it cannot remove stays on disk, and waiting leaves it out all the same."""
try:
paths = list(folder.glob("*.json"))
except OSError:
return
for path in paths:
with locked(folder, path.stem) as unlocked:
if not unlocked:
withdraw(folder, path.stem)
def read_ask(path: pathlib.Path) -> Ask | None:
"""The ask in path; None where a field has the wrong type, or names another session than path does."""
try:
@@ -147,8 +165,7 @@ def read_ask(path: pathlib.Path) -> Ask | None:
except (OSError, ValueError, TypeError, KeyError):
return None
texts = all(isinstance(text, str) for text in (ask.id, ask.session, ask.root, ask.question))
# A pid of 0 or below would name a process group to alive.
return ask if texts and ask.session == path.stem and isinstance(ask.asked, int | float) and isinstance(ask.pid, int) and ask.pid > 0 else None
return ask if texts and ask.session == path.stem and isinstance(ask.asked, int | float) else None
def ask_state(data: object) -> AskState:
@@ -192,7 +209,8 @@ def received(folder: pathlib.Path, ask: Ask) -> Message | None:
match data:
case {"kind": "Typed", "text": str(text)}:
return Typed(text)
case {"kind": "ClaudeOpening", "pid": int(pid)}:
# alive is always True for a pid of 0 or below, which names a process group or every process, so the loop would wait for claude forever.
case {"kind": "ClaudeOpening", "pid": int(pid)} if pid > 0:
return ClaudeOpening(pid)
case {"kind": "ClaudeEnded"}:
return ClaudeEnded()
+8 -6
View File
@@ -33,11 +33,12 @@ import sys
import typing
from loop_inbox.inbox import Answering, answering_lines, BACKSPACE, ENTER, ESCAPE, fitted, Listing, listing_lines, Open, pressed, Quit, Screen, Send
from loop_claude.waiting import Ask, ask_file, Asking, claim_talk, ClaudeEnded, MAKE_WAY_SECONDS, read_ask, send, Typed, waiting
from loop_claude.waiting import Ask, ask_file, Asking, claim_talk, ClaudeEnded, drop_ended, MAKE_WAY_SECONDS, read_ask, send, Typed, waiting
from loop_claude.effects import Effects, system_effects
from failure import Failure
from loop_claude.hand_over import hand_over
from loop_claude.paths import Paths, paths_from
from loop_claude.session_lock import running
USAGE = "usage: loop-inbox"
# Milliseconds between refreshes of the list while no key is pressed.
@@ -69,7 +70,8 @@ def run(window: curses.window, screen_off: typing.Callable[[], typing.ContextMan
window.timeout(REFRESH_MS)
screen: Screen = Listing()
while True:
screen = entered(screen, refreshed(screen, folder, effects.alive), effects)
drop_ended(folder)
screen = entered(screen, refreshed(screen, folder), effects)
draw(window, screen, effects)
try:
key = window.get_wch()
@@ -100,11 +102,11 @@ def key_name(key: str | int) -> str:
return KEYS.get(key, key if isinstance(key, str) else "")
def refreshed(screen: Screen, folder: pathlib.Path, alive: typing.Callable[[int], bool]) -> Screen:
def refreshed(screen: Screen, folder: pathlib.Path) -> Screen:
"""screen with the loops as they wait now, unless the human is typing a number; a question that no longer waits leaves the answer screen."""
match screen:
case Listing(_, "", note):
return Listing(tuple(waiting(folder, alive)), "", note)
return Listing(tuple(waiting(folder)), "", note)
case Answering(ask) if not still_waits(folder, ask):
return Listing(note=no_longer_waits(ask))
return screen
@@ -125,9 +127,9 @@ def draw(window: curses.window, screen: Screen, effects: Effects) -> None:
def still_waits(folder: pathlib.Path, ask: Ask) -> bool:
"""Whether ask still waits for an answer from loop-inbox."""
"""Whether ask's loop still runs and still waits for an answer from loop-inbox."""
now = read_ask(ask_file(folder, ask.session))
return now is not None and now.id == ask.id and isinstance(now.state, Asking)
return now is not None and now.id == ask.id and isinstance(now.state, Asking) and running(folder, ask.session)
def no_longer_waits(ask: Ask) -> str:
+83 -23
View File
@@ -4,6 +4,7 @@ import io
import json
import pathlib
import shutil
import subprocess
import sys
import tempfile
import unittest
@@ -17,21 +18,28 @@ from loop_claude.hand_over import ClaudeCommand
from failure import Failure
from loop_inbox import inbox, main
from loop_claude.paths import paths_from
from loop_claude import session_lock
from loop_claude.effects import system_effects
from loop_claude import waiting
ASKING = Asking(ClaudeCommand(["--resume", "s"], "/c", {}))
# The pids of a running loop, of this loop-inbox, and of a loop that has stopped.
LOOP, INBOX, GONE = 4242, 4343, 13
# The pid of this loop-inbox.
INBOX = 4343
ANSWERED_ON_TERMINAL = object()
def alive(pid):
return pid != GONE
def asked(session, root, question="Which one?", at=100.0, state=ASKING):
return Ask(f"ask-{session}", session, root, question, at, state)
def asked(session, root, question="Which one?", at=100.0, pid=LOOP, state=ASKING):
return Ask(f"ask-{session}", session, root, question, at, pid, state)
def loops_hold(test, folder, *sessions):
"""Holds each session's lock until the test ends, as the loop that lists its ask does."""
for session in sessions:
test.enterContext(session_lock.locked(folder, session))
def asks_and_answers(folder):
return sorted(path.name for path in folder.iterdir() if path.suffix != ".lock")
def keyed(screen, *keys):
@@ -82,10 +90,11 @@ class Answers(unittest.TestCase):
def setUp(self):
self.folder = pathlib.Path(tempfile.mkdtemp())
self.addCleanup(shutil.rmtree, self.folder)
loops_hold(self, self.folder, "s1", "s2")
def answer(self, number, text):
"""Picks loop number from the list as it waits now and types text to it, as the human does in loop-inbox."""
action = keyed(Listing(tuple(waiting.waiting(self.folder, alive))), *number, ENTER, *text, ENTER)
action = keyed(Listing(tuple(waiting.waiting(self.folder))), *number, ENTER, *text, ENTER)
self.assertIsInstance(action, Send)
return main.sent(self.folder, action.ask, action.text)
@@ -101,23 +110,23 @@ class Answers(unittest.TestCase):
log, bender = asked("s1", "/code/log", at=100), asked("s2", "/code/bender", at=200)
for ask in (log, bender):
waiting.publish(self.folder, ask)
picked = keyed(Listing(tuple(waiting.waiting(self.folder, alive))), "1", ENTER, "A", ENTER)
picked = keyed(Listing(tuple(waiting.waiting(self.folder))), "1", ENTER, "A", ENTER)
# log is answered on its terminal before the answer typed here is sent; bender is now first.
waiting.withdraw(self.folder, "s1")
self.assertEqual(main.sent(self.folder, picked.ask, picked.text), "/code/log no longer waits for that answer: it was answered elsewhere, or stopped.")
self.assertEqual(sorted(path.name for path in self.folder.iterdir()), ["s2.json"])
self.assertEqual(asks_and_answers(self.folder), ["s2.json"])
def test_the_list_shows_the_loops_still_waiting_and_keeps_its_note(self):
log = asked("s1", "/code/log")
for ask in (log, asked("s2", "/code/bender", pid=GONE)):
for ask in (log, asked("s3", "/code/bender")):
waiting.publish(self.folder, ask)
self.assertEqual(main.refreshed(Listing(note="Sent to /a."), self.folder, alive), Listing((log,), "", "Sent to /a."))
self.assertEqual(main.refreshed(Listing(note="Sent to /a."), self.folder), Listing((log,), "", "Sent to /a."))
def test_a_number_picks_the_loop_it_had_when_the_human_began_typing_it(self):
log, bender = asked("s1", "/code/log", at=100), asked("s2", "/code/bender", at=200)
typing = keyed(Listing((log, bender)), "2")
waiting.publish(self.folder, bender)
self.assertEqual(main.refreshed(typing, self.folder, alive), typing)
self.assertEqual(main.refreshed(typing, self.folder), typing)
self.assertEqual(inbox.pressed(typing, ENTER), Answering(bender))
def test_a_loop_whose_claude_is_open_takes_no_answer_here(self):
@@ -128,9 +137,14 @@ class Answers(unittest.TestCase):
def test_an_answer_screen_leaves_once_its_loop_no_longer_waits(self):
ask = asked("s1", "/code/log")
waiting.publish(self.folder, ask)
self.assertEqual(main.refreshed(Answering(ask, "Us"), self.folder, alive), Answering(ask, "Us"))
self.assertEqual(main.refreshed(Answering(ask, "Us"), self.folder), Answering(ask, "Us"))
waiting.publish(self.folder, dataclasses.replace(ask, id="a later ask"))
self.assertEqual(main.refreshed(Answering(ask, "Us"), self.folder, alive), Listing(note="/code/log no longer waits for that answer: it was answered elsewhere, or stopped."))
self.assertEqual(main.refreshed(Answering(ask, "Us"), self.folder), Listing(note="/code/log no longer waits for that answer: it was answered elsewhere, or stopped."))
def test_an_answer_screen_leaves_once_its_loop_ends_though_its_ask_stays_on_disk(self):
ask = asked("s3", "/code/bender")
waiting.publish(self.folder, ask)
self.assertEqual(main.refreshed(Answering(ask, "Us"), self.folder), Listing(note="/code/bender no longer waits for that answer: it was answered elsewhere, or stopped."))
def claim(self, ask, loop_does):
"""claim_talk's result for ask, and the seconds it waited; loop_does acts as the loop at claim_talk's first wait."""
@@ -176,6 +190,7 @@ class Opens(unittest.TestCase):
self.addCleanup(shutil.rmtree, home)
self.paths = paths_from(home)
self.ask = asked("s1", "/code/log")
loops_hold(self, self.paths.waiting, "s1")
waiting.publish(self.paths.waiting, self.ask)
def open(self, claude, loop_shows=OpenInInbox(INBOX)):
@@ -215,7 +230,7 @@ class Opens(unittest.TestCase):
def test_opens_no_claude_and_sends_nothing_to_a_loop_that_no_longer_waits(self):
waiting.withdraw(self.paths.waiting, "s1")
self.assertEqual(self.open(never_opens), "/code/log no longer waits for that answer: it was answered elsewhere, or stopped.")
self.assertEqual(list(self.paths.waiting.iterdir()), [])
self.assertEqual(asks_and_answers(self.paths.waiting), [])
def test_tells_the_loop_when_claude_is_interrupted(self):
def interrupted(args, cwd, env):
@@ -231,6 +246,7 @@ class Typing(unittest.TestCase):
with tempfile.TemporaryDirectory() as home:
paths = paths_from(pathlib.Path(home))
log, bender = asked("s1", "/code/log", at=100), asked("s2", "/code/bender", at=200)
loops_hold(self, paths.waiting, "s1", "s2")
for ask in (log, bender):
waiting.publish(paths.waiting, ask)
def answered_on_terminal():
@@ -238,7 +254,7 @@ class Typing(unittest.TestCase):
window = Window(answered_on_terminal if key is ANSWERED_ON_TERMINAL else key for key in keys)
def made_way(seconds):
waiting.publish(paths.waiting, dataclasses.replace(log, state=OpenInInbox(INBOX)))
effects = dataclasses.replace(system_effects(), alive=alive, claude_on_terminal=lambda args, cwd, env: 0, discard_typed=window.drop_typed, git=lambda *args, **kwargs: Failure("not a checkout"), now=lambda: 0.0, pid=lambda: INBOX, sleep=made_way)
effects = dataclasses.replace(system_effects(), claude_on_terminal=lambda args, cwd, env: 0, discard_typed=window.drop_typed, git=lambda *args, **kwargs: Failure("not a checkout"), now=lambda: 0.0, pid=lambda: INBOX, sleep=made_way)
with self.assertRaises(OutOfKeys), contextlib.redirect_stderr(io.StringIO()):
main.run(window, contextlib.nullcontext, paths, effects)
return waiting.answered(paths.waiting, log), waiting.answered(paths.waiting, bender)
@@ -294,27 +310,71 @@ class Keys(unittest.TestCase):
class Waiting(unittest.TestCase):
def test_lists_the_loops_still_running_oldest_first_and_skips_a_file_it_cannot_read(self):
with tempfile.TemporaryDirectory() as folder:
late, early, stopped = asked("s1", "/a", at=300, state=OpenInInbox(7)), asked("s2", "/b", at=100), asked("s3", "/c", at=50, pid=GONE, state=OpenOnTerminal())
late, early, stopped = asked("s1", "/a", at=300, state=OpenInInbox(7)), asked("s2", "/b", at=100), asked("s3", "/c", at=50, state=OpenOnTerminal())
loops_hold(self, pathlib.Path(folder), "s1", "s2")
for ask in (late, early, stopped):
waiting.publish(pathlib.Path(folder), ask)
pathlib.Path(folder, "s4.json").write_text("{")
pathlib.Path(folder, "s5.json").write_text('{"pid": 0}')
pathlib.Path(folder, "s5.json").write_text('{"question": "Which one?"}')
pathlib.Path(folder, "s6.json").write_text(pathlib.Path(folder, "s2.json").read_text().replace('"Asking"', '"Waiting"'))
self.assertEqual(waiting.waiting(pathlib.Path(folder), alive), [early, late])
self.assertEqual(waiting.waiting(pathlib.Path(folder), lambda pid: True), [stopped, early, late])
self.assertEqual(waiting.waiting(pathlib.Path(folder)), [early, late])
def test_drops_and_removes_the_ask_a_killed_loop_left_behind(self):
with tempfile.TemporaryDirectory() as temp:
folder = pathlib.Path(temp)
lists_and_waits = "import pathlib, sys, time\nfrom test_loop_inbox import asked, system_effects, waiting\nwith waiting.listed(pathlib.Path(sys.argv[1]), asked('s1', '/a'), system_effects()):\n\tprint(flush=True); time.sleep(60)"
loop = subprocess.Popen([sys.executable, "-c", lists_and_waits, temp], cwd=pathlib.Path(__file__).parent, stdout=subprocess.PIPE)
self.addCleanup(loop.wait)
self.addCleanup(loop.kill)
loop.stdout.readline()
waiting.send(folder, asked("s1", "/a"), Typed("Use A."))
self.assertEqual(waiting.waiting(folder), [asked("s1", "/a")])
# SIGKILL runs none of the loop's cleanup.
loop.kill()
loop.wait()
self.assertEqual(waiting.waiting(folder), [])
waiting.drop_ended(folder)
self.assertEqual(asks_and_answers(folder), [])
def test_loop_inbox_removes_a_killed_loops_ask_and_answer_as_it_looks(self):
with tempfile.TemporaryDirectory() as home:
paths = paths_from(pathlib.Path(home))
ask = asked("s1", "/a")
waiting.publish(paths.waiting, ask)
waiting.send(paths.waiting, ask, Typed("Use A."))
main.run(Window("q"), contextlib.nullcontext, paths, system_effects())
self.assertEqual(asks_and_answers(paths.waiting), [])
def test_removes_only_the_asks_and_answers_whose_loop_has_ended(self):
with tempfile.TemporaryDirectory() as temp:
folder = pathlib.Path(temp)
loops_hold(self, folder, "s1")
for ask in (asked("s1", "/a"), asked("s2", "/b")):
waiting.publish(folder, ask)
waiting.send(folder, ask, Typed("Use A."))
waiting.drop_ended(folder)
self.assertEqual(asks_and_answers(folder), ["s1.answer", "s1.json"])
def test_a_talk_claim_from_pid_0_or_below_is_no_answer_since_it_would_name_a_process_group(self):
with tempfile.TemporaryDirectory() as temp:
ask = asked("s1", "/a")
for pid in (0, -1):
with self.subTest(pid=pid):
waiting.send(pathlib.Path(temp), ask, waiting.ClaudeOpening(pid))
self.assertIsNone(waiting.answered(pathlib.Path(temp), ask))
def test_leaves_out_an_ask_with_a_field_of_the_wrong_type_or_value(self):
with tempfile.TemporaryDirectory() as temp:
path = waiting.ask_file(pathlib.Path(temp), "s1")
waiting.publish(path.parent, asked("s1", "/a", pid=1))
waiting.publish(path.parent, asked("s1", "/a"))
good = json.loads(path.read_text())
self.assertEqual(waiting.read_ask(path), asked("s1", "/a", pid=1))
self.assertEqual(waiting.read_ask(path), asked("s1", "/a"))
for field, value in (
("id", 1),
("session", "s2"),
("root", None),
("question", 3),
("pid", 0),
("asked", "noon"),
("state", {"kind": "Asking", "talk": {"args": [1], "cwd": "/c", "env": {}}}),
("state", {"kind": "Asking", "talk": {"args": [], "cwd": "/c", "env": {"A": 1}}}),
):
+1
View File
@@ -109,6 +109,7 @@ Valid while cache reads cost a twentieth of input and Claude Code's compaction k
- While claude is open for a question, as for a release ready to cut, the routing calls or a `/talk`, loop-inbox lists the loop and where claude is open, but takes no answer for it.
- loop-inbox runs the claude command the loop wrote, `bypassPermissions` included, so that claude runs in the same sandbox as the loop. Since loop-inbox runs a command read from a file, the folder is private to the user.
- Files, read by polling, need no daemon and only the standard library, and a loop with no loop-inbox running is answered on its terminal as before.
- loop-inbox lists a question only while its loop holds the session's lock file with flock, and removes a question whose lock is free. The kernel frees the lock however the loop ends, killed included. A process id could not tell a running loop from a killed one: on 2026-10-29 this machine's kernel handed out its 32,768 ids again every 30 to 75 minutes, so a killed loop's question came back whenever another process got its id. The lock file stays once the loop ends, one per project: removing it while another process has it open could let loop-inbox lock a file no loop holds. Todo item 252.
A bench of three readers seated as the README's audience picked the name `loop-inbox`, 3–0.
+11 -1
View File
@@ -6,7 +6,7 @@
`Bar = 0.1`
`Next ID = 252`
`Next ID = 255`
## Items
@@ -15,7 +15,9 @@
| 226 | 0.5.0 | | question | **Answer whether rule-hook's `run-heavy` rule should also catch a mutation run or docker build behind `uv run`, `poetry run`, `python3 -m`, `sudo`, `docker image build` and `docker compose up --build`, or narrow the `machine load:` decision's wording.** | 2 | 2 | 3 | 5 | 3 | 1.2 by 2, 1.5 by 2 | 4.0 |
| 248 | 0.5.0 | | question | **Answer whether the `rule-hook:` decision should name every rule that takes no override, `repeat-read`, `reviewer-report` and `reviewer-rung`, with each one's reason.** | 1 | 2 | 1 | 2 | 1 | 1.2 by 2 | 3.3 |
| 250 | 0.5.0 | | | **Move the repeat-read rule's transcript, mtime and file reads from `bin/rule_hook/main.py` into `bin/rule_hook/repeat_read.py`, behind one `*_breaches` entry point like the other rules, and name the tuple `results_on` returns.** | 2 | 1 | 3 | 4 | 3 | code health by 3 | 13.5 |
| 253 | 0.5.0 | | principle | **Group `bin/loop_claude/waiting.py`'s 29 top-level names, such as the ask's states, the answers and the /talk handshake, so each level holds about seven.** | 2 | 1 | 3 | 4 | 3 | code health by 3 | 13.5 |
| 235 | 0.5.0 | | decision | **Compare the first 20 chunks whose worker ran under the 200k compaction window with the 20 before them, on review rounds past each pass's first, unfinished verdicts, 🔴, 🟡 and misread findings, dollars and hours per chunk, and file an item where any rose.** | 1 | 2 | 1 | 2 | 2 | 1.1 by 2, 1.4 by 3 | 6.8 |
| 254 | 0.5.0 | | principle | **Store when a loop asked as an ISO UTC datetime in loop-inbox's ask files.** | 1 | 1 | 2 | 2 | 2 | code health by 1 | 6.0 |
| 167 | 0.5.0 | | | **Refuse a `/security-review` or `/claude-security` Skill call below the project's rung, as rule-hook refuses such an Agent call.** | 3 | 2 | 3 | 6 | 2 | 1.1 by 4 | 5.6 |
| 6 | 0.5.0 | | decision | **Move what `loop-claude` writes out of `~/.claude.json`, and ask the human about each write that must stay.** | 3 | 3 | 3 | 7 | 3 | 1.1 by 5 | 5.3 |
| 240 | 0.5.0 | | decision | **Give loop-claude's worker prompt the reading rule "never read more than 80 lines of a file at once, nor take a tool output over 3,000 characters into your context", and keep it only where the 20 chunks after it hold the 20 before's review rounds, unfinished verdicts, 🔴, 🟡 and misread findings, dollars and hours per chunk.** | 1 | 2 | 3 | 4 | 2 | 1.4 by 3 | 4.0 |
@@ -88,10 +90,18 @@ Filed from PR #387's architecture round 1. The decision's 2026-10-16 addendum sa
Found by the paired ruling of PR #387: all four seats ruled Locality worse at `read_breaches`, `modified` and `first_lines` in `main.py`. The rule's reads sit there while its logic sits in `repeat_read.py`, and two contracts cross the seam: `modified` must stamp the mtime as the transcript stamps entries, since `shown_lines` compares the two as text, and `first_lines` must read one line past the last shown one, which `repeat_breaches` needs. Make these places easier to read: keep both contracts inside `repeat_read.py`, the way `todo_check.py` and `reviewer_report.py` do their own reads. Replace `results_on`'s positional four-part tuple with a named type, and rename `repeat_read.written`, which names a path while `written` in `main.py` names the text that may carry an override marker.
### 253. Group `bin/loop_claude/waiting.py`'s 29 top-level names, such as the ask's states, the answers and the /talk handshake, so each level holds about seven.
Found by the principles review of item 252, against the technical principles' "about seven things per level". A split by role is one way: the ask's file and states, the answers loop-inbox sends, and the /talk handshake, `claim_talk` and `make_way`.
### 235. Compare the first 20 chunks whose worker ran under the 200k compaction window with the 20 before them, on review rounds past each pass's first, unfinished verdicts, 🔴, 🟡 and misread findings, dollars and hours per chunk, and file an item where any rose.
`docs/decisions.md` → `loop-claude: the worker's claude compacts its context before it fills a 200k window…` expects a saving of about 6% of all spend with no rise in the other figures. Measure from loop-claude's archive as that decision did: rounds past each pass's first and the 🔴, 🟡 and misread counts from the round commit titles, unfinished verdicts from the outcomes files, hours from the worker's first message to its last, and dollars at list prices, cache reads included, from the chunk's `cost-state` entry, which counts the compaction calls that no message's usage records; the routing figures now put such dollars in. A chunk ran under the window when its first worker started after that decision merged.
### 254. Store when a loop asked as an ISO UTC datetime in loop-inbox's ask files.
Found by the principles review of item 252, against the technical principles' rule that timestamps are ISO UTC. `Ask.asked` in `bin/loop_claude/waiting.py` is a float of seconds since the epoch, which `publish` writes to `<session>.json` and `read_ask` reads back. loop-inbox shows it as a local time and a wait, so change the code that shows it too.
### 167. Refuse a `/security-review` or `/claude-security` Skill call below the project's rung, as rule-hook refuses such an Agent call.
rule-hook checks Agent calls (item 163) but no Skill calls. A worker that invokes `/security-review` in its own context, instead of in a subagent, runs the pass on its own rung, and nothing blocks it. Check Skill calls too: `breaches_of` in bin/rule_hook/main.py takes a Skill call whose skill is `security-review` or `claude-security` as a review launch, and settings.json's PreToolUse matcher gains Skill. Found by the systems-architect's review of PR #295.