From 93d413f5f36fdebfa2eacf676ca5f93b289c4efe Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 29 Oct 2026 18:13:54 +0100 Subject: [PATCH 1/8] File item 252: drop a killed loop's question from loop-inbox whatever its pid now names --- todo.md | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/todo.md b/todo.md index 49438188..f8092eb5 100644 --- a/todo.md +++ b/todo.md @@ -6,12 +6,13 @@ `Bar = 0.1` -`Next ID = 252` +`Next ID = 253` ## Items | 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 | @@ -76,6 +77,10 @@ ## 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. -- 2.52.0 From 5df105033cc0107645c8f0ea02b0c22e7c0f5284 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 29 Oct 2026 18:14:44 +0100 Subject: [PATCH 2/8] 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. -- 2.52.0 From fb22bc33dbfbf7e92fcc2092ccdbca511101d4e7 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 29 Oct 2026 18:26:44 +0100 Subject: [PATCH 3/8] =?UTF-8?q?Answer=20principles=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=204=20=F0=9F=9F=A1=20(0=20misread);=20move=20the?= =?UTF-8?q?=20session=20lock=20into=20its=20own=20module,=20split=20loop-i?= =?UTF-8?q?nbox's=20look=20from=20its=20removal,=20test=20every=20lock=20b?= =?UTF-8?q?ranch,=20file=20items=20253=20and=20254?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin/loop_claude/session_lock.py | 55 +++++++++++++++++++++++ bin/loop_claude/test_loop_claude.py | 32 +++++++++++++- bin/loop_claude/waiting.py | 68 +++++++---------------------- bin/loop_inbox/main.py | 4 +- bin/loop_inbox/test_loop_inbox.py | 31 ++++++++++--- todo.md | 12 ++++- 6 files changed, 139 insertions(+), 63 deletions(-) create mode 100644 bin/loop_claude/session_lock.py diff --git a/bin/loop_claude/session_lock.py b/bin/loop_claude/session_lock.py new file mode 100644 index 00000000..f6529535 --- /dev/null +++ b/bin/loop_claude/session_lock.py @@ -0,0 +1,55 @@ +"""The lock a loop-claude holds on its worker's session while loop-inbox lists its question, which tells loop-inbox the loop still runs. + +The lock is .lock, held with flock. The kernel frees it however the loop ends, killed included, 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. +""" +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; a Failure where it cannot. loop-inbox holds it for a moment where it finds the session's question still listed, so a loop starting after another was killed may meet 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 cannot be read.""" + 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 diff --git a/bin/loop_claude/test_loop_claude.py b/bin/loop_claude/test_loop_claude.py index d6d64ac2..d58047c6 100644 --- a/bin/loop_claude/test_loop_claude.py +++ b/bin/loop_claude/test_loop_claude.py @@ -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 @@ -1278,6 +1279,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_loop_cannot_take_the_lock_another_holds_and_runs_until_it_lets_it_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 = [] diff --git a/bin/loop_claude/waiting.py b/bin/loop_claude/waiting.py index e4b90400..8f2141d0 100644 --- a/bin/loop_claude/waiting.py +++ b/bin/loop_claude/waiting.py @@ -1,14 +1,12 @@ """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 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. + is the worker's session id, so a loop lists one question at a time. The loop holds the session's lock, as +session_lock.py describes, 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 .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. @@ -19,7 +17,6 @@ answer on its terminal, never answers a later one. """ import contextlib import dataclasses -import fcntl import json import pathlib import typing @@ -27,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. @@ -97,10 +95,6 @@ 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) @@ -141,32 +135,6 @@ def listed(folder: pathlib.Path, ask: Ask, effects: Effects) -> typing.Iterator[ 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: - 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) -> list[Ask]: """The asks of loops still running, oldest first. A file that cannot be read or parsed is left out.""" try: @@ -177,22 +145,16 @@ def waiting(folder: pathlib.Path) -> list[Ask]: 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.""" +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: - handle = open(lock_file(folder, session), "a") + paths = list(folder.glob("*.json")) 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 + 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: diff --git a/bin/loop_inbox/main.py b/bin/loop_inbox/main.py index 416d0f37..374083f3 100644 --- a/bin/loop_inbox/main.py +++ b/bin/loop_inbox/main.py @@ -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, running, 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,6 +70,7 @@ def run(window: curses.window, screen_off: typing.Callable[[], typing.ContextMan window.timeout(REFRESH_MS) screen: Screen = Listing() while True: + drop_ended(folder) screen = entered(screen, refreshed(screen, folder), effects) draw(window, screen, effects) try: diff --git a/bin/loop_inbox/test_loop_inbox.py b/bin/loop_inbox/test_loop_inbox.py index ebe04b57..f2c0eb80 100644 --- a/bin/loop_inbox/test_loop_inbox.py +++ b/bin/loop_inbox/test_loop_inbox.py @@ -18,6 +18,7 @@ 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 @@ -31,10 +32,10 @@ def asked(session, root, question="Which one?", at=100.0, state=ASKING): return Ask(f"ask-{session}", session, root, question, at, state) -def running(test, folder, *sessions): +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(waiting.locked(folder, session)) + test.enterContext(session_lock.locked(folder, session)) def asks_and_answers(folder): @@ -89,7 +90,7 @@ 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") + 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.""" @@ -140,6 +141,11 @@ class Answers(unittest.TestCase): waiting.publish(self.folder, dataclasses.replace(ask, id="a later ask")) 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.""" tenths = [0] @@ -184,7 +190,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") + loops_hold(self, self.paths.waiting, "s1") waiting.publish(self.paths.waiting, self.ask) def open(self, claude, loop_shows=OpenInInbox(INBOX)): @@ -240,7 +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) - running(self, paths.waiting, "s1", "s2") + loops_hold(self, paths.waiting, "s1", "s2") for ask in (log, bender): waiting.publish(paths.waiting, ask) def answered_on_terminal(): @@ -305,11 +311,11 @@ 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, state=OpenOnTerminal()) - running(self, pathlib.Path(folder), "s1", "s2") + 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)), [early, late]) @@ -327,8 +333,19 @@ class Waiting(unittest.TestCase): loop.kill() loop.wait() self.assertEqual(waiting.waiting(folder), []) + waiting.drop_ended(folder) self.assertEqual(asks_and_answers(folder), []) + 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") diff --git a/todo.md b/todo.md index 5e7dad08..7c57be95 100644 --- a/todo.md +++ b/todo.md @@ -6,7 +6,7 @@ `Bar = 0.1` -`Next ID = 253` +`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, in place of seconds since the epoch.** | 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". The module held 28 names before item 252, which moved its lock into `bin/loop_claude/session_lock.py` and added `drop_ended`. 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, in place of seconds since the epoch. + +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 `.json` and `read_ask` reads back. loop-inbox shows it as a local time and a wait, so change those readers 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. -- 2.52.0 From 33834d2b04b498f273043857f836089d6a018fb5 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 29 Oct 2026 18:28:06 +0100 Subject: [PATCH 4/8] =?UTF-8?q?Answer=20principles=20round=202:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=200=20=F0=9F=9F=A1=20(0=20misread)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit -- 2.52.0 From 74a4a90b107b956d3506a5faebbb4a0017348994 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 29 Oct 2026 18:33:29 +0100 Subject: [PATCH 5/8] =?UTF-8?q?Answer=20product-owner=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=200=20=F0=9F=9F=A1=20(0=20misread);=20its=20nit?= =?UTF-8?q?=20on=20the=20stale=20warning=20is=20fixed=20in=20the=20prose?= =?UTF-8?q?=20round=201=20commit?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit -- 2.52.0 From bf78fedc541807996c03978c3340f2101e396d04 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 29 Oct 2026 18:33:29 +0100 Subject: [PATCH 6/8] =?UTF-8?q?Answer=20prose=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=205=20=F0=9F=9F=A1=20(0=20misread);=20drop=20the?= =?UTF-8?q?=20warning=20that=20loop-inbox=20may=20still=20list=20a=20quest?= =?UTF-8?q?ion,=20and=20make=20the=20lock's=20docstrings,=20decision,=20te?= =?UTF-8?q?st=20names=20and=20items=20253=20and=20254=20true=20and=20plain?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin/loop_claude/session_lock.py | 11 +++++------ bin/loop_claude/test_loop_claude.py | 4 ++-- bin/loop_claude/waiting.py | 20 ++++++++++---------- bin/loop_inbox/main.py | 2 +- bin/loop_inbox/test_loop_inbox.py | 4 ++-- docs/decisions.md | 2 +- todo.md | 8 ++++---- 7 files changed, 25 insertions(+), 26 deletions(-) diff --git a/bin/loop_claude/session_lock.py b/bin/loop_claude/session_lock.py index f6529535..db4cd4ab 100644 --- a/bin/loop_claude/session_lock.py +++ b/bin/loop_claude/session_lock.py @@ -1,8 +1,7 @@ -"""The lock a loop-claude holds on its worker's session while loop-inbox lists its question, which tells loop-inbox the loop still runs. +"""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 .lock, held with flock. The kernel frees it however the loop ends, killed included, 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 lock is .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 @@ -19,7 +18,7 @@ def lock_file(folder: pathlib.Path, session: str) -> pathlib.Path: @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 for a moment where it finds the session's question still listed, so a loop starting after another was killed may meet it held.""" + """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: @@ -44,7 +43,7 @@ def locked(folder: pathlib.Path, session: str) -> typing.Iterator[Failure | None def running(folder: pathlib.Path, session: str) -> bool: - """Whether a loop holds the session's lock; False also where the lock cannot be read.""" + """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) diff --git a/bin/loop_claude/test_loop_claude.py b/bin/loop_claude/test_loop_claude.py index d58047c6..7abed6e3 100644 --- a/bin/loop_claude/test_loop_claude.py +++ b/bin/loop_claude/test_loop_claude.py @@ -68,7 +68,7 @@ def human(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.""" + """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"] @@ -1285,7 +1285,7 @@ class SessionLock(unittest.TestCase): self.addCleanup(shutil.rmtree, self.folder) self.path = session_lock.lock_file(self.folder, "s1") - def test_a_loop_cannot_take_the_lock_another_holds_and_runs_until_it_lets_it_go(self): + 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) diff --git a/bin/loop_claude/waiting.py b/bin/loop_claude/waiting.py index 8f2141d0..fb725a60 100644 --- a/bin/loop_claude/waiting.py +++ b/bin/loop_claude/waiting.py @@ -1,12 +1,12 @@ """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 holds the session's lock, as -session_lock.py describes, 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 .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 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 .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. @@ -121,7 +121,7 @@ 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 only warns: the question is still answered on the loop's terminal, and loop-inbox drops the ask once the loop's process ends.""" + """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) @@ -131,8 +131,8 @@ def listed(folder: pathlib.Path, ask: Ask, effects: Effects) -> typing.Iterator[ try: yield finally: - if unwithdrawn := withdraw(folder, ask.session): - say(f"loop-inbox may still list this question: {unwithdrawn.reason}", effects) + # 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) -> list[Ask]: @@ -209,7 +209,7 @@ def received(folder: pathlib.Path, ask: Ask) -> Message | None: match data: case {"kind": "Typed", "text": str(text)}: return Typed(text) - # A pid of 0 or below would name a process group to the loop's alive. + # 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"}: diff --git a/bin/loop_inbox/main.py b/bin/loop_inbox/main.py index 374083f3..14d9657d 100644 --- a/bin/loop_inbox/main.py +++ b/bin/loop_inbox/main.py @@ -127,7 +127,7 @@ 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, from a loop that still runs.""" + """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) and running(folder, ask.session) diff --git a/bin/loop_inbox/test_loop_inbox.py b/bin/loop_inbox/test_loop_inbox.py index f2c0eb80..d1f7cb02 100644 --- a/bin/loop_inbox/test_loop_inbox.py +++ b/bin/loop_inbox/test_loop_inbox.py @@ -319,7 +319,7 @@ class Waiting(unittest.TestCase): pathlib.Path(folder, "s6.json").write_text(pathlib.Path(folder, "s2.json").read_text().replace('"Asking"', '"Waiting"')) 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): + 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)" @@ -329,7 +329,7 @@ class Waiting(unittest.TestCase): 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. + # SIGKILL runs none of the loop's cleanup. loop.kill() loop.wait() self.assertEqual(waiting.waiting(folder), []) diff --git a/docs/decisions.md b/docs/decisions.md index 96a17d33..23172f22 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -109,7 +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. +- 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. diff --git a/todo.md b/todo.md index 7c57be95..53c3beb9 100644 --- a/todo.md +++ b/todo.md @@ -17,7 +17,7 @@ | 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, in place of seconds since the epoch.** | 1 | 1 | 2 | 2 | 2 | code health by 1 | 6.0 | +| 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 | @@ -92,15 +92,15 @@ Found by the paired ruling of PR #387: all four seats ruled Locality worse at `r ### 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". The module held 28 names before item 252, which moved its lock into `bin/loop_claude/session_lock.py` and added `drop_ended`. 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`. +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, in place of seconds since the epoch. +### 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 `.json` and `read_ask` reads back. loop-inbox shows it as a local time and a wait, so change those readers too. +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 `.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. -- 2.52.0 From 2f27e66f5073a8649087aaea01ccb742e33fd47f Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 29 Oct 2026 18:37:23 +0100 Subject: [PATCH 7/8] =?UTF-8?q?Answer=20stability=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=203=20=F0=9F=9F=A1=20(0=20misread);=20test=20that?= =?UTF-8?q?=20loop-inbox=20removes=20a=20killed=20loop's=20ask=20as=20it?= =?UTF-8?q?=20looks=20and=20that=20a=20loop=20leaves=20the=20ask=20of=20an?= =?UTF-8?q?other=20that=20holds=20the=20session's=20lock?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin/loop_claude/test_loop_claude.py | 9 +++++++++ bin/loop_inbox/test_loop_inbox.py | 9 +++++++++ 2 files changed, 18 insertions(+) diff --git a/bin/loop_claude/test_loop_claude.py b/bin/loop_claude/test_loop_claude.py index 7abed6e3..1b59bd43 100644 --- a/bin/loop_claude/test_loop_claude.py +++ b/bin/loop_claude/test_loop_claude.py @@ -744,6 +744,15 @@ class Interrupts(unittest.TestCase): 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. diff --git a/bin/loop_inbox/test_loop_inbox.py b/bin/loop_inbox/test_loop_inbox.py index d1f7cb02..997d044b 100644 --- a/bin/loop_inbox/test_loop_inbox.py +++ b/bin/loop_inbox/test_loop_inbox.py @@ -336,6 +336,15 @@ class Waiting(unittest.TestCase): 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) -- 2.52.0 From a9605317ab4d0f60429084e53ddf055dd757dff8 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Thu, 29 Oct 2026 18:39:06 +0100 Subject: [PATCH 8/8] =?UTF-8?q?Answer=20stability=20round=202:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=200=20=F0=9F=9F=A1=20(0=20misread)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit -- 2.52.0