From 5df105033cc0107645c8f0ea02b0c22e7c0f5284 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 29 Oct 2026 18:14:44 +0100 Subject: [PATCH] List a loop's question in loop-inbox only while the loop holds the session's lock, so a killed loop's question stays gone whatever its pid now names --- CHANGELOG.md | 2 +- bin/loop_claude/cycle/interrupt.py | 2 +- bin/loop_claude/loop/routing_check.py | 2 +- bin/loop_claude/test_black_box.py | 4 +- bin/loop_claude/test_loop_claude.py | 27 ++++---- bin/loop_claude/waiting.py | 90 ++++++++++++++++++++++----- bin/loop_inbox/main.py | 12 ++-- bin/loop_inbox/test_loop_inbox.py | 78 ++++++++++++++++------- docs/decisions.md | 1 + todo.md | 5 -- 10 files changed, 157 insertions(+), 66 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0836a21b..31ba132f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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, `-item-`. 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. diff --git a/bin/loop_claude/cycle/interrupt.py b/bin/loop_claude/cycle/interrupt.py index 5676ccfd..9328e93f 100644 --- a/bin/loop_claude/cycle/interrupt.py +++ b/bin/loop_claude/cycle/interrupt.py @@ -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): diff --git a/bin/loop_claude/loop/routing_check.py b/bin/loop_claude/loop/routing_check.py index 92ac8384..5f6453f9 100644 --- a/bin/loop_claude/loop/routing_check.py +++ b/bin/loop_claude/loop/routing_check.py @@ -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: diff --git a/bin/loop_claude/test_black_box.py b/bin/loop_claude/test_black_box.py index dd7b3bfb..8dcc3289 100644 --- a/bin/loop_claude/test_black_box.py +++ b/bin/loop_claude/test_black_box.py @@ -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) diff --git a/bin/loop_claude/test_loop_claude.py b/bin/loop_claude/test_loop_claude.py index c8bbe960..d6d64ac2 100644 --- a/bin/loop_claude/test_loop_claude.py +++ b/bin/loop_claude/test_loop_claude.py @@ -66,6 +66,11 @@ def human(content): return {"type": "user", "message": {"content": content}} +def asks_and_answers(folder): + """What loop-inbox could still read in folder; the session's lock file stays once the loop lets it go.""" + 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 +672,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 +713,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,14 +732,14 @@ 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")) @@ -747,7 +752,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 +785,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 +830,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 +897,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): diff --git a/bin/loop_claude/waiting.py b/bin/loop_claude/waiting.py index 4f642332..e4b90400 100644 --- a/bin/loop_claude/waiting.py +++ b/bin/loop_claude/waiting.py @@ -1,11 +1,14 @@ """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 .json in Paths.waiting: the question, with an id new for each question. - 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 .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. + is the worker's session id, so a loop lists one question at a time. The loop holds .lock with flock +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 kernel frees a lock however its process ends, where +a process id the system may hand out again cannot tell a loop that runs from one that was killed. The lock file stays +once the loop ends: docs/decisions.md → `loop-inbox: …` says why. 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 +.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. @@ -16,6 +19,7 @@ never answers a later one. """ import contextlib import dataclasses +import fcntl import json import pathlib import typing @@ -61,7 +65,6 @@ class Ask: question: str # When the loop asked, in seconds since the epoch. asked: float - pid: int state: AskState @@ -94,6 +97,10 @@ def answer_file(folder: pathlib.Path, session: str) -> pathlib.Path: return folder / f"{session}.answer" +def lock_file(folder: pathlib.Path, session: str) -> pathlib.Path: + return folder / f"{session}.lock" + + def publish(folder: pathlib.Path, ask: Ask) -> Failure | None: try: make_private(folder) @@ -120,25 +127,74 @@ 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) + """Lists ask in loop-inbox while the with block runs, then takes it out, with any answer. A failure only warns: the question is still answered on the loop's terminal, and loop-inbox drops the ask once the loop's process ends.""" + 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: + if unwithdrawn := withdraw(folder, ask.session): + say(f"loop-inbox may still list this question: {unwithdrawn.reason}", effects) + + +@contextlib.contextmanager +def locked(folder: pathlib.Path, session: str) -> typing.Iterator[Failure | None]: + """Holds the session's lock while the with block runs; a Failure where it cannot. loop-inbox holds it only for as long as it takes to remove an ask, so a loop meets it held only while another loop lists a question for the session.""" try: - yield - finally: - if unwithdrawn := withdraw(folder, ask.session): - say(f"loop-inbox may still list this question: {unwithdrawn.reason}", effects) + 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 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 running(folder: pathlib.Path, session: str) -> bool: + """Whether the loop that listed the session's ask still holds its lock. Where it doesn't, removes the ask and any answer while holding the lock, so a loop that lists a new ask meanwhile keeps it.""" + try: + handle = open(lock_file(folder, session), "a") + except OSError: + return False + with handle: + try: + fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB) + except BlockingIOError: + return True + except OSError: + return False + # A failure to remove leaves the ask out all the same; the next look tries again. + withdraw(folder, session) + return False + + 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 +203,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 +247,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)}: + # A pid of 0 or below would name a process group to the loop's alive. + case {"kind": "ClaudeOpening", "pid": int(pid)} if pid > 0: return ClaudeOpening(pid) case {"kind": "ClaudeEnded"}: return ClaudeEnded() diff --git a/bin/loop_inbox/main.py b/bin/loop_inbox/main.py index ece26291..416d0f37 100644 --- a/bin/loop_inbox/main.py +++ b/bin/loop_inbox/main.py @@ -33,7 +33,7 @@ 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, MAKE_WAY_SECONDS, read_ask, running, send, Typed, waiting from loop_claude.effects import Effects, system_effects from failure import Failure from loop_claude.hand_over import hand_over @@ -69,7 +69,7 @@ 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) + screen = entered(screen, refreshed(screen, folder), effects) draw(window, screen, effects) try: key = window.get_wch() @@ -100,11 +100,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 +125,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 still waits for an answer from loop-inbox, from a loop that still runs.""" 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: diff --git a/bin/loop_inbox/test_loop_inbox.py b/bin/loop_inbox/test_loop_inbox.py index 59e9ae5b..ebe04b57 100644 --- a/bin/loop_inbox/test_loop_inbox.py +++ b/bin/loop_inbox/test_loop_inbox.py @@ -4,6 +4,7 @@ import io import json import pathlib import shutil +import subprocess import sys import tempfile import unittest @@ -21,17 +22,23 @@ 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 running(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(waiting.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 +89,11 @@ class Answers(unittest.TestCase): def setUp(self): self.folder = pathlib.Path(tempfile.mkdtemp()) self.addCleanup(shutil.rmtree, self.folder) + running(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 +109,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 +136,9 @@ 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 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 +184,7 @@ class Opens(unittest.TestCase): self.addCleanup(shutil.rmtree, home) self.paths = paths_from(home) self.ask = asked("s1", "/code/log") + running(self, self.paths.waiting, "s1") waiting.publish(self.paths.waiting, self.ask) def open(self, claude, loop_shows=OpenInInbox(INBOX)): @@ -215,7 +224,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 +240,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) + running(self, paths.waiting, "s1", "s2") for ask in (log, bender): waiting.publish(paths.waiting, ask) def answered_on_terminal(): @@ -238,7 +248,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 +304,51 @@ 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()) + running(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, "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_of_a_loop_killed_before_it_took_it_out_whatever_its_pid_now_names(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, and the system may hand its pid to another process at once. + loop.kill() + loop.wait() + self.assertEqual(waiting.waiting(folder), []) + self.assertEqual(asks_and_answers(folder), []) + + 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}}}), ): diff --git a/docs/decisions.md b/docs/decisions.md index db157bc8..96a17d33 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -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: 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. diff --git a/todo.md b/todo.md index f8092eb5..5e7dad08 100644 --- a/todo.md +++ b/todo.md @@ -12,7 +12,6 @@ | ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score | |---|---|---|---|---|---|---|---|---|---|---|---| -| 252 | 0.4.0 | | defect | **Have loop-inbox list a loop's question only while that loop holds a lock on it, so a killed loop's question stays gone when the system hands its process id to another process.** | 2 | 2 | 2 | 4 | 3 | 1 by 3 | 3.3 | | 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 | @@ -77,10 +76,6 @@ ## Details -### 252. Have loop-inbox list a loop's question only while that loop holds a lock on it, so a killed loop's question stays gone when the system hands its process id to another process. - -lilleman asked on 2026-10-29 to hold 0.4.0 for it. loop-inbox lists an ask while `os.kill(pid, 0)` finds the loop's pid, and the loop removes its ask in a `finally` that a SIGKILL, SIGHUP or out-of-memory kill skips. This machine's `pid_max` is 32768, and on 2026-10-29 its process ids came round again every 30 to 75 minutes, faster under load. So a killed loop's question comes back in the list whenever another process gets its id: an answer to it reaches no loop, and `/talk` on it fails after 5 s. Done when a loop killed outright drops off the list, and its ask and answer files are removed, whatever its process id names now. - ### 226. 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. Found by review of PR #370. Today `uv run mutmut run`, `poetry run mutmut run`, `python3 -m mutmut run`, `sudo docker build .`, `docker image build .` and `docker compose up --build` pass the rule, which `docs/decisions.md` → `machine load: …` and `RULES["run-heavy"]` describe as blocking docker builds and mutation runs. The rule's own text says a gate script isn't checked since no program can tell it from a light one, so the human decides where the line sits. Say what the rule's "checked" text promises either way. Where the answer widens the rule, the change touches `heavy` in `bin/rule_hook/heavy_command.py`, which the comprehension seats found hard: make it easier to read.