Restructure the interrupt so one function owns the ask and loop-inbox imports nothing from cycle/
This commit is contained in:
@@ -132,7 +132,7 @@ Then, in the copy: `uvx --with pytest==9.2.0 'mutmut>=3,<4' run && uvx --with py
|
||||
- `judge_replay` imports `loop_claude`'s judge.
|
||||
- `larv_review` imports `rank_todo.py`'s ranking.
|
||||
- `loop_claude` runs `chunk-preflight` as a process of its own.
|
||||
- `loop_inbox` imports `loop_claude`'s question files (`waiting.py`), its effects and paths, and `hand_over`, which opens claude for `/talk`.
|
||||
- `loop_inbox` imports `loop_claude`'s question files (`waiting.py`), its effects and paths, and `hand_over.py`, which opens claude for `/talk`.
|
||||
- `machine_load/` takes the machine's heavy slots, its shared lock files, for `run_heavy`, and reads the memory share that loop-claude waits for.
|
||||
- `model_routing/` holds the routing ladder, which loop-claude, `rule_hook`, both replay tools and `subagent-rung` read.
|
||||
- `rank_todo.py`, `settings_filter.py` and `statusline.py` are tools of one file each, tested beside them.
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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))
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -9,14 +9,21 @@ import time
|
||||
import typing
|
||||
import uuid
|
||||
|
||||
from loop_claude.waiting import Answer, POLL_SECONDS
|
||||
import git_repo
|
||||
from machine_load.memory import Memory, read_memory
|
||||
|
||||
# Seconds between a loop's looks for an answer from loop-inbox while it reads its terminal, and for the end of the claude loop-inbox opened.
|
||||
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
|
||||
|
||||
|
||||
class InputOr(typing.Protocol):
|
||||
"""Prints a prompt, then returns the line typed at the terminal, or the first answer that other returns, called every POLL_SECONDS. Raises EOFError where the input ends."""
|
||||
|
||||
def __call__[T](self, prompt: str, other: typing.Callable[[], T | None]) -> str | T: ...
|
||||
|
||||
|
||||
class Streaming(typing.Protocol):
|
||||
"""A started claude whose stream-json lines arrive as it works."""
|
||||
|
||||
@@ -36,8 +43,7 @@ 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 answer from loop-inbox that the callable returns, called every POLL_SECONDS. Raises EOFError where the input ends.
|
||||
input_or: typing.Callable[[str, typing.Callable[[], Answer | None]], str | Answer]
|
||||
input_or: InputOr
|
||||
# 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.
|
||||
@@ -117,7 +123,7 @@ 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(prompt: str, other: typing.Callable[[], Answer | None]) -> str | Answer:
|
||||
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:
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
"""Opens claude on the terminal for the human. It sits outside cycle/, since loop-inbox's /talk and the loop's routing calls open claude too."""
|
||||
import dataclasses
|
||||
|
||||
from loop_claude.effects import Effects, say
|
||||
from failure import Failure
|
||||
from loop_claude.paths import Paths
|
||||
from model_routing.ladder import Rung
|
||||
from claude_code.trust import trust
|
||||
from loop_claude.project.checkout import worktrees
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class ClaudeCommand:
|
||||
"""How claude opens on a terminal: its arguments, its folder and what it adds to the environment."""
|
||||
args: list[str]
|
||||
cwd: str
|
||||
env: dict[str, str]
|
||||
|
||||
|
||||
def claude_args(rung: Rung, args: list[str]) -> list[str]:
|
||||
return [*rung.flags(), "--permission-mode", "bypassPermissions", *args]
|
||||
|
||||
|
||||
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
|
||||
@@ -200,7 +200,7 @@ def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launc
|
||||
if isinstance(closed, Stop):
|
||||
return closed
|
||||
loop_run = closed
|
||||
if stop := check_routing(archive_root(paths.home, env), loop_run.root, project or Rung(models.worker), paths, effects):
|
||||
if stop := check_routing(archive_root(paths.home, env), loop_run.root, str(session.id), project or Rung(models.worker), paths, effects):
|
||||
return stop
|
||||
|
||||
|
||||
|
||||
@@ -2,9 +2,9 @@
|
||||
import pathlib
|
||||
|
||||
from routing_figures import archive
|
||||
from loop_claude.waiting import Ask, ClaudeCommand, OpenOnTerminal
|
||||
from loop_claude.waiting import Ask, listed, OpenOnTerminal
|
||||
from routing_figures.measure import calls, due, render, totals
|
||||
from loop_claude.cycle.interrupt import claude_args, hand_over, shown, withdrawn
|
||||
from loop_claude.hand_over import claude_args, ClaudeCommand, hand_over
|
||||
from loop_claude.effects import Effects, say
|
||||
from failure import Failure
|
||||
from loop_claude.paths import Paths
|
||||
@@ -13,14 +13,14 @@ from loop_claude.stop import Stop
|
||||
from utc_stamp import utc
|
||||
|
||||
|
||||
def check_routing(root: pathlib.Path, checkout: str, rung: Rung, paths: Paths, effects: Effects) -> Stop | None:
|
||||
"""Stops only when claude cannot start for the calls; a figure it cannot measure or keep is said on stderr, and the loop goes on. checkout is the loop's, and rung is the rung of the claude that puts the calls to the human."""
|
||||
def check_routing(root: pathlib.Path, checkout: str, session: str, rung: Rung, paths: Paths, effects: Effects) -> Stop | None:
|
||||
"""Stops only when claude cannot start for the calls; a figure it cannot measure or keep is said on stderr, and the loop goes on. checkout is the loop's, session is its worker's session id, which loop-inbox lists the calls under, and rung is the rung of the claude that puts the calls to the human."""
|
||||
with archive.locked(root) as held:
|
||||
new = new_calls(root, paths, effects) if held else []
|
||||
if isinstance(new, Failure):
|
||||
say(f"routing figures: {new.reason}", effects)
|
||||
return None
|
||||
return raise_calls(root, checkout, new, rung, paths, effects) if new else None
|
||||
return raise_calls(root, checkout, session, new, rung, paths, effects) if new else None
|
||||
|
||||
|
||||
def new_calls(root: pathlib.Path, paths: Paths, effects: Effects) -> list[str] | Failure:
|
||||
@@ -43,23 +43,18 @@ def new_calls(root: pathlib.Path, paths: Paths, effects: Effects) -> list[str] |
|
||||
return [call for call in found if call not in kept.calls]
|
||||
|
||||
|
||||
def raise_calls(root: pathlib.Path, checkout: str, new: list[str], rung: Rung, paths: Paths, effects: Effects) -> Stop | None:
|
||||
def raise_calls(root: pathlib.Path, checkout: str, session: str, new: list[str], rung: Rung, paths: Paths, effects: Effects) -> Stop | None:
|
||||
"""Puts the calls to the human through a claude in this setup's checkout, where the routing decision lives; loop-inbox lists them under the loop's checkout while that claude is open. Off a terminal they are only said, and stay in the figures, raised at the next measurement on a terminal."""
|
||||
listed = "".join(f"- {call}\n" for call in new)
|
||||
question = f"loop-claude's routing figures call for a routing change:\n{listed}The figures: {root / archive.FIGURES}"
|
||||
bullets = "".join(f"- {call}\n" for call in new)
|
||||
question = f"loop-claude's routing figures call for a routing change:\n{bullets}The figures: {root / archive.FIGURES}"
|
||||
say(f"\n{question}", effects)
|
||||
if not effects.on_terminal():
|
||||
say("Not on a terminal: the calls are raised again at the next measurement.", effects)
|
||||
return None
|
||||
prompt = f"Put these calls for a routing change from loop-claude's figures to the human, and change nothing until they answer:\n{listed}The figures are in {root / archive.FIGURES}. The ladder, its steps and the delegation rule are docs/decisions.md → `routing:`, and a change to them is the human's. Record what they decide as ~/.claude/CLAUDE.md says; the next chunk of this repo files the plan item for these calls."
|
||||
# No worker session answers the calls, so the ask is filed under its own id.
|
||||
ask_id = effects.new_id()
|
||||
ask = Ask(ask_id, ask_id, checkout, question, effects.now(), effects.pid(), OpenOnTerminal())
|
||||
shown(paths, ask, effects)
|
||||
try:
|
||||
prompt = f"Put these calls for a routing change from loop-claude's figures to the human, and change nothing until they answer:\n{bullets}The figures are in {root / archive.FIGURES}. The ladder, its steps and the delegation rule are docs/decisions.md → `routing:`, and a change to them is the human's. Record what they decide as ~/.claude/CLAUDE.md says; the next chunk of this repo files the plan item for these calls."
|
||||
ask = Ask(effects.new_id(), session, checkout, question, effects.now(), effects.pid(), OpenOnTerminal())
|
||||
with listed(paths.waiting, ask, effects):
|
||||
unstarted = hand_over(ClaudeCommand(claude_args(rung, [prompt]), str(paths.claude_dir), {}), paths, effects)
|
||||
finally:
|
||||
withdrawn(paths, ask, effects)
|
||||
if unstarted:
|
||||
return Stop(1, f"could not start claude for the routing calls: {unstarted.reason}")
|
||||
# Raised once the human has seen them, answered or not: an unanswered call reaches the plan through AGENTS.md, so it is not asked twice.
|
||||
|
||||
@@ -21,9 +21,9 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
from routing_figures import archive, measure
|
||||
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 loop_claude.effects import Effects, POLL_SECONDS, PYTHON_TIMEOUT, run_python, say, system_effects
|
||||
from claude_code import entries, reply, session
|
||||
from loop_claude import escalation_mark, paths, routing, waiting
|
||||
from loop_claude import escalation_mark, hand_over, 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
|
||||
@@ -54,6 +54,8 @@ STAMP = f"<{NOW}>"
|
||||
UNREAD = Failure("not a git repository")
|
||||
# The id FakeEffects gives each new ask, and its pid for loop-claude's process.
|
||||
ASK_ID, PID = "ask-1", 4242
|
||||
# The pid of a loop-inbox that opens claude for an ask.
|
||||
INBOX = 4343
|
||||
|
||||
|
||||
def assistant(*parts):
|
||||
@@ -176,8 +178,6 @@ class Streamed:
|
||||
|
||||
|
||||
TYPED = states.TypedAnswer("Which one?", "Use B.")
|
||||
# The human chose to answer in the worker's claude session.
|
||||
TALKED = states.Talk(waiting.Ask("a1", "s1", "/c", "q", NOW, 7, waiting.OpenOnTerminal()), waiting.OpenOnTerminal())
|
||||
|
||||
|
||||
class Transitions(unittest.TestCase):
|
||||
@@ -195,10 +195,8 @@ 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(TALKED), states.Talking("/t", TALKED)),
|
||||
(states.Interrupting("/t", Interrupt("e", "q"), 3), states.TalkChosen(TALKED), states.Talking("/t", TALKED, 3)),
|
||||
(states.Talking("/t", TALKED), states.HumanTalked(), states.Judging("/t")),
|
||||
(states.Talking("/t", TALKED, 3), states.HumanTalked(), states.Judging("/t", 3)),
|
||||
(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)),
|
||||
@@ -208,8 +206,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", TALKED), states.Talking("/t", TALKED, 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(TALKED), 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.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.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]:
|
||||
@@ -224,7 +222,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(TALKED), states.Talking("/t", TALKED)),
|
||||
(states.Interrupting("/t", interrupt, 0, step_up), states.HumanTalked(), states.Judging("/t")),
|
||||
(states.Working(TYPED, 0, step_up), states.WorkerRan("/t"), states.Judging("/t")),
|
||||
):
|
||||
with self.subTest(state=state, event=event):
|
||||
@@ -663,19 +661,31 @@ class Interrupts(unittest.TestCase):
|
||||
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):
|
||||
def put(self, fake, answer_here=True, effects=None, question="Which one?"):
|
||||
with contextlib.redirect_stderr(io.StringIO()) as said:
|
||||
put = interrupt.put_question("Which one?", answer_here, self.session, self.paths, effects or fake.effects())
|
||||
return put, said.getvalue()
|
||||
answer = interrupt.interrupt(question, answer_here, self.session, self.paths, effects or fake.effects())
|
||||
return answer, said.getvalue()
|
||||
|
||||
def asked(self):
|
||||
return waiting.waiting(self.paths.waiting, lambda pid: True)
|
||||
|
||||
def ask(self, question="Which one?", state=None):
|
||||
"""The ask put_question makes for question, in state; by default it waits for an answer, and /talk resumes the worker's session."""
|
||||
resumed = waiting.ClaudeCommand(["--model", "m", "--effort", "high", "--permission-mode", "bypassPermissions", "--resume", str(self.session.id)], str(self.home), {"LOOP_CLAUDE_WORKER_RUNG": "m at high effort"})
|
||||
"""The ask interrupt makes for question, in state; by default it waits for an answer, and /talk resumes the worker's session."""
|
||||
resumed = hand_over.ClaudeCommand(["--model", "m", "--effort", "high", "--permission-mode", "bypassPermissions", "--resume", str(self.session.id)], str(self.home), {"LOOP_CLAUDE_WORKER_RUNG": "m at high effort"})
|
||||
return waiting.Ask(ASK_ID, str(self.session.id), str(self.home), question, NOW, PID, state or waiting.Asking(resumed))
|
||||
|
||||
def opening(self, other):
|
||||
"""loop-inbox's /talk, as the loop's input sees it: loop-inbox claims the one ask listed, and the claim is the first answer."""
|
||||
[ask] = self.asked()
|
||||
waiting.send(self.paths.waiting, ask, waiting.ClaudeOpening(INBOX))
|
||||
return other()
|
||||
|
||||
def typed_there(self, args):
|
||||
"""The claude opened on the terminal: the human types a line in the worker's session, and it ends."""
|
||||
with open(self.transcript, "a") as handle:
|
||||
handle.write(json.dumps(human("cut it")) + "\n")
|
||||
return 0
|
||||
|
||||
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"))
|
||||
@@ -689,8 +699,8 @@ class Interrupts(unittest.TestCase):
|
||||
def test_talks_on_talk_or_at_once_where_the_answer_is_not_asked_for_here(self):
|
||||
for typed, answer_here in (([" /talk "], True), ([], False)):
|
||||
with self.subTest(typed=typed):
|
||||
fake = FakeEffects(inputs=typed)
|
||||
self.assertEqual(self.put(fake, answer_here)[0], states.Talk(self.ask(), waiting.OpenOnTerminal()))
|
||||
fake = FakeEffects(inputs=typed, on_terminal_claude=[self.typed_there], git=[""])
|
||||
self.assertEqual(self.put(fake, answer_here)[0], interrupt.Talked())
|
||||
self.assertEqual(len(fake.made("input")), len(typed))
|
||||
self.assertEqual(fake.calls[0], ("discard_typed", None))
|
||||
|
||||
@@ -725,71 +735,62 @@ class Interrupts(unittest.TestCase):
|
||||
answer, said = self.put(FakeEffects(inputs=["Use B."]))
|
||||
self.assertEqual(answer, "Use B.")
|
||||
self.assertIn(f"loop-inbox may still list this question: cannot remove {self.paths.waiting / f'{self.session.id}.json'}: Not a directory", said)
|
||||
stop, _ = self.talk(states.Talk(self.ask(), waiting.OpenOnTerminal()), FakeEffects(on_terminal_claude=[0], git=[""]).effects())
|
||||
stop, _ = self.put(FakeEffects(inputs=["/talk"], on_terminal_claude=[0], git=[""]))
|
||||
self.assertEqual(stop, Stop(2, "the human is needed to answer the question above, but the interrupt ended with nothing typed"))
|
||||
|
||||
def talk(self, chosen, effects):
|
||||
with contextlib.redirect_stderr(io.StringIO()) as said:
|
||||
stop = interrupt.talk(chosen, self.session, self.paths, effects)
|
||||
return stop, said.getvalue()
|
||||
|
||||
def test_makes_way_for_the_claude_loop_inbox_opens_and_goes_on_once_the_human_typed_there(self):
|
||||
inbox = 4343
|
||||
def opening(other):
|
||||
[ask] = self.asked()
|
||||
waiting.send(self.paths.waiting, ask, waiting.ClaudeOpening(inbox))
|
||||
return other()
|
||||
fake = FakeEffects(inputs=[opening])
|
||||
self.assertEqual(self.put(fake), (states.Talk(self.ask(), waiting.OpenInInbox(inbox)), f"\n{STAMP} Which one?\n"))
|
||||
def claude_ran(_):
|
||||
# loop-inbox opens claude only once the loop lists it as open there.
|
||||
self.assertEqual(self.asked(), [self.ask(state=waiting.OpenInInbox(inbox))])
|
||||
self.assertEqual(self.asked(), [self.ask(state=waiting.OpenInInbox(INBOX))])
|
||||
with open(self.transcript, "a") as handle:
|
||||
handle.write(json.dumps(human("cut it")) + "\n")
|
||||
waiting.send(self.paths.waiting, self.ask(), waiting.ClaudeEnded())
|
||||
effects = dataclasses.replace(fake.effects(), sleep=claude_ran)
|
||||
self.assertEqual(self.talk(states.Talk(self.ask(), waiting.OpenInInbox(inbox)), effects), (None, f"{STAMP} claude is open for this question in loop-inbox; waiting for it to end\n"))
|
||||
fake = FakeEffects(inputs=[self.opening])
|
||||
self.assertEqual(self.put(fake, effects=dataclasses.replace(fake.effects(), sleep=claude_ran)), (interrupt.Talked(), f"\n{STAMP} Which one?\n{STAMP} claude is open for this question in loop-inbox; waiting for it to end\n"))
|
||||
self.assertEqual((fake.made("claude_on_terminal"), list(self.paths.waiting.iterdir())), ([], []))
|
||||
|
||||
def test_stops_when_loop_inbox_ends_its_claude_with_nothing_typed(self):
|
||||
inbox, looked, slept = 4343, [], []
|
||||
looked, slept = [], []
|
||||
def alive(pid):
|
||||
looked.append(pid)
|
||||
return pid == inbox
|
||||
return pid == INBOX
|
||||
def ended(seconds):
|
||||
slept.append(seconds)
|
||||
waiting.send(self.paths.waiting, self.ask(), waiting.ClaudeEnded())
|
||||
stop, _ = self.talk(states.Talk(self.ask(), waiting.OpenInInbox(inbox)), dataclasses.replace(FakeEffects().effects(), alive=alive, sleep=ended))
|
||||
self.assertEqual((stop, looked, slept), (Stop(2, "the human is needed to answer the question above, but the interrupt ended with nothing typed"), [inbox], [waiting.POLL_SECONDS]))
|
||||
fake = FakeEffects(inputs=[self.opening])
|
||||
stop, _ = self.put(fake, effects=dataclasses.replace(fake.effects(), alive=alive, sleep=ended))
|
||||
self.assertEqual((stop, looked, slept), (Stop(2, "the human is needed to answer the question above, but the interrupt ended with nothing typed"), [INBOX], [POLL_SECONDS]))
|
||||
|
||||
def test_stops_when_loop_inbox_is_gone_with_nothing_typed(self):
|
||||
inbox, looked = 4343, []
|
||||
looked = []
|
||||
def alive(pid):
|
||||
looked.append(pid)
|
||||
# loop-inbox's process ends while the loop waits for its claude.
|
||||
return pid == inbox and len(looked) == 1
|
||||
fake = FakeEffects()
|
||||
stop, _ = self.talk(states.Talk(self.ask(), waiting.OpenInInbox(inbox)), dataclasses.replace(fake.effects(), alive=alive))
|
||||
self.assertEqual((stop, looked, fake.made("sleep")), (Stop(2, "the human is needed to answer the question above, but the interrupt ended with nothing typed"), [inbox, inbox], [waiting.POLL_SECONDS]))
|
||||
return pid == INBOX and len(looked) == 1
|
||||
fake = FakeEffects(inputs=[self.opening])
|
||||
stop, _ = self.put(fake, effects=dataclasses.replace(fake.effects(), alive=alive))
|
||||
self.assertEqual((stop, looked, fake.made("sleep")), (Stop(2, "the human is needed to answer the question above, but the interrupt ended with nothing typed"), [INBOX, INBOX], [POLL_SECONDS]))
|
||||
|
||||
def test_lists_the_claude_open_on_its_terminal_in_loop_inbox_while_it_runs(self):
|
||||
def ran(args):
|
||||
self.assertEqual(self.asked(), [self.ask("Cut 0.4.0?", waiting.OpenOnTerminal())])
|
||||
return 0
|
||||
fake = FakeEffects(on_terminal_claude=[ran], git=[""])
|
||||
self.talk(states.Talk(self.ask("Cut 0.4.0?"), waiting.OpenOnTerminal()), fake.effects())
|
||||
self.assertEqual(len(fake.made("claude_on_terminal")), 1)
|
||||
self.assertEqual(list(self.paths.waiting.iterdir()), [])
|
||||
for typed, answer_here in (([" /talk "], True), ([], False)):
|
||||
with self.subTest(typed=typed):
|
||||
def ran(args):
|
||||
self.assertEqual(self.asked(), [self.ask("Cut 0.4.0?", waiting.OpenOnTerminal())])
|
||||
return 0
|
||||
fake = FakeEffects(inputs=typed, on_terminal_claude=[ran], git=[""])
|
||||
self.put(fake, answer_here, question="Cut 0.4.0?")
|
||||
self.assertEqual(len(fake.made("claude_on_terminal")), 1)
|
||||
self.assertEqual(list(self.paths.waiting.iterdir()), [])
|
||||
|
||||
def test_stops_when_nothing_was_typed_in_the_session(self):
|
||||
fake = FakeEffects(on_terminal_claude=[0], git=[""])
|
||||
stop, _ = self.talk(states.Talk(self.ask(), waiting.OpenOnTerminal()), fake.effects())
|
||||
fake = FakeEffects(inputs=["/talk"], on_terminal_claude=[0], git=[""])
|
||||
stop, _ = self.put(fake)
|
||||
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):
|
||||
fake = FakeEffects(on_terminal_claude=[0], git=[""])
|
||||
self.talk(states.Talk(self.ask(), waiting.OpenOnTerminal()), fake.effects())
|
||||
fake = FakeEffects(inputs=["/talk"], on_terminal_claude=[0], git=[""])
|
||||
self.put(fake)
|
||||
self.assertEqual(fake.terminal_environments, [{"LOOP_CLAUDE_WORKER_RUNG": "m at high effort"}])
|
||||
|
||||
|
||||
@@ -817,14 +818,14 @@ class RoutingCheck(unittest.TestCase):
|
||||
def check(self, fake):
|
||||
"""What check_routing returns and says for a loop in /code/log."""
|
||||
with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()) as said:
|
||||
stop = routing_check.check_routing(self.root, "/code/log", Rung("m", "high"), self.paths, fake.effects())
|
||||
stop = routing_check.check_routing(self.root, "/code/log", "s1", Rung("m", "high"), self.paths, fake.effects())
|
||||
return stop, said.getvalue()
|
||||
|
||||
def test_lists_the_calls_in_loop_inbox_while_their_claude_is_open(self):
|
||||
self.chunks(5, 4)
|
||||
question = f"loop-claude's routing figures call for a routing change:\n- Explore subagents' reports took more of the worker's context than their searches would have.\nThe figures: {self.root / 'routing-figures.md'}"
|
||||
def ran(args):
|
||||
self.assertEqual(waiting.waiting(self.paths.waiting, lambda pid: True), [waiting.Ask(ASK_ID, ASK_ID, "/code/log", question, NOW, PID, waiting.OpenOnTerminal())])
|
||||
self.assertEqual(waiting.waiting(self.paths.waiting, lambda pid: True), [waiting.Ask(ASK_ID, "s1", "/code/log", question, NOW, PID, waiting.OpenOnTerminal())])
|
||||
return 0
|
||||
self.check(FakeEffects(on_terminal_claude=[ran], git=[UNREAD, ""]))
|
||||
self.assertEqual(list(self.paths.waiting.iterdir()), [])
|
||||
@@ -1720,7 +1721,7 @@ 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", "opened", "1", "f'could not start claude for the interrupt:", "claude cannot start for an interrupt"),
|
||||
("cycle/interrupt.py", "claude_open", "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"),
|
||||
|
||||
+32
-17
@@ -1,43 +1,36 @@
|
||||
"""The files by which a loop-claude shows its interrupt in loop-inbox, and takes an answer typed there.
|
||||
|
||||
A waiting loop keeps its ask in <session>.json in Paths.waiting: the question, with an id new for each question.
|
||||
<session> is the worker's session id, or the ask's own id for the routing calls, which have no worker session.
|
||||
The loop removes the file once the question is answered or the loop stops. The ask's state says whether the loop
|
||||
waits for an answer, or has claude open for it, on the loop's own terminal or in loop-inbox. loop-inbox answers by
|
||||
replacing <session>.answer, which names the ask's id. So an answer meant for an earlier question, or sent as the
|
||||
loop took an answer on its terminal, never answers a later one.
|
||||
<session> is the worker's session id, so a loop lists one question at a time. The loop removes the file once the
|
||||
question is answered or the loop stops. The ask's state says whether the loop waits for an answer, or has claude
|
||||
open for it, on the loop's own terminal or in loop-inbox. loop-inbox answers by replacing <session>.answer, which
|
||||
names the ask's id. So an answer meant for an earlier question, or sent as the loop took an answer on its terminal,
|
||||
never answers a later one.
|
||||
|
||||
/talk from loop-inbox goes in three steps, so that only one claude ever holds the worker's session:
|
||||
1. loop-inbox's claim_talk sends ClaudeOpening, with its pid.
|
||||
2. The loop stops reading its terminal and republishes its ask as OpenInInbox with that pid. claim_talk returns True
|
||||
once it reads that, and loop-inbox opens claude.
|
||||
2. The loop stops reading its terminal, and its make_way lists the ask as OpenInInbox with that pid. claim_talk
|
||||
returns True once it reads that, and loop-inbox opens claude.
|
||||
3. loop-inbox sends ClaudeEnded once claude exits, which the loop reads with claude_ended. The loop also stops waiting
|
||||
if loop-inbox's process is gone.
|
||||
"""
|
||||
import contextlib
|
||||
import dataclasses
|
||||
import json
|
||||
import pathlib
|
||||
import typing
|
||||
|
||||
from loop_claude.hand_over import ClaudeCommand
|
||||
from loop_claude.effects import Effects, POLL_SECONDS, say
|
||||
from failure import Failure
|
||||
from file_writes import make_private, replace_json
|
||||
|
||||
# Seconds between a loop's looks for an answer from loop-inbox, and for the end of the claude loop-inbox opened.
|
||||
POLL_SECONDS = 0.5
|
||||
# Seconds loop-inbox waits for a loop to make way for its claude: ten of the loop's looks, so a loop slow for a moment still makes way.
|
||||
MAKE_WAY_SECONDS = 10 * POLL_SECONDS
|
||||
# What the human types, on the loop's terminal or in loop-inbox, to open claude for the ask; picked on 2026-10-17 by a bench of three readers seated as the README's audience.
|
||||
TALK = "/talk"
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class ClaudeCommand:
|
||||
"""How claude opens on a terminal: its arguments, its folder and what it adds to the environment."""
|
||||
args: list[str]
|
||||
cwd: str
|
||||
env: dict[str, str]
|
||||
|
||||
|
||||
@dataclasses.dataclass(frozen=True)
|
||||
class Asking:
|
||||
"""The ask waits for an answer; talk opens the worker's claude session for /talk."""
|
||||
@@ -119,6 +112,23 @@ def withdraw(folder: pathlib.Path, session: str) -> Failure | None:
|
||||
return None
|
||||
|
||||
|
||||
def shown(folder: pathlib.Path, ask: Ask, effects: Effects) -> None:
|
||||
"""Lists ask in loop-inbox, in its state. A failure only warns: the question is still answered on the loop's terminal."""
|
||||
if unshown := publish(folder, ask):
|
||||
say(f"loop-inbox cannot show this question: {unshown.reason}", effects)
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def listed(folder: pathlib.Path, ask: Ask, effects: Effects) -> typing.Iterator[None]:
|
||||
"""Lists ask in loop-inbox while the with block runs, then takes it out, with any answer. A failure to take it out only warns: loop-inbox drops the ask once the loop's process ends."""
|
||||
shown(folder, ask, effects)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
if unwithdrawn := withdraw(folder, ask.session):
|
||||
say(f"loop-inbox may still list this question: {unwithdrawn.reason}", effects)
|
||||
|
||||
|
||||
def waiting(folder: pathlib.Path, alive: typing.Callable[[int], bool]) -> list[Ask]:
|
||||
"""The asks of loops still running, oldest first. A file that cannot be read or parsed is left out."""
|
||||
try:
|
||||
@@ -206,3 +216,8 @@ def claim_talk(folder: pathlib.Path, ask: Ask, pid: int, now: typing.Callable[[]
|
||||
# Takes the claim back: a loop that reads it late waits for no claude, and one that made way late, or failed to show it had, ends its wait.
|
||||
send(folder, ask, ClaudeEnded())
|
||||
return False
|
||||
|
||||
|
||||
def make_way(folder: pathlib.Path, ask: Ask, pid: int, effects: Effects) -> None:
|
||||
"""The loop's side of /talk from loop-inbox, once it has stopped reading its terminal: lists ask as having claude open in the loop-inbox whose process is pid, which claim_talk waits for. A failure only warns: claim_talk then gives up, and the loop stops."""
|
||||
shown(folder, dataclasses.replace(ask, state=OpenInInbox(pid)), effects)
|
||||
|
||||
@@ -36,7 +36,7 @@ from loop_inbox.inbox import Answering, answering_lines, BACKSPACE, ENTER, ESCAP
|
||||
from loop_claude.waiting import Ask, ask_file, Asking, claim_talk, ClaudeEnded, MAKE_WAY_SECONDS, read_ask, send, Typed, waiting
|
||||
from loop_claude.effects import Effects, system_effects
|
||||
from failure import Failure
|
||||
from loop_claude.cycle.interrupt import hand_over
|
||||
from loop_claude.hand_over import hand_over
|
||||
from loop_claude.paths import Paths, paths_from
|
||||
|
||||
USAGE = "usage: loop-inbox"
|
||||
|
||||
@@ -12,7 +12,8 @@ import unittest.mock
|
||||
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, Asking, ClaudeCommand, OpenInInbox, OpenOnTerminal, Typed
|
||||
from loop_claude.waiting import Ask, Asking, OpenInInbox, OpenOnTerminal, Typed
|
||||
from loop_claude.hand_over import ClaudeCommand
|
||||
from failure import Failure
|
||||
from loop_inbox import inbox, main
|
||||
from loop_claude.paths import paths_from
|
||||
|
||||
@@ -350,7 +350,7 @@ The key names the project's session, archive folder and models entry. `project_k
|
||||
|
||||
### 51. Hand loop-claude's terminal output to an injected effect, so no storage or retry function prints.
|
||||
|
||||
"Functional core, imperative shell", in `principles/technical-principles.md`: `retried`, the worker, `put_question`, `model_choice` and `say` print to stderr themselves, and the tests swap the global stream.
|
||||
"Functional core, imperative shell", in `principles/technical-principles.md`: `retried`, the worker, `first_answer`, `model_choice` and `say` print to stderr themselves, and the tests swap the global stream.
|
||||
|
||||
### 169. Have rule-hook's `todo-rank-check` catch a `todo.md` that the same Bash call edits and then commits.
|
||||
|
||||
@@ -366,7 +366,7 @@ The principles pass of PR #301 found that only `routed_by` in `bin/loop_claude/c
|
||||
|
||||
### 197. Let the human edit what they type at loop-claude's terminal questions with the arrow keys, so Left moves the cursor in place of printing `^[[D`.
|
||||
|
||||
`bin/loop_claude/effects.py` hands loop-claude Python's builtin `input`, and nothing under `bin/` imports `readline`, so the terminal gets no line editing: fixing a typo means erasing back to it. `effects.input` reads the answer to both of loop-claude's questions: the interrupt, in `cycle/interrupt.py`'s `put_question`, and the pick of the project's model, in `project/model_choice.py`'s `ask_for_model`. Importing `readline` in `effects.py` gives both line editing, at two costs. It moves the prompt from stderr to stdout, while the question above it stays on stderr. `test_black_box.py` waits for the prompt on stderr. `readline`'s bracketed paste takes a pasted block whole, so an answer can hold several lines. `prompts.typed_answer` ends the answer at its first blank line, so the judge would read the rest of such a paste as loop-claude's words. The product-owner review of PR #308 raised the interrupt's case. lilleman, 2026-10-18: "Not super-important, but a bit irritating."
|
||||
`bin/loop_claude/effects.py` hands loop-claude Python's builtin `input`, and nothing under `bin/` imports `readline`, so the terminal gets no line editing: fixing a typo means erasing back to it. loop-claude asks two questions at its terminal. `effects.input` reads the pick of the project's model, in `project/model_choice.py`'s `ask_for_model`. `effects.input_or` reads the interrupt's answer, in `cycle/interrupt.py`'s `first_answer`, straight from stdin, since it also watches loop-inbox. Importing `readline` in `effects.py` gives `input` line editing, at two costs; `input_or` would also need to read through `input` while it watches. It moves the prompt from stderr to stdout, while the question above it stays on stderr. `test_black_box.py` waits for the prompt on stderr. `readline`'s bracketed paste takes a pasted block whole, so an answer can hold several lines. `prompts.typed_answer` ends the answer at its first blank line, so the judge would read the rest of such a paste as loop-claude's words. The product-owner review of PR #308 raised the interrupt's case. lilleman, 2026-10-18: "Not super-important, but a bit irritating."
|
||||
|
||||
### 170. Re-tune `WORKER_STEPS` and `REVIEW_STEPS` once 50 chunks have shipped under them, from how well L, E and I order their review rounds and 🔴 findings.
|
||||
|
||||
|
||||
Reference in New Issue
Block a user