costclaw 0.2.3 → 0.2.4

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 +34 -0
  2. package/dist/index.js +242 -19
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -65,6 +65,40 @@ costclaw audit [--path <dir>] [--claude-md <file>] [--json] [--html [file]] [--c
65
65
  Run `costclaw --version` (or `-v` / `costclaw version`) to print the installed
66
66
  CLI version.
67
67
 
68
+ ## Diff
69
+
70
+ Every audit run saves a snapshot of the derived record to `~/.costclaw/history`
71
+ (local, nothing uploaded). Run the audit again after you have made changes, then:
72
+
73
+ ```bash
74
+ npx costclaw diff
75
+ ```
76
+
77
+ That compares your latest two audits and shows the movement, so you can verify
78
+ the fixes actually recovered dollars:
79
+
80
+ ```
81
+ CostClaw diff
82
+ Baseline: 2026-06-09 Current: 2026-07-09 (30 days)
83
+
84
+ Since the baseline:
85
+ New spend $842.10 across 210 new sessions
86
+ Marginal cache hit 97.1% (lifetime 96.2%)
87
+ Recoverable exposure +$96.40 (now $1131.61)
88
+
89
+ Overall setup score: 83 -> 86 (+3, Tight)
90
+ CLAUDE.md quality 69 -> 78 (+9)
91
+ ...
92
+
93
+ Fixes resolved since the baseline:
94
+ - [$52.40] Use a cheaper model for 61 small sessions
95
+ ```
96
+
97
+ The marginal cache hit rate covers only the period between the two audits, which
98
+ a lifetime average hides. You can also diff two explicit records saved with
99
+ `costclaw audit --json`: `costclaw diff baseline.json current.json`. Add `--json`
100
+ for the machine-readable diff. Free, like the audit.
101
+
68
102
  ## Badge
69
103
 
70
104
  ```bash
package/dist/index.js CHANGED
@@ -1219,9 +1219,9 @@ function synthesize(report, pillars, cmd) {
1219
1219
  const exposure = headlineWasteUsd;
1220
1220
  const fixes = [];
1221
1221
  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);
1222
+ const round23 = (n) => Math.round(n * 100) / 100;
1223
+ const usd7 = (n) => {
1224
+ const fixed = round23(n).toFixed(2);
1225
1225
  const dot = fixed.indexOf(".");
1226
1226
  const whole = fixed.slice(0, dot).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
1227
1227
  return `$${whole}${fixed.slice(dot)}`;
@@ -1246,9 +1246,9 @@ function synthesize(report, pillars, cmd) {
1246
1246
  pillar: "context_hygiene",
1247
1247
  pillarName: PILLARS.context_hygiene.name,
1248
1248
  severity: sevForUsd(exposure),
1249
- wasteUsd: round22(exposure),
1249
+ wasteUsd: round23(exposure),
1250
1250
  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"}.`
1251
+ `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
1252
  ),
1253
1253
  action: sanitizeText(
1254
1254
  "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 +1328,8 @@ function synthesize(report, pillars, cmd) {
1328
1328
  pillar: "cost_discipline",
1329
1329
  pillarName: PILLARS.cost_discipline.name,
1330
1330
  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.`),
1331
+ wasteUsd: round23(misrouteUsd),
1332
+ 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
1333
  action: sanitizeText("Route short, simple sessions to a cheaper model such as Sonnet, and reserve Opus for hard reasoning."),
1334
1334
  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
1335
  });
@@ -1342,8 +1342,8 @@ function synthesize(report, pillars, cmd) {
1342
1342
  pillar: "session_mgmt",
1343
1343
  pillarName: PILLARS.session_mgmt.name,
1344
1344
  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.`),
1345
+ wasteUsd: round23(marathonUsd),
1346
+ 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
1347
  action: sanitizeText("Compact or start a fresh session between tasks so the context stays small and the cache keeps working."),
1348
1348
  basis: sanitizeText("Recoverable estimate from the late-session cache shortfall versus the early-session hit rate.")
1349
1349
  });
@@ -1356,7 +1356,7 @@ function synthesize(report, pillars, cmd) {
1356
1356
  pillarName: PILLARS.cost_discipline.name,
1357
1357
  severity: "info",
1358
1358
  wasteUsd: 0,
1359
- problem: sanitizeText(`Workflow and subagent runs cost about ${usd6(workflowUsd)}; they are a power tool that can quietly dominate spend.`),
1359
+ problem: sanitizeText(`Workflow and subagent runs cost about ${usd7(workflowUsd)}; they are a power tool that can quietly dominate spend.`),
1360
1360
  action: sanitizeText("Scope workflows to genuinely large tasks and budget the agent count; a single high-effort prompt often suffices."),
1361
1361
  basis: sanitizeText("Summed cost of delegated subagent and workflow sub-logs.")
1362
1362
  });
@@ -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),
@@ -1938,6 +1938,92 @@ function buildAudit(input, opts = {}) {
1938
1938
  };
1939
1939
  }
1940
1940
 
1941
+ // ../../packages/engine/src/diff.ts
1942
+ var DIFF_SCHEMA_VERSION = "1";
1943
+ function round22(n) {
1944
+ return Math.round(n * 100) / 100;
1945
+ }
1946
+ function round42(n) {
1947
+ return Math.round(n * 1e4) / 1e4;
1948
+ }
1949
+ function assertRecord(r) {
1950
+ if (!r || typeof r !== "object" || !r.usageMetrics || !Array.isArray(r.pillarScores) || typeof r.overallScore !== "number" || typeof r.createdAt !== "string") {
1951
+ throw new Error("Not a costclaw audit record (run costclaw audit --json to produce one).");
1952
+ }
1953
+ }
1954
+ function side(r) {
1955
+ const m = r.usageMetrics;
1956
+ return {
1957
+ createdAt: r.createdAt,
1958
+ spendUsd: round22(m.spendUsd),
1959
+ recoverableUsd: round22(r.headlineWasteUsd),
1960
+ cacheHitRate: round42(m.cacheHitRate),
1961
+ overallScore: r.overallScore,
1962
+ band: r.band.label,
1963
+ sessionsCount: m.sessionsCount
1964
+ };
1965
+ }
1966
+ function diffAudits(a, b) {
1967
+ assertRecord(a);
1968
+ assertRecord(b);
1969
+ const [base, cur] = Date.parse(a.createdAt) <= Date.parse(b.createdAt) ? [a, b] : [b, a];
1970
+ const bm = base.usageMetrics;
1971
+ const cm = cur.usageMetrics;
1972
+ const newTokens = {
1973
+ input_tokens: cm.totalTokens.input_tokens - bm.totalTokens.input_tokens,
1974
+ output_tokens: cm.totalTokens.output_tokens - bm.totalTokens.output_tokens,
1975
+ cache_creation_tokens: cm.totalTokens.cache_creation_tokens - bm.totalTokens.cache_creation_tokens,
1976
+ cache_read_tokens: cm.totalTokens.cache_read_tokens - bm.totalTokens.cache_read_tokens
1977
+ };
1978
+ const newSpendUsd = cm.spendUsd - bm.spendUsd;
1979
+ const newSessions = cm.sessionsCount - bm.sessionsCount;
1980
+ const comparable = newSpendUsd >= -0.01 && newSessions >= 0 && Object.values(newTokens).every((t) => t >= 0);
1981
+ const periodMs = Date.parse(cur.createdAt) - Date.parse(base.createdAt);
1982
+ const periodDays = round22(Math.max(0, periodMs) / 864e5);
1983
+ const pillars = base.pillarScores.map((bp) => {
1984
+ const cp = cur.pillarScores.find((p) => p.id === bp.id);
1985
+ const before = bp.assessed ? bp.score : null;
1986
+ const after = cp && cp.assessed ? cp.score : null;
1987
+ return {
1988
+ id: bp.id,
1989
+ name: bp.name,
1990
+ before,
1991
+ after,
1992
+ delta: before !== null && after !== null ? after - before : null
1993
+ };
1994
+ });
1995
+ const baseFixes = new Map(base.fixes.map((f) => [f.id, f]));
1996
+ const curFixes = new Map(cur.fixes.map((f) => [f.id, f]));
1997
+ const resolved = base.fixes.filter((f) => !curFixes.has(f.id)).map((f) => ({ id: f.id, title: f.title, wasteUsd: round22(f.wasteUsd) }));
1998
+ const appeared = cur.fixes.filter((f) => !baseFixes.has(f.id)).map((f) => ({ id: f.id, title: f.title, wasteUsd: round22(f.wasteUsd) }));
1999
+ const changed = cur.fixes.filter((f) => baseFixes.has(f.id)).map((f) => {
2000
+ const beforeUsd = round22(baseFixes.get(f.id).wasteUsd);
2001
+ const afterUsd = round22(f.wasteUsd);
2002
+ return { id: f.id, title: f.title, beforeUsd, afterUsd, deltaUsd: round22(afterUsd - beforeUsd) };
2003
+ }).filter((c) => Math.abs(c.deltaUsd) >= 0.01);
2004
+ return {
2005
+ schemaVersion: DIFF_SCHEMA_VERSION,
2006
+ baseline: side(base),
2007
+ current: side(cur),
2008
+ periodDays,
2009
+ comparable,
2010
+ marginal: comparable ? {
2011
+ newSpendUsd: round22(newSpendUsd),
2012
+ newSessions,
2013
+ marginalCacheHitRate: round42(cacheHitRate(newTokens)),
2014
+ newTokens
2015
+ } : null,
2016
+ deltas: {
2017
+ spendUsd: round22(cm.spendUsd - bm.spendUsd),
2018
+ recoverableUsd: round22(cur.headlineWasteUsd - base.headlineWasteUsd),
2019
+ overallScore: cur.overallScore - base.overallScore,
2020
+ cacheHitRatePoints: round42(cm.cacheHitRate - bm.cacheHitRate)
2021
+ },
2022
+ pillars,
2023
+ fixes: { resolved, appeared, changed }
2024
+ };
2025
+ }
2026
+
1941
2027
  // ../../packages/engine/src/validate.ts
1942
2028
  var MAX_FILE_BYTES = 25 * 1024 * 1024;
1943
2029
  var MAX_TOTAL_BYTES = 60 * 1024 * 1024;
@@ -2044,7 +2130,7 @@ function modelMix(breakdown) {
2044
2130
  }
2045
2131
  const total = [...merged.values()].reduce((a, b) => a + b, 0);
2046
2132
  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}%`);
2133
+ 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
2134
  return parts.length > 0 ? parts.join(" / ") : null;
2049
2135
  }
2050
2136
  function unassessedLine(pillars) {
@@ -3186,10 +3272,130 @@ async function runBadge(opts) {
3186
3272
  return { output: `Badge written to ${target}`, record, target };
3187
3273
  }
3188
3274
 
3189
- // src/license.ts
3190
- import { mkdir as mkdir3, readFile as readFile5, writeFile as writeFile4, rm } from "fs/promises";
3275
+ // src/diff-command.ts
3276
+ import { readdir as readdir3, readFile as readFile5 } from "fs/promises";
3191
3277
  import { join as join6 } from "path";
3192
- import { homedir as homedir4, hostname } from "os";
3278
+ import { homedir as homedir4 } from "os";
3279
+
3280
+ // src/format-diff.ts
3281
+ function usd6(n) {
3282
+ return `$${(Math.round(Math.abs(n) * 100) / 100).toFixed(2)}`;
3283
+ }
3284
+ function signedUsd(n) {
3285
+ return `${n < 0 ? "-" : "+"}${usd6(n)}`;
3286
+ }
3287
+ function signedInt(n) {
3288
+ return n > 0 ? `+${n}` : `${n}`;
3289
+ }
3290
+ function pct(rate) {
3291
+ return `${(rate * 100).toFixed(1)}%`;
3292
+ }
3293
+ function day(iso) {
3294
+ return iso.slice(0, 10);
3295
+ }
3296
+ function formatDiff(d) {
3297
+ const lines = [];
3298
+ lines.push("CostClaw diff");
3299
+ lines.push(
3300
+ `Baseline: ${day(d.baseline.createdAt)} Current: ${day(d.current.createdAt)} (${d.periodDays} days)`
3301
+ );
3302
+ lines.push("");
3303
+ if (d.comparable && d.marginal) {
3304
+ lines.push("Since the baseline:");
3305
+ lines.push(
3306
+ ` New spend ${usd6(d.marginal.newSpendUsd)} across ${d.marginal.newSessions} new sessions`
3307
+ );
3308
+ lines.push(
3309
+ ` Marginal cache hit ${pct(d.marginal.marginalCacheHitRate)} (lifetime ${pct(d.current.cacheHitRate)})`
3310
+ );
3311
+ lines.push(
3312
+ ` Recoverable exposure ${signedUsd(d.deltas.recoverableUsd)} (now ${usd6(d.current.recoverableUsd)})`
3313
+ );
3314
+ } else {
3315
+ lines.push("Note: the current audit covers less history than the baseline (logs moved or");
3316
+ lines.push("pruned), so period metrics are omitted.");
3317
+ lines.push("");
3318
+ lines.push(
3319
+ `Baseline (${day(d.baseline.createdAt)}): spend ${usd6(d.baseline.spendUsd)}, cache hit ${pct(d.baseline.cacheHitRate)}, recoverable ${usd6(d.baseline.recoverableUsd)}`
3320
+ );
3321
+ lines.push(
3322
+ `Current (${day(d.current.createdAt)}): spend ${usd6(d.current.spendUsd)}, cache hit ${pct(d.current.cacheHitRate)}, recoverable ${usd6(d.current.recoverableUsd)}`
3323
+ );
3324
+ }
3325
+ lines.push("");
3326
+ lines.push(
3327
+ `Overall setup score: ${d.baseline.overallScore} -> ${d.current.overallScore} (${signedInt(d.deltas.overallScore)}, ${d.current.band})`
3328
+ );
3329
+ for (const p of d.pillars) {
3330
+ const before = p.before === null ? "n/a" : String(p.before);
3331
+ const after = p.after === null ? "n/a" : String(p.after);
3332
+ const delta = p.delta === null ? "" : ` (${signedInt(p.delta)})`;
3333
+ lines.push(` ${p.name.padEnd(22)} ${before.padStart(3)} -> ${after.padStart(3)}${delta}`);
3334
+ }
3335
+ const { resolved, appeared, changed } = d.fixes;
3336
+ if (resolved.length > 0) {
3337
+ lines.push("");
3338
+ lines.push("Fixes resolved since the baseline:");
3339
+ for (const f of resolved) lines.push(` - [${usd6(f.wasteUsd)}] ${f.title}`);
3340
+ }
3341
+ if (appeared.length > 0) {
3342
+ lines.push("");
3343
+ lines.push("New since the baseline:");
3344
+ for (const f of appeared) lines.push(` - [${usd6(f.wasteUsd)}] ${f.title}`);
3345
+ }
3346
+ if (changed.length > 0) {
3347
+ lines.push("");
3348
+ lines.push("Fixes that moved:");
3349
+ for (const c of changed) {
3350
+ lines.push(` - ${c.title}: ${usd6(c.beforeUsd)} -> ${usd6(c.afterUsd)} (${signedUsd(c.deltaUsd)})`);
3351
+ }
3352
+ }
3353
+ return lines.join("\n");
3354
+ }
3355
+
3356
+ // src/diff-command.ts
3357
+ async function readRecord(path) {
3358
+ let text2;
3359
+ try {
3360
+ text2 = await readFile5(path, "utf8");
3361
+ } catch {
3362
+ throw new Error(`Could not read ${path}.`);
3363
+ }
3364
+ try {
3365
+ return JSON.parse(text2);
3366
+ } catch {
3367
+ throw new Error(
3368
+ `${path} is not valid JSON. Pass a record from costclaw audit --json or ~/.costclaw/history.`
3369
+ );
3370
+ }
3371
+ }
3372
+ async function runDiff(opts) {
3373
+ let pathA = opts.fileA;
3374
+ let pathB = opts.fileB;
3375
+ if (!pathA || !pathB) {
3376
+ const dir = join6(opts.home ?? homedir4(), ".costclaw", "history");
3377
+ let files = [];
3378
+ try {
3379
+ files = (await readdir3(dir)).filter((f) => f.endsWith(".json")).sort();
3380
+ } catch {
3381
+ }
3382
+ if (files.length < 2) {
3383
+ throw new Error(
3384
+ "Need two audits to diff. Run costclaw audit now and again after you have made changes; each run saves a snapshot."
3385
+ );
3386
+ }
3387
+ pathA = join6(dir, files[files.length - 2]);
3388
+ pathB = join6(dir, files[files.length - 1]);
3389
+ }
3390
+ const diff = diffAudits(await readRecord(pathA), await readRecord(pathB));
3391
+ const output = opts.json ? JSON.stringify(diff, null, 2) : formatDiff(diff);
3392
+ return { output, diff };
3393
+ }
3394
+
3395
+ // src/license.ts
3396
+ import { mkdir as mkdir3, readFile as readFile6, writeFile as writeFile4, rm } from "fs/promises";
3397
+ import { join as join7 } from "path";
3398
+ import { homedir as homedir5, hostname } from "os";
3193
3399
  import { createPublicKey, verify as cryptoVerify } from "crypto";
3194
3400
  var LICENSE_PRODUCT = "costclaw-optimize";
3195
3401
  var DEFAULT_PUBLIC_KEY_PEM = `-----BEGIN PUBLIC KEY-----
@@ -3214,10 +3420,10 @@ var INVALID_MESSAGE = [
3214
3420
  "costclaw audit stays free."
3215
3421
  ].join("\n");
3216
3422
  function defaultConfigDir() {
3217
- return join6(homedir4(), ".costclaw");
3423
+ return join7(homedir5(), ".costclaw");
3218
3424
  }
3219
3425
  function licenseFile(dir) {
3220
- return join6(dir, "license.json");
3426
+ return join7(dir, "license.json");
3221
3427
  }
3222
3428
  function base64UrlDecode(part) {
3223
3429
  return Buffer.from(part.replace(/-/g, "+").replace(/_/g, "/"), "base64");
@@ -3241,7 +3447,7 @@ function verifyLicenseKey(licenseKey, publicKeyPem = DEFAULT_PUBLIC_KEY_PEM) {
3241
3447
  }
3242
3448
  async function readStoredLicense(dir) {
3243
3449
  try {
3244
- const data = JSON.parse(await readFile5(licenseFile(dir), "utf8"));
3450
+ const data = JSON.parse(await readFile6(licenseFile(dir), "utf8"));
3245
3451
  if (!data || typeof data.licenseKey !== "string") return null;
3246
3452
  return data;
3247
3453
  } catch {
@@ -3329,7 +3535,7 @@ function parseBadgeFlags(args) {
3329
3535
  };
3330
3536
  }
3331
3537
  function cliVersion() {
3332
- return true ? "0.2.3" : "0.0.0-dev";
3538
+ return true ? "0.2.4" : "0.0.0-dev";
3333
3539
  }
3334
3540
  function helpText() {
3335
3541
  return [
@@ -3337,6 +3543,7 @@ function helpText() {
3337
3543
  "",
3338
3544
  "Usage:",
3339
3545
  " costclaw audit [--path <dir>] [--claude-md <file>] [--json] [--html [file]] [--card [file]]",
3546
+ " costclaw diff [<baseline.json> <current.json>] [--json]",
3340
3547
  " costclaw badge [--path <dir>] [--claude-md <file>] [--out <file>]",
3341
3548
  " costclaw optimize [--path <dir>] [--claude-md <file>] [--project <dir>] [--out <dir>] [--write <file>] [--apply-settings [file]] [--force]",
3342
3549
  " costclaw activate <license-key> [--name <machine-name>]",
@@ -3350,6 +3557,12 @@ function helpText() {
3350
3557
  "--card writes a shareable 600x315 score card SVG (default: costclaw-card.svg):",
3351
3558
  "score, band, recoverable spend, cache hit rate, and your strongest pillar.",
3352
3559
  "",
3560
+ "diff compares two audits and shows the movement: new spend since the baseline,",
3561
+ "the marginal cache hit rate for just that period, score changes per pillar, and",
3562
+ "which fixes were resolved. Every audit run saves a snapshot to",
3563
+ "~/.costclaw/history, so plain `costclaw diff` compares your latest two runs;",
3564
+ "or pass two record files from costclaw audit --json. It is free.",
3565
+ "",
3353
3566
  "badge runs a fresh audit and writes a shields.io-style badge SVG (default:",
3354
3567
  "costclaw-badge.svg) showing your overall score, colored by its band. Embed it",
3355
3568
  "in a README with an <img> tag; it is a static, self-contained file.",
@@ -3383,6 +3596,16 @@ async function main() {
3383
3596
  process.stdout.write(output + "\n");
3384
3597
  return;
3385
3598
  }
3599
+ if (command === "diff") {
3600
+ const files = args.filter((a) => !a.startsWith("-"));
3601
+ const { output } = await runDiff({
3602
+ fileA: files[0],
3603
+ fileB: files[1],
3604
+ json: args.includes("--json")
3605
+ });
3606
+ process.stdout.write(output + "\n");
3607
+ return;
3608
+ }
3386
3609
  if (command === "badge") {
3387
3610
  const { output } = await runBadge(parseBadgeFlags(args));
3388
3611
  process.stdout.write(output + "\n");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "costclaw",
3
- "version": "0.2.3",
3
+ "version": "0.2.4",
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": {