Last week I pulled a real 232-turn local transcript from our Windows/Linux ISP ops repo because weekly coding-agent quota kept draining even though the headline prompt-cache hit rate looked healthy at 97.4%.
Parsing the raw JSONL turn-by-turn showed why aggregate cache hit percentages mislead you on long sessions:
- Turns:
232 - Total context processed:
40.08Mtokens - Peak single-turn context:
352.7ktokens (crossed80kon turn11and rode221turns without compacting) - Apparent cache hit rate:
97.4% - Effective cache hit rate:
10.9% - Estimated spend (list rates):
$16.01 - Recoverable waste:
$12.06(75.3%) - Detected events:
2cache-bust cliffs (99% -> 0%on a210kwindow),6consecutive Bash retry loops,2oversized tool blobs (including a16k-token command output on turn13re-read219times)
A 97.4% hit rate sounds great until you notice that 90% of those cached reads are re-reading stale history and giant command dumps across 200+ turns.
Exact JSONL Fields Across Agent Logs
The offline parser in token-audit-engine.js (browser) and agent-token-forensics (Python stdlib CLI) normalizes four provider log shapes into the same 4-tuple (input_tokens, output_tokens, cache_read_tokens, cache_write_tokens):
- Anthropic / Claude Code (
usage):-
input_tokens,output_tokens -
cache_read_input_tokens(fallback:cache_read_tokens) -
cache_creation_input_tokens(fallback:cache_creation_tokens)
-
- OpenAI Responses / Codex CLI (
event_msgtoken_count->last_token_usageor diff of cumulativetotal_token_usage):-
input_tokens,output_tokens,cached_input_tokens - Note:
cached_input_tokensis a subset ofinput_tokens, so uncached input ismax(0, input_tokens - cached_input_tokens).
-
- OpenAI Chat Completions (
usage):-
prompt_tokens,completion_tokens,prompt_tokens_details.cached_tokens
-
- Gemini (
usageMetadata):-
promptTokenCount,candidatesTokenCount,cachedContentTokenCount
-
Per turn, total context and apparent cache hit are:
total_context = input_tokens + cache_read_tokens + cache_write_tokens cache_hit_ratio = total_context > 0 ? cache_read_tokens / total_context : 0 How Effective Cache Hit Is Computed
To separate productive cached prefix reads from wasted re-reads, the engine tracks perTurnWastedCr[k] on every turn k across three waste buckets:
- Uncompacted tail past
80,000tokens (defaultcompactThreshold = 80_000,postCompactTarget = 20_000):- Once context crosses
80k, every subsequent turn carriesexcess = max(0, total_context - 20_000). - Wasted cached reads on turn
k:round(cache_read_tokens * (excess / total_context)). - Estimated dollar waste on turn
k:turn_cost * (excess / total_context) * 0.85.
- Once context crosses
- Consecutive identical tool-retry loops (
loopThreshold = 3turns):- When the same tool signature repeats
>= 3consecutive turns, every repeated turn after the first counts its fullcache_read_tokensas wasted.
- When the same tool signature repeats
- Oversized tool output blobs (
bloatCharThreshold = 24_000chars orbloatDeltaThreshold = 15_000context jump on a non-cache-bust turn):- Excess tokens above
2,000(excessBlob = max(0, blobTokens - 2_000)) are billed once at ingest (cache_writeorinputrate) and then carried atcache_readrate on every subsequent turnk > pos, contributingmin(cache_read_tokens, excessBlob)toperTurnWastedCr[k].
- Excess tokens above
We take the per-turn maximum across those buckets so overlapping waste is never double-counted, clamp to cache_read_tokens, sum totalWastedCacheReadTokens, and compute:
effective_cache_hit = total_context_sum > 0 ? Math.max(0, total_cache_read - total_wasted_cache_read) / total_context_sum : 0 Separately, the cache-bust cliff detector fires whenever the previous turn was warm (total_context >= 10_000 and cache_hit_ratio >= 0.7) and the current turn has total_context >= 10_000 with cache_hit_ratio < 0.3. Extra dollar cost is (input_tokens * (inRate - cacheReadRate) + cache_write_tokens * (cacheWriteRate - cacheReadRate)) / 1_000_000.
Per-turn dollar waste is deduplicated and capped at 95% of the turn's cost:
combinedTurnWaste = Math.min( turnCost * 0.95, Math.max( loopWaste, bustWaste + Math.max(tailWaste, bloatWaste) ) ) In our 232-turn trace, total_cache_read / total_context_sum was 97.4%, while (total_cache_read - total_wasted_cache_read) / total_context_sum dropped to 10.9%.
Running It Locally (Zero Upload)
Private repo transcripts should never leave your machine, so both interfaces run offline:
- Browser auditor (100% client-side JS, works with Wi-Fi off): https://integrityharness.dev/token-audit
- MIT Python CLI and read-only stdio MCP (
v0.1.1, 0 runtime deps, 39 tests on Win/Linux/macOS CI): https://github.com/BlackBadHope/agent-token-forensics
pipx install agent-token-forensics # Preview on built-in synthetic trace agent-token-forensics analyze --demo # Auto-scan local Claude Code / Codex / Antigravity JSONL logs agent-token-forensics analyze # Expose strictly read-only stdio MCP tools (analyze_transcripts, forensics_about) agent-token-forensics mcp-serve Scope note: this is strictly read-only offline forensics. Dollar figures are deterministic estimates from logged token counts and public list rates, not provider invoices, and the tool does not intercept or auto-compact live sessions.
What worked best on our own repo after reading these traces: compacting hard around 80k-120k, piping noisy shell commands through head/tail/rg or writing to a scratch file, and stopping identical retry loops after 2 failures.
