Answer architecture round 1: 0 🔴, 2 🟡; keep stepped_from through the typed answer, name the events HumanTyped and HumanTalked, parse the answer from the prompt's start, and say why the judge decides release_ready

This commit is contained in:
2026-10-17 23:16:34 +02:00
parent 831b9c63b6
commit 96834412c7
7 changed files with 90 additions and 96 deletions
+13 -15
View File
@@ -16,22 +16,20 @@ TALK = "/talk"
ASK_ANSWER = f"Answer ({TALK} opens claude, Enter stops the loop): " ASK_ANSWER = f"Answer ({TALK} opens claude, Enter stops the loop): "
def interrupt(root: str, session_id: uuid.UUID, worker: Rung, path: str, question: str, release_ready: bool, paths: Paths, env: dict[str, str], effects: Effects) -> Stop | str | None: def put_question(question: str, effects: Effects) -> Stop | None:
"""Puts question to the human on loop-claude's terminal and returns the answer they typed. Typing TALK instead opens the worker's session in claude on the terminal, and so does a release ready to cut, at once, since only the human may cut it; None is returned once they typed there.""" """Prints question for the human; a Stop where loop-claude is off a terminal, so no one can answer it."""
print(f"\n{question}", file=sys.stderr) print(f"\n{question}", file=sys.stderr)
if stop := needs_terminal(ANSWER_QUESTION, effects.on_terminal()): return needs_terminal(ANSWER_QUESTION, effects.on_terminal())
return stop
if not release_ready:
try: def read_answer(effects: Effects) -> str | Stop:
answer = effects.input(ASK_ANSWER).strip() """The line the human types at loop-claude's terminal, stripped: their answer, or TALK where they ask for claude's session; a Stop where they type nothing or the input ends."""
except EOFError: try:
print(file=sys.stderr) answer = effects.input(ASK_ANSWER).strip()
return needs_human(ANSWER_QUESTION, "the input ended") except EOFError:
if not answer: print(file=sys.stderr)
return needs_human(ANSWER_QUESTION, "nothing was typed") return needs_human(ANSWER_QUESTION, "the input ended")
if answer != TALK: return answer or needs_human(ANSWER_QUESTION, "nothing was typed")
return answer
return talk(root, session_id, worker, path, paths, env, effects)
def talk(root: str, session_id: uuid.UUID, worker: Rung, path: str, paths: Paths, env: dict[str, str], effects: Effects) -> Stop | None: def talk(root: str, session_id: uuid.UUID, worker: Rung, path: str, paths: Paths, env: dict[str, str], effects: Effects) -> Stop | None:
+1 -1
View File
@@ -72,7 +72,7 @@ class Reply:
finished: bool = dataclasses.field(metadata={"description": "Whether the chunk is finished."}) finished: bool = dataclasses.field(metadata={"description": "Whether the chunk is finished."})
interrupt: bool = dataclasses.field(metadata={"description": "Whether the human must now be interrupted."}) interrupt: bool = dataclasses.field(metadata={"description": "Whether the human must now be interrupted."})
question: str = dataclasses.field(metadata={"description": "With interrupt true, the single question to put to the human. With a quoted answer, the agent's question that the answer field answers. Empty otherwise."}) question: str = dataclasses.field(metadata={"description": "With interrupt true, the single question to put to the human. With a quoted answer, the agent's question that the answer field answers. Empty otherwise."})
# Opens claude's session for the human at once, in place of asking for a one-line answer: interrupt.interrupt. # Opens claude's session for the human at once, in place of asking for a one-line answer: run.ask. The judge decides it, not the plan's standing (todo_table.chunk_item), which loop-claude computes only as a chunk on the ladder is routed afresh, so a release ready to cut in a resumed chunk, or off the ladder, would be missed. A wrong ruling costs the human one typed /talk, or a session they leave.
release_ready: bool = dataclasses.field(metadata={"description": "Whether interrupt is true for a release ready to cut, which only the human may publish."}) release_ready: bool = dataclasses.field(metadata={"description": "Whether interrupt is true for a release ready to cut, which only the human may publish."})
+7 -7
View File
@@ -129,18 +129,18 @@ def answered(question: str, answer: str, route: Route, anchor: Rung | None, step
def typed(question: str, answer: str, route: Route, anchor: Rung | None, stepped: bool) -> str: def typed(question: str, answer: str, route: Route, anchor: Rung | None, stepped: bool) -> str:
"""Resumes the worker with the human's answer to an interrupt. answer is one line, as the terminal reads it, so typed_answer finds where it ends.""" """Resumes the worker with the human's answer to an interrupt. answer is one line, as the terminal reads it."""
return f"Your question: {question}\n\n{TYPED_HERE}\n\n{answer}\n\nContinue the task.{stepped_to(route, anchor, stepped)}" return f"{TYPED_HERE}\n{answer}\n\nYour question was: {question}\n\nContinue the task.{stepped_to(route, anchor, stepped)}"
# Precedes the answer in typed's prompt. # Opens typed's prompt, and the answer is the line after it, so typed_answer reads the answer from the prompt's start alone.
TYPED_HERE = "The human answers it at loop-claude's terminal:" TYPED_HERE = "The human answered your question at loop-claude's terminal:"
def typed_answer(prompt: str) -> str | None: def typed_answer(prompt: str) -> str | None:
"""The answer typed put in prompt, so the judge reads it as the human's; None for any other prompt. The last TYPED_HERE is typed's: the one-line answer cannot hold it, and only the sentences on a stepped rung follow.""" """The answer typed put in prompt, so the judge reads it as the human's; None for any other prompt."""
_, here, after = prompt.rpartition(f"\n\n{TYPED_HERE}\n\n") opening = f"{TYPED_HERE}\n"
return after.split("\n", 1)[0] if here and prompt.startswith("Your question: ") else None return prompt.removeprefix(opening).split("\n", 1)[0] if prompt.startswith(opening) else None
def stepped_to(route: Route, anchor: Rung | None, stepped: bool) -> str: def stepped_to(route: Route, anchor: Rung | None, stepped: bool) -> str:
+18 -12
View File
@@ -2,17 +2,17 @@ import dataclasses
import pathlib import pathlib
import typing import typing
from loop_claude.cycle.states import Active, Archived, Closing, Ended, Event, HumanAnswered, Interrupting, Judging, QUOTED_ANSWERS_PER_CYCLE, Ruled, State, 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 transcript_archive.write import archive from transcript_archive.write import archive
from claude_code.session import delete_session, Session, session_open, transcript_file from claude_code.session import delete_session, Session, session_open, transcript_file
from loop_claude.effects import Effects from loop_claude.effects import Effects
from failure import Failure from failure import Failure
from loop_claude.cycle.judge import Finished, Interrupt, judge, QuotedAnswer, Rejected, Unfinished, Verdict from loop_claude.cycle.judge import Finished, Interrupt, judge, QuotedAnswer, Rejected, Unfinished, Verdict
from loop_claude.cycle.interrupt import interrupt
from loop_claude.routing import judge_rung, stepped_by_ruling from loop_claude.routing import judge_rung, stepped_by_ruling
from transcript_archive import outcomes from transcript_archive import outcomes
from loop_claude.paths import Paths from loop_claude.paths import Paths
from loop_claude.cycle import prompts from loop_claude.cycle import prompts
from loop_claude.cycle.interrupt import put_question, read_answer, talk, TALK
from claude_code.transcript import read_transcript from claude_code.transcript import read_transcript
from loop_claude.cycle.retry import retried from loop_claude.cycle.retry import retried
from model_routing.route import Route from model_routing.route import Route
@@ -41,7 +41,7 @@ class Cycle:
# Empty when the previous cycle's verdict was not Unfinished. # Empty when the previous cycle's verdict was not Unfinished.
unfinished_evidence: str unfinished_evidence: str
# Only an interrupt's or a quoted answer's escalation changes the route within a cycle. No transition reads the route or the fields below, so they stay out of the states. # Only an interrupt's or a quoted answer's escalation changes the route within a cycle. No transition reads the route or the fields below, so they stay out of the states.
# The route before that ruling stepped it up, for ask and keep_answer to archive and for ask to tell the worker; None unless the latest event stepped the route up. # The route before that ruling stepped it up, for ask and keep_answer to archive and for worker_start to tell the worker; None unless the latest event is that ruling, or the answer the human typed to it.
stepped_from: Route | None = None stepped_from: Route | None = None
# Whether an interrupt or a quoted answer of this cycle took an escalation, after which no ruling of the cycle carries one. # Whether an interrupt or a quoted answer of this cycle took an escalation, after which no ruling of the cycle carries one.
escalation_spent: bool = False escalation_spent: bool = False
@@ -69,7 +69,9 @@ def run_cycle(cycle: Cycle) -> Stop | Concluded:
def escalated(cycle: Cycle, event: Event) -> Cycle: def escalated(cycle: Cycle, event: Event) -> Cycle:
"""The cycle after event. Where the judge interrupted or quoted an answer with an escalation, its route steps up before the human is asked or the worker resumes, so the work after the answer runs on it.""" """The cycle after event. Where the judge interrupted or quoted an answer with an escalation, its route steps up before the human is asked or the worker resumes, so the work after the answer runs on it. stepped_from holds through the answer the human types, so the worker resuming with it is told of the step."""
if isinstance(event, HumanTyped):
return cycle
cycle = dataclasses.replace(cycle, stepped_from=None) cycle = dataclasses.replace(cycle, stepped_from=None)
if not (isinstance(event, Ruled) and isinstance(event.verdict, Interrupt | QuotedAnswer) and event.verdict.escalation): if not (isinstance(event, Ruled) and isinstance(event.verdict, Interrupt | QuotedAnswer) and event.verdict.escalation):
return cycle return cycle
@@ -124,7 +126,7 @@ def worker_start(cycle: Cycle, answered: QuotedAnswer | TypedAnswer | None) -> l
if isinstance(answered, QuotedAnswer): if isinstance(answered, QuotedAnswer):
return worker_args(cycle.session, cycle.route.rung, prompts.answered(answered.question, answered.answer, cycle.route, cycle.anchor, cycle.stepped_from is not None), resume=True) return worker_args(cycle.session, cycle.route.rung, prompts.answered(answered.question, answered.answer, cycle.route, cycle.anchor, cycle.stepped_from is not None), resume=True)
if isinstance(answered, TypedAnswer): if isinstance(answered, TypedAnswer):
return worker_args(cycle.session, cycle.route.rung, prompts.typed(answered.question, answered.answer, cycle.route, cycle.anchor, answered.stepped), resume=True) return worker_args(cycle.session, cycle.route.rung, prompts.typed(answered.question, answered.answer, cycle.route, cycle.anchor, cycle.stepped_from is not None), resume=True)
if session_open(cycle.session): if session_open(cycle.session):
return worker_args(cycle.session, cycle.route.rung, prompts.resumed(cycle.unfinished_evidence, cycle.route, cycle.anchor), resume=True) return worker_args(cycle.session, cycle.route.rung, prompts.resumed(cycle.unfinished_evidence, cycle.route, cycle.anchor), resume=True)
return worker_args(cycle.session, cycle.route.rung, prompts.fresh(cycle.task, cycle.premises, cycle.route, cycle.anchor, cycle.facts), resume=False) return worker_args(cycle.session, cycle.route.rung, prompts.fresh(cycle.task, cycle.premises, cycle.route, cycle.anchor, cycle.facts), resume=False)
@@ -163,19 +165,23 @@ def keep_rejection(cycle: Cycle, transcript_path: str, rejected: Rejected) -> St
return None return None
def ask(cycle: Cycle, transcript_path: str, ruling: Interrupt | QuotedAnswer) -> HumanAnswered | Stop: def ask(cycle: Cycle, transcript_path: str, ruling: Interrupt | QuotedAnswer) -> HumanTyped | HumanTalked | Stop:
question = question_for(ruling) 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. # 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. # 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.
interrupted = outcomes.interrupted(question, ruling.evidence, str(judge_of(cycle)), ruling.escalation, str(cycle.stepped_from or cycle.route)) interrupted = outcomes.interrupted(question, ruling.evidence, str(judge_of(cycle)), ruling.escalation, str(cycle.stepped_from or cycle.route))
if failure := archive_stepped(cycle, transcript_path, interrupted): if failure := archive_stepped(cycle, transcript_path, interrupted):
return Stop(1, failure.reason) return Stop(1, failure.reason)
release_ready = isinstance(ruling, Interrupt) and ruling.release_ready if stop := put_question(question, cycle.effects):
answer = interrupt(cycle.root, cycle.session.id, cycle.route.rung, transcript_path, question, release_ready, cycle.paths, worker_environment(cycle), cycle.effects) return stop
if isinstance(answer, Stop): # Only the human may cut a release, so a release ready to cut opens claude's session at once.
return answer if not (isinstance(ruling, Interrupt) and ruling.release_ready):
# The step is told with the answer, since the worker resumes after the next event, which clears stepped_from. answer = read_answer(cycle.effects)
return HumanAnswered(TypedAnswer(question, answer, cycle.stepped_from is not None) if answer is not None else None) if isinstance(answer, Stop):
return answer
if answer != TALK:
return HumanTyped(TypedAnswer(question, answer))
return talk(cycle.root, cycle.session.id, cycle.route.rung, transcript_path, cycle.paths, worker_environment(cycle), cycle.effects) or HumanTalked()
def archive_stepped(cycle: Cycle, transcript_path: str, outcome: str) -> Failure | None: def archive_stepped(cycle: Cycle, transcript_path: str, outcome: str) -> Failure | None:
+11 -8
View File
@@ -8,10 +8,9 @@ QUOTED_ANSWERS_PER_CYCLE = 3
@dataclasses.dataclass(frozen=True) @dataclasses.dataclass(frozen=True)
class TypedAnswer: class TypedAnswer:
"""The human's answer to an interrupt, typed at loop-claude's terminal; stepped is whether the interrupt stepped the worker up.""" """The human's answer to an interrupt, typed at loop-claude's terminal."""
question: str question: str
answer: str answer: str
stepped: bool
@dataclasses.dataclass(frozen=True) @dataclasses.dataclass(frozen=True)
@@ -62,9 +61,13 @@ class Ruled:
@dataclasses.dataclass(frozen=True) @dataclasses.dataclass(frozen=True)
class HumanAnswered: class HumanTyped:
"""typed is None where the human answered in the interrupt's claude session.""" typed: TypedAnswer
typed: TypedAnswer | None = None
@dataclasses.dataclass(frozen=True)
class HumanTalked:
"""The human typed in the interrupt's claude session."""
@dataclasses.dataclass(frozen=True) @dataclasses.dataclass(frozen=True)
@@ -72,7 +75,7 @@ class Archived:
pass pass
Event = WorkerRan | Ruled | HumanAnswered | Archived Event = WorkerRan | Ruled | HumanTyped | HumanTalked | Archived
def transition(state: State, event: Event) -> State: def transition(state: State, event: Event) -> State:
@@ -87,10 +90,10 @@ def transition(state: State, event: Event) -> State:
return Interrupting(transcript_path, ruling, quoted_answers) return Interrupting(transcript_path, ruling, quoted_answers)
case Judging(transcript_path, _), Ruled(Finished() | Unfinished() as verdict): case Judging(transcript_path, _), Ruled(Finished() | Unfinished() as verdict):
return Closing(transcript_path, verdict) return Closing(transcript_path, verdict)
case Interrupting(_, _, quoted_answers), HumanAnswered(TypedAnswer() as typed): case Interrupting(_, _, quoted_answers), HumanTyped(typed):
return Working(typed, quoted_answers) return Working(typed, quoted_answers)
# The human worked in the interrupt's claude session, so the judge rules again on the transcript it leaves. # The human worked in the interrupt's claude session, so the judge rules again on the transcript it leaves.
case Interrupting(transcript_path, _, quoted_answers), HumanAnswered(None): case Interrupting(transcript_path, _, quoted_answers), HumanTalked():
return Judging(transcript_path, quoted_answers) return Judging(transcript_path, quoted_answers)
case Closing(_, verdict), Archived(): case Closing(_, verdict), Archived():
return Ended(verdict) return Ended(verdict)
+1 -1
View File
@@ -664,7 +664,7 @@ class Interrupt(unittest.TestCase):
self.assertIn("A or B?\nAnswer (/talk opens claude, Enter stops the loop): ", run.stderr) self.assertIn("A or B?\nAnswer (/talk opens claude, Enter stops the loop): ", run.stderr)
resumed = run.calls[2]["argv"] resumed = run.calls[2]["argv"]
self.assertEqual(argument(run.calls[2], "--resume"), argument(run.calls[0], "--session-id")) self.assertEqual(argument(run.calls[2], "--resume"), argument(run.calls[0], "--session-id"))
self.assertEqual(resumed[resumed.index("-p") + 1], "Your question: A or B?\n\nThe human answers it at loop-claude's terminal:\n\nB\n\nContinue the task.") self.assertEqual(resumed[resumed.index("-p") + 1], "The human answered your question at loop-claude's terminal:\nB\n\nYour question was: A or B?\n\nContinue the task.")
self.assertIn("[human] B\n\nUsing B.", run.calls[3]["stdin"]) self.assertIn("[human] B\n\nUsing B.", run.calls[3]["stdin"])
for transcript in checkout.transcripts(): for transcript in checkout.transcripts():
+39 -52
View File
@@ -143,7 +143,7 @@ class Streamed:
return self.code return self.code
TYPED = states.TypedAnswer("Which one?", "Use B.", False) TYPED = states.TypedAnswer("Which one?", "Use B.")
class Transitions(unittest.TestCase): class Transitions(unittest.TestCase):
@@ -161,10 +161,10 @@ class Transitions(unittest.TestCase):
(states.Judging("/t", 3), states.Ruled(Finished("e")), states.Closing("/t", Finished("e"))), (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"), states.Ruled(Unfinished("e")), states.Closing("/t", Unfinished("e"))),
(states.Judging("/t", 3), 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.HumanAnswered(), states.Judging("/t")), (states.Interrupting("/t", Interrupt("e", "q")), states.HumanTalked(), states.Judging("/t")),
(states.Interrupting("/t", Interrupt("e", "q"), 3), states.HumanAnswered(), states.Judging("/t", 3)), (states.Interrupting("/t", Interrupt("e", "q"), 3), states.HumanTalked(), states.Judging("/t", 3)),
(states.Interrupting("/t", Interrupt("e", "q")), states.HumanAnswered(TYPED), states.Working(TYPED)), (states.Interrupting("/t", Interrupt("e", "q")), states.HumanTyped(TYPED), states.Working(TYPED)),
(states.Interrupting("/t", Interrupt("e", "q"), 3), states.HumanAnswered(TYPED), states.Working(TYPED, 3)), (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)), (states.Working(TYPED, 3), states.WorkerRan("/t"), states.Judging("/t", 3)),
(states.Closing("/t", Finished("e")), states.Archived(), states.Ended(Finished("e"))), (states.Closing("/t", Finished("e")), states.Archived(), states.Ended(Finished("e"))),
(states.Closing("/t", Unfinished("e")), states.Archived(), states.Ended(Unfinished("e"))), (states.Closing("/t", Unfinished("e")), states.Archived(), states.Ended(Unfinished("e"))),
@@ -173,7 +173,7 @@ class Transitions(unittest.TestCase):
with self.subTest(state=state, event=event): with self.subTest(state=state, event=event):
self.assertEqual(states.transition(state, event), after) 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.Closing("/t", Finished("e")), states.Ended(Finished("e"))) 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.HumanAnswered(), states.HumanAnswered(TYPED), states.Archived()) 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 state in every_state:
for event in every_event: for event in every_event:
if (state, event) not in [(state, event) for state, event, _ in legal]: if (state, event) not in [(state, event) for state, event, _ in legal]:
@@ -384,10 +384,10 @@ class Cycles(unittest.TestCase):
self.assertEqual(fake.made("claude_on_terminal"), []) self.assertEqual(fake.made("claude_on_terminal"), [])
resumed = fake.made("stream_claude")[1] resumed = fake.made("stream_claude")[1]
self.assertEqual(resumed[resumed.index("--resume") + 1], str(self.session.id)) self.assertEqual(resumed[resumed.index("--resume") + 1], str(self.session.id))
self.assertEqual(resumed[resumed.index("-p") + 1], "Your question: Which one?\n\nThe human answers it at loop-claude's terminal:\n\nUse B.\n\nContinue the task.") self.assertEqual(resumed[resumed.index("-p") + 1], "The human answered your question at loop-claude's terminal:\nUse B.\n\nYour question was: Which one?\n\nContinue the task.")
judge_prompts = [stdin for args, stdin in fake.made("claude")] judge_prompts = [stdin for args, stdin in fake.made("claude")]
self.assertTrue(judge_prompts[1].split("\n\nDecide whether")[0].endswith("[human] Use B.\n\nworking")) self.assertTrue(judge_prompts[1].split("\n\nDecide whether")[0].endswith("[human] Use B.\n\nworking"))
self.assertNotIn("[loop] Your question", judge_prompts[1]) self.assertNotIn("[loop] The human answered", judge_prompts[1])
def test_an_interrupt_that_steps_the_worker_up_names_its_new_rung_in_the_prompt_that_resumes_it_with_the_typed_answer(self): def test_an_interrupt_that_steps_the_worker_up_names_its_new_rung_in_the_prompt_that_resumes_it_with_the_typed_answer(self):
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 2, claude=[judged("interrupt", escalation="working"), judged("finished")], inputs=["Use B."]) fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 2, claude=[judged("interrupt", escalation="working"), judged("finished")], inputs=["Use B."])
@@ -397,7 +397,7 @@ class Cycles(unittest.TestCase):
self.assertEqual(concluded.route, Route(Routing.OPUS, 179, 2, 5)) self.assertEqual(concluded.route, Route(Routing.OPUS, 179, 2, 5))
first, resumed = fake.made("stream_claude") first, resumed = fake.made("stream_claude")
self.assertEqual([args[args.index("--effort") + 1] for args in (first, resumed)], ["high", "medium"]) self.assertEqual([args[args.index("--effort") + 1] for args in (first, resumed)], ["high", "medium"])
self.assertTrue(resumed[resumed.index("-p") + 1].endswith(f"Use B.\n\nContinue the task. Your request for a higher rung went through: loop-claude runs you on {Routing.OPUS}.{prompts.rungs_held(concluded.route, Routing.OPUS)} A further request for a higher rung steps you up no more in this cycle.")) self.assertEqual(resumed[resumed.index("-p") + 1], f"The human answered your question at loop-claude's terminal:\nUse B.\n\nYour question was: Which one?\n\nContinue the task. Your request for a higher rung went through: loop-claude runs you on {Routing.OPUS}.{prompts.rungs_held(concluded.route, Routing.OPUS)} A further request for a higher rung steps you up no more in this cycle.")
def test_a_release_ready_to_cut_opens_claudes_session_without_asking_for_an_answer(self): def test_a_release_ready_to_cut_opens_claudes_session_without_asking_for_an_answer(self):
def answer(args): def answer(args):
@@ -513,59 +513,44 @@ class Limits(unittest.TestCase):
class Interrupts(unittest.TestCase): class Interrupts(unittest.TestCase):
def ask(self, fake, home="/h", path="/t", rung=Rung("m"), env=None, release_ready=False): def test_puts_the_question_and_stops_off_a_terminal(self):
with contextlib.redirect_stderr(io.StringIO()) as said: for on_terminal, want in ((False, 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")), (True, None)):
asked = interrupt.interrupt(home, uuid7(), rung, path, "Which one?", release_ready, paths.paths_from(pathlib.Path(home)), env or {}, fake.effects()) with self.subTest(on_terminal=on_terminal):
self.said = said.getvalue() fake = FakeEffects(on_terminal=on_terminal)
return asked with contextlib.redirect_stderr(io.StringIO()) as said:
self.assertEqual(interrupt.put_question("Which one?", fake.effects()), want)
self.assertEqual(said.getvalue(), "\nWhich one?\n")
self.assertEqual(fake.calls, [])
def test_stops_off_a_terminal_before_asking(self): def test_reads_the_line_typed_at_the_terminal_stripped(self):
fake = FakeEffects(on_terminal=False) for typed, want in ((" Use B. ", "Use B."), (" /talk ", "/talk")):
self.assertEqual(self.ask(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")) with self.subTest(typed=typed):
self.assertEqual(fake.calls, []) fake = FakeEffects(inputs=[typed])
self.assertEqual(interrupt.read_answer(fake.effects()), want)
def test_returns_the_answer_typed_at_the_terminal_without_starting_claude(self): self.assertEqual(fake.made("input"), ["Answer (/talk opens claude, Enter stops the loop): "])
fake = FakeEffects(inputs=[" Use B. "])
self.assertEqual(self.ask(fake), "Use B.")
self.assertEqual(self.said, "\nWhich one?\n")
self.assertEqual(fake.made("input"), ["Answer (/talk opens claude, Enter stops the loop): "])
self.assertEqual(fake.made("claude_on_terminal"), [])
def test_stops_on_an_empty_answer_or_the_inputs_end(self): def test_stops_on_an_empty_answer_or_the_inputs_end(self):
for typed, why in ((" ", "nothing was typed"), (EOFError(), "the input ended")): for typed, why, said in ((" ", "nothing was typed", ""), (EOFError(), "the input ended", "\n")):
with self.subTest(why=why): with self.subTest(why=why), contextlib.redirect_stderr(io.StringIO()) as printed:
fake = FakeEffects(inputs=[typed]) self.assertEqual(interrupt.read_answer(FakeEffects(inputs=[typed]).effects()), Stop(2, f"the human is needed to answer the question above, but {why}"))
self.assertEqual(self.ask(fake), Stop(2, f"the human is needed to answer the question above, but {why}")) self.assertEqual(printed.getvalue(), said)
self.assertEqual(fake.made("claude_on_terminal"), [])
def test_opens_claudes_session_on_talk_and_at_once_for_a_release_ready_to_cut(self):
for typed, release_ready in ((["/talk"], False), ([" /talk "], False), ([], True)):
with self.subTest(typed=typed), tempfile.TemporaryDirectory() as home:
path = pathlib.Path(home, "t.jsonl")
path.write_text(json.dumps(human("a")) + "\n")
def answer(args):
with open(path, "a") as handle:
handle.write(json.dumps(human("B")) + "\n")
return 0
fake = FakeEffects(inputs=typed, on_terminal_claude=[answer], git=[ran()])
self.assertIsNone(self.ask(fake, home, str(path), Rung("m", "high"), release_ready=release_ready))
self.assertEqual(fake.made("claude_on_terminal")[0][:4], ["--model", "m", "--effort", "high"])
self.assertEqual(len(fake.made("input")), len(typed))
def test_stops_when_nothing_was_typed_in_the_session(self): def test_stops_when_nothing_was_typed_in_the_session(self):
with tempfile.TemporaryDirectory() as home: with tempfile.TemporaryDirectory() as home:
path = pathlib.Path(home, "t.jsonl") path = pathlib.Path(home, "t.jsonl")
path.write_text(json.dumps(human("a")) + "\n") path.write_text(json.dumps(human("a")) + "\n")
fake = FakeEffects(inputs=["/talk"], on_terminal_claude=[0], git=[ran()]) fake = FakeEffects(on_terminal_claude=[0], git=[ran()])
self.assertEqual(self.ask(fake, home, str(path)), Stop(2, "the human is needed to answer the question above, but the interrupt ended with nothing typed")) stop = interrupt.talk(home, 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"))
def test_hands_the_claude_that_takes_the_terminal_the_workers_environment(self): def test_hands_the_claude_that_takes_the_terminal_the_workers_environment(self):
with tempfile.TemporaryDirectory() as home: with tempfile.TemporaryDirectory() as home:
path = pathlib.Path(home, "t.jsonl") path = pathlib.Path(home, "t.jsonl")
path.write_text(json.dumps(human("a")) + "\n") path.write_text(json.dumps(human("a")) + "\n")
fake = FakeEffects(inputs=["/talk"], on_terminal_claude=[0], git=[ran()]) fake = FakeEffects(on_terminal_claude=[0], git=[ran()])
handed = {"LOOP_CLAUDE_PROJECT_RUNG": "claude-opus-5-5 at medium effort", "LOOP_CLAUDE_WORKER_RUNG": "claude-haiku-5-5 at max effort"} handed = {"LOOP_CLAUDE_PROJECT_RUNG": "claude-opus-5-5 at medium effort", "LOOP_CLAUDE_WORKER_RUNG": "claude-haiku-5-5 at max effort"}
self.ask(fake, home, str(path), Rung("claude-haiku-5-5", "max"), handed) interrupt.talk(home, uuid7(), Rung("claude-haiku-5-5", "max"), str(path), paths.paths_from(pathlib.Path(home)), handed, fake.effects())
self.assertEqual(fake.terminal_environments, [handed]) self.assertEqual(fake.terminal_environments, [handed])
@@ -976,12 +961,14 @@ class PythonEffect(unittest.TestCase):
class TypedAnswers(unittest.TestCase): class TypedAnswers(unittest.TestCase):
def test_finds_the_answer_in_the_prompt_that_hands_it_over_and_in_no_other_prompt(self): def test_finds_the_answer_on_the_line_after_the_marker_that_opens_the_prompt_handing_it_over_and_in_no_other_prompt(self):
route = Route(Rung("worker-model")) route = Route(Rung("worker-model"))
self.assertEqual(prompts.typed_answer(prompts.typed("Which one?\n\nThe human answers it at loop-claude's terminal:\n\nA?", "Use B.", route, None, False)), "Use B.") marked = "The human answered your question at loop-claude's terminal:\nB"
self.assertEqual(prompts.typed_answer(prompts.typed("Which one?", "Use B.", route, None, False)), "Use B.")
self.assertEqual(prompts.typed_answer(prompts.typed(f"Which one?\n{marked}", "Use B.", route, None, False)), "Use B.")
self.assertEqual(prompts.typed_answer(prompts.typed("Which one?", "Use B.", Route(Routing.SONNET, 179, 2, 5), Routing.OPUS, True)), "Use B.") self.assertEqual(prompts.typed_answer(prompts.typed("Which one?", "Use B.", Route(Routing.SONNET, 179, 2, 5), Routing.OPUS, True)), "Use B.")
self.assertIsNone(prompts.typed_answer(prompts.answered("Which one?", "Use B.", route, None, False))) self.assertIsNone(prompts.typed_answer(prompts.answered("Which one?", marked, route, None, False)))
self.assertIsNone(prompts.typed_answer(prompts.resumed("Your question: A\n\nThe human answers it at loop-claude's terminal:\n\nB", route, None))) self.assertIsNone(prompts.typed_answer(prompts.resumed(marked, route, None)))
class WorkerArgs(unittest.TestCase): class WorkerArgs(unittest.TestCase):