diff --git a/AGENTS.md b/AGENTS.md index 506e834b..ff634586 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -37,7 +37,7 @@ Decisions live in `docs/decisions.md`: ## Working rules -- When `routing-calls-raised.md`, at the root of loop-claude's archive (`$LOOP_CLAUDE_TRANSCRIPTS`, default `~/.claude/loop-claude-transcripts`), lists a call stamped after the latest stamp `todo.md` or `docs/decisions.md` → `routing:` cites from it, file one `todo.md` item to settle the calls stamped since, or refresh the one already filed. Its detail quotes them, with the latest stamp and the figures in `routing-figures.md` beside it. A change to the ladder, its bands or the delegation rule is the human's. +- When `routing-calls-raised.md`, at the root of loop-claude's archive (`$LOOP_CLAUDE_TRANSCRIPTS`, default `~/.claude/loop-claude-transcripts`), lists a call stamped after the latest stamp `todo.md` or `docs/decisions.md` → `routing:` cites from it, file one `todo.md` item to settle the calls stamped since, or refresh the one already filed. Its detail quotes those calls with their stamps, and the routed-chunks table of `routing-figures.md` beside it, never the project names its other tables hold. A change to the ladder, its bands or the delegation rule is the human's. The chunk that ships one appends `- Reset` to `routing-calls-raised.md`, so the figures count only chunks finished after it, and its calls may be raised again. - When `~/.claude/settings.json` has uncommitted changes, commit them on a branch of their own and merge them through a PR: Claude Code writes that file from any session. Read their diff first. When it holds a credential, such as a token in `env` or `mcpServers`, ask the human to move it out of the file, and commit only once it is gone. A token in `env` moves to the shell profile; a server in `mcpServers` moves to `~/.claude.json` with `claude mcp add --scope user`. ## Scoring run diff --git a/CHANGELOG.md b/CHANGELOG.md index 136e8dbe..aa8e4e29 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ ## Unreleased -- Every 20th cycle across all projects, `loop-claude` measures every finished chunk in its archive, with no model run, and writes the figures to `routing-figures.md` at the archive's root: tokens by project, subagent type, rung and tool, 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 interrupts you, with `claude` on the terminal in `~/.claude`, 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 5 or more subagents of one type wrote reports longer than the tool results they read. Each call is raised once, then listed in `routing-calls-raised.md` beside the figures; the next chunk of this repo files a `todo.md` item for it. Expect a pause of about ten seconds at each 20th cycle, and an interrupt off a terminal to exit 2 as other interrupts do. +- Every 20 cycles across all projects, `loop-claude` measures every finished chunk in its archive, with no model run, and writes the figures to `routing-figures.md` at the archive's root: tokens by project, subagent type, rung and tool, 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 interrupts you, with `claude` on the project's model on the terminal in `~/.claude`, 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 5 or more subagents of one type wrote reports longer than the tool results they read. Each call is raised once, then listed in `routing-calls-raised.md` beside the figures; the next chunk of this repo files a `todo.md` item for it. Off a terminal, the calls are only said on stderr, the loop goes on, and they are raised at the next measurement. After a routing change, a `- Reset` line in that file makes the figures count only chunks finished after it. Expect a pause of about ten seconds at each measurement. - A session delegates a task to a subagent only when it needs just the task's conclusion, such as a search across many files, and keeps edits in its own thread. It scores the task's R and C as for a `todo.md` item, and launches the subagent on the model and effort that the new `bin/subagent-rung ` picks from the project's model, such as `model sonnet, effort high`. `CLAUDE.md` states the rule. Expect searches to run on cheaper models, and less of each session's context to fill with search output. - `loop-claude` routes each chunk's worker on a ladder of model and effort rungs, from Haiku 5.5 at low effort to Fable 5.1 at max, when the project's model is on it. As a chunk starts, the R + C of `todo.md`'s top item in the next release picks the rung: 11–12 picks one rung above the project's rung, so Opus 5.5 at high for an Opus 5.5 project, and so on up to four rungs. An item of R + C 10 or less runs the worker at or below the project's model's cheapest rung, which for Opus 5.5 is medium effort, below the xhigh `settings.json` sets. While the worker runs below the project's model's cheapest rung, it launches every reviewer, comprehension seat and security pass, the full scan included, in a subagent on that rung. While it runs above that rung, it launches each comprehension seat and the security pass on that rung. It steps up one rung after every second unfinished verdict on a chunk, and to a higher rung when it takes in an item of higher R + C. Each cycle's header, and each finished or unfinished verdict, stop and step-up in the archive, name the worker's rung; a rerun resumes an open chunk on the latest rung archived for it. `docs/decisions.md` → `routing:` gives the ladder, its source and the bands. Expect a chunk on an easy item to cost much less than under xhigh, and perhaps to take more review rounds, and one on an item of R + C 15 or more to cost more. - A session reads `todo.md` up to `## Details`, and the details of only the items its chunk takes. It reads a `docs/decisions.md` entry only where the entry's title leaves open what it needs. Both rules are in `CLAUDE.md`, so they hold from a session's start. The decisions rule replaces one in `rules/decisions.md`, which loads only once a session has opened `docs/decisions.md` or `AGENTS.md`. A chunk's opening line now counts the unreleased changes instead of listing them. Expect fewer tokens read before a chunk's first commit. diff --git a/bin/claude_code/entries.py b/bin/claude_code/entries.py index 84f2915a..f5a28942 100644 --- a/bin/claude_code/entries.py +++ b/bin/claude_code/entries.py @@ -119,3 +119,10 @@ def rejected_until(event: dict) -> int | None: return None resets_at = info.get("resetsAt") return resets_at if isinstance(resets_at, int) and not isinstance(resets_at, bool) else None + + +# A count Claude Code left out or wrote as another type adds nothing, so one odd entry leaves the rest of a figure standing. +def usage_count(usage: dict, field: str) -> int: + """One token count of a message's usage: {"input_tokens": 2, "cache_creation_input_tokens": 14541, "output_tokens": 8, ...}""" + value = usage.get(field) + return value if isinstance(value, int) else 0 diff --git a/bin/loop_claude/cycle/interrupt.py b/bin/loop_claude/cycle/interrupt.py index 01e73731..7684d1a3 100644 --- a/bin/loop_claude/cycle/interrupt.py +++ b/bin/loop_claude/cycle/interrupt.py @@ -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 diff --git a/bin/loop_claude/cycle/prompts.py b/bin/loop_claude/cycle/prompts.py index 51268049..21b76003 100644 --- a/bin/loop_claude/cycle/prompts.py +++ b/bin/loop_claude/cycle/prompts.py @@ -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`.""" diff --git a/bin/loop_claude/cycle/run.py b/bin/loop_claude/cycle/run.py index 00ea3d26..d6c834da 100644 --- a/bin/loop_claude/cycle/run.py +++ b/bin/loop_claude/cycle/run.py @@ -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 diff --git a/bin/loop_claude/loop/main.py b/bin/loop_claude/loop/main.py index 9877a4e4..1b17570c 100644 --- a/bin/loop_claude/loop/main.py +++ b/bin/loop_claude/loop/main.py @@ -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 `- 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 diff --git a/bin/loop_claude/loop/reload.py b/bin/loop_claude/loop/reload.py index a6379b3b..5483dccb 100644 --- a/bin/loop_claude/loop/reload.py +++ b/bin/loop_claude/loop/reload.py @@ -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" diff --git a/bin/loop_claude/loop/routing_check.py b/bin/loop_claude/loop/routing_check.py index 99fbb3cd..80a037f5 100644 --- a/bin/loop_claude/loop/routing_check.py +++ b/bin/loop_claude/loop/routing_check.py @@ -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 diff --git a/bin/loop_claude/routing.py b/bin/loop_claude/routing.py index 1064532f..7c539526 100644 --- a/bin/loop_claude/routing.py +++ b/bin/loop_claude/routing.py @@ -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\S+) at (?P\S+) effort(?:, routed by item (?P[0-9]+)'s R \+ C of (?P[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: diff --git a/bin/loop_claude/test_loop_claude.py b/bin/loop_claude/test_loop_claude.py index a2ed11b1..49c38bd0 100644 --- a/bin/loop_claude/test_loop_claude.py +++ b/bin/loop_claude/test_loop_claude.py @@ -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) diff --git a/bin/model_routing/ladder.py b/bin/model_routing/ladder.py index 844aa636..c1a3195d 100644 --- a/bin/model_routing/ladder.py +++ b/bin/model_routing/ladder.py @@ -15,7 +15,7 @@ class Rung: """The rung in the Agent tool's words. The tool takes a family name, such as opus, and runs that family's latest model, which is the model each rung names.""" return f"model {self.model.split('-')[1]}, effort {self.effort}" - # The archive records this wording, and loop_claude.routing.ROUTED reads it back to resume a chunk on its rung. + # The archive records this wording, and model_routing.route.ROUTED reads it back to resume a chunk on its rung. def __str__(self) -> str: return f"{self.model} at {self.effort} effort" if self.effort else self.model diff --git a/bin/model_routing/route.py b/bin/model_routing/route.py new file mode 100644 index 00000000..a4677520 --- /dev/null +++ b/bin/model_routing/route.py @@ -0,0 +1,31 @@ +"""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.""" +import dataclasses +import re + +from model_routing.ladder import Rung + +ROUTED = re.compile(r"(?P\S+) at (?P\S+) effort(?:, routed by item (?P[0-9]+)'s R \+ C of (?P[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)) diff --git a/bin/reading_cost/measure.py b/bin/reading_cost/measure.py index b8fe8b13..5e096d9a 100644 --- a/bin/reading_cost/measure.py +++ b/bin/reading_cost/measure.py @@ -1,7 +1,7 @@ import collections import dataclasses -from claude_code.entries import assistant_parts, parse_entry, tool_call +from claude_code.entries import assistant_parts, parse_entry, tool_call, usage_count from git_command import commits from reading_cost.shell_reads import Reads, shell_reads from shell_command import resolved, simple_commands @@ -52,13 +52,7 @@ def commit_time(worker: list[dict], home: str) -> str | None: def tokens_in(entries: list[dict]) -> int: # Claude Code writes one entry per content block of a message, each with the message's usage. usages = {str(message.get("id") or entry.get("uuid")): message.get("usage") for entry in entries if isinstance(message := entry.get("message"), dict)} - return sum(count(usage, "input_tokens") + count(usage, "cache_creation_input_tokens") for usage in usages.values() if isinstance(usage, dict)) - - -# A count Claude Code left out or wrote as another type adds nothing, so one odd entry leaves the rest of the figure standing. -def count(usage: dict, field: str) -> int: - value = usage.get(field) - return value if isinstance(value, int) else 0 + return sum(usage_count(usage, "input_tokens") + usage_count(usage, "cache_creation_input_tokens") for usage in usages.values() if isinstance(usage, dict)) def call_of(part: object) -> tuple[object, dict]: diff --git a/bin/routing_figures/archive.py b/bin/routing_figures/archive.py index d1cf3731..6d3ee802 100644 --- a/bin/routing_figures/archive.py +++ b/bin/routing_figures/archive.py @@ -1,32 +1,74 @@ -"""Reads the chunks of every project in loop-claude's archive, and keeps the routing figures and the calls already raised at the archive's root.""" +"""Reads the chunks of every project in loop-claude's archive, and keeps the routing figures and the calls raised at the archive's root.""" +import contextlib +import dataclasses +import fcntl import json import pathlib import re +import typing -from routing_figures.measure import Chunk, ChunkFigures, measured, Subagent +from routing_figures.measure import Chunk, ChunkFigures, measured, MEASURED_AT, Subagent from failure import Failure from transcript_archive.read import finished_chunks from claude_code.entries import parse_entry from file_writes import replace_file from utc_stamp import STAMPED +from transcript_archive.outcomes import VERDICT_AT FIGURES = "routing-figures.md" +LOCK = "routing-figures.lock" RAISED = "routing-calls-raised.md" RAISED_HEADING = "# Routing calls raised\n" -RAISED_CALL = re.compile(rf"^- {STAMPED} (.+)$", re.MULTILINE) -VERDICT = re.compile(rf"^{STAMPED} Verdict: (?:finished|unfinished)$", re.MULTILINE) +# Each line is a call and when it was raised, or a reset: `- ` or `- Reset`. +RAISED_LINE = re.compile(rf"^- ({STAMPED}) (.+)$", re.MULTILINE) +RESET = "Reset" + + +@dataclasses.dataclass(frozen=True) +class Raised: + """since is the latest reset's stamp, empty for none; calls are those raised after it.""" + since: str + calls: frozenset[str] + + +@contextlib.contextmanager +def locked(root: pathlib.Path) -> typing.Iterator[bool]: + """Whether this loop holds the archive's routing lock; while another loop holds it, measuring is that loop's.""" + try: + handle = open(root / LOCK, "a") + except OSError: + yield False + return + with handle: + try: + fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB) + except OSError: + yield False + return + yield True def cycles(root: pathlib.Path) -> int | Failure: """The cycles every project's loop has closed with a verdict.""" try: - return sum(len(VERDICT.findall(path.read_text(encoding="utf-8"))) for path in root.rglob("*.outcomes.md")) + return sum(len(VERDICT_AT.findall(path.read_text(encoding="utf-8"))) for path in root.rglob("*.outcomes.md")) except (OSError, UnicodeDecodeError) as failure: return Failure(f"could not count the cycles in {root}: {failure}") -def measure_archive(root: pathlib.Path, home: str) -> list[ChunkFigures] | Failure: - """Each finished chunk's figures, measured one chunk at a time, since the archive outgrows memory.""" +def last_measured(root: pathlib.Path) -> int | Failure: + """The cycle the kept figures were measured at; 0 before any.""" + try: + found = MEASURED_AT.search((root / FIGURES).read_text(encoding="utf-8")) + except FileNotFoundError: + return 0 + except (OSError, UnicodeDecodeError) as failure: + return Failure(f"could not read {root / FIGURES}: {failure}") + return int(found.group(1)) if found else 0 + + +def measure_archive(root: pathlib.Path, home: str, since: str) -> list[ChunkFigures] | Failure: + """The figures of each chunk that finished after since, measured one chunk at a time, since the archive outgrows memory.""" try: projects = sorted({path.parent.parent for path in root.rglob("*.outcomes.md")}) except OSError as failure: @@ -36,14 +78,15 @@ def measure_archive(root: pathlib.Path, home: str) -> list[ChunkFigures] | Failu chunks = finished_chunks(project) if isinstance(chunks, Failure): return chunks - for chunk in chunks: + for chunk in (chunk for chunk in chunks if chunk.finished > since): folder = project / chunk.folder try: kept = "\n".join(path.read_text(encoding="utf-8") for path in sorted(folder.glob("*.outcomes.md"))) - subagents = [Subagent(meta(path), entries(path)) for path in chunk.subagents] - found.append(measured(Chunk(str(project.relative_to(root)), kept, entries(chunk.transcript), subagents), home)) + subagents = [subagent(path) for path in chunk.subagents] + worker = entries(chunk.transcript) except (OSError, UnicodeDecodeError) as failure: return Failure(f"could not read the chunk {folder}: {failure}") + found.append(measured(Chunk(str(project.relative_to(root)), kept, worker, subagents), home)) return found @@ -52,14 +95,15 @@ def entries(path: pathlib.Path) -> list[dict]: return [entry for line in handle if (entry := parse_entry(line))] -def meta(transcript: pathlib.Path) -> dict: - """The .meta.json Claude Code writes beside a subagent's transcript; empty where it wrote none or one this cannot read.""" +def subagent(transcript: pathlib.Path) -> Subagent: + """The subagent, named by the .meta.json Claude Code writes beside its transcript: {"agentType": "Explore", "toolUseId": "toolu_01…", ...}. A meta missing or unreadable names nothing.""" path = transcript.with_name(transcript.name.removesuffix(".jsonl") + ".meta.json") try: - found = json.loads(path.read_text(encoding="utf-8")) + meta = json.loads(path.read_text(encoding="utf-8")) except (FileNotFoundError, ValueError): - return {} - return found if isinstance(found, dict) else {} + meta = {} + meta = meta if isinstance(meta, dict) else {} + return Subagent(str(meta.get("agentType") or ""), str(meta.get("toolUseId") or ""), entries(transcript)) def write_figures(root: pathlib.Path, text: str) -> Failure | None: @@ -67,19 +111,22 @@ def write_figures(root: pathlib.Path, text: str) -> Failure | None: return Failure(f"could not write {root / FIGURES}: {unwritten.reason}") if unwritten else None -def unraised(root: pathlib.Path, found: list[str]) -> list[str] | Failure: - """The calls among found that were never raised.""" - raised = read_raised(root) - return raised if isinstance(raised, Failure) else [call for call in found if call not in set(RAISED_CALL.findall(raised))] +def raised(root: pathlib.Path) -> Raised | Failure: + text = read_raised(root) + if isinstance(text, Failure): + return text + lines = RAISED_LINE.findall(text) + since = max((stamp for stamp, what in lines if what == RESET), default="") + return Raised(since, frozenset(what for stamp, what in lines if stamp > since and what != RESET)) -def mark_raised(root: pathlib.Path, raised: list[str], at: str) -> Failure | None: +def mark_raised(root: pathlib.Path, calls: list[str], at: str) -> Failure | None: kept = read_raised(root) if isinstance(kept, Failure): return kept - # The first call opens a list below the heading; each later one joins it. - gap = "\n" if RAISED_CALL.search(kept) else "\n\n" - unwritten = replace_file(root / RAISED, (kept.rstrip("\n") + gap + "".join(f"- {at} {call}\n" for call in raised)).encode()) + # The first line opens a list below the heading; each later one joins it. + gap = "\n" if RAISED_LINE.search(kept) else "\n\n" + unwritten = replace_file(root / RAISED, (kept.rstrip("\n") + gap + "".join(f"- {at} {call}\n" for call in calls)).encode()) return Failure(f"could not write {root / RAISED}: {unwritten.reason}") if unwritten else None diff --git a/bin/routing_figures/measure.py b/bin/routing_figures/measure.py index 0fa4ac72..efb7dbff 100644 --- a/bin/routing_figures/measure.py +++ b/bin/routing_figures/measure.py @@ -5,28 +5,28 @@ import re import statistics import typing -from claude_code.entries import assistant_parts, parts, tool_call +from claude_code.entries import assistant_parts, parts, tool_call, usage_count from git_command import commits -from reading_cost.measure import count from model_routing.ladder import position, Rung from round_titles import round_counts -from loop_claude.routing import route_from +from model_routing.route import route_from from shell_command import simple_commands -from utc_stamp import STAMPED -from transcript_archive.outcomes import workers +from transcript_archive.outcomes import UNFINISHED_AT, workers +CYCLES_PER_CHECK = 20 +MEASURED_AT = re.compile(r"^Measured .+, at cycle ([0-9]+) across", re.MULTILINE) # A rung or a subagent type is compared only once this many of its chunks or subagents are measured, so a single odd chunk calls for no change. MEASURED_AT_LEAST = 5 DIMENSIONS = ("project", "subagent type", "rung", "tool") # The tool label of a message that follows no tool call, such as the first message after a prompt. PROMPT = "prompt" -UNFINISHED_AT = re.compile(rf"^{STAMPED} Verdict: unfinished$", re.MULTILINE) @dataclasses.dataclass(frozen=True) class Subagent: - """meta is the subagent's .meta.json: its agentType, and the toolUseId of the worker's Agent call that launched it.""" - meta: dict + """What the subagent's .meta.json names, its agentType and the toolUseId of the worker's Agent call that launched it, each empty where it names none; and its transcript's entries.""" + kind: str + launched_by: str entries: list[dict] @@ -74,23 +74,33 @@ def measured(chunk: Chunk, home: str) -> ChunkFigures: tokens: dict[str, collections.Counter[str]] = {dimension: collections.Counter() for dimension in DIMENSIONS} for at, tools, spent in spend(chunk.worker): add(tokens, chunk.project, "worker", str(rung_at(cycles, at)), tools, spent) - launches = {str(part.get("id")): (str(entry.get("timestamp", "")), arguments) for entry in chunk.worker for part in assistant_parts(entry) if (found := tool_call(part)) and found[0] == "Agent" and isinstance(arguments := found[1], dict)} + launches = agent_calls(chunk.worker) reported = results(chunk.worker) delegated: collections.Counter[str] = collections.Counter() reports: dict[str, Reports] = {} for subagent in chunk.subagents: - launch = str(subagent.meta.get("toolUseId")) - launched_at, arguments = launches.get(launch, ("", {})) - kind = str(subagent.meta.get("agentType") or arguments.get("subagent_type") or "unknown") + launched_at, arguments = launches.get(subagent.launched_by, ("", {})) + kind = subagent.kind or str(arguments.get("subagent_type") or "unknown") rung = str(subagent_rung(subagent.entries, arguments, rung_at(cycles, launched_at))) delegated[rung] += 1 - reports[kind] = reports.get(kind, Reports(0, 0, 0)) + Reports(1, len(reported.get(launch, "")), 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): add(tokens, chunk.project, kind, rung, tools, spent) start = route_from(cycles[0][1]) if cycles else None return ChunkFigures(tokens, start.rung if start and start.item else None, rounds_past_first(chunk.worker, home), len(UNFINISHED_AT.findall(chunk.outcomes)), delegated, reports) +def agent_calls(worker: list[dict]) -> dict[str, tuple[str, dict]]: + """The timestamp and the arguments of each Agent call, by the call's id.""" + found = {} + for entry in worker: + for part in assistant_parts(entry): + call = tool_call(part) + if call and call[0] == "Agent" and isinstance(part, dict) and isinstance(call[1], dict): + found[str(part.get("id"))] = (str(entry.get("timestamp", "")), call[1]) + return found + + def add(tokens: dict[str, collections.Counter[str]], project: str, kind: str, rung: str, tools: list[str], spent: int) -> None: tokens["project"][project] += spent tokens["subagent type"][kind] += spent @@ -130,7 +140,7 @@ def spend(entries: list[dict]) -> list[tuple[str, list[str], int]]: spent = [] before = [PROMPT] for at, usage, called in messages.values(): - tokens = sum(count(usage, field) for field in ("input_tokens", "cache_creation_input_tokens", "output_tokens")) if isinstance(usage, dict) else 0 + tokens = sum(usage_count(usage, field) for field in ("input_tokens", "cache_creation_input_tokens", "output_tokens")) if isinstance(usage, dict) else 0 spent.append((at, before, tokens)) before = called or [PROMPT] return spent @@ -142,11 +152,17 @@ def results(entries: list[dict]) -> dict[str, str]: for entry in entries: for part in parts(entry): if isinstance(part, dict) and part.get("type") == "tool_result": - body = part.get("content") - found[str(part.get("tool_use_id"))] = body if isinstance(body, str) else "".join(block["text"] for block in body if isinstance(block, dict) and isinstance(block.get("text"), str)) if isinstance(body, list) else "" + found[str(part.get("tool_use_id"))] = result_text(part.get("content")) return found +# {"type": "tool_result", "content": "hi"} or {"type": "tool_result", "content": [{"type": "text", "text": "hi"}]} +def result_text(body: object) -> str: + if isinstance(body, str): + return body + return "".join(block["text"] for block in body if isinstance(block, dict) and isinstance(block.get("text"), str)) if isinstance(body, list) else "" + + def rounds_past_first(worker: list[dict], home: str) -> int: # A commit retried after a failed hook repeats its title, so each title counts once. titles = dict.fromkeys( @@ -158,6 +174,11 @@ def rounds_past_first(worker: list[dict], home: str) -> int: return sum(max(0, rounds - 1) for rounds in round_counts(list(titles)).values()) +def due(cycle: int, last_measured: int) -> bool: + """Whether the archive's cycle count has run CYCLES_PER_CHECK past the cycle the figures were last measured at: counting from the last measurement, a count another loop pushed past a multiple still measures.""" + return cycle >= last_measured + CYCLES_PER_CHECK + + def totals(chunks: list[ChunkFigures]) -> Figures: tokens = {dimension: sum((chunk.tokens.get(dimension, collections.Counter()) for chunk in chunks), collections.Counter()) for dimension in DIMENSIONS} routed: dict[Rung, list[ChunkFigures]] = {} @@ -178,7 +199,7 @@ def calls(figures: Figures) -> list[str]: for what, of in (("review rounds past each pass's first", lambda chunk: chunk.rounds_past_first), ("unfinished verdicts", lambda chunk: chunk.unfinished)): if mean(figures.routed[lower], of) > mean(figures.routed[upper], of): found.append(f"Chunks routed onto {lower} took more {what} than chunks routed onto {upper}.") - # Characters stand in for tokens: both sides are text the worker would read. + # Characters stand in for tokens: both sides are text the worker would read. Both would fill the same peak context, so comparing the sums compares their shares of it. found += [f"{kind} subagents' reports took more of the worker's context than their searches would have." for kind, reports in sorted(figures.reports.items()) if reports.subagents >= MEASURED_AT_LEAST and reports.report > reports.searches] return found @@ -187,10 +208,11 @@ def mean(chunks: list[ChunkFigures], of: typing.Callable[[ChunkFigures], int]) - return statistics.mean(map(of, chunks)) -def render(figures: Figures, found: list[str], at: str, cycle: int) -> str: +def render(figures: Figures, found: list[str], at: str, cycle: int, since: str) -> str: + """The figures as markdown; MEASURED_AT reads the cycle back. since is the latest reset's stamp, empty for none.""" sections = [ "# Routing figures", - f"Measured {at}, at cycle {cycle} across loop-claude's archive, from {figures.chunks} finished chunk{'' if figures.chunks == 1 else 's'}. Tokens are input, cache-written and output tokens; cache reads are left out. A message's tokens count towards the tools whose results it took in, split evenly.", + f"Measured {at}, at cycle {cycle} across loop-claude's archive, from {figures.chunks} finished chunk{'' if figures.chunks == 1 else 's'}{f' that finished after the reset of {since}' if since else ''}. Tokens are input, cache-written and output tokens; cache reads are left out. A message's tokens count towards the tools whose results it took in, split evenly.", "## Calls for a routing change", "".join(f"- {call}\n" for call in found).rstrip("\n") or "None.", *[part for dimension in DIMENSIONS for part in (f"## Tokens by {dimension}", table((dimension.capitalize(), "Tokens"), [(label, str(tokens)) for label, tokens in figures.tokens[dimension].most_common()]))], diff --git a/bin/routing_figures/test_routing_figures.py b/bin/routing_figures/test_routing_figures.py index f54aaefb..7d5378b2 100644 --- a/bin/routing_figures/test_routing_figures.py +++ b/bin/routing_figures/test_routing_figures.py @@ -1,6 +1,7 @@ import collections import json import pathlib +import shutil import sys import tempfile import unittest @@ -8,7 +9,7 @@ import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from routing_figures import archive -from routing_figures.measure import calls, Chunk, ChunkFigures, measured, render, Reports, Subagent, totals +from routing_figures.measure import calls, Chunk, ChunkFigures, due, measured, render, Reports, Subagent, totals from failure import Failure from transcript_archive import outcomes from model_routing.ladder import Rung @@ -61,8 +62,8 @@ class Measured(unittest.TestCase): result("a2", "y" * 5), ] subagents = [ - Subagent({"agentType": "Explore", "toolUseId": "a1"}, [message("s1", "2026-10-14T10:00:01Z", model="claude-sonnet-5-5"), result("r", "z" * 20)]), - Subagent({"agentType": "Explore", "toolUseId": "a2"}, [message("s2", "2026-10-14T10:00:01Z")]), + Subagent("Explore", "a1", [message("s1", "2026-10-14T10:00:01Z", model="claude-sonnet-5-5"), result("r", "z" * 20)]), + Subagent("", "a2", [message("s2", "2026-10-14T10:00:01Z")]), ] found = measured(Chunk("log", stamped("2026-10-14T11:00:00Z", outcomes.finished(LOW_ROUTE, "m")), worker, subagents), "/h") self.assertEqual(found.delegated, {"claude-sonnet-5-5 at high effort": 1, str(LOW): 1}) @@ -103,19 +104,24 @@ class Calls(unittest.TestCase): def test_renders_each_dimension_largest_first_and_the_calls(self): chunk = ChunkFigures({"project": collections.Counter({"a": 2, "b": 20})}, LOW, 1, 0, collections.Counter({str(HIGH): 2}), {"Explore": Reports(2, 3, 4)}) - text = render(totals([chunk]), ["Call."], "2026-10-15T00:00:00Z", 40) + text = render(totals([chunk]), ["Call."], "2026-10-15T00:00:00Z", 40, "") self.assertIn("Measured 2026-10-15T00:00:00Z, at cycle 40 across loop-claude's archive, from 1 finished chunk.", text) self.assertIn("## Calls for a routing change\n\n- Call.\n", text) self.assertIn("| b | 20 |\n| a | 2 |", text) self.assertIn(f"| {LOW} | 1 | 1.0 | 0.0 | {HIGH} 2 |", text) self.assertIn("| Explore | 2 | 3 | 4 |", text) - self.assertIn("## Calls for a routing change\n\nNone.\n", render(totals([]), [], "2026-10-15T00:00:00Z", 20)) + self.assertIn("## Calls for a routing change\n\nNone.\n", render(totals([]), [], "2026-10-15T00:00:00Z", 20, "")) + self.assertIn("from 0 finished chunks that finished after the reset of 2026-10-14T00:00:00Z.", render(totals([]), [], "2026-10-15T00:00:00Z", 20, "2026-10-14T00:00:00Z")) + + def test_measures_once_the_count_runs_20_past_the_last_measurement(self): + self.assertEqual([due(cycle, 20) for cycle in (39, 40, 41)], [False, True, True]) + self.assertTrue(due(20, 0)) class Archive(unittest.TestCase): def setUp(self): self.root = pathlib.Path(tempfile.mkdtemp()) - self.addCleanup(lambda: __import__("shutil").rmtree(self.root)) + self.addCleanup(shutil.rmtree, self.root) def chunk(self, key, name, kept, worker, subagent=None): folder = self.root / key / name @@ -136,22 +142,34 @@ class Archive(unittest.TestCase): def test_measures_each_finished_chunk_keyed_by_its_project(self): self.chunk("home/x", "c1", stamped("2026-10-14T10:00:00Z", outcomes.finished(LOW_ROUTE, "m")), [message("m1", "2026-10-14T09:00:00Z", call("Agent", "a1", subagent_type="Explore"))], ({"agentType": "Explore", "toolUseId": "a1"}, [message("s1", "2026-10-14T09:00:01Z")])) self.chunk("log", "c2", stamped("2026-10-14T10:00:00Z", outcomes.unfinished(LOW_ROUTE, "e")), [message("m1", "2026-10-14T09:00:00Z")]) - found = archive.measure_archive(self.root, "/h") + found = archive.measure_archive(self.root, "/h", "") self.assertEqual([chunk.tokens["project"] for chunk in found], [{"home/x": 222}]) self.assertEqual(found[0].tokens["subagent type"], {"worker": 111, "Explore": 111}) + self.assertEqual(archive.measure_archive(self.root, "/h", "2026-10-14T10:00:00Z"), []) - def test_keeps_the_figures_and_says_which_calls_it_raises_for_the_first_time(self): - self.assertIsNone(archive.write_figures(self.root, "# Routing figures\n")) - self.assertEqual((self.root / archive.FIGURES).read_text(), "# Routing figures\n") - self.assertEqual(archive.unraised(self.root, ["A.", "B."]), ["A.", "B."]) + def test_keeps_the_figures_and_reads_back_the_cycle_they_were_measured_at(self): + self.assertEqual(archive.last_measured(self.root), 0) + self.assertIsNone(archive.write_figures(self.root, render(totals([]), [], "2026-10-15T00:00:00Z", 40, ""))) + self.assertEqual(archive.last_measured(self.root), 40) + + def test_reads_the_calls_raised_since_the_latest_reset(self): + self.assertEqual(archive.raised(self.root), archive.Raised("", frozenset())) self.assertIsNone(archive.mark_raised(self.root, ["A."], "2026-10-15T00:00:00Z")) - self.assertEqual(archive.unraised(self.root, ["A.", "B."]), ["B."]) self.assertIsNone(archive.mark_raised(self.root, ["B."], "2026-10-15T01:00:00Z")) self.assertEqual((self.root / archive.RAISED).read_text(), "# Routing calls raised\n\n- 2026-10-15T00:00:00Z A.\n- 2026-10-15T01:00:00Z B.\n") + self.assertEqual(archive.raised(self.root), archive.Raised("", frozenset({"A.", "B."}))) + self.assertIsNone(archive.mark_raised(self.root, ["Reset"], "2026-10-15T00:30:00Z")) + self.assertEqual(archive.raised(self.root), archive.Raised("2026-10-15T00:30:00Z", frozenset({"B."}))) + + def test_holds_the_lock_while_no_other_loop_does(self): + with archive.locked(self.root) as held, archive.locked(self.root) as other: + self.assertEqual((held, other), (True, False)) + with archive.locked(self.root) as again: + self.assertTrue(again) def test_fails_on_an_archive_it_cannot_read(self): (self.root / archive.RAISED).mkdir() - self.assertIsInstance(archive.unraised(self.root, ["A."]), Failure) + self.assertIsInstance(archive.raised(self.root), Failure) if __name__ == "__main__": diff --git a/bin/transcript_archive/outcomes.py b/bin/transcript_archive/outcomes.py index 67df3265..a7ffcde2 100644 --- a/bin/transcript_archive/outcomes.py +++ b/bin/transcript_archive/outcomes.py @@ -4,7 +4,11 @@ from markdown_text import quoted from utc_stamp import STAMPED FINISHED = "Verdict: finished" +UNFINISHED = "Verdict: unfinished" FINISHED_AT = re.compile(rf"^({STAMPED}) {re.escape(FINISHED)}$", re.MULTILINE) +UNFINISHED_AT = re.compile(rf"^{STAMPED} {re.escape(UNFINISHED)}$", re.MULTILINE) +# A verdict closes each cycle the judge ruled on; an interrupt or a stop closes none. +VERDICT_AT = re.compile(rf"^{STAMPED} (?:{re.escape(FINISHED)}|{re.escape(UNFINISHED)})$", re.MULTILINE) # An outcome opens with its UTC stamp; a verdict that closes a cycle, a stop, or a step up ends with the worker line. OUTCOME_AT = re.compile(rf"^({STAMPED}) ", re.MULTILINE) NAMES_A_WORKER = ("Verdict: finished\n", "Verdict: unfinished\n", "Stopped: ", "Stepped up\n") @@ -16,7 +20,7 @@ def finished(worker: str, evidence: str) -> str: def unfinished(worker: str, evidence: str) -> str: - return f"Verdict: unfinished\n\nEvidence:\n{quoted(evidence)}\n\n{WORKER}{worker}" + return f"{UNFINISHED}\n\nEvidence:\n{quoted(evidence)}\n\n{WORKER}{worker}" def interrupted(question: str, evidence: str) -> str: diff --git a/docs/decisions.md b/docs/decisions.md index 03b65f69..f824ca6c 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -176,7 +176,7 @@ Valid while a mutation run on a chunk's changed lines stays cheap beside the rev The rungs, least competent first: Haiku 5.5 at low, medium, high, xhigh and max; Sonnet 5.5 at high; Opus 5.5 at medium, high, xhigh and max; Fable 5.1 at max. The order and the cut come from the Artificial Analysis Intelligence Index (https://artificialanalysis.ai/leaderboards/models, read 2026-10-14), which scores each model at each effort and gives a cost per task. A rung stays only where no cheaper rung scores as high, so a step up always buys more score (goal 1.4). That cut drops Sonnet 5.5 at low, medium, xhigh and max, Opus 5.5 at low, and every Fable 5.1 rung, and every tie in the index falls among the dropped rungs. lilleman put Fable 5.1 at max back on top: the index scores it under Opus 5.5 at high, but Anthropic's model catalog names Fable the most capable model, and for the hardest tasks lilleman wants the highest quality at any price. -A chunk's worker runs on the rung its item picks, below the project's rung too. Only chunks run below the project's rung can prove that a cheaper worker holds quality (goal 1.1). So on 2026-10-14 lilleman chose a trial on real chunks: a replay of past chunks spends on work nothing ships (goal 1.4). Review holds quality meanwhile. While the worker runs below the project's rung, loop-claude's prompt has it launch each reviewer, each comprehension seat and the security pass's subagent on the project's rung, through the Agent tool's model and effort. It runs a full scan only from such a subagent, because the `claude-security` plugin's researchers and verifiers inherit the model that starts them. A subagent that cannot run the scan leaves it unavailable, so larv-review runs `/security-review` in its place. The cost of a cheaper worker shows as extra review rounds and unfinished verdicts. Every 20th cycle across the archive, loop-claude measures them in code, with no model run (goal 1.4), and interrupts lilleman once per call when chunks routed onto a rung took more of either than chunks routed onto the next rung up, each rung with 5 chunks or more. Five keeps one odd chunk from calling for a change (goal 1.2). It also calls when the reports of 5 or more subagents of one type were longer than the tool results they read, so a delegated search cost the worker more context than it saved. `bin/routing_figures/` measures and words the calls. A loop on another project cannot commit here, so it writes the figures and the calls raised at the archive's root, and this repo's next chunk files the plan item, as `AGENTS.md` says. A project's rung is its model's cheapest rung, which for Opus 5.5 is its default effort, medium. lilleman chose medium knowing `settings.json` runs Opus 5.5 at xhigh, so a routed worker runs below the effort an interactive session takes. +A chunk's worker runs on the rung its item picks, below the project's rung too. Only chunks run below the project's rung can prove that a cheaper worker holds quality (goal 1.1). So on 2026-10-14 lilleman chose a trial on real chunks: a replay of past chunks spends on work nothing ships (goal 1.4). Review holds quality meanwhile. While the worker runs below the project's rung, loop-claude's prompt has it launch each reviewer, each comprehension seat and the security pass's subagent on the project's rung, through the Agent tool's model and effort. It runs a full scan only from such a subagent, because the `claude-security` plugin's researchers and verifiers inherit the model that starts them. A subagent that cannot run the scan leaves it unavailable, so larv-review runs `/security-review` in its place. The cost of a cheaper worker shows as extra review rounds and unfinished verdicts. Every 20 cycles across the archive, loop-claude measures them in code, with no model run (goal 1.4), and interrupts lilleman once per call when chunks routed onto a rung took more of either than chunks routed onto the next rung up, each rung with 5 chunks or more. Five keeps one odd chunk from calling for a change (goal 1.2). It also calls when the reports of 5 or more subagents of one type were longer than the tool results they read, so a delegated search cost the worker more context than it saved. `bin/routing_figures/` measures and words the calls. A loop on another project cannot commit here, so it writes the figures and the calls raised at the archive's root, and this repo's next chunk files the plan item, as `AGENTS.md` says. Off a terminal, a call is said on stderr and the loop goes on: it is about this setup, not the running project's chunk. A reset line in the calls file restarts the figures after a routing change, so they show whether the change worked. A project's rung is its model's cheapest rung, which for Opus 5.5 is its default effort, medium. lilleman chose medium knowing `settings.json` runs Opus 5.5 at xhigh, so a routed worker runs below the effort an interactive session takes. A model off the ladder routes nothing: claude runs it at the effort its settings give. R + C steps a task from the project's rung: 2–4 three rungs down, 5–6 two down, 7–8 one down, 9–10 none, 11–12 one up, 13–14 two up, 15–16 three up, 17 and above four up. A step past either end stops there. The bands spread the R + C that `todo.md`'s items held on 2026-10-14, 2 to 12, across the rungs, so most tasks step down. S never moves a rung, so a huge task with low R and C runs cheap. While the worker runs above the project's rung, loop-claude's prompt has it launch the comprehension seats and the security pass's subagent on the project's rung too. So the seats score every chunk on one rung, and the security pass spends no more than the project chose. The prompt after each unfinished verdict repeats this, since a step-up may have taken the worker above the project's rung. The other reviewers inherit the worker's higher rung until item 90 routes them. `score-outcomes` had too few finished chunks to ground the bands, and a change to the ladder or the bands is lilleman's.