Answer an interrupt on loop-claude's terminal and resume the worker headless with the answer

This commit is contained in:
2026-10-17 23:04:28 +02:00
parent eddc5bec95
commit 831b9c63b6
17 changed files with 304 additions and 117 deletions
+20 -1
View File
@@ -11,12 +11,31 @@ from claude_code.trust import trust
from loop_claude.project.checkout import worktrees
ANSWER_QUESTION = "answer the question above"
# The word and the line were picked on 2026-10-17 by a bench of three readers seated as the README's audience, as ~/.claude/CLAUDE.md → "Working loop" → "Bench a syntax with the people who write it." has it.
TALK = "/talk"
ASK_ANSWER = f"Answer ({TALK} opens claude, Enter stops the loop): "
def interrupt(root: str, session_id: uuid.UUID, worker: Rung, path: str, question: str, paths: Paths, env: dict[str, str], effects: Effects) -> Stop | None:
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:
"""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."""
print(f"\n{question}", file=sys.stderr)
if stop := needs_terminal(ANSWER_QUESTION, effects.on_terminal()):
return stop
if not release_ready:
try:
answer = effects.input(ASK_ANSWER).strip()
except EOFError:
print(file=sys.stderr)
return needs_human(ANSWER_QUESTION, "the input ended")
if not answer:
return needs_human(ANSWER_QUESTION, "nothing was typed")
if answer != TALK:
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:
"""Resumes the worker's session in claude on the terminal; the human must type something there."""
entries = read_transcript(path)
if isinstance(entries, Failure):
return Stop(1, entries.reason)
+27 -16
View File
@@ -3,7 +3,7 @@ import json
import re
import typing
from loop_claude.cycle.prompts import ANSWER_DESTINATIONS, ANSWERS_RECORDED
from loop_claude.cycle.prompts import ANSWER_DESTINATIONS, ANSWERS_RECORDED, typed_answer
from claude_code.reply import claude_reply, Limited
from loop_claude.effects import Effects
from failure import Failure
@@ -11,6 +11,7 @@ from loop_claude.project.records import HUMAN_RULE_NAMES
from todo_table import LEVELS
from markdown_text import listed
from model_routing.route import on_its_scale
from claude_code.transcript import render
from loop_claude.cycle.retry import retried
from model_routing.ladder import Rung
from loop_claude.stop import Stop
@@ -18,7 +19,8 @@ from claude_code.entries import structured_output
# At 3 to 4 characters a token, 100,000 to 133,000 tokens, which leaves a 200,000-token context room for the reply; the largest session rendered here was 364,000 characters on 2026-10-03.
JUDGE_PROMPT_CHARS = 400000
JUDGE_RULES = (
# The rules close the judge's prompt, in three parts: when to interrupt and what to ask; when README.md or the records answer the agent in the human's place; and when the chunk is finished.
INTERRUPT_RULES = (
"Decide whether the human must now be interrupted. interrupt=true when any of these appear:\n"
"- the agent asks the human anything, seeks approval, or says a decision is the human's, and neither "
"README.md nor the records settle the matter\n"
@@ -37,11 +39,15 @@ JUDGE_RULES = (
"is still open, never a question they already answered there. A [loop] line is what loop-claude told "
"the agent, such as an answer quoted from README.md or the records.\n\n"
"Where the agent asked or flagged something itself, the question is that one, in the agent's own "
"wording; never construct another from facts it stated.\n\n"
"wording; never construct another from facts it stated."
)
QUOTE_RULES = (
"Where README.md or the records answer the agent's own question and no [loop] line has "
"quoted that answer yet, set interrupt=false and quote the passage that answers it; the agent is "
"then given that passage in place of the human's reply. An interrupt outranks a quoted answer, and either "
"outranks finished.\n\n"
"outranks finished."
)
FINISHED_RULES = (
"The chunk is the piece of work the agent is on, shipped as one pull request. "
"finished=true when the chunk is complete: merged, or nothing remains that the agent could do on "
f"its own. Even then, it is finished only once {ANSWERS_RECORDED}. An answer counts as recorded "
@@ -50,6 +56,7 @@ JUDGE_RULES = (
f"{listed(HUMAN_RULE_NAMES, 'or')} does not count. finished=false when work remains that a further run can "
"continue: an open PR, a review not yet run, CI not yet reported, an answer not yet recorded."
)
JUDGE_RULES = "\n\n".join((INTERRUPT_RULES, QUOTE_RULES, FINISHED_RULES))
@dataclasses.dataclass(frozen=True)
@@ -65,6 +72,8 @@ class Reply:
finished: bool = dataclasses.field(metadata={"description": "Whether the chunk is finished."})
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."})
# Opens claude's session for the human at once, in place of asking for a one-line answer: interrupt.interrupt.
release_ready: bool = dataclasses.field(metadata={"description": "Whether interrupt is true for a release ready to cut, which only the human may publish."})
REPLY_TYPES = typing.get_type_hints(Reply)
@@ -91,6 +100,7 @@ class Interrupt:
escalation: str = ""
# The bundled L the judge saw, 0 for none, as on Unfinished: an escalation steps up from the rung that item picks.
bundled: int = 0
release_ready: bool = False
@dataclasses.dataclass(frozen=True)
@@ -135,7 +145,7 @@ def verdict_from(output: object) -> Verdict | Failure:
if output["interrupt"]:
if not output["question"].strip():
return Failure("the judge interrupted without a question")
return Interrupt(output["evidence"], output["question"], output["escalation"], bundled)
return Interrupt(output["evidence"], output["question"], output["escalation"], bundled, output["release_ready"])
if output["answer"].strip():
if not output["question"].strip():
return Failure("the judge quoted an answer without a question")
@@ -146,13 +156,13 @@ def verdict_from(output: object) -> Verdict | Failure:
return Unfinished(output["evidence"], bundled, output["escalation"], bundled_escape_and_impact)
def judge(root: str, task: str, premises: str, records: str, rendered_transcript: str, rung: Rung, effects: Effects, keep: typing.Callable[[Rejected], Stop | None]) -> Verdict | Stop:
return retried("judge", lambda: judge_once(root, task, premises, records, rendered_transcript, rung, effects), effects, lambda failure: keep(failure) if isinstance(failure, Rejected) else None)
def judge(root: str, task: str, premises: str, records: str, entries: list[dict], rung: Rung, effects: Effects, keep: typing.Callable[[Rejected], Stop | None]) -> Verdict | Stop:
return retried("judge", lambda: judge_once(root, task, premises, records, entries, rung, effects), effects, lambda failure: keep(failure) if isinstance(failure, Rejected) else None)
def judge_once(root: str, task: str, premises: str, records: str, rendered_transcript: str, rung: Rung, effects: Effects) -> Verdict | Failure | Limited:
"""One judge run, as judge retries it; judge-replay replays it."""
prompt, shown = judge_prompt(task, premises, records, rendered_transcript)
def judge_once(root: str, task: str, premises: str, records: str, entries: list[dict], rung: Rung, effects: Effects) -> Verdict | Failure | Limited:
"""One judge run on the transcript's entries, as judge retries it; judge-replay replays it."""
prompt, shown = judge_prompt(task, premises, records, render(entries, typed_answer))
return run_judge(root, judge_args(rung), prompt, shown, f"{premises}\n\n{records}", effects)
@@ -167,7 +177,12 @@ def judge_args(rung: Rung) -> list[str]:
def run_judge(root: str, args: list[str], prompt: str, shown: str, quotable: str, effects: Effects) -> Verdict | Failure | Limited:
"""One judge run. Its evidence is checked against shown, its fragments in order: a misquote is a Failure, which judge retries."""
"""One judge run. Each quote in its verdict is checked word for word, since stitched fragments can say what their source does not:
- the evidence, against shown, the transcript as the judge saw it, fragment by fragment in order: a misquote is Rejected, which judge retries;
- a quoted answer, against quotable: a misquote puts the question to the human;
- an escalation, against shown: a misquote drops it, so the worker's rung holds.
quotes_checked checks the last two. Neither misquote is a Failure, which would otherwise exit an unattended loop.
"""
reply = claude_reply(effects.claude, args, root, prompt, "the judge")
if isinstance(reply, Failure | Limited):
return reply
@@ -181,11 +196,7 @@ def run_judge(root: str, args: list[str], prompt: str, shown: str, quotable: str
def quotes_checked(verdict: Verdict, shown: str, quotable: str) -> Verdict:
"""The verdict with its quotes checked word for word, since stitched fragments can say what the records or the transcript do not:
- a quoted answer, against quotable: a misquote puts the question to the human, with the escalation it carried;
- an escalation, on any ruling but a finished one, against shown: a misquote drops it, so the worker's rung holds.
A misquote is no Failure, which would otherwise exit an unattended loop.
"""
"""The verdict with its quoted answer and its escalation checked, as run_judge says; a quoted answer put to the human keeps the escalation it carried."""
if isinstance(verdict, QuotedAnswer) and not verbatim(verdict.answer, quotable):
verdict = Interrupt(verdict.evidence, verdict.question, verdict.escalation, verdict.bundled)
if isinstance(verdict, Interrupt | QuotedAnswer | Unfinished) and verdict.escalation and not verbatim(verdict.escalation, shown):
+22 -3
View File
@@ -124,9 +124,28 @@ def rungs_held(route: Route, anchor: Rung | None) -> str:
def answered(question: str, answer: str, route: Route, anchor: Rung | None, stepped: bool) -> str:
"""stepped is whether the answer's ruling stepped the worker up, so the prompt names its new rung, as resumed does."""
on = f" Your request for a higher rung went through: loop-claude runs you on {route.rung}.{rungs_held(route, anchor)} A further request for a higher rung steps you up no more in this cycle." if stepped else ""
return f"Your question: {question}\n\n{QUOTE_SOURCES} answers it:\n\n{answer}\n\nContinue the task.{on}"
"""stepped is whether the answer's ruling stepped the worker up."""
return f"Your question: {question}\n\n{QUOTE_SOURCES} answers it:\n\n{answer}\n\nContinue the task.{stepped_to(route, anchor, stepped)}"
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."""
return f"Your question: {question}\n\n{TYPED_HERE}\n\n{answer}\n\nContinue the task.{stepped_to(route, anchor, stepped)}"
# Precedes the answer in typed's prompt.
TYPED_HERE = "The human answers it at loop-claude's terminal:"
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."""
_, here, after = prompt.rpartition(f"\n\n{TYPED_HERE}\n\n")
return after.split("\n", 1)[0] if here and prompt.startswith("Your question: ") else None
def stepped_to(route: Route, anchor: Rung | None, stepped: bool) -> str:
"""Where the ruling that brought the answer stepped the worker up, names its new rung, as resumed does."""
return f" Your request for a higher rung went through: loop-claude runs you on {route.rung}.{rungs_held(route, anchor)} A further request for a higher rung steps you up no more in this cycle." if stepped else ""
def past_the_cap(question: str, answer: str, cap: int) -> str:
+16 -9
View File
@@ -2,7 +2,7 @@ import dataclasses
import pathlib
import typing
from loop_claude.cycle.states import Active, Archived, Closing, Ended, Event, HumanAnswered, Interrupting, Judging, QUOTED_ANSWERS_PER_CYCLE, Ruled, State, transition, WorkerRan, Working
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 transcript_archive.write import archive
from claude_code.session import delete_session, Session, session_open, transcript_file
from loop_claude.effects import Effects
@@ -13,7 +13,7 @@ from loop_claude.routing import judge_rung, stepped_by_ruling
from transcript_archive import outcomes
from loop_claude.paths import Paths
from loop_claude.cycle import prompts
from claude_code.transcript import read_transcript, render
from claude_code.transcript import read_transcript
from loop_claude.cycle.retry import retried
from model_routing.route import Route
from loop_claude.cycle.worker import run_worker, worker_args
@@ -41,7 +41,7 @@ class Cycle:
# Empty when the previous cycle's verdict was not Unfinished.
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.
# The route before that ruling stepped it up, for ask and keep_answer to archive; 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 ask to tell the worker; None unless the latest event stepped the route up.
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.
escalation_spent: bool = False
@@ -103,8 +103,8 @@ def step(cycle: Cycle, state: Active) -> Event | Stop:
typing.assert_never(state)
def work(cycle: Cycle, answered: QuotedAnswer | None) -> WorkerRan | Stop:
if answered is not None:
def work(cycle: Cycle, answered: QuotedAnswer | TypedAnswer | None) -> WorkerRan | Stop:
if isinstance(answered, QuotedAnswer):
print(f"\n=== {prompts.QUOTE_SOURCES} answered: {answered.question} ===\n{answered.answer}", flush=True)
if stop := keep_answer(cycle, answered):
return stop
@@ -120,9 +120,11 @@ def worker_environment(cycle: Cycle) -> dict[str, str]:
return worker_rungs.environment(cycle.anchor, cycle.route)
def worker_start(cycle: Cycle, answered: QuotedAnswer | None) -> list[str]:
if answered is not None:
def worker_start(cycle: Cycle, answered: QuotedAnswer | TypedAnswer | None) -> list[str]:
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)
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)
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.fresh(cycle.task, cycle.premises, cycle.route, cycle.anchor, cycle.facts), resume=False)
@@ -143,7 +145,7 @@ def rule(cycle: Cycle, transcript_path: str) -> Ruled | Stop:
entries = read_transcript(transcript_path)
if isinstance(entries, Failure):
return Stop(1, entries.reason)
verdict = judge(cycle.root, cycle.task, cycle.premises, cycle.records, render(entries), judge_of(cycle), cycle.effects, lambda rejected: keep_rejection(cycle, transcript_path, rejected))
verdict = judge(cycle.root, cycle.task, cycle.premises, cycle.records, entries, judge_of(cycle), cycle.effects, lambda rejected: keep_rejection(cycle, transcript_path, rejected))
return verdict if isinstance(verdict, Stop) else Ruled(unspent(verdict, cycle.escalation_spent))
@@ -168,7 +170,12 @@ def ask(cycle: Cycle, transcript_path: str, ruling: Interrupt | QuotedAnswer) ->
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):
return Stop(1, failure.reason)
return interrupt(cycle.root, cycle.session.id, cycle.route.rung, transcript_path, question, cycle.paths, worker_environment(cycle), cycle.effects) or HumanAnswered()
release_ready = isinstance(ruling, Interrupt) and ruling.release_ready
answer = interrupt(cycle.root, cycle.session.id, cycle.route.rung, transcript_path, question, release_ready, cycle.paths, worker_environment(cycle), cycle.effects)
if isinstance(answer, Stop):
return answer
# The step is told with the answer, since the worker resumes after the next event, which clears stepped_from.
return HumanAnswered(TypedAnswer(question, answer, cycle.stepped_from is not None) if answer is not None else None)
def archive_stepped(cycle: Cycle, transcript_path: str, outcome: str) -> Failure | None:
+16 -5
View File
@@ -6,10 +6,18 @@ from loop_claude.cycle.judge import Finished, Interrupt, QuotedAnswer, Unfinishe
QUOTED_ANSWERS_PER_CYCLE = 3
@dataclasses.dataclass(frozen=True)
class TypedAnswer:
"""The human's answer to an interrupt, typed at loop-claude's terminal; stepped is whether the interrupt stepped the worker up."""
question: str
answer: str
stepped: bool
@dataclasses.dataclass(frozen=True)
class Working:
"""The worker runs, resumed with an answer quoted from README.md or the records when there is one."""
answered: QuotedAnswer | None = None
"""The worker runs, resumed with an answer quoted from README.md or the records, or typed by the human, when there is one."""
answered: QuotedAnswer | TypedAnswer | None = None
quoted_answers: int = 0
@@ -55,7 +63,8 @@ class Ruled:
@dataclasses.dataclass(frozen=True)
class HumanAnswered:
pass
"""typed is None where the human answered in the interrupt's claude session."""
typed: TypedAnswer | None = None
@dataclasses.dataclass(frozen=True)
@@ -78,8 +87,10 @@ def transition(state: State, event: Event) -> State:
return Interrupting(transcript_path, ruling, quoted_answers)
case Judging(transcript_path, _), Ruled(Finished() | Unfinished() as verdict):
return Closing(transcript_path, verdict)
# The human works in the interrupt's claude session, so the judge rules again on the transcript it leaves.
case Interrupting(transcript_path, _, quoted_answers), HumanAnswered():
case Interrupting(_, _, quoted_answers), HumanAnswered(TypedAnswer() as typed):
return Working(typed, quoted_answers)
# 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):
return Judging(transcript_path, quoted_answers)
case Closing(_, verdict), Archived():
return Ended(verdict)