Your AI Coding Agent's 87% Cache Hit Rate Is Lying to You (JSONL Token Forensics)
If you run autonomous coding agents (Claude Code, Codex CLI, Cursor, Gemini CLI, or Antigravity) on real repositories, you have seen the same pattern: a single debugging session chews through half a daily quota or racks
If you run autonomous coding agents (Claude Code, Codex CLI, Cursor, Gemini CLI, or Antigravity) on real repositories, you have seen the same pattern: a single debugging session chews through half a daily quota or racks up a dollar-plus on one task, yet the aggregate metrics look fine.
An aggregate 87% prompt-cache hit ratio sounds healthy. In practice, averages hide the exact turns where your budget actually died.
After watching long agent runs burn 30β55% of their context budget on avoidable tail weight, I built agent-token-forensics β a strictly read-only, zero-dependency Python 3.10+ CLI that scans local JSONL transcripts offline and points to the exact file, line, and turn responsible for the burn.
What a "Normal" 14-Turn Session Actually Hides
To demonstrate without exposing private work logs, here is real stdout from agent-token-forensics v0.1.0 run against a synthetic 14-turn claude-sonnet-4-6 transcript (demo_session.jsonl) that reproduces three common failure patterns:
=== Agent Token & Quota Burn Forensics ===
Files: 1 | Turns: 14 | Est. Cost: $0.9374
Context Tokens: 1,128,900 (cache_read=982,600, uncached=91,300, hit_ratio=87.0%)
Output Tokens: 10,830
Estimated Compaction Savings (threshold=80,000): 49.3% (~$0.2801)
Cache Busts Detected: 1 | Retry Loops: 1
Compaction Inflection Points:
- demo_session.jsonl: compact after turn 8 (ctx=85,700, tail=6 turns, saveable=556,800 tok)
Retry Loops Detected:
- demo_session.jsonl turn 8: 4x repeated ['Bash']
And the exact --markdown summary table you can paste straight into a team review or PR post-mortem:
| Metric | Value |
|---|---|
| Files analyzed | 1 |
| Model turns | 14 |
| Total context tokens | 1,128,900 |
| Prompt cache hit ratio | 87.0% |
| Output tokens | 10,830 |
| Estimated cost | $0.9374 |
| Est. compaction savings | 49.3% ($0.2801) |
| Cache bust events | 1 |
| Retry loops | 1 |
The 3 Mechanical Root Causes
agent-token-forensics does not guess with another LLM. It parses normalized per-turn usage (input_tokens, output_tokens, cache_read, cache_write, and tool invocations) across Claude Code/Anthropic, OpenAI/Codex/Cursor (prompt_tokens_details.cached_tokens), Gemini (usageMetadata), and Antigravity flat or stream-json logs, then checks three deterministic rules:
-
Silent prompt-cache busts (
>=70%collapse to<30%on>=10kcontext): In the--jsonoutput fordemo_session.jsonl, turn 6 (line 7) showscontext_tokens: 68800withcache_hit_ratio: 0.078. One cache TTL expiry, mid-session MCP tool-list change, or dynamic system-prompt edit forced a cold re-prefill of 54,800 uncached input tokens plus 8,600 cache-write tokens β roughly$0.20burned on a single turn while the session average still read87.0%. -
Uncompacted context tails (crossing
--compact-threshold, default80,000): Every turn past the inflection point pays to carry stale diffs, stack traces, and file dumps forward. Here, turn 8 crossed80,000at85,700tokens, dragging a 6-turn tail up to130,700tokens. Compacting after turn 8 down to--post-compact-target 20000trims556,800context tokens (49.3%of total context,~$0.2801estimated savings after a conservative0.85compaction-overhead factor). Lowering--compact-threshold 60000catches turn 5 right before the cache bust (64.6%/~$0.4947saveable). -
Identical tool retry loops (
>=3consecutive identical tool signatures): Starting on turn 8, the agent ranBashfour times in a row. Tool attribution in--jsonputsBashat583,600attributed tokens across 6 calls β more thanRead(273,150) andEdit(249,960) combined.
Copy-Paste Quickstart (Zero Dependencies, PEP 668 Safe)
The tool runs straight from the MIT GitHub repo today using Python 3.10+ stdlib only (zero pip dependencies, zero network calls):
# Linux / macOS β Zero-install direct run
git clone https://github.com/BlackBadHope/agent-token-forensics
cd agent-token-forensics
python3 agent_token_forensics_cli.py analyze ./transcripts --markdown
python3 agent_token_forensics_cli.py analyze ./session.jsonl --compact-threshold 60000 --json
# Or isolated CLI install (PEP 668 safe on Ubuntu/Debian 24.04)
uvx --from . agent-token-forensics analyze ./transcripts --markdown
pipx install . && agent-token-forensics analyze ./transcripts --markdown
# Windows (PowerShell 7) β Zero-install direct run
git clone https://github.com/BlackBadHope/agent-token-forensics
Set-Location .\agent-token-forensics
python agent_token_forensics_cli.py analyze .\transcripts --markdown
Honest Scope and Limits
-
Strictly read-only, zero telemetry: Scans files read-only, skips
.git,node_modules, and.venv, tolerates malformed/non-UTF-8 lines (errors="replace"), disambiguates collidingtranscript.jsonlbasenames across subdirectories so adjacent sessions never trigger false cache busts, and creates zero hidden state directories. -
Indicative pricing, not invoice accounting: Built-in per-1M rates (
opus,sonnet,haiku,gpt-4o,codex,o3,gemini, plusdefault) exist for relative burn diagnosis, not billing reconciliation. Pass custom pricing via the Python API if you run negotiated enterprise tiers. -
Diagnostics, not runtime enforcement:
agent-token-forensicstells you where quota burned after the fact (27 unit & E2E tests, MIT licensed). It does not kill runaway loops mid-flight.
Want automated guardrails beyond post-session audits?
- GitHub (MIT, free): BlackBadHope/agent-token-forensics
- 1-Click MCP Governance Skills & Paid Bundles (Agensi, USDC live): agensi.io/r/BLACKHOPE
-
Cloud Control Plane (multi-host Killswitch API, SHA-256 Cloud Witness notarization, live
$19/$49plans): integrity.subnet.zp.ua
Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.