agentleFS
luongnv89luongnv89/context-stats/CLAUDE.md

context-stats

CLAUDE.md117 starsChanged 11 months agoMITView on GitHub

context-stats provides real-time context window monitoring for Claude Code sessions. It tracks token consumption over time and displays live ASCII graphs so users can see how much context remains. The statusline is implemented in Python. Claude Code invokes the statusline script via stdin JSON pipe — the script reads JSON from stdin and writes formatted text to stdout. The Python implementation persists state to CSV files read by the context-stats CLI. The standalone statusline lives at scripts/statusline.py (Python 3, state-writing,…

The file

We split this CLAUDE.md into the rules it gives an agent

6 rules. About 0 are common, 5 are distinctive, and 1 is very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈5

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 1

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    After editing anything under src/ or scripts/statusline.py, run from the activated venv:

    line 27
  2. Distinctive:

    Never re-read files you just wrote or edited.

    line 107
  3. Distinctive:

    Never re-run commands to "verify" unless the outcome was uncertain.

    line 108
  4. Distinctive:

    Don't echo back large blocks of code or file contents unless asked.

    line 109
  5. Distinctive:

    If a task needs 1 tool call, don't use 3.

    line 112
  6. Distinctive:

    Do not summarize what you just did unless the result is ambiguous or you need additional input.

    line 113

≈ “Common” is an estimate: at least 1 in 5 of the 12,729 CLAUDE.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
CLAUDE.md

CLAUDE.md

Project Purpose

context-stats provides real-time context window monitoring for Claude Code sessions. It tracks token consumption over time and displays live ASCII graphs so users can see how much context remains.

Implementation

The statusline is implemented in Python. Claude Code invokes the statusline script via stdin JSON pipe — the script reads JSON from stdin and writes formatted text to stdout. The Python implementation persists state to CSV files read by the context-stats CLI. The standalone statusline lives at scripts/statusline.py (Python 3, state-writing, pip-installable via the package).

CSV Format Contract

State files are append-only CSV at ~/.claude/statusline/statusline.<session_id>.state with 15 comma-separated fields. See docs/CSV_FORMAT.md for the full field specification. Key constraint: workspace_project_dir has commas replaced with underscores before writing.

Test Commands

# Python tests (canonical — matches docs/DEVELOPMENT.md agent setup notes)
source venv/bin/activate && pytest tests/python/ -q -p no:cacheprovider

# Coverage (enforces the --cov-fail-under=94 floor from pyproject.toml addopts)
pytest tests/python/ -q -p no:cacheprovider --cov=src/claude_statusline --cov-report=term

Verification Gates

After editing anything under src/ or scripts/statusline.py, run from the activated venv:

ruff check .
mypy src scripts

IMPORTANT: work is not done until lint, typecheck, and tests all pass.

Key Architectural Decisions

  • Append-only CSV state files with rotation at 10,000 lines (keeps most recent 5,000); append+rotation serialized under a best-effort fcntl exclusive lock
  • No network requests — all data stays local in ~/.claude/statusline/
  • Session ID validation — rejects /, \, .., null bytes, plus comma/newline/control characters (CSV safety) for path-traversal and column-shift defense
  • 5-second git command timeout in the Python implementation
  • Config via ~/.claude/statusline.conf — simple key=value pairs

Sync Points: Package vs Standalone Script

The standalone script and the package single-source their shared logic in src/claude_statusline/_shared.py (Tasks 5.2/5.3, closing F-DEAD-001): the package modules import from it under their historical names, and the script loads it via a resolution chain — installed package → byte-identical vendored copy at scripts/_statusline_shared.py (equality enforced by tests/python/test_parity.py) → a repository src/ checkout bootstrap. Manual deployments must therefore ship both scripts/statusline.py and scripts/_statusline_shared.py. The rows below remain the behavioral contract; where both sides consume _shared, a change is made once and the parity suite guards equivalence.

The following logic is paired between the installable package (src/) and the standalone script (scripts/statusline.py) and must be kept in sync when modified:

| Logic | Package (src/) | Standalone Python (scripts/statusline.py) || |------------------------------------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------|| | Config parsing | core/config.py (key tables re-exported from _shared) | read_config() + _apply_config_value() dispatch tables over shared key sets; template hoisted to _DEFAULT_CONF_TEMPLATE || | Color name map | _shared.COLOR_NAMES (re-exported by core/colors.py) | _COLOR_NAMES (bound from the loaded shared module) || | Color parser | _shared.parse_color() (re-exported by core/colors.py) | _parse_color() (bound from the loaded shared module) || | Git info (accepts .git as directory OR worktree/submodule pointer file) | core/git.py:get_git_info() adapter over _shared.git_info() core (branch via _shared.git_branch() dir-keyed TTL cache; change count streamed and capped at _shared._STATUS_CHANGES_CAP, [N+] beyond) | get_git_info bound to the _shared.git_info() core | | PR number lookup | core/git.py:_get_pr_number() (branch from shared _git_branch cache, F-PERF-003) | get_pr_number() (same shared branch cache) | | PR number cache (60s TTL, 10s negative TTL for gh failures, per-branch, ~/.claude/statusline/pr_number_cache.json) | core/git.py:_PR_CACHE_TTL_SECONDS, _PR_CACHE_NEGATIVE_TTL_SECONDS, _pr_cache_file(), _pr_cache_get(), _pr_cache_set() | _PR_CACHE_TTL_SECONDS, _PR_CACHE_NEGATIVE_TTL_SECONDS, _pr_cache_file(), _pr_cache_get(), _pr_cache_set() | | Branch cache (10s TTL, 5s negative TTL, dir-keyed, ~/.claude/statusline/branch_cache.json; hoists the per-render rev-parse) | _shared.git_branch(), _branch_cache_file/_get/_set, _BRANCH_CACHE_*_TTL_SECONDS (re-exported by core/git.py) | same names bound from the loaded shared module | | State rotation (append+rotate serialized under best-effort fcntl exclusive lock; rotation core atomic temp+rename; _ROTATION_SCAN_FLOOR_BYTES byte gate skips the line count below a provable size floor, F-PERF-002) | core/state.py (_lock_state_file/_unlock_state_file, append_entry, _rotate_locked, _maybe_rotate) | _lock_state_file/_unlock_state_file, write site in _render, _rotate_state_file_locked(), maybe_rotate_state_file() || | MI profiles | graphs/intelligence.py:MODEL_PROFILES | MODEL_PROFILES || | MI formula | graphs/intelligence.py:calculate_context_pressure() | compute_mi() || | MI colors | graphs/intelligence.py:get_mi_color() (delegates to _shared.mi_color_name) | _mi_color_ansi() over the shared tier decision (bound as get_mi_color), rendering through an explicit _Palette resolved from config overrides || | Zone indicator | graphs/intelligence.py:get_context_zone() wrapping _shared.context_zone_tuple() into ZoneInfo (incl. the Pricing cost-warning band); threshold overrides travel as the ZoneThresholds dataclass (_ZONE_THRESHOLD_FIELDS lookup table incl. zone_pricing_max, Config extraction via from_config) | get_context_zone = _context_zone_from_config adapter over _shared.context_zone_tuple() (returns a tuple) || | Zone constants | ZONE_1M_*, ZONE_STD_*, LARGE_MODEL_THRESHOLD | same || | Per-property colors | colors.py:ColorManager props, config.py:_COLOR_KEYS | _COLOR_KEYS, per-property vars || | Context group separator (tokens·zone·pacman as ONE atomic part, · unspaced) | cli/statusline.py parts entry usage.context + usage.zone + usage.pacman; zone/pacman built with an INLINE_SEPARATOR prefix (core/colors.py) | same: parts entry context_info + zone_info + pacman_info, "·" prefixes || | Model suffix separator (Model·effort, unspaced) | cli/statusline.py model_suffix (f"·{...}") | model_suffix (f"·{...}") || | Layout / responsive width fit (multi-line reflow) | formatters/layout.py:visible_width(), get_terminal_width(), fit_to_width(), _PART_SEPARATOR | visible_width(), get_terminal_width(), fit_to_width(), _PART_SEPARATOR || | Compaction detection | graphs/statistics.py:detect_compaction_events() | detect_compaction_events() || | Compaction constants | core/config.py:compaction_drop_threshold, compact_mi_warn_threshold | COMPACTION_DROP_THRESHOLD, COMPACT_MI_WARN_THRESHOLD || | tok/s compute (rolling, token-weighted avg over N turns) | graphs/statistics.py:compute_tps(samples, window), format_tps() | compute_tps(samples, window), format_tps() || | tok/s config | core/config.py:show_tps, tps_precision, tps_unit, tps_window | read_config() show_tps/tps_precision/tps_unit/tps_window || | tok/s state field | core/state.py:StateEntry.api_duration_ms (CSV index 14) | state_data list + parse_state_row() api_duration_ms field (CSV index 14) || | tok/s rolling read (bounded tail) | cli/statusline.py:_build_metric_segments() calls core/state.py:StateFile.read_tail(_tps_tail_size(tps_window)) → (output, api_duration_ms) samples (NOT read_history(), which stays full for the CLI graph/export consumers); the read itself is window-bounded from EOF via _shared.tail_window_text with an exact full-read fallback (F-PERF-001) | tail-bounded backward walk over a byte-windowed tail_window_text read, skipping unparseable rows, collecting at most _tps_tail_size(tps_window) samples; full read only when the window cannot satisfy the tail | | tok/s tail size helper | cli/statusline.py:_tps_tail_size(), _TPS_TAIL_BUFFER | _tps_tail_size(), _TPS_TAIL_BUFFER || | State-row parsing (parse_state_row: last-entry + bounded-tail reads replace index-magic CSV access) | claude_statusline/_shared.py:parse_state_row (canonical; vendored byte-identically to scripts/_statusline_shared.py; mirrors StateFile.read_tail skip semantics) | parse_state_row serving the last-line delta read and the tok/s tail loop in _render || | Session cost display ($X.XX, default on) | core/config.py:show_cost, cli/statusline.py cost_info segment + parts, colors.py:ColorManager.cost, _COLOR_KEYS:color_cost | read_config() show_cost, cost_info build + parts, c_cost, _COLOR_KEYS:color_cost || | Effort display (effort.level next to model, default on) | core/config.py:show_effort (dataclass + parse + to_dict + _MINIMAL_CONFIG_FALLBACK), cli/statusline.py extract_payload() effort_level extract (isinstance-guarded effort_data.get("level")) + _render model_suffix; conf comment synced in data/statusline.conf.default + examples/statusline.conf (kept byte-identical by test_config_colors.py) | read_config() show_effort (defaults + parse), effort_level extract + model_suffix, conf comment block || | UTF-8 stdout guard (Windows cp1252 defense, called first in main()) | cli/statusline.py:_ensure_utf8_stdout() (guarded impl; cli/context_stats.py reuses it — single package copy) | _ensure_utf8_stdout() || | Pacman icon mapping (zone → glyph) | graphs/intelligence.py:PACMAN_ICONS, get_pacman_icon() | PACMAN_ICONS, get_pacman_icon() || | Pacman icon display (show_pacman, default on, next to zone label, reuses zone color) | core/config.py:show_pacman (dataclass + parse + to_dict() + fallback), cli/statusline.py _build_usage_segments() pacman build (reuses zone_result/colors.zone_color()) + parts; conf comment synced in data/statusline.conf.default + examples/statusline.conf (kept byte-identical by test_config_colors.py) | read_config() show_pacman (defaults + parse), pacman_info build (reuses zone_word/zone_ansi) + parts, conf comment block || | Session ID validation (path-traversal + CSV-safety defense: rejects /, \, .., null bytes, comma/newline/control chars) | core/state.py:_validate_session_id (enforced in StateFile.__init__), core/state.py:_validate_csv_field (write-time guard for session_id/model_id in StateEntry.to_csv_line), cli/statusline.py early validate-degrade (session_id → None + stderr warning before any path use) | _validate_session_id() + _validate_csv_field()/_sanitize_workspace_dir() (identical source), early validate-degrade in _render, write-site field guard || | External-input extraction (explicit JSON null treated as absent) | cli/statusline.py:extract_payload() over _extract() for all stdin dict chains (workspace/model/context_window/cost/session_id) | _extract() used identically in _render || | Render catch-all (unexpected exceptions → minimal line on stdout, traceback to stderr) | cli/statusline.py:main() wraps _render(data); fallback [Claude] ~ | main() wraps _render(data) with the same fallback || | project_dir trust gate (git/gh only run inside a verified-existing directory) | cli/statusline.py:_resolve_project_dir() gates get_git_info/_get_pr_number | _resolve_project_dir() gates get_git_info/get_pr_number || | State file creation mode (0600, owner-only) | core/state.py:append_entry (os.open(..., 0o600)) | state append in _render (os.open(..., 0o600)) || | Legacy-state migration (guarded move/remove, warns on OSError, never breaks the refresh; sentinel marker skips the sweep after a clean pass, F-PERF-005) | core/state.py:_migrate_old_files (+ _shared.legacy_migration_done/mark_legacy_migration_done) | _migrate_legacy_state_files() (same shared sentinel helpers) || | Named render constants (autocompact ratio, thinking tiers, zone RGB ANSI) | _shared.AUTOCOMPACT_RATIO (default of formatters/tokens.py:calculate_context_usage), THINKING_K_FLOOR/THINKING_K_ROUND_MIN/THINKING_M_THRESHOLD (in _format_thinking_info), ZONE_ORANGE_ANSI/ZONE_AMBER_ANSI/ZONE_DARK_RED_ANSI/ZONE_GRAY_ANSI (in _shared.zone_ansi_code, consumed by core/colors.py:ColorManager.zone_color(), the package's traffic-light map) | _AUTOCOMPACT_RATIO (bound from _shared, used by the context computation); tier + zone-ANSI constants consumed via the bound shared helpers ||

Cross-References

  • docs/ARCHITECTURE.md — system architecture and data flow
  • docs/DEVELOPMENT.md — setup, testing, and contribution guide
  • docs/CSV_FORMAT.md — state file field specification

Token Efficiency

  • Never re-read files you just wrote or edited. You know the contents.
  • Never re-run commands to "verify" unless the outcome was uncertain.
  • Don't echo back large blocks of code or file contents unless asked.
  • Batch related edits into single operations. Don't make 5 edits when 1 handles it.
  • Skip confirmations like "I'll continue..." Just do it.
  • If a task needs 1 tool call, don't use 3. Plan before acting.
  • Do not summarize what you just did unless the result is ambiguous or you need additional input.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.