Metadata-Version: 2.4
Name: ctx-profiler
Version: 0.1.1
Summary: Token economics and context-window profiler for coding agents (Claude Code, Codex, Cline, OpenClaw, OpenAI traces).
Author: Soural D
License: MIT
Project-URL: Homepage, https://github.com/cuhawk/ctx-profiler
Project-URL: Repository, https://github.com/cuhawk/ctx-profiler
Project-URL: Issues, https://github.com/cuhawk/ctx-profiler/issues
Keywords: llm,context-engineering,coding-agents,token-economics,claude-code,codex,cline,openclaw,mcp,profiler
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Software Development :: Quality Assurance
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: viz
Requires-Dist: Pillow>=10.0.0; extra == "viz"
Requires-Dist: matplotlib>=3.8.0; extra == "viz"
Provides-Extra: tiktoken
Requires-Dist: tiktoken>=0.7.0; extra == "tiktoken"
Provides-Extra: dev
Requires-Dist: pytest>=8.0.0; extra == "dev"
Requires-Dist: Pillow>=10.0.0; extra == "dev"
Requires-Dist: matplotlib>=3.8.0; extra == "dev"
Dynamic: license-file

# ctx-profiler

**Where did 60% of your coding-agent tokens go? Profile Claude Code, Codex & Cline logs in one command.**

`ctx-profiler` is a zero-dependency Python CLI and stdio MCP server for **context engineering and token economics**. It replays real multi-turn coding-agent transcripts turn by turn, attributes **every single token** across 6 mutually-exclusive, collectively-exhaustive (MECE) buckets, and simulates 5 concrete compaction policies before you change a line of harness code.

![ctx-profiler animated terminal demo](assets/demo.gif)

---

## Why This Exists

In multi-turn coding-agent loops, context cost grows **quadratically**: a single 4,500-token `pytest -vv` traceback or redundant file read on turn 5 isn't paid once — it is re-sent in every subsequent API call for the rest of the session.

This tool directly targets the context-bloat failure modes documented across major agent harnesses:
- **Claude Code** — oversized tool output & repeated file reads filling context windows ([anthropics/claude-code#16157](https://github.com/anthropics/claude-code/issues/16157), [anthropics/claude-code#38335](https://github.com/anthropics/claude-code/issues/38335))
- **OpenAI Codex CLI** — quadratic session replay, verbose shell logs, and reasoning overhead ([openai/codex#41220](https://github.com/openai/codex/issues/41220))
- **Cline / Roo** — `api_conversation_history.json` growth from recursive search dumps, repeated `<read_file>` calls, and retained `<thinking>` blocks ([cline/cline#4389](https://github.com/cline/cline/issues/4389))

---

## 10-Second Quickstart

Pure Python stdlib core (Python >= 3.10, zero required runtime dependencies):

```bash
# Run without installing globally (uvx)
uvx --from . ctx-profiler analyze fixtures/

# Or install editable locally
pip install -e .
ctx-profiler analyze fixtures/
ctx-profiler simulate fixtures/ --model claude-sonnet-4 --csv savings.csv
```

Optional visualization extras (`Pillow` + `matplotlib`) for generating PNG/GIF benchmark visuals:

```bash
pip install -e ".[viz]"
ctx-profiler bench
```

---

## The 6 MECE Token Categories (Hard Golden Invariant)

Every analyzed turn, session, and corpus enforces the **exact integer token invariant**:

```text
sum(category_tokens.values()) == total_session_tokens
```

| Category | Classification | What It Captures |
| :--- | :--- | :--- |
| `file_rereads` | **Waste** | Unchanged file paths read again (both emission and subsequent turn replays) |
| `tool_output_bloat` | **Waste** | Non-file-read shell/grep/ls/test/MCP output exceeding `--tool-bloat-threshold` (default `2,000` tok) + replays |
| `reasoning_think_replay` | **Waste** | Prior-turn `<think>...</think>` or reasoning blocks re-injected into subsequent prompts |
| `system_and_tool_schemas` | **Overhead** | Repeated system prompt + MCP/tool JSON schemas sent every turn |
| `history_replay` | **Overhead** | Prior useful conversation turns re-sent in subsequent prompts |
| `useful_new_work` | **Useful** | Fresh prompts, first-time file reads, within-threshold tool results, and newly generated completions |

**Waste Ratio %** is defined strictly as:

```text
Waste Ratio % = (file_rereads + tool_output_bloat + reasoning_think_replay) / total_session_tokens * 100
```

When API `usage` metadata is present in a log (Claude Code, Codex, OpenClaw, OpenAI traces), per-turn totals are reconciled to the exact reported integer count via **Largest-Remainder (Hamilton) apportionment** so there is zero rounding drift.

---

## Reproducible E2 Context Waste Benchmark

Every number below is generated deterministically by running `ctx-profiler bench` over the 6 realistic multi-turn coding-agent fixture logs shipped in [`fixtures/`](fixtures/) (raw outputs saved in [`benchmarks/context_waste_report.csv`](benchmarks/context_waste_report.csv) and [`benchmarks/context_waste_report.json`](benchmarks/context_waste_report.json)):

![E2 Context Waste Benchmark Chart](assets/context_waste_breakdown.png)

### Measured Per-Session Breakdown (`claude-sonnet-4`: `$3.00` in / `$0.30` cached / `$15.00` out per 1M tokens)

| Session | Agent Format | Turns | Total Tokens | File Re-reads | Tool Bloat | Think Replay | Schemas | History Replay | Useful Work | Waste % | Est. Cost |
| :--- | :--- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: |
| `01_claude_code_fastapi_debug` | `claude-code` | 32 | 2,438,603 | 1,118,883 | 339,691 | 4,180 | 40,224 | 894,316 | 41,309 | **59.98%** | $1.096 |
| `02_codex_ts_refactor` | `codex` | 30 | 1,584,583 | 481,915 | 385,012 | 3,853 | 18,390 | 660,756 | 34,657 | **54.95%** | $0.724 |
| `03_cline_multi_file_search_edit` | `cline` | 26 | 1,287,459 | 259,368 | 584,640 | 30,373 | 0 | 387,580 | 25,498 | **67.92%** | $0.629 |
| `04_claude_code_mcp_heavy_workspace` | `claude-code` | 30 | 1,078,884 | 132,963 | 133,476 | 0 | 364,590 | 420,953 | 26,902 | **24.70%** | $0.475 |
| `05_openclaw_qwen_think_loop` | `openclaw` | 36 | 1,193,084 | 139,269 | 0 | 609,549 | 24,913 | 366,745 | 52,608 | **62.76%** | $0.955 |
| `06_openai_trace_monorepo_migration` | `openai` | 28 | 918,816 | 202,619 | 390,735 | 15,795 | 70,532 | 226,635 | 12,500 | **66.30%** | $0.440 |
| **CORPUS TOTAL** | **all (6 logs)** | **182** | **8,501,429** | **2,335,017** | **1,833,554** | **663,750** | **518,649** | **2,956,985** | **193,474** | **56.84%** | **$4.319** |

*(Uncached list cost across the 6 sessions without prompt caching: **$26.062**; avoidable waste cost at effective cache-aware input rates: **$2.070**.)*

### Compaction Simulator Results (`ctx-profiler simulate fixtures/ --model claude-sonnet-4`)

| Policy | Before Tokens | After Tokens | Tokens Saved | Reduction | After Waste % | Est. Savings / 100 Sessions |
| :--- | ---: | ---: | ---: | ---: | ---: | ---: |
| `dedup-rereads` | 8,501,429 | 6,180,914 | 2,320,515 | 27.30% | 40.40% | $15.779 |
| `cap-tool-output-2k` | 8,501,429 | 6,635,189 | 1,866,240 | 21.95% | 45.19% | $13.485 |
| `strip-think-replay` | 8,501,429 | 7,837,682 | 663,747 | 7.81% | 53.19% | $3.738 |
| `lazy-mcp-schemas` | 8,501,429 | 8,110,575 | 390,854 | 4.60% | 59.58% | $3.377 |
| **`combined-all`** | **8,501,429** | **3,260,075** | **5,241,354** | **61.65%** | **0.00%** | **$36.379** |

---

## CLI Usage

```bash
# Profile a single file or entire directory (auto-detects agent format)
ctx-profiler analyze path/to/session.jsonl
ctx-profiler analyze path/to/logs/ --format markdown --out report.md
ctx-profiler analyze path/to/logs/ --format svg --out breakdown.svg
ctx-profiler analyze path/to/logs/ --format json --model gpt-5

# Override pricing (USD / 1M tokens) — e.g. self-hosted local GPU
ctx-profiler analyze fixtures/05_openclaw_qwen_think_loop.jsonl \
  --model qwen3.8-27b --input-price 0 --cached-price 0 --output-price 0

# Simulate all 5 compaction policies + export CSV
ctx-profiler simulate fixtures/ --model claude-sonnet-4 --csv compaction.csv

# Reproduce the full E2 benchmark + PNG + GIF
ctx-profiler bench
```

---

## Native MCP Server & Agent Skill

### 1. Run as a Stdio MCP Server (`ctx-profiler mcp`)
Exposes two tools over JSON-RPC 2.0 stdio (`analyze_session_log` and `simulate_compaction`). Published on the [Official MCP Registry](https://registry.modelcontextprotocol.io) as `io.github.cuhawk/ctx-profiler`. Add to Claude Code, Codex, or OpenClaw MCP config:

```json
{
  "mcpServers": {
    "ctx-profiler": {
      "command": "uvx",
      "args": ["ctx-profiler", "mcp"]
    }
  }
}
```

Or if installed locally (`pip install ctx-profiler`):

```json
{
  "mcpServers": {
    "ctx-profiler": {
      "command": "ctx-profiler",
      "args": ["mcp"]
    }
  }
}
```

### 2. Drop-in Agent Skill
Copy [`skills/ctx-profiler/SKILL.md`](skills/ctx-profiler/SKILL.md) into your project or user `.agents/skills/` (or `~/.claude/skills/`) directory so your coding agent can profile its own transcripts automatically.

---

## Limitations & What to Distrust

Transparency matters more than flattering charts. Read these caveats before citing numbers from any profiler — including this one:

1. **Tokenizer Approximation When API `usage` Is Missing:** Logs without per-turn API usage metadata (notably Cline's `api_conversation_history.json`) rely on our deterministic pure-stdlib BPE-aligned token estimator (`tokenizer.py`). Expect roughly ±4–8% variance versus proprietary provider tokenizers on dense code or non-ASCII text. When API `usage` *is* present, `ctx-profiler` reconciles every turn to the exact reported integer token count, but the *split* across categories inside a turn still follows text-weighted proportions.
2. **Prompt Caching Makes Dollar Savings Smaller Than Token Savings:** Deleting 60% of cached input tokens does **not** cut your invoice by 60% if 95% of your prompt was already hitting `$0.30/1M` cache reads while output tokens cost `$15.00/1M`. That is why `ctx-profiler` separates cache-aware cost (`$4.319`) from uncached list cost (`$26.062`) and reports realistic cache-aware savings (`$36.38 / 100 sessions`). Moreover, mid-history edits (like rewriting earlier tool results) can invalidate a provider's KV prefix cache if implemented naively — in production, compaction should happen at turn emission time (before appending to the prefix) rather than mutating cached history retroactively.
3. **Simulation Does Not Measure Task Accuracy Degradation:** `ctx-profiler simulate` computes exact token-economy bounds under deterministic transformations (`dedup-rereads`, `cap-tool-output-2k`, `strip-think-replay`, `lazy-mcp-schemas`). It does **not** re-run the LLM to verify whether truncating a middle stack frame or omitting a reread would cause the agent to take an extra recovery turn. Always pair token profiling with a task pass-rate eval on your own repo.
4. **Heuristic File-Modification Tracking:** If a file is modified externally outside logged write tools (e.g., via a complex shell build script whose output target isn't parsed as a direct edit), a subsequent read of that path may be flagged as `file_rereads` even though its contents changed on disk.
5. **Shipped Benchmark Fixtures Are Representative Synthetic Traces:** The 6 sessions in `fixtures/` model realistic 26–36 turn multi-agent sessions matching each harness's real wire schema (`claude-code`, `codex`, `cline`, `openclaw`, `openai`), not private user transcripts. Always run `ctx-profiler analyze` on your own real local session logs before making budget decisions.

---

## Development

```bash
make test    # Run full pytest suite
make bench   # Re-run E2 benchmark & regenerate CSV, JSON, PNG, GIF
make demo    # Print terminal analyze + simulate tables
```

## License

MIT — see [LICENSE](LICENSE).

<!-- mcp-name: io.github.cuhawk/ctx-profiler -->
