Show every waiting loop-claude in loop-inbox and take each one's answer there

This commit is contained in:
2026-10-28 23:24:29 +01:00
parent d13c4fb0db
commit a7fe878631
24 changed files with 938 additions and 81 deletions
+80 -12
View File
@@ -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]
+17 -8
View File
@@ -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:
+8 -6
View File
@@ -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)
+21
View File
@@ -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")
+11 -7
View File
@@ -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.
+3
View File
@@ -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",
)
+15
View File
@@ -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")
+106 -27
View File
@@ -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"),
+136
View File
@@ -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, <session id>.json, in Paths.waiting, and removes it once answered or stopped.
loop-inbox answers by replacing <session id>.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