From 831b9c63b66adc1385f6c32d38c91fd80f5f8703 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sat, 17 Oct 2026 23:04:28 +0200 Subject: [PATCH 01/15] Answer an interrupt on loop-claude's terminal and resume the worker headless with the answer --- AGENTS.md | 2 +- CHANGELOG.md | 1 + bin/claude_code/test_claude_code.py | 7 +- bin/claude_code/transcript.py | 7 +- bin/judge_replay/main.py | 4 +- bin/judge_replay/test_judge_replay.py | 2 +- bin/loop_claude/cycle/interrupt.py | 21 ++- bin/loop_claude/cycle/judge.py | 43 +++--- bin/loop_claude/cycle/prompts.py | 25 +++- bin/loop_claude/cycle/run.py | 25 ++-- bin/loop_claude/cycle/states.py | 21 ++- bin/loop_claude/loop/main.py | 19 ++- bin/loop_claude/test_black_box.py | 42 ++++-- bin/loop_claude/test_loop_claude.py | 181 +++++++++++++++++++------- docs/decisions.md | 8 +- docs/reading-cost.md | 4 + todo.md | 9 +- 17 files changed, 304 insertions(+), 117 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index f0296173..e3c42093 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -5,7 +5,7 @@ Decisions live in `docs/decisions.md`: - larv-review: a project lifting itself to the comprehension floor starts at the lowest dimension - loop-claude: a judge decides each interrupt and each quoted answer from the transcript, the README's premises, `AGENTS.md`, `docs/decisions.md`, `~/.claude/CLAUDE.md`, `~/.claude/rules/` and larv-review's standards, and holds a chunk open while an answer the human typed in it is recorded nowhere; the worker's own account of which goal settles a choice decides nothing - loop-claude: one session per project, its id derived from the checkout's path relative to `~/code`, or to `/` outside it -- loop-claude: before an interrupt, it marks the checkout and each of its worktrees trusted in `~/.claude.json` +- loop-claude: before it opens claude on the terminal, it marks the checkout and each of its worktrees trusted in `~/.claude.json` - bin/: the tests rerun themselves on a `uv`-fetched Python at README Install's floor - bin/: the tools and their tests run on the host's Python, with no container - comprehension floor: every dimension and the overall at 7.0 or above is the target, and blocks no merge or release diff --git a/CHANGELOG.md b/CHANGELOG.md index f6100774..d9d008a9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## Unreleased +- `loop-claude` asks an interrupt's question on its own terminal and resumes the worker headless with your one-line answer, so the loop no longer waits for you to leave a claude session. Type `/talk` instead to open the worker's session in claude, as every interrupt did before, to read the diff or discuss first. A release ready to cut opens that session at once. Pressing Enter on an empty answer stops the loop, exit 2. The judge reads your answer as typed by you, so the chunk stays open until the worker records it. - When a worker's run ends with a question and a request for a higher rung, `loop-claude` now steps the worker one rung up as the judge interrupts, or as it answers the question with a quote from `README.md` or another file it may quote. The judge must quote a passage showing that the escalation trigger the run cites fired. Before, the step was lost for an answered question, and the worker carried on from the answer on its old rung. The step has the same limits as the step on an unfinished verdict, and no later ruling of that cycle carries a second escalation. The archive's interrupt and quoted-answer outcomes now name the worker's rung. - A scoring run due because a release's items ran out costs four more seats: it is done twice on one head. `larv-review agreement` compares how often Mid A and the inherited architect vote alike in paired rulings with how often their overall scores move the same way between the two runs. After 10 such pairs it gives a verdict, and on `Assumption fails:` larv-review asks you whether to keep the paired ruling. - `workflow-bench/bench.py` gives each run a fixed list of allowed tools. Before, it skipped every permission check. A run may launch agents, run `/security-review`, edit its clone (not the clone's `.git/` or `.claude/`) and its report, and read its clone and the copy of `~/.claude` it benches. For git it gets one command, `workflow-bench/review_git.py`, and no bare `git`. The wrapper runs `log`, `diff`, `show`, `status`, `ls-files`, `add` and `commit -m` on the run's clone, whatever the working directory. It allows only the options it lists for each, and refuses an argument that names a path outside the clone. git runs with no global or system config, hook, pager or editor. A run loads no settings or MCP servers from `~/.claude` or from the case's clone, so their hooks and extra directories do not apply to it. Every other call is denied. Expect a benched review that needs another git command, or to run a project's code or tests, to say in its report that it could not. diff --git a/bin/claude_code/test_claude_code.py b/bin/claude_code/test_claude_code.py index a07d331e..bd18d1e2 100644 --- a/bin/claude_code/test_claude_code.py +++ b/bin/claude_code/test_claude_code.py @@ -23,7 +23,7 @@ def queued(prompt, kind): class Render(unittest.TestCase): - def test_joins_assistant_text_tool_calls_human_turns_and_loop_prompts_and_skips_the_rest(self): + def test_joins_assistant_text_tool_calls_human_turns_and_loop_prompts_labelling_a_typed_answer_the_humans_and_skips_the_rest(self): said = transcript.render([ human("do it"), assistant({"type": "text", "text": "Starting."}, {"type": "tool_use", "name": "Bash", "input": {"command": "ls"}}), @@ -34,8 +34,9 @@ class Render(unittest.TestCase): queued("B, while you work", "human"), queued("origin/main moved", "coordinator"), {**human("Continue the task; the previous run stopped before it was finished."), "promptSource": "sdk"}, - ]) - self.assertEqual(said, '[human] do it\n\nStarting.\n\n[tool Bash] {"command": "ls"}\n\n[human] yes, merge it\n\n[human] B, while you work\n\n[loop] Continue the task; the previous run stopped before it was finished.') + {**human("Answered: use B"), "promptSource": "sdk"}, + ], lambda prompt: prompt.removeprefix("Answered: ") if prompt.startswith("Answered: ") else None) + self.assertEqual(said, '[human] do it\n\nStarting.\n\n[tool Bash] {"command": "ls"}\n\n[human] yes, merge it\n\n[human] B, while you work\n\n[loop] Continue the task; the previous run stopped before it was finished.\n\n[human] use B') class FirstTimestampedLine(unittest.TestCase): diff --git a/bin/claude_code/transcript.py b/bin/claude_code/transcript.py index 0991bf16..07ce9fde 100644 --- a/bin/claude_code/transcript.py +++ b/bin/claude_code/transcript.py @@ -1,4 +1,5 @@ import json +import typing from claude_code.entries import assistant_parts, human_text, loop_text, parse_entry, part_text, tool_call from failure import Failure @@ -24,14 +25,16 @@ def human_turns(entries: list[dict]) -> int: return sum(1 for entry in entries if human_text(entry) is not None) -def render(entries: list[dict]) -> str: +def render(entries: list[dict], typed_answer: typing.Callable[[str], str | None]) -> str: + """The transcript as the judge reads it. typed_answer finds an answer the human typed in a -p prompt of loop-claude's, which reads as the human's, like one typed in claude.""" lines = [] for entry in entries: lines += [line for part in assistant_parts(entry) if (line := part_line(part, JUDGED_TOOL_INPUT))] if (text := human_text(entry)) is not None: lines.append("[human] " + text) elif (text := loop_text(entry)) is not None: - lines.append("[loop] " + text) + typed = typed_answer(text) + lines.append("[loop] " + text if typed is None else "[human] " + typed) return "\n\n".join(lines) diff --git a/bin/judge_replay/main.py b/bin/judge_replay/main.py index 3c406497..7d7c021b 100644 --- a/bin/judge_replay/main.py +++ b/bin/judge_replay/main.py @@ -38,7 +38,7 @@ from loop_claude.cycle.judge import judge_once, Verdict from claude_code.reply import Limited from loop_claude.project.premises import read_premises from loop_claude.project.records import read_records -from claude_code.transcript import read_transcript, render +from claude_code.transcript import read_transcript from model_routing.ladder import Rung from loop_claude.stop import Stop @@ -91,5 +91,5 @@ def rule(case: Case, rung: Rung, claude_dir: pathlib.Path, effects: Effects) -> return verdict_kind(Failure(records.reason)) if isinstance(entries, Failure): return verdict_kind(entries) - verdict: Verdict | Failure | Limited = first_reply(lambda: judge_once(case.root, case.task, premises, records, render(entries), rung, effects)) + verdict: Verdict | Failure | Limited = first_reply(lambda: judge_once(case.root, case.task, premises, records, entries, rung, effects)) return verdict if isinstance(verdict, Limited) else verdict_kind(verdict) diff --git a/bin/judge_replay/test_judge_replay.py b/bin/judge_replay/test_judge_replay.py index faf513b1..a30aa1a5 100644 --- a/bin/judge_replay/test_judge_replay.py +++ b/bin/judge_replay/test_judge_replay.py @@ -122,7 +122,7 @@ class Main(unittest.TestCase): @staticmethod def verdict(interrupt, evidence): - output = {"answer": "", "bundled": 0, "bundled_escape_and_impact": 0, "escalation": "", "evidence": evidence, "finished": not interrupt, "interrupt": interrupt, "question": "Which?" if interrupt else ""} + output = {"answer": "", "bundled": 0, "bundled_escape_and_impact": 0, "escalation": "", "evidence": evidence, "finished": not interrupt, "interrupt": interrupt, "question": "Which?" if interrupt else "", "release_ready": False} return {"type": "result", "structured_output": output} def test_replays_the_models_projects_on_the_reference_then_from_the_projects_rung_down_and_prints_the_lowest_that_returns_all(self): diff --git a/bin/loop_claude/cycle/interrupt.py b/bin/loop_claude/cycle/interrupt.py index 9408f0fc..8e7adeb9 100644 --- a/bin/loop_claude/cycle/interrupt.py +++ b/bin/loop_claude/cycle/interrupt.py @@ -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) diff --git a/bin/loop_claude/cycle/judge.py b/bin/loop_claude/cycle/judge.py index 0bc893d6..8564176f 100644 --- a/bin/loop_claude/cycle/judge.py +++ b/bin/loop_claude/cycle/judge.py @@ -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): diff --git a/bin/loop_claude/cycle/prompts.py b/bin/loop_claude/cycle/prompts.py index 7f144d5a..ee34cfd4 100644 --- a/bin/loop_claude/cycle/prompts.py +++ b/bin/loop_claude/cycle/prompts.py @@ -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: diff --git a/bin/loop_claude/cycle/run.py b/bin/loop_claude/cycle/run.py index 9ac9d7dc..5e5b6045 100644 --- a/bin/loop_claude/cycle/run.py +++ b/bin/loop_claude/cycle/run.py @@ -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: diff --git a/bin/loop_claude/cycle/states.py b/bin/loop_claude/cycle/states.py index b4a68b5a..2636f322 100644 --- a/bin/loop_claude/cycle/states.py +++ b/bin/loop_claude/cycle/states.py @@ -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) diff --git a/bin/loop_claude/loop/main.py b/bin/loop_claude/loop/main.py index 6f3d1757..ccf921dc 100644 --- a/bin/loop_claude/loop/main.py +++ b/bin/loop_claude/loop/main.py @@ -16,13 +16,19 @@ worker made that the premises or the records settle is not asked about. When the question they answer, the judge quotes the answer, loop-claude prints it, and the worker resumes with it. A quote they do not hold word for word is dropped, and the question goes to the human. So does a question asked again after its answer. The fourth question they answer in one cycle goes to -the human too, with the quote. -A question only the human can answer, or a release ready to cut, is an interrupt: `claude --resume` -on the terminal, every worktree first marked trusted in ~/.claude.json. An unfinished chunk resumes -its session next cycle, and the worker is shown the passage the judge quoted as the work remaining. -The next chunk starts a fresh session. +the human too, with the quote. An unfinished chunk resumes its session next cycle, and the worker +is shown the passage the judge quoted as the work remaining. The next chunk starts a fresh session. Cycles continue until an exit below or Ctrl-C. Words: ~/.claude/CLAUDE.md → "Vocabulary". +A question only the human can answer is an interrupt (bin/loop_claude/cycle/interrupt.py). +loop-claude prints the question and reads a one-line answer on its terminal. The worker resumes +headless with the answer. The judge reads it as the human's, so the chunk stays unfinished until the +answer is recorded. An empty answer stops the loop. Typing /talk instead opens the worker's session +on the terminal with `claude --resume`, to read the diff or discuss first; once that claude exits, +the judge rules on what was typed there. A release ready to cut opens that session at once, since +only the human may cut it. Before claude opens, the checkout and each of its worktrees are marked +trusted in ~/.claude.json. + As a chunk starts, before it is routed, loop-claude runs bin/chunk-preflight (bin/chunk_preflight/), which finds the chunk's facts and makes its worktree; chunk-preflight --help lists them, and prompts.preflight_facts in bin/loop_claude/cycle/prompts.py quotes them in the first prompt. A @@ -147,7 +153,8 @@ Exit 1, saying why, when: Exit 2, when the human is needed and cannot answer: - stdin or stdout is not a terminal, when a model must be picked or an interrupt answered - the input ends while a model is picked -- an interrupt ends with nothing typed +- an interrupt's answer is empty or the input ends, or the claude that /talk opened ends with + nothing typed Rerunning resumes any open session. """ diff --git a/bin/loop_claude/test_black_box.py b/bin/loop_claude/test_black_box.py index d5702a90..70a1972e 100644 --- a/bin/loop_claude/test_black_box.py +++ b/bin/loop_claude/test_black_box.py @@ -125,8 +125,8 @@ def worker(**step): return {"role": "worker", **step} -def judge(interrupt=False, finished=False, evidence="working", question="", bundled=0, bundled_escape_and_impact=0, escalation="", **step): - verdict = {"answer": "", "bundled": bundled, "bundled_escape_and_impact": bundled_escape_and_impact, "escalation": escalation, "evidence": evidence, "finished": finished, "interrupt": interrupt, "question": question} +def judge(interrupt=False, finished=False, evidence="working", question="", bundled=0, bundled_escape_and_impact=0, escalation="", release_ready=False, **step): + verdict = {"answer": "", "bundled": bundled, "bundled_escape_and_impact": bundled_escape_and_impact, "escalation": escalation, "evidence": evidence, "finished": finished, "interrupt": interrupt, "question": question, "release_ready": release_ready} return {"role": "judge", "verdict": verdict, **step} @@ -467,7 +467,7 @@ class Cycles(unittest.TestCase): worker(say=f"{cited} Trigger 3 fired; I ask for a higher rung. Shall I use A or B?"), judge(interrupt=True, evidence="Shall I use A or B?", question="A or B?", escalation=cited), interrupt(type="B"), judge(evidence="B", escalation="Trigger 3 fired; I ask for a higher rung."), worker(say="carrying on"), - ], terminal_input="") + ], terminal_input="/talk\n") self.assertEqual(run.code, 130) self.assertEqual(run.roles(), ["worker", "judge", "interrupt", "judge", "worker", "judge"]) self.assertEqual([(argument(call, "--model"), argument(call, "--effort")) for call in run.calls if call["role"] != "judge"], [("claude-opus-5-5", "high"), ("claude-opus-5-5", "xhigh"), ("claude-opus-5-5", "xhigh")]) @@ -655,6 +655,24 @@ class Interrupt(unittest.TestCase): self.assertEqual(run.code, 2) self.assertEqual(len(checkout.archived()), 2) + def test_resumes_the_worker_headless_with_the_answer_typed_at_its_terminal_and_has_the_judge_read_it_as_the_humans(self): + checkout = Checkout(self) + asked = [worker(say="Shall I use A or B?"), judge(interrupt=True, evidence="Shall I use A or B?", question="A or B?")] + run = checkout.run([*asked, worker(say="Using B."), judge(evidence="Using B.")], terminal_input="B\n") + self.assertEqual(run.code, 130) + self.assertEqual(run.roles(), ["worker", "judge", "worker", "judge", "worker"]) + self.assertIn("A or B?\nAnswer (/talk opens claude, Enter stops the loop): ", run.stderr) + resumed = run.calls[2]["argv"] + 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.assertIn("[human] B\n\nUsing B.", run.calls[3]["stdin"]) + + for transcript in checkout.transcripts(): + transcript.unlink() + run = checkout.run(asked, terminal_input="\n") + self.assertEqual((run.code, run.roles()), (2, ["worker", "judge"])) + self.assertTrue(run.stderr.strip().endswith("Answer (/talk opens claude, Enter stops the loop): the human is needed to answer the question above, but nothing was typed")) + def test_hands_the_terminal_over_and_exits_2_when_nothing_is_typed(self): checkout = Checkout(self) checkout.git("commit", "--allow-empty", "--quiet", "-m", "start") @@ -663,7 +681,7 @@ class Interrupt(unittest.TestCase): checkout.claude_json().chmod(0o644) asked = [worker(say="Shall I use A or B?"), judge(interrupt=True, evidence="Shall I use A or B?", question="A or B?")] (checkout.root / "sub").mkdir() - run = checkout.run([*asked, interrupt(type="B"), judge(evidence="B"), worker()], cwd=checkout.root / "sub", terminal_input="") + run = checkout.run([*asked, interrupt(type="B"), judge(evidence="B"), worker()], cwd=checkout.root / "sub", terminal_input="/talk\n") self.assertEqual(run.code, 130) self.assertEqual(run.roles(), ["worker", "judge", "interrupt", "judge", "worker", "judge"]) handed = run.calls[2]["argv"] @@ -681,13 +699,13 @@ class Interrupt(unittest.TestCase): for transcript in checkout.transcripts(): transcript.unlink() - run = checkout.run([*asked, interrupt()], terminal_input="") + run = checkout.run([*asked, interrupt()], terminal_input="/talk\n") self.assertEqual((run.code, run.roles()), (2, ["worker", "judge", "interrupt"])) - self.assertEqual(run.stderr.strip().splitlines()[-1], "the human is needed to answer the question above, but the interrupt ended with nothing typed") + self.assertTrue(run.stderr.strip().endswith("the human is needed to answer the question above, but the interrupt ended with nothing typed")) - run = checkout.run([worker(say="A or B?"), judge(interrupt=True, evidence="A or B?", question="A or B?", vanish=True)], terminal_input="") + run = checkout.run([worker(say="A or B?"), judge(interrupt=True, evidence="A or B?", question="A or B?", vanish=True)], terminal_input="/talk\n") self.assertEqual((run.code, run.roles()), (1, ["worker", "judge"])) - self.assertEqual(run.stderr.strip().splitlines()[-1], "could not start claude for the interrupt: No such file or directory") + self.assertTrue(run.stderr.strip().endswith("could not start claude for the interrupt: No such file or directory")) def test_says_why_the_trust_file_cannot_be_read_and_leaves_it_as_it_was(self): checkout = Checkout(self) @@ -705,14 +723,14 @@ class Interrupt(unittest.TestCase): checkout.claude_json().unlink(missing_ok=True) if text is not None: checkout.claude_json().write_text(text) - run = checkout.run(asked, terminal_input="") + run = checkout.run(asked, terminal_input="/talk\n") self.assertEqual(run.code, 2) self.assertIn(f"could not read {checkout.claude_json()}: {said}\n", run.stderr) self.assertEqual(checkout.claude_json().read_text() if checkout.claude_json().exists() else None, text) trusted = json.dumps({"projects": {str(checkout.root): {"hasTrustDialogAccepted": True}}}) checkout.claude_json().write_text(trusted) - run = checkout.run(asked, terminal_input="") + run = checkout.run(asked, terminal_input="/talk\n") self.assertNotIn(str(checkout.claude_json()), run.stderr) self.assertNotIn("trusted for the interrupt", run.stderr) self.assertEqual(checkout.claude_json().read_text(), trusted) @@ -725,7 +743,7 @@ class Interrupt(unittest.TestCase): checkout.run(asked[:2]) checkout.home.chmod(0o500) self.addCleanup(checkout.home.chmod, 0o700) - run = checkout.run([worker(), *asked[1:]], terminal_input="") + run = checkout.run([worker(), *asked[1:]], terminal_input="/talk\n") self.assertEqual(run.code, 2) self.assertIn(f"could not write {checkout.claude_json()}: Permission denied\n", run.stderr) self.assertEqual(checkout.claude_json().read_text(), "{}") @@ -733,7 +751,7 @@ class Interrupt(unittest.TestCase): @unittest.skipIf(os.geteuid() == 0, "root reads an unreadable file") def test_exits_1_when_the_transcript_cannot_be_read_after_the_interrupt(self): checkout = Checkout(self) - run = checkout.run([worker(say="A or B?"), judge(interrupt=True, evidence="A or B?", question="A or B?"), interrupt(type="B", unreadable=True)], terminal_input="") + run = checkout.run([worker(say="A or B?"), judge(interrupt=True, evidence="A or B?", question="A or B?"), interrupt(type="B", unreadable=True)], terminal_input="/talk\n") self.assertEqual((run.code, run.roles()), (1, ["worker", "judge", "interrupt"])) self.assertRegex(run.stderr.strip().splitlines()[-1], r"^could not tell whether you typed anything: could not read the transcript .*\.jsonl: Permission denied$") diff --git a/bin/loop_claude/test_loop_claude.py b/bin/loop_claude/test_loop_claude.py index ae2dc662..e01ddfe4 100644 --- a/bin/loop_claude/test_loop_claude.py +++ b/bin/loop_claude/test_loop_claude.py @@ -105,16 +105,18 @@ def ran(stdout="", code=0, stderr=""): return subprocess.CompletedProcess([], code, stdout, stderr) -def judged(verdict, evidence="working", answer="", escalation=""): - reply = {"answer": answer, "bundled": 0, "bundled_escape_and_impact": 0, "escalation": escalation, "evidence": evidence, "finished": verdict == "finished", "interrupt": verdict == "interrupt", "question": "Which one?" if verdict in ("interrupt", "quoted") else ""} +def judged(verdict, evidence="working", answer="", escalation="", release_ready=False): + reply = {"answer": answer, "bundled": 0, "bundled_escape_and_impact": 0, "escalation": escalation, "evidence": evidence, "finished": verdict == "finished", "interrupt": verdict == "interrupt", "question": "Which one?" if verdict in ("interrupt", "quoted") else "", "release_ready": release_ready} return ran(json.dumps({"structured_output": reply})) class Worker: """A worker claude: writes a line to the session's transcript, then streams a result.""" - def __init__(self, home): + def __init__(self, home, prompted=False): self.home = home + # Whether it records its -p prompt in the transcript first, as claude does. + self.prompted = prompted def __call__(self, args): flag = "--session-id" if "--session-id" in args else "--resume" @@ -123,6 +125,8 @@ class Worker: with open(path, "a") as handle: if flag == "--session-id": handle.write(json.dumps({"type": "custom-title"}) + "\n" + json.dumps({"type": "queue-operation", "timestamp": str(uuid7())}) + "\n") + if self.prompted: + handle.write(json.dumps({**human(args[args.index("-p") + 1]), "promptSource": "sdk"}) + "\n") handle.write(json.dumps(assistant({"type": "text", "text": "working"})) + "\n") return Streamed(0) @@ -139,6 +143,9 @@ class Streamed: return self.code +TYPED = states.TypedAnswer("Which one?", "Use B.", False) + + class Transitions(unittest.TestCase): def test_each_state_moves_on_its_events_and_only_on_them(self): answered = states.Ruled(QuotedAnswer("e", "Which one?", "A.")) @@ -156,14 +163,17 @@ class Transitions(unittest.TestCase): (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"), 3), states.HumanAnswered(), states.Judging("/t", 3)), + (states.Interrupting("/t", Interrupt("e", "q")), states.HumanAnswered(TYPED), states.Working(TYPED)), + (states.Interrupting("/t", Interrupt("e", "q"), 3), states.HumanAnswered(TYPED), states.Working(TYPED, 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", Unfinished("e")), states.Archived(), states.Ended(Unfinished("e"))), ) 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.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.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.HumanAnswered(), states.HumanAnswered(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]: @@ -218,9 +228,10 @@ class Cycles(unittest.TestCase): with open(session.transcript_file(self.session), "a") as handle: handle.write(json.dumps(human("the second")) + "\n") return 0 - fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("interrupt"), judged("finished")], on_terminal_claude=[answer], git=[ran()]) + fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("interrupt"), judged("finished")], inputs=["/talk"], on_terminal_claude=[answer], git=[ran()]) cycle = dataclasses.replace(self.cycle(fake), anchor=Rung("claude-opus-5-5", "medium"), route=Route(Rung("claude-haiku-5-5", "max"), 163, 1, 5)) - self.assertEqual(run.run_cycle(cycle).verdict, Finished("working")) + with contextlib.redirect_stderr(io.StringIO()): + self.assertEqual(run.run_cycle(cycle).verdict, Finished("working")) self.assertEqual(fake.terminal_environments, fake.worker_environments) self.assertEqual(fake.terminal_environments[0]["LOOP_CLAUDE_WORKER_RUNG"], "claude-haiku-5-5 at max effort") @@ -308,13 +319,14 @@ class Cycles(unittest.TestCase): fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("unfinished")]) self.assertEqual(run.run_cycle(self.cycle(fake)), Stop(1, f"could not archive the transcript: {locked}: Permission denied")) - def test_an_interrupt_is_archived_answered_and_judged_again(self): + def test_an_interrupt_talked_over_in_claude_is_archived_answered_and_judged_again(self): def answer(args): with open(session.transcript_file(self.session), "a") as handle: handle.write(json.dumps(human("the second")) + "\n") return 0 - fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("interrupt"), judged("unfinished")], on_terminal_claude=[answer], git=[ran()]) - self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Unfinished("working")) + fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("interrupt"), judged("unfinished")], inputs=["/talk"], on_terminal_claude=[answer], git=[ran()]) + with contextlib.redirect_stderr(io.StringIO()): + self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Unfinished("working")) self.assertEqual(self.archived_outcomes(), ["Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: interrupt\n\nWhich one?\n\nEvidence:\n> working\n\nJudge: judge-model\nWorker: worker-model\n", "Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: unfinished\n\nEvidence:\n> working\n\nJudge: judge-model\nWorker: worker-model\n"]) self.assertIn(str(self.session.id), fake.made("claude_on_terminal")[0]) judge_prompts = [stdin for args, stdin in fake.made("claude")] @@ -326,16 +338,16 @@ class Cycles(unittest.TestCase): def test_a_question_the_records_answer_resumes_the_worker_with_the_answer_three_times_a_cycle(self): answered = judged("quoted", answer="Use *A*.") - fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 4, claude=[answered] * 4, on_terminal_claude=[0], git=[ran()]) + fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 4, claude=[answered] * 4, inputs=[""]) with contextlib.redirect_stderr(io.StringIO()) as said, contextlib.redirect_stdout(io.StringIO()) as printed: - self.assertEqual(run.run_cycle(self.cycle(fake, records="From AGENTS.md:\nUse A.")), Stop(2, "the human is needed to answer the question above, but the interrupt ended with nothing typed")) + self.assertEqual(run.run_cycle(self.cycle(fake, records="From AGENTS.md:\nUse A.")), Stop(2, "the human is needed to answer the question above, but nothing was typed")) resumed = fake.made("stream_claude")[1] self.assertEqual(resumed[resumed.index("-p") + 1], "Your question: Which one?\n\nREADME.md's Goals and Audience, AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/ or ~/.claude/skills/larv-review/standards/ answers it:\n\nUse *A*.\n\nContinue the task.") self.assertEqual(len(fake.made("stream_claude")), 4) self.assertEqual(printed.getvalue().count("=== README.md's Goals and Audience, AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/ or ~/.claude/skills/larv-review/standards/ answered: Which one? ===\nUse *A*."), 3) self.assertIn("Which one?\n\nREADME.md's Goals and Audience, AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/ or ~/.claude/skills/larv-review/standards/ says:\nUse *A*.\n\nThose files have answered 3 questions this cycle", said.getvalue()) quoted = "2026-09-21T14:13:20Z Verdict: quoted answer\n\nWhich one?\n\nREADME.md's Goals and Audience, AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/ or ~/.claude/skills/larv-review/standards/ says:\n> Use *A*.\n\nEvidence:\n> working\n\nJudge: judge-model\nWorker: worker-model\n" - self.assertEqual(self.archived_outcomes(), [f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: interrupt\n\nWhich one?\n\nREADME.md's Goals and Audience, AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/ or ~/.claude/skills/larv-review/standards/ says:\nUse *A*.\n\nThose files have answered 3 questions this cycle, the most allowed, so this one comes to you.\n\nEvidence:\n> working\n\nJudge: judge-model\nWorker: worker-model\n\n2026-09-21T14:13:20Z Stopped: the human is needed to answer the question above, but the interrupt ended with nothing typed\n\nWorker: worker-model\n", *[f"Task: Do it.\n\n{quoted}"] * 3]) + self.assertEqual(self.archived_outcomes(), [f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: interrupt\n\nWhich one?\n\nREADME.md's Goals and Audience, AGENTS.md, docs/decisions.md, ~/.claude/CLAUDE.md, ~/.claude/rules/ or ~/.claude/skills/larv-review/standards/ says:\nUse *A*.\n\nThose files have answered 3 questions this cycle, the most allowed, so this one comes to you.\n\nEvidence:\n> working\n\nJudge: judge-model\nWorker: worker-model\n\n2026-09-21T14:13:20Z Stopped: the human is needed to answer the question above, but nothing was typed\n\nWorker: worker-model\n", *[f"Task: Do it.\n\n{quoted}"] * 3]) def test_a_quoted_answer_that_cites_an_escalation_trigger_steps_the_worker_up_before_it_resumes_and_archives_the_step(self): fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 2, claude=[judged("quoted", answer="Use A.", escalation="working"), judged("finished")]) @@ -355,21 +367,56 @@ class Cycles(unittest.TestCase): def test_a_quoted_answer_past_the_cap_archives_the_escalation_it_carried_with_the_interrupt_and_steps_up(self): steps = [judged("quoted", answer="Use A.")] * 3 + [judged("quoted", answer="Use A.", escalation="working")] - fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 4, claude=steps, on_terminal_claude=[0], git=[ran()]) + fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 4, claude=steps, inputs=[""]) cycle = dataclasses.replace(self.cycle(fake, records="From AGENTS.md:\nUse A."), anchor=Routing.OPUS, route=Route(Routing.SONNET, 179, 2, 5)) with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()): - self.assertEqual(run.run_cycle(cycle), Stop(2, "the human is needed to answer the question above, but the interrupt ended with nothing typed")) + self.assertEqual(run.run_cycle(cycle), Stop(2, "the human is needed to answer the question above, but nothing was typed")) kept = "".join(self.archived_outcomes()) self.assertIn(f"Evidence:\n> working\n\nEscalation:\n> working\n\nJudge: judge-model\nWorker: {Route(Routing.SONNET, 179, 2, 5)}\n", kept) self.assertIn(f"Stepped up\n\nWorker: {Route(Routing.OPUS, 179, 2, 5)}\n", kept) + def test_an_answer_typed_at_the_terminal_resumes_the_worker_headless_and_the_judge_reads_it_as_the_humans(self): + worker = Worker(self.paths.claude_code_transcripts.parent, prompted=True) + fake = FakeEffects(streams=[worker, worker], claude=[judged("interrupt"), judged("unfinished")], inputs=["Use B."]) + with contextlib.redirect_stderr(io.StringIO()) as said: + self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Unfinished("working")) + self.assertIn("\nWhich one?\n", said.getvalue()) + self.assertEqual(fake.made("claude_on_terminal"), []) + resumed = fake.made("stream_claude")[1] + 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.") + 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.assertNotIn("[loop] Your question", 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): + fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 2, claude=[judged("interrupt", escalation="working"), judged("finished")], inputs=["Use B."]) + cycle = dataclasses.replace(self.cycle(fake), anchor=Routing.OPUS, route=Route(Routing.SONNET, 179, 2, 5)) + with contextlib.redirect_stderr(io.StringIO()): + concluded = run.run_cycle(cycle) + self.assertEqual(concluded.route, Route(Routing.OPUS, 179, 2, 5)) + first, resumed = fake.made("stream_claude") + 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.")) + + def test_a_release_ready_to_cut_opens_claudes_session_without_asking_for_an_answer(self): + def answer(args): + with open(session.transcript_file(self.session), "a") as handle: + handle.write(json.dumps(human("cut")) + "\n") + return 0 + fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("interrupt", release_ready=True), judged("finished")], on_terminal_claude=[answer], git=[ran()]) + with contextlib.redirect_stderr(io.StringIO()): + self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Finished("working")) + self.assertEqual(fake.made("input"), []) + self.assertEqual(len(fake.made("claude_on_terminal")), 1) + def test_stops_when_an_interrupt_cannot_be_archived(self): self.archive.parent.mkdir(parents=True) self.archive.write_text("") - fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("interrupt")], on_terminal_claude=[0]) + fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("interrupt")], inputs=["Use B."]) stop = run.run_cycle(self.cycle(fake)) self.assertRegex(stop.reason, f"^could not archive the transcript: {self.archive}/[0-9a-f]{{64}}: Not a directory$") - self.assertEqual(fake.made("claude_on_terminal"), []) + self.assertEqual(fake.made("input"), []) def test_stops_when_a_quoted_answer_cannot_be_archived(self): self.archive.parent.mkdir(parents=True) @@ -381,9 +428,9 @@ class Cycles(unittest.TestCase): self.assertEqual(len(fake.made("stream_claude")), 1) def test_an_answer_the_records_do_not_hold_is_dropped_and_the_question_goes_to_the_human(self): - fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("quoted", answer="Use ... A.")], on_terminal_claude=[0], git=[ran()]) + fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("quoted", answer="Use ... A.")], inputs=[""]) with contextlib.redirect_stderr(io.StringIO()) as said: - self.assertEqual(run.run_cycle(self.cycle(fake, records="From AGENTS.md:\nUse B. Use A.")), Stop(2, "the human is needed to answer the question above, but the interrupt ended with nothing typed")) + self.assertEqual(run.run_cycle(self.cycle(fake, records="From AGENTS.md:\nUse B. Use A.")), Stop(2, "the human is needed to answer the question above, but nothing was typed")) self.assertEqual(len(fake.made("stream_claude")), 1) self.assertIn("\nWhich one?\n", said.getvalue()) self.assertNotIn("Use ... A.", said.getvalue()) @@ -466,28 +513,59 @@ class Limits(unittest.TestCase): class Interrupts(unittest.TestCase): - def test_stops_off_a_terminal_before_starting_claude(self): + def ask(self, fake, home="/h", path="/t", rung=Rung("m"), env=None, release_ready=False): + with contextlib.redirect_stderr(io.StringIO()) as said: + asked = interrupt.interrupt(home, uuid7(), rung, path, "Which one?", release_ready, paths.paths_from(pathlib.Path(home)), env or {}, fake.effects()) + self.said = said.getvalue() + return asked + + def test_stops_off_a_terminal_before_asking(self): fake = FakeEffects(on_terminal=False) - stop = interrupt.interrupt("/r", uuid7(), Rung("m"), "/t", "Which one?", paths.paths_from(pathlib.Path("/h")), {}, fake.effects()) - self.assertEqual(stop, 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")) + 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")) self.assertEqual(fake.calls, []) - def test_stops_when_nothing_was_typed_in_the_handover(self): + def test_returns_the_answer_typed_at_the_terminal_without_starting_claude(self): + 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): + for typed, why in ((" ", "nothing was typed"), (EOFError(), "the input ended")): + with self.subTest(why=why): + fake = FakeEffects(inputs=[typed]) + self.assertEqual(self.ask(fake), Stop(2, f"the human is needed to answer the question above, but {why}")) + 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): with tempfile.TemporaryDirectory() as home: path = pathlib.Path(home, "t.jsonl") path.write_text(json.dumps(human("a")) + "\n") - fake = FakeEffects(on_terminal_claude=[0], git=[ran()]) - stop = interrupt.interrupt(home, uuid7(), Rung("m", "high"), str(path), "Which one?", paths.paths_from(pathlib.Path(home)), {}, fake.effects()) - self.assertEqual(fake.made("claude_on_terminal")[0][:4], ["--model", "m", "--effort", "high"]) - self.assertEqual(stop, Stop(2, "the human is needed to answer the question above, but the interrupt ended with nothing typed")) + fake = FakeEffects(inputs=["/talk"], 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")) def test_hands_the_claude_that_takes_the_terminal_the_workers_environment(self): with tempfile.TemporaryDirectory() as home: path = pathlib.Path(home, "t.jsonl") path.write_text(json.dumps(human("a")) + "\n") - fake = FakeEffects(on_terminal_claude=[0], git=[ran()]) + fake = FakeEffects(inputs=["/talk"], 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"} - interrupt.interrupt(home, uuid7(), Rung("claude-haiku-5-5", "max"), str(path), "Which one?", paths.paths_from(pathlib.Path(home)), handed, fake.effects()) + self.ask(fake, home, str(path), Rung("claude-haiku-5-5", "max"), handed) self.assertEqual(fake.terminal_environments, [handed]) @@ -897,6 +975,15 @@ class PythonEffect(unittest.TestCase): self.assertIn(gone, done.stderr) +class TypedAnswers(unittest.TestCase): + def test_finds_the_answer_in_the_prompt_that_hands_it_over_and_in_no_other_prompt(self): + 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.") + 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.resumed("Your question: A\n\nThe human answers it at loop-claude's terminal:\n\nB", route, None))) + + class WorkerArgs(unittest.TestCase): SCAN = " Run a full scan only from such a subagent, since the scan's agents run on the model that starts them." SEATS = " Launch each comprehension seat and the security pass's subagent with the Agent tool set to model opus, effort medium, the project's rung." @@ -1084,19 +1171,21 @@ class Grounded(unittest.TestCase): class Verdict(unittest.TestCase): def test_needs_every_field_the_schema_requires(self): - self.assertEqual(verdict_from({"bundled": 0, "bundled_escape_and_impact": 0, "escalation": "", "answer": "", "interrupt": False, "evidence": "e", "finished": True, "question": ""}), Finished("e")) - self.assertEqual(verdict_from({"bundled": 0, "bundled_escape_and_impact": 0, "escalation": "", "answer": "", "interrupt": False, "evidence": "e", "finished": False, "question": "ignored"}), Unfinished("e")) - self.assertEqual(verdict_from({"bundled": 0, "bundled_escape_and_impact": 0, "escalation": "", "answer": "", "interrupt": True, "evidence": "e", "finished": True, "question": "Which one?"}), Interrupt("e", "Which one?")) - self.assertEqual(verdict_from({"bundled": 0, "bundled_escape_and_impact": 0, "escalation": "", "answer": "A.", "interrupt": False, "evidence": "e", "finished": False, "question": "Which one?"}), QuotedAnswer("e", "Which one?", "A.")) - self.assertEqual(verdict_from({"bundled": 0, "bundled_escape_and_impact": 0, "escalation": "", "answer": "A.", "interrupt": True, "evidence": "e", "finished": False, "question": "Which one?"}), Interrupt("e", "Which one?")) - self.assertEqual(verdict_from({"bundled": 0, "bundled_escape_and_impact": 0, "escalation": "", "answer": "A.", "interrupt": False, "evidence": "e", "finished": True, "question": ""}), Failure("the judge quoted an answer without a question")) - self.assertEqual(verdict_from({"bundled": 0, "bundled_escape_and_impact": 0, "escalation": "", "answer": "", "interrupt": "no", "evidence": "", "finished": True, "question": ""}), Failure("the judge's reply has no interrupt of type boolean")) - self.assertEqual(verdict_from({"bundled": 0, "bundled_escape_and_impact": 0, "escalation": "", "answer": "", "interrupt": False, "evidence": None, "finished": True, "question": ""}), Failure("the judge's reply has no evidence of type string")) - self.assertEqual(verdict_from({"bundled": 0, "bundled_escape_and_impact": 0, "escalation": "", "answer": "", "interrupt": True, "evidence": "x", "finished": False, "question": " "}), Failure("the judge interrupted without a question")) + self.assertEqual(verdict_from({"bundled": 0, "bundled_escape_and_impact": 0, "escalation": "", "answer": "", "interrupt": False, "evidence": "e", "finished": True, "question": "", "release_ready": False}), Finished("e")) + self.assertEqual(verdict_from({"bundled": 0, "bundled_escape_and_impact": 0, "escalation": "", "answer": "", "interrupt": False, "evidence": "e", "finished": False, "question": "ignored", "release_ready": False}), Unfinished("e")) + self.assertEqual(verdict_from({"bundled": 0, "bundled_escape_and_impact": 0, "escalation": "", "answer": "", "interrupt": True, "evidence": "e", "finished": True, "question": "Which one?", "release_ready": False}), Interrupt("e", "Which one?")) + self.assertEqual(verdict_from({"bundled": 0, "bundled_escape_and_impact": 0, "escalation": "", "answer": "", "interrupt": True, "evidence": "e", "finished": False, "question": "Cut 0.2.0?", "release_ready": True}), Interrupt("e", "Cut 0.2.0?", release_ready=True)) + self.assertEqual(verdict_from({"bundled": 0, "bundled_escape_and_impact": 0, "escalation": "", "answer": "", "interrupt": True, "evidence": "e", "finished": False, "question": "Cut 0.2.0?"}), Failure("the judge's reply has no release_ready of type boolean")) + self.assertEqual(verdict_from({"bundled": 0, "bundled_escape_and_impact": 0, "escalation": "", "answer": "A.", "interrupt": False, "evidence": "e", "finished": False, "question": "Which one?", "release_ready": False}), QuotedAnswer("e", "Which one?", "A.")) + self.assertEqual(verdict_from({"bundled": 0, "bundled_escape_and_impact": 0, "escalation": "", "answer": "A.", "interrupt": True, "evidence": "e", "finished": False, "question": "Which one?", "release_ready": False}), Interrupt("e", "Which one?")) + self.assertEqual(verdict_from({"bundled": 0, "bundled_escape_and_impact": 0, "escalation": "", "answer": "A.", "interrupt": False, "evidence": "e", "finished": True, "question": "", "release_ready": False}), Failure("the judge quoted an answer without a question")) + self.assertEqual(verdict_from({"bundled": 0, "bundled_escape_and_impact": 0, "escalation": "", "answer": "", "interrupt": "no", "evidence": "", "finished": True, "question": "", "release_ready": False}), Failure("the judge's reply has no interrupt of type boolean")) + self.assertEqual(verdict_from({"bundled": 0, "bundled_escape_and_impact": 0, "escalation": "", "answer": "", "interrupt": False, "evidence": None, "finished": True, "question": "", "release_ready": False}), Failure("the judge's reply has no evidence of type string")) + self.assertEqual(verdict_from({"bundled": 0, "bundled_escape_and_impact": 0, "escalation": "", "answer": "", "interrupt": True, "evidence": "x", "finished": False, "question": " ", "release_ready": False}), Failure("the judge interrupted without a question")) self.assertEqual(verdict_from(None), Failure("the judge returned no reply")) def test_takes_a_bundled_l_on_its_scale_and_counts_any_other_as_none(self): - reply = {"answer": "", "bundled_escape_and_impact": 0, "escalation": "", "interrupt": False, "evidence": "e", "finished": False, "question": ""} + reply = {"answer": "", "bundled_escape_and_impact": 0, "escalation": "", "interrupt": False, "evidence": "e", "finished": False, "question": "", "release_ready": False} self.assertEqual(verdict_from({**reply, "bundled": 4}), Unfinished("e", 4)) self.assertEqual(verdict_from({**reply, "bundled": True}), Failure("the judge's reply has no bundled of type integer")) for bundled in (5, 13, -1): @@ -1105,7 +1194,7 @@ class Verdict(unittest.TestCase): def test_takes_a_bundled_e_plus_i_on_its_scale_and_counts_any_other_as_none(self): - reply = {"answer": "", "bundled": 0, "escalation": "", "interrupt": False, "evidence": "e", "finished": False, "question": ""} + reply = {"answer": "", "bundled": 0, "escalation": "", "interrupt": False, "evidence": "e", "finished": False, "question": "", "release_ready": False} self.assertEqual(verdict_from({**reply, "bundled_escape_and_impact": 6}), Unfinished("e", 0, bundled_escape_and_impact=6)) self.assertEqual(verdict_from({**reply, "bundled_escape_and_impact": 2}), Unfinished("e", 0, bundled_escape_and_impact=2)) self.assertEqual(verdict_from({**reply, "bundled_escape_and_impact": False}), Failure("the judge's reply has no bundled_escape_and_impact of type integer")) @@ -1114,13 +1203,13 @@ class Verdict(unittest.TestCase): self.assertEqual(verdict_from({**reply, "bundled_escape_and_impact": bundled}), Unfinished("e", 0)) def test_takes_an_escalation_quote_on_an_unfinished_verdict(self): - reply = {"answer": "", "bundled": 0, "bundled_escape_and_impact": 0, "escalation": "round 2: 🔴", "interrupt": False, "evidence": "e", "finished": False, "question": ""} + reply = {"answer": "", "bundled": 0, "bundled_escape_and_impact": 0, "escalation": "round 2: 🔴", "interrupt": False, "evidence": "e", "finished": False, "question": "", "release_ready": False} self.assertEqual(verdict_from(reply), Unfinished("e", 0, "round 2: 🔴")) self.assertEqual(verdict_from({**reply, "finished": True}), Finished("e")) self.assertEqual(verdict_from({**reply, "escalation": None}), Failure("the judge's reply has no escalation of type string")) def test_takes_an_escalation_quote_on_an_interrupt(self): - reply = {"answer": "", "bundled": 0, "bundled_escape_and_impact": 0, "escalation": "round 2: 🔴", "interrupt": True, "evidence": "e", "finished": False, "question": "Which one?"} + reply = {"answer": "", "bundled": 0, "bundled_escape_and_impact": 0, "escalation": "round 2: 🔴", "interrupt": True, "evidence": "e", "finished": False, "question": "Which one?", "release_ready": False} self.assertEqual(verdict_from(reply), Interrupt("e", "Which one?", "round 2: 🔴")) self.assertEqual(verdict_from({**reply, "bundled": 4}), Interrupt("e", "Which one?", "round 2: 🔴", 4)) self.assertEqual(verdict_from({**reply, "bundled": 5}), Interrupt("e", "Which one?", "round 2: 🔴")) @@ -1132,7 +1221,7 @@ class Verdict(unittest.TestCase): self.assertEqual(judge.quotes_checked(Unfinished("e", 0, "round 3: 🔴"), shown, ""), Unfinished("e")) def test_takes_an_escalation_quote_and_a_bundled_l_on_a_quoted_answer(self): - reply = {"answer": "A.", "bundled": 4, "bundled_escape_and_impact": 0, "escalation": "round 2: 🔴", "interrupt": False, "evidence": "e", "finished": False, "question": "Which one?"} + reply = {"answer": "A.", "bundled": 4, "bundled_escape_and_impact": 0, "escalation": "round 2: 🔴", "interrupt": False, "evidence": "e", "finished": False, "question": "Which one?", "release_ready": False} self.assertEqual(verdict_from(reply), QuotedAnswer("e", "Which one?", "A.", "round 2: 🔴", 4)) self.assertEqual(verdict_from({**reply, "bundled": 5}), QuotedAnswer("e", "Which one?", "A.", "round 2: 🔴")) @@ -1227,9 +1316,9 @@ class ExitContract(unittest.TestCase): unreadable = f"README.md, or {', '.join(names[:-1])} or {names[-1]} where they exist, cannot be read or is not UTF-8" # Every Stop whose code is not a literal 0, 2 or 130, in source order: path, function, code, start of reason, its --help clause. clauses = [ - ("cycle/interrupt.py", "interrupt", "1", "entries.reason", read), - ("cycle/interrupt.py", "interrupt", "1", "f'could not start claude for the interrupt:", "claude cannot start for an interrupt"), - ("cycle/interrupt.py", "interrupt", "1", "f'could not tell whether you typed anything:", read), + ("cycle/interrupt.py", "talk", "1", "entries.reason", read), + ("cycle/interrupt.py", "talk", "1", "f'could not start claude for the interrupt:", "claude cannot start for an interrupt"), + ("cycle/interrupt.py", "talk", "1", "f'could not tell whether you typed anything:", read), ("cycle/retry.py", "retried", "1", "f'the {who} failed three times running:", "the worker or the judge fails three times running"), ("cycle/run.py", "stopped", "1", "f'{failure.reason}", read), ("cycle/run.py", "work", "1", "f'claude left no transcript for session", "claude leaves no transcript"), diff --git a/docs/decisions.md b/docs/decisions.md index 0131a346..0c15e7c4 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -22,11 +22,13 @@ 2026-10-13, implementing todo item 104: the judge reads each file under `~/.claude/skills/larv-review/standards/` whole too, for the same reason, as the `worker:` decision moved rules there. +2026-10-17, implementing todo item 168: the human answers an interrupt on loop-claude's terminal, and the worker resumes headless with the answer in a `-p` prompt. The judge reads that answer as a `[human]` line, not a `[loop]` one, so it holds the chunk open until the answer is recorded, as it does for an answer typed in claude. + ## loop-claude: one session per project, its id derived from the checkout's path relative to `~/code`, or to `/` outside it 2026-09-21, lilleman; revised 2026-09-30 by lilleman. Serves goal 1. One fixed id per project keeps the session picker at one entry per project and makes any transcript under that id loop-claude's own to delete. A checkout outside `~/code` mirroring a path inside it shares that id, and a second loop on it is not refused. Once `todo.md` item 5 lands, the id comes from the full path, so no two checkouts share one, and `loop-claude` refuses to start while another session on that id is active. Moving the checkout orphans its open sessions, archive folder and models entry: sessions stay in the picker until the human deletes them, migration code not being worth a one-human audience. Valid while claude takes `--session-id` and resumes by it. -## loop-claude: before an interrupt, it marks the checkout and each of its worktrees trusted in `~/.claude.json` +## loop-claude: before it opens claude on the terminal, it marks the checkout and each of its worktrees trusted in `~/.claude.json` 2026-09-21, lilleman; the lost-write risk accepted 2026-09-24 by larv-review. Serves goal 1. A write by another claude inside `trust`'s read-modify-write window is lost. @@ -34,6 +36,8 @@ 2026-09-30, lilleman: Claude Code owns and writes that file, so `loop-claude` is to move out of it, bringing each case that must stay to the human. Stands until `todo.md` item 6 ends it. +2026-10-17, implementing todo item 168: the human answers an interrupt on loop-claude's own terminal, so claude opens on the terminal only when they type `/talk`, for a release ready to cut, and for the routing calls; the trust is marked only then. + ## bin/: the tests rerun themselves on a `uv`-fetched Python at README Install's floor 2026-09-26, larv-review. Serves goal 2. The suite reruns itself on a `uv`-fetched interpreter of the version Install names: `ast.parse(feature_version=)` on the host's Python accepts the nested f-string 186181a fixed, a compile check passes a call newer than the floor, like 3.12's `itertools.batched`, and a `python3.N` on `PATH` is installed by hand on every machine and again at each bump. Valid while `uv` can fetch the floor interpreter and no machine taking the checkout ships an older Python. @@ -288,7 +292,7 @@ Valid while the ladder orders its rungs by competence. 2026-10-15, lilleman asked for it. Serves goals 1.1 and 1.4: when the hard part is the rest of the chunk, handing it to subagents piece by piece leaves the worker, which reads and checks each of their diffs, on a rung that proved too low. The worker climbs only once its run records a trigger. -loop-claude's prompt offers the step beside the escalated subagent of `routing: a worker hands a task one rung up`, as long as the limit leaves a rung that subagent may take without the human's yes. The worker then ends its run asking loop-claude for a higher rung and naming the trigger. The judge quotes an earlier passage that shows the trigger fired, such as a review round's commit title or the worker's report of the failing test, never the request itself. The trigger must have fired since any earlier such request, so one trigger buys one step. The judge sees the worker's text and tool calls but no tool results, so the quote shows that the run recorded the trigger, not that a tool's output bears it out. loop-claude checks the quote word for word, as it checks a quoted answer, since stitched fragments can make up a trigger. Without such a quote, the rung holds. A misquote is no failure, since holding the rung is safe and three failures stop an unattended loop. The next cycle's prompt names the worker's rung, so the worker learns whether the step went through. A worker that a quoted answer stepped up learns it sooner, from the prompt that resumes it with the answer. +loop-claude's prompt offers the step beside the escalated subagent of `routing: a worker hands a task one rung up`, as long as the limit leaves a rung that subagent may take without the human's yes. The worker then ends its run asking loop-claude for a higher rung and naming the trigger. The judge quotes an earlier passage that shows the trigger fired, such as a review round's commit title or the worker's report of the failing test, never the request itself. The trigger must have fired since any earlier such request, so one trigger buys one step. The judge sees the worker's text and tool calls but no tool results, so the quote shows that the run recorded the trigger, not that a tool's output bears it out. loop-claude checks the quote word for word, as it checks a quoted answer, since stitched fragments can make up a trigger. Without such a quote, the rung holds. A misquote is no failure, since holding the rung is safe and three failures stop an unattended loop. The next cycle's prompt names the worker's rung, so the worker learns whether the step went through. A worker that a quoted answer, or an interrupt the human answers on loop-claude's terminal, stepped up learns it sooner, from the prompt that resumes it with the answer. A run that asks for a higher rung may also ask a question. The judge then interrupts, or quotes the answer from README.md or the records, and either ruling carries the escalation quote too, checked the same way. loop-claude steps the rung as the ruling comes in, before the human is asked or the worker resumes with the quoted answer, since the work after the answer is work the stepped rung should do. An interrupt or a quoted answer is no unfinished verdict, so it adds to no count. The judge may quote a different passage for the trigger that already stepped the rung, and loop-claude cannot tell that from a new trigger. So once an interrupt or a quoted answer has taken an escalation, no later ruling of that cycle carries one. A trigger that fires after the answer steps nothing in that cycle. diff --git a/docs/reading-cost.md b/docs/reading-cost.md index 5ae353ef..ee66058d 100644 --- a/docs/reading-cost.md +++ b/docs/reading-cost.md @@ -632,3 +632,7 @@ Read most (opens and searches): Read most (opens and searches): - `rules/todo-items.md` 1 + +## Reading cost, chunk 055546870eaf, finished 2026-10-17T20:46:45Z + +100998 new input tokens before the first commit. diff --git a/todo.md b/todo.md index 9ab4e3d5..d0b522e8 100644 --- a/todo.md +++ b/todo.md @@ -13,7 +13,6 @@ | ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score | |---|---|---|---|---|---|---|---|---|---|---|---| | 180 | 0.2.0 | | question | **Settle how a trigger that fires after a step-up at an interrupt or a quoted answer steps the worker, which today it never does.** | 2 | 2 | 2 | 4 | 3 | 1.1 by 3 | 4.1 | -| 168 | 0.2.0 | | | **Have the human answer an interrupt on loop-claude's terminal and resume the worker headless with the answer, opening the interactive session only when they ask for it.** | 4 | 2 | 3 | 7 | 5 | 1.5 by 8 | 1.8 | | 73 | 0.2.0 | | | **Have each reviewer write its full report to a file and return the worker only its findings' one-line summaries.** | 3 | 2 | 3 | 6 | 5 | 1.4 by 4 | 1.1 | | 159 | 0.2.0 | | decision | **Run each review pass on the lowest rung that a replay of its archived rounds shows finding every 🔴 and 🟡 the project's rung finds, even below the worker's rung.** | 4 | 2 | 3 | 7 | 6 | 1.4 by 7 | 1.1 | | 80 | 0.3.0 | | defect | **State in README → Install that every machine taking this checkout must be a sandbox, as `settings.json`'s auto mode assumes.** | 1 | 2 | 1 | 2 | 1 | 2 by 4 | 17.5 | @@ -95,12 +94,6 @@ Options: Only the human can choose, and the answer revises that decision. Found by the stability review of PR #307. -### 168. Have the human answer an interrupt on loop-claude's terminal and resume the worker headless with the answer, opening the interactive session only when they ask for it. - -Today an interrupt runs `claude --resume` on the terminal and waits for it to exit (`bin/loop_claude/cycle/interrupt.py`). Once the human answers, the worker carries on in that interactive session, so the loop waits until the human exits it, often for the rest of the chunk. Instead, the loop prints the question and reads the answer on its own terminal. The next cycle resumes the worker headless with a prompt like `prompts.answered`'s, saying the human gave the answer. A word typed in place of an answer, such as `/talk`, opens today's interactive session, for when the human wants to read the diff or discuss first. An empty answer stops the loop, as an interrupt with nothing typed does today. A release ready to cut still opens the interactive session. Bench the word, and the line that asks for the answer, as `CLAUDE.md` says. - -The judge must treat an answer typed at the loop's terminal as the human's. `bin/claude_code/transcript.py`'s `render` labels every `-p` prompt `[loop]`, so an answer passed on headless would read as one quoted from the records. The judge would then never hold the chunk open until that answer is recorded. The change touches two places the comprehension seats found hard: `bin/loop_claude/cycle/judge.py`'s `run_judge` and `bin/loop_claude/loop/main.py`'s help. Leave each easier to read. When the interrupt stepped the worker's rung up (`Cycle.stepped_from`), have the headless resume prompt name the new rung and repeat `prompts.rungs_held`, as `prompts.answered` does after a quoted answer's step. Otherwise the worker learns of the step only next cycle, though `docs/decisions.md` says the next prompt names it. - ### 73. Have each reviewer write its full report to a file and return the worker only its findings' one-line summaries. 2026-10-08, lilleman: rescored from A10/G8 to A4/G4 on the measurement below, so other items that lower token use go first. @@ -370,7 +363,7 @@ While `rank_todo.py` ranks two shapes, projects follow two sets of scoring rules ### 155. Lower the reading cost of the files a chunk reads most before its first commit. -`bin/reading-cost` on 2026-10-16: the median of the last 5 chunks is 189,487 new input tokens before their first commit, up from 146,584 for the 5 before them. Read most over the last 5, by opens and searches: `todo.md` 51, `README.md` 12, `CHANGELOG.md` 11, `bin/loop_claude/test_loop_claude.py` 11, `AGENTS.md` 7, `bin/todo_table.py` 7, `docs/decisions.md` 7, `agents/stability-reviewer.md` 6, `bin/loop_claude/cycle/judge.py` 5, `bin/rule_hook/test_rule_hook.py` 5. The chunk that ships this item runs `bin/reading-cost --reset`. +`bin/reading-cost` on 2026-10-17: the median of the last 5 chunks is 117,108 new input tokens before their first commit, up from 107,738 for the 5 before them. Read most over the last 5, by opens and searches: `bin/loop_claude/test_loop_claude.py` 14, `todo.md` 11, `bin/loop_claude/test_black_box.py` 10, `bin/rank_todo.py` 6, `CHANGELOG.md` 5, `README.md` 5, `docs/decisions.md` 4, `.gitignore` 3, `bin/loop_claude/routing.py` 2, `bin/markdown_text.py` 2. The chunk that ships this item runs `bin/reading-cost --reset`. ### 1. Say in README → Install how the transcript archive is backed up, once bender-infra backs up ai-sandbox's data volume. From 96834412c7d0bbdfc3088906333b1432f4c331a2 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sat, 17 Oct 2026 23:16:34 +0200 Subject: [PATCH 02/15] =?UTF-8?q?Answer=20architecture=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=202=20=F0=9F=9F=A1;=20keep=20stepped=5Ffrom=20thr?= =?UTF-8?q?ough=20the=20typed=20answer,=20name=20the=20events=20HumanTyped?= =?UTF-8?q?=20and=20HumanTalked,=20parse=20the=20answer=20from=20the=20pro?= =?UTF-8?q?mpt's=20start,=20and=20say=20why=20the=20judge=20decides=20rele?= =?UTF-8?q?ase=5Fready?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin/loop_claude/cycle/interrupt.py | 28 +++++---- bin/loop_claude/cycle/judge.py | 2 +- bin/loop_claude/cycle/prompts.py | 14 ++--- bin/loop_claude/cycle/run.py | 30 ++++++---- bin/loop_claude/cycle/states.py | 19 +++--- bin/loop_claude/test_black_box.py | 2 +- bin/loop_claude/test_loop_claude.py | 91 +++++++++++++---------------- 7 files changed, 90 insertions(+), 96 deletions(-) diff --git a/bin/loop_claude/cycle/interrupt.py b/bin/loop_claude/cycle/interrupt.py index 8e7adeb9..65b10c9b 100644 --- a/bin/loop_claude/cycle/interrupt.py +++ b/bin/loop_claude/cycle/interrupt.py @@ -16,22 +16,20 @@ 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, 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.""" +def put_question(question: str, effects: Effects) -> Stop | None: + """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) - 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) + return needs_terminal(ANSWER_QUESTION, effects.on_terminal()) + + +def read_answer(effects: Effects) -> str | Stop: + """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.""" + try: + answer = effects.input(ASK_ANSWER).strip() + except EOFError: + print(file=sys.stderr) + return needs_human(ANSWER_QUESTION, "the input ended") + return answer or needs_human(ANSWER_QUESTION, "nothing was typed") def talk(root: str, session_id: uuid.UUID, worker: Rung, path: str, paths: Paths, env: dict[str, str], effects: Effects) -> Stop | None: diff --git a/bin/loop_claude/cycle/judge.py b/bin/loop_claude/cycle/judge.py index 8564176f..605ab253 100644 --- a/bin/loop_claude/cycle/judge.py +++ b/bin/loop_claude/cycle/judge.py @@ -72,7 +72,7 @@ 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. + # 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."}) diff --git a/bin/loop_claude/cycle/prompts.py b/bin/loop_claude/cycle/prompts.py index ee34cfd4..c1661be4 100644 --- a/bin/loop_claude/cycle/prompts.py +++ b/bin/loop_claude/cycle/prompts.py @@ -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: - """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)}" + """Resumes the worker with the human's answer to an interrupt. answer is one line, as the terminal reads it.""" + 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. -TYPED_HERE = "The human answers it at loop-claude's terminal:" +# 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 answered your question 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 + """The answer typed put in prompt, so the judge reads it as the human's; None for any other prompt.""" + opening = f"{TYPED_HERE}\n" + 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: diff --git a/bin/loop_claude/cycle/run.py b/bin/loop_claude/cycle/run.py index 5e5b6045..6354b15f 100644 --- a/bin/loop_claude/cycle/run.py +++ b/bin/loop_claude/cycle/run.py @@ -2,17 +2,17 @@ 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, 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 claude_code.session import delete_session, Session, session_open, transcript_file from loop_claude.effects import Effects from failure import Failure 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 transcript_archive import outcomes from loop_claude.paths import Paths 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 loop_claude.cycle.retry import retried from model_routing.route import Route @@ -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 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 # 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 @@ -69,7 +69,9 @@ def run_cycle(cycle: Cycle) -> Stop | Concluded: 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) if not (isinstance(event, Ruled) and isinstance(event.verdict, Interrupt | QuotedAnswer) and event.verdict.escalation): return cycle @@ -124,7 +126,7 @@ def worker_start(cycle: Cycle, answered: QuotedAnswer | TypedAnswer | None) -> l 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) + 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): 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) @@ -163,19 +165,23 @@ def keep_rejection(cycle: Cycle, transcript_path: str, rejected: Rejected) -> St 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) # 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. 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) - 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) + if stop := put_question(question, cycle.effects): + return stop + # Only the human may cut a release, so a release ready to cut opens claude's session at once. + if not (isinstance(ruling, Interrupt) and ruling.release_ready): + answer = read_answer(cycle.effects) + 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: diff --git a/bin/loop_claude/cycle/states.py b/bin/loop_claude/cycle/states.py index 2636f322..27e8fc13 100644 --- a/bin/loop_claude/cycle/states.py +++ b/bin/loop_claude/cycle/states.py @@ -8,10 +8,9 @@ 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.""" + """The human's answer to an interrupt, typed at loop-claude's terminal.""" question: str answer: str - stepped: bool @dataclasses.dataclass(frozen=True) @@ -62,9 +61,13 @@ class Ruled: @dataclasses.dataclass(frozen=True) -class HumanAnswered: - """typed is None where the human answered in the interrupt's claude session.""" - typed: TypedAnswer | None = None +class HumanTyped: + typed: TypedAnswer + + +@dataclasses.dataclass(frozen=True) +class HumanTalked: + """The human typed in the interrupt's claude session.""" @dataclasses.dataclass(frozen=True) @@ -72,7 +75,7 @@ class Archived: pass -Event = WorkerRan | Ruled | HumanAnswered | Archived +Event = WorkerRan | Ruled | HumanTyped | HumanTalked | Archived 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) case Judging(transcript_path, _), Ruled(Finished() | Unfinished() as 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) # 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) case Closing(_, verdict), Archived(): return Ended(verdict) diff --git a/bin/loop_claude/test_black_box.py b/bin/loop_claude/test_black_box.py index 70a1972e..50f0a268 100644 --- a/bin/loop_claude/test_black_box.py +++ b/bin/loop_claude/test_black_box.py @@ -664,7 +664,7 @@ class Interrupt(unittest.TestCase): self.assertIn("A or B?\nAnswer (/talk opens claude, Enter stops the loop): ", run.stderr) resumed = run.calls[2]["argv"] 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"]) for transcript in checkout.transcripts(): diff --git a/bin/loop_claude/test_loop_claude.py b/bin/loop_claude/test_loop_claude.py index e01ddfe4..e0a4d7b8 100644 --- a/bin/loop_claude/test_loop_claude.py +++ b/bin/loop_claude/test_loop_claude.py @@ -143,7 +143,7 @@ class Streamed: return self.code -TYPED = states.TypedAnswer("Which one?", "Use B.", False) +TYPED = states.TypedAnswer("Which one?", "Use B.") 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"), 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"), 3), states.HumanAnswered(), states.Judging("/t", 3)), - (states.Interrupting("/t", Interrupt("e", "q")), states.HumanAnswered(TYPED), states.Working(TYPED)), - (states.Interrupting("/t", Interrupt("e", "q"), 3), states.HumanAnswered(TYPED), states.Working(TYPED, 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)), (states.Closing("/t", Finished("e")), states.Archived(), states.Ended(Finished("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): 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_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 event in every_event: 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"), []) resumed = fake.made("stream_claude")[1] 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")] 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): 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)) first, resumed = fake.made("stream_claude") 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 answer(args): @@ -513,59 +513,44 @@ class Limits(unittest.TestCase): class Interrupts(unittest.TestCase): - def ask(self, fake, home="/h", path="/t", rung=Rung("m"), env=None, release_ready=False): - with contextlib.redirect_stderr(io.StringIO()) as said: - asked = interrupt.interrupt(home, uuid7(), rung, path, "Which one?", release_ready, paths.paths_from(pathlib.Path(home)), env or {}, fake.effects()) - self.said = said.getvalue() - return asked + def test_puts_the_question_and_stops_off_a_terminal(self): + 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)): + with self.subTest(on_terminal=on_terminal): + fake = FakeEffects(on_terminal=on_terminal) + 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): - fake = FakeEffects(on_terminal=False) - 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")) - self.assertEqual(fake.calls, []) - - def test_returns_the_answer_typed_at_the_terminal_without_starting_claude(self): - 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_reads_the_line_typed_at_the_terminal_stripped(self): + for typed, want in ((" Use B. ", "Use B."), (" /talk ", "/talk")): + with self.subTest(typed=typed): + fake = FakeEffects(inputs=[typed]) + self.assertEqual(interrupt.read_answer(fake.effects()), want) + self.assertEqual(fake.made("input"), ["Answer (/talk opens claude, Enter stops the loop): "]) def test_stops_on_an_empty_answer_or_the_inputs_end(self): - for typed, why in ((" ", "nothing was typed"), (EOFError(), "the input ended")): - with self.subTest(why=why): - fake = FakeEffects(inputs=[typed]) - self.assertEqual(self.ask(fake), Stop(2, f"the human is needed to answer the question above, but {why}")) - 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)) + for typed, why, said in ((" ", "nothing was typed", ""), (EOFError(), "the input ended", "\n")): + with self.subTest(why=why), contextlib.redirect_stderr(io.StringIO()) as printed: + 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(printed.getvalue(), said) def test_stops_when_nothing_was_typed_in_the_session(self): with tempfile.TemporaryDirectory() as home: path = pathlib.Path(home, "t.jsonl") path.write_text(json.dumps(human("a")) + "\n") - fake = FakeEffects(inputs=["/talk"], 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")) + fake = FakeEffects(on_terminal_claude=[0], git=[ran()]) + 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): with tempfile.TemporaryDirectory() as home: path = pathlib.Path(home, "t.jsonl") 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"} - 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]) @@ -976,12 +961,14 @@ class PythonEffect(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")) - 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.assertIsNone(prompts.typed_answer(prompts.answered("Which one?", "Use B.", 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.answered("Which one?", marked, route, None, False))) + self.assertIsNone(prompts.typed_answer(prompts.resumed(marked, route, None))) class WorkerArgs(unittest.TestCase): From 44fa8a7fe6dbbdb5d1aa5cf95d99ce7b7b52f8ec Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sat, 17 Oct 2026 23:32:21 +0200 Subject: [PATCH 03/15] =?UTF-8?q?Answer=20architecture=20round=202:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=200=20=F0=9F=9F=A1;=20the=20architect=20approved?= =?UTF-8?q?=20the=20answers?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit From 4b2d4a17349ba3189fb433b621d868619517dfa3 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sat, 17 Oct 2026 23:32:21 +0200 Subject: [PATCH 04/15] =?UTF-8?q?Answer=20principles=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=206=20=F0=9F=9F=A1;=20correct=20the=20interrupt's?= =?UTF-8?q?=20definition,=20show=20the=20judge=20the=20question=20beside?= =?UTF-8?q?=20the=20typed=20answer,=20ask=20in=20one=20call=20returning=20?= =?UTF-8?q?Talk,=20add=20a=20Talking=20state,=20give=20the=20worker=20its?= =?UTF-8?q?=20own=20question=20past=20the=20cap,=20assert=20the=20prompts'?= =?UTF-8?q?=20facts,=20and=20keep=20stepped=5Ffrom=20as=20the=20step's=20o?= =?UTF-8?q?ne=20owner?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CLAUDE.md | 2 +- bin/claude_code/test_claude_code.py | 6 +- bin/claude_code/transcript.py | 6 +- bin/judge_replay/test_judge_replay.py | 2 +- bin/loop_claude/cycle/interrupt.py | 25 ++++-- bin/loop_claude/cycle/prompts.py | 11 ++- bin/loop_claude/cycle/run.py | 24 +++--- bin/loop_claude/cycle/states.py | 22 ++++- bin/loop_claude/effects.py | 4 + bin/loop_claude/loop/main.py | 4 +- bin/loop_claude/test_black_box.py | 42 +++++----- bin/loop_claude/test_loop_claude.py | 81 ++++++++++++------- bin/stability_replay/test_stability_replay.py | 2 +- todo.md | 14 +++- 14 files changed, 153 insertions(+), 92 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 4c1215dd..360357df 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -96,7 +96,7 @@ The rules only reviewers apply, for quality, comments, READMEs and prose, live i - **chunk** — the unit of work, shipped as one PR; "Working loop" says what it holds. - **cycle** — in `loop-claude`, worker runs and the judge's verdict on each, until the chunk closes or is left for the next cycle. In between, the human answers any interrupt, or the worker resumes with an answer the judge quoted from `README.md`, `AGENTS.md`, `docs/decisions.md`, `~/.claude/CLAUDE.md`, `~/.claude/rules/` or `~/.claude/skills/larv-review/standards/`. - **gate** — the merge gate: the checks a PR passes before it merges. -- **interrupt** — `loop-claude` handing the terminal to the human, `claude --resume`, for a decision that is theirs. +- **interrupt** — `loop-claude` asking the human, on its terminal, for a decision that is theirs; typing `/talk` there, or a release ready to cut, opens the worker's session with `claude --resume`. - **judge** — the headless claude that reads a worker's transcript each cycle and decides whether to interrupt and whether the chunk is finished. - **pass** — one kind of review a chunk may take, run in rounds by its reviewers until clean; `larv-review` §3 lists them. - **plan** — `todo.md`. diff --git a/bin/claude_code/test_claude_code.py b/bin/claude_code/test_claude_code.py index bd18d1e2..4d436dc8 100644 --- a/bin/claude_code/test_claude_code.py +++ b/bin/claude_code/test_claude_code.py @@ -34,9 +34,9 @@ class Render(unittest.TestCase): queued("B, while you work", "human"), queued("origin/main moved", "coordinator"), {**human("Continue the task; the previous run stopped before it was finished."), "promptSource": "sdk"}, - {**human("Answered: use B"), "promptSource": "sdk"}, - ], lambda prompt: prompt.removeprefix("Answered: ") if prompt.startswith("Answered: ") else None) - self.assertEqual(said, '[human] do it\n\nStarting.\n\n[tool Bash] {"command": "ls"}\n\n[human] yes, merge it\n\n[human] B, while you work\n\n[loop] Continue the task; the previous run stopped before it was finished.\n\n[human] use B') + {**human("Answered: use B\nYour question: A or B?"), "promptSource": "sdk"}, + ], lambda prompt: tuple(reversed(prompt.removeprefix("Answered: ").split("\n"))) if prompt.startswith("Answered: ") else None) + self.assertEqual(said, '[human] do it\n\nStarting.\n\n[tool Bash] {"command": "ls"}\n\n[human] yes, merge it\n\n[human] B, while you work\n\n[loop] Continue the task; the previous run stopped before it was finished.\n\n[loop] Your question: A or B?\n\n[human] use B') class FirstTimestampedLine(unittest.TestCase): diff --git a/bin/claude_code/transcript.py b/bin/claude_code/transcript.py index 07ce9fde..a14dd904 100644 --- a/bin/claude_code/transcript.py +++ b/bin/claude_code/transcript.py @@ -25,8 +25,8 @@ def human_turns(entries: list[dict]) -> int: return sum(1 for entry in entries if human_text(entry) is not None) -def render(entries: list[dict], typed_answer: typing.Callable[[str], str | None]) -> str: - """The transcript as the judge reads it. typed_answer finds an answer the human typed in a -p prompt of loop-claude's, which reads as the human's, like one typed in claude.""" +def render(entries: list[dict], typed_answer: typing.Callable[[str], tuple[str, str] | None]) -> str: + """The transcript as the judge reads it. typed_answer splits a -p prompt of loop-claude's that carries an answer the human typed into loop-claude's words and that answer, which reads as the human's, like one typed in claude.""" lines = [] for entry in entries: lines += [line for part in assistant_parts(entry) if (line := part_line(part, JUDGED_TOOL_INPUT))] @@ -34,7 +34,7 @@ def render(entries: list[dict], typed_answer: typing.Callable[[str], str | None] lines.append("[human] " + text) elif (text := loop_text(entry)) is not None: typed = typed_answer(text) - lines.append("[loop] " + text if typed is None else "[human] " + typed) + lines += ["[loop] " + text] if typed is None else ["[loop] " + typed[0], "[human] " + typed[1]] return "\n\n".join(lines) diff --git a/bin/judge_replay/test_judge_replay.py b/bin/judge_replay/test_judge_replay.py index a30aa1a5..9bef31d2 100644 --- a/bin/judge_replay/test_judge_replay.py +++ b/bin/judge_replay/test_judge_replay.py @@ -114,7 +114,7 @@ class Main(unittest.TestCase): result = reply(Rung(args[args.index("--model") + 1], args[args.index("--effort") + 1]), "said Verdict: interrupt" in prompt.rsplit("latest last:", 1)[-1]) return subprocess.CompletedProcess(args, 0, json.dumps(result), "") - effects = Effects(claude=claude, claude_on_terminal=unused, execv=unused, git=unused, input=unused, local_time=unused, now=unused, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused) + effects = Effects(claude=claude, claude_on_terminal=unused, discard_typed=unused, execv=unused, git=unused, input=unused, local_time=unused, now=unused, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused) out, err = io.StringIO(), io.StringIO() with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): code = main.main(argv, {}, self.home, effects) diff --git a/bin/loop_claude/cycle/interrupt.py b/bin/loop_claude/cycle/interrupt.py index 65b10c9b..d73820f9 100644 --- a/bin/loop_claude/cycle/interrupt.py +++ b/bin/loop_claude/cycle/interrupt.py @@ -1,3 +1,4 @@ +import dataclasses import sys import uuid @@ -16,20 +17,28 @@ TALK = "/talk" ASK_ANSWER = f"Answer ({TALK} opens claude, Enter stops the loop): " -def put_question(question: str, effects: Effects) -> Stop | None: - """Prints question for the human; a Stop where loop-claude is off a terminal, so no one can answer it.""" +@dataclasses.dataclass(frozen=True) +class Talk: + """The human answers in the worker's claude session, which talk opens.""" + + +def put_question(question: str, answer_here: bool, effects: Effects) -> str | Talk | Stop: + """Prints question for the human. Where answer_here, returns the line they type at loop-claude's terminal, stripped, or Talk where they type TALK; else Talk at once. A Stop where loop-claude is off a terminal, or they type nothing, or the input ends.""" print(f"\n{question}", file=sys.stderr) - return needs_terminal(ANSWER_QUESTION, effects.on_terminal()) - - -def read_answer(effects: Effects) -> str | Stop: - """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.""" + if stop := needs_terminal(ANSWER_QUESTION, effects.on_terminal()): + return stop + if not answer_here: + return Talk() + # Keys typed while the worker ran wait on the terminal, so they would answer a question no one has read. A paste's lines after the first are dropped with them at the next question, never taken as its answer; a longer answer goes through TALK. + effects.discard_typed() try: answer = effects.input(ASK_ANSWER).strip() except EOFError: print(file=sys.stderr) return needs_human(ANSWER_QUESTION, "the input ended") - return answer or needs_human(ANSWER_QUESTION, "nothing was typed") + if not answer: + return needs_human(ANSWER_QUESTION, "nothing was typed") + return Talk() if answer == TALK else answer def talk(root: str, session_id: uuid.UUID, worker: Rung, path: str, paths: Paths, env: dict[str, str], effects: Effects) -> Stop | None: diff --git a/bin/loop_claude/cycle/prompts.py b/bin/loop_claude/cycle/prompts.py index c1661be4..5ef9de49 100644 --- a/bin/loop_claude/cycle/prompts.py +++ b/bin/loop_claude/cycle/prompts.py @@ -130,17 +130,20 @@ 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: """Resumes the worker with the human's answer to an interrupt. answer is one line, as the terminal reads it.""" - return f"{TYPED_HERE}\n{answer}\n\nYour question was: {question}\n\nContinue the task.{stepped_to(route, anchor, stepped)}" + return f"{TYPED_HERE}\n{answer}\n\nYour question was: {question}\n\nContinue the task. The chunk is finished only once {ANSWERS_RECORDED}.{stepped_to(route, anchor, stepped)}" # 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 answered your question 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.""" +def typed_answer(prompt: str) -> tuple[str, str] | None: + """The rest of the prompt typed made, and the answer it put there, so the judge reads the answer as the human's; None for any other prompt.""" opening = f"{TYPED_HERE}\n" - return prompt.removeprefix(opening).split("\n", 1)[0] if prompt.startswith(opening) else None + if not prompt.startswith(opening): + return None + answer, _, rest = prompt.removeprefix(opening).partition("\n\n") + return rest, answer def stepped_to(route: Route, anchor: Rung | None, stepped: bool) -> str: diff --git a/bin/loop_claude/cycle/run.py b/bin/loop_claude/cycle/run.py index 6354b15f..79d26764 100644 --- a/bin/loop_claude/cycle/run.py +++ b/bin/loop_claude/cycle/run.py @@ -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, 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, TalkChosen, Talking, 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 @@ -12,7 +12,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 loop_claude.cycle.interrupt import put_question, read_answer, talk, TALK +from loop_claude.cycle.interrupt import put_question, talk, Talk from claude_code.transcript import read_transcript from loop_claude.cycle.retry import retried from model_routing.route import Route @@ -69,7 +69,7 @@ def run_cycle(cycle: Cycle) -> Stop | Concluded: 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. stepped_from holds through the answer the human types, so the worker resuming with it is told of the step.""" + """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; a copy on TypedAnswer would give the step a second owner.""" if isinstance(event, HumanTyped): return cycle cycle = dataclasses.replace(cycle, stepped_from=None) @@ -99,6 +99,8 @@ def step(cycle: Cycle, state: Active) -> Event | Stop: return rule(cycle, transcript_path) case Interrupting(transcript_path, ruling, _): return ask(cycle, transcript_path, ruling) + case Talking(transcript_path, _): + return talk(cycle.root, cycle.session.id, cycle.route.rung, transcript_path, cycle.paths, worker_environment(cycle), cycle.effects) or HumanTalked() case Closing(transcript_path, verdict): return close(cycle, transcript_path, verdict) case _: @@ -165,23 +167,19 @@ def keep_rejection(cycle: Cycle, transcript_path: str, rejected: Rejected) -> St return None -def ask(cycle: Cycle, transcript_path: str, ruling: Interrupt | QuotedAnswer) -> HumanTyped | HumanTalked | Stop: +def ask(cycle: Cycle, transcript_path: str, ruling: Interrupt | QuotedAnswer) -> HumanTyped | TalkChosen | 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. 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) - if stop := put_question(question, cycle.effects): - return stop # Only the human may cut a release, so a release ready to cut opens claude's session at once. - if not (isinstance(ruling, Interrupt) and ruling.release_ready): - answer = read_answer(cycle.effects) - 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() + answer = put_question(question, not (isinstance(ruling, Interrupt) and ruling.release_ready), cycle.effects) + if isinstance(answer, Stop): + return answer + # The worker gets the question it asked, not the one put to the human past the cap. + return TalkChosen() if isinstance(answer, Talk) else HumanTyped(TypedAnswer(ruling.question, answer)) def archive_stepped(cycle: Cycle, transcript_path: str, outcome: str) -> Failure | None: diff --git a/bin/loop_claude/cycle/states.py b/bin/loop_claude/cycle/states.py index 27e8fc13..05227e67 100644 --- a/bin/loop_claude/cycle/states.py +++ b/bin/loop_claude/cycle/states.py @@ -35,6 +35,13 @@ class Interrupting: quoted_answers: int = 0 +@dataclasses.dataclass(frozen=True) +class Talking: + """The human answers in the worker's claude session, on the terminal.""" + transcript_path: str + quoted_answers: int = 0 + + @dataclasses.dataclass(frozen=True) class Closing: transcript_path: str @@ -46,7 +53,7 @@ class Ended: verdict: Finished | Unfinished -Active = Working | Judging | Interrupting | Closing +Active = Working | Judging | Interrupting | Talking | Closing State = Active | Ended @@ -65,6 +72,11 @@ class HumanTyped: typed: TypedAnswer +@dataclasses.dataclass(frozen=True) +class TalkChosen: + """The human typed /talk, or the question is a release ready to cut, which only the human may cut.""" + + @dataclasses.dataclass(frozen=True) class HumanTalked: """The human typed in the interrupt's claude session.""" @@ -75,7 +87,7 @@ class Archived: pass -Event = WorkerRan | Ruled | HumanTyped | HumanTalked | Archived +Event = WorkerRan | Ruled | HumanTyped | TalkChosen | HumanTalked | Archived def transition(state: State, event: Event) -> State: @@ -92,8 +104,10 @@ def transition(state: State, event: Event) -> State: return Closing(transcript_path, verdict) case Interrupting(_, _, quoted_answers), HumanTyped(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), HumanTalked(): + case Interrupting(transcript_path, _, quoted_answers), TalkChosen(): + return Talking(transcript_path, 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(): return Judging(transcript_path, quoted_answers) case Closing(_, verdict), Archived(): return Ended(verdict) diff --git a/bin/loop_claude/effects.py b/bin/loop_claude/effects.py index 760444e9..1ba2bf22 100644 --- a/bin/loop_claude/effects.py +++ b/bin/loop_claude/effects.py @@ -2,6 +2,7 @@ import dataclasses import os import subprocess import sys +import termios import time import typing @@ -21,6 +22,8 @@ class Streaming(typing.Protocol): class Effects: claude: typing.Callable[[list[str], str, str], subprocess.CompletedProcess[str]] claude_on_terminal: typing.Callable[[list[str], str, dict[str, str]], int] + # Drops what was typed on the terminal and not yet read. + discard_typed: typing.Callable[[], None] execv: typing.Callable[[str, list[str]], None] git: typing.Callable[[list[str], str], subprocess.CompletedProcess[str]] input: typing.Callable[[str], str] @@ -49,6 +52,7 @@ def system_effects() -> Effects: return Effects( claude=lambda args, cwd, stdin: subprocess.run(["claude", *args], capture_output=True, cwd=cwd, input=stdin, text=True), claude_on_terminal=lambda args, cwd, env: subprocess.run(["claude", *args], cwd=cwd, env={**os.environ, **env}).returncode, + discard_typed=lambda: termios.tcflush(sys.stdin, termios.TCIFLUSH), execv=os.execv, git=lambda args, cwd: subprocess.run(["git", *args], capture_output=True, cwd=cwd, text=True), input=input, diff --git a/bin/loop_claude/loop/main.py b/bin/loop_claude/loop/main.py index ccf921dc..22e2cd07 100644 --- a/bin/loop_claude/loop/main.py +++ b/bin/loop_claude/loop/main.py @@ -153,8 +153,8 @@ Exit 1, saying why, when: Exit 2, when the human is needed and cannot answer: - stdin or stdout is not a terminal, when a model must be picked or an interrupt answered - the input ends while a model is picked -- an interrupt's answer is empty or the input ends, or the claude that /talk opened ends with - nothing typed +- an interrupt's answer is empty or the input ends, or the claude opened for /talk or a release + ready to cut ends with nothing typed Rerunning resumes any open session. """ diff --git a/bin/loop_claude/test_black_box.py b/bin/loop_claude/test_black_box.py index 50f0a268..57f04ce1 100644 --- a/bin/loop_claude/test_black_box.py +++ b/bin/loop_claude/test_black_box.py @@ -121,6 +121,10 @@ TODO = "## Items\n\n| ID | Release | Exempt | Item | L | E | I | R | S | Moves | CHEAP = TODO.replace("| 4 | 2 | 3 | 7 |", "| 2 | 1 | 2 | 3 |") +# Waits for the interrupt's prompt before typing the answer, since loop-claude drops what was typed before it. +ANSWERING = ("Answer (", lambda: None) + + def worker(**step): return {"role": "worker", **step} @@ -196,7 +200,7 @@ class Checkout: self.git("add", "todo.md") self.git("commit", "--quiet", "-m", "plan") - def run(self, steps, argv=(TASK,), cwd=None, terminal_input=None, stdout_on_terminal=True, before_typing=None): + def run(self, steps, argv=(TASK,), cwd=None, terminal_input=None, stdout_on_terminal=True, before_typing=None, typed_early=""): for name in ("FAKE_CLAUDE_LOG", "LOOP_TEST_LOG"): pathlib.Path(self.env[name]).unlink(missing_ok=True) pathlib.Path(self.env["FAKE_CLAUDE_SCENARIO"]).write_text(json.dumps(steps)) @@ -206,7 +210,7 @@ class Checkout: done = subprocess.run(command, capture_output=True, cwd=cwd, env=self.env, stdin=subprocess.DEVNULL, text=True, timeout=60) code, stdout, stderr = done.returncode, done.stdout, done.stderr else: - code, stdout, stderr = self.run_on_terminal(command, cwd, terminal_input, stdout_on_terminal, before_typing) + code, stdout, stderr = self.run_on_terminal(command, cwd, terminal_input, stdout_on_terminal, before_typing, typed_early) started = lines(pathlib.Path(self.env["LOOP_TEST_LOG"])) return Run( calls=lines(pathlib.Path(self.env["FAKE_CLAUDE_LOG"])), @@ -217,8 +221,8 @@ class Checkout: stdout=stdout, ) - def run_on_terminal(self, command, cwd, typed, stdout_on_terminal, before_typing): - """Types the input at once, or once stderr shows before_typing's text and its callback has run.""" + def run_on_terminal(self, command, cwd, typed, stdout_on_terminal, before_typing, typed_early): + """Types typed_early at once, then the input at once, or once stderr shows before_typing's text and its callback has run.""" controller, terminal = pty.openpty() with tempfile.TemporaryFile() as stderr, tempfile.TemporaryFile() as stdout: try: @@ -226,6 +230,7 @@ class Checkout: finally: os.close(terminal) try: + os.write(controller, typed_early.encode()) prompt, callback = before_typing or (None, None) if prompt is None: os.write(controller, typed.encode()) @@ -467,7 +472,7 @@ class Cycles(unittest.TestCase): worker(say=f"{cited} Trigger 3 fired; I ask for a higher rung. Shall I use A or B?"), judge(interrupt=True, evidence="Shall I use A or B?", question="A or B?", escalation=cited), interrupt(type="B"), judge(evidence="B", escalation="Trigger 3 fired; I ask for a higher rung."), worker(say="carrying on"), - ], terminal_input="/talk\n") + ], terminal_input="/talk\n", before_typing=ANSWERING) self.assertEqual(run.code, 130) self.assertEqual(run.roles(), ["worker", "judge", "interrupt", "judge", "worker", "judge"]) self.assertEqual([(argument(call, "--model"), argument(call, "--effort")) for call in run.calls if call["role"] != "judge"], [("claude-opus-5-5", "high"), ("claude-opus-5-5", "xhigh"), ("claude-opus-5-5", "xhigh")]) @@ -655,23 +660,16 @@ class Interrupt(unittest.TestCase): self.assertEqual(run.code, 2) self.assertEqual(len(checkout.archived()), 2) - def test_resumes_the_worker_headless_with_the_answer_typed_at_its_terminal_and_has_the_judge_read_it_as_the_humans(self): + def test_resumes_the_worker_headless_with_the_answer_typed_at_its_terminal_not_with_keys_typed_before_it(self): checkout = Checkout(self) asked = [worker(say="Shall I use A or B?"), judge(interrupt=True, evidence="Shall I use A or B?", question="A or B?")] - run = checkout.run([*asked, worker(say="Using B."), judge(evidence="Using B.")], terminal_input="B\n") + run = checkout.run([*asked, worker(say="Using B."), judge(evidence="Using B.")], terminal_input="B\n", before_typing=ANSWERING, typed_early="stray\n") self.assertEqual(run.code, 130) self.assertEqual(run.roles(), ["worker", "judge", "worker", "judge", "worker"]) self.assertIn("A or B?\nAnswer (/talk opens claude, Enter stops the loop): ", run.stderr) - resumed = run.calls[2]["argv"] self.assertEqual(argument(run.calls[2], "--resume"), argument(run.calls[0], "--session-id")) - 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"]) - - for transcript in checkout.transcripts(): - transcript.unlink() - run = checkout.run(asked, terminal_input="\n") - self.assertEqual((run.code, run.roles()), (2, ["worker", "judge"])) - self.assertTrue(run.stderr.strip().endswith("Answer (/talk opens claude, Enter stops the loop): the human is needed to answer the question above, but nothing was typed")) + self.assertNotIn("stray", run.calls[3]["stdin"]) def test_hands_the_terminal_over_and_exits_2_when_nothing_is_typed(self): checkout = Checkout(self) @@ -681,7 +679,7 @@ class Interrupt(unittest.TestCase): checkout.claude_json().chmod(0o644) asked = [worker(say="Shall I use A or B?"), judge(interrupt=True, evidence="Shall I use A or B?", question="A or B?")] (checkout.root / "sub").mkdir() - run = checkout.run([*asked, interrupt(type="B"), judge(evidence="B"), worker()], cwd=checkout.root / "sub", terminal_input="/talk\n") + run = checkout.run([*asked, interrupt(type="B"), judge(evidence="B"), worker()], cwd=checkout.root / "sub", terminal_input="/talk\n", before_typing=ANSWERING) self.assertEqual(run.code, 130) self.assertEqual(run.roles(), ["worker", "judge", "interrupt", "judge", "worker", "judge"]) handed = run.calls[2]["argv"] @@ -699,11 +697,11 @@ class Interrupt(unittest.TestCase): for transcript in checkout.transcripts(): transcript.unlink() - run = checkout.run([*asked, interrupt()], terminal_input="/talk\n") + run = checkout.run([*asked, interrupt()], terminal_input="/talk\n", before_typing=ANSWERING) self.assertEqual((run.code, run.roles()), (2, ["worker", "judge", "interrupt"])) self.assertTrue(run.stderr.strip().endswith("the human is needed to answer the question above, but the interrupt ended with nothing typed")) - run = checkout.run([worker(say="A or B?"), judge(interrupt=True, evidence="A or B?", question="A or B?", vanish=True)], terminal_input="/talk\n") + run = checkout.run([worker(say="A or B?"), judge(interrupt=True, evidence="A or B?", question="A or B?", vanish=True)], terminal_input="/talk\n", before_typing=ANSWERING) self.assertEqual((run.code, run.roles()), (1, ["worker", "judge"])) self.assertTrue(run.stderr.strip().endswith("could not start claude for the interrupt: No such file or directory")) @@ -723,14 +721,14 @@ class Interrupt(unittest.TestCase): checkout.claude_json().unlink(missing_ok=True) if text is not None: checkout.claude_json().write_text(text) - run = checkout.run(asked, terminal_input="/talk\n") + run = checkout.run(asked, terminal_input="/talk\n", before_typing=ANSWERING) self.assertEqual(run.code, 2) self.assertIn(f"could not read {checkout.claude_json()}: {said}\n", run.stderr) self.assertEqual(checkout.claude_json().read_text() if checkout.claude_json().exists() else None, text) trusted = json.dumps({"projects": {str(checkout.root): {"hasTrustDialogAccepted": True}}}) checkout.claude_json().write_text(trusted) - run = checkout.run(asked, terminal_input="/talk\n") + run = checkout.run(asked, terminal_input="/talk\n", before_typing=ANSWERING) self.assertNotIn(str(checkout.claude_json()), run.stderr) self.assertNotIn("trusted for the interrupt", run.stderr) self.assertEqual(checkout.claude_json().read_text(), trusted) @@ -743,7 +741,7 @@ class Interrupt(unittest.TestCase): checkout.run(asked[:2]) checkout.home.chmod(0o500) self.addCleanup(checkout.home.chmod, 0o700) - run = checkout.run([worker(), *asked[1:]], terminal_input="/talk\n") + run = checkout.run([worker(), *asked[1:]], terminal_input="/talk\n", before_typing=ANSWERING) self.assertEqual(run.code, 2) self.assertIn(f"could not write {checkout.claude_json()}: Permission denied\n", run.stderr) self.assertEqual(checkout.claude_json().read_text(), "{}") @@ -751,7 +749,7 @@ class Interrupt(unittest.TestCase): @unittest.skipIf(os.geteuid() == 0, "root reads an unreadable file") def test_exits_1_when_the_transcript_cannot_be_read_after_the_interrupt(self): checkout = Checkout(self) - run = checkout.run([worker(say="A or B?"), judge(interrupt=True, evidence="A or B?", question="A or B?"), interrupt(type="B", unreadable=True)], terminal_input="/talk\n") + run = checkout.run([worker(say="A or B?"), judge(interrupt=True, evidence="A or B?", question="A or B?"), interrupt(type="B", unreadable=True)], terminal_input="/talk\n", before_typing=ANSWERING) self.assertEqual((run.code, run.roles()), (1, ["worker", "judge", "interrupt"])) self.assertRegex(run.stderr.strip().splitlines()[-1], r"^could not tell whether you typed anything: could not read the transcript .*\.jsonl: Permission denied$") diff --git a/bin/loop_claude/test_loop_claude.py b/bin/loop_claude/test_loop_claude.py index e0a4d7b8..23346e03 100644 --- a/bin/loop_claude/test_loop_claude.py +++ b/bin/loop_claude/test_loop_claude.py @@ -61,6 +61,7 @@ class FakeEffects: return Effects( claude=lambda args, cwd, stdin: self.answer("claude", (args, stdin)), claude_on_terminal=self.on_terminal_claude, + discard_typed=lambda: self.calls.append(("discard_typed", None)), execv=self.execv, git=lambda args, cwd: self.answer("git", args), input=lambda prompt: self.answer("input", prompt), @@ -161,8 +162,10 @@ 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.HumanTalked(), states.Judging("/t")), - (states.Interrupting("/t", Interrupt("e", "q"), 3), states.HumanTalked(), states.Judging("/t", 3)), + (states.Interrupting("/t", Interrupt("e", "q")), states.TalkChosen(), states.Talking("/t")), + (states.Interrupting("/t", Interrupt("e", "q"), 3), states.TalkChosen(), states.Talking("/t", 3)), + (states.Talking("/t"), states.HumanTalked(), states.Judging("/t")), + (states.Talking("/t", 3), states.HumanTalked(), states.Judging("/t", 3)), (states.Interrupting("/t", Interrupt("e", "q")), states.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)), @@ -172,8 +175,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.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()) + every_state = (states.Working(), states.Working(QuotedAnswer("e", "Which one?", "A."), 3), states.Working(TYPED, 3), states.Judging("/t"), states.Judging("/t", 3), states.Interrupting("/t", Interrupt("e", "q")), states.Interrupting("/t", Interrupt("e", "q"), 3), states.Talking("/t"), states.Talking("/t", 3), states.Closing("/t", Finished("e")), states.Ended(Finished("e"))) + every_event = (states.WorkerRan("/t"), states.Ruled(Interrupt("e", "Which one?")), answered, states.Ruled(Finished("e")), states.Ruled(Unfinished("e")), states.TalkChosen(), states.HumanTalked(), states.HumanTyped(TYPED), states.Archived()) for state in every_state: for event in every_event: if (state, event) not in [(state, event) for state, event, _ in legal]: @@ -384,10 +387,13 @@ class Cycles(unittest.TestCase): self.assertEqual(fake.made("claude_on_terminal"), []) resumed = fake.made("stream_claude")[1] self.assertEqual(resumed[resumed.index("--resume") + 1], str(self.session.id)) - 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.") + typed = resumed[resumed.index("-p") + 1] + self.assertEqual(prompts.typed_answer(typed)[1], "Use B.") + self.assertIn("Which one?", typed) + self.assertIn("Continue the task. The chunk is finished only once every answer the human typed in it", typed) 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.assertNotIn("[loop] The human answered", judge_prompts[1]) + self.assertRegex(judge_prompts[1], r"(?s)\[loop\] Your question was: Which one\?.*\n\n\[human\] Use B\.\n\nworking\n\nDecide whether") + self.assertNotIn("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): fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 2, claude=[judged("interrupt", escalation="working"), judged("finished")], inputs=["Use B."]) @@ -397,7 +403,19 @@ class Cycles(unittest.TestCase): self.assertEqual(concluded.route, Route(Routing.OPUS, 179, 2, 5)) first, resumed = fake.made("stream_claude") self.assertEqual([args[args.index("--effort") + 1] for args in (first, resumed)], ["high", "medium"]) - 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.") + typed = resumed[resumed.index("-p") + 1] + self.assertIn("Your request for a higher rung went through: loop-claude runs you on claude-opus-5-5 at medium effort.", typed) + self.assertIn(" Launch each reviewer with the Agent tool set to model opus, effort high, the rung item 179's E + I of 5 picks.", typed) + self.assertNotIn("went through", first[first.index("-p") + 1]) + + def test_a_typed_answer_past_the_quoted_answers_cap_reaches_the_worker_with_its_own_question(self): + worker = Worker(self.paths.claude_code_transcripts.parent) + fake = FakeEffects(streams=[worker] * 5, claude=[judged("quoted", answer="Use A.")] * 4 + [judged("finished")], inputs=["Use B."]) + with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()): + self.assertEqual(run.run_cycle(self.cycle(fake, records="From AGENTS.md:\nUse A.")).verdict, Finished("working")) + typed = fake.made("stream_claude")[4] + self.assertIn("Your question was: Which one?\n\nContinue the task.", typed[typed.index("-p") + 1]) + self.assertNotIn("Those files have answered", typed[typed.index("-p") + 1]) def test_a_release_ready_to_cut_opens_claudes_session_without_asking_for_an_answer(self): def answer(args): @@ -513,27 +531,32 @@ class Limits(unittest.TestCase): class Interrupts(unittest.TestCase): - def test_puts_the_question_and_stops_off_a_terminal(self): - 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)): - with self.subTest(on_terminal=on_terminal): - fake = FakeEffects(on_terminal=on_terminal) - 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 put(self, fake, answer_here=True): + with contextlib.redirect_stderr(io.StringIO()) as said: + put = interrupt.put_question("Which one?", answer_here, fake.effects()) + return put, said.getvalue() - def test_reads_the_line_typed_at_the_terminal_stripped(self): - for typed, want in ((" Use B. ", "Use B."), (" /talk ", "/talk")): + 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"), "\nWhich one?\n")) + self.assertEqual(fake.calls, []) + + def test_returns_the_line_typed_after_the_question_stripped_dropping_what_was_typed_before(self): + fake = FakeEffects(inputs=[" Use B. "]) + self.assertEqual(self.put(fake), ("Use B.", "\nWhich one?\n")) + self.assertEqual(fake.calls, [("discard_typed", None), ("input", "Answer (/talk opens claude, Enter stops the loop): ")]) + + 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(interrupt.read_answer(fake.effects()), want) - self.assertEqual(fake.made("input"), ["Answer (/talk opens claude, Enter stops the loop): "]) + fake = FakeEffects(inputs=typed) + self.assertEqual(self.put(fake, answer_here)[0], interrupt.Talk()) + self.assertEqual(len(fake.made("input")), len(typed)) def test_stops_on_an_empty_answer_or_the_inputs_end(self): for typed, why, said in ((" ", "nothing was typed", ""), (EOFError(), "the input ended", "\n")): - with self.subTest(why=why), contextlib.redirect_stderr(io.StringIO()) as printed: - 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(printed.getvalue(), said) + with self.subTest(why=why): + self.assertEqual(self.put(FakeEffects(inputs=[typed])), (Stop(2, f"the human is needed to answer the question above, but {why}"), f"\nWhich one?\n{said}")) def test_stops_when_nothing_was_typed_in_the_session(self): with tempfile.TemporaryDirectory() as home: @@ -961,12 +984,14 @@ class PythonEffect(unittest.TestCase): class TypedAnswers(unittest.TestCase): - def test_finds_the_answer_on_the_line_after_the_marker_that_opens_the_prompt_handing_it_over_and_in_no_other_prompt(self): + def test_splits_the_prompt_handing_over_the_answer_into_the_answer_on_the_line_after_its_marker_and_the_rest_and_no_other_prompt(self): route = Route(Rung("worker-model")) 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.") + rest, answer = prompts.typed_answer(prompts.typed("Which one?", "Use B.", route, None, False)) + self.assertEqual(answer, "Use B.") + self.assertTrue(rest.startswith("Your question was: Which one?\n\nContinue the task.")) + self.assertEqual(prompts.typed_answer(prompts.typed(f"Which one?\n{marked}", "Use B.", route, None, False))[1], "Use B.") + self.assertEqual(prompts.typed_answer(prompts.typed("Which one?", "Use B.", Route(Routing.SONNET, 179, 2, 5), Routing.OPUS, True))[1], "Use B.") self.assertIsNone(prompts.typed_answer(prompts.answered("Which one?", marked, route, None, False))) self.assertIsNone(prompts.typed_answer(prompts.resumed(marked, route, None))) diff --git a/bin/stability_replay/test_stability_replay.py b/bin/stability_replay/test_stability_replay.py index d1012e4a..f854167f 100644 --- a/bin/stability_replay/test_stability_replay.py +++ b/bin/stability_replay/test_stability_replay.py @@ -213,7 +213,7 @@ class Main(unittest.TestCase): result = result if "api_error_status" in result else {"type": "result", "structured_output": {"found": [n + 1 for n in result["found"]]}} return subprocess.CompletedProcess(args, 0, json.dumps(result), "") - effects = Effects(claude=claude, claude_on_terminal=unused, execv=unused, git=system_effects().git, input=unused, local_time=unused, now=unused, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused) + effects = Effects(claude=claude, claude_on_terminal=unused, discard_typed=unused, execv=unused, git=system_effects().git, input=unused, local_time=unused, now=unused, on_terminal=unused, python=unused, sleep=unused, stream_claude=unused) out, err = io.StringIO(), io.StringIO() with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): code = main.main(argv, {}, self.home, effects) diff --git a/todo.md b/todo.md index d0b522e8..a6a023ed 100644 --- a/todo.md +++ b/todo.md @@ -6,7 +6,7 @@ `Bar = 0.1` -`Next ID = 181` +`Next ID = 183` ## Items @@ -39,7 +39,9 @@ | 173 | 0.3.0 | | | **Have rule-hook's `todo-rank-check` run a worktree's own `bin/rank_todo.py` when the worktree is of this repo, so a branch that changes `todo.md`'s shape commits without an override.** | 2 | 1 | 3 | 4 | 2 | 1.1 by 2, 1.4 by 2 | 5.5 | | 162 | 0.3.0 | | owner | **Script each step that 0.2.0's chunks repeated by hand and a program can compute, filing one item per step, and file this audit again for the next release.** | 2 | 2 | 1 | 3 | 3 | 1.4 by 4, 1.5 by 4 | 4.9 | | 175 | 0.3.0 | | | **Compare the first five chunks loop-claude starts with `chunk-preflight` against the five before them, and file an item where the preflight did not pay off.** | 1 | 2 | 1 | 2 | 2 | 1.4 by 3, 1.5 by 3 | 4.9 | +| 181 | 0.3.0 | | principle | **Have the test of a quoted answer's step-up assert the stepped rung's facts as literals, not through `prompts.rungs_held`.** | 1 | 1 | 1 | 1 | 1 | 1.1 by 2 | 4.4 | | 177 | 0.3.0 | | | **Move the next chunk's pick, from `LastCut` and `standing` to `chunk_item` and `default_plan`, into one module named for it, so `git_repo` only runs git and `todo_table` only parses the plan.** | 3 | 1 | 3 | 5 | 4 | 1.1 by 4 | 3.6 | +| 182 | 0.3.0 | | | **Give the answer line of loop-claude's interrupts line editing, so an arrow key moves the cursor instead of typing an escape code into the human's answer.** | 2 | 2 | 1 | 3 | 2 | 1.1 by 2 | 3.6 | | 171 | 0.3.0 | | decision | **Group the routing figures' review rounds by the reviewers' rung as well as the worker's, so a call blames a rung only for rounds its own reviews raised.** | 3 | 2 | 2 | 5 | 4 | 1.2 by 3, 1.4 by 3 | 3.2 | | 165 | 0.3.0 | | | **Make this repo's tests assert the facts a prompt or help text carries in place of its sentences, and drop the tests that scan source or assert a constant.** | 3 | 2 | 1 | 4 | 5 | 1.1 by 4, 1.4 by 3 | 3.0 | | 169 | 0.3.0 | | | **Have rule-hook's `todo-rank-check` catch a `todo.md` that the same Bash call edits and then commits.** | 3 | 1 | 3 | 5 | 3 | 1.1 by 2 | 2.7 | @@ -85,7 +87,7 @@ ### 180. Settle how a trigger that fires after a step-up at an interrupt or a quoted answer steps the worker, which today it never does. -`docs/decisions.md` → `routing: a worker whose run ends asking for a higher rung…` says a trigger that fires after the human's answer waits for the next cycle. Today it steps nothing: once an interrupt or a quoted answer has taken an escalation, `unspent` in `bin/loop_claude/cycle/run.py` drops the escalation of every later ruling of the cycle. The dropped request stays in the transcript, so in the next cycle the judge finds no trigger that fired since the worker's last request, and the worker cannot be stepped for it. Since a quoted answer resumes the worker headless up to three times a cycle, the loss is now reachable unattended. +`docs/decisions.md` → `routing: a worker whose run ends asking for a higher rung…` says a trigger that fires after the human's answer waits for the next cycle. Today it steps nothing: once an interrupt or a quoted answer has taken an escalation, `unspent` in `bin/loop_claude/cycle/run.py` drops the escalation of every later ruling of the cycle. The dropped request stays in the transcript, so in the next cycle the judge finds no trigger that fired since the worker's last request, and the worker cannot be stepped for it. A quoted answer resumes the worker headless up to three times a cycle, and an answer the human types on loop-claude's terminal resumes it headless in the same cycle too, so the loss is now reachable unattended. Options: @@ -215,6 +217,10 @@ The chunk that ships this item files a copy of it in the release after the one i Item 161 put `chunk-preflight`'s facts into a fresh worker's prompt, so the worker no longer finds them itself. Before that, in item 140's chunk, the worker spent 5 min 46 s of 30 min, 16 of its 68 messages and 226k of its 491k fresh tokens before its first edit, through 12 Bash and 5 Read calls. Measure those figures from loop-claude's archive, as medians over the first five chunks that started with the preflight and the five before them: one chunk is too noisy a baseline, as `docs/decisions.md` → `reading cost: a rise is …` records. Measure the counter-signals beside them: goal 1.4's review rounds and unfinished verdicts, and goal 1.5's 🔴 findings, per chunk, since a worker that reads less may start sooner and need more rounds or let more defects through. Where time or tokens did not fall, or a counter-signal rose, file an item naming the facts the workers still found by hand, or what the preflight got wrong. +### 181. Have the test of a quoted answer's step-up assert the stepped rung's facts as literals, not through `prompts.rungs_held`. + +`bin/loop_claude/test_loop_claude.py`'s `test_a_quoted_answer_that_cites_an_escalation_trigger_steps_the_worker_up_before_it_resumes_and_archives_the_step` builds its expected prompt from `prompts.rungs_held`, the code under test, so a bug there passes it. The technical principles' test bullet bans that shape. Assert the new rung and one review launch as literals, as the typed answer's step-up test does. Raised by the principles audit of PR #308. + ### 177. Move the next chunk's pick, from `LastCut` and `standing` to `chunk_item` and `default_plan`, into one module named for it, so `git_repo` only runs git and `todo_table` only parses the plan. Raised by PR #302's paired ruling, where two of four seats read the project as worse at these places. Item 161 put the pick in `bin/todo_table.py` (`Standing`, `LastCut`, `unreleased_entries`, `landed`, `named_releases`, `standing`, `chunk_item`) and its reader in `bin/git_repo.py` (`DefaultPlan`, `default_plan`, `todos_since`), so the git module now imports the plan model and the table parser decides how a release stands. Make each of those places easier to read: @@ -225,6 +231,10 @@ Raised by PR #302's paired ruling, where two of four seats read the project as w - `bin/loop_claude/loop/main.py` → `run_loop`: routing reads the plan as chunk-preflight's fetch left it, an order only a comment states. - `bin/chunk_preflight/gathered.py`: the name covers the data, not the pure choices it also holds. +### 182. Give the answer line of loop-claude's interrupts line editing, so an arrow key moves the cursor instead of typing an escape code into the human's answer. + +`bin/loop_claude/cycle/interrupt.py`'s `put_question` reads the answer with `input()`, and nothing under `bin/` imports `readline`, so Left types `^[[D` into the answer the worker gets. Importing `readline` gives line editing, but it writes the prompt to stdout rather than stderr, and its bracketed paste can return several lines, which `prompts.typed_answer` reads only the first of. Raised by the product-owner review of PR #308. + ### 171. Group the routing figures' review rounds by the reviewers' rung as well as the worker's, so a call blames a rung only for rounds its own reviews raised. Raised by the goals audit of PR #296. `bin/routing_figures/measure.py` groups a chunk's review rounds by the rung its worker started on, and calls for a routing change when a lower rung took more of them. Since PR #296 the reviewers may run above the worker's rung, on the one their item's E + I picks, and no figure groups rounds by it, though the archived worker line names the E + I it follows from. A cheap worker on an item of high E + I gets stronger reviewers, who may raise more rounds, and a call could then blame the worker's rung for them: an interrupt of lilleman that settles nothing (goal 1.2). From 3229045af9f74359849153a08c1d7c6eaf5d7853 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sat, 17 Oct 2026 23:32:21 +0200 Subject: [PATCH 05/15] =?UTF-8?q?Answer=20security=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=200=20=F0=9F=9F=A1;=20no=20finding?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit From 84e34b8e23a9dac08689d3ccc9ae84d72287af31 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sat, 17 Oct 2026 23:32:21 +0200 Subject: [PATCH 06/15] =?UTF-8?q?Answer=20stability=20round=201:=201=20?= =?UTF-8?q?=F0=9F=94=B4,=202=20=F0=9F=9F=A1;=20drop=20keys=20typed=20befor?= =?UTF-8?q?e=20the=20question,=20correct=20the=20interrupt's=20definition,?= =?UTF-8?q?=20assert=20the=20prompts'=20facts,=20and=20name=20the=20releas?= =?UTF-8?q?e's=20session=20in=20exit=202?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit From 2bb61f385a7375ec70aa56db76c11dfaaa894545 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sat, 17 Oct 2026 23:32:21 +0200 Subject: [PATCH 07/15] =?UTF-8?q?Answer=20product-owner=20round=201:=200?= =?UTF-8?q?=20=F0=9F=94=B4,=202=20=F0=9F=9F=A1;=20drop=20keys=20typed=20be?= =?UTF-8?q?fore=20the=20question,=20keeping=20a=20paste's=20later=20lines?= =?UTF-8?q?=20from=20answering=20the=20next=20one,=20correct=20the=20inter?= =?UTF-8?q?rupt's=20definition,=20and=20file=20line=20editing=20as=20item?= =?UTF-8?q?=20182?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit From c4a4f40aa66e9726ffce68fffa2da67e44297239 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sat, 17 Oct 2026 23:41:59 +0200 Subject: [PATCH 08/15] =?UTF-8?q?Answer=20architecture=20round=203:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=200=20=F0=9F=9F=A1;=20the=20architect=20approved?= =?UTF-8?q?=20the=20fix?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit From e7f544368890162514c8f1014c9142bf77d853ed Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sat, 17 Oct 2026 23:41:59 +0200 Subject: [PATCH 09/15] =?UTF-8?q?Answer=20principles=20round=202:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=200=20=F0=9F=9F=A1;=20name=20the=20typed=20answer?= =?UTF-8?q?'s=20two=20parts=20in=20Typed?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin/claude_code/test_claude_code.py | 2 +- bin/claude_code/transcript.py | 12 +++++++++--- bin/loop_claude/cycle/prompts.py | 7 ++++--- 3 files changed, 14 insertions(+), 7 deletions(-) diff --git a/bin/claude_code/test_claude_code.py b/bin/claude_code/test_claude_code.py index 4d436dc8..72d68d74 100644 --- a/bin/claude_code/test_claude_code.py +++ b/bin/claude_code/test_claude_code.py @@ -35,7 +35,7 @@ class Render(unittest.TestCase): queued("origin/main moved", "coordinator"), {**human("Continue the task; the previous run stopped before it was finished."), "promptSource": "sdk"}, {**human("Answered: use B\nYour question: A or B?"), "promptSource": "sdk"}, - ], lambda prompt: tuple(reversed(prompt.removeprefix("Answered: ").split("\n"))) if prompt.startswith("Answered: ") else None) + ], lambda prompt: transcript.Typed(*reversed(prompt.removeprefix("Answered: ").split("\n"))) if prompt.startswith("Answered: ") else None) self.assertEqual(said, '[human] do it\n\nStarting.\n\n[tool Bash] {"command": "ls"}\n\n[human] yes, merge it\n\n[human] B, while you work\n\n[loop] Continue the task; the previous run stopped before it was finished.\n\n[loop] Your question: A or B?\n\n[human] use B') diff --git a/bin/claude_code/transcript.py b/bin/claude_code/transcript.py index a14dd904..248d9535 100644 --- a/bin/claude_code/transcript.py +++ b/bin/claude_code/transcript.py @@ -7,6 +7,12 @@ from failure import Failure JUDGED_TOOL_INPUT = 400 +class Typed(typing.NamedTuple): + """A -p prompt of loop-claude's that carries an answer the human typed: loop-claude's words, and that answer.""" + loop_words: str + answer: str + + def read_transcript(path: str) -> list[dict] | Failure: try: with open(path, "rb") as handle: @@ -25,8 +31,8 @@ def human_turns(entries: list[dict]) -> int: return sum(1 for entry in entries if human_text(entry) is not None) -def render(entries: list[dict], typed_answer: typing.Callable[[str], tuple[str, str] | None]) -> str: - """The transcript as the judge reads it. typed_answer splits a -p prompt of loop-claude's that carries an answer the human typed into loop-claude's words and that answer, which reads as the human's, like one typed in claude.""" +def render(entries: list[dict], typed_answer: typing.Callable[[str], Typed | None]) -> str: + """The transcript as the judge reads it. typed_answer splits a -p prompt of loop-claude's that carries an answer the human typed, which reads as the human's, like one typed in claude.""" lines = [] for entry in entries: lines += [line for part in assistant_parts(entry) if (line := part_line(part, JUDGED_TOOL_INPUT))] @@ -34,7 +40,7 @@ def render(entries: list[dict], typed_answer: typing.Callable[[str], tuple[str, lines.append("[human] " + text) elif (text := loop_text(entry)) is not None: typed = typed_answer(text) - lines += ["[loop] " + text] if typed is None else ["[loop] " + typed[0], "[human] " + typed[1]] + lines += ["[loop] " + text] if typed is None else ["[loop] " + typed.loop_words, "[human] " + typed.answer] return "\n\n".join(lines) diff --git a/bin/loop_claude/cycle/prompts.py b/bin/loop_claude/cycle/prompts.py index 5ef9de49..9b769945 100644 --- a/bin/loop_claude/cycle/prompts.py +++ b/bin/loop_claude/cycle/prompts.py @@ -3,6 +3,7 @@ from model_routing.route import ESCALATION_MARKER, HIGHEST_ESCAPE_AND_IMPACT, Ro from loop_claude.routing import escalation_rungs from loop_claude.project.records import HUMAN_RULE_NAMES, RECORD_FILES from markdown_text import listed, quoted +from claude_code.transcript import Typed # Where the judge may quote an answer from, named as the human and the worker see them; of README.md the judge sees only the premises. QUOTE_SOURCES = listed(("README.md's Goals and Audience", *RECORD_FILES, *HUMAN_RULE_NAMES), "or") @@ -137,13 +138,13 @@ def typed(question: str, answer: str, route: Route, anchor: Rung | None, stepped TYPED_HERE = "The human answered your question at loop-claude's terminal:" -def typed_answer(prompt: str) -> tuple[str, str] | None: - """The rest of the prompt typed made, and the answer it put there, so the judge reads the answer as the human's; None for any other prompt.""" +def typed_answer(prompt: str) -> Typed | None: + """The answer typed put in prompt, and the rest of that prompt, so the judge reads the answer as the human's; None for any other prompt.""" opening = f"{TYPED_HERE}\n" if not prompt.startswith(opening): return None answer, _, rest = prompt.removeprefix(opening).partition("\n\n") - return rest, answer + return Typed(rest, answer) def stepped_to(route: Route, anchor: Rung | None, stepped: bool) -> str: From 1f380af695af85e0d6f51d2a7a5895a2d0fc968a Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sat, 17 Oct 2026 23:41:59 +0200 Subject: [PATCH 10/15] =?UTF-8?q?Answer=20stability=20round=202:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=201=20=F0=9F=9F=A1;=20drop=20keys=20typed=20befor?= =?UTF-8?q?e=20the=20question=20when=20a=20release=20ready=20to=20cut=20op?= =?UTF-8?q?ens=20claude=20too,=20and=20say=20where=20item=20182's=20paste?= =?UTF-8?q?=20ends?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bin/loop_claude/cycle/interrupt.py | 4 ++-- bin/loop_claude/test_loop_claude.py | 13 +++++++------ todo.md | 2 +- 3 files changed, 10 insertions(+), 9 deletions(-) diff --git a/bin/loop_claude/cycle/interrupt.py b/bin/loop_claude/cycle/interrupt.py index d73820f9..619d7927 100644 --- a/bin/loop_claude/cycle/interrupt.py +++ b/bin/loop_claude/cycle/interrupt.py @@ -27,10 +27,10 @@ def put_question(question: str, answer_here: bool, effects: Effects) -> str | Ta print(f"\n{question}", file=sys.stderr) if stop := needs_terminal(ANSWER_QUESTION, effects.on_terminal()): return stop + # Keys typed while the worker ran wait on the terminal, so they would answer a question no one has read, here or in claude's session, which reads them too. A paste's lines after the first are dropped with them at the next question, never taken as its answer; a longer answer goes through TALK. + effects.discard_typed() if not answer_here: return Talk() - # Keys typed while the worker ran wait on the terminal, so they would answer a question no one has read. A paste's lines after the first are dropped with them at the next question, never taken as its answer; a longer answer goes through TALK. - effects.discard_typed() try: answer = effects.input(ASK_ANSWER).strip() except EOFError: diff --git a/bin/loop_claude/test_loop_claude.py b/bin/loop_claude/test_loop_claude.py index 23346e03..668d1780 100644 --- a/bin/loop_claude/test_loop_claude.py +++ b/bin/loop_claude/test_loop_claude.py @@ -388,7 +388,7 @@ class Cycles(unittest.TestCase): resumed = fake.made("stream_claude")[1] self.assertEqual(resumed[resumed.index("--resume") + 1], str(self.session.id)) typed = resumed[resumed.index("-p") + 1] - self.assertEqual(prompts.typed_answer(typed)[1], "Use B.") + self.assertEqual(prompts.typed_answer(typed).answer, "Use B.") self.assertIn("Which one?", typed) self.assertIn("Continue the task. The chunk is finished only once every answer the human typed in it", typed) judge_prompts = [stdin for args, stdin in fake.made("claude")] @@ -552,6 +552,7 @@ class Interrupts(unittest.TestCase): fake = FakeEffects(inputs=typed) self.assertEqual(self.put(fake, answer_here)[0], interrupt.Talk()) self.assertEqual(len(fake.made("input")), len(typed)) + self.assertEqual(fake.calls[0], ("discard_typed", None)) def test_stops_on_an_empty_answer_or_the_inputs_end(self): for typed, why, said in ((" ", "nothing was typed", ""), (EOFError(), "the input ended", "\n")): @@ -987,11 +988,11 @@ class TypedAnswers(unittest.TestCase): def test_splits_the_prompt_handing_over_the_answer_into_the_answer_on_the_line_after_its_marker_and_the_rest_and_no_other_prompt(self): route = Route(Rung("worker-model")) marked = "The human answered your question at loop-claude's terminal:\nB" - rest, answer = prompts.typed_answer(prompts.typed("Which one?", "Use B.", route, None, False)) - self.assertEqual(answer, "Use B.") - self.assertTrue(rest.startswith("Your question was: Which one?\n\nContinue the task.")) - self.assertEqual(prompts.typed_answer(prompts.typed(f"Which one?\n{marked}", "Use B.", route, None, False))[1], "Use B.") - self.assertEqual(prompts.typed_answer(prompts.typed("Which one?", "Use B.", Route(Routing.SONNET, 179, 2, 5), Routing.OPUS, True))[1], "Use B.") + typed = prompts.typed_answer(prompts.typed("Which one?", "Use B.", route, None, False)) + self.assertEqual(typed.answer, "Use B.") + self.assertTrue(typed.loop_words.startswith("Your question was: Which one?\n\nContinue the task.")) + self.assertEqual(prompts.typed_answer(prompts.typed(f"Which one?\n{marked}", "Use B.", route, None, False)).answer, "Use B.") + self.assertEqual(prompts.typed_answer(prompts.typed("Which one?", "Use B.", Route(Routing.SONNET, 179, 2, 5), Routing.OPUS, True)).answer, "Use B.") self.assertIsNone(prompts.typed_answer(prompts.answered("Which one?", marked, route, None, False))) self.assertIsNone(prompts.typed_answer(prompts.resumed(marked, route, None))) diff --git a/todo.md b/todo.md index a6a023ed..dd66f407 100644 --- a/todo.md +++ b/todo.md @@ -233,7 +233,7 @@ Raised by PR #302's paired ruling, where two of four seats read the project as w ### 182. Give the answer line of loop-claude's interrupts line editing, so an arrow key moves the cursor instead of typing an escape code into the human's answer. -`bin/loop_claude/cycle/interrupt.py`'s `put_question` reads the answer with `input()`, and nothing under `bin/` imports `readline`, so Left types `^[[D` into the answer the worker gets. Importing `readline` gives line editing, but it writes the prompt to stdout rather than stderr, and its bracketed paste can return several lines, which `prompts.typed_answer` reads only the first of. Raised by the product-owner review of PR #308. +`bin/loop_claude/cycle/interrupt.py`'s `put_question` reads the answer with `input()`, and nothing under `bin/` imports `readline`, so Left types `^[[D` into the answer the worker gets. Importing `readline` gives line editing, but it writes the prompt to stdout rather than stderr, and its bracketed paste can return several lines, while `prompts.typed_answer` ends the answer at its first blank line and shows the judge what follows as loop-claude's words. Raised by the product-owner review of PR #308. ### 171. Group the routing figures' review rounds by the reviewers' rung as well as the worker's, so a call blames a rung only for rounds its own reviews raised. From d9fb90ee0313d42631ae6e697950f4a4da6fac8d Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sat, 17 Oct 2026 23:41:59 +0200 Subject: [PATCH 11/15] =?UTF-8?q?Answer=20product-owner=20round=202:=200?= =?UTF-8?q?=20=F0=9F=94=B4,=200=20=F0=9F=9F=A1;=20flush=20on=20both=20bran?= =?UTF-8?q?ches=20and=20correct=20item=20182's=20detail?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit From 2760c50915beea38cda92e9766254c5d24d2703c Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sat, 17 Oct 2026 23:45:45 +0200 Subject: [PATCH 12/15] =?UTF-8?q?Answer=20principles=20round=203:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=200=20=F0=9F=9F=A1;=20both=20auditors=20approved?= =?UTF-8?q?=20the=20fix?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit From 062af261d8ebf7e126f080cb111d8ede2282cca2 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sat, 17 Oct 2026 23:45:45 +0200 Subject: [PATCH 13/15] =?UTF-8?q?Answer=20stability=20round=203:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=200=20=F0=9F=9F=A1;=20the=20reviewer=20approved?= =?UTF-8?q?=20the=20fix?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit From 023380f5a571cbd2964216b207da6875c1a8f824 Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sat, 17 Oct 2026 23:55:59 +0200 Subject: [PATCH 14/15] =?UTF-8?q?Answer=20prose=20round=201:=200=20?= =?UTF-8?q?=F0=9F=94=B4,=2013=20=F0=9F=9F=A1;=20split=20the=20exit-2=20lin?= =?UTF-8?q?e,=20stop=20calling=20the=20claude=20session=20the=20interrupt,?= =?UTF-8?q?=20reword=20the=20interrupt's=20definition,=20the=20release=5Fr?= =?UTF-8?q?eady=20comment,=20the=20changelog=20and=20items=20180=20and=201?= =?UTF-8?q?82,=20and=20file=20items=20183=20and=20184?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 2 +- CLAUDE.md | 2 +- README.md | 2 +- bin/claude_code/transcript.py | 2 +- bin/claude_code/trust.py | 2 +- bin/loop_claude/cycle/interrupt.py | 4 ++-- bin/loop_claude/cycle/judge.py | 7 +++---- bin/loop_claude/cycle/prompts.py | 8 ++++---- bin/loop_claude/cycle/states.py | 4 ++-- bin/loop_claude/loop/main.py | 12 ++++++------ docs/decisions.md | 6 +++--- todo.md | 22 ++++++++++++++++------ 12 files changed, 41 insertions(+), 32 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d9d008a9..3024ff3a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ ## Unreleased -- `loop-claude` asks an interrupt's question on its own terminal and resumes the worker headless with your one-line answer, so the loop no longer waits for you to leave a claude session. Type `/talk` instead to open the worker's session in claude, as every interrupt did before, to read the diff or discuss first. A release ready to cut opens that session at once. Pressing Enter on an empty answer stops the loop, exit 2. The judge reads your answer as typed by you, so the chunk stays open until the worker records it. +- `loop-claude` asks an interrupt's question on its own terminal and resumes the worker headless with your one-line answer, so the loop no longer waits for you to leave a claude session. Type `/talk` instead to open the worker's session in claude, as every interrupt did before, to read the diff or discuss first. A release ready to cut opens that session at once. Pressing Enter on an empty answer stops the loop, exit 2. Keys typed before the question shows are dropped, and a pasted answer keeps only its first line; type `/talk` for a longer one. The judge counts that answer as yours, like one typed in claude: the chunk stays open until the answer is recorded, where a later chunk could need it. - When a worker's run ends with a question and a request for a higher rung, `loop-claude` now steps the worker one rung up as the judge interrupts, or as it answers the question with a quote from `README.md` or another file it may quote. The judge must quote a passage showing that the escalation trigger the run cites fired. Before, the step was lost for an answered question, and the worker carried on from the answer on its old rung. The step has the same limits as the step on an unfinished verdict, and no later ruling of that cycle carries a second escalation. The archive's interrupt and quoted-answer outcomes now name the worker's rung. - A scoring run due because a release's items ran out costs four more seats: it is done twice on one head. `larv-review agreement` compares how often Mid A and the inherited architect vote alike in paired rulings with how often their overall scores move the same way between the two runs. After 10 such pairs it gives a verdict, and on `Assumption fails:` larv-review asks you whether to keep the paired ruling. - `workflow-bench/bench.py` gives each run a fixed list of allowed tools. Before, it skipped every permission check. A run may launch agents, run `/security-review`, edit its clone (not the clone's `.git/` or `.claude/`) and its report, and read its clone and the copy of `~/.claude` it benches. For git it gets one command, `workflow-bench/review_git.py`, and no bare `git`. The wrapper runs `log`, `diff`, `show`, `status`, `ls-files`, `add` and `commit -m` on the run's clone, whatever the working directory. It allows only the options it lists for each, and refuses an argument that names a path outside the clone. git runs with no global or system config, hook, pager or editor. A run loads no settings or MCP servers from `~/.claude` or from the case's clone, so their hooks and extra directories do not apply to it. Every other call is denied. Expect a benched review that needs another git command, or to run a project's code or tests, to say in its report that it could not. diff --git a/CLAUDE.md b/CLAUDE.md index 360357df..727e162d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -96,7 +96,7 @@ The rules only reviewers apply, for quality, comments, READMEs and prose, live i - **chunk** — the unit of work, shipped as one PR; "Working loop" says what it holds. - **cycle** — in `loop-claude`, worker runs and the judge's verdict on each, until the chunk closes or is left for the next cycle. In between, the human answers any interrupt, or the worker resumes with an answer the judge quoted from `README.md`, `AGENTS.md`, `docs/decisions.md`, `~/.claude/CLAUDE.md`, `~/.claude/rules/` or `~/.claude/skills/larv-review/standards/`. - **gate** — the merge gate: the checks a PR passes before it merges. -- **interrupt** — `loop-claude` asking the human, on its terminal, for a decision that is theirs; typing `/talk` there, or a release ready to cut, opens the worker's session with `claude --resume`. +- **interrupt** — `loop-claude` asking the human, on its terminal, for a decision that is theirs. They type a one-line answer, or `/talk` to open the worker's session with `claude --resume`; a release ready to cut opens that session at once, and a routing call opens claude in `~/.claude`. - **judge** — the headless claude that reads a worker's transcript each cycle and decides whether to interrupt and whether the chunk is finished. - **pass** — one kind of review a chunk may take, run in rounds by its reviewers until clean; `larv-review` §3 lists them. - **plan** — `todo.md`. diff --git a/README.md b/README.md index 09c872b4..bed8b534 100644 --- a/README.md +++ b/README.md @@ -54,7 +54,7 @@ claude plugin install code-review@claude-plugins-official claude plugin install rust-analyzer-lsp@claude-plugins-official ``` -Link `loop-claude` onto `PATH`: `ln -s ~/.claude/bin/loop-claude ~/.local/bin/loop-claude`. Run `loop-claude` only in a sandbox with no direct access to a production environment, such as a dedicated VM: every claude it starts, the interrupt included, skips every permission prompt. +Link `loop-claude` onto `PATH`: `ln -s ~/.claude/bin/loop-claude ~/.local/bin/loop-claude`. Run `loop-claude` only in a sandbox with no direct access to a production environment, such as a dedicated VM: every claude it starts, the interactive ones included, skips every permission prompt. ## Update diff --git a/bin/claude_code/transcript.py b/bin/claude_code/transcript.py index 248d9535..e7e8b984 100644 --- a/bin/claude_code/transcript.py +++ b/bin/claude_code/transcript.py @@ -32,7 +32,7 @@ def human_turns(entries: list[dict]) -> int: def render(entries: list[dict], typed_answer: typing.Callable[[str], Typed | None]) -> str: - """The transcript as the judge reads it. typed_answer splits a -p prompt of loop-claude's that carries an answer the human typed, which reads as the human's, like one typed in claude.""" + """The transcript as the judge reads it. typed_answer splits the answer the human typed out of a -p prompt of loop-claude's, so that answer reads as the human's, like one typed in claude.""" lines = [] for entry in entries: lines += [line for part in assistant_parts(entry) if (line := part_line(part, JUDGED_TOOL_INPUT))] diff --git a/bin/claude_code/trust.py b/bin/claude_code/trust.py index a6d5bb2a..de8e0b32 100644 --- a/bin/claude_code/trust.py +++ b/bin/claude_code/trust.py @@ -6,7 +6,7 @@ from failure import Failure from file_writes import replace_json -# A failure only warns: the interrupt still runs, and the human answers Claude Code's trust dialog. +# A failure only warns: claude still opens, and the human answers Claude Code's trust dialog. def trust(config: pathlib.Path, roots: list[str]) -> None: try: with open(config, encoding="utf-8") as handle: diff --git a/bin/loop_claude/cycle/interrupt.py b/bin/loop_claude/cycle/interrupt.py index 619d7927..d5d2b455 100644 --- a/bin/loop_claude/cycle/interrupt.py +++ b/bin/loop_claude/cycle/interrupt.py @@ -12,7 +12,7 @@ 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 and ASK_ANSWER were picked on 2026-10-17 by a bench of three readers seated as the README's audience, as ~/.claude/CLAUDE.md → "Working loop" → "Bench a syntax with the people who write it." has it. TALK = "/talk" ASK_ANSWER = f"Answer ({TALK} opens claude, Enter stops the loop): " @@ -27,7 +27,7 @@ def put_question(question: str, answer_here: bool, effects: Effects) -> str | Ta print(f"\n{question}", file=sys.stderr) if stop := needs_terminal(ANSWER_QUESTION, effects.on_terminal()): return stop - # Keys typed while the worker ran wait on the terminal, so they would answer a question no one has read, here or in claude's session, which reads them too. A paste's lines after the first are dropped with them at the next question, never taken as its answer; a longer answer goes through TALK. + # Keys typed while the worker ran wait on the terminal, and would answer a question no one has read, here or in claude's session, which reads them too. Of a pasted answer, input takes the first line; the rest wait, and the next question drops them. A longer answer goes through TALK. effects.discard_typed() if not answer_here: return Talk() diff --git a/bin/loop_claude/cycle/judge.py b/bin/loop_claude/cycle/judge.py index 605ab253..5c64ea92 100644 --- a/bin/loop_claude/cycle/judge.py +++ b/bin/loop_claude/cycle/judge.py @@ -19,7 +19,6 @@ 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 -# 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 " @@ -72,8 +71,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: 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."}) + # True opens claude's session at once, in place of the one-line answer (run.ask). The judge decides it, since loop-claude computes the plan's standing (todo_table.chunk_item) only when it routes a chunk on the ladder afresh: it would miss a release ready to cut in a resumed chunk or off the ladder. A wrong ruling costs the human one typed /talk, or answering in claude, which stops the loop if they leave it with nothing typed. + release_ready: bool = dataclasses.field(metadata={"description": "With interrupt true, whether the question is about a release ready to cut, which only the human may publish. False otherwise."}) REPLY_TYPES = typing.get_type_hints(Reply) @@ -178,7 +177,7 @@ 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. 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; + - the evidence, against shown (the transcript as the judge saw it), its fragments 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. diff --git a/bin/loop_claude/cycle/prompts.py b/bin/loop_claude/cycle/prompts.py index 9b769945..bbc638d9 100644 --- a/bin/loop_claude/cycle/prompts.py +++ b/bin/loop_claude/cycle/prompts.py @@ -130,16 +130,16 @@ 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: - """Resumes the worker with the human's answer to an interrupt. answer is one line, as the terminal reads it.""" + """The prompt that resumes the worker with the human's answer to an interrupt. answer is one line, as the terminal reads it.""" return f"{TYPED_HERE}\n{answer}\n\nYour question was: {question}\n\nContinue the task. The chunk is finished only once {ANSWERS_RECORDED}.{stepped_to(route, anchor, stepped)}" -# Opens typed's prompt, and the answer is the line after it, so typed_answer reads the answer from the prompt's start alone. +# Opens typed's prompt, with the answer on the line after it, so typed_answer finds the answer at the prompt's start, whatever the question holds. TYPED_HERE = "The human answered your question at loop-claude's terminal:" def typed_answer(prompt: str) -> Typed | None: - """The answer typed put in prompt, and the rest of that prompt, so the judge reads the answer as the human's; None for any other prompt.""" + """Splits a prompt from typed() into its answer and the rest, so the judge reads the answer as the human's; None for any other prompt.""" opening = f"{TYPED_HERE}\n" if not prompt.startswith(opening): return None @@ -148,7 +148,7 @@ def typed_answer(prompt: str) -> Typed | 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.""" + """The sentences naming the worker's new rung, as resumed has them, where the ruling that brought the answer stepped the worker up; empty otherwise.""" 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 "" diff --git a/bin/loop_claude/cycle/states.py b/bin/loop_claude/cycle/states.py index 05227e67..aec4349b 100644 --- a/bin/loop_claude/cycle/states.py +++ b/bin/loop_claude/cycle/states.py @@ -74,12 +74,12 @@ class HumanTyped: @dataclasses.dataclass(frozen=True) class TalkChosen: - """The human typed /talk, or the question is a release ready to cut, which only the human may cut.""" + """The human typed /talk, or the interrupt is for a release ready to cut.""" @dataclasses.dataclass(frozen=True) class HumanTalked: - """The human typed in the interrupt's claude session.""" + """The human typed in the worker's claude session.""" @dataclasses.dataclass(frozen=True) diff --git a/bin/loop_claude/loop/main.py b/bin/loop_claude/loop/main.py index 22e2cd07..477f6763 100644 --- a/bin/loop_claude/loop/main.py +++ b/bin/loop_claude/loop/main.py @@ -24,7 +24,7 @@ A question only the human can answer is an interrupt (bin/loop_claude/cycle/inte loop-claude prints the question and reads a one-line answer on its terminal. The worker resumes headless with the answer. The judge reads it as the human's, so the chunk stays unfinished until the answer is recorded. An empty answer stops the loop. Typing /talk instead opens the worker's session -on the terminal with `claude --resume`, to read the diff or discuss first; once that claude exits, +on the terminal with `claude --resume`, to read the diff or discuss first. Once that claude exits, the judge rules on what was typed there. A release ready to cut opens that session at once, since only the human may cut it. Before claude opens, the checkout and each of its worktrees are marked trusted in ~/.claude.json. @@ -52,12 +52,12 @@ rewrote lands beside its copy as .. Every claude loop-claude starts runs the project's model, saved per in ~/.claude/loop-claude-models.json and read each cycle, unless routing, below, puts the worker, -the interrupt and the judge on another rung; a project without an entry, as on its first +the session /talk opens and the judge on another rung; a project without an entry, as on its first run, is asked for one. LOOP_CLAUDE_JUDGE_MODEL overrides it for the judge, LOOP_CLAUDE_WORKER_MODEL -for the worker and the interrupt; with both set, nothing is asked. +for the worker and the session /talk opens; with both set, nothing is asked. Where that model is on the routing ladder (bin/model_routing/ladder.py), the worker and the -interrupt run on one of the ladder's rungs: a model at an effort. As a chunk starts, it is routed +session /talk opens run on one of the ladder's rungs: a model at an effort. As a chunk starts, it is routed on the item chunk-preflight names, read from todo.md on the default branch as the preflight just fetched it (todo_table.chunk_item). That item is the earliest release's top item that does not wait, but only where that release is the next one: the earliest after the newest vX.Y.Z tag that todo.md @@ -153,8 +153,8 @@ Exit 1, saying why, when: Exit 2, when the human is needed and cannot answer: - stdin or stdout is not a terminal, when a model must be picked or an interrupt answered - the input ends while a model is picked -- an interrupt's answer is empty or the input ends, or the claude opened for /talk or a release - ready to cut ends with nothing typed +- an interrupt's answer is empty, or the input ends before one is typed +- the claude opened for /talk, or for a release ready to cut, ends with nothing typed Rerunning resumes any open session. """ diff --git a/docs/decisions.md b/docs/decisions.md index 0c15e7c4..7c561df5 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -36,7 +36,7 @@ 2026-09-30, lilleman: Claude Code owns and writes that file, so `loop-claude` is to move out of it, bringing each case that must stay to the human. Stands until `todo.md` item 6 ends it. -2026-10-17, implementing todo item 168: the human answers an interrupt on loop-claude's own terminal, so claude opens on the terminal only when they type `/talk`, for a release ready to cut, and for the routing calls; the trust is marked only then. +2026-10-17, implementing todo item 168: the human answers an interrupt on loop-claude's own terminal. claude now opens on the terminal only for `/talk`, a release ready to cut and the routing calls, and the trust is marked only then. ## bin/: the tests rerun themselves on a `uv`-fetched Python at README Install's floor @@ -116,7 +116,7 @@ Valid while the ladder orders its rungs by competence. ## loop-claude: every claude it starts bypasses permissions inside its sandbox -2026-09-30, lilleman. Applies "Always grant explicit access to data": the sandbox `loop-claude` runs in is where access is granted, so the worker and the interrupt run with `bypassPermissions`. The worker may read `~/.claude/.credentials.json`: it holds Claude Code's own credentials, which claude reads to run anyway. Its one seam to production is the forge: what it pushes or merges can publish through CI. Valid while `loop-claude` runs only in the sandbox README → Install names. +2026-09-30, lilleman. Applies "Always grant explicit access to data": the sandbox `loop-claude` runs in is where access is granted, so the worker and the claude an interrupt opens run with `bypassPermissions`. The worker may read `~/.claude/.credentials.json`: it holds Claude Code's own credentials, which claude reads to run anyway. Its one seam to production is the forge: what it pushes or merges can publish through CI. Valid while `loop-claude` runs only in the sandbox README → Install names. ## review: `/security-review` is the security pass of record, except where the full scan runs on the same change and replaces it @@ -292,7 +292,7 @@ Valid while the ladder orders its rungs by competence. 2026-10-15, lilleman asked for it. Serves goals 1.1 and 1.4: when the hard part is the rest of the chunk, handing it to subagents piece by piece leaves the worker, which reads and checks each of their diffs, on a rung that proved too low. The worker climbs only once its run records a trigger. -loop-claude's prompt offers the step beside the escalated subagent of `routing: a worker hands a task one rung up`, as long as the limit leaves a rung that subagent may take without the human's yes. The worker then ends its run asking loop-claude for a higher rung and naming the trigger. The judge quotes an earlier passage that shows the trigger fired, such as a review round's commit title or the worker's report of the failing test, never the request itself. The trigger must have fired since any earlier such request, so one trigger buys one step. The judge sees the worker's text and tool calls but no tool results, so the quote shows that the run recorded the trigger, not that a tool's output bears it out. loop-claude checks the quote word for word, as it checks a quoted answer, since stitched fragments can make up a trigger. Without such a quote, the rung holds. A misquote is no failure, since holding the rung is safe and three failures stop an unattended loop. The next cycle's prompt names the worker's rung, so the worker learns whether the step went through. A worker that a quoted answer, or an interrupt the human answers on loop-claude's terminal, stepped up learns it sooner, from the prompt that resumes it with the answer. +loop-claude's prompt offers the step beside the escalated subagent of `routing: a worker hands a task one rung up`, as long as the limit leaves a rung that subagent may take without the human's yes. The worker then ends its run asking loop-claude for a higher rung and naming the trigger. The judge quotes an earlier passage that shows the trigger fired, such as a review round's commit title or the worker's report of the failing test, never the request itself. The trigger must have fired since any earlier such request, so one trigger buys one step. The judge sees the worker's text and tool calls but no tool results, so the quote shows that the run recorded the trigger, not that a tool's output bears it out. loop-claude checks the quote word for word, as it checks a quoted answer, since stitched fragments can make up a trigger. Without such a quote, the rung holds. A misquote is no failure, since holding the rung is safe and three failures stop an unattended loop. The next cycle's prompt names the worker's rung, so the worker learns whether the step went through. When a quoted answer, or an interrupt the human answers on loop-claude's terminal, steps the worker up, the prompt that resumes it with the answer names the new rung, so the worker learns of the step sooner. A run that asks for a higher rung may also ask a question. The judge then interrupts, or quotes the answer from README.md or the records, and either ruling carries the escalation quote too, checked the same way. loop-claude steps the rung as the ruling comes in, before the human is asked or the worker resumes with the quoted answer, since the work after the answer is work the stepped rung should do. An interrupt or a quoted answer is no unfinished verdict, so it adds to no count. The judge may quote a different passage for the trigger that already stepped the rung, and loop-claude cannot tell that from a new trigger. So once an interrupt or a quoted answer has taken an escalation, no later ruling of that cycle carries one. A trigger that fires after the answer steps nothing in that cycle. diff --git a/todo.md b/todo.md index dd66f407..e7e9ca39 100644 --- a/todo.md +++ b/todo.md @@ -6,7 +6,7 @@ `Bar = 0.1` -`Next ID = 183` +`Next ID = 185` ## Items @@ -41,10 +41,12 @@ | 175 | 0.3.0 | | | **Compare the first five chunks loop-claude starts with `chunk-preflight` against the five before them, and file an item where the preflight did not pay off.** | 1 | 2 | 1 | 2 | 2 | 1.4 by 3, 1.5 by 3 | 4.9 | | 181 | 0.3.0 | | principle | **Have the test of a quoted answer's step-up assert the stepped rung's facts as literals, not through `prompts.rungs_held`.** | 1 | 1 | 1 | 1 | 1 | 1.1 by 2 | 4.4 | | 177 | 0.3.0 | | | **Move the next chunk's pick, from `LastCut` and `standing` to `chunk_item` and `default_plan`, into one module named for it, so `git_repo` only runs git and `todo_table` only parses the plan.** | 3 | 1 | 3 | 5 | 4 | 1.1 by 4 | 3.6 | -| 182 | 0.3.0 | | | **Give the answer line of loop-claude's interrupts line editing, so an arrow key moves the cursor instead of typing an escape code into the human's answer.** | 2 | 2 | 1 | 3 | 2 | 1.1 by 2 | 3.6 | +| 182 | 0.3.0 | | | **Let the human edit an interrupt's answer with the arrow keys, so Left moves the cursor instead of typing ^[[D into the answer.** | 2 | 2 | 1 | 3 | 2 | 1.1 by 2 | 3.6 | | 171 | 0.3.0 | | decision | **Group the routing figures' review rounds by the reviewers' rung as well as the worker's, so a call blames a rung only for rounds its own reviews raised.** | 3 | 2 | 2 | 5 | 4 | 1.2 by 3, 1.4 by 3 | 3.2 | | 165 | 0.3.0 | | | **Make this repo's tests assert the facts a prompt or help text carries in place of its sentences, and drop the tests that scan source or assert a constant.** | 3 | 2 | 1 | 4 | 5 | 1.1 by 4, 1.4 by 3 | 3.0 | | 169 | 0.3.0 | | | **Have rule-hook's `todo-rank-check` catch a `todo.md` that the same Bash call edits and then commits.** | 3 | 1 | 3 | 5 | 3 | 1.1 by 2 | 2.7 | +| 183 | 0.3.0 | | | **Merge the two 2026-10-13 paragraphs of `docs/decisions.md` → `loop-claude: a judge decides each interrupt …` into one.** | 1 | 1 | 1 | 1 | 1 | 1.1 by 1 | 2.2 | +| 184 | 0.3.0 | | | **Rewrap the lines of `loop-claude --help` that run past the column the rest of it wraps at.** | 1 | 1 | 1 | 1 | 1 | 1.1 by 1 | 2.2 | | 174 | 0.3.0 | | | **In a chunk no item routed, ask the worker to name each todo.md item it takes, with its L and E + I, so loop-claude can route on an item it takes in.** | 1 | 2 | 3 | 4 | 2 | 1.1 by 1 | 1.8 | | 122 | 0.4.0 | | | **Assemble the judge's prompt in `bin/loop_claude/cycle/judge.py`, importing only wording the worker also sees, and call the worker "the worker" in it.** | 2 | 2 | 3 | 5 | 3 | 1.1 by 5, 1.4 by 5 | 10.3 | | 158 | 0.4.0 | | decision | **Measure the fixed cost of a chunk from loop-claude's archive, in tokens and hours against its items' S, and set F in `Score = 100 * V / (2**S + F)` to it.** | 2 | 2 | 1 | 3 | 3 | 1.1 by 5, 1.4 by 5 | 10.3 | @@ -87,7 +89,7 @@ ### 180. Settle how a trigger that fires after a step-up at an interrupt or a quoted answer steps the worker, which today it never does. -`docs/decisions.md` → `routing: a worker whose run ends asking for a higher rung…` says a trigger that fires after the human's answer waits for the next cycle. Today it steps nothing: once an interrupt or a quoted answer has taken an escalation, `unspent` in `bin/loop_claude/cycle/run.py` drops the escalation of every later ruling of the cycle. The dropped request stays in the transcript, so in the next cycle the judge finds no trigger that fired since the worker's last request, and the worker cannot be stepped for it. A quoted answer resumes the worker headless up to three times a cycle, and an answer the human types on loop-claude's terminal resumes it headless in the same cycle too, so the loss is now reachable unattended. +`docs/decisions.md` → `routing: a worker whose run ends asking for a higher rung…` says a trigger that fires after the human's answer waits for the next cycle. Today it steps nothing: once an interrupt or a quoted answer has taken an escalation, `unspent` in `bin/loop_claude/cycle/run.py` drops the escalation of every later ruling of the cycle. The dropped request stays in the transcript, so in the next cycle the judge finds no trigger that fired since the worker's last request, and the worker cannot be stepped for it. A quoted answer resumes the worker headless up to three times a cycle, and an answer the human types at loop-claude's terminal resumes it headless too. So the loss is now reachable with no one watching the session. Options: @@ -231,9 +233,9 @@ Raised by PR #302's paired ruling, where two of four seats read the project as w - `bin/loop_claude/loop/main.py` → `run_loop`: routing reads the plan as chunk-preflight's fetch left it, an order only a comment states. - `bin/chunk_preflight/gathered.py`: the name covers the data, not the pure choices it also holds. -### 182. Give the answer line of loop-claude's interrupts line editing, so an arrow key moves the cursor instead of typing an escape code into the human's answer. +### 182. Let the human edit an interrupt's answer with the arrow keys, so Left moves the cursor instead of typing ^[[D into the answer. -`bin/loop_claude/cycle/interrupt.py`'s `put_question` reads the answer with `input()`, and nothing under `bin/` imports `readline`, so Left types `^[[D` into the answer the worker gets. Importing `readline` gives line editing, but it writes the prompt to stdout rather than stderr, and its bracketed paste can return several lines, while `prompts.typed_answer` ends the answer at its first blank line and shows the judge what follows as loop-claude's words. Raised by the product-owner review of PR #308. +`bin/loop_claude/cycle/interrupt.py`'s `put_question` reads the answer with `input()`, and nothing under `bin/` imports `readline`, so Left types `^[[D` into the answer the worker gets. Importing `readline` gives line editing, at two costs. It writes the prompt to stdout, not stderr. And its bracketed paste can return several lines, while `prompts.typed_answer` ends the answer at its first blank line and shows the judge the rest as loop-claude's words. Raised by the product-owner review of PR #308. ### 171. Group the routing figures' review rounds by the reviewers' rung as well as the worker's, so a call blames a rung only for rounds its own reviews raised. @@ -247,6 +249,14 @@ A test audit across lilleman's projects on 2026-10-16 found 10 of 33 sampled tes The hook judges a call before it runs, and `changed` in `bin/rule_hook/todo_check.py` compares `todo.md` with the index and HEAD as they stand then. A call that edits `todo.md` and commits it, such as a heredoc script followed by `git commit`, passes unchecked: PR #296's commit 149108e did, and the override marker it carried was never logged. larv-review's gate still runs `rank_todo.py --check`, so an unranked plan stops at merge rather than at commit. A git pre-commit hook would see the staged file. +### 183. Merge the two 2026-10-13 paragraphs of `docs/decisions.md` → `loop-claude: a judge decides each interrupt …` into one. + +They say the same thing for `~/.claude/rules/` (item 95) and `~/.claude/skills/larv-review/standards/` (item 104), and the entry grows a paragraph per chunk. Raised by the prose review of PR #308. + +### 184. Rewrap the lines of `loop-claude --help` that run past the column the rest of it wraps at. + +In `bin/loop_claude/loop/main.py`'s docstring, the line holding "of one PR, is finished" and the one ending "Each of these opens with its UTC time." run to 107 and 159 columns. Raised by the prose review of PR #308. + ### 174. In a chunk no item routed, ask the worker to name each todo.md item it takes, with its L and E + I, so loop-claude can route on an item it takes in. The principles pass of PR #301 found that only `routed_by` in `bin/loop_claude/cycle/prompts.py` asks the worker to name each item it takes with its L and E + I, and `fresh` uses it only where an item routed the chunk. In an unrouted chunk the judge has no levels to report, so neither the taken-in L nor the taken-in E + I lifts the worker, the reviewers or the judge, and the first prompt names no reviewers' rung for a higher E + I. @@ -425,7 +435,7 @@ Claude's answers overlapped the truth by a median Jaccard index of 0.76. A run t ### 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`: `archive`, `trust`, `retried`, the worker, `interrupt` and `model_choice` print to stderr themselves, and the tests swap the global stream. +"Functional core, imperative shell", in `principles/technical-principles.md`: `archive`, `trust`, `retried`, the worker, `put_question` and `model_choice` print to stderr themselves, and the tests swap the global stream. ### 151. Keep 10 to 20 settled decisions per project as its goals' test set, and rerun them after a goal changes. From dbaf32fc74acb4292fec054c8c233b38d0757f1e Mon Sep 17 00:00:00 2001 From: Lilleman auf Larv Date: Sun, 18 Oct 2026 00:03:24 +0200 Subject: [PATCH 15/15] Record the comprehension check: paired ruling worse against 59344de --- docs/comprehension-history.md | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/docs/comprehension-history.md b/docs/comprehension-history.md index 7cdbd893..abef9f05 100644 --- a/docs/comprehension-history.md +++ b/docs/comprehension-history.md @@ -2119,3 +2119,25 @@ Inherited architect, decided by: - Locality: `skills/larv-review/SKILL.md:118` "Second run" and `bin/larv_review/plan.py:22` `scoring_run_due`: the second run keys on the exact wording of a reason string, with no test or import linking the two - Locality: `bin/larv_review/agreement.py:10` `overall_cells`: the last cell means overall only through `table_rows`' first-row-wins rule and the pre-#232 `Vote` table, described at `comprehension_history.py:82` - Locality: `bin/larv_review/main.py:81` `__doc__`: the help hard-codes 10 pairs where `MIN_PAIRS` holds the number + +## 2026-10-17T22:03:15Z, PR #308 at 023380f, against 59344de + +Ruling: worse + +| Seat | Navigation | Locality | Shape | Self-sufficiency | Overall | +|---|---|---|---|---|---| +| Mid A | same | worse | same | same | worse | +| Inherited architect | same | worse | worse | same | worse | + +Mid A, decided by: + +- Locality, Overall: `bin/loop_claude/cycle/run.py:43` `Cycle.stepped_from` and `escalated`: the cycle carries route state outside its state machine, which `escalated` rewrites before every transition, keeping `stepped_from` only through `HumanTyped`, so `ask`, `keep_answer` and `worker_start` trust the event before them +- Locality: `bin/loop_claude/cycle/run.py:156` `unspent`: whether a verdict keeps its escalation depends on `escalation_spent`, set by an earlier ruling of the cycle; escalation now spans `escalated`, `unspent` and `loop/main.py`'s step from `concluded.route` +- Locality: `bin/loop_claude/cycle/prompts.py:132` `typed` / `typed_answer`: the typed answer is written into a prompt and parsed back out of the transcript, and `render` takes a callback the generic `claude_code` module cannot make sense of alone + +Inherited architect, decided by: + +- Locality, Overall: `bin/loop_claude/cycle/run.py:71` `escalated`: the route now also changes inside a cycle, through two fields kept out of the state machine; "why did the worker resume on this rung" spans `escalated`, `unspent`, `routing.stepped_by_ruling`, `after_verdict` and two archive-the-step sites +- Locality: `bin/loop_claude/cycle/prompts.py:138` `TYPED_HERE` / `typed_answer`: the resume prompt doubles as a data channel back to the judge, resting on `typed`'s layout, the blank-line partition and `put_question` returning one line, in three modules linked only by a comment +- Shape: `bin/loop_claude/routing.py:80` `stepped_from`: returns the stepped route, while `Cycle.stepped_from` holds the route before the step; `escalated` is likewise a function, a bool parameter and a local string +- Shape: `bin/loop_claude/cycle/judge.py:95` `Interrupt`: shares `escalation` and `bundled` with `Unfinished` in the opposite positional order, and both are built positionally