claude-token-saver 2.16.0 → 2.17.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.
Files changed (4) hide show
  1. package/README.en.md +126 -193
  2. package/README.md +117 -185
  3. package/package.json +1 -1
  4. package/src/cost.js +16 -1
package/README.en.md CHANGED
@@ -7,168 +7,92 @@
7
7
 
8
8
  # claude-token-saver
9
9
 
10
- > Renamed from `claude-cache-monitor` in v2.0. Existing users see [Migration](#migration-from-claude-cache-monitor).
10
+ **Diagnose and save Claude Code tokens from a single statusline.** Zero dependencies, one-line install.
11
11
 
12
- A CLI to **diagnose and save tokens on Claude Code**. Cache hit rate, TTL countdown, 1M-context detection, 5h/7d cap warnings — all in one statusline chip.
12
+ ```bash
13
+ npm i -g claude-token-saver # postinstall auto-registers the statusline + Skill
14
+ ```
13
15
 
14
16
  ![statusline example](./docs/statusline.png)
15
17
 
16
- 📺 [Launch Short (60s)](https://www.youtube.com/shorts/RaD8qMsPTnA)
17
-
18
- ## Cost-savings report — harness + ratchet adoption
19
-
20
- ![claude-token-saver — harness + ratchet adoption impact](./docs/harness-impact.png)
21
-
22
- The recently added **harness 5/5 + ratchet** features applied to the author's own Claude Code work, normalized **per user message** (cutoff 2026-05-02, Opus 4.7 pricing):
23
-
24
- | metric | before (7d / 739 msgs) | after (2d / 157 msgs) | Δ |
25
- |---|---:|---:|---:|
26
- | cost / user message | $2.345 | $1.910 | **−18.6%** |
27
- | output tokens / user message | 7,391 | 6,052 | −18.1% |
28
- | assistant turns / user message | 9.73 | 8.83 | −9.2% |
29
- | tool calls / user message | 5.72 | 5.25 | −8.2% |
30
-
31
- Same request resolved in fewer round-trips → first-try success rate up. Looks like the effect of PEV + Structured Task forcing one-shot delivery.
32
-
33
- ### Why cache hit rate isn't in this measurement — Max vs Pro
34
-
35
- **Cache hit rate improvement isn't included** in this comparison. The author is on the Max plan with a 1-hour cache TTL and stays inside the same context for the full hour, so the hit rate had already converged near ~98% with little headroom left. **Pro-plan users (5-minute TTL)** see caches expire frequently, so the harness "one-shot" pattern + a "handoff right before TTL expiry" workflow likely **lifts hit rate itself**.
18
+ ## Why — the 30-second pitch
36
19
 
37
- ### Handoff-before-expiry workflow
38
-
39
- Watching the TTL countdown in the statusline, the habit is now: just before expiry, run `claude-token-saver handoff` to dump current work state into a markdown brief, then start a fresh cache cycle. Same flow handles the 1M-context warning and 5H/7D cap chips.
20
+ | | |
21
+ |---|---|
22
+ | 💸 **−18.6% measured cost** | Cost per user message $2.35 $1.91 after adopting harness+ratchet (author's logs, [details](#real-world-impact--beforeafter-report)) |
23
+ | 🚨 **No surprise rate limits** | Instant warning when the 5H/7D window hits 90% + `handoff` to back up your work |
24
+ | 🧠 **Cache waste detection** | Hit rate, TTL countdown, 1M-context detection — token spikes diagnosed with issue codes |
25
+ | 🅷 **Stop repeating mistakes** | Recurring errors get promoted to ratchet rules — auto-applied from the next session |
26
+ | 💰 **Savings made visible** | See what prompt caching saved you, live (`💰 Cache saved $2.1K`) |
40
27
 
41
- > ⚠️ **Sample caveats** — POST window is only 2 days (157 msgs); statistical confidence is low. The work topic mix differs week to week (PRE was video-script production with long pasted text, POST was package release with short directives), so the tool/harness effect isn't cleanly isolated. **Once 5 more days of POST data are in (around 2026-05-09)**, the same analysis will be re-run to check whether the trend stabilises, and an update will be posted.
28
+ 📺 [Launch Short (60s)](https://www.youtube.com/shorts/RaD8qMsPTnA)
42
29
 
43
30
  ---
44
31
 
45
- ## Install
46
-
47
- ### Prerequisite — Node.js (≥ 18)
32
+ ## Getting started
48
33
 
49
- `npm` ships with Node.js. Check whether it's installed:
34
+ **Prerequisite:** Node.js ≥ 18 (`node -v` · macOS `brew install node` · Windows `winget install OpenJS.NodeJS.LTS` · Linux/WSL: [nvm](https://github.com/nvm-sh/nvm) recommended)
50
35
 
51
36
  ```bash
52
- node -v # v18.0.0 or later is fine
53
- ```
54
-
55
- If not, install it:
56
-
57
- - **macOS** — `brew install node` (Homebrew) or the installer at [nodejs.org](https://nodejs.org/)
58
- - **Windows** — [nodejs.org](https://nodejs.org/) LTS installer, or `winget install OpenJS.NodeJS.LTS`
59
- - **Linux / WSL** — your distro's package manager (`apt install nodejs npm`, etc.) or — recommended — [nvm](https://github.com/nvm-sh/nvm) for a user-scoped install (no sudo)
60
-
61
- > Avoid installing globally with `sudo`. The postinstall hook writes the Skill into root's `~/.claude` instead of yours, and auto-registration silently misses. Use nvm/fnm/Volta, or set `npm config set prefix ~/.npm-global` first.
62
-
63
- ### Install claude-token-saver
64
-
65
- ```bash
66
- # (existing users) remove the old package
67
- npm uninstall -g claude-cache-monitor
68
-
69
- # install — the postinstall hook auto-registers the Skill and statusline
37
+ npm uninstall -g claude-cache-monitor # (previous-package users only)
70
38
  npm i -g claude-token-saver
71
39
  ```
72
40
 
73
- Or run once with no install: `npx claude-token-saver`.
74
-
75
- If postinstall was skipped (e.g. `--ignore-scripts`, sudo, or sandboxed installs), register manually:
76
-
77
- ```bash
78
- claude-token-saver install
79
- ```
80
-
81
- ## Claude Code statusline
41
+ The statusline appears at the bottom of Claude Code right away. If auto-registration was skipped (`--ignore-scripts`, sudo, sandboxed installs), run `claude-token-saver install`.
82
42
 
83
- After install, Claude Code's bottom statusline updates every 5 seconds with cache state (postinstall registers it in `~/.claude/settings.json` automatically).
43
+ > ⚠️ Avoid `sudo` global installs the Skill lands in root's `~/.claude` instead of yours. Use nvm/fnm/Volta or `npm config set prefix ~/.npm-global`.
84
44
 
85
- ```
86
- 🤖 Opus 4.7 · 🧠 Cache hit 98.0% · ⏳ Cache expires 58:38 · ✦ current █░░░░░ 15% 🔄 08:50 · 📅 weekly █▒░░░░ 24% 🔄 Thu 13:00 · 📦 Ctx 200k · 💰 Cache saved $205 · last 1d
87
- ```
88
-
89
- Segments — `🤖 model` · `🧠 cache hit rate` · `⏳ TTL countdown` · `✦ current` (5-hour window) · `📅 weekly` (7-day window) · `📦 context` · `💰 cumulative savings` · `last <window>`.
45
+ ## Reading the statusline
90
46
 
91
- When excessive token usage is detected, a warning chip is prepended at the front of the statusline:
92
-
93
- ```
94
- 🚨 5H 94% (resets in 12m) · 🤖 Opus 4.7 · 🧠 Cache hit 72.1% · ⚠ Cache miss · ✦ current ██████ 94% · 📦 Ctx 200k · last 1d
95
47
  ```
96
-
97
- Risk chips: `🚨 5H/7D NN%`, `⚠ 1M ON`, `⚠ Input spike`, `⚠ Cache miss`, `⚠ 5m TTL`, `⚠ Rebuild churn`, `⚠ Output heavy`, `⚠ Call surge`.
98
-
99
- **What to do** — run the `/claude-token-saver` Skill in Claude. It calls `claude-token-saver last` and surfaces the root cause + step-by-step fix. Saying the chip wording out loud (e.g. "5H cap is up", "cache miss") also auto-activates the same Skill. See the [Skill workflow](#when-a-warning-chip-appears--skill-workflow) section below for the full flow.
100
-
101
- If postinstall was skipped (you already use a different statusline, etc.), wire it manually:
102
-
103
- ```json
104
- {
105
- "statusLine": {
106
- "type": "command",
107
- "command": "claude-token-saver --statusline --icon",
108
- "refreshInterval": 5
109
- }
110
- }
48
+ 🤖 Opus 4.8 · 🧠 Cache hit 98.0% · ⏳ Cache expires 58:38 · ✦ current █░░░░░ 15% 🔄 08:50 · 📅 weekly █▒░░░░ 24% 🔄 Thu 13:00 · 📦 Ctx 200k · 💰 Cache saved $205 · last 1d
111
49
  ```
112
50
 
113
- `refreshInterval: 5` keeps the TTL countdown ticking while idle. For Windows PowerShell see `examples/statusline-command.ps1`.
114
-
115
- ## When a warning chip appears — Skill workflow
116
-
117
- The Claude Code Skill registered at install time bridges "warning chip → remediation":
118
-
119
- 1. **A risk chip appears in the statusline** e.g. `🚨 5H 94%`, `⚠ Cache miss`, `⚠ 1M ON`.
120
- 2. **Run `/claude-token-saver`** invoking the Skill via slash is the simplest path. Mentioning the chip wording to Claude ("5H cap is up", "cache miss showing", "why is 1M context on?") auto-activates the same Skill.
121
- 3. **The Skill fetches the remediation.** Internally it runs `claude-token-saver last` to surface the most recent warning + root-cause code + step-by-step fix, and recommends `claude-token-saver handoff` when a cap is imminent.
122
- 4. **Run manually any time.** `claude-token-saver last` (latest event), `claude-token-saver history` (last 7 days of transitions), `claude-token-saver handoff` (back up before a cap blocks you) — same information, on demand.
123
-
124
- > v2.6.0 folded the legacy `/token-monitor` slash command into this Skill. On older installs, run `claude-token-saver install` once and the legacy file is cleaned up automatically.
125
-
126
- ## One-shot report
51
+ | Segment | Meaning |
52
+ |---|---|
53
+ | `🤖` | Active model |
54
+ | `🅷 5/5` | Harness principle score ([Harness mode](#-harness-mode)) |
55
+ | `🧠` | Cache hit rate (green at 85%+) |
56
+ | `⏳` | Cache TTL countdown — send a message before expiry to keep the cache warm |
57
+ | `✦ current` / `📅 weekly` | 5-hour / 7-day rate-limit window usage + reset time |
58
+ | `📦` | Context window (1M shows red a major cost driver) |
59
+ | `💰` | Cumulative savings from prompt caching |
127
60
 
128
- Run `claude-token-saver` for the last-day diagnostic table:
61
+ When something is wrong, a **warning chip leads the line**:
129
62
 
130
63
  ```
131
- Claude Token Saver Last 1 day
132
- (claude-token-saver v2.9.0)
133
- ══════════════════════════════════════════════════
134
-
135
- Context window: 200k ✓ 200k context (standard)
136
- Sessions: 11 | API calls: 578 | Cache hit rate: 98.0%
137
- TTL Breakdown / Cost Impact / Daily Trend …
64
+ 🚨 5H █████▓ 94% 🔄 12:36 · 🅷 5/5 · 🤖 Opus 4.8 · 🧠 Cache hit 72.1% · ⚠ Cache miss · 📅 weekly ▓░░░░░ 12% 🔄 Sun 14:26 · 📦 Ctx 200k · last 1d
138
65
  ```
139
66
 
140
- If a session spiked, a `⚠ Spike detected` block leads the report with the root-cause code (table below) and an OS-aware remediation command.
141
-
142
- ## Output language
67
+ Chips `🚨 5H/7D NN%` (cap imminent) · `⚠ 1M ON` · `⚠ Cache miss` · `⚠ Input spike` · `⚠ Output heavy` · `⚠ Call surge` · `⚠ Rebuild churn` · `⚠ 5m TTL`. When both windows cross 90% at once, the sooner-resetting one is promoted to 🚨 and the other stays visible as a red segment (v2.16.0+).
143
68
 
144
- `last` / `history` / advice messages render in one language at a time (statusline chips stay symbolic). English is the default — switch via:
69
+ ### When a chip appears
145
70
 
146
- ```bash
147
- claude-token-saver mode ko # or: claude-token-saver mode lang=ko
148
- claude-token-saver mode en # back to English
149
- claude-token-saver mode # show current settings
150
- ```
71
+ Run the `/claude-token-saver` Skill inside Claude — or just say the chip wording ("5H cap is up", "cache miss") and it auto-activates. The Skill surfaces the **root-cause code + step-by-step fix**. When a cap is imminent, run `claude-token-saver handoff` to back up your work state to markdown and continue in a fresh session.
151
72
 
152
73
  ## Commands
153
74
 
154
- All of the commands below run in your **shell (terminal)**. Inside a Claude Code session, the only entry point is the `/claude-token-saver` Skill, which calls these commands for you. The `--statusline` form is invoked automatically by Claude Code on each statusline refresh — you never type it yourself.
75
+ Run these in your shell (inside Claude Code, the `/claude-token-saver` Skill is the only entry point):
155
76
 
156
77
  | Command | What it does |
157
78
  |---|---|
158
- | `claude-token-saver` | Last-1-day diagnostic report (`--days N` to change window) |
159
- | `claude-token-saver last` | Most recent warning + remediation (the command the Skill invokes) |
160
- | `claude-token-saver history` | Last 7 days of chip transitions (1M ON, Cache miss, cap, …) |
161
- | `claude-token-saver handoff` | Back current work up to `HANDOFF-YYYY-MM-DD-HHMM.md` before a cap blocks you |
162
- | `claude-token-saver mode [keywords...]` | Configure output (`icon`/`text`, `en`/`ko`, `verbose`, `1d`/`7d`, …) |
163
- | `claude-token-saver --statusline --icon` | One-line statusline output (called by Claude Code) |
164
- | `claude-token-saver install` | Manually register Skill + statusline (postinstall fallback) |
165
- | `claude-token-saver --install-hook` | Optionally auto-log cache stats on every tool call |
79
+ | `claude-token-saver` | Last-1-day diagnostic report (`--days N` / `--hours N`) |
80
+ | `claude-token-saver last` | Most recent warning + remediation |
81
+ | `claude-token-saver history` | Last 7 days of warning transitions |
82
+ | `claude-token-saver handoff` | Back work up to `HANDOFF-*.md` before a cap blocks you |
83
+ | `claude-token-saver mode [keywords...]` | Output config (`icon`/`text`, `en`/`ko`, `1h`–`30d` window, …) |
84
+ | `claude-token-saver harness ...` | 🅷 Harness management (below) |
85
+ | `claude-token-saver install` | Manually register Skill + statusline |
166
86
 
167
- ## Options
87
+ Switch output language with `mode ko` / `mode en` (English default; statusline chips stay symbolic).
88
+
89
+ <details>
90
+ <summary>All CLI options</summary>
168
91
 
169
92
  | Flag | Description | Default |
170
93
  |------|-------------|---------|
171
94
  | `--days, -d` | Analysis period in days | 30 |
95
+ | `--hours` | Analysis window in hours (overrides `--days`) | – |
172
96
  | `--format, -f` | `table` / `json` / `csv` | table |
173
97
  | `--project, -p` | Filter by project directory | all |
174
98
  | `--threshold` | Hit-rate alert threshold (0.0–1.0) | 0.7 |
@@ -179,31 +103,35 @@ All of the commands below run in your **shell (terminal)**. Inside a Claude Code
179
103
  | `--no-color` | Strip ANSI codes | – |
180
104
  | `--segments=…` | Limit statusline segments (e.g. `model,five_hour,seven_day,saved`) | all |
181
105
  | `--install-hook` / `--uninstall-hook` | Manage the PostToolUse hook | – |
106
+ </details>
182
107
 
183
108
  ## 🅷 Harness mode
184
109
 
185
- Bootstrap five engineering principles (Ratchet, Evidence, PEV, Structured Task, Default Safe Path) into your project's `CLAUDE.md` with one command, then watch the statusline track your score (`🅷 5/5`). When the same error keeps recurring, a `🅷⚠ ratchet?` nudge appears.
110
+ Bootstrap five engineering principles (Ratchet · Evidence · PEV · Structured Task · Default Safe Path) into `CLAUDE.md` with one command; the statusline scores it as `🅷 5/5`. When the same error keeps recurring, a `🅷⚠ ratchet?` nudge appears so you can promote it to a rule.
186
111
 
187
112
  ```bash
188
- claude-token-saver harness init # writes CLAUDE.md (5 sections) + .claude/ratchet.md
189
- claude-token-saver harness check # current score
190
- claude-token-saver harness promote <N> # turn statusline warning #N into a one-line ratchet rule
191
- claude-token-saver harness list # list registered ratchet rules with numbers
192
- claude-token-saver harness rm <N> # delete rule N (auto .bak backup)
193
- claude-token-saver harness uninit # remove the harness block (other CLAUDE.md content preserved)
113
+ claude-token-saver harness init # this project
114
+ claude-token-saver harness init --global # ~/.claude/CLAUDE.md — every project
115
+ claude-token-saver harness check # current score (global fallback honored)
116
+ claude-token-saver harness promote <N> --project|--global # warning #N ratchet rule (scope required)
117
+ claude-token-saver harness list / rm <N> # view / delete rules (auto .bak)
194
118
  claude-token-saver harness off | on # toggle the 🅷 chip
195
119
  ```
196
120
 
197
- ### ⚠️ `harness rm` — handle with care
121
+ - `promote` **requires** `--project`/`--global` in non-TTY contexts (scripts, LLM calls) a scope choice is never silently made for the caller.
122
+ - 🅷⚠ runtime warnings (`ratchet?` `no-evidence` `PEV-skip`) expire after 30 minutes, subdirectory sessions match their project correctly, and PEV-skip counts only mutating tools (Edit/Write/Bash) so read-only research sessions don't trip it (v2.16.0+).
123
+
124
+ <details>
125
+ <summary>⚠️ <code>harness rm</code> — checklist before deleting</summary>
198
126
 
199
- The whole point of the ratchet is **one-direction accumulation**. Deleting rules casually means the same mistakes start re-occurring. **Before deleting, ask**:
127
+ The whole point of the ratchet is **one-direction accumulation**. Deleting rules casually means the same mistakes return.
200
128
 
201
- - **Is the rule too broad and blocking valid cases?** → ❌ delete ✅ **narrow the condition instead**
202
- - e.g. `"no hardcoded values"``"no hardcoded values outside tests"`
203
- - **Is the rule too narrow and almost never firing?** → delete ✅ **leave it** (zero cost)
204
- - **Genuinely wrong rule?** → ✅ delete then
129
+ - **Rule too broad, blocking valid cases?** → ❌ delete ✅ narrow the condition (e.g. `"no hardcoded values"` → `"no hardcoded values outside tests"`)
130
+ - **Rule too narrow, almost never fires?** delete leave it (zero cost)
131
+ - **Genuinely wrong?** → delete then
205
132
 
206
- Most "over-ratcheting" complaints turn out to be **rules that weren't phrased tightly enough**. Open `.claude/ratchet.md` and refine the condition first; deletion is the last resort. An auto `.bak` is left behind, but **the session context that made the rule earn its place is not recoverable**.
133
+ An auto `.bak` is kept, but **the session context that earned the rule its place is not recoverable.**
134
+ </details>
207
135
 
208
136
  ## Spike issue codes
209
137
 
@@ -218,31 +146,44 @@ Most "over-ratcheting" complaints turn out to be **rules that weren't phrased ti
218
146
 
219
147
  Remediation commands are OS-aware (`~/.zshrc` for macOS/Linux/WSL, `setx` for Windows).
220
148
 
221
- ## Migration from claude-cache-monitor
149
+ ## Real-world impact — before/after report
222
150
 
223
- ```bash
224
- npm uninstall -g claude-cache-monitor
225
- npm i -g claude-token-saver
226
- ```
151
+ ![claude-token-saver — harness + ratchet adoption impact](./docs/harness-impact.png)
227
152
 
228
- Then update `~/.claude/settings.json` change `claude-cache-monitor …` to `claude-token-saver …`. The v2.0 alias bin was dropped because it caused `EEXIST` on global installs.
153
+ harness 5/5 + ratchet applied to the author's own Claude Code work, normalized **per user message** (cutoff 2026-05-02, Opus 4.7 pricing):
229
154
 
230
- ## How it works
155
+ | metric | before (7d / 739 msgs) | after (2d / 157 msgs) | Δ |
156
+ |---|---:|---:|---:|
157
+ | cost / user message | $2.345 | $1.910 | **−18.6%** |
158
+ | output tokens / message | 7,391 | 6,052 | −18.1% |
159
+ | assistant turns / message | 9.73 | 8.83 | −9.2% |
160
+ | tool calls / message | 5.72 | 5.25 | −8.2% |
231
161
 
232
- Claude Code logs every API call to `~/.claude/projects/<dir>/<session>.jsonl`. This tool dedupes streaming chunks by `requestId` and aggregates `cache_read_input_tokens` / `cache_creation.ephemeral_5m_input_tokens` / `cache_creation.ephemeral_1h_input_tokens` by day and session.
162
+ Same request resolved in fewer round-trips first-try success rate up the effect of PEV + Structured Task forcing one-shot delivery.
233
163
 
234
- ## Pricing (Apr 2026)
164
+ <details>
165
+ <summary>Measurement notes — why cache hit rate isn't included · sample caveats</summary>
166
+
167
+ - The author is on the Max plan (1-hour cache TTL) with hit rate already converged near ~98%, so little headroom there. **Pro-plan users (5-minute TTL)** likely see hit rate itself rise with the handoff-before-expiry workflow.
168
+ - Handoff-before-expiry: watch the TTL countdown, run `claude-token-saver handoff` just before expiry to dump work state into a markdown brief, start a fresh cache cycle. Same flow handles the 1M warning and cap chips.
169
+ - ⚠️ POST window is only 2 days (157 msgs); statistical confidence is low, and week-to-week topic mix differs, so the tool effect isn't cleanly isolated.
170
+ </details>
171
+
172
+ ## Pricing (Jul 2026)
173
+
174
+ Per million tokens (USD), as used by the cost estimator:
235
175
 
236
176
  | Tier | Models | Input | 5m Write | 1h Write | Read | Output |
237
177
  |---|---|---|---|---|---|---|
238
- | `claude-opus-new` | Opus 4.5 / 4.6 / 4.7 | $5 | $6.25 | $10 | $0.50 | $25 |
178
+ | `claude-fable-5` | Fable 5 / Mythos 5 | $10 | $12.50 | $20 | $1 | $50 |
179
+ | `claude-opus-new` | Opus 4.5 / 4.6 / 4.7 / 4.8 | $5 | $6.25 | $10 | $0.50 | $25 |
239
180
  | `claude-opus-legacy` | Opus 4 / 4.1 / 3 | $15 | $18.75 | $30 | $1.50 | $75 |
240
- | `claude-sonnet` | Sonnet 3.7 / 4 / 4.5 / 4.6 | $3 | $3.75 | $6 | $0.30 | $15 |
181
+ | `claude-sonnet` | Sonnet 3.7 / 4 / 4.5 / 4.6 / 5 | $3 | $3.75 | $6 | $0.30 | $15 |
241
182
  | `claude-haiku-4-5` | Haiku 4.5 | $1 | $1.25 | $2 | $0.10 | $5 |
242
183
 
243
- Source: [Anthropic pricing docs](https://docs.claude.com/en/docs/about-claude/pricing). Versions ≤ 1.0.x over-estimated Opus 4.5+ by ~3× — upgrade if you're below 1.1.0.
184
+ Source: [Anthropic pricing docs](https://platform.claude.com/docs/en/about-claude/pricing). Sonnet 5 has an introductory $2/$10 rate through 2026-08-31; the estimator uses the standard sticker. Versions ≤ 2.16.x priced Fable 5 at the Sonnet tier (~3× under-estimate) — upgrade to 2.17.0+.
244
185
 
245
- ## Cache TTL by plan
186
+ ### Cache TTL by plan
246
187
 
247
188
  | Plan | TTL | Controlled by |
248
189
  |---|---|---|
@@ -250,69 +191,61 @@ Source: [Anthropic pricing docs](https://docs.claude.com/en/docs/about-claude/pr
250
191
  | Pro ($20/mo) | **5m fixed** | not configurable |
251
192
  | API key | 5m default (1h via beta header) | `cache_control.ttl` |
252
193
 
253
- ## Environment
254
-
255
- Node.js ≥ 18 · macOS / Windows / Linux / WSL · zero dependencies.
194
+ ## How it works · Environment
256
195
 
257
- ## Background
196
+ Claude Code logs every API call to `~/.claude/projects/<dir>/<session>.jsonl`. This tool dedupes streaming chunks by `requestId` and aggregates `cache_read_input_tokens` / `cache_creation.ephemeral_5m/1h_input_tokens` by day and session.
258
197
 
259
- - [GitHub Issue #46829](https://github.com/anthropics/claude-code/issues/46829) cache TTL regression
260
- - [HN discussion](https://news.ycombinator.com/item?id=47736476) — 168 points, 142 comments
261
- - [DeepPulse KR](https://www.youtube.com/@DeepPulseKR) — Korean HN tech deep-dives
262
- - [DeepPulse EN](https://www.youtube.com/@DeepPulseEN) — English HN tech deep-dives
263
- - [Homepage](https://rootstudioyaml.github.io/) — project site
198
+ Node.js 18 · macOS / Linux / Windows / WSL · **zero dependencies**.
264
199
 
265
- ## Known environment quirks
200
+ <details>
201
+ <summary>Known quirks · Migration · Background</summary>
266
202
 
267
- **IntelliJ Claude Code plugin** — the statusline widget fuses prior and current frames at the character level when emoji are in the output, producing artifacts like `Cache expires 59:548`. v2.8.5+ detects `TERMINAL_EMULATOR=JetBrains-JediTerm` and falls back to text mode automatically (`--icon` is also ignored under IntelliJ). Other terminals (iTerm, Terminal, WSL, etc.) are unaffected.
203
+ **IntelliJ Claude Code plugin** — the statusline widget fuses frames at the character level when emoji are present (`59:548` artifacts). v2.8.5+ detects `TERMINAL_EMULATOR=JetBrains-JediTerm` and falls back to text mode automatically.
268
204
 
269
- ## Release notes
270
-
271
- ### v2.15.0 (2026-06-13)
272
- - **Global harness init** — `harness init`/`uninit`/`check` gain the same scope concept ratchet already had. `harness init --global` installs the 5 sections into `~/.claude/CLAUDE.md` (+ `~/.claude/ratchet.md`) once, so they **apply to every project**. The no-flag default stays `project` (back-compat).
273
- - `harness check` now treats global as a **fallback** — a project with no local block but a global harness installed reports `🅷 5/5 (covered by global)`, matching how Claude Code loads the global `CLAUDE.md` for every project. Use `--project`/`--global` to inspect a single scope.
274
- - npm package homepage changed to `https://rootstudioyaml.github.io/`; README adds the **@DeepPulseEN** channel and a homepage badge.
205
+ **Migration from claude-cache-monitor:**
206
+ ```bash
207
+ npm uninstall -g claude-cache-monitor && npm i -g claude-token-saver
208
+ ```
209
+ Also update `statusLine.command` in `~/.claude/settings.json` to `claude-token-saver …`.
275
210
 
276
- ### v2.13.3 (2026-05-04)
277
- - "Real-world impact" section restructured as a **harness + ratchet adoption cost-savings report**. Added Max(1h)/Pro(5m) cache TTL distinction (different hit-rate headroom), the handoff-before-expiry workflow, and the 2026-05-09 refresh promise. Chart title updated to match.
211
+ **Background:** [GitHub Issue #46829](https://github.com/anthropics/claude-code/issues/46829) (cache TTL regression) · [HN discussion](https://news.ycombinator.com/item?id=47736476) · [DeepPulse KR](https://www.youtube.com/@DeepPulseKR) / [EN](https://www.youtube.com/@DeepPulseEN) · [Homepage](https://rootstudioyaml.github.io/)
212
+ </details>
278
213
 
279
- ### v2.13.2 (2026-05-04)
280
- - YouTube channel handle corrected to `@DeepPulseKR` (package.json + both READMEs).
214
+ ## Release notes
281
215
 
282
- ### v2.13.1 (2026-05-04)
283
- - README now opens with the actual statusline screenshot and a "harness 5/5 + ratchet before/after" impact chart, with daily/monthly/yearly cost-savings impact card. Author's own logs show −18.6% cost / user message, −9.2% assistant turns. Sample caveats, work-topic confound, and refresh schedule (2026-05-09) called out.
284
- - npm package metadata cleaned up (homepage / bugs / author) package page now links to the DeepPulse YouTube channel.
216
+ ### v2.17.0 (2026-07-02)
217
+ - **Fable 5 pricing tier** `claude-fable-5`/`claude-mythos-5` previously fell through to the Sonnet tier ($3/$15), under-estimating costs ~3×. Now priced at the real rates ($10 input / $50 output / $12.50 5m-write / $20 1h-write / $1 read).
218
+ - README overhaul top-level impact summary, segment table, harness scope-flag docs, pricing table brought current.
285
219
 
286
- ### v2.11.0 (2026-05-02)
287
- - Added `harness list` / `harness rm <N>` to view registered ratchet rules with numbers and delete individually (auto `.bak` backup). The CLI prompts users to "narrow the condition first" before deleting; see [⚠️ `harness rm` handle with care](#️-harness-rm--handle-with-care).
220
+ ### v2.16.0 (2026-07-02)
221
+ - **Statusline fixes** when two rate-limit windows are ≥90% at once, only the cap-warn-promoted window is suppressed (the other stayed hidden before); `--no-color` output is truly ANSI-free; the no-session fallback line keeps cap-warn / 🅷 / model chips.
222
+ - **Harness warning accuracy** — 🅷⚠ warnings expire after 30 minutes (previously lingered indefinitely); session cwd normalized to the project root (subdirectory launches match); no-cwd states no longer leak into every project.
223
+ - **Fewer PEV-skip false positives** — only mutating tools count; windows sliced by assistant turns.
288
224
 
289
- ### v2.9.4 (2026-04-27)
290
- - README now opens with a Node.js prerequisite block (macOS / Windows / Linux). First-time visitors arriving from GitHub no longer hit `npm: command not found` with no guidance. Also flags the `sudo` global-install trap where postinstall writes the Skill under root's home instead of the user's.
225
+ <details>
226
+ <summary>Older versions (v2.8.5 v2.15.0)</summary>
291
227
 
292
- ### v2.9.3 (2026-04-27)
293
- - Skill body (`SKILL.md`) now instructs Claude to respond in the user's configured output language. Previously even when the CLI was on `mode ko`, Claude itself still narrated the answer in English ("All clear — no warnings…"), so the language toggle felt half-applied.
294
- - `installSkill` now auto-updates the on-disk `SKILL.md` whenever the bundled body differs, so upgrades pick up new instructions without `--force`.
228
+ ### v2.15.0 (2026-06-13)
229
+ - **Global harness init** `harness init --global` installs the 5 sections into `~/.claude/CLAUDE.md` (+ `~/.claude/ratchet.md`), applying to every project. `harness check` honors global as a fallback (`🅷 5/5 (covered by global)`).
230
+ - npm homepage change; @DeepPulseEN + homepage badges.
295
231
 
296
- ### v2.9.2 (2026-04-27)
297
- - `last` / `history` empty-state messages now respect the language setting too. Previously they were hard-coded English, so users on `mode ko` still saw English when there were no warnings to report.
232
+ ### v2.13.x (2026-05-04)
233
+ - "Real-world impact" restructured as the harness+ratchet before/after report; statusline screenshot + impact chart; npm metadata cleanup; YouTube handle fix.
298
234
 
299
- ### v2.9.1 (2026-04-27)
300
- - Fix the README statusline sample so it matches actual output (includes the `✦ current` / `📅 weekly` window segments that were missing).
301
- - Add a 4-step "When a warning chip appears" Skill workflow — spot the chip → mention its wording to Claude → Skill runs `last` → apply remediation.
302
- - Move `language` from `cfg.statusline.language` to top-level `cfg.language` (it doesn't belong with statusline toggles). The legacy location is still read as a fallback so existing configs migrate transparently. `mode` output also splits the statusline section from the output-language section.
235
+ ### v2.11.0 (2026-05-02)
236
+ - `harness list` / `harness rm <N>` (auto `.bak`, "narrow the condition first" guidance).
303
237
 
304
- ### v2.9.0 (2026-04-27)
305
- - **Output language is now configurable.** `last` / `history` / advice render in a single language at a time. English by default; switch with `claude-token-saver mode ko`. Statusline chips remain symbolic.
306
- - History files stay bilingual on disk; the language toggle is applied at display time.
238
+ ### v2.9.x (2026-04-27)
239
+ - Output language toggle (`mode ko`/`en`) for `last`/`history`/advice; Skill responds in the configured language; Node.js prerequisite block; Skill workflow guide; `language` config location cleanup.
307
240
 
308
241
  ### v2.8.6 (2026-04-27)
309
- - **Skill auto-registers on install.** A `postinstall` hook wires the Claude Code Skill and statusline into `~/.claude` automatically — no second command. `claude-token-saver install` still works as a fallback for `--ignore-scripts` / sudo / sandboxed environments.
310
- - README polish in both languages; corrected the `claude-cache-monitor` alias-removal note (timing was reversed).
242
+ - **Skill auto-registers on install** via postinstall hook.
311
243
 
312
244
  ### v2.8.5
313
- - IntelliJ Claude Code plugin: auto-fall back to text mode when `TERMINAL_EMULATOR=JetBrains-JediTerm` to avoid frame-fusion artefacts.
245
+ - IntelliJ plugin frame-fusion workaround auto text mode under JediTerm.
314
246
 
315
247
  Older versions: see `git log`.
248
+ </details>
316
249
 
317
250
  ## License
318
251
 
package/README.md CHANGED
@@ -7,189 +7,112 @@
7
7
 
8
8
  # claude-token-saver
9
9
 
10
- > v2.0에서 `claude-cache-monitor` `claude-token-saver`로 이름이 바뀌었습니다. 기존 사용자는 아래 [마이그레이션](#마이그레이션-claude-cache-monitor에서) 항목을 참고하세요.
10
+ **Claude Code 토큰 사용량을 statusline 줄로 진단하고 절약하는 CLI.** 의존성 0, 설치 한 줄이면 끝.
11
11
 
12
- Claude Code의 **토큰 사용량을 진단·절약**하는 CLI. 캐시 히트율, TTL 카운트다운, 1M 컨텍스트 감지, 5h/7d 한도 경고를 statusline 한 줄로 보여줍니다.
12
+ ```bash
13
+ npm i -g claude-token-saver # postinstall이 statusline + Skill 자동 등록
14
+ ```
13
15
 
14
16
  ![statusline 예시](./docs/statusline.png)
15
17
 
16
- 📺 [출시 영상 (60)](https://www.youtube.com/shorts/RaD8qMsPTnA)
17
-
18
- ## 실제 효과 — harness + ratchet 도입 전후 비용 절감 리포트
19
-
20
- ![claude-token-saver — harness + ratchet 도입 효과](./docs/harness-impact.png)
21
-
22
- claude-token-saver에 최근 추가된 **harness 5/5 + ratchet** 기능을 실제 적용해보고 도입 전후를 비교한 결과입니다 (저자 본인의 Claude Code 사용 로그, **사용자 메시지 1건당**으로 정규화, 2026-05-02 기준, Opus 4.7 가격):
23
-
24
- | 메트릭 | 도입 전 (7일 / 739msg) | 도입 후 (2일 / 157msg) | 변화 |
25
- |---|---:|---:|---:|
26
- | 메시지당 비용 | $2.345 | $1.910 | **−18.6%** |
27
- | 메시지당 출력 토큰 | 7,391 | 6,052 | −18.1% |
28
- | 메시지당 assistant 왕복 | 9.73 | 8.83 | −9.2% |
29
- | 메시지당 도구 호출 | 5.72 | 5.25 | −8.2% |
30
-
31
- 같은 요청을 더 적은 왕복으로 끝낸다 = 첫 시도 적중률 ↑. PEV·Structured Task가 강제로 한 번에 가게 만든 효과로 보입니다.
18
+ ## 쓰나 — 30 요약
32
19
 
33
- ### 캐시 히트율은 왜 이번 측정에 없는가 — Pro 플랜과의 차이
34
-
35
- 이번 비교에는 **캐시 히트율 개선**이 포함되지 않았습니다. 저자는 Max 플랜이라 캐시 TTL이 1시간이고, 1시간 내내 같은 컨텍스트를 유지하며 작업해서 히트율이 이미 ~98%에 수렴해 있어 추가 개선 여지가 작습니다. **Pro 플랜 사용자(5분 TTL) 캐시가 자주 만료되기 때문에**, harness가 만든 "한 번에 가는" 패턴 + 만료 직전 handoff 워크플로 조합으로 **히트율 자체가 올라갈 가능성이 큽니다.**
36
-
37
- ### 만료 직전 handoff 워크플로
38
-
39
- statusline에 TTL이 카운트다운되는 보면서, 만료 직전에 `claude-token-saver handoff`로 현재 작업 상태를 마크다운으로 백업해두고 캐시 사이클을 시작하는 흐름이 자리잡았습니다. 1M 컨텍스트 경고나 5H/7D cap 칩이 떠도 같은 흐름으로 처리합니다.
20
+ | | |
21
+ |---|---|
22
+ | 💸 **비용 실측 −18.6%** | harness+ratchet 도입 전후, 사용자 메시지당 비용 $2.35 → $1.91 (저자 로그, [상세](#실제-효과--도입-전후-리포트)) |
23
+ | 🚨 **한도 초과 예방** | 5H/7D rate-limit 윈도 90% 도달 시 즉시 경고 + `handoff`로 작업 백업 |
24
+ | 🧠 **캐시 낭비 감지** | 히트율·TTL 카운트다운·1M 컨텍스트 자동 감지 — 토큰 급증 원인을 코드로 진단 |
25
+ | 🅷 **같은 실수 차단** | 반복 에러를 감지해 ratchet 룰로 승격 — 다음 세션부터 자동 적용 |
26
+ | 💰 **절감액 가시화** | 프롬프트 캐시가 아껴준 금액을 실시간 표시 (`💰 Cache saved $2.1K`) |
40
27
 
41
- > ⚠️ **샘플 주의** — 도입 후 데이터는 2일치(157 msgs)로 통계적 의미가 약하고, 그 주에 무슨 작업을 했냐(긴 텍스트 vs 짧은 지시)가 결과에 섞여 있어 도구 효과만 깨끗이 분리되진 않습니다. **총 7일치(추가 5일)가 쌓이는 2026-05-09경** 같은 분석을 다시 돌려 추세 안정화 여부와 함께 갱신할 예정입니다.
28
+ 📺 [출시 영상 (60초)](https://www.youtube.com/shorts/RaD8qMsPTnA)
42
29
 
43
30
  ---
44
31
 
45
- ## 설치
46
-
47
- ### 사전 준비 — Node.js (≥ 18) 필요
48
-
49
- `npm`은 Node.js에 포함되어 있습니다. 설치돼 있는지 확인:
50
-
51
- ```bash
52
- node -v # v18.0.0 이상이면 OK
53
- ```
54
-
55
- 설치되어 있지 않다면:
56
-
57
- - **macOS** — `brew install node` (Homebrew) 또는 [nodejs.org](https://nodejs.org/) 설치 프로그램
58
- - **Windows** — [nodejs.org](https://nodejs.org/) LTS 설치 프로그램, 또는 `winget install OpenJS.NodeJS.LTS`
59
- - **Linux / WSL** — 배포판 패키지 매니저(`apt install nodejs npm` 등) 또는 [nvm](https://github.com/nvm-sh/nvm)으로 사용자 영역 설치 (sudo 없이 가능, 추천)
60
-
61
- > sudo로 글로벌 설치하면 postinstall 훅이 root의 `~/.claude`에 SKILL을 만들어 자동 등록이 어긋납니다. 가능하면 nvm/fnm/Volta로 사용자 영역에 Node를 설치하거나 `npm config set prefix ~/.npm-global` 같은 prefix 변경 후 사용하세요.
32
+ ## 시작하기
62
33
 
63
- ### claude-token-saver 설치
34
+ **사전 준비:** Node.js ≥ 18 (`node -v`로 확인 · macOS `brew install node` · Windows `winget install OpenJS.NodeJS.LTS` · Linux/WSL은 [nvm](https://github.com/nvm-sh/nvm) 권장)
64
35
 
65
36
  ```bash
66
- # (기존 사용자) 구 패키지 제거
67
- npm uninstall -g claude-cache-monitor
68
-
69
- # 설치 — postinstall 훅이 Skill과 statusline을 자동 등록합니다
37
+ npm uninstall -g claude-cache-monitor # (구 패키지 사용자만)
70
38
  npm i -g claude-token-saver
71
39
  ```
72
40
 
73
- 설치 없이 번만 실행하려면 `npx claude-token-saver`.
74
-
75
- `--ignore-scripts`나 sudo 등으로 postinstall이 실행되지 않은 환경에서는 다음 명령으로 수동 등록할 수 있습니다.
76
-
77
- ```bash
78
- claude-token-saver install
79
- ```
41
+ 설치 즉시 Claude Code 하단에 statusline이 나타납니다. `--ignore-scripts`/sudo 등으로 자동 등록이 안 됐다면 `claude-token-saver install`로 수동 등록하세요.
80
42
 
81
- ## Claude Code statusline
43
+ > ⚠️ sudo 글로벌 설치는 Skill이 root의 `~/.claude`에 등록되는 함정이 있습니다 — nvm/fnm/Volta로 사용자 영역 설치를 권장합니다.
82
44
 
83
- 설치 후 Claude Code 하단 statusline 캐시 상태가 5초마다 갱신됩니다 (postinstall이 `~/.claude/settings.json`에 자동 등록).
45
+ ## statusline 읽는
84
46
 
85
47
  ```
86
- 🤖 Opus 4.7 · 🧠 Cache hit 98.0% · ⏳ Cache expires 58:38 · ✦ current █░░░░░ 15% 🔄 08:50 · 📅 weekly █▒░░░░ 24% 🔄 Thu 13:00 · 📦 Ctx 200k · 💰 Cache saved $205 · last 1d
48
+ 🤖 Opus 4.8 · 🧠 Cache hit 98.0% · ⏳ Cache expires 58:38 · ✦ current █░░░░░ 15% 🔄 08:50 · 📅 weekly █▒░░░░ 24% 🔄 Thu 13:00 · 📦 Ctx 200k · 💰 Cache saved $205 · last 1d
87
49
  ```
88
50
 
89
- 세그먼트 `🤖 모델` · `🧠 캐시 히트율` · `⏳ TTL 카운트다운` · `✦ current` (5시간 윈도) · `📅 weekly` (7일 윈도) · `📦 컨텍스트` · `💰 누적 절감액` · `last <기간>`.
90
-
91
- 토큰이 과도하게 사용되는 상황이 감지되면 경고 칩이 맨 앞에 노출됩니다.
92
-
93
- ```
94
- 🚨 5H 94% (resets in 12m) · 🤖 Opus 4.7 · 🧠 Cache hit 72.1% · ⚠ Cache miss · ✦ current ██████ 94% · 📦 Ctx 200k · last 1d
95
- ```
96
-
97
- 경고 종류 `🚨 5H/7D NN%`, `⚠ 1M ON`, `⚠ Input spike`, `⚠ Cache miss`, `⚠ 5m TTL`, `⚠ Rebuild churn`, `⚠ Output heavy`, `⚠ Call surge`.
98
-
99
- **해야 할 일** — Claude에서 `/claude-token-saver` Skill을 실행하면 됩니다. Skill이 `claude-token-saver last`를 호출해 원인 코드와 단계별 해결 명령을 자동으로 보여줍니다. 칩 문구(예: "5H cap 떴어", "cache miss")만 말해도 동일한 Skill이 자동 활성화됩니다. 자세한 흐름은 아래 [Skill 워크플로](#경고-칩이-떴을-때--skill-워크플로) 참고.
100
-
101
- 수동 등록이 필요한 경우(다른 statusline을 이미 쓰고 있어 postinstall이 건너뛴 경우 등):
102
-
103
- ```json
104
- {
105
- "statusLine": {
106
- "type": "command",
107
- "command": "claude-token-saver --statusline --icon",
108
- "refreshInterval": 5
109
- }
110
- }
111
- ```
112
-
113
- `refreshInterval: 5`는 idle 상태에서도 TTL 카운트다운을 5초마다 갱신합니다. Windows(PowerShell)는 `examples/statusline-command.ps1` 참고.
114
-
115
- ## 경고 칩이 떴을 때 — Skill 워크플로
116
-
117
- 설치 시 함께 등록되는 Claude Code Skill이 "경고 칩 → 처방"의 다리 역할을 합니다.
118
-
119
- 1. **statusline에 경고 칩이 뜬다** — 예: `🚨 5H 94%`, `⚠ Cache miss`, `⚠ 1M ON`.
120
- 2. **`/claude-token-saver` Skill을 실행한다** — Claude에서 슬래시로 Skill을 직접 호출하는 게 가장 간단합니다. 또는 칩 문구를 그대로 말해도 동일한 Skill이 자동 활성화됩니다 ("5H cap 떴어", "cache miss 떴어", "1M context 왜 켜졌지?" 등 — 칩 텍스트가 트리거 단어로 등록돼 있음).
121
- 3. **Skill이 처방을 가져온다** — 내부적으로 `claude-token-saver last`를 실행해 가장 최근 경고 + 원인 코드 + 단계별 해결 명령을 한 번에 보여주고, 캡 임박 시에는 `claude-token-saver handoff`로 현재 작업 백업을 권합니다.
122
- 4. **수동 확인이 필요하면** — `claude-token-saver last` (최근 1건), `claude-token-saver history` (최근 7일 전이 로그), `claude-token-saver handoff` (cap 직전 백업)를 직접 실행해도 같은 정보를 얻을 수 있습니다.
123
-
124
- > v2.6.0에서 레거시 `/token-monitor` 슬래시 커맨드는 이 Skill로 흡수됐습니다. 이전 버전 사용자는 `claude-token-saver install`을 한 번 더 실행하면 자동 정리됩니다.
125
-
126
- ## 단발 리포트
51
+ | 세그먼트 | 의미 |
52
+ |---|---|
53
+ | `🤖` | 현재 모델 |
54
+ | `🅷 5/5` | harness 원칙 점수 ([Harness 모드](#-harness-모드)) |
55
+ | `🧠` | 캐시 히트율 (85%+ 녹색) |
56
+ | `⏳` | 캐시 TTL 카운트다운 만료 전에 메시지를 보내면 캐시 유지 |
57
+ | `✦ current` / `📅 weekly` | 5시간 / 7일 rate-limit 윈도 사용률 + 리셋 시각 |
58
+ | `📦` | 컨텍스트 윈도 (1M이면 빨간 경고 — 비용 급증 요인) |
59
+ | `💰` | 캐시가 절약해준 누적 금액 |
127
60
 
128
- `claude-token-saver`를 실행하면 최근 1일 진단 표가 출력됩니다.
61
+ 문제가 감지되면 **경고 칩이 앞에** 붙습니다:
129
62
 
130
63
  ```
131
- Claude Token Saver Last 1 day
132
- (claude-token-saver v2.9.0)
133
- ══════════════════════════════════════════════════
134
-
135
- Context window: 200k ✓ 200k context (standard)
136
- Sessions: 11 | API calls: 578 | Cache hit rate: 98.0%
137
- TTL Breakdown / Cost Impact / Daily Trend …
64
+ 🚨 5H █████▓ 94% 🔄 12:36 · 🅷 5/5 · 🤖 Opus 4.8 · 🧠 Cache hit 72.1% · ⚠ Cache miss · 📅 weekly ▓░░░░░ 12% 🔄 Sun 14:26 · 📦 Ctx 200k · last 1d
138
65
  ```
139
66
 
140
- 급증 세션이 있으면 상단에 `⚠ Spike detected` 블록과 원인 코드(아래 표) · OS별 해결 명령이 함께 출력됩니다.
67
+ 종류 `🚨 5H/7D NN%`(캡 임박) · `⚠ 1M ON` · `⚠ Cache miss` · `⚠ Input spike` · `⚠ Output heavy` · `⚠ Call surge` · `⚠ Rebuild churn` · `⚠ 5m TTL`. 두 윈도가 동시에 90%+면 리셋이 임박한 쪽이 🚨로 승격되고 나머지는 빨간 세그먼트로 유지됩니다 (v2.16.0+).
141
68
 
142
- ## 출력 언어 전환
69
+ ### 경고 칩이 떴을 때
143
70
 
144
- `last` / `history` / 처방 메시지는 영어가 기본값이며 번에 언어만 출력합니다 (statusline 칩은 항상 동일한 기호 형식). 한국어로 바꾸려면:
145
-
146
- ```bash
147
- claude-token-saver mode ko # 또는: claude-token-saver mode lang=ko
148
- claude-token-saver mode en # 영어로 복귀
149
- claude-token-saver mode # 현재 설정 확인
150
- ```
71
+ Claude 안에서 `/claude-token-saver` Skill을 실행하거나 문구를 그대로 말하면("5H cap 떴어", "cache miss") Skill이 자동 활성화되어 **원인 코드 + 단계별 해결 명령**을 보여줍니다. 캡 임박 시에는 `claude-token-saver handoff`로 현재 작업을 마크다운으로 백업한 뒤 새 세션에서 이어가는 워크플로를 권합니다.
151
72
 
152
73
  ## 주요 명령
153
74
 
154
- 아래 명령은 모두 **셸(터미널)에서 직접 실행**합니다. Claude Code 세션 안에서는 `/claude-token-saver` Skill 하나만 쓰며, Skill이 내부적으로 이 명령들을 호출합니다. `--statusline` 형식은 Claude Code가 statusline 갱신마다 자동으로 호출하므로 사용자가 직접 입력하지 않습니다.
75
+ 셸에서 직접 실행합니다 (Claude Code 안에서는 `/claude-token-saver` Skill 하나만 사용):
155
76
 
156
77
  | 명령 | 설명 |
157
78
  |---|---|
158
- | `claude-token-saver` | 최근 1일 진단 리포트 (`--days N`로 기간 변경) |
159
- | `claude-token-saver last` | 가장 최근 경고 1건 + 처방 (Skill이 호출하는 명령) |
160
- | `claude-token-saver history` | 최근 7일간 전이 로그 (1M ON, Cache miss, cap 등) |
161
- | `claude-token-saver handoff` | 현재 작업을 `HANDOFF-YYYY-MM-DD-HHMM.md`로 백업 (cap 임박 시) |
162
- | `claude-token-saver mode [keywords...]` | 출력 모드 설정 (`icon`/`text`, `ko`/`en`, `verbose`, `1d`/`7d` 등) |
163
- | `claude-token-saver --statusline --icon` | statusline용 출력 (Claude Code가 호출) |
164
- | `claude-token-saver install` | Skill·statusline 수동 등록 (postinstall이 막힌 환경) |
165
- | `claude-token-saver --install-hook` | 매 도구 호출마다 캐시 통계 자동 로깅 (선택) |
79
+ | `claude-token-saver` | 최근 1일 진단 리포트 (`--days N` / `--hours N`) |
80
+ | `claude-token-saver last` | 가장 최근 경고 1건 + 처방 |
81
+ | `claude-token-saver history` | 최근 7 경고 전이 로그 |
82
+ | `claude-token-saver handoff` | 작업 상태를 `HANDOFF-*.md`로 백업 ( 임박 시) |
83
+ | `claude-token-saver mode [keywords...]` | 출력 설정 (`icon`/`text`, `ko`/`en`, `1h`~`30d` 윈도 등) |
84
+ | `claude-token-saver harness ...` | 🅷 Harness 관리 (아래 참고) |
85
+ | `claude-token-saver install` | Skill·statusline 수동 등록 |
166
86
 
167
- 전체 옵션은 `--help` 또는 [영문 README](./README.en.md#options).
87
+ 출력 언어는 `mode ko` / `mode en`으로 전환합니다 (기본 영어, statusline 칩은 항상 기호). 전체 옵션은 [영문 README](./README.en.md#options) 참고.
168
88
 
169
89
  ## 🅷 Harness 모드
170
90
 
171
- 다섯 가지 원칙(Ratchet, Evidence, PEV, Structured Task, Default Safe Path)을 한 줄 명령으로 `CLAUDE.md`에 셋업하고, statusline `🅷 5/5`로 점수화합니다. 같은 에러가 반복되면 `🅷⚠ ratchet?`로 알림이 뜹니다.
91
+ 다섯 원칙(Ratchet · Evidence · PEV · Structured Task · Default Safe Path)을 한 줄 명령으로 `CLAUDE.md`에 셋업하고 statusline `🅷 5/5`로 점수화합니다. 같은 에러가 반복되면 `🅷⚠ ratchet?` 알림이 떠서 룰로 승격할 수 있습니다.
172
92
 
173
93
  ```bash
174
- claude-token-saver harness init # CLAUDE.md(5섹션) + .claude/ratchet.md
175
- claude-token-saver harness check # 현재 점수
176
- claude-token-saver harness promote <N> # statusline 경고 #N ratchet에 한 줄 등록
177
- claude-token-saver harness list # 등록된 ratchet 룰 번호 매겨 보기
178
- claude-token-saver harness rm <N> # 룰 삭제 (자동 .bak 백업)
179
- claude-token-saver harness uninit # harness 블록 제거 (CLAUDE.md 다른 내용은 보존)
180
- claude-token-saver harness off | on # statusline 🅷 표시 토글
94
+ claude-token-saver harness init # 프로젝트에 셋업
95
+ claude-token-saver harness init --global # ~/.claude/CLAUDE.md — 모든 프로젝트 적용
96
+ claude-token-saver harness check # 현재 점수 (글로벌 fallback 인정)
97
+ claude-token-saver harness promote <N> --project|--global # 경고 #N → ratchet 룰 (스코프 필수)
98
+ claude-token-saver harness list / rm <N> # 룰 조회 / 삭제 (자동 .bak)
99
+ claude-token-saver harness off | on # 🅷 표시 토글
181
100
  ```
182
101
 
183
- ### ⚠️ 주의 `harness rm`은 신중하게
102
+ - `promote`는 non-TTY(스크립트·LLM 호출)에서 `--project`/`--global` 플래그가 **필수** — 스코프가 묻지 않고 결정되는 사고를 막기 위한 설계입니다.
103
+ - 🅷⚠ 런타임 경고(`ratchet?` `no-evidence` `PEV-skip`)는 30분 후 자동 만료되고, 하위 디렉터리 세션도 프로젝트에 올바르게 매칭됩니다. PEV-skip은 변경성 도구(Edit/Write/Bash)만 카운트해 읽기 위주 세션에서는 발동하지 않습니다 (v2.16.0+).
184
104
 
185
- ratchet의 가치는 **"한 방향 누적"**에 있습니다. 룰을 가볍게 지우기 시작하면 같은 실수가 다시 새기 시작합니다. **지우기 전에 다음을 확인하세요**:
105
+ <details>
106
+ <summary>⚠️ <code>harness rm</code>은 신중하게 — 삭제 전 체크리스트</summary>
186
107
 
187
- - **룰이 너무 광범위해서 정상 케이스도 막나?** 삭제 **조건을 좁혀서 다듬기**
188
- - 예: `"하드코딩 금지"` → `"테스트 외 코드에서 하드코딩 금지"`
189
- - **룰이 너무 좁아 거의 발동 안 되나?** → ❌ 삭제 ✅ **그냥 두기** (비용 0)
190
- - **정말 잘못된 룰이라 확신?** → ✅ **그때만 삭제**
108
+ ratchet의 가치는 **한 방향 누적**에 있습니다. 룰을 가볍게 지우면 같은 실수가 다시 새기 시작합니다.
191
109
 
192
- 대부분의 "과도한 ratchet" 문제는 **룰의 표현이 좁지 못해서** 생깁니다. 삭제는 마지막 수단으로 두고, 먼저 `.claude/ratchet.md`를 직접 열어 조건을 다듬는 쪽을 우선하세요. 삭제 자동 `.bak`이 남지만, **세션 컨텍스트(왜 그 룰이 박혔는지)는 백업으로 복원되지 않습니다**.
110
+ - **룰이 너무 광범위해서 정상 케이스도 막나?** 삭제 조건을 좁혀 다듬기 (예: `"하드코딩 금지"` `"테스트 코드에서 하드코딩 금지"`)
111
+ - **룰이 너무 좁아 거의 발동 안 되나?** → ❌ 삭제 ✅ 그냥 두기 (비용 0)
112
+ - **정말 잘못된 룰이라 확신?** → ✅ 그때만 삭제
113
+
114
+ 삭제 시 `.bak`이 남지만 **그 룰이 박힌 세션 컨텍스트(왜)는 복원되지 않습니다.**
115
+ </details>
193
116
 
194
117
  ## 토큰 급증 원인 코드
195
118
 
@@ -197,80 +120,89 @@ ratchet의 가치는 **"한 방향 누적"**에 있습니다. 룰을 가볍게
197
120
  |---|---|
198
121
  | `LARGE_INPUT_PER_REQUEST` | 단일 요청 250k+ → 1M 컨텍스트 의심 |
199
122
  | `LOW_HIT_RATE` | 캐시 히트율 50% 미만 |
200
- | `BUCKET_5M_DOMINANT` | 캐시 쓰기의 70% 이상이 5분 버킷에 집중 (Pro 플랜 또는 Max 다운그레이드) |
201
- | `HIGH_OUTPUT_RATIO` | 출력/입력 비율 0.15 초과 (출력 단가가 입력의 5배) |
123
+ | `BUCKET_5M_DOMINANT` | 캐시 쓰기의 70%+가 5분 버킷 (Pro 플랜/Max 다운그레이드) |
124
+ | `HIGH_OUTPUT_RATIO` | 출력/입력 비율 0.15 초과 (출력 단가는 입력의 5배) |
125
+ | `HIGH_REQUEST_COUNT` | 요청 수가 중앙값의 3배+ (도구 호출 루프 의심) |
202
126
  | `FREQUENT_CACHE_REBUILD` | 캐시 재작성이 읽기보다 많음 |
203
127
 
204
- 각 코드마다 OS별 해결 명령(`~/.zshrc` / `setx`)이 함께 출력됩니다.
128
+ 각 코드마다 OS별 해결 명령이 함께 출력됩니다.
205
129
 
206
- ## 마이그레이션 (claude-cache-monitor에서)
130
+ ## 실제 효과 — 도입 전후 리포트
207
131
 
208
- ```bash
209
- npm uninstall -g claude-cache-monitor
210
- npm i -g claude-token-saver
211
- ```
132
+ ![claude-token-saver — harness + ratchet 도입 효과](./docs/harness-impact.png)
212
133
 
213
- `~/.claude/settings.json`의 `statusLine.command`를 `claude-cache-monitor …` `claude-token-saver …`로 교체하세요. v2.0에 잠시 제공됐던 `claude-cache-monitor` 바이너리 별칭은 글로벌 설치 npm 충돌(EEXIST)을 일으켜 이후 버전에서 제거됐습니다.
134
+ harness 5/5 + ratchet을 실제 적용한 전후 비교입니다 (저자 Claude Code 로그, **사용자 메시지 1건당** 정규화, 2026-05-02 기준, Opus 4.7 가격):
214
135
 
215
- ## 동작 원리
136
+ | 메트릭 | 도입 전 (7일/739msg) | 도입 후 (2일/157msg) | 변화 |
137
+ |---|---:|---:|---:|
138
+ | 메시지당 비용 | $2.345 | $1.910 | **−18.6%** |
139
+ | 메시지당 출력 토큰 | 7,391 | 6,052 | −18.1% |
140
+ | 메시지당 assistant 왕복 | 9.73 | 8.83 | −9.2% |
141
+ | 메시지당 도구 호출 | 5.72 | 5.25 | −8.2% |
216
142
 
217
- Claude Code는 모든 API 응답을 `~/.claude/projects/<dir>/<session>.jsonl`에 기록합니다. 도구는 `cache_read_input_tokens`, `cache_creation.ephemeral_5m/1h_input_tokens` 같은 필드를 `requestId` 기준으로 중복 제거한 일·세션 단위로 집계합니다.
143
+ 같은 요청을 적은 왕복으로 끝낸다 = 시도 적중률 ↑. PEV·Structured Task가 번에 가게 만든 효과로 보입니다.
218
144
 
219
- ## 환경
145
+ <details>
146
+ <summary>측정 배경 — 캐시 히트율이 빠진 이유 · 샘플 주의</summary>
220
147
 
221
- Node.js 18 · macOS / Linux / Windows / WSL · 의존성 0.
148
+ - 저자는 Max 플랜(캐시 TTL 1시간)이라 히트율이 이미 ~98%에 수렴해 개선 여지가 작았습니다. **Pro 플랜(5분 TTL) 사용자는** 만료 직전 handoff 워크플로 조합으로 히트율 자체가 오를 가능성이 큽니다.
149
+ - 만료 직전 handoff 워크플로: statusline TTL 카운트다운을 보다가 만료 직전 `claude-token-saver handoff`로 작업 상태를 백업하고 새 캐시 사이클을 시작. 1M 경고·cap 칩도 같은 흐름으로 처리.
150
+ - ⚠️ 도입 후 데이터는 2일치(157msg)로 통계적 의미가 약하고, 주별 작업 토픽 차이가 섞여 있어 도구 효과만 깨끗이 분리되진 않습니다.
151
+ </details>
222
152
 
223
- ## 알려진 환경 이슈
153
+ ## 동작 원리 · 환경
224
154
 
225
- **IntelliJ Claude Code plugin** statusline 위젯이 이전 프레임과 프레임을 글자 단위로 잘못 합쳐 `Cache expires 59:548` 같은 잔재 문자열이 보이는 버그가 있습니다 (이모지가 포함된 출력에서만 재현). v2.8.5+는 `TERMINAL_EMULATOR=JetBrains-JediTerm`을 감지하면 자동으로 text 모드로 폴백해 이모지 없이 출력합니다 (`--icon` 플래그도 IntelliJ에서는 무시됩니다). 다른 터미널(iTerm, Terminal, WSL 등)에는 영향 없습니다.
155
+ Claude Code 모든 API 응답을 `~/.claude/projects/<dir>/<session>.jsonl`에 기록합니다. 도구는 `cache_read_input_tokens`, `cache_creation.ephemeral_5m/1h_input_tokens` 등을 `requestId` 기준으로 중복 제거 집계합니다.
226
156
 
227
- ## 릴리스 노트
157
+ Node.js 18 · macOS / Linux / Windows / WSL · **의존성 0**.
228
158
 
229
- ### v2.15.0 (2026-06-13)
230
- - **글로벌 harness init** — `harness init`/`uninit`/`check`에 ratchet과 동일한 스코프 개념 도입. `harness init --global`이 `~/.claude/CLAUDE.md`(+ `~/.claude/ratchet.md`)에 5개 섹션을 한 번에 깔아 **모든 프로젝트에 적용**됩니다. 무플래그 기본값은 종전대로 `project`(하위호환).
231
- - `harness check`는 이제 글로벌을 **fallback**으로 인정 — 로컬 블록이 없어도 글로벌 harness가 깔려 있으면 `🅷 5/5 (covered by global)`로 표시(Claude Code가 전역 `CLAUDE.md`를 모든 프로젝트에 로드하는 실제 동작과 일치). `--project`/`--global`로 특정 스코프만 조회 가능.
232
- - npm 패키지 homepage를 `https://rootstudioyaml.github.io/`로 변경, README에 **@DeepPulseEN** 채널·홈페이지 배지 추가.
159
+ <details>
160
+ <summary>알려진 환경 이슈 · 마이그레이션</summary>
161
+
162
+ **IntelliJ Claude Code plugin** — statusline 위젯이 프레임을 잘못 합성해 `59:548` 같은 잔재가 보이는 버그가 있습니다(이모지 출력에서만). v2.8.5+는 `TERMINAL_EMULATOR=JetBrains-JediTerm` 감지 자동으로 text 모드 폴백합니다.
233
163
 
234
- ### v2.13.3 (2026-05-04)
235
- - "실제 효과" 섹션을 **harness + ratchet 도입 전후 비용 절감 리포트** 형태로 재구성. Max(1h)/Pro(5m) 캐시 TTL 차이에 따른 히트율 개선 여지 차이 설명, 만료 직전 handoff 워크플로 안내, 7일치 누적 시점(2026-05-09) 갱신 예고 추가. 차트 제목도 동일하게 갱신.
164
+ **claude-cache-monitor에서 마이그레이션:**
165
+ ```bash
166
+ npm uninstall -g claude-cache-monitor && npm i -g claude-token-saver
167
+ ```
168
+ `~/.claude/settings.json`의 `statusLine.command`도 `claude-token-saver …`로 교체하세요.
169
+ </details>
236
170
 
237
- ### v2.13.2 (2026-05-04)
238
- - YouTube 채널 핸들 `@DeepPulseKR`로 정정 (package.json + 두 README 일괄).
171
+ ## 릴리스 노트
239
172
 
240
- ### v2.13.1 (2026-05-04)
241
- - README에 실제 statusline 스크린샷과 "harness 5/5 + ratchet 적용 전후 효과" 차트 추가. 자체 사용 로그 기준 메시지당 비용 −18.6%, assistant 왕복 −9.2%, 일/월/년 환산 비용 절감 임팩트 카드 포함. 샘플 주의사항·작업 토픽 변수·갱신 일정(2026-05-09) 명시.
242
- - npm 패키지 메타데이터(homepage / bugs / author) 정비 DeepPulse YouTube 채널 링크 노출.
173
+ ### v2.17.0 (2026-07-02)
174
+ - **Fable 5 가격 티어 추가** — `claude-fable-5`/`claude-mythos-5`가 Sonnet 단가($3/$15)로 폴백돼 비용이 ~3배 과소 추정되던 문제 수정. 실제 단가(입력 $10 / 출력 $50 / 캐시쓰기 5m $12.50·1h $20 / 캐시읽기 $1) 적용.
175
+ - README 전면 개편 최상위 임팩트 요약, 세그먼트 표, harness scope 플래그 문서화, 가격 테이블 최신화.
243
176
 
244
- ### v2.11.0 (2026-05-02)
245
- - `harness list` / `harness rm <N>` 추가. 등록된 ratchet 룰을 번호로 보고 개별 삭제 가능 (자동 `.bak` 백업). 삭제 "조건을 좁혀서 다듬기" 우선 검토 안내가 CLI에 표시됩니다. README의 [⚠️ 주의 — `harness rm`은 신중하게](#️-주의--harness-rm은-신중하게) 항목 참고.
177
+ ### v2.16.0 (2026-07-02)
178
+ - **statusline 버그 수정** 윈도 동시 90%+ 하나가 사라지던 문제(cap-warn 승격분만 숨김), `--no-color` 출력의 ANSI escape 제거, 세션 데이터 없어도 cap-warn·🅷·모델 유지.
179
+ - **harness 경고 정확도** — 🅷⚠ 경고 30분 자동 만료(무기한 잔류 수정), 하위 디렉터리 세션 매칭, cwd 없는 상태의 전 프로젝트 누출 수정.
180
+ - **PEV-skip 오탐 감소** — 변경성 도구만 카운트(Read/Grep 제외), 윈도를 어시스턴트 턴 기준으로.
246
181
 
247
- ### v2.9.4 (2026-04-27)
248
- - README에 Node.js 사전 설치 안내 추가 (macOS/Windows/Linux별). GitHub에서 처음 본 사용자가 npm 명령부터 막히는 일을 방지. sudo 글로벌 설치 시 postinstall이 root 홈에 SKILL을 만드는 함정도 함께 안내.
182
+ <details>
183
+ <summary>이전 버전 (v2.8.5 ~ v2.15.0)</summary>
249
184
 
250
- ### v2.9.3 (2026-04-27)
251
- - Skill 본문(`SKILL.md`)에 "사용자 설정 언어로 응답" 지시 추가. 이전엔 Skill이 호출돼도 Claude가 영어로 요약을 생성하는 탓에 `mode ko` 상태에서도 영문 답이 나왔습니다 (`All clear - no warnings...` 같은 문구).
252
- - `installSkill`이 번들된 SKILL.md와 디스크의 내용이 다르면 자동 갱신하도록 변경 (`--force` 없이도 업그레이드 시 새 지시가 적용됨).
185
+ ### v2.15.0 (2026-06-13)
186
+ - **글로벌 harness init** `harness init --global`이 `~/.claude/CLAUDE.md`(+ `~/.claude/ratchet.md`)에 5개 섹션을 설치해 모든 프로젝트에 적용. `harness check`는 글로벌을 fallback으로 인정(`🅷 5/5 (covered by global)`).
187
+ - npm homepage 변경, @DeepPulseEN 채널·홈페이지 배지 추가.
253
188
 
254
- ### v2.9.2 (2026-04-27)
255
- - `last`/`history`가 경고 없을 출력하는 안내 문구도 언어 설정을 따르도록 수정 (이전엔 항상 영문 출력 한국어 모드인데도 영문이 보이는 버그).
189
+ ### v2.13.x (2026-05-04)
190
+ - "실제 효과" 섹션을 harness+ratchet 도입 전후 리포트로 재구성, statusline 스크린샷·임팩트 차트 추가, npm 메타데이터 정비, YouTube 핸들 정정.
256
191
 
257
- ### v2.9.1 (2026-04-27)
258
- - README의 statusline 예시를 실제 출력(`✦ current` / `📅 weekly` 윈도 세그먼트 포함)으로 정정.
259
- - "경고 칩이 떴을 때" Skill 워크플로 4단계 가이드 추가 — 칩 발견 → Claude에게 칩 문구 그대로 말하기 → Skill이 `last` 실행 → 처방 적용.
260
- - `language` 설정 위치를 `cfg.statusline` 하위에서 top-level `cfg.language`로 이동(statusline 토글이 아니므로). 구버전 위치도 fallback으로 계속 읽어 마이그레이션은 자동. `mode` 출력도 statusline / output language를 분리해서 표시.
192
+ ### v2.11.0 (2026-05-02)
193
+ - `harness list` / `harness rm <N>` 추가 (자동 `.bak` 백업, 삭제 "조건 좁히기 우선" 안내).
261
194
 
262
- ### v2.9.0 (2026-04-27)
263
- - **출력 언어 전환 추가** — `last` / `history` / 처방 메시지가 번에 언어만 출력합니다. 기본은 영어, `claude-token-saver mode ko`로 한국어 전환 (statusline 칩은 영향 없음).
264
- - 기존 history 파일은 이중언어로 보관되며, 표시할 때 선택한 언어만 필터링됩니다.
195
+ ### v2.9.x (2026-04-27)
196
+ - 출력 언어 전환(`mode ko`/`en`) 추가 — `last`/`history`/처방이 언어로 출력. Skill이 사용자 언어로 응답하도록 지시 추가. README에 Node.js 사전 설치 안내·Skill 워크플로 4단계 추가. `language` 설정 위치 정리.
265
197
 
266
198
  ### v2.8.6 (2026-04-27)
267
- - **Skill 자동 등록** — `npm i -g claude-token-saver` 시 postinstall 훅이 Skill과 statusline을 자동으로 `~/.claude`에 등록. 수동 `claude-token-saver install`은 `--ignore-scripts` / sudo 환경용 폴백으로 유지.
268
- - 한·영 README 문장 다듬기, `claude-cache-monitor` alias 제거 시점 설명 정정.
199
+ - **Skill 자동 등록** — postinstall 훅이 Skill과 statusline을 `~/.claude`에 자동 등록.
269
200
 
270
201
  ### v2.8.5
271
- - IntelliJ Claude Code plugin에서 statusline 프레임 합성 버그 회피 — `TERMINAL_EMULATOR=JetBrains-JediTerm` 감지 시 자동 text 모드.
202
+ - IntelliJ plugin 프레임 합성 버그 회피 — JediTerm 감지 시 자동 text 모드.
272
203
 
273
- 이전 버전은 `git log`를 참고하세요.
204
+ 이전 버전은 `git log` 참고.
205
+ </details>
274
206
 
275
207
  ## 라이선스
276
208
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-token-saver",
3
- "version": "2.16.0",
3
+ "version": "2.17.0",
4
4
  "description": "Save tokens on Claude Code — spike diagnosis, 1M-context detection, TTL countdown, statusline. (formerly claude-cache-monitor)",
5
5
  "type": "module",
6
6
  "bin": {
package/src/cost.js CHANGED
@@ -8,7 +8,17 @@
8
8
  */
9
9
 
10
10
  const PRICING = {
11
- // Opus 4.5+ (new pricing tierincludes 4.5, 4.6, 4.7, and future)
11
+ // Fable 5 / Mythos 5premium tier above Opus ($10/$50). Cache write
12
+ // rates follow the standard multipliers (1.25x input for 5m, 2x for 1h),
13
+ // cache read is 0.1x input.
14
+ 'claude-fable-5': {
15
+ input: 10.0,
16
+ cacheWrite5m: 12.5,
17
+ cacheWrite1h: 20.0,
18
+ cacheRead: 1.0,
19
+ output: 50.0,
20
+ },
21
+ // Opus 4.5+ (new pricing tier — includes 4.5, 4.6, 4.7, 4.8, and future)
12
22
  'claude-opus-new': {
13
23
  input: 5.0,
14
24
  cacheWrite5m: 6.25,
@@ -66,6 +76,11 @@ function detectPricingTier(model) {
66
76
  if (!model) return 'claude-sonnet';
67
77
  const m = model.toLowerCase();
68
78
 
79
+ // Fable 5 / Mythos 5 — must be checked before the generic fallback:
80
+ // without this, 'claude-fable-5' fell through to the Sonnet tier and
81
+ // under-estimated costs ~3x ($3/$15 vs the real $10/$50).
82
+ if (m.includes('fable') || m.includes('mythos')) return 'claude-fable-5';
83
+
69
84
  if (m.includes('opus')) {
70
85
  // Opus 4.5, 4.6, 4.7, and future 5+ use the new reduced pricing.
71
86
  if (/opus[-_.]?4[-_.]?[5-9]\b/.test(m)) return 'claude-opus-new';