costclaw 0.2.3 → 0.3.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 (3) hide show
  1. package/README.md +65 -1
  2. package/dist/index.js +427 -89
  3. package/package.json +2 -1
package/README.md CHANGED
@@ -44,15 +44,44 @@ Top fixes by recoverable spend:
44
44
  Evidence: XX% of input tokens missed the cache across N sessions.
45
45
  ```
46
46
 
47
+ ## On a subscription? Declare your plan
48
+
49
+ Every dollar the audit prints is an API-equivalent price: what those tokens
50
+ would cost at pay-as-you-go rates. On a Claude subscription (Pro or Max) your
51
+ marginal token cost is zero, so those dollars are not money back - they measure
52
+ your rate-limit headroom. Declare your plan once and the audit reframes itself
53
+ honestly:
54
+
55
+ ```bash
56
+ npx costclaw audit --plan max20x # or pro, max5x; --plan api switches back
57
+ ```
58
+
59
+ The headline becomes recoverable usage - the share of your token consumption
60
+ you could win back - with the dollars demoted to API-equivalent context:
61
+
62
+ ```
63
+ Recoverable usage (cache-miss exposure): 14.3% of analyzed usage ($1134.61 at API rates)
64
+
65
+ Usage analyzed (API-equivalent): $7921.99 Cache hit: 96.2% Active hours: 1889.7
66
+ Plan: max20x. Dollar figures are API-equivalent token value, not money back;
67
+ recovering them buys rate-limit headroom (more work per usage window).
68
+ ```
69
+
70
+ The value is saved to `~/.costclaw/config.json`, so later runs (and `optimize`)
71
+ remember it. The findings and their ranking are identical either way; only the
72
+ unit is framed to match how you actually pay.
73
+
47
74
  ## Options
48
75
 
49
76
  ```
50
- costclaw audit [--path <dir>] [--claude-md <file>] [--json] [--html [file]] [--card [file]]
77
+ costclaw audit [--path <dir>] [--claude-md <file>] [--plan <plan>] [--json] [--html [file]] [--card [file]]
51
78
  ```
52
79
 
53
80
  - `--path <dir>` audit a specific projects directory (default `~/.claude/projects`).
54
81
  - `--claude-md <file>` score a specific CLAUDE.md file's quality (by default the
55
82
  audit scores `~/.claude/CLAUDE.md` when it exists).
83
+ - `--plan <api|pro|max5x|max20x>` declare how you pay for Claude (see above);
84
+ persisted for later runs.
56
85
  - `--json` print the raw, derived `AuditRecord` instead of the human report.
57
86
  - `--html [file]` also write a self-contained HTML report (default
58
87
  `costclaw-report.html` in the current directory) and open it in your browser.
@@ -65,6 +94,41 @@ costclaw audit [--path <dir>] [--claude-md <file>] [--json] [--html [file]] [--c
65
94
  Run `costclaw --version` (or `-v` / `costclaw version`) to print the installed
66
95
  CLI version.
67
96
 
97
+ ## Diff
98
+
99
+ Every audit run saves a snapshot of the derived record to `~/.costclaw/history`
100
+ (local, nothing uploaded). Run the audit again after you have made changes, then:
101
+
102
+ ```bash
103
+ npx costclaw diff
104
+ ```
105
+
106
+ That compares your latest two audits and shows the movement, so you can verify
107
+ the fixes actually recovered dollars:
108
+
109
+ ```
110
+ CostClaw diff
111
+ Baseline: 2026-06-09 Current: 2026-07-09 (30 days)
112
+
113
+ Since the baseline:
114
+ New spend $842.10 across 210 new sessions
115
+ Marginal cache hit 97.1% (lifetime 96.2%)
116
+ Recoverable exposure +$96.40 (now $1131.61)
117
+
118
+ Overall setup score: 83 -> 86 (+3, Tight)
119
+ CLAUDE.md quality 69 -> 78 (+9)
120
+ ...
121
+
122
+ Fixes resolved since the baseline:
123
+ - [$52.40] Use a cheaper model for 61 small sessions
124
+ ```
125
+
126
+ The marginal cache hit rate covers only the period between the two audits, which
127
+ a lifetime average hides. You can also diff two explicit records saved with
128
+ `costclaw audit --json`: `costclaw diff baseline.json current.json`. Add `--json`
129
+ for the machine-readable diff. Free, like the audit. The history keeps the newest
130
+ 50 snapshots and prunes older ones automatically.
131
+
68
132
  ## Badge
69
133
 
70
134
  ```bash
package/dist/index.js CHANGED
@@ -3,16 +3,14 @@
3
3
  // src/index.ts
4
4
  import { pathToFileURL } from "url";
5
5
 
6
- // src/audit-command.ts
7
- import { mkdir, readFile as readFile2, writeFile } from "fs/promises";
8
- import { join as join3, resolve } from "path";
9
- import { homedir as homedir3 } from "os";
10
- import { spawn } from "child_process";
11
-
12
6
  // ../../packages/engine/src/types.ts
13
7
  function emptyTotals() {
14
8
  return { input_tokens: 0, output_tokens: 0, cache_creation_tokens: 0, cache_read_tokens: 0 };
15
9
  }
10
+ var PLANS = ["api", "pro", "max5x", "max20x"];
11
+ function isPlan(value) {
12
+ return PLANS.includes(value);
13
+ }
16
14
 
17
15
  // ../../packages/engine/src/pricing.ts
18
16
  var PRICING_SNAPSHOT_DATE = "2026-05-13";
@@ -1212,16 +1210,17 @@ function sizeFix(cmd) {
1212
1210
  action: "Your CLAUDE.md is thin. Add the conventions, commands, and constraints the agent keeps getting wrong so it stops re-deriving them every session."
1213
1211
  };
1214
1212
  }
1215
- function synthesize(report, pillars, cmd) {
1213
+ function synthesize(report, pillars, cmd, plan = "api") {
1216
1214
  const headlineWasteUsd = cacheMissExposureUsd(report);
1217
- const headlineWasteLabel = "Recoverable spend (cache-miss exposure)";
1215
+ const headlineWasteLabel = plan === "api" ? "Recoverable spend (cache-miss exposure)" : "Recoverable usage (cache-miss exposure)";
1218
1216
  const spend = report.summary.cost_usd;
1217
+ const headlineWasteShare = spend > 0 ? headlineWasteUsd / spend : 0;
1219
1218
  const exposure = headlineWasteUsd;
1220
1219
  const fixes = [];
1221
1220
  const covered = /* @__PURE__ */ new Set();
1222
- const round22 = (n) => Math.round(n * 100) / 100;
1223
- const usd6 = (n) => {
1224
- const fixed = round22(n).toFixed(2);
1221
+ const round23 = (n) => Math.round(n * 100) / 100;
1222
+ const usd7 = (n) => {
1223
+ const fixed = round23(n).toFixed(2);
1225
1224
  const dot = fixed.indexOf(".");
1226
1225
  const whole = fixed.slice(0, dot).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
1227
1226
  return `$${whole}${fixed.slice(dot)}`;
@@ -1246,9 +1245,9 @@ function synthesize(report, pillars, cmd) {
1246
1245
  pillar: "context_hygiene",
1247
1246
  pillarName: PILLARS.context_hygiene.name,
1248
1247
  severity: sevForUsd(exposure),
1249
- wasteUsd: round22(exposure),
1248
+ wasteUsd: round23(exposure),
1250
1249
  problem: sanitizeText(
1251
- `Up to ${usd6(exposure)} of input spend was paid at full price instead of the cache-read rate. Biggest contributors: ${worst.length ? worst.join(", ") : "your largest projects"}.`
1250
+ `Up to ${usd7(exposure)} of input spend was paid at full price instead of the cache-read rate. Biggest contributors: ${worst.length ? worst.join(", ") : "your largest projects"}.`
1252
1251
  ),
1253
1252
  action: sanitizeText(
1254
1253
  "Keep the start of each session stable (a steady CLAUDE.md and consistent first reads) so the prompt cache is reused across turns and sessions."
@@ -1328,8 +1327,8 @@ function synthesize(report, pillars, cmd) {
1328
1327
  pillar: "cost_discipline",
1329
1328
  pillarName: PILLARS.cost_discipline.name,
1330
1329
  severity: sevForUsd(misrouteUsd),
1331
- wasteUsd: round22(misrouteUsd),
1332
- problem: sanitizeText(`${n} short Opus ${sWord(n)} with light tool use and small output cost about ${usd6(misrouteUsd)} more than a cheaper model would have.`),
1330
+ wasteUsd: round23(misrouteUsd),
1331
+ problem: sanitizeText(`${n} short Opus ${sWord(n)} with light tool use and small output cost about ${usd7(misrouteUsd)} more than a cheaper model would have.`),
1333
1332
  action: sanitizeText("Route short, simple sessions to a cheaper model such as Sonnet, and reserve Opus for hard reasoning."),
1334
1333
  basis: sanitizeText("Opus session cost minus the same tokens re-priced at the Sonnet rate, summed over sessions that pass a conservative triviality gate.")
1335
1334
  });
@@ -1342,8 +1341,8 @@ function synthesize(report, pillars, cmd) {
1342
1341
  pillar: "session_mgmt",
1343
1342
  pillarName: PILLARS.session_mgmt.name,
1344
1343
  severity: sevForUsd(marathonUsd),
1345
- wasteUsd: round22(marathonUsd),
1346
- problem: sanitizeText(`${n} long ${sWord(n)} kept growing until the prompt cache stopped helping, re-paying about ${usd6(marathonUsd)} for context in the later turns.`),
1344
+ wasteUsd: round23(marathonUsd),
1345
+ problem: sanitizeText(`${n} long ${sWord(n)} kept growing until the prompt cache stopped helping, re-paying about ${usd7(marathonUsd)} for context in the later turns.`),
1347
1346
  action: sanitizeText("Compact or start a fresh session between tasks so the context stays small and the cache keeps working."),
1348
1347
  basis: sanitizeText("Recoverable estimate from the late-session cache shortfall versus the early-session hit rate.")
1349
1348
  });
@@ -1356,7 +1355,7 @@ function synthesize(report, pillars, cmd) {
1356
1355
  pillarName: PILLARS.cost_discipline.name,
1357
1356
  severity: "info",
1358
1357
  wasteUsd: 0,
1359
- problem: sanitizeText(`Workflow and subagent runs cost about ${usd6(workflowUsd)}; they are a power tool that can quietly dominate spend.`),
1358
+ problem: sanitizeText(`Workflow and subagent runs cost about ${usd7(workflowUsd)}; they are a power tool that can quietly dominate spend.`),
1360
1359
  action: sanitizeText("Scope workflows to genuinely large tasks and budget the agent count; a single high-effort prompt often suffices."),
1361
1360
  basis: sanitizeText("Summed cost of delegated subagent and workflow sub-logs.")
1362
1361
  });
@@ -1388,6 +1387,7 @@ function synthesize(report, pillars, cmd) {
1388
1387
  return {
1389
1388
  headlineWasteUsd,
1390
1389
  headlineWasteLabel,
1390
+ headlineWasteShare,
1391
1391
  fixes
1392
1392
  };
1393
1393
  }
@@ -1878,7 +1878,7 @@ function toUsageMetrics(report) {
1878
1878
  cacheHitRate: round4(cacheHitRate(sess.totals))
1879
1879
  }));
1880
1880
  const modelBreakdown = {};
1881
- for (const [model, usd6] of Object.entries(s.modelBreakdown)) modelBreakdown[model] = round2(usd6);
1881
+ for (const [model, usd7] of Object.entries(s.modelBreakdown)) modelBreakdown[model] = round2(usd7);
1882
1882
  return {
1883
1883
  spendUsd: round2(s.cost_usd),
1884
1884
  cacheSavingsUsd: round2(s.cache_savings_usd),
@@ -1913,7 +1913,8 @@ function buildAudit(input, opts = {}) {
1913
1913
  const report = analyzeUploads(input.logs);
1914
1914
  const cmd = analyzeClaudeMd(input.claudeMd);
1915
1915
  const { pillars, overall, band } = scorePillars(report, cmd, input.questionnaire, input.setup);
1916
- const { headlineWasteUsd, headlineWasteLabel, fixes } = synthesize(report, pillars, cmd);
1916
+ const plan = input.plan ?? "api";
1917
+ const { headlineWasteUsd, headlineWasteLabel, headlineWasteShare, fixes } = synthesize(report, pillars, cmd, plan);
1917
1918
  const answered = Object.values(input.questionnaire).filter((v) => typeof v === "string" && v.length > 0).length;
1918
1919
  return {
1919
1920
  schemaVersion: "1",
@@ -1932,17 +1933,112 @@ function buildAudit(input, opts = {}) {
1932
1933
  band: { ...band, description: sanitizeText(band.description) },
1933
1934
  headlineWasteUsd: round2(headlineWasteUsd),
1934
1935
  headlineWasteLabel: sanitizeText(headlineWasteLabel),
1936
+ plan,
1937
+ headlineWasteShare: round4(headlineWasteShare),
1935
1938
  fixes: fixes.map(cleanFix),
1936
1939
  writer: opts.writer ?? "template",
1937
1940
  paid: false
1938
1941
  };
1939
1942
  }
1940
1943
 
1944
+ // ../../packages/engine/src/diff.ts
1945
+ var DIFF_SCHEMA_VERSION = "1";
1946
+ function round22(n) {
1947
+ return Math.round(n * 100) / 100;
1948
+ }
1949
+ function round42(n) {
1950
+ return Math.round(n * 1e4) / 1e4;
1951
+ }
1952
+ function assertRecord(r) {
1953
+ if (!r || typeof r !== "object" || !r.usageMetrics || !Array.isArray(r.pillarScores) || typeof r.overallScore !== "number" || typeof r.createdAt !== "string") {
1954
+ throw new Error("Not a costclaw audit record (run costclaw audit --json to produce one).");
1955
+ }
1956
+ }
1957
+ function side(r) {
1958
+ const m = r.usageMetrics;
1959
+ return {
1960
+ createdAt: r.createdAt,
1961
+ spendUsd: round22(m.spendUsd),
1962
+ recoverableUsd: round22(r.headlineWasteUsd),
1963
+ cacheHitRate: round42(m.cacheHitRate),
1964
+ overallScore: r.overallScore,
1965
+ band: r.band.label,
1966
+ sessionsCount: m.sessionsCount,
1967
+ plan: r.plan
1968
+ };
1969
+ }
1970
+ function diffAudits(a, b) {
1971
+ assertRecord(a);
1972
+ assertRecord(b);
1973
+ const [base, cur] = Date.parse(a.createdAt) <= Date.parse(b.createdAt) ? [a, b] : [b, a];
1974
+ const bm = base.usageMetrics;
1975
+ const cm = cur.usageMetrics;
1976
+ const newTokens = {
1977
+ input_tokens: cm.totalTokens.input_tokens - bm.totalTokens.input_tokens,
1978
+ output_tokens: cm.totalTokens.output_tokens - bm.totalTokens.output_tokens,
1979
+ cache_creation_tokens: cm.totalTokens.cache_creation_tokens - bm.totalTokens.cache_creation_tokens,
1980
+ cache_read_tokens: cm.totalTokens.cache_read_tokens - bm.totalTokens.cache_read_tokens
1981
+ };
1982
+ const newSpendUsd = cm.spendUsd - bm.spendUsd;
1983
+ const newSessions = cm.sessionsCount - bm.sessionsCount;
1984
+ const comparable = newSpendUsd >= -0.01 && newSessions >= 0 && Object.values(newTokens).every((t) => t >= 0);
1985
+ const periodMs = Date.parse(cur.createdAt) - Date.parse(base.createdAt);
1986
+ const periodDays = round22(Math.max(0, periodMs) / 864e5);
1987
+ const pillars = base.pillarScores.map((bp) => {
1988
+ const cp = cur.pillarScores.find((p) => p.id === bp.id);
1989
+ const before = bp.assessed ? bp.score : null;
1990
+ const after = cp && cp.assessed ? cp.score : null;
1991
+ return {
1992
+ id: bp.id,
1993
+ name: bp.name,
1994
+ before,
1995
+ after,
1996
+ delta: before !== null && after !== null ? after - before : null
1997
+ };
1998
+ });
1999
+ const baseFixes = new Map(base.fixes.map((f) => [f.id, f]));
2000
+ const curFixes = new Map(cur.fixes.map((f) => [f.id, f]));
2001
+ const resolved = base.fixes.filter((f) => !curFixes.has(f.id)).map((f) => ({ id: f.id, title: f.title, wasteUsd: round22(f.wasteUsd) }));
2002
+ const appeared = cur.fixes.filter((f) => !baseFixes.has(f.id)).map((f) => ({ id: f.id, title: f.title, wasteUsd: round22(f.wasteUsd) }));
2003
+ const changed = cur.fixes.filter((f) => baseFixes.has(f.id)).map((f) => {
2004
+ const beforeUsd = round22(baseFixes.get(f.id).wasteUsd);
2005
+ const afterUsd = round22(f.wasteUsd);
2006
+ return { id: f.id, title: f.title, beforeUsd, afterUsd, deltaUsd: round22(afterUsd - beforeUsd) };
2007
+ }).filter((c) => Math.abs(c.deltaUsd) >= 0.01);
2008
+ return {
2009
+ schemaVersion: DIFF_SCHEMA_VERSION,
2010
+ baseline: side(base),
2011
+ current: side(cur),
2012
+ periodDays,
2013
+ comparable,
2014
+ marginal: comparable ? {
2015
+ newSpendUsd: round22(newSpendUsd),
2016
+ newSessions,
2017
+ marginalCacheHitRate: round42(cacheHitRate(newTokens)),
2018
+ newTokens
2019
+ } : null,
2020
+ deltas: {
2021
+ spendUsd: round22(cm.spendUsd - bm.spendUsd),
2022
+ recoverableUsd: round22(cur.headlineWasteUsd - base.headlineWasteUsd),
2023
+ overallScore: cur.overallScore - base.overallScore,
2024
+ cacheHitRatePoints: round42(cm.cacheHitRate - bm.cacheHitRate)
2025
+ },
2026
+ pillars,
2027
+ fixes: { resolved, appeared, changed }
2028
+ };
2029
+ }
2030
+
1941
2031
  // ../../packages/engine/src/validate.ts
1942
2032
  var MAX_FILE_BYTES = 25 * 1024 * 1024;
1943
2033
  var MAX_TOTAL_BYTES = 60 * 1024 * 1024;
1944
2034
  var MAX_CLAUDEMD_BYTES = 1 * 1024 * 1024;
1945
2035
 
2036
+ // src/audit-command.ts
2037
+ import { mkdir as mkdir2, readFile as readFile3, readdir as readdir2, rm, writeFile as writeFile2 } from "fs/promises";
2038
+ import { join as join4, resolve } from "path";
2039
+ import { homedir as homedir3 } from "os";
2040
+ import { spawn } from "child_process";
2041
+
1946
2042
  // src/read-sessions.ts
1947
2043
  import { readdir } from "fs/promises";
1948
2044
  import { readFileSync, openSync, closeSync } from "fs";
@@ -2044,7 +2140,7 @@ function modelMix(breakdown) {
2044
2140
  }
2045
2141
  const total = [...merged.values()].reduce((a, b) => a + b, 0);
2046
2142
  if (total <= 0) return null;
2047
- const parts = [...merged.entries()].sort((a, b) => b[1] - a[1]).map(([name, spend]) => [name, Math.round(spend / total * 100)]).filter(([, pct]) => pct >= 1).map(([name, pct]) => `${name} ${pct}%`);
2143
+ const parts = [...merged.entries()].sort((a, b) => b[1] - a[1]).map(([name, spend]) => [name, Math.round(spend / total * 100)]).filter(([, pct2]) => pct2 >= 1).map(([name, pct2]) => `${name} ${pct2}%`);
2048
2144
  return parts.length > 0 ? parts.join(" / ") : null;
2049
2145
  }
2050
2146
  function unassessedLine(pillars) {
@@ -2059,17 +2155,33 @@ function unassessedLine(pillars) {
2059
2155
  }
2060
2156
  function formatAudit(record, meta) {
2061
2157
  const m = record.usageMetrics;
2158
+ const subscription = record.plan !== void 0 && record.plan !== "api";
2159
+ const share = record.headlineWasteShare ?? (m.spendUsd > 0 ? record.headlineWasteUsd / m.spendUsd : 0);
2160
+ const shareText = `${(share * 100).toFixed(1)}%`;
2062
2161
  const lines = [];
2063
2162
  lines.push("CostClaw audit");
2064
2163
  lines.push(`Source: ${meta.root} (${meta.sessionCount} sessions across ${m.projectsCount} projects)`);
2065
2164
  if (meta.claudeMdSource) lines.push(`CLAUDE.md: ${meta.claudeMdSource}`);
2066
2165
  lines.push("");
2067
- lines.push(`${record.headlineWasteLabel}: ${usd2(record.headlineWasteUsd)}`);
2166
+ lines.push(
2167
+ subscription ? `${record.headlineWasteLabel}: ${shareText} of analyzed usage (${usd2(record.headlineWasteUsd)} at API rates)` : `${record.headlineWasteLabel}: ${usd2(record.headlineWasteUsd)}`
2168
+ );
2068
2169
  lines.push("");
2069
- lines.push(`Spend analyzed: ${usd2(m.spendUsd)} Cache hit: ${(m.cacheHitRate * 100).toFixed(1)}% Active hours: ${m.durationHours.toFixed(1)}`);
2170
+ lines.push(
2171
+ `${subscription ? "Usage analyzed (API-equivalent)" : "Spend analyzed"}: ${usd2(m.spendUsd)} Cache hit: ${(m.cacheHitRate * 100).toFixed(1)}% Active hours: ${m.durationHours.toFixed(1)}`
2172
+ );
2070
2173
  lines.push(`Pricing snapshot: ${m.pricingSnapshotDate}`);
2071
2174
  const mix = modelMix(m.modelBreakdown);
2072
2175
  if (mix) lines.push(`Model spend: ${mix}`);
2176
+ if (subscription) {
2177
+ lines.push(
2178
+ `Plan: ${record.plan}. Dollar figures are API-equivalent token value, not money back; recovering them buys rate-limit headroom (more work per usage window).`
2179
+ );
2180
+ } else if (meta.planSource === "default") {
2181
+ lines.push(
2182
+ "Dollar figures are API-equivalent rates. On a Claude subscription? Rerun with --plan max20x (or pro, max5x) to frame results as token efficiency."
2183
+ );
2184
+ }
2073
2185
  if (m.topProjects.length > 0) {
2074
2186
  lines.push("");
2075
2187
  lines.push("Top projects by spend:");
@@ -2211,6 +2323,7 @@ h2 { font-size: 18px; margin: 40px 0 14px; color: #822d1d; }
2211
2323
  }
2212
2324
  .banner .label { font-size: 14px; text-transform: uppercase; letter-spacing: 0.08em; opacity: 0.9; }
2213
2325
  .banner .amount { font-size: 40px; font-weight: 700; margin-top: 4px; letter-spacing: -0.02em; }
2326
+ .banner .amount-sub { font-size: 15px; font-weight: 500; margin-top: 2px; opacity: 0.9; }
2214
2327
  .stats { display: flex; flex-wrap: wrap; gap: 14px; margin: 18px 0 0; }
2215
2328
  .stat { flex: 1 1 150px; padding: 14px 16px; background: #fff; border: 1px solid #f0e2da; border-radius: 10px; }
2216
2329
  .stat .k { font-size: 12px; color: #7a6a63; text-transform: uppercase; letter-spacing: 0.05em; }
@@ -2244,6 +2357,12 @@ ul.fixes { list-style: none; margin: 0; padding: 0; }
2244
2357
  function renderHtml(record, meta) {
2245
2358
  const m = record.usageMetrics;
2246
2359
  const mix = modelMix(m.modelBreakdown);
2360
+ const subscription = record.plan !== void 0 && record.plan !== "api";
2361
+ const share = record.headlineWasteShare ?? (m.spendUsd > 0 ? record.headlineWasteUsd / m.spendUsd : 0);
2362
+ const shareText = `${(share * 100).toFixed(1)}%`;
2363
+ const bannerAmount = subscription ? `<div class="amount">${shareText} of analyzed usage</div><div class="amount-sub">${esc(usd3(record.headlineWasteUsd))} at API rates</div>` : `<div class="amount">${esc(usd3(record.headlineWasteUsd))}</div>`;
2364
+ const spendLabel = subscription ? "Usage analyzed (API-equivalent)" : "Spend analyzed";
2365
+ const planNote = subscription ? `<p class="sub">Plan: ${esc(record.plan)}. Dollar figures are API-equivalent token value, not money back; recovering them buys rate-limit headroom (more work per usage window).</p>` : meta.planSource === "default" ? `<p class="sub">Dollar figures are API-equivalent rates. On a Claude subscription? Rerun with --plan max20x (or pro, max5x) to frame results as token efficiency.</p>` : "";
2247
2366
  const dollarFixes = record.fixes.filter((f) => f.wasteUsd > 0).sort((a, b) => b.wasteUsd - a.wasteUsd);
2248
2367
  const otherIssues = record.fixes.filter((f) => f.wasteUsd === 0);
2249
2368
  const dollarSection = dollarFixes.length === 0 ? `<p class="muted">No directly recoverable dollars found. See issues below.</p>` : `<ul class="fixes">${dollarFixes.map(dollarFixCard).join("")}</ul>`;
@@ -2266,11 +2385,11 @@ ${meta.claudeMdSource ? `<p class="sub">CLAUDE.md: ${esc(meta.claudeMdSource)}</
2266
2385
 
2267
2386
  <div class="banner">
2268
2387
  <div class="label">${esc(record.headlineWasteLabel)}</div>
2269
- <div class="amount">${esc(usd3(record.headlineWasteUsd))}</div>
2388
+ ${bannerAmount}
2270
2389
  </div>
2271
-
2390
+ ${planNote}
2272
2391
  <div class="stats">
2273
- <div class="stat"><div class="k">Spend analyzed</div><div class="v">${esc(usd3(m.spendUsd))}</div></div>
2392
+ <div class="stat"><div class="k">${spendLabel}</div><div class="v">${esc(usd3(m.spendUsd))}</div></div>
2274
2393
  <div class="stat"><div class="k">Cache hit rate</div><div class="v">${(m.cacheHitRate * 100).toFixed(1)}%</div></div>
2275
2394
  <div class="stat"><div class="k">Active hours</div><div class="v">${m.durationHours.toFixed(1)}</div></div>
2276
2395
  ${mix ? `<div class="stat"><div class="k">Model spend</div><div class="v v-small">${esc(mix)}</div></div>` : ""}
@@ -2322,7 +2441,10 @@ function renderCard(record) {
2322
2441
  const strongest = strongestPillar(record.pillarScores);
2323
2442
  const strongestText = strongest ? `${strongest.name} (${strongest.score})` : "n/a";
2324
2443
  const cacheHitPct = `${(record.usageMetrics.cacheHitRate * 100).toFixed(1)}%`;
2325
- const wasteText = usd4(record.headlineWasteUsd);
2444
+ const subscription = record.plan !== void 0 && record.plan !== "api";
2445
+ const spend = record.usageMetrics.spendUsd;
2446
+ const share = record.headlineWasteShare ?? (spend > 0 ? record.headlineWasteUsd / spend : 0);
2447
+ const wasteLine = subscription ? `Recoverable usage: ${(share * 100).toFixed(1)}%` : `Recoverable spend: ${usd4(record.headlineWasteUsd)}`;
2326
2448
  const ariaLabel = `CostClaw score ${record.overallScore} of 100, ${record.band.label}`;
2327
2449
  const scoreText = String(record.overallScore);
2328
2450
  const scoreX = 32;
@@ -2335,7 +2457,7 @@ function renderCard(record) {
2335
2457
  const statX = 32;
2336
2458
  const statY = 224;
2337
2459
  const statGap = 30;
2338
- return `<svg xmlns="http://www.w3.org/2000/svg" width="${WIDTH}" height="${HEIGHT}" viewBox="0 0 ${WIDTH} ${HEIGHT}" role="img" aria-label="${esc(ariaLabel)}">` + rect(0, 0, WIDTH, HEIGHT, PAPER, 16) + `<rect x="0.5" y="0.5" width="${WIDTH - 1}" height="${HEIGHT - 1}" rx="16" fill="none" stroke="${BORDER}"></rect>` + text(32, 48, "CostClaw", { size: 22, weight: 700, fill: UMBER }) + text(scoreX, 150, scoreText, { size: 72, weight: 700, fill: INK }) + text(outOf100X, 150, "/ 100", { size: 22, weight: 600, fill: MUTED }) + rect(32, pillY, pillW, pillH, scoreColor, 15) + text(32 + pillW / 2, pillY + pillH / 2 + 5, pillLabel, { size: 14, weight: 700, fill: "#ffffff", anchor: "middle" }) + text(statX, statY, `Recoverable spend: ${wasteText}`, { size: 15, weight: 600, fill: INK }) + text(statX, statY + statGap, `Cache hit rate: ${cacheHitPct}`, { size: 15, weight: 600, fill: INK }) + text(statX, statY + statGap * 2, `Strongest pillar: ${strongestText}`, { size: 15, weight: 600, fill: INK }) + `</svg>`;
2460
+ return `<svg xmlns="http://www.w3.org/2000/svg" width="${WIDTH}" height="${HEIGHT}" viewBox="0 0 ${WIDTH} ${HEIGHT}" role="img" aria-label="${esc(ariaLabel)}">` + rect(0, 0, WIDTH, HEIGHT, PAPER, 16) + `<rect x="0.5" y="0.5" width="${WIDTH - 1}" height="${HEIGHT - 1}" rx="16" fill="none" stroke="${BORDER}"></rect>` + text(32, 48, "CostClaw", { size: 22, weight: 700, fill: UMBER }) + text(scoreX, 150, scoreText, { size: 72, weight: 700, fill: INK }) + text(outOf100X, 150, "/ 100", { size: 22, weight: 600, fill: MUTED }) + rect(32, pillY, pillW, pillH, scoreColor, 15) + text(32 + pillW / 2, pillY + pillH / 2 + 5, pillLabel, { size: 14, weight: 700, fill: "#ffffff", anchor: "middle" }) + text(statX, statY, wasteLine, { size: 15, weight: 600, fill: INK }) + text(statX, statY + statGap, `Cache hit rate: ${cacheHitPct}`, { size: 15, weight: 600, fill: INK }) + text(statX, statY + statGap * 2, `Strongest pillar: ${strongestText}`, { size: 15, weight: 600, fill: INK }) + `</svg>`;
2339
2461
  }
2340
2462
 
2341
2463
  // src/read-setup.ts
@@ -2383,9 +2505,49 @@ async function readSetup(home = homedir2()) {
2383
2505
  };
2384
2506
  }
2385
2507
 
2508
+ // src/config.ts
2509
+ import { mkdir, readFile as readFile2, writeFile } from "fs/promises";
2510
+ import { join as join3 } from "path";
2511
+ function configFile(dir) {
2512
+ return join3(dir, "config.json");
2513
+ }
2514
+ async function readRaw(dir) {
2515
+ try {
2516
+ const parsed = JSON.parse(await readFile2(configFile(dir), "utf8"));
2517
+ return parsed !== null && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
2518
+ } catch {
2519
+ return {};
2520
+ }
2521
+ }
2522
+ async function readCliConfig(dir) {
2523
+ const raw = await readRaw(dir);
2524
+ const cfg = {};
2525
+ if (typeof raw["plan"] === "string" && isPlan(raw["plan"])) cfg.plan = raw["plan"];
2526
+ return cfg;
2527
+ }
2528
+ async function saveCliConfig(dir, patch) {
2529
+ const merged = { ...await readRaw(dir), ...patch };
2530
+ await mkdir(dir, { recursive: true });
2531
+ await writeFile(configFile(dir), JSON.stringify(merged, null, 2), "utf8");
2532
+ }
2533
+
2386
2534
  // src/audit-command.ts
2535
+ async function resolvePlan(configDir, flag) {
2536
+ if (flag) {
2537
+ try {
2538
+ await saveCliConfig(configDir, { plan: flag });
2539
+ } catch (err) {
2540
+ process.stderr.write(`Could not save the plan setting: ${err instanceof Error ? err.message : String(err)}
2541
+ `);
2542
+ }
2543
+ return { plan: flag, planSource: "flag" };
2544
+ }
2545
+ const saved = (await readCliConfig(configDir)).plan;
2546
+ return saved ? { plan: saved, planSource: "config" } : { plan: "api", planSource: "default" };
2547
+ }
2387
2548
  var DEFAULT_HTML_FILE = "costclaw-report.html";
2388
2549
  var DEFAULT_CARD_FILE = "costclaw-card.svg";
2550
+ var SNAPSHOT_KEEP = 50;
2389
2551
  function openInBrowser(target) {
2390
2552
  try {
2391
2553
  const platform = process.platform;
@@ -2406,12 +2568,12 @@ async function loadAuditInputs(opts) {
2406
2568
  let claudeMd;
2407
2569
  let claudeMdSource = null;
2408
2570
  if (opts.claudeMdPath) {
2409
- claudeMd = await readFile2(opts.claudeMdPath, "utf8");
2571
+ claudeMd = await readFile3(opts.claudeMdPath, "utf8");
2410
2572
  claudeMdSource = resolve(opts.claudeMdPath);
2411
2573
  } else {
2412
- const fallback = join3(opts.home ?? homedir3(), ".claude", "CLAUDE.md");
2574
+ const fallback = join4(opts.home ?? homedir3(), ".claude", "CLAUDE.md");
2413
2575
  try {
2414
- claudeMd = await readFile2(fallback, "utf8");
2576
+ claudeMd = await readFile3(fallback, "utf8");
2415
2577
  claudeMdSource = fallback;
2416
2578
  } catch {
2417
2579
  }
@@ -2425,32 +2587,38 @@ async function runAudit(opts) {
2425
2587
  home: opts.home
2426
2588
  });
2427
2589
  const setup = await readSetup();
2428
- const record = buildAudit({ logs, claudeMd, questionnaire: {}, setup });
2590
+ const configDir = join4(opts.home ?? homedir3(), ".costclaw");
2591
+ const { plan, planSource } = await resolvePlan(configDir, opts.plan);
2592
+ const record = buildAudit({ logs, claudeMd, questionnaire: {}, setup, plan });
2429
2593
  let snapshotNotice = null;
2430
2594
  try {
2431
- const historyDir = join3(opts.home ?? homedir3(), ".costclaw", "history");
2432
- await mkdir(historyDir, { recursive: true });
2595
+ const historyDir = join4(opts.home ?? homedir3(), ".costclaw", "history");
2596
+ await mkdir2(historyDir, { recursive: true });
2433
2597
  const name = record.createdAt.replace(/[:.]/g, "-") + ".json";
2434
- await writeFile(join3(historyDir, name), JSON.stringify(record, null, 2), "utf8");
2598
+ await writeFile2(join4(historyDir, name), JSON.stringify(record, null, 2), "utf8");
2599
+ const snapshots = (await readdir2(historyDir)).filter((f) => f.endsWith(".json")).sort();
2600
+ for (const stale of snapshots.slice(0, Math.max(0, snapshots.length - SNAPSHOT_KEEP))) {
2601
+ await rm(join4(historyDir, stale), { force: true });
2602
+ }
2435
2603
  snapshotNotice = "Snapshot saved for costclaw diff.";
2436
2604
  } catch (err) {
2437
2605
  process.stderr.write(`Could not save the audit snapshot: ${err instanceof Error ? err.message : String(err)}
2438
2606
  `);
2439
2607
  }
2440
- let output = opts.json ? JSON.stringify(record, null, 2) : formatAudit(record, { root, sessionCount: logs.length, skipped, claudeMdSource });
2608
+ let output = opts.json ? JSON.stringify(record, null, 2) : formatAudit(record, { root, sessionCount: logs.length, skipped, claudeMdSource, planSource });
2441
2609
  const notices = [];
2442
2610
  if (snapshotNotice) notices.push(snapshotNotice);
2443
2611
  if (opts.html) {
2444
2612
  const target = resolve(opts.htmlPath || DEFAULT_HTML_FILE);
2445
- const doc = renderHtml(record, { root, sessionCount: logs.length, skipped, claudeMdSource });
2446
- await writeFile(target, doc, "utf8");
2613
+ const doc = renderHtml(record, { root, sessionCount: logs.length, skipped, claudeMdSource, planSource });
2614
+ await writeFile2(target, doc, "utf8");
2447
2615
  openInBrowser(target);
2448
2616
  notices.push(`HTML report written to ${target}`);
2449
2617
  }
2450
2618
  if (opts.card) {
2451
2619
  const target = resolve(opts.cardPath || DEFAULT_CARD_FILE);
2452
2620
  const svg = renderCard(record);
2453
- await writeFile(target, svg, "utf8");
2621
+ await writeFile2(target, svg, "utf8");
2454
2622
  notices.push(`Score card written to ${target}`);
2455
2623
  }
2456
2624
  if (opts.json) {
@@ -2462,12 +2630,13 @@ async function runAudit(opts) {
2462
2630
  }
2463
2631
 
2464
2632
  // src/optimize-command.ts
2465
- import { mkdir as mkdir2, writeFile as writeFile2, readFile as readFile4, stat as stat2 } from "fs/promises";
2466
- import { join as join5, dirname } from "path";
2633
+ import { mkdir as mkdir3, writeFile as writeFile3, readFile as readFile5, stat as stat2 } from "fs/promises";
2634
+ import { join as join6, dirname } from "path";
2635
+ import { homedir as homedir4 } from "os";
2467
2636
 
2468
2637
  // src/project-scan.ts
2469
- import { readdir as readdir2, readFile as readFile3, stat } from "fs/promises";
2470
- import { join as join4, basename } from "path";
2638
+ import { readdir as readdir3, readFile as readFile4, stat } from "fs/promises";
2639
+ import { join as join5, basename } from "path";
2471
2640
  var NOISE_DIRS = /* @__PURE__ */ new Set([
2472
2641
  "node_modules",
2473
2642
  ".git",
@@ -2496,7 +2665,7 @@ var DIR_NOTES = {
2496
2665
  };
2497
2666
  async function readText(p) {
2498
2667
  try {
2499
- return await readFile3(p, "utf8");
2668
+ return await readFile4(p, "utf8");
2500
2669
  } catch {
2501
2670
  return null;
2502
2671
  }
@@ -2506,7 +2675,7 @@ async function listEntries(dir) {
2506
2675
  const dirs = [];
2507
2676
  let entries;
2508
2677
  try {
2509
- entries = await readdir2(dir, { withFileTypes: true });
2678
+ entries = await readdir3(dir, { withFileTypes: true });
2510
2679
  } catch {
2511
2680
  return { files, dirs };
2512
2681
  }
@@ -2607,7 +2776,7 @@ async function detectTestsLocation(dir, files, dirs) {
2607
2776
  if (dirs.includes("__tests__")) return "tests in __tests__/";
2608
2777
  if (files.some((f) => /\.(test|spec)\.[cm]?[jt]sx?$/.test(f))) return "tests alongside source (*.test.* / *.spec.*)";
2609
2778
  if (dirs.includes("src")) {
2610
- const sub = await listEntries(join4(dir, "src"));
2779
+ const sub = await listEntries(join5(dir, "src"));
2611
2780
  if (sub.files.some((f) => /\.(test|spec)\.[cm]?[jt]sx?$/.test(f))) {
2612
2781
  return "tests alongside source (*.test.* / *.spec.*)";
2613
2782
  }
@@ -2690,7 +2859,7 @@ async function scanNode(dir, files, dirs, pkg, profile) {
2690
2859
  if (oneFileCmd !== null && "test" in scripts) {
2691
2860
  profile.commands.push({ label: "test one file", command: oneFileCmd });
2692
2861
  }
2693
- const tsconfig = parseJson(await readText(join4(dir, "tsconfig.json")));
2862
+ const tsconfig = parseJson(await readText(join5(dir, "tsconfig.json")));
2694
2863
  if (tsconfig) {
2695
2864
  const co = tsconfig.compilerOptions;
2696
2865
  if (co && co.strict === true) pushUnique(profile.codeStyle, "TypeScript strict mode");
@@ -2793,7 +2962,7 @@ async function scanPython(dir, files, profile) {
2793
2962
  const deps = [];
2794
2963
  const tables = /* @__PURE__ */ new Set();
2795
2964
  let hasPoetry = false;
2796
- const pyprojectText = await readText(join4(dir, "pyproject.toml"));
2965
+ const pyprojectText = await readText(join5(dir, "pyproject.toml"));
2797
2966
  if (pyprojectText !== null) {
2798
2967
  const parsed = parsePyproject(pyprojectText);
2799
2968
  name = parsed.name;
@@ -2803,7 +2972,7 @@ async function scanPython(dir, files, profile) {
2803
2972
  hasPoetry = parsed.hasPoetry;
2804
2973
  }
2805
2974
  if (files.includes("requirements.txt")) {
2806
- const reqText = await readText(join4(dir, "requirements.txt"));
2975
+ const reqText = await readText(join5(dir, "requirements.txt"));
2807
2976
  if (reqText !== null) for (const d of pyDepsFromRequirements(reqText)) pushUnique(deps, d);
2808
2977
  }
2809
2978
  if (name !== null && name.trim() !== "") profile.name = name;
@@ -2837,7 +3006,7 @@ async function scanPython(dir, files, profile) {
2837
3006
  }
2838
3007
  }
2839
3008
  async function scanRust(dir, profile) {
2840
- const text2 = await readText(join4(dir, "Cargo.toml"));
3009
+ const text2 = await readText(join5(dir, "Cargo.toml"));
2841
3010
  pushUnique(profile.stack, "Rust");
2842
3011
  profile.packageManager = "cargo";
2843
3012
  if (text2 !== null) {
@@ -2863,7 +3032,7 @@ async function scanRust(dir, profile) {
2863
3032
  profile.commands.push({ label: "lint", command: "cargo clippy" });
2864
3033
  }
2865
3034
  async function scanGo(dir, profile) {
2866
- const text2 = await readText(join4(dir, "go.mod"));
3035
+ const text2 = await readText(join5(dir, "go.mod"));
2867
3036
  pushUnique(profile.stack, "Go");
2868
3037
  profile.packageManager = "go";
2869
3038
  if (text2 !== null) {
@@ -2928,7 +3097,7 @@ async function scanProject(dir) {
2928
3097
  const profile = emptyProfile(basename(dir));
2929
3098
  const { files, dirs } = await listEntries(dir);
2930
3099
  if (files.includes("package.json")) {
2931
- const pkg = parseJson(await readText(join4(dir, "package.json")));
3100
+ const pkg = parseJson(await readText(join5(dir, "package.json")));
2932
3101
  if (pkg) await scanNode(dir, files, dirs, pkg, profile);
2933
3102
  }
2934
3103
  if (files.includes("pyproject.toml") || files.includes("requirements.txt") || files.includes("setup.py")) {
@@ -2941,7 +3110,7 @@ async function scanProject(dir) {
2941
3110
  await scanGo(dir, profile);
2942
3111
  }
2943
3112
  if (files.includes("Makefile") && profile.commands.length === 0) {
2944
- const text2 = await readText(join4(dir, "Makefile"));
3113
+ const text2 = await readText(join5(dir, "Makefile"));
2945
3114
  if (text2 !== null) {
2946
3115
  for (const t of parseMakefile(text2)) {
2947
3116
  profile.commands.push({ label: t, command: `make ${t}` });
@@ -2951,7 +3120,7 @@ async function scanProject(dir) {
2951
3120
  if (profile.description === null || profile.name === basename(dir)) {
2952
3121
  const readmeName = files.find((f) => /^readme(\.md|\.markdown|\.txt)?$/i.test(f));
2953
3122
  if (readmeName) {
2954
- const text2 = await readText(join4(dir, readmeName));
3123
+ const text2 = await readText(join5(dir, readmeName));
2955
3124
  if (text2 !== null) {
2956
3125
  const parsed = parseReadme(text2);
2957
3126
  if (profile.name === basename(dir) && parsed.name !== null) profile.name = parsed.name;
@@ -2964,7 +3133,7 @@ async function scanProject(dir) {
2964
3133
  profile.structure = await detectStructure(dir, dirs);
2965
3134
  const envFile = files.includes(".env.example") ? ".env.example" : files.includes(".env.sample") ? ".env.sample" : null;
2966
3135
  if (envFile) {
2967
- const text2 = await readText(join4(dir, envFile));
3136
+ const text2 = await readText(join5(dir, envFile));
2968
3137
  if (text2 !== null) profile.envVars = parseEnvNames(text2);
2969
3138
  }
2970
3139
  return profile;
@@ -3040,7 +3209,7 @@ async function applyDerivedSettings(target, suggestedJson, force) {
3040
3209
  let existingText = "";
3041
3210
  let existing = {};
3042
3211
  if (await pathExists(target)) {
3043
- existingText = await readFile4(target, "utf8");
3212
+ existingText = await readFile5(target, "utf8");
3044
3213
  if (existingText.trim() !== "") {
3045
3214
  let parsed;
3046
3215
  try {
@@ -3067,9 +3236,9 @@ async function applyDerivedSettings(target, suggestedJson, force) {
3067
3236
  mergedPerms.deny = unionStrings(asStringArray(existingPerms.deny), suggestedDeny);
3068
3237
  const merged = { ...existing, permissions: mergedPerms };
3069
3238
  const mergedText = JSON.stringify(merged, null, 2) + "\n";
3070
- await mkdir2(dirname(target), { recursive: true });
3071
- await writeFile2(backup, existingText, "utf8");
3072
- await writeFile2(target, mergedText, "utf8");
3239
+ await mkdir3(dirname(target), { recursive: true });
3240
+ await writeFile3(backup, existingText, "utf8");
3241
+ await writeFile3(target, mergedText, "utf8");
3073
3242
  return [
3074
3243
  `Merged the derived permission allowlist into ${target}`,
3075
3244
  `Backed up the previous file to ${backup}`,
@@ -3084,17 +3253,18 @@ async function runOptimize(opts) {
3084
3253
  const report = analyzeUploads(logs);
3085
3254
  const cmd = analyzeClaudeMd(claudeMd);
3086
3255
  const { pillars } = scorePillars(report, cmd, {});
3087
- const { fixes } = synthesize(report, pillars, cmd);
3256
+ const { plan } = await resolvePlan(join6(opts.home ?? homedir4(), ".costclaw"), opts.plan);
3257
+ const { fixes } = synthesize(report, pillars, cmd, plan);
3088
3258
  const projectDir = opts.projectDir || process.cwd();
3089
3259
  const project = await scanProject(projectDir);
3090
3260
  const result = optimize({ report, scores: pillars, fixes, currentClaudeMd: claudeMd, project });
3091
3261
  const recoverable = cacheMissExposureUsd(report);
3092
- const outDir = opts.out || join5(process.cwd(), "costclaw-out");
3093
- await mkdir2(outDir, { recursive: true });
3094
- const playbookPath = join5(outDir, PLAYBOOK_NAME);
3095
- await writeFile2(playbookPath, result.playbook, "utf8");
3096
- const settingsPath = join5(outDir, SETTINGS_NAME);
3097
- await writeFile2(settingsPath, result.settingsJson, "utf8");
3262
+ const outDir = opts.out || join6(process.cwd(), "costclaw-out");
3263
+ await mkdir3(outDir, { recursive: true });
3264
+ const playbookPath = join6(outDir, PLAYBOOK_NAME);
3265
+ await writeFile3(playbookPath, result.playbook, "utf8");
3266
+ const settingsPath = join6(outDir, SETTINGS_NAME);
3267
+ await writeFile3(settingsPath, result.settingsJson, "utf8");
3098
3268
  const lines = [];
3099
3269
  lines.push("CostClaw optimize");
3100
3270
  lines.push("");
@@ -3108,10 +3278,10 @@ async function runOptimize(opts) {
3108
3278
  }
3109
3279
  let original = "";
3110
3280
  if (await pathExists(target)) {
3111
- original = await readFile4(target, "utf8");
3281
+ original = await readFile5(target, "utf8");
3112
3282
  }
3113
- await writeFile2(backup, original, "utf8");
3114
- await writeFile2(target, result.optimizedClaudeMd, "utf8");
3283
+ await writeFile3(backup, original, "utf8");
3284
+ await writeFile3(target, result.optimizedClaudeMd, "utf8");
3115
3285
  lines.push(`Backed up the original to ${backup}`);
3116
3286
  lines.push(`Wrote the optimized CLAUDE.md to ${target}`);
3117
3287
  lines.push(`Wrote the playbook to ${playbookPath}`);
@@ -3123,15 +3293,23 @@ async function runOptimize(opts) {
3123
3293
  lines.push("Warning: this scaffold has placeholders to fill in. Search it for <!-- ... --> and replace each with your project's real details.");
3124
3294
  lines.push("A suggested settings.json was written to the out dir for review; it is not applied in place.");
3125
3295
  } else {
3126
- const optimizedPath = join5(outDir, OPTIMIZED_NAME);
3127
- await writeFile2(optimizedPath, result.optimizedClaudeMd, "utf8");
3296
+ const optimizedPath = join6(outDir, OPTIMIZED_NAME);
3297
+ await writeFile3(optimizedPath, result.optimizedClaudeMd, "utf8");
3128
3298
  lines.push("Dry run (no files of yours were changed).");
3129
3299
  lines.push(`Wrote the optimized CLAUDE.md scaffold to ${optimizedPath}`);
3130
3300
  lines.push(`Wrote the playbook to ${playbookPath}`);
3131
3301
  lines.push(`Wrote a suggested settings.json to ${settingsPath}`);
3132
3302
  lines.push("");
3133
3303
  lines.push(describeDetection(project));
3134
- lines.push(`Recoverable spend (cache-miss exposure): ${usd5(recoverable)}`);
3304
+ if (plan === "api") {
3305
+ lines.push(`Recoverable spend (cache-miss exposure): ${usd5(recoverable)}`);
3306
+ } else {
3307
+ const spend = report.summary.cost_usd;
3308
+ const share = spend > 0 ? recoverable / spend * 100 : 0;
3309
+ lines.push(
3310
+ `Recoverable usage (cache-miss exposure): ${share.toFixed(1)}% of analyzed usage (${usd5(recoverable)} at API rates)`
3311
+ );
3312
+ }
3135
3313
  lines.push("");
3136
3314
  lines.push("The optimized CLAUDE.md is a scaffold: it has placeholders to fill in.");
3137
3315
  lines.push("Search it for <!-- ... --> and replace each with your project's real details.");
@@ -3140,7 +3318,7 @@ async function runOptimize(opts) {
3140
3318
  lines.push("To merge it into the project's .claude/settings.json for you (with a backup and a diff first), rerun with --apply-settings.");
3141
3319
  }
3142
3320
  if (opts.applySettings) {
3143
- const target = opts.applySettingsPath || join5(projectDir, ".claude", "settings.json");
3321
+ const target = opts.applySettingsPath || join6(projectDir, ".claude", "settings.json");
3144
3322
  const applyLines = await applyDerivedSettings(target, result.settingsJson, opts.force ?? false);
3145
3323
  lines.push("");
3146
3324
  lines.push(...applyLines);
@@ -3156,7 +3334,7 @@ async function runOptimize(opts) {
3156
3334
  }
3157
3335
 
3158
3336
  // src/badge-command.ts
3159
- import { writeFile as writeFile3 } from "fs/promises";
3337
+ import { writeFile as writeFile4 } from "fs/promises";
3160
3338
  import { resolve as resolve2 } from "path";
3161
3339
 
3162
3340
  // src/badge.ts
@@ -3179,17 +3357,143 @@ function renderBadge(record) {
3179
3357
  // src/badge-command.ts
3180
3358
  var DEFAULT_BADGE_FILE = "costclaw-badge.svg";
3181
3359
  async function runBadge(opts) {
3182
- const { record } = await runAudit({ path: opts.path, claudeMdPath: opts.claudeMdPath });
3360
+ const { record } = await runAudit({ path: opts.path, claudeMdPath: opts.claudeMdPath, home: opts.home });
3183
3361
  const svg = renderBadge(record);
3184
3362
  const target = resolve2(opts.out || DEFAULT_BADGE_FILE);
3185
- await writeFile3(target, svg, "utf8");
3363
+ await writeFile4(target, svg, "utf8");
3186
3364
  return { output: `Badge written to ${target}`, record, target };
3187
3365
  }
3188
3366
 
3367
+ // src/diff-command.ts
3368
+ import { readdir as readdir4, readFile as readFile6 } from "fs/promises";
3369
+ import { join as join7 } from "path";
3370
+ import { homedir as homedir5 } from "os";
3371
+
3372
+ // src/format-diff.ts
3373
+ function usd6(n) {
3374
+ return `$${(Math.round(Math.abs(n) * 100) / 100).toFixed(2)}`;
3375
+ }
3376
+ function signedUsd(n) {
3377
+ return `${n < 0 ? "-" : "+"}${usd6(n)}`;
3378
+ }
3379
+ function signedInt(n) {
3380
+ return n > 0 ? `+${n}` : `${n}`;
3381
+ }
3382
+ function pct(rate) {
3383
+ return `${(rate * 100).toFixed(1)}%`;
3384
+ }
3385
+ function day(iso) {
3386
+ return iso.slice(0, 10);
3387
+ }
3388
+ function formatDiff(d) {
3389
+ const lines = [];
3390
+ lines.push("CostClaw diff");
3391
+ lines.push(
3392
+ `Baseline: ${day(d.baseline.createdAt)} Current: ${day(d.current.createdAt)} (${d.periodDays} days)`
3393
+ );
3394
+ lines.push("");
3395
+ if (d.comparable && d.marginal) {
3396
+ lines.push("Since the baseline:");
3397
+ lines.push(
3398
+ ` New spend ${usd6(d.marginal.newSpendUsd)} across ${d.marginal.newSessions} new sessions`
3399
+ );
3400
+ lines.push(
3401
+ ` Marginal cache hit ${pct(d.marginal.marginalCacheHitRate)} (lifetime ${pct(d.current.cacheHitRate)})`
3402
+ );
3403
+ lines.push(
3404
+ ` Recoverable exposure ${signedUsd(d.deltas.recoverableUsd)} (now ${usd6(d.current.recoverableUsd)})`
3405
+ );
3406
+ } else {
3407
+ lines.push("Note: the current audit covers less history than the baseline (logs moved or");
3408
+ lines.push("pruned), so period metrics are omitted.");
3409
+ lines.push("");
3410
+ lines.push(
3411
+ `Baseline (${day(d.baseline.createdAt)}): spend ${usd6(d.baseline.spendUsd)}, cache hit ${pct(d.baseline.cacheHitRate)}, recoverable ${usd6(d.baseline.recoverableUsd)}`
3412
+ );
3413
+ lines.push(
3414
+ `Current (${day(d.current.createdAt)}): spend ${usd6(d.current.spendUsd)}, cache hit ${pct(d.current.cacheHitRate)}, recoverable ${usd6(d.current.recoverableUsd)}`
3415
+ );
3416
+ }
3417
+ lines.push("");
3418
+ lines.push(
3419
+ `Overall setup score: ${d.baseline.overallScore} -> ${d.current.overallScore} (${signedInt(d.deltas.overallScore)}, ${d.current.band})`
3420
+ );
3421
+ for (const p of d.pillars) {
3422
+ const before = p.before === null ? "n/a" : String(p.before);
3423
+ const after = p.after === null ? "n/a" : String(p.after);
3424
+ const delta = p.delta === null ? "" : ` (${signedInt(p.delta)})`;
3425
+ lines.push(` ${p.name.padEnd(22)} ${before.padStart(3)} -> ${after.padStart(3)}${delta}`);
3426
+ }
3427
+ if (d.current.plan && d.current.plan !== "api") {
3428
+ lines.push("");
3429
+ lines.push(
3430
+ `Plan: ${d.current.plan}. Dollar figures are API-equivalent token value on your subscription; recovering them buys rate-limit headroom, not money back.`
3431
+ );
3432
+ }
3433
+ const { resolved, appeared, changed } = d.fixes;
3434
+ if (resolved.length > 0) {
3435
+ lines.push("");
3436
+ lines.push("Fixes resolved since the baseline:");
3437
+ for (const f of resolved) lines.push(` - [${usd6(f.wasteUsd)}] ${f.title}`);
3438
+ }
3439
+ if (appeared.length > 0) {
3440
+ lines.push("");
3441
+ lines.push("New since the baseline:");
3442
+ for (const f of appeared) lines.push(` - [${usd6(f.wasteUsd)}] ${f.title}`);
3443
+ }
3444
+ if (changed.length > 0) {
3445
+ lines.push("");
3446
+ lines.push("Fixes that moved:");
3447
+ for (const c of changed) {
3448
+ lines.push(` - ${c.title}: ${usd6(c.beforeUsd)} -> ${usd6(c.afterUsd)} (${signedUsd(c.deltaUsd)})`);
3449
+ }
3450
+ }
3451
+ return lines.join("\n");
3452
+ }
3453
+
3454
+ // src/diff-command.ts
3455
+ async function readRecord(path) {
3456
+ let text2;
3457
+ try {
3458
+ text2 = await readFile6(path, "utf8");
3459
+ } catch {
3460
+ throw new Error(`Could not read ${path}.`);
3461
+ }
3462
+ try {
3463
+ return JSON.parse(text2);
3464
+ } catch {
3465
+ throw new Error(
3466
+ `${path} is not valid JSON. Pass a record from costclaw audit --json or ~/.costclaw/history.`
3467
+ );
3468
+ }
3469
+ }
3470
+ async function runDiff(opts) {
3471
+ let pathA = opts.fileA;
3472
+ let pathB = opts.fileB;
3473
+ if (!pathA || !pathB) {
3474
+ const dir = join7(opts.home ?? homedir5(), ".costclaw", "history");
3475
+ let files = [];
3476
+ try {
3477
+ files = (await readdir4(dir)).filter((f) => f.endsWith(".json")).sort();
3478
+ } catch {
3479
+ }
3480
+ if (files.length < 2) {
3481
+ throw new Error(
3482
+ "Need two audits to diff. Run costclaw audit now and again after you have made changes; each run saves a snapshot."
3483
+ );
3484
+ }
3485
+ pathA = join7(dir, files[files.length - 2]);
3486
+ pathB = join7(dir, files[files.length - 1]);
3487
+ }
3488
+ const diff = diffAudits(await readRecord(pathA), await readRecord(pathB));
3489
+ const output = opts.json ? JSON.stringify(diff, null, 2) : formatDiff(diff);
3490
+ return { output, diff };
3491
+ }
3492
+
3189
3493
  // src/license.ts
3190
- import { mkdir as mkdir3, readFile as readFile5, writeFile as writeFile4, rm } from "fs/promises";
3191
- import { join as join6 } from "path";
3192
- import { homedir as homedir4, hostname } from "os";
3494
+ import { mkdir as mkdir4, readFile as readFile7, writeFile as writeFile5, rm as rm2 } from "fs/promises";
3495
+ import { join as join8 } from "path";
3496
+ import { homedir as homedir6, hostname } from "os";
3193
3497
  import { createPublicKey, verify as cryptoVerify } from "crypto";
3194
3498
  var LICENSE_PRODUCT = "costclaw-optimize";
3195
3499
  var DEFAULT_PUBLIC_KEY_PEM = `-----BEGIN PUBLIC KEY-----
@@ -3214,10 +3518,10 @@ var INVALID_MESSAGE = [
3214
3518
  "costclaw audit stays free."
3215
3519
  ].join("\n");
3216
3520
  function defaultConfigDir() {
3217
- return join6(homedir4(), ".costclaw");
3521
+ return join8(homedir6(), ".costclaw");
3218
3522
  }
3219
3523
  function licenseFile(dir) {
3220
- return join6(dir, "license.json");
3524
+ return join8(dir, "license.json");
3221
3525
  }
3222
3526
  function base64UrlDecode(part) {
3223
3527
  return Buffer.from(part.replace(/-/g, "+").replace(/_/g, "/"), "base64");
@@ -3241,7 +3545,7 @@ function verifyLicenseKey(licenseKey, publicKeyPem = DEFAULT_PUBLIC_KEY_PEM) {
3241
3545
  }
3242
3546
  async function readStoredLicense(dir) {
3243
3547
  try {
3244
- const data = JSON.parse(await readFile5(licenseFile(dir), "utf8"));
3548
+ const data = JSON.parse(await readFile7(licenseFile(dir), "utf8"));
3245
3549
  if (!data || typeof data.licenseKey !== "string") return null;
3246
3550
  return data;
3247
3551
  } catch {
@@ -3249,11 +3553,11 @@ async function readStoredLicense(dir) {
3249
3553
  }
3250
3554
  }
3251
3555
  async function writeStoredLicense(dir, lic) {
3252
- await mkdir3(dir, { recursive: true });
3253
- await writeFile4(licenseFile(dir), JSON.stringify(lic, null, 2) + "\n", "utf8");
3556
+ await mkdir4(dir, { recursive: true });
3557
+ await writeFile5(licenseFile(dir), JSON.stringify(lic, null, 2) + "\n", "utf8");
3254
3558
  }
3255
3559
  async function clearStoredLicense(dir) {
3256
- await rm(licenseFile(dir), { force: true });
3560
+ await rm2(licenseFile(dir), { force: true });
3257
3561
  }
3258
3562
  async function activateLicense(licenseKey, opts = {}) {
3259
3563
  const key = licenseKey.trim();
@@ -3308,6 +3612,14 @@ function optionalPathAfter(args, flag) {
3308
3612
  const next = args[i + 1];
3309
3613
  return next !== void 0 && !next.startsWith("-") ? next : void 0;
3310
3614
  }
3615
+ function planFlag(args) {
3616
+ if (!args.includes("--plan")) return void 0;
3617
+ const value = getFlag(args, "--plan");
3618
+ if (value === void 0 || !isPlan(value)) {
3619
+ throw new Error(`--plan must be one of: ${PLANS.join(", ")}`);
3620
+ }
3621
+ return value;
3622
+ }
3311
3623
  function parseAuditFlags(args) {
3312
3624
  const html = args.includes("--html");
3313
3625
  const card = args.includes("--card");
@@ -3318,7 +3630,8 @@ function parseAuditFlags(args) {
3318
3630
  html,
3319
3631
  htmlPath: html ? optionalPathAfter(args, "--html") : void 0,
3320
3632
  card,
3321
- cardPath: card ? optionalPathAfter(args, "--card") : void 0
3633
+ cardPath: card ? optionalPathAfter(args, "--card") : void 0,
3634
+ plan: planFlag(args)
3322
3635
  };
3323
3636
  }
3324
3637
  function parseBadgeFlags(args) {
@@ -3329,14 +3642,15 @@ function parseBadgeFlags(args) {
3329
3642
  };
3330
3643
  }
3331
3644
  function cliVersion() {
3332
- return true ? "0.2.3" : "0.0.0-dev";
3645
+ return true ? "0.3.0" : "0.0.0-dev";
3333
3646
  }
3334
3647
  function helpText() {
3335
3648
  return [
3336
3649
  "CostClaw - privacy-first Claude Code cost and setup audit",
3337
3650
  "",
3338
3651
  "Usage:",
3339
- " costclaw audit [--path <dir>] [--claude-md <file>] [--json] [--html [file]] [--card [file]]",
3652
+ " costclaw audit [--path <dir>] [--claude-md <file>] [--plan <plan>] [--json] [--html [file]] [--card [file]]",
3653
+ " costclaw diff [<baseline.json> <current.json>] [--json]",
3340
3654
  " costclaw badge [--path <dir>] [--claude-md <file>] [--out <file>]",
3341
3655
  " costclaw optimize [--path <dir>] [--claude-md <file>] [--project <dir>] [--out <dir>] [--write <file>] [--apply-settings [file]] [--force]",
3342
3656
  " costclaw activate <license-key> [--name <machine-name>]",
@@ -3349,6 +3663,18 @@ function helpText() {
3349
3663
  "it in your browser; the terminal report still prints.",
3350
3664
  "--card writes a shareable 600x315 score card SVG (default: costclaw-card.svg):",
3351
3665
  "score, band, recoverable spend, cache hit rate, and your strongest pillar.",
3666
+ "--plan <api|pro|max5x|max20x> declares how you pay for Claude. On a",
3667
+ "subscription (Pro/Max) the dollar figures are API-equivalent token value, not",
3668
+ "money back, so the audit reframes the headline as recoverable usage: the share",
3669
+ "of your token consumption (and rate-limit headroom) you could win back. The",
3670
+ "value is saved to ~/.costclaw/config.json so later runs remember it;",
3671
+ "--plan api switches back.",
3672
+ "",
3673
+ "diff compares two audits and shows the movement: new spend since the baseline,",
3674
+ "the marginal cache hit rate for just that period, score changes per pillar, and",
3675
+ "which fixes were resolved. Every audit run saves a snapshot to",
3676
+ "~/.costclaw/history, so plain `costclaw diff` compares your latest two runs;",
3677
+ "or pass two record files from costclaw audit --json. It is free.",
3352
3678
  "",
3353
3679
  "badge runs a fresh audit and writes a shields.io-style badge SVG (default:",
3354
3680
  "costclaw-badge.svg) showing your overall score, colored by its band. Embed it",
@@ -3383,6 +3709,16 @@ async function main() {
3383
3709
  process.stdout.write(output + "\n");
3384
3710
  return;
3385
3711
  }
3712
+ if (command === "diff") {
3713
+ const files = args.filter((a) => !a.startsWith("-"));
3714
+ const { output } = await runDiff({
3715
+ fileA: files[0],
3716
+ fileB: files[1],
3717
+ json: args.includes("--json")
3718
+ });
3719
+ process.stdout.write(output + "\n");
3720
+ return;
3721
+ }
3386
3722
  if (command === "badge") {
3387
3723
  const { output } = await runBadge(parseBadgeFlags(args));
3388
3724
  process.stdout.write(output + "\n");
@@ -3417,6 +3753,7 @@ Run: costclaw optimize
3417
3753
  const { output } = await runOptimize({
3418
3754
  path: getFlag(args, "--path"),
3419
3755
  claudeMdPath: getFlag(args, "--claude-md"),
3756
+ plan: planFlag(args),
3420
3757
  projectDir: getFlag(args, "--project") || process.cwd(),
3421
3758
  out: getFlag(args, "--out"),
3422
3759
  write: getFlag(args, "--write"),
@@ -3441,5 +3778,6 @@ export {
3441
3778
  cliVersion,
3442
3779
  helpText,
3443
3780
  parseAuditFlags,
3444
- parseBadgeFlags
3781
+ parseBadgeFlags,
3782
+ planFlag
3445
3783
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "costclaw",
3
- "version": "0.2.3",
3
+ "version": "0.3.0",
4
4
  "description": "Local cost and setup audit for Claude Code. Finds recoverable token spend and scores your setup across six pillars, with your prompts never leaving your machine.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -31,6 +31,7 @@
31
31
  ],
32
32
  "scripts": {
33
33
  "audit": "tsx src/index.ts audit",
34
+ "diff": "tsx src/index.ts diff",
34
35
  "optimize": "tsx src/index.ts optimize",
35
36
  "dev": "tsx src/index.ts",
36
37
  "build": "tsup",