Archive the route as a JSON record, hand routing the verdict, and name after_unfinished and the judge's highest levels taken in by what they do

This commit is contained in:
2026-10-22 21:46:36 +02:00
parent 0782ac6721
commit 851d7d7c79
15 changed files with 334 additions and 302 deletions
+1 -1
View File
@@ -6,7 +6,7 @@ import typing
from transcript_archive.outcomes import ANSWERED, FINISHED, first_verdict, INTERRUPTED, task_of, UNFINISHED from transcript_archive.outcomes import ANSWERED, FINISHED, first_verdict, INTERRUPTED, task_of, UNFINISHED
from failure import Failure from failure import Failure
from loop_claude.cycle.judge import Finished, Interrupt, QuotedAnswer, Unfinished, Verdict from loop_claude.cycle.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished, Verdict
from rung_replay.search import Replay from rung_replay.search import Replay
from model_routing.ladder import Rung from model_routing.ladder import Rung
+1 -1
View File
@@ -122,7 +122,7 @@ class Main(unittest.TestCase):
@staticmethod @staticmethod
def verdict(interrupt, evidence): 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 "", "release_ready": False} output = {"answer": "", "highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 0, "escalation": "", "evidence": evidence, "finished": not interrupt, "interrupt": interrupt, "question": "Which?" if interrupt else "", "release_ready": False}
return {"type": "result", "structured_output": output} 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): def test_replays_the_models_projects_on_the_reference_then_from_the_projects_rung_down_and_prints_the_lowest_that_returns_all(self):
+11 -59
View File
@@ -7,6 +7,7 @@ from loop_claude.cycle.prompts import ANSWER_DESTINATIONS, ANSWERS_RECORDED, typ
from claude_code.reply import claude_reply, Limited from claude_code.reply import claude_reply, Limited
from loop_claude.effects import Effects from loop_claude.effects import Effects
from failure import Failure from failure import Failure
from loop_claude.cycle.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished, Verdict
from claude_code.entries import human_text, loop_text from claude_code.entries import human_text, loop_text
from todo_table import LEVELS from todo_table import LEVELS
from model_routing.route import on_its_scale from model_routing.route import on_its_scale
@@ -65,9 +66,9 @@ STEP_LINE = "[step] loop-claude stepped the worker up a rung here, so the escala
class Reply: class Reply:
answer: str = dataclasses.field(metadata={"description": "With interrupt false, the passage of README.md or the records that answers the worker's question, quoted verbatim, without elisions. Empty otherwise."}) answer: str = dataclasses.field(metadata={"description": "With interrupt false, the passage of README.md or the records that answers the worker's question, quoted verbatim, without elisions. Empty otherwise."})
# Routes the next cycle's worker. Counting the item the chunk was routed on is harmless: loop-claude never steps the worker down. # Routes the next cycle's worker. Counting the item the chunk was routed on is harmless: loop-claude never steps the worker down.
bundled: int = dataclasses.field(metadata={"description": "The highest L the worker states for a todo.md item it took into this chunk; 0 when it states none."}) highest_likelihood_taken_in: int = dataclasses.field(metadata={"description": "The highest L the worker states for a todo.md item it took into this chunk; 0 when it states none."})
# Routes the next cycle's judge and reviewers, as bundled routes the worker. # Routes the next cycle's judge and reviewers, as highest_likelihood_taken_in routes the worker.
bundled_escape_and_impact: int = dataclasses.field(metadata={"description": "The highest E + I the worker states for a todo.md item it took into this chunk; 0 when it states none."}) highest_escape_and_impact_taken_in: int = dataclasses.field(metadata={"description": "The highest E + I the worker states for a todo.md item it took into this chunk; 0 when it states none."})
# Routes the worker one rung up, as the judge interrupts or quotes an answer, or on the next cycle: docs/decisions.md → `routing: a worker whose run ends asking for a higher rung`. # Routes the worker one rung up, as the judge interrupts or quotes an answer, or on the next cycle: docs/decisions.md → `routing: a worker whose run ends asking for a higher rung`.
escalation: str = dataclasses.field(metadata={"description": "Empty unless the chunk is unfinished, interrupt is true or answer quotes a passage, and the worker's run ends asking loop-claude for a higher rung, citing an escalation trigger. Then: a verbatim quote, without elisions, of the transcript passage where the trigger fired, such as a review round's commit title or the worker's report of the finding or failing test. Where a [step] line says loop-claude stepped the worker up a rung, quote only the worker's own words after it, and leave this empty where the trigger fired only before it. Never a later mention of the trigger, and never the request itself."}) escalation: str = dataclasses.field(metadata={"description": "Empty unless the chunk is unfinished, interrupt is true or answer quotes a passage, and the worker's run ends asking loop-claude for a higher rung, citing an escalation trigger. Then: a verbatim quote, without elisions, of the transcript passage where the trigger fired, such as a review round's commit title or the worker's report of the finding or failing test. Where a [step] line says loop-claude stepped the worker up a rung, quote only the worker's own words after it, and leave this empty where the trigger fired only before it. Never a later mention of the trigger, and never the request itself."})
evidence: str = dataclasses.field(metadata={"description": "A verbatim quote of the one transcript passage the verdict rests on, without elisions: what triggers the interrupt; for a quoted answer, the worker's question; else what shows the chunk finished or the work remaining."}) evidence: str = dataclasses.field(metadata={"description": "A verbatim quote of the one transcript passage the verdict rests on, without elisions: what triggers the interrupt; for a quoted answer, the worker's question; else what shows the chunk finished or the work remaining."})
@@ -94,50 +95,6 @@ class Rejected(Failure):
reply: str reply: str
@dataclasses.dataclass(frozen=True)
class Interrupt:
evidence: str
question: str
# The judge's quote showing that the worker's cited escalation trigger fired; empty for none.
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
# How many transcript entries the judge read, which judge_once stamps. An escalation the verdict carries moves the route's mark there; one on a verdict never stamped, None, steps nothing.
entries_read: int | None = None
@dataclasses.dataclass(frozen=True)
class QuotedAnswer:
"""The worker asked a question that README.md or the records answer. The answer field quotes the passage."""
evidence: str
question: str
answer: str
# As on Interrupt.
escalation: str = ""
bundled: int = 0
entries_read: int | None = None
@dataclasses.dataclass(frozen=True)
class Finished:
evidence: str
@dataclasses.dataclass(frozen=True)
class Unfinished:
evidence: str
# The bundled L the judge saw, 0 for none.
bundled: int = 0
# The judge's quote showing that the worker's cited escalation trigger fired; empty for none.
escalation: str = ""
# The bundled E + I the judge saw, 0 for none.
bundled_escape_and_impact: int = 0
# As on Interrupt.
entries_read: int | None = None
Verdict = Interrupt | QuotedAnswer | Finished | Unfinished
class Grounds(typing.NamedTuple): class Grounds(typing.NamedTuple):
@@ -150,11 +107,6 @@ class Grounds(typing.NamedTuple):
quotable: str quotable: str
def escalation_mark(verdict: Interrupt | QuotedAnswer | Unfinished) -> int | None:
"""Where the verdict's escalation would move the route's mark, if it steps the worker; None where it carries none."""
return verdict.entries_read if verdict.escalation else None
def verdict_from(output: object) -> Verdict | Failure: def verdict_from(output: object) -> Verdict | Failure:
if not isinstance(output, dict): if not isinstance(output, dict):
return Failure("the judge returned no reply") return Failure("the judge returned no reply")
@@ -162,20 +114,20 @@ def verdict_from(output: object) -> Verdict | Failure:
# type(), not isinstance(): JSON true is no integer. # type(), not isinstance(): JSON true is no integer.
if type(output.get(name)) is not kind: if type(output.get(name)) is not kind:
return Failure(f"the judge's reply has no {name} of type {JSON_TYPES[kind]}") return Failure(f"the judge's reply has no {name} of type {JSON_TYPES[kind]}")
# A bundled level off its scale counts as none: holding the rung is safe, and three failures would stop an unattended loop. # An L taken in off its scale counts as none: holding the rung is safe, and three failures would stop an unattended loop.
bundled = output["bundled"] if 0 <= output["bundled"] <= HIGHEST_L else 0 likelihood = output["highest_likelihood_taken_in"] if 0 <= output["highest_likelihood_taken_in"] <= HIGHEST_L else 0
if output["interrupt"]: if output["interrupt"]:
if not output["question"].strip(): if not output["question"].strip():
return Failure("the judge interrupted without a question") return Failure("the judge interrupted without a question")
return Interrupt(output["evidence"], output["question"], output["escalation"], bundled, output["release_ready"]) return Interrupt(output["evidence"], output["question"], output["escalation"], likelihood, output["release_ready"])
if output["answer"].strip(): if output["answer"].strip():
if not output["question"].strip(): if not output["question"].strip():
return Failure("the judge quoted an answer without a question") return Failure("the judge quoted an answer without a question")
return QuotedAnswer(output["evidence"], output["question"], output["answer"], output["escalation"], bundled) return QuotedAnswer(output["evidence"], output["question"], output["answer"], output["escalation"], likelihood)
if output["finished"]: if output["finished"]:
return Finished(output["evidence"]) return Finished(output["evidence"])
bundled_escape_and_impact = output["bundled_escape_and_impact"] if on_its_scale(output["bundled_escape_and_impact"]) else 0 escape_and_impact = output["highest_escape_and_impact_taken_in"] if on_its_scale(output["highest_escape_and_impact_taken_in"]) else 0
return Unfinished(output["evidence"], bundled, output["escalation"], bundled_escape_and_impact) return Unfinished(output["evidence"], likelihood, output["escalation"], escape_and_impact)
def judge(root: str, task: str, premises: str, records: str, entries: list[dict], escalated_at: int, rung: Rung, effects: Effects, keep: typing.Callable[[Rejected], Stop | None]) -> Verdict | Stop: def judge(root: str, task: str, premises: str, records: str, entries: list[dict], escalated_at: int, rung: Rung, effects: Effects, keep: typing.Callable[[Rejected], Stop | None]) -> Verdict | Stop:
@@ -216,7 +168,7 @@ def run_judge(root: str, args: list[str], prompt: str, grounds: Grounds, effects
def quotes_checked(verdict: Verdict, grounds: Grounds) -> Verdict: def quotes_checked(verdict: Verdict, grounds: Grounds) -> Verdict:
"""The verdict with its quoted answer and its escalation checked, as Grounds says; a quoted answer put to the human keeps the escalation it carried.""" """The verdict with its quoted answer and its escalation checked, as Grounds says; a quoted answer put to the human keeps the escalation it carried."""
if isinstance(verdict, QuotedAnswer) and not verbatim(verdict.answer, grounds.quotable): if isinstance(verdict, QuotedAnswer) and not verbatim(verdict.answer, grounds.quotable):
verdict = Interrupt(verdict.evidence, verdict.question, verdict.escalation, verdict.bundled) verdict = Interrupt(verdict.evidence, verdict.question, verdict.escalation, verdict.highest_likelihood_taken_in)
if isinstance(verdict, Interrupt | QuotedAnswer | Unfinished) and verdict.escalation and not (verbatim(verdict.escalation, grounds.since_step) and verbatim(verdict.escalation, grounds.shown)): if isinstance(verdict, Interrupt | QuotedAnswer | Unfinished) and verdict.escalation and not (verbatim(verdict.escalation, grounds.since_step) and verbatim(verdict.escalation, grounds.shown)):
return dataclasses.replace(verdict, escalation="") return dataclasses.replace(verdict, escalation="")
return verdict return verdict
+9 -8
View File
@@ -3,12 +3,13 @@ import pathlib
import typing import typing
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 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 loop_claude.routing import after_ruling, judge_rung
from transcript_archive.write import archive from transcript_archive.write import archive
from claude_code.session import delete_session, Session, session_open, transcript_file from claude_code.session import delete_session, Session, session_open, transcript_file
from loop_claude.effects import Effects from loop_claude.effects import Effects
from loop_claude.cycle.judge import escalation_mark, Finished, Interrupt, judge, QuotedAnswer, Rejected, Unfinished
from failure import Failure from failure import Failure
from loop_claude.routing import judge_rung, stepped_by_ruling from loop_claude.cycle.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished
from loop_claude.cycle.judge import judge, Rejected
from transcript_archive import outcomes from transcript_archive import outcomes
from loop_claude.paths import Paths from loop_claude.paths import Paths
from loop_claude.cycle import prompts from loop_claude.cycle import prompts
@@ -73,13 +74,13 @@ def escalated(cycle: Cycle, event: Event) -> Cycle:
cycle = dataclasses.replace(cycle, stepped_from=None) cycle = dataclasses.replace(cycle, stepped_from=None)
if not (isinstance(event, Ruled) and isinstance(event.verdict, Interrupt | QuotedAnswer) and cycle.anchor): if not (isinstance(event, Ruled) and isinstance(event.verdict, Interrupt | QuotedAnswer) and cycle.anchor):
return cycle return cycle
route = stepped_by_ruling(cycle.anchor, cycle.route, event.verdict.bundled, escalation_mark(event.verdict)) route = after_ruling(cycle.anchor, cycle.route, event.verdict)
return dataclasses.replace(cycle, route=route, stepped_from=cycle.route if route != cycle.route else None) return dataclasses.replace(cycle, route=route, stepped_from=cycle.route if route != cycle.route else None)
def stopped(cycle: Cycle, stop: Stop, why: str) -> Stop: def stopped(cycle: Cycle, stop: Stop, why: str) -> Stop:
path = transcript_file(cycle.session) path = transcript_file(cycle.session)
failure = archive(cycle.project_archive, path, cycle.task, outcomes.stopped(str(cycle.route), why), cycle.effects.now()) if path else None failure = archive(cycle.project_archive, path, cycle.task, outcomes.stopped(cycle.route.record(), why), cycle.effects.now()) if path else None
# A failed archive exits 1 whatever the stop; when the stop was this archive failing, its reason is said once. # A failed archive exits 1 whatever the stop; when the stop was this archive failing, its reason is said once.
return Stop(1, f"{failure.reason}\n{stop.reason}".rstrip()) if failure and failure.reason != stop.reason else stop return Stop(1, f"{failure.reason}\n{stop.reason}".rstrip()) if failure and failure.reason != stop.reason else stop
@@ -137,7 +138,7 @@ def keep_answer(cycle: Cycle, answered: QuotedAnswer) -> Stop | None:
if not path: if not path:
return None return None
# As in ask: the answer names the rung the worker ran on until then, and a step-up archived after it names the rung it runs on from then. # As in ask: the answer names the rung the worker ran on until then, and a step-up archived after it names the rung it runs on from then.
quoted = outcomes.answered(answered.question, prompts.QUOTE_SOURCES, answered.answer, answered.evidence, answered.escalation, str(judge_of(cycle)), str(cycle.stepped_from or cycle.route)) quoted = outcomes.answered(answered.question, prompts.QUOTE_SOURCES, answered.answer, answered.evidence, answered.escalation, str(judge_of(cycle)), (cycle.stepped_from or cycle.route).record())
if failure := archive_stepped(cycle, path, quoted): if failure := archive_stepped(cycle, path, quoted):
return Stop(1, failure.reason) return Stop(1, failure.reason)
return None return None
@@ -162,7 +163,7 @@ def ask(cycle: Cycle, transcript_path: str, ruling: Interrupt | QuotedAnswer) ->
question = question_for(ruling) question = question_for(ruling)
# Archived now, so the transcript the question was asked on is kept with it; the human's answer then grows the transcript. # Archived now, so the transcript the question was asked on is kept with it; the human's answer then grows the transcript.
# The interrupt names the rung the worker ran on before it; a step-up archived after it names the stepped rung, so the figures charge each stretch to its own rung. # The interrupt names the rung the worker ran on before it; a step-up archived after it names the stepped rung, so the figures charge each stretch to its own rung.
interrupted = outcomes.interrupted(question, ruling.evidence, str(judge_of(cycle)), ruling.escalation, str(cycle.stepped_from or cycle.route)) interrupted = outcomes.interrupted(question, ruling.evidence, str(judge_of(cycle)), ruling.escalation, (cycle.stepped_from or cycle.route).record())
if failure := archive_stepped(cycle, transcript_path, interrupted): if failure := archive_stepped(cycle, transcript_path, interrupted):
return Stop(1, failure.reason) return Stop(1, failure.reason)
# Only the human may cut a release, so a release ready to cut opens claude's session at once. # Only the human may cut a release, so a release ready to cut opens claude's session at once.
@@ -175,7 +176,7 @@ def ask(cycle: Cycle, transcript_path: str, ruling: Interrupt | QuotedAnswer) ->
def archive_stepped(cycle: Cycle, transcript_path: str, outcome: str) -> Failure | None: def archive_stepped(cycle: Cycle, transcript_path: str, outcome: str) -> Failure | None:
"""Archives the outcome of a ruling, then the step-up it caused when it stepped the route. The first failure is returned.""" """Archives the outcome of a ruling, then the step-up it caused when it stepped the route. The first failure is returned."""
for kept in (outcome, outcomes.stepped_up(str(cycle.route))) if cycle.stepped_from else (outcome,): for kept in (outcome, outcomes.stepped_up(cycle.route.record())) if cycle.stepped_from else (outcome,):
if failure := archive(cycle.project_archive, transcript_path, cycle.task, kept, cycle.effects.now()): if failure := archive(cycle.project_archive, transcript_path, cycle.task, kept, cycle.effects.now()):
return failure return failure
return None return None
@@ -188,7 +189,7 @@ def question_for(ruling: Interrupt | QuotedAnswer) -> str:
def close(cycle: Cycle, transcript_path: str, verdict: Finished | Unfinished) -> Archived | Stop: def close(cycle: Cycle, transcript_path: str, verdict: Finished | Unfinished) -> Archived | Stop:
outcome = outcomes.finished(str(cycle.route), verdict.evidence, str(judge_of(cycle))) if isinstance(verdict, Finished) else outcomes.unfinished(str(cycle.route), verdict.evidence, str(judge_of(cycle)), verdict.escalation) outcome = outcomes.finished(cycle.route.record(), verdict.evidence, str(judge_of(cycle))) if isinstance(verdict, Finished) else outcomes.unfinished(cycle.route.record(), verdict.evidence, str(judge_of(cycle)), verdict.escalation)
if failure := archive(cycle.project_archive, transcript_path, cycle.task, outcome, cycle.effects.now()): if failure := archive(cycle.project_archive, transcript_path, cycle.task, outcome, cycle.effects.now()):
return Stop(1, failure.reason) return Stop(1, failure.reason)
if isinstance(verdict, Finished) and (failure := delete_session(cycle.session)): if isinstance(verdict, Finished) and (failure := delete_session(cycle.session)):
+1 -1
View File
@@ -1,6 +1,6 @@
import dataclasses import dataclasses
from loop_claude.cycle.judge import Finished, Interrupt, QuotedAnswer, Unfinished, Verdict from loop_claude.cycle.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished, Verdict
# A backstop for what the judge misses, such as a reworded repeat, so the worker cannot loop unattended on answers quoted from README.md or the records. # A backstop for what the judge misses, such as a reworded repeat, so the worker cannot loop unattended on answers quoted from README.md or the records.
QUOTED_ANSWERS_PER_CYCLE = 3 QUOTED_ANSWERS_PER_CYCLE = 3
+53
View File
@@ -0,0 +1,53 @@
"""What the judge rules on a cycle: the verdicts judge.verdict_from builds from its reply."""
import dataclasses
@dataclasses.dataclass(frozen=True)
class Interrupt:
evidence: str
question: str
# The judge's quote showing that the worker's cited escalation trigger fired; empty for none.
escalation: str = ""
# The highest L the judge saw the worker take into the chunk, 0 for none: an escalation steps up from the rung that L picks.
highest_likelihood_taken_in: int = 0
release_ready: bool = False
# How many transcript entries the judge read, which judge_once stamps. An escalation the verdict carries moves the route's mark there; one on a verdict never stamped, None, steps nothing.
entries_read: int | None = None
@dataclasses.dataclass(frozen=True)
class QuotedAnswer:
"""The worker asked a question that README.md or the records answer. The answer field quotes the passage."""
evidence: str
question: str
answer: str
# As on Interrupt.
escalation: str = ""
highest_likelihood_taken_in: int = 0
entries_read: int | None = None
@dataclasses.dataclass(frozen=True)
class Finished:
evidence: str
@dataclasses.dataclass(frozen=True)
class Unfinished:
evidence: str
# As on Interrupt; it raises the worker to the rung it picks.
highest_likelihood_taken_in: int = 0
# The judge's quote showing that the worker's cited escalation trigger fired; empty for none.
escalation: str = ""
# The highest E + I the judge saw the worker take into the chunk, 0 for none.
highest_escape_and_impact_taken_in: int = 0
# As on Interrupt.
entries_read: int | None = None
Verdict = Interrupt | QuotedAnswer | Finished | Unfinished
def escalation_mark(verdict: Interrupt | QuotedAnswer | Unfinished) -> int | None:
"""Where the verdict's escalation would move the route's mark, if it steps the worker; None where it carries none."""
return verdict.entries_read if verdict.escalation else None
+29 -28
View File
@@ -105,13 +105,15 @@ chunk's item picks, and the worker's prompts offer it only while the worker is b
Routing: the archive and reruns Routing: the archive and reruns
Each finished or unfinished verdict, interrupt, quoted answer, stop and step-up in the archive names Each finished or unfinished verdict, interrupt, quoted answer, stop and step-up in the archive ends
the worker's rung, with the item, L and E + I that routed the chunk, any taken-in E + I that picks a with a Worker: line, a JSON record of the route: the worker's rung as model and effort, the item, L
higher review rung (archived as a step-up too), and the mark. A rerun resumes an open chunk on the and E + I that routed the chunk, any taken-in E + I that picks a higher review rung (archived as a
latest route named there, and counts its unfinished verdicts afresh. A rung no longer on the ladder, step-up too), and the mark. A rerun resumes an open chunk on the latest route named there, and
or below the one its item's L picks, is dropped, and the chunk is routed afresh from todo.md. So is counts its unfinished verdicts afresh; it also reads the prose lines written before the record. A
a chunk whose archived line names an R + C, as loop-claude wrote before it routed on L. A todo.md or rung no longer on the ladder, or below the one its item's L picks, is dropped, and the chunk is
an archive that cannot be read or parsed is said on stderr, and the chunk is routed without it. routed afresh from todo.md. So is a chunk whose archived line names an R + C, as loop-claude wrote
before it routed on L. A todo.md or an archive that cannot be read or parsed is said on stderr, and
the chunk is routed without it.
Routing: the judge's rung Routing: the judge's rung
@@ -181,18 +183,18 @@ import pathlib
import sys import sys
import typing import typing
from loop_claude.routing import after_unfinished, first_route, kept, routed_item
from transcript_archive.write import archive from transcript_archive.write import archive
from transcript_archive.location import archive_root, project_archive from transcript_archive.location import archive_root, project_archive
from loop_claude.loop.routing_check import check_routing from loop_claude.loop.routing_check import check_routing
from loop_claude.project.checkout import checkout_root from loop_claude.project.checkout import checkout_root
from loop_claude.cycle.run import Cycle, run_cycle from loop_claude.cycle.run import Concluded, Cycle, run_cycle
from loop_claude.loop.reload import decode_handed, exec_if_edited, fingerprint, LoopRun, RELOAD_FLAG from loop_claude.loop.reload import decode_handed, exec_if_edited, fingerprint, LoopRun, RELOAD_FLAG
from chunk_pick import default_plan, DefaultPlan from chunk_pick import default_plan, DefaultPlan
from git_repo import default_ref from git_repo import default_ref
from loop_claude.effects import Effects from loop_claude.effects import Effects
from loop_claude.cycle.judge import escalation_mark, Finished, Unfinished
from failure import Failure from failure import Failure
from loop_claude.routing import first_route, kept, routed_item, stepped from loop_claude.cycle.verdicts import Finished
from loop_claude.project.model_choice import get_or_ask_models from loop_claude.project.model_choice import get_or_ask_models
from todo_table import Item from todo_table import Item
from transcript_archive.read import latest_worker from transcript_archive.read import latest_worker
@@ -246,43 +248,42 @@ def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launc
# After the reads above, so a loop that stops on one makes no worktree. # After the reads above, so a loop that stops on one makes no worktree.
facts, item = chunk_start(session, launcher.with_name("chunk-preflight"), loop_run.root, effects) facts, item = chunk_start(session, launcher.with_name("chunk-preflight"), loop_run.root, effects)
anchor = project_rung(models.worker) anchor = project_rung(models.worker)
loop_run = routed(loop_run, anchor, lambda: archived_route(archive_folder, session), item) route = routed(loop_run.route, anchor, models.worker, lambda: archived_route(archive_folder, session), item)
route = loop_run.route or Route(Rung(models.worker))
print(f"\n=== cycle {loop_run.cycle_number}, worker on {route.rung} ===", flush=True) print(f"\n=== cycle {loop_run.cycle_number}, worker on {route.rung} ===", flush=True)
concluded = run_cycle(Cycle(anchor=anchor, effects=effects, facts=facts, judge_model=models.judge, paths=paths, premises=premises, project_archive=archive_folder, records=records, root=loop_run.root, route=route, session=session, task=loop_run.task, unfinished_evidence=loop_run.unfinished_evidence)) concluded = run_cycle(Cycle(anchor=anchor, effects=effects, facts=facts, judge_model=models.judge, paths=paths, premises=premises, project_archive=archive_folder, records=records, root=loop_run.root, route=route, session=session, task=loop_run.task, unfinished_evidence=loop_run.unfinished_evidence))
if isinstance(concluded, Stop): if isinstance(concluded, Stop):
return concluded return concluded
# The route the cycle ended on, which a step-up at an interrupt or a quoted answer may have raised and archived, is the one the verdict steps from. loop_run = after_verdict(loop_run, anchor, concluded)
ended = dataclasses.replace(loop_run, route=concluded.route if anchor else None) if stop := archive_step(archive_folder, session, loop_run.task, concluded.route, loop_run.route, effects):
before, loop_run = ended.route, after_verdict(ended, anchor, concluded.verdict)
if stop := archive_step(archive_folder, session, loop_run, before, effects):
return stop return stop
if stop := check_routing(archive_root(paths.home, env), anchor or Rung(models.worker), paths, effects): if stop := check_routing(archive_root(paths.home, env), anchor or Rung(models.worker), paths, effects):
return stop return stop
def routed(loop_run: LoopRun, anchor: Rung | None, archived: typing.Callable[[], Route | None], item: typing.Callable[[], Item | None]) -> LoopRun: def routed(route: Route | None, anchor: Rung | None, model: str, archived: typing.Callable[[], Route | None], item: typing.Callable[[], Item | None]) -> Route:
"""The loop run with its chunk's route, or None when the project's model is off the ladder. A chunk keeps its route, or on a rerun the one its archive last names, """The route the cycle runs on. Off the ladder, where anchor, the project's rung, is None, the worker runs on model, the project's.
while that is at or above the rung its item's L picks from anchor, the project's rung; else the plan item routes it afresh.""" On it, a chunk keeps route, or on a rerun the one its archive last names, while that is at or above the rung its item's L picks from anchor; else the plan item routes it afresh."""
if anchor is None: if anchor is None:
return dataclasses.replace(loop_run, route=None) return Route(Rung(model))
route = loop_run.route or archived() route = route or archived()
return dataclasses.replace(loop_run, route=route if route and kept(route, anchor) else first_route(anchor, item())) return route if route and kept(route, anchor) else first_route(anchor, item())
def after_verdict(loop_run: LoopRun, anchor: Rung | None, verdict: Finished | Unfinished) -> LoopRun: def after_verdict(loop_run: LoopRun, anchor: Rung | None, concluded: Concluded) -> LoopRun:
"""The loop run the next cycle starts from. A finished chunk drops its route. An unfinished one steps from the route its cycle ended on, which an interrupt's or a quoted answer's escalation may have raised; off the ladder, it keeps that route."""
verdict = concluded.verdict
if isinstance(verdict, Finished): if isinstance(verdict, Finished):
return dataclasses.replace(loop_run, route=None, unfinished_evidence="") return dataclasses.replace(loop_run, route=None, unfinished_evidence="")
route = stepped(anchor, loop_run.route, verdict.bundled, escalation_mark(verdict)).taking_in(verdict.bundled_escape_and_impact) if anchor and loop_run.route else loop_run.route route = after_unfinished(anchor, concluded.route, verdict) if anchor else concluded.route
return dataclasses.replace(loop_run, route=route, unfinished_evidence=verdict.evidence) return dataclasses.replace(loop_run, route=route, unfinished_evidence=verdict.evidence)
def archive_step(archive_folder: pathlib.Path, session: Session, loop_run: LoopRun, before: Route | None, effects: Effects) -> Stop | None: def archive_step(archive_folder: pathlib.Path, session: Session, task: str, before: Route, after: Route | None, effects: Effects) -> Stop | None:
"""Archives the rung an unfinished verdict stepped the chunk up to, or the higher E + I it took in; the verdict itself names the route its cycle ran on.""" """Archives after, the route an unfinished verdict moved the chunk to from before, where its record differs: a rung up, or a higher E + I taken in. The verdict itself names before, the route its cycle ran on."""
if not (before and loop_run.route) or str(loop_run.route) == str(before): if after is None or after.record() == before.record():
return None return None
path = transcript_file(session) path = transcript_file(session)
failure = archive(archive_folder, path, loop_run.task, outcomes.stepped_up(str(loop_run.route)), effects.now()) if path else None failure = archive(archive_folder, path, task, outcomes.stepped_up(after.record()), effects.now()) if path else None
return Stop(1, failure.reason) if failure else None return Stop(1, failure.reason) if failure else None
+1 -1
View File
@@ -22,7 +22,7 @@ class LoopRun:
root: str root: str
task: str task: str
unfinished_evidence: str unfinished_evidence: str
# None until the chunk is routed, and where the project's model is off the ladder. # None until the chunk is routed, and once it finishes.
route: Route | None = None route: Route | None = None
+20 -16
View File
@@ -3,6 +3,7 @@ import dataclasses
from chunk_pick import chunk_item, LastCut, Next from chunk_pick import chunk_item, LastCut, Next
from model_routing.ladder import climbed, highest, LADDER, position, project_rung, review_floor, Rung, stepped_up, worker_rung from model_routing.ladder import climbed, highest, LADDER, position, project_rung, review_floor, Rung, stepped_up, worker_rung
from loop_claude.cycle.verdicts import escalation_mark, Interrupt, QuotedAnswer, Unfinished
from failure import Failure from failure import Failure
from todo_table import Item, items, NoItemsTable from todo_table import Item, items, NoItemsTable
from model_routing.route import Route from model_routing.route import Route
@@ -63,24 +64,27 @@ def escalation_cap(anchor: Rung, route: Route) -> Rung:
return climbed(item_rung(anchor, route), ESCALATION_CAP) return climbed(item_rung(anchor, route), ESCALATION_CAP)
def stepped(anchor: Rung, route: Route, bundled: int, escalated_at: int | None) -> Route: def after_unfinished(anchor: Rung, route: Route, verdict: Unfinished) -> Route:
"""The route after one more unfinished verdict. Its rung never falls below taken_in's. It steps up one rung on every second unfinished verdict, or on an escalation the judge found while the rung is below escalation_cap; where both fall on one verdict, it steps once. """The route the next cycle runs on after an unfinished verdict.
bundled is the highest L the judge saw the worker take in, 0 for none. escalated_at is how many transcript entries the judge read where the verdict carries an escalation, None where it carries none. A step moves the route's mark, Route.escalated_at, to escalated_at; a step on the count of unfinished verdicts alone keeps the mark. They are passed in place of the verdict, since loop_claude.cycle.judge imports this module through prompts. Its rung rises to the one the highest L the worker took in picks, and never falls. From there it steps one rung up on every second unfinished verdict, or on an escalation while below escalation_cap; where both fall on one verdict, it steps once. A step on an escalation moves the route's mark, Route.escalated_at, to where the judge stopped reading, so the trigger it quoted buys no second step; a step on the count of unfinished verdicts alone keeps the mark. The highest E + I taken in moves to the route where Route.taking_in keeps it.
""" """
rung = taken_in(anchor, route, bundled) rung = raised(anchor, route, verdict.highest_likelihood_taken_in)
unfinished = route.unfinished + 1 mark = escalation_mark(verdict)
if unfinished >= UNFINISHED_PER_STEP or (escalated_at is not None and below_cap(anchor, route, rung)): if route.unfinished + 1 >= UNFINISHED_PER_STEP or (mark is not None and below_cap(anchor, route, rung)):
return one_rung_up(route, rung, route.escalated_at if escalated_at is None else escalated_at) after = one_rung_up(route, rung, route.escalated_at if mark is None else mark)
return dataclasses.replace(route, rung=rung, unfinished=unfinished) else:
after = dataclasses.replace(route, rung=rung, unfinished=route.unfinished + 1)
return after.taking_in(verdict.highest_escape_and_impact_taken_in)
def stepped_by_ruling(anchor: Rung, route: Route, bundled: int, escalated_at: int | None) -> Route: def after_ruling(anchor: Rung, route: Route, verdict: Interrupt | QuotedAnswer) -> Route:
"""The route after the judge's interrupt or quoted answer, its arguments as stepped's: unchanged without an escalation; with one, taken_in's rung, one rung up while that is below escalation_cap. Neither is an unfinished verdict, so the count of those restarts only with a step.""" """The route after the judge's interrupt or quoted answer: unchanged without an escalation. With one, raised to the rung the highest L taken in picks, and one rung up from there while below escalation_cap, moving the mark as after_unfinished does. Neither is an unfinished verdict, so the count of those restarts only with a step."""
if escalated_at is None: mark = escalation_mark(verdict)
if mark is None:
return route return route
rung = taken_in(anchor, route, bundled) rung = raised(anchor, route, verdict.highest_likelihood_taken_in)
return one_rung_up(route, rung, escalated_at) if below_cap(anchor, route, rung) else dataclasses.replace(route, rung=rung) return one_rung_up(route, rung, mark) if below_cap(anchor, route, rung) else dataclasses.replace(route, rung=rung)
def one_rung_up(route: Route, rung: Rung, escalated_at: int) -> Route: def one_rung_up(route: Route, rung: Rung, escalated_at: int) -> Route:
@@ -93,9 +97,9 @@ def below_cap(anchor: Rung, route: Route, rung: Rung) -> bool:
return position(rung) < position(escalation_cap(anchor, route)) return position(rung) < position(escalation_cap(anchor, route))
def taken_in(anchor: Rung, route: Route, bundled: int) -> Rung: def raised(anchor: Rung, route: Route, likelihood_taken_in: int) -> Rung:
"""kept_rung, raised to the rung bundled picks from anchor; bundled is the highest L the judge saw the worker take into the chunk, 0 for none.""" """kept_rung, raised to the rung likelihood_taken_in, the highest L the worker took into the chunk, picks from anchor; 0 for none."""
return highest(kept_rung(anchor, route), worker_rung(anchor, bundled)) if bundled else kept_rung(anchor, route) return highest(kept_rung(anchor, route), worker_rung(anchor, likelihood_taken_in)) if likelihood_taken_in else kept_rung(anchor, route)
def judge_rung(judge_model: str, route: Route) -> Rung: def judge_rung(judge_model: str, route: Route) -> Rung:
+22 -18
View File
@@ -21,6 +21,10 @@ from test_env import isolated_env
BIN = pathlib.Path(__file__).resolve().parents[1] BIN = pathlib.Path(__file__).resolve().parents[1]
TASK = "Do the next chunk." TASK = "Do the next chunk."
# How the archive records a worker that runs off the ladder.
OFF_LADDER = '{"model": "worker-model"}'
# How a reload hands that worker's route.
OFF_LADDER_ROUTE = {"rung": {"model": "worker-model", "effort": ""}, "item": 0, "likelihood": 0, "escape_and_impact": 0, "unfinished": 0, "escape_and_impact_taken_in": 0, "escalated_at": 0}
# Plays claude from FAKE_CLAUDE_SCENARIO, one step per call, logging each call; a step for another role, # Plays claude from FAKE_CLAUDE_SCENARIO, one step per call, logging each call; a step for another role,
@@ -129,8 +133,8 @@ def worker(**step):
return {"role": "worker", **step} return {"role": "worker", **step}
def judge(interrupt=False, finished=False, evidence="working", question="", bundled=0, bundled_escape_and_impact=0, escalation="", release_ready=False, **step): def judge(interrupt=False, finished=False, evidence="working", question="", highest_likelihood_taken_in=0, highest_escape_and_impact_taken_in=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} verdict = {"answer": "", "highest_likelihood_taken_in": highest_likelihood_taken_in, "highest_escape_and_impact_taken_in": highest_escape_and_impact_taken_in, "escalation": escalation, "evidence": evidence, "finished": finished, "interrupt": interrupt, "question": question, "release_ready": release_ready}
return {"role": "judge", "verdict": verdict, **step} return {"role": "judge", "verdict": verdict, **step}
@@ -386,9 +390,9 @@ class Cycles(unittest.TestCase):
self.assertEqual([path.name for path in checkout.transcripts()[0].parent.iterdir()], [checkout.transcripts()[0].name]) self.assertEqual([path.name for path in checkout.transcripts()[0].parent.iterdir()], [checkout.transcripts()[0].name])
self.assertIn("=== cycle 3, worker on worker-model ===", run.stdout) self.assertIn("=== cycle 3, worker on worker-model ===", run.stdout)
copies = {verdict.removeprefix(f"Task: {TASK}\n\n"): copy for copy, verdict in checkout.archived().items()} copies = {verdict.removeprefix(f"Task: {TASK}\n\n"): copy for copy, verdict in checkout.archived().items()}
self.assertEqual(sorted(copies), ["<UTC> Stopped: Ctrl-C\n\nWorker: worker-model\n", "<UTC> Verdict: finished\n\nEvidence:\n> landed-it\n\nJudge: judge-model\nWorker: worker-model\n", "<UTC> Verdict: unfinished\n\nEvidence:\n> started\n\nJudge: judge-model\nWorker: worker-model\n"]) self.assertEqual(sorted(copies), [f"<UTC> Stopped: Ctrl-C\n\nWorker: {OFF_LADDER}\n", f"<UTC> Verdict: finished\n\nEvidence:\n> landed-it\n\nJudge: judge-model\nWorker: {OFF_LADDER}\n", f"<UTC> Verdict: unfinished\n\nEvidence:\n> started\n\nJudge: judge-model\nWorker: {OFF_LADDER}\n"])
self.assertIn('"text": "landed-it"', copies["<UTC> Verdict: finished\n\nEvidence:\n> landed-it\n\nJudge: judge-model\nWorker: worker-model\n"]) self.assertIn('"text": "landed-it"', copies[f"<UTC> Verdict: finished\n\nEvidence:\n> landed-it\n\nJudge: judge-model\nWorker: {OFF_LADDER}\n"])
self.assertIn('"text": "next chunk"', copies["<UTC> Stopped: Ctrl-C\n\nWorker: worker-model\n"]) self.assertIn('"text": "next chunk"', copies[f"<UTC> Stopped: Ctrl-C\n\nWorker: {OFF_LADDER}\n"])
self.assertEqual(len(list(checkout.archive().glob(f"proj/*/session/{session}.orphaned-1-ab.jsonl"))), 1) self.assertEqual(len(list(checkout.archive().glob(f"proj/*/session/{session}.orphaned-1-ab.jsonl"))), 1)
def test_routes_the_worker_by_its_items_l_and_steps_it_up_within_the_chunk(self): def test_routes_the_worker_by_its_items_l_and_steps_it_up_within_the_chunk(self):
@@ -398,7 +402,7 @@ class Cycles(unittest.TestCase):
run = checkout.run([ run = checkout.run([
worker(say="one"), judge(evidence="one"), worker(say="one"), judge(evidence="one"),
worker(say="two"), judge(evidence="two"), worker(say="two"), judge(evidence="two"),
worker(say="three"), judge(evidence="three", bundled=4), worker(say="three"), judge(evidence="three", highest_likelihood_taken_in=4),
worker(say="four"), judge(finished=True, evidence="four"), worker(say="four"), judge(finished=True, evidence="four"),
worker(say="next chunk"), worker(say="next chunk"),
]) ])
@@ -414,8 +418,8 @@ class Cycles(unittest.TestCase):
self.assertEqual({(argument(call, "--model"), argument(call, "--effort")) for call in run.calls if call["role"] == "judge"}, {("judge-model", None)}) self.assertEqual({(argument(call, "--model"), argument(call, "--effort")) for call in run.calls if call["role"] == "judge"}, {("judge-model", None)})
self.assertIn("loop-claude runs you on claude-sonnet-5-5 at high effort, routed by item 4's L of 2. Name each todo.md item this chunk takes, with its L and E + I, whether or not it is item 4.", argument(workers[0], "-p")) self.assertIn("loop-claude runs you on claude-sonnet-5-5 at high effort, routed by item 4's L of 2. Name each todo.md item this chunk takes, with its L and E + I, whether or not it is item 4.", argument(workers[0], "-p"))
outcomes = sorted(verdict.removeprefix(f"Task: {TASK}\n\n") for verdict in checkout.archived().values()) outcomes = sorted(verdict.removeprefix(f"Task: {TASK}\n\n") for verdict in checkout.archived().values())
self.assertIn("<UTC> Verdict: unfinished\n\nEvidence:\n> three\n\nJudge: judge-model\nWorker: claude-opus-5-5 at medium effort, routed by item 4's L of 2 and E + I of 3\n\n<UTC> Stepped up\n\nWorker: claude-opus-5-5 at high effort, routed by item 4's L of 2 and E + I of 3\n", outcomes) self.assertIn('<UTC> Verdict: unfinished\n\nEvidence:\n> three\n\nJudge: judge-model\nWorker: {"model": "claude-opus-5-5", "effort": "medium", "item": 4, "likelihood": 2, "escape_and_impact": 3}\n\n<UTC> Stepped up\n\nWorker: {"model": "claude-opus-5-5", "effort": "high", "item": 4, "likelihood": 2, "escape_and_impact": 3}\n', outcomes)
self.assertIn("<UTC> Verdict: finished\n\nEvidence:\n> four\n\nJudge: judge-model\nWorker: claude-opus-5-5 at high effort, routed by item 4's L of 2 and E + I of 3\n", outcomes) self.assertIn('<UTC> Verdict: finished\n\nEvidence:\n> four\n\nJudge: judge-model\nWorker: {"model": "claude-opus-5-5", "effort": "high", "item": 4, "likelihood": 2, "escape_and_impact": 3}\n', outcomes)
def test_routes_on_and_states_the_same_item_from_the_fetched_default_branch_whatever_the_checkout_holds(self): def test_routes_on_and_states_the_same_item_from_the_fetched_default_branch_whatever_the_checkout_holds(self):
checkout = Checkout(self) checkout = Checkout(self)
@@ -460,8 +464,8 @@ class Cycles(unittest.TestCase):
("claude-opus-5-5", "high"), ("claude-opus-5-5", "high"),
]) ])
outcomes = sorted(verdict.removeprefix(f"Task: {TASK}\n\n") for verdict in checkout.archived().values()) outcomes = sorted(verdict.removeprefix(f"Task: {TASK}\n\n") for verdict in checkout.archived().values())
self.assertIn("<UTC> Verdict: unfinished\n\nEvidence:\n> I ask for a higher rung.\n\nEscalation:\n> Stability round 2: a 🔴.\n\nJudge: judge-model\nWorker: claude-opus-5-5 at high effort, routed by item 4's L of 4 and E + I of 5\n\n<UTC> Stepped up\n\nWorker: claude-opus-5-5 at xhigh effort, routed by item 4's L of 4 and E + I of 5, escalated at transcript entry 4\n", outcomes) self.assertIn('<UTC> Verdict: unfinished\n\nEvidence:\n> I ask for a higher rung.\n\nEscalation:\n> Stability round 2: a 🔴.\n\nJudge: judge-model\nWorker: {"model": "claude-opus-5-5", "effort": "high", "item": 4, "likelihood": 4, "escape_and_impact": 5}\n\n<UTC> Stepped up\n\nWorker: {"model": "claude-opus-5-5", "effort": "xhigh", "item": 4, "likelihood": 4, "escape_and_impact": 5, "escalated_at": 4}\n', outcomes)
self.assertIn("<UTC> Verdict: unfinished\n\nEvidence:\n> I ask for a higher rung.\n\nJudge: judge-model\nWorker: claude-opus-5-5 at xhigh effort, routed by item 4's L of 4 and E + I of 5, escalated at transcript entry 4\n", outcomes) self.assertIn('<UTC> Verdict: unfinished\n\nEvidence:\n> I ask for a higher rung.\n\nJudge: judge-model\nWorker: {"model": "claude-opus-5-5", "effort": "xhigh", "item": 4, "likelihood": 4, "escape_and_impact": 5, "escalated_at": 4}\n', outcomes)
def test_steps_the_worker_up_once_as_the_judge_interrupts_when_the_run_also_cites_an_escalation_trigger(self): def test_steps_the_worker_up_once_as_the_judge_interrupts_when_the_run_also_cites_an_escalation_trigger(self):
checkout = Checkout(self) checkout = Checkout(self)
@@ -477,9 +481,9 @@ class Cycles(unittest.TestCase):
self.assertEqual(run.roles(), ["worker", "judge", "interrupt", "judge", "worker", "judge"]) 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")]) 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")])
outcomes = sorted(verdict.removeprefix(f"Task: {TASK}\n\n") for verdict in checkout.archived().values()) outcomes = sorted(verdict.removeprefix(f"Task: {TASK}\n\n") for verdict in checkout.archived().values())
self.assertIn("<UTC> Stepped up\n\nWorker: claude-opus-5-5 at xhigh effort, routed by item 4's L of 4 and E + I of 5, escalated at transcript entry 4\n", "".join(outcomes)) self.assertIn('<UTC> Stepped up\n\nWorker: {"model": "claude-opus-5-5", "effort": "xhigh", "item": 4, "likelihood": 4, "escape_and_impact": 5, "escalated_at": 4}\n', "".join(outcomes))
self.assertNotIn("at max effort", "".join(outcomes)) self.assertNotIn("at max effort", "".join(outcomes))
self.assertIn("Verdict: interrupt\n\nA or B?\n\nEvidence:\n> Shall I use A or B?\n\nEscalation:\n> Stability round 2: a 🔴.\n\nJudge: judge-model\nWorker: claude-opus-5-5 at high effort, routed by item 4's L of 4 and E + I of 5\n\n<UTC> Stepped up\n\nWorker: claude-opus-5-5 at xhigh effort, routed by item 4's L of 4 and E + I of 5, escalated at transcript entry 4\n", "".join(outcomes)) self.assertIn('Verdict: interrupt\n\nA or B?\n\nEvidence:\n> Shall I use A or B?\n\nEscalation:\n> Stability round 2: a 🔴.\n\nJudge: judge-model\nWorker: {"model": "claude-opus-5-5", "effort": "high", "item": 4, "likelihood": 4, "escape_and_impact": 5}\n\n<UTC> Stepped up\n\nWorker: {"model": "claude-opus-5-5", "effort": "xhigh", "item": 4, "likelihood": 4, "escape_and_impact": 5, "escalated_at": 4}\n', "".join(outcomes))
def test_runs_a_cheap_items_worker_below_the_projects_rung_with_its_reviewers_and_judge_on_it(self): def test_runs_a_cheap_items_worker_below_the_projects_rung_with_its_reviewers_and_judge_on_it(self):
checkout = Checkout(self) checkout = Checkout(self)
@@ -491,7 +495,7 @@ class Cycles(unittest.TestCase):
self.assertEqual((argument(first, "--model"), argument(first, "--effort")), ("claude-sonnet-5-5", "high")) self.assertEqual((argument(first, "--model"), argument(first, "--effort")), ("claude-sonnet-5-5", "high"))
ruling = next(call for call in run.calls if call["role"] == "judge") ruling = next(call for call in run.calls if call["role"] == "judge")
self.assertEqual((argument(ruling, "--model"), argument(ruling, "--effort")), ("claude-opus-5-5", "medium")) self.assertEqual((argument(ruling, "--model"), argument(ruling, "--effort")), ("claude-opus-5-5", "medium"))
self.assertIn("Judge: claude-opus-5-5 at medium effort\nWorker: claude-sonnet-5-5 at high effort", "".join(checkout.archived().values())) self.assertIn('Judge: claude-opus-5-5 at medium effort\nWorker: {"model": "claude-sonnet-5-5", "effort": "high", ', "".join(checkout.archived().values()))
self.assertIn("Launch each reviewer, each comprehension seat and the security pass's subagent with the Agent tool set to model opus, effort medium, the project's rung.", argument(first, "-p")) self.assertIn("Launch each reviewer, each comprehension seat and the security pass's subagent with the Agent tool set to model opus, effort medium, the project's rung.", argument(first, "-p"))
def test_routes_the_judge_and_the_reviewers_on_the_highest_e_plus_i_the_worker_takes_in(self): def test_routes_the_judge_and_the_reviewers_on_the_highest_e_plus_i_the_worker_takes_in(self):
@@ -499,7 +503,7 @@ class Cycles(unittest.TestCase):
checkout.env["LOOP_CLAUDE_WORKER_MODEL"] = checkout.env["LOOP_CLAUDE_JUDGE_MODEL"] = "claude-opus-5-5" checkout.env["LOOP_CLAUDE_WORKER_MODEL"] = checkout.env["LOOP_CLAUDE_JUDGE_MODEL"] = "claude-opus-5-5"
checkout.commit_plan(CHEAP) checkout.commit_plan(CHEAP)
run = checkout.run([ run = checkout.run([
worker(say="one"), judge(evidence="one", bundled_escape_and_impact=6), worker(say="one"), judge(evidence="one", highest_escape_and_impact_taken_in=6),
worker(say="two"), judge(finished=True, evidence="two"), worker(say="two"), judge(finished=True, evidence="two"),
worker(say="next chunk"), worker(say="next chunk"),
]) ])
@@ -509,8 +513,8 @@ class Cycles(unittest.TestCase):
self.assertEqual({argument(call, "--effort") for call in workers}, {"high"}) self.assertEqual({argument(call, "--effort") for call in workers}, {"high"})
self.assertIn("Launch each reviewer with the Agent tool set to model opus, effort xhigh, the rung picked by an item of E + I 6 taken into the chunk.", argument(workers[1], "-p")) self.assertIn("Launch each reviewer with the Agent tool set to model opus, effort xhigh, the rung picked by an item of E + I 6 taken into the chunk.", argument(workers[1], "-p"))
outcomes = "".join(checkout.archived().values()) outcomes = "".join(checkout.archived().values())
self.assertIn("<UTC> Stepped up\n\nWorker: claude-sonnet-5-5 at high effort, routed by item 4's L of 2 and E + I of 3, taking in an E + I of 6\n", outcomes) self.assertIn('<UTC> Stepped up\n\nWorker: {"model": "claude-sonnet-5-5", "effort": "high", "item": 4, "likelihood": 2, "escape_and_impact": 3, "escape_and_impact_taken_in": 6}\n', outcomes)
self.assertIn("Judge: claude-opus-5-5 at xhigh effort\nWorker: claude-sonnet-5-5 at high effort, routed by item 4's L of 2 and E + I of 3, taking in an E + I of 6\n", outcomes) self.assertIn('Judge: claude-opus-5-5 at xhigh effort\nWorker: {"model": "claude-sonnet-5-5", "effort": "high", "item": 4, "likelihood": 2, "escape_and_impact": 3, "escape_and_impact_taken_in": 6}\n', outcomes)
def test_a_rerun_resumes_an_open_chunk_on_the_rung_it_last_ran(self): def test_a_rerun_resumes_an_open_chunk_on_the_rung_it_last_ran(self):
checkout = Checkout(self) checkout = Checkout(self)
@@ -647,7 +651,7 @@ class Interrupt(unittest.TestCase):
self.assertEqual(run.stderr.strip().splitlines()[-2:], ["A or B?", "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(run.stderr.strip().splitlines()[-2:], ["A or B?", "the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun loop-claude on a terminal"])
[(copy, verdict)] = checkout.archived().items() [(copy, verdict)] = checkout.archived().items()
self.assertEqual(copy, (checkout.transcripts()[0]).read_text()) self.assertEqual(copy, (checkout.transcripts()[0]).read_text())
self.assertEqual(verdict, f"Task: {TASK}\n\n<UTC> Verdict: interrupt\n\nA or B?\n\nEvidence:\n> Shall I use A or B?\n\nJudge: judge-model\nWorker: worker-model\n\n<UTC> Stopped: the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun loop-claude on a terminal\n\nWorker: worker-model\n") self.assertEqual(verdict, f"Task: {TASK}\n\n<UTC> Verdict: interrupt\n\nA or B?\n\nEvidence:\n> Shall I use A or B?\n\nJudge: judge-model\nWorker: {OFF_LADDER}\n\n<UTC> Stopped: the human is needed to answer the question above, but stdin or stdout is not a terminal; rerun loop-claude on a terminal\n\nWorker: {OFF_LADDER}\n")
self.assertEqual(stat.S_IMODE((checkout.temp / "deep").stat().st_mode), 0o700) self.assertEqual(stat.S_IMODE((checkout.temp / "deep").stat().st_mode), 0o700)
self.assertIn(f"transcript: {checkout.archive() / 'proj'}/", run.stderr) self.assertIn(f"transcript: {checkout.archive() / 'proj'}/", run.stderr)
session = argument(run.calls[0], "--session-id") session = argument(run.calls[0], "--session-id")
@@ -857,7 +861,7 @@ class Reload(unittest.TestCase):
self.assertEqual(run.roles(), ["worker", "judge"] * 5) self.assertEqual(run.roles(), ["worker", "judge"] * 5)
self.assertIn("keeping the running script", run.stderr) self.assertIn("keeping the running script", run.stderr)
reloads = [json.loads(argv[1]) for argv in run.starts if argv[:1] == ["--reloaded"]] reloads = [json.loads(argv[1]) for argv in run.starts if argv[:1] == ["--reloaded"]]
self.assertEqual(reloads, [{"cycle_number": cycle, "root": str(checkout.root), "task": TASK, "unfinished_evidence": "working", "route": None} for cycle in (2, 3, 4)]) self.assertEqual(reloads, [{"cycle_number": cycle, "root": str(checkout.root), "task": TASK, "unfinished_evidence": "working", "route": OFF_LADDER_ROUTE} for cycle in (2, 3, 4)])
self.assertIn("=== cycle 5,", run.stdout) self.assertIn("=== cycle 5,", run.stdout)
outside = checkout.temp / "outside" outside = checkout.temp / "outside"
+137 -118
View File
@@ -23,7 +23,7 @@ from chunk_pick import DefaultPlan, LastCut
from loop_claude.effects import Effects, PYTHON_TIMEOUT, run_python from loop_claude.effects import Effects, PYTHON_TIMEOUT, run_python
from claude_code import entries, reply, session from claude_code import entries, reply, session
from failure import Failure from failure import Failure
from loop_claude.cycle.judge import Finished, Interrupt, QuotedAnswer, Unfinished, verdict_from from loop_claude.cycle.verdicts import Finished, Interrupt, QuotedAnswer, Unfinished
from loop_claude.cycle import interrupt, judge, prompts, retry, run, states, worker from loop_claude.cycle import interrupt, judge, prompts, retry, run, states, worker
from model_routing import ladder from model_routing import ladder
from model_routing.ladder import LADDER, Rung from model_routing.ladder import LADDER, Rung
@@ -35,6 +35,10 @@ from transcript_archive.location import project_archive
from model_routing.route import Route, route_from from model_routing.route import Route, route_from
from loop_claude.stop import Stop from loop_claude.stop import Stop
from utc_stamp import utc from utc_stamp import utc
from loop_claude.cycle.judge import verdict_from
# How the archive records a worker that runs off the ladder.
OFF_LADDER = '{"model": "worker-model"}'
CWD = pathlib.Path("/c") CWD = pathlib.Path("/c")
NOW = 1790000000 NOW = 1790000000
@@ -108,7 +112,7 @@ def ran(stdout="", code=0, stderr=""):
def judged(verdict, evidence="working", answer="", escalation="", release_ready=False): 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} reply = {"answer": answer, "highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 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})) return ran(json.dumps({"structured_output": reply}))
@@ -210,7 +214,7 @@ class Cycles(unittest.TestCase):
def test_a_finished_chunk_is_archived_and_its_session_deleted(self): def test_a_finished_chunk_is_archived_and_its_session_deleted(self):
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("finished")]) fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("finished")])
self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Finished("working")) self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Finished("working"))
self.assertEqual(self.archived_outcomes(), ["Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: finished\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: finished\n\nEvidence:\n> working\n\nJudge: judge-model\nWorker: {OFF_LADDER}\n"])
self.assertIsNone(session.transcript_file(self.session)) self.assertIsNone(session.transcript_file(self.session))
def test_a_fresh_worker_reads_the_preflights_facts_and_a_resumed_one_does_not(self): def test_a_fresh_worker_reads_the_preflights_facts_and_a_resumed_one_does_not(self):
@@ -249,14 +253,14 @@ class Cycles(unittest.TestCase):
self.assertIn("--session-id", workers[0]) self.assertIn("--session-id", workers[0])
self.assertIn("--resume", workers[1]) self.assertIn("--resume", workers[1])
self.assertIn("as the work remaining:\n\n> working\n\nThe chunk is finished once", workers[1][workers[1].index("-p") + 1]) self.assertIn("as the work remaining:\n\n> working\n\nThe chunk is finished once", workers[1][workers[1].index("-p") + 1])
self.assertEqual(self.archived_outcomes(), ["Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: unfinished\n\nEvidence:\n> working\n\nJudge: judge-model\nWorker: worker-model\n"] * 2) self.assertEqual(self.archived_outcomes(), [f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: unfinished\n\nEvidence:\n> working\n\nJudge: judge-model\nWorker: {OFF_LADDER}\n"] * 2)
def test_a_cycle_stopped_by_a_failure_or_ctrl_c_archives_what_its_session_holds(self): def test_a_cycle_stopped_by_a_failure_or_ctrl_c_archives_what_its_session_holds(self):
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[ran(code=1)] * 3) fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[ran(code=1)] * 3)
self.assertEqual(run.run_cycle(self.cycle(fake)).code, 1) self.assertEqual(run.run_cycle(self.cycle(fake)).code, 1)
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[KeyboardInterrupt()]) fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[KeyboardInterrupt()])
self.assertEqual(run.run_cycle(self.cycle(fake)), Stop(130, "")) self.assertEqual(run.run_cycle(self.cycle(fake)), Stop(130, ""))
self.assertEqual(self.archived_outcomes(), ["Task: Do it.\n\n2026-09-21T14:13:20Z Stopped: Ctrl-C\n\nWorker: worker-model\n", "Task: Do it.\n\n2026-09-21T14:13:20Z Stopped: the judge failed three times running: the judge exited 1\n\nWorker: worker-model\n"]) self.assertEqual(self.archived_outcomes(), [f"Task: Do it.\n\n2026-09-21T14:13:20Z Stopped: Ctrl-C\n\nWorker: {OFF_LADDER}\n", f"Task: Do it.\n\n2026-09-21T14:13:20Z Stopped: the judge failed three times running: the judge exited 1\n\nWorker: {OFF_LADDER}\n"])
def test_each_judge_reply_the_loop_rejects_is_archived_with_why_beside_the_verdict_that_follows(self): def test_each_judge_reply_the_loop_rejects_is_archived_with_why_beside_the_verdict_that_follows(self):
unfilled = ran(json.dumps({"structured_output": {"interrupt": False}})) unfilled = ran(json.dumps({"structured_output": {"interrupt": False}}))
@@ -268,7 +272,7 @@ class Cycles(unittest.TestCase):
"Task: Do it.\n\n" "Task: Do it.\n\n"
f"{stamp} Judge reply rejected: the judge's reply has no answer of type string\n\nReply:\n> {unfilled.stdout}\n\nJudge: judge-model\n\n" f"{stamp} Judge reply rejected: the judge's reply has no answer of type string\n\nReply:\n> {unfilled.stdout}\n\nJudge: judge-model\n\n"
f"{stamp} Judge reply rejected: the judge quoted 'never said', which is not in the transcript\n\nReply:\n> {misquoted.stdout}\n\nJudge: judge-model\n\n" f"{stamp} Judge reply rejected: the judge quoted 'never said', which is not in the transcript\n\nReply:\n> {misquoted.stdout}\n\nJudge: judge-model\n\n"
f"{stamp} Verdict: finished\n\nEvidence:\n> working\n\nJudge: judge-model\nWorker: worker-model\n"]) f"{stamp} Verdict: finished\n\nEvidence:\n> working\n\nJudge: judge-model\nWorker: {OFF_LADDER}\n"])
def test_stops_when_a_rejected_reply_cannot_be_archived(self): def test_stops_when_a_rejected_reply_cannot_be_archived(self):
self.archive.parent.mkdir(parents=True) self.archive.parent.mkdir(parents=True)
@@ -332,7 +336,7 @@ class Cycles(unittest.TestCase):
fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("interrupt"), judged("unfinished")], inputs=["/talk"], on_terminal_claude=[answer], git=[""]) fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)], claude=[judged("interrupt"), judged("unfinished")], inputs=["/talk"], on_terminal_claude=[answer], git=[""])
with contextlib.redirect_stderr(io.StringIO()): with contextlib.redirect_stderr(io.StringIO()):
self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Unfinished("working", entries_read=4)) self.assertEqual(run.run_cycle(self.cycle(fake)).verdict, Unfinished("working", entries_read=4))
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.assertEqual(self.archived_outcomes(), [f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: interrupt\n\nWhich one?\n\nEvidence:\n> working\n\nJudge: judge-model\nWorker: {OFF_LADDER}\n", f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: unfinished\n\nEvidence:\n> working\n\nJudge: judge-model\nWorker: {OFF_LADDER}\n"])
self.assertIn(str(self.session.id), fake.made("claude_on_terminal")[0]) self.assertIn(str(self.session.id), fake.made("claude_on_terminal")[0])
judge_prompts = [stdin for args, stdin in fake.made("claude")] judge_prompts = [stdin for args, stdin in fake.made("claude")]
self.assertEqual(len(judge_prompts), 2) self.assertEqual(len(judge_prompts), 2)
@@ -351,8 +355,8 @@ class Cycles(unittest.TestCase):
self.assertEqual(len(fake.made("stream_claude")), 4) 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.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()) 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" quoted = f"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: {OFF_LADDER}\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 nothing was 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: {OFF_LADDER}\n\n2026-09-21T14:13:20Z Stopped: the human is needed to answer the question above, but nothing was typed\n\nWorker: {OFF_LADDER}\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): 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")]) fake = FakeEffects(streams=[Worker(self.paths.claude_code_transcripts.parent)] * 2, claude=[judged("quoted", answer="Use A.", escalation="working"), judged("finished")])
@@ -364,8 +368,8 @@ class Cycles(unittest.TestCase):
self.assertEqual([args[args.index("--effort") + 1] for args in (first, resumed)], ["high", "medium"]) self.assertEqual([args[args.index("--effort") + 1] for args in (first, resumed)], ["high", "medium"])
self.assertTrue(resumed[resumed.index("-p") + 1].endswith(f"Continue the task. Your request for a higher rung went through: loop-claude runs you on {Routing.OPUS}. The escalation triggers that fired before this step are spent.{prompts.rungs_held(concluded.route, Routing.OPUS)}")) self.assertTrue(resumed[resumed.index("-p") + 1].endswith(f"Continue the task. Your request for a higher rung went through: loop-claude runs you on {Routing.OPUS}. The escalation triggers that fired before this step are spent.{prompts.rungs_held(concluded.route, Routing.OPUS)}"))
self.assertNotIn("went through", first[first.index("-p") + 1]) self.assertNotIn("went through", first[first.index("-p") + 1])
answered = f"Verdict: quoted answer\n\nWhich one?\n\n{prompts.QUOTE_SOURCES} says:\n> Use A.\n\nEvidence:\n> working\n\nEscalation:\n> working\n\nJudge: judge-model\nWorker: {Route(Routing.SONNET, 179, 2, 5)}\n" answered = f"Verdict: quoted answer\n\nWhich one?\n\n{prompts.QUOTE_SOURCES} says:\n> Use A.\n\nEvidence:\n> working\n\nEscalation:\n> working\n\nJudge: judge-model\nWorker: {Route(Routing.SONNET, 179, 2, 5).record()}\n"
stepped = f"Stepped up\n\nWorker: {Route(Routing.OPUS, 179, 2, 5, escalated_at=3)}\n" stepped = f"Stepped up\n\nWorker: {Route(Routing.OPUS, 179, 2, 5, escalated_at=3).record()}\n"
kept = "".join(self.archived_outcomes()) kept = "".join(self.archived_outcomes())
self.assertIn(f"Z {answered}\n20", kept) self.assertIn(f"Z {answered}\n20", kept)
self.assertIn(f"Z {stepped}", kept) self.assertIn(f"Z {stepped}", kept)
@@ -377,10 +381,10 @@ class Cycles(unittest.TestCase):
with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()): 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 nothing was 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()) 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"Evidence:\n> working\n\nEscalation:\n> working\n\nJudge: judge-model\nWorker: {Route(Routing.SONNET, 179, 2, 5).record()}\n", kept)
self.assertIn(f"Stepped up\n\nWorker: {Route(Routing.OPUS, 179, 2, 5, escalated_at=6)}\n", kept) self.assertIn(f"Stepped up\n\nWorker: {Route(Routing.OPUS, 179, 2, 5, escalated_at=6).record()}\n", kept)
def test_a_ruling_steps_the_route_only_on_an_escalation_from_the_rung_its_bundled_l_picks(self): def test_a_ruling_steps_the_route_only_on_an_escalation_from_the_rung_its_taken_in_l_picks(self):
cycle = dataclasses.replace(self.cycle(FakeEffects()), anchor=Routing.OPUS, route=Route(Routing.OPUS, 3, 3, 4)) cycle = dataclasses.replace(self.cycle(FakeEffects()), anchor=Routing.OPUS, route=Route(Routing.OPUS, 3, 3, 4))
for ruling in (Interrupt("e", "q", entries_read=3), QuotedAnswer("e", "q", "A.", entries_read=3)): for ruling in (Interrupt("e", "q", entries_read=3), QuotedAnswer("e", "q", "A.", entries_read=3)):
with self.subTest(ruling=ruling): with self.subTest(ruling=ruling):
@@ -495,7 +499,7 @@ class Cycles(unittest.TestCase):
stop = run.run_cycle(self.cycle(fake)) stop = run.run_cycle(self.cycle(fake))
self.assertEqual(stop, Stop(1, f"could not delete {folder}: Permission denied; delete every file and folder matching {folder}*, then rerun loop-claude; a rerun before that resumes the finished chunk's session")) self.assertEqual(stop, Stop(1, f"could not delete {folder}: Permission denied; delete every file and folder matching {folder}*, then rerun loop-claude; a rerun before that resumes the finished chunk's session"))
self.assertTrue(session.session_open(self.session)) self.assertTrue(session.session_open(self.session))
self.assertEqual(self.archived_outcomes(), [f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: finished\n\nEvidence:\n> working\n\nJudge: judge-model\nWorker: worker-model\n\n2026-09-21T14:13:20Z Stopped: {stop.reason}\n\nWorker: worker-model\n"]) self.assertEqual(self.archived_outcomes(), [f"Task: Do it.\n\n2026-09-21T14:13:20Z Verdict: finished\n\nEvidence:\n> working\n\nJudge: judge-model\nWorker: {OFF_LADDER}\n\n2026-09-21T14:13:20Z Stopped: {stop.reason}\n\nWorker: {OFF_LADDER}\n"])
def test_stops_when_the_worker_leaves_no_transcript(self): def test_stops_when_the_worker_leaves_no_transcript(self):
fake = FakeEffects(streams=[Streamed(0)]) fake = FakeEffects(streams=[Streamed(0)])
@@ -736,6 +740,16 @@ TODO = """# todo
""" """
def unfinished(likelihood=0, escalated_at=None):
"""An unfinished verdict: the worker took in an item of that L, 0 for none, and the judge found an escalation after reading escalated_at transcript entries, None for none."""
return Unfinished("e", likelihood, "round 2: 🔴" if escalated_at is not None else "", entries_read=escalated_at)
def interrupted(likelihood=0, escalated_at=None):
"""An interrupt, its arguments as unfinished's."""
return Interrupt("e", "q", "round 2: 🔴" if escalated_at is not None else "", likelihood, entries_read=escalated_at)
class Routing(unittest.TestCase): class Routing(unittest.TestCase):
OPUS = Rung("claude-opus-5-5", "medium") OPUS = Rung("claude-opus-5-5", "medium")
HIGH = Rung("claude-opus-5-5", "high") HIGH = Rung("claude-opus-5-5", "high")
@@ -774,47 +788,47 @@ class Routing(unittest.TestCase):
self.assertEqual(routing.first_route(self.OPUS, None), Route(self.OPUS)) self.assertEqual(routing.first_route(self.OPUS, None), Route(self.OPUS))
def test_steps_up_a_rung_after_every_second_unfinished_verdict(self): def test_steps_up_a_rung_after_every_second_unfinished_verdict(self):
once = routing.stepped(self.OPUS, Route(self.OPUS, 3, 3, 4), 0, None) once = routing.after_unfinished(self.OPUS, Route(self.OPUS, 3, 3, 4), unfinished())
self.assertEqual(once, Route(self.OPUS, 3, 3, 4, unfinished=1)) self.assertEqual(once, Route(self.OPUS, 3, 3, 4, unfinished=1))
self.assertEqual(routing.stepped(self.OPUS, once, 0, None), Route(self.HIGH, 3, 3, 4)) self.assertEqual(routing.after_unfinished(self.OPUS, once, unfinished()), Route(self.HIGH, 3, 3, 4))
self.assertEqual(routing.stepped(self.OPUS, Route(LADDER[-1], unfinished=1), 0, None).rung, LADDER[-1]) self.assertEqual(routing.after_unfinished(self.OPUS, Route(LADDER[-1], unfinished=1), unfinished()).rung, LADDER[-1])
def test_steps_up_to_the_rung_a_bundled_items_l_picks_and_never_down(self): def test_steps_up_to_the_rung_a_taken_in_items_l_picks_and_never_down(self):
self.assertEqual(routing.stepped(self.OPUS, Route(self.OPUS), 4, None).rung, self.HIGH) self.assertEqual(routing.after_unfinished(self.OPUS, Route(self.OPUS), unfinished(4)).rung, self.HIGH)
self.assertEqual(routing.stepped(self.OPUS, Route(self.XHIGH), 4, None).rung, self.XHIGH) self.assertEqual(routing.after_unfinished(self.OPUS, Route(self.XHIGH), unfinished(4)).rung, self.XHIGH)
self.assertEqual(routing.stepped(self.OPUS, Route(self.OPUS, unfinished=1), 4, None).rung, self.XHIGH) self.assertEqual(routing.after_unfinished(self.OPUS, Route(self.OPUS, unfinished=1), unfinished(4)).rung, self.XHIGH)
def test_steps_up_from_a_rung_below_the_projects_one_rung_at_a_time(self): def test_steps_up_from_a_rung_below_the_projects_one_rung_at_a_time(self):
low = Route(self.SONNET, 3, 1, 3, unfinished=1) low = Route(self.SONNET, 3, 1, 3, unfinished=1)
self.assertEqual(routing.stepped(self.OPUS, low, 0, None).rung, self.OPUS) self.assertEqual(routing.after_unfinished(self.OPUS, low, unfinished()).rung, self.OPUS)
self.assertEqual(routing.stepped(self.OPUS, Route(low.rung, 3, 1, 3), 0, None).rung, low.rung) self.assertEqual(routing.after_unfinished(self.OPUS, Route(low.rung, 3, 1, 3), unfinished()).rung, low.rung)
self.assertEqual(routing.stepped(self.OPUS, Route(low.rung, 3, 1, 3), 3, None).rung, self.OPUS) self.assertEqual(routing.after_unfinished(self.OPUS, Route(low.rung, 3, 1, 3), unfinished(3)).rung, self.OPUS)
def test_steps_up_a_rung_on_an_escalation_the_judge_found_up_to_two_above_the_items_rung_marking_the_transcript_entries_it_read(self): def test_steps_up_a_rung_on_an_escalation_the_judge_found_up_to_two_above_the_items_rung_marking_the_transcript_entries_it_read(self):
self.assertEqual(routing.stepped(self.OPUS, Route(self.HIGH, 3, 4, 5), 0, 7), Route(self.XHIGH, 3, 4, 5, escalated_at=7)) self.assertEqual(routing.after_unfinished(self.OPUS, Route(self.HIGH, 3, 4, 5), unfinished(escalated_at=7)), Route(self.XHIGH, 3, 4, 5, escalated_at=7))
self.assertEqual(routing.stepped(self.OPUS, Route(self.XHIGH, 3, 4, 5, escalated_at=7), 0, 9), Route(self.MAX, 3, 4, 5, escalated_at=9)) self.assertEqual(routing.after_unfinished(self.OPUS, Route(self.XHIGH, 3, 4, 5, escalated_at=7), unfinished(escalated_at=9)), Route(self.MAX, 3, 4, 5, escalated_at=9))
self.assertEqual(routing.stepped(self.OPUS, Route(self.MAX, 3, 4, 5, escalated_at=9), 0, 12), Route(self.MAX, 3, 4, 5, unfinished=1, escalated_at=9)) self.assertEqual(routing.after_unfinished(self.OPUS, Route(self.MAX, 3, 4, 5, escalated_at=9), unfinished(escalated_at=12)), Route(self.MAX, 3, 4, 5, unfinished=1, escalated_at=9))
self.assertEqual(routing.stepped(self.OPUS, Route(self.HIGH, 3, 4, 5, unfinished=1), 0, 7), Route(self.XHIGH, 3, 4, 5, escalated_at=7)) self.assertEqual(routing.after_unfinished(self.OPUS, Route(self.HIGH, 3, 4, 5, unfinished=1), unfinished(escalated_at=7)), Route(self.XHIGH, 3, 4, 5, escalated_at=7))
self.assertEqual(routing.stepped(self.OPUS, Route(self.XHIGH), 0, 7), Route(self.XHIGH, unfinished=1)) self.assertEqual(routing.after_unfinished(self.OPUS, Route(self.XHIGH), unfinished(escalated_at=7)), Route(self.XHIGH, unfinished=1))
self.assertEqual(routing.stepped(self.OPUS, Route(self.SONNET, 3, 2, 4), 4, 7), Route(self.HIGH, 3, 2, 4, unfinished=1)) self.assertEqual(routing.after_unfinished(self.OPUS, Route(self.SONNET, 3, 2, 4), unfinished(4, escalated_at=7)), Route(self.HIGH, 3, 2, 4, unfinished=1))
def test_keeps_the_mark_through_a_step_no_escalation_took(self): def test_keeps_the_mark_through_a_step_no_escalation_took(self):
self.assertEqual(routing.stepped(self.OPUS, Route(self.OPUS, 3, 3, 4, unfinished=1, escalated_at=5), 0, None), Route(self.HIGH, 3, 3, 4, escalated_at=5)) self.assertEqual(routing.after_unfinished(self.OPUS, Route(self.OPUS, 3, 3, 4, unfinished=1, escalated_at=5), unfinished()), Route(self.HIGH, 3, 3, 4, escalated_at=5))
def test_steps_up_a_rung_as_the_judge_interrupts_up_to_two_above_the_items_rung_without_counting_an_unfinished_verdict(self): def test_steps_up_a_rung_as_the_judge_interrupts_up_to_two_above_the_items_rung_without_counting_an_unfinished_verdict(self):
self.assertEqual(routing.stepped_by_ruling(self.OPUS, Route(self.HIGH, 3, 4, 5, unfinished=1), 0, 7), Route(self.XHIGH, 3, 4, 5, escalated_at=7)) self.assertEqual(routing.after_ruling(self.OPUS, Route(self.HIGH, 3, 4, 5, unfinished=1), interrupted(escalated_at=7)), Route(self.XHIGH, 3, 4, 5, escalated_at=7))
self.assertEqual(routing.stepped_by_ruling(self.OPUS, Route(self.XHIGH, 3, 4, 5, escalated_at=7), 0, 9), Route(self.MAX, 3, 4, 5, escalated_at=9)) self.assertEqual(routing.after_ruling(self.OPUS, Route(self.XHIGH, 3, 4, 5, escalated_at=7), interrupted(escalated_at=9)), Route(self.MAX, 3, 4, 5, escalated_at=9))
self.assertEqual(routing.stepped_by_ruling(self.OPUS, Route(self.MAX, 3, 4, 5, unfinished=1, escalated_at=9), 0, 12), Route(self.MAX, 3, 4, 5, unfinished=1, escalated_at=9)) self.assertEqual(routing.after_ruling(self.OPUS, Route(self.MAX, 3, 4, 5, unfinished=1, escalated_at=9), interrupted(escalated_at=12)), Route(self.MAX, 3, 4, 5, unfinished=1, escalated_at=9))
self.assertEqual(routing.stepped_by_ruling(self.OPUS, Route(self.SONNET, 3, 2, 4), 0, 7), Route(self.OPUS, 3, 2, 4, escalated_at=7)) self.assertEqual(routing.after_ruling(self.OPUS, Route(self.SONNET, 3, 2, 4), interrupted(escalated_at=7)), Route(self.OPUS, 3, 2, 4, escalated_at=7))
self.assertEqual(routing.stepped_by_ruling(self.OPUS, Route(self.HIGH, 3, 4, 5, unfinished=1, escalated_at=2), 4, None), Route(self.HIGH, 3, 4, 5, unfinished=1, escalated_at=2)) self.assertEqual(routing.after_ruling(self.OPUS, Route(self.HIGH, 3, 4, 5, unfinished=1, escalated_at=2), interrupted(4)), Route(self.HIGH, 3, 4, 5, unfinished=1, escalated_at=2))
def test_raises_the_worker_to_a_taken_in_items_rung_above_the_escalation_cap_without_a_step_as_the_judge_interrupts(self): def test_raises_the_worker_to_a_taken_in_items_rung_above_the_escalation_cap_without_a_step_as_the_judge_interrupts(self):
self.assertEqual(routing.stepped_by_ruling(self.OPUS, Route(self.OPUS, 3, 1, 3, escalated_at=2), 4, 7), Route(self.HIGH, 3, 1, 3, escalated_at=2)) self.assertEqual(routing.after_ruling(self.OPUS, Route(self.OPUS, 3, 1, 3, escalated_at=2), interrupted(4, escalated_at=7)), Route(self.HIGH, 3, 1, 3, escalated_at=2))
def test_steps_up_from_the_rung_a_taken_in_item_picks_as_the_judge_interrupts(self): def test_steps_up_from_the_rung_a_taken_in_item_picks_as_the_judge_interrupts(self):
self.assertEqual(routing.stepped_by_ruling(self.OPUS, Route(self.OPUS, 3, 3, 4), 4, 7), Route(self.XHIGH, 3, 3, 4, escalated_at=7)) self.assertEqual(routing.after_ruling(self.OPUS, Route(self.OPUS, 3, 3, 4), interrupted(4, escalated_at=7)), Route(self.XHIGH, 3, 3, 4, escalated_at=7))
self.assertEqual(routing.stepped_by_ruling(self.OPUS, Route(self.XHIGH, 3, 4, 5), 4, 7), Route(self.MAX, 3, 4, 5, escalated_at=7)) self.assertEqual(routing.after_ruling(self.OPUS, Route(self.XHIGH, 3, 4, 5), interrupted(4, escalated_at=7)), Route(self.MAX, 3, 4, 5, escalated_at=7))
self.assertEqual(routing.stepped_by_ruling(self.OPUS, Route(self.MAX, 3, 4, 5, unfinished=1), 4, 7), Route(self.MAX, 3, 4, 5, unfinished=1)) self.assertEqual(routing.after_ruling(self.OPUS, Route(self.MAX, 3, 4, 5, unfinished=1), interrupted(4, escalated_at=7)), Route(self.MAX, 3, 4, 5, unfinished=1))
def test_keeps_an_e_plus_i_taken_in_only_where_it_picks_a_higher_review_rung(self): def test_keeps_an_e_plus_i_taken_in_only_where_it_picks_a_higher_review_rung(self):
taken = Route(self.OPUS, 3, 3, 4).taking_in(6) taken = Route(self.OPUS, 3, 3, 4).taking_in(6)
@@ -829,8 +843,8 @@ class Routing(unittest.TestCase):
self.assertEqual(Route(self.OPUS).taking_in(0), Route(self.OPUS)) self.assertEqual(Route(self.OPUS).taking_in(0), Route(self.OPUS))
def test_a_rung_an_edit_took_off_the_ladder_counts_as_the_projects(self): def test_a_rung_an_edit_took_off_the_ladder_counts_as_the_projects(self):
self.assertEqual(routing.stepped(self.OPUS, Route(Rung("claude-opus-5-5", "low")), 0, None).rung, self.OPUS) self.assertEqual(routing.after_unfinished(self.OPUS, Route(Rung("claude-opus-5-5", "low")), unfinished()).rung, self.OPUS)
self.assertEqual(routing.stepped(self.OPUS, Route(Rung("claude-opus-5-5", "low")), 2, None).rung, self.OPUS) self.assertEqual(routing.after_unfinished(self.OPUS, Route(Rung("claude-opus-5-5", "low")), unfinished(2)).rung, self.OPUS)
def test_runs_the_judge_on_the_rung_its_chunks_items_e_plus_i_picks_never_below_the_projects(self): def test_runs_the_judge_on_the_rung_its_chunks_items_e_plus_i_picks_never_below_the_projects(self):
self.assertEqual(routing.judge_rung("claude-opus-5-5", Route(self.OPUS, 3, 3, 5)), self.HIGH) self.assertEqual(routing.judge_rung("claude-opus-5-5", Route(self.OPUS, 3, 3, 5)), self.HIGH)
@@ -864,46 +878,47 @@ class Routing(unittest.TestCase):
without_i = TODO.replace("| E | I | R |", "| E | R |").replace("|---|---|---|---|---|---|---|---|---|---|---|", "|---|---|---|---|---|---|---|---|---|---|").replace("| 4 | 3 | 5 | 10 |", "| 4 | 3 | 10 |").replace("| 4 | 2 | 3 | 7 |", "| 4 | 2 | 7 |").replace("| 1 | 1 | 1 | 1 |", "| 1 | 1 | 1 |") without_i = TODO.replace("| E | I | R |", "| E | R |").replace("|---|---|---|---|---|---|---|---|---|---|---|", "|---|---|---|---|---|---|---|---|---|---|").replace("| 4 | 3 | 5 | 10 |", "| 4 | 3 | 10 |").replace("| 4 | 2 | 3 | 7 |", "| 4 | 2 | 7 |").replace("| 1 | 1 | 1 | 1 |", "| 1 | 1 | 1 |")
self.assertIsNone(routing.routed_item(without_i, NO_CUT)) self.assertIsNone(routing.routed_item(without_i, NO_CUT))
def test_archives_the_route_in_a_line_it_reads_back(self): def test_archives_the_route_as_a_json_record_it_reads_back_field_by_field(self):
route = Route(self.HIGH, 3, 4, 5) route = Route(self.HIGH, 3, 4, 5)
self.assertEqual(str(route), "claude-opus-5-5 at high effort, routed by item 3's L of 4 and E + I of 5") self.assertEqual(route.record(), '{"model": "claude-opus-5-5", "effort": "high", "item": 3, "likelihood": 4, "escape_and_impact": 5}')
self.assertEqual(route_from(str(route)), route) self.assertEqual(route_from(route.record()), route)
self.assertEqual(route_from(str(Route(self.HIGH))), Route(self.HIGH)) self.assertEqual(Route(Rung("worker-model")).record(), '{"model": "worker-model"}')
self.assertEqual(str(Route(Rung("worker-model"))), "worker-model") self.assertEqual(route_from('{"model": "worker-model"}'), Route(Rung("worker-model")))
self.assertIsNone(route_from("worker-model")) marked = Route(self.HIGH, 3, 4, 5, escape_and_impact_taken_in=7, escalated_at=12)
taken = Route(self.HIGH, 3, 4, 5, escape_and_impact_taken_in=7) self.assertEqual(marked.record(), '{"model": "claude-opus-5-5", "effort": "high", "item": 3, "likelihood": 4, "escape_and_impact": 5, "escape_and_impact_taken_in": 7, "escalated_at": 12}')
self.assertEqual(str(taken), "claude-opus-5-5 at high effort, routed by item 3's L of 4 and E + I of 5, taking in an E + I of 7") self.assertEqual(route_from(marked.record()), marked)
self.assertEqual(route_from(str(taken)), taken) self.assertEqual(route_from(Route(self.HIGH, escalated_at=3).record()), Route(self.HIGH, escalated_at=3))
unrouted = Route(self.HIGH, escape_and_impact_taken_in=6)
self.assertEqual(str(unrouted), "claude-opus-5-5 at high effort, taking in an E + I of 6")
self.assertEqual(route_from(str(unrouted)), unrouted)
self.assertIsNone(route_from("claude-opus-5-5 at high effort, taking in an E + I of 9"))
self.assertIsNone(route_from("claude-opus-5-5 at high effort, routed by item 3's L of 4 and E + I of 5, taking in an E + I of 5"))
marked = Route(self.HIGH, 3, 4, 5, escalated_at=12, escape_and_impact_taken_in=7)
self.assertEqual(str(marked), "claude-opus-5-5 at high effort, routed by item 3's L of 4 and E + I of 5, taking in an E + I of 7, escalated at transcript entry 12")
self.assertEqual(route_from(str(marked)), marked)
self.assertEqual(route_from(str(Route(self.HIGH, escalated_at=3))), Route(self.HIGH, escalated_at=3))
def test_reads_no_route_from_a_line_whose_levels_are_off_their_scales_or_an_r_plus_c_route_wrote(self): def test_leaves_the_count_of_unfinished_verdicts_out_of_the_record_so_a_rerun_restarts_it(self):
for line in ("claude-opus-5-5 at high effort, routed by item 3's L of 5 and E + I of 5", "claude-opus-5-5 at high effort, routed by item 3's L of 0 and E + I of 5", "claude-opus-5-5 at high effort, routed by item 3's L of 4 and E + I of 9", "claude-opus-5-5 at high effort, routed by item 3's L of 4 and E + I of 1", "claude-opus-5-5 at high effort, routed by item 3's R + C of 11"): self.assertEqual(route_from(Route(self.HIGH, 3, 4, 5, unfinished=1).record()), Route(self.HIGH, 3, 4, 5))
def test_reads_no_route_from_a_record_of_unknown_or_mistyped_fields_or_levels_off_their_scales(self):
for record in ('{"effort": "high"}', '{"model": "claude-opus-5-5", "effort": "high", "unfinished": 1}', '{"model": "claude-opus-5-5", "item": "3"}', '{"model": "claude-opus-5-5", "effort": "high", "escalated_at": -3}', '{"model": "claude-opus-5-5", "item": true, "likelihood": 4, "escape_and_impact": 5}', '{"model": "claude-opus-5-5", "effort": "high", "item": 3, "likelihood": 5, "escape_and_impact": 5}', '{"model": "claude-opus-5-5", "effort": "high", "escape_and_impact_taken_in": 9}', '["claude-opus-5-5"]', '{"model": '):
with self.subTest(record=record):
self.assertIsNone(route_from(record))
def test_reads_the_route_from_a_line_loop_claude_wrote_before_it_archived_json(self):
self.assertEqual(route_from("claude-opus-5-5 at high effort, routed by item 3's L of 4 and E + I of 5"), Route(self.HIGH, 3, 4, 5))
self.assertEqual(route_from("claude-opus-5-5 at high effort"), Route(self.HIGH))
self.assertEqual(route_from("claude-opus-5-5 at high effort, routed by item 3's L of 4 and E + I of 5, taking in an E + I of 7, escalated at transcript entry 12"), Route(self.HIGH, 3, 4, 5, escape_and_impact_taken_in=7, escalated_at=12))
self.assertEqual(route_from("claude-opus-5-5 at high effort, taking in an E + I of 6"), Route(self.HIGH, escape_and_impact_taken_in=6))
for line in ("worker-model", "claude-opus-5-5 at high effort, routed by item 3's L of 5 and E + I of 5", "claude-opus-5-5 at high effort, routed by item 3's L of 4 and E + I of 5, taking in an E + I of 5", "claude-opus-5-5 at high effort, routed by item 3's R + C of 11"):
with self.subTest(line=line): with self.subTest(line=line):
self.assertIsNone(route_from(line)) self.assertIsNone(route_from(line))
def test_keeps_a_chunks_route_or_its_archived_one_at_or_above_the_rung_its_item_picks_and_else_routes_afresh(self): def test_keeps_a_chunks_route_or_its_archived_one_at_or_above_the_rung_its_item_picks_and_else_routes_afresh(self):
def run_with(route=None):
return main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="", route=route)
item = routing.routed_item(TODO, NO_CUT) item = routing.routed_item(TODO, NO_CUT)
archived = Route(self.XHIGH, 3, 4, 5) archived = Route(self.XHIGH, 3, 4, 5)
def never(): def never():
raise AssertionError("not asked") raise AssertionError("not asked")
self.assertIsNone(main.routed(run_with(archived), None, never, never).route) self.assertEqual(main.routed(archived, None, "worker-model", never, never), Route(Rung("worker-model")))
self.assertEqual(main.routed(run_with(archived), self.OPUS, never, never).route, archived) self.assertEqual(main.routed(archived, self.OPUS, "claude-opus-5-5", never, never), archived)
self.assertEqual(main.routed(run_with(), self.OPUS, lambda: archived, never).route, archived) self.assertEqual(main.routed(None, self.OPUS, "claude-opus-5-5", lambda: archived, never), archived)
self.assertEqual(main.routed(run_with(), self.OPUS, lambda: None, lambda: item).route, Route(self.HIGH, 3, 4, 5)) self.assertEqual(main.routed(None, self.OPUS, "claude-opus-5-5", lambda: None, lambda: item), Route(self.HIGH, 3, 4, 5))
self.assertEqual(main.routed(run_with(Route(self.SONNET)), self.OPUS, never, lambda: None).route, Route(self.OPUS)) self.assertEqual(main.routed(Route(self.SONNET), self.OPUS, "claude-opus-5-5", never, lambda: None), Route(self.OPUS))
cheap = Route(self.SONNET, 4, 2, 3) cheap = Route(self.SONNET, 4, 2, 3)
self.assertEqual(main.routed(run_with(cheap), self.OPUS, never, never).route, cheap) self.assertEqual(main.routed(cheap, self.OPUS, "claude-opus-5-5", never, never), cheap)
self.assertEqual(main.routed(run_with(Route(Rung("claude-haiku-5-5", "max"), 4, 2, 3)), self.OPUS, never, lambda: None).route, Route(self.OPUS)) self.assertEqual(main.routed(Route(Rung("claude-haiku-5-5", "max"), 4, 2, 3), self.OPUS, "claude-opus-5-5", never, lambda: None), Route(self.OPUS))
class RouteSources(unittest.TestCase): class RouteSources(unittest.TestCase):
@@ -929,7 +944,7 @@ class RouteSources(unittest.TestCase):
self.assertIsNone(main.archived_route(archive, opened)) self.assertIsNone(main.archived_route(archive, opened))
route = Route(Rung("claude-opus-5-5", "high"), 3, 4, 5) route = Route(Rung("claude-opus-5-5", "high"), 3, 4, 5)
with contextlib.redirect_stderr(io.StringIO()): with contextlib.redirect_stderr(io.StringIO()):
self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.unfinished(str(route), "working", "j", ""), NOW)) self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.unfinished(route.record(), "working", "j", ""), NOW))
self.assertEqual(main.archived_route(archive, opened), route) self.assertEqual(main.archived_route(archive, opened), route)
(chunk,) = archive.iterdir() (chunk,) = archive.iterdir()
chunk.chmod(0) chunk.chmod(0)
@@ -946,13 +961,18 @@ class Steps(unittest.TestCase):
def test_a_finished_verdict_clears_the_route_and_the_evidence(self): def test_a_finished_verdict_clears_the_route_and_the_evidence(self):
run_with = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="old", route=Route(self.OPUS)) run_with = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="old", route=Route(self.OPUS))
self.assertEqual(main.after_verdict(run_with, self.OPUS, Finished("x")), dataclasses.replace(run_with, route=None, unfinished_evidence="")) self.assertEqual(main.after_verdict(run_with, self.OPUS, run.Concluded(Finished("x"), run_with.route)), dataclasses.replace(run_with, route=None, unfinished_evidence=""))
self.assertEqual(main.after_verdict(run_with, self.OPUS, Unfinished("new", 4)), dataclasses.replace(run_with, route=Route(Rung("claude-opus-5-5", "high"), unfinished=1), unfinished_evidence="new")) self.assertEqual(main.after_verdict(run_with, self.OPUS, run.Concluded(Unfinished("new", 4), run_with.route)), dataclasses.replace(run_with, route=Route(Rung("claude-opus-5-5", "high"), unfinished=1), unfinished_evidence="new"))
def test_keeps_the_route_its_cycle_ended_on_off_the_ladder(self):
off_ladder = Route(Rung("worker-model"))
run_with = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="")
self.assertEqual(main.after_verdict(run_with, None, run.Concluded(Unfinished("new", 4, "round 2: 🔴", entries_read=9), off_ladder)).route, off_ladder)
def test_an_unfinished_verdicts_escalation_marks_the_transcript_entries_the_judge_read(self): def test_an_unfinished_verdicts_escalation_marks_the_transcript_entries_the_judge_read(self):
run_with = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="", route=Route(self.OPUS, 3, 3, 4, escalated_at=2)) run_with = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="", route=Route(self.OPUS, 3, 3, 4, escalated_at=2))
self.assertEqual(main.after_verdict(run_with, self.OPUS, Unfinished("new", 0, "round 2: 🔴", entries_read=9)).route, Route(Rung("claude-opus-5-5", "high"), 3, 3, 4, escalated_at=9)) self.assertEqual(main.after_verdict(run_with, self.OPUS, run.Concluded(Unfinished("new", 0, "round 2: 🔴", entries_read=9), run_with.route)).route, Route(Rung("claude-opus-5-5", "high"), 3, 3, 4, escalated_at=9))
self.assertEqual(main.after_verdict(run_with, self.OPUS, Unfinished("new", entries_read=9)).route, Route(self.OPUS, 3, 3, 4, unfinished=1, escalated_at=2)) self.assertEqual(main.after_verdict(run_with, self.OPUS, run.Concluded(Unfinished("new", entries_read=9), run_with.route)).route, Route(self.OPUS, 3, 3, 4, unfinished=1, escalated_at=2))
def test_archives_a_step_up_as_it_happens_so_a_rerun_resumes_on_it(self): def test_archives_a_step_up_as_it_happens_so_a_rerun_resumes_on_it(self):
with tempfile.TemporaryDirectory() as home: with tempfile.TemporaryDirectory() as home:
@@ -963,18 +983,17 @@ class Steps(unittest.TestCase):
transcript.write_text(json.dumps({"type": "queue-operation", "timestamp": "1"}) + "\n") transcript.write_text(json.dumps({"type": "queue-operation", "timestamp": "1"}) + "\n")
before = Route(self.OPUS, 3, 3, 4) before = Route(self.OPUS, 3, 3, 4)
with contextlib.redirect_stderr(io.StringIO()): with contextlib.redirect_stderr(io.StringIO()):
self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.unfinished(str(before), "working", "j", ""), NOW)) self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.unfinished(before.record(), "working", "j", ""), NOW))
after = main.after_verdict(main.LoopRun(cycle_number=1, root="/r", task="Do it.", unfinished_evidence="", route=before), self.OPUS, Unfinished("working", 4)) after = main.after_verdict(main.LoopRun(cycle_number=1, root="/r", task="Do it.", unfinished_evidence=""), self.OPUS, run.Concluded(Unfinished("working", 4), before))
self.assertIsNone(main.archive_step(archive, opened, after, before, FakeEffects().effects())) self.assertIsNone(main.archive_step(archive, opened, "Do it.", before, after.route, FakeEffects().effects()))
self.assertEqual(main.archived_route(archive, opened), Route(Rung("claude-opus-5-5", "high"), 3, 3, 4)) self.assertEqual(main.archived_route(archive, opened), Route(Rung("claude-opus-5-5", "high"), 3, 3, 4))
self.assertIsNone(main.archive_step(archive, opened, after, after.route, FakeEffects().effects())) self.assertIsNone(main.archive_step(archive, opened, "Do it.", after.route, after.route, FakeEffects().effects()))
self.assertIsNone(main.archive_step(archive, opened, after, None, FakeEffects().effects())) finished = main.after_verdict(after, self.OPUS, run.Concluded(Finished("done"), after.route))
finished = main.after_verdict(after, self.OPUS, Finished("done")) self.assertIsNone(main.archive_step(archive, opened, "Do it.", after.route, finished.route, FakeEffects().effects()))
self.assertIsNone(main.archive_step(archive, opened, finished, after.route, FakeEffects().effects()))
self.assertEqual(main.archived_route(archive, opened), Route(Rung("claude-opus-5-5", "high"), 3, 3, 4)) self.assertEqual(main.archived_route(archive, opened), Route(Rung("claude-opus-5-5", "high"), 3, 3, 4))
blocked = pathlib.Path(home, "blocked") blocked = pathlib.Path(home, "blocked")
blocked.write_text("") blocked.write_text("")
stop = main.archive_step(blocked, opened, after, before, FakeEffects().effects()) stop = main.archive_step(blocked, opened, "Do it.", before, after.route, FakeEffects().effects())
self.assertEqual((stop.code, stop.reason.split(":")[0]), (1, "could not archive the transcript")) self.assertEqual((stop.code, stop.reason.split(":")[0]), (1, "could not archive the transcript"))
def test_archives_a_higher_e_plus_i_taken_in_so_a_rerun_keeps_it(self): def test_archives_a_higher_e_plus_i_taken_in_so_a_rerun_keeps_it(self):
@@ -986,9 +1005,9 @@ class Steps(unittest.TestCase):
transcript.write_text(json.dumps({"type": "queue-operation", "timestamp": "1"}) + "\n") transcript.write_text(json.dumps({"type": "queue-operation", "timestamp": "1"}) + "\n")
before = Route(self.OPUS, 3, 3, 4) before = Route(self.OPUS, 3, 3, 4)
with contextlib.redirect_stderr(io.StringIO()): with contextlib.redirect_stderr(io.StringIO()):
self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.unfinished(str(before), "working", "j", ""), NOW)) self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.unfinished(before.record(), "working", "j", ""), NOW))
after = main.after_verdict(main.LoopRun(cycle_number=1, root="/r", task="Do it.", unfinished_evidence="", route=before), self.OPUS, Unfinished("working", 0, bundled_escape_and_impact=6)) after = main.after_verdict(main.LoopRun(cycle_number=1, root="/r", task="Do it.", unfinished_evidence=""), self.OPUS, run.Concluded(Unfinished("working", highest_escape_and_impact_taken_in=6), before))
self.assertIsNone(main.archive_step(archive, opened, after, before, FakeEffects().effects())) self.assertIsNone(main.archive_step(archive, opened, "Do it.", before, after.route, FakeEffects().effects()))
self.assertEqual(main.archived_route(archive, opened), Route(self.OPUS, 3, 3, 4, escape_and_impact_taken_in=6)) self.assertEqual(main.archived_route(archive, opened), Route(self.OPUS, 3, 3, 4, escape_and_impact_taken_in=6))
@@ -1297,48 +1316,48 @@ class Grounded(unittest.TestCase):
class Verdict(unittest.TestCase): class Verdict(unittest.TestCase):
def test_needs_every_field_the_schema_requires(self): 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": "", "release_ready": False}), Finished("e")) self.assertEqual(verdict_from({"highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 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({"highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 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({"highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 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({"highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 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({"highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 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({"highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 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({"highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 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({"highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 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({"highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 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({"highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 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({"highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 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")) 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): 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": "", "release_ready": False} reply = {"answer": "", "highest_escape_and_impact_taken_in": 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, "highest_likelihood_taken_in": 4}), Unfinished("e", 4))
self.assertEqual(verdict_from({**reply, "bundled": True}), Failure("the judge's reply has no bundled of type integer")) self.assertEqual(verdict_from({**reply, "highest_likelihood_taken_in": True}), Failure("the judge's reply has no highest_likelihood_taken_in of type integer"))
for bundled in (5, 13, -1): for highest_likelihood_taken_in in (5, 13, -1):
with self.subTest(bundled=bundled): with self.subTest(highest_likelihood_taken_in=highest_likelihood_taken_in):
self.assertEqual(verdict_from({**reply, "bundled": bundled}), Unfinished("e", 0)) self.assertEqual(verdict_from({**reply, "highest_likelihood_taken_in": highest_likelihood_taken_in}), Unfinished("e", 0))
def test_takes_a_bundled_e_plus_i_on_its_scale_and_counts_any_other_as_none(self): 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": "", "release_ready": False} reply = {"answer": "", "highest_likelihood_taken_in": 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, "highest_escape_and_impact_taken_in": 6}), Unfinished("e", 0, highest_escape_and_impact_taken_in=6))
self.assertEqual(verdict_from({**reply, "bundled_escape_and_impact": 2}), Unfinished("e", 0, bundled_escape_and_impact=2)) self.assertEqual(verdict_from({**reply, "highest_escape_and_impact_taken_in": 2}), Unfinished("e", 0, highest_escape_and_impact_taken_in=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")) self.assertEqual(verdict_from({**reply, "highest_escape_and_impact_taken_in": False}), Failure("the judge's reply has no highest_escape_and_impact_taken_in of type integer"))
for bundled in (1, 9, -1): for highest_likelihood_taken_in in (1, 9, -1):
with self.subTest(bundled=bundled): with self.subTest(highest_likelihood_taken_in=highest_likelihood_taken_in):
self.assertEqual(verdict_from({**reply, "bundled_escape_and_impact": bundled}), Unfinished("e", 0)) self.assertEqual(verdict_from({**reply, "highest_escape_and_impact_taken_in": highest_likelihood_taken_in}), Unfinished("e", 0))
def test_takes_an_escalation_quote_on_an_unfinished_verdict(self): 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": "", "release_ready": False} reply = {"answer": "", "highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 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), Unfinished("e", 0, "round 2: 🔴"))
self.assertEqual(verdict_from({**reply, "finished": True}), Finished("e")) 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")) 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): 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?", "release_ready": False} reply = {"answer": "", "highest_likelihood_taken_in": 0, "highest_escape_and_impact_taken_in": 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), 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, "highest_likelihood_taken_in": 4}), Interrupt("e", "Which one?", "round 2: 🔴", 4))
self.assertEqual(verdict_from({**reply, "bundled": 5}), Interrupt("e", "Which one?", "round 2: 🔴")) self.assertEqual(verdict_from({**reply, "highest_likelihood_taken_in": 5}), Interrupt("e", "Which one?", "round 2: 🔴"))
def test_drops_an_escalation_quote_the_transcript_does_not_hold_word_for_word_from_an_interrupt_or_an_unfinished_verdict(self): def test_drops_an_escalation_quote_the_transcript_does_not_hold_word_for_word_from_an_interrupt_or_an_unfinished_verdict(self):
shown = "The agent: round 2: 🔴. Which one?" shown = "The agent: round 2: 🔴. Which one?"
@@ -1347,9 +1366,9 @@ class Verdict(unittest.TestCase):
self.assertEqual(judge.quotes_checked(Unfinished("e", 0, "round 3: 🔴"), judge.Grounds(shown, shown, "")), Unfinished("e")) self.assertEqual(judge.quotes_checked(Unfinished("e", 0, "round 3: 🔴"), judge.Grounds(shown, shown, "")), Unfinished("e"))
def test_takes_an_escalation_quote_and_a_bundled_l_on_a_quoted_answer(self): 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?", "release_ready": False} reply = {"answer": "A.", "highest_likelihood_taken_in": 4, "highest_escape_and_impact_taken_in": 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), QuotedAnswer("e", "Which one?", "A.", "round 2: 🔴", 4))
self.assertEqual(verdict_from({**reply, "bundled": 5}), QuotedAnswer("e", "Which one?", "A.", "round 2: 🔴")) self.assertEqual(verdict_from({**reply, "highest_likelihood_taken_in": 5}), QuotedAnswer("e", "Which one?", "A.", "round 2: 🔴"))
def test_drops_an_escalation_quote_the_transcript_does_not_hold_word_for_word_from_a_quoted_answer(self): def test_drops_an_escalation_quote_the_transcript_does_not_hold_word_for_word_from_a_quoted_answer(self):
shown = "The agent: round 2: 🔴. Which one?" shown = "The agent: round 2: 🔴. Which one?"
+1 -1
View File
@@ -36,7 +36,7 @@ class Rung:
return Rung(model, effort) return Rung(model, effort)
return Rung(family.model, effort) if effort else family return Rung(family.model, effort) if effort else family
# The one spelling of a rung. It is persisted, so changing it routes every stored chunk afresh: parse no longer reads their rungs. # The one spelling of a rung. loop-claude hands it to rule-hook in environment variables, and archive lines written before route.Route.record hold it, so parse must keep reading it.
def __str__(self) -> str: def __str__(self) -> str:
return f"{self.model} at {self.effort} effort" if self.effort else self.model return f"{self.model} at {self.effort} effort" if self.effort else self.model
+36 -39
View File
@@ -1,5 +1,6 @@
"""A chunk's route: its worker's rung and the plan item that picked it, in the words the archive records each verdict's worker in.""" """A chunk's route: its worker's rung and the plan item that picked it, and the record of it the archive keeps beside each verdict."""
import dataclasses import dataclasses
import json
import re import re
import typing import typing
@@ -8,24 +9,10 @@ from model_routing.ladder import REVIEW_STEPS, Rung
# How a worker opens the prompt of a subagent it escalates a task to, `Escalation trigger 2: …`: docs/decisions.md → `routing: a worker hands a task one rung up`. # How a worker opens the prompt of a subagent it escalates a task to, `Escalation trigger 2: …`: docs/decisions.md → `routing: a worker hands a task one rung up`.
ESCALATION_MARKER = "Escalation trigger" ESCALATION_MARKER = "Escalation trigger"
# An archived worker line. A line an older loop-claude wrote names an R + C in place of L and E + I: archived_worker reads only its rung, for the routing figures; with no levels, route_from returns None and the chunk routes afresh. # The Route fields the archive records beside the rung's model and effort. unfinished stays out, so a rerun restarts that count.
# Each group reads one fragment of Route.__str__. A reworded fragment leaves the line unreadable, so the chunk routes afresh, its mark back at 0. RECORDED = ("item", "likelihood", "escape_and_impact", "escape_and_impact_taken_in", "escalated_at")
ROUTED = re.compile(r""" # A worker line loop-claude wrote before it archived the route as a record. Nothing writes this format any more, so its wording never changes. route_from reads it for the chunks the routing figures still count, and for a chunk a rerun resumes across the change.
(?P<rung>.+?) # the rung, lazy so the groups below take what follows it LEGACY_WORKER = re.compile(r"(?P<rung>.+?)(?:, routed by item (?P<item>[0-9]+)'s L of (?P<likelihood>[0-9]+) and E \+ I of (?P<escape_and_impact>[0-9]+))?(?:, taking in an E \+ I of (?P<escape_and_impact_taken_in>[0-9]+))?(?:, escalated at transcript entry (?P<escalated_at>[0-9]+))?")
(?:,\ routed\ by\ item\ (?P<item>[0-9]+)'s\ (?:L\ of\ (?P<likelihood>[0-9]+)\ and\ E\ \+\ I\ of\ (?P<escape_and_impact>[0-9]+)|.+?))? # routed: `, routed by item 3's L of 4 and E + I of 5`, or an older line's R + C
(?:,\ taking\ in\ an\ E\ \+\ I\ of\ (?P<escape_and_impact_taken_in>[0-9]+))? # taken_in: `, taking in an E + I of 6`
(?:,\ escalated\ at\ transcript\ entry\ (?P<escalated_at>[0-9]+))? # escalated: `, escalated at transcript entry 12`
""", re.VERBOSE)
class ArchivedWorker(typing.NamedTuple):
"""What an archived worker line names: the worker's rung, the item that routed it, its L and E + I, the E + I taken in and the escalation's mark; 0 for each it does not name."""
rung: Rung
item: int
likelihood: int
escape_and_impact: int
escape_and_impact_taken_in: int
escalated_at: int
HIGHEST_ESCAPE_AND_IMPACT = LEVELS["E"] + LEVELS["I"] HIGHEST_ESCAPE_AND_IMPACT = LEVELS["E"] + LEVELS["I"]
@@ -66,7 +53,7 @@ class Route:
escalated_at: int = 0 escalated_at: int = 0
def __post_init__(self) -> None: def __post_init__(self) -> None:
# Raises on a programming error only, so nothing catches it: route_from and the reload decoder check levels_fit before they build a route. # Raises on a programming error only, so nothing catches it: route_from and the reload decoder check fits before they build a route.
if not levels_fit(self.item, self.likelihood, self.escape_and_impact, self.escape_and_impact_taken_in): if not levels_fit(self.item, self.likelihood, self.escape_and_impact, self.escape_and_impact_taken_in):
raise ValueError(f"a route by item {self.item} cannot hold an L of {self.likelihood}, an E + I of {self.escape_and_impact} and an E + I taken in of {self.escape_and_impact_taken_in}") raise ValueError(f"a route by item {self.item} cannot hold an L of {self.likelihood}, an E + I of {self.escape_and_impact} and an E + I taken in of {self.escape_and_impact_taken_in}")
@@ -83,26 +70,36 @@ class Route:
"""The E + I that picks the reviewers' and the judge's rung: the routed item's or the highest taken in, whichever is higher; 0 for neither.""" """The E + I that picks the reviewers' and the judge's rung: the routed item's or the highest taken in, whichever is higher; 0 for neither."""
return max(self.escape_and_impact, self.escape_and_impact_taken_in) return max(self.escape_and_impact, self.escape_and_impact_taken_in)
def __str__(self) -> str: def record(self) -> str:
"""What the archive records as each verdict's worker; ROUTED reads it back.""" """What the archive records as each verdict's worker: a JSON object of the rung's model and effort and the RECORDED fields, leaving out each that is 0 or empty; route_from reads it back."""
routed = f", routed by item {self.item}'s L of {self.likelihood} and E + I of {self.escape_and_impact}" if self.item else "" fields = {"model": self.rung.model, "effort": self.rung.effort, **{name: getattr(self, name) for name in RECORDED}}
taken_in = f", taking in an E + I of {self.escape_and_impact_taken_in}" if self.escape_and_impact_taken_in else "" return json.dumps({name: value for name, value in fields.items() if value})
escalated = f", escalated at transcript entry {self.escalated_at}" if self.escalated_at else ""
return f"{self.rung}{routed}{taken_in}{escalated}"
def archived_worker(worker: str) -> ArchivedWorker | None:
"""What an archived worker line names; None for a model run off the ladder."""
found = ROUTED.fullmatch(worker)
rung = Rung.parse(found["rung"]) if found else None
if not (found and rung):
return None
return ArchivedWorker(rung, *(int(found[name] or 0) for name in ("item", "likelihood", "escape_and_impact", "escape_and_impact_taken_in", "escalated_at")))
def route_from(worker: str) -> Route | None: def route_from(worker: str) -> Route | None:
"""The route an archived worker line names; None for a model run off the ladder, or a route by anything but levels on their scales.""" """The route an archived worker line names, whether a record or a line written before records. None where it names no model, holds fields Route.record never writes, or holds levels off their scales; and for an older line, where it names a model without an effort."""
archived = archived_worker(worker) fields = recorded(worker) if worker.startswith("{") else legacy_fields(worker)
if archived is None or not levels_fit(archived.item, archived.likelihood, archived.escape_and_impact, archived.escape_and_impact_taken_in): if fields is None or not Route.fits(fields):
return None return None
return Route(archived.rung, archived.item, archived.likelihood, archived.escape_and_impact, escape_and_impact_taken_in=archived.escape_and_impact_taken_in, escalated_at=archived.escalated_at) return Route(Rung(fields["model"], fields.get("effort", "")), **{name: fields.get(name, 0) for name in RECORDED})
def recorded(record: str) -> dict[str, typing.Any] | None:
"""The fields of a record Route.record wrote; None for any other text."""
try:
fields = json.loads(record)
except ValueError:
return None
if not (isinstance(fields, dict) and isinstance(fields.get("model"), str) and isinstance(fields.get("effort", ""), str) and fields.keys() <= {"model", "effort", *RECORDED}):
return None
# type(), not isinstance(): JSON true is no integer.
return fields if all(type(fields.get(name, 0)) is int and fields.get(name, 0) >= 0 for name in RECORDED) else None
def legacy_fields(line: str) -> dict[str, typing.Any] | None:
"""The fields of a LEGACY_WORKER line, as recorded gives them; None for any other text."""
found = LEGACY_WORKER.fullmatch(line)
rung = Rung.parse(found["rung"]) if found else None
if not (found and rung):
return None
return {"model": rung.model, "effort": rung.effort, **{name: int(found[name] or 0) for name in RECORDED}}
+4 -4
View File
@@ -5,9 +5,9 @@ import re
import statistics import statistics
import typing import typing
from model_routing.route import archived_worker, ESCALATION_MARKER
from claude_code.entries import assistant_parts, parts, tool_call, usage_count from claude_code.entries import assistant_parts, parts, tool_call, usage_count
from git_command import commits from git_command import commits
from model_routing.route import ESCALATION_MARKER, route_from
from model_routing.ladder import position, Rung from model_routing.ladder import position, Rung
from round_titles import round_counts from round_titles import round_counts
from shell_command import simple_commands from shell_command import simple_commands
@@ -91,7 +91,7 @@ def measured(chunk: Chunk, home: str) -> ChunkFigures:
reports[kind] = reports.get(kind, Reports(0, 0, 0)) + Reports(1, len(reported.get(subagent.launched_by, "")), sum(map(len, results(subagent.entries).values()))) reports[kind] = reports.get(kind, Reports(0, 0, 0)) + Reports(1, len(reported.get(subagent.launched_by, "")), sum(map(len, results(subagent.entries).values())))
for _, tools, spent in spend(subagent.entries): for _, tools, spent in spend(subagent.entries):
add(tokens, chunk.project, kind, rung, tools, spent) add(tokens, chunk.project, kind, rung, tools, spent)
start = archived_worker(cycles[0][1]) if cycles else None start = route_from(cycles[0][1]) if cycles else None
return ChunkFigures( return ChunkFigures(
tokens=tokens, tokens=tokens,
start=start.rung if start and start.item else None, start=start.rung if start and start.item else None,
@@ -133,8 +133,8 @@ def rung_at(cycles: list[tuple[str, str]], timestamp: str) -> Rung | str:
"""The rung of the cycle running at timestamp: the worker named by the first outcome stamped at or after it, or else by the last outcome. A worker off the ladder is returned as its text.""" """The rung of the cycle running at timestamp: the worker named by the first outcome stamped at or after it, or else by the last outcome. A worker off the ladder is returned as its text."""
second = timestamp[:19] + "Z" second = timestamp[:19] + "Z"
found = next((rung for stamp, rung in cycles if stamp >= second), cycles[-1][1] if cycles else "unrouted") found = next((rung for stamp, rung in cycles if stamp >= second), cycles[-1][1] if cycles else "unrouted")
archived = archived_worker(found) route = route_from(found)
return archived.rung if archived else found return route.rung if route else found
def subagent_rung(entries: list[dict], arguments: dict, worker: Rung | str) -> Rung: def subagent_rung(entries: list[dict], arguments: dict, worker: Rung | str) -> Rung:
+8 -7
View File
@@ -15,10 +15,11 @@ from routing_figures.measure import calls, Chunk, ChunkFigures, due, measured, r
from failure import Failure from failure import Failure
from model_routing.ladder import LADDER, Rung from model_routing.ladder import LADDER, Rung
from transcript_archive import outcomes, write from transcript_archive import outcomes, write
from model_routing.route import Route
LOW = Rung("claude-opus-5-5", "medium") LOW = Rung("claude-opus-5-5", "medium")
HIGH = Rung("claude-opus-5-5", "high") HIGH = Rung("claude-opus-5-5", "high")
LOW_ROUTE = f"{LOW}, routed by item 7's L of 3 and E + I of 4" LOW_ROUTE = Route(LOW, 7, 3, 4).record()
def message(id_, at, *parts, model="claude-opus-5-5", tokens=(1, 10, 100)): def message(id_, at, *parts, model="claude-opus-5-5", tokens=(1, 10, 100)):
@@ -49,7 +50,7 @@ class Measured(unittest.TestCase):
message("m2", "2026-10-14T10:05:00.000Z", {"type": "text", "text": "done"}), message("m2", "2026-10-14T10:05:00.000Z", {"type": "text", "text": "done"}),
message("m3", "2026-10-14T11:00:00.000Z", {"type": "text", "text": "on"}), message("m3", "2026-10-14T11:00:00.000Z", {"type": "text", "text": "on"}),
] ]
kept = stamped("2026-10-14T10:30:00Z", outcomes.unfinished(LOW_ROUTE, "e", "j", "")) + stamped("2026-10-14T10:30:00Z", outcomes.stepped_up(str(HIGH))) + stamped("2026-10-14T12:00:00Z", outcomes.finished(str(HIGH), "merged", "j")) kept = stamped("2026-10-14T10:30:00Z", outcomes.unfinished(LOW_ROUTE, "e", "j", "")) + stamped("2026-10-14T10:30:00Z", outcomes.stepped_up(Route(HIGH).record())) + stamped("2026-10-14T12:00:00Z", outcomes.finished(Route(HIGH).record(), "merged", "j"))
found = measured(Chunk("log", [kept], worker, []), "/h") found = measured(Chunk("log", [kept], worker, []), "/h")
self.assertEqual(found.tokens["project"], {"log": 333}) self.assertEqual(found.tokens["project"], {"log": 333})
self.assertEqual(found.tokens["subagent type"], {"worker": 333}) self.assertEqual(found.tokens["subagent type"], {"worker": 333})
@@ -84,22 +85,22 @@ class Measured(unittest.TestCase):
worker = [commit("m1", "Answer stability round 1: 1 🔴, 0 🟡"), commit("m2", "Answer stability round 2: 0 🔴, 0 🟡"), commit("m3", "Answer stability round 2: 0 🔴, 0 🟡"), commit("m4", "Answer prose round 1: 0 🔴, 1 🟡")] worker = [commit("m1", "Answer stability round 1: 1 🔴, 0 🟡"), commit("m2", "Answer stability round 2: 0 🔴, 0 🟡"), commit("m3", "Answer stability round 2: 0 🔴, 0 🟡"), commit("m4", "Answer prose round 1: 0 🔴, 1 🟡")]
self.assertEqual(measured(Chunk("log", [], worker, []), "/h").rounds_past_first, 1) self.assertEqual(measured(Chunk("log", [], worker, []), "/h").rounds_past_first, 1)
def test_reads_the_rung_of_a_route_an_older_loop_claude_archived_by_r_plus_c(self): def test_reads_the_route_of_a_line_loop_claude_wrote_before_it_archived_json(self):
older = f"{LOW}, routed by item 7's R + C of 9" older = f"{LOW}, routed by item 7's L of 3 and E + I of 4"
kept = stamped("2026-10-14T10:00:00Z", outcomes.finished(older, "m", "j")) kept = stamped("2026-10-14T10:00:00Z", outcomes.finished(older, "m", "j"))
found = measured(Chunk("log", [kept], [message("m1", "2026-10-14T09:00:00Z")], []), "/h") found = measured(Chunk("log", [kept], [message("m1", "2026-10-14T09:00:00Z")], []), "/h")
self.assertEqual(found.start, LOW) self.assertEqual(found.start, LOW)
self.assertEqual(found.tokens["rung"], {str(LOW): 111}) self.assertEqual(found.tokens["rung"], {str(LOW): 111})
def test_starts_no_route_for_a_chunk_no_item_routed(self): def test_starts_no_route_for_a_chunk_no_item_routed(self):
kept = stamped("2026-10-14T10:00:00Z", outcomes.finished(str(LOW), "m", "j")) kept = stamped("2026-10-14T10:00:00Z", outcomes.finished(Route(LOW).record(), "m", "j"))
found = measured(Chunk("log", [kept], [message("m1", "2026-10-14T09:00:00Z")], []), "/h") found = measured(Chunk("log", [kept], [message("m1", "2026-10-14T09:00:00Z")], []), "/h")
self.assertIsNone(found.start) self.assertIsNone(found.start)
self.assertEqual(found.tokens["rung"], {str(LOW): 111}) self.assertEqual(found.tokens["rung"], {str(LOW): 111})
def test_puts_a_subagent_on_the_model_it_ran_at_the_effort_of_the_cycle_that_launched_it(self): def test_puts_a_subagent_on_the_model_it_ran_at_the_effort_of_the_cycle_that_launched_it(self):
kept = stamped("2026-10-14T10:00:00Z", outcomes.unfinished(LOW_ROUTE, "e", "j", "")) + stamped("2026-10-14T11:00:00Z", outcomes.finished(str(HIGH), "m", "j")) kept = stamped("2026-10-14T10:00:00Z", outcomes.unfinished(LOW_ROUTE, "e", "j", "")) + stamped("2026-10-14T11:00:00Z", outcomes.finished(Route(HIGH).record(), "m", "j"))
worker = [ worker = [
message("m1", "2026-10-14T10:00:00.900Z"), message("m1", "2026-10-14T10:00:00.900Z"),
message("m2", "2026-10-14T10:30:00Z", call("Agent", "a1", subagent_type="Explore", model="sonnet")), message("m2", "2026-10-14T10:30:00Z", call("Agent", "a1", subagent_type="Explore", model="sonnet")),
@@ -211,7 +212,7 @@ class Archive(unittest.TestCase):
with contextlib.redirect_stderr(io.StringIO()): with contextlib.redirect_stderr(io.StringIO()):
self.assertIsNone(write.archive(kept / "log", str(transcript), "t", outcomes.unfinished(LOW_ROUTE, "e", "j", ""), 1790000000)) self.assertIsNone(write.archive(kept / "log", str(transcript), "t", outcomes.unfinished(LOW_ROUTE, "e", "j", ""), 1790000000))
transcript.write_text(json.dumps(first) + "\n" + json.dumps(message("m2", "2099-01-01T00:00:00Z")) + "\n") transcript.write_text(json.dumps(first) + "\n" + json.dumps(message("m2", "2099-01-01T00:00:00Z")) + "\n")
self.assertIsNone(write.archive(kept / "log", str(transcript), "t", outcomes.finished(str(HIGH), "m", "j"), 4070908800)) self.assertIsNone(write.archive(kept / "log", str(transcript), "t", outcomes.finished(Route(HIGH).record(), "m", "j"), 4070908800))
(found,) = archive.measure_archive(kept, "/h", "").chunks (found,) = archive.measure_archive(kept, "/h", "").chunks
self.assertEqual((found.start, found.unfinished), (LOW, 1)) self.assertEqual((found.start, found.unfinished), (LOW, 1))
self.assertEqual(found.tokens["rung"], {str(LOW): 111, str(HIGH): 111}) self.assertEqual(found.tokens["rung"], {str(LOW): 111, str(HIGH): 111})