costclaw 0.5.3 → 0.5.5

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 (2) hide show
  1. package/dist/index.js +196 -49
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -71,6 +71,11 @@ function isOpus(model) {
71
71
  if (!model) return false;
72
72
  return model.replace(/\[[^\]]*\]$/, "").startsWith("claude-opus");
73
73
  }
74
+ function isPremiumModel(model) {
75
+ if (!model) return false;
76
+ const base = model.replace(/\[[^\]]*\]$/, "");
77
+ return base.startsWith("claude-opus") || base.startsWith("claude-fable");
78
+ }
74
79
 
75
80
  // ../../packages/engine/src/sanitize.ts
76
81
  var EM_OR_EN = /[—–]/;
@@ -569,7 +574,7 @@ function ruleModelMisroute(ctx) {
569
574
  for (const proj of ctx.projects) {
570
575
  for (const s of proj.sessions) {
571
576
  if (s.kind !== "main") continue;
572
- if (!isOpus(s.modelPrimary)) continue;
577
+ if (!isPremiumModel(s.modelPrimary)) continue;
573
578
  if (s.turnCache.length > MISROUTE_MAX_TURNS) continue;
574
579
  if (s.durationMinutes == null || s.durationMinutes > MISROUTE_MAX_MINUTES) continue;
575
580
  const tu = s.toolUsage;
@@ -578,13 +583,14 @@ function ruleModelMisroute(ctx) {
578
583
  if (s.totals.output_tokens > MISROUTE_MAX_OUTPUT) continue;
579
584
  const exposure = s.cost_usd - costForTotals(MISROUTE_BASELINE, s.totals);
580
585
  if (exposure < MISROUTE_MIN_EXPOSURE) continue;
586
+ const family = /fable/.test(s.modelPrimary ?? "") ? "Fable" : "Opus";
581
587
  out.push({
582
588
  ruleId: "MODEL_MISROUTE",
583
589
  severity: severityForSavings(exposure),
584
590
  project: proj.slug,
585
- title: "Opus used for a small task",
586
- description: `An Opus session ran ${s.turnCache.length} turns in ${s.durationMinutes.toFixed(1)} minutes with light tool use and a small output; a cheaper model would have served it.`,
587
- suggestedAction: "Use a cheaper model such as Sonnet for short, simple sessions, and reserve Opus for hard problems.",
591
+ title: `${family} used for a small task`,
592
+ description: `A ${family} session ran ${s.turnCache.length} turns in ${s.durationMinutes.toFixed(1)} minutes with light tool use and a small output; a cheaper model would have served it.`,
593
+ suggestedAction: "Use a cheaper model such as Sonnet for short, simple sessions, and reserve premium models for hard problems.",
588
594
  estimatedMonthlySavingsUsd: exposure,
589
595
  evidence: { model: s.modelPrimary, turns: s.turnCache.length, minutes: s.durationMinutes, outputTokens: s.totals.output_tokens, exposureUsd: exposure, sessionUuid: s.sessionUuid }
590
596
  });
@@ -1363,9 +1369,9 @@ function synthesize(report, pillars, cmd, plan = "api") {
1363
1369
  pillarName: PILLARS.cost_discipline.name,
1364
1370
  severity: sevForUsd(misrouteUsd),
1365
1371
  wasteUsd: round23(misrouteUsd),
1366
- problem: sanitizeText(`${n} short Opus ${sWord(n)} with light tool use and small output cost about ${usd7(misrouteUsd)} more than a cheaper model would have.`),
1367
- action: sanitizeText("Route short, simple sessions to a cheaper model such as Sonnet, and reserve Opus for hard reasoning."),
1368
- basis: sanitizeText("Opus session cost minus the same tokens re-priced at the Sonnet rate, summed over sessions that pass a conservative triviality gate.")
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.`),
1373
+ action: sanitizeText("Route short, simple sessions to a cheaper model such as Sonnet, and reserve premium models for hard reasoning."),
1374
+ basis: sanitizeText("Premium session cost minus the same tokens re-priced at the Sonnet rate, summed over sessions that pass a conservative triviality gate.")
1369
1375
  });
1370
1376
  }
1371
1377
  if (marathonSet.size > 0) {
@@ -1573,13 +1579,23 @@ var VOLATILE_HEADING = /^(status|changelog|progress|history|roadmap|todos?|next
1573
1579
  var WORKFLOW_HEADING = /workflow|etiquette|contributing|branch|commit/i;
1574
1580
  var ARCH_HEADING = /architecture|gotcha|footgun|how it works|data flow|overview/i;
1575
1581
  function carriedSections(currentClaudeMd) {
1576
- const out = { workflow: null, architecture: null, other: [], droppedVolatile: [], replaced: [] };
1582
+ const out = {
1583
+ workflow: null,
1584
+ architecture: null,
1585
+ other: [],
1586
+ droppedVolatile: [],
1587
+ replaced: [],
1588
+ commandsBody: null
1589
+ };
1577
1590
  if (!currentClaudeMd) return out;
1578
1591
  for (const section of parseSections(currentClaudeMd)) {
1579
1592
  if (VOLATILE_HEADING.test(section.heading)) {
1580
1593
  out.droppedVolatile.push(section.heading);
1581
1594
  } else if (REGENERATED_HEADING.some((re) => re.test(section.heading))) {
1582
1595
  out.replaced.push(section.heading);
1596
+ if (out.commandsBody === null && /^(commands?|scripts?)\b/i.test(section.heading)) {
1597
+ out.commandsBody = section.body;
1598
+ }
1583
1599
  } else if (out.workflow === null && WORKFLOW_HEADING.test(section.heading)) {
1584
1600
  out.workflow = section.body;
1585
1601
  } else if (out.architecture === null && ARCH_HEADING.test(section.heading)) {
@@ -1613,11 +1629,30 @@ function curateCommands(commands) {
1613
1629
  const chosen = (kept.length >= 4 ? kept : commands).slice(0, MAX_COMMANDS);
1614
1630
  return { kept: chosen, dropped: commands.length - chosen.length };
1615
1631
  }
1616
- function commandLine(c) {
1632
+ function commandLine(c, note) {
1633
+ if (note) return `- \`${c.command}\` ${note}`;
1617
1634
  const tokens = c.command.toLowerCase().split(/[^a-z0-9:_-]+/);
1618
1635
  const redundant = tokens.includes(c.label.toLowerCase());
1619
1636
  return redundant ? `- \`${c.command}\`` : `- \`${c.command}\` ${c.label}`;
1620
1637
  }
1638
+ var NOTE_MAX = 80;
1639
+ function extractCommandNotes(body) {
1640
+ const notes = /* @__PURE__ */ new Map();
1641
+ if (!body) return notes;
1642
+ const keyOf = (cmd) => cmd.trim().replace(/\s+/g, " ");
1643
+ for (const raw of body.split("\n")) {
1644
+ const line = raw.trim();
1645
+ if (!line || line.startsWith("```") || line.startsWith("#")) continue;
1646
+ const fence = line.match(/^([^#`]+?)\s+#\s*(.+)$/);
1647
+ if (fence) {
1648
+ notes.set(keyOf(fence[1]), fence[2].trim().slice(0, NOTE_MAX));
1649
+ continue;
1650
+ }
1651
+ const bullet = line.match(/^[-*]\s+`([^`]+)`\s+(.+)$/);
1652
+ if (bullet) notes.set(keyOf(bullet[1]), bullet[2].trim().slice(0, NOTE_MAX));
1653
+ }
1654
+ return notes;
1655
+ }
1621
1656
  function stackOneLiner(stack) {
1622
1657
  const items = stack.map((s) => s.trim()).filter((s) => s.length > 0);
1623
1658
  if (items.length === 0) return null;
@@ -1631,7 +1666,7 @@ function stackOneLiner(stack) {
1631
1666
  }
1632
1667
  return `A ${joined} project.`;
1633
1668
  }
1634
- function buildClaudeMd(input, recoverable, notes) {
1669
+ function buildClaudeMd(input, recoverable, notes, stats) {
1635
1670
  const { currentClaudeMd, project } = input;
1636
1671
  const { title, intro, introDropped } = carriedIntro(currentClaudeMd);
1637
1672
  const carried = carriedSections(currentClaudeMd);
@@ -1678,7 +1713,13 @@ function buildClaudeMd(input, recoverable, notes) {
1678
1713
  }
1679
1714
  const projectDesc = project?.description?.trim() || null;
1680
1715
  const synthesized = project ? stackOneLiner(project.stack) : null;
1681
- const descLine = projectDesc ?? synthesized ?? intro ?? "<!-- one line: the stack and what this project does, e.g. Node and Postgres API on Render -->";
1716
+ let descLine;
1717
+ if (projectDesc ?? synthesized ?? intro) {
1718
+ descLine = projectDesc ?? synthesized ?? intro;
1719
+ } else {
1720
+ descLine = "<!-- one line: the stack and what this project does, e.g. Node and Postgres API on Render -->";
1721
+ stats.placeholders += 1;
1722
+ }
1682
1723
  if (projectDesc) {
1683
1724
  filled.push("Description");
1684
1725
  } else if (synthesized) {
@@ -1693,9 +1734,12 @@ function buildClaudeMd(input, recoverable, notes) {
1693
1734
  parts.push([`# ${titleText}`, "", descLine].join("\n"));
1694
1735
  const allCommands = project?.commands ?? [];
1695
1736
  const { kept: commands, dropped: droppedCommands } = curateCommands(allCommands);
1737
+ const commandNotes = extractCommandNotes(carried.commandsBody);
1696
1738
  if (commands.length > 0) {
1697
1739
  const lines = ["## Commands", ""];
1698
- for (const c of commands) lines.push(commandLine(c));
1740
+ for (const c of commands) {
1741
+ lines.push(commandLine(c, commandNotes.get(c.command.trim().replace(/\s+/g, " "))));
1742
+ }
1699
1743
  if (project?.preCommit) lines.push(`- IMPORTANT: ${project.preCommit}.`);
1700
1744
  if (droppedCommands > 0) {
1701
1745
  lines.push("");
@@ -1709,6 +1753,7 @@ function buildClaudeMd(input, recoverable, notes) {
1709
1753
  parts.push(lines.join("\n"));
1710
1754
  filled.push("Commands");
1711
1755
  } else {
1756
+ stats.placeholders += 1;
1712
1757
  parts.push(
1713
1758
  [
1714
1759
  "## Commands",
@@ -1739,6 +1784,7 @@ function buildClaudeMd(input, recoverable, notes) {
1739
1784
  parts.push(lines.join("\n"));
1740
1785
  filled.push("Project structure");
1741
1786
  } else {
1787
+ stats.placeholders += 1;
1742
1788
  parts.push(
1743
1789
  [
1744
1790
  "## Project structure",
@@ -1761,6 +1807,7 @@ function buildClaudeMd(input, recoverable, notes) {
1761
1807
  parts.push(lines.join("\n"));
1762
1808
  filled.push("Code style");
1763
1809
  } else {
1810
+ stats.placeholders += 1;
1764
1811
  parts.push(
1765
1812
  [
1766
1813
  "## Code style",
@@ -1783,6 +1830,7 @@ function buildClaudeMd(input, recoverable, notes) {
1783
1830
  parts.push(lines.join("\n"));
1784
1831
  filled.push("Testing");
1785
1832
  } else {
1833
+ stats.placeholders += 1;
1786
1834
  parts.push(
1787
1835
  [
1788
1836
  "## Testing",
@@ -1800,6 +1848,7 @@ function buildClaudeMd(input, recoverable, notes) {
1800
1848
  parts.push(["## Workflow", "", carried.workflow].join("\n"));
1801
1849
  filled.push("Workflow");
1802
1850
  } else {
1851
+ stats.placeholders += 1;
1803
1852
  parts.push(
1804
1853
  [
1805
1854
  "## Workflow",
@@ -1817,6 +1866,7 @@ function buildClaudeMd(input, recoverable, notes) {
1817
1866
  parts.push(["## Architecture and gotchas", "", carried.architecture].join("\n"));
1818
1867
  filled.push("Architecture and gotchas");
1819
1868
  } else {
1869
+ stats.placeholders += 1;
1820
1870
  parts.push(
1821
1871
  [
1822
1872
  "## Architecture and gotchas",
@@ -1847,6 +1897,7 @@ function buildClaudeMd(input, recoverable, notes) {
1847
1897
  );
1848
1898
  filled.push("Environment");
1849
1899
  } else {
1900
+ stats.placeholders += 1;
1850
1901
  parts.push(
1851
1902
  [
1852
1903
  "## Environment",
@@ -1894,6 +1945,11 @@ function buildClaudeMd(input, recoverable, notes) {
1894
1945
  `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.`
1895
1946
  );
1896
1947
  }
1948
+ if (currentClaudeMd && /^---\r?\n/.test(currentClaudeMd.trimStart())) {
1949
+ notes.push(
1950
+ "Left out the YAML frontmatter: CLAUDE.md needs none, and metadata like last-verified dates churns the cache."
1951
+ );
1952
+ }
1897
1953
  if (project) {
1898
1954
  if (filled.length > 0) {
1899
1955
  const growNote = carried.architecture ? "" : "; Architecture and gotchas is left as a placeholder for you to grow";
@@ -1974,7 +2030,7 @@ function countSessions(report, ruleId) {
1974
2030
  function tokenDiscipline(report) {
1975
2031
  const misroute = countSessions(report, "MODEL_MISROUTE");
1976
2032
  const marathon = countSessions(report, "MARATHON_SESSION");
1977
- const modelLead = misroute > 0 ? `Your audit flagged ${misroute} short Opus session${misroute === 1 ? "" : "s"} a cheaper model would have served. ` : "";
2033
+ const modelLead = misroute > 0 ? `Your audit flagged ${misroute} short premium-model session${misroute === 1 ? "" : "s"} a cheaper model would have served. ` : "";
1978
2034
  const compactLead = marathon > 0 ? `Your audit found ${marathon} long session${marathon === 1 ? "" : "s"} whose cache decayed. ` : "";
1979
2035
  return [
1980
2036
  "## Token discipline",
@@ -1986,7 +2042,7 @@ function tokenDiscipline(report) {
1986
2042
  "- Leaving everything on one high level pays for reasoning you do not need. Match the level to the task.",
1987
2043
  "",
1988
2044
  "### Match the model to the task",
1989
- `- ${modelLead}Use a cheaper model such as Sonnet for routine edits, a fast model such as Haiku for throwaway questions, and reserve Opus for hard reasoning.`,
2045
+ `- ${modelLead}Use a cheaper model such as Sonnet for routine edits, a fast model such as Haiku for throwaway questions, and reserve premium models (Opus, Fable) for hard reasoning.`,
1990
2046
  "",
1991
2047
  "### Use fast mode for bulk work",
1992
2048
  "- `/fast` pays off when the model already knows what to do: large refactors, documentation, and test generation.",
@@ -2059,7 +2115,8 @@ function buildSettings(project) {
2059
2115
  function optimize(input) {
2060
2116
  const recoverable = cacheMissExposureUsd(input.report);
2061
2117
  const notes = [];
2062
- const optimizedClaudeMd = buildClaudeMd(input, recoverable, notes);
2118
+ const stats = { placeholders: 0 };
2119
+ const optimizedClaudeMd = buildClaudeMd(input, recoverable, notes, stats);
2063
2120
  const playbook = buildPlaybook(input.report, input.fixes, input.scores, recoverable, input.project);
2064
2121
  const settingsJson = buildSettings(input.project);
2065
2122
  const cleanNotes = notes.map((n) => clean(n));
@@ -2068,10 +2125,11 @@ function optimize(input) {
2068
2125
  optimizedClaudeMd: sanitizeText(optimizedClaudeMd),
2069
2126
  playbook: sanitizeText(playbook),
2070
2127
  settingsJson: sanitizeText(settingsJson),
2071
- notes: cleanNotes.map(sanitizeText)
2128
+ notes: cleanNotes.map(sanitizeText),
2129
+ placeholdersRemaining: stats.placeholders
2072
2130
  };
2073
2131
  }
2074
- return { optimizedClaudeMd, playbook, settingsJson, notes: cleanNotes };
2132
+ return { optimizedClaudeMd, playbook, settingsJson, notes: cleanNotes, placeholdersRemaining: stats.placeholders };
2075
2133
  }
2076
2134
 
2077
2135
  // ../../packages/engine/src/audit.ts
@@ -2107,6 +2165,7 @@ function toUsageMetrics(report) {
2107
2165
  cacheHitRate: round4(s.cacheHitRate),
2108
2166
  totalTokens: { ...s.totals },
2109
2167
  sessionsCount: s.sessionsCount,
2168
+ delegatedSessionsCount: s.delegatedSessionsCount,
2110
2169
  projectsCount: s.projectsCount,
2111
2170
  durationHours: round2(s.durationHours),
2112
2171
  modelBreakdown,
@@ -2261,6 +2320,34 @@ function diffAudits(a, b) {
2261
2320
  fixes: { resolved, appeared, changed }
2262
2321
  };
2263
2322
  }
2323
+ var SINCE_BASELINE_MIN_TOKENS = 1e6;
2324
+ function sinceBaseline(baseline, current) {
2325
+ const cur = current.usageMetrics.totalTokens;
2326
+ const base = baseline.totals;
2327
+ const period = {
2328
+ input_tokens: cur.input_tokens - base.input_tokens,
2329
+ output_tokens: cur.output_tokens - base.output_tokens,
2330
+ cache_creation_tokens: cur.cache_creation_tokens - base.cache_creation_tokens,
2331
+ cache_read_tokens: cur.cache_read_tokens - base.cache_read_tokens
2332
+ };
2333
+ if (period.input_tokens < 0 || period.output_tokens < 0 || period.cache_creation_tokens < 0 || period.cache_read_tokens < 0) {
2334
+ return { comparable: false, reason: "history reset" };
2335
+ }
2336
+ const inputClass = period.input_tokens + period.cache_creation_tokens + period.cache_read_tokens;
2337
+ if (inputClass < SINCE_BASELINE_MIN_TOKENS) {
2338
+ return { comparable: false, reason: "not enough new usage yet" };
2339
+ }
2340
+ const periodCacheHitRate = cacheHitRate(period);
2341
+ const improvement = Math.max(0, periodCacheHitRate - baseline.cacheHitRate);
2342
+ const recoveredUsd = round22(improvement * inputClass * (FALLBACK.input - FALLBACK.cache_read) / 1e6);
2343
+ return {
2344
+ comparable: true,
2345
+ baselineCacheHitRate: round42(baseline.cacheHitRate),
2346
+ periodCacheHitRate: round42(periodCacheHitRate),
2347
+ recoveredUsd,
2348
+ newSpendUsd: round22(current.usageMetrics.spendUsd - baseline.spendUsd)
2349
+ };
2350
+ }
2264
2351
 
2265
2352
  // ../../packages/engine/src/validate.ts
2266
2353
  var MAX_FILE_BYTES = 25 * 1024 * 1024;
@@ -2408,6 +2495,15 @@ function ansi(enabled) {
2408
2495
  }
2409
2496
 
2410
2497
  // src/format.ts
2498
+ function sinceOptimizeLine(meta) {
2499
+ const so = meta.sinceOptimize;
2500
+ if (!so || !so.result.comparable) return null;
2501
+ const r = so.result;
2502
+ const date = so.at.slice(0, 10);
2503
+ const move = `${(r.baselineCacheHitRate * 100).toFixed(1)}% -> ${(r.periodCacheHitRate * 100).toFixed(1)}%`;
2504
+ const worth = r.recoveredUsd >= 0.01 ? `; worth about ${usd2(r.recoveredUsd)} at Sonnet rates` : "";
2505
+ return `Since optimize (${date}): cache hit ${move} on new usage${worth}.`;
2506
+ }
2411
2507
  function usd2(n) {
2412
2508
  return `$${(Math.round(n * 100) / 100).toFixed(2)}`;
2413
2509
  }
@@ -2506,9 +2602,10 @@ function formatAudit(record, meta, color = false) {
2506
2602
  const shareText = `${(share * 100).toFixed(1)}%`;
2507
2603
  const lines = [];
2508
2604
  lines.push(a.bold("CostClaw audit"));
2605
+ const delegated = m.delegatedSessionsCount ?? 0;
2509
2606
  pushProse(
2510
2607
  lines,
2511
- `Source: ${meta.root} (${meta.sessionCount} ${plural(meta.sessionCount, "session")} across ${m.projectsCount} ${plural(m.projectsCount, "project")})`,
2608
+ `Source: ${meta.root} (${m.sessionsCount} ${plural(m.sessionsCount, "session")}${delegated > 0 ? ` +${delegated} delegated` : ""} across ${m.projectsCount} ${plural(m.projectsCount, "project")})`,
2512
2609
  0,
2513
2610
  a.dim
2514
2611
  );
@@ -2518,6 +2615,8 @@ function formatAudit(record, meta, color = false) {
2518
2615
  lines.push(
2519
2616
  subscription ? `${a.bold(record.headlineWasteLabel + ":")} ${a.brand(shareText + " of analyzed usage")} (${usd2(record.headlineWasteUsd)} at API rates)` : `${a.bold(record.headlineWasteLabel + ":")} ${a.brand(usd2(record.headlineWasteUsd))}`
2520
2617
  );
2618
+ const receipt = sinceOptimizeLine(meta);
2619
+ if (receipt) pushProse(lines, receipt, 0, a.dim);
2521
2620
  lines.push("");
2522
2621
  const mix = modelMix(m.modelBreakdown);
2523
2622
  const statBlock = [
@@ -2836,10 +2935,12 @@ function renderHtml(record, meta) {
2836
2935
  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>`;
2837
2936
  const otherSection = otherIssues.length === 0 ? "" : `<h2>Other issues to tighten</h2><ul class="fixes">${otherIssues.map(otherFixCard).join("")}</ul>`;
2838
2937
  const skippedNote = meta.skipped.length > 0 ? `<p class="sub">Note: ${meta.skipped.length} file(s) could not be read and were skipped.</p>` : "";
2938
+ const receipt = sinceOptimizeLine(meta);
2839
2939
  const metaBlock = [
2840
- `Source: ${esc(meta.root)} (${meta.sessionCount} ${plural(meta.sessionCount, "session")} across ${m.projectsCount} ${plural(m.projectsCount, "project")})`,
2940
+ `Source: ${esc(meta.root)} (${m.sessionsCount} ${plural(m.sessionsCount, "session")}${(m.delegatedSessionsCount ?? 0) > 0 ? ` +${m.delegatedSessionsCount} delegated` : ""} across ${m.projectsCount} ${plural(m.projectsCount, "project")})`,
2841
2941
  meta.claudeMdSource ? `CLAUDE.md: ${esc(meta.claudeMdSource)}` : "",
2842
- `Pricing snapshot: ${esc(m.pricingSnapshotDate)}`
2942
+ `Pricing snapshot: ${esc(m.pricingSnapshotDate)}`,
2943
+ receipt ? `<strong>${esc(receipt)}</strong>` : ""
2843
2944
  ].filter((line) => line.length > 0).map((line) => `<p class="meta">${line}</p>`).join("\n");
2844
2945
  return `<!doctype html>
2845
2946
  <html lang="en">
@@ -2983,6 +3084,16 @@ async function readSetup(home = homedir2()) {
2983
3084
  // src/config.ts
2984
3085
  import { mkdir, readFile as readFile2, writeFile } from "fs/promises";
2985
3086
  import { join as join3 } from "path";
3087
+ var TOTAL_KEYS = ["input_tokens", "output_tokens", "cache_creation_tokens", "cache_read_tokens"];
3088
+ function asBaseline(value) {
3089
+ if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
3090
+ const o = value;
3091
+ const totals = o["totals"];
3092
+ if (!totals || typeof totals !== "object" || Array.isArray(totals)) return void 0;
3093
+ const t = totals;
3094
+ const ok = typeof o["at"] === "string" && typeof o["cacheHitRate"] === "number" && typeof o["headlineWasteShare"] === "number" && typeof o["spendUsd"] === "number" && TOTAL_KEYS.every((k) => typeof t[k] === "number");
3095
+ return ok ? value : void 0;
3096
+ }
2986
3097
  function configFile(dir) {
2987
3098
  return join3(dir, "config.json");
2988
3099
  }
@@ -2998,6 +3109,8 @@ async function readCliConfig(dir) {
2998
3109
  const raw = await readRaw(dir);
2999
3110
  const cfg = {};
3000
3111
  if (typeof raw["plan"] === "string" && isPlan(raw["plan"])) cfg.plan = raw["plan"];
3112
+ const baseline = asBaseline(raw["lastOptimize"]);
3113
+ if (baseline) cfg.lastOptimize = baseline;
3001
3114
  return cfg;
3002
3115
  }
3003
3116
  async function saveCliConfig(dir, patch) {
@@ -3065,6 +3178,8 @@ async function runAudit(opts) {
3065
3178
  const configDir = join4(opts.home ?? homedir3(), ".costclaw");
3066
3179
  const { plan, planSource } = await resolvePlan(configDir, opts.plan);
3067
3180
  const record = buildAudit({ logs, claudeMd, questionnaire: {}, setup, plan });
3181
+ const baseline = (await readCliConfig(configDir)).lastOptimize;
3182
+ const sinceOptimize = baseline ? { at: baseline.at, result: sinceBaseline(baseline, record) } : void 0;
3068
3183
  let snapshotNotice = null;
3069
3184
  try {
3070
3185
  const historyDir = join4(opts.home ?? homedir3(), ".costclaw", "history");
@@ -3081,12 +3196,12 @@ async function runAudit(opts) {
3081
3196
  `);
3082
3197
  }
3083
3198
  const color = !opts.json && process.stdout.isTTY === true && !process.env["NO_COLOR"];
3084
- let output = opts.json ? JSON.stringify(record, null, 2) : formatAudit(record, { root, sessionCount: logs.length, skipped, claudeMdSource, planSource }, color);
3199
+ let output = opts.json ? JSON.stringify(record, null, 2) : formatAudit(record, { root, sessionCount: logs.length, skipped, claudeMdSource, planSource, sinceOptimize }, color);
3085
3200
  const notices = [];
3086
3201
  if (snapshotNotice) notices.push(snapshotNotice);
3087
3202
  if (opts.html) {
3088
3203
  const target = resolve(opts.htmlPath || DEFAULT_HTML_FILE);
3089
- const doc = renderHtml(record, { root, sessionCount: logs.length, skipped, claudeMdSource, planSource });
3204
+ const doc = renderHtml(record, { root, sessionCount: logs.length, skipped, claudeMdSource, planSource, sinceOptimize });
3090
3205
  await writeFile2(target, doc, "utf8");
3091
3206
  openInBrowser(target);
3092
3207
  notices.push(`HTML report written to ${target}`);
@@ -3735,11 +3850,22 @@ async function runOptimize(opts) {
3735
3850
  const report = analyzeUploads(logs);
3736
3851
  const cmd = analyzeClaudeMd(claudeMd);
3737
3852
  const { pillars } = scorePillars(report, cmd, {});
3738
- const { plan } = await resolvePlan(join6(opts.home ?? homedir4(), ".costclaw"), opts.plan);
3853
+ const configDir = join6(opts.home ?? homedir4(), ".costclaw");
3854
+ const { plan } = await resolvePlan(configDir, opts.plan);
3739
3855
  const { fixes } = synthesize(report, pillars, cmd, plan);
3740
3856
  const project = await scanProject(projectDir);
3741
3857
  const result = optimize({ report, scores: pillars, fixes, currentClaudeMd: claudeMd, project });
3742
3858
  const recoverable = cacheMissExposureUsd(report);
3859
+ const baselineSpend = report.summary.cost_usd;
3860
+ await saveCliConfig(configDir, {
3861
+ lastOptimize: {
3862
+ at: (/* @__PURE__ */ new Date()).toISOString(),
3863
+ totals: { ...report.summary.totals },
3864
+ cacheHitRate: report.summary.cacheHitRate,
3865
+ headlineWasteShare: baselineSpend > 0 ? recoverable / baselineSpend : 0,
3866
+ spendUsd: baselineSpend
3867
+ }
3868
+ });
3743
3869
  const outDir = opts.out || join6(process.cwd(), "costclaw-out");
3744
3870
  await mkdir3(outDir, { recursive: true });
3745
3871
  const playbookPath = join6(outDir, PLAYBOOK_NAME);
@@ -3771,7 +3897,9 @@ async function runOptimize(opts) {
3771
3897
  lines.push("Diff (old vs new):");
3772
3898
  lines.push(lineDiff(original, result.optimizedClaudeMd));
3773
3899
  lines.push("");
3774
- lines.push("Warning: this scaffold has placeholders to fill in. Search it for <!-- ... --> and replace each with your project's real details.");
3900
+ if (result.placeholdersRemaining > 0) {
3901
+ lines.push("Warning: this scaffold has placeholders to fill in. Search it for <!-- ... --> and replace each with your project's real details.");
3902
+ }
3775
3903
  lines.push("A suggested settings.json was written to the out dir for review; it is not applied in place.");
3776
3904
  } else {
3777
3905
  const optimizedPath = join6(outDir, OPTIMIZED_NAME);
@@ -3793,8 +3921,14 @@ async function runOptimize(opts) {
3793
3921
  );
3794
3922
  }
3795
3923
  lines.push("");
3796
- lines.push("The optimized CLAUDE.md is a scaffold: it has placeholders to fill in.");
3797
- lines.push("Search it for <!-- ... --> and replace each with your project's real details.");
3924
+ if (result.placeholdersRemaining > 0) {
3925
+ const n = result.placeholdersRemaining;
3926
+ lines.push(`The optimized CLAUDE.md has ${n} section${n === 1 ? "" : "s"} left as placeholders (no evidence to fill them).`);
3927
+ lines.push("Search it for <!-- ... --> and replace each with your project's real details.");
3928
+ } else {
3929
+ lines.push("Every section was filled from your project and your existing CLAUDE.md; nothing is left as a placeholder.");
3930
+ lines.push("Review it (the notes below say what changed), then apply it.");
3931
+ }
3798
3932
  lines.push("To apply it in place (with a backup and a diff first), rerun with --write <your-CLAUDE.md>.");
3799
3933
  lines.push("The settings.suggested.json is a conservative permission allowlist. Review it, then merge the rules you want into ~/.claude/settings.json or the project's .claude/settings.json. It is never applied unless you ask.");
3800
3934
  lines.push("To merge it into the project's .claude/settings.json for you (with a backup and a diff first), rerun with --apply-settings.");
@@ -3811,6 +3945,7 @@ async function runOptimize(opts) {
3811
3945
  for (const note of result.notes) lines.push(` - ${note}`);
3812
3946
  }
3813
3947
  lines.push("");
3948
+ lines.push("Baseline recorded: your next audits will show cache-hit progress since this optimize.");
3814
3949
  lines.push("Nothing left your machine.");
3815
3950
  return { output: lines.join("\n") };
3816
3951
  }
@@ -3976,12 +4111,44 @@ async function runDiff(opts) {
3976
4111
  import { mkdir as mkdir4, readFile as readFile7, writeFile as writeFile5, rm as rm2 } from "fs/promises";
3977
4112
  import { join as join8 } from "path";
3978
4113
  import { homedir as homedir6, hostname } from "os";
3979
- import { createPublicKey, verify as cryptoVerify } from "crypto";
4114
+
4115
+ // ../../packages/license/src/keys.ts
3980
4116
  var LICENSE_PRODUCT = "costclaw-optimize";
4117
+ var KEY_PREFIX = "CC1";
3981
4118
  var DEFAULT_PUBLIC_KEY_PEM = `-----BEGIN PUBLIC KEY-----
3982
4119
  MCowBQYDK2VwAyEAXKdEIiMqeB4HIUb8si3LxRPBnrDpCIJrWvJWUCQLROg=
3983
4120
  -----END PUBLIC KEY-----`;
3984
- var KEY_PREFIX = "CC1";
4121
+
4122
+ // ../../packages/license/src/verify.ts
4123
+ import { createPublicKey, verify as cryptoVerify } from "crypto";
4124
+ function base64UrlDecode(part) {
4125
+ return Buffer.from(part.replace(/-/g, "+").replace(/_/g, "/"), "base64");
4126
+ }
4127
+ function verifyLicenseKey(licenseKey, publicKeyPem = DEFAULT_PUBLIC_KEY_PEM) {
4128
+ const parts = licenseKey.trim().split(".");
4129
+ if (parts.length !== 3 || parts[0] !== KEY_PREFIX) return null;
4130
+ const [prefix, payloadPart, signaturePart] = parts;
4131
+ if (prefix === void 0 || payloadPart === void 0 || signaturePart === void 0) return null;
4132
+ try {
4133
+ const publicKey = createPublicKey(publicKeyPem);
4134
+ const signed = Buffer.from(`${prefix}.${payloadPart}`, "utf8");
4135
+ const signature = base64UrlDecode(signaturePart);
4136
+ if (!cryptoVerify(null, signed, publicKey, signature)) return null;
4137
+ const payload = JSON.parse(base64UrlDecode(payloadPart).toString("utf8"));
4138
+ if (payload.p !== LICENSE_PRODUCT) return null;
4139
+ return payload;
4140
+ } catch {
4141
+ return null;
4142
+ }
4143
+ }
4144
+
4145
+ // ../../packages/license/src/mint.ts
4146
+ import { createPrivateKey, sign } from "crypto";
4147
+
4148
+ // ../../packages/license/src/stripe.ts
4149
+ import { createHmac, timingSafeEqual } from "crypto";
4150
+
4151
+ // src/license.ts
3985
4152
  var NOT_ACTIVATED_MESSAGE = [
3986
4153
  "costclaw optimize needs a license.",
3987
4154
  "",
@@ -4005,26 +4172,6 @@ function defaultConfigDir() {
4005
4172
  function licenseFile(dir) {
4006
4173
  return join8(dir, "license.json");
4007
4174
  }
4008
- function base64UrlDecode(part) {
4009
- return Buffer.from(part.replace(/-/g, "+").replace(/_/g, "/"), "base64");
4010
- }
4011
- function verifyLicenseKey(licenseKey, publicKeyPem = DEFAULT_PUBLIC_KEY_PEM) {
4012
- const parts = licenseKey.trim().split(".");
4013
- if (parts.length !== 3 || parts[0] !== KEY_PREFIX) return null;
4014
- const [prefix, payloadPart, signaturePart] = parts;
4015
- if (prefix === void 0 || payloadPart === void 0 || signaturePart === void 0) return null;
4016
- try {
4017
- const publicKey = createPublicKey(publicKeyPem);
4018
- const signed = Buffer.from(`${prefix}.${payloadPart}`, "utf8");
4019
- const signature = base64UrlDecode(signaturePart);
4020
- if (!cryptoVerify(null, signed, publicKey, signature)) return null;
4021
- const payload = JSON.parse(base64UrlDecode(payloadPart).toString("utf8"));
4022
- if (payload.p !== LICENSE_PRODUCT) return null;
4023
- return payload;
4024
- } catch {
4025
- return null;
4026
- }
4027
- }
4028
4175
  async function readStoredLicense(dir) {
4029
4176
  try {
4030
4177
  const data = JSON.parse(await readFile7(licenseFile(dir), "utf8"));
@@ -4126,7 +4273,7 @@ function parseBadgeFlags(args) {
4126
4273
  };
4127
4274
  }
4128
4275
  function cliVersion() {
4129
- return true ? "0.5.3" : "0.0.0-dev";
4276
+ return true ? "0.5.5" : "0.0.0-dev";
4130
4277
  }
4131
4278
  function helpText() {
4132
4279
  return [
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "costclaw",
3
- "version": "0.5.3",
3
+ "version": "0.5.5",
4
4
  "description": "Local cost and setup audit for Claude Code. Finds recoverable token spend and scores your setup across six pillars, with your prompts never leaving your machine.",
5
5
  "type": "module",
6
6
  "bin": {