Review your coding agents' spend like a slow query

· Maksym Lyskov

When the agent bill goes up, the total doesn’t point at anything to fix. Treat it like a slow database. To tune Postgres you pull the worst queries out of pg_stat_statements, read their plans and fix those first.

For agents, the worst queries are runs, and the plan is the transcript. So once a day I read yesterday’s transcripts with a script that names the patterns that burn money: blind waits, the same file read over and over, a big model doing read-only work, and runs that cost far more than the rest. Each hit becomes a rule or a ticket.

The script below is real and runs on Node 22 with no dependencies. The transcripts it reads in this post are made up, generated in Claude Code’s format, and the output block is what it printed.

Where the transcripts are

Claude Code stores every session as JSONL at ~/.claude/projects/<project>/<session-id>.jsonl. Subagents get their own files in a subagents/ folder next to the session. Each assistant line carries the model, the token usage and one content block: a thinking block, some text or a tool call.

One trap before you sum anything. A single API response is written as several lines, one per content block (the thinking, then each tool call), and every one of those lines repeats the same usage. Sum per line and you count most responses twice or more. On one long session of mine, summing per line came out 2.4 times the real output total. Count each message.id once.

The script

Save it as agent-spend.mjs:

#!/usr/bin/env node
// agent-spend: name the wasteful patterns in the last day of Claude Code transcripts.
// usage: agent-spend.mjs [PROJECTS_DIR] [HOURS]
import { readdirSync, readFileSync, statSync } from "node:fs";
import { join } from "node:path";
import { homedir } from "node:os";

const root = process.argv[2] ?? join(homedir(), ".claude/projects");
const since = Date.now() - Number(process.argv[3] ?? 24) * 3600e3;

function* transcripts(dir) {
  for (const e of readdirSync(dir, { withFileTypes: true })) {
    const p = join(dir, e.name);
    if (e.isDirectory()) yield* transcripts(p);
    else if (p.endsWith(".jsonl") && statSync(p).mtimeMs >= since) yield p;
  }
}

// Cost in input-token units, from Anthropic's price ratios: 5-minute cache writes 1.25x,
// 1-hour cache writes 2x, cache reads 0.1x, output 5x.
const units = (u) => {
  const w = u.cache_creation;
  const writes = w
    ? 1.25 * (w.ephemeral_5m_input_tokens ?? 0) + 2 * (w.ephemeral_1h_input_tokens ?? 0)
    : 1.25 * (u.cache_creation_input_tokens ?? 0);
  return (u.input_tokens ?? 0) + writes + 0.1 * (u.cache_read_input_tokens ?? 0) + 5 * (u.output_tokens ?? 0);
};

const runs = [];
for (const file of transcripts(root)) {
  const run = { file, model: null, cost: 0, seen: new Set(), tools: [], reads: new Map(), sleeps: [] };
  for (const line of readFileSync(file, "utf8").split("\n")) {
    let r;
    try { r = JSON.parse(line); } catch { continue; }
    if (r.type !== "assistant" || Date.parse(r.timestamp) < since) continue;
    const m = r.message;
    // One API response is written as one line per content block, each with the same usage.
    if (!run.seen.has(m.id)) { run.seen.add(m.id); run.cost += units(m.usage ?? {}); }
    run.model = m.model;
    for (const c of m.content ?? []) {
      if (c.type !== "tool_use") continue;
      run.tools.push(c.name);
      if (c.name === "Read") run.reads.set(c.input.file_path, (run.reads.get(c.input.file_path) ?? 0) + 1);
      if (c.name === "Bash" && /(^|[;&|( ])sleep [0-9]|until .*sleep/.test(c.input.command)) run.sleeps.push(c.input.command);
    }
  }
  if (run.seen.size) runs.push(run);
}

const costs = runs.map((r) => r.cost).sort((a, b) => a - b);
const median = costs[Math.floor(costs.length / 2)] ?? 0;
const readOnly = new Set(["Read", "Grep", "Glob", "WebFetch", "WebSearch"]);
const name = (r) => r.file.replace(root + "/", "");

console.log(`${runs.length} runs, median cost ${Math.round(median)} units\n`);
for (const r of runs) {
  const found = [];
  if (r.cost > 3 * median) found.push(`outlier: ${(r.cost / median).toFixed(1)}x the median run`);
  for (const s of r.sleeps) found.push(`blind wait: ${s.replace(/\s+/g, " ").slice(0, 60)}`);
  for (const [f, n] of r.reads) if (n >= 3) found.push(`reread: ${f} read ${n} times`);
  if (/opus/.test(r.model) && r.tools.length && r.tools.every((t) => readOnly.has(t)))
    found.push(`big model, read-only work: ${r.model}, ${r.tools.length} tool calls, all ${[...new Set(r.tools)].join("/")}`);
  if (found.length) console.log(`${name(r)}\n  ${found.join("\n  ")}`);
}

It ranks runs by a cost in input-token units, with the ratios from the price list: cache reads at a tenth, output at five times, and cache writes at 1.25x or 2x depending on whether they’re 5-minute or 1-hour. The usage block splits writes by that lifetime, and the Claude Code session I checked wrote everything to the 1-hour cache. I left dollars out on purpose: a run that’s 5x the median is worth opening whatever the rate is.

What it printed

Over a day of made-up transcripts for one project, five sessions and one subagent:

6 runs, median cost 206060 units

-home-dev-shop-api/2b7c.jsonl
  blind wait: sleep 10 && curl -s localhost:3000/health
  blind wait: sleep 20 && curl -s localhost:3000/health
-home-dev-shop-api/3d9e.jsonl
  reread: src/orders/pricing.ts read 6 times
-home-dev-shop-api/4e21.jsonl
  outlier: 5.2x the median run
-home-dev-shop-api/5a08/subagents/agent-c41.jsonl
  reread: src/app.ts read 5 times
  big model, read-only work: claude-opus-4-5, 9 tool calls, all Read/Grep

Four of the six runs got flagged, and each one names a file you can open.

Turn each finding into a rule or a ticket

Blind wait. The agent started a dev server and guessed how long it needed. Every sleep is a full turn spent waiting, and when the guess is short it tries again with a bigger number. The fix is a rule in CLAUDE.md: never wait with sleep, run a readiness check that polls the URL and stops at a deadline.

Reread. Six reads of one file in one run means the agent kept losing it, either to compaction or because the file is too long to hold. Split the file, or add a short map of it to the rules file so the agent knows where to look.

Big model, read-only work. A subagent that only reads and greps doesn’t need the largest model. Subagent definitions in .claude/agents/ take a model field in their frontmatter (haiku, sonnet, opus, or inherit). Without one, the subagent runs on the main conversation’s model. The first time I ran this on my own machine, it flagged the reviewer agents I use to proofread drafts: the biggest model, one Read call each, then an answer.

Outlier. This one gets a ticket, the same way a query at 5x its normal time does. Open the transcript and find where the cost went: a loop of failed tests, a huge tool result read back on every turn, or a task that was really three tasks. A loop of failed tests gets a rule, a huge tool result gets capped where it’s produced, and a task that was really three gets split.

Run it every day

Run it once a day, on the previous 24 hours, and read the output before standup. When a fix works, its pattern drops off the next day’s list, and that’s how you know the rule took.

The same docs page says the transcript format is internal and changes between versions. If a field moves, the script will print fewer findings. So keep one known-bad transcript (a session with a sleep 10 in it is enough) and make sure the script still flags it after you update Claude Code.

Transcripts are kept for 30 days by default (cleanupPeriodDays in settings.json). So the first time, run it over the whole month with node agent-spend.mjs ~/.claude/projects 720 to see which patterns were there before you started looking.