diff --git a/CHANGELOG.md b/CHANGELOG.md index ca8cee45..a1688c22 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## Unreleased +- `routing-figures.md` now reports dollars by project, subagent type, rung and tool, in place of tokens. Cache reads are included; the tokens left them out, though they were about a quarter of the cost. The dollars are what each worker transcript's last `cost-state` entry records for each model, split across the messages of the worker and its subagents in proportion to their cost at list prices. The judge's runs are not counted, since the archive doesn't hold them. - larv-review's principles pass now launches one auditor per round, which checks the README's goals, code health and every principles file that applies, so it reads the project once per round. It used to launch one auditor for the goals with code health and one for each principles file, each reading the whole project. Its report is `principles-round-.md`, like every other pass's. - A session running larv-review now enters the chunk's worktree with `EnterWorktree` before the first review pass, so `/security-review` and the full scan read the branch's diff. Run from the checkout root, they used to find it empty. - `loop-claude` now stops with exit 2 when the judge rules one chunk unfinished 6 cycles running, so a worker and a judge that disagree can no longer cycle unattended without end. Rerunning resumes the chunk and gives it 6 more cycles. diff --git a/bin/routing_figures/measure.py b/bin/routing_figures/measure.py index 6dced9ac..67b24ea6 100644 --- a/bin/routing_figures/measure.py +++ b/bin/routing_figures/measure.py @@ -1,13 +1,14 @@ -"""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.""" +"""Dollar 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 claude_code.entries import assistant_parts, parts, tool_call from git_command import commits from model_routing.route import ESCALATION_MARKER, route_from +from routing_figures.prices import listed from model_routing.ladder import position, Rung from round_titles import round_counts from shell_command import simple_commands @@ -18,6 +19,8 @@ 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") +# Each of DIMENSIONS to its labels' dollars. +Dollars = dict[str, collections.defaultdict[str, float]] # 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]+):") @@ -53,32 +56,50 @@ class Reports: @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]] + """dollars maps each of DIMENSIONS to its labels' dollars; start is the rung a routed chunk started on, None where no item routed it; escalated counts the worker's escalations by trigger; unattributed is the recorded cost of a model with no priced message in the chunk; lacking counts the Agent calls, the worker's and the subagents', that have no subagent transcript in the archive.""" + dollars: Dollars start: Rung | None rounds_past_first: int unfinished: int delegated: collections.Counter[str] reports: dict[str, Reports] escalated: collections.Counter[int] + unattributed: float + lacking: int = 0 @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]] + dollars: Dollars routed: dict[Rung, list[ChunkFigures]] reports: dict[str, Reports] escalated: collections.Counter[int] skipped: tuple[str, ...] = () + unattributed: float = 0.0 + lacking: int = 0 + + +@dataclasses.dataclass(frozen=True) +class Message: + """An assistant message, counted once: when it was written, the tools whose results it took in, the model that wrote it and what its usage costs at list prices.""" + at: str + tools: list[str] + model: str + list_price: float + + +class Spent(typing.NamedTuple): + """A message with the subagent type that wrote it, or `worker`, and the rung it ran on.""" + kind: str + rung: str + message: Message 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) + spent = [Spent("worker", str(rung_at(cycles, message.at)), message) for message in messages(chunk.worker)] launches = agent_calls(chunk.worker) reported = results(chunk.worker) delegated: collections.Counter[str] = collections.Counter() @@ -89,17 +110,19 @@ def measured(chunk: Chunk, home: str) -> ChunkFigures: 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) + spent += [Spent(kind, rung, message) for message in messages(subagent.entries)] + dollars, unattributed = costed(spent, chunk.project, recorded_costs(chunk.worker)) start = route_from(cycles[0][1]) if cycles else None return ChunkFigures( - tokens=tokens, + dollars=dollars, 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), + unattributed=unattributed, + lacking=max(0, len(launches) + sum(len(agent_calls(subagent.entries)) for subagent in chunk.subagents) - len(chunk.subagents)), ) @@ -120,13 +143,30 @@ def agent_calls(worker: list[dict]) -> dict[str, tuple[str, dict]]: 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 index, tool in enumerate(tools): - tokens["tool"][tool] += spent // len(tools) + (index < spent % len(tools)) +# {"type": "cost-state", "totalCostUSD": 40.1, "modelUsage": {"claude-opus-5-5": {"costUSD": 40.1, "outputTokens": 334504, ...}}, ...} +def recorded_costs(worker: list[dict]) -> dict[str, float]: + """The cost the worker transcript's last cost-state entry records for each model. Claude Code counts every call of the session in it, the subagents' and the compactions' too.""" + for entry in reversed(worker): + if entry.get("type") == "cost-state" and isinstance(by_model := entry.get("modelUsage"), dict): + return {model: cost for model, usage in by_model.items() if isinstance(usage, dict) and isinstance(cost := usage.get("costUSD"), (int, float))} + return {} + + +def costed(spent: list[Spent], project: str, recorded: dict[str, float]) -> tuple[Dollars, float]: + """Each message's dollars by DIMENSIONS, and the recorded cost left over, that of a recorded model with no priced message. A model's recorded cost is split across its messages in proportion to their list prices, so the calls no message records, such as compactions, are counted. A subagent transcript the archive lacks puts its cost on the archived messages of the model that ran it, in the same proportion. A model the record omits keeps its list prices.""" + listed_by_model: collections.defaultdict[str, float] = collections.defaultdict(float) + for _, _, message in spent: + listed_by_model[message.model] += message.list_price + scale = {model: recorded[model] / total for model, total in listed_by_model.items() if total and model in recorded} + dollars: Dollars = {dimension: collections.defaultdict(float) for dimension in DIMENSIONS} + for kind, rung, message in spent: + cost = message.list_price * scale.get(message.model, 1.0) + dollars["project"][project] += cost + dollars["subagent type"][kind] += cost + dollars["rung"][rung] += cost + for tool in message.tools: + dollars["tool"][tool] += cost / len(message.tools) + return dollars, sum(cost for model, cost in recorded.items() if not listed_by_model[model]) def rung_at(cycles: list[tuple[str, str]], timestamp: str) -> Rung | str: @@ -144,22 +184,22 @@ def subagent_rung(entries: list[dict], arguments: dict, worker: Rung | str) -> R 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]]] = {} +def messages(entries: list[dict]) -> list[Message]: + """The assistant messages, counted once each, each with the tools whose results it took in, or `prompt` where it took none in.""" + # Claude Code writes one entry per content block of a message, each with the message's usage. The usage is the same in every entry (none of 1,681 multi-entry messages in the archive of 2026-10-28 differed), so the first is kept, where reading_cost's tokens_in keeps the last. + kept: dict[str, tuple[str, dict, 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 = [] + found = kept.setdefault(str(message.get("id") or entry.get("uuid")), (str(entry.get("timestamp", "")), message, [])) + found[2].extend(name for part in assistant_parts(entry) if (call := tool_call(part)) and isinstance(name := call[0], str)) + counted = [] 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)) + for at, message, called in kept.values(): + model = str(message.get("model") or "") + counted.append(Message(at, before, model, listed(model, message.get("usage")))) before = called or [PROMPT] - return spent + return counted def results(entries: list[dict]) -> dict[str, str]: @@ -196,7 +236,11 @@ def due(cycle: int, last_measured: int) -> bool: 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} + dollars: Dollars = {dimension: collections.defaultdict(float) for dimension in DIMENSIONS} + for chunk in chunks: + for dimension in DIMENSIONS: + for label, amount in chunk.dollars.get(dimension, {}).items(): + dollars[dimension][label] += amount routed: dict[Rung, list[ChunkFigures]] = {} reports: dict[str, Reports] = {} for chunk in chunks: @@ -204,7 +248,7 @@ def totals(chunks: list[ChunkFigures], skipped: tuple[str, ...] = ()) -> Figures 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) + return Figures(len(chunks), dollars, routed, reports, summed(chunks, lambda chunk: chunk.escalated), skipped, sum(chunk.unattributed for chunk in chunks), sum(chunk.lacking for chunk in chunks)) def calls(figures: Figures) -> list[str]: @@ -224,14 +268,24 @@ def mean(chunks: list[ChunkFigures], of: typing.Callable[[ChunkFigures], int]) - return statistics.mean(map(of, chunks)) +def basis(figures: Figures) -> str: + """What the dollars are, what they leave out, and where the archive falls short of the recorded cost.""" + text = "Dollars are what each worker transcript's last `cost-state` entry records for each model, cache reads included. A model's dollars are split across its messages in the archive in proportion to their cost at list prices, so the cost of a compaction, or of a subagent transcript the archive lacks, lands on the archived messages of the model that ran it. A chunk without the entry, or a model it leaves out, keeps the list prices, which may be a little off. A message's dollars count towards the tools whose results it took in, split evenly; a message that took in no tool result counts towards `prompt`. The judge's runs are not archived, so their cost is not counted." + if figures.unattributed: + text += f" {money(figures.unattributed)} of the recorded cost is left out, since it belongs to a model with no list price or with no priced message in the archive." + if figures.lacking: + text += f" The archive holds no subagent transcript for {figures.lacking} of the chunks' Agent calls." + return text + + 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`.", + 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 ''}. {basis(figures)}", "## 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()]))], + *[part for dimension in DIMENSIONS for part in (f"## Dollars by {dimension}", table((dimension.capitalize(), "Dollars"), [(label, money(dollars)) for label, dollars in sorted(figures.dollars[dimension].items(), key=lambda spent: -spent[1])]))], "## 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))) @@ -260,6 +314,10 @@ def triggers(escalated: collections.Counter[int]) -> str: return ", ".join(f"trigger {trigger}: {times}" for trigger, times in sorted(escalated.items())) +def money(dollars: float) -> str: + return f"${dollars:,.2f}" + + def table(header: tuple[str, ...], rows: list[tuple[str, ...]]) -> str: if not rows: return "None." diff --git a/bin/routing_figures/prices.py b/bin/routing_figures/prices.py new file mode 100644 index 00000000..0540199e --- /dev/null +++ b/bin/routing_figures/prices.py @@ -0,0 +1,44 @@ +"""What a message costs at list prices: the weights that split a chunk's recorded cost between its messages.""" +import dataclasses + +from claude_code.entries import usage_count + + +@dataclasses.dataclass(frozen=True) +class Price: + """Dollars per million tokens. A cache write costs 1.25 times the input for a five-minute cache and 2 times for an hour's, as Opus 5.5's $5 and $8 show.""" + input: float + read: float + output: float + + @property + def write_5m(self) -> float: + return self.input * 1.25 + + @property + def write_1h(self) -> float: + return self.input * 2 + + +# Anthropic's list prices as the claude-api skill lists them (cached 2026-10-06), with Opus 5.5's cache prices from `docs/decisions.md` → `loop-claude: the worker's claude compacts…`. Haiku 5.5's cache read is assumed at a tenth of its input, and its dearer prompts above 200k tokens are left out. Where a chunk records its cost, only the proportions between one model's messages matter, so these may be a little off. +PRICES = { + "claude-fable-5-1": Price(10, 0.25, 50), + "claude-haiku-5-5": Price(0.1, 0.01, 0.5), + "claude-opus-5-5": Price(4, 0.2, 20), + "claude-sonnet-5-5": Price(2, 0.2, 10), +} + + +# {"input_tokens": 2, "cache_creation": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 25919}, "cache_read_input_tokens": 10365, "output_tokens": 193, ...} +def listed(model: str, usage: object) -> float: + """The cost of one message's usage at the model's list price; 0 for a model without one.""" + price = PRICES.get(model) + if not price or not isinstance(usage, dict): + return 0.0 + written = usage.get("cache_creation") + # A write without the split by lifetime counts as a five-minute one. + five, hour = (usage_count(written, "ephemeral_5m_input_tokens"), usage_count(written, "ephemeral_1h_input_tokens")) if isinstance(written, dict) else (usage_count(usage, "cache_creation_input_tokens"), 0) + return ( + usage_count(usage, "input_tokens") * price.input + five * price.write_5m + hour * price.write_1h + + usage_count(usage, "cache_read_input_tokens") * price.read + usage_count(usage, "output_tokens") * price.output + ) / 1_000_000 diff --git a/bin/routing_figures/test_routing_figures.py b/bin/routing_figures/test_routing_figures.py index afade8d4..71b4786b 100644 --- a/bin/routing_figures/test_routing_figures.py +++ b/bin/routing_figures/test_routing_figures.py @@ -1,5 +1,6 @@ import collections import contextlib +import dataclasses import io import json import pathlib @@ -22,8 +23,13 @@ HIGH = Rung("claude-opus-5-5", "high") LOW_ROUTE = Route(LOW, 7, 3, 4).worker_line() -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 message(id_, at, *parts, model="claude-opus-5-5", usage=None): + """Costs $2 on Opus 5.5, whose output is $20 per million tokens, and $1 on Sonnet 5.5, whose output is $10.""" + return {"type": "assistant", "timestamp": at, "cwd": "/c", "message": {"id": id_, "model": model, "content": list(parts), "usage": usage or {"output_tokens": 100_000}}} + + +def cost_state(**costs): + return {"type": "cost-state", "totalCostUSD": sum(costs.values()), "modelUsage": {model.replace("_", "-"): {"costUSD": cost} for model, cost in costs.items()}} def call(name, id_="t1", **arguments): @@ -39,11 +45,11 @@ def stamped(at, outcome): 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 {})) + return ChunkFigures({}, start, rounds, unfinished, collections.Counter(), reports or {}, collections.Counter(escalated or {}), 0.0) class Measured(unittest.TestCase): - def test_counts_each_messages_tokens_once_by_project_type_rung_and_the_tool_it_followed(self): + def test_prices_each_message_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")), @@ -52,10 +58,10 @@ class Measured(unittest.TestCase): ] kept = stamped("2026-10-14T10:30:00Z", outcomes.unfinished(LOW_ROUTE, "e", "j", "")) + stamped("2026-10-14T10:30:00Z", outcomes.stepped_up(Route(HIGH).worker_line())) + stamped("2026-10-14T12:00:00Z", outcomes.finished(Route(HIGH).worker_line(), "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.dollars["project"], {"log": 6.0}) + self.assertEqual(found.dollars["subagent type"], {"worker": 6.0}) + self.assertEqual(found.dollars["rung"], {str(LOW): 4.0, str(HIGH): 2.0}) + self.assertEqual(found.dollars["tool"], {"prompt": 4.0, "Read": 2.0}) 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): @@ -70,7 +76,7 @@ class Measured(unittest.TestCase): ] 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.dollars["subagent type"], {"worker": 2.0, "Explore": 3.0}) self.assertEqual(found.reports, {"Explore": Reports(2, 35, 20)}) def test_counts_the_workers_escalations_by_the_trigger_each_subagents_prompt_opens_with(self): @@ -90,14 +96,13 @@ class Measured(unittest.TestCase): 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}) + self.assertEqual(found.dollars["rung"], {str(LOW): 2.0}) def test_starts_no_route_for_a_chunk_no_item_routed(self): kept = stamped("2026-10-14T10:00:00Z", outcomes.finished(Route(LOW).worker_line(), "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}) - + self.assertEqual(found.dollars["rung"], {str(LOW): 2.0}) 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(Route(HIGH).worker_line(), "m", "j")) @@ -109,23 +114,72 @@ class Measured(unittest.TestCase): 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}) + self.assertEqual(found.dollars["rung"], {str(LOW): 2.0, str(HIGH): 6.0}) 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): + def test_counts_a_message_without_usage_or_a_priced_model_as_nothing_and_splits_a_cost_evenly_across_tools(self): worker = [ - {"type": "assistant", "uuid": "u1", "message": {"content": [call("Read"), call("Grep")], "usage": {"input_tokens": 3, "output_tokens": "many"}}}, + {"type": "assistant", "uuid": "u1", "message": {"model": "claude-opus-5-5", "content": [call("Read"), call("Grep")], "usage": {"input_tokens": 1_000_000, "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": []}}, + {"type": "assistant", "uuid": "u2", "message": {"model": "claude-opus-5-5", "content": [], "usage": {"input_tokens": 2_000_000}}}, + {"type": "assistant", "uuid": "u3", "message": {"model": "claude-opus-5-5", "content": []}}, + {"type": "assistant", "uuid": "u4", "message": {"model": "claude-unheard-of", "content": [], "usage": {"input_tokens": 9_000_000}}}, ] found = measured(Chunk("log", [], worker, []), "/h") - self.assertEqual(found.tokens["tool"], {"prompt": 3, "Read": 3, "Grep": 2}) - self.assertEqual(found.tokens["project"], {"log": 8}) + self.assertEqual(found.dollars["tool"], {"prompt": 4.0, "Read": 4.0, "Grep": 4.0}) + self.assertEqual(found.dollars["project"], {"log": 12.0}) + + def test_prices_input_cache_writes_by_their_lifetime_cache_reads_and_output_at_the_models_list_prices(self): + usage = {"input_tokens": 1_000_000, "cache_creation_input_tokens": 2_000_000, "cache_creation": {"ephemeral_5m_input_tokens": 1_000_000, "ephemeral_1h_input_tokens": 1_000_000}, "cache_read_input_tokens": 1_000_000, "output_tokens": 1_000_000} + opus = measured(Chunk("log", [], [message("m1", "2026-10-14T10:00:00Z", usage=usage)], []), "/h") + self.assertAlmostEqual(opus.dollars["project"]["log"], 4 + 5 + 8 + 0.2 + 20) + sonnet = measured(Chunk("log", [], [message("m1", "2026-10-14T10:00:00Z", model="claude-sonnet-5-5", usage=usage)], []), "/h") + self.assertAlmostEqual(sonnet.dollars["project"]["log"], 2 + 2.5 + 4 + 0.2 + 10) + + def test_counts_a_cache_write_without_a_lifetime_as_a_five_minute_one(self): + usage = {"cache_creation_input_tokens": 1_000_000} + found = measured(Chunk("log", [], [message("m1", "2026-10-14T10:00:00Z", usage=usage)], []), "/h") + self.assertAlmostEqual(found.dollars["project"]["log"], 5) + + def test_splits_the_cost_a_chunks_last_cost_state_records_for_each_model_across_its_messages_by_list_price(self): + worker = [ + message("m1", "2026-10-14T10:00:00Z", call("Agent", "a1", subagent_type="Explore")), + message("m2", "2026-10-14T10:01:00Z"), + cost_state(claude_opus_5_5=1.0), + cost_state(claude_opus_5_5=9.0, claude_haiku_5_5=0.5), + ] + subagents = [Subagent("Explore", "a1", [message("s1", "2026-10-14T10:00:01Z")])] + found = measured(Chunk("log", [], worker, subagents), "/h") + self.assertEqual(found.dollars["subagent type"], {"worker": 6.0, "Explore": 3.0}) + self.assertEqual(found.dollars["project"], {"log": 9.0}) + self.assertEqual(found.unattributed, 0.5) + + def test_counts_the_subagents_the_worker_launched_that_have_no_transcript(self): + worker = [message("m1", "2026-10-14T10:00:00Z", call("Agent", "a1", subagent_type="Explore"), call("Agent", "a2", subagent_type="Explore"), call("Read", "r1", file_path="/c/a"))] + found = measured(Chunk("log", [], worker, [Subagent("Explore", "a1", [message("s1", "2026-10-14T10:00:01Z")])]), "/h") + self.assertEqual(found.lacking, 1) + unnamed = measured(Chunk("log", [], worker, [Subagent("", "", [message("s1", "2026-10-14T10:00:01Z")]), Subagent("", "", [message("s2", "2026-10-14T10:00:02Z")])]), "/h") + self.assertEqual(unnamed.lacking, 0) + nested = [message("s1", "2026-10-14T10:00:01Z", call("Agent", "n1", subagent_type="Explore"))] + launched = measured(Chunk("log", [], worker, [Subagent("Explore", "a1", nested), Subagent("Explore", "a2", [message("s2", "2026-10-14T10:00:02Z")]), Subagent("Explore", "n1", [message("s3", "2026-10-14T10:00:03Z")])]), "/h") + self.assertEqual(launched.lacking, 0) + self.assertEqual(measured(Chunk("log", [], worker, [Subagent("Explore", "a1", nested), Subagent("Explore", "a2", [])]), "/h").lacking, 1) + + def test_charges_a_message_without_a_timestamp_to_the_rung_of_the_last_outcome(self): + undated = message("m1", "") + del undated["timestamp"] + kept = stamped("2026-10-14T10:30:00Z", outcomes.unfinished(LOW_ROUTE, "e", "j", "")) + stamped("2026-10-14T12:00:00Z", outcomes.finished(Route(HIGH).worker_line(), "merged", "j")) + self.assertEqual(measured(Chunk("log", [kept], [undated], []), "/h").dollars["rung"], {str(HIGH): 2.0}) + + def test_keeps_list_prices_for_a_model_the_cost_state_does_not_name(self): + worker = [message("m1", "2026-10-14T10:00:00Z"), message("m2", "2026-10-14T10:01:00Z", model="claude-sonnet-5-5"), cost_state(claude_opus_5_5=3.0)] + found = measured(Chunk("log", [], worker, []), "/h") + self.assertEqual(found.dollars["project"], {"log": 4.0}) + self.assertEqual(found.unattributed, 0.0) class Calls(unittest.TestCase): @@ -154,13 +208,20 @@ class Calls(unittest.TestCase): 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()) + chunk = ChunkFigures({"project": collections.Counter({"a": 2.5, "b": 1234.5})}, LOW, 1, 0, collections.Counter({str(HIGH): 2}), {"Explore": Reports(2, 3, 4)}, collections.Counter(), 0.0) 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("## Dollars by project", text) + self.assertIn("| b | $1,234.50 |\n| a | $2.50 |", text) + self.assertIn("cache reads included", text) + self.assertIn("The judge's runs are not archived, so their cost is not counted.", text) + self.assertNotIn("left out", text) + self.assertNotIn("no transcript", text) + self.assertIn("The archive holds no subagent transcript for 2 of the chunks' Agent calls.", render(totals([dataclasses.replace(chunk, lacking=1)] * 2), [], "2026-10-15T00:00:00Z", 40, "")) + self.assertIn("$0.50 of the recorded cost is left out", render(totals([ChunkFigures({}, LOW, 0, 0, collections.Counter(), {}, collections.Counter(), 0.5), chunk]), [], "2026-10-15T00:00:00Z", 40, "")) 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()) + two = ChunkFigures({}, HIGH, 0, 1, collections.Counter({str(HIGH): 2, str(LOW): 1}), {}, collections.Counter(), 0.0) 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, "") @@ -200,8 +261,8 @@ class Archive(unittest.TestCase): 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([chunk.dollars["project"] for chunk in found.chunks], [{"home/x": 4.0}]) + self.assertEqual(found.chunks[0].dollars["subagent type"], {"worker": 2.0, "Explore": 2.0}) 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): @@ -215,7 +276,7 @@ class Archive(unittest.TestCase): self.assertIsNone(write.archive(kept / "log", str(transcript), "t", outcomes.finished(Route(HIGH).worker_line(), "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}) + self.assertEqual(found.dollars["rung"], {str(LOW): 2.0, str(HIGH): 2.0}) 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")), []) diff --git a/docs/reading-cost.md b/docs/reading-cost.md index 9c8bad9d..ff8eacd7 100644 --- a/docs/reading-cost.md +++ b/docs/reading-cost.md @@ -879,3 +879,7 @@ Read most (opens and searches): ## Reading cost, chunk 6164ac372ce5, finished 2026-10-28T08:48:34Z 94183 new input tokens before the first commit. + +## Reading cost, chunk 22d616a7a912, finished 2026-10-28T10:14:46Z + +116420 new input tokens before the first commit. diff --git a/todo.md b/todo.md index 81418de0..76dbf4e3 100644 --- a/todo.md +++ b/todo.md @@ -13,7 +13,6 @@ | ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score | |---|---|---|---|---|---|---|---|---|---|---|---| | 245 | 0.4.0 | | owner | **Run the test suite once, on the latest stable Python alone, with its test files spread across the machine's CPUs, so a full run takes under a minute instead of about 3.3.** | 3 | 1 | 2 | 4 | 4 | 1.5 by 5 | 3.2 | -| 234 | 0.4.0 | | | **Report the routing figures in dollars, cache reads included, from the cost each archived run records.** | 2 | 2 | 2 | 4 | 3 | 1.4 by 3 | 3.0 | | 239 | 0.4.0 | 245 | owner | **Block a Read, `cat`, `sed` or `head` of a file range already in the session's context, with a note saying so, and let it through once a compaction dropped the range or the file changed.** | 3 | 2 | 3 | 6 | 4 | 1.4 by 3 | 2.0 | | 244 | 0.4.0 | 245 | owner | **Open every line loop-claude prints to its terminal with the machine's local time, as in `2026-10-28 11:46:01`.** | 2 | 2 | 1 | 3 | 3 | 1.5 by 2 | 1.9 | | 243 | 0.4.0 | 245 | owner | **Show every loop-claude on the machine that waits for the human in one terminal app, and let the human answer each one there, `/talk` included.** | 4 | 2 | 3 | 7 | 6 | 1.5 by 4 | 0.9 | @@ -90,10 +89,6 @@ lilleman's call, 2026-10-28: support only the latest stable Python, today 3.14, - In `run_on_terminal` in `test_black_box.py`, check for the prompt every 50 ms instead of every second. - Then, if the run is still over a minute, have the black-box tests copy one prepared git repo per class instead of building one per test. -### 234. Report the routing figures in dollars, cache reads included, from the cost each archived run records. - -The routing figures count input, cache-written and output tokens, and leave out cache reads, which were 28% of the cost since 2026-10-21, $340 of $1,215 at list prices. So their tables rank the principles auditor above the worker, while in dollars the worker cost 1.4 times as much, $375 against $274. Each archived worker transcript ends with a `cost-state` entry holding `totalCostUSD` and each model's cost, and each message's usage attributes the cost to a subagent type. The judge's runs record no cost in the archive: count them too, or say why not. The change touches `bin/routing_figures/measure.py`, which the comprehension seats found hard (item 139): make the places it touches easier to read. - ### 239. Block a Read, `cat`, `sed` or `head` of a file range already in the session's context, with a note saying so, and let it through once a compaction dropped the range or the file changed. lilleman's call, 2026-10-27, filed from PR #376's measurement of loop-claude's archive since 2026-10-21: a read of a file the agent read earlier in the thread, more than three messages before and without editing it in between, is 13% of the worker's reading, about $6 of the $45 its reads cost, and 1 to 2% of a reviewer's. How many of those repeat a range exactly is unmeasured, so the figures are a ceiling. A hook on `Read` and on the Bash reads `cat`, `sed` and `head` blocks such a read with a short note that the content is already in context and unchanged. It lets the read through after a compaction, when the content has left the context, or when the file changed since the read. A PreToolUse hook gets a `transcript_path`, which holds the earlier reads and each `compact_boundary`, so it may need no state of its own; check whether a hook inside a subagent gets the subagent's own transcript. @@ -121,7 +116,7 @@ Found by review of PR #370. Today `uv run mutmut run`, `poetry run mutmut run`, ### 235. Compare the first 20 chunks whose worker ran under the 200k compaction window with the 20 before them, on review rounds past each pass's first, unfinished verdicts, 🔴, 🟡 and misread findings, dollars and hours per chunk, and file an item where any rose. -`docs/decisions.md` → `loop-claude: the worker's claude compacts its context before it fills a 200k window…` expects a saving of about 6% of all spend with no rise in the other figures. Measure from loop-claude's archive as that decision did: rounds past each pass's first and the 🔴, 🟡 and misread counts from the round commit titles, unfinished verdicts from the outcomes files, hours from the worker's first message to its last, and dollars at list prices, cache reads included, from the chunk's `cost-state` entry, which counts the compaction calls that no message's usage records; item 234 puts such dollars into the routing figures. A chunk ran under the window when its first worker started after that decision merged. +`docs/decisions.md` → `loop-claude: the worker's claude compacts its context before it fills a 200k window…` expects a saving of about 6% of all spend with no rise in the other figures. Measure from loop-claude's archive as that decision did: rounds past each pass's first and the 🔴, 🟡 and misread counts from the round commit titles, unfinished verdicts from the outcomes files, hours from the worker's first message to its last, and dollars at list prices, cache reads included, from the chunk's `cost-state` entry, which counts the compaction calls that no message's usage records; the routing figures now put such dollars in. A chunk ran under the window when its first worker started after that decision merged. ### 167. Refuse a `/security-review` or `/claude-security` Skill call below the project's rung, as rule-hook refuses such an Agent call.