Measure routing figures every 20th cycle and raise each call for a routing change once
This commit is contained in:
@@ -60,6 +60,18 @@ 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.
|
||||
|
||||
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.
|
||||
|
||||
@@ -101,6 +113,8 @@ import sys
|
||||
import typing
|
||||
|
||||
from transcript_archive.write import archive
|
||||
from transcript_archive.location import archive_root, project_archive
|
||||
from loop_claude.loop.routing_check import check_routing
|
||||
from loop_claude.project.checkout import checkout_root
|
||||
from loop_claude.cycle.run import Cycle, run_cycle
|
||||
from loop_claude.loop.reload import decode_handed, exec_if_edited, fingerprint, LoopRun, RELOAD_FLAG
|
||||
@@ -113,7 +127,6 @@ from todo_table import Item
|
||||
from transcript_archive.read import latest_worker
|
||||
from transcript_archive import outcomes
|
||||
from loop_claude.paths import Paths
|
||||
from transcript_archive.location import project_archive
|
||||
from project_key import project_key
|
||||
from model_routing.ladder import project_rung, Rung
|
||||
from loop_claude.project.premises import read_premises
|
||||
@@ -165,6 +178,8 @@ 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):
|
||||
return stop
|
||||
|
||||
|
||||
def routed(loop_run: LoopRun, anchor: Rung | None, archived: typing.Callable[[], Route | None], item: typing.Callable[[], Item | None]) -> LoopRun:
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
"""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:`."""
|
||||
import pathlib
|
||||
import sys
|
||||
|
||||
from routing_figures import archive
|
||||
from routing_figures.measure import calls, render, totals
|
||||
from loop_claude.effects import Effects
|
||||
from failure import Failure
|
||||
from loop_claude.stop import needs_terminal, Stop
|
||||
from loop_claude.paths import Paths
|
||||
from claude_code.trust import trust
|
||||
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 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."""
|
||||
cycle = archive.cycles(root)
|
||||
if isinstance(cycle, Failure) or not cycle or cycle % CYCLES_PER_CHECK:
|
||||
return cycle if isinstance(cycle, Failure) else []
|
||||
print(f"\n=== cycle {cycle} across loop-claude's archive: measuring the routing figures ===", flush=True)
|
||||
measured = archive.measure_archive(root, str(paths.home))
|
||||
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)
|
||||
|
||||
|
||||
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}")
|
||||
if unmarked := archive.mark_raised(root, new, utc(effects.now())):
|
||||
print(f"routing figures: {unmarked.reason}", file=sys.stderr)
|
||||
return None
|
||||
@@ -5,6 +5,7 @@ import io
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import shutil
|
||||
import stat
|
||||
import subprocess
|
||||
import sys
|
||||
@@ -23,7 +24,7 @@ from loop_claude.cycle.judge import Finished, Interrupt, QuotedAnswer, Unfinishe
|
||||
from loop_claude.cycle import interrupt, judge, prompts, retry, run, states, worker
|
||||
from model_routing.ladder import LADDER, Rung
|
||||
from loop_claude.cycle.retry import Limited
|
||||
from loop_claude.loop import main, reload
|
||||
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
|
||||
@@ -365,6 +366,64 @@ class Interrupts(unittest.TestCase):
|
||||
self.assertEqual(stop, Stop(2, "the human is needed to answer the question above, but the interrupt ended with nothing typed"))
|
||||
|
||||
|
||||
class RoutingCheck(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.home = pathlib.Path(tempfile.mkdtemp())
|
||||
self.addCleanup(shutil.rmtree, self.home)
|
||||
self.root = self.home / "archive"
|
||||
self.paths = paths.paths_from(self.home)
|
||||
|
||||
def chunks(self, count, verdicts):
|
||||
"""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}"
|
||||
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))
|
||||
(folder / "copy.outcomes.md").write_text(f"Task: t\n\n{kept}2026-10-14T11:00:00Z {outcomes.finished('w', 'm')}\n")
|
||||
launch = {"type": "assistant", "timestamp": "2026-10-14T09:00:00Z", "message": {"id": "m", "content": [{"type": "tool_use", "id": "a", "name": "Agent", "input": {"subagent_type": "Explore"}}]}}
|
||||
report = {"type": "user", "message": {"content": [{"type": "tool_result", "tool_use_id": "a", "content": "long report"}]}}
|
||||
(folder / "copy.jsonl").write_text(json.dumps(launch) + "\n" + json.dumps(report) + "\n")
|
||||
(subagents / "agent-a.jsonl").write_text("")
|
||||
(subagents / "agent-a.meta.json").write_text(json.dumps({"agentType": "Explore", "toolUseId": "a"}))
|
||||
|
||||
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())
|
||||
return stop, said.getvalue()
|
||||
|
||||
def test_measures_only_at_every_20th_cycle(self):
|
||||
self.chunks(5, 3)
|
||||
self.assertEqual(self.check(FakeEffects()), (None, ""))
|
||||
self.assertFalse((self.root / "routing-figures.md").exists())
|
||||
|
||||
def test_hands_the_terminal_over_once_for_each_new_call(self):
|
||||
self.chunks(5, 4)
|
||||
fake = FakeEffects(on_terminal_claude=[0], git=[ran()])
|
||||
stop, said = self.check(fake)
|
||||
self.assertIsNone(stop)
|
||||
call = "Explore subagents' reports took more of the worker's context than their searches would have."
|
||||
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, ""))
|
||||
|
||||
def test_stops_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)
|
||||
|
||||
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)
|
||||
|
||||
|
||||
class ModelPrompt(unittest.TestCase):
|
||||
OFFERED = [("claude-opus-5-5", "Opus 5.5"), ("claude-haiku-4-5", "Haiku 4.5")]
|
||||
|
||||
@@ -725,6 +784,7 @@ class ExitContract(unittest.TestCase):
|
||||
("loop/main.py", "loop_run_from", "0 if task else 1", "__doc__.strip()", "no task is given"),
|
||||
("loop/main.py", "loop_run_from", "1", 'f"the edited loop-claude cannot read the state', "a reload cannot read the state the running script handed it"),
|
||||
("loop/reload.py", "exec_if_edited", "1", "f'could not reload loop-claude:", "python cannot start for a reload"),
|
||||
("loop/routing_check.py", "raise_calls", "1", "f'could not start claude for the routing calls:", "claude cannot start for an interrupt"),
|
||||
("project/checkout.py", "checkout_root", "1", "f'could not start git:", git),
|
||||
("project/checkout.py", "checkout_root", "1", "found.stderr.strip()", git),
|
||||
("project/model_choice.py", "get_or_ask_model", "1", "f'could not save the model in", models_),
|
||||
|
||||
Reference in New Issue
Block a user