diff --git a/CHANGELOG.md b/CHANGELOG.md index ca8cee45..4521d761 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, cache reads included, where it counted input, cache-written and output tokens and left cache reads out, a quarter of the cost. The dollars are what each worker transcript's last `cost-state` entry records for each model, split across its messages in proportion to their cost at list prices. The judge's runs are not counted, since the archive doesn't hold them. The figures now rank the worker above the principles auditor. - 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..59fe340f 100644 --- a/bin/routing_figures/measure.py +++ b/bin/routing_figures/measure.py @@ -1,15 +1,16 @@ -"""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 model_routing.ladder import position, Rung from round_titles import round_counts +from routing_figures.prices import listed from shell_command import simple_commands from transcript_archive.outcomes import UNFINISHED_AT, workers @@ -53,32 +54,41 @@ 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 that no message of the chunk takes.""" + dollars: 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] + unattributed: float @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: dict[str, collections.Counter[str]] routed: dict[Rung, list[ChunkFigures]] reports: dict[str, Reports] escalated: collections.Counter[int] skipped: tuple[str, ...] = () + unattributed: float = 0.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 + listed: float 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 = [("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 +99,18 @@ 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 += [(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, ) @@ -120,13 +131,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]: + """What the worker transcript's last cost-state entry records each model cost. 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[tuple[str, str, Message]], project: str, recorded: dict[str, float]) -> tuple[dict[str, collections.Counter[str]], float]: + """Each message's dollars by DIMENSIONS, and the recorded cost that no message takes. 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 model the record omits keeps its list prices; a recorded model with no priced message is the cost no message takes.""" + listed_by_model: collections.Counter[str] = collections.Counter() + for _, _, message in spent: + listed_by_model[message.model] += message.listed + scale = {model: recorded[model] / total for model, total in listed_by_model.items() if total and model in recorded} + dollars: dict[str, collections.Counter[str]] = {dimension: collections.Counter() for dimension in DIMENSIONS} + for kind, rung, message in spent: + cost = message.listed * 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 +172,21 @@ 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 as reading_cost's tokens_in dedupes them, each with the tools whose results it took in, or `prompt` where it took none in.""" + 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 +223,7 @@ 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 = {dimension: summed(chunks, lambda chunk: chunk.dollars.get(dimension, collections.Counter())) for dimension in DIMENSIONS} routed: dict[Rung, list[ChunkFigures]] = {} reports: dict[str, Reports] = {} for chunk in chunks: @@ -204,7 +231,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)) def calls(figures: Figures) -> list[str]: @@ -228,10 +255,10 @@ def render(figures: Figures, found: list[str], at: str, cycle: int, since: 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 ''}. Dollars are what each worker transcript's last `cost-state` entry records for each model, cache reads included, split across the messages in the archive in proportion to their cost at list prices; a chunk without the entry keeps the list prices. 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.{f' {money(figures.unattributed)} of the recorded cost is left out, since it belongs to a model with no list price or with no message in the archive.' if figures.unattributed else ''}", "## 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 figures.dollars[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))) @@ -260,6 +287,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..ed12c985 --- /dev/null +++ b/bin/routing_figures/prices.py @@ -0,0 +1,38 @@ +"""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.""" + input: float + write_5m: float + write_1h: float + read: float + output: float + + +# 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…`. A cache write costs 1.25 times the input for five minutes and 2 times for an hour, as Opus 5.5's $5 and $8 show. Haiku 5.5's cache read is assumed at a tenth of its input, and its dearer prompts over 100k tokens are left out. Only the proportions between one model's messages matter, since a chunk's recorded cost sets the amounts, so these may be a little off. +PRICES = { + "claude-opus-5-5": Price(4, 5, 8, 0.2, 20), + "claude-sonnet-5-5": Price(2, 2.5, 4, 0.2, 10), + "claude-fable-5-1": Price(10, 12.5, 20, 0.25, 50), + "claude-haiku-5-5": Price(0.1, 0.125, 0.2, 0.01, 0.5), +} + + +# {"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..11d560ad 100644 --- a/bin/routing_figures/test_routing_figures.py +++ b/bin/routing_figures/test_routing_figures.py @@ -22,8 +22,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 +44,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 +57,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 +75,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 +95,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 +113,55 @@ 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_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 +190,18 @@ 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.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 +241,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 +256,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 44c2807f..90e30855 100644 --- a/todo.md +++ b/todo.md @@ -12,7 +12,6 @@ | ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score | |---|---|---|---|---|---|---|---|---|---|---|---| -| 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 | | 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 | | 226 | 0.5.0 | | question | **Answer whether rule-hook's `run-heavy` rule should also catch a mutation run or docker build behind `uv run`, `poetry run`, `python3 -m`, `sudo`, `docker image build` and `docker compose up --build`, or narrow the `machine load:` decision's wording.** | 2 | 2 | 3 | 5 | 3 | 1.2 by 2, 1.5 by 2 | 4.0 | | 235 | 0.5.0 | | decision | **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.** | 1 | 2 | 1 | 2 | 2 | 1.1 by 2, 1.4 by 3 | 6.8 | @@ -77,10 +76,6 @@ ## Details -### 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.