{"id":47914909,"url":"https://github.com/galando/tokenomics","last_synced_at":"2026-04-15T13:02:54.181Z","repository":{"id":348126451,"uuid":"1196547718","full_name":"galando/tokenomics","owner":"galando","description":"CLI tool which analyzes your Claude Code complete session history, finds behavioral patterns that waste tokens, and coaches you with personalized advice","archived":false,"fork":false,"pushed_at":"2026-04-02T15:47:19.000Z","size":241,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-04-04T05:37:50.244Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/galando.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2026-03-30T20:02:31.000Z","updated_at":"2026-04-02T15:46:36.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/galando/tokenomics","commit_stats":null,"previous_names":["galando/tokenomics"],"tags_count":2,"template":false,"template_full_name":null,"purl":"pkg:github/galando/tokenomics","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/galando%2Ftokenomics","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/galando%2Ftokenomics/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/galando%2Ftokenomics/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/galando%2Ftokenomics/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/galando","download_url":"https://codeload.github.com/galando/tokenomics/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/galando%2Ftokenomics/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":31842193,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-15T11:29:19.690Z","status":"ssl_error","status_checked_at":"2026-04-15T11:29:19.171Z","response_time":63,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2026-04-04T05:31:42.499Z","updated_at":"2026-04-15T13:02:54.175Z","avatar_url":"https://github.com/galando.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Tokenomics — Token Intelligence for Claude Code\n\nA CLI tool that analyzes your Claude Code session history to identify token waste patterns and provide actionable fixes. Runs locally, no LLM needed.\n\n**v2.2** adds human-readable findings with plain-English explanations, collapsible HTML report sections, and evidence-based action items.\n\n**The mental model: tokenomics is a coach, not a remote control.** It writes suggestions into your CLAUDE.md where Claude can see them. Claude is smart enough to follow most of them — suggesting `/compact` when context grows, recommending Sonnet for simple tasks, warning when you're overspending. But it cannot switch models, run commands, or force behavior. The user is always in control.\n\n## Install\n\n```bash\nnpm install -g tokenomics\n```\n\nOr run directly:\n\n```bash\nnpx tokenomics --html\n```\n\n## Quick Start\n\n```bash\n# First time — install hooks + create config\ntokenomics --setup\n\n# Analyze a prompt before sending to Claude\ntokenomics --prompt \"fix the typo in auth.ts\"\n# → Model:   sonnet (85%) — simple task keywords detected\n# → Grade:   A — clean prompt\n# → Savings: ~80% vs opus\n\n# Check your token budget mid-session\ntokenomics --budget\n# → Session: 27% (134K / 500K)\n# → Daily:    7% (134K / 2M)\n# → Project:  1% (134K / 10M)\n\n# Default: analyze session history\ntokenomics                        # Terminal summary\ntokenomics --html                 # HTML dashboard, opens in browser\ntokenomics --json                 # Machine-readable JSON\n```\n\n## How It Works Inside Claude Code\n\nAfter running `tokenomics --setup`, two hooks are installed. They run silently in the background during your Claude Code sessions.\n\n### 1. SessionStart Hook — Behavioral Coaching (automatic)\n\nWhen you start a Claude Code session, the hook runs `tokenomics --inject --quiet`. This:\n\n1. Reads your past session history (JSONL files in `~/.claude/projects/`)\n2. Runs all detectors (context snowball, model selection, vague prompts, etc.)\n3. Writes behavioral insights into your CLAUDE.md between `\u003c!-- TOKENOMICS:START --\u003e` and `\u003c!-- TOKENOMICS:END --\u003e` markers\n\nClaude reads CLAUDE.md at session start and sees instructions like:\n\n```markdown\n\u003c!-- TOKENOMICS:START --\u003e\n## Token Optimization Insights\n\n### Model Usage\n- You use Opus for **50%** of simple tasks. Prefer **Sonnet** for editing,\n  small fixes, and exploration tasks to reduce token usage by ~5x.\n\n### Context Management\n- Your context snowballs at **turn 7** on average.\n  Use `/compact` proactively after turn 5-7.\n\u003c!-- TOKENOMICS:END --\u003e\n```\n\n**What Claude actually does with this:**\n\n| Instruction | What Claude does |\n|------------|-----------------|\n| \"Prefer Sonnet for simple tasks\" | Claude **suggests** switching to Sonnet. You still need to run `/model sonnet` yourself. |\n| \"Use /compact after turn 5-7\" | Claude **suggests** running `/compact` when context grows. You run it. |\n| \"Include file paths in prompts\" | Claude may **remind** you to be specific when you send vague prompts. |\n\nTokenomics cannot switch models or run commands on its own. It writes suggestions into CLAUDE.md, and Claude treats them as behavioral guidance. Think of it as a coach whispering tips — Claude listens, but the user is always in control.\n\n### 2. PostToolUse Hook — Budget Monitoring (automatic)\n\nAfter every tool use (Read, Edit, Bash, etc.), the hook runs `tokenomics --budget-check`. This:\n\n1. Finds the active session JSONL file (most recently modified)\n2. **Tail-reads only the last ~8KB** (not the whole file — keeps it under 200ms)\n3. Sums token usage from the records\n4. Compares against your budget ceilings\n5. If a threshold is crossed (50%, 80%, 90%), updates CLAUDE.md with a budget warning\n\n```\nYour budget config (~/.claude/tokenomics.json):\n  Session: 500K tokens    → warns at 250K (50%), 400K (80%), 450K (90%)\n  Daily:   2M tokens      → same thresholds\n  Project: 10M tokens     → same thresholds\n```\n\nWhen a threshold is crossed, CLAUDE.md gets updated. Claude then **suggests** actions like:\n- At 80%: \"You're at 82% of your session budget. Consider wrapping up.\"\n- At 100%: \"Session budget exceeded. Consider switching to Sonnet with `/model sonnet`.\"\n\n**Important:** The `ceilingAction` setting (`\"warn\"`, `\"downgrade\"`, `\"pause\"`) controls what text gets injected into CLAUDE.md — not what Claude actually does. Claude reads the suggestion but cannot change the model itself.\n\n### 3. Manual Commands — For When You Want More Control\n\n| Command | When to Use |\n|---------|------------|\n| `--prompt \"your prompt\"` | Before a prompt — get model recommendation + quality grade, then manually pick the model |\n| `--budget` | Mid-session — see full budget dashboard with progress bars |\n| `--budget-check` | Used by hooks (silent, exit code 0/1) |\n| `--setup` | One-time — install hooks + create budget config |\n| `--inject` | Manually refresh CLAUDE.md insights |\n\n## How `--prompt` Works\n\n`tokenomics --prompt \"your prompt here\"` analyzes your prompt before you send it to Claude and returns two things:\n\n1. **Model recommendation** — which Claude model is the best fit (and why)\n2. **Quality grade** — whether your prompt will waste tokens\n\n### Model Routing\n\nThe router reads your prompt for complexity signals:\n\n| Signal | Example | Routes to |\n|--------|---------|-----------|\n| Complex keywords | \"design\", \"plan\", \"analyze\", \"refactor\", \"architecture\" | Opus |\n| Simple keywords | \"fix\", \"rename\", \"format\", \"lint\" | Sonnet |\n| URLs or code blocks | `https://...`, `` ```code``` `` | Opus |\n| Very short prompt | \u003c10 words, no file references | Sonnet |\n| Multiple file references | \u003e3 files mentioned | Opus |\n\n**Priority:** Complex signals always win. If your prompt says \"fix the typo\" it routes to Sonnet (~80% cheaper). If it says \"design and implement\" it routes to Opus.\n\n### Prompt Quality Audit\n\nChecks your prompt for common waste patterns and assigns a grade:\n\n| Grade | Meaning |\n|-------|---------|\n| A | Clean — no issues found |\n| B | Minor — small improvements possible |\n| C | Warning — prompt wastes tokens |\n| D | Critical — significant waste |\n\nThe audit detects: pasted code blocks that Claude could read itself, vague prompts without file/function names, over-scoped requests like \"fix everything\", and duplicate context.\n\n### Example\n\n```\n$ tokenomics --prompt \"fix all the bugs everywhere and refactor everything\"\n\nModel:   opus (85%) — complex reasoning keywords detected\nGrade:   B — 2 findings\nWaste:   ~700 tokens\n\n  [info] Low Specificity — Add specific file paths, function names\n  [warning] Over-Scoped Request — Scope the work to specific files\n```\n\n## How the Budget Works\n\nTokenomics tracks your token spend across three scopes:\n\n| Scope | What it measures | Default ceiling |\n|-------|-----------------|----------------|\n| Session | Current active Claude Code session | 500K tokens |\n| Daily | All sessions today (currently: same as session) | 2M tokens |\n| Project | Rolling 30 days (currently: same as session) | 10M tokens |\n\n### How it counts tokens\n\nThe budget reads the **current active session** — the most recently modified JSONL file in `~/.claude/projects/`. It sums `input_tokens + output_tokens + cache tokens` from each assistant message. For the background hook (runs after every tool use), it only reads the last 8KB of the file to keep it fast.\n\n**Current limitation:** Daily and project scopes both read from the same active session file. Aggregation across all session files is planned for a future release. For now, all three scopes show the same number.\n\n### Alert thresholds\n\nEach scope triggers alerts at 50%, 80%, and 90% of its ceiling. Each alert fires **once** — tokenomics remembers which thresholds have already fired.\n\nWhen a scope hits 100%, the `ceilingAction` setting controls what Claude sees:\n\n| Action | What happens |\n|--------|-------------|\n| `warn` (default) | Claude suggests wrapping up or being more concise |\n| `downgrade` | Claude suggests switching to Sonnet (`/model sonnet`) |\n| `pause` | Claude asks for your confirmation before continuing |\n\nThese are suggestions Claude reads from CLAUDE.md — tokenomics cannot force model changes.\n\n### Disable alerts\n\nTo turn off budget alerts entirely:\n\n```bash\n# One-time: run budget check without alerts\ntokenomics --budget --no-alerts\n\n# Persistent: add to config\n# Edit ~/.claude/tokenomics.json and set \"muteAlerts\": true\n```\n\nWhen `muteAlerts` is `true`, the budget check still runs and shows the dashboard, but no alerts are injected into CLAUDE.md.\n\n### Configuration\n\nBudget config lives at `~/.claude/tokenomics.json`:\n\n```json\n{\n  \"sessionCeiling\": 500000,\n  \"dailyCeiling\": 2000000,\n  \"projectCeiling\": 10000000,\n  \"alertThresholds\": [50, 80, 90],\n  \"ceilingAction\": \"warn\",\n  \"muteAlerts\": false\n}\n```\n\n## Options\n\n| Flag | Description | Default |\n|------|-------------|---------|\n| `--prompt \u003ctext\u003e` | Analyze a prompt: model recommendation + quality grade | - |\n| `--budget` | Show token budget dashboard | false |\n| `--budget-check` | Lightweight budget check (for hooks) | false |\n| `--no-alerts` | Suppress budget alerts (no CLAUDE.md injection) | false |\n| `--html` | Generate HTML report and open in browser | false |\n| `--json` | Output JSON (pipe to jq, scripts, etc.) | false |\n| `--report` | Full markdown coaching report | false |\n| `--out \u003cfile\u003e` | Write JSON to file | - |\n| `--days \u003cN\u003e` | Analyze last N days | 30 |\n| `--project \u003cP\u003e` | Filter to specific project path | - |\n| `--claude-dir \u003cpath\u003e` | Claude installation dir (default: auto-detect all `~/.claude*`) | auto |\n| `--fix` | Apply auto-fixable optimizations | false |\n| `--fix --dry-run` | Preview fixes without writing files | false |\n| `--setup` | One-time setup: install hooks + create budget config + initial injection | false |\n| `--inject` | Re-analyze sessions + update CLAUDE.md findings | false |\n| `--quiet` | Suppress terminal output (used by hooks) | false |\n| `--verbose` | Show discovery progress and debug info | false |\n| `--help` | Show help message | - |\n| `--version` | Show version | - |\n\n## What `--fix` Does\n\n1. **Set default model to Sonnet** — edits `~/.claude/settings.json` to make Sonnet the default. This is a real settings change — Claude Code will use Sonnet by default on new sessions (you can still switch with `/model`).\n2. **Remove never-used MCP servers** — edits `~/.claude.json` to remove servers that haven't been used in any of your sessions. Reduces per-session overhead.\n3. **Inject findings into CLAUDE.md** — writes behavioral coaching into your CLAUDE.md (project and global). Claude reads and follows these as suggestions.\n\n## Detectors\n\n| Detector | What It Finds | Potential Savings |\n|----------|--------------|-------------------|\n| Context Snowball | Unbounded context growth | 40%+ |\n| CLAUDE.md Overhead | Oversized config duplication | 5-15% |\n| Model Selection | Suboptimal model choices | 3-5x |\n| MCP Tool Tax | Rarely-used servers | Hidden token cost |\n| Vague Prompts | Prompts requiring clarification | Turn reduction |\n| File Read Waste | Unnecessary file re-reads | I/O + token cost |\n| Bash Output Bloat | Excessive command output | Context pollution |\n| Session Timing | Time-based efficiency patterns | Rate limit optimization |\n| Subagent Opportunity | Delegation opportunities | Parallel execution |\n| Smart Router | Historical routing patterns | ~80% on simple tasks |\n\n## Output Examples\n\n### Terminal\n\n```\n  TOKENOMICS — Token Intelligence for Claude Code\n  60 sessions // 30 day range // v2.2.2\n\n  Sessions:   60\n  Total:     1.2M tokens\n  Cache Hit: 42.3%\n  Issues:    4\n\n  ┌─────────────────────────┬──────────┬────────────┬────────────┐\n  │ Detector                │ Severity │ Savings    │ Confidence │\n  ├─────────────────────────┼──────────┼────────────┼────────────┤\n  │ Context Snowball        │ ● HIGH   │ ~38%       │ 92%        │\n  │ Model Selection         │ ● MED    │ ~15%       │ 85%        │\n  └─────────────────────────┴──────────┴────────────┴────────────┘\n\n  ──────────────────────────────────────────────────────────────\n  ● Your context window ballooned without /compact in 12 of 60 sessions (20%).\n\n  Evidence:\n    Worst: my-project on Mar 24 at 14:30 — context grew 4.2x by message 9,\n    wasting 38K tokens.\n    You were working on: \"refactor the auth module\"\n\n  Impact:    Every message in a snowballed session re-sends the entire\n             conversation history, compounding token cost.\n\n  Action:\n    In my-project, your context typically snowballs around message 9.\n    Run /compact around message 7 — before it grows, not after.\n    When switching to a different task, run /clear instead.\n```\n\n### HTML Report\n\nThe `--html` report now features:\n\n- **Collapsible sections** — Overview, Findings, and Actions sections are open by default and can be collapsed/expanded. State persists via localStorage.\n- **Human-readable finding cards** — Each finding has four parts: headline, evidence, impact, and action. Cards are collapsible and filterable by severity.\n- **Plain-English explanations** — Instead of jargon like \"turn 8 snowball detected\", findings say \"your context typically snowballs around message 9 in my-project — run /compact around message 7\".\n\n```bash\ntokenomics --html    # Opens interactive report in browser\n```\n\n### Prompt Analysis\n\n```\n$ tokenomics --prompt \"design a multi-tenant database schema with row-level security\"\n\nModel:   opus (85%) — complex reasoning keywords detected\nGrade:   A — clean prompt\n```\n\n### Budget Dashboard\n\n```\n$ tokenomics --budget\n\nToken Budget Status\n==================================================\n\nSESSION: 82%\n  ██████████████████████████████████████░░░░░░░░░░\n  410,000 / 500,000 tokens\n\nDAILY: 55%\n  ███████████████████████████░░░░░░░░░░░░░░░░░░░░\n  1,100,000 / 2,000,000 tokens\n\nPROJECT: 32%\n  ████████████████░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░\n  3,200,000 / 10,000,000 tokens\n```\n\n## Privacy\n\n- **Local-only**: No network calls, no telemetry\n- **No API keys required**: Reads Claude Code's existing session files\n- **No data leaves your machine**: All processing happens locally\n\n## Development\n\n```bash\nnpm install        # Install dependencies\nnpm run build      # Compile TypeScript\nnpm test           # Run tests\nnpm run typecheck  # Type checking\nnpm run dev        # Watch mode\n```\n\n## Requirements\n\n- Node.js \u003e= 18\n- Claude Code installed (for session data to analyze)\n\n## License\n\nMIT\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgalando%2Ftokenomics","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fgalando%2Ftokenomics","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgalando%2Ftokenomics/lists"}