{"id":48337341,"url":"https://github.com/dhanushkumarsivaji/kerf-cli","last_synced_at":"2026-06-02T06:01:05.200Z","repository":{"id":349243345,"uuid":"1201564756","full_name":"dhanushkumarsivaji/kerf-cli","owner":"dhanushkumarsivaji","description":"Cost intelligence for Claude Code. Real-time dashboards, pre-flight estimation, budgets, and ghost token auditing.","archived":false,"fork":false,"pushed_at":"2026-05-31T18:25:41.000Z","size":2661,"stargazers_count":5,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-05-31T19:24:31.973Z","etag":null,"topics":["anthropic","claude","claude-code","cli","cost-intelligence","developer-tools","token-optimization","typescript"],"latest_commit_sha":null,"homepage":"https://www.npmjs.com/package/kerf-cli","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/dhanushkumarsivaji.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","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-04-04T21:09:16.000Z","updated_at":"2026-05-31T18:25:44.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/dhanushkumarsivaji/kerf-cli","commit_stats":null,"previous_names":["dhanushkumarsivaji/kerf","dhanushkumarsivaji/kerf-cli"],"tags_count":8,"template":false,"template_full_name":null,"purl":"pkg:github/dhanushkumarsivaji/kerf-cli","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dhanushkumarsivaji%2Fkerf-cli","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dhanushkumarsivaji%2Fkerf-cli/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dhanushkumarsivaji%2Fkerf-cli/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dhanushkumarsivaji%2Fkerf-cli/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/dhanushkumarsivaji","download_url":"https://codeload.github.com/dhanushkumarsivaji/kerf-cli/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dhanushkumarsivaji%2Fkerf-cli/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":33808702,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-06-02T02:00:07.132Z","response_time":109,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"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":["anthropic","claude","claude-code","cli","cost-intelligence","developer-tools","token-optimization","typescript"],"created_at":"2026-04-05T03:03:19.180Z","updated_at":"2026-06-02T06:01:05.178Z","avatar_url":"https://github.com/dhanushkumarsivaji.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# kerf-cli\n\n**Know exactly what you're spending on AI coding — before it surprises you.**\n\n[![npm version](https://img.shields.io/npm/v/kerf-cli)](https://www.npmjs.com/package/kerf-cli)\n[![CI](https://github.com/dhanushkumarsivaji/kerf-cli/actions/workflows/ci.yml/badge.svg)](https://github.com/dhanushkumarsivaji/kerf-cli/actions/workflows/ci.yml)\n[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)\n[![Node 20+](https://img.shields.io/badge/node-20%2B-green.svg)]()\n\n![kerf dashboard](docs/assets/dashboard.png)\n\n\u003e Real screenshot from a live machine — `$178.04 spent in the last 7 days, 25 sessions, 98% cache hit rate, 37% of weekly budget used, $141/mo potential savings`.\n\n---\n\n## What is kerf?\n\nIf you use **Claude Code**, **Codex CLI**, or other AI coding agents, you're spending real money on every token. kerf is a free, local CLI tool that:\n\n- **Tracks** every AI coding session automatically — no setup beyond a one-time `kerf init`\n- **Shows** how much you've spent, by model, by project, by tool, by day\n- **Alerts** you the instant a session starts running away (runaway loops, cache drops)\n- **Helps you spend less** — finds where you're over-using expensive models and how much you'd save by switching\n- **Enforces budgets** — can physically stop Claude Code when you go over a limit\n\nEverything happens **100% on your machine**. No cloud account. No API key required. No data leaves your laptop.\n\n\u003e *kerf (n.) — the width of material removed by a cutting tool. Every token operation has a kerf.*\n\n---\n\n## Who is this for?\n\n- **Developers using Claude Code or Codex CLI** who want to understand and control what they're spending\n- **Teams** who want to set budgets and get alerts when someone goes over\n- **Anyone** who has ever been surprised by an AI billing statement\n\nYou don't need to know SQL. You don't need to understand how tokens work. The defaults just work.\n\n---\n\n## Supported tools\n\n| Tool | Status | Where kerf reads data from |\n|------|--------|---------------------------|\n| **Claude Code** | ✅ Full support | `~/.claude/projects/**/*.jsonl` |\n| **Codex CLI** (incl. Codex Desktop) | ✅ Full support | `~/.codex/sessions/**/rollout-*.jsonl` |\n| **Cursor, Copilot, others** | ✅ Via manual export | `~/.kerf/external-additions.json` |\n| **Gemini CLI, OpenCode, Qwen** | ✅ Via OpenTelemetry | `~/.kerf/otel-sources.json` |\n\nkerf auto-detects which tools are installed on your machine and ingests them all with a single `kerf sync`.\n\n---\n\n## Install\n\nYou need **Node.js 20 or newer**. Check with `node --version`. If you don't have it, download from [nodejs.org](https://nodejs.org) — pick any **LTS** version.\n\n**Install globally (recommended — use `kerf` anywhere):**\n\n```bash\nnpm install -g kerf-cli\n```\n\n**Or run without installing (always uses the latest version):**\n\n```bash\nnpx kerf-cli@latest \u003ccommand\u003e\n```\n\nAfter a global install, both `kerf` and `kerf-cli` work as command names:\n\n```bash\nkerf summary     # shorter\nkerf-cli summary # same thing\n```\n\n\u003e **Windows users:** if you see a native-module error about \"Visual Studio\", you're on a very new Node version without a prebuilt binary. Fix: `nvm use 22` (or install Node 22 LTS from nodejs.org) and reinstall.\n\n---\n\n## Quick start (5 minutes)\n\n```bash\n# Step 1 — one-time setup (creates the database, installs usage hooks)\nkerf init\n\n# Step 2 — import your sessions into kerf's database\nkerf sync\n\n# Step 3 — see what you've spent\nkerf summary\n\n# Step 4 — find wasted money\nkerf efficiency\n\n# Step 5 — open the visual dashboard\nkerf dashboard\n```\n\nThat's it. From here, `kerf sync` + `kerf summary` is your daily habit. Everything else is when you want to dig deeper.\n\n---\n\n## How does it work?\n\nWhen you use Claude Code or Codex CLI, they write **session log files** to your home directory. kerf reads those files, calculates the cost of every message, and stores it all in a local SQLite database (`~/.kerf/kerf.db`). That database is just a file on your machine — you own it, you can query it directly, and deleting it resets everything.\n\n```\nClaude Code logs          Codex CLI logs           External / OTel\n~/.claude/projects/       ~/.codex/sessions/        ~/.kerf/external-additions.json\n  session.jsonl             rollout-*.jsonl          ~/.kerf/otel-sources.json\n        │                        │                           │\n        └────────────────────────┴───────────────────────────┘\n                                 │\n                           kerf sync\n                                 │\n                    ~/.kerf/kerf.db  (SQLite)\n                                 │\n          ┌──────────────────────┼──────────────────────┐\n          ▼                      ▼                      ▼\n     CLI commands          Web dashboard          SQL queries\n  (summary, efficiency…)  (kerf dashboard)    (kerf query \"…\")\n```\n\nBecause all data is local SQLite, every command responds instantly — even with years of session history.\n\n---\n\n## All commands\n\n### First-time setup\n\n---\n\n#### `kerf init` — set up kerf\n\nRun once after installing. Creates the `~/.kerf/` directory, initialises the database, and optionally installs hooks into Claude Code so kerf automatically logs every session.\n\n```bash\nkerf init                    # standard setup (recommended for most people)\nkerf init --enforce-budgets  # also add a hard BLOCK when you go over budget\nkerf init --global           # install hooks for all projects (not just this one)\nkerf init --no-hooks         # only create the database, skip hooks entirely\nkerf init --hooks-only       # only install hooks, database already exists\n```\n\n**What are hooks?** Hooks are small shell scripts that Claude Code runs automatically. kerf uses three:\n- **Notification hook** — logs every Claude Code message to kerf's database in real-time\n- **Stop hook** — shows you a warning when you hit 80% or 100% of your budget\n- **PreToolUse hook** *(optional, only with `--enforce-budgets`)* — physically blocks Claude Code from making tool calls when you're over budget\n\n---\n\n#### `kerf doctor` — check your setup\n\nRuns 10 checks and tells you if anything is misconfigured, with plain-English fixes.\n\n```bash\nkerf doctor         # shows a checklist in the terminal\nkerf doctor --json  # same output as JSON (useful for scripts)\n```\n\nExample output:\n```\n[OK]   Claude Code installed: /Users/you/.claude\n[OK]   Codex CLI detected\n[OK]   Claude projects directory has session logs\n[OK]   kerf database exists and is writable\n[OK]   Database schema up to date\n[WARN] No kerf hooks registered\n       Fix: run kerf init\n[OK]   kerf hook scripts installed\n```\n\nIf something is `[FAIL]` or `[WARN]`, the Fix line tells you exactly what to run.\n\n---\n\n#### `kerf sync` — import sessions into the database\n\nReads all session files from your AI coding tools and imports any new messages into kerf's SQLite database. Incremental — re-running it is safe and only picks up new data.\n\n```bash\nkerf sync                  # import everything (Claude Code + Codex + any configured sources)\nkerf sync --tool claude-code  # only import Claude Code sessions\nkerf sync --tool codex        # only import Codex CLI sessions\nkerf sync --json              # show results as JSON\n```\n\nAfter syncing you'll see a breakdown:\n```\n✔ Synced 285 files, 13,695 new messages in 1.2s\n  Claude Code    247 files,  12,491 new messages\n  Codex CLI       38 files,   1,204 new messages\n```\n\n\u003e Most analytics commands (`summary`, `efficiency`, etc.) auto-sync before running, so you usually don't need to call this manually. Add `--no-sync` to any command to skip it and use whatever's already in the database.\n\n---\n\n### Understanding your spend\n\n---\n\n#### `kerf summary` — how much did I spend?\n\nThe command you'll run most often. Shows cost, messages, sessions, and token counts for a time period.\n\n```bash\nkerf summary                    # today (default)\nkerf summary --period week      # last 7 days\nkerf summary --period month     # last 30 days\nkerf summary --period all       # all time\n\n# Break it down further\nkerf summary --model            # split by model (Opus vs Sonnet vs Haiku)\nkerf summary --by-project       # split by project folder\nkerf summary --by-tool          # split by tool (Claude Code vs Codex vs …)\n\n# Filter to a specific project or tool\nkerf summary --project ~/code/myapp   # only sessions in this folder\nkerf summary --tool codex             # only Codex CLI sessions\n\n# Output formats\nkerf summary --json     # machine-readable JSON\nkerf summary --csv      # spreadsheet-friendly CSV\nkerf summary --no-sync  # skip the auto-sync (faster if data is fresh)\n```\n\nExample:\n```\n  kerf summary — today\n\n  Cost:      $26.39\n  Messages:  146\n  Sessions:  5\n  Input:     186\n  Output:    107.6K\n  Cache rd:  60.9M\n  Cache wr:  1.7M\n```\n\n**Cross-tool view** with `--by-tool`:\n```\n  By tool:\n\n  Tool            Cost  Share  Sessions\n  -----------  -------  -----  --------\n  claude-code  $178.04    63%        25\n  codex         $89.12    31%        18\n```\n\n**Spend projection:** on `--period week` or `--period month`, kerf appends a one-line forecast of where you'll end up by end of period, based on your current run rate. See `kerf forecast` for the full breakdown.\n\n---\n\n#### `kerf sessions` — list your sessions\n\nShows individual Claude Code / Codex sessions with their cost, duration, and model. Use this to find which sessions spent the most.\n\n```bash\nkerf sessions                       # 20 most recent sessions\nkerf sessions --limit 50            # show more\nkerf sessions --sort cost           # most expensive first\nkerf sessions --sort messages       # most messages first\nkerf sessions --sort duration       # longest first\nkerf sessions --since 2026-04-01    # only sessions after this date\nkerf sessions --project ~/code/app  # only sessions in this folder\nkerf sessions --tool codex          # only Codex sessions\nkerf sessions --json                # JSON output\n\nkerf sessions abc12345              # drill into a specific session (paste any part of the ID)\n```\n\nThe list shows a **Tool** column so you can see Claude Code vs Codex at a glance:\n```\n  When     Tool    Project     Models     Msgs    Cost  Duration  Session\n  -------  ------  ----------  ---------  ----  ------  --------  --------\n  2h ago   claude  kerf-cli    opus-4-8    387  $38.96    36h 5m  6eb7d6ab\n  2mo ago  codex   my-trader   gpt-5.4      22   $0.41        5m  rollout-\n```\n\n**Drilling into a session** shows a full timeline — every message with its timestamp, model, token counts, and cost:\n```bash\nkerf sessions 6eb7d6ab   # paste the ID shown in the list\n```\n\n---\n\n#### `kerf report` — historical report with anomalies\n\nA detailed view of a time period, including anomaly detection (unusual spikes in cost or cache drops).\n\n```bash\nkerf report                   # today\nkerf report --period week     # last 7 days\nkerf report --period month    # last 30 days\nkerf report --sessions        # include per-session breakdown\nkerf report --model           # include per-model breakdown\nkerf report --sessions --model  # both\nkerf report --json\nkerf report --csv\n```\n\nExample (anomaly detection built in):\n```\n  kerf-cli report — today\n\n  Total Cost:       $22.17\n  Cache Hit Rate:   98.4%\n\n  Anomalies Detected: 2\n    [CRITICAL] Turn cost $0.85 is 6x the session average of $0.14\n      → Investigate this turn for unnecessary tool calls or large file reads\n    [CRITICAL] Cache ratio dropped from 100% to 7%\n      → Cache may have been evicted — consider shorter sessions\n```\n\n---\n\n#### `kerf forecast` — where am I headed this month?\n\nProjects your total spend for the current week or month based on how much you've spent so far, compared to your typical spend in prior periods.\n\n```bash\nkerf forecast                # project this month's total\nkerf forecast --period week  # project this week's total\nkerf forecast --json\n```\n\nExample:\n```\n  kerf forecast — this month\n\n  Spent so far:    $86.40\n  Daily run-rate:  $8.64/day\n  Projected total: $259.20  ($172.80 remaining)\n  vs. your usual:  ↑ 18% above\n  Confidence:      high\n```\n\n**Confidence** is how much of the period has elapsed. After 3+ weeks it's `high`; in the first few days it's `low` — the projection is a rough extrapolation.\n\n\u003e A one-line version of this forecast also appears automatically at the bottom of `kerf summary --period week` and `kerf summary --period month`.\n\n---\n\n#### `kerf efficiency` — am I wasting money on expensive models?\n\nThe most actionable command. Tells you how much you'd save if you moved Opus traffic to Sonnet, and which sessions are driving the most cost.\n\n```bash\nkerf efficiency                      # last 30 days (default)\nkerf efficiency --period week\nkerf efficiency --period month\nkerf efficiency --period all\nkerf efficiency --project ~/code/app   # filter to one project\nkerf efficiency --tool codex           # filter to one tool\nkerf efficiency --expensive-sessions   # list the 10 most expensive sessions\nkerf efficiency --cross-tool           # cross-model + cross-tool optimization tips\nkerf efficiency --json\n```\n\nExample:\n```\n  kerf efficiency report  (month)\n\n  Estimated savings: $144.55 (72.0% of spend)\n  if Opus traffic were routed to Sonnet for this month.\n\n  Total spend: $200.69\n\n  Model breakdown:\n    opus     $180.69  (90.0% — 2569 msgs, 30 sessions) ##############################\n    sonnet    $13.22  ( 6.6% — 365 msgs,   3 sessions) ##\n    haiku      $6.78  ( 3.4% — 239 msgs,  21 sessions) #\n```\n\n**What is `--cross-tool`?** When you use multiple tools (Claude Code + Codex), kerf can identify cases where you're doing similar work on a more expensive tool. It produces ranked recommendations:\n```\n  Cross-tool optimization:\n    $29.31/mo  Routing Opus traffic to Sonnet would save ~$29.31/month\n               380 Opus messages across 1 sessions in the last 30 days\n```\n\n**Run this weekly.** If your Opus share is over 50%, you're leaving significant money on the table.\n\n---\n\n#### `kerf cache` — is my context caching working?\n\nClaude's prompt caching can reduce costs by up to 90% on repeated context. This command shows how much you're benefiting from it — and how much you're leaving on the table.\n\n```bash\nkerf cache                       # last 30 days\nkerf cache --period week\nkerf cache --period month\nkerf cache --period all\nkerf cache --project ~/code/app  # filter to one project\nkerf cache --tool codex          # filter to one tool\nkerf cache --poor-sessions       # list sessions with low cache utilization\nkerf cache --json\n```\n\nExample:\n```\n  kerf cache report  (month)\n\n  Cache hit rate: 98.7%  (102.1M read / 102.1M cacheable)\n\n  Tokens:\n    Input (uncached):    13.4K\n    Cache reads:        102.1M\n    Cache creation:       1.3M\n\n  Cost breakdown:\n    Cache read cost:    $30.62\n    Non-cached input:    $0.04\n    Saved by cache:    $275.54   ← money cache saved you\n    Could still save:    $0.00   ← additional savings at 80% hit rate\n```\n\nA hit rate above 70% is healthy. Below 30%, your sessions are probably starting cold too often — consider keeping sessions alive longer or reducing how often you restart Claude Code.\n\n---\n\n#### `kerf query` — write your own SQL queries\n\nFor when you want to ask a question kerf doesn't have a built-in command for. Runs directly against the SQLite database. Completely **read-only** — write operations (INSERT, UPDATE, DELETE, etc.) are rejected.\n\n```bash\nkerf query --schema                     # print the full database schema\nkerf query --examples                   # show 5 useful example queries\n\nkerf query \"SELECT ...\"                 # run a query inline\nkerf query --file my-query.sql          # run a query from a file\nkerf query --json \"SELECT ...\"          # JSON output\nkerf query --csv \"SELECT ...\"           # CSV output\n```\n\n**You don't need to know SQL to use kerf** — all the useful things are already built-in commands. But if you do know SQL, the full database is yours to explore.\n\nUseful queries:\n\n```sql\n-- How much have I spent per project, all time?\nSELECT project_path, ROUND(SUM(cost_usd), 2) AS cost\nFROM messages\nGROUP BY project_path\nORDER BY cost DESC\nLIMIT 10;\n\n-- Daily spend over the last 30 days\nSELECT date(timestamp) AS day, ROUND(SUM(cost_usd), 2) AS cost\nFROM messages\nWHERE timestamp \u003e= date('now', '-30 days')\nGROUP BY day\nORDER BY day DESC;\n\n-- My most expensive sessions\nSELECT session_id, project_path, total_cost_usd, message_count\nFROM sessions_meta\nWHERE total_cost_usd \u003e 5\nORDER BY total_cost_usd DESC;\n\n-- Spend by tool (Claude Code vs Codex vs …)\nSELECT tool, ROUND(SUM(cost_usd), 2) AS cost, COUNT(DISTINCT session_id) AS sessions\nFROM messages\nWHERE timestamp \u003e= date('now', '-30 days')\nGROUP BY tool\nORDER BY cost DESC;\n```\n\nEvery row in the database carries a `tool` column (`claude-code`, `codex`, `cursor`, etc.), so you can filter any query to a specific tool by adding `WHERE tool = 'claude-code'`.\n\n---\n\n### Watching your spend in real time\n\n---\n\n#### `kerf watch` — live terminal dashboard\n\nOpens a real-time dashboard in your terminal that updates every 2 seconds while Claude Code is running. Open this in a second terminal tab alongside your Claude Code session.\n\n```bash\nkerf watch                         # auto-finds your active session\nkerf watch --session abc123        # watch a specific session by its ID\nkerf watch --project ~/code/app    # filter to a specific project\nkerf watch --interval 5000         # refresh every 5 seconds instead of 2\nkerf watch --alerts                # also fire desktop notifications for anomalies\n```\n\nThe dashboard shows:\n- **Cost meter** — how much you've spent this session and at what rate\n- **Context bar** — how full your context window is (helps you know when to start a new session)\n- **Cache health** — HEALTHY / DEGRADED / BROKEN with the current hit rate\n- **Anomaly alerts** — if a turn costs 5× more than usual or cache suddenly drops\n- **Recent messages** — last 8 messages with per-turn cost and cache ratio\n\nPress `q` to quit, `b` to toggle the budget view.\n\n\u003e **Note:** `kerf watch` requires a real terminal (TTY). It won't work piped into another command or in a non-interactive environment.\n\n---\n\n#### `kerf monitor` — background alert watcher\n\nA headless (no UI) process that runs in the background and **alerts you the moment a cost anomaly happens** — even while you're not watching. The key use case: a runaway Claude Code loop that would burn $40/hour while you step away.\n\n```bash\nkerf monitor                                # watch all active sessions, alert on critical anomalies\nkerf monitor --severity warning             # also alert on warnings (lower threshold)\nkerf monitor --webhook https://hooks.slack.com/...  # post alerts to Slack or Discord\nkerf monitor --interval 5000               # check every 5 seconds (default: every 3s)\nkerf monitor --once                        # check right now and exit (good for cron jobs)\n```\n\nAlert channels are configurable in `~/.kerf/config.json`. This persists your settings so you don't have to pass flags every time:\n\n```json\n{\n  \"alerts\": {\n    \"channels\": [\"terminal\", \"desktop\", \"webhook\"],\n    \"minSeverity\": \"critical\",\n    \"webhookUrl\": \"https://hooks.slack.com/services/YOUR/WEBHOOK/URL\",\n    \"debounceSeconds\": 120\n  }\n}\n```\n\n| Setting | Values | Default | Meaning |\n|---------|--------|---------|---------|\n| `channels` | `terminal`, `desktop`, `webhook` | `[\"terminal\",\"desktop\"]` | Where alerts go |\n| `minSeverity` | `critical`, `warning` | `critical` | Only fire for critical by default |\n| `webhookUrl` | any URL | (none) | Slack/Discord/generic JSON webhook |\n| `debounceSeconds` | any number | `120` | Don't repeat the same alert for 2 minutes |\n\nDesktop notifications work natively on macOS (via `osascript`), Linux (via `notify-send`), and Windows (PowerShell toast).\n\nTo start the monitor automatically when your computer starts, add `kerf monitor` to your system's startup items or use a tool like `pm2`.\n\n---\n\n### Controlling costs\n\n---\n\n#### `kerf budget` — set spending limits\n\nSet a dollar limit per project per time period. kerf will warn you when you approach it, and (optionally) block Claude Code when you hit it.\n\n```bash\n# Set a budget for the current project\nkerf budget set 50 --period weekly     # $50/week\nkerf budget set 10 --period daily      # $10/day\nkerf budget set 200 --period monthly   # $200/month\n\n# See your current budget and spend\nkerf budget show               # current project\nkerf budget show --project ~/code/other-project   # a different project\nkerf budget show --json\n\n# List budgets across all projects\nkerf budget list\n\n# Remove a budget\nkerf budget remove             # remove for current project\n\n# Check programmatically (for scripts and hooks)\nkerf budget check              # exit 0 if under budget, exit 2 if over\nkerf budget check --json       # returns JSON with full status\n```\n\nWhat `kerf budget show` looks like:\n```\n  kerf budget\n\n  Period:  weekly (2026-04-07 to 2026-04-13)\n  Budget:  $50.00\n  Spent:   $42.30\n  [████████████████░░░░] 84.6%\n```\n\n**Two enforcement modes:**\n\n| Mode | How to enable | What happens when over budget |\n|------|--------------|------------------------------|\n| **Warning** (default) | `kerf init` | You see a warning, Claude Code keeps running |\n| **Blocking** (strict) | `kerf init --enforce-budgets` | Claude Code physically stops making tool calls |\n\nWarning mode is the safe default for most people. Blocking mode is for when you really need a hard cap (e.g. on a shared API key).\n\n---\n\n#### `kerf estimate` — know the cost before you start\n\nBefore starting a big Claude Code task, ask kerf to estimate what it will cost. Uses complexity signals (keywords, file sizes) to predict the number of turns and cost range.\n\n```bash\nkerf estimate \"fix the login bug\"\nkerf estimate \"rewrite the entire auth module\"\nkerf estimate \"add a new dashboard page with charts\"\n\nkerf estimate --compare \"add OAuth login\"      # compare Sonnet vs Opus vs Haiku side-by-side\nkerf estimate --model opus \"complex task\"       # estimate for a specific model\nkerf estimate --files 'src/auth/*.ts' \"refactor auth\"  # include file context in the estimate\nkerf estimate --precise \"refactor the parser\"  # use Anthropic's API for exact token counts (needs ANTHROPIC_API_KEY)\nkerf estimate --json \"any task\"\n```\n\nExample `--compare` output:\n```\n  kerf-cli estimate: 'add OAuth login'\n  Complexity: moderate\n\n  Model      Turns      Low       Expected   High\n  -------------------------------------------------------\n  sonnet     10-32      $0.96     $1.68      $2.65\n  opus       10-32      $4.78     $8.38      $13.26\n  haiku      10-32      $0.25     $0.45      $0.71\n\n  Cheapest: haiku at $0.45\n  Priciest: opus at $8.38\n```\n\nThe estimate is a range, not a guarantee. Actual cost depends on how many turns it takes, which files Claude Code reads, and whether it uses tools. Use it as a gut-check before committing to a large task on Opus.\n\n---\n\n#### `kerf audit` — find invisible token waste\n\nYour 200K context window fills up with \"ghost tokens\" — system prompts, built-in tools, MCP server definitions, and the CLAUDE.md file — before you type a single word. This command quantifies that overhead and grades your setup.\n\n```bash\nkerf audit                    # full audit with all checks\nkerf audit --claude-md-only   # only analyse your CLAUDE.md file\nkerf audit --mcp-only         # only analyse MCP server token cost\nkerf audit --fix              # auto-reorder CLAUDE.md to put critical rules where Claude reads them best\nkerf audit --json\n```\n\nExample output:\n```\n  kerf-cli audit report\n\n  Context Window Health: B (69% usable)\n\n  Ghost Token Breakdown:\n    System prompt:         14,328 tokens   (7.2%)\n    Built-in tools:        15,000 tokens   (7.5%)\n    MCP tools (0 servers):      0 tokens   (0.0%)\n    CLAUDE.md:                427 tokens   (0.2%)\n    Autocompact buffer:    33,000 tokens  (16.5%)\n    ─────────────────────────────────────────────\n    Total overhead:        62,755 tokens  (31.4%)\n    Effective window:     137,245 tokens  (68.6%)\n\n  CLAUDE.md Analysis:\n    1 critical rule in the low-attention dead zone (lines 30-70%)\n```\n\n**Grades:** A (\u003e70% usable) · B (50-70%) · C (30-50%) · D (\u003c30%)\n\n**The CLAUDE.md attention trick:** Claude's attention is U-shaped — it pays most attention to the first 30% and last 30% of your CLAUDE.md, and least attention to the middle 40%. Critical rules (NEVER, ALWAYS, MUST) buried in the middle often get ignored. `kerf audit --fix` automatically reorders them to the attention zones. It makes a `.kerf-backup` first so you can undo it.\n\n---\n\n### Tools for teams and CI/CD\n\n---\n\n#### `kerf ci` — attribute AI cost to a git branch\n\nTracks how much AI coding cost is attributable to the branch you're currently working on. Useful for:\n- Understanding the AI cost of a specific feature or PR\n- Setting hard cost limits on a branch to enforce team budgets\n- Adding AI cost as a line item to your PR summaries\n\n\u003e **How it works:** kerf records the git branch for every message. `kerf ci` queries your local database filtered to the current branch. It reads from your local machine — a cloud CI runner won't have this data unless you set up a self-hosted runner with your `~/.kerf/kerf.db`.\n\n**`kerf ci report`** — show what a branch cost:\n\n```bash\nkerf ci report                            # current branch, current folder\nkerf ci report --format json              # machine-readable output\nkerf ci report --branch feature/login     # a specific branch\nkerf ci report --any-project              # don't filter to current directory\nkerf ci report --since 2026-05-01         # only usage after this date\nkerf ci report --no-sync                  # skip syncing before reporting\n```\n\nOutput (Markdown, ready for a PR comment or GitHub Step Summary):\n```markdown\n### 🪚 kerf — AI coding cost for this branch\n\n**Branch:** `feature/login`\n\n| Metric | Value |\n| --- | --- |\n| Total cost | **$11.05** |\n| Messages | 75 |\n| Sessions | 1 |\n\n| Model | Cost | Messages |\n| --- | --- | --- |\n| claude-opus-4-8 | $8.67 | 59 |\n| claude-sonnet-4-6 | $2.38 | 16 |\n```\n\n**`kerf ci gate`** — fail a build if cost is too high:\n\n```bash\nkerf ci gate --max 10.00               # exit 1 if this branch cost \u003e $10, exit 0 if under\nkerf ci gate --max 10 --branch main    # gate a specific branch\nkerf ci gate --max 5 --any-project     # don't filter by project path\n```\n\nExit codes: `0` = within limit, `1` = over limit, `2` = bad arguments.\n\n**Add to your GitHub workflow:**\n\n```yaml\n# Add AI cost to the PR job summary\n- run: npx kerf-cli@latest ci report --format markdown \u003e\u003e $GITHUB_STEP_SUMMARY\n\n# Or use the included composite action (also supports max-usd gating)\n- uses: dhanushkumarsivaji/kerf-cli/.github/actions/kerf-cost@main\n  with:\n    max-usd: \"20\"           # optional — fail the job if over $20\n    comment-summary: \"true\" # append the report to the job summary\n```\n\n---\n\n#### `kerf roi` — is it paying off? *(exploratory)*\n\nA rough \"value for money\" view that correlates your AI spend against code delivery (commits and merges) for the current repository. Helpful for the recurring question every manager asks: \"what are we getting for this spend?\"\n\n```bash\nkerf roi                    # this month (default)\nkerf roi --period week      # this week\nkerf roi --period all       # all time\nkerf roi --json\n```\n\nExample:\n```\n  kerf roi — month\n\n  Spent:    $23.01\n  Commits:  9\n  Merges:   0\n  Cost / commit: $2.56\n\n  Exploratory: commits/merges are a rough delivery proxy.\n```\n\n\u003e Commit counts are a coarse proxy. They don't measure code quality, complexity, or impact. Use this as a conversation starter, not a hard metric.\n\n---\n\n### Ask your AI assistant about your spend\n\n---\n\n#### `kerf mcp` — query costs from inside Claude Code\n\nkerf ships a **Model Context Protocol (MCP) server** that lets Claude Code, Cursor, or any MCP-compatible AI assistant answer questions about your spend directly — without leaving your editor.\n\nOnce registered, you can literally ask:\n- *\"How much have I spent on this project this week?\"*\n- *\"Which model am I spending the most on?\"*\n- *\"Am I on track to stay within my monthly budget?\"*\n\n**Register with Claude Code (one-time):**\n\n```bash\nclaude mcp add kerf -- kerf mcp\n```\n\nThen just ask your assistant naturally — it calls kerf's tools and answers in plain English.\n\n**Available tools the assistant can use:**\n\n| Tool | What it returns |\n|------|----------------|\n| `kerf_summary` | Cost totals + breakdown by model and tool |\n| `kerf_query` | Results of any read-only SQL query |\n| `kerf_efficiency` | Model usage report + savings opportunities |\n| `kerf_forecast` | Projected spend for the current week/month |\n| `kerf_budget_status` | Current budget and how much you've used |\n\n**Safety:** The MCP server is completely read-only. It uses the same write-protection as `kerf query` — any attempt to insert, update, or delete data is rejected. It communicates over stdio only (no network port, no external connections).\n\n---\n\n## Importing data from other tools\n\n---\n\n### Cursor, Copilot, and other tools (external additions)\n\nIf you use an AI coding tool that kerf doesn't natively support, you (or a community exporter script) can add its usage data manually via a JSON file at `~/.kerf/external-additions.json`.\n\n`kerf sync` picks this file up automatically. You can also import it explicitly:\n\n```bash\nkerf import --external                          # import from ~/.kerf/external-additions.json\nkerf import --external ./cursor-export.json     # import from a specific file\nkerf import --external --dry-run                # preview without writing anything\n```\n\n**File format:**\n\n```json\n{\n  \"tool\": \"cursor\",\n  \"sessions\": [\n    {\n      \"sessionId\": \"cursor-2026-05-29-001\",\n      \"projectPath\": \"/code/myapp\",\n      \"messages\": [\n        {\n          \"id\": \"m1\",\n          \"model\": \"claude-sonnet-4\",\n          \"timestamp\": \"2026-05-29T10:00:00Z\",\n          \"input_tokens\": 1200,\n          \"output_tokens\": 800,\n          \"cache_read_input_tokens\": 5000,\n          \"cache_creation_input_tokens\": 0\n        }\n      ]\n    }\n  ]\n}\n```\n\nFields: `tool` (the tool name, e.g. `\"cursor\"`), `sessionId` (any unique string), `projectPath` (folder path), and per-message `model`, `timestamp`, token counts, and optionally `cost_usd` (if you already know the cost; otherwise kerf calculates it from the model's pricing).\n\n---\n\n### Gemini CLI, OpenCode, Qwen Code (OpenTelemetry)\n\nAny AI coding tool that emits the [OpenTelemetry GenAI conventions](https://opentelemetry.io/docs/specs/semconv/gen-ai/) can be ingested by kerf. Register your telemetry log files in `~/.kerf/otel-sources.json`:\n\n```json\n[\n  { \"path\": \"/Users/you/.gemini/telemetry.log\", \"tool\": \"gemini\" }\n]\n```\n\n`kerf sync` reads each file, extracts `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, and `gen_ai.request.model`, and stores them in the database tagged with the tool name. After your first sync, run `kerf summary --by-tool` to verify the numbers look right.\n\n---\n\n## Recommended daily workflow\n\n```bash\n# Morning: check yesterday's spend\nkerf summary --period week\n\n# Before a big task: estimate cost and check your budget\nkerf estimate --compare \"the task I'm about to start\"\nkerf budget show\n\n# Any time: open the visual dashboard\nkerf dashboard\n\n# Weekly: find wasted money\nkerf efficiency\nkerf cache\n\n# When something seems wrong: diagnose\nkerf doctor\nkerf report --period week\n```\n\n---\n\n## Quick reference — all commands\n\n| Command | What it does |\n|---------|-------------|\n| `kerf init` | First-time setup (database + hooks) |\n| `kerf init --enforce-budgets` | Setup + hard-block when over budget |\n| `kerf doctor` | Check for setup problems |\n| `kerf sync` | Import sessions from all tools into the database |\n| `kerf sync --tool \u003cid\u003e` | Import from one specific tool |\n| `kerf summary` | Cost summary (default: today) |\n| `kerf summary --period week\\|month\\|all` | Different time windows |\n| `kerf summary --by-tool` | Split cost by tool (Claude Code vs Codex vs …) |\n| `kerf summary --model` | Split cost by model (Opus vs Sonnet vs Haiku) |\n| `kerf summary --by-project` | Split cost by project folder |\n| `kerf sessions` | List recent sessions |\n| `kerf sessions \u003cid\u003e` | Full detail for one session |\n| `kerf report` | Detailed report with anomaly detection |\n| `kerf efficiency` | Find wasted spend on expensive models |\n| `kerf efficiency --cross-tool` | Cross-tool optimization tips |\n| `kerf forecast` | Project spend to end of week/month |\n| `kerf cache` | Cache hit rate and savings analysis |\n| `kerf query \"\u003csql\u003e\"` | Run custom SQL against the analytics database |\n| `kerf query --examples` | Show example SQL queries |\n| `kerf watch` | Live terminal dashboard (while Claude Code is running) |\n| `kerf watch --alerts` | Live dashboard + desktop notifications |\n| `kerf monitor` | Background alert watcher (headless) |\n| `kerf monitor --once` | Check once and exit |\n| `kerf monitor --webhook \u003curl\u003e` | Send alerts to Slack/Discord |\n| `kerf dashboard` | Open visual web dashboard in browser |\n| `kerf budget set \u003c$\u003e --period \u003cp\u003e` | Set a spending limit |\n| `kerf budget show` | Show current budget and spend |\n| `kerf budget list` | Show all project budgets |\n| `kerf budget remove` | Remove budget for current project |\n| `kerf budget check` | Exit 0 if under, 2 if over (for scripts) |\n| `kerf estimate \"\u003ctask\u003e\"` | Estimate cost before starting |\n| `kerf estimate --compare \"\u003ctask\u003e\"` | Compare Sonnet vs Opus vs Haiku |\n| `kerf audit` | Find invisible token waste |\n| `kerf audit --fix` | Auto-fix CLAUDE.md attention ordering |\n| `kerf import` | Import historical Claude Code data into budget tables |\n| `kerf import --external [path]` | Import Cursor/Copilot/other tool data |\n| `kerf mcp` | Start MCP server (ask AI assistants about your spend) |\n| `kerf ci report` | Report branch AI cost as Markdown or JSON |\n| `kerf ci gate --max \u003c$\u003e` | Fail CI/build when branch cost is too high |\n| `kerf roi` | Spend vs commits/merges (exploratory) |\n\n**Flags that work on most commands:**\n- `--json` — machine-readable JSON output\n- `--csv` — spreadsheet-friendly CSV output\n- `--period today|week|month|all` — time window\n- `--project \u003cpath\u003e` — filter to a specific project folder\n- `--tool claude-code|codex|…` — filter to a specific AI tool\n- `--no-sync` — skip auto-sync before querying (faster)\n\n---\n\n## Privacy and data\n\n- **Everything stays on your machine.** Session data, cost calculations, and the database never leave your computer.\n- **No telemetry.** kerf does not phone home.\n- **No API key needed** for core features. The only optional network call is `kerf estimate --precise`, which uses Anthropic's free token-counting API if you have `ANTHROPIC_API_KEY` set.\n- **The one outbound call that's opt-in:** `kerf monitor --webhook \u003curl\u003e` sends anomaly alert text to a webhook URL you explicitly configure. It sends only the alert description — no session content, no file paths.\n- **Your database is yours.** `~/.kerf/kerf.db` is a standard SQLite file. Open it with any SQLite client, back it up, or delete it.\n- **Open source, MIT licensed.** Read every line of code at [github.com/dhanushkumarsivaji/kerf-cli](https://github.com/dhanushkumarsivaji/kerf-cli).\n\n---\n\n## Files on your machine\n\n```\n~/.claude/projects/                  ← Claude Code writes session logs here; kerf reads them\n~/.claude/settings.json              ← kerf hooks are registered here (after kerf init)\n~/.codex/sessions/                   ← Codex CLI writes session logs here; kerf reads them\n~/.kerf/\n├── kerf.db                          ← The analytics database (all your cost data)\n├── config.json                      ← Alert settings (channels, severity, webhook URL)\n├── external-additions.json          ← Optional: manually import Cursor/Copilot/etc. data\n├── otel-sources.json                ← Optional: OpenTelemetry log file sources\n├── session-log.jsonl                ← Hook event log (written by the notification hook)\n└── hooks/\n    ├── notification.sh              ← Logs every message (installed by kerf init)\n    ├── stop.sh                      ← Budget warning at 80%/100% (installed by kerf init)\n    └── pretool.sh                   ← Hard block when over budget (only with --enforce-budgets)\n```\n\n---\n\n## Why kerf instead of ccusage?\n\n[ccusage](https://github.com/ryoppippi/ccusage) is a great quick cost checker. kerf is what you reach for when you need more:\n\n| | ccusage | kerf |\n|--|---------|------|\n| Quick cost check | ✅ | ✅ |\n| Budget enforcement | ❌ | ✅ hooks that warn or block |\n| Cost-per-project attribution | ❌ | ✅ |\n| Model efficiency analysis | ❌ | ✅ $ savings estimate |\n| Cache hit rate visibility | ❌ | ✅ |\n| Web dashboard | ❌ | ✅ |\n| SQL query interface | ❌ | ✅ |\n| Multiple AI tools (Codex, etc.) | ❌ | ✅ |\n| Real-time anomaly alerts | ❌ | ✅ |\n| MCP server (ask in your editor) | ❌ | ✅ |\n| CI/CD cost gates | ❌ | ✅ |\n\nThey complement each other. Use ccusage for a 5-second check, kerf when you actually want to do something about your spend.\n\n---\n\n## Learn more\n\n- [CHANGELOG.md](CHANGELOG.md) — full version history\n- [ARCHITECTURE.md](ARCHITECTURE.md) — how the code is structured (for contributors)\n\n---\n\n## Contributing\n\n```bash\ngit clone https://github.com/dhanushkumarsivaji/kerf-cli.git\ncd kerf-cli\nnpm install\nnpm test\n```\n\nIssues and PRs are welcome. Please open an issue first for large changes so we can discuss the approach.\n\n### Releasing (maintainers only)\n\nkerf publishes to npm automatically via GitHub Actions — no manual `npm publish`.\n\n**One-time setup:** create an npm Automation token at npmjs.com → Access Tokens, then add it as `NPM_TOKEN` in the GitHub repo's Settings → Secrets and variables → Actions.\n\n**To cut a release:**\n\n```bash\n# 1. Update CHANGELOG.md, then bump the version (this also creates a git tag)\nnpm version 3.4.0 -m \"release: v%s\"\n\n# 2. Push the commit and the tag\ngit push \u0026\u0026 git push --tags\n```\n\nPushing the tag (`v3.4.0`) triggers the workflow: lint → test → build → publish to npm → create GitHub Release with CHANGELOG notes. The workflow is idempotent — if that version is already on npm it skips rather than failing.\n\n---\n\n## License\n\n[MIT](LICENSE) — Dhanush Kumar Sivaji\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdhanushkumarsivaji%2Fkerf-cli","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdhanushkumarsivaji%2Fkerf-cli","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdhanushkumarsivaji%2Fkerf-cli/lists"}