kerf-cli 0.1.4 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,198 @@
1
+ # kerf-cli Architecture
2
+
3
+ ## Overview
4
+
5
+ kerf-cli is a TypeScript CLI tool that provides cost intelligence for Claude Code. It parses Claude Code's JSONL session logs, calculates token costs, and presents the data through an interactive terminal UI.
6
+
7
+ ## System Diagram
8
+
9
+ ```
10
+ ┌─────────────────────────────────────────────────────────┐
11
+ │ kerf-cli │
12
+ │ ┌──────┐ ┌──────┐ ┌──────┐ ┌──────┐ ┌──────┐ ┌─────┐ │
13
+ │ │watch │ │esti- │ │budget│ │audit │ │report│ │init │ │
14
+ │ │ │ │mate │ │ │ │ │ │ │ │ │ │
15
+ │ └──┬───┘ └──┬───┘ └──┬───┘ └──┬───┘ └──┬───┘ └──┬──┘ │
16
+ ├─────┼────────┼────────┼────────┼────────┼────────┼────┤
17
+ │ ▼ ▼ ▼ ▼ ▼ ▼ │
18
+ │ ┌─────────────────────────────────────────────────┐ │
19
+ │ │ Core Engine Layer │ │
20
+ │ │ ┌────────┐ ┌──────────┐ ┌───────────────────┐ │ │
21
+ │ │ │ JSONL │ │ Cost │ │ Token │ │ │
22
+ │ │ │ Parser │ │Calculator│ │ Counter │ │ │
23
+ │ │ └────────┘ └──────────┘ └───────────────────┘ │ │
24
+ │ │ ┌────────┐ ┌──────────┐ ┌───────────────────┐ │ │
25
+ │ │ │Estimat-│ │ Budget │ │ Cache │ │ │
26
+ │ │ │ or │ │ Manager │ │ Analyzer │ │ │
27
+ │ │ └────────┘ └──────────┘ └───────────────────┘ │ │
28
+ │ └─────────────────────────────────────────────────┘ │
29
+ ├────────────────────────────────────────────────────────┤
30
+ │ ┌──────────────┐ ┌─────────────┐ ┌──────────────┐ │
31
+ │ │ ~/.claude/ │ │ ~/.kerf/ │ │ .claude/ │ │
32
+ │ │ projects/ │ │ kerf.db │ │ settings.json│ │
33
+ │ │ *.jsonl │ │ (SQLite) │ │ (hooks) │ │
34
+ │ └──────────────┘ └─────────────┘ └──────────────┘ │
35
+ └────────────────────────────────────────────────────────┘
36
+ ```
37
+
38
+ ## Project Structure
39
+
40
+ ```
41
+ kerf-cli/
42
+ ├── src/
43
+ │ ├── cli/ # CLI layer
44
+ │ │ ├── index.ts # Entry point (Commander.js)
45
+ │ │ ├── commands/
46
+ │ │ │ ├── watch.ts # Real-time dashboard
47
+ │ │ │ ├── estimate.ts # Pre-flight cost estimation
48
+ │ │ │ ├── budget.ts # Budget management
49
+ │ │ │ ├── audit.ts # Ghost token audit
50
+ │ │ │ ├── report.ts # Historical reports
51
+ │ │ │ └── init.ts # Setup & hook installation
52
+ │ │ └── ui/
53
+ │ │ ├── Dashboard.tsx # Main Ink dashboard
54
+ │ │ ├── CostMeter.tsx # Token burn rate gauge
55
+ │ │ ├── ContextBar.tsx # Context window fill bar
56
+ │ │ ├── BudgetAlert.tsx # Budget threshold warnings
57
+ │ │ └── EstimateCard.tsx# Pre-flight estimate display
58
+ │ ├── core/ # Business logic
59
+ │ │ ├── parser.ts # JSONL session log parser
60
+ │ │ ├── costCalculator.ts # Per-model pricing engine
61
+ │ │ ├── tokenCounter.ts # Token counting + context overhead
62
+ │ │ ├── estimator.ts # Pre-flight cost estimation
63
+ │ │ ├── budgetManager.ts # SQLite budget CRUD
64
+ │ │ ├── cacheAnalyzer.ts # Cache hit/miss analysis
65
+ │ │ └── config.ts # Constants & configuration
66
+ │ ├── audit/ # Audit modules
67
+ │ │ ├── ghostTokens.ts # Ghost token overhead calculator
68
+ │ │ ├── claudeMdLinter.ts # CLAUDE.md attention curve scorer
69
+ │ │ ├── mcpAnalyzer.ts # MCP server token cost analysis
70
+ │ │ └── recommendations.ts # Actionable optimization suggestions
71
+ │ ├── hooks/ # Claude Code hook system
72
+ │ │ ├── templates/
73
+ │ │ │ ├── notification.sh # Token usage logger
74
+ │ │ │ └── stop.sh # Budget enforcement
75
+ │ │ └── installer.ts # Hook installation logic
76
+ │ ├── db/
77
+ │ │ ├── schema.ts # SQLite schema & init
78
+ │ │ └── migrations.ts # Database migrations
79
+ │ └── types/
80
+ │ ├── jsonl.ts # JSONL log types
81
+ │ ├── pricing.ts # Model pricing types
82
+ │ └── config.ts # Config & audit types
83
+ ├── tests/
84
+ │ ├── parser.test.ts
85
+ │ ├── costCalculator.test.ts
86
+ │ ├── estimator.test.ts
87
+ │ ├── tokenCounter.test.ts
88
+ │ └── fixtures/
89
+ │ ├── sample-session.jsonl
90
+ │ └── sample-claude-md.md
91
+ ├── package.json
92
+ ├── tsconfig.json
93
+ ├── tsup.config.ts
94
+ └── vitest.config.ts
95
+ ```
96
+
97
+ ## Technology Stack
98
+
99
+ | Component | Technology | Why |
100
+ |-----------|-----------|-----|
101
+ | CLI framework | Commander.js | Subcommand routing, option parsing |
102
+ | Terminal UI | Ink 5 (React 18) | Interactive dashboard with live updates |
103
+ | Database | better-sqlite3 | Synchronous access, fast for CLI tools |
104
+ | File watching | chokidar | Cross-platform file change detection |
105
+ | Dates | Day.js | Lightweight, immutable date operations |
106
+ | Colors | chalk | Terminal color output |
107
+ | Bundler | tsup | Fast ESM bundling with shebang support |
108
+ | Testing | vitest | Fast, ESM-native test runner |
109
+
110
+ ## Key Design Decisions
111
+
112
+ ### Token counting: heuristic over API
113
+
114
+ kerf-cli uses `characters / 3.5` as a fast local heuristic instead of calling the Anthropic token counting API. This keeps the tool instant and dependency-free. For actual session costs, it reads the authoritative `total_cost_usd` field from JSONL logs when available.
115
+
116
+ ### Synchronous SQLite
117
+
118
+ `better-sqlite3` is used instead of async alternatives because CLI tools benefit from synchronous access — no event loop overhead, faster startup, simpler code.
119
+
120
+ ### Multiply-then-divide cost calculation
121
+
122
+ To avoid floating point drift in financial calculations:
123
+ ```typescript
124
+ const cost = (tokens * pricePerMillion) / 1_000_000;
125
+ ```
126
+ When `total_cost_usd` is present in the JSONL, it's used as the authoritative source.
127
+
128
+ ### JSONL message deduplication
129
+
130
+ Claude Code streams responses, producing intermediate JSONL entries with partial data (e.g., `output_tokens: 1`). The parser deduplicates by message ID, keeping the **last** occurrence for each ID to get final token counts.
131
+
132
+ ### Context overhead constants
133
+
134
+ ```
135
+ System prompt: 14,328 tokens (fixed)
136
+ Built-in tools: 15,000 tokens (fixed, 24 tools)
137
+ MCP tools: ~600 tokens per tool (variable)
138
+ CLAUDE.md: variable (parsed from file)
139
+ Autocompact buffer: 33,000 tokens (fixed)
140
+ Context window: 200,000 tokens total
141
+ ```
142
+
143
+ ### CLAUDE.md attention curve
144
+
145
+ Claude's attention follows a U-shaped curve across the context. kerf-cli maps each CLAUDE.md section to an attention zone:
146
+ - **0-30%:** High attention (top of file)
147
+ - **30-70%:** Low attention ("dead zone")
148
+ - **70-100%:** High attention (bottom of file)
149
+
150
+ Critical rules (NEVER, ALWAYS, MUST, CRITICAL) in the dead zone are flagged for reordering.
151
+
152
+ ## Data Flow
153
+
154
+ ### Watch command
155
+ ```
156
+ ~/.claude/projects/*.jsonl → parser.ts → costCalculator.ts → Dashboard.tsx
157
+ ↑ chokidar watches ↓ React state updates every 2s
158
+ ```
159
+
160
+ ### Estimate command
161
+ ```
162
+ task description → estimator.ts → complexity detection → turn estimation
163
+
164
+ tokenCounter.ts → context overhead
165
+
166
+ costCalculator.ts → pricing per model
167
+
168
+ EstimateCard.tsx (or JSON output)
169
+ ```
170
+
171
+ ### Audit command
172
+ ```
173
+ CLAUDE.md → claudeMdLinter.ts → section analysis + attention scoring
174
+ .mcp.json → mcpAnalyzer.ts → tool count + token overhead
175
+
176
+ ghostTokens.ts → total overhead + grade
177
+
178
+ recommendations.ts → prioritized actions
179
+ ```
180
+
181
+ ## Model Pricing (as of May 2025)
182
+
183
+ | Model | Input | Output | Cache Read | Cache Creation |
184
+ |-------|-------|--------|------------|----------------|
185
+ | Sonnet 4 | $3/M | $15/M | $0.30/M | $3.75/M |
186
+ | Opus 4 | $15/M | $75/M | $1.50/M | $18.75/M |
187
+ | Haiku 4 | $0.80/M | $4/M | $0.08/M | $1.00/M |
188
+
189
+ ## Key Paths
190
+
191
+ | Path | Purpose |
192
+ |------|---------|
193
+ | `~/.claude/projects/<encoded-path>/<session>.jsonl` | Claude Code session logs |
194
+ | `~/.claude/settings.json` | Global Claude Code settings & hooks |
195
+ | `.claude/settings.json` | Project-level settings & hooks |
196
+ | `.mcp.json` / `~/.claude.json` | MCP server configurations |
197
+ | `~/.kerf/kerf.db` | SQLite database (budgets, usage) |
198
+ | `~/.kerf/session-log.jsonl` | kerf-cli hook event log |
package/CHANGELOG.md CHANGED
@@ -1,17 +1,72 @@
1
1
  # Changelog
2
2
 
3
- ## v0.1.1 (2026-04-04)
3
+ All notable changes to this project will be documented in this file.
4
4
 
5
- - Fix: ContextBar crash when token usage exceeds 100% of context window
6
- - Fix: Package published as `kerf-cli` (npm blocked unscoped `kerf`)
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
- ## v0.1.0 (2026-04-04)
8
+ ## [0.2.0] - 2026-04-04
9
9
 
10
- Initial release.
10
+ ### Added
11
+ - `kerf` binary alias — both `kerf` and `kerf-cli` now work as command names
12
+ - Repository metadata (homepage, bugs, repository fields in package.json)
13
+ - CI badge in README
14
+ - `test:coverage` script
15
+ - Separate CHANGELOG.md following Keep a Changelog format
16
+ - ARCHITECTURE.md with project structure, design decisions, and data flow
17
+ - LAUNCH-POST.md for social media launch content
11
18
 
12
- - `npx kerf-cli watch` — Real-time cost dashboard
13
- - `npx kerf-cli estimate <task>` Pre-flight cost estimation
14
- - `npx kerf-cli budget set/show/list/remove` Per-project budget management
15
- - `npx kerf-cli audit` — Ghost token & CLAUDE.md audit
16
- - `npx kerf-cli report` — Historical cost reports
17
- - `npx kerf-cli init` — Setup hooks and database
19
+ ### Changed
20
+ - README rewritten with `kerf` as primary command name for brevity
21
+ - All command examples use short `kerf` form
22
+
23
+ ## [0.1.5] - 2026-04-04
24
+
25
+ ### Fixed
26
+ - Version injection via tsup `define` instead of runtime `createRequire` — fixes `Cannot find module '../../package.json'` when running from npm
27
+
28
+ ## [0.1.4] - 2026-04-04
29
+
30
+ ### Fixed
31
+ - `--version` now reads dynamically from package.json
32
+ - `--compare` shows proper side-by-side table for all 3 models (was only rendering first)
33
+ - `watch` gracefully exits in non-TTY environments with helpful message
34
+ - `useInput` disabled in non-TTY to prevent raw mode crash
35
+
36
+ ## [0.1.3] - 2026-04-04
37
+
38
+ ### Fixed
39
+ - CLAUDE.md detection now searches git root and `~/.claude/` (not just cwd)
40
+ - `--claude-md-only` shows per-section breakdown with attention zones and suggested reorder
41
+ - `--mcp-only` properly filters to MCP-only output and recommendations
42
+ - Hourly report dates no longer show "Invalid Date"
43
+
44
+ ## [0.1.1] - 2026-04-04
45
+
46
+ ### Fixed
47
+ - ContextBar crash when token usage exceeds 100% of context window (negative `String.repeat`)
48
+
49
+ ## [0.1.0] - 2026-04-04
50
+
51
+ ### Added
52
+ - `kerf-cli watch` — Real-time cost dashboard with Ink (React for CLI)
53
+ - `kerf-cli estimate <task>` — Pre-flight cost estimation with complexity detection
54
+ - `kerf-cli budget set/show/list/remove` — Per-project budget management with SQLite
55
+ - `kerf-cli audit` — Ghost token audit with CLAUDE.md attention curve analysis
56
+ - `kerf-cli report` — Historical cost reports with hourly charts, CSV/JSON export
57
+ - `kerf-cli init` — Setup hooks, database, and detect compatible tools
58
+ - JSONL session log parser with message deduplication
59
+ - Per-model pricing engine (Sonnet 4, Opus 4, Haiku 4)
60
+ - Token counting heuristic (characters / 3.5)
61
+ - Context overhead calculator (ghost tokens)
62
+ - MCP server token cost analyzer
63
+ - Claude Code hook templates (notification + budget enforcement)
64
+ - 34 vitest tests with fixture data
65
+ - CI/CD with GitHub Actions (test on Node 20/22, publish on release)
66
+
67
+ [0.2.0]: https://github.com/dhanushkumarsivaji/kerf-cli/compare/v0.1.5...v0.2.0
68
+ [0.1.5]: https://github.com/dhanushkumarsivaji/kerf-cli/compare/v0.1.4...v0.1.5
69
+ [0.1.4]: https://github.com/dhanushkumarsivaji/kerf-cli/compare/v0.1.3...v0.1.4
70
+ [0.1.3]: https://github.com/dhanushkumarsivaji/kerf-cli/compare/v0.1.1...v0.1.3
71
+ [0.1.1]: https://github.com/dhanushkumarsivaji/kerf-cli/compare/v0.1.0...v0.1.1
72
+ [0.1.0]: https://github.com/dhanushkumarsivaji/kerf-cli/releases/tag/v0.1.0
package/LAUNCH-POST.md ADDED
@@ -0,0 +1,173 @@
1
+ # kerf-cli — Launch Post Brief
2
+
3
+ > Use this document to generate a launch post for Twitter/X, Reddit, LinkedIn, or any platform.
4
+
5
+ ---
6
+
7
+ ## What It Is
8
+
9
+ **kerf-cli** — Cost intelligence for Claude Code. Real-time dashboards, pre-flight cost estimation, per-project budgets, and ghost token auditing.
10
+
11
+ - **npm:** https://www.npmjs.com/package/kerf-cli
12
+ - **GitHub:** https://github.com/dhanushkumarsivaji/kerf-cli
13
+ - **Install:** `npx kerf-cli@latest`
14
+ - **Author:** Dhanush Kumar Sivaji
15
+
16
+ ---
17
+
18
+ ## The Problem It Solves
19
+
20
+ Claude Code users have no visibility into token spending during sessions. People exhaust their 20x Max plan in under 20 minutes without knowing why. Context windows get silently consumed by ghost tokens — system prompts (14K), built-in tools (15K), MCP servers, CLAUDE.md files, and autocompact buffers — before any conversation even starts.
21
+
22
+ ---
23
+
24
+ ## What It Does (6 Commands)
25
+
26
+ ### 1. `kerf-cli watch` — Real-Time Dashboard
27
+ Live cost monitoring in a second terminal tab while Claude Code runs.
28
+
29
+ ```
30
+ ┌──────────────────────────────────────────────────────────────┐
31
+ │ kerf-cli watch | session: a3f8c2d1... | 47 messages │
32
+ ├──────────────────────────────────────────────────────────────┤
33
+ │ >> $4.82 / ~$15.00 window | $0.18/min | ~56m remaining │
34
+ │ [████████████░░░░░░░░░░░░░░░░░░] 38% | 76K / 200K tokens │
35
+ │ system(14K) + tools(15K) + mcp(8K) + conversation(39K) │
36
+ └──────────────────────────────────────────────────────────────┘
37
+ ```
38
+
39
+ ### 2. `kerf-cli estimate` — Pre-Flight Cost Estimation
40
+ Know what a task will cost before you start. Compares Sonnet vs Opus vs Haiku.
41
+
42
+ ```
43
+ $ kerf-cli estimate --compare 'add feature'
44
+
45
+ Model Turns Low Expected High
46
+ ----------------------------------------------------------
47
+ sonnet 5-15 $0.67 $1.05 $1.45
48
+ opus 5-15 $3.35 $5.24 $7.26
49
+ haiku 5-15 $0.18 $0.28 $0.39
50
+ ```
51
+
52
+ ### 3. `kerf-cli budget` — Per-Project Budgets
53
+ Set weekly/monthly spending limits. Automatic warnings at 80% and alerts at 100%.
54
+
55
+ ```
56
+ $ kerf-cli budget show
57
+
58
+ Budget: $50.00/weekly
59
+ Spent: $42.30
60
+ [████████████████░░░░] 84.6%
61
+ ```
62
+
63
+ ### 4. `kerf-cli audit` — Ghost Token Audit
64
+ Find invisible token waste eating your 200K context window.
65
+
66
+ ```
67
+ $ kerf-cli audit
68
+
69
+ Context Window Health: B (62% usable)
70
+
71
+ Ghost Token Breakdown:
72
+ System prompt: 14,328 tokens (7.2%)
73
+ Built-in tools: 15,000 tokens (7.5%)
74
+ MCP tools (3 srv): 8,400 tokens (4.2%)
75
+ CLAUDE.md: 2,100 tokens (1.1%)
76
+ Autocompact buffer:33,000 tokens (16.5%)
77
+ Total overhead: 72,828 tokens (36.4%)
78
+
79
+ Recommendations:
80
+ 1. [HIGH] Reorder CLAUDE.md — 3 critical rules in dead zone
81
+ 2. [MED] Disable unused 'playwright' MCP server (-7,200 tokens)
82
+ ```
83
+
84
+ ### 5. `kerf-cli audit --claude-md-only` — CLAUDE.md Attention Curve Analysis
85
+ Maps each section to Claude's U-shaped attention curve. Flags critical rules (NEVER, ALWAYS, MUST) stuck in the low-attention "dead zone" (30-70% of file).
86
+
87
+ ```
88
+ Sections:
89
+ Conventions 110 tokens L15-23 [dead zone] *critical rules*
90
+ Key Paths 87 tokens L24-30 [dead zone]
91
+ Testing 26 tokens L31-35 [high attention]
92
+ ```
93
+
94
+ ### 6. `kerf-cli report` — Historical Cost Reports
95
+ Daily/weekly/monthly spending with hourly charts, per-model and per-session breakdowns. CSV and JSON export.
96
+
97
+ ```
98
+ $ kerf-cli report --sessions --model
99
+
100
+ Total Cost: $12.77
101
+ Cache Hit Rate: 100.0%
102
+
103
+ Model Breakdown:
104
+ sonnet: $6.20 (73.6%) — 3 sessions
105
+ opus: $2.22 (26.4%) — 1 session
106
+
107
+ Hourly:
108
+ Apr 4, 2 PM ████░░░░░░░░ $1.75
109
+ Apr 4, 6 PM ████████████ $5.64
110
+ ```
111
+
112
+ ---
113
+
114
+ ## Tech Stack
115
+
116
+ - TypeScript, Commander.js, Ink (React for CLI), better-sqlite3, chokidar, Day.js
117
+ - Parses Claude Code's JSONL session logs from `~/.claude/projects/`
118
+ - Stores budgets in SQLite at `~/.kerf/kerf.db`
119
+ - 34 tests passing, zero TypeScript errors
120
+ - Bundled with tsup, published as ESM
121
+
122
+ ---
123
+
124
+ ## How It Was Built
125
+
126
+ Built entirely in a single Claude Code session using Opus. The entire project — scaffolding, 7 core modules, 5 Ink UI components, 6 CLI commands, 4 audit analyzers, hook system, SQLite schema, 34 tests, CI/CD, README, and npm publishing — was implemented from a detailed implementation guide in one conversation.
127
+
128
+ ---
129
+
130
+ ## Comparison
131
+
132
+ | Feature | kerf-cli | RTK | ccusage | token-optimizer |
133
+ |---------|----------|-----|---------|-----------------|
134
+ | Real-time dashboard | Yes | No | No | No |
135
+ | Pre-flight estimation | Yes | No | No | No |
136
+ | Per-project budgets | Yes | No | No | No |
137
+ | Ghost token audit | Yes | No | No | Partial |
138
+ | CLAUDE.md optimization | Yes | No | No | Yes |
139
+ | Historical reports | Yes | No | Yes | No |
140
+
141
+ **RTK compresses. ccusage tracks. kerf predicts.**
142
+
143
+ ---
144
+
145
+ ## Quick Start (3 commands)
146
+
147
+ ```bash
148
+ npx kerf-cli@latest init # set up database & hooks
149
+ npx kerf-cli@latest watch # live dashboard in second terminal
150
+ npx kerf-cli@latest audit # find ghost token waste
151
+ ```
152
+
153
+ ---
154
+
155
+ ## Key Stats
156
+
157
+ - **Package:** kerf-cli on npm
158
+ - **Version:** 0.1.5
159
+ - **Size:** 56KB bundled
160
+ - **Tests:** 34 passing
161
+ - **License:** MIT
162
+ - **Node:** 20+
163
+ - **Published:** April 4, 2026
164
+
165
+ ---
166
+
167
+ ## Taglines (pick one)
168
+
169
+ - "Cost intelligence for Claude Code. Know before you spend."
170
+ - "Stop burning tokens blind. kerf-cli gives you a dashboard for Claude Code."
171
+ - "Your Claude Code plan just got a speedometer."
172
+ - "Every token has a kerf. Now you can see it."
173
+ - "I built a CLI that shows you exactly where your Claude Code tokens go."