costclaw 0.6.0 → 0.8.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 -3
  2. package/dist/index.js +711 -74
  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;
@@ -687,20 +687,20 @@ function cacheMissExposureUsd(report) {
687
687
  function cacheMissByProject(report) {
688
688
  const out = [];
689
689
  for (const proj of report.projects) {
690
- let usd7 = 0;
690
+ let usd8 = 0;
691
691
  let sessionsCount = 0;
692
692
  const mainTotals = emptyTotals();
693
693
  for (const s of proj.sessions) {
694
694
  if (s.kind !== "main") continue;
695
695
  sessionsCount += 1;
696
696
  const p = priceFor(s.modelPrimary);
697
- usd7 += (s.totals.input_tokens + s.totals.cache_creation_tokens) * (p.input - p.cache_read) / 1e6;
697
+ usd8 += (s.totals.input_tokens + s.totals.cache_creation_tokens) * (p.input - p.cache_read) / 1e6;
698
698
  mainTotals.input_tokens += s.totals.input_tokens;
699
699
  mainTotals.output_tokens += s.totals.output_tokens;
700
700
  mainTotals.cache_creation_tokens += s.totals.cache_creation_tokens;
701
701
  mainTotals.cache_read_tokens += s.totals.cache_read_tokens;
702
702
  }
703
- out.push({ slug: proj.slug, usd: usd7, cacheHitRate: cacheHitRate(mainTotals), sessionsCount });
703
+ out.push({ slug: proj.slug, usd: usd8, cacheHitRate: cacheHitRate(mainTotals), sessionsCount });
704
704
  }
705
705
  return out.sort((a, b) => b.usd - a.usd);
706
706
  }
@@ -1256,14 +1256,18 @@ var CHECK_FIX = {
1256
1256
  action: "Use a cheaper model for routine edits and reserve the top model for the hard reasoning. Same work, lower bill."
1257
1257
  }
1258
1258
  };
1259
+ var HEAVY_TOOL_PATTERN_MIN_SESSIONS = 2;
1259
1260
  function severityRank(s) {
1260
1261
  return s === "critical" ? 3 : s === "warn" ? 2 : 1;
1261
1262
  }
1263
+ function num2(n) {
1264
+ return String(Math.round(n)).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
1265
+ }
1262
1266
  function sizeFix(cmd) {
1263
1267
  if (cmd.chars > 6e3) {
1264
1268
  return {
1265
1269
  title: "Trim your CLAUDE.md",
1266
- 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."
1270
+ action: `Your CLAUDE.md is an estimated ${num2(cmd.estTokens)} tokens (${num2(cmd.chars)} 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.`
1267
1271
  };
1268
1272
  }
1269
1273
  return {
@@ -1280,7 +1284,7 @@ function synthesize(report, pillars, cmd, plan = "api") {
1280
1284
  const fixes = [];
1281
1285
  const covered = /* @__PURE__ */ new Set();
1282
1286
  const round23 = (n) => Math.round(n * 100) / 100;
1283
- const usd7 = (n) => {
1287
+ const usd8 = (n) => {
1284
1288
  const fixed = round23(n).toFixed(2);
1285
1289
  const dot = fixed.indexOf(".");
1286
1290
  const whole = fixed.slice(0, dot).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
@@ -1366,7 +1370,7 @@ function synthesize(report, pillars, cmd, plan = "api") {
1366
1370
  severity: sevForUsd(exposure),
1367
1371
  wasteUsd: round23(exposure),
1368
1372
  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"}.`
1373
+ `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"}.`
1370
1374
  ),
1371
1375
  action: sanitizeText(action),
1372
1376
  basis: sanitizeText("Cache-miss exposure summed across projects at the published input minus cache-read delta. Upper bound on recoverable spend.")
@@ -1375,8 +1379,13 @@ function synthesize(report, pillars, cmd, plan = "api") {
1375
1379
  covered.add("cache_churn");
1376
1380
  covered.add("recoverable_exposure");
1377
1381
  }
1382
+ const singleSessionTools = [];
1378
1383
  for (const [tool, e] of heavyByTool) {
1379
1384
  const n = Math.max(e.sessionsAffected, 1);
1385
+ if (n < HEAVY_TOOL_PATTERN_MIN_SESSIONS) {
1386
+ singleSessionTools.push([tool, e]);
1387
+ continue;
1388
+ }
1380
1389
  fixes.push({
1381
1390
  id: `heavy_tool_${tool}`,
1382
1391
  title: `Heavy ${tool} usage in ${n} ${sWord(n)}`,
@@ -1389,6 +1398,21 @@ function synthesize(report, pillars, cmd, plan = "api") {
1389
1398
  basis: sanitizeText("Aggregated from per-session tool-use counts over the heavy-loop threshold.")
1390
1399
  });
1391
1400
  }
1401
+ if (singleSessionTools.length > 0) {
1402
+ const named = singleSessionTools.map(([tool, e]) => `${tool} (${e.maxFires}+ fires, 1 session)`);
1403
+ const k = singleSessionTools.length;
1404
+ fixes.push({
1405
+ id: "heavy_tool_single_session",
1406
+ title: `${k} more tool${k === 1 ? "" : "s"} flagged in a single session`,
1407
+ pillar: "prompting",
1408
+ pillarName: PILLARS.prompting.name,
1409
+ severity: "info",
1410
+ wasteUsd: 0,
1411
+ 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.`),
1412
+ action: sanitizeText("Worth a look if it recurs across more sessions; not yet a repeating pattern to fix."),
1413
+ basis: sanitizeText("Aggregated from per-session tool-use counts over the heavy-loop threshold; grouped because each tool affected only one session.")
1414
+ });
1415
+ }
1392
1416
  if (shortCount > 0) {
1393
1417
  fixes.push({
1394
1418
  id: "short_sessions",
@@ -1411,7 +1435,7 @@ function synthesize(report, pillars, cmd, plan = "api") {
1411
1435
  pillarName: PILLARS.cost_discipline.name,
1412
1436
  severity: sevForUsd(misrouteUsd),
1413
1437
  wasteUsd: round23(misrouteUsd),
1414
- 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.`),
1438
+ 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.`),
1415
1439
  action: sanitizeText("Route short, simple sessions to a cheaper model such as Sonnet, and reserve premium models for hard reasoning."),
1416
1440
  basis: sanitizeText("Premium session cost minus the same tokens re-priced at the Sonnet rate, summed over sessions that pass a conservative triviality gate.")
1417
1441
  });
@@ -1425,7 +1449,7 @@ function synthesize(report, pillars, cmd, plan = "api") {
1425
1449
  pillarName: PILLARS.session_mgmt.name,
1426
1450
  severity: sevForUsd(marathonUsd),
1427
1451
  wasteUsd: round23(marathonUsd),
1428
- 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.`),
1452
+ 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.`),
1429
1453
  action: sanitizeText("Compact or start a fresh session between tasks so the context stays small and the cache keeps working."),
1430
1454
  basis: sanitizeText("Recoverable estimate from the late-session cache shortfall versus the early-session hit rate.")
1431
1455
  });
@@ -1438,7 +1462,7 @@ function synthesize(report, pillars, cmd, plan = "api") {
1438
1462
  pillarName: PILLARS.cost_discipline.name,
1439
1463
  severity: "info",
1440
1464
  wasteUsd: 0,
1441
- problem: sanitizeText(`Workflow and subagent runs cost about ${usd7(workflowUsd)}; they are a power tool that can quietly dominate spend.`),
1465
+ problem: sanitizeText(`Workflow and subagent runs cost about ${usd8(workflowUsd)}; they are a power tool that can quietly dominate spend.`),
1442
1466
  action: sanitizeText("Scope workflows to genuinely large tasks and budget the agent count; a single high-effort prompt often suffices."),
1443
1467
  basis: sanitizeText("Summed cost of delegated subagent and workflow sub-logs.")
1444
1468
  });
@@ -1511,20 +1535,20 @@ function computeWindowStats(report) {
1511
1535
  }
1512
1536
  const windows = [];
1513
1537
  let windowStart = -Infinity;
1514
- for (const [t, usd7] of buckets) {
1538
+ for (const [t, usd8] of buckets) {
1515
1539
  if (t >= windowStart + WINDOW_BUCKETS) {
1516
1540
  windows.push({ usd: 0, activeMinutes: 0 });
1517
1541
  windowStart = t;
1518
1542
  }
1519
1543
  const w = windows[windows.length - 1];
1520
- w.usd += usd7;
1544
+ w.usd += usd8;
1521
1545
  w.activeMinutes += BUCKET_MINUTES;
1522
1546
  }
1523
1547
  const firstT = buckets[0][0];
1524
1548
  const weeks = /* @__PURE__ */ new Map();
1525
- for (const [t, usd7] of buckets) {
1549
+ for (const [t, usd8] of buckets) {
1526
1550
  const week = Math.floor((t - firstT) / WEEK_BUCKETS);
1527
- weeks.set(week, (weeks.get(week) ?? 0) + usd7);
1551
+ weeks.set(week, (weeks.get(week) ?? 0) + usd8);
1528
1552
  }
1529
1553
  const byUsd = windows.slice().sort((a, b) => a.usd - b.usd);
1530
1554
  const usdAsc = byUsd.map((w) => w.usd);
@@ -1567,22 +1591,22 @@ function burnClock(report, offsetMinutes = 0) {
1567
1591
  const byDay = [0, 0, 0, 0, 0, 0, 0];
1568
1592
  const byQuarter = [0, 0, 0, 0];
1569
1593
  const slot = Array.from({ length: 7 }, () => [0, 0, 0, 0]);
1570
- for (const [t, usd7] of merged) {
1594
+ for (const [t, usd8] of merged) {
1571
1595
  const d = new Date(t * 9e5 + offsetMinutes * 6e4);
1572
1596
  const day2 = d.getUTCDay();
1573
1597
  const quarter = Math.floor(d.getUTCHours() / 6);
1574
- byDay[day2] += usd7;
1575
- byQuarter[quarter] += usd7;
1576
- slot[day2][quarter] += usd7;
1598
+ byDay[day2] += usd8;
1599
+ byQuarter[quarter] += usd8;
1600
+ slot[day2][quarter] += usd8;
1577
1601
  }
1578
1602
  let topSlot = null;
1579
1603
  let quietSlot = null;
1580
1604
  for (let day2 = 0; day2 < 7; day2++) {
1581
1605
  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 };
1606
+ const usd8 = slot[day2][quarter];
1607
+ if (usd8 <= 0) continue;
1608
+ if (!topSlot || usd8 > topSlot.usd) topSlot = { day: day2, quarter, usd: usd8 };
1609
+ if (!quietSlot || usd8 < quietSlot.usd) quietSlot = { day: day2, quarter, usd: usd8 };
1586
1610
  }
1587
1611
  }
1588
1612
  return { assessed: true, byDay, byQuarter, topSlot, quietSlot, activeDays: activeDaySet.size };
@@ -1599,6 +1623,9 @@ function usd(n) {
1599
1623
  const grouped = whole.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
1600
1624
  return `${neg ? "-" : ""}$${grouped}${cents}`;
1601
1625
  }
1626
+ function num3(n) {
1627
+ return String(Math.round(n)).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
1628
+ }
1602
1629
  function clean(text2) {
1603
1630
  return sanitizeText(text2);
1604
1631
  }
@@ -1643,16 +1670,25 @@ function parseSections(md) {
1643
1670
  const lines = md.split(/\r?\n/);
1644
1671
  const sections = [];
1645
1672
  let current = null;
1673
+ const finish = (c) => {
1674
+ const body = c.body.join("\n").trim();
1675
+ return {
1676
+ heading: c.heading,
1677
+ body,
1678
+ tokens: Math.round(body.length / 4),
1679
+ volatileLines: c.body.filter((l) => VOLATILE_MARKER.test(l)).length
1680
+ };
1681
+ };
1646
1682
  for (const line of lines) {
1647
1683
  const m = line.match(/^##\s+(.+?)\s*$/);
1648
1684
  if (m) {
1649
- if (current) sections.push({ heading: current.heading, body: current.body.join("\n").trim() });
1685
+ if (current) sections.push(finish(current));
1650
1686
  current = { heading: m[1], body: [] };
1651
1687
  } else if (current) {
1652
1688
  current.body.push(line);
1653
1689
  }
1654
1690
  }
1655
- if (current) sections.push({ heading: current.heading, body: current.body.join("\n").trim() });
1691
+ if (current) sections.push(finish(current));
1656
1692
  return sections.filter((s) => s.body.length > 0);
1657
1693
  }
1658
1694
  var REGENERATED_HEADING = [
@@ -1672,7 +1708,9 @@ function carriedSections(currentClaudeMd) {
1672
1708
  other: [],
1673
1709
  droppedVolatile: [],
1674
1710
  replaced: [],
1675
- commandsBody: null
1711
+ commandsBody: null,
1712
+ carriedTokens: 0,
1713
+ carriedList: []
1676
1714
  };
1677
1715
  if (!currentClaudeMd) return out;
1678
1716
  for (const section of parseSections(currentClaudeMd)) {
@@ -1685,10 +1723,16 @@ function carriedSections(currentClaudeMd) {
1685
1723
  }
1686
1724
  } else if (out.workflow === null && WORKFLOW_HEADING.test(section.heading)) {
1687
1725
  out.workflow = section.body;
1726
+ out.carriedTokens += section.tokens;
1727
+ out.carriedList.push(section);
1688
1728
  } else if (out.architecture === null && ARCH_HEADING.test(section.heading)) {
1689
1729
  out.architecture = section.body;
1730
+ out.carriedTokens += section.tokens;
1731
+ out.carriedList.push(section);
1690
1732
  } else {
1691
1733
  out.other.push(section);
1734
+ out.carriedTokens += section.tokens;
1735
+ out.carriedList.push(section);
1692
1736
  }
1693
1737
  }
1694
1738
  return out;
@@ -1753,7 +1797,20 @@ function stackOneLiner(stack) {
1753
1797
  }
1754
1798
  return `A ${joined} project.`;
1755
1799
  }
1756
- function buildClaudeMd(input, recoverable, notes, stats, carried) {
1800
+ function regenDisposition(label, categoryIndex, carried, hasContent, filledWhy) {
1801
+ const re = REGENERATED_HEADING[categoryIndex];
1802
+ const wasReplaced = carried.replaced.some((h) => re.test(h));
1803
+ if (wasReplaced) {
1804
+ return {
1805
+ name: label,
1806
+ disposition: "replaced",
1807
+ why: `Replaced your existing ${label} section with the version derived from the project scan.`
1808
+ };
1809
+ }
1810
+ if (hasContent) return { name: label, disposition: "filled", why: filledWhy };
1811
+ return { name: label, disposition: "placeholder", why: `${label} was left as a placeholder; no matching evidence was found.` };
1812
+ }
1813
+ function buildClaudeMd(input, recoverable, notes, stats, carried, dispositions) {
1757
1814
  const { currentClaudeMd, project } = input;
1758
1815
  const { title, intro, introDropped } = carriedIntro(currentClaudeMd);
1759
1816
  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.";
@@ -1766,8 +1823,8 @@ function buildClaudeMd(input, recoverable, notes, stats, carried) {
1766
1823
  " How to use this file:",
1767
1824
  " - Replace every placeholder comment with your project's real details, then",
1768
1825
  " delete any line that does not earn its place.",
1769
- " - Keep it lean. Current Anthropic guidance is under about 200 lines. For each",
1770
- ' line ask "would removing this make the agent make a mistake?" If not, cut it.',
1826
+ ' - Keep it lean, but do not cut to a line count. For each line ask "would',
1827
+ ' removing this make the agent make a mistake?" If not, cut it.',
1771
1828
  " - Only include what the agent cannot infer from the code: commands it cannot",
1772
1829
  " guess, conventions that differ from the language defaults, and non-obvious",
1773
1830
  " gotchas. Skip anything self-evident.",
@@ -1792,10 +1849,13 @@ function buildClaudeMd(input, recoverable, notes, stats, carried) {
1792
1849
  const titleText = projectName ?? title ?? "Project name";
1793
1850
  if (projectName) {
1794
1851
  filled.push("Title");
1852
+ dispositions.push({ name: "Title", disposition: "filled", why: "Filled from the project's detected name." });
1795
1853
  } else if (title) {
1796
1854
  notes.push(`Carried across the project title from your CLAUDE.md: "${title}".`);
1855
+ dispositions.push({ name: "Title", disposition: "carried", why: "Carried across from your existing CLAUDE.md." });
1797
1856
  } else {
1798
1857
  notes.push("No project title was detectable, so the title is a placeholder.");
1858
+ dispositions.push({ name: "Title", disposition: "placeholder", why: "No project title was detectable." });
1799
1859
  }
1800
1860
  const projectDesc = project?.description?.trim() || null;
1801
1861
  const synthesized = project ? stackOneLiner(project.stack) : null;
@@ -1808,14 +1868,24 @@ function buildClaudeMd(input, recoverable, notes, stats, carried) {
1808
1868
  }
1809
1869
  if (projectDesc) {
1810
1870
  filled.push("Description");
1871
+ dispositions.push({ name: "Description", disposition: "filled", why: "Filled from the project's manifest description." });
1811
1872
  } else if (synthesized) {
1812
1873
  filled.push("Stack");
1874
+ dispositions.push({ name: "Description", disposition: "filled", why: "Filled with a one-line summary of the detected stack." });
1813
1875
  } else if (intro) {
1814
1876
  notes.push("Carried across your one-line project description.");
1877
+ dispositions.push({ name: "Description", disposition: "carried", why: "Carried across from your existing CLAUDE.md." });
1815
1878
  } else if (introDropped) {
1816
1879
  notes.push(
1817
1880
  "Left your existing description out because it carried volatile markers (a date or status note) that would churn the cache."
1818
1881
  );
1882
+ dispositions.push({
1883
+ name: "Description",
1884
+ disposition: "placeholder",
1885
+ why: "Your existing description carried volatile markers that would churn the cache, so it was left out."
1886
+ });
1887
+ } else {
1888
+ dispositions.push({ name: "Description", disposition: "placeholder", why: "No description was detectable." });
1819
1889
  }
1820
1890
  parts.push([`# ${titleText}`, "", descLine].join("\n"));
1821
1891
  const allCommands = project?.commands ?? [];
@@ -1838,8 +1908,10 @@ function buildClaudeMd(input, recoverable, notes, stats, carried) {
1838
1908
  }
1839
1909
  parts.push(lines.join("\n"));
1840
1910
  filled.push("Commands");
1911
+ dispositions.push(regenDisposition("Commands", 0, carried, true, "Filled from the project's manifest commands."));
1841
1912
  } else {
1842
1913
  stats.placeholders += 1;
1914
+ dispositions.push(regenDisposition("Commands", 0, carried, false, ""));
1843
1915
  parts.push(
1844
1916
  [
1845
1917
  "## Commands",
@@ -1869,8 +1941,10 @@ function buildClaudeMd(input, recoverable, notes, stats, carried) {
1869
1941
  }
1870
1942
  parts.push(lines.join("\n"));
1871
1943
  filled.push("Project structure");
1944
+ dispositions.push(regenDisposition("Project structure", 1, carried, true, "Filled from the project's detected directory layout."));
1872
1945
  } else {
1873
1946
  stats.placeholders += 1;
1947
+ dispositions.push(regenDisposition("Project structure", 1, carried, false, ""));
1874
1948
  parts.push(
1875
1949
  [
1876
1950
  "## Project structure",
@@ -1892,8 +1966,10 @@ function buildClaudeMd(input, recoverable, notes, stats, carried) {
1892
1966
  for (const s of codeStyle) lines.push(`- ${s}`);
1893
1967
  parts.push(lines.join("\n"));
1894
1968
  filled.push("Code style");
1969
+ dispositions.push(regenDisposition("Code style", 2, carried, true, "Filled from the project's detected style conventions."));
1895
1970
  } else {
1896
1971
  stats.placeholders += 1;
1972
+ dispositions.push(regenDisposition("Code style", 2, carried, false, ""));
1897
1973
  parts.push(
1898
1974
  [
1899
1975
  "## Code style",
@@ -1915,8 +1991,10 @@ function buildClaudeMd(input, recoverable, notes, stats, carried) {
1915
1991
  for (const t of testing) lines.push(`- ${t}`);
1916
1992
  parts.push(lines.join("\n"));
1917
1993
  filled.push("Testing");
1994
+ dispositions.push(regenDisposition("Testing", 3, carried, true, "Filled from the project's detected test setup."));
1918
1995
  } else {
1919
1996
  stats.placeholders += 1;
1997
+ dispositions.push(regenDisposition("Testing", 3, carried, false, ""));
1920
1998
  parts.push(
1921
1999
  [
1922
2000
  "## Testing",
@@ -1932,8 +2010,10 @@ function buildClaudeMd(input, recoverable, notes, stats, carried) {
1932
2010
  }
1933
2011
  if (carried.workflow) {
1934
2012
  parts.push(["## Workflow", "", carried.workflow].join("\n"));
2013
+ dispositions.push({ name: "Workflow", disposition: "carried", why: "Carried across your Workflow section from the existing CLAUDE.md." });
1935
2014
  } else {
1936
2015
  stats.placeholders += 1;
2016
+ dispositions.push({ name: "Workflow", disposition: "placeholder", why: "No Workflow section was found, so this is a placeholder." });
1937
2017
  parts.push(
1938
2018
  [
1939
2019
  "## Workflow",
@@ -1949,8 +2029,10 @@ function buildClaudeMd(input, recoverable, notes, stats, carried) {
1949
2029
  }
1950
2030
  if (carried.architecture) {
1951
2031
  parts.push(["## Architecture and gotchas", "", carried.architecture].join("\n"));
2032
+ dispositions.push({ name: "Architecture and gotchas", disposition: "carried", why: "Carried across your Architecture and gotchas section from the existing CLAUDE.md." });
1952
2033
  } else {
1953
2034
  stats.placeholders += 1;
2035
+ 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." });
1954
2036
  parts.push(
1955
2037
  [
1956
2038
  "## Architecture and gotchas",
@@ -1968,6 +2050,7 @@ function buildClaudeMd(input, recoverable, notes, stats, carried) {
1968
2050
  }
1969
2051
  for (const section of carried.other) {
1970
2052
  parts.push([`## ${section.heading}`, "", section.body].join("\n"));
2053
+ dispositions.push({ name: section.heading, disposition: "carried", why: "Carried across from your existing CLAUDE.md under its own heading." });
1971
2054
  }
1972
2055
  const envVars = (project?.envVars ?? []).map((v) => v.trim()).filter((v) => v.length > 0);
1973
2056
  if (envVars.length > 0) {
@@ -1980,8 +2063,10 @@ function buildClaudeMd(input, recoverable, notes, stats, carried) {
1980
2063
  ].join("\n")
1981
2064
  );
1982
2065
  filled.push("Environment");
2066
+ dispositions.push(regenDisposition("Environment", 4, carried, true, "Filled from the project's detected environment variable names."));
1983
2067
  } else {
1984
2068
  stats.placeholders += 1;
2069
+ dispositions.push(regenDisposition("Environment", 4, carried, false, ""));
1985
2070
  parts.push(
1986
2071
  [
1987
2072
  "## Environment",
@@ -2028,6 +2113,13 @@ function buildClaudeMd(input, recoverable, notes, stats, carried) {
2028
2113
  notes.push(
2029
2114
  `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.`
2030
2115
  );
2116
+ for (const heading of carried.droppedVolatile) {
2117
+ dispositions.push({
2118
+ name: heading,
2119
+ disposition: "dropped",
2120
+ why: "Status-style sections churn on every update and bust the prompt cache."
2121
+ });
2122
+ }
2031
2123
  }
2032
2124
  if (currentClaudeMd && /^---\r?\n/.test(currentClaudeMd.trimStart())) {
2033
2125
  notes.push(
@@ -2091,6 +2183,10 @@ function renderCacheTable(report) {
2091
2183
  `${tail.length} smaller project${tail.length === 1 ? "" : "s"} account for the remaining ${usd(tailUsd)}.`
2092
2184
  );
2093
2185
  }
2186
+ lines.push("");
2187
+ lines.push(
2188
+ "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."
2189
+ );
2094
2190
  return lines.join("\n");
2095
2191
  }
2096
2192
  function practices(report, scores, recoverable) {
@@ -2165,7 +2261,16 @@ function tokenDiscipline(report) {
2165
2261
  "- 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."
2166
2262
  ].join("\n");
2167
2263
  }
2168
- function buildPlaybook(report, fixes, scores, recoverable, project) {
2264
+ function claudeMdReceiptLine(claudeMdTokens) {
2265
+ const { before, after } = claudeMdTokens;
2266
+ if (before == null || before === after) return null;
2267
+ const delta = after - before;
2268
+ const grew = delta > 0;
2269
+ const pct2 = before > 0 ? ` (${(Math.abs(delta) / before * 100).toFixed(1)}% ${grew ? "larger" : "smaller"})` : "";
2270
+ 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.";
2271
+ return `Your optimized CLAUDE.md goes from an estimated ${num3(before)} tokens to ${num3(after)}${pct2}. ${tail}`;
2272
+ }
2273
+ function buildPlaybook(report, fixes, scores, recoverable, claudeMdTokens, project) {
2169
2274
  const dollarFixes = fixes.filter((f) => f.wasteUsd > 0);
2170
2275
  const warnFixes = fixes.filter((f) => f.wasteUsd <= 0);
2171
2276
  const parts = [];
@@ -2181,6 +2286,8 @@ function buildPlaybook(report, fixes, scores, recoverable, project) {
2181
2286
  "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."
2182
2287
  ].join("\n")
2183
2288
  );
2289
+ const receipt = claudeMdReceiptLine(claudeMdTokens);
2290
+ if (receipt) parts.push(receipt);
2184
2291
  dollarFixes.forEach((fix, i) => {
2185
2292
  parts.push(renderDollarFix(fix, i + 1));
2186
2293
  if (fix.id === "cache_recovery") {
@@ -2231,7 +2338,9 @@ function buildSettings(project) {
2231
2338
  const settings = { permissions: { allow, deny: [...BASE_DENY] } };
2232
2339
  return clean(JSON.stringify(settings, null, 2) + "\n");
2233
2340
  }
2234
- function buildHarnessPrompt(input, carried) {
2341
+ var CARRY_HEAVY_TOKENS = 1500;
2342
+ var CARRY_WORKLIST_CAP = 8;
2343
+ function buildHarnessPrompt(input, carried, claudeMdTokens) {
2235
2344
  const project = input.project;
2236
2345
  const name = project?.name?.trim() || "this project";
2237
2346
  const findings = input.report.findings;
@@ -2258,8 +2367,9 @@ function buildHarnessPrompt(input, carried) {
2258
2367
  "- Never invent project facts. When a merge choice is unclear, ask.",
2259
2368
  "- Show a diff before replacing any human-written file, and back the",
2260
2369
  " file up first (CLAUDE.md -> CLAUDE.md.bak).",
2261
- "- Keep the final CLAUDE.md lean: under about 200 lines, and every line",
2262
- ' must pass "would removing this make the agent make a mistake?"',
2370
+ '- Keep the final CLAUDE.md lean: every line must pass "would removing',
2371
+ ' this make the agent make a mistake?" Cut what fails that test, not down',
2372
+ " to a line count. There is no target number of lines.",
2263
2373
  "- Commit per this repo's conventions when a task completes cleanly."
2264
2374
  ].join("\n")
2265
2375
  );
@@ -2292,6 +2402,43 @@ function buildHarnessPrompt(input, carried) {
2292
2402
  ].join("\n")
2293
2403
  );
2294
2404
  let n = 3;
2405
+ const worklist = [...carried.carriedList].sort((a, b) => b.tokens - a.tokens).slice(0, CARRY_WORKLIST_CAP);
2406
+ if (carried.carriedTokens >= CARRY_HEAVY_TOKENS && worklist.length > 0) {
2407
+ const rows = worklist.map((s) => {
2408
+ const n2 = s.volatileLines;
2409
+ const dated = n2 > 0 ? `, ${num3(n2)} dated ${n2 === 1 ? "line" : "lines"}` : "";
2410
+ return `- ${s.heading}: est. ${num3(s.tokens)} tokens${dated}.`;
2411
+ });
2412
+ const shown = worklist.reduce((sum, s) => sum + s.tokens, 0);
2413
+ const rest = carried.carriedList.length - worklist.length;
2414
+ const tail = rest > 0 ? [`The remaining ${num3(rest)} carried ${rest === 1 ? "section accounts" : "sections account"} for the other ${num3(carried.carriedTokens - shown)} tokens.`] : [];
2415
+ const before = claudeMdTokens.before;
2416
+ const saved = before != null && before > 0 ? (before - claudeMdTokens.after) / before : 0;
2417
+ const consequence = saved <= 0 ? "that is why the optimized file is no smaller." : saved < 0.2 ? "that is why the optimized file is barely smaller." : "it is the weight that is left.";
2418
+ parts.push(
2419
+ [
2420
+ `## Task ${n++}: Reclaim the carried sections`,
2421
+ "",
2422
+ `Your CLAUDE.md carries an estimated ${num3(carried.carriedTokens)} tokens of your`,
2423
+ "own prose, paid on every turn of every session.",
2424
+ `costclaw does not rewrite your prose, so it passed all of it through untouched:`,
2425
+ `${consequence} Doing the actual trimming is this task,`,
2426
+ "and it needs judgment costclaw will not fake.",
2427
+ "",
2428
+ "Heaviest carried sections, largest first:",
2429
+ "",
2430
+ ...rows,
2431
+ ...tail,
2432
+ "",
2433
+ "For each one decide, line by line: is this a durable operating rule the agent",
2434
+ "needs loaded every turn, or is it narrative history? Dated lines are the usual",
2435
+ "giveaway for history. Rules stay in CLAUDE.md. History moves to docs/ (a",
2436
+ "DECISIONS.md for choices, an ERRORS.md for incidents) where the agent can open",
2437
+ "it on demand. Move it, do not delete it. Ask before cutting anything you cannot",
2438
+ "confidently classify."
2439
+ ].join("\n")
2440
+ );
2441
+ }
2295
2442
  if (carried.droppedVolatile.length > 0) {
2296
2443
  parts.push(
2297
2444
  [
@@ -2361,9 +2508,15 @@ function buildHarnessPrompt(input, carried) {
2361
2508
  const lintCmd = project?.commands.find((c) => c.label === "lint")?.command;
2362
2509
  if (testCmd) verify.push(`- Run \`${testCmd}\` and read the output.`);
2363
2510
  if (lintCmd) verify.push(`- Run \`${lintCmd}\` and read the output.`);
2511
+ verify.push("- Confirm no generator comment blocks are left in CLAUDE.md.");
2512
+ if (carried.carriedTokens >= CARRY_HEAVY_TOKENS) {
2513
+ verify.push(
2514
+ "- Confirm every line moved out of CLAUDE.md landed in a file under",
2515
+ " docs/, and that re-reading CLAUDE.md start to finish still answers",
2516
+ " what the agent needs to know. Report the token count before and after."
2517
+ );
2518
+ }
2364
2519
  verify.push(
2365
- "- Confirm CLAUDE.md is under about 200 lines with no generator comments",
2366
- " left in it.",
2367
2520
  "- After about a week of normal usage, run `npx costclaw audit`: the",
2368
2521
  ' "Since optimize" line measures the cache-hit movement these changes',
2369
2522
  " are meant to produce."
@@ -2376,22 +2529,42 @@ function optimize(input) {
2376
2529
  const notes = [];
2377
2530
  const stats = { placeholders: 0 };
2378
2531
  const carried = carriedSections(input.currentClaudeMd);
2379
- const optimizedClaudeMd = buildClaudeMd(input, recoverable, notes, stats, carried);
2380
- const playbook = buildPlaybook(input.report, input.fixes, input.scores, recoverable, input.project);
2532
+ const dispositions = [];
2533
+ const optimizedClaudeMd = buildClaudeMd(input, recoverable, notes, stats, carried, dispositions);
2534
+ const claudeMdTokens = {
2535
+ before: input.currentClaudeMd ? Math.round(input.currentClaudeMd.trim().length / 4) : null,
2536
+ after: Math.round(optimizedClaudeMd.trim().length / 4)
2537
+ };
2538
+ const carriedTokens = carried.carriedTokens;
2539
+ const playbook = buildPlaybook(input.report, input.fixes, input.scores, recoverable, claudeMdTokens, input.project);
2381
2540
  const settingsJson = buildSettings(input.project);
2382
- const harnessPrompt = buildHarnessPrompt(input, carried);
2541
+ const harnessPrompt = buildHarnessPrompt(input, carried, claudeMdTokens);
2383
2542
  const cleanNotes = notes.map((n) => clean(n));
2384
- if (hasEmDash(optimizedClaudeMd) || hasEmDash(playbook) || hasEmDash(settingsJson) || hasEmDash(harnessPrompt) || cleanNotes.some(hasEmDash)) {
2543
+ const cleanDispositions = dispositions.map((d) => ({ ...d, name: clean(d.name), why: clean(d.why) }));
2544
+ if (hasEmDash(optimizedClaudeMd) || hasEmDash(playbook) || hasEmDash(settingsJson) || hasEmDash(harnessPrompt) || cleanNotes.some(hasEmDash) || cleanDispositions.some((d) => hasEmDash(d.name) || hasEmDash(d.why))) {
2385
2545
  return {
2386
2546
  optimizedClaudeMd: sanitizeText(optimizedClaudeMd),
2387
2547
  playbook: sanitizeText(playbook),
2388
2548
  settingsJson: sanitizeText(settingsJson),
2389
2549
  harnessPrompt: sanitizeText(harnessPrompt),
2390
2550
  notes: cleanNotes.map(sanitizeText),
2391
- placeholdersRemaining: stats.placeholders
2551
+ placeholdersRemaining: stats.placeholders,
2552
+ claudeMdTokens,
2553
+ carriedTokens,
2554
+ sectionDispositions: cleanDispositions.map((d) => ({ ...d, name: sanitizeText(d.name), why: sanitizeText(d.why) }))
2392
2555
  };
2393
2556
  }
2394
- return { optimizedClaudeMd, playbook, settingsJson, harnessPrompt, notes: cleanNotes, placeholdersRemaining: stats.placeholders };
2557
+ return {
2558
+ optimizedClaudeMd,
2559
+ playbook,
2560
+ settingsJson,
2561
+ harnessPrompt,
2562
+ notes: cleanNotes,
2563
+ placeholdersRemaining: stats.placeholders,
2564
+ claudeMdTokens,
2565
+ carriedTokens,
2566
+ sectionDispositions: cleanDispositions
2567
+ };
2395
2568
  }
2396
2569
 
2397
2570
  // ../../packages/engine/src/audit.ts
@@ -2420,7 +2593,7 @@ function toUsageMetrics(report) {
2420
2593
  cacheHitRate: round4(cacheHitRate(sess.totals))
2421
2594
  }));
2422
2595
  const modelBreakdown = {};
2423
- for (const [model, usd7] of Object.entries(s.modelBreakdown)) modelBreakdown[model] = round2(usd7);
2596
+ for (const [model, usd8] of Object.entries(s.modelBreakdown)) modelBreakdown[model] = round2(usd8);
2424
2597
  return {
2425
2598
  spendUsd: round2(s.cost_usd),
2426
2599
  cacheSavingsUsd: round2(s.cache_savings_usd),
@@ -2630,7 +2803,20 @@ var MAX_CLAUDEMD_BYTES = 1 * 1024 * 1024;
2630
2803
  import { mkdir as mkdir2, readFile as readFile3, readdir as readdir2, rm, writeFile as writeFile2 } from "fs/promises";
2631
2804
  import { join as join4, resolve } from "path";
2632
2805
  import { homedir as homedir3 } from "os";
2806
+
2807
+ // src/open.ts
2633
2808
  import { spawn } from "child_process";
2809
+ function openInBrowser(target) {
2810
+ try {
2811
+ const platform = process.platform;
2812
+ const [cmd, args] = platform === "win32" ? ["cmd", ["/c", "start", "", target]] : platform === "darwin" ? ["open", [target]] : ["xdg-open", [target]];
2813
+ const child = spawn(cmd, args, { detached: true, stdio: "ignore" });
2814
+ child.on("error", () => {
2815
+ });
2816
+ child.unref();
2817
+ } catch {
2818
+ }
2819
+ }
2634
2820
 
2635
2821
  // src/read-sessions.ts
2636
2822
  import { readdir } from "fs/promises";
@@ -3477,17 +3663,6 @@ async function resolvePlan(configDir, flag) {
3477
3663
  var DEFAULT_HTML_FILE = "costclaw-report.html";
3478
3664
  var DEFAULT_CARD_FILE = "costclaw-card.svg";
3479
3665
  var SNAPSHOT_KEEP = 50;
3480
- function openInBrowser(target) {
3481
- try {
3482
- const platform = process.platform;
3483
- const [cmd, args] = platform === "win32" ? ["cmd", ["/c", "start", "", target]] : platform === "darwin" ? ["open", [target]] : ["xdg-open", [target]];
3484
- const child = spawn(cmd, args, { detached: true, stdio: "ignore" });
3485
- child.on("error", () => {
3486
- });
3487
- child.unref();
3488
- } catch {
3489
- }
3490
- }
3491
3666
  async function loadAuditInputs(opts) {
3492
3667
  const root = opts.path || defaultProjectsPath();
3493
3668
  const { logs, skipped } = await readSessions(root);
@@ -3573,6 +3748,417 @@ import { mkdir as mkdir3, writeFile as writeFile3, readFile as readFile5, stat a
3573
3748
  import { join as join6, dirname } from "path";
3574
3749
  import { homedir as homedir4 } from "os";
3575
3750
 
3751
+ // src/optimize-dashboard.ts
3752
+ function usd5(n) {
3753
+ const rounded = Math.round(n * 100) / 100;
3754
+ const neg = rounded < 0;
3755
+ const fixed = Math.abs(rounded).toFixed(2);
3756
+ const dot = fixed.indexOf(".");
3757
+ const whole = fixed.slice(0, dot);
3758
+ const cents = fixed.slice(dot);
3759
+ const grouped = whole.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
3760
+ return `${neg ? "-" : ""}$${grouped}${cents}`;
3761
+ }
3762
+ function fmtTokens(n) {
3763
+ const rounded = Math.round(n);
3764
+ const neg = rounded < 0;
3765
+ const grouped = Math.abs(rounded).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
3766
+ return `${neg ? "-" : ""}${grouped}`;
3767
+ }
3768
+ function approxTokens(n) {
3769
+ return `~${fmtTokens(n)}`;
3770
+ }
3771
+ function plural2(n, noun) {
3772
+ return n === 1 ? noun : `${noun}s`;
3773
+ }
3774
+ function num4(n) {
3775
+ return String(Math.round(n)).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
3776
+ }
3777
+ var STYLE2 = `
3778
+ :root{
3779
+ --bg:#faf9f7; --panel:#fff; --ink:#1a1a19; --ink2:#5c5a55; --line:#e3e0da;
3780
+ --accent:#8a5a2b; --good:#2f6f4f; --warn:#8a6a1f; --bad:#8a3a2b;
3781
+ --mono:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;
3782
+ --sans:ui-sans-serif,system-ui,-apple-system,Segoe UI,Roboto,sans-serif;
3783
+ }
3784
+ @media (prefers-color-scheme:dark){:root:not([data-theme="light"]){
3785
+ --bg:#15151a; --panel:#1d1d23; --ink:#f0eeea; --ink2:#a8a49c; --line:#33323a;
3786
+ --accent:#d9a05b; --good:#6fbf8f; --warn:#d9b95b; --bad:#e08a72;
3787
+ }}
3788
+ *{box-sizing:border-box}
3789
+ body{margin:0;background:var(--bg);color:var(--ink);font:16px/1.55 var(--sans);
3790
+ -webkit-font-smoothing:antialiased}
3791
+ .wrap{max-width:1080px;margin:0 auto;padding:40px 24px 96px}
3792
+ header{border-bottom:1px solid var(--line);padding-bottom:24px;margin-bottom:32px}
3793
+ .kicker{font-size:.72rem;letter-spacing:.13em;text-transform:uppercase;color:var(--ink2);margin:0 0 10px}
3794
+ h1{font-size:clamp(1.6rem,3.6vw,2.3rem);margin:0 0 6px;letter-spacing:-.02em;font-weight:750}
3795
+ .sub{color:var(--ink2);margin:0;font-size:.95rem}
3796
+ h2{font-size:1.06rem;letter-spacing:-.01em;margin:40px 0 14px;font-weight:700}
3797
+ h2 .n{color:var(--ink2);font-weight:400;font-size:.85rem;margin-left:8px}
3798
+ .panel{background:var(--panel);border:1px solid var(--line);border-radius:12px;padding:20px 22px}
3799
+ .grid{display:grid;gap:16px}
3800
+ .g3{grid-template-columns:repeat(auto-fit,minmax(210px,1fr))}
3801
+ .g2{grid-template-columns:repeat(auto-fit,minmax(300px,1fr))}
3802
+ .stat{font-variant-numeric:tabular-nums}
3803
+ .stat .v{font-size:1.65rem;font-weight:750;letter-spacing:-.02em;display:block}
3804
+ .stat .l{color:var(--ink2);font-size:.8rem;text-transform:uppercase;letter-spacing:.07em}
3805
+ .stat .d{font-size:.83rem;margin-top:6px;color:var(--ink2)}
3806
+ .win{color:var(--good);font-weight:650}
3807
+ .bar{height:26px;border-radius:6px;background:linear-gradient(90deg,var(--accent) 0%,var(--accent) 100%);
3808
+ position:relative;overflow:hidden}
3809
+ .bar .cut{position:absolute;inset:0 0 0 95.6%;background:var(--good);opacity:.85}
3810
+ .barlabels{display:flex;justify-content:space-between;font-size:.78rem;color:var(--ink2);margin-top:6px;
3811
+ font-variant-numeric:tabular-nums}
3812
+ table{width:100%;border-collapse:collapse;font-size:.9rem;font-variant-numeric:tabular-nums}
3813
+ th,td{text-align:left;padding:9px 10px;border-bottom:1px solid var(--line)}
3814
+ th{font-size:.74rem;text-transform:uppercase;letter-spacing:.07em;color:var(--ink2);font-weight:600}
3815
+ td.num,th.num{text-align:right}
3816
+ .scroll{overflow-x:auto}
3817
+ .fix{border-left:3px solid var(--accent);padding:2px 0 2px 16px;margin:0 0 22px}
3818
+ .fix h3{margin:0 0 4px;font-size:1rem}
3819
+ .fix .amt{font-family:var(--mono);color:var(--accent);font-weight:700}
3820
+ .fix p{margin:8px 0 0;font-size:.93rem}
3821
+ .fix .do{background:color-mix(in srgb,var(--accent) 8%,transparent);border-radius:8px;padding:11px 13px;margin-top:10px}
3822
+ ul.warn{list-style:none;padding:0;margin:0}
3823
+ ul.warn li{padding:10px 0;border-bottom:1px solid var(--line);font-size:.92rem}
3824
+ ul.warn li:last-child{border-bottom:0}
3825
+ ul.warn b{font-weight:650}
3826
+ .pill{display:inline-block;font-size:.7rem;padding:2px 8px;border-radius:99px;border:1px solid var(--line);
3827
+ color:var(--ink2);margin-left:8px;vertical-align:1px}
3828
+ .files{display:grid;gap:12px;grid-template-columns:repeat(auto-fit,minmax(250px,1fr))}
3829
+ .file{border:1px solid var(--line);border-radius:10px;padding:15px 16px;background:var(--panel);
3830
+ display:flex;flex-direction:column;gap:6px}
3831
+ .file .nm{font-family:var(--mono);font-size:.86rem;font-weight:650;color:var(--accent)}
3832
+ .file .ds{font-size:.84rem;color:var(--ink2)}
3833
+ .file a{margin-top:auto;font-size:.83rem;color:var(--ink);text-decoration:none;border-bottom:1px solid var(--line);
3834
+ align-self:flex-start;padding-bottom:1px}
3835
+ .file a:hover{border-color:var(--accent)}
3836
+ .cta{background:var(--panel);border:1px solid var(--line);border-left:3px solid var(--good);
3837
+ border-radius:10px;padding:18px 20px}
3838
+ code.cmd{display:block;font-family:var(--mono);font-size:.86rem;background:color-mix(in srgb,var(--ink) 6%,transparent);
3839
+ padding:11px 13px;border-radius:7px;margin-top:10px;overflow-x:auto;white-space:pre}
3840
+ .note{font-size:.82rem;color:var(--ink2);margin-top:10px}
3841
+ footer{margin-top:56px;padding-top:20px;border-top:1px solid var(--line);color:var(--ink2);font-size:.82rem}
3842
+ details summary{cursor:pointer;font-size:.88rem;color:var(--ink2)}
3843
+ details[open] summary{margin-bottom:10px}
3844
+ .cols{columns:2;column-gap:28px;font-size:.86rem;color:var(--ink2)}
3845
+ @media(max-width:640px){.cols{columns:1}}
3846
+ .tabs input{position:absolute;opacity:0;pointer-events:none}
3847
+ .tabs label{display:inline-block;font-size:.85rem;padding:7px 13px;border:1px solid var(--line);
3848
+ border-radius:7px;margin:0 6px 14px 0;cursor:pointer;color:var(--ink2);user-select:none}
3849
+ .tabs label:hover{border-color:var(--accent)}
3850
+ .tabs input:checked + label{background:var(--accent);border-color:var(--accent);color:#fff;font-weight:600}
3851
+ .tabpane{display:none}
3852
+ #t-sections:checked ~ .tabpane[data-for="t-sections"],
3853
+ #t-diff:checked ~ .tabpane[data-for="t-diff"],
3854
+ #t-side:checked ~ .tabpane[data-for="t-side"]{display:block}
3855
+ .tag{font-family:var(--mono);font-size:.72rem;padding:2px 7px;border-radius:5px;white-space:nowrap}
3856
+ .tag.keep{background:color-mix(in srgb,var(--ink2) 16%,transparent);color:var(--ink)}
3857
+ .tag.fill{background:color-mix(in srgb,var(--good) 20%,transparent);color:var(--good)}
3858
+ .tag.repl{background:color-mix(in srgb,var(--warn) 22%,transparent);color:var(--warn)}
3859
+ .tag.drop{background:color-mix(in srgb,var(--bad) 18%,transparent);color:var(--bad)}
3860
+ .tag.hole{background:color-mix(in srgb,var(--accent) 18%,transparent);color:var(--accent)}
3861
+ pre.diff,pre.src{font-family:var(--mono);font-size:.8rem;line-height:1.5;overflow-x:auto;
3862
+ background:color-mix(in srgb,var(--ink) 5%,transparent);padding:14px 16px;border-radius:8px;margin:0}
3863
+ pre.diff .add{color:var(--good);display:block}
3864
+ pre.diff .del{color:var(--bad);display:block}
3865
+ pre.diff .ctx{color:var(--ink2);display:block}
3866
+ .paneh{font-size:.8rem;text-transform:uppercase;letter-spacing:.07em;color:var(--ink2);
3867
+ margin:0 0 8px;font-weight:600}
3868
+ `;
3869
+ var TAG_META = {
3870
+ carried: { cls: "keep", label: "carried" },
3871
+ filled: { cls: "fill", label: "filled" },
3872
+ replaced: { cls: "repl", label: "replaced" },
3873
+ dropped: { cls: "drop", label: "left out" },
3874
+ placeholder: { cls: "hole", label: "placeholder" }
3875
+ };
3876
+ function renderSectionsTable(sections) {
3877
+ const rows = sections.map((s) => {
3878
+ const meta = TAG_META[s.disposition];
3879
+ return `<tr><td>${esc(s.name)}</td><td><span class="tag ${meta.cls}">${meta.label}</span></td><td>${esc(s.why)}</td></tr>`;
3880
+ }).join("");
3881
+ 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>`;
3882
+ }
3883
+ var DIFF_LCS_LIMIT = 3e3;
3884
+ function diffLines(before, after) {
3885
+ const a = before.split("\n");
3886
+ const b = after.split("\n");
3887
+ const n = a.length;
3888
+ const m = b.length;
3889
+ if (n > DIFF_LCS_LIMIT || m > DIFF_LCS_LIMIT) {
3890
+ const ops2 = [];
3891
+ for (const line of a) ops2.push({ type: "del", text: line });
3892
+ for (const line of b) ops2.push({ type: "add", text: line });
3893
+ return ops2;
3894
+ }
3895
+ const width = m + 1;
3896
+ const dp = new Int32Array((n + 1) * width);
3897
+ for (let i2 = n - 1; i2 >= 0; i2--) {
3898
+ for (let j2 = m - 1; j2 >= 0; j2--) {
3899
+ const ai = a[i2];
3900
+ const bj = b[j2];
3901
+ 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)]);
3902
+ }
3903
+ }
3904
+ const ops = [];
3905
+ let i = 0;
3906
+ let j = 0;
3907
+ while (i < n && j < m) {
3908
+ if (a[i] === b[j]) {
3909
+ ops.push({ type: "ctx", text: a[i] });
3910
+ i++;
3911
+ j++;
3912
+ } else if (dp[(i + 1) * width + j] >= dp[i * width + (j + 1)]) {
3913
+ ops.push({ type: "del", text: a[i] });
3914
+ i++;
3915
+ } else {
3916
+ ops.push({ type: "add", text: b[j] });
3917
+ j++;
3918
+ }
3919
+ }
3920
+ while (i < n) {
3921
+ ops.push({ type: "del", text: a[i] });
3922
+ i++;
3923
+ }
3924
+ while (j < m) {
3925
+ ops.push({ type: "add", text: b[j] });
3926
+ j++;
3927
+ }
3928
+ return ops;
3929
+ }
3930
+ var DIFF_CONTEXT = 2;
3931
+ var DIFF_MAX_LINES = 4e3;
3932
+ function buildHunks(ops) {
3933
+ const keep = new Array(ops.length).fill(false);
3934
+ for (let i = 0; i < ops.length; i++) {
3935
+ if (ops[i].type !== "ctx") {
3936
+ for (let j = Math.max(0, i - DIFF_CONTEXT); j <= Math.min(ops.length - 1, i + DIFF_CONTEXT); j++) {
3937
+ keep[j] = true;
3938
+ }
3939
+ }
3940
+ }
3941
+ const out = [];
3942
+ let lastKept = -2;
3943
+ for (let i = 0; i < ops.length; i++) {
3944
+ if (!keep[i]) continue;
3945
+ if (out.length > 0 && i - lastKept > 1) out.push({ type: "ctx", text: "" });
3946
+ out.push(ops[i]);
3947
+ lastKept = i;
3948
+ }
3949
+ return out;
3950
+ }
3951
+ function renderDiffTab(before, after) {
3952
+ 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>`;
3953
+ if (before === null) {
3954
+ 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>`;
3955
+ }
3956
+ const hunks = buildHunks(diffLines(before, after));
3957
+ const truncated = hunks.length > DIFF_MAX_LINES;
3958
+ const shown = truncated ? hunks.slice(0, DIFF_MAX_LINES) : hunks;
3959
+ const body = shown.map((op) => {
3960
+ if (op.type === "ctx") return `<span class="ctx">${esc(op.text)}</span>`;
3961
+ const prefix = op.type === "add" ? "+ " : "- ";
3962
+ return `<span class="${op.type}">${esc(prefix + op.text)}</span>`;
3963
+ }).join("\n");
3964
+ const note = truncated ? `<p class="note">Diff truncated at ${DIFF_MAX_LINES} lines; open the file for the rest.</p>` : "";
3965
+ return `${intro}<pre class="diff">${body}</pre>${note}`;
3966
+ }
3967
+ var SIDE_PANE_CHAR_CAP = 2e4;
3968
+ function renderPane(text2) {
3969
+ const truncated = text2.length > SIDE_PANE_CHAR_CAP;
3970
+ const shown = truncated ? text2.slice(0, SIDE_PANE_CHAR_CAP) : text2;
3971
+ const note = truncated ? `<p class="note">Truncated; open the file for the rest.</p>` : "";
3972
+ return `<pre class="src">${esc(shown)}</pre>${note}`;
3973
+ }
3974
+ function renderSideBySideTab(before, after, tokens) {
3975
+ const afterCol = `<p class="paneh">Optimized <span class="win" style="font-weight:600">${esc(approxTokens(tokens.after))} tokens</span></p>` + renderPane(after);
3976
+ 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);
3977
+ return `<div class="grid g2" style="gap:14px"><div>${beforeCol}</div><div>${afterCol}</div></div>`;
3978
+ }
3979
+ function renderComparisonTabs(input) {
3980
+ 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>`;
3981
+ }
3982
+ function countLines(s) {
3983
+ return s.length === 0 ? 0 : s.split("\n").length;
3984
+ }
3985
+ function renderTokenStat(input) {
3986
+ const { before, after } = input.claudeMdTokens;
3987
+ if (before === null) {
3988
+ 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>`;
3989
+ }
3990
+ const delta = after - before;
3991
+ const saved = delta < 0;
3992
+ const pct2 = before > 0 ? delta / before * 100 : 0;
3993
+ const deltaText = `${delta >= 0 ? "+" : ""}${fmtTokens(delta)} tokens`;
3994
+ const pctText = `${pct2 >= 0 ? "+" : ""}${pct2.toFixed(1)}%`;
3995
+ 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>`;
3996
+ }
3997
+ function renderSectionsStat(sections) {
3998
+ const counts = { carried: 0, filled: 0, replaced: 0, dropped: 0, placeholder: 0 };
3999
+ for (const s of sections) counts[s.disposition]++;
4000
+ const total = sections.length;
4001
+ const headline = counts.carried > 0 ? `${counts.carried} carried` : `${total} ${plural2(total, "section")}`;
4002
+ const rest = [];
4003
+ if (counts.replaced > 0) rest.push(`${counts.replaced} replaced from the scan`);
4004
+ if (counts.dropped > 0) rest.push(`${counts.dropped} volatile ${plural2(counts.dropped, "section")} dropped`);
4005
+ if (counts.filled > 0) rest.push(`${counts.filled} filled from your project`);
4006
+ if (counts.placeholder > 0) rest.push(`${counts.placeholder} left as ${counts.placeholder === 1 ? "a placeholder" : "placeholders"}`);
4007
+ const restText = rest.length > 0 ? rest.join(", ") + "." : "Nothing else to report.";
4008
+ return `<div class="stat"><span class="l">Sections handled</span><span class="v">${esc(headline)}</span><span class="d">${esc(restText)}</span></div>`;
4009
+ }
4010
+ function renderRecoverableStat(input) {
4011
+ const pct2 = `${(input.headlineWasteShare * 100).toFixed(1)}%`;
4012
+ 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>`;
4013
+ }
4014
+ function renderReceipt(input) {
4015
+ const stats = `<div class="grid g3">${renderTokenStat(input)}${renderSectionsStat(input.sectionDispositions)}${renderRecoverableStat(input)}</div>`;
4016
+ const { before, after } = input.claudeMdTokens;
4017
+ let bar2 = "";
4018
+ if (before !== null && after < before) {
4019
+ const cutPct = Math.max(0, Math.min(100, after / before * 100));
4020
+ const savedTokens = before - after;
4021
+ 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>`;
4022
+ const lineDelta = countLines(input.optimizedClaudeMd) - countLines(input.currentClaudeMd ?? "");
4023
+ if (lineDelta !== 0) {
4024
+ 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>`;
4025
+ }
4026
+ }
4027
+ return `<div class="panel">${stats}${bar2}</div>`;
4028
+ }
4029
+ var CACHE_TABLE_FLOOR2 = 1;
4030
+ var CACHE_TABLE_CAP2 = 10;
4031
+ function renderCacheTable2(report) {
4032
+ const all = cacheMissByProject(report);
4033
+ const shown = all.filter((r) => r.usd >= CACHE_TABLE_FLOOR2).slice(0, CACHE_TABLE_CAP2);
4034
+ if (shown.length === 0) return "";
4035
+ const shownSlugs = new Set(shown.map((r) => r.slug));
4036
+ const tail = all.filter((r) => !shownSlugs.has(r.slug));
4037
+ const rows = shown.map(
4038
+ (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>`
4039
+ ).join("");
4040
+ let tailRow = "";
4041
+ if (tail.length > 0) {
4042
+ const tailUsd = tail.reduce((sum, r) => sum + r.usd, 0);
4043
+ 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>`;
4044
+ }
4045
+ 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>`;
4046
+ }
4047
+ function renderFixes(fixes, report) {
4048
+ const dollarFixes = fixes.filter((f) => f.wasteUsd > 0).sort((a, b) => b.wasteUsd - a.wasteUsd);
4049
+ if (dollarFixes.length === 0) return `<p class="note">No directly recoverable dollars found.</p>`;
4050
+ return dollarFixes.map((f, i) => {
4051
+ const table = f.id === "cache_recovery" ? renderCacheTable2(report) : "";
4052
+ 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>`;
4053
+ }).join("");
4054
+ }
4055
+ function toolWarnings(report) {
4056
+ const out = [];
4057
+ for (const f of report.findings) {
4058
+ const sessions = f.evidence?.["sessionsAffected"];
4059
+ const tool = f.evidence?.["tool"];
4060
+ if (typeof sessions === "number" && typeof tool === "string") {
4061
+ out.push({ title: f.title, sessions, tool, action: f.suggestedAction });
4062
+ }
4063
+ }
4064
+ return out.sort((a, b) => b.sessions - a.sessions);
4065
+ }
4066
+ function renderSetupWarnings(fixes, report) {
4067
+ const warnFixes = fixes.filter((f) => f.wasteUsd <= 0);
4068
+ const tool = toolWarnings(report);
4069
+ const multi = tool.filter((t) => t.sessions > 1);
4070
+ const single = tool.filter((t) => t.sessions === 1);
4071
+ const items = [];
4072
+ for (const f of warnFixes) {
4073
+ items.push(`<li><b>${esc(f.title)}.</b> ${esc(f.action)} <span class="pill">measured</span></li>`);
4074
+ }
4075
+ for (const t of multi) {
4076
+ const sentence = t.action ? ` ${esc(t.action)}` : "";
4077
+ items.push(
4078
+ `<li><b>${esc(t.title)}.</b>${sentence} <span class="pill">${t.sessions} ${plural2(t.sessions, "session")}</span></li>`
4079
+ );
4080
+ }
4081
+ const list = items.length > 0 ? `<ul class="warn">${items.join("")}</ul>` : `<p class="note">No setup warnings found.</p>`;
4082
+ let disclosure = "";
4083
+ if (single.length > 0) {
4084
+ const names = [...new Set(single.map((t) => t.tool))].map(esc).join(", ");
4085
+ 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>`;
4086
+ }
4087
+ return `<div class="panel">${list}${disclosure}</div>`;
4088
+ }
4089
+ var OPTIMIZED_NAME = "CLAUDE.optimized.md";
4090
+ var PLAYBOOK_NAME = "PLAYBOOK.md";
4091
+ var SETTINGS_NAME = "settings.suggested.json";
4092
+ var HARNESS_NAME = "HARNESS-UPGRADE.md";
4093
+ function renderArtifactCards(input) {
4094
+ const { before, after } = input.claudeMdTokens;
4095
+ const lighter = before !== null && after < before ? ` and ${fmtTokens(before - after)} tokens lighter` : "";
4096
+ const placeholders = `${input.placeholdersRemaining} ${plural2(input.placeholdersRemaining, "placeholder")} to fill.`;
4097
+ const claudeDesc = before === null ? `A new CLAUDE.md scaffold for your project. ${placeholders}` : `Your CLAUDE.md, restructured${lighter}. ${placeholders}`;
4098
+ 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>`;
4099
+ 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>`;
4100
+ }
4101
+ function renderApplyCta(input) {
4102
+ 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>`;
4103
+ }
4104
+ function renderCarriedDisclosure(sections, carriedTokens) {
4105
+ const carried = sections.filter((s) => s.disposition === "carried");
4106
+ if (carried.length === 0) return "";
4107
+ const names = carried.map((s) => esc(s.name)).join(" &middot; ");
4108
+ const weight = carriedTokens > 0 ? `, about ${num4(carriedTokens)} tokens` : "";
4109
+ const note = carriedTokens > 0 ? `<p class="note">Carried through as written. costclaw does not rewrite your prose, so this is where the remaining weight sits. HARNESS-UPGRADE.md ranks these sections and flags their dated lines for you to move into docs/.</p>` : "";
4110
+ return `<details style="margin-top:34px"><summary>All ${carried.length} ${plural2(carried.length, "section")} carried across from your existing CLAUDE.md${weight}</summary><div class="cols">${names}</div>${note}</details>`;
4111
+ }
4112
+ function renderHeader(input) {
4113
+ const parts = [];
4114
+ const stack = input.stack.map((s) => s.trim()).filter((s) => s.length > 0);
4115
+ if (stack.length > 0) parts.push(esc(stack.join(", ")));
4116
+ parts.push(`${input.commandsCount} ${plural2(input.commandsCount, "command")} detected`);
4117
+ parts.push(`4 artifacts written to ${esc(input.artifactsDir)}/`);
4118
+ 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>`;
4119
+ }
4120
+ function renderOptimizeDashboard(input) {
4121
+ return `<!doctype html>
4122
+ <html lang="en">
4123
+ <head>
4124
+ <meta charset="utf-8">
4125
+ <meta name="viewport" content="width=device-width,initial-scale=1">
4126
+ <title>CostClaw optimize: ${esc(input.projectName)}</title>
4127
+ <style>${STYLE2}</style>
4128
+ </head>
4129
+ <body>
4130
+ <div class="wrap">
4131
+ ${renderHeader(input)}
4132
+
4133
+ <h2>What this run changed<span class="n">the receipt</span></h2>
4134
+ ${renderReceipt(input)}
4135
+
4136
+ <h2>Your CLAUDE.md, before and after<span class="n">what actually changed</span></h2>
4137
+ <div class="panel">${renderComparisonTabs(input)}</div>
4138
+
4139
+ <h2>Fixes, ranked by what they recover</h2>
4140
+ ${renderFixes(input.fixes, input.report)}
4141
+
4142
+ <h2>Setup warnings<span class="n">no direct dollar figure, still costly</span></h2>
4143
+ ${renderSetupWarnings(input.fixes, input.report)}
4144
+
4145
+ <h2>Your four artifacts</h2>
4146
+ ${renderArtifactCards(input)}
4147
+
4148
+ <h2>Apply it</h2>
4149
+ ${renderApplyCta(input)}
4150
+
4151
+ ${renderCarriedDisclosure(input.sectionDispositions, input.carriedTokens)}
4152
+
4153
+ <footer>Generated locally by CostClaw v${esc(input.version)}. Dry run: none of your files were changed.
4154
+ No network calls, no telemetry, no model calls.</footer>
4155
+
4156
+ </div>
4157
+ </body>
4158
+ </html>
4159
+ `;
4160
+ }
4161
+
3576
4162
  // src/project-scan.ts
3577
4163
  import { readdir as readdir3, readFile as readFile4, stat } from "fs/promises";
3578
4164
  import { join as join5, basename } from "path";
@@ -4095,11 +4681,12 @@ async function scanProject(dir) {
4095
4681
  }
4096
4682
 
4097
4683
  // src/optimize-command.ts
4098
- var OPTIMIZED_NAME = "CLAUDE.optimized.md";
4099
- var PLAYBOOK_NAME = "PLAYBOOK.md";
4100
- var SETTINGS_NAME = "settings.suggested.json";
4101
- var HARNESS_NAME = "HARNESS-UPGRADE.md";
4102
- function usd5(n) {
4684
+ var OPTIMIZED_NAME2 = "CLAUDE.optimized.md";
4685
+ var PLAYBOOK_NAME2 = "PLAYBOOK.md";
4686
+ var SETTINGS_NAME2 = "settings.suggested.json";
4687
+ var HARNESS_NAME2 = "HARNESS-UPGRADE.md";
4688
+ var DASHBOARD_NAME = "DASHBOARD.html";
4689
+ function usd6(n) {
4103
4690
  return `$${(Math.round(n * 100) / 100).toFixed(2)}`;
4104
4691
  }
4105
4692
  function describeDetection(project) {
@@ -4243,12 +4830,36 @@ async function runOptimize(opts) {
4243
4830
  });
4244
4831
  const outDir = opts.out || join6(process.cwd(), "costclaw-out");
4245
4832
  await mkdir3(outDir, { recursive: true });
4246
- const playbookPath = join6(outDir, PLAYBOOK_NAME);
4833
+ const playbookPath = join6(outDir, PLAYBOOK_NAME2);
4247
4834
  await writeFile3(playbookPath, result.playbook, "utf8");
4248
- const settingsPath = join6(outDir, SETTINGS_NAME);
4835
+ const settingsPath = join6(outDir, SETTINGS_NAME2);
4249
4836
  await writeFile3(settingsPath, result.settingsJson, "utf8");
4250
- const harnessPath = join6(outDir, HARNESS_NAME);
4837
+ const harnessPath = join6(outDir, HARNESS_NAME2);
4251
4838
  await writeFile3(harnessPath, result.harnessPrompt, "utf8");
4839
+ const wantDashboard = opts.dashboard !== false;
4840
+ let dashboardPath = null;
4841
+ if (wantDashboard) {
4842
+ const spend = report.summary.cost_usd;
4843
+ const html = renderOptimizeDashboard({
4844
+ version: opts.version ?? "",
4845
+ projectName: project.name ?? "your project",
4846
+ stack: project.stack,
4847
+ commandsCount: project.commands.length,
4848
+ artifactsDir: outDir,
4849
+ currentClaudeMd: claudeMd ?? null,
4850
+ optimizedClaudeMd: result.optimizedClaudeMd,
4851
+ claudeMdTokens: result.claudeMdTokens,
4852
+ carriedTokens: result.carriedTokens,
4853
+ sectionDispositions: result.sectionDispositions,
4854
+ placeholdersRemaining: result.placeholdersRemaining,
4855
+ fixes,
4856
+ report,
4857
+ headlineWasteShare: spend > 0 ? recoverable / spend : 0,
4858
+ headlineWasteUsd: recoverable
4859
+ });
4860
+ dashboardPath = join6(outDir, DASHBOARD_NAME);
4861
+ await writeFile3(dashboardPath, html, "utf8");
4862
+ }
4252
4863
  const lines = [];
4253
4864
  lines.push("CostClaw optimize");
4254
4865
  lines.push("");
@@ -4284,7 +4895,7 @@ async function runOptimize(opts) {
4284
4895
  }
4285
4896
  lines.push("A suggested settings.json was written to the out dir for review; it is not applied in place.");
4286
4897
  } else {
4287
- const optimizedPath = join6(outDir, OPTIMIZED_NAME);
4898
+ const optimizedPath = join6(outDir, OPTIMIZED_NAME2);
4288
4899
  await writeFile3(optimizedPath, result.optimizedClaudeMd, "utf8");
4289
4900
  lines.push("Dry run (no files of yours were changed).");
4290
4901
  lines.push(`Wrote the optimized CLAUDE.md scaffold to ${optimizedPath}`);
@@ -4295,14 +4906,30 @@ async function runOptimize(opts) {
4295
4906
  lines.push(describeDetection(project));
4296
4907
  if (claudeMdSource) lines.push(`Existing CLAUDE.md: ${claudeMdSource}`);
4297
4908
  if (plan === "api") {
4298
- lines.push(`Recoverable spend (cache-miss exposure): ${usd5(recoverable)}`);
4909
+ lines.push(`Recoverable spend (cache-miss exposure): ${usd6(recoverable)}`);
4299
4910
  } else {
4300
4911
  const spend = report.summary.cost_usd;
4301
4912
  const share = spend > 0 ? recoverable / spend * 100 : 0;
4302
4913
  lines.push(
4303
- `Recoverable usage (cache-miss exposure): ${share.toFixed(1)}% of analyzed usage (${usd5(recoverable)} at API rates)`
4914
+ `Recoverable usage (cache-miss exposure): ${share.toFixed(1)}% of analyzed usage (${usd6(recoverable)} at API rates)`
4304
4915
  );
4305
4916
  }
4917
+ const { before, after } = result.claudeMdTokens;
4918
+ if (before != null && before !== after) {
4919
+ const pct2 = before > 0 ? (Math.abs(after - before) / before * 100).toFixed(1) : "0.0";
4920
+ const dir = after > before ? "larger" : "smaller";
4921
+ const g = (n) => String(Math.round(n)).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
4922
+ lines.push(
4923
+ `Your CLAUDE.md: an estimated ${g(before)} tokens to ${g(after)} (${pct2}% ${dir}), paid on every turn.`
4924
+ );
4925
+ if (result.carriedTokens >= after / 2) {
4926
+ lines.push(
4927
+ `About ${g(result.carriedTokens)} of those tokens are your own prose, carried through as written.`,
4928
+ "costclaw does not rewrite prose, so trimming it is judgment work: HARNESS-UPGRADE.md",
4929
+ "ranks your heaviest sections and flags the dated lines to move into docs/."
4930
+ );
4931
+ }
4932
+ }
4306
4933
  lines.push("");
4307
4934
  if (result.placeholdersRemaining > 0) {
4308
4935
  const n = result.placeholdersRemaining;
@@ -4334,6 +4961,12 @@ async function runOptimize(opts) {
4334
4961
  lines.push("");
4335
4962
  lines.push("Baseline recorded: your next audits will show cache-hit progress since this optimize.");
4336
4963
  lines.push("Nothing left your machine.");
4964
+ if (dashboardPath) {
4965
+ lines.push("");
4966
+ lines.push(`Opening the summary dashboard: ${dashboardPath}`);
4967
+ 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.");
4968
+ openInBrowser(dashboardPath);
4969
+ }
4337
4970
  return { output: lines.join("\n") };
4338
4971
  }
4339
4972
 
@@ -4374,11 +5007,11 @@ import { join as join7 } from "path";
4374
5007
  import { homedir as homedir5 } from "os";
4375
5008
 
4376
5009
  // src/format-diff.ts
4377
- function usd6(n) {
5010
+ function usd7(n) {
4378
5011
  return `$${(Math.round(Math.abs(n) * 100) / 100).toFixed(2)}`;
4379
5012
  }
4380
5013
  function signedUsd(n) {
4381
- return `${n < 0 ? "-" : "+"}${usd6(n)}`;
5014
+ return `${n < 0 ? "-" : "+"}${usd7(n)}`;
4382
5015
  }
4383
5016
  function signedInt(n) {
4384
5017
  return n > 0 ? `+${n}` : `${n}`;
@@ -4399,23 +5032,23 @@ function formatDiff(d) {
4399
5032
  if (d.comparable && d.marginal) {
4400
5033
  lines.push("Since the baseline:");
4401
5034
  lines.push(
4402
- ` New spend ${usd6(d.marginal.newSpendUsd)} across ${d.marginal.newSessions} new sessions`
5035
+ ` New spend ${usd7(d.marginal.newSpendUsd)} across ${d.marginal.newSessions} new sessions`
4403
5036
  );
4404
5037
  lines.push(
4405
5038
  ` Marginal cache hit ${pct(d.marginal.marginalCacheHitRate)} (lifetime ${pct(d.current.cacheHitRate)})`
4406
5039
  );
4407
5040
  lines.push(
4408
- ` Recoverable exposure ${signedUsd(d.deltas.recoverableUsd)} (now ${usd6(d.current.recoverableUsd)})`
5041
+ ` Recoverable exposure ${signedUsd(d.deltas.recoverableUsd)} (now ${usd7(d.current.recoverableUsd)})`
4409
5042
  );
4410
5043
  } else {
4411
5044
  lines.push("Note: the current audit covers less history than the baseline (logs moved or");
4412
5045
  lines.push("pruned), so period metrics are omitted.");
4413
5046
  lines.push("");
4414
5047
  lines.push(
4415
- `Baseline (${day(d.baseline.createdAt)}): spend ${usd6(d.baseline.spendUsd)}, cache hit ${pct(d.baseline.cacheHitRate)}, recoverable ${usd6(d.baseline.recoverableUsd)}`
5048
+ `Baseline (${day(d.baseline.createdAt)}): spend ${usd7(d.baseline.spendUsd)}, cache hit ${pct(d.baseline.cacheHitRate)}, recoverable ${usd7(d.baseline.recoverableUsd)}`
4416
5049
  );
4417
5050
  lines.push(
4418
- `Current (${day(d.current.createdAt)}): spend ${usd6(d.current.spendUsd)}, cache hit ${pct(d.current.cacheHitRate)}, recoverable ${usd6(d.current.recoverableUsd)}`
5051
+ `Current (${day(d.current.createdAt)}): spend ${usd7(d.current.spendUsd)}, cache hit ${pct(d.current.cacheHitRate)}, recoverable ${usd7(d.current.recoverableUsd)}`
4419
5052
  );
4420
5053
  }
4421
5054
  lines.push("");
@@ -4438,18 +5071,18 @@ function formatDiff(d) {
4438
5071
  if (resolved.length > 0) {
4439
5072
  lines.push("");
4440
5073
  lines.push("Fixes resolved since the baseline:");
4441
- for (const f of resolved) lines.push(` - [${usd6(f.wasteUsd)}] ${f.title}`);
5074
+ for (const f of resolved) lines.push(` - [${usd7(f.wasteUsd)}] ${f.title}`);
4442
5075
  }
4443
5076
  if (appeared.length > 0) {
4444
5077
  lines.push("");
4445
5078
  lines.push("New since the baseline:");
4446
- for (const f of appeared) lines.push(` - [${usd6(f.wasteUsd)}] ${f.title}`);
5079
+ for (const f of appeared) lines.push(` - [${usd7(f.wasteUsd)}] ${f.title}`);
4447
5080
  }
4448
5081
  if (changed.length > 0) {
4449
5082
  lines.push("");
4450
5083
  lines.push("Fixes that moved:");
4451
5084
  for (const c of changed) {
4452
- lines.push(` - ${c.title}: ${usd6(c.beforeUsd)} -> ${usd6(c.afterUsd)} (${signedUsd(c.deltaUsd)})`);
5085
+ lines.push(` - ${c.title}: ${usd7(c.beforeUsd)} -> ${usd7(c.afterUsd)} (${signedUsd(c.deltaUsd)})`);
4453
5086
  }
4454
5087
  }
4455
5088
  return lines.join("\n");
@@ -4660,7 +5293,7 @@ function parseBadgeFlags(args) {
4660
5293
  };
4661
5294
  }
4662
5295
  function cliVersion() {
4663
- return true ? "0.6.0" : "0.0.0-dev";
5296
+ return true ? "0.8.0" : "0.0.0-dev";
4664
5297
  }
4665
5298
  function isHelpRequest(command, args) {
4666
5299
  if (command === void 0) return false;
@@ -4675,7 +5308,7 @@ function helpText() {
4675
5308
  " costclaw audit [--path <dir>] [--claude-md <file>] [--plan <plan>] [--json] [--html [file]] [--no-html] [--card [file]]",
4676
5309
  " costclaw diff [<baseline.json> <current.json>] [--json]",
4677
5310
  " costclaw badge [--path <dir>] [--claude-md <file>] [--out <file>]",
4678
- " costclaw optimize [--path <dir>] [--claude-md <file>] [--project <dir>] [--out <dir>] [--write <file>] [--apply-settings [file]] [--force]",
5311
+ " costclaw optimize [--path <dir>] [--claude-md <file>] [--project <dir>] [--out <dir>] [--write <file>] [--apply-settings [file]] [--no-dashboard] [--force]",
4679
5312
  " costclaw activate <license-key> [--name <machine-name>]",
4680
5313
  " costclaw deactivate",
4681
5314
  " costclaw --version",
@@ -4714,6 +5347,8 @@ function helpText() {
4714
5347
  "--apply-settings [file] additively merges the derived permission allowlist into",
4715
5348
  "the project's .claude/settings.json (or [file]); it only touches",
4716
5349
  "permissions.allow and permissions.deny, backs up the original, and prints a diff.",
5350
+ "It also writes DASHBOARD.html and opens it: one page that browses every artifact,",
5351
+ "the ranked fixes, and a before and after of your CLAUDE.md. --no-dashboard skips it.",
4717
5352
  "optimize needs a one-time license: buy at https://costclaw.io, then run",
4718
5353
  "costclaw activate <key>. activate and deactivate move that license between",
4719
5354
  "machines. audit never needs a license.",
@@ -4787,6 +5422,8 @@ Run: costclaw optimize
4787
5422
  out: getFlag(args, "--out"),
4788
5423
  write: getFlag(args, "--write"),
4789
5424
  force: args.includes("--force"),
5425
+ dashboard: !args.includes("--no-dashboard"),
5426
+ version: cliVersion(),
4790
5427
  applySettings: args.includes("--apply-settings"),
4791
5428
  applySettingsPath: args.includes("--apply-settings") ? optionalPathAfter(args, "--apply-settings") : void 0
4792
5429
  });