Skip to content

Latest commit

 

History

History
357 lines (254 loc) · 11.4 KB

File metadata and controls

357 lines (254 loc) · 11.4 KB
context-stats

Know your context zone. Act before Claude degrades.

PyPI version PyPI Downloads GitHub stars License: MIT

Real-time context window monitoring for Claude Code. Five zones tell you exactly what to do next — keep coding, finish up, export your session, or restart.

Get Started →


How It Works

graph LR
    A["Claude Code session"] --> B["Python statusline script"]
    B --> C["Context zone + MI score"]
    B --> D["Local CSV state file"]
    D --> E["Live graph dashboard"]
    D --> F["Session export report"]
    D --> G["Cross-project analytics"]
    E --> H["Delta · Cumulative · Cache · MI · I/O"]
    F --> I["Snapshot · Takeaways · Timeline · Charts"]
    G --> J["Cost · Tokens · Patterns · Sessions"]
Loading
  1. Claude Code pipes session JSON to the Python statusline script on every refresh.
  2. The script computes zone, Model Intelligence (MI) score, and displays a compact status line.
  3. The CLI reads local state files for live charts, session reports, and cross-project analytics.
  4. Everything stays local — ~/.claude/statusline/ for session state, ~/.claude/projects/ for analytics.

Context Zones

Five zones with a clear action for each:

Zone Color Meaning Do this now
Planning Green Plenty of room Keep planning and coding
Code-only Yellow Context tightening Finish the current task, no new plans
Dump Orange Quality declining Wrap up and prepare to export
ExDump Dark red Near hard limit Start a new session
Dead Gray Exhausted Stop — nothing productive left

Thresholds are model-size-aware: 1M context models use absolute token counts (70k/100k/250k/275k); standard models use utilization ratios (40%/70%/75%). Both are configurable.

Plan zone Code zone Dump zone
Plan zone Code zone Dump zone

Status Line

A single line in your Claude Code terminal that shows everything at a glance:

my-project | main [3] | 64,000 free (32.0%) | Code | MI:0.918 | +2,500 | Opus 4.6 | abc-123
Element What it tells you
my-project Current directory
main [3] Git branch + uncommitted changes
64,000 free (32.0%) Available tokens and utilization
Code Current context zone (color-coded)
MI:0.918 Model Intelligence score — how sharp the model still is
+2,500 Tokens consumed since last refresh
Opus 4.6 Active model
abc-123 Session ID (double-click to copy)

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

Green status Warning state
Green statusline Yellow statusline

Customization

Every element has its own color key. Override per-property or set hex values:

# ~/.claude/statusline.conf
color_project_name=bright_cyan
color_branch_name=bright_magenta
color_mi_score=#ff9e64
color_green=#7dcfff
color_yellow=#e0af68
color_red=#f7768e
show_mi=true
show_delta=true
token_detail=true

Full palette: 18 named colors + any #rrggbb hex. Copy the annotated example to get started:

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

Model Intelligence (MI)

MI estimates how well Claude performs at the current context fill level. It is a single number from 0.000 to 1.000 calibrated from the MRCR v2 8-needle long-context retrieval benchmark.

MI(u) = max(0, 1 - u^β)

Each model family has a measured beta:

Model β MI at 50% MI at 75%
Opus 4.6 1.8 0.713 0.404
Sonnet 4.6 1.5 0.646 0.350
Haiku 4.5 1.2 0.565 0.292

Color-coded: green (>0.70, operating well), yellow (0.40–0.70, pressure building), red (<0.40, start new session). Override the curve with mi_curve_beta=1.5 in config.


Live Graph Dashboard

context-stats <session_id> graph               # Context growth per interaction (default)
context-stats <session_id> graph --type all    # All graphs
Graph What it answers
delta How many tokens each interaction consumed
cumulative Total context used over the session
cache Cache creation and read tokens over time, with 5-min TTL countdown
mi How MI degraded across the session
io Input/output token breakdown
both Cumulative + delta side by side

Auto-refreshes every 2 seconds (flicker-free). Pass -w 5 to slow it down or --no-watch to show once.

Context growth Cumulative graph Cache activity
Delta graph Cumulative graph Cache graph
MI over time
Model Intelligence view

Cross-Project Analytics

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

context-stats report                     # Full analytics report (all time)
context-stats report --since-days 30     # Last 30 days only
context-stats report --output report.md  # Write to specific file

The report breaks down every token dollar spent across projects, models, and sessions:

## Grand Totals

- Total Tokens: 128,254,398
  - Input: 19,574,606 · Output: 46,329,340
  - Cache Creation: 1,835,113 · Cache Read: 60,515,339
- Total Cost: $6,292.64
- Total Sessions: 751 across 59 projects
Section What you learn
Grand Totals Total spend, token breakdown (input/output/cache), session count
Per-project breakdown Which projects consume the most tokens and cost the most
Top sessions Heaviest sessions per project — identify costly workflows
Cache efficiency Cache read vs. cache creation ratio — high read ratio means good reuse
Token composition How much of your spend is output (expensive) vs. cache reads (cheap)

Cache reads cost ~10x less than input tokens. The report makes cache efficiency visible so you can optimize session structure.


Session Export

Export a full session report when you need the timeline, charts, and analysis in one Markdown file:

context-stats <session_id> export --output report.md
Section Contents
Executive Snapshot Model, project, duration, interactions, final zone, cache activity
Summary Window size, token totals, cost, final MI
Key Takeaways Short read of what changed
Visual Summary Mermaid charts: context, zones, cache, composition
Interaction Timeline Per-interaction context, MI, and zone history

Example output:

## Executive Snapshot
| Signal | Value | Why it matters |
|--------|-------|----------------|
| Session | `8bb55603-...` | Link back to source session |
| Project | claude-howto | Identify where the report came from |
| Model | claude-sonnet-4-6 | See which model produced the session |
| Duration | 59m 32s | Relate context growth to session length |
| Interactions | 135 | Show how active the session was |
| Final usage | 129,755 (64.9%) | See how close the session got to the limit |
| Final zone | Dump zone | See 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. A background heartbeat prevents expensive cache misses during pauses.

context-stats <session_id> cache-warm on 30m
context-stats <session_id> cache-warm off

Heartbeats fire every 4 minutes (under the 5-min TTL). Runs as a detached background process on Unix, subprocess fallback on Windows.


Installation

pip

pip install context-stats

uv

uv pip install context-stats

Claude Code setup

Add to your Claude Code settings:

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

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


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 only. 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