Answer architecture round 1: 0 🔴, 12 🟡; break the import loop, share the interrupt hand-over and formats, measure under a lock 20 cycles past the last measurement, go on off a terminal, and add a reset

This commit is contained in:
2026-10-15 00:49:02 +02:00
parent 5e0816bd80
commit acdba1abf4
19 changed files with 333 additions and 200 deletions
+12 -5
View File
@@ -17,16 +17,23 @@ def interrupt(root: str, session_id: uuid.UUID, worker: Rung, path: str, questio
print(f"\n{question}", file=sys.stderr)
if stop := needs_terminal(ANSWER_QUESTION, effects.on_terminal()):
return stop
trust(paths.claude_json, worktrees(root, effects))
entries = read_transcript(path)
if isinstance(entries, Failure):
return Stop(1, entries.reason)
before = human_turns(entries)
try:
effects.claude_on_terminal([*worker.flags(), "--permission-mode", "bypassPermissions", "--resume", str(session_id)], root)
except OSError as failure:
return Stop(1, f"could not start claude for the interrupt: {failure.strerror}")
if unstarted := hand_over(worker, ["--resume", str(session_id)], root, paths, effects):
return Stop(1, f"could not start claude for the interrupt: {unstarted.reason}")
entries = read_transcript(path)
if isinstance(entries, Failure):
return Stop(1, f"could not tell whether you typed anything: {entries.reason}")
return None if human_turns(entries) > before else needs_human(ANSWER_QUESTION, "the interrupt ended with nothing typed")
def hand_over(rung: Rung, args: list[str], root: str, paths: Paths, effects: Effects) -> Failure | None:
"""Runs claude on the terminal in root on rung, the checkout and each of its worktrees first marked trusted; the failure is why claude could not start."""
trust(paths.claude_json, worktrees(root, effects))
try:
effects.claude_on_terminal([*rung.flags(), "--permission-mode", "bypassPermissions", *args], root)
except OSError as failure:
return Failure(str(failure.strerror))
return None
+1 -1
View File
@@ -1,7 +1,7 @@
from model_routing.ladder import highest, Rung
from loop_claude.project.records import HUMAN_RULE_NAMES, RECORD_FILES
from markdown_text import quoted
from loop_claude.routing import Route
from model_routing.route import Route
def either(names: tuple[str, ...]) -> str:
"""The names as `a, b or c`."""
+1 -1
View File
@@ -14,7 +14,7 @@ from loop_claude.paths import Paths
from loop_claude.cycle import prompts
from claude_code.transcript import read_transcript, render
from loop_claude.cycle.retry import retried
from loop_claude.routing import Route
from model_routing.route import Route
from loop_claude.cycle.worker import run_worker, worker_args
from model_routing.ladder import Rung
from loop_claude.stop import Stop
+18 -13
View File
@@ -60,17 +60,21 @@ and counts its unfinished verdicts afresh. A rung no longer on the ladder, or be
item's R + C picks, is dropped, and the chunk is routed afresh from todo.md. A todo.md or an
archive that cannot be read or parsed is said on stderr, and the chunk is routed without it.
Every 20th cycle across all projects in the archive, counting the cycles a verdict closed, it
measures every finished chunk there, with no model run: tokens by project, subagent type, rung and
the tool whose results they took in, and for each chunk an item routed, by the rung it started on,
its review rounds past each pass's first, its unfinished verdicts and its subagents' rungs. It
writes them to routing-figures.md at the archive's root. They call for a routing change when chunks
routed onto a rung took more review rounds or unfinished verdicts than chunks routed onto the next
rung up, each rung with 5 chunks or more, or when the reports of 5 or more subagents of one type
were longer than the tool results they read. Each call not raised before is an interrupt: claude
on the terminal in ~/.claude, asked the calls. Once that claude ends, the calls are listed in
routing-calls-raised.md beside the figures, and never raised again. A figure that cannot be
measured or written is said on stderr, and the loop goes on.
Every 20 cycles across all projects in the archive, counting the cycles a verdict closed, the loop
that closes the 20th measures every finished chunk there, with no model run: tokens by project,
subagent type, rung and the tool whose results they took in, and for each chunk an item routed, by
the rung it started on, its review rounds past each pass's first, its unfinished verdicts and its
subagents' rungs. It writes them to routing-figures.md at the archive's root. They call for a
routing change when chunks routed onto a rung took more review rounds or unfinished verdicts than
chunks routed onto the next rung up, each rung with 5 chunks or more, or when the reports of 5 or
more subagents of one type were longer than the tool results they read. Each call not raised before
is an interrupt: claude, on the project's model, on the terminal in ~/.claude, asked to put the
calls to the human. Once that claude ends, the calls are listed in routing-calls-raised.md beside the
figures, and not raised again. Off a terminal, the calls are said on stderr, the loop goes on, and
they are raised again at the next measurement. A line `- <UTC time> Reset` in
routing-calls-raised.md restarts both: the figures count only chunks that finished after it, and a
call raised before it may be raised again. A figure that cannot be measured or written is said on
stderr, and the loop goes on.
A change to bin/loop-claude or any bin/**/*.py takes effect at the next cycle boundary, once
loop-claude --help succeeds: the loop reloads into the edited script.
@@ -121,7 +125,7 @@ from loop_claude.loop.reload import decode_handed, exec_if_edited, fingerprint,
from loop_claude.effects import Effects
from failure import Failure
from loop_claude.cycle.judge import Finished, Unfinished
from loop_claude.routing import first_route, kept, Route, route_from, routed_item, stepped
from loop_claude.routing import first_route, kept, routed_item, stepped
from loop_claude.project.model_choice import get_or_ask_models
from todo_table import Item
from transcript_archive.read import latest_worker
@@ -131,6 +135,7 @@ from project_key import project_key
from model_routing.ladder import project_rung, Rung
from loop_claude.project.premises import read_premises
from loop_claude.project.records import read_records
from model_routing.route import Route, route_from
from claude_code.session import Session, session_named, transcript_file
from loop_claude.stop import Stop
@@ -178,7 +183,7 @@ def run_loop(argv: list[str], env: typing.Mapping[str, str], paths: Paths, launc
before, loop_run = loop_run.route, after_verdict(loop_run, anchor, verdict)
if stop := archive_step(archive_folder, session, loop_run, before, effects):
return stop
if stop := check_routing(archive_root(paths.home, env), paths, effects):
if stop := check_routing(archive_root(paths.home, env), anchor or Rung(models.worker), paths, effects):
return stop
+1 -1
View File
@@ -7,7 +7,7 @@ import types
import typing
from loop_claude.effects import Effects
from loop_claude.routing import Route
from model_routing.route import Route
from loop_claude.stop import Stop
RELOAD_FLAG = "--reloaded"
+35 -31
View File
@@ -1,55 +1,59 @@
"""Every CYCLES_PER_CHECK-th cycle across all projects, measure the archive's routing figures, keep them at its root, and interrupt the human with each call for a routing change not raised before: docs/decisions.md → `routing:`."""
"""Every CYCLES_PER_CHECK cycles across all projects, measure the archive's routing figures, keep them at its root, and interrupt the human with each call for a routing change not raised before: docs/decisions.md → `routing:`."""
import pathlib
import sys
from routing_figures import archive
from routing_figures.measure import calls, render, totals
from routing_figures.measure import calls, due, render, totals
from loop_claude.effects import Effects
from failure import Failure
from loop_claude.stop import needs_terminal, Stop
from loop_claude.cycle.interrupt import hand_over
from loop_claude.paths import Paths
from claude_code.trust import trust
from model_routing.ladder import Rung
from loop_claude.stop import Stop
from utc_stamp import utc
from loop_claude.project.checkout import worktrees
CYCLES_PER_CHECK = 20
ANSWER_CALLS = "answer the routing calls above"
def check_routing(root: pathlib.Path, paths: Paths, effects: Effects) -> Stop | None:
"""Stops only for an interrupt it cannot hold; a figure it cannot measure or keep is said on stderr, and the loop goes on."""
new = new_calls(root, paths, effects)
if isinstance(new, Failure):
print(f"routing figures: {new.reason}", file=sys.stderr)
return None
return raise_calls(root, new, paths, effects) if new else None
def check_routing(root: pathlib.Path, rung: Rung, paths: Paths, effects: Effects) -> Stop | None:
"""Stops only when claude cannot start for the calls; a figure it cannot measure or keep is said on stderr, and the loop goes on. rung runs the claude the calls are put to."""
with archive.locked(root) as held:
new = new_calls(root, paths, effects) if held else []
if isinstance(new, Failure):
print(f"routing figures: {new.reason}", file=sys.stderr)
return None
return raise_calls(root, new, rung, paths, effects) if new else None
def new_calls(root: pathlib.Path, paths: Paths, effects: Effects) -> list[str] | Failure:
"""The calls not raised before, measured and kept at every CYCLES_PER_CHECK-th cycle; none at any other."""
"""Once due, measures and keeps the figures, and returns their calls not raised since the latest reset; none while not due."""
cycle = archive.cycles(root)
if isinstance(cycle, Failure) or not cycle or cycle % CYCLES_PER_CHECK:
return cycle if isinstance(cycle, Failure) else []
last = archive.last_measured(root)
if isinstance(cycle, Failure) or isinstance(last, Failure) or not due(cycle, last):
return cycle if isinstance(cycle, Failure) else last if isinstance(last, Failure) else []
kept = archive.raised(root)
if isinstance(kept, Failure):
return kept
print(f"\n=== cycle {cycle} across loop-claude's archive: measuring the routing figures ===", flush=True)
measured = archive.measure_archive(root, str(paths.home))
measured = archive.measure_archive(root, str(paths.home), kept.since)
if isinstance(measured, Failure):
return measured
figures = totals(measured)
found = calls(figures)
return archive.write_figures(root, render(figures, found, utc(effects.now()), cycle)) or archive.unraised(root, found)
if unwritten := archive.write_figures(root, render(figures, found, utc(effects.now()), cycle, kept.since)):
return unwritten
return [call for call in found if call not in kept.calls]
def raise_calls(root: pathlib.Path, new: list[str], paths: Paths, effects: Effects) -> Stop | None:
"""Hands the terminal to a claude in this setup's checkout, where the routing decision lives; a call counts as raised once that claude ends."""
question = "loop-claude's routing figures call for a routing change, which is yours to decide:\n" + "".join(f"- {call}\n" for call in new) + f"The figures are in {root / archive.FIGURES}. The ladder's bands and the delegation rule are docs/decisions.md → `routing:`."
print(f"\n{question}", file=sys.stderr)
if stop := needs_terminal(ANSWER_CALLS, effects.on_terminal()):
return stop
trust(paths.claude_json, worktrees(str(paths.claude_dir), effects))
try:
effects.claude_on_terminal(["--permission-mode", "bypassPermissions", question], str(paths.claude_dir))
except OSError as failure:
return Stop(1, f"could not start claude for the routing calls: {failure.strerror}")
def raise_calls(root: pathlib.Path, new: list[str], rung: Rung, paths: Paths, effects: Effects) -> Stop | None:
"""Puts the calls to the human through a claude in this setup's checkout, where the routing decision lives. Off a terminal they are only said, and raised again at the next measurement; this repo's AGENTS.md files them meanwhile."""
listed = "".join(f"- {call}\n" for call in new)
print(f"\nloop-claude's routing figures call for a routing change:\n{listed}The figures: {root / archive.FIGURES}", file=sys.stderr)
if not effects.on_terminal():
print("Not on a terminal: the calls are raised again at the next measurement.", file=sys.stderr)
return None
prompt = f"Put these calls for a routing change from loop-claude's figures to the human, and change nothing until they answer:\n{listed}The figures are in {root / archive.FIGURES}. The ladder, its bands and the delegation rule are docs/decisions.md → `routing:`, and a change to them is the human's."
if unstarted := hand_over(rung, [prompt], str(paths.claude_dir), paths, effects):
return Stop(1, f"could not start claude for the routing calls: {unstarted.reason}")
# Raised once the human has seen them, answered or not: an unanswered call reaches the plan through AGENTS.md, so it is not asked twice.
if unmarked := archive.mark_raised(root, new, utc(effects.now())):
print(f"routing figures: {unmarked.reason}", file=sys.stderr)
return None
+1 -26
View File
@@ -1,37 +1,12 @@
"""Which ladder rung a chunk's worker runs on: docs/decisions.md → `routing:`."""
import dataclasses
import re
from failure import Failure
from model_routing.ladder import highest, LADDER, picked, Rung, stepped_up
from todo_table import Item, items
from model_routing.route import Route
UNFINISHED_PER_STEP = 2
ROUTED = re.compile(r"(?P<model>\S+) at (?P<effort>\S+) effort(?:, routed by item (?P<item>[0-9]+)'s R \+ C of (?P<sum>[0-9]+))?")
@dataclasses.dataclass(frozen=True)
class Route:
"""A chunk's worker rung and the plan item whose R + C picked it, 0 for none.
unfinished counts the unfinished verdicts towards the next one-rung step; a reload hands it over with the rung.
"""
rung: Rung
item: int = 0
risk_and_complexity: int = 0
unfinished: int = 0
def __str__(self) -> str:
"""What the archive records as each verdict's worker; ROUTED reads it back."""
return f"{self.rung}, routed by item {self.item}'s R + C of {self.risk_and_complexity}" if self.item else str(self.rung)
def route_from(worker: str) -> Route | None:
"""The route an archived worker line names; None for a model run off the ladder."""
found = ROUTED.fullmatch(worker)
if not found:
return None
return Route(Rung(found["model"], found["effort"]), int(found["item"] or 0), int(found["sum"] or 0))
def routed_item(todo: str) -> Item | Failure | None:
+73 -54
View File
@@ -16,6 +16,7 @@ import uuid
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from routing_figures import archive
from loop_claude.project import checkout, model_choice, records
from loop_claude.effects import Effects
from claude_code import entries, session
@@ -28,6 +29,7 @@ from loop_claude.loop import main, reload, routing_check
from transcript_archive import outcomes, write
from loop_claude import paths, routing
from transcript_archive.location import project_archive
from model_routing.route import Route, route_from
from loop_claude.stop import Stop
CWD = pathlib.Path("/c")
@@ -172,7 +174,7 @@ class Cycles(unittest.TestCase):
self.archive = project_archive(str(self.home / "code" / "proj"), self.home, {})
def cycle(self, fake, records="", unfinished_evidence=""):
return run.Cycle(anchor=None, effects=fake.effects(), judge_model="judge-model", paths=self.paths, premises="## Goals", project_archive=self.archive, records=records, root=str(self.home), route=routing.Route(Rung("worker-model")), session=self.session, task="Do it.", unfinished_evidence=unfinished_evidence)
return run.Cycle(anchor=None, effects=fake.effects(), judge_model="judge-model", paths=self.paths, premises="## Goals", project_archive=self.archive, records=records, root=str(self.home), route=Route(Rung("worker-model")), session=self.session, task="Do it.", unfinished_evidence=unfinished_evidence)
def archived_outcomes(self):
return sorted(path.read_text() for path in self.archive.glob("*/*.outcomes.md"))
@@ -373,10 +375,10 @@ class RoutingCheck(unittest.TestCase):
self.root = self.home / "archive"
self.paths = paths.paths_from(self.home)
def chunks(self, count, verdicts):
def chunks(self, count, verdicts, project="log"):
"""count finished chunks, each closed by verdicts verdicts, each with one Explore subagent whose report outgrew its searches."""
for number in range(count):
folder = self.root / "log" / f"c{number}"
folder = self.root / project / f"c{number}"
subagents = folder / "session" / "s" / "subagents"
subagents.mkdir(parents=True)
kept = "".join(f"2026-10-14T10:0{verdict}:00Z {outcomes.unfinished('w', 'e')}\n" for verdict in range(verdicts - 1))
@@ -389,13 +391,16 @@ class RoutingCheck(unittest.TestCase):
def check(self, fake):
with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()) as said:
stop = routing_check.check_routing(self.root, self.paths, fake.effects())
stop = routing_check.check_routing(self.root, Rung("m", "high"), self.paths, fake.effects())
return stop, said.getvalue()
def test_measures_only_at_every_20th_cycle(self):
def test_measures_once_20_cycles_have_closed_since_the_last_measurement(self):
self.chunks(5, 3)
self.assertEqual(self.check(FakeEffects()), (None, ""))
self.assertFalse((self.root / "routing-figures.md").exists())
self.chunks(6, 1, "other")
self.assertEqual(self.check(FakeEffects(on_terminal=False))[0], None)
self.assertIn("at cycle 21 across", (self.root / "routing-figures.md").read_text())
def test_hands_the_terminal_over_once_for_each_new_call(self):
self.chunks(5, 4)
@@ -406,22 +411,36 @@ class RoutingCheck(unittest.TestCase):
self.assertIn(f"- {call}", said)
self.assertIn(f"- {call}", (self.root / "routing-figures.md").read_text())
((args),) = fake.made("claude_on_terminal")
self.assertEqual(args[:2], ["--permission-mode", "bypassPermissions"])
self.assertIn(call, args[2])
self.assertEqual(self.check(FakeEffects()), (None, ""))
self.assertEqual(args[:6], ["--model", "m", "--effort", "high", "--permission-mode", "bypassPermissions"])
self.assertIn(f"change nothing until they answer:\n- {call}", args[6])
(self.root / "routing-figures.md").write_text("Measured x, at cycle 0 across")
self.assertEqual(self.check(FakeEffects())[0], None)
self.assertNotIn(call, self.check(FakeEffects())[1])
def test_stops_off_a_terminal_and_raises_the_call_again_next_time(self):
def test_goes_on_off_a_terminal_and_raises_the_call_again_next_time(self):
self.chunks(5, 4)
stop, _ = self.check(FakeEffects(on_terminal=False))
self.assertEqual(stop, Stop(2, "the human is needed to answer the routing calls above, but stdin or stdout is not a terminal; rerun loop-claude on a terminal"))
self.assertEqual(self.check(FakeEffects(on_terminal=False))[0].code, 2)
stop, said = self.check(FakeEffects(on_terminal=False))
self.assertIsNone(stop)
self.assertIn("Not on a terminal: the calls are raised again at the next measurement.", said)
(self.root / "routing-figures.md").write_text("Measured x, at cycle 0 across")
self.assertIn("Not on a terminal", self.check(FakeEffects(on_terminal=False))[1])
def test_leaves_the_measuring_to_a_loop_holding_the_lock(self):
self.chunks(5, 4)
with archive.locked(self.root):
self.assertEqual(self.check(FakeEffects()), (None, ""))
def test_stops_when_claude_cannot_start_for_the_calls(self):
self.chunks(5, 4)
stop, _ = self.check(FakeEffects(on_terminal_claude=[OSError(2, "No such file or directory")], git=[ran()]))
self.assertEqual(stop, Stop(1, "could not start claude for the routing calls: No such file or directory"))
def test_says_a_figure_it_cannot_write_and_goes_on(self):
self.chunks(5, 4)
(self.root / "routing-figures.md").mkdir()
stop, said = self.check(FakeEffects())
self.assertIsNone(stop)
self.assertIn("routing figures: could not write", said)
self.assertIn("routing figures: could not read", said)
class ModelPrompt(unittest.TestCase):
@@ -470,56 +489,56 @@ class Routing(unittest.TestCase):
self.assertEqual(routing.routed_item(TODO.replace("| 5 | 3 |", "| x | 3 |")), Failure("item 3's R 'x' is not a whole number from 1 to 10"))
def test_starts_a_chunk_on_the_rung_its_items_r_plus_c_picks_below_the_projects_too(self):
self.assertEqual(routing.first_route(self.OPUS, routing.routed_item(TODO)), routing.Route(self.HIGH, 3, 11))
self.assertEqual(routing.first_route(self.OPUS, routing.routed_item(TODO)), Route(self.HIGH, 3, 11))
cheap = routing.routed_item(TODO.replace("| 5 | 3 | 6 |", "| 1 | 3 | 1 |"))
self.assertEqual(routing.first_route(self.OPUS, cheap), routing.Route(Rung("claude-haiku-5-5", "xhigh"), 3, 2))
self.assertEqual(routing.first_route(self.OPUS, None), routing.Route(self.OPUS))
self.assertEqual(routing.first_route(self.OPUS, cheap), Route(Rung("claude-haiku-5-5", "xhigh"), 3, 2))
self.assertEqual(routing.first_route(self.OPUS, None), Route(self.OPUS))
def test_steps_up_a_rung_after_every_second_unfinished_verdict(self):
once = routing.stepped(self.OPUS, routing.Route(self.OPUS, 3, 9), 0)
self.assertEqual(once, routing.Route(self.OPUS, 3, 9, 1))
self.assertEqual(routing.stepped(self.OPUS, once, 0), routing.Route(self.HIGH, 3, 9, 0))
self.assertEqual(routing.stepped(self.OPUS, routing.Route(LADDER[-1], unfinished=1), 0).rung, LADDER[-1])
once = routing.stepped(self.OPUS, Route(self.OPUS, 3, 9), 0)
self.assertEqual(once, Route(self.OPUS, 3, 9, 1))
self.assertEqual(routing.stepped(self.OPUS, once, 0), Route(self.HIGH, 3, 9, 0))
self.assertEqual(routing.stepped(self.OPUS, Route(LADDER[-1], unfinished=1), 0).rung, LADDER[-1])
def test_steps_up_to_the_rung_a_bundled_items_r_plus_c_picks_and_never_down(self):
self.assertEqual(routing.stepped(self.OPUS, routing.Route(self.OPUS), 13).rung, self.XHIGH)
self.assertEqual(routing.stepped(self.OPUS, routing.Route(self.XHIGH), 11).rung, self.XHIGH)
self.assertEqual(routing.stepped(self.OPUS, routing.Route(self.OPUS, unfinished=1), 13).rung, Rung("claude-opus-5-5", "max"))
self.assertEqual(routing.stepped(self.OPUS, Route(self.OPUS), 13).rung, self.XHIGH)
self.assertEqual(routing.stepped(self.OPUS, Route(self.XHIGH), 11).rung, self.XHIGH)
self.assertEqual(routing.stepped(self.OPUS, Route(self.OPUS, unfinished=1), 13).rung, Rung("claude-opus-5-5", "max"))
def test_steps_up_from_a_rung_below_the_projects_one_rung_at_a_time(self):
low = routing.Route(Rung("claude-haiku-5-5", "xhigh"), 3, 2, 1)
low = Route(Rung("claude-haiku-5-5", "xhigh"), 3, 2, 1)
self.assertEqual(routing.stepped(self.OPUS, low, 0).rung, Rung("claude-haiku-5-5", "max"))
self.assertEqual(routing.stepped(self.OPUS, routing.Route(low.rung, 3, 2), 0).rung, low.rung)
self.assertEqual(routing.stepped(self.OPUS, routing.Route(low.rung, 3, 2), 7).rung, Rung("claude-sonnet-5-5", "high"))
self.assertEqual(routing.stepped(self.OPUS, Route(low.rung, 3, 2), 0).rung, low.rung)
self.assertEqual(routing.stepped(self.OPUS, Route(low.rung, 3, 2), 7).rung, Rung("claude-sonnet-5-5", "high"))
def test_a_rung_an_edit_took_off_the_ladder_counts_as_the_projects(self):
self.assertEqual(routing.stepped(self.OPUS, routing.Route(Rung("claude-opus-5-5", "low")), 0).rung, self.OPUS)
self.assertEqual(routing.stepped(self.OPUS, routing.Route(Rung("claude-opus-5-5", "low")), 2).rung, self.OPUS)
self.assertEqual(routing.stepped(self.OPUS, Route(Rung("claude-opus-5-5", "low")), 0).rung, self.OPUS)
self.assertEqual(routing.stepped(self.OPUS, Route(Rung("claude-opus-5-5", "low")), 2).rung, self.OPUS)
def test_archives_the_route_in_a_line_it_reads_back(self):
route = routing.Route(self.HIGH, 3, 11)
route = Route(self.HIGH, 3, 11)
self.assertEqual(str(route), "claude-opus-5-5 at high effort, routed by item 3's R + C of 11")
self.assertEqual(routing.route_from(str(route)), route)
self.assertEqual(routing.route_from(str(routing.Route(self.HIGH))), routing.Route(self.HIGH))
self.assertEqual(str(routing.Route(Rung("worker-model"))), "worker-model")
self.assertIsNone(routing.route_from("worker-model"))
self.assertEqual(route_from(str(route)), route)
self.assertEqual(route_from(str(Route(self.HIGH))), Route(self.HIGH))
self.assertEqual(str(Route(Rung("worker-model"))), "worker-model")
self.assertIsNone(route_from("worker-model"))
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)
archived = routing.Route(self.XHIGH, 3, 11)
archived = Route(self.XHIGH, 3, 11)
def never():
raise AssertionError("not asked")
self.assertIsNone(main.routed(run_with(archived), None, never, never).route)
self.assertEqual(main.routed(run_with(archived), self.OPUS, never, never).route, archived)
self.assertEqual(main.routed(run_with(), self.OPUS, lambda: archived, never).route, archived)
self.assertEqual(main.routed(run_with(), self.OPUS, lambda: None, lambda: item).route, routing.Route(self.HIGH, 3, 11))
below = routing.Route(Rung("claude-sonnet-5-5", "high"))
self.assertEqual(main.routed(run_with(below), self.OPUS, never, lambda: None).route, routing.Route(self.OPUS))
cheap = routing.Route(Rung("claude-sonnet-5-5", "high"), 4, 6)
self.assertEqual(main.routed(run_with(), self.OPUS, lambda: None, lambda: item).route, Route(self.HIGH, 3, 11))
below = Route(Rung("claude-sonnet-5-5", "high"))
self.assertEqual(main.routed(run_with(below), self.OPUS, never, lambda: None).route, Route(self.OPUS))
cheap = Route(Rung("claude-sonnet-5-5", "high"), 4, 6)
self.assertEqual(main.routed(run_with(cheap), self.OPUS, never, never).route, cheap)
self.assertEqual(main.routed(run_with(routing.Route(Rung("claude-haiku-5-5", "max"), 4, 7)), self.OPUS, never, lambda: None).route, routing.Route(self.OPUS))
self.assertEqual(main.routed(run_with(Route(Rung("claude-haiku-5-5", "max"), 4, 7)), self.OPUS, never, lambda: None).route, Route(self.OPUS))
class RouteSources(unittest.TestCase):
@@ -545,7 +564,7 @@ class RouteSources(unittest.TestCase):
transcript.parent.mkdir(parents=True)
transcript.write_text(json.dumps({"type": "queue-operation", "timestamp": "1"}) + "\n")
self.assertIsNone(main.archived_route(archive, opened))
route = routing.Route(Rung("claude-opus-5-5", "high"), 3, 11)
route = Route(Rung("claude-opus-5-5", "high"), 3, 11)
with contextlib.redirect_stderr(io.StringIO()):
self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.unfinished(str(route), "working"), NOW))
self.assertEqual(main.archived_route(archive, opened), route)
@@ -563,9 +582,9 @@ class Steps(unittest.TestCase):
OPUS = Rung("claude-opus-5-5", "medium")
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=routing.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, Unfinished("new", 13)), dataclasses.replace(run_with, route=routing.Route(Rung("claude-opus-5-5", "xhigh"), unfinished=1), unfinished_evidence="new"))
self.assertEqual(main.after_verdict(run_with, self.OPUS, Unfinished("new", 13)), dataclasses.replace(run_with, route=Route(Rung("claude-opus-5-5", "xhigh"), unfinished=1), unfinished_evidence="new"))
def test_archives_a_step_up_as_it_happens_so_a_rerun_resumes_on_it(self):
with tempfile.TemporaryDirectory() as home:
@@ -574,12 +593,12 @@ class Steps(unittest.TestCase):
transcript = pathlib.Path(home, "projects", "-fake", f"{opened.id}.jsonl")
transcript.parent.mkdir(parents=True)
transcript.write_text(json.dumps({"type": "queue-operation", "timestamp": "1"}) + "\n")
before = routing.Route(self.OPUS, 3, 9)
before = Route(self.OPUS, 3, 9)
with contextlib.redirect_stderr(io.StringIO()):
self.assertIsNone(write.archive(archive, str(transcript), "Do it.", outcomes.unfinished(str(before), "working"), NOW))
after = main.after_verdict(main.LoopRun(cycle_number=1, root="/r", task="Do it.", unfinished_evidence="", route=before), self.OPUS, Unfinished("working", 13))
self.assertIsNone(main.archive_step(archive, opened, after, before, FakeEffects().effects()))
self.assertEqual(main.archived_route(archive, opened), routing.Route(Rung("claude-opus-5-5", "xhigh"), 3, 9))
self.assertEqual(main.archived_route(archive, opened), Route(Rung("claude-opus-5-5", "xhigh"), 3, 9))
self.assertIsNone(main.archive_step(archive, opened, after, after.route, FakeEffects().effects()))
self.assertIsNone(main.archive_step(archive, opened, after, None, FakeEffects().effects()))
blocked = pathlib.Path(home, "blocked")
@@ -590,32 +609,32 @@ class Steps(unittest.TestCase):
class WorkerArgs(unittest.TestCase):
def test_names_the_route_in_a_fresh_prompt_only_where_an_item_routed_it(self):
routed = prompts.fresh("Do it.", "## Goals", routing.Route(Rung("m", "high"), 3, 11), None)
routed = prompts.fresh("Do it.", "## Goals", Route(Rung("m", "high"), 3, 11), None)
self.assertIn("Continue any open draft PR or worktree for the chunk before creating a new one.\n\nloop-claude runs you on m at high effort, routed by item 3's R + C of 11. Name each todo.md item this chunk takes, with its R + C, whether or not it is item 3.\n\nThe chunk's", routed)
unrouted = prompts.fresh("Do it.", "## Goals", routing.Route(Rung("m")), None)
unrouted = prompts.fresh("Do it.", "## Goals", Route(Rung("m")), None)
self.assertIn("before creating a new one.\n\nThe chunk's", unrouted)
self.assertNotIn("loop-claude runs you on", unrouted)
def test_keeps_reviewers_on_the_projects_rung_while_the_worker_runs_below_it(self):
opus = Rung("claude-opus-5-5", "medium")
below = prompts.fresh("Do it.", "## Goals", routing.Route(Rung("claude-sonnet-5-5", "high"), 3, 5), opus)
below = prompts.fresh("Do it.", "## Goals", Route(Rung("claude-sonnet-5-5", "high"), 3, 5), opus)
self.assertIn("whether or not it is item 3. Your rung is below the project's, claude-opus-5-5 at medium effort: launch each reviewer, each comprehension seat and the security pass's subagent with the Agent tool set to model opus, effort medium. Run a full scan only from such a subagent, since the scan's agents run on the model that starts them.\n\n", below)
self.assertNotIn("the project's", prompts.fresh("Do it.", "## Goals", routing.Route(opus, 3, 9), opus))
self.assertNotIn("the project's", prompts.fresh("Do it.", "## Goals", Route(opus, 3, 9), opus))
def test_keeps_seats_and_the_security_pass_on_the_projects_rung_while_the_worker_runs_above_it(self):
opus = Rung("claude-opus-5-5", "medium")
above = prompts.fresh("Do it.", "## Goals", routing.Route(Rung("claude-opus-5-5", "high"), 3, 11), opus)
stepped_up = prompts.resumed("", routing.Route(Rung("claude-opus-5-5", "high"), 3, 9), opus)
above = prompts.fresh("Do it.", "## Goals", Route(Rung("claude-opus-5-5", "high"), 3, 11), opus)
stepped_up = prompts.resumed("", Route(Rung("claude-opus-5-5", "high"), 3, 9), opus)
self.assertTrue(stepped_up.endswith(" Your rung is above the project's, claude-opus-5-5 at medium effort: launch each comprehension seat and the security pass's subagent with the Agent tool set to model opus, effort medium. Run a full scan only from such a subagent, since the scan's agents run on the model that starts them."), stepped_up)
self.assertNotIn("the project's", prompts.resumed("", routing.Route(opus, 3, 9), opus))
self.assertNotIn("the project's", prompts.resumed("", Route(opus, 3, 9), opus))
self.assertIn("whether or not it is item 3. Your rung is above the project's, claude-opus-5-5 at medium effort: launch each comprehension seat and the security pass's subagent with the Agent tool set to model opus, effort medium. Run a full scan only from such a subagent, since the scan's agents run on the model that starts them.\n\n", above)
def test_opens_a_fresh_session_by_name_and_resumes_an_open_one(self):
opened = session.session_named("A proj loop-claude", pathlib.Path("/h/.claude/projects"))
fresh = worker.worker_args(opened, Rung("m"), prompts.fresh("Do it.", "## Goals\n1. g\n\n## Audience\nme", routing.Route(Rung("m")), None), resume=False)
fresh = worker.worker_args(opened, Rung("m"), prompts.fresh("Do it.", "## Goals\n1. g\n\n## Audience\nme", Route(Rung("m")), None), resume=False)
self.assertEqual(fresh[fresh.index("--session-id") + 1], str(opened.id))
self.assertEqual(fresh[fresh.index("--name") + 1], "A proj loop-claude")
resumed = worker.worker_args(opened, Rung("m"), prompts.resumed("", routing.Route(Rung("m")), None), resume=True)
resumed = worker.worker_args(opened, Rung("m"), prompts.resumed("", Route(Rung("m")), None), resume=True)
self.assertEqual(resumed[resumed.index("--resume") + 1], str(opened.id))
self.assertNotIn("--session-id", resumed)
self.assertTrue(resumed[resumed.index("-p") + 1].startswith("Continue the task; the previous run ended before the chunk was finished. The chunk is finished once"))
@@ -730,7 +749,7 @@ class LoopRuns(unittest.TestCase):
self.assertIsNone(reload.decode_handed('{"count": "1", "name": "n"}', Stringly))
def test_decodes_a_route_inside_the_state_or_none(self):
state = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="", route=routing.Route(Rung("claude-opus-5-5", "high"), 3, 11, 1))
state = main.LoopRun(cycle_number=1, root="/r", task="do it", unfinished_evidence="", route=Route(Rung("claude-opus-5-5", "high"), 3, 11, 1))
self.assertEqual(reload.decode_handed(json.dumps(dataclasses.asdict(state)), main.LoopRun), state)
unrouted = dataclasses.replace(state, route=None)
self.assertEqual(reload.decode_handed(json.dumps(dataclasses.asdict(unrouted)), main.LoopRun), unrouted)