Restructure the interrupt so one function owns the ask and loop-inbox imports nothing from cycle/

This commit is contained in:
2026-10-29 13:11:04 +01:00
parent 60cb0dc851
commit 9ebd06e748
13 changed files with 189 additions and 200 deletions
+28 -63
View File
@@ -3,16 +3,14 @@ import sys
import typing
import uuid
from loop_claude.waiting import answered, Ask, Asking, claude_ended, ClaudeCommand, ClaudeOpening, OpenInInbox, OpenOnTerminal, POLL_SECONDS, publish, TALK, Typed, withdraw
from loop_claude.effects import Effects, say
from loop_claude.waiting import Answer, answered, Ask, Asking, claude_ended, ClaudeOpening, listed, make_way, OpenInInbox, OpenOnTerminal, shown, TALK, Typed
from loop_claude.hand_over import claude_args, ClaudeCommand, hand_over
from loop_claude.effects import Effects, POLL_SECONDS, say
from failure import Failure
from claude_code.transcript import human_turns, read_transcript
from loop_claude.stop import needs_human, needs_terminal, Stop
from loop_claude.paths import Paths
from model_routing.ladder import Rung
from loop_claude.cycle.states import Talk
from claude_code.trust import trust
from loop_claude.project.checkout import worktrees
ANSWER_QUESTION = "answer the question above"
# ASK_ANSWER was picked on 2026-10-17 by a bench of three readers seated as the README's audience, as ~/.claude/CLAUDE.md → "Working loop" → "Bench a syntax with the people who write it." has it.
@@ -33,36 +31,37 @@ class WorkerSession:
return ClaudeCommand(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 | Stop:
"""Prints question for the human. Where answer_here, shows it in loop-inbox too and returns the first answer, typed at loop-claude's terminal or in loop-inbox: the line, stripped, or a Talk where they type TALK. Else a Talk at once, on the terminal. A Stop where loop-claude is off a terminal, or they type nothing, or the input ends."""
@dataclasses.dataclass(frozen=True)
class Talked:
"""The human typed in the worker's claude session."""
def interrupt(question: str, answer_here: bool, session: WorkerSession, paths: Paths, effects: Effects) -> str | Talked | Stop:
"""Prints question for the human and returns their answer: where answer_here, the first line typed at loop-claude's terminal or in loop-inbox, stripped, or Talked once they typed in the worker's claude session, which TALK opens; else Talked once they typed in that session, which opens at once on the terminal. loop-inbox lists the question meanwhile. 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, the first line answers; the rest wait, and the next question drops them. A longer answer goes through TALK.
effects.discard_typed()
ask = Ask(effects.new_id(), str(session.id), session.root, question, effects.now(), effects.pid(), Asking(session.claude_command()))
if not answer_here:
return Talk(ask, OpenOnTerminal())
shown(paths, ask, effects)
answer: str | Talk | Stop | None = None
try:
answer = first_answer(ask, paths, effects)
ask = Ask(effects.new_id(), str(session.id), session.root, question, effects.now(), effects.pid(), Asking(session.claude_command()) if answer_here else OpenOnTerminal())
with listed(paths.waiting, ask, effects):
answer = first_answer(ask, paths, effects) if answer_here else OpenOnTerminal()
if isinstance(answer, OpenOnTerminal | OpenInInbox):
return human_typed(session.transcript_path, lambda: claude_open(ask, answer, session, paths, effects)) or Talked()
return answer
finally:
# A Talk keeps ask listed, under its id, for talk to show loop-inbox where claude opens.
if not isinstance(answer, Talk):
withdrawn(paths, ask, effects)
def first_answer(ask: Ask, paths: Paths, effects: Effects) -> str | Talk | Stop:
def first_answer(ask: Ask, paths: Paths, effects: Effects) -> str | OpenOnTerminal | OpenInInbox | Stop:
"""The first answer to ask, from loop-claude's terminal or loop-inbox: the line typed, stripped, or where claude is to open for it. A Stop where they type nothing, or the input ends."""
try:
answer = effects.input_or(ASK_ANSWER, lambda: answered(paths.waiting, ask))
# Annotated since mypy infers input_or's T as object from the lambda.
answer: str | Answer = effects.input_or(ASK_ANSWER, lambda: answered(paths.waiting, ask))
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")
match answer:
case ClaudeOpening(pid):
return Talk(ask, OpenInInbox(pid))
return OpenInInbox(pid)
case Typed(text):
say(f"Answered in loop-inbox: {text}", effects)
case str(text):
@@ -72,43 +71,23 @@ def first_answer(ask: Ask, paths: Paths, effects: Effects) -> str | Talk | Stop:
text = text.strip()
if not text:
return needs_human(ANSWER_QUESTION, "nothing was typed")
return Talk(ask, OpenOnTerminal()) if text == TALK else text
return OpenOnTerminal() if text == TALK else text
def shown(paths: Paths, ask: Ask, effects: Effects) -> None:
"""Shows ask in loop-inbox. A failure only warns. The question is then still answered on the terminal, unless claude was to open in loop-inbox: loop-inbox then gives up, and the loop stops."""
if unshown := publish(paths.waiting, ask):
say(f"loop-inbox cannot show this question: {unshown.reason}", effects)
def withdrawn(paths: Paths, ask: Ask, effects: Effects) -> None:
"""Takes ask out of loop-inbox. A failure only warns: loop-inbox drops the ask once the loop's process ends."""
if unwithdrawn := withdraw(paths.waiting, ask.session):
say(f"loop-inbox may still list this question: {unwithdrawn.reason}", effects)
def talk(chosen: Talk, session: WorkerSession, paths: Paths, effects: Effects) -> Stop | None:
"""Holds the loop while the human answers in the worker's claude session, which loop-inbox lists as open on loop-claude's terminal or in loop-inbox. A Stop where they type nothing there."""
try:
return human_typed(session.transcript_path, lambda: opened(chosen, session, paths, effects))
finally:
withdrawn(paths, chosen.ask, effects)
def opened(chosen: Talk, session: WorkerSession, paths: Paths, effects: Effects) -> Stop | None:
"""Returns once the claude the human answers in has ended: the one it opens on the terminal, or the one loop-inbox opened."""
# Tells loop-inbox where claude is open; for OpenInInbox, it is the go-ahead claim_talk waits for.
shown(paths, dataclasses.replace(chosen.ask, state=chosen.where), effects)
match chosen.where:
def claude_open(ask: Ask, where: OpenOnTerminal | OpenInInbox, session: WorkerSession, paths: Paths, effects: Effects) -> Stop | None:
"""Lists ask in loop-inbox as having claude open where, then returns once that claude has ended: the one it opens on the terminal, or the one loop-inbox opened."""
match where:
case OpenOnTerminal():
shown(paths.waiting, dataclasses.replace(ask, state=where), effects)
if unstarted := hand_over(session.claude_command(), paths, effects):
return Stop(1, f"could not start claude for the interrupt: {unstarted.reason}")
case OpenInInbox(pid):
make_way(paths.waiting, ask, pid, effects)
say("claude is open for this question in loop-inbox; waiting for it to end", effects)
while not claude_ended(paths.waiting, chosen.ask) and effects.alive(pid):
while not claude_ended(paths.waiting, ask) and effects.alive(pid):
effects.sleep(POLL_SECONDS)
case _:
typing.assert_never(chosen.where)
typing.assert_never(where)
return None
@@ -124,17 +103,3 @@ def human_typed(transcript_path: str, held_open: typing.Callable[[], Stop | None
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")
def hand_over(command: ClaudeCommand, paths: Paths, effects: Effects) -> Failure | None:
"""Marks trusted the checkout that command runs in, and each of its worktrees, then runs claude on the terminal as command says; the failure is why claude could not start."""
trust(paths.claude_json, worktrees(command.cwd, effects), lambda text: say(text, effects))
try:
effects.claude_on_terminal(command.args, command.cwd, command.env)
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]
+6 -8
View File
@@ -2,7 +2,7 @@ import dataclasses
import pathlib
import typing
from loop_claude.cycle.states import Active, Archived, Closing, Ended, Event, HumanTalked, HumanTyped, Interrupting, Judging, QUOTED_ANSWERS_PER_CYCLE, Ruled, State, Talk, TalkChosen, Talking, transition, TypedAnswer, WorkerRan, Working
from loop_claude.cycle.states import Active, Archived, Closing, Ended, Event, HumanTalked, HumanTyped, Interrupting, Judging, QUOTED_ANSWERS_PER_CYCLE, Ruled, State, transition, TypedAnswer, WorkerRan, Working
from loop_claude.routing import after_ruling, judge_rung
from transcript_archive.write import archive
from loop_claude.cycle.worker import AUTO_COMPACT_WINDOW, COMPACT_WINDOW, run_worker, worker_args
@@ -10,11 +10,11 @@ from claude_code.session import delete_session, Session, session_open, transcrip
from loop_claude.effects import Effects, say
from failure import Failure
from loop_claude.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished, Verdict
from loop_claude.cycle.interrupt import interrupt, Talked, WorkerSession
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, WorkerSession
from claude_code.transcript import read_transcript
from loop_claude.cycle.retry import retried
from model_routing.route import Route
@@ -99,8 +99,6 @@ 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, chosen, _):
return talk(chosen, worker_session(cycle, transcript_path), cycle.paths, cycle.effects) or HumanTalked()
case Closing(transcript_path, verdict):
return close(cycle, transcript_path, verdict)
case _:
@@ -164,7 +162,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 | 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.
@@ -172,12 +170,12 @@ 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), worker_session(cycle, transcript_path), cycle.paths, cycle.effects)
answer = interrupt(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(answer)
case Talked():
return HumanTalked()
# The worker gets the question it asked, not the one put to the human past the cap.
return HumanTyped(TypedAnswer(ruling.question, answer))
+6 -29
View File
@@ -1,6 +1,5 @@
import dataclasses
from loop_claude.waiting import Ask, OpenInInbox, OpenOnTerminal
from loop_claude.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished, Verdict
from loop_claude.escalation_mark import StepUp
@@ -10,7 +9,7 @@ QUOTED_ANSWERS_PER_CYCLE = 3
@dataclasses.dataclass(frozen=True)
class TypedAnswer:
"""The human's answer to an interrupt, typed at loop-claude's terminal."""
"""The human's answer to an interrupt, typed at loop-claude's terminal or in loop-inbox."""
question: str
answer: str
@@ -33,7 +32,7 @@ class Judging:
@dataclasses.dataclass(frozen=True)
class Interrupting:
"""The human answers; a QuotedAnswer reaches here only after the cycle has used up its QUOTED_ANSWERS_PER_CYCLE."""
"""The human answers, by typing or in the worker's claude session; a QuotedAnswer reaches here only after the cycle has used up its QUOTED_ANSWERS_PER_CYCLE."""
transcript_path: str
ruling: Interrupt | QuotedAnswer
quoted_answers: int = 0
@@ -41,20 +40,6 @@ class Interrupting:
step_up: StepUp | None = None
@dataclasses.dataclass(frozen=True)
class Talk:
"""The human answers in the worker's claude session, open on loop-claude's terminal or in loop-inbox, as where says. ask is the question they were asked, which loop-inbox lists as open there."""
ask: Ask
where: OpenOnTerminal | OpenInInbox
@dataclasses.dataclass(frozen=True)
class Talking:
transcript_path: str
talk: Talk
quoted_answers: int = 0
@dataclasses.dataclass(frozen=True)
class Closing:
transcript_path: str
@@ -66,7 +51,7 @@ class Ended:
verdict: Finished | Unfinished
Active = Working | Judging | Interrupting | Talking | Closing
Active = Working | Judging | Interrupting | Closing
State = Active | Ended
@@ -87,15 +72,9 @@ class HumanTyped:
typed: TypedAnswer
@dataclasses.dataclass(frozen=True)
class TalkChosen:
"""The human typed /talk, at loop-claude's terminal or in loop-inbox, or the interrupt is for a release ready to cut."""
talk: Talk
@dataclasses.dataclass(frozen=True)
class HumanTalked:
"""The human typed in the worker's claude session."""
"""The human typed in the worker's claude session, which /talk opens, or a release ready to cut opens at once."""
@dataclasses.dataclass(frozen=True)
@@ -103,7 +82,7 @@ class Archived:
pass
Event = WorkerRan | Ruled | HumanTyped | TalkChosen | HumanTalked | Archived
Event = WorkerRan | Ruled | HumanTyped | HumanTalked | Archived
def transition(state: State, event: Event) -> State:
@@ -120,10 +99,8 @@ 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(talk):
return Talking(transcript_path, talk, 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 Interrupting(transcript_path, _, quoted_answers), HumanTalked():
return Judging(transcript_path, quoted_answers)
case Closing(_, verdict), Archived():
return Ended(verdict)