costclaw 0.5.8 → 0.7.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 +45 -2
  2. package/dist/index.js +865 -84
  3. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -244,7 +244,7 @@ function parseSession(text2, opts = {}) {
244
244
  }
245
245
  }
246
246
  }
247
- s.costBuckets = [...buckets.entries()].sort((a, b) => a[0] - b[0]).map(([t, usd7]) => ({ t, usd: usd7 }));
247
+ s.costBuckets = [...buckets.entries()].sort((a, b) => a[0] - b[0]).map(([t, usd8]) => ({ t, usd: usd8 }));
248
248
  s.projectSlug = opts.projectSlug ?? projectFromCwd(cwd);
249
249
  let best = null;
250
250
  let bestCount = 0;
@@ -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 usd8 = 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
+ usd8 += (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: usd8, 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) {
@@ -1236,6 +1256,7 @@ var CHECK_FIX = {
1236
1256
  action: "Use a cheaper model for routine edits and reserve the top model for the hard reasoning. Same work, lower bill."
1237
1257
  }
1238
1258
  };
1259
+ var HEAVY_TOOL_PATTERN_MIN_SESSIONS = 2;
1239
1260
  function severityRank(s) {
1240
1261
  return s === "critical" ? 3 : s === "warn" ? 2 : 1;
1241
1262
  }
@@ -1243,7 +1264,7 @@ function sizeFix(cmd) {
1243
1264
  if (cmd.chars > 6e3) {
1244
1265
  return {
1245
1266
  title: "Trim your CLAUDE.md",
1246
- action: "Your CLAUDE.md is large and rides on every turn. Cut it to the durable conventions the agent actually needs and move the rest into docs it can open on demand."
1267
+ action: `Your CLAUDE.md is an estimated ${cmd.estTokens.toLocaleString()} tokens (${cmd.chars.toLocaleString()} characters), paid on every turn of every session. Cut it to the durable conventions the agent actually needs and move the rest into docs it can open on demand.`
1247
1268
  };
1248
1269
  }
1249
1270
  return {
@@ -1260,7 +1281,7 @@ function synthesize(report, pillars, cmd, plan = "api") {
1260
1281
  const fixes = [];
1261
1282
  const covered = /* @__PURE__ */ new Set();
1262
1283
  const round23 = (n) => Math.round(n * 100) / 100;
1263
- const usd7 = (n) => {
1284
+ const usd8 = (n) => {
1264
1285
  const fixed = round23(n).toFixed(2);
1265
1286
  const dot = fixed.indexOf(".");
1266
1287
  const whole = fixed.slice(0, dot).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
@@ -1268,44 +1289,16 @@ function synthesize(report, pillars, cmd, plan = "api") {
1268
1289
  };
1269
1290
  const sevForUsd = (n) => n >= 50 ? "critical" : n >= 10 ? "warn" : "info";
1270
1291
  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
1292
  const heavyByTool = /* @__PURE__ */ new Map();
1303
1293
  let shortCount = 0;
1304
1294
  let misrouteUsd = 0;
1305
1295
  const misrouteSet = /* @__PURE__ */ new Set();
1306
1296
  let marathonUsd = 0;
1307
1297
  const marathonSet = /* @__PURE__ */ new Set();
1298
+ let marathonBest = null;
1299
+ let marathonBestSpread = -Infinity;
1308
1300
  let workflowUsd = 0;
1301
+ let badCacheBest = null;
1309
1302
  for (const f of report.findings) {
1310
1303
  if (f.ruleId === "HEAVY_TOOL_LOOPS" && f.evidence) {
1311
1304
  const tool = String(f.evidence["tool"] ?? "a tool");
@@ -1329,12 +1322,67 @@ function synthesize(report, pillars, cmd, plan = "api") {
1329
1322
  if (typeof sid === "string") marathonSet.add(sid);
1330
1323
  covered.add("session_marathon");
1331
1324
  covered.add("session_scope");
1325
+ const earlyHit = Number(f.evidence?.["earlyHit"]);
1326
+ const lateHit = Number(f.evidence?.["lateHit"]);
1327
+ if (Number.isFinite(earlyHit) && Number.isFinite(lateHit)) {
1328
+ const spread = earlyHit - lateHit;
1329
+ if (spread > marathonBestSpread) {
1330
+ marathonBestSpread = spread;
1331
+ marathonBest = { earlyHit, lateHit };
1332
+ }
1333
+ }
1332
1334
  } else if (f.ruleId === "WORKFLOW_COST") {
1333
1335
  workflowUsd += Number(f.evidence?.["delegatedCostUsd"]) || 0;
1336
+ } else if (f.ruleId === "BAD_CACHE_HIT") {
1337
+ const savings = f.estimatedMonthlySavingsUsd || 0;
1338
+ if (!badCacheBest || savings > badCacheBest.savings) {
1339
+ badCacheBest = {
1340
+ slug: f.project ?? "",
1341
+ recentHitRate: Number(f.evidence?.["recentHitRate"]) || 0,
1342
+ sessionsConsidered: Number(f.evidence?.["sessionsConsidered"]) || 0,
1343
+ savings
1344
+ };
1345
+ }
1334
1346
  }
1335
1347
  }
1348
+ const exposureMaterial = round23(exposure) > 0;
1349
+ if (exposureMaterial) {
1350
+ const worst = cacheMissByProject(report).filter((r) => r.usd > 0).slice(0, 3).map((r) => r.slug);
1351
+ const pct2 = (n) => Math.round(n * 100);
1352
+ let action;
1353
+ if (marathonBest && marathonUsd >= 0.25 * exposure && marathonBest.lateHit < marathonBest.earlyHit) {
1354
+ 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.`;
1355
+ } else if (cmd.present && cmd.stabilityScore != null && cmd.stabilityScore < GAP_THRESHOLD && cmd.volatileMarkers >= 5) {
1356
+ 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.`;
1357
+ } else if (badCacheBest) {
1358
+ 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.`;
1359
+ } else {
1360
+ 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.";
1361
+ }
1362
+ fixes.push({
1363
+ id: "cache_recovery",
1364
+ title: "Recover spend lost to cache misses",
1365
+ pillar: "context_hygiene",
1366
+ pillarName: PILLARS.context_hygiene.name,
1367
+ severity: sevForUsd(exposure),
1368
+ wasteUsd: round23(exposure),
1369
+ problem: sanitizeText(
1370
+ `Up to ${usd8(exposure)} of input spend was paid at full price instead of the cache-read rate. Biggest contributors: ${worst.length ? worst.join(", ") : "your largest projects"}.`
1371
+ ),
1372
+ action: sanitizeText(action),
1373
+ basis: sanitizeText("Cache-miss exposure summed across projects at the published input minus cache-read delta. Upper bound on recoverable spend.")
1374
+ });
1375
+ covered.add("cache_hit");
1376
+ covered.add("cache_churn");
1377
+ covered.add("recoverable_exposure");
1378
+ }
1379
+ const singleSessionTools = [];
1336
1380
  for (const [tool, e] of heavyByTool) {
1337
1381
  const n = Math.max(e.sessionsAffected, 1);
1382
+ if (n < HEAVY_TOOL_PATTERN_MIN_SESSIONS) {
1383
+ singleSessionTools.push([tool, e]);
1384
+ continue;
1385
+ }
1338
1386
  fixes.push({
1339
1387
  id: `heavy_tool_${tool}`,
1340
1388
  title: `Heavy ${tool} usage in ${n} ${sWord(n)}`,
@@ -1347,6 +1395,21 @@ function synthesize(report, pillars, cmd, plan = "api") {
1347
1395
  basis: sanitizeText("Aggregated from per-session tool-use counts over the heavy-loop threshold.")
1348
1396
  });
1349
1397
  }
1398
+ if (singleSessionTools.length > 0) {
1399
+ const named = singleSessionTools.map(([tool, e]) => `${tool} (${e.maxFires}+ fires, 1 session)`);
1400
+ const k = singleSessionTools.length;
1401
+ fixes.push({
1402
+ id: "heavy_tool_single_session",
1403
+ title: `${k} more tool${k === 1 ? "" : "s"} flagged in a single session`,
1404
+ pillar: "prompting",
1405
+ pillarName: PILLARS.prompting.name,
1406
+ severity: "info",
1407
+ wasteUsd: 0,
1408
+ problem: sanitizeText(`${named.join(", ")} each fired 100 or more times, but only in one session so far, so it may be a one-off rather than a pattern.`),
1409
+ action: sanitizeText("Worth a look if it recurs across more sessions; not yet a repeating pattern to fix."),
1410
+ basis: sanitizeText("Aggregated from per-session tool-use counts over the heavy-loop threshold; grouped because each tool affected only one session.")
1411
+ });
1412
+ }
1350
1413
  if (shortCount > 0) {
1351
1414
  fixes.push({
1352
1415
  id: "short_sessions",
@@ -1369,7 +1432,7 @@ function synthesize(report, pillars, cmd, plan = "api") {
1369
1432
  pillarName: PILLARS.cost_discipline.name,
1370
1433
  severity: sevForUsd(misrouteUsd),
1371
1434
  wasteUsd: round23(misrouteUsd),
1372
- problem: sanitizeText(`${n} short premium-model ${sWord(n)} (Opus or Fable) with light tool use and small output cost about ${usd7(misrouteUsd)} more than a cheaper model would have.`),
1435
+ problem: sanitizeText(`${n} short premium-model ${sWord(n)} (Opus or Fable) with light tool use and small output cost about ${usd8(misrouteUsd)} more than a cheaper model would have.`),
1373
1436
  action: sanitizeText("Route short, simple sessions to a cheaper model such as Sonnet, and reserve premium models for hard reasoning."),
1374
1437
  basis: sanitizeText("Premium session cost minus the same tokens re-priced at the Sonnet rate, summed over sessions that pass a conservative triviality gate.")
1375
1438
  });
@@ -1383,7 +1446,7 @@ function synthesize(report, pillars, cmd, plan = "api") {
1383
1446
  pillarName: PILLARS.session_mgmt.name,
1384
1447
  severity: sevForUsd(marathonUsd),
1385
1448
  wasteUsd: round23(marathonUsd),
1386
- 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.`),
1449
+ problem: sanitizeText(`${n} long ${sWord(n)} kept growing until the prompt cache stopped helping, re-paying about ${usd8(marathonUsd)} for context in the later turns.`),
1387
1450
  action: sanitizeText("Compact or start a fresh session between tasks so the context stays small and the cache keeps working."),
1388
1451
  basis: sanitizeText("Recoverable estimate from the late-session cache shortfall versus the early-session hit rate.")
1389
1452
  });
@@ -1396,7 +1459,7 @@ function synthesize(report, pillars, cmd, plan = "api") {
1396
1459
  pillarName: PILLARS.cost_discipline.name,
1397
1460
  severity: "info",
1398
1461
  wasteUsd: 0,
1399
- problem: sanitizeText(`Workflow and subagent runs cost about ${usd7(workflowUsd)}; they are a power tool that can quietly dominate spend.`),
1462
+ problem: sanitizeText(`Workflow and subagent runs cost about ${usd8(workflowUsd)}; they are a power tool that can quietly dominate spend.`),
1400
1463
  action: sanitizeText("Scope workflows to genuinely large tasks and budget the agent count; a single high-effort prompt often suffices."),
1401
1464
  basis: sanitizeText("Summed cost of delegated subagent and workflow sub-logs.")
1402
1465
  });
@@ -1469,20 +1532,20 @@ function computeWindowStats(report) {
1469
1532
  }
1470
1533
  const windows = [];
1471
1534
  let windowStart = -Infinity;
1472
- for (const [t, usd7] of buckets) {
1535
+ for (const [t, usd8] of buckets) {
1473
1536
  if (t >= windowStart + WINDOW_BUCKETS) {
1474
1537
  windows.push({ usd: 0, activeMinutes: 0 });
1475
1538
  windowStart = t;
1476
1539
  }
1477
1540
  const w = windows[windows.length - 1];
1478
- w.usd += usd7;
1541
+ w.usd += usd8;
1479
1542
  w.activeMinutes += BUCKET_MINUTES;
1480
1543
  }
1481
1544
  const firstT = buckets[0][0];
1482
1545
  const weeks = /* @__PURE__ */ new Map();
1483
- for (const [t, usd7] of buckets) {
1546
+ for (const [t, usd8] of buckets) {
1484
1547
  const week = Math.floor((t - firstT) / WEEK_BUCKETS);
1485
- weeks.set(week, (weeks.get(week) ?? 0) + usd7);
1548
+ weeks.set(week, (weeks.get(week) ?? 0) + usd8);
1486
1549
  }
1487
1550
  const byUsd = windows.slice().sort((a, b) => a.usd - b.usd);
1488
1551
  const usdAsc = byUsd.map((w) => w.usd);
@@ -1500,6 +1563,51 @@ function computeWindowStats(report) {
1500
1563
  maxWeekUsd: weekUsdAsc[weekUsdAsc.length - 1]
1501
1564
  };
1502
1565
  }
1566
+ var UNASSESSED_BURN_CLOCK = {
1567
+ assessed: false,
1568
+ byDay: [0, 0, 0, 0, 0, 0, 0],
1569
+ byQuarter: [0, 0, 0, 0],
1570
+ topSlot: null,
1571
+ quietSlot: null,
1572
+ activeDays: 0
1573
+ };
1574
+ function burnClock(report, offsetMinutes = 0) {
1575
+ const merged = /* @__PURE__ */ new Map();
1576
+ for (const project of report.projects) {
1577
+ for (const session of project.sessions) {
1578
+ for (const b of session.costBuckets) merged.set(b.t, (merged.get(b.t) ?? 0) + b.usd);
1579
+ }
1580
+ }
1581
+ if (merged.size === 0) return UNASSESSED_BURN_CLOCK;
1582
+ const activeDaySet = /* @__PURE__ */ new Set();
1583
+ for (const t of merged.keys()) {
1584
+ const d = new Date(t * 9e5 + offsetMinutes * 6e4);
1585
+ activeDaySet.add(`${d.getUTCFullYear()}-${d.getUTCMonth()}-${d.getUTCDate()}`);
1586
+ }
1587
+ if (activeDaySet.size < 7) return { ...UNASSESSED_BURN_CLOCK, activeDays: activeDaySet.size };
1588
+ const byDay = [0, 0, 0, 0, 0, 0, 0];
1589
+ const byQuarter = [0, 0, 0, 0];
1590
+ const slot = Array.from({ length: 7 }, () => [0, 0, 0, 0]);
1591
+ for (const [t, usd8] of merged) {
1592
+ const d = new Date(t * 9e5 + offsetMinutes * 6e4);
1593
+ const day2 = d.getUTCDay();
1594
+ const quarter = Math.floor(d.getUTCHours() / 6);
1595
+ byDay[day2] += usd8;
1596
+ byQuarter[quarter] += usd8;
1597
+ slot[day2][quarter] += usd8;
1598
+ }
1599
+ let topSlot = null;
1600
+ let quietSlot = null;
1601
+ for (let day2 = 0; day2 < 7; day2++) {
1602
+ for (let quarter = 0; quarter < 4; quarter++) {
1603
+ const usd8 = slot[day2][quarter];
1604
+ if (usd8 <= 0) continue;
1605
+ if (!topSlot || usd8 > topSlot.usd) topSlot = { day: day2, quarter, usd: usd8 };
1606
+ if (!quietSlot || usd8 < quietSlot.usd) quietSlot = { day: day2, quarter, usd: usd8 };
1607
+ }
1608
+ }
1609
+ return { assessed: true, byDay, byQuarter, topSlot, quietSlot, activeDays: activeDaySet.size };
1610
+ }
1503
1611
 
1504
1612
  // ../../packages/engine/src/optimize.ts
1505
1613
  function usd(n) {
@@ -1666,7 +1774,20 @@ function stackOneLiner(stack) {
1666
1774
  }
1667
1775
  return `A ${joined} project.`;
1668
1776
  }
1669
- function buildClaudeMd(input, recoverable, notes, stats, carried) {
1777
+ function regenDisposition(label, categoryIndex, carried, hasContent, filledWhy) {
1778
+ const re = REGENERATED_HEADING[categoryIndex];
1779
+ const wasReplaced = carried.replaced.some((h) => re.test(h));
1780
+ if (wasReplaced) {
1781
+ return {
1782
+ name: label,
1783
+ disposition: "replaced",
1784
+ why: `Replaced your existing ${label} section with the version derived from the project scan.`
1785
+ };
1786
+ }
1787
+ if (hasContent) return { name: label, disposition: "filled", why: filledWhy };
1788
+ return { name: label, disposition: "placeholder", why: `${label} was left as a placeholder; no matching evidence was found.` };
1789
+ }
1790
+ function buildClaudeMd(input, recoverable, notes, stats, carried, dispositions) {
1670
1791
  const { currentClaudeMd, project } = input;
1671
1792
  const { title, intro, introDropped } = carriedIntro(currentClaudeMd);
1672
1793
  const recoverableLine = recoverable >= 1 ? ` - Your audit valued cache-miss exposure at ${usd(recoverable)}. Keeping this file small and stable is part of recovering it; the matching PLAYBOOK.md has the rest.` : " - Keeping this file small and stable keeps the cached prefix cheap to reuse each turn.";
@@ -1705,10 +1826,13 @@ function buildClaudeMd(input, recoverable, notes, stats, carried) {
1705
1826
  const titleText = projectName ?? title ?? "Project name";
1706
1827
  if (projectName) {
1707
1828
  filled.push("Title");
1829
+ dispositions.push({ name: "Title", disposition: "filled", why: "Filled from the project's detected name." });
1708
1830
  } else if (title) {
1709
1831
  notes.push(`Carried across the project title from your CLAUDE.md: "${title}".`);
1832
+ dispositions.push({ name: "Title", disposition: "carried", why: "Carried across from your existing CLAUDE.md." });
1710
1833
  } else {
1711
1834
  notes.push("No project title was detectable, so the title is a placeholder.");
1835
+ dispositions.push({ name: "Title", disposition: "placeholder", why: "No project title was detectable." });
1712
1836
  }
1713
1837
  const projectDesc = project?.description?.trim() || null;
1714
1838
  const synthesized = project ? stackOneLiner(project.stack) : null;
@@ -1721,14 +1845,24 @@ function buildClaudeMd(input, recoverable, notes, stats, carried) {
1721
1845
  }
1722
1846
  if (projectDesc) {
1723
1847
  filled.push("Description");
1848
+ dispositions.push({ name: "Description", disposition: "filled", why: "Filled from the project's manifest description." });
1724
1849
  } else if (synthesized) {
1725
1850
  filled.push("Stack");
1851
+ dispositions.push({ name: "Description", disposition: "filled", why: "Filled with a one-line summary of the detected stack." });
1726
1852
  } else if (intro) {
1727
1853
  notes.push("Carried across your one-line project description.");
1854
+ dispositions.push({ name: "Description", disposition: "carried", why: "Carried across from your existing CLAUDE.md." });
1728
1855
  } else if (introDropped) {
1729
1856
  notes.push(
1730
1857
  "Left your existing description out because it carried volatile markers (a date or status note) that would churn the cache."
1731
1858
  );
1859
+ dispositions.push({
1860
+ name: "Description",
1861
+ disposition: "placeholder",
1862
+ why: "Your existing description carried volatile markers that would churn the cache, so it was left out."
1863
+ });
1864
+ } else {
1865
+ dispositions.push({ name: "Description", disposition: "placeholder", why: "No description was detectable." });
1732
1866
  }
1733
1867
  parts.push([`# ${titleText}`, "", descLine].join("\n"));
1734
1868
  const allCommands = project?.commands ?? [];
@@ -1751,8 +1885,10 @@ function buildClaudeMd(input, recoverable, notes, stats, carried) {
1751
1885
  }
1752
1886
  parts.push(lines.join("\n"));
1753
1887
  filled.push("Commands");
1888
+ dispositions.push(regenDisposition("Commands", 0, carried, true, "Filled from the project's manifest commands."));
1754
1889
  } else {
1755
1890
  stats.placeholders += 1;
1891
+ dispositions.push(regenDisposition("Commands", 0, carried, false, ""));
1756
1892
  parts.push(
1757
1893
  [
1758
1894
  "## Commands",
@@ -1782,8 +1918,10 @@ function buildClaudeMd(input, recoverable, notes, stats, carried) {
1782
1918
  }
1783
1919
  parts.push(lines.join("\n"));
1784
1920
  filled.push("Project structure");
1921
+ dispositions.push(regenDisposition("Project structure", 1, carried, true, "Filled from the project's detected directory layout."));
1785
1922
  } else {
1786
1923
  stats.placeholders += 1;
1924
+ dispositions.push(regenDisposition("Project structure", 1, carried, false, ""));
1787
1925
  parts.push(
1788
1926
  [
1789
1927
  "## Project structure",
@@ -1805,8 +1943,10 @@ function buildClaudeMd(input, recoverable, notes, stats, carried) {
1805
1943
  for (const s of codeStyle) lines.push(`- ${s}`);
1806
1944
  parts.push(lines.join("\n"));
1807
1945
  filled.push("Code style");
1946
+ dispositions.push(regenDisposition("Code style", 2, carried, true, "Filled from the project's detected style conventions."));
1808
1947
  } else {
1809
1948
  stats.placeholders += 1;
1949
+ dispositions.push(regenDisposition("Code style", 2, carried, false, ""));
1810
1950
  parts.push(
1811
1951
  [
1812
1952
  "## Code style",
@@ -1828,8 +1968,10 @@ function buildClaudeMd(input, recoverable, notes, stats, carried) {
1828
1968
  for (const t of testing) lines.push(`- ${t}`);
1829
1969
  parts.push(lines.join("\n"));
1830
1970
  filled.push("Testing");
1971
+ dispositions.push(regenDisposition("Testing", 3, carried, true, "Filled from the project's detected test setup."));
1831
1972
  } else {
1832
1973
  stats.placeholders += 1;
1974
+ dispositions.push(regenDisposition("Testing", 3, carried, false, ""));
1833
1975
  parts.push(
1834
1976
  [
1835
1977
  "## Testing",
@@ -1845,8 +1987,10 @@ function buildClaudeMd(input, recoverable, notes, stats, carried) {
1845
1987
  }
1846
1988
  if (carried.workflow) {
1847
1989
  parts.push(["## Workflow", "", carried.workflow].join("\n"));
1990
+ dispositions.push({ name: "Workflow", disposition: "carried", why: "Carried across your Workflow section from the existing CLAUDE.md." });
1848
1991
  } else {
1849
1992
  stats.placeholders += 1;
1993
+ dispositions.push({ name: "Workflow", disposition: "placeholder", why: "No Workflow section was found, so this is a placeholder." });
1850
1994
  parts.push(
1851
1995
  [
1852
1996
  "## Workflow",
@@ -1862,8 +2006,10 @@ function buildClaudeMd(input, recoverable, notes, stats, carried) {
1862
2006
  }
1863
2007
  if (carried.architecture) {
1864
2008
  parts.push(["## Architecture and gotchas", "", carried.architecture].join("\n"));
2009
+ dispositions.push({ name: "Architecture and gotchas", disposition: "carried", why: "Carried across your Architecture and gotchas section from the existing CLAUDE.md." });
1865
2010
  } else {
1866
2011
  stats.placeholders += 1;
2012
+ dispositions.push({ name: "Architecture and gotchas", disposition: "placeholder", why: "No Architecture and gotchas section was found, so this is a placeholder to grow over time." });
1867
2013
  parts.push(
1868
2014
  [
1869
2015
  "## Architecture and gotchas",
@@ -1881,6 +2027,7 @@ function buildClaudeMd(input, recoverable, notes, stats, carried) {
1881
2027
  }
1882
2028
  for (const section of carried.other) {
1883
2029
  parts.push([`## ${section.heading}`, "", section.body].join("\n"));
2030
+ dispositions.push({ name: section.heading, disposition: "carried", why: "Carried across from your existing CLAUDE.md under its own heading." });
1884
2031
  }
1885
2032
  const envVars = (project?.envVars ?? []).map((v) => v.trim()).filter((v) => v.length > 0);
1886
2033
  if (envVars.length > 0) {
@@ -1893,8 +2040,10 @@ function buildClaudeMd(input, recoverable, notes, stats, carried) {
1893
2040
  ].join("\n")
1894
2041
  );
1895
2042
  filled.push("Environment");
2043
+ dispositions.push(regenDisposition("Environment", 4, carried, true, "Filled from the project's detected environment variable names."));
1896
2044
  } else {
1897
2045
  stats.placeholders += 1;
2046
+ dispositions.push(regenDisposition("Environment", 4, carried, false, ""));
1898
2047
  parts.push(
1899
2048
  [
1900
2049
  "## Environment",
@@ -1941,6 +2090,13 @@ function buildClaudeMd(input, recoverable, notes, stats, carried) {
1941
2090
  notes.push(
1942
2091
  `Left out ${joinAnd(carried.droppedVolatile)}: status-style sections churn on every update and bust the prompt cache. Keep that content in docs or a scratch note the agent opens on demand.`
1943
2092
  );
2093
+ for (const heading of carried.droppedVolatile) {
2094
+ dispositions.push({
2095
+ name: heading,
2096
+ disposition: "dropped",
2097
+ why: "Status-style sections churn on every update and bust the prompt cache."
2098
+ });
2099
+ }
1944
2100
  }
1945
2101
  if (currentClaudeMd && /^---\r?\n/.test(currentClaudeMd.trimStart())) {
1946
2102
  notes.push(
@@ -1980,6 +2136,36 @@ function renderDollarFix(fix, n) {
1980
2136
  `Do this: ${fix.action}`
1981
2137
  ].join("\n");
1982
2138
  }
2139
+ var CACHE_TABLE_FLOOR = 1;
2140
+ var CACHE_TABLE_CAP = 10;
2141
+ function renderCacheTable(report) {
2142
+ const all = cacheMissByProject(report);
2143
+ const shown = all.filter((r) => r.usd >= CACHE_TABLE_FLOOR).slice(0, CACHE_TABLE_CAP);
2144
+ if (shown.length === 0) return null;
2145
+ const shownSlugs = new Set(shown.map((r) => r.slug));
2146
+ const tail = all.filter((r) => !shownSlugs.has(r.slug));
2147
+ const lines = [
2148
+ "### Where that money is",
2149
+ "",
2150
+ "| Project | Recoverable | Cache hit | Main sessions |",
2151
+ "| --- | --- | --- | --- |"
2152
+ ];
2153
+ for (const r of shown) {
2154
+ lines.push(`| ${r.slug} | ${usd(r.usd)} | ${Math.round(r.cacheHitRate * 100)}% | ${r.sessionsCount} |`);
2155
+ }
2156
+ if (tail.length > 0) {
2157
+ const tailUsd = tail.reduce((acc, r) => acc + r.usd, 0);
2158
+ lines.push("");
2159
+ lines.push(
2160
+ `${tail.length} smaller project${tail.length === 1 ? "" : "s"} account for the remaining ${usd(tailUsd)}.`
2161
+ );
2162
+ }
2163
+ lines.push("");
2164
+ lines.push(
2165
+ "A high cache hit rate next to a real dollar figure is not a contradiction: this total also prices new cache-creation (write) tokens against the cache-read rate, not misses alone, so a project that keeps writing fresh content into the cache every turn can carry a big number even at a high hit rate. Treat it as an upper bound, not a guarantee."
2166
+ );
2167
+ return lines.join("\n");
2168
+ }
1983
2169
  function practices(report, scores, recoverable) {
1984
2170
  const blocks = [];
1985
2171
  if (recoverable >= 1) {
@@ -2052,7 +2238,16 @@ function tokenDiscipline(report) {
2052
2238
  "- Set `ANTHROPIC_MODEL` and `CLAUDE_CODE_EFFORT_LEVEL` in your shell profile so every session starts on the right model and effort without a per-session step."
2053
2239
  ].join("\n");
2054
2240
  }
2055
- function buildPlaybook(report, fixes, scores, recoverable, project) {
2241
+ function claudeMdReceiptLine(claudeMdTokens) {
2242
+ const { before, after } = claudeMdTokens;
2243
+ if (before == null || before === after) return null;
2244
+ const delta = after - before;
2245
+ const grew = delta > 0;
2246
+ const pct2 = before > 0 ? ` (${(Math.abs(delta) / before * 100).toFixed(1)}% ${grew ? "larger" : "smaller"})` : "";
2247
+ const tail = grew ? "It is re-read on every turn, so the larger file costs a little more every time too." : "It is re-read on every turn, so that saving repeats every session.";
2248
+ return `Your optimized CLAUDE.md goes from an estimated ${before.toLocaleString()} tokens to ${after.toLocaleString()}${pct2}. ${tail}`;
2249
+ }
2250
+ function buildPlaybook(report, fixes, scores, recoverable, claudeMdTokens, project) {
2056
2251
  const dollarFixes = fixes.filter((f) => f.wasteUsd > 0);
2057
2252
  const warnFixes = fixes.filter((f) => f.wasteUsd <= 0);
2058
2253
  const parts = [];
@@ -2068,7 +2263,15 @@ function buildPlaybook(report, fixes, scores, recoverable, project) {
2068
2263
  "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
2264
  ].join("\n")
2070
2265
  );
2071
- dollarFixes.forEach((fix, i) => parts.push(renderDollarFix(fix, i + 1)));
2266
+ const receipt = claudeMdReceiptLine(claudeMdTokens);
2267
+ if (receipt) parts.push(receipt);
2268
+ dollarFixes.forEach((fix, i) => {
2269
+ parts.push(renderDollarFix(fix, i + 1));
2270
+ if (fix.id === "cache_recovery") {
2271
+ const table = renderCacheTable(report);
2272
+ if (table) parts.push(table);
2273
+ }
2274
+ });
2072
2275
  if (warnFixes.length > 0) {
2073
2276
  const warnLines = [
2074
2277
  "## Setup warnings",
@@ -2257,22 +2460,39 @@ function optimize(input) {
2257
2460
  const notes = [];
2258
2461
  const stats = { placeholders: 0 };
2259
2462
  const carried = carriedSections(input.currentClaudeMd);
2260
- const optimizedClaudeMd = buildClaudeMd(input, recoverable, notes, stats, carried);
2261
- const playbook = buildPlaybook(input.report, input.fixes, input.scores, recoverable, input.project);
2463
+ const dispositions = [];
2464
+ const optimizedClaudeMd = buildClaudeMd(input, recoverable, notes, stats, carried, dispositions);
2465
+ const claudeMdTokens = {
2466
+ before: input.currentClaudeMd ? Math.round(input.currentClaudeMd.trim().length / 4) : null,
2467
+ after: Math.round(optimizedClaudeMd.trim().length / 4)
2468
+ };
2469
+ const playbook = buildPlaybook(input.report, input.fixes, input.scores, recoverable, claudeMdTokens, input.project);
2262
2470
  const settingsJson = buildSettings(input.project);
2263
2471
  const harnessPrompt = buildHarnessPrompt(input, carried);
2264
2472
  const cleanNotes = notes.map((n) => clean(n));
2265
- if (hasEmDash(optimizedClaudeMd) || hasEmDash(playbook) || hasEmDash(settingsJson) || hasEmDash(harnessPrompt) || cleanNotes.some(hasEmDash)) {
2473
+ const cleanDispositions = dispositions.map((d) => ({ ...d, name: clean(d.name), why: clean(d.why) }));
2474
+ if (hasEmDash(optimizedClaudeMd) || hasEmDash(playbook) || hasEmDash(settingsJson) || hasEmDash(harnessPrompt) || cleanNotes.some(hasEmDash) || cleanDispositions.some((d) => hasEmDash(d.name) || hasEmDash(d.why))) {
2266
2475
  return {
2267
2476
  optimizedClaudeMd: sanitizeText(optimizedClaudeMd),
2268
2477
  playbook: sanitizeText(playbook),
2269
2478
  settingsJson: sanitizeText(settingsJson),
2270
2479
  harnessPrompt: sanitizeText(harnessPrompt),
2271
2480
  notes: cleanNotes.map(sanitizeText),
2272
- placeholdersRemaining: stats.placeholders
2481
+ placeholdersRemaining: stats.placeholders,
2482
+ claudeMdTokens,
2483
+ sectionDispositions: cleanDispositions.map((d) => ({ ...d, name: sanitizeText(d.name), why: sanitizeText(d.why) }))
2273
2484
  };
2274
2485
  }
2275
- return { optimizedClaudeMd, playbook, settingsJson, harnessPrompt, notes: cleanNotes, placeholdersRemaining: stats.placeholders };
2486
+ return {
2487
+ optimizedClaudeMd,
2488
+ playbook,
2489
+ settingsJson,
2490
+ harnessPrompt,
2491
+ notes: cleanNotes,
2492
+ placeholdersRemaining: stats.placeholders,
2493
+ claudeMdTokens,
2494
+ sectionDispositions: cleanDispositions
2495
+ };
2276
2496
  }
2277
2497
 
2278
2498
  // ../../packages/engine/src/audit.ts
@@ -2301,7 +2521,7 @@ function toUsageMetrics(report) {
2301
2521
  cacheHitRate: round4(cacheHitRate(sess.totals))
2302
2522
  }));
2303
2523
  const modelBreakdown = {};
2304
- for (const [model, usd7] of Object.entries(s.modelBreakdown)) modelBreakdown[model] = round2(usd7);
2524
+ for (const [model, usd8] of Object.entries(s.modelBreakdown)) modelBreakdown[model] = round2(usd8);
2305
2525
  return {
2306
2526
  spendUsd: round2(s.cost_usd),
2307
2527
  cacheSavingsUsd: round2(s.cache_savings_usd),
@@ -2328,6 +2548,15 @@ function roundWindows(w) {
2328
2548
  maxWeekUsd: round2(w.maxWeekUsd)
2329
2549
  };
2330
2550
  }
2551
+ function roundBurnClock(b) {
2552
+ return {
2553
+ ...b,
2554
+ byDay: b.byDay.map(round2),
2555
+ byQuarter: b.byQuarter.map(round2),
2556
+ topSlot: b.topSlot ? { ...b.topSlot, usd: round2(b.topSlot.usd) } : null,
2557
+ quietSlot: b.quietSlot ? { ...b.quietSlot, usd: round2(b.quietSlot.usd) } : null
2558
+ };
2559
+ }
2331
2560
  function cleanFix(f) {
2332
2561
  return {
2333
2562
  ...f,
@@ -2371,6 +2600,7 @@ function buildAudit(input, opts = {}) {
2371
2600
  plan,
2372
2601
  headlineWasteShare: round4(headlineWasteShare),
2373
2602
  usageWindows: roundWindows(computeWindowStats(report)),
2603
+ burnClock: roundBurnClock(burnClock(report, input.tzOffsetMinutes ?? 0)),
2374
2604
  fixes: fixes.map(cleanFix),
2375
2605
  writer: opts.writer ?? "template",
2376
2606
  paid: false
@@ -2501,7 +2731,20 @@ var MAX_CLAUDEMD_BYTES = 1 * 1024 * 1024;
2501
2731
  import { mkdir as mkdir2, readFile as readFile3, readdir as readdir2, rm, writeFile as writeFile2 } from "fs/promises";
2502
2732
  import { join as join4, resolve } from "path";
2503
2733
  import { homedir as homedir3 } from "os";
2734
+
2735
+ // src/open.ts
2504
2736
  import { spawn } from "child_process";
2737
+ function openInBrowser(target) {
2738
+ try {
2739
+ const platform = process.platform;
2740
+ const [cmd, args] = platform === "win32" ? ["cmd", ["/c", "start", "", target]] : platform === "darwin" ? ["open", [target]] : ["xdg-open", [target]];
2741
+ const child = spawn(cmd, args, { detached: true, stdio: "ignore" });
2742
+ child.on("error", () => {
2743
+ });
2744
+ child.unref();
2745
+ } catch {
2746
+ }
2747
+ }
2505
2748
 
2506
2749
  // src/read-sessions.ts
2507
2750
  import { readdir } from "fs/promises";
@@ -2650,6 +2893,30 @@ function sinceOptimizeLine(meta) {
2650
2893
  function usd2(n) {
2651
2894
  return `$${(Math.round(n * 100) / 100).toFixed(2)}`;
2652
2895
  }
2896
+ var BURN_DAY_NAMES = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
2897
+ var BURN_DAY_ORDER = [1, 2, 3, 4, 5, 6, 0];
2898
+ var BURN_QUARTER_NAMES = ["night", "morning", "afternoon", "evening"];
2899
+ function burnSlotLabel(day2, quarter) {
2900
+ return `${BURN_DAY_NAMES[day2]} ${BURN_QUARTER_NAMES[quarter]}`;
2901
+ }
2902
+ function burnClockSentence(bc) {
2903
+ const spendDays = bc.byDay.filter((v) => v > 0);
2904
+ if (spendDays.length === 0) return null;
2905
+ let topDay = 0;
2906
+ for (let d = 0; d < bc.byDay.length; d += 1) {
2907
+ if ((bc.byDay[d] ?? 0) > (bc.byDay[topDay] ?? 0)) topDay = d;
2908
+ }
2909
+ const topUsd = bc.byDay[topDay] ?? 0;
2910
+ const average = spendDays.reduce((sum, v) => sum + v, 0) / spendDays.length;
2911
+ let sentence = `${BURN_DAY_NAMES[topDay]} is your most expensive day (${usd2(topUsd)})`;
2912
+ if (spendDays.length >= 2 && average > 0) {
2913
+ sentence += `, about ${(topUsd / average).toFixed(1)}x an average day across ${bc.activeDays} active days`;
2914
+ }
2915
+ sentence += ".";
2916
+ const top = bc.topSlot;
2917
+ if (top) sentence += ` Peak stretch: ${burnSlotLabel(top.day, top.quarter)}.`;
2918
+ return sentence;
2919
+ }
2653
2920
  var WRAP_WIDTH = 92;
2654
2921
  function wrapLines(text2, indent = 0) {
2655
2922
  const pad = " ".repeat(indent);
@@ -2824,6 +3091,23 @@ function formatAudit(record, meta, color = false) {
2824
3091
  );
2825
3092
  }
2826
3093
  }
3094
+ const bc = record.burnClock;
3095
+ if (bc?.assessed) {
3096
+ lines.push("");
3097
+ lines.push(a.bold("Burn Clock (spend by day):"));
3098
+ const max = Math.max(...bc.byDay, 0.01);
3099
+ for (const day2 of BURN_DAY_ORDER) {
3100
+ const v = bc.byDay[day2];
3101
+ const filled = Math.round(v / max * 20);
3102
+ const barStr = `[${a.brand("#".repeat(filled))}${a.dim(".".repeat(20 - filled))}]`;
3103
+ lines.push(` ${BURN_DAY_NAMES[day2].padEnd(10)} ${barStr} ${a.bold(usd2(v).padStart(9))}`);
3104
+ }
3105
+ const sentence = burnClockSentence(bc);
3106
+ if (sentence) {
3107
+ lines.push("");
3108
+ pushProse(lines, sentence);
3109
+ }
3110
+ }
2827
3111
  lines.push("");
2828
3112
  lines.push(
2829
3113
  `${a.bold("Overall setup score:")} ${a.score(record.overallScore, `${record.overallScore} / 100`)} (${a.score(record.overallScore, record.band.label)})`
@@ -2921,6 +3205,27 @@ function projectChart(projects) {
2921
3205
  }).join("");
2922
3206
  return `<svg viewBox="0 0 ${width} ${height}" width="100%" height="${height}" role="img" aria-label="Top projects by cost" preserveAspectRatio="xMinYMin meet">${rows}</svg>`;
2923
3207
  }
3208
+ function burnClockChart(bc) {
3209
+ const rowH = 22;
3210
+ const gap = 6;
3211
+ const labelW = 90;
3212
+ const valW = 70;
3213
+ const barMax = 300;
3214
+ const barH = 12;
3215
+ const width = labelW + barMax + valW;
3216
+ const height = BURN_DAY_ORDER.length * (rowH + gap) - gap;
3217
+ const max = Math.max(...bc.byDay, 0.01);
3218
+ const rows = BURN_DAY_ORDER.map((day2, i) => {
3219
+ const y = i * (rowH + gap);
3220
+ const v = bc.byDay[day2];
3221
+ const w = Math.max(barH, Math.round(v / max * barMax));
3222
+ const mid = y + rowH / 2;
3223
+ const barY = mid - barH / 2;
3224
+ const label = esc(BURN_DAY_NAMES[day2]);
3225
+ 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>`;
3226
+ }).join("");
3227
+ 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>`;
3228
+ }
2924
3229
  function pillarBars(pillars) {
2925
3230
  return pillars.map((p) => {
2926
3231
  const name = esc(p.name);
@@ -3077,6 +3382,12 @@ function renderHtml(record, meta) {
3077
3382
  const otherIssues = record.fixes.filter((f) => f.wasteUsd === 0);
3078
3383
  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>`;
3079
3384
  const otherSection = otherIssues.length === 0 ? "" : `<h2>Other issues to tighten</h2><ul class="fixes">${otherIssues.map(otherFixCard).join("")}</ul>`;
3385
+ const bc = record.burnClock;
3386
+ const burnSentence = bc?.assessed ? burnClockSentence(bc) : null;
3387
+ const burnSection = bc?.assessed ? `<h2>Burn Clock (spend by day)</h2>
3388
+ <div class="chart">${burnClockChart(bc)}</div>
3389
+ ` + (burnSentence ? `<p class="sub">${esc(burnSentence)}</p>
3390
+ ` : "") : "";
3080
3391
  const skippedNote = meta.skipped.length > 0 ? `<p class="sub">Note: ${meta.skipped.length} file(s) could not be read and were skipped.</p>` : "";
3081
3392
  const receipt = sinceOptimizeLine(meta);
3082
3393
  const metaBlock = [
@@ -3116,6 +3427,7 @@ ${windowTiles}
3116
3427
  <h2>Spend by project</h2>
3117
3428
  <div class="chart">${projectChart(m.topProjects)}</div>
3118
3429
 
3430
+ ${burnSection}
3119
3431
  <h2>Setup score</h2>
3120
3432
  <div class="score-head">
3121
3433
  <span class="big">${record.overallScore} / 100</span>
@@ -3279,17 +3591,6 @@ async function resolvePlan(configDir, flag) {
3279
3591
  var DEFAULT_HTML_FILE = "costclaw-report.html";
3280
3592
  var DEFAULT_CARD_FILE = "costclaw-card.svg";
3281
3593
  var SNAPSHOT_KEEP = 50;
3282
- function openInBrowser(target) {
3283
- try {
3284
- const platform = process.platform;
3285
- const [cmd, args] = platform === "win32" ? ["cmd", ["/c", "start", "", target]] : platform === "darwin" ? ["open", [target]] : ["xdg-open", [target]];
3286
- const child = spawn(cmd, args, { detached: true, stdio: "ignore" });
3287
- child.on("error", () => {
3288
- });
3289
- child.unref();
3290
- } catch {
3291
- }
3292
- }
3293
3594
  async function loadAuditInputs(opts) {
3294
3595
  const root = opts.path || defaultProjectsPath();
3295
3596
  const { logs, skipped } = await readSessions(root);
@@ -3320,7 +3621,14 @@ async function runAudit(opts) {
3320
3621
  const setup = await readSetup();
3321
3622
  const configDir = join4(opts.home ?? homedir3(), ".costclaw");
3322
3623
  const { plan, planSource } = await resolvePlan(configDir, opts.plan);
3323
- const record = buildAudit({ logs, claudeMd, questionnaire: {}, setup, plan });
3624
+ const record = buildAudit({
3625
+ logs,
3626
+ claudeMd,
3627
+ questionnaire: {},
3628
+ setup,
3629
+ plan,
3630
+ tzOffsetMinutes: -(/* @__PURE__ */ new Date()).getTimezoneOffset()
3631
+ });
3324
3632
  const baseline = (await readCliConfig(configDir)).lastOptimize;
3325
3633
  const sinceOptimize = baseline ? { at: baseline.at, result: sinceBaseline(baseline, record) } : void 0;
3326
3634
  let snapshotNotice = null;
@@ -3368,6 +3676,412 @@ import { mkdir as mkdir3, writeFile as writeFile3, readFile as readFile5, stat a
3368
3676
  import { join as join6, dirname } from "path";
3369
3677
  import { homedir as homedir4 } from "os";
3370
3678
 
3679
+ // src/optimize-dashboard.ts
3680
+ function usd5(n) {
3681
+ const rounded = Math.round(n * 100) / 100;
3682
+ const neg = rounded < 0;
3683
+ const fixed = Math.abs(rounded).toFixed(2);
3684
+ const dot = fixed.indexOf(".");
3685
+ const whole = fixed.slice(0, dot);
3686
+ const cents = fixed.slice(dot);
3687
+ const grouped = whole.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
3688
+ return `${neg ? "-" : ""}$${grouped}${cents}`;
3689
+ }
3690
+ function fmtTokens(n) {
3691
+ const rounded = Math.round(n);
3692
+ const neg = rounded < 0;
3693
+ const grouped = Math.abs(rounded).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
3694
+ return `${neg ? "-" : ""}${grouped}`;
3695
+ }
3696
+ function approxTokens(n) {
3697
+ return `~${fmtTokens(n)}`;
3698
+ }
3699
+ function plural2(n, noun) {
3700
+ return n === 1 ? noun : `${noun}s`;
3701
+ }
3702
+ var STYLE2 = `
3703
+ :root{
3704
+ --bg:#faf9f7; --panel:#fff; --ink:#1a1a19; --ink2:#5c5a55; --line:#e3e0da;
3705
+ --accent:#8a5a2b; --good:#2f6f4f; --warn:#8a6a1f; --bad:#8a3a2b;
3706
+ --mono:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;
3707
+ --sans:ui-sans-serif,system-ui,-apple-system,Segoe UI,Roboto,sans-serif;
3708
+ }
3709
+ @media (prefers-color-scheme:dark){:root:not([data-theme="light"]){
3710
+ --bg:#15151a; --panel:#1d1d23; --ink:#f0eeea; --ink2:#a8a49c; --line:#33323a;
3711
+ --accent:#d9a05b; --good:#6fbf8f; --warn:#d9b95b; --bad:#e08a72;
3712
+ }}
3713
+ *{box-sizing:border-box}
3714
+ body{margin:0;background:var(--bg);color:var(--ink);font:16px/1.55 var(--sans);
3715
+ -webkit-font-smoothing:antialiased}
3716
+ .wrap{max-width:1080px;margin:0 auto;padding:40px 24px 96px}
3717
+ header{border-bottom:1px solid var(--line);padding-bottom:24px;margin-bottom:32px}
3718
+ .kicker{font-size:.72rem;letter-spacing:.13em;text-transform:uppercase;color:var(--ink2);margin:0 0 10px}
3719
+ h1{font-size:clamp(1.6rem,3.6vw,2.3rem);margin:0 0 6px;letter-spacing:-.02em;font-weight:750}
3720
+ .sub{color:var(--ink2);margin:0;font-size:.95rem}
3721
+ h2{font-size:1.06rem;letter-spacing:-.01em;margin:40px 0 14px;font-weight:700}
3722
+ h2 .n{color:var(--ink2);font-weight:400;font-size:.85rem;margin-left:8px}
3723
+ .panel{background:var(--panel);border:1px solid var(--line);border-radius:12px;padding:20px 22px}
3724
+ .grid{display:grid;gap:16px}
3725
+ .g3{grid-template-columns:repeat(auto-fit,minmax(210px,1fr))}
3726
+ .g2{grid-template-columns:repeat(auto-fit,minmax(300px,1fr))}
3727
+ .stat{font-variant-numeric:tabular-nums}
3728
+ .stat .v{font-size:1.65rem;font-weight:750;letter-spacing:-.02em;display:block}
3729
+ .stat .l{color:var(--ink2);font-size:.8rem;text-transform:uppercase;letter-spacing:.07em}
3730
+ .stat .d{font-size:.83rem;margin-top:6px;color:var(--ink2)}
3731
+ .win{color:var(--good);font-weight:650}
3732
+ .bar{height:26px;border-radius:6px;background:linear-gradient(90deg,var(--accent) 0%,var(--accent) 100%);
3733
+ position:relative;overflow:hidden}
3734
+ .bar .cut{position:absolute;inset:0 0 0 95.6%;background:var(--good);opacity:.85}
3735
+ .barlabels{display:flex;justify-content:space-between;font-size:.78rem;color:var(--ink2);margin-top:6px;
3736
+ font-variant-numeric:tabular-nums}
3737
+ table{width:100%;border-collapse:collapse;font-size:.9rem;font-variant-numeric:tabular-nums}
3738
+ th,td{text-align:left;padding:9px 10px;border-bottom:1px solid var(--line)}
3739
+ th{font-size:.74rem;text-transform:uppercase;letter-spacing:.07em;color:var(--ink2);font-weight:600}
3740
+ td.num,th.num{text-align:right}
3741
+ .scroll{overflow-x:auto}
3742
+ .fix{border-left:3px solid var(--accent);padding:2px 0 2px 16px;margin:0 0 22px}
3743
+ .fix h3{margin:0 0 4px;font-size:1rem}
3744
+ .fix .amt{font-family:var(--mono);color:var(--accent);font-weight:700}
3745
+ .fix p{margin:8px 0 0;font-size:.93rem}
3746
+ .fix .do{background:color-mix(in srgb,var(--accent) 8%,transparent);border-radius:8px;padding:11px 13px;margin-top:10px}
3747
+ ul.warn{list-style:none;padding:0;margin:0}
3748
+ ul.warn li{padding:10px 0;border-bottom:1px solid var(--line);font-size:.92rem}
3749
+ ul.warn li:last-child{border-bottom:0}
3750
+ ul.warn b{font-weight:650}
3751
+ .pill{display:inline-block;font-size:.7rem;padding:2px 8px;border-radius:99px;border:1px solid var(--line);
3752
+ color:var(--ink2);margin-left:8px;vertical-align:1px}
3753
+ .files{display:grid;gap:12px;grid-template-columns:repeat(auto-fit,minmax(250px,1fr))}
3754
+ .file{border:1px solid var(--line);border-radius:10px;padding:15px 16px;background:var(--panel);
3755
+ display:flex;flex-direction:column;gap:6px}
3756
+ .file .nm{font-family:var(--mono);font-size:.86rem;font-weight:650;color:var(--accent)}
3757
+ .file .ds{font-size:.84rem;color:var(--ink2)}
3758
+ .file a{margin-top:auto;font-size:.83rem;color:var(--ink);text-decoration:none;border-bottom:1px solid var(--line);
3759
+ align-self:flex-start;padding-bottom:1px}
3760
+ .file a:hover{border-color:var(--accent)}
3761
+ .cta{background:var(--panel);border:1px solid var(--line);border-left:3px solid var(--good);
3762
+ border-radius:10px;padding:18px 20px}
3763
+ code.cmd{display:block;font-family:var(--mono);font-size:.86rem;background:color-mix(in srgb,var(--ink) 6%,transparent);
3764
+ padding:11px 13px;border-radius:7px;margin-top:10px;overflow-x:auto;white-space:pre}
3765
+ .note{font-size:.82rem;color:var(--ink2);margin-top:10px}
3766
+ footer{margin-top:56px;padding-top:20px;border-top:1px solid var(--line);color:var(--ink2);font-size:.82rem}
3767
+ details summary{cursor:pointer;font-size:.88rem;color:var(--ink2)}
3768
+ details[open] summary{margin-bottom:10px}
3769
+ .cols{columns:2;column-gap:28px;font-size:.86rem;color:var(--ink2)}
3770
+ @media(max-width:640px){.cols{columns:1}}
3771
+ .tabs input{position:absolute;opacity:0;pointer-events:none}
3772
+ .tabs label{display:inline-block;font-size:.85rem;padding:7px 13px;border:1px solid var(--line);
3773
+ border-radius:7px;margin:0 6px 14px 0;cursor:pointer;color:var(--ink2);user-select:none}
3774
+ .tabs label:hover{border-color:var(--accent)}
3775
+ .tabs input:checked + label{background:var(--accent);border-color:var(--accent);color:#fff;font-weight:600}
3776
+ .tabpane{display:none}
3777
+ #t-sections:checked ~ .tabpane[data-for="t-sections"],
3778
+ #t-diff:checked ~ .tabpane[data-for="t-diff"],
3779
+ #t-side:checked ~ .tabpane[data-for="t-side"]{display:block}
3780
+ .tag{font-family:var(--mono);font-size:.72rem;padding:2px 7px;border-radius:5px;white-space:nowrap}
3781
+ .tag.keep{background:color-mix(in srgb,var(--ink2) 16%,transparent);color:var(--ink)}
3782
+ .tag.fill{background:color-mix(in srgb,var(--good) 20%,transparent);color:var(--good)}
3783
+ .tag.repl{background:color-mix(in srgb,var(--warn) 22%,transparent);color:var(--warn)}
3784
+ .tag.drop{background:color-mix(in srgb,var(--bad) 18%,transparent);color:var(--bad)}
3785
+ .tag.hole{background:color-mix(in srgb,var(--accent) 18%,transparent);color:var(--accent)}
3786
+ pre.diff,pre.src{font-family:var(--mono);font-size:.8rem;line-height:1.5;overflow-x:auto;
3787
+ background:color-mix(in srgb,var(--ink) 5%,transparent);padding:14px 16px;border-radius:8px;margin:0}
3788
+ pre.diff .add{color:var(--good);display:block}
3789
+ pre.diff .del{color:var(--bad);display:block}
3790
+ pre.diff .ctx{color:var(--ink2);display:block}
3791
+ .paneh{font-size:.8rem;text-transform:uppercase;letter-spacing:.07em;color:var(--ink2);
3792
+ margin:0 0 8px;font-weight:600}
3793
+ `;
3794
+ var TAG_META = {
3795
+ carried: { cls: "keep", label: "carried" },
3796
+ filled: { cls: "fill", label: "filled" },
3797
+ replaced: { cls: "repl", label: "replaced" },
3798
+ dropped: { cls: "drop", label: "left out" },
3799
+ placeholder: { cls: "hole", label: "placeholder" }
3800
+ };
3801
+ function renderSectionsTable(sections) {
3802
+ const rows = sections.map((s) => {
3803
+ const meta = TAG_META[s.disposition];
3804
+ return `<tr><td>${esc(s.name)}</td><td><span class="tag ${meta.cls}">${meta.label}</span></td><td>${esc(s.why)}</td></tr>`;
3805
+ }).join("");
3806
+ return `<p class="note" style="margin-top:0">Every section of your file and what this run did with it. Nothing was deleted silently: dropped sections are named with a reason.</p><div class="scroll"><table><thead><tr><th>Section</th><th>What happened</th><th>Why</th></tr></thead><tbody>${rows}</tbody></table></div>`;
3807
+ }
3808
+ var DIFF_LCS_LIMIT = 3e3;
3809
+ function diffLines(before, after) {
3810
+ const a = before.split("\n");
3811
+ const b = after.split("\n");
3812
+ const n = a.length;
3813
+ const m = b.length;
3814
+ if (n > DIFF_LCS_LIMIT || m > DIFF_LCS_LIMIT) {
3815
+ const ops2 = [];
3816
+ for (const line of a) ops2.push({ type: "del", text: line });
3817
+ for (const line of b) ops2.push({ type: "add", text: line });
3818
+ return ops2;
3819
+ }
3820
+ const width = m + 1;
3821
+ const dp = new Int32Array((n + 1) * width);
3822
+ for (let i2 = n - 1; i2 >= 0; i2--) {
3823
+ for (let j2 = m - 1; j2 >= 0; j2--) {
3824
+ const ai = a[i2];
3825
+ const bj = b[j2];
3826
+ dp[i2 * width + j2] = ai === bj ? dp[(i2 + 1) * width + (j2 + 1)] + 1 : Math.max(dp[(i2 + 1) * width + j2], dp[i2 * width + (j2 + 1)]);
3827
+ }
3828
+ }
3829
+ const ops = [];
3830
+ let i = 0;
3831
+ let j = 0;
3832
+ while (i < n && j < m) {
3833
+ if (a[i] === b[j]) {
3834
+ ops.push({ type: "ctx", text: a[i] });
3835
+ i++;
3836
+ j++;
3837
+ } else if (dp[(i + 1) * width + j] >= dp[i * width + (j + 1)]) {
3838
+ ops.push({ type: "del", text: a[i] });
3839
+ i++;
3840
+ } else {
3841
+ ops.push({ type: "add", text: b[j] });
3842
+ j++;
3843
+ }
3844
+ }
3845
+ while (i < n) {
3846
+ ops.push({ type: "del", text: a[i] });
3847
+ i++;
3848
+ }
3849
+ while (j < m) {
3850
+ ops.push({ type: "add", text: b[j] });
3851
+ j++;
3852
+ }
3853
+ return ops;
3854
+ }
3855
+ var DIFF_CONTEXT = 2;
3856
+ var DIFF_MAX_LINES = 4e3;
3857
+ function buildHunks(ops) {
3858
+ const keep = new Array(ops.length).fill(false);
3859
+ for (let i = 0; i < ops.length; i++) {
3860
+ if (ops[i].type !== "ctx") {
3861
+ for (let j = Math.max(0, i - DIFF_CONTEXT); j <= Math.min(ops.length - 1, i + DIFF_CONTEXT); j++) {
3862
+ keep[j] = true;
3863
+ }
3864
+ }
3865
+ }
3866
+ const out = [];
3867
+ let lastKept = -2;
3868
+ for (let i = 0; i < ops.length; i++) {
3869
+ if (!keep[i]) continue;
3870
+ if (out.length > 0 && i - lastKept > 1) out.push({ type: "ctx", text: "" });
3871
+ out.push(ops[i]);
3872
+ lastKept = i;
3873
+ }
3874
+ return out;
3875
+ }
3876
+ function renderDiffTab(before, after) {
3877
+ const intro = `<p class="note" style="margin-top:0">Only the regions that differ, with context. A large file is not worth printing twice.</p>`;
3878
+ if (before === null) {
3879
+ return intro + `<p class="note">No existing CLAUDE.md was found, so there is nothing to compare. See Side by side for the new file.</p>`;
3880
+ }
3881
+ const hunks = buildHunks(diffLines(before, after));
3882
+ const truncated = hunks.length > DIFF_MAX_LINES;
3883
+ const shown = truncated ? hunks.slice(0, DIFF_MAX_LINES) : hunks;
3884
+ const body = shown.map((op) => {
3885
+ if (op.type === "ctx") return `<span class="ctx">${esc(op.text)}</span>`;
3886
+ const prefix = op.type === "add" ? "+ " : "- ";
3887
+ return `<span class="${op.type}">${esc(prefix + op.text)}</span>`;
3888
+ }).join("\n");
3889
+ const note = truncated ? `<p class="note">Diff truncated at ${DIFF_MAX_LINES} lines; open the file for the rest.</p>` : "";
3890
+ return `${intro}<pre class="diff">${body}</pre>${note}`;
3891
+ }
3892
+ var SIDE_PANE_CHAR_CAP = 2e4;
3893
+ function renderPane(text2) {
3894
+ const truncated = text2.length > SIDE_PANE_CHAR_CAP;
3895
+ const shown = truncated ? text2.slice(0, SIDE_PANE_CHAR_CAP) : text2;
3896
+ const note = truncated ? `<p class="note">Truncated; open the file for the rest.</p>` : "";
3897
+ return `<pre class="src">${esc(shown)}</pre>${note}`;
3898
+ }
3899
+ function renderSideBySideTab(before, after, tokens) {
3900
+ const afterCol = `<p class="paneh">Optimized <span class="win" style="font-weight:600">${esc(approxTokens(tokens.after))} tokens</span></p>` + renderPane(after);
3901
+ const beforeCol = before === null ? `<p class="paneh">Original</p><p class="note" style="margin-top:0">No existing CLAUDE.md.</p>` : `<p class="paneh">Original <span style="color:var(--ink2);font-weight:400">${esc(approxTokens(tokens.before))} tokens</span></p>` + renderPane(before);
3902
+ return `<div class="grid g2" style="gap:14px"><div>${beforeCol}</div><div>${afterCol}</div></div>`;
3903
+ }
3904
+ function renderComparisonTabs(input) {
3905
+ return `<div class="tabs"><input type="radio" name="cmp" id="t-sections" checked><label for="t-sections">By section</label><input type="radio" name="cmp" id="t-diff"><label for="t-diff">Line changes</label><input type="radio" name="cmp" id="t-side"><label for="t-side">Side by side</label><div class="tabpane" data-for="t-sections">${renderSectionsTable(input.sectionDispositions)}</div><div class="tabpane" data-for="t-diff">${renderDiffTab(input.currentClaudeMd, input.optimizedClaudeMd)}</div><div class="tabpane" data-for="t-side">${renderSideBySideTab(input.currentClaudeMd, input.optimizedClaudeMd, input.claudeMdTokens)}</div></div>`;
3906
+ }
3907
+ function countLines(s) {
3908
+ return s.length === 0 ? 0 : s.split("\n").length;
3909
+ }
3910
+ function renderTokenStat(input) {
3911
+ const { before, after } = input.claudeMdTokens;
3912
+ if (before === null) {
3913
+ return `<div class="stat"><span class="l">CLAUDE.md, every turn</span><span class="v">${esc(approxTokens(after))} tokens</span><span class="d">No existing CLAUDE.md was found, so this is a new file. It is re-read on every turn of every session, so its size sets a fixed cost per turn.</span></div>`;
3914
+ }
3915
+ const delta = after - before;
3916
+ const saved = delta < 0;
3917
+ const pct2 = before > 0 ? delta / before * 100 : 0;
3918
+ const deltaText = `${delta >= 0 ? "+" : ""}${fmtTokens(delta)} tokens`;
3919
+ const pctText = `${pct2 >= 0 ? "+" : ""}${pct2.toFixed(1)}%`;
3920
+ return `<div class="stat"><span class="l">CLAUDE.md, every turn</span><span class="v${saved ? " win" : ""}">${esc(deltaText)}</span><span class="d">${esc(approxTokens(before))} &rarr; ${esc(approxTokens(after))} tokens (${esc(pctText)}). This file is re-read on every turn of every session, so the ${saved ? "saving" : "change"} repeats.</span></div>`;
3921
+ }
3922
+ function renderSectionsStat(sections) {
3923
+ const counts = { carried: 0, filled: 0, replaced: 0, dropped: 0, placeholder: 0 };
3924
+ for (const s of sections) counts[s.disposition]++;
3925
+ const total = sections.length;
3926
+ const headline = counts.carried > 0 ? `${counts.carried} carried` : `${total} ${plural2(total, "section")}`;
3927
+ const rest = [];
3928
+ if (counts.replaced > 0) rest.push(`${counts.replaced} replaced from the scan`);
3929
+ if (counts.dropped > 0) rest.push(`${counts.dropped} volatile ${plural2(counts.dropped, "section")} dropped`);
3930
+ if (counts.filled > 0) rest.push(`${counts.filled} filled from your project`);
3931
+ if (counts.placeholder > 0) rest.push(`${counts.placeholder} left as ${counts.placeholder === 1 ? "a placeholder" : "placeholders"}`);
3932
+ const restText = rest.length > 0 ? rest.join(", ") + "." : "Nothing else to report.";
3933
+ return `<div class="stat"><span class="l">Sections handled</span><span class="v">${esc(headline)}</span><span class="d">${esc(restText)}</span></div>`;
3934
+ }
3935
+ function renderRecoverableStat(input) {
3936
+ const pct2 = `${(input.headlineWasteShare * 100).toFixed(1)}%`;
3937
+ return `<div class="stat"><span class="l">Recoverable usage</span><span class="v">${esc(pct2)}</span><span class="d">of analyzed usage, about ${esc(usd5(input.headlineWasteUsd))} at API rates. On a subscription that is rate-limit headroom, not money back.</span></div>`;
3938
+ }
3939
+ function renderReceipt(input) {
3940
+ const stats = `<div class="grid g3">${renderTokenStat(input)}${renderSectionsStat(input.sectionDispositions)}${renderRecoverableStat(input)}</div>`;
3941
+ const { before, after } = input.claudeMdTokens;
3942
+ let bar2 = "";
3943
+ if (before !== null && after < before) {
3944
+ const cutPct = Math.max(0, Math.min(100, after / before * 100));
3945
+ const savedTokens = before - after;
3946
+ bar2 = `<div style="margin-top:22px"><div class="bar"><div class="cut" style="inset:0 0 0 ${cutPct.toFixed(1)}%"></div></div><div class="barlabels"><span>optimized ${esc(approxTokens(after))} tokens</span><span>saved ${esc(fmtTokens(savedTokens))}</span></div></div>`;
3947
+ const lineDelta = countLines(input.optimizedClaudeMd) - countLines(input.currentClaudeMd ?? "");
3948
+ if (lineDelta !== 0) {
3949
+ bar2 += `<p class="note">Line count ${lineDelta > 0 ? "went up" : "went down"} by ${Math.abs(lineDelta)} while tokens went down by ${esc(fmtTokens(savedTokens))}. Tokens are what the cache charges for, so tokens are what is reported here.</p>`;
3950
+ }
3951
+ }
3952
+ return `<div class="panel">${stats}${bar2}</div>`;
3953
+ }
3954
+ var CACHE_TABLE_FLOOR2 = 1;
3955
+ var CACHE_TABLE_CAP2 = 10;
3956
+ function renderCacheTable2(report) {
3957
+ const all = cacheMissByProject(report);
3958
+ const shown = all.filter((r) => r.usd >= CACHE_TABLE_FLOOR2).slice(0, CACHE_TABLE_CAP2);
3959
+ if (shown.length === 0) return "";
3960
+ const shownSlugs = new Set(shown.map((r) => r.slug));
3961
+ const tail = all.filter((r) => !shownSlugs.has(r.slug));
3962
+ const rows = shown.map(
3963
+ (r) => `<tr><td>${esc(r.slug)}</td><td class="num">${esc(usd5(r.usd))}</td><td class="num">${Math.round(r.cacheHitRate * 100)}%</td><td class="num">${r.sessionsCount}</td></tr>`
3964
+ ).join("");
3965
+ let tailRow = "";
3966
+ if (tail.length > 0) {
3967
+ const tailUsd = tail.reduce((sum, r) => sum + r.usd, 0);
3968
+ tailRow = `<tr><td colspan="4" style="color:var(--ink2)">${tail.length} smaller ${plural2(tail.length, "project")} account${tail.length === 1 ? "s" : ""} for the remaining ${esc(usd5(tailUsd))}.</td></tr>`;
3969
+ }
3970
+ return `<h4 style="margin:20px 0 8px;font-size:.9rem">Where that money is</h4><div class="scroll"><table><thead><tr><th>Project</th><th class="num">Recoverable</th><th class="num">Cache hit</th><th class="num">Main sessions</th></tr></thead><tbody>${rows}${tailRow}</tbody></table></div><p class="note"><b>Why a high hit rate can still leave money on the table:</b> the exposure counts cache writes, not just misses. A project can read its prefix from cache almost every turn and still rebuild that prefix often. This figure is an upper bound on what tighter session starts could recover.</p>`;
3971
+ }
3972
+ function renderFixes(fixes, report) {
3973
+ const dollarFixes = fixes.filter((f) => f.wasteUsd > 0).sort((a, b) => b.wasteUsd - a.wasteUsd);
3974
+ if (dollarFixes.length === 0) return `<p class="note">No directly recoverable dollars found.</p>`;
3975
+ return dollarFixes.map((f, i) => {
3976
+ const table = f.id === "cache_recovery" ? renderCacheTable2(report) : "";
3977
+ return `<div class="fix"><h3>${i + 1}. ${esc(f.title)} <span class="amt">${esc(usd5(f.wasteUsd))}</span></h3><p>${esc(f.problem)}</p><div class="do"><b>Do this:</b> ${esc(f.action)}</div>${table}</div>`;
3978
+ }).join("");
3979
+ }
3980
+ function toolWarnings(report) {
3981
+ const out = [];
3982
+ for (const f of report.findings) {
3983
+ const sessions = f.evidence?.["sessionsAffected"];
3984
+ const tool = f.evidence?.["tool"];
3985
+ if (typeof sessions === "number" && typeof tool === "string") {
3986
+ out.push({ title: f.title, sessions, tool, action: f.suggestedAction });
3987
+ }
3988
+ }
3989
+ return out.sort((a, b) => b.sessions - a.sessions);
3990
+ }
3991
+ function renderSetupWarnings(fixes, report) {
3992
+ const warnFixes = fixes.filter((f) => f.wasteUsd <= 0);
3993
+ const tool = toolWarnings(report);
3994
+ const multi = tool.filter((t) => t.sessions > 1);
3995
+ const single = tool.filter((t) => t.sessions === 1);
3996
+ const items = [];
3997
+ for (const f of warnFixes) {
3998
+ items.push(`<li><b>${esc(f.title)}.</b> ${esc(f.action)} <span class="pill">measured</span></li>`);
3999
+ }
4000
+ for (const t of multi) {
4001
+ const sentence = t.action ? ` ${esc(t.action)}` : "";
4002
+ items.push(
4003
+ `<li><b>${esc(t.title)}.</b>${sentence} <span class="pill">${t.sessions} ${plural2(t.sessions, "session")}</span></li>`
4004
+ );
4005
+ }
4006
+ const list = items.length > 0 ? `<ul class="warn">${items.join("")}</ul>` : `<p class="note">No setup warnings found.</p>`;
4007
+ let disclosure = "";
4008
+ if (single.length > 0) {
4009
+ const names = [...new Set(single.map((t) => t.tool))].map(esc).join(", ");
4010
+ disclosure = `<details style="margin-top:14px"><summary>${single.length} ${plural2(single.length, "finding")} seen in a single session each (${names})</summary><p class="note" style="margin:0">One session is not yet a pattern. These are listed for completeness and are not worth acting on until they repeat.</p></details>`;
4011
+ }
4012
+ return `<div class="panel">${list}${disclosure}</div>`;
4013
+ }
4014
+ var OPTIMIZED_NAME = "CLAUDE.optimized.md";
4015
+ var PLAYBOOK_NAME = "PLAYBOOK.md";
4016
+ var SETTINGS_NAME = "settings.suggested.json";
4017
+ var HARNESS_NAME = "HARNESS-UPGRADE.md";
4018
+ function renderArtifactCards(input) {
4019
+ const { before, after } = input.claudeMdTokens;
4020
+ const lighter = before !== null && after < before ? ` and ${fmtTokens(before - after)} tokens lighter` : "";
4021
+ const placeholders = `${input.placeholdersRemaining} ${plural2(input.placeholdersRemaining, "placeholder")} to fill.`;
4022
+ const claudeDesc = before === null ? `A new CLAUDE.md scaffold for your project. ${placeholders}` : `Your CLAUDE.md, restructured${lighter}. ${placeholders}`;
4023
+ const card = (name, desc) => `<div class="file"><span class="nm">${esc(name)}</span><span class="ds">${esc(desc)}</span><a href="${esc(name)}">Open file</a></div>`;
4024
+ return `<div class="files">` + card(OPTIMIZED_NAME, claudeDesc) + card(PLAYBOOK_NAME, "The ranked plan above, as a file you can keep or paste into an issue.") + card(SETTINGS_NAME, "A conservative permission allowlist derived from what you already run. Never applied unless you ask.") + card(HARNESS_NAME, "A work order for your own Claude Code. It merges the CLAUDE.md and applies what you approve.") + `</div>`;
4025
+ }
4026
+ function renderApplyCta(input) {
4027
+ return `<div class="cta"><b>Hand the work order to your own Claude Code.</b> It merges the optimized CLAUDE.md (your facts win, the optimized structure wins), applies the permissions you approve, and fixes the harness-level findings above.<code class="cmd">claude "Follow ${esc(input.artifactsDir)}/${HARNESS_NAME}"</code><p class="note">CostClaw itself never calls a model. That is the privacy line: every number on this page came from logs already on your disk.</p></div>`;
4028
+ }
4029
+ function renderCarriedDisclosure(sections) {
4030
+ const carried = sections.filter((s) => s.disposition === "carried");
4031
+ if (carried.length === 0) return "";
4032
+ const names = carried.map((s) => esc(s.name)).join(" &middot; ");
4033
+ return `<details style="margin-top:34px"><summary>All ${carried.length} ${plural2(carried.length, "section")} carried across from your existing CLAUDE.md</summary><div class="cols">${names}</div></details>`;
4034
+ }
4035
+ function renderHeader(input) {
4036
+ const parts = [];
4037
+ const stack = input.stack.map((s) => s.trim()).filter((s) => s.length > 0);
4038
+ if (stack.length > 0) parts.push(esc(stack.join(", ")));
4039
+ parts.push(`${input.commandsCount} ${plural2(input.commandsCount, "command")} detected`);
4040
+ parts.push(`4 artifacts written to ${esc(input.artifactsDir)}/`);
4041
+ return `<header><p class="kicker">CostClaw optimize &middot; dry run &middot; nothing left your machine</p><h1>${esc(input.projectName)}</h1><p class="sub">${parts.join(" &middot; ")}</p></header>`;
4042
+ }
4043
+ function renderOptimizeDashboard(input) {
4044
+ return `<!doctype html>
4045
+ <html lang="en">
4046
+ <head>
4047
+ <meta charset="utf-8">
4048
+ <meta name="viewport" content="width=device-width,initial-scale=1">
4049
+ <title>CostClaw optimize: ${esc(input.projectName)}</title>
4050
+ <style>${STYLE2}</style>
4051
+ </head>
4052
+ <body>
4053
+ <div class="wrap">
4054
+ ${renderHeader(input)}
4055
+
4056
+ <h2>What this run changed<span class="n">the receipt</span></h2>
4057
+ ${renderReceipt(input)}
4058
+
4059
+ <h2>Your CLAUDE.md, before and after<span class="n">what actually changed</span></h2>
4060
+ <div class="panel">${renderComparisonTabs(input)}</div>
4061
+
4062
+ <h2>Fixes, ranked by what they recover</h2>
4063
+ ${renderFixes(input.fixes, input.report)}
4064
+
4065
+ <h2>Setup warnings<span class="n">no direct dollar figure, still costly</span></h2>
4066
+ ${renderSetupWarnings(input.fixes, input.report)}
4067
+
4068
+ <h2>Your four artifacts</h2>
4069
+ ${renderArtifactCards(input)}
4070
+
4071
+ <h2>Apply it</h2>
4072
+ ${renderApplyCta(input)}
4073
+
4074
+ ${renderCarriedDisclosure(input.sectionDispositions)}
4075
+
4076
+ <footer>Generated locally by CostClaw v${esc(input.version)}. Dry run: none of your files were changed.
4077
+ No network calls, no telemetry, no model calls.</footer>
4078
+
4079
+ </div>
4080
+ </body>
4081
+ </html>
4082
+ `;
4083
+ }
4084
+
3371
4085
  // src/project-scan.ts
3372
4086
  import { readdir as readdir3, readFile as readFile4, stat } from "fs/promises";
3373
4087
  import { join as join5, basename } from "path";
@@ -3890,11 +4604,12 @@ async function scanProject(dir) {
3890
4604
  }
3891
4605
 
3892
4606
  // src/optimize-command.ts
3893
- var OPTIMIZED_NAME = "CLAUDE.optimized.md";
3894
- var PLAYBOOK_NAME = "PLAYBOOK.md";
3895
- var SETTINGS_NAME = "settings.suggested.json";
3896
- var HARNESS_NAME = "HARNESS-UPGRADE.md";
3897
- function usd5(n) {
4607
+ var OPTIMIZED_NAME2 = "CLAUDE.optimized.md";
4608
+ var PLAYBOOK_NAME2 = "PLAYBOOK.md";
4609
+ var SETTINGS_NAME2 = "settings.suggested.json";
4610
+ var HARNESS_NAME2 = "HARNESS-UPGRADE.md";
4611
+ var DASHBOARD_NAME = "DASHBOARD.html";
4612
+ function usd6(n) {
3898
4613
  return `$${(Math.round(n * 100) / 100).toFixed(2)}`;
3899
4614
  }
3900
4615
  function describeDetection(project) {
@@ -3904,6 +4619,16 @@ function describeDetection(project) {
3904
4619
  const stack = project.stack.length > 0 ? project.stack.join(", ") : "no stack detected";
3905
4620
  return `Detected: ${name}, ${cmds}, ${stack}`;
3906
4621
  }
4622
+ function looksUnscanned(project) {
4623
+ return project.stack.length === 0 && project.commands.length === 0;
4624
+ }
4625
+ function unscannedWarning(projectDir) {
4626
+ return [
4627
+ `Warning: the scan found no stack and no commands in ${projectDir}.`,
4628
+ "Are you in the right folder? optimize fills the scaffold from a project's own files,",
4629
+ "so run it from inside a project, or point it at one with --project <dir>."
4630
+ ];
4631
+ }
3907
4632
  async function pathExists(p) {
3908
4633
  try {
3909
4634
  await stat2(p);
@@ -4028,15 +4753,42 @@ async function runOptimize(opts) {
4028
4753
  });
4029
4754
  const outDir = opts.out || join6(process.cwd(), "costclaw-out");
4030
4755
  await mkdir3(outDir, { recursive: true });
4031
- const playbookPath = join6(outDir, PLAYBOOK_NAME);
4756
+ const playbookPath = join6(outDir, PLAYBOOK_NAME2);
4032
4757
  await writeFile3(playbookPath, result.playbook, "utf8");
4033
- const settingsPath = join6(outDir, SETTINGS_NAME);
4758
+ const settingsPath = join6(outDir, SETTINGS_NAME2);
4034
4759
  await writeFile3(settingsPath, result.settingsJson, "utf8");
4035
- const harnessPath = join6(outDir, HARNESS_NAME);
4760
+ const harnessPath = join6(outDir, HARNESS_NAME2);
4036
4761
  await writeFile3(harnessPath, result.harnessPrompt, "utf8");
4762
+ const wantDashboard = opts.dashboard !== false;
4763
+ let dashboardPath = null;
4764
+ if (wantDashboard) {
4765
+ const spend = report.summary.cost_usd;
4766
+ const html = renderOptimizeDashboard({
4767
+ version: opts.version ?? "",
4768
+ projectName: project.name ?? "your project",
4769
+ stack: project.stack,
4770
+ commandsCount: project.commands.length,
4771
+ artifactsDir: outDir,
4772
+ currentClaudeMd: claudeMd ?? null,
4773
+ optimizedClaudeMd: result.optimizedClaudeMd,
4774
+ claudeMdTokens: result.claudeMdTokens,
4775
+ sectionDispositions: result.sectionDispositions,
4776
+ placeholdersRemaining: result.placeholdersRemaining,
4777
+ fixes,
4778
+ report,
4779
+ headlineWasteShare: spend > 0 ? recoverable / spend : 0,
4780
+ headlineWasteUsd: recoverable
4781
+ });
4782
+ dashboardPath = join6(outDir, DASHBOARD_NAME);
4783
+ await writeFile3(dashboardPath, html, "utf8");
4784
+ }
4037
4785
  const lines = [];
4038
4786
  lines.push("CostClaw optimize");
4039
4787
  lines.push("");
4788
+ if (looksUnscanned(project)) {
4789
+ lines.push(...unscannedWarning(projectDir));
4790
+ lines.push("");
4791
+ }
4040
4792
  if (opts.write) {
4041
4793
  const target = opts.write;
4042
4794
  const backup = `${target}.bak`;
@@ -4065,7 +4817,7 @@ async function runOptimize(opts) {
4065
4817
  }
4066
4818
  lines.push("A suggested settings.json was written to the out dir for review; it is not applied in place.");
4067
4819
  } else {
4068
- const optimizedPath = join6(outDir, OPTIMIZED_NAME);
4820
+ const optimizedPath = join6(outDir, OPTIMIZED_NAME2);
4069
4821
  await writeFile3(optimizedPath, result.optimizedClaudeMd, "utf8");
4070
4822
  lines.push("Dry run (no files of yours were changed).");
4071
4823
  lines.push(`Wrote the optimized CLAUDE.md scaffold to ${optimizedPath}`);
@@ -4076,12 +4828,20 @@ async function runOptimize(opts) {
4076
4828
  lines.push(describeDetection(project));
4077
4829
  if (claudeMdSource) lines.push(`Existing CLAUDE.md: ${claudeMdSource}`);
4078
4830
  if (plan === "api") {
4079
- lines.push(`Recoverable spend (cache-miss exposure): ${usd5(recoverable)}`);
4831
+ lines.push(`Recoverable spend (cache-miss exposure): ${usd6(recoverable)}`);
4080
4832
  } else {
4081
4833
  const spend = report.summary.cost_usd;
4082
4834
  const share = spend > 0 ? recoverable / spend * 100 : 0;
4083
4835
  lines.push(
4084
- `Recoverable usage (cache-miss exposure): ${share.toFixed(1)}% of analyzed usage (${usd5(recoverable)} at API rates)`
4836
+ `Recoverable usage (cache-miss exposure): ${share.toFixed(1)}% of analyzed usage (${usd6(recoverable)} at API rates)`
4837
+ );
4838
+ }
4839
+ const { before, after } = result.claudeMdTokens;
4840
+ if (before != null && before !== after) {
4841
+ const pct2 = before > 0 ? (Math.abs(after - before) / before * 100).toFixed(1) : "0.0";
4842
+ const dir = after > before ? "larger" : "smaller";
4843
+ lines.push(
4844
+ `Your CLAUDE.md: an estimated ${before.toLocaleString()} tokens to ${after.toLocaleString()} (${pct2}% ${dir}), paid on every turn.`
4085
4845
  );
4086
4846
  }
4087
4847
  lines.push("");
@@ -4115,6 +4875,12 @@ async function runOptimize(opts) {
4115
4875
  lines.push("");
4116
4876
  lines.push("Baseline recorded: your next audits will show cache-hit progress since this optimize.");
4117
4877
  lines.push("Nothing left your machine.");
4878
+ if (dashboardPath) {
4879
+ lines.push("");
4880
+ lines.push(`Opening the summary dashboard: ${dashboardPath}`);
4881
+ lines.push("It browses all of this in one page, including a before and after of your CLAUDE.md. Pass --no-dashboard to skip it.");
4882
+ openInBrowser(dashboardPath);
4883
+ }
4118
4884
  return { output: lines.join("\n") };
4119
4885
  }
4120
4886
 
@@ -4155,11 +4921,11 @@ import { join as join7 } from "path";
4155
4921
  import { homedir as homedir5 } from "os";
4156
4922
 
4157
4923
  // src/format-diff.ts
4158
- function usd6(n) {
4924
+ function usd7(n) {
4159
4925
  return `$${(Math.round(Math.abs(n) * 100) / 100).toFixed(2)}`;
4160
4926
  }
4161
4927
  function signedUsd(n) {
4162
- return `${n < 0 ? "-" : "+"}${usd6(n)}`;
4928
+ return `${n < 0 ? "-" : "+"}${usd7(n)}`;
4163
4929
  }
4164
4930
  function signedInt(n) {
4165
4931
  return n > 0 ? `+${n}` : `${n}`;
@@ -4180,23 +4946,23 @@ function formatDiff(d) {
4180
4946
  if (d.comparable && d.marginal) {
4181
4947
  lines.push("Since the baseline:");
4182
4948
  lines.push(
4183
- ` New spend ${usd6(d.marginal.newSpendUsd)} across ${d.marginal.newSessions} new sessions`
4949
+ ` New spend ${usd7(d.marginal.newSpendUsd)} across ${d.marginal.newSessions} new sessions`
4184
4950
  );
4185
4951
  lines.push(
4186
4952
  ` Marginal cache hit ${pct(d.marginal.marginalCacheHitRate)} (lifetime ${pct(d.current.cacheHitRate)})`
4187
4953
  );
4188
4954
  lines.push(
4189
- ` Recoverable exposure ${signedUsd(d.deltas.recoverableUsd)} (now ${usd6(d.current.recoverableUsd)})`
4955
+ ` Recoverable exposure ${signedUsd(d.deltas.recoverableUsd)} (now ${usd7(d.current.recoverableUsd)})`
4190
4956
  );
4191
4957
  } else {
4192
4958
  lines.push("Note: the current audit covers less history than the baseline (logs moved or");
4193
4959
  lines.push("pruned), so period metrics are omitted.");
4194
4960
  lines.push("");
4195
4961
  lines.push(
4196
- `Baseline (${day(d.baseline.createdAt)}): spend ${usd6(d.baseline.spendUsd)}, cache hit ${pct(d.baseline.cacheHitRate)}, recoverable ${usd6(d.baseline.recoverableUsd)}`
4962
+ `Baseline (${day(d.baseline.createdAt)}): spend ${usd7(d.baseline.spendUsd)}, cache hit ${pct(d.baseline.cacheHitRate)}, recoverable ${usd7(d.baseline.recoverableUsd)}`
4197
4963
  );
4198
4964
  lines.push(
4199
- `Current (${day(d.current.createdAt)}): spend ${usd6(d.current.spendUsd)}, cache hit ${pct(d.current.cacheHitRate)}, recoverable ${usd6(d.current.recoverableUsd)}`
4965
+ `Current (${day(d.current.createdAt)}): spend ${usd7(d.current.spendUsd)}, cache hit ${pct(d.current.cacheHitRate)}, recoverable ${usd7(d.current.recoverableUsd)}`
4200
4966
  );
4201
4967
  }
4202
4968
  lines.push("");
@@ -4219,18 +4985,18 @@ function formatDiff(d) {
4219
4985
  if (resolved.length > 0) {
4220
4986
  lines.push("");
4221
4987
  lines.push("Fixes resolved since the baseline:");
4222
- for (const f of resolved) lines.push(` - [${usd6(f.wasteUsd)}] ${f.title}`);
4988
+ for (const f of resolved) lines.push(` - [${usd7(f.wasteUsd)}] ${f.title}`);
4223
4989
  }
4224
4990
  if (appeared.length > 0) {
4225
4991
  lines.push("");
4226
4992
  lines.push("New since the baseline:");
4227
- for (const f of appeared) lines.push(` - [${usd6(f.wasteUsd)}] ${f.title}`);
4993
+ for (const f of appeared) lines.push(` - [${usd7(f.wasteUsd)}] ${f.title}`);
4228
4994
  }
4229
4995
  if (changed.length > 0) {
4230
4996
  lines.push("");
4231
4997
  lines.push("Fixes that moved:");
4232
4998
  for (const c of changed) {
4233
- lines.push(` - ${c.title}: ${usd6(c.beforeUsd)} -> ${usd6(c.afterUsd)} (${signedUsd(c.deltaUsd)})`);
4999
+ lines.push(` - ${c.title}: ${usd7(c.beforeUsd)} -> ${usd7(c.afterUsd)} (${signedUsd(c.deltaUsd)})`);
4234
5000
  }
4235
5001
  }
4236
5002
  return lines.join("\n");
@@ -4441,7 +5207,12 @@ function parseBadgeFlags(args) {
4441
5207
  };
4442
5208
  }
4443
5209
  function cliVersion() {
4444
- return true ? "0.5.8" : "0.0.0-dev";
5210
+ return true ? "0.7.0" : "0.0.0-dev";
5211
+ }
5212
+ function isHelpRequest(command, args) {
5213
+ if (command === void 0) return false;
5214
+ if (command === "help" || command === "--help" || command === "-h") return true;
5215
+ return args.includes("--help") || args.includes("-h");
4445
5216
  }
4446
5217
  function helpText() {
4447
5218
  return [
@@ -4451,10 +5222,11 @@ function helpText() {
4451
5222
  " costclaw audit [--path <dir>] [--claude-md <file>] [--plan <plan>] [--json] [--html [file]] [--no-html] [--card [file]]",
4452
5223
  " costclaw diff [<baseline.json> <current.json>] [--json]",
4453
5224
  " costclaw badge [--path <dir>] [--claude-md <file>] [--out <file>]",
4454
- " costclaw optimize [--path <dir>] [--claude-md <file>] [--project <dir>] [--out <dir>] [--write <file>] [--apply-settings [file]] [--force]",
5225
+ " costclaw optimize [--path <dir>] [--claude-md <file>] [--project <dir>] [--out <dir>] [--write <file>] [--apply-settings [file]] [--no-dashboard] [--force]",
4455
5226
  " costclaw activate <license-key> [--name <machine-name>]",
4456
5227
  " costclaw deactivate",
4457
5228
  " costclaw --version",
5229
+ " costclaw --help (or --help on any command above)",
4458
5230
  "",
4459
5231
  "audit reads your Claude Code logs from ~/.claude/projects (or --path) on this",
4460
5232
  "machine and prints a cost report plus a six-pillar setup score. It is free.",
@@ -4489,6 +5261,8 @@ function helpText() {
4489
5261
  "--apply-settings [file] additively merges the derived permission allowlist into",
4490
5262
  "the project's .claude/settings.json (or [file]); it only touches",
4491
5263
  "permissions.allow and permissions.deny, backs up the original, and prints a diff.",
5264
+ "It also writes DASHBOARD.html and opens it: one page that browses every artifact,",
5265
+ "the ranked fixes, and a before and after of your CLAUDE.md. --no-dashboard skips it.",
4492
5266
  "optimize needs a one-time license: buy at https://costclaw.io, then run",
4493
5267
  "costclaw activate <key>. activate and deactivate move that license between",
4494
5268
  "machines. audit never needs a license.",
@@ -4504,6 +5278,10 @@ async function main() {
4504
5278
  process.stdout.write(cliVersion() + "\n");
4505
5279
  return;
4506
5280
  }
5281
+ if (isHelpRequest(command, args)) {
5282
+ process.stdout.write(helpText() + "\n");
5283
+ return;
5284
+ }
4507
5285
  if (command === "audit") {
4508
5286
  const { output } = await runAudit(parseAuditFlags(args));
4509
5287
  process.stdout.write(output + "\n");
@@ -4558,6 +5336,8 @@ Run: costclaw optimize
4558
5336
  out: getFlag(args, "--out"),
4559
5337
  write: getFlag(args, "--write"),
4560
5338
  force: args.includes("--force"),
5339
+ dashboard: !args.includes("--no-dashboard"),
5340
+ version: cliVersion(),
4561
5341
  applySettings: args.includes("--apply-settings"),
4562
5342
  applySettingsPath: args.includes("--apply-settings") ? optionalPathAfter(args, "--apply-settings") : void 0
4563
5343
  });
@@ -4577,6 +5357,7 @@ if (isEntryPoint) {
4577
5357
  export {
4578
5358
  cliVersion,
4579
5359
  helpText,
5360
+ isHelpRequest,
4580
5361
  parseAuditFlags,
4581
5362
  parseBadgeFlags,
4582
5363
  planFlag