Repository avatar
AI Tools
v0.1.2
active

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

agent-token-forensics

Read-only offline JSONL forensics pinpointing prompt-cache bust cliffs, compaction inflection points & retry loops.

CI PyPI Python 3.10+ 0 stdlib deps 39 tests passing Win / Linux / macOS MIT License

Glama MCP Server

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 analyze with no path to auto-discover recent local transcripts (~/.claude, ~/.codex, ~/.cursor, ~/.gemini), run agent-token-forensics analyze --demo to preview sample output, or drop a .jsonl into 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):

Real 232-turn session audit showing 97.4% apparent vs 10.9% effective cache hit rate and $12.06 recoverable waste


Live Demo

Verified output from agent-token-forensics analyze --demo (v0.1.1):

agent-token-forensics verified CLI demo output


Architecture

agent-token-forensics read-only offline pipeline architecture

What It Detects

SignalMechanismDefault Threshold
Multi-Vendor JSONL SchemasParses 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 FinderIdentifies 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 DetectorCatches 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 ForensicsFlags 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 over stdio.

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, optional compact_threshold, post_compact_target, output_format: "json" | "markdown") and returns cache_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, Gemini usageMetadata, 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 .jsonl files: exits 0 with 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 2 and an error message on stderr.
  • No compaction recommendations shown: your sessions stayed under --compact-threshold (default 80000 tokens); 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

RepositoryRole in the HarnessStack
BlackBadHope/agent-killswitchOS process-tree killswitch & runaway execution breakerPython stdlib · Win32 / POSIX
BlackBadHope/agent-token-forensicsRead-only JSONL token, cache-cliff & retry-loop forensicsPython 3.10+ stdlib · MCP
BlackBadHope/evidence-gateSHA-256 digest-bound test cache & anti-loop monitor gatePython 3.10+ stdlib · CLI
BlackBadHope/integrity-platformMulti-plane execution firewall, witness ledger & control planeGo / Python · Hybrid
BlackBadHope/neon-studioMulti-stage agent studio & CAS patch railTypeScript / Python
BlackBadHope/integrity-landingPublic control-plane site & docs (integrityharness.dev)Cloudflare Pages

License

MIT — see LICENSE.

PYPI
agent-token-forensics
Install Command
pip install agent-token-forensics
Runtime: python