lake-meter 0.1.1 → 0.1.3

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.
package/README.md CHANGED
@@ -72,14 +72,14 @@ Stop says: Lake Meter · run $3.44 · 524k tok (313k cache reads, 155k out) · O
72
72
 
73
73
  | | |
74
74
  |---|---|
75
- | `npx lake-meter init` | install hooks, statusline, `/meter` skill and two optional subagents into `~/.claude` |
76
- | `npx lake-meter init --project` | install into this repo's `.claude/settings.local.json` instead |
77
- | `npx lake-meter init --cap 10 --no-agents --statusline` | set the cap, skip the subagents, replace an existing statusline |
75
+ | `npx lake-meter@latest init` | install hooks, statusline, `/meter` skill and two subagents (installed by default; skip with `--no-agents`) into `~/.claude` |
76
+ | `npx lake-meter@latest init --project` | install hooks into this repo's `.claude/settings.local.json` (also writes `.claude/skills` and `.claude/agents` with machine-specific paths: don't commit them) |
77
+ | `npx lake-meter@latest init --cap 10 --no-agents --statusline` | set the cap, skip the subagents, replace an existing statusline |
78
78
  | `/meter`, `/meter cap 10`, `/meter cap off`, `/meter report` | inside Claude Code (uses one short model turn to display) |
79
- | `lake-meter cap 10` · `lake-meter status` · `lake-meter report` | same, from any terminal, no model turn |
80
- | `lake-meter plan plan.md [--why] [--openai] [--json]` | plan breakdown for any markdown plan |
81
- | `lake-meter mcp` | MCP server with `estimate_plan` and `meter_status` (works in Cursor too) |
82
- | `npx lake-meter uninstall` | remove everything `init` added (your settings are restored; a backup is kept as `settings.json.lake-meter.bak`) |
79
+ | `npx lake-meter@latest cap 10` · `npx lake-meter@latest status` · `npx lake-meter@latest report` | same, from any terminal, no model turn (or `npm i -g lake-meter` and drop `npx`) |
80
+ | `npx lake-meter@latest plan plan.md [--why] [--openai] [--json]` (flags after the file) | plan breakdown for any markdown plan |
81
+ | `npx lake-meter@latest mcp` | MCP server with `estimate_plan` and `meter_status` (works in Cursor too) |
82
+ | `npx lake-meter@latest uninstall` | remove everything `init` added (your settings are restored; a backup of the original is kept as `settings.json.lake-meter.bak`) |
83
83
 
84
84
  ### Config
85
85
 
@@ -87,25 +87,40 @@ Stop says: Lake Meter · run $3.44 · 524k tok (313k cache reads, 155k out) · O
87
87
 
88
88
  ```json
89
89
  {
90
- "capUsd": 5, // per run, API list-price equivalent. null = off
91
- "capTokens": null, // per run, all tokens incl. cache reads
92
- "capFiveHourPct": null, // e.g. 80: stop when your 5-hour subscription window passes 80% (needs the statusline)
93
- "sessionCapUsd": null, // across the whole session
94
- "onCap": "ask", // "ask" = permission prompt; "stop" = end the turn
95
- "extendPct": 50, // headroom granted when you press Yes
96
- "warnPct": 80, // one heads-up (to you and to Claude) at 80% of the cap
97
- "provider": "anthropic",// or "openai" for plan recommendations
98
- "annotatePlans": true // add the table to plan files in plan mode
90
+ "capUsd": 5,
91
+ "capTokens": null,
92
+ "capFiveHourPct": null,
93
+ "sessionCapUsd": null,
94
+ "onCap": "ask",
95
+ "extendPct": 50,
96
+ "warnPct": 80,
97
+ "provider": "anthropic",
98
+ "annotatePlans": true
99
99
  }
100
100
  ```
101
101
 
102
+ | Key | Meaning |
103
+ |---|---|
104
+ | `capUsd` | per run, API list-price equivalent. `null` = off |
105
+ | `capTokens` | per run, all tokens incl. cache reads |
106
+ | `capFiveHourPct` | e.g. `80`: stop when your 5-hour subscription window passes 80% (needs the statusline) |
107
+ | `sessionCapUsd` | across the whole session |
108
+ | `onCap` | `"ask"` = permission prompt; `"stop"` = end the turn |
109
+ | `extendPct` | headroom granted when you press Yes |
110
+ | `warnPct` | one heads-up (to you and to Claude) at this % of the cap |
111
+ | `provider` | `"anthropic"` or `"openai"` for plan recommendations |
112
+ | `annotatePlans` | add the table to plan files in plan mode |
113
+
114
+ Simplest: `npx lake-meter@latest cap 10` writes this file for you.
115
+
102
116
  A **run** is everything from one prompt you submit until Claude stops.
103
117
 
104
118
  ### Cursor and other MCP clients
105
119
 
120
+ Add to `~/.cursor/mcp.json` (or any MCP client's config):
121
+
106
122
  ```json
107
- // ~/.cursor/mcp.json
108
- { "mcpServers": { "lake-meter": { "command": "npx", "args": ["-y", "lake-meter", "mcp"] } } }
123
+ { "mcpServers": { "lake-meter": { "command": "npx", "args": ["-y", "lake-meter@latest", "mcp"] } } }
109
124
  ```
110
125
 
111
126
  Then ask the agent to "estimate this plan with lake-meter". In Cursor you get the per-step model and cost breakdown. The cap and the receipt are Claude Code only, because Cursor doesn't expose per-run token usage to extensions.
@@ -117,7 +132,7 @@ Then ask the agent to "estimate this plan with lake-meter". In Cursor you get th
117
132
  | **Tokens per run** | **Measured.** Read from Claude Code's session transcript (`message.usage` on each response, de-duplicated by message id) plus subagent transcripts in `<session>/subagents/`. | Exact as reported by the API, up to transcript write lag (see limits). |
118
133
  | **Dollars per run** | **Computed** from measured tokens × list prices in [`src/prices.json`](src/prices.json), per request, including cache writes (5m/1h), cache reads and Haiku's long-context tier. | Matches Claude Code's own `total_cost_usd` in our tests. It's an **API-equivalent** figure: on Pro/Max you don't pay it per token; it tells you how heavy a run was. Your invoice can differ (discounts, batch, regions). |
119
134
  | **5-hour window %** | **Reported by Claude Code** to the statusline (`rate_limits.five_hour.used_percentage`, Pro/Max only). | As accurate as Claude Code's own number. |
120
- | **Plan breakdown** | **Estimate.** Keyword and size heuristics rate each step 1–5; token budgets per complexity live in `prices.json` (`assumptions`). Run `lake-meter plan plan.md --why` to see every reason. | Rough. Ranges are wide on purpose. Tune the budgets from your own `lake-meter report` history. |
135
+ | **Plan breakdown** | **Estimate.** Keyword and size heuristics rate each step 1–5; token budgets per complexity live in `prices.json` (`assumptions`). Run `npx lake-meter@latest plan plan.md --why` to see every reason. | Rough. Ranges are wide on purpose. Tune the budgets from your own `npx lake-meter@latest report` history. |
121
136
  | **Model recommendation** | **Opinion**, encoded as complexity → tier (1–2 Haiku, 3 Sonnet, 4–5 Opus). Frontier models are never recommended by default. | A starting point, not a guarantee of quality. |
122
137
 
123
138
  Prices last verified **2026‑11‑12** from [Anthropic pricing](https://platform.claude.com/docs/en/about-claude/pricing) and [OpenAI pricing](https://developers.openai.com/api/docs/pricing). To update, edit `src/prices.json`, or drop an override at `~/.lake-meter/prices.json` with the same shape.
@@ -134,13 +149,13 @@ Prices last verified **2026‑11‑12** from [Anthropic pricing](https://platfor
134
149
  | `Stop` hook | prints the receipt (`systemMessage`, never blocks) and appends one line to `~/.lake-meter/runs.jsonl` |
135
150
  | `statusLine` | shows the meter and stores Claude Code's own session cost and rate-limit % for the window cap. Only installed if you don't already have a statusline |
136
151
  | `~/.claude/skills/meter` | the `/meter` command |
137
- | `~/.claude/agents/lake-light.md`, `lake-standard.md` | optional subagents pinned to `haiku` and `sonnet`, so the per-step advice is actionable. Claude only uses them if it decides to; skip with `--no-agents` |
152
+ | `~/.claude/agents/lake-light.md`, `lake-standard.md` | subagents pinned to `haiku` and `sonnet` (installed by default; skip with `--no-agents`), so the per-step advice is actionable. Claude only uses them if it decides to |
138
153
 
139
154
  ## Limits (honest list)
140
155
 
141
156
  - **The cap is checked before each tool call.** A single long model response can overshoot it, and the final text answer of a turn isn't gated. Expect a run to end slightly above the cap.
142
157
  - **Transcript lag.** Claude Code writes transcripts asynchronously, so the newest response may land a moment late. Spend can lag by about one response.
143
- - **Pressing No interrupts the turn.** Claude Code doesn't run Stop hooks on interrupts, so there's no receipt for that turn; `lake-meter status` still has the numbers.
158
+ - **Pressing No interrupts the turn.** Claude Code doesn't run Stop hooks on interrupts, so there's no receipt for that turn; `npx lake-meter@latest status` still has the numbers.
144
159
  - **"Run" = one submitted prompt.** Background subagent reports and `/loop` iterations also fire `UserPromptSubmit` and start a new run; use `sessionCapUsd` to bound the whole session.
145
160
  - **Dollar figures are list-price equivalents**, not your bill. On subscriptions use `capTokens` or `capFiveHourPct` if dollars feel abstract.
146
161
  - **Plan breakdown is heuristic** and English-keyword based. Unknown models count tokens but not dollars (and the receipt says so).
@@ -153,11 +168,11 @@ Step titles are stored locally in `~/.lake-meter`, along with config and a run l
153
168
 
154
169
  ## Verification
155
170
 
156
- - `npm test`: 38 tests (pricing math, transcript parsing and de-duplication, plan splitting and scoring, every hook path, install/uninstall round-trip, MCP over stdio, a simulated session through the real CLI).
171
+ - `npm test`: 54 tests (pricing math, transcript parsing and de-duplication, plan splitting and scoring, every hook path, install/uninstall round-trip, MCP over stdio, a simulated session through the real CLI).
157
172
  - `test/real-claude.test.js` runs the **real Claude Code binary** (2.1.322 at time of writing) against a local mock of the Messages API (`scripts/mock-anthropic.js`, no account needed). It checks that the hooks fire, the cap produces a permission decision, `bypassPermissions` stops the turn, and that lake-meter's measured run cost equals Claude Code's own `total_cost_usd`. Skipped when no Claude Code binary is installed.
158
173
  - The screens in [What you see](#what-you-see) were captured from an interactive Claude Code session driven against the same mock.
159
174
 
160
- ## Demo (no account needed)
175
+ ## Demo (from a clone, no account needed)
161
176
 
162
177
  ```bash
163
178
  npm run demo # simulated session: plan breakdown → cap prompt → receipt
@@ -165,7 +180,7 @@ npm run demo # simulated session: plan breakdown → cap prompt → recei
165
180
 
166
181
  ## Teams
167
182
 
168
- Works with [lake-gate](https://getlake.github.io/lake-gate/): a teammate approves the plan before the expensive run. Shared caps and a dashboard of runs by repo and model are in early access. [Talk to us](https://getlake.github.io/lake-meter/#waitlist).
183
+ Works with [lake-gate](https://getlake.github.io/lake-gate/): a teammate approves the plan before the expensive run. Shared caps and a dashboard of runs by repo and model are in early access. [Request a team pilot](https://getlake.github.io/lake-meter/#waitlist).
169
184
 
170
185
  ## License
171
186
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "lake-meter",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "description": "Per-step model picks and a hard per-run cost cap for Claude Code. Hooks + MCP, local only, no telemetry.",
5
5
  "type": "module",
6
6
  "bin": {
package/src/cli.js CHANGED
@@ -4,7 +4,7 @@ import { loadPrices } from './pricing.js';
4
4
  import { analyzePlan } from './plan.js';
5
5
  import { planTable, runSummary, usd } from './format.js';
6
6
  import { onUserPromptSubmit, onPreToolUse, onPostToolUse, onStop, onStatusLine, effectiveCaps } from './hooks.js';
7
- import { loadConfig, saveUserConfig, loadSession, latestSessionId, readRuns, home } from './state.js';
7
+ import { loadConfig, saveUserConfig, loadSession, latestSessionId, readRuns, uniqueRuns, home, parseCapUsd } from './state.js';
8
8
  import { totals } from './transcript.js';
9
9
  import { init, uninstall } from './init.js';
10
10
  import { serve } from './mcp.js';
@@ -41,15 +41,27 @@ function status(sessionId) {
41
41
  }
42
42
 
43
43
  function setCap(v) {
44
- if (v === 'off' || v === 'none') { saveUserConfig({ capUsd: null }); return 'Per-run cap turned off.'; }
45
- const n = Number(String(v).replace('$', ''));
46
- if (!Number.isFinite(n) || n <= 0) return 'Usage: cap <usd> | off e.g. cap 10';
47
- saveUserConfig({ capUsd: n });
48
- return `Per-run cap set to ${usd(n)} (API list-price equivalent). Applies from the next tool call.`;
44
+ if (v == null || v === '') {
45
+ process.exitCode = 1;
46
+ return 'Usage: cap <usd> | off e.g. cap 10 or cap \'$10\'';
47
+ }
48
+ const parsed = parseCapUsd(v, { allowOff: true });
49
+ if (!parsed.ok) {
50
+ process.exitCode = 1;
51
+ return `lake-meter: invalid cap '${v}'. Use a positive number (e.g. 10 or $10) or 'off'.`;
52
+ }
53
+ try {
54
+ if (parsed.value == null) { saveUserConfig({ capUsd: null }); return 'Per-run cap turned off.'; }
55
+ saveUserConfig({ capUsd: parsed.value });
56
+ } catch (e) {
57
+ process.exitCode = 1;
58
+ return e.message;
59
+ }
60
+ return `Per-run cap set to ${usd(parsed.value)} (API list-price equivalent). Applies from the next tool call.`;
49
61
  }
50
62
 
51
63
  function report() {
52
- const runs = readRuns().slice(-15);
64
+ const runs = uniqueRuns(readRuns()).slice(-15);
53
65
  if (!runs.length) return 'No finished runs yet.';
54
66
  const lines = ['Lake Meter · last runs (measured tokens, list-price $)', ''];
55
67
  for (const r of runs) {
@@ -99,7 +111,8 @@ export async function main(argv) {
99
111
  return;
100
112
  }
101
113
  case 'plan': {
102
- console.log(planFile(args[0], args));
114
+ const out = planFile(args[0], args);
115
+ console.log(out);
103
116
  return;
104
117
  }
105
118
  case 'cap': console.log(setCap(args[0])); return;
@@ -108,13 +121,33 @@ export async function main(argv) {
108
121
  case 'mcp': serve(); return;
109
122
  case 'init': {
110
123
  const cap = opt(args, '--cap');
111
- init({ project: flag(args, '--project'), capUsd: cap != null ? Number(cap) : undefined, agents: !flag(args, '--no-agents'), statusline: flag(args, '--statusline') });
124
+ let capUsd;
125
+ if (cap != null) {
126
+ const parsed = parseCapUsd(cap);
127
+ if (!parsed.ok) {
128
+ process.stderr.write(`lake-meter: invalid --cap '${cap}'. Use a positive number, e.g. --cap 10 or --cap '$10'.\n`);
129
+ process.exitCode = 1;
130
+ return;
131
+ }
132
+ capUsd = parsed.value;
133
+ }
134
+ try {
135
+ init({ project: flag(args, '--project'), capUsd, agents: !flag(args, '--no-agents'), statusline: flag(args, '--statusline') });
136
+ } catch (e) {
137
+ process.stderr.write(`lake-meter: ${e.message}\n`);
138
+ process.exitCode = 1;
139
+ }
112
140
  return;
113
141
  }
114
142
  case 'uninstall': uninstall({ project: flag(args, '--project') }); return;
115
143
  case 'where': console.log(home()); return;
116
144
  case '--version': case '-v': console.log(JSON.parse(readFileSync(new URL('../package.json', import.meta.url))).version); return;
117
- default: console.log(HELP);
145
+ case '--help': case '-h': case undefined:
146
+ console.log(HELP);
147
+ return;
148
+ default:
149
+ process.stderr.write(`lake-meter: unknown command '${cmd}'\n${HELP}\n`);
150
+ process.exitCode = 1;
118
151
  }
119
152
  }
120
153
 
@@ -122,7 +155,10 @@ function planFile(file, args) {
122
155
  let text;
123
156
  if (!file || file === '-') text = readFileSync(0, 'utf8');
124
157
  else if (existsSync(file)) text = readFileSync(file, 'utf8');
125
- else return `File not found: ${file}`;
158
+ else {
159
+ process.exitCode = 1;
160
+ return `File not found: ${file}`;
161
+ }
126
162
  const a = analyzePlan(text, loadPrices(), { provider: flag(args, '--openai') ? 'openai' : loadConfig(process.cwd()).provider });
127
163
  if (!a.steps.length) return 'Could not find steps in that plan (use numbered items, headings or bullets).';
128
164
  return flag(args, '--json') ? JSON.stringify(a, null, 2) : planTable(a, { reasons: flag(args, '--why') });
package/src/hooks.js CHANGED
@@ -9,6 +9,21 @@ import { existsSync, readFileSync, writeFileSync } from 'node:fs';
9
9
 
10
10
  const UNATTENDED_MODES = new Set(['bypassPermissions', 'dontAsk']);
11
11
 
12
+ function defaultWarn(msg) {
13
+ process.stderr.write(msg.endsWith('\n') ? msg : msg + '\n');
14
+ }
15
+
16
+ /** Load config and, once per session, return a user-visible notice for parse/validation warnings (M-22). */
17
+ function loadConfigNotices(cwd, s) {
18
+ const warnings = [];
19
+ const cfg = loadConfig(cwd, (m) => { defaultWarn(m); warnings.push(m); });
20
+ if (!warnings.length) return { cfg, notice: null };
21
+ if (s.configNoticeShown) return { cfg, notice: null };
22
+ s.configNoticeShown = true;
23
+ return { cfg, notice: warnings.join('\n') };
24
+ }
25
+
26
+
12
27
  function ensureRun(s, now) {
13
28
  if (!s.run) s.run = { start: 0, seen: {}, extraUsd: 0, extraTokens: 0, capHits: 0, warned: false, pendingAsk: null, startedAt: now };
14
29
  return s.run;
@@ -31,25 +46,77 @@ export function refresh(s, input, prices) {
31
46
  return totals(run.seen, prices);
32
47
  }
33
48
 
34
- export function effectiveCaps(cfg, run) {
49
+ export function effectiveCaps(cfg, run, s = {}) {
35
50
  return {
36
- usd: cfg.capUsd != null ? cfg.capUsd + (run.extraUsd || 0) : null,
37
- tokens: cfg.capTokens != null ? cfg.capTokens + (run.extraTokens || 0) : null,
38
- fiveHourPct: cfg.capFiveHourPct != null ? cfg.capFiveHourPct + (run.extraPct || 0) : null,
51
+ usd: cfg.capUsd != null ? cfg.capUsd + (run?.extraUsd || 0) : null,
52
+ tokens: cfg.capTokens != null ? cfg.capTokens + (run?.extraTokens || 0) : null,
53
+ fiveHourPct: cfg.capFiveHourPct != null ? cfg.capFiveHourPct + (run?.extraPct || 0) : null,
54
+ sessionUsd: cfg.sessionCapUsd != null ? cfg.sessionCapUsd + (s.extraSessionUsd || 0) : null,
39
55
  };
40
56
  }
41
57
 
42
- function overCap(t, caps, s, cfg) {
43
- if (caps.usd != null && t.usd >= caps.usd) return `this run has used about ${usd(t.usd)} (cap ${usd(caps.usd)})`;
44
- if (caps.tokens != null && t.tokens >= caps.tokens) return `this run has used ${Math.round(t.tokens / 1000)}k tokens (cap ${Math.round(caps.tokens / 1000)}k)`;
58
+ function overCap(t, caps, s) {
59
+ if (caps.usd != null && t.usd >= caps.usd)
60
+ return { kind: 'usd', reason: `this run has used about ${usd(t.usd)} (cap ${usd(caps.usd)})`, amount: t.usd, cap: caps.usd };
61
+ if (caps.tokens != null && t.tokens >= caps.tokens)
62
+ return { kind: 'tokens', reason: `this run has used ${Math.round(t.tokens / 1000)}k tokens (cap ${Math.round(caps.tokens / 1000)}k)`, amount: t.tokens, cap: caps.tokens };
45
63
  const sl = s.statusline;
46
64
  if (caps.fiveHourPct != null && sl?.fiveHourPct != null && Date.now() - sl.at < 10 * 60e3 && sl.fiveHourPct >= caps.fiveHourPct)
47
- return `your 5-hour usage window is at ${Math.round(sl.fiveHourPct)}% (cap ${caps.fiveHourPct}%)`;
48
- if (cfg.sessionCapUsd != null && s.sessionUsd != null && s.sessionUsd >= cfg.sessionCapUsd) return `this session has used about ${usd(s.sessionUsd)} (session cap ${usd(cfg.sessionCapUsd)})`;
65
+ return { kind: 'fiveHour', reason: `your 5-hour usage window is at ${Math.round(sl.fiveHourPct)}% (cap ${Math.round(caps.fiveHourPct)}%)`, amount: sl.fiveHourPct, cap: caps.fiveHourPct };
66
+ if (caps.sessionUsd != null && s.sessionUsd != null && s.sessionUsd >= caps.sessionUsd)
67
+ return { kind: 'session', reason: `this session has used about ${usd(s.sessionUsd)} (session cap ${usd(caps.sessionUsd)})`, amount: s.sessionUsd, cap: caps.sessionUsd };
49
68
  return null;
50
69
  }
51
70
 
52
- /** UserPromptSubmit: a new run starts. */
71
+ function headroomLabel(hit, cfg) {
72
+ const pct = cfg.extendPct;
73
+ if (hit.kind === 'usd' && cfg.capUsd != null) return usd(cfg.capUsd * pct / 100);
74
+ if (hit.kind === 'session' && cfg.sessionCapUsd != null) return usd(cfg.sessionCapUsd * pct / 100);
75
+ if (hit.kind === 'tokens' && cfg.capTokens != null) return `${Math.round(cfg.capTokens * pct / 100 / 1000)}k tokens`;
76
+ return `${pct}%`;
77
+ }
78
+
79
+ /** Exact user-facing pause line. Do not wrap this in hook-error language. */
80
+ export function pauseMessage(hit) {
81
+ if (hit.kind === 'usd' || hit.kind === 'session')
82
+ return `Lake Meter paused the run at ${usd(hit.amount)} (cap ${usd(hit.cap)})`;
83
+ if (hit.kind === 'tokens')
84
+ return `Lake Meter paused the run at ${Math.round(hit.amount / 1000)}k tokens (cap ${Math.round(hit.cap / 1000)}k)`;
85
+ if (hit.kind === 'fiveHour')
86
+ return `Lake Meter paused the run at ${Math.round(hit.amount)}% of the 5-hour window (cap ${Math.round(hit.cap)}%)`;
87
+ return `Lake Meter paused the run: ${hit.reason}`;
88
+ }
89
+
90
+ function applyHeadroom(cfg, run, s, t, kinds) {
91
+ const pct = cfg.extendPct / 100;
92
+ for (const kind of kinds) {
93
+ if (kind === 'usd' && cfg.capUsd != null) {
94
+ const target = Math.max(t.usd, cfg.capUsd + (run.extraUsd || 0)) + cfg.capUsd * pct;
95
+ run.extraUsd = target - cfg.capUsd;
96
+ }
97
+ if (kind === 'tokens' && cfg.capTokens != null) {
98
+ run.extraTokens = Math.max(t.tokens, cfg.capTokens + (run.extraTokens || 0)) + cfg.capTokens * pct - cfg.capTokens;
99
+ }
100
+ if (kind === 'fiveHour' && cfg.capFiveHourPct != null) {
101
+ run.extraPct = Math.max(0, (s.statusline?.fiveHourPct ?? cfg.capFiveHourPct) - cfg.capFiveHourPct) + 5;
102
+ }
103
+ if (kind === 'session' && cfg.sessionCapUsd != null) {
104
+ const current = cfg.sessionCapUsd + (s.extraSessionUsd || 0);
105
+ const target = Math.max(s.sessionUsd ?? 0, current) + cfg.sessionCapUsd * pct;
106
+ s.extraSessionUsd = target - cfg.sessionCapUsd;
107
+ }
108
+ }
109
+ }
110
+
111
+ /** /meter (and /meter status, /meter cap, …) is itself a UserPromptSubmit; it must not start a new run. */
112
+ export function isMeterCommand(prompt) {
113
+ const p = String(prompt || '').trim();
114
+ if (/^\/meter\b/i.test(p)) return true;
115
+ if (/<(?:command-name|command_name)>\s*\/?meter\b/i.test(p)) return true;
116
+ return false;
117
+ }
118
+
119
+ /** UserPromptSubmit: a new run starts, unless this prompt is the /meter slash command. */
53
120
  export function onUserPromptSubmit(input) {
54
121
  const s = loadSession(input.session_id);
55
122
  if (input.transcript_path) s.transcriptPath = input.transcript_path;
@@ -59,17 +126,20 @@ export function onUserPromptSubmit(input) {
59
126
  const { entries, offset } = scanFile(f, s.offsets[f] || 0);
60
127
  s.offsets[f] = offset;
61
128
  absorb((s.sessionSeen ||= {}), entries, 0);
129
+ if (s.run) absorb(s.run.seen, entries, s.run.start);
130
+ }
131
+ if (!isMeterCommand(input.prompt)) {
132
+ const now = Date.now();
133
+ s.run = { start: now, seen: {}, extraUsd: 0, extraTokens: 0, extraPct: 0, capHits: 0, warned: false, pendingAsk: null, pendingAskKind: null, startedAt: now };
62
134
  }
63
- const now = Date.now();
64
- s.run = { start: now, seen: {}, extraUsd: 0, extraTokens: 0, extraPct: 0, capHits: 0, warned: false, pendingAsk: null, startedAt: now };
65
135
  saveSession(s);
66
136
  return null;
67
137
  }
68
138
 
69
139
  /** PreToolUse (all tools): enforce the cap; on ExitPlanMode also produce the plan breakdown. */
70
140
  export function onPreToolUse(input, prices = loadPrices()) {
71
- const cfg = loadConfig(input.cwd);
72
141
  const s = loadSession(input.session_id);
142
+ const { cfg, notice } = loadConfigNotices(input.cwd, s);
73
143
  const t = refresh(s, input, prices);
74
144
  const run = s.run;
75
145
  const out = { hookSpecificOutput: { hookEventName: 'PreToolUse' } };
@@ -90,22 +160,30 @@ export function onPreToolUse(input, prices = loadPrices()) {
90
160
  }
91
161
  }
92
162
 
93
- const caps = effectiveCaps(cfg, run);
94
- const reason = overCap(t, caps, s, cfg);
95
- if (reason) {
163
+ const caps = effectiveCaps(cfg, run, s);
164
+ const hit = overCap(t, caps, s);
165
+ if (hit) {
96
166
  run.capHits++;
97
- const ext = cfg.capUsd != null ? usd(cfg.capUsd * cfg.extendPct / 100) : `${cfg.extendPct}%`;
167
+ const ext = headroomLabel(hit, cfg);
98
168
  const unattended = cfg.onCap === 'stop' || UNATTENDED_MODES.has(input.permission_mode);
99
169
  if (unattended) {
170
+ const pause = pauseMessage(hit);
171
+ // continue:false is required to end the turn. Without it, bypass mode keeps
172
+ // calling tools and -p result is "Done.", not the pause line (M-26 / Claude Code).
100
173
  out.continue = false;
101
- out.stopReason = `Lake Meter paused the run: ${reason}. Reply "continue" to start a new run, or raise the cap with /meter cap <usd>.`;
174
+ out.stopReason = `${pause}. Reply "continue" to start a new run, or raise the cap with /meter cap <usd>.`;
175
+ // permissionDecision: deny is what actually blocks the tool in unattended modes.
176
+ // The reason must be the clear pause line — not "hook error" / "the user has been asked".
102
177
  out.hookSpecificOutput.permissionDecision = 'deny';
103
- out.hookSpecificOutput.permissionDecisionReason = `Lake Meter cap reached: ${reason}. The user has been asked how to proceed. Stop and wait for the user.`;
104
- appendRun({ session: input.session_id, start: run.start || null, end: Date.now(), usd: +t.usd.toFixed(4), tokens: t.tokens, output: t.output, cacheRead: t.cacheRead, requests: t.requests, byModel: t.byModel, subagentUsd: +t.subagent.usd.toFixed(4), capUsd: caps.usd, capHits: run.capHits, stoppedByCap: true });
178
+ out.hookSpecificOutput.permissionDecisionReason = pause;
179
+ out.systemMessage = `${pause}\n${runSummary(t, { cap: caps.usd ?? caps.sessionUsd, capHits: run.capHits })}`;
180
+ if (appendRun({ session: input.session_id, start: run.start || null, end: Date.now(), usd: +t.usd.toFixed(4), tokens: t.tokens, output: t.output, cacheRead: t.cacheRead, requests: t.requests, byModel: t.byModel, subagentUsd: +t.subagent.usd.toFixed(4), capUsd: caps.usd, capHits: run.capHits, stoppedByCap: true }))
181
+ run.logged = true;
105
182
  } else {
106
183
  run.pendingAsk = input.tool_use_id || 'pending';
184
+ run.pendingAskKind = hit.kind;
107
185
  out.hookSpecificOutput.permissionDecision = 'ask';
108
- out.hookSpecificOutput.permissionDecisionReason = `Lake Meter: ${reason}. Approve to continue with +${ext} headroom. Deny to stop here. Or run /meter cap <usd> to set a new cap.`;
186
+ out.hookSpecificOutput.permissionDecisionReason = `Lake Meter: ${hit.reason}. Approve to continue with +${ext} headroom. Deny to stop here. Or run /meter cap <usd> to set a new cap.`;
109
187
  }
110
188
  } else if (!run.warned && caps.usd && t.usd >= caps.usd * (cfg.warnPct / 100)) {
111
189
  run.warned = true;
@@ -113,9 +191,10 @@ export function onPreToolUse(input, prices = loadPrices()) {
113
191
  ctx.push(`Run spend is at ${Math.round((t.usd / caps.usd) * 100)}% of the user's per-run budget of ${usd(caps.usd)}. Tool calls will need the user's approval once it is reached.`);
114
192
  }
115
193
 
194
+ if (notice) msgs.push(notice);
116
195
  saveSession(s);
117
196
  if (ctx.length) out.hookSpecificOutput.additionalContext = ctx.join('\n');
118
- if (msgs.length) out.systemMessage = msgs.join('\n\n');
197
+ if (msgs.length) out.systemMessage = (out.systemMessage ? out.systemMessage + '\n\n' : '') + msgs.join('\n\n');
119
198
  const hso = out.hookSpecificOutput;
120
199
  if (!out.systemMessage && !hso.additionalContext && !hso.permissionDecision && out.continue === undefined) return null;
121
200
  return out;
@@ -163,13 +242,18 @@ export function onPostToolUse(input, prices = loadPrices()) {
163
242
  if (run.pendingAsk !== 'pending' && input.tool_use_id && input.tool_use_id !== run.pendingAsk) return null;
164
243
  const cfg = loadConfig(input.cwd);
165
244
  const t = totals(run.seen, prices);
166
- if (cfg.capUsd != null) {
167
- const target = Math.max(t.usd, cfg.capUsd + run.extraUsd) + cfg.capUsd * cfg.extendPct / 100;
168
- run.extraUsd = target - cfg.capUsd;
245
+ // Session totals may have been computed on the last PreToolUse; keep them current if we have statusline/sessionSeen.
246
+ if (s.sessionUsd == null && s.sessionSeen) {
247
+ try { s.sessionUsd = totals(s.sessionSeen, prices).usd; } catch { /* ignore */ }
169
248
  }
170
- if (cfg.capTokens != null) run.extraTokens = Math.max(t.tokens, cfg.capTokens + run.extraTokens) + cfg.capTokens * cfg.extendPct / 100 - cfg.capTokens;
171
- if (cfg.capFiveHourPct != null) run.extraPct = Math.max(0, (s.statusline?.fiveHourPct ?? cfg.capFiveHourPct) - cfg.capFiveHourPct) + 5;
249
+ const kinds = new Set();
250
+ if (run.pendingAskKind) kinds.add(run.pendingAskKind);
251
+ const still = overCap(t, effectiveCaps(cfg, run, s), s);
252
+ if (still) kinds.add(still.kind);
253
+ if (!kinds.size && cfg.capUsd != null) kinds.add('usd');
254
+ applyHeadroom(cfg, run, s, t, kinds);
172
255
  run.pendingAsk = null;
256
+ run.pendingAskKind = null;
173
257
  run.warned = true; // the user just chose to continue; no extra heads-up for this extension
174
258
  saveSession(s);
175
259
  return null;
@@ -178,8 +262,8 @@ export function onPostToolUse(input, prices = loadPrices()) {
178
262
  /** Stop: end-of-run summary (shown to the user, never blocks). */
179
263
  export async function onStop(input, prices = loadPrices(), { settleMs = 300 } = {}) {
180
264
  if (settleMs) await new Promise((r) => setTimeout(r, settleMs)); // transcript is written asynchronously
181
- const cfg = loadConfig(input.cwd);
182
265
  const s = loadSession(input.session_id);
266
+ const { cfg, notice } = loadConfigNotices(input.cwd, s);
183
267
  const t = refresh(s, input, prices);
184
268
  const run = s.run;
185
269
  let plan = null;
@@ -188,13 +272,19 @@ export async function onStop(input, prices = loadPrices(), { settleMs = 300 } =
188
272
  for (const f of sessionFiles(s.transcriptPath)) absorb(seen, scanFile(f, 0).entries, s.plan.createdAt);
189
273
  plan = { actualUsd: totals(seen, prices).usd, estimateUsd: s.plan.estimateUsd };
190
274
  }
191
- const caps = effectiveCaps(cfg, run);
275
+ const caps = effectiveCaps(cfg, run, s);
192
276
  const summary = runSummary(t, { cap: caps.usd, capHits: run.capHits, plan });
193
- appendRun({ session: input.session_id, start: run.start || null, end: Date.now(), usd: +t.usd.toFixed(4), tokens: t.tokens, output: t.output, cacheRead: t.cacheRead, requests: t.requests, byModel: t.byModel, subagentUsd: +t.subagent.usd.toFixed(4), capUsd: caps.usd, capHits: run.capHits, plan, statuslineSessionUsd: s.statusline?.costUsd ?? null });
277
+ const record = { session: input.session_id, start: run.start || null, end: Date.now(), usd: +t.usd.toFixed(4), tokens: t.tokens, output: t.output, cacheRead: t.cacheRead, requests: t.requests, byModel: t.byModel, subagentUsd: +t.subagent.usd.toFixed(4), capUsd: caps.usd, capHits: run.capHits, plan, statuslineSessionUsd: s.statusline?.costUsd ?? null };
278
+ // /meter and a second Stop after an unattended cap must not record or re-print the receipt (M-23).
279
+ if (run.logged || appendRun(record) === false) {
280
+ saveSession(s);
281
+ return notice ? { systemMessage: notice } : null;
282
+ }
283
+ run.logged = true;
194
284
  s.lastRun = { usd: t.usd, tokens: t.tokens, end: Date.now() };
195
285
  saveSession(s);
196
- if (!t.requests) return null;
197
- return { systemMessage: summary };
286
+ if (!t.requests) return notice ? { systemMessage: notice } : null;
287
+ return { systemMessage: [summary, notice].filter(Boolean).join('\n\n') };
198
288
  }
199
289
 
200
290
  /** statusLine command: show the meter, and keep Claude Code's own session cost + rate-limit % for cap checks. */
@@ -206,7 +296,7 @@ export function onStatusLine(input, prices = loadPrices()) {
206
296
  s.sessionUsd = s.statusline.costUsd ?? s.sessionUsd ?? null;
207
297
  const t = s.run ? totals(s.run.seen, prices) : null;
208
298
  saveSession(s);
209
- const caps = s.run ? effectiveCaps(cfg, s.run) : { usd: cfg.capUsd };
299
+ const caps = s.run ? effectiveCaps(cfg, s.run, s) : { usd: cfg.capUsd };
210
300
  const parts = ['◒ Lake'];
211
301
  if (t) parts.push(`run ${usd(t.usd)}${caps.usd != null ? ` / ${usd(caps.usd)}` : ''}`);
212
302
  if (s.statusline.costUsd != null) parts.push(`session ${usd(s.statusline.costUsd)}`);
package/src/init.js CHANGED
@@ -40,13 +40,27 @@ export function installRuntime() {
40
40
  return join(rt, 'bin', 'lake-meter.js');
41
41
  }
42
42
 
43
+
44
+ /** Cap display: $1,000.50 (not $1000.5). */
45
+ function formatCapUsd(n) {
46
+ if (n == null) return 'off';
47
+ const [ints, frac] = Number(n).toFixed(2).split('.');
48
+ return `$${ints.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}.${frac}`;
49
+ }
50
+ function capExample(n) {
51
+ if (n == null) return '10';
52
+ const v = Number(n);
53
+ return Number.isInteger(v) ? String(v) : v.toFixed(2);
54
+ }
55
+
43
56
  export function init(opts = {}) {
44
57
  const log = opts.log || console.log;
45
58
  const node = opts.node || process.execPath;
46
59
  const cli = opts.cli || installRuntime();
47
60
  const t = targets(opts);
48
61
  const settings = readJson(t.settings);
49
- if (existsSync(t.settings)) copyFileSync(t.settings, `${t.settings}.lake-meter.bak`);
62
+ const bak = `${t.settings}.lake-meter.bak`;
63
+ if (existsSync(t.settings) && !existsSync(bak)) copyFileSync(t.settings, bak);
50
64
  settings.hooks ||= {};
51
65
  const add = (evt, group) => {
52
66
  settings.hooks[evt] = (settings.hooks[evt] || []).filter((g) => !isOurs(g));
@@ -105,7 +119,8 @@ You implement one step of an approved plan. Stay inside the step's scope, follow
105
119
  log(`✓ Lake Meter installed in ${t.settings}`);
106
120
  log(` hooks: UserPromptSubmit, PreToolUse, PostToolUse, Stop · ${statusNote}`);
107
121
  log(` /meter skill: ${t.skillDir}${opts.agents !== false ? ` · subagents lake-light (haiku), lake-standard (sonnet) in ${t.agentsDir}` : ''}`);
108
- log(` per-run cap: ${'$'}${opts.capUsd ?? JSON.parse(readFileSync(join(home(), 'config.json'), 'utf8')).capUsd} (change with: npx lake-meter cap 10)`);
122
+ const capVal = opts.capUsd ?? JSON.parse(readFileSync(join(home(), 'config.json'), 'utf8')).capUsd;
123
+ log(` per-run cap: ${formatCapUsd(capVal)} (change with: npx lake-meter cap ${capExample(capVal)})`);
109
124
  log(' Restart Claude Code (or open /hooks) to load it. No data leaves your machine.');
110
125
  return t;
111
126
  }
package/src/mcp.js CHANGED
@@ -1,6 +1,7 @@
1
1
  // Minimal MCP server over stdio (JSON-RPC 2.0, newline-delimited), no dependencies.
2
2
  // Tools: estimate_plan (any MCP client: Claude Code, Cursor, ...) and meter_status (Claude Code sessions).
3
3
  import { createInterface } from 'node:readline';
4
+ import { readFileSync } from 'node:fs';
4
5
  import { loadPrices } from './pricing.js';
5
6
  import { analyzePlan } from './plan.js';
6
7
  import { planMarkdown, runSummary } from './format.js';
@@ -32,7 +33,7 @@ export function handle(msg, prices = loadPrices()) {
32
33
  const { id, method, params } = msg;
33
34
  const ok = (result) => ({ jsonrpc: '2.0', id, result });
34
35
  if (method === 'initialize') {
35
- return ok({ protocolVersion: params?.protocolVersion || '2025-06-18', capabilities: { tools: {} }, serverInfo: { name: 'lake-meter', version: '0.1.0' } });
36
+ return ok({ protocolVersion: params?.protocolVersion || '2025-06-18', capabilities: { tools: {} }, serverInfo: { name: 'lake-meter', version: JSON.parse(readFileSync(new URL('../package.json', import.meta.url))).version } });
36
37
  }
37
38
  if (method === 'notifications/initialized' || id === undefined) return null;
38
39
  if (method === 'ping') return ok({});
package/src/state.js CHANGED
@@ -15,6 +15,7 @@ export const DEFAULT_CONFIG = {
15
15
  extendPct: 50, // approving a cap prompt adds this % of the cap as headroom
16
16
  warnPct: 80, // one heads-up when a run passes this % of its cap
17
17
  provider: 'anthropic',
18
+ annotatePlans: true,
18
19
  };
19
20
 
20
21
  export function home() {
@@ -25,6 +26,21 @@ function readJson(p, fallback) {
25
26
  try { return JSON.parse(readFileSync(p, 'utf8')); } catch { return fallback; }
26
27
  }
27
28
 
29
+ /** Read a JSON object file. On missing file, returns fallback. On parse failure, warns and returns fallback without mutating the file. */
30
+ export function readConfigFile(p, fallback, warn = defaultWarn) {
31
+ if (!existsSync(p)) return fallback;
32
+ try {
33
+ return JSON.parse(readFileSync(p, 'utf8'));
34
+ } catch (err) {
35
+ warn(`lake-meter: could not parse ${p}: ${err.message}. Ignoring this file and using defaults for its values.`);
36
+ return fallback;
37
+ }
38
+ }
39
+
40
+ function defaultWarn(msg) {
41
+ process.stderr.write(msg.endsWith('\n') ? msg : msg + '\n');
42
+ }
43
+
28
44
  export function writeJsonAtomic(p, data) {
29
45
  mkdirSync(join(p, '..'), { recursive: true });
30
46
  const tmp = `${p}.${process.pid}.${Date.now()}.tmp`;
@@ -32,16 +48,129 @@ export function writeJsonAtomic(p, data) {
32
48
  renameSync(tmp, p);
33
49
  }
34
50
 
51
+ /**
52
+ * Parse a user-supplied USD cap (CLI --cap, `lake-meter cap`).
53
+ * Accepts optional leading $ and commas: 10, $10, "$10", 1,000.50.
54
+ * 'off' / 'none' (case-insensitive) clears the cap when allowOff is true.
55
+ */
56
+ export function parseCapUsd(raw, { allowOff = false } = {}) {
57
+ if (raw == null) return { ok: false };
58
+ const s = String(raw).trim();
59
+ if (allowOff && /^(off|none)$/i.test(s)) return { ok: true, value: null };
60
+ const n = Number(s.replace(/^\$/, '').replace(/,/g, ''));
61
+ if (!Number.isFinite(n) || n <= 0) return { ok: false };
62
+ return { ok: true, value: n };
63
+ }
64
+
65
+ const NUMERIC_KEYS = new Set(['capUsd', 'capTokens', 'capFiveHourPct', 'sessionCapUsd', 'extendPct', 'warnPct']);
66
+ const NULLABLE_CAPS = new Set(['capUsd', 'capTokens', 'capFiveHourPct', 'sessionCapUsd']);
67
+
68
+ function coerceNumber(value) {
69
+ if (typeof value === 'number' && Number.isFinite(value)) return { ok: true, value, coerced: false };
70
+ if (typeof value === 'string' && value.trim() !== '') {
71
+ const n = Number(value.trim().replace(/^\$/, '').replace(/,/g, ''));
72
+ if (Number.isFinite(n)) return { ok: true, value: n, coerced: true };
73
+ }
74
+ return { ok: false };
75
+ }
76
+
77
+ /** Validate and coerce a raw config object. Invalid or missing fields fall back to `base` (defaults, or already-normalized user config). */
78
+ export function normalizeConfig(raw, warn = defaultWarn, source = 'config', base = DEFAULT_CONFIG) {
79
+ const out = { ...base };
80
+ if (raw == null || typeof raw !== 'object' || Array.isArray(raw)) {
81
+ warn(`lake-meter: ${source} is not a JSON object; using previous values.`);
82
+ return out;
83
+ }
84
+ for (const key of Object.keys(DEFAULT_CONFIG)) {
85
+ if (!(key in raw)) continue;
86
+ const v = raw[key];
87
+ if (NUMERIC_KEYS.has(key)) {
88
+ if (v == null) {
89
+ if (NULLABLE_CAPS.has(key)) { out[key] = null; continue; }
90
+ warn(`lake-meter: ${source}: ${key} cannot be null; using ${out[key]}.`);
91
+ continue;
92
+ }
93
+ const n = coerceNumber(v);
94
+ if (!n.ok) {
95
+ warn(`lake-meter: ${source}: invalid ${key} ${JSON.stringify(v)}; using ${out[key]}.`);
96
+ continue;
97
+ }
98
+ if (n.coerced) warn(`lake-meter: ${source}: ${key} should be a number, not a string; using ${n.value}.`);
99
+ if (key === 'extendPct') {
100
+ if (!(n.value > 0)) {
101
+ warn(`lake-meter: ${source}: extendPct must be greater than 0; using ${out.extendPct}.`);
102
+ continue;
103
+ }
104
+ out[key] = n.value;
105
+ continue;
106
+ }
107
+ if (key === 'warnPct') {
108
+ if (n.value < 0 || n.value > 100) {
109
+ warn(`lake-meter: ${source}: warnPct must be between 0 and 100; using ${out.warnPct}.`);
110
+ continue;
111
+ }
112
+ out[key] = n.value;
113
+ continue;
114
+ }
115
+ if (n.value <= 0) {
116
+ warn(`lake-meter: ${source}: ${key} must be a positive number; using ${out[key]}.`);
117
+ continue;
118
+ }
119
+ out[key] = n.value;
120
+ continue;
121
+ }
122
+ if (key === 'onCap') {
123
+ const s = String(v).toLowerCase();
124
+ if (s === 'ask' || s === 'stop') { out.onCap = s; continue; }
125
+ warn(`lake-meter: ${source}: invalid onCap ${JSON.stringify(v)}; using '${out.onCap}'.`);
126
+ continue;
127
+ }
128
+ if (key === 'provider') {
129
+ const s = String(v).toLowerCase();
130
+ if (s === 'anthropic' || s === 'openai') { out.provider = s; continue; }
131
+ warn(`lake-meter: ${source}: invalid provider ${JSON.stringify(v)}; using '${out.provider}'.`);
132
+ continue;
133
+ }
134
+ if (key === 'annotatePlans') {
135
+ if (typeof v === 'boolean') { out.annotatePlans = v; continue; }
136
+ if (v === 'true' || v === 'false') {
137
+ out.annotatePlans = v === 'true';
138
+ warn(`lake-meter: ${source}: annotatePlans should be a boolean, not a string; using ${out.annotatePlans}.`);
139
+ continue;
140
+ }
141
+ warn(`lake-meter: ${source}: invalid annotatePlans ${JSON.stringify(v)}; using ${out.annotatePlans}.`);
142
+ }
143
+ }
144
+ // Keep unknown keys out of the runtime config so they cannot poison comparisons.
145
+ return out;
146
+ }
147
+
35
148
  /** Config = defaults < ~/.lake-meter/config.json < <project>/.lake-meter.json */
36
- export function loadConfig(cwd) {
37
- const user = readJson(join(home(), 'config.json'), {});
38
- const proj = cwd ? readJson(join(cwd, '.lake-meter.json'), {}) : {};
39
- return { ...DEFAULT_CONFIG, ...user, ...proj };
149
+ export function loadConfig(cwd, warn = defaultWarn) {
150
+ const userPath = join(home(), 'config.json');
151
+ const user = normalizeConfig(readConfigFile(userPath, {}, warn), warn, userPath);
152
+ if (!cwd) return user;
153
+ const projPath = join(cwd, '.lake-meter.json');
154
+ if (!existsSync(projPath)) return user;
155
+ const projRaw = readConfigFile(projPath, null, warn);
156
+ if (projRaw == null) return user;
157
+ return normalizeConfig(projRaw, warn, projPath, user);
40
158
  }
41
159
 
42
- export function saveUserConfig(patch) {
160
+ export function saveUserConfig(patch, warn = defaultWarn) {
43
161
  const p = join(home(), 'config.json');
44
- const cur = readJson(p, {});
162
+ let cur = {};
163
+ if (existsSync(p)) {
164
+ try {
165
+ cur = JSON.parse(readFileSync(p, 'utf8'));
166
+ } catch (err) {
167
+ // Throw only (no warn): callers print the message once (M-25).
168
+ throw new Error(`lake-meter: refusing to overwrite unparseable ${p}: ${err.message}. Fix or remove the file, then retry.`);
169
+ }
170
+ if (cur == null || typeof cur !== 'object' || Array.isArray(cur)) {
171
+ throw new Error(`lake-meter: refusing to overwrite ${p}: expected a JSON object.`);
172
+ }
173
+ }
45
174
  writeJsonAtomic(p, { ...cur, ...patch });
46
175
  }
47
176
 
@@ -72,9 +201,34 @@ export function latestSessionId() {
72
201
  return best;
73
202
  }
74
203
 
204
+ /** Identity of a recorded run: same session + same run start ⇒ the same run (M-23). */
205
+ export function runKey(record) {
206
+ if (record?.session && record.start) return `${record.session}:${record.start}`;
207
+ return null;
208
+ }
209
+
210
+ /** Dedupe by session+start so /meter or a later Stop cannot double-count the same run. Returns false if skipped. */
75
211
  export function appendRun(record) {
212
+ const key = runKey(record);
213
+ if (key && readRuns().some((r) => runKey(r) === key)) return false;
76
214
  mkdirSync(home(), { recursive: true });
77
215
  appendFileSync(join(home(), 'runs.jsonl'), JSON.stringify(record) + '\n');
216
+ return true;
217
+ }
218
+
219
+ /** First occurrence of each session+start, in file order (the original Stop, not a later /meter recopy). */
220
+ export function uniqueRuns(runs) {
221
+ const seen = new Set();
222
+ const out = [];
223
+ for (const r of runs) {
224
+ const k = runKey(r);
225
+ if (k) {
226
+ if (seen.has(k)) continue;
227
+ seen.add(k);
228
+ }
229
+ out.push(r);
230
+ }
231
+ return out;
78
232
  }
79
233
 
80
234
  export function readRuns() {