"""Token spend and routing outcomes of the chunks loop-claude finished, and the routing changes they call for: docs/decisions.md → `routing:`. A chunk that cannot be read is skipped and named in the figures.""" import collections import dataclasses import re import statistics import typing from claude_code.entries import assistant_parts, parts, tool_call, usage_count from git_command import commits from model_routing.route import ESCALATION_MARKER, route_from from model_routing.ladder import position, Rung from round_titles import round_counts from shell_command import simple_commands 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" ESCALATION = re.compile(rf"{ESCALATION_MARKER} ([0-9]+):") @dataclasses.dataclass(frozen=True) class Subagent: """kind is the agentType and launched_by the toolUseId of the launching Agent call, as the subagent's .meta.json names them, each empty where it names none; entries are its transcript's entries.""" kind: str launched_by: str entries: list[dict] @dataclasses.dataclass(frozen=True) class Chunk: """outcomes holds each outcomes file archived for the chunk, one per transcript copy, each opening with its task; worker is its finished transcript's entries.""" project: str outcomes: list[str] worker: list[dict] subagents: list[Subagent] @dataclasses.dataclass(frozen=True) class Reports: """How many subagents of a type reported, and the characters of their reports and of the tool results they read.""" subagents: int report: int searches: int def __add__(self, other: "Reports") -> "Reports": return Reports(self.subagents + other.subagents, self.report + other.report, self.searches + other.searches) @dataclasses.dataclass(frozen=True) class ChunkFigures: """tokens maps each of DIMENSIONS to its labels' tokens; start is the rung a routed chunk started on, None where no item routed it; escalated counts the worker's escalations by trigger.""" tokens: dict[str, collections.Counter[str]] start: Rung | None rounds_past_first: int unfinished: int delegated: collections.Counter[str] reports: dict[str, Reports] escalated: collections.Counter[int] @dataclasses.dataclass(frozen=True) class Figures: """escalated counts every chunk's escalations by trigger, routed or not; skipped names each chunk folder the archive could not read whole.""" chunks: int tokens: dict[str, collections.Counter[str]] routed: dict[Rung, list[ChunkFigures]] reports: dict[str, Reports] escalated: collections.Counter[int] skipped: tuple[str, ...] = () def measured(chunk: Chunk, home: str) -> ChunkFigures: cycles = sorted((cycle for kept in chunk.outcomes for cycle in workers(kept)), key=lambda cycle: cycle[0]) 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 = agent_calls(chunk.worker) reported = results(chunk.worker) delegated: collections.Counter[str] = collections.Counter() reports: dict[str, Reports] = {} for subagent in chunk.subagents: 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(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=tokens, start=start.rung if start and start.item else None, rounds_past_first=rounds_past_first(chunk.worker, home), unfinished=sum(len(UNFINISHED_AT.findall(kept)) for kept in chunk.outcomes), delegated=delegated, reports=reports, escalated=escalations(launches), ) def escalations(launches: dict[str, tuple[str, dict]]) -> collections.Counter[int]: """How many of the worker's Agent calls open with each escalation trigger's number.""" opened = (ESCALATION.match(str(arguments.get("prompt") or "")) for _, arguments in launches.values()) return collections.Counter(int(found[1]) for found in opened if found) 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 tokens["rung"][rung] += spent # Split whole, the first tools taking the remainder, so the tool table adds up to the others. for place, tool in enumerate(tools): tokens["tool"][tool] += spent // len(tools) + (place < spent % len(tools)) def rung_at(cycles: list[tuple[str, str]], timestamp: str) -> Rung | str: """The rung of the cycle running at timestamp: the worker named by the first outcome stamped at or after it, or else by the last outcome. A worker line route_from cannot read is returned as its text, and "unrouted" where no outcome names a worker.""" second = timestamp[:19] + "Z" found = next((rung for stamp, rung in cycles if stamp >= second), cycles[-1][1] if cycles else "unrouted") route = route_from(found) return route.rung if route else found def subagent_rung(entries: list[dict], arguments: dict, worker: Rung | str) -> Rung: """The model the subagent ran, at the effort its Agent call set, or else at the worker's.""" model = next((message["model"] for entry in entries if entry.get("type") == "assistant" and isinstance(message := entry.get("message"), dict) and isinstance(message.get("model"), str)), str(arguments.get("model") or "unknown")) effort = arguments.get("effort") or (worker.effort if isinstance(worker, Rung) else "") return Rung(model, str(effort)) def spend(entries: list[dict]) -> list[tuple[str, list[str], int]]: """Each message's timestamp, the tools whose results it took in, and its input, cache-written and output tokens, counted once per message, as reading_cost's tokens_in dedupes them, though tokens_in leaves output tokens out.""" messages: dict[str, tuple[str, object, list[str]]] = {} for entry in entries: if entry.get("type") != "assistant" or not isinstance(message := entry.get("message"), dict): continue key = str(message.get("id") or entry.get("uuid")) kept = messages.setdefault(key, (str(entry.get("timestamp", "")), message.get("usage"), [])) kept[2].extend(name for part in assistant_parts(entry) if (found := tool_call(part)) and isinstance(name := found[0], str)) spent = [] before = [PROMPT] for at, usage, called in messages.values(): 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 def results(entries: list[dict]) -> dict[str, str]: """Each tool result's text by the id of the call it answers.""" found = {} for entry in entries: for part in parts(entry): if isinstance(part, dict) and part.get("type") == "tool_result": 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( commit.messages[0].split("\n", 1)[0] for entry in worker for part in assistant_parts(entry) if (found := tool_call(part)) and found[0] == "Bash" and isinstance(found[1], dict) for commit in commits(simple_commands(str(found[1].get("command", "")), str(entry.get("cwd") or "/"), home), home) if commit.messages ) return sum(max(0, rounds - 1) for rounds in round_counts(list(titles)).values()) def due(cycle: int, last_measured: int) -> bool: """Whether CYCLES_PER_CHECK cycles have closed since the figures were last measured. Counting from the last measurement still measures when another loop's cycles carried the count past a multiple of CYCLES_PER_CHECK.""" return cycle >= last_measured + CYCLES_PER_CHECK def totals(chunks: list[ChunkFigures], skipped: tuple[str, ...] = ()) -> 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]] = {} reports: dict[str, Reports] = {} for chunk in chunks: if chunk.start: routed.setdefault(chunk.start, []).append(chunk) for kind, found in chunk.reports.items(): reports[kind] = reports.get(kind, Reports(0, 0, 0)) + found return Figures(len(chunks), tokens, routed, reports, summed(chunks, lambda chunk: chunk.escalated), skipped) def calls(figures: Figures) -> list[str]: """Each routing change the figures call for, worded alike whatever the numbers, so a call already raised is known again.""" compared = sorted((rung for rung, chunks in figures.routed.items() if len(chunks) >= MEASURED_AT_LEAST and position(rung) >= 0), key=position) found = [] for lower, upper in zip(compared, compared[1:]): 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: reports and searches are both text the worker would read, so their sums compare their shares of its context. 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 def mean(chunks: list[ChunkFigures], of: typing.Callable[[ChunkFigures], int]) -> float: return statistics.mean(map(of, chunks)) 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'}{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; a message that took in no tool result counts towards `prompt`.", "## 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()]))], "## Routed chunks by the rung they started on", table(("Rung", "Chunks", "Review rounds past each pass's first, mean", "Unfinished verdicts, mean", "Subagent rungs", "Escalations by trigger"), [ (str(rung), str(len(chunks)), f"{mean(chunks, lambda chunk: chunk.rounds_past_first):.1f}", f"{mean(chunks, lambda chunk: chunk.unfinished):.1f}", subagent_rungs(chunks), triggers(summed(chunks, lambda chunk: chunk.escalated))) for rung, chunks in sorted(figures.routed.items(), key=lambda item: position(item[0])) ]), "## Escalations by trigger across every chunk, routed or not", f"{triggers(figures.escalated) or 'None'}.", "## Subagent reports against the searches they ran, in characters", table(("Subagent type", "Subagents", "Reports", "Searches"), [(kind, str(found.subagents), str(found.report), str(found.searches)) for kind, found in sorted(figures.reports.items())]), *(["## Chunks skipped, unreadable", "".join(f"- {folder}\n" for folder in figures.skipped).rstrip("\n")] if figures.skipped else []), ] return "\n\n".join(sections) + "\n" def summed(chunks: list[ChunkFigures], of: typing.Callable[[ChunkFigures], collections.Counter]) -> collections.Counter: return sum(map(of, chunks), collections.Counter()) def subagent_rungs(chunks: list[ChunkFigures]) -> str: """The rungs the chunks' subagents ran on, most used first, as `claude-opus-5-5 at high effort 2, …`.""" return ", ".join(f"{label} {times}" for label, times in summed(chunks, lambda chunk: chunk.delegated).most_common()) def triggers(escalated: collections.Counter[int]) -> str: """Escalations as `trigger 2: 3, trigger 3: 1`.""" return ", ".join(f"trigger {trigger}: {times}" for trigger, times in sorted(escalated.items())) def table(header: tuple[str, ...], rows: list[tuple[str, ...]]) -> str: if not rows: return "None." return "\n".join(f"| {' | '.join(row)} |" for row in [header, tuple("---" for _ in header), *rows])