costclaw 0.5.7 → 0.6.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 +33 -1
  2. package/dist/index.js +291 -42
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -30,6 +30,14 @@ Model spend: opus 71% / sonnet 24% / haiku 5%
30
30
  Top projects by spend:
31
31
  C--Projects-demo $XXX.XX 312 sessions cache 96.4% opus
32
32
 
33
+ Burn Clock (spend by day):
34
+ Monday [###########.........] $XXX.XX
35
+ ...
36
+ Friday [####################] $X,XXX.XX
37
+
38
+ Friday is your most expensive day ($X,XXX.XX), about 2.0x an average day across
39
+ 42 active days. Peak stretch: Friday morning.
40
+
33
41
  Overall setup score: 91 / 100 (Dialed in)
34
42
  CLAUDE.md quality [#################...] 85
35
43
  Context hygiene [###################.] 95
@@ -40,10 +48,17 @@ Overall setup score: 91 / 100 (Dialed in)
40
48
 
41
49
  Top fixes by recoverable spend:
42
50
  - [$XXX.XX] Recover spend lost to cache misses
43
- Keep the start of each session stable so the prompt cache is reused.
51
+ Your longest sessions started at 71% cache reuse and finished at 9%.
52
+ Compact or start a fresh session before the context outgrows the cache.
44
53
  Evidence: XX% of input tokens missed the cache across N sessions.
45
54
  ```
46
55
 
56
+ The cache fix names the specific reason your cache is missing, picked from what
57
+ your logs actually show: sessions whose cache decayed as they ran, a `CLAUDE.md`
58
+ churning with dates and TODOs, or a project that keeps starting cold. Burn Clock
59
+ needs at least 7 active days of logs; below that it is left out rather than
60
+ guessed at.
61
+
47
62
  ## On a subscription? Declare your plan
48
63
 
49
64
  Every dollar the audit prints is an API-equivalent price: what those tokens
@@ -169,6 +184,23 @@ scaffold, a prioritized fix playbook, and a conservative, project-derived
169
184
  (default: the current directory) to auto-fill the scaffold from your real files.
170
185
  By default it dry-runs into `./costclaw-out` and touches none of your files.
171
186
 
187
+ The playbook breaks the recoverable headline down by project, so you can see
188
+ which repo owes which dollars and at what cache hit rate:
189
+
190
+ ```
191
+ ### Where that money is
192
+
193
+ | Project | Recoverable | Cache hit | Main sessions |
194
+ | --- | --- | --- | --- |
195
+ | some-app | $490.43 | 98% | 229 |
196
+ | another-app | $312.43 | 99% | 131 |
197
+
198
+ 39 smaller projects account for the remaining $172.06.
199
+ ```
200
+
201
+ The rows plus that remainder line always add up to the headline figure above
202
+ them, so the breakdown reconciles rather than approximating.
203
+
172
204
  ```
173
205
  costclaw optimize [--path <dir>] [--claude-md <file>] [--project <dir>] [--out <dir>] [--write <file>] [--apply-settings [file]] [--force]
174
206
  ```
package/dist/index.js CHANGED
@@ -684,6 +684,26 @@ function cacheMissExposureUsd(report) {
684
684
  }
685
685
  return total;
686
686
  }
687
+ function cacheMissByProject(report) {
688
+ const out = [];
689
+ for (const proj of report.projects) {
690
+ let usd7 = 0;
691
+ let sessionsCount = 0;
692
+ const mainTotals = emptyTotals();
693
+ for (const s of proj.sessions) {
694
+ if (s.kind !== "main") continue;
695
+ sessionsCount += 1;
696
+ const p = priceFor(s.modelPrimary);
697
+ usd7 += (s.totals.input_tokens + s.totals.cache_creation_tokens) * (p.input - p.cache_read) / 1e6;
698
+ mainTotals.input_tokens += s.totals.input_tokens;
699
+ mainTotals.output_tokens += s.totals.output_tokens;
700
+ mainTotals.cache_creation_tokens += s.totals.cache_creation_tokens;
701
+ mainTotals.cache_read_tokens += s.totals.cache_read_tokens;
702
+ }
703
+ out.push({ slug: proj.slug, usd: usd7, cacheHitRate: cacheHitRate(mainTotals), sessionsCount });
704
+ }
705
+ return out.sort((a, b) => b.usd - a.usd);
706
+ }
687
707
 
688
708
  // ../../packages/engine/src/claudemd.ts
689
709
  function lerp(x, x0, x1, y0, y1) {
@@ -1268,44 +1288,16 @@ function synthesize(report, pillars, cmd, plan = "api") {
1268
1288
  };
1269
1289
  const sevForUsd = (n) => n >= 50 ? "critical" : n >= 10 ? "warn" : "info";
1270
1290
  const sWord = (k) => k === 1 ? "session" : "sessions";
1271
- const exposureMaterial = round23(exposure) > 0;
1272
- if (exposureMaterial) {
1273
- const ranked = report.projects.map((p) => {
1274
- let contrib = 0;
1275
- for (const sess of p.sessions) {
1276
- if (sess.kind !== "main") continue;
1277
- const rate = priceFor(sess.modelPrimary);
1278
- contrib += (sess.totals.input_tokens + sess.totals.cache_creation_tokens) * (rate.input - rate.cache_read) / 1e6;
1279
- }
1280
- return { slug: p.slug, contrib };
1281
- }).filter((r) => r.contrib > 0).sort((a, b) => b.contrib - a.contrib);
1282
- const worst = ranked.slice(0, 3).map((r) => r.slug);
1283
- fixes.push({
1284
- id: "cache_recovery",
1285
- title: "Recover spend lost to cache misses",
1286
- pillar: "context_hygiene",
1287
- pillarName: PILLARS.context_hygiene.name,
1288
- severity: sevForUsd(exposure),
1289
- wasteUsd: round23(exposure),
1290
- problem: sanitizeText(
1291
- `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"}.`
1292
- ),
1293
- action: sanitizeText(
1294
- "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."
1295
- ),
1296
- basis: sanitizeText("Cache-miss exposure summed across projects at the published input minus cache-read delta. Upper bound on recoverable spend.")
1297
- });
1298
- covered.add("cache_hit");
1299
- covered.add("cache_churn");
1300
- covered.add("recoverable_exposure");
1301
- }
1302
1291
  const heavyByTool = /* @__PURE__ */ new Map();
1303
1292
  let shortCount = 0;
1304
1293
  let misrouteUsd = 0;
1305
1294
  const misrouteSet = /* @__PURE__ */ new Set();
1306
1295
  let marathonUsd = 0;
1307
1296
  const marathonSet = /* @__PURE__ */ new Set();
1297
+ let marathonBest = null;
1298
+ let marathonBestSpread = -Infinity;
1308
1299
  let workflowUsd = 0;
1300
+ let badCacheBest = null;
1309
1301
  for (const f of report.findings) {
1310
1302
  if (f.ruleId === "HEAVY_TOOL_LOOPS" && f.evidence) {
1311
1303
  const tool = String(f.evidence["tool"] ?? "a tool");
@@ -1329,10 +1321,60 @@ function synthesize(report, pillars, cmd, plan = "api") {
1329
1321
  if (typeof sid === "string") marathonSet.add(sid);
1330
1322
  covered.add("session_marathon");
1331
1323
  covered.add("session_scope");
1324
+ const earlyHit = Number(f.evidence?.["earlyHit"]);
1325
+ const lateHit = Number(f.evidence?.["lateHit"]);
1326
+ if (Number.isFinite(earlyHit) && Number.isFinite(lateHit)) {
1327
+ const spread = earlyHit - lateHit;
1328
+ if (spread > marathonBestSpread) {
1329
+ marathonBestSpread = spread;
1330
+ marathonBest = { earlyHit, lateHit };
1331
+ }
1332
+ }
1332
1333
  } else if (f.ruleId === "WORKFLOW_COST") {
1333
1334
  workflowUsd += Number(f.evidence?.["delegatedCostUsd"]) || 0;
1335
+ } else if (f.ruleId === "BAD_CACHE_HIT") {
1336
+ const savings = f.estimatedMonthlySavingsUsd || 0;
1337
+ if (!badCacheBest || savings > badCacheBest.savings) {
1338
+ badCacheBest = {
1339
+ slug: f.project ?? "",
1340
+ recentHitRate: Number(f.evidence?.["recentHitRate"]) || 0,
1341
+ sessionsConsidered: Number(f.evidence?.["sessionsConsidered"]) || 0,
1342
+ savings
1343
+ };
1344
+ }
1334
1345
  }
1335
1346
  }
1347
+ const exposureMaterial = round23(exposure) > 0;
1348
+ if (exposureMaterial) {
1349
+ const worst = cacheMissByProject(report).filter((r) => r.usd > 0).slice(0, 3).map((r) => r.slug);
1350
+ const pct2 = (n) => Math.round(n * 100);
1351
+ let action;
1352
+ if (marathonBest && marathonUsd >= 0.25 * exposure && marathonBest.lateHit < marathonBest.earlyHit) {
1353
+ action = `The longest sessions started at ${pct2(marathonBest.earlyHit)}% cache reuse and finished at ${pct2(marathonBest.lateHit)}%. Compact or start a fresh session before the context outgrows the cache: the later turns re-pay for context you already bought.`;
1354
+ } else if (cmd.present && cmd.stabilityScore != null && cmd.stabilityScore < GAP_THRESHOLD && cmd.volatileMarkers >= 5) {
1355
+ action = `Your CLAUDE.md carries ${cmd.volatileMarkers} volatile markers (dates, TODOs, status notes). Every edit invalidates the cached prefix, so the next session re-pays full price for the whole file. Move the churn into a scratch note the agent opens on demand.`;
1356
+ } else if (badCacheBest) {
1357
+ action = `The last ${badCacheBest.sessionsConsidered} sessions in ${badCacheBest.slug} reused only ${pct2(badCacheBest.recentHitRate)}% from the cache. Open each session the same way (same CLAUDE.md, same first reads) so turn two onward reads the prefix at about a tenth of the input price.`;
1358
+ } else {
1359
+ action = "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.";
1360
+ }
1361
+ fixes.push({
1362
+ id: "cache_recovery",
1363
+ title: "Recover spend lost to cache misses",
1364
+ pillar: "context_hygiene",
1365
+ pillarName: PILLARS.context_hygiene.name,
1366
+ severity: sevForUsd(exposure),
1367
+ wasteUsd: round23(exposure),
1368
+ problem: sanitizeText(
1369
+ `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"}.`
1370
+ ),
1371
+ action: sanitizeText(action),
1372
+ basis: sanitizeText("Cache-miss exposure summed across projects at the published input minus cache-read delta. Upper bound on recoverable spend.")
1373
+ });
1374
+ covered.add("cache_hit");
1375
+ covered.add("cache_churn");
1376
+ covered.add("recoverable_exposure");
1377
+ }
1336
1378
  for (const [tool, e] of heavyByTool) {
1337
1379
  const n = Math.max(e.sessionsAffected, 1);
1338
1380
  fixes.push({
@@ -1500,6 +1542,51 @@ function computeWindowStats(report) {
1500
1542
  maxWeekUsd: weekUsdAsc[weekUsdAsc.length - 1]
1501
1543
  };
1502
1544
  }
1545
+ var UNASSESSED_BURN_CLOCK = {
1546
+ assessed: false,
1547
+ byDay: [0, 0, 0, 0, 0, 0, 0],
1548
+ byQuarter: [0, 0, 0, 0],
1549
+ topSlot: null,
1550
+ quietSlot: null,
1551
+ activeDays: 0
1552
+ };
1553
+ function burnClock(report, offsetMinutes = 0) {
1554
+ const merged = /* @__PURE__ */ new Map();
1555
+ for (const project of report.projects) {
1556
+ for (const session of project.sessions) {
1557
+ for (const b of session.costBuckets) merged.set(b.t, (merged.get(b.t) ?? 0) + b.usd);
1558
+ }
1559
+ }
1560
+ if (merged.size === 0) return UNASSESSED_BURN_CLOCK;
1561
+ const activeDaySet = /* @__PURE__ */ new Set();
1562
+ for (const t of merged.keys()) {
1563
+ const d = new Date(t * 9e5 + offsetMinutes * 6e4);
1564
+ activeDaySet.add(`${d.getUTCFullYear()}-${d.getUTCMonth()}-${d.getUTCDate()}`);
1565
+ }
1566
+ if (activeDaySet.size < 7) return { ...UNASSESSED_BURN_CLOCK, activeDays: activeDaySet.size };
1567
+ const byDay = [0, 0, 0, 0, 0, 0, 0];
1568
+ const byQuarter = [0, 0, 0, 0];
1569
+ const slot = Array.from({ length: 7 }, () => [0, 0, 0, 0]);
1570
+ for (const [t, usd7] of merged) {
1571
+ const d = new Date(t * 9e5 + offsetMinutes * 6e4);
1572
+ const day2 = d.getUTCDay();
1573
+ const quarter = Math.floor(d.getUTCHours() / 6);
1574
+ byDay[day2] += usd7;
1575
+ byQuarter[quarter] += usd7;
1576
+ slot[day2][quarter] += usd7;
1577
+ }
1578
+ let topSlot = null;
1579
+ let quietSlot = null;
1580
+ for (let day2 = 0; day2 < 7; day2++) {
1581
+ for (let quarter = 0; quarter < 4; quarter++) {
1582
+ const usd7 = slot[day2][quarter];
1583
+ if (usd7 <= 0) continue;
1584
+ if (!topSlot || usd7 > topSlot.usd) topSlot = { day: day2, quarter, usd: usd7 };
1585
+ if (!quietSlot || usd7 < quietSlot.usd) quietSlot = { day: day2, quarter, usd: usd7 };
1586
+ }
1587
+ }
1588
+ return { assessed: true, byDay, byQuarter, topSlot, quietSlot, activeDays: activeDaySet.size };
1589
+ }
1503
1590
 
1504
1591
  // ../../packages/engine/src/optimize.ts
1505
1592
  function usd(n) {
@@ -1743,7 +1830,7 @@ function buildClaudeMd(input, recoverable, notes, stats, carried) {
1743
1830
  if (droppedCommands > 0) {
1744
1831
  lines.push("");
1745
1832
  lines.push(
1746
- `The remaining ${droppedCommands} scripts stay in \`package.json\`; add one here only when the agent keeps needing it.`
1833
+ "The remaining scripts stay in `package.json`; add one here only when the agent keeps needing it."
1747
1834
  );
1748
1835
  notes.push(
1749
1836
  `Kept the ${commands.length} canonical commands of ${allCommands.length} detected; the rest stay in the manifest so this file stays lean.`
@@ -1980,6 +2067,32 @@ function renderDollarFix(fix, n) {
1980
2067
  `Do this: ${fix.action}`
1981
2068
  ].join("\n");
1982
2069
  }
2070
+ var CACHE_TABLE_FLOOR = 1;
2071
+ var CACHE_TABLE_CAP = 10;
2072
+ function renderCacheTable(report) {
2073
+ const all = cacheMissByProject(report);
2074
+ const shown = all.filter((r) => r.usd >= CACHE_TABLE_FLOOR).slice(0, CACHE_TABLE_CAP);
2075
+ if (shown.length === 0) return null;
2076
+ const shownSlugs = new Set(shown.map((r) => r.slug));
2077
+ const tail = all.filter((r) => !shownSlugs.has(r.slug));
2078
+ const lines = [
2079
+ "### Where that money is",
2080
+ "",
2081
+ "| Project | Recoverable | Cache hit | Main sessions |",
2082
+ "| --- | --- | --- | --- |"
2083
+ ];
2084
+ for (const r of shown) {
2085
+ lines.push(`| ${r.slug} | ${usd(r.usd)} | ${Math.round(r.cacheHitRate * 100)}% | ${r.sessionsCount} |`);
2086
+ }
2087
+ if (tail.length > 0) {
2088
+ const tailUsd = tail.reduce((acc, r) => acc + r.usd, 0);
2089
+ lines.push("");
2090
+ lines.push(
2091
+ `${tail.length} smaller project${tail.length === 1 ? "" : "s"} account for the remaining ${usd(tailUsd)}.`
2092
+ );
2093
+ }
2094
+ return lines.join("\n");
2095
+ }
1983
2096
  function practices(report, scores, recoverable) {
1984
2097
  const blocks = [];
1985
2098
  if (recoverable >= 1) {
@@ -2068,7 +2181,13 @@ function buildPlaybook(report, fixes, scores, recoverable, project) {
2068
2181
  "This is the ranked plan from your audit. The priority fixes are ordered by the dollars they recover; the setup warnings follow. CostClaw generates the plan; working through it is what recovers the spend."
2069
2182
  ].join("\n")
2070
2183
  );
2071
- dollarFixes.forEach((fix, i) => parts.push(renderDollarFix(fix, i + 1)));
2184
+ dollarFixes.forEach((fix, i) => {
2185
+ parts.push(renderDollarFix(fix, i + 1));
2186
+ if (fix.id === "cache_recovery") {
2187
+ const table = renderCacheTable(report);
2188
+ if (table) parts.push(table);
2189
+ }
2190
+ });
2072
2191
  if (warnFixes.length > 0) {
2073
2192
  const warnLines = [
2074
2193
  "## Setup warnings",
@@ -2090,9 +2209,12 @@ var BASE_DENY = [
2090
2209
  "Bash(rm *)",
2091
2210
  "Bash(rm -rf:*)",
2092
2211
  "Bash(sudo:*)",
2093
- "Bash(git push:*)",
2212
+ "Bash(git push --force:*)",
2213
+ "Bash(git push -f:*)",
2094
2214
  "Read(.env)",
2095
- "Read(.env.*)",
2215
+ "Read(.env.local)",
2216
+ "Read(.env.production)",
2217
+ "Read(.env.*.local)",
2096
2218
  "Read(**/*.pem)",
2097
2219
  "Read(**/*.key)",
2098
2220
  "Read(~/.ssh/**)"
@@ -2325,6 +2447,15 @@ function roundWindows(w) {
2325
2447
  maxWeekUsd: round2(w.maxWeekUsd)
2326
2448
  };
2327
2449
  }
2450
+ function roundBurnClock(b) {
2451
+ return {
2452
+ ...b,
2453
+ byDay: b.byDay.map(round2),
2454
+ byQuarter: b.byQuarter.map(round2),
2455
+ topSlot: b.topSlot ? { ...b.topSlot, usd: round2(b.topSlot.usd) } : null,
2456
+ quietSlot: b.quietSlot ? { ...b.quietSlot, usd: round2(b.quietSlot.usd) } : null
2457
+ };
2458
+ }
2328
2459
  function cleanFix(f) {
2329
2460
  return {
2330
2461
  ...f,
@@ -2368,6 +2499,7 @@ function buildAudit(input, opts = {}) {
2368
2499
  plan,
2369
2500
  headlineWasteShare: round4(headlineWasteShare),
2370
2501
  usageWindows: roundWindows(computeWindowStats(report)),
2502
+ burnClock: roundBurnClock(burnClock(report, input.tzOffsetMinutes ?? 0)),
2371
2503
  fixes: fixes.map(cleanFix),
2372
2504
  writer: opts.writer ?? "template",
2373
2505
  paid: false
@@ -2647,6 +2779,30 @@ function sinceOptimizeLine(meta) {
2647
2779
  function usd2(n) {
2648
2780
  return `$${(Math.round(n * 100) / 100).toFixed(2)}`;
2649
2781
  }
2782
+ var BURN_DAY_NAMES = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
2783
+ var BURN_DAY_ORDER = [1, 2, 3, 4, 5, 6, 0];
2784
+ var BURN_QUARTER_NAMES = ["night", "morning", "afternoon", "evening"];
2785
+ function burnSlotLabel(day2, quarter) {
2786
+ return `${BURN_DAY_NAMES[day2]} ${BURN_QUARTER_NAMES[quarter]}`;
2787
+ }
2788
+ function burnClockSentence(bc) {
2789
+ const spendDays = bc.byDay.filter((v) => v > 0);
2790
+ if (spendDays.length === 0) return null;
2791
+ let topDay = 0;
2792
+ for (let d = 0; d < bc.byDay.length; d += 1) {
2793
+ if ((bc.byDay[d] ?? 0) > (bc.byDay[topDay] ?? 0)) topDay = d;
2794
+ }
2795
+ const topUsd = bc.byDay[topDay] ?? 0;
2796
+ const average = spendDays.reduce((sum, v) => sum + v, 0) / spendDays.length;
2797
+ let sentence = `${BURN_DAY_NAMES[topDay]} is your most expensive day (${usd2(topUsd)})`;
2798
+ if (spendDays.length >= 2 && average > 0) {
2799
+ sentence += `, about ${(topUsd / average).toFixed(1)}x an average day across ${bc.activeDays} active days`;
2800
+ }
2801
+ sentence += ".";
2802
+ const top = bc.topSlot;
2803
+ if (top) sentence += ` Peak stretch: ${burnSlotLabel(top.day, top.quarter)}.`;
2804
+ return sentence;
2805
+ }
2650
2806
  var WRAP_WIDTH = 92;
2651
2807
  function wrapLines(text2, indent = 0) {
2652
2808
  const pad = " ".repeat(indent);
@@ -2821,6 +2977,23 @@ function formatAudit(record, meta, color = false) {
2821
2977
  );
2822
2978
  }
2823
2979
  }
2980
+ const bc = record.burnClock;
2981
+ if (bc?.assessed) {
2982
+ lines.push("");
2983
+ lines.push(a.bold("Burn Clock (spend by day):"));
2984
+ const max = Math.max(...bc.byDay, 0.01);
2985
+ for (const day2 of BURN_DAY_ORDER) {
2986
+ const v = bc.byDay[day2];
2987
+ const filled = Math.round(v / max * 20);
2988
+ const barStr = `[${a.brand("#".repeat(filled))}${a.dim(".".repeat(20 - filled))}]`;
2989
+ lines.push(` ${BURN_DAY_NAMES[day2].padEnd(10)} ${barStr} ${a.bold(usd2(v).padStart(9))}`);
2990
+ }
2991
+ const sentence = burnClockSentence(bc);
2992
+ if (sentence) {
2993
+ lines.push("");
2994
+ pushProse(lines, sentence);
2995
+ }
2996
+ }
2824
2997
  lines.push("");
2825
2998
  lines.push(
2826
2999
  `${a.bold("Overall setup score:")} ${a.score(record.overallScore, `${record.overallScore} / 100`)} (${a.score(record.overallScore, record.band.label)})`
@@ -2918,6 +3091,27 @@ function projectChart(projects) {
2918
3091
  }).join("");
2919
3092
  return `<svg viewBox="0 0 ${width} ${height}" width="100%" height="${height}" role="img" aria-label="Top projects by cost" preserveAspectRatio="xMinYMin meet">${rows}</svg>`;
2920
3093
  }
3094
+ function burnClockChart(bc) {
3095
+ const rowH = 22;
3096
+ const gap = 6;
3097
+ const labelW = 90;
3098
+ const valW = 70;
3099
+ const barMax = 300;
3100
+ const barH = 12;
3101
+ const width = labelW + barMax + valW;
3102
+ const height = BURN_DAY_ORDER.length * (rowH + gap) - gap;
3103
+ const max = Math.max(...bc.byDay, 0.01);
3104
+ const rows = BURN_DAY_ORDER.map((day2, i) => {
3105
+ const y = i * (rowH + gap);
3106
+ const v = bc.byDay[day2];
3107
+ const w = Math.max(barH, Math.round(v / max * barMax));
3108
+ const mid = y + rowH / 2;
3109
+ const barY = mid - barH / 2;
3110
+ const label = esc(BURN_DAY_NAMES[day2]);
3111
+ return `<text x="0" y="${mid}" class="c-lbl" dominant-baseline="middle">${label}</text><rect x="${labelW}" y="${barY}" width="${barMax}" height="${barH}" rx="${barH / 2}" fill="#f5ece6"></rect><rect x="${labelW}" y="${barY}" width="${w}" height="${barH}" rx="${barH / 2}" fill="#e07a5f"></rect><text x="${width}" y="${mid}" class="c-val" text-anchor="end" dominant-baseline="middle">${esc(usd3(v))}</text>`;
3112
+ }).join("");
3113
+ return `<svg viewBox="0 0 ${width} ${height}" width="100%" height="${height}" role="img" aria-label="Spend by day of week" preserveAspectRatio="xMinYMin meet">${rows}</svg>`;
3114
+ }
2921
3115
  function pillarBars(pillars) {
2922
3116
  return pillars.map((p) => {
2923
3117
  const name = esc(p.name);
@@ -3074,6 +3268,12 @@ function renderHtml(record, meta) {
3074
3268
  const otherIssues = record.fixes.filter((f) => f.wasteUsd === 0);
3075
3269
  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>`;
3076
3270
  const otherSection = otherIssues.length === 0 ? "" : `<h2>Other issues to tighten</h2><ul class="fixes">${otherIssues.map(otherFixCard).join("")}</ul>`;
3271
+ const bc = record.burnClock;
3272
+ const burnSentence = bc?.assessed ? burnClockSentence(bc) : null;
3273
+ const burnSection = bc?.assessed ? `<h2>Burn Clock (spend by day)</h2>
3274
+ <div class="chart">${burnClockChart(bc)}</div>
3275
+ ` + (burnSentence ? `<p class="sub">${esc(burnSentence)}</p>
3276
+ ` : "") : "";
3077
3277
  const skippedNote = meta.skipped.length > 0 ? `<p class="sub">Note: ${meta.skipped.length} file(s) could not be read and were skipped.</p>` : "";
3078
3278
  const receipt = sinceOptimizeLine(meta);
3079
3279
  const metaBlock = [
@@ -3113,6 +3313,7 @@ ${windowTiles}
3113
3313
  <h2>Spend by project</h2>
3114
3314
  <div class="chart">${projectChart(m.topProjects)}</div>
3115
3315
 
3316
+ ${burnSection}
3116
3317
  <h2>Setup score</h2>
3117
3318
  <div class="score-head">
3118
3319
  <span class="big">${record.overallScore} / 100</span>
@@ -3317,7 +3518,14 @@ async function runAudit(opts) {
3317
3518
  const setup = await readSetup();
3318
3519
  const configDir = join4(opts.home ?? homedir3(), ".costclaw");
3319
3520
  const { plan, planSource } = await resolvePlan(configDir, opts.plan);
3320
- const record = buildAudit({ logs, claudeMd, questionnaire: {}, setup, plan });
3521
+ const record = buildAudit({
3522
+ logs,
3523
+ claudeMd,
3524
+ questionnaire: {},
3525
+ setup,
3526
+ plan,
3527
+ tzOffsetMinutes: -(/* @__PURE__ */ new Date()).getTimezoneOffset()
3528
+ });
3321
3529
  const baseline = (await readCliConfig(configDir)).lastOptimize;
3322
3530
  const sinceOptimize = baseline ? { at: baseline.at, result: sinceBaseline(baseline, record) } : void 0;
3323
3531
  let snapshotNotice = null;
@@ -3501,14 +3709,30 @@ async function detectStructure(dir, dirs) {
3501
3709
  }
3502
3710
  return structure;
3503
3711
  }
3712
+ var TEST_FILE = /\.(test|spec)\.[cm]?[jt]sx?$/;
3713
+ async function containsTestFiles(dir) {
3714
+ const top = await listEntries(dir);
3715
+ if (top.files.some((f) => TEST_FILE.test(f))) return true;
3716
+ for (const sub of top.dirs) {
3717
+ const inner = await listEntries(join5(dir, sub));
3718
+ if (inner.files.some((f) => TEST_FILE.test(f))) return true;
3719
+ }
3720
+ return false;
3721
+ }
3504
3722
  async function detectTestsLocation(dir, files, dirs) {
3505
- if (dirs.includes("tests")) return "tests in tests/";
3506
- if (dirs.includes("test")) return "tests in test/";
3507
- if (dirs.includes("__tests__")) return "tests in __tests__/";
3508
- if (files.some((f) => /\.(test|spec)\.[cm]?[jt]sx?$/.test(f))) return "tests alongside source (*.test.* / *.spec.*)";
3723
+ const candidates = ["tests", "test", "__tests__"].filter((d) => dirs.includes(d));
3724
+ if (candidates.length > 0) {
3725
+ const withTests = [];
3726
+ for (const c of candidates) {
3727
+ if (await containsTestFiles(join5(dir, c))) withTests.push(c);
3728
+ }
3729
+ const chosen = withTests.length > 0 ? withTests : candidates;
3730
+ return `tests in ${chosen.map((c) => `${c}/`).join(" and ")}`;
3731
+ }
3732
+ if (files.some((f) => TEST_FILE.test(f))) return "tests alongside source (*.test.* / *.spec.*)";
3509
3733
  if (dirs.includes("src")) {
3510
3734
  const sub = await listEntries(join5(dir, "src"));
3511
- if (sub.files.some((f) => /\.(test|spec)\.[cm]?[jt]sx?$/.test(f))) {
3735
+ if (sub.files.some((f) => TEST_FILE.test(f))) {
3512
3736
  return "tests alongside source (*.test.* / *.spec.*)";
3513
3737
  }
3514
3738
  }
@@ -3885,6 +4109,16 @@ function describeDetection(project) {
3885
4109
  const stack = project.stack.length > 0 ? project.stack.join(", ") : "no stack detected";
3886
4110
  return `Detected: ${name}, ${cmds}, ${stack}`;
3887
4111
  }
4112
+ function looksUnscanned(project) {
4113
+ return project.stack.length === 0 && project.commands.length === 0;
4114
+ }
4115
+ function unscannedWarning(projectDir) {
4116
+ return [
4117
+ `Warning: the scan found no stack and no commands in ${projectDir}.`,
4118
+ "Are you in the right folder? optimize fills the scaffold from a project's own files,",
4119
+ "so run it from inside a project, or point it at one with --project <dir>."
4120
+ ];
4121
+ }
3888
4122
  async function pathExists(p) {
3889
4123
  try {
3890
4124
  await stat2(p);
@@ -4018,6 +4252,10 @@ async function runOptimize(opts) {
4018
4252
  const lines = [];
4019
4253
  lines.push("CostClaw optimize");
4020
4254
  lines.push("");
4255
+ if (looksUnscanned(project)) {
4256
+ lines.push(...unscannedWarning(projectDir));
4257
+ lines.push("");
4258
+ }
4021
4259
  if (opts.write) {
4022
4260
  const target = opts.write;
4023
4261
  const backup = `${target}.bak`;
@@ -4422,7 +4660,12 @@ function parseBadgeFlags(args) {
4422
4660
  };
4423
4661
  }
4424
4662
  function cliVersion() {
4425
- return true ? "0.5.7" : "0.0.0-dev";
4663
+ return true ? "0.6.0" : "0.0.0-dev";
4664
+ }
4665
+ function isHelpRequest(command, args) {
4666
+ if (command === void 0) return false;
4667
+ if (command === "help" || command === "--help" || command === "-h") return true;
4668
+ return args.includes("--help") || args.includes("-h");
4426
4669
  }
4427
4670
  function helpText() {
4428
4671
  return [
@@ -4436,6 +4679,7 @@ function helpText() {
4436
4679
  " costclaw activate <license-key> [--name <machine-name>]",
4437
4680
  " costclaw deactivate",
4438
4681
  " costclaw --version",
4682
+ " costclaw --help (or --help on any command above)",
4439
4683
  "",
4440
4684
  "audit reads your Claude Code logs from ~/.claude/projects (or --path) on this",
4441
4685
  "machine and prints a cost report plus a six-pillar setup score. It is free.",
@@ -4485,6 +4729,10 @@ async function main() {
4485
4729
  process.stdout.write(cliVersion() + "\n");
4486
4730
  return;
4487
4731
  }
4732
+ if (isHelpRequest(command, args)) {
4733
+ process.stdout.write(helpText() + "\n");
4734
+ return;
4735
+ }
4488
4736
  if (command === "audit") {
4489
4737
  const { output } = await runAudit(parseAuditFlags(args));
4490
4738
  process.stdout.write(output + "\n");
@@ -4558,6 +4806,7 @@ if (isEntryPoint) {
4558
4806
  export {
4559
4807
  cliVersion,
4560
4808
  helpText,
4809
+ isHelpRequest,
4561
4810
  parseAuditFlags,
4562
4811
  parseBadgeFlags,
4563
4812
  planFlag
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "costclaw",
3
- "version": "0.5.7",
3
+ "version": "0.6.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": {