{
  "markdown": "<div align=\"center\">\n\n# 🧠 claude-context-monitor\n\n### Stop losing work to silent context overflows.\n\nA [Claude Code](https://docs.claude.com/en/docs/claude-code) plugin that watches your context window in real time, predicts when you'll hit the limit, and warns you **before** it's too late — then makes your `/compact` actually remember what matters.\n\n<br/>\n\n[![Version](https://img.shields.io/badge/version-1.1.3-3b82f6?style=flat-square)](https://github.com/fomyio/claude-context-monitor/releases)\n[![License: MIT](https://img.shields.io/github/license/fomyio/claude-context-monitor?style=flat-square&color=22c55e)](LICENSE)\n[![Node](https://img.shields.io/badge/node-%E2%89%A5%2018-339933?style=flat-square&logo=node.js&logoColor=white)](https://nodejs.org)\n[![Platform](https://img.shields.io/badge/platform-macOS%20%7C%20Linux-64748b?style=flat-square)](#requirements)\n[![Claude Code](https://img.shields.io/badge/Claude%20Code-plugin-d97757?style=flat-square)](https://docs.claude.com/en/docs/claude-code/plugins)\n\n[![Stars](https://img.shields.io/github/stars/fomyio/claude-context-monitor?style=flat-square&color=eab308)](https://github.com/fomyio/claude-context-monitor/stargazers)\n[![Issues](https://img.shields.io/github/issues/fomyio/claude-context-monitor?style=flat-square)](https://github.com/fomyio/claude-context-monitor/issues)\n[![Last commit](https://img.shields.io/github/last-commit/fomyio/claude-context-monitor?style=flat-square&color=8b5cf6)](https://github.com/fomyio/claude-context-monitor/commits)\n[![PRs welcome](https://img.shields.io/badge/PRs-welcome-ff69b4?style=flat-square)](#contributing)\n\n<br/>\n\n**[Quick start](#quick-start)** · **[Features](#features)** · **[How it works](#how-the-scoring-works)** · **[Configuration](#configuration)** · **[Cost](#cost)** · **[Privacy](#privacy)** · **[Contributing](#contributing)**\n\n</div>\n\n![ClaudeContextPlugin-ezgif com-optimize](https://github.com/user-attachments/assets/9666a5a8-bede-4493-8a36-34e92b6e1ad8)\n\n---\n\n<details>\n<summary><b>📑 Table of contents</b></summary>\n\n- [Why this exists](#why-this-exists)\n- [Quick start](#quick-start)\n- [Features](#features)\n- [How the scoring works](#how-the-scoring-works)\n- [Smart Compact Instructions](#smart-compact-instructions)\n- [Architecture](#architecture)\n- [Requirements](#requirements)\n- [Installation](#installation)\n- [Configuration](#configuration)\n- [CLI dashboard](#cli-dashboard)\n- [Hooks](#hooks)\n- [Cost](#cost)\n- [Privacy](#privacy)\n- [Project structure](#project-structure)\n- [Contributing](#contributing)\n- [Uninstalling](#uninstalling)\n- [License](#license)\n\n</details>\n\n---\n\n## Why this exists\n\nClaude Code's context window fills up — and when it does, your session ends abruptly, mid-refactor or mid-debug. You get no warning. You just hit a wall.\n\nThree problems, one plugin:\n\n| Problem | What it feels like | How this plugin fixes it |\n|---------|--------------------|--------------------------|\n| **No warning** | The session dies with no heads-up | A live token bar + desktop alerts at 70 / 85 / 95% |\n| **Bad timing** | Compact too early and waste a session; too late and lose context | A semantic score tells you *when* — and *why* |\n| **Cumulative amnesia** | Each `/compact` summarizes the last summary, so after 2–3 rounds key decisions vanish | Carry-forward memory injected into the compact prompt |\n\n> The amnesia problem is well documented — see [anthropics/claude-code#33212](https://github.com/anthropics/claude-code/issues/33212), [#28721](https://github.com/anthropics/claude-code/issues/28721), and [#3288](https://github.com/anthropics/claude-code/issues/3288).\n\n---\n\n## Quick start\n\n```bash\n# 1. Add this repo as a plugin marketplace\n/plugin marketplace add fomyio/claude-context-monitor\n\n# 2. Install the plugin\n/plugin install context-monitor@claude-context-monitor\n\n# 3. Reload, then start a new session — the token bar appears immediately\n/reload-plugins\n```\n\nThat's it — the five hooks register automatically. For the semantic compact scoring, the plugin uses your existing `ANTHROPIC_API_KEY` (see [API key](#api-key-for-the-haiku-evaluation)); everything else works with no key.\n\n> **Tip:** prefer manual setup or want to disable the API eval entirely? See [Installation](#installation) and [SETUP.md](SETUP.md).\n\n---\n\n## Features\n\n### 1. Real-time context monitoring\n\nEvery message, the plugin injects a status line into Claude's context:\n\n```text\n[CTX] 🟢 [████░░░░░░░░░░░░░░░░] 22.1% | 44K/200K | ~124 turns left\n```\n\nAs the session grows, the color shifts 🟢 → 🟡 → 🔴 so you always know where you stand.\n\n### 2. Smart compact recommendations\n\nAbove 45% usage, the plugin sends a lightweight fingerprint of your recent conversation to **Claude Haiku** (~$0.0005/call) and asks: *is this prompt a continuation, or a new topic?* It then scores the situation and escalates:\n\n```text\n[CTX] 💡 Suggestion: You might want to /compact (Topic drift detected)\n[CTX] ⚠️  Warning: Good time to /compact soon (Score 47)\n[CTX] 🚨 URGENT: Strongly recommend running /compact now (Score 71)\n```\n\n### 3. Smart Compact Instructions — *solves cumulative amnesia*\n\nWhen you run `/compact`, the plugin doesn't just tell you *when* — it tells Claude *what to keep and what to drop*, and carries the previous summary forward verbatim. See [Smart Compact Instructions](#smart-compact-instructions).\n\n### 4. Desktop notifications\n\nNative alerts (macOS `osascript` / Linux `notify-send`) at **70%, 85%, and 95%** usage — so you're never caught off guard, even away from the terminal.\n\n### 5. Status line integration\n\nA real-time status bar in Claude Code's UI showing usage, turns left, cost, cache efficiency, and the active model:\n\n```text\n🟢 [████░░░░░░░░░░░░░░░░] 22.1% · 44K/200K · ~124 turns · $0.012 · eff 74% · Opus 4.8\n```\n\nThe model label tracks the **live** model and updates the moment you switch models mid-session — the context-window size shown is always the limit for the model currently in use.\n\n---\n\n## How the scoring works\n\nEvery prompt is scored across four signals:\n\n| Signal | Points | What it measures |\n|--------|:------:|------------------|\n| Token pressure | 0–40 | How full the context is right now |\n| Task completion | 0–20 | Whether Claude's last response signals the task is done |\n| Relevance drift | 0–30 | How related the new prompt is to the session (via Haiku) |\n| Conversation age | 0–10 | How long since the last compact |\n\nThe total drives the recommendation (all thresholds configurable):\n\n| Score | Action |\n|:-----:|--------|\n| 0–25 | 🟢 Silent token bar only |\n| 26–45 | 💡 Suggestion |\n| 46–65 | ⚠️ Warning |\n| 66–79 | 🚨 Urgent |\n| 80+ | 🛑 Block prompt until compacted *(opt-in via `block_on_critical`)* |\n\n---\n\n## Smart Compact Instructions\n\nClaude Code's native compaction summarizes the *previous summary*, not the original conversation — so after a few rounds, key decisions and file paths are lost. This plugin injects **dynamic, context-aware instructions** into the compact prompt via the `PreCompact` hook.\n\n<details>\n<summary><b>1. Carry-forward memory (solves amnesia)</b></summary>\n\n<br/>\n\nThe full summary from the *previous* compaction is preserved verbatim under a \"Historical Context\" section, creating a cumulative memory chain that prevents exponential fidelity loss.\n\n```text\n--- PREVIOUS COMPACT SUMMARY (PRESERVE VERBATIM) ---\nThis is a summary from a previous compaction in this session.\nYou MUST include this content in your new summary under a\n\"Historical Context\" section. Do NOT discard or paraphrase it.\n\nSession involved refactoring authentication module. Key decisions:\nswitched from JWT to session-based auth, updated middleware in auth.ts.\n```\n\n</details>\n\n<details>\n<summary><b>2. Topic-aware summarization (solves \"what to keep\")</b></summary>\n\n<br/>\n\nThe advisor's Haiku-based drift detection marks which topics are **stale** (summarize aggressively) vs **active** (preserve in full detail).\n\n```text\n--- TOPIC HISTORY ---\nTopic shifts detected during this session:\n  [1] Turn 5: auth refactor\n  [2] Turn 18: API rate limiting [drifted]\n  [3] Turn 34: deployment config\nActive topic: deployment config (preserve in FULL detail)\nStale topics: auth refactor, API rate limiting\nFor stale topics: summarize AGGRESSIVELY — keep only final decisions and outcomes.\n```\n\n</details>\n\n<details>\n<summary><b>3. Task completion signaling (solves \"what to drop\")</b></summary>\n\n<br/>\n\nThe advisor detects whether your current task is complete, partial, or in progress:\n\n- **COMPLETE** → \"It is SAFE to compact this task's details aggressively. Preserve only final decisions.\"\n- **IN PROGRESS** → \"Do NOT compact away the active debugging state or work-in-progress.\"\n- **UNRELATED topic shift** → \"The user has started a new topic. Previous context is STALE. Summarize aggressively.\"\n\n</details>\n\n<details>\n<summary><b>4. Compaction history warning</b></summary>\n\n<br/>\n\nAfter 3+ compactions, the prompt explicitly warns about cumulative quality degradation:\n\n```text\n--- COMPACTION HISTORY ---\nThis session has been compacted 3 time(s) before.\nWARNING: Multiple compactions cause cumulative context loss.\nBe EXTRA thorough in preserving key decisions, file paths, and\nuser-stated constraints. Include the Historical Context section.\n```\n\n</details>\n\nAll data flows through a per-session state file — no external services, no API calls beyond the existing Haiku eval.\n\n---\n\n## Architecture\n\n<details>\n<summary><b>Show the full data flow</b></summary>\n\n<br/>\n\n```text\nSessionStart\n  └── session-init.sh\n        Creates per-session state file, checks CLAUDE.md bloat,\n        sets up the statusline wrapper\n\nEvery prompt (UserPromptSubmit)\n  └── check.sh (orchestrator)\n        ├── analyze.js\n        │     Reads the JSONL transcript → token counts\n        │     Burn rate, turns left, cache efficiency, cost\n        │     (prefers Claude Code's ground-truth context_window data)\n        │\n        ├── [if usage > 45%] advisor.js\n        │     fingerprint.js → last 5 turns summary\n        │     → Claude Haiku API (~$0.0005)\n        │     Scores: token_pressure + task_completion + drift + age\n        │     Persists: topic shifts, active_task to state\n        │     Returns: score, action, recommendation text\n        │\n        └── stdout → injected into Claude's context\n            osascript / notify-send → desktop notification\n\nAfter each response (Stop hook, background)\n  └── update-state.sh\n        Persists token history, burn rate to state (atomic write)\n        Writes tmux status file (if enabled)\n\n/compact lifecycle\n  ├── pre-compact.sh  → Smart Compact Instructions (carry-forward, topics, task, count)\n  └── post-compact.sh → saves full summary for carry-forward, resets, notifies\n\nStatus line (real-time, from Claude Code UI)\n  └── statusline.sh\n        Reads Claude Code's native context_window data + live model\n        Augments with burn rate, turns left, cache efficiency\n        🟢 [████░░░] 22.1% · 44K/200K · ~124 turns · $0.012 · eff 74% · Opus 4.8\n```\n\nAll writers read-fresh and write atomically (temp + rename), and pass every value to `node` via the environment — never interpolated into script source.\n\n</details>\n\n---\n\n## Requirements\n\n- **Node.js ≥ 18**\n- **Claude Code**\n- **macOS or Linux** (desktop notifications use `osascript` / `notify-send`; Windows is not yet supported)\n- *(Optional)* an **`ANTHROPIC_API_KEY`** for the Haiku relevance evaluation\n\n---\n\n## Installation\n\n### Plugin marketplace (recommended)\n\n```bash\n/plugin marketplace add fomyio/claude-context-monitor\n/plugin install context-monitor@claude-context-monitor\n/reload-plugins\n```\n\n<details>\n<summary><b>Manual installation</b></summary>\n\n<br/>\n\n```bash\n# Clone into your plugins directory\nmkdir -p ~/.claude/plugins\ngit clone https://github.com/fomyio/claude-context-monitor.git ~/.claude/plugins/context-monitor\n\n# Install dependencies\ncd ~/.claude/plugins/context-monitor\nnpm install\n\n# Register hooks — merge hooks/settings-snippet.json into ~/.claude/settings.json\n```\n\n</details>\n\n### API key for the Haiku evaluation\n\nThe plugin uses `ANTHROPIC_API_KEY` from your Claude Code session automatically. If it's not in your environment:\n\n```bash\necho \"sk-ant-...\" > ~/.anthropic_key\nchmod 600 ~/.anthropic_key\n```\n\nThe token bar, notifications, and status line work **without** a key — only the topic-drift scoring needs one. See [SETUP.md](SETUP.md) for alternatives (custom key command, or disabling the eval entirely).\n\n---\n\n## Configuration\n\nAll settings live in `config.json`. The defaults work well out of the box.\n\n<details>\n<summary><b>Show all configuration options</b></summary>\n\n<br/>\n\n```jsonc\n{\n  // Toggle the Haiku relevance evaluation (disable to save API calls)\n  \"relevance_eval_enabled\": true,\n\n  // Only run the eval above this usage percentage (saves cost at low usage)\n  \"relevance_eval_threshold_pct\": 45,\n\n  // Shell command that prints your API key (fallback when ANTHROPIC_API_KEY is unset)\n  \"anthropic_api_key_cmd\": \"cat ~/.anthropic_key\",\n\n  // Desktop notification thresholds (percentage)\n  \"notify_thresholds\": { \"info\": 70, \"warning\": 85, \"critical\": 95 },\n\n  // Compact score thresholds\n  \"compact_score_thresholds\": {\n    \"suggest\": 26,   // 💡 soft suggestion\n    \"warn\": 46,      // ⚠️  warning\n    \"urgent\": 66,    // 🚨 urgent\n    \"block\": 80      // 🛑 block the prompt (requires block_on_critical: true)\n  },\n\n  // Set to true to hard-block prompts when score >= block threshold\n  \"block_on_critical\": false,\n\n  // How many recent turns to include in the relevance fingerprint\n  \"fingerprint_max_turns\": 5,\n\n  // Number of recent turns used for burn-rate calculation\n  \"burn_rate_window_turns\": 4,\n\n  // Warn if CLAUDE.md exceeds this % of the context limit\n  \"claude_md_bloat_threshold_pct\": 15,\n\n  // Status line integration\n  \"statusline_enabled\": true,\n\n  // Write context status to a file for a tmux status bar (opt-in)\n  \"tmux_status_enabled\": false,\n  \"tmux_status_file\": \"/tmp/claude-ctx-status\",\n\n  // Where per-session state is stored\n  \"state_dir\": \"~/.claude/plugins/context-monitor/state\",\n\n  // Per-model context limits (tokens). Claude Code's live value overrides these.\n  \"context_limits\": {\n    \"claude-opus-4-7\": 200000,\n    \"claude-opus-4-6\": 200000,\n    \"claude-opus-4-5\": 200000,\n    \"claude-opus-4\": 200000,\n    \"claude-sonnet-4-6\": 200000,\n    \"claude-sonnet-4-5\": 200000,\n    \"claude-haiku-4-5\": 200000\n  },\n\n  // Per-model pricing (USD per million input tokens)\n  \"model_prices_per_million_input\": {\n    \"claude-opus-4-7\": 15.00,\n    \"claude-opus-4-6\": 15.00,\n    \"claude-opus-4-5\": 15.00,\n    \"claude-opus-4\": 15.00,\n    \"claude-sonnet-4-6\": 3.00,\n    \"claude-sonnet-4-5\": 3.00,\n    \"claude-haiku-4-5\": 0.80\n  }\n}\n```\n\n> The static `context_limits` table is only a fallback — when Claude Code reports a live `limit_tokens` (e.g. a 1M-token model), the plugin uses that instead, so the bar always reflects the model actually in use.\n\n</details>\n\n---\n\n## CLI dashboard\n\nSee a summary of your current session at any time:\n\n```bash\ncontext-monitor report   # or: node src/dashboard.js\n```\n\n```text\nSession: 34 turns | 47 min | Sonnet 4.6\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\nContext:  [████████████████████░░░░░░░░░░░░░░░░░░░░]  51.3%  (103K / 200K)\nCost:     ~$0.041 this session  |  Cache eff: 74%\nBurn:     ~8200 tokens/turn   |  ~12 turns remaining\nTopics:   [auth refactor → API rate limiting]\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\nRecommendation: ⚠️ Warning — Context threshold high. Consider /compact.\n```\n\n---\n\n## Hooks\n\nThe plugin registers five Claude Code hooks (`hooks/hooks.json`):\n\n| Hook | Script | Purpose |\n|------|--------|---------|\n| `SessionStart` | `hooks/session-init.sh` | Initialize per-session state, check CLAUDE.md bloat, set up statusline |\n| `UserPromptSubmit` | `hooks/check.sh` | Run token analysis + advisor scoring, inject the status line |\n| `Stop` | `hooks/update-state.sh` | Persist token history and stats after each response *(background)* |\n| `PreCompact` | `hooks/pre-compact.sh` | Inject Smart Compact Instructions before summarization |\n| `PostCompact` | `hooks/post-compact.sh` | Save the compact summary for carry-forward, reset state, notify |\n\n---\n\n## Cost\n\nThe Haiku eval only activates **above 45%** context usage.\n\n| Usage pattern | Estimated monthly cost |\n|---------------|:----------------------:|\n| Normal use | **~$0.05 – $0.15** |\n| Heavy use (≈1000 turns/mo) | **~$0.50** |\n\nEach eval is a single Haiku call over a ~400–600 token conversation fingerprint (≈$0.0005). With the eval disabled (`relevance_eval_enabled: false`), the plugin costs **$0** to run.\n\n---\n\n## Privacy\n\nThe plugin runs entirely on your machine. The **only** outbound network call is the optional Haiku relevance eval, which sends a short fingerprint of your recent turns to the Anthropic API — and only above 45% usage, only if enabled. No telemetry, no third-party services. Full details in **[PRIVACY.md](PRIVACY.md)**.\n\n---\n\n## Project structure\n\n<details>\n<summary><b>Show the file tree</b></summary>\n\n<br/>\n\n```text\nclaude-context-monitor/\n├── .claude-plugin/\n│   ├── plugin.json           # Plugin manifest (name, version, author)\n│   └── marketplace.json      # Marketplace manifest for /plugin install\n├── hooks/\n│   ├── hooks.json            # Hook registrations (${CLAUDE_PLUGIN_ROOT} paths)\n│   ├── settings-snippet.json # Manual install: merge into settings.json\n│   ├── session-init.sh       # SessionStart — initialize session state\n│   ├── check.sh              # UserPromptSubmit — main orchestrator\n│   ├── update-state.sh       # Stop — persist stats after each response\n│   ├── pre-compact.sh        # PreCompact — smart compact instructions\n│   └── post-compact.sh       # PostCompact — save summary, reset state\n├── src/\n│   ├── analyze.js            # Token analyzer: reads the JSONL transcript\n│   ├── advisor.js            # Scoring engine: Haiku eval + compact score\n│   ├── fingerprint.js        # Context summarizer: builds the Haiku input\n│   ├── statusline.sh         # Claude Code status line integration\n│   ├── notify.sh             # Desktop notifications (macOS + Linux)\n│   ├── dashboard.js          # CLI report (bin: context-monitor)\n│   └── uninstall.sh          # Clean uninstall script\n├── docs/\n│   ├── HOMEPAGE.md           # Plugin homepage\n│   ├── PLAN.md               # Implementation plan / roadmap\n│   ├── PRIVACY.md            # Privacy details\n│   └── MARKETPLACE_SUBMISSION.md\n├── config.json               # User-configurable thresholds + settings\n├── SETUP.md                  # API key setup guide\n├── PRIVACY.md                # Privacy policy\n├── LICENSE                   # MIT\n└── package.json\n```\n\nPer-session state lives outside the repo, under `~/.claude/plugins/context-monitor/state/` (configurable via `state_dir`).\n\n</details>\n\n---\n\n## Contributing\n\nContributions are welcome!\n\n<details>\n<summary><b>Getting started, branch naming, and PR checklist</b></summary>\n\n<br/>\n\n```bash\ngit clone https://github.com/fomyio/claude-context-monitor.git\ncd claude-context-monitor\nnpm install\n```\n\n**Branch naming**\n\n| Prefix | Purpose |\n|--------|---------|\n| `feature/` | New features |\n| `fix/` | Bug fixes |\n| `refactor/` | Code restructuring |\n| `docs/` | Documentation |\n| `chore/` | Maintenance, dependencies |\n\nAlways branch off `main`:\n\n```bash\ngit checkout main && git pull origin main\ngit checkout -b feature/your-feature-name\n```\n\n**Before submitting a PR**\n\n- [ ] `npm install` succeeds\n- [ ] `node --check src/*.js` and `bash -n hooks/*.sh src/*.sh` pass\n- [ ] All hooks run without errors in a live Claude Code session\n- [ ] `node src/analyze.js <transcript> <model> <session_id>` returns valid JSON\n- [ ] No secrets, `.env` files, or API keys committed\n- [ ] Commits follow [Conventional Commits](https://www.conventionalcommits.org): `type(scope): description`\n\n**In scope:** hook improvements, platform support (e.g. Windows notifications), opt-in config features, richer dashboard output, tests for `analyze.js` / `advisor.js`.\n\n**Out of scope:** breaking `config.json` key renames, requiring internet for core functionality, runtime deps beyond the Anthropic SDK.\n\n**Reporting issues** — include your OS + Claude Code version, sample `analyze.js` output (redacted), your `config.json` (redact keys), and the exact hook output. Open an issue [here](https://github.com/fomyio/claude-context-monitor/issues).\n\n</details>\n\n---\n\n## Uninstalling\n\n```bash\n/plugin uninstall context-monitor@claude-context-monitor\n```\n\nOr manually:\n\n```bash\nbash ${CLAUDE_PLUGIN_ROOT}/src/uninstall.sh\n```\n\nThis removes the statusline entry from `settings.json`, cleans up the statusline wrapper, and removes orphaned cache directories.\n\n---\n\n## License\n\n[MIT](LICENSE) — built by [Mosaab](https://fomy.io).\n\n<div align=\"center\">\n<br/>\n<sub>If this plugin saved you from a lost session, consider giving it a ⭐ — it helps others find it.</sub>\n</div>\n",
  "bytes": 20992,
  "sha": "14391ec6733cfcaf6cdbe5319a3e9f957a7e5c3f830d4b3ca34989349eadff24",
  "repo_slug": "fomyio/claude-context-monitor",
  "fonte": "repo",
  "truncated": false,
  "api": "https://agentalog.com/api/listings/plg_fomyio_claude_context_monitor_claude_con_852fe769/readme"
}