diff --git a/CHANGELOG.md b/CHANGELOG.md index 64185ea4..21d7e13b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ ## Unreleased -- New tool `loop-inbox` lists every loop-claude on the machine that waits for you, oldest first, in one terminal. Each entry shows the loop's checkout, how long it has waited and the question's first lines, and you answer it there as on the loop's own terminal, `/talk` included, which opens claude in loop-inbox's terminal. 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, is listed but answered in that claude. Link it onto `PATH` as README β†’ Install shows. `loop-claude --help` now describes interrupts more plainly. +- 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. - 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. - `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. - `score-outcomes` now counts each finished chunk's later fixes: the later chunks on the default branch that fixed code it shipped, each a defect that review let through. A later chunk counts where a change of it rewrites or removes lines that `git blame` traces to the earlier chunk: its whole change where it ships a `todo.md` item marked `defect` or `security`, or one of its round commits whose title counts both a πŸ”΄ and a finding a reviewer marked `[misread]`. Each finished item shows the count beside its guessed scores, and a new list, after the misread findings, names the chunks that fixed each one, newest first. `routing-figures.md` shows the mean per rung, over the chunks whose later fixes are known, in a new column of the routed-chunks table. To find them, loop-claude now reads each archived project's checkout, and the figures name each project whose default branch it could not read. diff --git a/CLAUDE.md b/CLAUDE.md index 0f6bfd33..153600e9 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -122,7 +122,7 @@ Claude Code reads this section by its heading when it compacts a conversation. K - **chunk** β€” the unit of work, shipped as one PR; "Working loop" says what it holds. - **cycle** β€” in `loop-claude`, worker runs and the judge's verdict on each, until the chunk closes or is left for the next cycle. In between, the human answers any interrupt, or the worker resumes with an answer the judge quoted from `README.md` or the judge's records. - **gate** β€” the merge gate: the checks a PR passes before it merges. -- **interrupt** β€” `loop-claude` asking the human, on its terminal and in `loop-inbox`, for a decision that is theirs. They type a one-line answer in either, or `/talk` to open the worker's session with `claude --resume` where they typed it; a release ready to cut opens that session at once, and a routing call opens claude in `~/.claude`. +- **interrupt** β€” `loop-claude` asking the human, on its terminal and in `loop-inbox`, for a decision that is theirs. They type a one-line answer in either, or `/talk` to open the worker's session with `claude --resume` where they typed it; a release ready to cut opens that session at once, and a routing call opens claude in `~/.claude`, both on loop-claude's terminal. - **judge** β€” the headless claude that reads a worker's transcript each cycle and decides whether to interrupt and whether the chunk is finished. - **judge's records** β€” the files the judge reads beside the README's premises: the project's `AGENTS.md` and `docs/decisions.md`, then the human's `~/.claude/CLAUDE.md` and the `.md` files in `~/.claude/rules/` and `~/.claude/skills/larv-review/standards/`. - **paired ruling** β€” the seats vote whether the project reads better, the same or worse at the branch's head than at the base, the commit `larv-review ruling-base` prints; `larv-review --help` says how the votes make the ruling. diff --git a/README.md b/README.md index 07c1b8fe..e6ba56db 100644 --- a/README.md +++ b/README.md @@ -99,7 +99,7 @@ Install puts only `loop-claude` and `loop-inbox` on `PATH`; call the others by t - `judge-replay ` replays loop-claude's judge on archived verdicts of the projects run on the model, and prints the lowest rung that, like each rung above it, returns them; `judge-replay --help` states the replay. - `larv-review ` holds larv-review's mechanical rules: the chunk's review folder, the paired ruling's base and vote count, each pass's round count, the scoring run's trigger, and the comprehension history's format and latest places, and its count of how often seats agree; `larv-review --help` states them. - `loop-claude ` runs a project's next chunk cycle after cycle; `loop-claude --help` states its contract. -- `loop-inbox` shows every loop-claude on the machine that waits for the human, oldest first, and takes each one's answer, `/talk` included; `loop-inbox --help` states how. +- `loop-inbox` shows the interrupts of every loop-claude on the machine, oldest first, and takes each one's answer, `/talk` included; `loop-inbox --help` states how. - `metric-bench [history]` benches cheap static metrics of a project's Python against the places its comprehension history names as hardest; `metric-bench --help` states the metrics and the scores. - `rank_todo.py [--check] [todo.md]` scores and ranks a project's `todo.md`; `rank_todo.py --help` states the format. - `reading-cost [--reset] [record]` appends a figure for each chunk `loop-claude` finished to a project's `docs/reading-cost.md`, and says whether the figures rise; `reading-cost --help` states the measure. @@ -132,7 +132,7 @@ Then, in the copy: `uvx --with pytest==9.2.0 'mutmut>=3,<4' run && uvx --with py - `judge_replay` imports `loop_claude`'s judge. - `larv_review` imports `rank_todo.py`'s ranking. - `loop_claude` runs `chunk-preflight` as a process of its own. -- `loop_inbox` reads and answers the questions `loop_claude/waiting.py` writes, and opens claude for `/talk` as `loop_claude` does. +- `loop_inbox` imports `loop_claude`'s question files (`waiting.py`), its effects and paths, and `hand_over`, which opens claude for `/talk`. - `machine_load/` takes the machine's heavy slots, its shared lock files, for `run_heavy`, and reads the memory share that loop-claude waits for. - `model_routing/` holds the routing ladder, which loop-claude, `rule_hook`, both replay tools and `subagent-rung` read. - `rank_todo.py`, `settings_filter.py` and `statusline.py` are tools of one file each, tested beside them. diff --git a/bin/loop_claude/cycle/interrupt.py b/bin/loop_claude/cycle/interrupt.py index 6b453b24..83df68eb 100644 --- a/bin/loop_claude/cycle/interrupt.py +++ b/bin/loop_claude/cycle/interrupt.py @@ -15,7 +15,7 @@ from claude_code.trust import trust from loop_claude.project.checkout import worktrees ANSWER_QUESTION = "answer the question above" -# TALK and ASK_ANSWER were picked on 2026-10-17 by a bench of three readers seated as the README's audience, as ~/.claude/CLAUDE.md β†’ "Working loop" β†’ "Bench a syntax with the people who write it." has it. +# ASK_ANSWER was picked on 2026-10-17 by a bench of three readers seated as the README's audience, as ~/.claude/CLAUDE.md β†’ "Working loop" β†’ "Bench a syntax with the people who write it." has it. ASK_ANSWER = f"Answer ({TALK} opens claude, Enter stops the loop): " @@ -26,7 +26,7 @@ class WorkerSession: id: uuid.UUID rung: Rung transcript_path: str - # What the worker's claude adds to its environment, as the claude /talk opens does. + # Added to the environment of the worker's claude, and of the claude /talk opens. env: dict[str, str] def claude_command(self) -> ClaudeCommand: @@ -76,7 +76,7 @@ def first_answer(ask: Ask, paths: Paths, effects: Effects) -> str | Talk | Stop: def shown(paths: Paths, ask: Ask, effects: Effects) -> None: - """Shows ask in loop-inbox. A failure only warns: the question is still answered on the terminal.""" + """Shows ask in loop-inbox. A failure only warns. The question is then still answered on the terminal, unless claude was to open in loop-inbox: loop-inbox then gives up, and the loop stops.""" if unshown := publish(paths.waiting, ask): say(f"loop-inbox cannot show this question: {unshown.reason}", effects) @@ -88,7 +88,7 @@ def withdrawn(paths: Paths, ask: Ask, effects: Effects) -> None: def talk(chosen: Talk, session: WorkerSession, paths: Paths, effects: Effects) -> Stop | None: - """Holds the loop while the human answers in the worker's claude session, listed in loop-inbox as open where it is; the human must type something there.""" + """Holds the loop while the human answers in the worker's claude session, which loop-inbox lists as open on loop-claude's terminal or in loop-inbox. A Stop where they type nothing there.""" try: return human_typed(session.transcript_path, lambda: opened(chosen, session, paths, effects)) finally: @@ -97,7 +97,7 @@ def talk(chosen: Talk, session: WorkerSession, paths: Paths, effects: Effects) - def opened(chosen: Talk, session: WorkerSession, paths: Paths, effects: Effects) -> Stop | None: """Returns once the claude the human answers in has ended: the one it opens on the terminal, or the one loop-inbox opened.""" - # For loop-inbox, this shows that the loop has stopped reading its terminal, so it may open claude. + # Tells loop-inbox where claude is open; for OpenInInbox, it is the go-ahead claim_talk waits for. shown(paths, dataclasses.replace(chosen.ask, state=chosen.where), effects) match chosen.where: case OpenOnTerminal(): @@ -127,7 +127,7 @@ def human_typed(transcript_path: str, held_open: typing.Callable[[], Stop | None def hand_over(command: ClaudeCommand, paths: Paths, effects: Effects) -> Failure | None: - """Marks the checkout command runs in, and each of its worktrees, trusted, then runs claude on the terminal as command says; the failure is why claude could not start.""" + """Marks trusted the checkout that command runs in, and each of its worktrees, then runs claude on the terminal as command says; the failure is why claude could not start.""" trust(paths.claude_json, worktrees(command.cwd, effects), lambda text: say(text, effects)) try: effects.claude_on_terminal(command.args, command.cwd, command.env) diff --git a/bin/loop_claude/effects.py b/bin/loop_claude/effects.py index 32ab54d5..9c63fc03 100644 --- a/bin/loop_claude/effects.py +++ b/bin/loop_claude/effects.py @@ -42,11 +42,9 @@ class Effects: local_time: typing.Callable[[float], str] # The machine's memory; None where it cannot be read. memory: typing.Callable[[], Memory | None] - # A new random id. new_id: typing.Callable[[], str] now: typing.Callable[[], float] on_terminal: typing.Callable[[], bool] - # This process's pid. pid: typing.Callable[[], int] # Runs a Python script in a directory, as run_python does. python: typing.Callable[[list[str], str], subprocess.CompletedProcess[str]] diff --git a/bin/loop_claude/loop/main.py b/bin/loop_claude/loop/main.py index b9804a05..b7e3dedb 100644 --- a/bin/loop_claude/loop/main.py +++ b/bin/loop_claude/loop/main.py @@ -22,12 +22,12 @@ is shown the passage the judge quoted as the work remaining. The next chunk star Cycles continue until an exit below or Ctrl-C. Words: ~/.claude/CLAUDE.md β†’ "Vocabulary". A question only the human can answer is an interrupt (bin/loop_claude/cycle/interrupt.py). -loop-claude prints the question on its terminal and lists it in loop-inbox, which shows every -loop on the machine that waits for the human. The first answer counts, from either place: +loop-claude prints the question on its terminal and lists it in loop-inbox, which shows the +interrupts of every loop on the machine. The first answer counts, from either place: - A line of text: the worker resumes headless with it. The judge reads it as the human's, so the chunk stays unfinished until the answer is recorded. -- /talk: opens the worker's session with `claude --resume`, to read the diff or discuss first. Once - that claude exits, the judge rules on what was typed there. +- /talk: opens the worker's session with `claude --resume` where it was typed, to read the diff or + discuss first. Once that claude exits, the judge rules on what was typed there. - Enter alone, on loop-claude's terminal: stops the loop. A release ready to cut opens that session on the terminal at once, since only the human may cut it; loop-inbox lists it too. Before claude opens, the checkout and each of its worktrees are marked @@ -57,9 +57,9 @@ compacts its context at about 170k tokens. Every claude loop-claude starts runs the project's model, saved per in ~/.claude/loop-claude-models.json and read each cycle, unless routing, below, puts the worker, the session /talk opens and the judge on another rung, a model at an effort. A project without an -entry, as on its first run, is asked for one. LOOP_CLAUDE_JUDGE_MODEL overrides the model for the -judge, LOOP_CLAUDE_WORKER_MODEL for the worker and the session /talk opens; with both set, nothing -is asked. +entry, as on its first run, is asked for one on the terminal; loop-inbox doesn't list that +question. LOOP_CLAUDE_JUDGE_MODEL overrides the model for the judge, LOOP_CLAUDE_WORKER_MODEL for +the worker and the session /talk opens; with both set, nothing is asked. Where the project's model is on the routing ladder (bin/model_routing/ladder.py), the worker and the session /talk opens run on the rung that the chunk's todo.md item picks, and the judge of some @@ -78,9 +78,10 @@ Once 20 cycles have closed across all projects in the archive since the last mea loop to close one measures every finished chunk there, with no model run, and writes routing-figures.md at the archive's root (bin/routing_figures/measure.py). Each call the figures make for a routing change, unless raised before, is an interrupt: claude, on the project's model, -on the terminal in ~/.claude, asked to put the calls to the human. Once that claude ends, the calls -are listed in routing-calls-raised.md beside the figures, and not raised again. Off a terminal, the -calls are said on stderr, the loop goes on, and they are raised again at the next measurement. +on the terminal in ~/.claude, asked to put the calls to the human; loop-inbox lists it too. Once +that claude ends, the calls are listed in routing-calls-raised.md beside the figures, and not +raised again. Off a terminal, the calls are said on stderr, the loop goes on, and they are raised +again at the next measurement. A change to bin/loop-claude or any bin/**/*.py takes effect at the next cycle boundary, once loop-claude --help succeeds: the loop reloads into the edited script. @@ -199,7 +200,7 @@ def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launc if isinstance(closed, Stop): return closed loop_run = closed - if stop := check_routing(archive_root(paths.home, env), project or Rung(models.worker), paths, effects): + if stop := check_routing(archive_root(paths.home, env), loop_run.root, project or Rung(models.worker), paths, effects): return stop diff --git a/bin/loop_claude/loop/routing_check.py b/bin/loop_claude/loop/routing_check.py index 007d60fb..b8b38344 100644 --- a/bin/loop_claude/loop/routing_check.py +++ b/bin/loop_claude/loop/routing_check.py @@ -2,9 +2,9 @@ import pathlib from routing_figures import archive +from loop_claude.waiting import Ask, ClaudeCommand, OpenOnTerminal from routing_figures.measure import calls, due, render, totals -from loop_claude.cycle.interrupt import claude_args, hand_over -from loop_claude.waiting import ClaudeCommand +from loop_claude.cycle.interrupt import claude_args, hand_over, shown, withdrawn from loop_claude.effects import Effects, say from failure import Failure from loop_claude.paths import Paths @@ -13,14 +13,14 @@ from loop_claude.stop import Stop from utc_stamp import utc -def check_routing(root: pathlib.Path, rung: Rung, paths: Paths, effects: Effects) -> Stop | None: - """Stops only when claude cannot start for the calls; a figure it cannot measure or keep is said on stderr, and the loop goes on. rung is the rung of the claude that puts the calls to the human.""" +def check_routing(root: pathlib.Path, checkout: str, rung: Rung, paths: Paths, effects: Effects) -> Stop | None: + """Stops only when claude cannot start for the calls; a figure it cannot measure or keep is said on stderr, and the loop goes on. checkout is the loop's, and rung is the rung of the claude that puts the calls to the human.""" with archive.locked(root) as held: new = new_calls(root, paths, effects) if held else [] if isinstance(new, Failure): say(f"routing figures: {new.reason}", effects) return None - return raise_calls(root, new, rung, paths, effects) if new else None + return raise_calls(root, checkout, new, rung, paths, effects) if new else None def new_calls(root: pathlib.Path, paths: Paths, effects: Effects) -> list[str] | Failure: @@ -43,15 +43,24 @@ def new_calls(root: pathlib.Path, paths: Paths, effects: Effects) -> list[str] | return [call for call in found if call not in kept.calls] -def raise_calls(root: pathlib.Path, new: list[str], rung: Rung, paths: Paths, effects: Effects) -> Stop | None: - """Puts the calls to the human through a claude in this setup's checkout, where the routing decision lives. Off a terminal they are only said, and stay in the figures, raised at the next measurement on a terminal.""" +def raise_calls(root: pathlib.Path, checkout: str, new: list[str], rung: Rung, paths: Paths, effects: Effects) -> Stop | None: + """Puts the calls to the human through a claude in this setup's checkout, where the routing decision lives; loop-inbox lists them under the loop's checkout while that claude is open. Off a terminal they are only said, and stay in the figures, raised at the next measurement on a terminal.""" listed = "".join(f"- {call}\n" for call in new) - say(f"\nloop-claude's routing figures call for a routing change:\n{listed}The figures: {root / archive.FIGURES}", effects) + question = f"loop-claude's routing figures call for a routing change:\n{listed}The figures: {root / archive.FIGURES}" + say(f"\n{question}", effects) if not effects.on_terminal(): say("Not on a terminal: the calls are raised again at the next measurement.", effects) return None prompt = f"Put these calls for a routing change from loop-claude's figures to the human, and change nothing until they answer:\n{listed}The figures are in {root / archive.FIGURES}. The ladder, its steps and the delegation rule are docs/decisions.md β†’ `routing:`, and a change to them is the human's. Record what they decide as ~/.claude/CLAUDE.md says; the next chunk of this repo files the plan item for these calls." - if unstarted := hand_over(ClaudeCommand(claude_args(rung, [prompt]), str(paths.claude_dir), {}), paths, effects): + # No worker session answers the calls, so the ask is filed under its own id. + ask_id = effects.new_id() + ask = Ask(ask_id, ask_id, checkout, question, effects.now(), effects.pid(), OpenOnTerminal()) + shown(paths, ask, effects) + try: + unstarted = hand_over(ClaudeCommand(claude_args(rung, [prompt]), str(paths.claude_dir), {}), paths, effects) + finally: + withdrawn(paths, ask, effects) + if unstarted: return Stop(1, f"could not start claude for the routing calls: {unstarted.reason}") # Raised once the human has seen them, answered or not: an unanswered call reaches the plan through AGENTS.md, so it is not asked twice. if unmarked := archive.mark_raised(root, new, utc(effects.now())): diff --git a/bin/loop_claude/paths.py b/bin/loop_claude/paths.py index ff0be455..269bc383 100644 --- a/bin/loop_claude/paths.py +++ b/bin/loop_claude/paths.py @@ -10,7 +10,7 @@ class Paths: home: pathlib.Path model_catalog: pathlib.Path models_file: pathlib.Path - # Where a loop that waits for the human shows its question to loop-inbox (bin/loop_claude/waiting.py). + # Where a loop shows its interrupt to loop-inbox (bin/loop_claude/waiting.py). waiting: pathlib.Path diff --git a/bin/loop_claude/test_black_box.py b/bin/loop_claude/test_black_box.py index ebd37473..dd7b3bfb 100644 --- a/bin/loop_claude/test_black_box.py +++ b/bin/loop_claude/test_black_box.py @@ -100,9 +100,8 @@ elif role == "judge": print(step.get("stderr", ""), file=sys.stderr) else: if step.get("ctrl_c"): - # A Ctrl-C on the terminal reaches every process in its foreground, loop-claude too. + # A Ctrl-C on the terminal reaches every process in its foreground, loop-claude too. kill returns once the signal is pending in loop-claude, before this process exits and loop-claude stops waiting for it. os.kill(os.getppid(), signal.SIGINT) - time.sleep(0.5) if "type" in step: append({{"type": "user", "message": {{"content": step["type"]}}}}) if step.get("unreadable"): diff --git a/bin/loop_claude/test_loop_claude.py b/bin/loop_claude/test_loop_claude.py index 540512df..c23d23a0 100644 --- a/bin/loop_claude/test_loop_claude.py +++ b/bin/loop_claude/test_loop_claude.py @@ -6,6 +6,7 @@ import json import os import pathlib import shutil +import signal import stat import subprocess import sys @@ -66,10 +67,8 @@ def human(content): class FakeEffects: """Effects that record each call and answer from a script, one answer per call.""" - def __init__(self, claude=(), on_terminal_claude=(), git=(), inputs=(), python=(), streams=(), on_terminal=True, free_memory=(), gone=()): + def __init__(self, claude=(), on_terminal_claude=(), git=(), inputs=(), python=(), streams=(), on_terminal=True, free_memory=()): self.calls = [] - # The pids of processes that no longer run. - self.gone = set(gone) self.scripts = {"claude": list(claude), "claude_on_terminal": list(on_terminal_claude), "git": list(git), "input": list(inputs), "python": list(python), "stream_claude": list(streams)} # Without a script, every read finds all memory available. self.free_memory = list(free_memory) @@ -79,7 +78,7 @@ class FakeEffects: def effects(self): return Effects( - alive=lambda pid: pid not in self.gone, + alive=lambda pid: True, claude=lambda args, cwd, stdin: self.answer("claude", (args, stdin)), claude_on_terminal=self.on_terminal_claude, discard_typed=lambda: self.calls.append(("discard_typed", None)), @@ -103,7 +102,7 @@ class FakeEffects: return self.free_memory.pop(0) if self.free_memory else memory.Memory(available=16, total=16) def input_or(self, prompt, other): - """Answers from the input script as input does, but hands a callable in it other, which loop-inbox's answer comes from.""" + """Answers from the input script as input does; a callable in the script gets other, the source of loop-inbox's answer.""" self.calls.append(("input", prompt)) answer = self.scripts["input"].pop(0) if isinstance(answer, BaseException): @@ -752,15 +751,26 @@ class Interrupts(unittest.TestCase): self.assertEqual(self.talk(states.Talk(self.ask(), waiting.OpenInInbox(inbox)), effects), (None, f"{STAMP} claude is open for this question in loop-inbox; waiting for it to end\n")) self.assertEqual((fake.made("claude_on_terminal"), list(self.paths.waiting.iterdir())), ([], [])) - def test_stops_when_loop_inbox_ends_its_claude_or_is_gone_with_nothing_typed(self): - inbox = 4343 - def ended(_): + def test_stops_when_loop_inbox_ends_its_claude_with_nothing_typed(self): + inbox, looked, slept = 4343, [], [] + def alive(pid): + looked.append(pid) + return pid == inbox + def ended(seconds): + slept.append(seconds) waiting.send(self.paths.waiting, self.ask(), waiting.ClaudeEnded()) - # loop-inbox's claude ends while the loop waits, or loop-inbox is gone before the loop looks. - for gone in ((), (inbox,)): - with self.subTest(gone=gone): - stop, _ = self.talk(states.Talk(self.ask(), waiting.OpenInInbox(inbox)), dataclasses.replace(FakeEffects(gone=gone).effects(), sleep=ended)) - self.assertEqual(stop, Stop(2, "the human is needed to answer the question above, but the interrupt ended with nothing typed")) + stop, _ = self.talk(states.Talk(self.ask(), waiting.OpenInInbox(inbox)), dataclasses.replace(FakeEffects().effects(), alive=alive, sleep=ended)) + self.assertEqual((stop, looked, slept), (Stop(2, "the human is needed to answer the question above, but the interrupt ended with nothing typed"), [inbox], [waiting.POLL_SECONDS])) + + def test_stops_when_loop_inbox_is_gone_with_nothing_typed(self): + inbox, looked = 4343, [] + def alive(pid): + looked.append(pid) + # loop-inbox's process ends while the loop waits for its claude. + return pid == inbox and len(looked) == 1 + fake = FakeEffects() + stop, _ = self.talk(states.Talk(self.ask(), waiting.OpenInInbox(inbox)), dataclasses.replace(fake.effects(), alive=alive)) + self.assertEqual((stop, looked, fake.made("sleep")), (Stop(2, "the human is needed to answer the question above, but the interrupt ended with nothing typed"), [inbox, inbox], [waiting.POLL_SECONDS])) def test_lists_the_claude_open_on_its_terminal_in_loop_inbox_while_it_runs(self): def ran(args): @@ -805,10 +815,20 @@ class RoutingCheck(unittest.TestCase): (subagents / "agent-a.meta.json").write_text(json.dumps({"agentType": "Explore", "toolUseId": "a"})) def check(self, fake): + """What check_routing returns and says for a loop in /code/log.""" with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()) as said: - stop = routing_check.check_routing(self.root, Rung("m", "high"), self.paths, fake.effects()) + stop = routing_check.check_routing(self.root, "/code/log", Rung("m", "high"), self.paths, fake.effects()) return stop, said.getvalue() + def test_lists_the_calls_in_loop_inbox_while_their_claude_is_open(self): + self.chunks(5, 4) + question = f"loop-claude's routing figures call for a routing change:\n- Explore subagents' reports took more of the worker's context than their searches would have.\nThe figures: {self.root / 'routing-figures.md'}" + def ran(args): + self.assertEqual(waiting.waiting(self.paths.waiting, lambda pid: True), [waiting.Ask(ASK_ID, ASK_ID, "/code/log", question, NOW, PID, waiting.OpenOnTerminal())]) + return 0 + self.check(FakeEffects(on_terminal_claude=[ran], git=[UNREAD, ""])) + self.assertEqual(list(self.paths.waiting.iterdir()), []) + def test_measures_once_20_cycles_have_closed_since_the_last_measurement(self): self.chunks(5, 3) self.assertEqual(self.check(FakeEffects()), (None, "")) @@ -871,6 +891,7 @@ class RoutingCheck(unittest.TestCase): self.chunks(5, 4) stop, _ = self.check(FakeEffects(on_terminal_claude=[OSError(2, "No such file or directory")], git=[UNREAD, ""])) self.assertEqual(stop, Stop(1, "could not start claude for the routing calls: No such file or directory")) + self.assertEqual(list(self.paths.waiting.iterdir()), []) @unittest.skipIf(os.geteuid() == 0, "root writes into a read-only directory") def test_says_a_figure_it_cannot_write_and_goes_on(self): @@ -1243,6 +1264,28 @@ class LocalTime(unittest.TestCase): self.assertEqual(system_effects().local_time(NOW), "2026-09-21 16:13:20") +class Alive(unittest.TestCase): + def test_a_process_that_runs_is_alive_and_one_that_ended_is_not(self): + ended = subprocess.Popen([sys.executable, "-c", "pass"]) + ended.wait() + # Unless this process runs as root, it may not signal pid 1, which still runs. + self.assertEqual([system_effects().alive(pid) for pid in (os.getpid(), ended.pid, 1)], [True, False, True]) + + +class ClaudeOnTerminal(unittest.TestCase): + def test_leaves_ctrl_c_to_claude_while_it_runs_and_returns_its_exit_code(self): + caught = [] + self.addCleanup(signal.signal, signal.SIGINT, signal.signal(signal.SIGINT, lambda number, frame: caught.append(number))) + before = signal.getsignal(signal.SIGINT) + with tempfile.TemporaryDirectory() as folder: + claude = pathlib.Path(folder, "claude") + # A Ctrl-C on the terminal reaches every process in its foreground. kill returns once the signal is pending in the test's process, before claude exits and claude_on_terminal returns. + claude.write_text(f"#!{sys.executable}\nimport os, signal, sys\nos.kill(os.getppid(), signal.SIGINT)\nsys.exit(3)\n") + claude.chmod(0o755) + code = system_effects().claude_on_terminal([], folder, {"PATH": folder}) + self.assertEqual((code, caught, signal.getsignal(signal.SIGINT)), (3, [], before)) + + class PythonEffect(unittest.TestCase): def test_runs_a_script_in_the_given_directory(self): with tempfile.TemporaryDirectory() as cwd: diff --git a/bin/loop_claude/waiting.py b/bin/loop_claude/waiting.py index b957b597..25d2c2f9 100644 --- a/bin/loop_claude/waiting.py +++ b/bin/loop_claude/waiting.py @@ -1,9 +1,11 @@ -"""The files by which a loop-claude that waits for the human shows its question in loop-inbox, and takes an answer typed there. +"""The files by which a loop-claude shows its interrupt in loop-inbox, and takes an answer typed there. -A waiting loop keeps one file per session, .json, in Paths.waiting, and removes it once answered or stopped. -Its state says whether it waits for an answer, or has claude open for it, on the loop's own terminal or in loop-inbox. -loop-inbox answers by replacing .answer. The answer names the ask it answers by its id, so an answer -meant for an earlier question, or sent as the loop took an answer on its terminal, never answers a later one. +A waiting loop keeps its ask in .json in Paths.waiting: the question, with an id new for each question. + is the worker's session id, or the ask's own id for the routing calls, which have no worker session. +The loop removes the file once the question is answered or the loop stops. The ask's state says whether the loop +waits for an answer, or has claude open for it, on the loop's own terminal or in loop-inbox. loop-inbox answers by +replacing .answer, which names the ask's id. So an answer meant for an earlier question, or sent as the +loop took an answer on its terminal, never answers a later one. /talk from loop-inbox goes in three steps, so that only one claude ever holds the worker's session: 1. loop-inbox's claim_talk sends ClaudeOpening, with its pid. @@ -24,7 +26,7 @@ from file_writes import make_private, replace_json POLL_SECONDS = 0.5 # Seconds loop-inbox waits for a loop to make way for its claude: ten of the loop's looks, so a loop slow for a moment still makes way. MAKE_WAY_SECONDS = 10 * POLL_SECONDS -# What the human types, on the loop's terminal or in loop-inbox, to open claude for the ask; interrupt.py says who picked it. +# What the human types, on the loop's terminal or in loop-inbox, to open claude for the ask; picked on 2026-10-17 by a bench of three readers seated as the README's audience. TALK = "/talk" @@ -44,7 +46,7 @@ class Asking: @dataclasses.dataclass(frozen=True) class OpenOnTerminal: - """claude is open for the ask on the loop's own terminal, and takes no answer from loop-inbox.""" + """claude is open for the ask on the loop's own terminal; the loop takes no answer from loop-inbox.""" @dataclasses.dataclass(frozen=True) @@ -118,7 +120,7 @@ def withdraw(folder: pathlib.Path, session: str) -> Failure | None: def waiting(folder: pathlib.Path, alive: typing.Callable[[int], bool]) -> list[Ask]: - """The asks of loops still running, oldest first. A file that cannot be read or parsed is left out, as is one being replaced.""" + """The asks of loops still running, oldest first. A file that cannot be read or parsed is left out.""" try: paths = sorted(folder.glob("*.json")) except OSError: @@ -188,7 +190,7 @@ def received(folder: pathlib.Path, ask: Ask) -> Message | None: def claim_talk(folder: pathlib.Path, ask: Ask, pid: int, now: typing.Callable[[], float], sleep: typing.Callable[[float], None]) -> bool | Failure: - """loop-inbox's side of /talk: asks the loop to make way for a claude that the loop-inbox whose process is pid opens for ask. True once the loop shows it has stopped reading its terminal, within MAKE_WAY_SECONDS; False where it was answered first, or stopped, or didn't make way in time.""" + """loop-inbox's side of /talk, where pid is loop-inbox's process: asks the loop to make way for the claude loop-inbox opens for ask. True once the loop shows it has stopped reading its terminal, within MAKE_WAY_SECONDS; False where it was answered first, stopped, made way for another loop-inbox, or didn't make way in time.""" if unsent := send(folder, ask, ClaudeOpening(pid)): return unsent deadline = now() + MAKE_WAY_SECONDS diff --git a/bin/loop_inbox/inbox.py b/bin/loop_inbox/inbox.py index 2d737395..4794736f 100644 --- a/bin/loop_inbox/inbox.py +++ b/bin/loop_inbox/inbox.py @@ -13,14 +13,18 @@ from loop_claude.waiting import Ask, Asking, OpenInInbox, OpenOnTerminal, TALK ENTER = "enter" BACKSPACE = "backspace" ESCAPE = "escape" -# Lines of a question the list shows; the answer screen shows it whole. +# Lines of a question the list shows; the answer screen shows as much as fits. SHOWN_LINES = 2 QUIT = "q" +ANSWER_PROMPT = f"Answer ({TALK} opens claude; Enter alone, or Esc, goes back, and the loop keeps waiting):" +INDENT = " " +ELLIPSIS = "…" +NARROWEST = 20 @dataclasses.dataclass(frozen=True) class Listing: - """The waiting loops, as shown when the human began typing a number, which keeps a loop's number from changing under them.""" + """The waiting loops as they were when the human began typing a number, so a loop's number doesn't change while they type it.""" shown: tuple[Ask, ...] = () typed: str = "" note: str = "" @@ -62,7 +66,8 @@ def pressed(screen: Screen, key: str) -> Screen | Send | Open | Quit: return picked(shown, typed) if key == BACKSPACE: return Listing(shown, typed[:-1]) - return Listing(shown, typed + key) if key.isdigit() else screen + # isdigit would also take "Β²", which int() rejects. + return Listing(shown, typed + key) if key.isdecimal() else screen case Answering(ask, typed): if key == ESCAPE or (key == ENTER and not typed.strip()): return Listing() @@ -91,47 +96,50 @@ def where_open(state: OpenOnTerminal | OpenInInbox) -> str: return "in loop-inbox" if isinstance(state, OpenInInbox) else "on its terminal" -def listing_lines(screen: Listing, now: float, local_time: typing.Callable[[float], str], width: int) -> list[str]: - """The list, its last line the prompt for a number.""" +def listing_lines(screen: Listing, now: float, local_time: typing.Callable[[float], str], width: int) -> tuple[list[str], list[str]]: + """The list, in lines of at most width characters, and its foot: the note, what the keys do, and the prompt for a number.""" count = len(screen.shown) head = "No loop waits for you." if not count else "1 loop waits for you." if count == 1 else f"{count} loops wait for you, oldest first." - lines = [head, ""] + lines = [*wrapped(head, width), ""] for number, ask in enumerate(screen.shown, 1): state = "" if isinstance(ask.state, Asking) else f"; claude is open {where_open(ask.state)}" - lines.append(f"[{number}] {ask.root}, waiting since {local_time(ask.asked)} ({waited(now - ask.asked)}){state}") - lines += cut(wrapped(ask.question, width - 4), SHOWN_LINES, " ") + lines += wrapped(f"[{number}] {ask.root}, waiting since {local_time(ask.asked)} ({waited(now - ask.asked)}){state}", width) + lines += cut(wrapped(ask.question, width - len(INDENT) - len(ELLIPSIS)), SHOWN_LINES) lines.append("") - lines += [screen.note] if screen.note else [] ask_for = "Type a number and Enter to answer that loop; " if count else "" - return [*lines, f"{ask_for}{QUIT} quits loop-inbox, and the loops keep waiting.", f"> {screen.typed}"] + return lines, [*wrapped(screen.note, width), *wrapped(f"{ask_for}{QUIT} quits loop-inbox, and the loops keep waiting.", width), *typed_after(">", screen.typed, width)] -def answering_lines(screen: Answering, now: float, local_time: typing.Callable[[float], str], width: int) -> list[str]: - """The whole question, its last line the prompt for the answer.""" +def answering_lines(screen: Answering, now: float, local_time: typing.Callable[[float], str], width: int) -> tuple[list[str], list[str]]: + """The question, in lines of at most width characters, and its foot, the prompt for the answer.""" ask = screen.ask - return [ - f"{ask.root}, waiting since {local_time(ask.asked)} ({waited(now - ask.asked)}):", - "", - *wrapped(ask.question, width), - "", - f"Answer ({TALK} opens claude; Enter alone, or Esc, goes back, and the loop keeps waiting): {screen.typed}", - ] + head = f"{ask.root}, waiting since {local_time(ask.asked)} ({waited(now - ask.asked)}):" + return [*wrapped(head, width), "", *wrapped(ask.question, width), ""], typed_after(ANSWER_PROMPT, screen.typed, width) -def fitted(lines: list[str], height: int) -> list[str]: - """lines cut to height, keeping the last, the prompt; a cut is marked with an ellipsis.""" - if len(lines) <= height: - return lines - return [*lines[: max(height - 2, 0)], "…", lines[-1]][-height:] +def fitted(lines: list[str], foot: list[str], height: int) -> list[str]: + """lines, then foot, cut to height: lines lose their end first, and the cut is marked with an ellipsis.""" + if len(lines) + len(foot) <= height: + return [*lines, *foot] + return [*lines[: max(height - len(foot) - 1, 0)], ELLIPSIS, *foot][-height:] def wrapped(text: str, width: int) -> list[str]: - return [line for paragraph in text.splitlines() for line in textwrap.wrap(paragraph, max(width, 20)) or [""]] + return [line for paragraph in text.splitlines() for line in textwrap.wrap(paragraph, max(width, NARROWEST)) or [""]] -def cut(lines: list[str], count: int, indent: str) -> list[str]: - shown = [f"{indent}{line}" for line in lines[:count]] - return [*shown[:-1], f"{shown[-1]}…"] if len(lines) > count else shown +def typed_after(prompt: str, typed: str, width: int) -> list[str]: + """prompt wrapped to width, then what the human typed after it, cut every width characters so that each space typed shows.""" + *lines, last = wrapped(prompt, width) + line = f"{last} {typed}" + step = max(width, NARROWEST) + return [*lines, *(line[start : start + step] for start in range(0, len(line), step))] + + +def cut(lines: list[str], count: int) -> list[str]: + """The first count lines, indented; a cut is marked with an ellipsis.""" + shown = [f"{INDENT}{line}" for line in lines[:count]] + return [*shown[:-1], f"{shown[-1]}{ELLIPSIS}"] if len(lines) > count else shown def waited(seconds: float) -> str: diff --git a/bin/loop_inbox/main.py b/bin/loop_inbox/main.py index 2977f7e1..3d15b72d 100644 --- a/bin/loop_inbox/main.py +++ b/bin/loop_inbox/main.py @@ -1,21 +1,23 @@ -"""Show every loop-claude on this machine that waits for you, oldest first, and answer each one here. +"""Show the interrupts of every loop-claude on this machine, oldest first, and answer each one here. usage: loop-inbox -Each loop-claude that asks you a question lists it here, as well as on its own terminal, until it is -answered or the loop stops. The list shows each loop's checkout, when it asked and how long it has -waited, and the question's first lines; it refreshes every second. Type a loop's number and Enter -to see its whole question, then answer as on the loop's terminal: +Each loop-claude lists its interrupt here, as well as on its own terminal, until it is answered or +the loop stops. The list shows each loop's checkout, when it asked and how long it has waited, and +the question's first lines; it refreshes every second. Type a loop's number and Enter to see as much +of its question as fits; the loop's terminal shows it whole. Answer as on the loop's terminal: -- A line and Enter sends it to that loop, which goes on with it. +- A line and Enter sends it to that loop, which goes on with it. Of a pasted answer, only the first + line is sent, and the rest is dropped; a longer answer goes through /talk. - /talk opens the worker's claude session here, with `claude --resume`, as /talk does on the loop's - terminal. Once that claude ends, the loop goes on, and the judge rules on what was typed there; a - loop whose claude ends with nothing typed stops. + terminal. Once that claude ends, the loop goes on if you typed there, and the judge rules on what + you typed; if you typed nothing, the loop stops. - Enter alone, or Esc, goes back to the list; unlike on the loop's terminal, it doesn't stop the loop. The loop takes whichever answer comes first, here or on its terminal, so it keeps working with no -loop-inbox running. A loop whose release is ready to cut, or whose /talk is open, shows that claude -is open, and is answered there. A loop whose process is gone drops off the list. q quits +loop-inbox running. A loop with claude open, for a release ready to cut, the routing calls or a +/talk, says where, and is answered there. A loop whose process is gone drops off the list. A loop +asking for its project's model, as on a project's first run, asks on its own terminal only. q quits loop-inbox; the loops keep waiting. The loops' questions are files in ~/.local/state/loop-claude, read and written as @@ -25,6 +27,7 @@ Exit 2 when stdin or stdout is not a terminal, or on an unknown argument. """ import contextlib import curses +import dataclasses import pathlib import sys import typing @@ -52,33 +55,44 @@ def main(argv: list[str], home: pathlib.Path) -> int: if not (sys.stdin.isatty() and sys.stdout.isatty()): print("loop-inbox: stdin or stdout is not a terminal; run it on one", file=sys.stderr) return 2 + # curses may hold keys it has read ahead, which only flushinp drops. + effects = dataclasses.replace(system_effects(), discard_typed=curses.flushinp) try: - curses.wrapper(lambda window: run(window, paths_from(home), system_effects())) + curses.wrapper(lambda window: run(window, lambda: off_screen(window), paths_from(home), effects)) except KeyboardInterrupt: pass return 0 -def run(window: curses.window, paths: Paths, effects: Effects) -> None: +def run(window: curses.window, screen_off: typing.Callable[[], typing.ContextManager[None]], paths: Paths, effects: Effects) -> None: folder = paths.waiting window.timeout(REFRESH_MS) screen: Screen = Listing() while True: - screen = refreshed(screen, folder, effects.alive) + screen = entered(screen, refreshed(screen, folder, effects.alive), effects) draw(window, screen, effects) try: key = window.get_wch() except curses.error: continue # No key within REFRESH_MS. + after: Screen match pressed(screen, key_name(key)): case Quit(): return case Send(ask, text): - screen = Listing(note=sent(folder, ask, text)) + after = Listing(note=sent(folder, ask, text)) case Open(ask): - screen = Listing(note=opened(lambda: off_screen(window), paths, ask, effects)) + after = Listing(note=opened(screen_off, paths, ask, effects)) case Listing() | Answering() as next_screen: - screen = next_screen + after = next_screen + screen = entered(screen, after, effects) + + +def entered(before: Screen, after: Screen, effects: Effects) -> Screen: + """after, the screen that follows before. Leaving the answer screen drops the keys typed ahead, since on the list the rest of a pasted answer would pick a loop and answer it.""" + if isinstance(before, Answering) and isinstance(after, Listing): + effects.discard_typed() + return after def key_name(key: str | int) -> str: @@ -97,13 +111,16 @@ def refreshed(screen: Screen, folder: pathlib.Path, alive: typing.Callable[[int] def draw(window: curses.window, screen: Screen, effects: Effects) -> None: - height, width = window.getmaxyx() + height, columns = window.getmaxyx() + # The screen's last cell cannot be written without an error, so lines leave the last column empty. + width = columns - 1 now = effects.now() - lines = listing_lines(screen, now, effects.local_time, width) if isinstance(screen, Listing) else answering_lines(screen, now, effects.local_time, width) + lines, foot = listing_lines(screen, now, effects.local_time, width) if isinstance(screen, Listing) else answering_lines(screen, now, effects.local_time, width) window.erase() - for row, line in enumerate(fitted(lines, height)): - # The last cell of the screen cannot be written without an error, so each line stops one short of it. - window.addnstr(row, 0, line, width - 1) + for row, line in enumerate(fitted(lines, foot, height)): + # addnstr counts characters, not cells, so a line of wide characters, such as emoji, can still run into the last cell. + with contextlib.suppress(curses.error): + window.addnstr(row, 0, line, width) window.refresh() @@ -114,7 +131,7 @@ def still_waits(folder: pathlib.Path, ask: Ask) -> bool: def no_longer_waits(ask: Ask) -> str: - return f"{ask.root} no longer waits for that answer: it was answered on its terminal, or stopped." + return f"{ask.root} no longer waits for that answer: it was answered elsewhere, or stopped." def sent(folder: pathlib.Path, ask: Ask, text: str) -> str: @@ -135,15 +152,16 @@ def opened(screen_off: typing.Callable[[], typing.ContextManager[None]], paths: if isinstance(claimed, Failure): return f"Could not open claude for {ask.root}: {claimed.reason}" if not claimed: - return f"{ask.root} did not make way for claude within {MAKE_WAY_SECONDS:g} s; it was answered on its terminal, or stopped." + return f"Could not open claude for {ask.root}: the loop was answered elsewhere or stopped, or didn't respond within {MAKE_WAY_SECONDS:g} s. If it is still listed, pick it again." with screen_off(): try: unstarted = hand_over(ask.state.talk, paths, effects) finally: unsent = send(folder, ask, ClaudeEnded()) - said = f"Could not start claude for {ask.root}: {unstarted.reason}" if unstarted else f"claude for {ask.root} has ended; the loop goes on." - # Without ClaudeEnded, the loop goes on only once loop-inbox quits. - return f"{said} Could not tell the loop: {unsent.reason}; quit loop-inbox to let it go on." if unsent else said + # The loop goes on only where the human typed in the worker's session, as interrupt.human_typed checks. + said = f"Could not start claude for {ask.root}: {unstarted.reason}. The loop stops." if unstarted else f"claude for {ask.root} has ended; the loop goes on if you typed there, and stops if you didn't." + # The loop also stops waiting for claude once loop-inbox's process ends. + return f"{said} Could not tell the loop that claude ended: {unsent.reason}; it waits until you quit loop-inbox." if unsent else said @contextlib.contextmanager diff --git a/bin/loop_inbox/test_loop_inbox.py b/bin/loop_inbox/test_loop_inbox.py index 276e3c32..c13da1b5 100644 --- a/bin/loop_inbox/test_loop_inbox.py +++ b/bin/loop_inbox/test_loop_inbox.py @@ -7,6 +7,7 @@ import shutil import sys import tempfile import unittest +import unittest.mock sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) @@ -21,6 +22,7 @@ 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 +ANSWERED_ON_TERMINAL = object() def alive(pid): @@ -37,6 +39,44 @@ def keyed(screen, *keys): return screen +class OutOfKeys(Exception): + pass + + +class Window: + """A curses window that records the lines drawn on it, and hands out keys in turn, running each callable among them as it comes.""" + + def __init__(self, keys=(), height=24, width=80): + self.keys, self.height, self.width = list(keys), height, width + self.lines = {} + + def getmaxyx(self): + return self.height, self.width + + def timeout(self, milliseconds): + pass + + def get_wch(self): + while self.keys and callable(self.keys[0]): + self.keys.pop(0)() + if not self.keys: + raise OutOfKeys + return self.keys.pop(0) + + def drop_typed(self): + """Drops the keys not yet read, as curses.flushinp does.""" + self.keys.clear() + + def erase(self): + self.lines = {} + + def addnstr(self, row, column, text, count): + self.lines[row] = text[:count] + + def refresh(self): + pass + + class Answers(unittest.TestCase): def setUp(self): self.folder = pathlib.Path(tempfile.mkdtemp()) @@ -63,9 +103,15 @@ class Answers(unittest.TestCase): picked = keyed(Listing(tuple(waiting.waiting(self.folder, alive))), "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 on its terminal, or stopped.") + 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"]) + 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)): + waiting.publish(self.folder, ask) + self.assertEqual(main.refreshed(Listing(note="Sent to /a."), self.folder, alive), 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") @@ -83,7 +129,7 @@ class Answers(unittest.TestCase): waiting.publish(self.folder, ask) self.assertEqual(main.refreshed(Answering(ask, "Us"), self.folder, alive), 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 on its terminal, or stopped.")) + 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.")) 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.""" @@ -96,8 +142,12 @@ class Answers(unittest.TestCase): def test_talk_opens_claude_only_once_the_loop_has_made_way_for_this_loop_inbox(self): ask = asked("s1", "/code/log") + def made_way_for_the_claim(): + claim = waiting.answered(self.folder, ask) + if isinstance(claim, waiting.ClaudeOpening): + waiting.publish(self.folder, dataclasses.replace(ask, state=OpenInInbox(claim.pid))) for loop_does, claimed in ( - (lambda: waiting.publish(self.folder, dataclasses.replace(ask, state=OpenInInbox(INBOX))), (True, 0.1)), + (made_way_for_the_claim, (True, 0.1)), (lambda: waiting.withdraw(self.folder, "s1"), (False, 0.1)), (lambda: waiting.publish(self.folder, dataclasses.replace(ask, state=OpenOnTerminal())), (False, 0.1)), (lambda: waiting.publish(self.folder, dataclasses.replace(ask, state=OpenInInbox(7))), (False, 0.1)), @@ -115,33 +165,57 @@ class Answers(unittest.TestCase): self.assertEqual((waiting.answered(self.folder, ask), waiting.claude_ended(self.folder, ask)), (None, True)) +def never_opens(args, cwd, env): + raise AssertionError("claude opened") + + class Opens(unittest.TestCase): def setUp(self): home = pathlib.Path(tempfile.mkdtemp()) self.addCleanup(shutil.rmtree, home) self.paths = paths_from(home) + self.ask = asked("s1", "/code/log") + waiting.publish(self.paths.waiting, self.ask) - def open(self, claude): - """What /talk in loop-inbox says for an ask whose loop makes way at once; claude stands in for claude_on_terminal. Sets self.ended to whether it told the loop that claude ended.""" - ask = asked("s1", "/code/log") - waiting.publish(self.paths.waiting, ask) - def made_way(_): - waiting.publish(self.paths.waiting, dataclasses.replace(ask, state=OpenInInbox(INBOX))) - effects = dataclasses.replace(system_effects(), claude_on_terminal=claude, git=lambda *args, **kwargs: Failure("not a checkout"), now=lambda: 0.0, pid=lambda: INBOX, sleep=made_way) + def open(self, claude, loop_shows=OpenInInbox(INBOX)): + """What /talk in loop-inbox says for self.ask, whose loop shows loop_shows once claim_talk has asked it to make way; claude stands in for claude_on_terminal. Sets self.ended to whether it told the loop that claude ended.""" + def loop_looks(_): + waiting.publish(self.paths.waiting, dataclasses.replace(self.ask, state=loop_shows)) + effects = dataclasses.replace(system_effects(), claude_on_terminal=claude, git=lambda *args, **kwargs: Failure("not a checkout"), now=lambda: 0.0, pid=lambda: INBOX, sleep=loop_looks) try: with contextlib.redirect_stderr(io.StringIO()): - return main.opened(contextlib.nullcontext, self.paths, ask, effects) + return main.opened(contextlib.nullcontext, self.paths, self.ask, effects) finally: - self.ended = waiting.claude_ended(self.paths.waiting, ask) + self.ended = waiting.claude_ended(self.paths.waiting, self.ask) - def test_tells_the_loop_once_claude_ends_or_cannot_start(self): + def test_tells_the_loop_once_claude_ends_or_cannot_start_and_says_what_the_loop_does(self): def unstarted(args, cwd, env): raise OSError(2, "No such file or directory") - for claude, said in ((lambda args, cwd, env: 0, "claude for /code/log has ended; the loop goes on."), (unstarted, "Could not start claude for /code/log: No such file or directory")): + for claude, said in ( + (lambda args, cwd, env: 0, "claude for /code/log has ended; the loop goes on if you typed there, and stops if you didn't."), + (unstarted, "Could not start claude for /code/log: No such file or directory. The loop stops."), + ): with self.subTest(said=said): + waiting.publish(self.paths.waiting, self.ask) self.assertEqual(self.open(claude), said) self.assertTrue(self.ended) + def test_says_the_loop_waits_for_loop_inbox_to_quit_where_it_cannot_tell_it_that_claude_ended(self): + def folder_lost(args, cwd, env): + shutil.rmtree(self.paths.waiting) + self.paths.waiting.write_text("") + said = "claude for /code/log has ended; the loop goes on if you typed there, and stops if you didn't. Could not tell the loop that claude ended: Not a directory; it waits until you quit loop-inbox." + self.assertEqual(self.open(folder_lost), said) + + def test_opens_no_claude_for_a_loop_that_takes_talk_on_its_terminal_first(self): + said = "Could not open claude for /code/log: the loop was answered elsewhere or stopped, or didn't respond within 5 s. If it is still listed, pick it again." + self.assertEqual(self.open(never_opens, loop_shows=OpenOnTerminal()), said) + + 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()), []) + def test_tells_the_loop_when_claude_is_interrupted(self): def interrupted(args, cwd, env): raise KeyboardInterrupt @@ -150,14 +224,46 @@ class Opens(unittest.TestCase): self.assertTrue(self.ended) +class Typing(unittest.TestCase): + def typed(self, *keys): + """What the log and bender loops get once keys are typed into loop-inbox, which lists log first. ANSWERED_ON_TERMINAL among the keys stands for log being answered on its terminal. Fails where loop-inbox quits before the keys run out.""" + 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) + for ask in (log, bender): + waiting.publish(paths.waiting, ask) + def answered_on_terminal(): + waiting.withdraw(paths.waiting, "s1") + 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) + 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) + + def test_keys_typed_ahead_are_dropped_once_the_answer_screen_is_left(self): + # Each case types, after leaving log's answer screen, a line that would pick bender and one that would answer it, or a line that would quit. + for case, keys, got in ( + ("a pasted answer", "1\nYes.\nSee item 2.\nThen release.\n", (Typed("Yes."), None)), + ("a pasted answer with a line that would quit", "1\nOk.\nquick check first\n", (Typed("Ok."), None)), + ("/talk", "1\n/talk\n2\nUse B.\n", (None, None)), + ("a paste that opens with an empty line", "1\n\nSee item 2.\nThen release.\n", (None, None)), + ("an answer typed as log is answered on its terminal", ["1", "\n", "U", "s", "e", ANSWERED_ON_TERMINAL, *" option 1.\nThen release.\n"], (None, None)), + ): + with self.subTest(case): + self.assertEqual(self.typed(*keys), got) + + class Keys(unittest.TestCase): def test_the_list_takes_a_number_and_quits_on_q(self): ask = asked("s1", "/code/log") for keys, after in ( (("q",), Quit()), (("1", "q"), Listing((ask,), "1")), - (("1", "2", BACKSPACE), Listing((ask,), "1")), + (("1", "2", "3", BACKSPACE), Listing((ask,), "12")), (("x",), Listing((ask,))), + (("Β²",), Listing((ask,))), ((ENTER,), Listing()), (("2", ENTER), Listing(note="No loop has the number 2.")), (("1", ENTER), Answering(ask)), @@ -170,7 +276,7 @@ class Keys(unittest.TestCase): for keys, after in ( ((*" Use B. ", ENTER), Send(ask, "Use B.")), ((*" /talk", ENTER), Open(ask)), - (("U", "x", BACKSPACE), Answering(ask, "U")), + (("U", "s", "e", "x", BACKSPACE), Answering(ask, "Use")), ((" ", ENTER), Listing()), (("U", ESCAPE), Listing()), (("\t",), Answering(ask)), @@ -196,17 +302,18 @@ class Waiting(unittest.TestCase): self.assertEqual(waiting.waiting(pathlib.Path(folder), alive), [early, late]) self.assertEqual(waiting.waiting(pathlib.Path(folder), lambda pid: True), [stopped, early, late]) - def test_leaves_out_an_ask_with_a_field_of_the_wrong_type_or_another_sessions_name(self): + 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")) + waiting.publish(path.parent, asked("s1", "/a", pid=1)) good = json.loads(path.read_text()) - self.assertEqual(waiting.read_ask(path), asked("s1", "/a")) + self.assertEqual(waiting.read_ask(path), asked("s1", "/a", pid=1)) for field, value in ( ("id", 1), ("session", "s2"), ("root", None), ("question", 3), + ("pid", 0), ("state", {"kind": "Asking", "talk": {"args": [1], "cwd": "/c", "env": {}}}), ("state", {"kind": "Asking", "talk": {"args": [], "cwd": "/c", "env": {"A": 1}}}), ): @@ -232,34 +339,111 @@ class Waiting(unittest.TestCase): class Shown(unittest.TestCase): + def drawn(self, screen, window): + """The lines draw puts on window for screen, 3700 s after the epoch.""" + main.draw(window, screen, dataclasses.replace(system_effects(), local_time=lambda seconds: f"<{seconds}>", now=lambda: 3700)) + return [window.lines[row] for row in range(len(window.lines))] + def test_the_list_shows_each_loops_checkout_wait_and_the_first_lines_of_its_question(self): log = asked("s1", "/code/log", "Which store should the cache use: Redis or SQLite? Redis is already deployed for sessions.", at=0) - cut = asked("s2", "/code/c", "Cut 0.4.0?", at=3600 * 25, state=OpenOnTerminal()) - lines = inbox.listing_lines(Listing((log, cut), "1"), 3600 * 26 + 120, lambda seconds: f"<{seconds}>", 34) - self.assertEqual(lines, [ + cut = asked("s2", "/code/c", "Cut 0.4.0?\nIts changelog is ready.", at=3600 * 25, state=OpenInInbox(INBOX)) + lines = inbox.listing_lines(Listing((log, cut), "1"), 3600 * 26 + 120, lambda seconds: f"<{seconds}>", 50) + self.assertEqual(lines, ([ "2 loops wait for you, oldest first.", "", "[1] /code/log, waiting since <0> (1 d 2 h)", - " Which store should the cache", - " use: Redis or SQLite? Redis is…", + " Which store should the cache use: Redis or", + " SQLite? Redis is already deployed for…", "", - "[2] /code/c, waiting since <90000> (1 h 2 min); claude is open on its terminal", + "[2] /code/c, waiting since <90000> (1 h 2 min);", + "claude is open in loop-inbox", " Cut 0.4.0?", + " Its changelog is ready.", "", - "Type a number and Enter to answer that loop; q quits loop-inbox, and the loops keep waiting.", + ], [ + "Type a number and Enter to answer that loop; q", + "quits loop-inbox, and the loops keep waiting.", "> 1", - ]) + ])) def test_an_empty_list_says_no_loop_waits(self): - self.assertEqual(inbox.listing_lines(Listing(note="Sent to /a."), 0, str, 80), ["No loop waits for you.", "", "Sent to /a.", "q quits loop-inbox, and the loops keep waiting.", "> "]) + self.assertEqual(inbox.listing_lines(Listing(note="Sent to /a."), 0, str, 79), (["No loop waits for you.", ""], ["Sent to /a.", "q quits loop-inbox, and the loops keep waiting.", "> "])) - def test_the_answer_screen_shows_the_whole_question_and_says_what_enter_alone_does(self): - lines = inbox.answering_lines(Answering(asked("s1", "/code/log", "A or B?\n\nB is cheaper.", at=0), "Use B"), 59, lambda seconds: f"<{seconds}>", 80) - self.assertEqual(lines, ["/code/log, waiting since <0> (0 min):", "", "A or B?", "", "B is cheaper.", "", "Answer (/talk opens claude; Enter alone, or Esc, goes back, and the loop keeps waiting): Use B"]) + def test_the_answer_screen_at_80_columns_shows_every_character_of_each_line_and_says_what_enter_alone_does(self): + # The question's first line has 80 characters, one more than a line drawn at 80 columns holds. + ask = asked("s1", "/code/log", "The changelog lists four fixes and three new tools, so the next release is 0.6.0\n\nCut it?", at=100) + self.assertEqual(self.drawn(Answering(ask, "Yes"), Window(width=80)), [ + "/code/log, waiting since <100> (1 h 0 min):", + "", + "The changelog lists four fixes and three new tools, so the next release is", + "0.6.0", + "", + "Cut it?", + "", + "Answer (/talk opens claude; Enter alone, or Esc, goes back, and the loop keeps", + "waiting): Yes", + ]) - def test_a_screen_too_short_keeps_the_prompt_and_marks_the_cut(self): - self.assertEqual(inbox.fitted(["a", "b", "c", "d", "> "], 4), ["a", "b", "…", "> "]) - self.assertEqual(inbox.fitted(["a", "> "], 4), ["a", "> "]) + def test_an_answer_longer_than_its_line_goes_on_below_it_with_every_space_typed(self): + typed = "Use B, as the cache then runs next to the sessions it serves and then cut 0.6.0." + lines = self.drawn(Answering(asked("s1", "/code/log", "A or B?", at=100), typed), Window(width=80)) + self.assertEqual(lines[-2:], ["waiting): Use B, as the cache then runs next to the sessions it serves and then", " cut 0.6.0."]) + + def test_a_line_that_runs_into_the_screens_last_cell_leaves_the_screen_drawn(self): + class Refusing(Window): + """Refuses the screen's last row, as curses refuses a line of wide characters, such as emoji, that runs into the last cell.""" + + def addnstr(self, row, column, text, count): + super().addnstr(row, column, text, count) + if row == self.height - 1: + raise main.curses.error("addnwstr() returned ERR") + self.assertEqual(self.drawn(Listing(), Refusing(height=3)), ["…", "q quits loop-inbox, and the loops keep waiting.", "> "]) + + def test_a_screen_too_short_keeps_the_foot_and_marks_the_cut(self): + for lines, foot, height, shown in ( + (["a", "b", "c"], ["> "], 4, ["a", "b", "c", "> "]), + (["a", "b", "c"], ["> "], 3, ["a", "…", "> "]), + (["a", "b", "c"], ["n", "> "], 4, ["a", "…", "n", "> "]), + (["a", "b", "c", "d"], ["n", "h", "> "], 2, ["h", "> "]), + ): + with self.subTest(lines=lines, foot=foot, height=height): + self.assertEqual(inbox.fitted(lines, foot, height), shown) + + def test_a_wait_reads_in_minutes_under_an_hour_and_in_hours_under_a_day(self): + for seconds, read in ((3599, "59 min"), (3600, "1 h 0 min"), (86399, "23 h 59 min"), (86400, "1 d 0 h")): + with self.subTest(seconds=seconds): + self.assertEqual(inbox.waited(seconds), read) + + +class Terminal(io.StringIO): + def isatty(self): + return True + + +class Starts(unittest.TestCase): + def started(self, argv, stdin, stdout): + """What main returns for argv, run with stdin and stdout, and what it writes to stderr.""" + stderr = io.StringIO() + with unittest.mock.patch.object(sys, "stdin", stdin), contextlib.redirect_stdout(stdout), contextlib.redirect_stderr(stderr): + code = main.main(argv, pathlib.Path("/no home")) + return code, stderr.getvalue() + + def test_help_prints_the_docstring(self): + for flag in ("-h", "--help"): + with self.subTest(flag): + stdout = io.StringIO() + self.assertEqual(self.started([flag], io.StringIO(), stdout), (0, "")) + self.assertEqual(stdout.getvalue(), f"{main.__doc__.strip()}\n") + + def test_exits_2_on_an_unknown_argument_or_off_a_terminal(self): + off_a_terminal = "loop-inbox: stdin or stdout is not a terminal; run it on one\n" + for case, argv, stdin, stdout, said in ( + ("an unknown argument", ["--x"], Terminal(), Terminal(), "loop-inbox: unknown argument --x; usage: loop-inbox\n"), + ("stdout off a terminal", [], Terminal(), io.StringIO(), off_a_terminal), + ("stdin off a terminal", [], io.StringIO(), Terminal(), off_a_terminal), + ): + with self.subTest(case): + self.assertEqual(self.started(argv, stdin, stdout), (2, said)) if __name__ == "__main__": diff --git a/docs/decisions.md b/docs/decisions.md index 67022e63..db157bc8 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -103,14 +103,14 @@ Valid while cache reads cost a twentieth of input and Claude Code's compaction k ## loop-inbox: a waiting loop-claude lists its question as one file per session under `~/.local/state/loop-claude/`, and takes the first answer, from its terminal or from loop-inbox, that names that question -2026-10-28, lilleman, todo item 243. Serves goal 1. With several loops running, each asked on its own terminal, and the human searched the terminals for the ones that waited. loop-inbox lists them all, oldest first, and answers each one there. `bin/loop_claude/waiting.py` holds the protocol: -- 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. +2026-10-28, lilleman, todo item 243. Serves goal 1. With several loops running, each asked on its own terminal, and the human searched the terminals for the ones that waited. loop-inbox lists every loop's interrupts, the routing calls included, oldest first, and the human answers each one there. A loop asking for its project's model, as on a project's first run, asks on its terminal only: the human has just started it there, and no worker session exists yet. `bin/loop_claude/waiting.py` holds the protocol: - An answer reaching the wrong loop is the worst failure. Each answer names the question it answers by a fresh id, so an answer meant for an earlier question, or sent as the terminal answered, never answers a later one. - `/talk` from loop-inbox waits for the loop to stop reading its terminal before claude opens, so only one claude holds the worker's session. -- While claude holds the session, as for a release ready to cut or a `/talk` typed on the loop's terminal, loop-inbox lists the loop but takes no answer for it. -- loop-inbox runs the claude command the loop wrote, `bypassPermissions` included, so it runs in the same sandbox as the loop. The folder is private to the user. +- 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. -A bench of three readers seated as the README's audience picked the name `loop-inbox`, 3–0, and a block per loop: its checkout's path, how long it has waited, and the question's first two lines. +A bench of three readers seated as the README's audience picked the name `loop-inbox`, 3–0. Valid while every loop and loop-inbox run on one machine under one user's home.