import collections import contextlib import io import json import pathlib import shutil import sys import tempfile 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, due, measured, render, Reports, Subagent, totals from failure import Failure from model_routing.ladder import LADDER, Rung from transcript_archive import outcomes, write LOW = Rung("claude-opus-5-5", "medium") HIGH = Rung("claude-opus-5-5", "high") LOW_ROUTE = f"{LOW}, routed by item 7's L of 3 and E + I of 4" def message(id_, at, *parts, model="claude-opus-5-5", tokens=(1, 10, 100)): return {"type": "assistant", "timestamp": at, "cwd": "/c", "message": {"id": id_, "model": model, "content": list(parts), "usage": {"input_tokens": tokens[0], "cache_creation_input_tokens": tokens[1], "output_tokens": tokens[2], "cache_read_input_tokens": 5000}}} def call(name, id_="t1", **arguments): return {"type": "tool_use", "id": id_, "name": name, "input": arguments} def result(id_, text): return {"type": "user", "message": {"content": [{"type": "tool_result", "tool_use_id": id_, "content": [{"type": "text", "text": text}]}]}} def stamped(at, outcome): return f"{at} {outcome}\n" def figures(start=LOW, rounds=0, unfinished=0, reports=None, escalated=None): return ChunkFigures({}, start, rounds, unfinished, collections.Counter(), reports or {}, collections.Counter(escalated or {})) class Measured(unittest.TestCase): def test_counts_each_messages_tokens_once_by_project_type_rung_and_the_tool_it_followed(self): worker = [ message("m1", "2026-10-14T10:00:00.100Z", {"type": "text", "text": "reading"}), message("m1", "2026-10-14T10:00:00.200Z", call("Read", file_path="/c/a")), message("m2", "2026-10-14T10:05:00.000Z", {"type": "text", "text": "done"}), message("m3", "2026-10-14T11:00:00.000Z", {"type": "text", "text": "on"}), ] kept = stamped("2026-10-14T10:30:00Z", outcomes.unfinished(LOW_ROUTE, "e", "j", "")) + stamped("2026-10-14T10:30:00Z", outcomes.stepped_up(str(HIGH))) + stamped("2026-10-14T12:00:00Z", outcomes.finished(str(HIGH), "merged", "j")) found = measured(Chunk("log", [kept], worker, []), "/h") self.assertEqual(found.tokens["project"], {"log": 333}) self.assertEqual(found.tokens["subagent type"], {"worker": 333}) self.assertEqual(found.tokens["rung"], {str(LOW): 222, str(HIGH): 111}) self.assertEqual(found.tokens["tool"], {"prompt": 222, "Read": 111}) self.assertEqual((found.start, found.unfinished), (LOW, 1)) def test_reads_a_subagents_rung_from_its_model_and_the_effort_its_call_set_or_else_the_workers(self): worker = [ message("m1", "2026-10-14T10:00:00Z", call("Agent", "a1", subagent_type="Explore", model="sonnet", effort="high", prompt="find"), call("Agent", "a2", subagent_type="Explore", prompt="find")), result("a1", "x" * 30), result("a2", "y" * 5), ] subagents = [ 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", "j"))], worker, subagents), "/h") self.assertEqual(found.delegated, {"claude-sonnet-5-5 at high effort": 1, str(LOW): 1}) self.assertEqual(found.tokens["subagent type"], {"worker": 111, "Explore": 222}) self.assertEqual(found.reports, {"Explore": Reports(2, 35, 20)}) def test_counts_the_workers_escalations_by_the_trigger_each_subagents_prompt_opens_with(self): worker = [ message("m1", "2026-10-14T10:00:00Z", call("Agent", "a1", prompt="Escalation trigger 2: the test failed twice"), call("Agent", "a2", prompt="Escalation trigger 2: again"), call("Agent", "a3", prompt="Escalation trigger 3: a 🔴 in round 2")), message("m2", "2026-10-14T10:01:00Z", call("Agent", "a4", prompt="Find the callers. Escalation trigger 1: not at the start"), call("Agent", "a5", prompt="Escalation trigger x: no number")), ] self.assertEqual(measured(Chunk("log", [], worker, []), "/h").escalated, {2: 2, 3: 1}) def test_counts_review_rounds_past_each_passs_first_once_per_title(self): commit = lambda id_, title: message(id_, "2026-10-14T10:00:00Z", call("Bash", command=f"git commit -m '{title}'")) worker = [commit("m1", "Answer stability round 1: 1 🔴, 0 🟡"), commit("m2", "Answer stability round 2: 0 🔴, 0 🟡"), commit("m3", "Answer stability round 2: 0 🔴, 0 🟡"), commit("m4", "Answer prose round 1: 0 🔴, 1 🟡")] self.assertEqual(measured(Chunk("log", [], worker, []), "/h").rounds_past_first, 1) def test_reads_the_rung_of_a_route_an_older_loop_claude_archived_by_r_plus_c(self): older = f"{LOW}, routed by item 7's R + C of 9" kept = stamped("2026-10-14T10:00:00Z", outcomes.finished(older, "m", "j")) found = measured(Chunk("log", [kept], [message("m1", "2026-10-14T09:00:00Z")], []), "/h") self.assertEqual(found.start, LOW) self.assertEqual(found.tokens["rung"], {str(LOW): 111}) def test_starts_no_route_for_a_chunk_no_item_routed(self): kept = stamped("2026-10-14T10:00:00Z", outcomes.finished(str(LOW), "m", "j")) found = measured(Chunk("log", [kept], [message("m1", "2026-10-14T09:00:00Z")], []), "/h") self.assertIsNone(found.start) self.assertEqual(found.tokens["rung"], {str(LOW): 111}) def test_puts_a_subagent_on_the_model_it_ran_at_the_effort_of_the_cycle_that_launched_it(self): kept = stamped("2026-10-14T10:00:00Z", outcomes.unfinished(LOW_ROUTE, "e", "j", "")) + stamped("2026-10-14T11:00:00Z", outcomes.finished(str(HIGH), "m", "j")) worker = [ message("m1", "2026-10-14T10:00:00.900Z"), message("m2", "2026-10-14T10:30:00Z", call("Agent", "a1", subagent_type="Explore", model="sonnet")), message("m3", "2026-10-14T10:31:00Z", call("Agent", "a2", subagent_type="Explore")), ] subagents = [Subagent("Explore", "a1", [result("r", "x")]), Subagent("Explore", "a2", [message("s2", "2026-10-14T10:31:01Z", model="claude-opus-5-5")])] found = measured(Chunk("log", [kept], worker, subagents), "/h") self.assertEqual(found.delegated, {"sonnet at high effort": 1, str(HIGH): 1}) self.assertEqual(found.tokens["rung"], {str(LOW): 111, str(HIGH): 333}) def test_names_a_subagent_by_its_meta_or_else_its_call_or_else_unknown(self): worker = [message("m1", "2026-10-14T10:00:00Z", call("Agent", "a1", subagent_type="Explore"), call("Agent", "a2", subagent_type="Plan"))] subagents = [Subagent("stability-reviewer", "a1", []), Subagent("", "a2", []), Subagent("", "", [])] self.assertEqual(measured(Chunk("log", [], worker, subagents), "/h").reports, {"stability-reviewer": Reports(1, 0, 0), "Plan": Reports(1, 0, 0), "unknown": Reports(1, 0, 0)}) def test_counts_a_message_without_usage_as_nothing_and_splits_tokens_whole_across_tools(self): worker = [ {"type": "assistant", "uuid": "u1", "message": {"content": [call("Read"), call("Grep")], "usage": {"input_tokens": 3, "output_tokens": "many"}}}, {"type": "user", "message": {"content": [{"type": "tool_result", "tool_use_id": "t1", "content": "plain"}, "odd"]}}, {"type": "assistant", "uuid": "u2", "message": {"content": [], "usage": {"input_tokens": 5}}}, {"type": "assistant", "uuid": "u3", "message": {"content": []}}, ] found = measured(Chunk("log", [], worker, []), "/h") self.assertEqual(found.tokens["tool"], {"prompt": 3, "Read": 3, "Grep": 2}) self.assertEqual(found.tokens["project"], {"log": 8}) class Calls(unittest.TestCase): def test_calls_when_chunks_on_a_rung_took_more_rounds_or_unfinished_verdicts_than_the_rung_above(self): chunks = [figures(LOW, rounds=2)] * 5 + [figures(HIGH, unfinished=1)] * 5 self.assertEqual(calls(totals(chunks)), [ f"Chunks routed onto {LOW} took more review rounds past each pass's first than chunks routed onto {HIGH}.", ]) self.assertEqual(calls(totals([figures(LOW, unfinished=1)] * 5 + [figures(HIGH)] * 5)), [ f"Chunks routed onto {LOW} took more unfinished verdicts than chunks routed onto {HIGH}.", ]) def test_compares_the_bottom_rungs_and_calls_nothing_on_a_tie(self): self.assertEqual(calls(totals([figures(LADDER[0], rounds=1)] * 5 + [figures(LADDER[1])] * 5)), [f"Chunks routed onto {LADDER[0]} took more review rounds past each pass's first than chunks routed onto {LADDER[1]}."]) self.assertEqual(calls(totals([figures(LOW, rounds=1)] * 5 + [figures(HIGH, rounds=1)] * 5)), []) self.assertEqual(calls(totals([figures(reports={"Explore": Reports(1, 20, 20)})] * 5)), []) def test_compares_only_rungs_with_five_chunks_each(self): self.assertEqual(calls(totals([figures(LOW, rounds=2)] * 5 + [figures(HIGH)] * 4)), []) def test_calls_when_a_subagent_types_reports_outgrow_the_searches_they_ran(self): self.assertEqual(calls(totals([figures(reports={"Explore": Reports(1, 30, 20)})] * 5)), [ "Explore subagents' reports took more of the worker's context than their searches would have.", ]) self.assertEqual(calls(totals([figures(reports={"Explore": Reports(1, 30, 20)})] * 4)), []) self.assertEqual(calls(totals([figures(reports={"Explore": Reports(1, 20, 30)})] * 5)), []) 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)}, collections.Counter()) 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) two = ChunkFigures({}, HIGH, 0, 1, collections.Counter({str(HIGH): 2, str(LOW): 1}), {}, collections.Counter()) self.assertIn(f"| {LOW} | 1 | 1.0 | 0.0 | {HIGH} 2 | |\n| {HIGH} | 1 | 0.0 | 1.0 | {HIGH} 2, {LOW} 1 | |", render(totals([two, chunk]), [], "2026-10-15T00:00:00Z", 40, "")) self.assertIn("| Explore | 2 | 3 | 4 |", text) escalated = render(totals([figures(escalated={2: 2}), figures(escalated={2: 1, 10: 1}), figures(start=None, escalated={3: 1})]), [], "2026-10-15T00:00:00Z", 40, "") self.assertIn(f"| {LOW} | 2 | 0.0 | 0.0 | | trigger 2: 3, trigger 10: 1 |", escalated) self.assertIn("## Escalations by trigger across every chunk, routed or not\n\ntrigger 2: 3, trigger 3: 1, trigger 10: 1.\n", escalated) self.assertIn("## Escalations by trigger across every chunk, routed or not\n\nNone.\n", text) 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(shutil.rmtree, self.root) def chunk(self, key, name, kept, worker, subagent=None): folder = self.root / key / name (folder / "session" / "s" / "subagents").mkdir(parents=True) (folder / "copy.outcomes.md").write_text(f"Task: t\n\n{kept}") (folder / "copy.jsonl").write_text("".join(json.dumps(entry) + "\n" for entry in worker)) if subagent: meta, entries = subagent (folder / "session" / "s" / "subagents" / "agent-a.jsonl").write_text("".join(json.dumps(entry) + "\n" for entry in entries)) (folder / "session" / "s" / "subagents" / "agent-a.meta.json").write_text(json.dumps(meta)) def test_counts_the_verdicts_across_every_projects_chunks(self): self.chunk("home/x", "c1", stamped("2026-10-14T10:00:00Z", outcomes.unfinished("w", "e", "j", "")) + stamped("2026-10-14T10:01:00Z", outcomes.stopped("w", "Ctrl-C")) + stamped("2026-10-14T10:02:00Z", outcomes.finished("w", "e", "j")), []) self.chunk("log", "c2", stamped("2026-10-14T10:00:00Z", outcomes.interrupted("q", "e", "j", "", "w")), []) self.assertEqual(archive.cycles(self.root), 2) self.assertEqual(archive.cycles(self.root / "missing"), 0) 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", "j")), [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", "j", "")), [message("m1", "2026-10-14T09:00:00Z")]) found = archive.measure_archive(self.root, "/h", "") self.assertEqual([chunk.tokens["project"] for chunk in found.chunks], [{"home/x": 222}]) self.assertEqual(found.chunks[0].tokens["subagent type"], {"worker": 111, "Explore": 111}) self.assertEqual(archive.measure_archive(self.root, "/h", "2026-10-14T10:00:00Z"), archive.Measured([], ())) def test_reads_each_cycles_route_from_its_own_outcomes_file(self): transcript = self.root / "t.jsonl" kept = self.root / "archive" first = message("m1", "2026-09-21T00:00:00Z") transcript.write_text(json.dumps(first) + "\n") with contextlib.redirect_stderr(io.StringIO()): self.assertIsNone(write.archive(kept / "log", str(transcript), "t", outcomes.unfinished(LOW_ROUTE, "e", "j", ""), 1790000000)) transcript.write_text(json.dumps(first) + "\n" + json.dumps(message("m2", "2099-01-01T00:00:00Z")) + "\n") self.assertIsNone(write.archive(kept / "log", str(transcript), "t", outcomes.finished(str(HIGH), "m", "j"), 4070908800)) (found,) = archive.measure_archive(kept, "/h", "").chunks self.assertEqual((found.start, found.unfinished), (LOW, 1)) self.assertEqual(found.tokens["rung"], {str(LOW): 111, str(HIGH): 111}) def test_skips_a_chunk_it_cannot_read_and_names_it(self): self.chunk("log", "c1", stamped("2026-10-14T10:00:00Z", outcomes.finished(LOW_ROUTE, "m", "j")), []) (self.root / "log" / "c1" / "copy.jsonl").unlink() self.chunk("other", "c2", stamped("2026-10-14T10:00:00Z", outcomes.finished(LOW_ROUTE, "m", "j")), [message("m1", "2026-10-14T09:00:00Z")]) self.chunk("broken", "c3", "", []) (self.root / "broken" / "c3" / "copy.outcomes.md").write_bytes(b"\xff") found = archive.measure_archive(self.root, "/h", "") self.assertEqual((len(found.chunks), found.skipped), (1, ("broken", "log/c1"))) self.assertIn("## Chunks skipped, unreadable\n\n- log/c1\n", render(totals([], ("log/c1",)), [], "2026-10-15T00:00:00Z", 20, "")) 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.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", "C."], "2026-10-15T00:30:00Z")) self.assertEqual(archive.raised(self.root), archive.Raised("2026-10-15T00:30:00Z", frozenset({"B."}))) def test_reads_no_measured_cycle_from_figures_that_name_none(self): (self.root / archive.FIGURES).write_text("# Routing figures\n") self.assertEqual(archive.last_measured(self.root), 0) (self.root / archive.FIGURES).unlink() (self.root / archive.FIGURES).mkdir() self.assertIsInstance(archive.last_measured(self.root), Failure) 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.raised(self.root), Failure) if __name__ == "__main__": unittest.main()