costclaw 0.3.0 → 0.4.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 +8 -0
  2. package/dist/index.js +121 -5
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -65,8 +65,16 @@ Recoverable usage (cache-miss exposure): 14.3% of analyzed usage ($1134.61 at AP
65
65
  Usage analyzed (API-equivalent): $7921.99 Cache hit: 96.2% Active hours: 1889.7
66
66
  Plan: max20x. Dollar figures are API-equivalent token value, not money back;
67
67
  recovering them buys rate-limit headroom (more work per usage window).
68
+ Usage windows (5h, like your rate limit): median $8.10, busiest $34.20; busiest week $310.55 (API-equivalent)
69
+ Recovering 14.3% buys about 17% more work per window: up to ~42 extra minutes in a window like your busiest.
68
70
  ```
69
71
 
72
+ The usage windows are modeled from your own activity timestamps, mirroring how
73
+ the limits actually work: a 5-hour window opens at your first activity, and a
74
+ weekly cap sits above it. Nothing is assumed about Anthropic's actual budgets;
75
+ everything is relative to your observed consumption ("busiest" is the 90th
76
+ percentile window, so one freak outlier does not set the bar).
77
+
70
78
  The value is saved to `~/.costclaw/config.json`, so later runs (and `optimize`)
71
79
  remember it. The findings and their ranking are identical either way; only the
72
80
  unit is framed to match how you actually pay.
package/dist/index.js CHANGED
@@ -153,9 +153,12 @@ function parseSession(text2, opts = {}) {
153
153
  skippedLines: 0,
154
154
  kind: opts.kind ?? "main",
155
155
  parentSessionId: opts.parentSessionId ?? null,
156
- turnCache: []
156
+ turnCache: [],
157
+ costBuckets: []
157
158
  };
158
159
  const seen = /* @__PURE__ */ new Set();
160
+ const buckets = /* @__PURE__ */ new Map();
161
+ const BUCKET_MS = 15 * 60 * 1e3;
159
162
  const modelCounts = /* @__PURE__ */ new Map();
160
163
  let cwd = null;
161
164
  let seq = 0;
@@ -198,8 +201,16 @@ function parseSession(text2, opts = {}) {
198
201
  s.totals.output_tokens += Number(usage.output_tokens) || 0;
199
202
  s.totals.cache_creation_tokens += Number(usage.cache_creation_input_tokens) || 0;
200
203
  s.totals.cache_read_tokens += Number(usage.cache_read_input_tokens) || 0;
201
- s.cost_usd += costForUsage(model, usage);
204
+ const fragmentUsd = costForUsage(model, usage);
205
+ s.cost_usd += fragmentUsd;
202
206
  s.cache_savings_usd += cacheSavingsForUsage(model, usage);
207
+ if (rec.timestamp) {
208
+ const ms = Date.parse(rec.timestamp);
209
+ if (!Number.isNaN(ms)) {
210
+ const t = Math.floor(ms / BUCKET_MS);
211
+ buckets.set(t, (buckets.get(t) ?? 0) + fragmentUsd);
212
+ }
213
+ }
203
214
  s.turnCache.push({
204
215
  read: Number(usage.cache_read_input_tokens) || 0,
205
216
  miss: (Number(usage.input_tokens) || 0) + (Number(usage.cache_creation_input_tokens) || 0)
@@ -207,6 +218,7 @@ function parseSession(text2, opts = {}) {
207
218
  }
208
219
  }
209
220
  }
221
+ s.costBuckets = [...buckets.entries()].sort((a, b) => a[0] - b[0]).map(([t, usd7]) => ({ t, usd: usd7 }));
210
222
  s.projectSlug = opts.projectSlug ?? projectFromCwd(cwd);
211
223
  let best = null;
212
224
  let bestCount = 0;
@@ -1392,6 +1404,74 @@ function synthesize(report, pillars, cmd, plan = "api") {
1392
1404
  };
1393
1405
  }
1394
1406
 
1407
+ // ../../packages/engine/src/windows.ts
1408
+ var BUCKET_MINUTES = 15;
1409
+ var WINDOW_BUCKETS = 5 * 60 / BUCKET_MINUTES;
1410
+ var WEEK_BUCKETS = 7 * 24 * 60 / BUCKET_MINUTES;
1411
+ function median(sortedAsc) {
1412
+ const n = sortedAsc.length;
1413
+ if (n === 0) return 0;
1414
+ const mid = Math.floor(n / 2);
1415
+ return n % 2 === 1 ? sortedAsc[mid] : (sortedAsc[mid - 1] + sortedAsc[mid]) / 2;
1416
+ }
1417
+ function p90Index(n) {
1418
+ return Math.max(0, Math.ceil(0.9 * n) - 1);
1419
+ }
1420
+ function computeWindowStats(report) {
1421
+ const merged = /* @__PURE__ */ new Map();
1422
+ for (const project of report.projects) {
1423
+ for (const session of project.sessions) {
1424
+ for (const b of session.costBuckets) merged.set(b.t, (merged.get(b.t) ?? 0) + b.usd);
1425
+ }
1426
+ }
1427
+ const buckets = [...merged.entries()].sort((a, b) => a[0] - b[0]);
1428
+ if (buckets.length === 0) {
1429
+ return {
1430
+ assessed: false,
1431
+ windowsCount: 0,
1432
+ medianWindowUsd: 0,
1433
+ p90WindowUsd: 0,
1434
+ maxWindowUsd: 0,
1435
+ p90WindowActiveMinutes: 0,
1436
+ weeksCount: 0,
1437
+ medianWeekUsd: 0,
1438
+ maxWeekUsd: 0
1439
+ };
1440
+ }
1441
+ const windows = [];
1442
+ let windowStart = -Infinity;
1443
+ for (const [t, usd7] of buckets) {
1444
+ if (t >= windowStart + WINDOW_BUCKETS) {
1445
+ windows.push({ usd: 0, activeMinutes: 0 });
1446
+ windowStart = t;
1447
+ }
1448
+ const w = windows[windows.length - 1];
1449
+ w.usd += usd7;
1450
+ w.activeMinutes += BUCKET_MINUTES;
1451
+ }
1452
+ const firstT = buckets[0][0];
1453
+ const weeks = /* @__PURE__ */ new Map();
1454
+ for (const [t, usd7] of buckets) {
1455
+ const week = Math.floor((t - firstT) / WEEK_BUCKETS);
1456
+ weeks.set(week, (weeks.get(week) ?? 0) + usd7);
1457
+ }
1458
+ const byUsd = windows.slice().sort((a, b) => a.usd - b.usd);
1459
+ const usdAsc = byUsd.map((w) => w.usd);
1460
+ const p90 = byUsd[p90Index(byUsd.length)];
1461
+ const weekUsdAsc = [...weeks.values()].sort((a, b) => a - b);
1462
+ return {
1463
+ assessed: true,
1464
+ windowsCount: windows.length,
1465
+ medianWindowUsd: median(usdAsc),
1466
+ p90WindowUsd: p90.usd,
1467
+ maxWindowUsd: usdAsc[usdAsc.length - 1],
1468
+ p90WindowActiveMinutes: p90.activeMinutes,
1469
+ weeksCount: weekUsdAsc.length,
1470
+ medianWeekUsd: median(weekUsdAsc),
1471
+ maxWeekUsd: weekUsdAsc[weekUsdAsc.length - 1]
1472
+ };
1473
+ }
1474
+
1395
1475
  // ../../packages/engine/src/optimize.ts
1396
1476
  function usd(n) {
1397
1477
  const rounded = Math.round(n * 100) / 100;
@@ -1893,6 +1973,17 @@ function toUsageMetrics(report) {
1893
1973
  pricingSnapshotDate: PRICING_SNAPSHOT_DATE
1894
1974
  };
1895
1975
  }
1976
+ function roundWindows(w) {
1977
+ return {
1978
+ ...w,
1979
+ medianWindowUsd: round2(w.medianWindowUsd),
1980
+ p90WindowUsd: round2(w.p90WindowUsd),
1981
+ maxWindowUsd: round2(w.maxWindowUsd),
1982
+ p90WindowActiveMinutes: Math.round(w.p90WindowActiveMinutes),
1983
+ medianWeekUsd: round2(w.medianWeekUsd),
1984
+ maxWeekUsd: round2(w.maxWeekUsd)
1985
+ };
1986
+ }
1896
1987
  function cleanFix(f) {
1897
1988
  return {
1898
1989
  ...f,
@@ -1935,6 +2026,7 @@ function buildAudit(input, opts = {}) {
1935
2026
  headlineWasteLabel: sanitizeText(headlineWasteLabel),
1936
2027
  plan,
1937
2028
  headlineWasteShare: round4(headlineWasteShare),
2029
+ usageWindows: roundWindows(computeWindowStats(report)),
1938
2030
  fixes: fixes.map(cleanFix),
1939
2031
  writer: opts.writer ?? "template",
1940
2032
  paid: false
@@ -2173,13 +2265,27 @@ function formatAudit(record, meta) {
2173
2265
  lines.push(`Pricing snapshot: ${m.pricingSnapshotDate}`);
2174
2266
  const mix = modelMix(m.modelBreakdown);
2175
2267
  if (mix) lines.push(`Model spend: ${mix}`);
2268
+ const w = record.usageWindows;
2176
2269
  if (subscription) {
2177
2270
  lines.push(
2178
2271
  `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
2272
  );
2273
+ if (w?.assessed) {
2274
+ lines.push(
2275
+ `Usage windows (5h, like your rate limit): median ${usd2(w.medianWindowUsd)}, busiest ${usd2(w.p90WindowUsd)}; busiest week ${usd2(w.maxWeekUsd)} (API-equivalent)`
2276
+ );
2277
+ if (share >= 0.01 && share < 1) {
2278
+ const gain = share / (1 - share);
2279
+ const extraMinutes = Math.round(w.p90WindowActiveMinutes * gain);
2280
+ lines.push(
2281
+ `Recovering ${shareText} buys about ${Math.round(gain * 100)}% more work per window: up to ~${extraMinutes} extra minutes in a window like your busiest.`
2282
+ );
2283
+ }
2284
+ }
2180
2285
  } else if (meta.planSource === "default") {
2286
+ const burn = w?.assessed && w.medianWeekUsd >= 50 ? ` Your median week burns ${usd2(w.medianWeekUsd)} at API rates.` : "";
2181
2287
  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."
2288
+ `Dollar figures are API-equivalent rates.${burn} On a Claude subscription? Rerun with --plan max20x (or pro, max5x) to frame results as token efficiency.`
2183
2289
  );
2184
2290
  }
2185
2291
  if (m.topProjects.length > 0) {
@@ -2362,7 +2468,16 @@ function renderHtml(record, meta) {
2362
2468
  const shareText = `${(share * 100).toFixed(1)}%`;
2363
2469
  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
2470
  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>` : "";
2471
+ const w = record.usageWindows;
2472
+ let headroom = "";
2473
+ if (subscription && w?.assessed && share >= 0.01 && share < 1) {
2474
+ const gain = share / (1 - share);
2475
+ const extraMinutes = Math.round(w.p90WindowActiveMinutes * gain);
2476
+ headroom = ` Recovering ${shareText} buys about ${Math.round(gain * 100)}% more work per window: up to ~${extraMinutes} extra minutes in a window like your busiest.`;
2477
+ }
2478
+ const weeklyBurn = !subscription && meta.planSource === "default" && w?.assessed && w.medianWeekUsd >= 50 ? ` Your median week burns ${esc(usd3(w.medianWeekUsd))} at API rates.` : "";
2479
+ 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).${headroom}</p>` : meta.planSource === "default" ? `<p class="sub">Dollar figures are API-equivalent rates.${weeklyBurn} On a Claude subscription? Rerun with --plan max20x (or pro, max5x) to frame results as token efficiency.</p>` : "";
2480
+ const windowTiles = subscription && w?.assessed ? `<div class="stats"><div class="stat"><div class="k">Median 5h window</div><div class="v">${esc(usd3(w.medianWindowUsd))}</div></div><div class="stat"><div class="k">Busiest 5h window (p90)</div><div class="v">${esc(usd3(w.p90WindowUsd))}</div></div><div class="stat"><div class="k">Busiest week</div><div class="v">${esc(usd3(w.maxWeekUsd))}</div></div></div>` : "";
2366
2481
  const dollarFixes = record.fixes.filter((f) => f.wasteUsd > 0).sort((a, b) => b.wasteUsd - a.wasteUsd);
2367
2482
  const otherIssues = record.fixes.filter((f) => f.wasteUsd === 0);
2368
2483
  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>`;
@@ -2394,6 +2509,7 @@ ${planNote}
2394
2509
  <div class="stat"><div class="k">Active hours</div><div class="v">${m.durationHours.toFixed(1)}</div></div>
2395
2510
  ${mix ? `<div class="stat"><div class="k">Model spend</div><div class="v v-small">${esc(mix)}</div></div>` : ""}
2396
2511
  </div>
2512
+ ${windowTiles}
2397
2513
 
2398
2514
  <h2>Spend by project</h2>
2399
2515
  <div class="chart">${projectChart(m.topProjects)}</div>
@@ -3642,7 +3758,7 @@ function parseBadgeFlags(args) {
3642
3758
  };
3643
3759
  }
3644
3760
  function cliVersion() {
3645
- return true ? "0.3.0" : "0.0.0-dev";
3761
+ return true ? "0.4.0" : "0.0.0-dev";
3646
3762
  }
3647
3763
  function helpText() {
3648
3764
  return [
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "costclaw",
3
- "version": "0.3.0",
3
+ "version": "0.4.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": {