README.md

April 16, 2026 · View on GitHub

context-stats

Understand how you use Claude Code — and spend less doing it.

PyPI version PyPI Downloads GitHub stars License: MIT

Three levels of analytics — live session awareness, per-session deep dives, and multi-week cost reports — so you can use Claude Code at its best and know exactly where your tokens go.

Get Started →


Three Levels of Stats

graph TD
    A["Claude Code session"] --> B["statusline script"]
    B --> D["Live status line · context zone · MI"]
    B --> C["Local CSV state"]

    C --> E["context-stats graph"]
    C --> F["context-stats export"]
    C --> G["context-stats report"]
    C --> H["context-stats sessions"]

    subgraph L1["Level 1 — Live"]
        D
        E
        H
    end

    subgraph L2["Level 2 — Session"]
        F
    end

    subgraph L3["Level 3 — Report"]
        G
    end
LevelToolWhat you learn
LiveStatus line + graph dashboard + sessions listContext zone, MI score, token delta — act now, not after it's too late
Sessioncontext-stats exportCache efficiency, interaction timeline, zone history for one session
Reportcontext-stats reportCost breakdown, cache analysis, cross-project patterns across weeks or months

Level 1: Live Stats

Status Line

A single line in your Claude Code terminal updated on every refresh:

my-project | main [3] | 64,000 free (32.0%) | Code | MI:0.918 | +2,500 | Opus 4.6 | abc-123
ElementWhat it tells you
64,000 free (32.0%)Available tokens and utilization
CodeContext zone — color-coded action signal
MI:0.918Model Intelligence score — how sharp the model still is
+2,500Tokens consumed since last refresh

When the terminal is narrow, lower-priority elements drop off in order — the project name is always shown.

Green statusWarning state
Green statuslineYellow statusline

Context Zones

Five zones tell you exactly what to do next:

ZoneColorMeaningAction
PlanningGreenPlenty of roomKeep planning and coding
Code-onlyYellowContext tighteningFinish current task, no new plans
DumpOrangeQuality decliningWrap up and prepare to export
ExDumpDark redNear hard limitStart a new session
DeadGrayExhaustedStop — nothing productive left

Thresholds are model-size-aware: 1M context models use absolute token counts; standard models use utilization ratios. Both are configurable.

Plan zoneCode zoneDump zone
Plan zoneCode zoneDump zone

Model Intelligence (MI)

MI estimates how well Claude performs at the current fill level, calibrated from the MRCR v2 8-needle benchmark:

MI(u) = max(0, 1 - u^β)
ModelβMI at 50%MI at 75%
Opus 4.61.80.7130.404
Sonnet 4.61.50.6460.350
Haiku 4.51.20.5650.292

Color-coded: green (>0.70), yellow (0.40–0.70), red (<0.40 — start a new session). Override with mi_curve_beta=1.5 in config.

Session Listing

Find and switch between active sessions:

context-stats sessions                  # Sessions from the last 5 minutes
context-stats sessions --minutes 30     # Widen the search window

Each session shows the project name, model, token count, and how recently it was active.

Live Graph Dashboard

context-stats graph                     # Context growth for the latest session
context-stats graph --type all          # All graphs
context-stats <session_id> graph        # Specific session
GraphWhat it answers
deltaHow many tokens each interaction consumed
cumulativeTotal context used over the session
cacheCache creation and read tokens, with 5-min TTL countdown
miHow MI degraded across the session
ioInput/output token breakdown

Auto-refreshes every 2 seconds. Pass -w 5 to slow down or --no-watch to show once.

Context growthCumulative graphCache activity
Delta graphCumulative graphCache graph
MI over time
Model Intelligence view

Level 2: Session Report

Export a full deep-dive when you need to understand what happened in a specific session:

context-stats export --output report.md              # Latest session
context-stats <session_id> export --output report.md  # Specific session
SectionWhat you learn
Executive SnapshotModel, project, duration, interactions, final zone
Cache ActivityCache creation vs. read ratio — did your session reuse the cache?
Interaction TimelinePer-interaction context, MI score, and zone history
Visual ChartsMermaid charts: context growth, zones, cache, token composition
Key TakeawaysShort read of what changed

Example output:

## Executive Snapshot
| Signal | Value | Why it matters |
|--------|-------|----------------|
| Model | claude-sonnet-4-6 | Which model produced the session |
| Duration | 59m 32s | Relate context growth to session length |
| Interactions | 135 | How active the session was |
| Final usage | 129,755 (64.9%) | How close the session got to the limit |
| Final zone | Dump zone | Whether the session stayed in a safe range |

See the full example in context-stats-export-output.md.

Cache Keep-Warm

Claude's prompt cache has a ~5 minute TTL. Keep it alive during pauses to avoid expensive cache misses:

context-stats cache-warm on 30m              # Latest session
context-stats <session_id> cache-warm on 30m  # Specific session
context-stats cache-warm off

Heartbeats fire every 4 minutes. Runs as a detached background process.


Level 3: Usage Report

Aggregate token usage and cost across all Claude Code projects and sessions:

context-stats report                     # All time
context-stats report --since-days 30     # Last 30 days
context-stats report --output report.md  # Write to file

The report is a Markdown file with these sections:

SectionWhat you learn
Executive SummaryTotal spend, sessions, projects, cache hit ratio, avg session cost, most expensive project
Model Usage BreakdownCost and token share per model family (Opus / Sonnet / Haiku) with pie chart
Cost OptimizationTop 10 costliest sessions, sessions with low cache efficiency, high-spend projects
Cost EfficiencyOverall cache hit ratio, tokens per dollar, most and least efficient sessions
Daily Activity HeatmapSessions by day-of-week and hour — see when you code and how that affects cost
Weekly TrendSpend and session count per week with charts
Code ProductivityLines changed per dollar and per 1k tokens across projects
Projects TablePer-project: sessions, cost, % of total, tokens, cache hit %, avg cost, dominant model

Example executive summary:

| Metric | Value |
|--------|-------|
| Report Period | 2026-03-08 → 2026-04-07 |
| Total Spend | \$6,413.24 |
| Total Sessions | 764 |
| Projects Analyzed | 58 |
| Cache Hit Ratio | 46.9% |
| Avg Session Cost | \$8.39 |
| Avg Session Duration | 2h 1m 8s |
| Most Expensive Project | agent-skill-manager (\$1,204.58, 18.8% of total) |

Cache reads cost ~10x less than input tokens. Sessions with low cache hit ratios are flagged in the optimization section so you know exactly where to cut costs.


Installation

pip install context-stats
uv pip install context-stats

Add to Claude Code settings:

{
  "statusLine": {
    "type": "command",
    "command": "claude-statusline"
  }
}

Restart Claude Code. The status line, graph dashboard, session export, and report all read the same local state files.


Customization

# ~/.claude/statusline.conf
color_project_name=bright_cyan
color_branch_name=bright_magenta
color_mi_score=#ff9e64
show_mi=true
show_delta=true
token_detail=true

Full palette: 18 named colors + any #rrggbb hex.

cp examples/statusline.conf ~/.claude/statusline.conf

FAQ

Is it free? Yes. MIT licensed, zero external dependencies.

Does it send my data anywhere? No. Session data stays local in ~/.claude/statusline/. Analytics read from ~/.claude/projects/.

What runtimes does it support? Python 3.9+. Install via pip install context-stats.


Get Started

pip install context-stats

Read the docs · View export example · MIT Licensed


Documentation
Contributing

Contributions are welcome. Read CONTRIBUTING.md for development setup, branching, and PR process.

This project follows the Contributor Covenant Code of Conduct.

How It Works (Architecture)

Context Stats hooks into Claude Code's status line feature to track token usage across sessions. The Python statusline script writes state data to local CSV files, which the context-stats CLI reads to render live graphs. Data is stored locally in ~/.claude/statusline/ and never sent anywhere.

Claude Code invokes the statusline script via stdin JSON pipe — the script reads JSON from stdin and writes formatted text to stdout. The report subcommand reads Claude Code's own project logs from ~/.claude/projects/ to aggregate cross-session analytics.

Migration from cc-statusline

If you were using the previous cc-statusline package:

pip uninstall cc-statusline
pip install context-stats

The claude-statusline command still works. The main change is token-graph is now context-stats.

License

MIT

claude-howto · asm · custats.info