From a7fe878631984c9204b8e080b5ce508be85e68b9 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Wed, 28 Oct 2026 23:24:29 +0100 Subject: [PATCH] Show every waiting loop-claude in loop-inbox and take each one's answer there --- .gitignore | 3 + AGENTS.md | 3 +- CHANGELOG.md | 1 + README.md | 6 +- bin/judge_replay/test_judge_replay.py | 2 +- bin/loop-inbox | 9 ++ bin/loop_claude/cycle/interrupt.py | 92 ++++++++++-- bin/loop_claude/cycle/run.py | 25 ++-- bin/loop_claude/cycle/states.py | 14 +- bin/loop_claude/effects.py | 21 +++ bin/loop_claude/loop/main.py | 18 ++- bin/loop_claude/paths.py | 3 + bin/loop_claude/test_black_box.py | 15 ++ bin/loop_claude/test_loop_claude.py | 133 ++++++++++++++---- bin/loop_claude/waiting.py | 136 ++++++++++++++++++ bin/loop_inbox/__init__.py | 0 bin/loop_inbox/inbox.py | 146 +++++++++++++++++++ bin/loop_inbox/main.py | 176 +++++++++++++++++++++++ bin/loop_inbox/test_loop_inbox.py | 177 ++++++++++++++++++++++++ bin/repo_checks/test_import_order.py | 2 +- bin/review_replay/test_review_replay.py | 2 +- docs/decisions.md | 17 ++- docs/reading-cost.md | 4 + todo.md | 14 -- 24 files changed, 938 insertions(+), 81 deletions(-) create mode 100755 bin/loop-inbox create mode 100644 bin/loop_claude/waiting.py create mode 100644 bin/loop_inbox/__init__.py create mode 100644 bin/loop_inbox/inbox.py create mode 100644 bin/loop_inbox/main.py create mode 100644 bin/loop_inbox/test_loop_inbox.py diff --git a/.gitignore b/.gitignore index c9618c2f..0dfe63ed 100644 --- a/.gitignore +++ b/.gitignore @@ -42,6 +42,9 @@ !bin/loop_claude/ !bin/loop_claude/**/ !bin/loop_claude/**/*.py +!bin/loop-inbox +!bin/loop_inbox/ +!bin/loop_inbox/*.py !bin/machine_load/ !bin/machine_load/*.py !bin/markdown_text.py diff --git a/AGENTS.md b/AGENTS.md index fc83c32b..a8c9579a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -10,12 +10,13 @@ Decisions live in `docs/decisions.md`: - larv-review: within a chunk lifting a project towards the comprehension floor, work on the project's lowest-scoring dimension comes first, and the floor doesn't block anything - loop-claude: a `claude` that cannot start is a failed worker run, retried - loop-claude: a judge decides each interrupt and each quoted answer from the transcript, the README's premises, `AGENTS.md`, `docs/decisions.md`, `~/.claude/CLAUDE.md`, `~/.claude/rules/` and larv-review's standards, and holds a chunk open while an answer the human typed in it is recorded nowhere; the worker's own account of which goal settles a choice decides nothing -- loop-claude: before it opens claude on the terminal, it marks the checkout and each of its worktrees trusted in `~/.claude.json` +- loop-claude: before it or loop-inbox opens claude on a terminal, it marks the checkout and each of its worktrees trusted in `~/.claude.json` - loop-claude: each project's model lives in `~/.claude/loop-claude-models.json`, which only loop-claude writes - loop-claude: every claude it starts bypasses permissions inside its sandbox - loop-claude: one session per project, its id derived from the checkout's path relative to `~/code`, or to `/` outside it - loop-claude: the archive keeps the raw transcript, and a failed archive stops the loop - loop-claude: the worker's claude compacts its context before it fills a 200k window, at about 170k tokens, and `CLAUDE.md` β†’ "Compact instructions" says what the summary keeps +- 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 - machine load: a heavy command waits for one of the machine's heavy slots, one for every 4 CPUs, which every session shares, and loop-claude starts a worker only while at least a quarter of the machine's memory is available - machine load: every container a session starts has a memory limit and a swap limit as large as its work needs; rule-hook's `docker-run-memory` blocks a `docker run` or `docker create` without them outside run-heavy, under which a container that lacks them gets the slot's share of three quarters of the memory; and no daemon-wide cap limits all containers together - principles: about seven things per level, four or five where they act on each other, more where a reader finds them by name; crossing a limit asks for a grouping or a recorded reason diff --git a/CHANGELOG.md b/CHANGELOG.md index 6de37e6b..a9176223 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +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. - `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. - `loop-claude` now opens every message it prints with the machine's local time, as in `2026-10-28 11:46:01`, so you can see when each happened, such as how long a question has waited. A message of several lines, such as a question, carries the time on its first line only. The `retrying at …` time of a usage-limit wait now also shows seconds, and no longer names the zone. diff --git a/README.md b/README.md index 66978645..07c1b8fe 100644 --- a/README.md +++ b/README.md @@ -66,7 +66,7 @@ Then pick a model with `/model`. After a pick, `git status` may list `settings.json`, and a `git pull` that changes the file refuses to run. `git add settings.json` stages no change and clears both. Once it is staged, such a pull goes through and drops the model: pick it again. -Link `loop-claude` onto `PATH`: `ln -s ~/.claude/bin/loop-claude ~/.local/bin/loop-claude`. Every claude it starts, the interactive ones included, skips every permission prompt. +Link `loop-claude` and `loop-inbox` onto `PATH`: `ln -s ~/.claude/bin/loop-claude ~/.local/bin/loop-claude` and `ln -s ~/.claude/bin/loop-inbox ~/.local/bin/loop-inbox`. Every claude they start, the interactive ones included, skips every permission prompt. ## Update @@ -93,12 +93,13 @@ Rename `## Unreleased` in `CHANGELOG.md` to the version, commit, tag that commit ## Tools -Install puts only `loop-claude` on `PATH`; call the others by their path, such as `~/.claude/bin/metric-bench`, from the project's checkout. +Install puts only `loop-claude` and `loop-inbox` on `PATH`; call the others by their path, such as `~/.claude/bin/metric-bench`, from the project's checkout. - `chunk-preflight` finds the mechanical facts a chunk starts from and makes its worktree; `loop-claude` runs it before it routes each chunk, and `chunk-preflight --help` lists the facts. - `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. - `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. @@ -131,6 +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. - `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/judge_replay/test_judge_replay.py b/bin/judge_replay/test_judge_replay.py index d7cadc72..83ed1602 100644 --- a/bin/judge_replay/test_judge_replay.py +++ b/bin/judge_replay/test_judge_replay.py @@ -114,7 +114,7 @@ class Main(unittest.TestCase): result = reply(Rung(args[args.index("--model") + 1], args[args.index("--effort") + 1]), "said Verdict: interrupt" in prompt.rsplit("latest last:", 1)[-1]) return subprocess.CompletedProcess(args, 0, json.dumps(result), "") - effects = Effects(claude=claude, claude_on_terminal=unused, discard_typed=unused, execv=unused, git=unused, input=unused, local_time=unused, memory=unused, now=unused, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused) + effects = Effects(claude=claude, claude_on_terminal=unused, discard_typed=unused, execv=unused, git=unused, input=unused, input_or=unused, local_time=unused, memory=unused, now=unused, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused) out, err = io.StringIO(), io.StringIO() with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): code = main.main(argv, {}, self.home, effects) diff --git a/bin/loop-inbox b/bin/loop-inbox new file mode 100755 index 00000000..de1b22e1 --- /dev/null +++ b/bin/loop-inbox @@ -0,0 +1,9 @@ +#!/usr/bin/env python3 +import pathlib +import sys + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent)) + +from loop_inbox import main + +sys.exit(main.main(sys.argv[1:], pathlib.Path.home())) diff --git a/bin/loop_claude/cycle/interrupt.py b/bin/loop_claude/cycle/interrupt.py index 1978ab2d..a26dbce0 100644 --- a/bin/loop_claude/cycle/interrupt.py +++ b/bin/loop_claude/cycle/interrupt.py @@ -1,7 +1,10 @@ import dataclasses +import os import sys +import typing import uuid +from loop_claude.waiting import alive, answered, Ask, publish, TalkCommand, Talked, Talking, Typed, withdraw from loop_claude.effects import Effects, say from failure import Failure from claude_code.transcript import human_turns, read_transcript @@ -15,41 +18,102 @@ 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. TALK = "/talk" ASK_ANSWER = f"Answer ({TALK} opens claude, Enter stops the loop): " +# Seconds between looks at whether the claude loop-inbox opened has ended. +TALK_POLL = 0.5 @dataclasses.dataclass(frozen=True) class Talk: - """The human answers in the worker's claude session, which talk opens.""" + """The human answers in the worker's claude session, which talk opens on loop-claude's terminal.""" -def put_question(question: str, answer_here: bool, effects: Effects) -> str | Talk | Stop: - """Prints question for the human. Where answer_here, returns the line they type at loop-claude's terminal, stripped, or Talk where they type TALK; else Talk at once. A Stop where loop-claude is off a terminal, or they type nothing, or the input ends.""" +@dataclasses.dataclass(frozen=True) +class WorkerSession: + """The worker's claude session, which /talk opens on loop-claude's terminal or in loop-inbox.""" + root: str + id: uuid.UUID + rung: Rung + transcript_path: str + # What the worker's claude adds to its environment, as the claude /talk opens does. + env: dict[str, str] + + def talk_command(self) -> TalkCommand: + return TalkCommand(claude_args(self.rung, ["--resume", str(self.id)]), self.root, self.env) + + +def put_question(question: str, answer_here: bool, session: WorkerSession, paths: Paths, effects: Effects) -> str | Talk | Talked | Stop: + """Prints question for the human. Where answer_here, shows it in loop-inbox too and returns the first answer: the line they type at loop-claude's terminal, stripped, or Talk where they type TALK; a line typed in loop-inbox; or Talked once the claude loop-inbox opened ends with something typed. Else Talk at once. A Stop where loop-claude is off a terminal, or they type nothing, or the input ends.""" say(f"\n{question}", effects) if stop := needs_terminal(ANSWER_QUESTION, effects.on_terminal()): 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, input takes the first line; the rest wait, and the next question drops them. A longer answer goes through TALK. + # 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() if not answer_here: return Talk() + ask = Ask(str(uuid.uuid4()), str(session.id), session.root, question, effects.now(), os.getpid(), session.talk_command()) + shown(paths, ask, effects) try: - answer = effects.input(ASK_ANSWER).strip() + answer = effects.input_or(ASK_ANSWER, lambda: answered(paths.waiting, ask)) + if isinstance(answer, Talking | Talked): + return talked_in_inbox(ask, answer, session.transcript_path, paths, effects) + if isinstance(answer, Typed): + say(f"Answered in loop-inbox: {answer.text}", effects) + answer = answer.text except EOFError: print(file=sys.stderr) # Ends the prompt's line. It isn't a message, so it gets no time. return needs_human(ANSWER_QUESTION, "the input ended") + finally: + withdraw(paths.waiting, ask.session) + answer = answer.strip() if not answer: return needs_human(ANSWER_QUESTION, "nothing was typed") return Talk() if answer == TALK else answer -def talk(root: str, session_id: uuid.UUID, worker: Rung, path: str, paths: Paths, env: dict[str, str], effects: Effects) -> Stop | None: - """Resumes the worker's session in claude on the terminal; the human must type something there.""" - entries = read_transcript(path) +def talked_in_inbox(ask: Ask, answer: Talking | Talked, transcript_path: str, paths: Paths, effects: Effects) -> Talked | Stop: + """Waits, off the terminal, while the claude that loop-inbox opened on the worker's session runs; the human must type something there.""" + def waited() -> None: + if isinstance(answer, Talked): + return + # Shows loop-inbox that the loop stopped reading its terminal, so loop-inbox may open claude. + shown(paths, dataclasses.replace(ask, talk=None, talking=answer.pid), effects) + say("claude is open for this question in loop-inbox; waiting for it to end", effects) + while not isinstance(answered(paths.waiting, ask), Talked) and alive(answer.pid): + effects.sleep(TALK_POLL) + return human_typed(transcript_path, waited) or Talked() + + +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.""" + if unshown := publish(paths.waiting, ask): + say(f"loop-inbox cannot show this question: {unshown.reason}", effects) + + +def talk(question: str, session: WorkerSession, paths: Paths, effects: Effects) -> Stop | None: + """Resumes the worker's session in claude on the terminal, listed in loop-inbox while it runs; the human must type something there.""" + ask = Ask(str(uuid.uuid4()), str(session.id), session.root, question, effects.now(), os.getpid(), talk=None) + shown(paths, ask, effects) + try: + return human_typed(session.transcript_path, lambda: opened(session, paths, effects)) + finally: + withdraw(paths.waiting, ask.session) + + +def opened(session: WorkerSession, paths: Paths, effects: Effects) -> Stop | None: + if unstarted := hand_over(session.rung, ["--resume", str(session.id)], session.root, paths, session.env, effects): + return Stop(1, f"could not start claude for the interrupt: {unstarted.reason}") + return None + + +def human_typed(transcript_path: str, held_open: typing.Callable[[], Stop | None]) -> Stop | None: + """Runs held_open, which returns once the claude the human answers in has ended, then checks that the human typed something there.""" + entries = read_transcript(transcript_path) if isinstance(entries, Failure): return Stop(1, entries.reason) before = human_turns(entries) - if unstarted := hand_over(worker, ["--resume", str(session_id)], root, paths, env, effects): - return Stop(1, f"could not start claude for the interrupt: {unstarted.reason}") - entries = read_transcript(path) + if stop := held_open(): + return stop + entries = read_transcript(transcript_path) if isinstance(entries, Failure): return Stop(1, f"could not tell whether you typed anything: {entries.reason}") return None if human_turns(entries) > before else needs_human(ANSWER_QUESTION, "the interrupt ended with nothing typed") @@ -59,7 +123,11 @@ def hand_over(rung: Rung, args: list[str], root: str, paths: Paths, env: dict[st """Marks the checkout and each of its worktrees trusted, then runs claude on the terminal in root, on rung, with env added to its environment; the failure is why claude could not start.""" trust(paths.claude_json, worktrees(root, effects), lambda text: say(text, effects)) try: - effects.claude_on_terminal([*rung.flags(), "--permission-mode", "bypassPermissions", *args], root, env) + effects.claude_on_terminal(claude_args(rung, args), root, env) except OSError as failure: return Failure(str(failure.strerror)) return None + + +def claude_args(rung: Rung, args: list[str]) -> list[str]: + return [*rung.flags(), "--permission-mode", "bypassPermissions", *args] diff --git a/bin/loop_claude/cycle/run.py b/bin/loop_claude/cycle/run.py index 449b0f3b..7d419a0e 100644 --- a/bin/loop_claude/cycle/run.py +++ b/bin/loop_claude/cycle/run.py @@ -14,7 +14,7 @@ from loop_claude.cycle.judge import judge, Rejected from transcript_archive import outcomes from loop_claude.paths import Paths from loop_claude.cycle import prompts -from loop_claude.cycle.interrupt import put_question, talk, Talk +from loop_claude.cycle.interrupt import put_question, talk, Talk, Talked, WorkerSession from claude_code.transcript import read_transcript from loop_claude.cycle.retry import retried from model_routing.route import Route @@ -99,8 +99,8 @@ def step(cycle: Cycle, state: Active) -> Event | Stop: return rule(cycle, transcript_path) case Interrupting(transcript_path, ruling, _, step_up): return ask(cycle, transcript_path, ruling, step_up) - case Talking(transcript_path, _): - return talk(cycle.root, cycle.session.id, cycle.route.rung, transcript_path, cycle.paths, worker_environment(cycle), cycle.effects) or HumanTalked() + case Talking(transcript_path, question, _): + return talk(question, worker_session(cycle, transcript_path), cycle.paths, cycle.effects) or HumanTalked() case Closing(transcript_path, verdict): return close(cycle, transcript_path, verdict) case _: @@ -124,6 +124,10 @@ def worker_environment(cycle: Cycle) -> dict[str, str]: return {**worker_rungs.environment(cycle.project, cycle.route), AUTO_COMPACT_WINDOW: str(COMPACT_WINDOW)} +def worker_session(cycle: Cycle, transcript_path: str) -> WorkerSession: + return WorkerSession(cycle.root, cycle.session.id, cycle.route.rung, transcript_path, worker_environment(cycle)) + + def worker_start(cycle: Cycle, answered: QuotedAnswer | TypedAnswer | None, step_up: StepUp | None) -> list[str]: if isinstance(answered, QuotedAnswer): return worker_args(cycle.session, cycle.route.rung, prompts.answered(answered.question, answered.answer, cycle.route, cycle.project, step_up is not None), resume=True) @@ -160,7 +164,7 @@ def keep_rejection(cycle: Cycle, transcript_path: str, rejected: Rejected) -> St return None -def ask(cycle: Cycle, transcript_path: str, ruling: Interrupt | QuotedAnswer, step_up: StepUp | None) -> HumanTyped | TalkChosen | Stop: +def ask(cycle: Cycle, transcript_path: str, ruling: Interrupt | QuotedAnswer, step_up: StepUp | None) -> HumanTyped | TalkChosen | HumanTalked | Stop: question = question_for(ruling) # Archived now, so the transcript the question was asked on is kept with it; the human's answer then grows the transcript. # The interrupt names the rung the worker ran on before it; a step-up archived after it names the stepped rung, so the figures charge each stretch to its own rung. @@ -168,11 +172,16 @@ def ask(cycle: Cycle, transcript_path: str, ruling: Interrupt | QuotedAnswer, st if failure := archive_stepped(cycle, transcript_path, interrupted, step_up): return Stop(1, failure.reason) # Only the human may cut a release, so a release ready to cut opens claude's session at once. - answer = put_question(question, not (isinstance(ruling, Interrupt) and ruling.release_ready), cycle.effects) - if isinstance(answer, Stop): - return answer + answer = put_question(question, not (isinstance(ruling, Interrupt) and ruling.release_ready), worker_session(cycle, transcript_path), cycle.paths, cycle.effects) + match answer: + case Stop(): + return answer + case Talk(): + return TalkChosen(question) + case Talked(): + return HumanTalked() # The worker gets the question it asked, not the one put to the human past the cap. - return TalkChosen() if isinstance(answer, Talk) else HumanTyped(TypedAnswer(ruling.question, answer)) + return HumanTyped(TypedAnswer(ruling.question, answer)) def ran_on(cycle: Cycle, step_up: StepUp | None) -> Route: diff --git a/bin/loop_claude/cycle/states.py b/bin/loop_claude/cycle/states.py index c8790b81..29677c1b 100644 --- a/bin/loop_claude/cycle/states.py +++ b/bin/loop_claude/cycle/states.py @@ -42,8 +42,9 @@ class Interrupting: @dataclasses.dataclass(frozen=True) class Talking: - """The human answers in the worker's claude session, on the terminal.""" + """The human answers in the worker's claude session, on the terminal; question is what they were asked.""" transcript_path: str + question: str quoted_answers: int = 0 @@ -81,12 +82,13 @@ class HumanTyped: @dataclasses.dataclass(frozen=True) class TalkChosen: - """The human typed /talk, or the interrupt is for a release ready to cut.""" + """The human typed /talk at loop-claude's terminal, or the interrupt is for a release ready to cut.""" + question: str @dataclasses.dataclass(frozen=True) class HumanTalked: - """The human typed in the worker's claude session.""" + """The human typed in the worker's claude session, opened on loop-claude's terminal or in loop-inbox.""" @dataclasses.dataclass(frozen=True) @@ -111,10 +113,10 @@ def transition(state: State, event: Event) -> State: return Closing(transcript_path, verdict) case Interrupting(_, _, quoted_answers, step_up), HumanTyped(typed): return Working(typed, quoted_answers, step_up) - case Interrupting(transcript_path, _, quoted_answers), TalkChosen(): - return Talking(transcript_path, quoted_answers) + case Interrupting(transcript_path, _, quoted_answers), TalkChosen(question): + return Talking(transcript_path, question, quoted_answers) # The human worked in the worker's claude session, so the judge rules again on the transcript it leaves. - case Talking(transcript_path, quoted_answers), HumanTalked(): + case Talking(transcript_path, _, quoted_answers) | Interrupting(transcript_path, _, quoted_answers), HumanTalked(): return Judging(transcript_path, quoted_answers) case Closing(_, verdict), Archived(): return Ended(verdict) diff --git a/bin/loop_claude/effects.py b/bin/loop_claude/effects.py index d65a4425..8bc40c77 100644 --- a/bin/loop_claude/effects.py +++ b/bin/loop_claude/effects.py @@ -1,5 +1,6 @@ import dataclasses import os +import select import subprocess import sys import termios @@ -9,6 +10,8 @@ import typing import git_repo from machine_load.memory import Memory, read_memory +# Seconds between calls input_or makes while nothing is typed. +POLL_SECONDS = 0.5 # Seconds before a Python script loop-claude runs is stopped, so a hung one, such as chunk-preflight, cannot hold the loop. PYTHON_TIMEOUT = 600 @@ -30,6 +33,8 @@ class Effects: execv: typing.Callable[[str, list[str]], None] git: git_repo.Git input: typing.Callable[[str], str] + # Prints a prompt, then returns the line typed at the terminal, or the first value other than None that the callable returns, called every POLL_SECONDS. Raises EOFError where the input ends. + input_or: typing.Callable[[str, typing.Callable[[], typing.Any]], typing.Any] # A date and time in the machine's zone, as `2026-10-28 11:46:01`. lilleman chose this spelling and local time over UTC on 2026-10-28, since the human reads these on their own clock. local_time: typing.Callable[[float], str] # The machine's memory; None where it cannot be read. @@ -62,6 +67,7 @@ def system_effects() -> Effects: execv=os.execv, git=git_repo.git, input=input, + input_or=input_or, local_time=lambda seconds: time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(seconds)), memory=read_memory, now=time.time, @@ -83,6 +89,21 @@ def run_python(args: list[str], cwd: str, timeout: float) -> subprocess.Complete return subprocess.CompletedProcess(command, 1, "", f"stopped after {timeout} s") +def input_or[T](prompt: str, other: typing.Callable[[], T | None]) -> str | T: + # On stderr, where input prints its prompt on a terminal. + print(prompt, end="", file=sys.stderr, flush=True) + while True: + if select.select([sys.stdin], [], [], POLL_SECONDS)[0]: + # On a terminal, one read returns at most one line, so nothing typed after it is buffered here, out of discard_typed's reach. + line = os.read(sys.stdin.fileno(), 65536) + if not line: + raise EOFError + return line.decode("utf-8", "replace").removesuffix("\n") + if (got := other()) is not None: + print(file=sys.stderr, flush=True) # Ends the prompt's line. + return got + + def say(text: str, effects: Effects, *, stdout: bool = False) -> None: """Prints text on stderr, or on stdout where stdout, opening the first line of words with the machine's local time. Blank lines before those words stay blank, and later lines get no time.""" body = text.lstrip("\n") diff --git a/bin/loop_claude/loop/main.py b/bin/loop_claude/loop/main.py index def511a9..eff4ed69 100644 --- a/bin/loop_claude/loop/main.py +++ b/bin/loop_claude/loop/main.py @@ -22,12 +22,15 @@ 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 and reads a one-line answer on its terminal. The worker resumes -headless with the answer. The judge reads it as the human's, so the chunk stays unfinished until the -answer is recorded. An empty answer stops the loop. Typing /talk instead opens the worker's session -on the terminal with `claude --resume`, to read the diff or discuss first. Once that claude exits, -the judge rules on what was typed there. A release ready to cut opens that session at once, since -only the human may cut it. Before claude opens, the checkout and each of its worktrees are marked +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: +- 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. +- 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 trusted in ~/.claude.json. As a chunk starts, before it is routed, loop-claude runs bin/chunk-preflight (bin/chunk_preflight/), @@ -110,7 +113,8 @@ Exit 2, when the human is needed to go on: - stdin or stdout is not a terminal, when a model must be picked or an interrupt answered - the input ends while a model is picked - an interrupt's answer is empty, or the input ends before one is typed -- the claude opened for /talk, or for a release ready to cut, ends with nothing typed +- the claude opened for /talk, here or in loop-inbox, or for a release ready to cut, ends with + nothing typed - the judge rules a chunk unfinished 6 cycles running; rerun to give it 6 more Rerunning resumes any open session. diff --git a/bin/loop_claude/paths.py b/bin/loop_claude/paths.py index fcca1544..ff0be455 100644 --- a/bin/loop_claude/paths.py +++ b/bin/loop_claude/paths.py @@ -10,6 +10,8 @@ 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). + waiting: pathlib.Path def paths_from(home: pathlib.Path) -> Paths: @@ -21,4 +23,5 @@ def paths_from(home: pathlib.Path) -> Paths: home=home, model_catalog=claude / "cache" / "model-catalog", models_file=claude / "loop-claude-models.json", + waiting=home / ".local" / "state" / "loop-claude", ) diff --git a/bin/loop_claude/test_black_box.py b/bin/loop_claude/test_black_box.py index d08131fe..df885baa 100644 --- a/bin/loop_claude/test_black_box.py +++ b/bin/loop_claude/test_black_box.py @@ -18,6 +18,7 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from test_env import isolated_env +from loop_claude import waiting BIN = pathlib.Path(__file__).resolve().parents[1] TASK = "Do the next chunk." @@ -726,6 +727,20 @@ class Interrupt(unittest.TestCase): self.assertIn("[human] B\n\nUsing B.", run.calls[3]["stdin"]) self.assertNotIn("stray", run.calls[3]["stdin"]) + def test_resumes_the_worker_headless_with_the_answer_typed_in_loop_inbox(self): + checkout = Checkout(self) + folder = checkout.home / ".local" / "state" / "loop-claude" + def answered_in_inbox(): + [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)) + self.assertEqual(run.code, 130) + 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()), []) + def test_hands_the_terminal_over_and_exits_2_when_nothing_is_typed(self): checkout = Checkout(self) checkout.git("commit", "--allow-empty", "--quiet", "-m", "start") diff --git a/bin/loop_claude/test_loop_claude.py b/bin/loop_claude/test_loop_claude.py index de1dd7b5..210eb985 100644 --- a/bin/loop_claude/test_loop_claude.py +++ b/bin/loop_claude/test_loop_claude.py @@ -22,7 +22,7 @@ from loop_claude.project import checkout, model_choice, records from chunk_pick import DefaultPlan, LastCut from loop_claude.effects import Effects, PYTHON_TIMEOUT, run_python, say, system_effects from claude_code import entries, reply, session -from loop_claude import escalation_mark, paths, routing +from loop_claude import escalation_mark, paths, routing, 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 @@ -81,6 +81,7 @@ class FakeEffects: execv=self.execv, git=lambda *args, cwd=None, timeout=None, guarded=False, errors="strict": self.answer("git", list(args)), input=lambda prompt: self.answer("input", prompt), + input_or=self.input_or, local_time=lambda seconds: f"<{seconds}>", memory=self.memory, now=lambda: NOW, @@ -94,6 +95,14 @@ class FakeEffects: self.calls.append(("memory", None)) 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.""" + self.calls.append(("input", prompt)) + answer = self.scripts["input"].pop(0) + if isinstance(answer, BaseException): + raise answer + return answer(other) if callable(answer) else answer + def on_terminal_claude(self, args, cwd, env): self.terminal_environments.append(env) return self.answer("claude_on_terminal", args) @@ -178,10 +187,13 @@ class Transitions(unittest.TestCase): (states.Judging("/t", 3), states.Ruled(Finished("e")), states.Closing("/t", Finished("e"))), (states.Judging("/t"), states.Ruled(Unfinished("e")), states.Closing("/t", Unfinished("e"))), (states.Judging("/t", 3), states.Ruled(Unfinished("e")), states.Closing("/t", Unfinished("e"))), - (states.Interrupting("/t", Interrupt("e", "q")), states.TalkChosen(), states.Talking("/t")), - (states.Interrupting("/t", Interrupt("e", "q"), 3), states.TalkChosen(), states.Talking("/t", 3)), - (states.Talking("/t"), states.HumanTalked(), states.Judging("/t")), - (states.Talking("/t", 3), states.HumanTalked(), states.Judging("/t", 3)), + (states.Interrupting("/t", Interrupt("e", "q")), states.TalkChosen("q"), states.Talking("/t", "q")), + (states.Interrupting("/t", Interrupt("e", "q"), 3), states.TalkChosen("q"), states.Talking("/t", "q", 3)), + (states.Talking("/t", "q"), states.HumanTalked(), states.Judging("/t")), + (states.Talking("/t", "q", 3), states.HumanTalked(), states.Judging("/t", 3)), + # The human talked in the claude loop-inbox opened. + (states.Interrupting("/t", Interrupt("e", "q")), states.HumanTalked(), states.Judging("/t")), + (states.Interrupting("/t", Interrupt("e", "q"), 3), states.HumanTalked(), states.Judging("/t", 3)), (states.Interrupting("/t", Interrupt("e", "q")), states.HumanTyped(TYPED), states.Working(TYPED)), (states.Interrupting("/t", Interrupt("e", "q"), 3), states.HumanTyped(TYPED), states.Working(TYPED, 3)), (states.Working(TYPED, 3), states.WorkerRan("/t"), states.Judging("/t", 3)), @@ -191,8 +203,8 @@ class Transitions(unittest.TestCase): for state, event, after in legal: with self.subTest(state=state, event=event): self.assertEqual(states.transition(state, event), after) - every_state = (states.Working(), states.Working(QuotedAnswer("e", "Which one?", "A."), 3), states.Working(TYPED, 3), states.Judging("/t"), states.Judging("/t", 3), states.Interrupting("/t", Interrupt("e", "q")), states.Interrupting("/t", Interrupt("e", "q"), 3), states.Talking("/t"), states.Talking("/t", 3), states.Closing("/t", Finished("e")), states.Ended(Finished("e"))) - every_event = (states.WorkerRan("/t"), states.Ruled(Interrupt("e", "Which one?")), answered, states.Ruled(Finished("e")), states.Ruled(Unfinished("e")), states.TalkChosen(), states.HumanTalked(), states.HumanTyped(TYPED), states.Archived()) + every_state = (states.Working(), states.Working(QuotedAnswer("e", "Which one?", "A."), 3), states.Working(TYPED, 3), states.Judging("/t"), states.Judging("/t", 3), states.Interrupting("/t", Interrupt("e", "q")), states.Interrupting("/t", Interrupt("e", "q"), 3), states.Talking("/t", "q"), states.Talking("/t", "q", 3), states.Closing("/t", Finished("e")), states.Ended(Finished("e"))) + every_event = (states.WorkerRan("/t"), states.Ruled(Interrupt("e", "Which one?")), answered, states.Ruled(Finished("e")), states.Ruled(Unfinished("e")), states.TalkChosen("q"), states.HumanTalked(), states.HumanTyped(TYPED), states.Archived()) for state in every_state: for event in every_event: if (state, event) not in [(state, event) for state, event, _ in legal]: @@ -207,7 +219,7 @@ class Transitions(unittest.TestCase): (states.Judging("/t", 3), states.Ruled(quoted, step_up), states.Interrupting("/t", quoted, 3, step_up)), (states.Judging("/t"), states.Ruled(interrupt, step_up), states.Interrupting("/t", interrupt, 0, step_up)), (states.Interrupting("/t", interrupt, 0, step_up), states.HumanTyped(TYPED), states.Working(TYPED, 0, step_up)), - (states.Interrupting("/t", interrupt, 0, step_up), states.TalkChosen(), states.Talking("/t")), + (states.Interrupting("/t", interrupt, 0, step_up), states.TalkChosen("q"), states.Talking("/t", "q")), (states.Working(TYPED, 0, step_up), states.WorkerRan("/t"), states.Judging("/t")), ): with self.subTest(state=state, event=event): @@ -638,11 +650,22 @@ class MemoryWait(unittest.TestCase): class Interrupts(unittest.TestCase): - def put(self, fake, answer_here=True): + def setUp(self): + self.home = pathlib.Path(tempfile.mkdtemp()) + self.addCleanup(shutil.rmtree, self.home) + self.paths = paths.paths_from(self.home) + self.transcript = self.home / "t.jsonl" + self.transcript.write_text(json.dumps(human("a")) + "\n") + self.session = interrupt.WorkerSession(str(self.home), uuid.uuid7(), Rung("m", "high"), str(self.transcript), {"LOOP_CLAUDE_WORKER_RUNG": "m at high effort"}) + + def put(self, fake, answer_here=True, effects=None): with contextlib.redirect_stderr(io.StringIO()) as said: - put = interrupt.put_question("Which one?", answer_here, fake.effects()) + put = interrupt.put_question("Which one?", answer_here, self.session, self.paths, effects or fake.effects()) return put, said.getvalue() + def asked(self): + return waiting.waiting(self.paths.waiting) + def test_stops_off_a_terminal_before_asking(self): fake = FakeEffects(on_terminal=False) self.assertEqual(self.put(fake), (Stop(2, "the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun loop-claude on a terminal"), f"\n{STAMP} Which one?\n")) @@ -665,24 +688,80 @@ 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()), []) + + def test_shows_the_question_in_loop_inbox_while_it_waits_and_only_then(self): + def typed(_): + [ask] = self.asked() + self.assertEqual((ask.session, ask.root, ask.question, ask.asked, ask.pid, ask.talking), (str(self.session.id), str(self.home), "Which one?", NOW, os.getpid(), None)) + self.assertEqual(ask.talk, waiting.TalkCommand(["--model", "m", "--effort", "high", "--permission-mode", "bypassPermissions", "--resume", str(self.session.id)], str(self.home), {"LOOP_CLAUDE_WORKER_RUNG": "m at high effort"})) + return "Use B." + self.assertEqual(self.put(FakeEffects(inputs=[typed]))[0], "Use B.") + self.assertEqual(list(self.paths.waiting.iterdir()), []) + + def test_takes_a_line_typed_in_loop_inbox_for_this_question_and_no_other(self): + def answered(_, other): + [ask] = self.asked() + waiting.send(self.paths.waiting, dataclasses.replace(ask, id="an earlier ask"), waiting.Typed("Use A.")) + self.assertIsNone(other()) + waiting.send(self.paths.waiting, ask, waiting.Typed(" Use C. ")) + return other() + 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()), []) + + def test_waits_off_the_terminal_while_loop_inbox_has_claude_open_and_goes_on_once_the_human_typed_there(self): + inbox = os.getpid() + def talking(other): + [ask] = self.asked() + waiting.send(self.paths.waiting, ask, waiting.Talking(inbox)) + return other() + def claude_ran(_): + [ask] = self.asked() + self.assertEqual((ask.talk, ask.talking), (None, inbox)) + with open(self.transcript, "a") as handle: + handle.write(json.dumps(human("cut it")) + "\n") + waiting.send(self.paths.waiting, ask, waiting.Talked()) + fake = FakeEffects(inputs=[talking]) + 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(list(self.paths.waiting.iterdir()), []) + + def test_stops_when_loop_inbox_ends_its_claude_or_is_gone_with_nothing_typed(self): + gone = subprocess.run([sys.executable, "-c", "import os; print(os.getpid())"], capture_output=True, text=True).stdout.strip() + for pid, ended in ((os.getpid(), True), (int(gone), False)): + with self.subTest(ended=ended): + def talking(other): + [ask] = self.asked() + waiting.send(self.paths.waiting, ask, waiting.Talking(pid)) + if ended: + waiting.send(self.paths.waiting, ask, waiting.Talked()) + return other() + self.assertEqual(self.put(FakeEffects(inputs=[talking]))[0], Stop(2, "the human is needed to answer the question above, but the interrupt ended with nothing typed")) + + def test_lists_the_claude_open_on_its_terminal_in_loop_inbox_while_it_runs(self): + def ran(args): + [ask] = self.asked() + self.assertEqual((ask.question, ask.talk, ask.talking), ("Cut 0.4.0?", None, None)) + return 0 + fake = FakeEffects(on_terminal_claude=[ran], git=[""]) + with contextlib.redirect_stderr(io.StringIO()): + interrupt.talk("Cut 0.4.0?", self.session, self.paths, fake.effects()) + self.assertEqual(len(fake.made("claude_on_terminal")), 1) + self.assertEqual(list(self.paths.waiting.iterdir()), []) def test_stops_when_nothing_was_typed_in_the_session(self): - with tempfile.TemporaryDirectory() as home: - path = pathlib.Path(home, "t.jsonl") - path.write_text(json.dumps(human("a")) + "\n") - fake = FakeEffects(on_terminal_claude=[0], git=[""]) - stop = interrupt.talk(home, uuid.uuid7(), Rung("m", "high"), str(path), paths.paths_from(pathlib.Path(home)), {}, fake.effects()) - self.assertEqual(fake.made("claude_on_terminal")[0][:4], ["--model", "m", "--effort", "high"]) - self.assertEqual(stop, Stop(2, "the human is needed to answer the question above, but the interrupt ended with nothing typed")) + fake = FakeEffects(on_terminal_claude=[0], git=[""]) + with contextlib.redirect_stderr(io.StringIO()): + stop = interrupt.talk("Which one?", self.session, self.paths, fake.effects()) + self.assertEqual(fake.made("claude_on_terminal")[0][:4], ["--model", "m", "--effort", "high"]) + self.assertEqual(stop, Stop(2, "the human is needed to answer the question above, but the interrupt ended with nothing typed")) def test_hands_the_claude_that_takes_the_terminal_the_workers_environment(self): - with tempfile.TemporaryDirectory() as home: - path = pathlib.Path(home, "t.jsonl") - path.write_text(json.dumps(human("a")) + "\n") - fake = FakeEffects(on_terminal_claude=[0], git=[""]) - handed = {"LOOP_CLAUDE_PROJECT_RUNG": "claude-opus-5-5 at medium effort", "LOOP_CLAUDE_WORKER_RUNG": "claude-haiku-5-5 at max effort"} - interrupt.talk(home, uuid.uuid7(), Rung("claude-haiku-5-5", "max"), str(path), paths.paths_from(pathlib.Path(home)), handed, fake.effects()) - self.assertEqual(fake.terminal_environments, [handed]) + fake = FakeEffects(on_terminal_claude=[0], git=[""]) + with contextlib.redirect_stderr(io.StringIO()): + interrupt.talk("Which one?", self.session, self.paths, fake.effects()) + self.assertEqual(fake.terminal_environments, [{"LOOP_CLAUDE_WORKER_RUNG": "m at high effort"}]) class RoutingCheck(unittest.TestCase): @@ -1579,9 +1658,9 @@ class ExitContract(unittest.TestCase): unreadable = f"README.md, or {', '.join(names[:-1])} or {names[-1]} where they exist, cannot be read or is not UTF-8" # Every Stop whose code is not a literal 0, 2 or 130, in source order: path, function, code, start of reason, its --help clause. clauses = [ - ("cycle/interrupt.py", "talk", "1", "entries.reason", read), - ("cycle/interrupt.py", "talk", "1", "f'could not start claude for the interrupt:", "claude cannot start for an interrupt"), - ("cycle/interrupt.py", "talk", "1", "f'could not tell whether you typed anything:", read), + ("cycle/interrupt.py", "opened", "1", "f'could not start claude for the interrupt:", "claude cannot start for an interrupt"), + ("cycle/interrupt.py", "human_typed", "1", "entries.reason", read), + ("cycle/interrupt.py", "human_typed", "1", "f'could not tell whether you typed anything:", read), ("cycle/retry.py", "retried", "1", "f'the {who} failed three times running:", "the worker or the judge fails three times running"), ("cycle/run.py", "archived_stop", "1", "f'{failure.reason}", read), ("cycle/run.py", "work", "1", "f'claude left no transcript for session", "claude leaves no transcript"), diff --git a/bin/loop_claude/waiting.py b/bin/loop_claude/waiting.py new file mode 100644 index 00000000..5e391b98 --- /dev/null +++ b/bin/loop_claude/waiting.py @@ -0,0 +1,136 @@ +"""The files by which a loop-claude that waits for the human shows its question 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. +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. + +/talk from loop-inbox goes in three steps, so that only one claude ever holds the worker's session: +1. loop-inbox writes Talking, with its pid. +2. The loop stops reading its terminal and republishes its ask with talking set to that pid; loop-inbox opens claude only once it reads that. +3. loop-inbox writes Talked once claude exits. The loop also stops waiting if loop-inbox's process is gone. +""" +import dataclasses +import json +import os +import pathlib + +from failure import Failure +from file_writes import make_private, replace_json + + +@dataclasses.dataclass(frozen=True) +class TalkCommand: + """How loop-inbox runs claude on the worker's session: claude's arguments, its folder and what it adds to the environment.""" + args: list[str] + cwd: str + env: dict[str, str] + + +@dataclasses.dataclass(frozen=True) +class Ask: + id: str + session: str + # The checkout the loop runs in. + root: str + question: str + # When the loop asked, in seconds since the epoch. + asked: float + pid: int + # How loop-inbox opens claude for /talk; None while claude is open for this question, which then takes no answer from loop-inbox. + talk: TalkCommand | None + # The pid of the loop-inbox that has claude open for this question; None while claude is open on the loop's own terminal, or not open. + talking: int | None = None + + +@dataclasses.dataclass(frozen=True) +class Typed: + text: str + + +@dataclasses.dataclass(frozen=True) +class Talking: + pid: int + + +@dataclasses.dataclass(frozen=True) +class Talked: + pass + + +Answer = Typed | Talking | Talked + + +def ask_file(folder: pathlib.Path, session: str) -> pathlib.Path: + return folder / f"{session}.json" + + +def answer_file(folder: pathlib.Path, session: str) -> pathlib.Path: + return folder / f"{session}.answer" + + +def publish(folder: pathlib.Path, ask: Ask) -> Failure | None: + try: + make_private(folder) + except OSError as failure: + return Failure(f"cannot make {folder}: {failure.strerror}") + return replace_json(ask_file(folder, ask.session), dataclasses.asdict(ask)) + + +def withdraw(folder: pathlib.Path, session: str) -> None: + """Removes the session's ask and any answer to it.""" + for path in (ask_file(folder, session), answer_file(folder, session)): + path.unlink(missing_ok=True) + + +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, as is one being replaced.""" + try: + paths = sorted(folder.glob("*.json")) + except OSError: + return [] + asks = [ask for path in paths if (ask := read_ask(path)) and alive(ask.pid)] + return sorted(asks, key=lambda ask: ask.asked) + + +def read_ask(path: pathlib.Path) -> Ask | None: + try: + data = json.loads(path.read_text(encoding="utf-8")) + talk = data["talk"] and TalkCommand(**data["talk"]) + ask = Ask(**{**data, "talk": talk}) + except (OSError, ValueError, TypeError, KeyError): + return None + # A pid of 0 or below would name a process group to alive. + return ask if isinstance(ask.asked, int | float) and isinstance(ask.pid, int) and ask.pid > 0 else None + + +def send(folder: pathlib.Path, ask: Ask, answer: Answer) -> Failure | None: + kind = dataclasses.asdict(answer) | {"kind": type(answer).__name__} + return replace_json(answer_file(folder, ask.session), {"ask": ask.id, **kind}) + + +def answered(folder: pathlib.Path, ask: Ask) -> Answer | None: + """The answer loop-inbox sent to this ask; None for none, or one meant for another ask of the session.""" + try: + data = json.loads(answer_file(folder, ask.session).read_text(encoding="utf-8")) + except (OSError, ValueError): + return None + if not isinstance(data, dict) or data.get("ask") != ask.id: + return None + match data: + case {"kind": "Typed", "text": str(text)}: + return Typed(text) + case {"kind": "Talking", "pid": int(pid)}: + return Talking(pid) + case {"kind": "Talked"}: + return Talked() + return None + + +def alive(pid: int) -> bool: + try: + os.kill(pid, 0) + except ProcessLookupError: + return False + except PermissionError: + return True + return True diff --git a/bin/loop_inbox/__init__.py b/bin/loop_inbox/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/bin/loop_inbox/inbox.py b/bin/loop_inbox/inbox.py new file mode 100644 index 00000000..291ec624 --- /dev/null +++ b/bin/loop_inbox/inbox.py @@ -0,0 +1,146 @@ +"""What loop-inbox shows, and what each key does there: the core that main.py's curses screen runs. + +How it shows the loops and a question was picked on 2026-10-28 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: a block per +loop with its checkout's path and how long it has waited, and an answer prompt saying that Enter alone stops nothing. +""" +import dataclasses +import textwrap +import typing + +from loop_claude.waiting import Ask +from loop_claude.cycle.interrupt import TALK + +ENTER = "enter" +BACKSPACE = "backspace" +ESCAPE = "escape" +# Lines of a question the list shows; the answer screen shows it whole. +SHOWN_LINES = 2 +QUIT = "q" + + +@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.""" + shown: tuple[Ask, ...] = () + typed: str = "" + note: str = "" + + +@dataclasses.dataclass(frozen=True) +class Answering: + ask: Ask + typed: str = "" + + +Screen = Listing | Answering + + +@dataclasses.dataclass(frozen=True) +class Send: + ask: Ask + text: str + + +@dataclasses.dataclass(frozen=True) +class Open: + """Opens the worker's claude session for /talk.""" + ask: Ask + + +@dataclasses.dataclass(frozen=True) +class Quit: + pass + + +def pressed(screen: Screen, key: str) -> Screen | Send | Open | Quit: + """What follows key, which is ENTER, BACKSPACE, ESCAPE or one character typed.""" + match screen: + case Listing(shown, typed): + if key == QUIT and not typed: + return Quit() + if key == ENTER: + return picked(shown, typed) + if key == BACKSPACE: + return Listing(shown, typed[:-1]) + return Listing(shown, typed + key) if key.isdigit() else screen + case Answering(ask, typed): + if key == ESCAPE or (key == ENTER and not typed.strip()): + return Listing() + if key == ENTER: + return Open(ask) if typed.strip() == TALK else Send(ask, typed.strip()) + if key == BACKSPACE: + return Answering(ask, typed[:-1]) + return Answering(ask, typed + key) if len(key) == 1 and key.isprintable() else screen + case _: + typing.assert_never(screen) + + +def picked(shown: tuple[Ask, ...], typed: str) -> Listing | Answering: + if not typed: + return Listing() + number = int(typed) + if not 1 <= number <= len(shown): + return Listing(note=f"No loop has the number {number}.") + ask = shown[number - 1] + if ask.talk is None: + return Listing(note=f"{ask.root}: claude is open {where_open(ask)}; answer there.") + return Answering(ask) + + +def where_open(ask: Ask) -> str: + return "in loop-inbox" if ask.talking 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.""" + 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, ""] + for number, ask in enumerate(screen.shown, 1): + state = f"; claude is open {where_open(ask)}" if ask.talk is None else "" + 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.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}"] + + +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.""" + 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}", + ] + + +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 wrapped(text: str, width: int) -> list[str]: + return [line for paragraph in text.splitlines() for line in textwrap.wrap(paragraph, max(width, 20)) 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 waited(seconds: float) -> str: + minutes = int(seconds // 60) + if minutes < 60: + return f"{minutes} min" + hours, minutes = divmod(minutes, 60) + if hours < 24: + return f"{hours} h {minutes} min" + days, hours = divmod(hours, 24) + return f"{days} d {hours} h" diff --git a/bin/loop_inbox/main.py b/bin/loop_inbox/main.py new file mode 100644 index 00000000..bc27b169 --- /dev/null +++ b/bin/loop_inbox/main.py @@ -0,0 +1,176 @@ +"""Show every loop-claude on this machine that waits for you, 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: + +- A line and Enter sends it to that loop, which goes on with it. +- /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. +- 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; the loops keep waiting. + +The loops' questions are files in ~/.local/state/loop-claude, read and written as +bin/loop_claude/waiting.py describes. + +Exit 2 when stdin or stdout is not a terminal, or on an unknown argument. +""" +import curses +import os +import pathlib +import signal +import subprocess +import sys +import time + +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, read_ask, send, Talked, Talking, Typed, waiting +from loop_claude.paths import Paths, paths_from +from loop_claude.effects import system_effects +from claude_code.trust import trust +from loop_claude.project.checkout import worktrees + +USAGE = "usage: loop-inbox" +# Milliseconds between refreshes of the list while no key is pressed. +REFRESH_MS = 1000 +# Seconds loop-inbox waits for a loop to stop reading its terminal before it opens claude for /talk; the loop looks for an answer every half second. +MAKE_WAY_SECONDS = 5 +KEYS = {"\n": ENTER, "\r": ENTER, curses.KEY_ENTER: ENTER, "\x7f": BACKSPACE, "\b": BACKSPACE, curses.KEY_BACKSPACE: BACKSPACE, "\x1b": ESCAPE} + + +def main(argv: list[str], home: pathlib.Path) -> int: + if argv[:1] in (["-h"], ["--help"]): + print(__doc__.strip()) + return 0 + if argv: + print(f"loop-inbox: unknown argument {argv[0]}; {USAGE}", file=sys.stderr) + return 2 + 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 + try: + curses.wrapper(lambda window: run(window, paths_from(home))) + except KeyboardInterrupt: + pass + return 0 + + +def run(window: curses.window, paths: Paths) -> None: + folder = paths.waiting + window.timeout(REFRESH_MS) + screen: Screen = Listing() + while True: + screen = refreshed(screen, folder) + draw(window, screen) + try: + key = window.get_wch() + except curses.error: + continue # No key within REFRESH_MS. + match pressed(screen, key_name(key)): + case Quit(): + return + case Send(ask, text): + screen = Listing(note=sent(folder, ask, text)) + case Open(ask): + screen = Listing(note=talked(window, paths, ask)) + case Listing() | Answering() as next_screen: + screen = next_screen + + +def key_name(key: str | int) -> str: + """inbox's name for a key curses read; an empty string for a key loop-inbox has no use for, such as an arrow.""" + return KEYS.get(key, key if isinstance(key, str) else "") + + +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)), "", note) + case Answering(ask) if not still_waits(folder, ask): + return Listing(note=no_longer_waits(ask)) + return screen + + +def draw(window: curses.window, screen: Screen) -> None: + height, width = window.getmaxyx() + now = time.time() + lines = listing_lines(screen, now, local_time, width) if isinstance(screen, Listing) else answering_lines(screen, now, 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) + window.refresh() + + +def local_time(seconds: float) -> str: + return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(seconds)) + + +def still_waits(folder: pathlib.Path, ask: Ask) -> bool: + """Whether ask 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 now.talk is not None + + +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." + + +def sent(folder: pathlib.Path, ask: Ask, text: str) -> str: + """Sends text to the loop that asked ask, and says what came of it.""" + if not still_waits(folder, ask): + return no_longer_waits(ask) + if unsent := send(folder, ask, Typed(text)): + return f"Could not send the answer to {ask.root}: {unsent.reason}" + return f"Sent to {ask.root}." + + +def talked(window: curses.window, paths: Paths, ask: Ask) -> str: + """Opens the worker's claude session on this terminal once the loop has stopped reading its own, and says what came of it.""" + folder = paths.waiting + if not still_waits(folder, ask) or ask.talk is None: + return no_longer_waits(ask) + if unsent := send(folder, ask, Talking(os.getpid())): + return f"Could not open claude for {ask.root}: {unsent.reason}" + if not made_way(folder, ask): + return f"{ask.root} did not make way for claude within {MAKE_WAY_SECONDS} s; it was answered on its terminal, or stopped." + curses.def_prog_mode() + curses.endwin() + # As loop-claude's hand_over does before it opens claude on its own terminal. + trust(paths.claude_json, worktrees(ask.talk.cwd, system_effects()), lambda text: print(f"loop-inbox: {text}", file=sys.stderr)) + # Ctrl-C belongs to claude while it runs, not to loop-inbox. + interrupt = signal.signal(signal.SIGINT, signal.SIG_IGN) + try: + subprocess.run(["claude", *ask.talk.args], cwd=ask.talk.cwd, env={**os.environ, **ask.talk.env}) + said = f"claude for {ask.root} has ended; the loop goes on." + except OSError as failure: + said = f"Could not start claude for {ask.root}: {failure.strerror}" + finally: + signal.signal(signal.SIGINT, interrupt) + unsent = send(folder, ask, Talked()) + curses.reset_prog_mode() + window.refresh() + # Without Talked, 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 + + +def made_way(folder: pathlib.Path, ask: Ask) -> bool: + """Whether the loop shows, within MAKE_WAY_SECONDS, that it has stopped reading its terminal for this loop-inbox.""" + deadline = time.monotonic() + MAKE_WAY_SECONDS + while time.monotonic() < deadline: + now = read_ask(ask_file(folder, ask.session)) + if now is None or now.id != ask.id: + return False + if now.talking == os.getpid(): + return True + time.sleep(0.1) + return False diff --git a/bin/loop_inbox/test_loop_inbox.py b/bin/loop_inbox/test_loop_inbox.py new file mode 100644 index 00000000..7a8bc48d --- /dev/null +++ b/bin/loop_inbox/test_loop_inbox.py @@ -0,0 +1,177 @@ +import dataclasses +import os +import pathlib +import shutil +import subprocess +import sys +import tempfile +import unittest + +sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) + +from loop_inbox.inbox import Answering, BACKSPACE, ENTER, ESCAPE, Listing, Open, Quit, Send +from loop_claude.waiting import Ask, TalkCommand, Typed +from loop_inbox import inbox, main +from loop_claude import waiting + +TALK = TalkCommand(["--resume", "s"], "/c", {}) + + +def asked(session, root, question="Which one?", at=100.0, pid=None, talk=TALK, talking=None): + return Ask(f"ask-{session}", session, root, question, at, os.getpid() if pid is None else pid, talk, talking) + + +def keyed(screen, *keys): + for key in keys: + screen = inbox.pressed(screen, key) + return screen + + +def gone_pid(): + """The pid of a process that has exited.""" + return int(subprocess.run([sys.executable, "-c", "import os; print(os.getpid())"], capture_output=True, text=True).stdout) + + +class Answers(unittest.TestCase): + def setUp(self): + self.folder = pathlib.Path(tempfile.mkdtemp()) + self.addCleanup(shutil.rmtree, self.folder) + + 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))), *number, ENTER, *text, ENTER) + self.assertIsInstance(action, Send) + return main.sent(self.folder, action.ask, action.text) + + def test_two_waiting_loops_each_get_their_own_answer(self): + log, bender = asked("s1", "/code/log", at=100), asked("s2", "/code/bender", at=200) + for ask in (bender, log): + waiting.publish(self.folder, ask) + self.assertEqual(self.answer("2", "Use B."), "Sent to /code/bender.") + self.assertEqual(self.answer("1", "Use A."), "Sent to /code/log.") + self.assertEqual((waiting.answered(self.folder, log), waiting.answered(self.folder, bender)), (Typed("Use A."), Typed("Use B."))) + + def test_an_answer_to_a_loop_that_stopped_waiting_reaches_no_loop(self): + 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))), "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(sorted(path.name for path in self.folder.iterdir()), ["s2.json"]) + + 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), typing) + self.assertEqual(inbox.pressed(typing, ENTER), Answering(bender)) + + def test_a_loop_whose_claude_is_open_takes_no_answer_here(self): + for talking, where in ((None, "on its terminal"), (7, "in loop-inbox")): + with self.subTest(where=where): + self.assertEqual(keyed(Listing((asked("s1", "/code/log", talk=None, talking=talking),)), "1", ENTER), Listing(note=f"/code/log: claude is open {where}; answer there.")) + + 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), Answering(ask, "Us")) + 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 on its terminal, or stopped.")) + + def test_talk_opens_claude_only_once_the_loop_has_stopped_reading_its_terminal(self): + ask = asked("s1", "/code/log") + waiting.publish(self.folder, dataclasses.replace(ask, talk=None, talking=os.getpid())) + self.assertTrue(main.made_way(self.folder, ask)) + waiting.withdraw(self.folder, "s1") + self.assertFalse(main.made_way(self.folder, ask)) + + +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")), + (("x",), Listing((ask,))), + ((ENTER,), Listing()), + (("2", ENTER), Listing(note="No loop has the number 2.")), + (("1", ENTER), Answering(ask)), + ): + with self.subTest(keys=keys): + self.assertEqual(keyed(Listing((ask,)), *keys), after) + + def test_an_answer_is_sent_stripped_talk_opens_claude_and_enter_alone_or_esc_goes_back(self): + ask = asked("s1", "/code/log") + for keys, after in ( + ((*" Use B. ", ENTER), Send(ask, "Use B.")), + ((*" /talk", ENTER), Open(ask)), + (("U", "x", BACKSPACE), Answering(ask, "U")), + ((" ", ENTER), Listing()), + (("U", ESCAPE), Listing()), + (("\t",), Answering(ask)), + ): + with self.subTest(keys=keys): + self.assertEqual(keyed(Answering(ask), *keys), after) + + def test_curses_keys_get_inboxs_names(self): + for key, name in (("\n", ENTER), (main.curses.KEY_ENTER, ENTER), ("\x7f", BACKSPACE), (main.curses.KEY_BACKSPACE, BACKSPACE), ("\x1b", ESCAPE), ("a", "a"), (main.curses.KEY_LEFT, "")): + with self.subTest(key=key): + self.assertEqual(main.key_name(key), name) + + +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), asked("s2", "/b", at=100), asked("s3", "/c", at=50, pid=gone_pid()) + 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}') + self.assertEqual(waiting.waiting(pathlib.Path(folder)), [early, late]) + + def test_an_answer_names_the_ask_it_answers(self): + with tempfile.TemporaryDirectory() as folder: + ask = asked("s1", "/a") + for answer in (Typed("A"), waiting.Talking(7), waiting.Talked()): + with self.subTest(answer=answer): + waiting.send(pathlib.Path(folder), ask, answer) + self.assertEqual(waiting.answered(pathlib.Path(folder), ask), answer) + self.assertIsNone(waiting.answered(pathlib.Path(folder), dataclasses.replace(ask, id="another"))) + + +class Shown(unittest.TestCase): + 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, talk=None) + lines = inbox.listing_lines(Listing((log, cut), "1"), 3600 * 26 + 120, lambda seconds: f"<{seconds}>", 34) + 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…", + "", + "[2] /code/c, waiting since <90000> (1 h 2 min); claude is open on its terminal", + " Cut 0.4.0?", + "", + "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.", "> "]) + + 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_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", "> "]) + + +if __name__ == "__main__": + unittest.main() diff --git a/bin/repo_checks/test_import_order.py b/bin/repo_checks/test_import_order.py index c8e43d42..40a1658a 100644 --- a/bin/repo_checks/test_import_order.py +++ b/bin/repo_checks/test_import_order.py @@ -23,7 +23,7 @@ def unsorted_imports(source: str) -> list[int]: class ImportOrder(unittest.TestCase): def test_each_python_file_sorts_its_imports_by_their_first_binding(self): - listed = subprocess.run(["git", "ls-files", "*.py", "bin/loop-claude"], capture_output=True, check=True, cwd=ROOT, text=True).stdout.split() + listed = subprocess.run(["git", "ls-files", "*.py", "bin/loop-claude", "bin/loop-inbox"], capture_output=True, check=True, cwd=ROOT, text=True).stdout.split() self.assertIn("bin/loop-claude", listed) for name in listed: with self.subTest(name): diff --git a/bin/review_replay/test_review_replay.py b/bin/review_replay/test_review_replay.py index 61a9ebb0..8daeb44d 100644 --- a/bin/review_replay/test_review_replay.py +++ b/bin/review_replay/test_review_replay.py @@ -215,7 +215,7 @@ class Main(unittest.TestCase): result = result if "api_error_status" in result else {"type": "result", "structured_output": {"found": [n + 1 for n in result["found"]]}} return subprocess.CompletedProcess(args, 0, json.dumps(result), "") - effects = Effects(claude=claude, claude_on_terminal=unused, discard_typed=unused, execv=unused, git=system_effects().git, input=unused, local_time=unused, memory=unused, now=unused, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused) + effects = Effects(claude=claude, claude_on_terminal=unused, discard_typed=unused, execv=unused, git=system_effects().git, input=unused, input_or=unused, local_time=unused, memory=unused, now=unused, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused) out, err = io.StringIO(), io.StringIO() with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): code = main.main(argv, {}, self.home, effects) diff --git a/docs/decisions.md b/docs/decisions.md index 30a42e83..808cc957 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -50,12 +50,14 @@ The cap is 5, `bin/todo_table.py`'s `BUNDLE_MAX_R`, from the same chunks: by the 2026-10-17, lilleman, todo item 168. The human answers an interrupt on loop-claude's terminal, and the worker resumes headless with the answer in a `-p` prompt. The judge reads that answer as a `[human]` line, not a `[loop]` one, so it holds the chunk open until the answer is recorded, as it does for an answer typed in claude. -## loop-claude: before it opens claude on the terminal, it marks the checkout and each of its worktrees trusted in `~/.claude.json` +## loop-claude: before it or loop-inbox opens claude on a terminal, it marks the checkout and each of its worktrees trusted in `~/.claude.json` 2026-09-21, lilleman. Serves goal 1. `claude --resume` re-enters the worktree the worker last entered, recorded in the transcript's `worktree-state` entry, and Claude Code asks trust per path, so trusting the checkout alone still lands the human in the dialog. Trusting every worktree `git worktree list` names spares reading which one from the transcript. Since the human answers an interrupt on loop-claude's own terminal (todo item 168), claude opens there only for `/talk`, a release ready to cut and the routing calls, and the trust is marked only then. Valid while resume re-enters a recorded worktree and trust is kept per path. 2026-09-30, lilleman. A write by another claude inside `trust`'s read-modify-write window is lost, a risk larv-review accepted on 2026-09-24. Claude Code owns and writes `~/.claude.json`, so `loop-claude` is to move out of it, bringing each case that must stay to the human. Stands until `todo.md` item 6 ends it. +2026-10-28, lilleman, todo item 243. `/talk` from loop-inbox opens claude in loop-inbox's terminal, so loop-inbox marks the trust itself, with the same code, just before. It adds a second writer to `~/.claude.json`, under the same risk, until item 6 ends it. + ## loop-claude: each project's model lives in `~/.claude/loop-claude-models.json`, which only loop-claude writes 2026-09-26, lilleman. Serves goal 1. Claude Code rewrites the user settings' `model` whenever one is picked inside a session, so a loop reading settings runs whatever was picked last; `~/.claude/loop-claude-models.json` has loop-claude as its one writer, and every claude it starts gets that model as `--model`. The file is per machine, outside the synced allowlist, since a tracked file the loop writes would dirty the checkout. 2026-10-02, lilleman: goal 2 shares the setup across machines, and a project's model is each machine's own choice, so a new machine asks once per project, which is not asking the same thing twice (goal 1.2). Valid while Claude Code keeps rewriting the settings' model from inside a session. @@ -99,6 +101,19 @@ Hours. A chunk ran a median 0.7 hours from its first message to its last, one in Valid while cache reads cost a twentieth of input and Claude Code's compaction keeps the worker's task. +## 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. +- 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. + +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. + +Valid while every loop and loop-inbox run on one machine under one user's home. + ## machine load: a heavy command waits for one of the machine's heavy slots, one for every 4 CPUs, which every session shares, and loop-claude starts a worker only while at least a quarter of the machine's memory is available 2026-10-23, lilleman. Serves goal 1.5. On 2026-10-22 ai-sandbox, with 8 CPUs and 16 GiB, thrashed for hours: four to six loops ran mutation tests, full gates, `docker build`s and QEMU-booting e2e tests at once, and nothing told one loop how busy the machine was. lilleman chose both limits; no standard sets either, and GNU parallel's `--memfree`, which does the memory wait's job, has no default. A slot is a file lock, so a session that dies frees its slot. The memory wait reads `/proc/meminfo` only, and off Linux a worker starts at once. `bin/machine_load/` holds the slots and the memory share, `bin/run-heavy` takes a slot, `CLAUDE.md` β†’ "Working with the codebase" has every session use it, and loop-claude's worker waits for the share. rule-hook's rule `run-heavy` blocks a `docker build`, and a run of a mutation tool stability-reviewer names, outside run-heavy, whether direct or inside a container. No program can tell a gate script from a light one, so only `CLAUDE.md` asks a session to run a gate under run-heavy. Valid while one machine runs several loops at once. diff --git a/docs/reading-cost.md b/docs/reading-cost.md index dbccf37e..7c6ffc96 100644 --- a/docs/reading-cost.md +++ b/docs/reading-cost.md @@ -919,3 +919,7 @@ Read most (opens and searches): Read most (opens and searches): - `rules/todo-items.md` 1 + +## Reading cost, chunk cfd9ab4f5b1b, finished 2026-10-28T22:00:08Z + +64114 new input tokens before the first commit. diff --git a/todo.md b/todo.md index 19c1d9f0..c0d085a2 100644 --- a/todo.md +++ b/todo.md @@ -12,7 +12,6 @@ | ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score | |---|---|---|---|---|---|---|---|---|---|---|---| -| 243 | 0.4.0 | | owner | **Show every loop-claude on the machine that waits for the human in one terminal app, and let the human answer each one there, `/talk` included.** | 4 | 2 | 3 | 7 | 6 | 1.5 by 4 | 0.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 | @@ -77,19 +76,6 @@ ## Details -### 243. Show every loop-claude on the machine that waits for the human in one terminal app, and let the human answer each one there, `/talk` included. - -lilleman's call, 2026-10-28: with several loops running, each asks on its own terminal, so the human jumps between terminals to find which wait. On 2026-10-28 three of five loops waited on round-cap questions at once. Today `put_question` in `bin/loop_claude/cycle/interrupt.py` reads the answer with `input()`, and nothing outside that terminal sees a question. - -- Each loop, as it asks, writes one file per session under `~/.local/state/loop-claude/`, holding the project, the question, when it was asked, its pid and whether `/talk` is offered, and removes it once answered or stopped. -- While it waits, the loop takes the first answer from either its terminal or the app, so a loop keeps working with no app running. -- The app lists the waiting loops oldest first and sends a typed one-line answer to the loop it is meant for. A loop whose pid is gone drops off the list. -- `/talk` from the app runs `claude --resume` for that session in the app's terminal; the loop then waits, as `talk` does today, until a human turn appears in the transcript. -- A release ready to cut, which today opens the session at once, shows in the app too. -- It runs on the host's Python with the standard library, such as `curses`, as `docs/decisions.md` β†’ `bin/: the tools and their tests run on the host's Python` has it. - -Bench the app's command name and how it shows a question with readers seated as the README's audience before it ships. An answer reaching the wrong loop is the worst failure: a test sends answers to two waiting loops and checks each gets its own. The change touches `loop-claude --help` in `bin/loop_claude/loop/main.py`, which the comprehension seats found hard: make it easier to read where it describes the interrupt. - ### 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.