
agent-token-forensics
io.github.BlackBadHope/agent-token-forensics
Read-only JSONL token, prompt-cache, compaction, and retry-loop forensics for AI coding agents.
Documentation
agent-token-forensics
Read-only offline JSONL forensics pinpointing prompt-cache bust cliffs, compaction inflection points & retry loops.
Browser auditor (100% offline JS, 0 bytes uploaded): integrityharness.dev/token-audit
Quick Start · Real Trace · Live Demo · Architecture · CLI & Flags · MCP Server · Troubleshooting · Ecosystem
I built agent-token-forensics after watching my own long coding-agent sessions report 97%+ prompt-cache hit rates while still burning most of the budget on uncompacted context tails (>80k tokens), idle cache-TTL cliffs, and identical tool-retry loops. It scans local JSONL transcripts strictly read-only using pure Python 3.10+ stdlib (zero runtime dependencies, zero network calls, zero disk writes).
[!NOTE] Zero-arg UX: Run
agent-token-forensics analyzewith no path to auto-discover recent local transcripts (~/.claude,~/.codex,~/.cursor,~/.gemini), runagent-token-forensics analyze --demoto preview sample output, or drop a.jsonlinto the 100% offline browser auditor (0 bytes uploaded).
Quick Start
Live on PyPI as agent-token-forensics. Choose uvx, pipx, pip in a .venv, or zero-install from source.
Linux / macOS (bash)
# Option 1: Zero-Install Ephemeral Run via uvx (recommended)
uvx agent-token-forensics analyze --demo
uvx agent-token-forensics analyze ./transcripts --markdown
# Option 2: Isolated CLI Install via pipx (PEP 668 safe)
pipx install agent-token-forensics
agent-token-forensics analyze ./transcripts --markdown
agent-token-forensics analyze ./session.jsonl --json
# Option 3: Isolated .venv via pip
python3 -m venv .venv
.venv/bin/python -m pip install agent-token-forensics
.venv/bin/agent-token-forensics analyze ./transcripts --markdown
Windows (pwsh 7)
# Option 1: Zero-Install Ephemeral Run via uvx
uvx agent-token-forensics analyze --demo
uvx agent-token-forensics analyze .\transcripts --markdown
# Option 2: Isolated CLI Install via pipx
pipx install agent-token-forensics
agent-token-forensics analyze .\transcripts --markdown
# Option 3: Isolated .venv via pip
python -m venv .venv
.\.venv\Scripts\python.exe -m pip install agent-token-forensics
.\.venv\Scripts\agent-token-forensics.exe analyze .\transcripts --markdown
Real Session Trace
Output on a real sanitized 232-turn coding session from my own ops repo (40.08M total context tokens, 352.7k peak context): 97.4% apparent cache hit vs 10.9% effective hit ($12.06 recoverable out of $16.01 estimated spend across 2 cache busts, 6 retry loops, and 221 turns riding above 80k tokens):
Live Demo
Verified output from agent-token-forensics analyze --demo (v0.1.1):
Architecture
What It Detects
| Signal | Mechanism | Default Threshold |
|---|---|---|
| Multi-Vendor JSONL Schemas | Parses Claude Code / Anthropic (usage.input_tokens, cache_read_input_tokens), OpenAI / Codex / Cursor (prompt_tokens, prompt_tokens_details.cached_tokens), Gemini (usageMetadata), and Antigravity flat transcripts. | Auto-detected per line |
| Compaction Inflection Finder | Identifies the exact turn where context crosses --compact-threshold and estimates realistic token & USD savings from compacting to --post-compact-target. | 80,000 tokens |
| Prompt-Cache Bust Detector | Catches turns where a warm prompt cache (>=70% hit ratio) suddenly collapses (<30%), exposing silent prefix mutations or idle TTL evictions. | >=70% -> <30% |
| Retry-Loop & Tool-Bloat Forensics | Flags consecutive identical tool invocations and ranks tools by attributed token burn. | >=3 consecutive calls (--loop-threshold) |
CLI Reference
agent-token-forensics analyze [paths ...] [--demo]
[--compact-threshold N]
[--post-compact-target N]
[--loop-threshold N]
[--json | --markdown]
agent-token-forensics mcp-serve
- Omit
paths: auto-discovers recent local JSONL sessions (~/.claude,~/.codex,~/.cursor,~/.gemini). --demo: runs the built-in sample transcript so you can verify output before scanning local logs.--json/--markdown: emit machine-readable JSON for CI budgets or clean Markdown summary tables.mcp-serve: starts the strictly read-only JSON-RPC 2.0 MCP server overstdio.
MCP Server (stdio)
agent-token-forensics ships a zero-dependency, strictly read-only MCP JSON-RPC 2.0 server over stdio (pure Python 3.10+ stdlib, zero writes, zero telemetry, zero network calls).
Exposed Read-Only Tools:
analyze_transcripts— analyzes a JSONL transcript file or directory (path, optionalcompact_threshold,post_compact_target,output_format:"json"|"markdown") and returnscache_bust_events,compaction_inflection_points,retry_loops,top_tools_by_tokens, and cost/savings summary.forensics_about— returns version, supported transcript schemas (Claude Code/Anthropic, OpenAI/Codex/Cursor, GeminiusageMetadata, Antigravity), and zero-telemetry / read-only guarantees.
Run directly from a cloned repo or source install:
python -m agent_token_forensics.mcp_server
# or via the zero-install shim / installed CLI:
python agent_token_forensics_cli.py mcp-serve
agent-token-forensics mcp-serve
Claude Code / Cursor / Antigravity MCP config (mcpServers):
{
"mcpServers": {
"agent-token-forensics": {
"command": "python",
"args": ["/path/to/agent-token-forensics/agent_token_forensics_cli.py", "mcp-serve"]
}
}
}
Or if installed from PyPI / source into your environment (or via uvx --from git+https://github.com/BlackBadHope/agent-token-forensics):
{
"mcpServers": {
"agent-token-forensics": {
"command": "python",
"args": ["-m", "agent_token_forensics.mcp_server"]
}
}
}
Troubleshooting & Clean Uninstall
1. Ubuntu / Debian 24.04: error: externally-managed-environment (PEP 668)
Modern Debian/Ubuntu blocks global pip install under PEP 668. Use either clean option (no --break-system-packages needed):
# Option A: Zero-install direct run (pure Python 3.10+ stdlib)
python3 agent_token_forensics_cli.py analyze ./session.jsonl --markdown
# Option B: Isolated virtual environment (zero external deps)
python3 -m venv .venv
.venv/bin/python -m pip install --no-deps .
.venv/bin/agent-token-forensics analyze ./transcripts --markdown
2. Empty Directories, Zero-Turn Files, and Corrupt JSONL Lines
agent-token-forensics is strictly read-only and designed to survive messy real-world logs:
- Empty directory or no
.jsonlfiles: exits0with a clean zero-turn summary (files_scanned: 0,turns: 0) rather than crashing. - Truncated, malformed, or non-UTF-8 JSONL lines: invalid lines and non-usage metadata events are skipped safely (
errors="replace"), while all valid turns in the same file are still analyzed. - Non-existent path: fails explicitly with exit
2and an error message onstderr. - No compaction recommendations shown: your sessions stayed under
--compact-threshold(default80000tokens); lower it (e.g.--compact-threshold 40000) for smaller context windows.
3. Clean Uninstall / Reset-to-Zero
agent-token-forensics creates zero hidden state directories, caches, or background daemons. To uninstall and reset to zero:
# Linux / macOS
python3 -m pip uninstall -y agent-token-forensics 2>/dev/null || true
rm -rf ./agent-token-forensics # or remove your .venv directory
# Windows (PowerShell 7)
python -m pip uninstall -y agent-token-forensics
Remove-Item -Recurse -Force ".\agent-token-forensics" -ErrorAction SilentlyContinue
Development & Verification
ruff check agent_token_forensics agent_token_forensics_cli.py tests agensi-skill
python -m pytest -q
# or unittest:
python -m unittest discover -s tests -p "test_*.py" -v
Browser Auditor & Related Tools
- Zero-Upload Browser Auditor: integrityharness.dev/token-audit (same deterministic detector math running 100% client-side in JS; free forever).
- Optional Cloud Control Plane: integrityharness.dev (if you need multi-host killswitch toggles or team alerts across machines; this CLI and MCP server remain MIT/free forever).
Integrity Harness Ecosystem
| Repository | Role in the Harness | Stack |
|---|---|---|
| BlackBadHope/agent-killswitch | OS process-tree killswitch & runaway execution breaker | Python stdlib · Win32 / POSIX |
| BlackBadHope/agent-token-forensics | Read-only JSONL token, cache-cliff & retry-loop forensics | Python 3.10+ stdlib · MCP |
| BlackBadHope/evidence-gate | SHA-256 digest-bound test cache & anti-loop monitor gate | Python 3.10+ stdlib · CLI |
| BlackBadHope/integrity-platform | Multi-plane execution firewall, witness ledger & control plane | Go / Python · Hybrid |
| BlackBadHope/neon-studio | Multi-stage agent studio & CAS patch rail | TypeScript / Python |
| BlackBadHope/integrity-landing | Public control-plane site & docs (integrityharness.dev) | Cloudflare Pages |
License
MIT — see LICENSE.
agent-token-forensicspip install agent-token-forensics