costclaw 0.2.0 → 0.2.2

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 +122 -54
  2. package/dist/index.js +681 -129
  3. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,7 +1,13 @@
1
1
  #!/usr/bin/env node
2
2
 
3
+ // src/index.ts
4
+ import { pathToFileURL } from "url";
5
+
3
6
  // src/audit-command.ts
4
- import { readFile as readFile3 } from "fs/promises";
7
+ import { readFile as readFile2, writeFile } from "fs/promises";
8
+ import { join as join3, resolve } from "path";
9
+ import { homedir as homedir3 } from "os";
10
+ import { spawn } from "child_process";
5
11
 
6
12
  // ../../packages/engine/src/types.ts
7
13
  function emptyTotals() {
@@ -60,8 +66,8 @@ function isOpus(model) {
60
66
 
61
67
  // ../../packages/engine/src/sanitize.ts
62
68
  var EM_OR_EN = /[—–]/;
63
- function hasEmDash(text) {
64
- return EM_OR_EN.test(text);
69
+ function hasEmDash(text2) {
70
+ return EM_OR_EN.test(text2);
65
71
  }
66
72
  function sanitizeText(input) {
67
73
  let out = input;
@@ -127,7 +133,7 @@ function extractTools(content) {
127
133
  }
128
134
  return { names, events };
129
135
  }
130
- function parseSession(text, opts = {}) {
136
+ function parseSession(text2, opts = {}) {
131
137
  const s = {
132
138
  sessionUuid: null,
133
139
  projectSlug: null,
@@ -155,7 +161,7 @@ function parseSession(text, opts = {}) {
155
161
  const modelCounts = /* @__PURE__ */ new Map();
156
162
  let cwd = null;
157
163
  let seq = 0;
158
- for (const line of text.split("\n")) {
164
+ for (const line of text2.split("\n")) {
159
165
  if (!line.trim()) continue;
160
166
  const rec = safeParse(line);
161
167
  if (!rec) {
@@ -325,6 +331,7 @@ var MISROUTE_MIN_EXPOSURE = 0.5;
325
331
  var MISROUTE_BASELINE = "claude-sonnet-4-6";
326
332
  var WORKFLOW_MIN_COST = 5;
327
333
  var WORKFLOW_WARN_SHARE = 0.5;
334
+ var REDUNDANT_TARGET_MIN_FIRES = 10;
328
335
  function thirdHit(turns, lo, hi) {
329
336
  let read = 0;
330
337
  let total = 0;
@@ -418,6 +425,57 @@ function ruleHeavyToolLoops(ctx) {
418
425
  }
419
426
  return out;
420
427
  }
428
+ function targetNounFor(tool) {
429
+ if (["Bash", "PowerShell"].includes(tool)) return "command";
430
+ if (["WebFetch", "WebSearch"].includes(tool)) return "query";
431
+ if (tool === "Agent" || tool.startsWith("Task")) return "subagent";
432
+ return "file";
433
+ }
434
+ function ruleRedundantTargetThrash(ctx) {
435
+ const out = [];
436
+ for (const proj of ctx.projects) {
437
+ const byTool = /* @__PURE__ */ new Map();
438
+ for (const s of proj.sessions) {
439
+ if (s.kind !== "main") continue;
440
+ const counts = /* @__PURE__ */ new Map();
441
+ for (const e of s.toolEvents) {
442
+ if (e.target == null) continue;
443
+ const byTarget = counts.get(e.name) ?? /* @__PURE__ */ new Map();
444
+ byTarget.set(e.target, (byTarget.get(e.target) ?? 0) + 1);
445
+ counts.set(e.name, byTarget);
446
+ }
447
+ const perToolMax = /* @__PURE__ */ new Map();
448
+ for (const [tool, byTarget] of counts) {
449
+ for (const n of byTarget.values()) {
450
+ if (n < REDUNDANT_TARGET_MIN_FIRES) continue;
451
+ perToolMax.set(tool, Math.max(perToolMax.get(tool) ?? 0, n));
452
+ }
453
+ }
454
+ for (const [tool, n] of perToolMax) {
455
+ const entry = byTool.get(tool) ?? { sessionsAffected: 0, maxFires: 0, sessionUuids: [] };
456
+ entry.sessionsAffected += 1;
457
+ entry.maxFires = Math.max(entry.maxFires, n);
458
+ if (s.sessionUuid) entry.sessionUuids.push(s.sessionUuid);
459
+ byTool.set(tool, entry);
460
+ }
461
+ }
462
+ for (const [tool, e] of byTool) {
463
+ const n = e.sessionsAffected;
464
+ const noun = targetNounFor(tool);
465
+ out.push({
466
+ ruleId: "REDUNDANT_TARGET_THRASH",
467
+ severity: "warn",
468
+ project: proj.slug,
469
+ title: `Repeated ${tool} calls on the same ${noun} in ${n} session${n === 1 ? "" : "s"}`,
470
+ description: `${tool} hit the same ${noun} up to ${e.maxFires} times in a single session across ${n} session${n === 1 ? "" : "s"}, a sign of redundant repeated calls instead of new progress.`,
471
+ suggestedAction: `Cache or reuse the result instead of calling ${tool} again on the same ${noun}.`,
472
+ estimatedMonthlySavingsUsd: 0,
473
+ evidence: { tool, fires: e.maxFires, sessionsAffected: n, sessionUuids: e.sessionUuids }
474
+ });
475
+ }
476
+ }
477
+ return out;
478
+ }
421
479
  function ruleShortSessionBloat(ctx) {
422
480
  const out = [];
423
481
  for (const proj of ctx.projects) {
@@ -535,6 +593,7 @@ var RULES = [
535
593
  { id: "BAD_CACHE_HIT", run: ruleBadCacheHit },
536
594
  { id: "HOT_PROJECT", run: ruleHotProject },
537
595
  { id: "HEAVY_TOOL_LOOPS", run: ruleHeavyToolLoops },
596
+ { id: "REDUNDANT_TARGET_THRASH", run: ruleRedundantTargetThrash },
538
597
  { id: "SHORT_SESSION_BLOAT", run: ruleShortSessionBloat },
539
598
  { id: "MARATHON_SESSION", run: ruleMarathonSession },
540
599
  { id: "MODEL_MISROUTE", run: ruleModelMisroute },
@@ -619,8 +678,8 @@ function scoreStability(chars, volatileMarkers) {
619
678
  const per1k = volatileMarkers / chars * 1e3;
620
679
  return clamp(100 - per1k * 28);
621
680
  }
622
- function analyzeClaudeMd(text) {
623
- const raw = (text ?? "").trim();
681
+ function analyzeClaudeMd(text2) {
682
+ const raw = (text2 ?? "").trim();
624
683
  if (!raw) {
625
684
  return {
626
685
  present: false,
@@ -881,7 +940,7 @@ function buildChecks(report, cmd, answers, setup) {
881
940
  "claude_md",
882
941
  "Size",
883
942
  cmd.present ? cmd.sizeScore : null,
884
- cmd.present ? `Your CLAUDE.md is ${cmd.chars.toLocaleString()} characters, about ${cmd.estTokens.toLocaleString()} tokens loaded on every turn.` : "No CLAUDE.md was uploaded.",
943
+ cmd.present ? `Your CLAUDE.md is ${cmd.chars.toLocaleString()} characters, about ${cmd.estTokens.toLocaleString()} tokens loaded on every turn.` : "No CLAUDE.md was provided.",
885
944
  "claudemd"
886
945
  )
887
946
  );
@@ -891,7 +950,7 @@ function buildChecks(report, cmd, answers, setup) {
891
950
  "claude_md",
892
951
  "Structure",
893
952
  cmd.present ? cmd.structureScore : null,
894
- cmd.present ? `${cmd.headings} heading${cmd.headings === 1 ? "" : "s"} and ${cmd.bullets} bullet point${cmd.bullets === 1 ? "" : "s"} across ${cmd.chars.toLocaleString()} characters.` : "No CLAUDE.md was uploaded.",
953
+ cmd.present ? `${cmd.headings} heading${cmd.headings === 1 ? "" : "s"} and ${cmd.bullets} bullet point${cmd.bullets === 1 ? "" : "s"} across ${cmd.chars.toLocaleString()} characters.` : "No CLAUDE.md was provided.",
895
954
  "claudemd"
896
955
  )
897
956
  );
@@ -901,7 +960,7 @@ function buildChecks(report, cmd, answers, setup) {
901
960
  "claude_md",
902
961
  "Cache stability",
903
962
  cmd.present ? cmd.stabilityScore : null,
904
- cmd.present ? `${cmd.volatileMarkers} volatile marker${cmd.volatileMarkers === 1 ? "" : "s"} (dates, TODOs, "updated" notes) that change between sessions and reset the cache.` : "No CLAUDE.md was uploaded.",
963
+ cmd.present ? `${cmd.volatileMarkers} volatile marker${cmd.volatileMarkers === 1 ? "" : "s"} (dates, TODOs, "updated" notes) that change between sessions and reset the cache.` : "No CLAUDE.md was provided.",
905
964
  "claudemd"
906
965
  )
907
966
  );
@@ -935,7 +994,7 @@ function buildChecks(report, cmd, answers, setup) {
935
994
  checks.push(questionnaireCheck("clear_between", "Clearing between tasks", answers));
936
995
  checks.push(questionnaireCheck("plan_first", "Planning first", answers));
937
996
  checks.push(questionnaireCheck("success_criteria", "Self-verification", answers));
938
- const heavyLoops = report.findings.filter((f) => f.ruleId === "HEAVY_TOOL_LOOPS");
997
+ const heavyLoops = report.findings.filter((f) => f.ruleId === "HEAVY_TOOL_LOOPS" || f.ruleId === "REDUNDANT_TARGET_THRASH");
939
998
  const thrashSessions = new Set(
940
999
  heavyLoops.flatMap((f) => {
941
1000
  const uuids = f.evidence?.["sessionUuids"];
@@ -950,7 +1009,7 @@ function buildChecks(report, cmd, answers, setup) {
950
1009
  "prompting",
951
1010
  "Tool looping",
952
1011
  s.sessionsCount > 0 ? clamp2(100 - thrashShare * 180) : null,
953
- s.sessionsCount === 0 ? "No sessions to assess." : thrashSessions === 0 ? "No single tool fired 100 or more times in a session." : `${thrashSessions} of ${s.sessionsCount} sessions (${thrashPct}%) fired one tool 100 or more times.`,
1012
+ s.sessionsCount === 0 ? "No sessions to assess." : thrashSessions === 0 ? "No sign of a stuck tool loop." : `${thrashSessions} of ${s.sessionsCount} sessions (${thrashPct}%) showed heavy tool repetition: one tool firing 100 or more times, or the same file, command, or target hit 10 or more times.`,
954
1013
  "metrics"
955
1014
  )
956
1015
  );
@@ -1161,7 +1220,7 @@ function synthesize(report, pillars, cmd) {
1161
1220
  const fixes = [];
1162
1221
  const covered = /* @__PURE__ */ new Set();
1163
1222
  const round22 = (n) => Math.round(n * 100) / 100;
1164
- const usd4 = (n) => {
1223
+ const usd6 = (n) => {
1165
1224
  const fixed = round22(n).toFixed(2);
1166
1225
  const dot = fixed.indexOf(".");
1167
1226
  const whole = fixed.slice(0, dot).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
@@ -1189,7 +1248,7 @@ function synthesize(report, pillars, cmd) {
1189
1248
  severity: sevForUsd(exposure),
1190
1249
  wasteUsd: round22(exposure),
1191
1250
  problem: sanitizeText(
1192
- `Up to ${usd4(exposure)} of input spend was paid at full price instead of the cache-read rate. Biggest contributors: ${worst.length ? worst.join(", ") : "your largest projects"}.`
1251
+ `Up to ${usd6(exposure)} of input spend was paid at full price instead of the cache-read rate. Biggest contributors: ${worst.length ? worst.join(", ") : "your largest projects"}.`
1193
1252
  ),
1194
1253
  action: sanitizeText(
1195
1254
  "Keep the start of each session stable (a steady CLAUDE.md and consistent first reads) so the prompt cache is reused across turns and sessions."
@@ -1270,7 +1329,7 @@ function synthesize(report, pillars, cmd) {
1270
1329
  pillarName: PILLARS.cost_discipline.name,
1271
1330
  severity: sevForUsd(misrouteUsd),
1272
1331
  wasteUsd: round22(misrouteUsd),
1273
- problem: sanitizeText(`${n} short Opus ${sWord(n)} with light tool use and small output cost about ${usd4(misrouteUsd)} more than a cheaper model would have.`),
1332
+ problem: sanitizeText(`${n} short Opus ${sWord(n)} with light tool use and small output cost about ${usd6(misrouteUsd)} more than a cheaper model would have.`),
1274
1333
  action: sanitizeText("Route short, simple sessions to a cheaper model such as Sonnet, and reserve Opus for hard reasoning."),
1275
1334
  basis: sanitizeText("Opus session cost minus the same tokens re-priced at the Sonnet rate, summed over sessions that pass a conservative triviality gate.")
1276
1335
  });
@@ -1284,7 +1343,7 @@ function synthesize(report, pillars, cmd) {
1284
1343
  pillarName: PILLARS.session_mgmt.name,
1285
1344
  severity: sevForUsd(marathonUsd),
1286
1345
  wasteUsd: round22(marathonUsd),
1287
- problem: sanitizeText(`${n} long ${sWord(n)} kept growing until the prompt cache stopped helping, re-paying about ${usd4(marathonUsd)} for context in the later turns.`),
1346
+ problem: sanitizeText(`${n} long ${sWord(n)} kept growing until the prompt cache stopped helping, re-paying about ${usd6(marathonUsd)} for context in the later turns.`),
1288
1347
  action: sanitizeText("Compact or start a fresh session between tasks so the context stays small and the cache keeps working."),
1289
1348
  basis: sanitizeText("Recoverable estimate from the late-session cache shortfall versus the early-session hit rate.")
1290
1349
  });
@@ -1297,7 +1356,7 @@ function synthesize(report, pillars, cmd) {
1297
1356
  pillarName: PILLARS.cost_discipline.name,
1298
1357
  severity: "info",
1299
1358
  wasteUsd: 0,
1300
- problem: sanitizeText(`Workflow and subagent runs cost about ${usd4(workflowUsd)}; they are a power tool that can quietly dominate spend.`),
1359
+ problem: sanitizeText(`Workflow and subagent runs cost about ${usd6(workflowUsd)}; they are a power tool that can quietly dominate spend.`),
1301
1360
  action: sanitizeText("Scope workflows to genuinely large tasks and budget the agent count; a single high-effort prompt often suffices."),
1302
1361
  basis: sanitizeText("Summed cost of delegated subagent and workflow sub-logs.")
1303
1362
  });
@@ -1344,8 +1403,8 @@ function usd(n) {
1344
1403
  const grouped = whole.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
1345
1404
  return `${neg ? "-" : ""}$${grouped}${cents}`;
1346
1405
  }
1347
- function clean(text) {
1348
- return sanitizeText(text);
1406
+ function clean(text2) {
1407
+ return sanitizeText(text2);
1349
1408
  }
1350
1409
  function weakCostDiscipline(scores) {
1351
1410
  const p = scores.find((s) => s.id === "cost_discipline");
@@ -1819,7 +1878,7 @@ function toUsageMetrics(report) {
1819
1878
  cacheHitRate: round4(cacheHitRate(sess.totals))
1820
1879
  }));
1821
1880
  const modelBreakdown = {};
1822
- for (const [model, usd4] of Object.entries(s.modelBreakdown)) modelBreakdown[model] = round2(usd4);
1881
+ for (const [model, usd6] of Object.entries(s.modelBreakdown)) modelBreakdown[model] = round2(usd6);
1823
1882
  return {
1824
1883
  spendUsd: round2(s.cost_usd),
1825
1884
  cacheSavingsUsd: round2(s.cache_savings_usd),
@@ -1857,6 +1916,7 @@ function buildAudit(input, opts = {}) {
1857
1916
  const { headlineWasteUsd, headlineWasteLabel, fixes } = synthesize(report, pillars, cmd);
1858
1917
  const answered = Object.values(input.questionnaire).filter((v) => typeof v === "string" && v.length > 0).length;
1859
1918
  return {
1919
+ schemaVersion: "1",
1860
1920
  id: randomUUID(),
1861
1921
  createdAt: (/* @__PURE__ */ new Date()).toISOString(),
1862
1922
  contactEmail: input.contactEmail?.trim() || null,
@@ -1884,7 +1944,8 @@ var MAX_TOTAL_BYTES = 60 * 1024 * 1024;
1884
1944
  var MAX_CLAUDEMD_BYTES = 1 * 1024 * 1024;
1885
1945
 
1886
1946
  // src/read-sessions.ts
1887
- import { readdir, readFile } from "fs/promises";
1947
+ import { readdir } from "fs/promises";
1948
+ import { readFileSync, openSync, closeSync } from "fs";
1888
1949
  import { join, relative, sep } from "path";
1889
1950
  import { homedir } from "os";
1890
1951
  function defaultProjectsPath() {
@@ -1912,6 +1973,21 @@ function classify(rel) {
1912
1973
  if (parts.includes("workflows")) return { kind: "workflow", parentSessionId: parent };
1913
1974
  return { kind: "subagent", parentSessionId: parent };
1914
1975
  }
1976
+ function lazyLog(full, meta) {
1977
+ return {
1978
+ name: meta.name,
1979
+ kind: meta.kind,
1980
+ parentSessionId: meta.parentSessionId,
1981
+ projectSlug: meta.projectSlug,
1982
+ get text() {
1983
+ try {
1984
+ return readFileSync(full, "utf8");
1985
+ } catch {
1986
+ return "";
1987
+ }
1988
+ }
1989
+ };
1990
+ }
1915
1991
  async function readSessions(rootPath) {
1916
1992
  const logs = [];
1917
1993
  const skipped = [];
@@ -1936,8 +2012,8 @@ async function readSessions(rootPath) {
1936
2012
  const name = `${dir.name}/${rel}`;
1937
2013
  const { kind, parentSessionId } = classify(rel);
1938
2014
  try {
1939
- const text = await readFile(full, "utf8");
1940
- logs.push({ name, text, kind, parentSessionId, projectSlug: dir.name });
2015
+ closeSync(openSync(full, "r"));
2016
+ logs.push(lazyLog(full, { name, kind, parentSessionId, projectSlug: dir.name }));
1941
2017
  } catch {
1942
2018
  skipped.push(name);
1943
2019
  }
@@ -1955,16 +2031,56 @@ function bar(score, width = 20) {
1955
2031
  const filled = Math.round(score / 100 * width);
1956
2032
  return `[${"#".repeat(filled)}${".".repeat(width - filled)}] ${score}`;
1957
2033
  }
2034
+ function shortModel(id) {
2035
+ const m = /(opus|sonnet|haiku|fable)/i.exec(id);
2036
+ return m && m[1] ? m[1].toLowerCase() : id;
2037
+ }
2038
+ function modelMix(breakdown) {
2039
+ const merged = /* @__PURE__ */ new Map();
2040
+ for (const [model, spend] of Object.entries(breakdown)) {
2041
+ if (spend <= 0) continue;
2042
+ const key = shortModel(model);
2043
+ merged.set(key, (merged.get(key) ?? 0) + spend);
2044
+ }
2045
+ const total = [...merged.values()].reduce((a, b) => a + b, 0);
2046
+ if (total <= 0) return null;
2047
+ const parts = [...merged.entries()].sort((a, b) => b[1] - a[1]).map(([name, spend]) => [name, Math.round(spend / total * 100)]).filter(([, pct]) => pct >= 1).map(([name, pct]) => `${name} ${pct}%`);
2048
+ return parts.length > 0 ? parts.join(" / ") : null;
2049
+ }
2050
+ function unassessedLine(pillars) {
2051
+ const gaps = pillars.filter((p) => !p.assessed);
2052
+ if (gaps.length === 0) return null;
2053
+ const parts = gaps.map((p) => {
2054
+ const reason = p.checks[0]?.basis;
2055
+ const hint = p.id === "claude_md" ? " Pass --claude-md <file> to score it." : "";
2056
+ return reason ? `${p.name} (${reason}${hint})` : p.name;
2057
+ });
2058
+ return `Not yet scored: ${parts.join(" ")}`;
2059
+ }
1958
2060
  function formatAudit(record, meta) {
1959
2061
  const m = record.usageMetrics;
1960
2062
  const lines = [];
1961
2063
  lines.push("CostClaw audit");
1962
2064
  lines.push(`Source: ${meta.root} (${meta.sessionCount} sessions across ${m.projectsCount} projects)`);
2065
+ if (meta.claudeMdSource) lines.push(`CLAUDE.md: ${meta.claudeMdSource}`);
1963
2066
  lines.push("");
1964
2067
  lines.push(`${record.headlineWasteLabel}: ${usd2(record.headlineWasteUsd)}`);
1965
2068
  lines.push("");
1966
2069
  lines.push(`Spend analyzed: ${usd2(m.spendUsd)} Cache hit: ${(m.cacheHitRate * 100).toFixed(1)}% Active hours: ${m.durationHours.toFixed(1)}`);
1967
2070
  lines.push(`Pricing snapshot: ${m.pricingSnapshotDate}`);
2071
+ const mix = modelMix(m.modelBreakdown);
2072
+ if (mix) lines.push(`Model spend: ${mix}`);
2073
+ if (m.topProjects.length > 0) {
2074
+ lines.push("");
2075
+ lines.push("Top projects by spend:");
2076
+ for (const p of m.topProjects.slice(0, 5)) {
2077
+ const name = p.slug.length > 30 ? p.slug.slice(0, 27) + "..." : p.slug;
2078
+ const model = p.modelPrimary ? shortModel(p.modelPrimary) : "n/a";
2079
+ lines.push(
2080
+ ` ${name.padEnd(32)}${usd2(p.costUsd).padStart(10)} ${String(p.sessionsCount).padStart(4)} sessions cache ${(p.cacheHitRate * 100).toFixed(1)}% ${model}`
2081
+ );
2082
+ }
2083
+ }
1968
2084
  lines.push("");
1969
2085
  lines.push(`Overall setup score: ${record.overallScore} / 100 (${record.band.label})`);
1970
2086
  for (const p of record.pillarScores) {
@@ -1980,6 +2096,7 @@ function formatAudit(record, meta) {
1980
2096
  for (const f of dollarFixes.slice(0, 6)) {
1981
2097
  lines.push(` - [${usd2(f.wasteUsd)}] ${f.title}`);
1982
2098
  lines.push(` ${f.action}`);
2099
+ if (f.basis) lines.push(` Evidence: ${f.basis}`);
1983
2100
  }
1984
2101
  }
1985
2102
  if (otherIssues.length > 0) {
@@ -1987,6 +2104,7 @@ function formatAudit(record, meta) {
1987
2104
  lines.push("Other issues to tighten:");
1988
2105
  for (const f of otherIssues.slice(0, 6)) {
1989
2106
  lines.push(` - ${f.title}`);
2107
+ if (f.basis) lines.push(` ${f.basis}`);
1990
2108
  }
1991
2109
  if (otherIssues.length > 6) {
1992
2110
  lines.push(` ... and ${otherIssues.length - 6} more`);
@@ -1996,18 +2114,240 @@ function formatAudit(record, meta) {
1996
2114
  lines.push("");
1997
2115
  lines.push(`Note: ${meta.skipped.length} file(s) could not be read and were skipped.`);
1998
2116
  }
1999
- lines.push("");
2000
- lines.push("Tip: answer the hygiene questionnaire on the web for a fuller score. Nothing left your machine.");
2117
+ const gapLine = unassessedLine(record.pillarScores);
2118
+ if (gapLine) {
2119
+ lines.push("");
2120
+ lines.push(gapLine);
2121
+ }
2001
2122
  return lines.join("\n");
2002
2123
  }
2003
2124
 
2125
+ // src/svg.ts
2126
+ var SYSTEM_FONT = "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif";
2127
+ function esc(s) {
2128
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
2129
+ }
2130
+ function bandColorForScore(score) {
2131
+ if (score < 40) return "#c0392b";
2132
+ if (score < 60) return "#e07a5f";
2133
+ if (score < 75) return "#d99a2b";
2134
+ if (score < 90) return "#5f8f4f";
2135
+ return "#3f7d4e";
2136
+ }
2137
+ function rect(x, y, w, h, fill, rx = 0) {
2138
+ return `<rect x="${x}" y="${y}" width="${w}" height="${h}" rx="${rx}" fill="${fill}"></rect>`;
2139
+ }
2140
+ function text(x, y, s, opts = {}) {
2141
+ const size = opts.size ?? 13;
2142
+ const weight = opts.weight ?? 400;
2143
+ const fill = opts.fill ?? "#251d1a";
2144
+ const anchor = opts.anchor ?? "start";
2145
+ return `<text x="${x}" y="${y}" font-family="${SYSTEM_FONT}" font-size="${size}" font-weight="${weight}" fill="${fill}" text-anchor="${anchor}">${esc(s)}</text>`;
2146
+ }
2147
+ function estimateTextWidth(s, size) {
2148
+ return Math.round(s.length * size * 0.62);
2149
+ }
2150
+
2151
+ // src/html-report.ts
2152
+ function usd3(n) {
2153
+ return `$${(Math.round(n * 100) / 100).toFixed(2)}`;
2154
+ }
2155
+ function truncate(s, max) {
2156
+ return s.length > max ? s.slice(0, max - 3) + "..." : s;
2157
+ }
2158
+ function projectChart(projects) {
2159
+ if (projects.length === 0) {
2160
+ return `<p class="muted">No project spend to chart.</p>`;
2161
+ }
2162
+ const rowH = 30;
2163
+ const gap = 10;
2164
+ const labelW = 220;
2165
+ const barMax = 340;
2166
+ const valW = 96;
2167
+ const width = labelW + barMax + valW;
2168
+ const height = projects.length * (rowH + gap) - gap;
2169
+ const maxCost = Math.max(...projects.map((p) => p.costUsd), 0.01);
2170
+ const rows = projects.map((p, i) => {
2171
+ const y = i * (rowH + gap);
2172
+ const w = Math.max(3, Math.round(p.costUsd / maxCost * barMax));
2173
+ const mid = y + rowH / 2;
2174
+ const label = esc(truncate(p.slug, 32));
2175
+ return `<text x="0" y="${mid}" class="c-lbl" dominant-baseline="middle">${label}</text><rect x="${labelW}" y="${y + 3}" width="${w}" height="${rowH - 6}" rx="4" fill="#e07a5f"></rect><text x="${labelW + w + 8}" y="${mid}" class="c-val" dominant-baseline="middle">${esc(usd3(p.costUsd))}</text>`;
2176
+ }).join("");
2177
+ return `<svg viewBox="0 0 ${width} ${height}" width="100%" height="${height}" role="img" aria-label="Top projects by cost" preserveAspectRatio="xMinYMin meet">${rows}</svg>`;
2178
+ }
2179
+ function pillarBars(pillars) {
2180
+ return pillars.map((p) => {
2181
+ const name = esc(p.name);
2182
+ if (!p.assessed || p.score === null) {
2183
+ return `<div class="pillar"><span class="p-name">${name}</span><span class="p-track"><span class="p-fill p-na" style="width:100%"></span></span><span class="p-score muted">n/a</span></div>`;
2184
+ }
2185
+ const score = p.score;
2186
+ const color = bandColorForScore(score);
2187
+ return `<div class="pillar"><span class="p-name">${name}</span><span class="p-track"><span class="p-fill" style="width:${score}%;background:${color}"></span></span><span class="p-score">${score}</span></div>`;
2188
+ }).join("");
2189
+ }
2190
+ function dollarFixCard(f) {
2191
+ return `<li class="fix"><div class="fix-head"><span class="fix-amt">${esc(usd3(f.wasteUsd))}</span><span class="fix-title">${esc(f.title)}</span></div><p class="fix-problem">${esc(f.problem)}</p><p class="fix-action">${esc(f.action)}</p>` + (f.basis ? `<p class="fix-basis">${esc(f.basis)}</p>` : "") + `</li>`;
2192
+ }
2193
+ function otherFixCard(f) {
2194
+ return `<li class="fix other"><div class="fix-head"><span class="fix-title">${esc(f.title)}</span></div><p class="fix-action">${esc(f.action)}</p>` + (f.basis ? `<p class="fix-basis">${esc(f.basis)}</p>` : "") + `</li>`;
2195
+ }
2196
+ var STYLE = `
2197
+ :root { color-scheme: light; }
2198
+ * { box-sizing: border-box; }
2199
+ body {
2200
+ margin: 0;
2201
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
2202
+ color: #251d1a;
2203
+ background: #fefaf7;
2204
+ line-height: 1.5;
2205
+ }
2206
+ .wrap { max-width: 860px; margin: 0 auto; padding: 40px 24px 64px; }
2207
+ h1 { font-size: 28px; margin: 0 0 4px; letter-spacing: -0.01em; }
2208
+ h2 { font-size: 18px; margin: 40px 0 14px; color: #822d1d; }
2209
+ .sub { color: #7a6a63; font-size: 14px; margin: 0 0 8px; }
2210
+ .banner {
2211
+ margin: 28px 0 8px; padding: 22px 26px; border-radius: 14px;
2212
+ background: linear-gradient(135deg, #822d1d, #e07a5f); color: #fefaf7;
2213
+ box-shadow: 0 8px 24px rgba(130, 45, 29, 0.18);
2214
+ }
2215
+ .banner .label { font-size: 14px; text-transform: uppercase; letter-spacing: 0.08em; opacity: 0.9; }
2216
+ .banner .amount { font-size: 40px; font-weight: 700; margin-top: 4px; letter-spacing: -0.02em; }
2217
+ .stats { display: flex; flex-wrap: wrap; gap: 14px; margin: 18px 0 0; }
2218
+ .stat { flex: 1 1 150px; padding: 14px 16px; background: #fff; border: 1px solid #f0e2da; border-radius: 10px; }
2219
+ .stat .k { font-size: 12px; color: #7a6a63; text-transform: uppercase; letter-spacing: 0.05em; }
2220
+ .stat .v { font-size: 20px; font-weight: 600; margin-top: 2px; }
2221
+ .score-head { display: flex; align-items: baseline; gap: 12px; }
2222
+ .score-head .big { font-size: 30px; font-weight: 700; }
2223
+ .score-head .band { font-size: 15px; color: #822d1d; font-weight: 600; }
2224
+ .pillar { display: flex; align-items: center; gap: 12px; margin: 8px 0; }
2225
+ .p-name { flex: 0 0 190px; font-size: 14px; }
2226
+ .p-track { flex: 1; height: 14px; background: #f0e2da; border-radius: 7px; overflow: hidden; }
2227
+ .p-fill { display: block; height: 100%; border-radius: 7px; }
2228
+ .p-fill.p-na { background: repeating-linear-gradient(45deg, #ece0d8, #ece0d8 6px, #f5ece6 6px, #f5ece6 12px); }
2229
+ .p-score { flex: 0 0 40px; text-align: right; font-variant-numeric: tabular-nums; font-weight: 600; font-size: 14px; }
2230
+ .muted { color: #9a8a82; font-weight: 500; }
2231
+ .chart { background: #fff; border: 1px solid #f0e2da; border-radius: 12px; padding: 18px; overflow-x: auto; }
2232
+ .c-lbl { font-size: 13px; fill: #251d1a; }
2233
+ .c-val { font-size: 13px; fill: #822d1d; font-weight: 600; }
2234
+ ul.fixes { list-style: none; margin: 0; padding: 0; }
2235
+ .fix { background: #fff; border: 1px solid #f0e2da; border-left: 4px solid #e07a5f; border-radius: 10px; padding: 14px 18px; margin: 10px 0; }
2236
+ .fix.other { border-left-color: #cbb8ae; }
2237
+ .fix-head { display: flex; align-items: baseline; gap: 12px; }
2238
+ .fix-amt { font-size: 18px; font-weight: 700; color: #822d1d; font-variant-numeric: tabular-nums; }
2239
+ .fix-title { font-size: 15px; font-weight: 600; }
2240
+ .fix-problem { margin: 8px 0 4px; color: #5a4a43; font-size: 14px; }
2241
+ .fix-action { margin: 4px 0 0; font-size: 14px; }
2242
+ .fix-basis { margin: 6px 0 0; font-size: 13px; color: #9a8a82; }
2243
+ .stat .v-small { font-size: 14px; font-weight: 600; margin-top: 6px; }
2244
+ .footer { margin-top: 48px; padding-top: 18px; border-top: 1px solid #f0e2da; color: #7a6a63; font-size: 13px; }
2245
+ .footer strong { color: #251d1a; }
2246
+ `;
2247
+ function renderHtml(record, meta) {
2248
+ const m = record.usageMetrics;
2249
+ const mix = modelMix(m.modelBreakdown);
2250
+ const dollarFixes = record.fixes.filter((f) => f.wasteUsd > 0).sort((a, b) => b.wasteUsd - a.wasteUsd);
2251
+ const otherIssues = record.fixes.filter((f) => f.wasteUsd === 0);
2252
+ 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>`;
2253
+ const otherSection = otherIssues.length === 0 ? "" : `<h2>Other issues to tighten</h2><ul class="fixes">${otherIssues.map(otherFixCard).join("")}</ul>`;
2254
+ const skippedNote = meta.skipped.length > 0 ? `<p class="sub">Note: ${meta.skipped.length} file(s) could not be read and were skipped.</p>` : "";
2255
+ return `<!doctype html>
2256
+ <html lang="en">
2257
+ <head>
2258
+ <meta charset="utf-8" />
2259
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
2260
+ <title>CostClaw audit report</title>
2261
+ <style>${STYLE}</style>
2262
+ </head>
2263
+ <body>
2264
+ <div class="wrap">
2265
+ <h1>CostClaw audit</h1>
2266
+ <p class="sub">Source: ${esc(meta.root)} (${meta.sessionCount} sessions across ${m.projectsCount} projects)</p>
2267
+ ${meta.claudeMdSource ? `<p class="sub">CLAUDE.md: ${esc(meta.claudeMdSource)}</p>` : ""}
2268
+ <p class="sub">Pricing snapshot: ${esc(m.pricingSnapshotDate)}</p>
2269
+
2270
+ <div class="banner">
2271
+ <div class="label">${esc(record.headlineWasteLabel)}</div>
2272
+ <div class="amount">${esc(usd3(record.headlineWasteUsd))}</div>
2273
+ </div>
2274
+
2275
+ <div class="stats">
2276
+ <div class="stat"><div class="k">Spend analyzed</div><div class="v">${esc(usd3(m.spendUsd))}</div></div>
2277
+ <div class="stat"><div class="k">Cache hit rate</div><div class="v">${(m.cacheHitRate * 100).toFixed(1)}%</div></div>
2278
+ <div class="stat"><div class="k">Active hours</div><div class="v">${m.durationHours.toFixed(1)}</div></div>
2279
+ ${mix ? `<div class="stat"><div class="k">Model spend</div><div class="v v-small">${esc(mix)}</div></div>` : ""}
2280
+ </div>
2281
+
2282
+ <h2>Spend by project</h2>
2283
+ <div class="chart">${projectChart(m.topProjects)}</div>
2284
+
2285
+ <h2>Setup score</h2>
2286
+ <div class="score-head">
2287
+ <span class="big">${record.overallScore} / 100</span>
2288
+ <span class="band">${esc(record.band.label)}</span>
2289
+ </div>
2290
+ ${pillarBars(record.pillarScores)}
2291
+
2292
+ <h2>Top fixes by recoverable spend</h2>
2293
+ ${dollarSection}
2294
+ ${otherSection}
2295
+ ${skippedNote}
2296
+
2297
+ <div class="footer">
2298
+ <strong>This report was generated locally on your machine.</strong> Nothing was uploaded:
2299
+ your prompts, file contents, and paths never left this computer. Generated ${esc(record.createdAt)}.
2300
+ </div>
2301
+ </div>
2302
+ </body>
2303
+ </html>
2304
+ `;
2305
+ }
2306
+
2307
+ // src/card.ts
2308
+ var WIDTH = 600;
2309
+ var HEIGHT = 315;
2310
+ var INK = "#251d1a";
2311
+ var UMBER = "#822d1d";
2312
+ var PAPER = "#fefaf7";
2313
+ var BORDER = "#f0e2da";
2314
+ var MUTED = "#7a6a63";
2315
+ function usd4(n) {
2316
+ return `$${(Math.round(n * 100) / 100).toFixed(2)}`;
2317
+ }
2318
+ function strongestPillar(pillars) {
2319
+ const assessed = pillars.filter((p) => p.assessed && p.score !== null);
2320
+ if (assessed.length === 0) return null;
2321
+ return assessed.reduce((best, p) => p.score > best.score ? p : best);
2322
+ }
2323
+ function renderCard(record) {
2324
+ const scoreColor = bandColorForScore(record.overallScore);
2325
+ const strongest = strongestPillar(record.pillarScores);
2326
+ const strongestText = strongest ? `${strongest.name} (${strongest.score})` : "n/a";
2327
+ const cacheHitPct = `${(record.usageMetrics.cacheHitRate * 100).toFixed(1)}%`;
2328
+ const wasteText = usd4(record.headlineWasteUsd);
2329
+ const ariaLabel = `CostClaw score ${record.overallScore} of 100, ${record.band.label}`;
2330
+ const scoreText = String(record.overallScore);
2331
+ const scoreX = 32;
2332
+ const scoreW = estimateTextWidth(scoreText, 72);
2333
+ const outOf100X = scoreX + scoreW + 8;
2334
+ const pillLabel = record.band.label;
2335
+ const pillW = estimateTextWidth(pillLabel, 14) + 32;
2336
+ const pillY = 168;
2337
+ const pillH = 30;
2338
+ const statX = 32;
2339
+ const statY = 224;
2340
+ const statGap = 30;
2341
+ return `<svg xmlns="http://www.w3.org/2000/svg" width="${WIDTH}" height="${HEIGHT}" viewBox="0 0 ${WIDTH} ${HEIGHT}" role="img" aria-label="${esc(ariaLabel)}">` + rect(0, 0, WIDTH, HEIGHT, PAPER, 16) + `<rect x="0.5" y="0.5" width="${WIDTH - 1}" height="${HEIGHT - 1}" rx="16" fill="none" stroke="${BORDER}"></rect>` + text(32, 48, "CostClaw", { size: 22, weight: 700, fill: UMBER }) + text(scoreX, 150, scoreText, { size: 72, weight: 700, fill: INK }) + text(outOf100X, 150, "/ 100", { size: 22, weight: 600, fill: MUTED }) + rect(32, pillY, pillW, pillH, scoreColor, 15) + text(32 + pillW / 2, pillY + pillH / 2 + 5, pillLabel, { size: 14, weight: 700, fill: "#ffffff", anchor: "middle" }) + text(statX, statY, `Recoverable spend: ${wasteText}`, { size: 15, weight: 600, fill: INK }) + text(statX, statY + statGap, `Cache hit rate: ${cacheHitPct}`, { size: 15, weight: 600, fill: INK }) + text(statX, statY + statGap * 2, `Strongest pillar: ${strongestText}`, { size: 15, weight: 600, fill: INK }) + `</svg>`;
2342
+ }
2343
+
2004
2344
  // src/read-setup.ts
2005
- import { readFile as readFile2 } from "fs/promises";
2345
+ import { readFile } from "fs/promises";
2006
2346
  import { join as join2 } from "path";
2007
2347
  import { homedir as homedir2 } from "os";
2008
2348
  async function readJson(path) {
2009
2349
  try {
2010
- const parsed = JSON.parse(await readFile2(path, "utf8"));
2350
+ const parsed = JSON.parse(await readFile(path, "utf8"));
2011
2351
  return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
2012
2352
  } catch {
2013
2353
  return null;
@@ -2047,6 +2387,19 @@ async function readSetup(home = homedir2()) {
2047
2387
  }
2048
2388
 
2049
2389
  // src/audit-command.ts
2390
+ var DEFAULT_HTML_FILE = "costclaw-report.html";
2391
+ var DEFAULT_CARD_FILE = "costclaw-card.svg";
2392
+ function openInBrowser(target) {
2393
+ try {
2394
+ const platform = process.platform;
2395
+ const [cmd, args] = platform === "win32" ? ["cmd", ["/c", "start", "", target]] : platform === "darwin" ? ["open", [target]] : ["xdg-open", [target]];
2396
+ const child = spawn(cmd, args, { detached: true, stdio: "ignore" });
2397
+ child.on("error", () => {
2398
+ });
2399
+ child.unref();
2400
+ } catch {
2401
+ }
2402
+ }
2050
2403
  async function loadAuditInputs(opts) {
2051
2404
  const root = opts.path || defaultProjectsPath();
2052
2405
  const { logs, skipped } = await readSessions(root);
@@ -2054,26 +2407,58 @@ async function loadAuditInputs(opts) {
2054
2407
  throw new Error(`No .jsonl sessions found under ${root}. Set CLAUDE_PROJECTS_PATH or pass --path <dir>.`);
2055
2408
  }
2056
2409
  let claudeMd;
2410
+ let claudeMdSource = null;
2057
2411
  if (opts.claudeMdPath) {
2058
- claudeMd = await readFile3(opts.claudeMdPath, "utf8");
2412
+ claudeMd = await readFile2(opts.claudeMdPath, "utf8");
2413
+ claudeMdSource = resolve(opts.claudeMdPath);
2414
+ } else {
2415
+ const fallback = join3(opts.home ?? homedir3(), ".claude", "CLAUDE.md");
2416
+ try {
2417
+ claudeMd = await readFile2(fallback, "utf8");
2418
+ claudeMdSource = fallback;
2419
+ } catch {
2420
+ }
2059
2421
  }
2060
- return { logs, claudeMd, root, skipped };
2422
+ return { logs, claudeMd, claudeMdSource, root, skipped };
2061
2423
  }
2062
2424
  async function runAudit(opts) {
2063
- const { logs, claudeMd, root, skipped } = await loadAuditInputs(opts);
2425
+ const { logs, claudeMd, claudeMdSource, root, skipped } = await loadAuditInputs({
2426
+ path: opts.path,
2427
+ claudeMdPath: opts.claudeMdPath,
2428
+ home: opts.home
2429
+ });
2064
2430
  const setup = await readSetup();
2065
2431
  const record = buildAudit({ logs, claudeMd, questionnaire: {}, setup });
2066
- const output = opts.json ? JSON.stringify(record, null, 2) : formatAudit(record, { root, sessionCount: logs.length, skipped });
2432
+ let output = opts.json ? JSON.stringify(record, null, 2) : formatAudit(record, { root, sessionCount: logs.length, skipped, claudeMdSource });
2433
+ const notices = [];
2434
+ if (opts.html) {
2435
+ const target = resolve(opts.htmlPath || DEFAULT_HTML_FILE);
2436
+ const doc = renderHtml(record, { root, sessionCount: logs.length, skipped, claudeMdSource });
2437
+ await writeFile(target, doc, "utf8");
2438
+ openInBrowser(target);
2439
+ notices.push(`HTML report written to ${target}`);
2440
+ }
2441
+ if (opts.card) {
2442
+ const target = resolve(opts.cardPath || DEFAULT_CARD_FILE);
2443
+ const svg = renderCard(record);
2444
+ await writeFile(target, svg, "utf8");
2445
+ notices.push(`Score card written to ${target}`);
2446
+ }
2447
+ if (opts.json) {
2448
+ for (const notice of notices) process.stderr.write(notice + "\n");
2449
+ } else if (notices.length > 0) {
2450
+ output += "\n\n" + notices.join("\n\n");
2451
+ }
2067
2452
  return { output, record };
2068
2453
  }
2069
2454
 
2070
2455
  // src/optimize-command.ts
2071
- import { mkdir, writeFile, readFile as readFile5, stat as stat2 } from "fs/promises";
2072
- import { join as join4 } from "path";
2456
+ import { mkdir, writeFile as writeFile2, readFile as readFile4, stat as stat2 } from "fs/promises";
2457
+ import { join as join5, dirname } from "path";
2073
2458
 
2074
2459
  // src/project-scan.ts
2075
- import { readdir as readdir2, readFile as readFile4, stat } from "fs/promises";
2076
- import { join as join3, basename } from "path";
2460
+ import { readdir as readdir2, readFile as readFile3, stat } from "fs/promises";
2461
+ import { join as join4, basename } from "path";
2077
2462
  var NOISE_DIRS = /* @__PURE__ */ new Set([
2078
2463
  "node_modules",
2079
2464
  ".git",
@@ -2102,7 +2487,7 @@ var DIR_NOTES = {
2102
2487
  };
2103
2488
  async function readText(p) {
2104
2489
  try {
2105
- return await readFile4(p, "utf8");
2490
+ return await readFile3(p, "utf8");
2106
2491
  } catch {
2107
2492
  return null;
2108
2493
  }
@@ -2128,18 +2513,18 @@ async function listEntries(dir) {
2128
2513
  function pushUnique(arr, value) {
2129
2514
  if (!arr.includes(value)) arr.push(value);
2130
2515
  }
2131
- function parseJson(text) {
2132
- if (text === null) return null;
2516
+ function parseJson(text2) {
2517
+ if (text2 === null) return null;
2133
2518
  try {
2134
- const parsed = JSON.parse(text);
2519
+ const parsed = JSON.parse(text2);
2135
2520
  return parsed && typeof parsed === "object" ? parsed : null;
2136
2521
  } catch {
2137
2522
  return null;
2138
2523
  }
2139
2524
  }
2140
- function parseEnvNames(text) {
2525
+ function parseEnvNames(text2) {
2141
2526
  const names = [];
2142
- for (const raw of text.split(/\r?\n/)) {
2527
+ for (const raw of text2.split(/\r?\n/)) {
2143
2528
  const line = raw.trim();
2144
2529
  if (line === "" || line.startsWith("#")) continue;
2145
2530
  const eq = line.indexOf("=");
@@ -2213,7 +2598,7 @@ async function detectTestsLocation(dir, files, dirs) {
2213
2598
  if (dirs.includes("__tests__")) return "tests in __tests__/";
2214
2599
  if (files.some((f) => /\.(test|spec)\.[cm]?[jt]sx?$/.test(f))) return "tests alongside source (*.test.* / *.spec.*)";
2215
2600
  if (dirs.includes("src")) {
2216
- const sub = await listEntries(join3(dir, "src"));
2601
+ const sub = await listEntries(join4(dir, "src"));
2217
2602
  if (sub.files.some((f) => /\.(test|spec)\.[cm]?[jt]sx?$/.test(f))) {
2218
2603
  return "tests alongside source (*.test.* / *.spec.*)";
2219
2604
  }
@@ -2296,7 +2681,7 @@ async function scanNode(dir, files, dirs, pkg, profile) {
2296
2681
  if (oneFileCmd !== null && "test" in scripts) {
2297
2682
  profile.commands.push({ label: "test one file", command: oneFileCmd });
2298
2683
  }
2299
- const tsconfig = parseJson(await readText(join3(dir, "tsconfig.json")));
2684
+ const tsconfig = parseJson(await readText(join4(dir, "tsconfig.json")));
2300
2685
  if (tsconfig) {
2301
2686
  const co = tsconfig.compilerOptions;
2302
2687
  if (co && co.strict === true) pushUnique(profile.codeStyle, "TypeScript strict mode");
@@ -2318,7 +2703,7 @@ async function scanNode(dir, files, dirs, pkg, profile) {
2318
2703
  profile.preCommit = `run ${lintCmd} and ${typecheckCmd} before committing`;
2319
2704
  }
2320
2705
  }
2321
- function parsePyproject(text) {
2706
+ function parsePyproject(text2) {
2322
2707
  const tables = /* @__PURE__ */ new Set();
2323
2708
  let name = null;
2324
2709
  let description = null;
@@ -2331,7 +2716,7 @@ function parsePyproject(text) {
2331
2716
  const m = cleaned.match(/^[A-Za-z0-9_.\-]+/);
2332
2717
  if (m) pushUnique(deps, m[0].toLowerCase());
2333
2718
  };
2334
- for (const raw of text.split(/\r?\n/)) {
2719
+ for (const raw of text2.split(/\r?\n/)) {
2335
2720
  const line = raw.trim();
2336
2721
  if (line === "" || line.startsWith("#")) continue;
2337
2722
  const header = line.match(/^\[([^\]]+)\]$/);
@@ -2383,9 +2768,9 @@ var PY_STACK = {
2383
2768
  sqlalchemy: "SQLAlchemy",
2384
2769
  pydantic: "Pydantic"
2385
2770
  };
2386
- function pyDepsFromRequirements(text) {
2771
+ function pyDepsFromRequirements(text2) {
2387
2772
  const deps = [];
2388
- for (const raw of text.split(/\r?\n/)) {
2773
+ for (const raw of text2.split(/\r?\n/)) {
2389
2774
  const line = raw.trim();
2390
2775
  if (line === "" || line.startsWith("#") || line.startsWith("-")) continue;
2391
2776
  const m = line.match(/^[A-Za-z0-9_.\-]+/);
@@ -2399,7 +2784,7 @@ async function scanPython(dir, files, profile) {
2399
2784
  const deps = [];
2400
2785
  const tables = /* @__PURE__ */ new Set();
2401
2786
  let hasPoetry = false;
2402
- const pyprojectText = await readText(join3(dir, "pyproject.toml"));
2787
+ const pyprojectText = await readText(join4(dir, "pyproject.toml"));
2403
2788
  if (pyprojectText !== null) {
2404
2789
  const parsed = parsePyproject(pyprojectText);
2405
2790
  name = parsed.name;
@@ -2409,7 +2794,7 @@ async function scanPython(dir, files, profile) {
2409
2794
  hasPoetry = parsed.hasPoetry;
2410
2795
  }
2411
2796
  if (files.includes("requirements.txt")) {
2412
- const reqText = await readText(join3(dir, "requirements.txt"));
2797
+ const reqText = await readText(join4(dir, "requirements.txt"));
2413
2798
  if (reqText !== null) for (const d of pyDepsFromRequirements(reqText)) pushUnique(deps, d);
2414
2799
  }
2415
2800
  if (name !== null && name.trim() !== "") profile.name = name;
@@ -2443,12 +2828,12 @@ async function scanPython(dir, files, profile) {
2443
2828
  }
2444
2829
  }
2445
2830
  async function scanRust(dir, profile) {
2446
- const text = await readText(join3(dir, "Cargo.toml"));
2831
+ const text2 = await readText(join4(dir, "Cargo.toml"));
2447
2832
  pushUnique(profile.stack, "Rust");
2448
2833
  profile.packageManager = "cargo";
2449
- if (text !== null) {
2834
+ if (text2 !== null) {
2450
2835
  let section = "";
2451
- for (const raw of text.split(/\r?\n/)) {
2836
+ for (const raw of text2.split(/\r?\n/)) {
2452
2837
  const line = raw.trim();
2453
2838
  const header = line.match(/^\[([^\]]+)\]$/);
2454
2839
  if (header) {
@@ -2469,11 +2854,11 @@ async function scanRust(dir, profile) {
2469
2854
  profile.commands.push({ label: "lint", command: "cargo clippy" });
2470
2855
  }
2471
2856
  async function scanGo(dir, profile) {
2472
- const text = await readText(join3(dir, "go.mod"));
2857
+ const text2 = await readText(join4(dir, "go.mod"));
2473
2858
  pushUnique(profile.stack, "Go");
2474
2859
  profile.packageManager = "go";
2475
- if (text !== null) {
2476
- const m = text.match(/^module\s+(\S+)/m);
2860
+ if (text2 !== null) {
2861
+ const m = text2.match(/^module\s+(\S+)/m);
2477
2862
  if (m) {
2478
2863
  const mod = m[1];
2479
2864
  profile.name = mod.includes("/") ? mod.slice(mod.lastIndexOf("/") + 1) : mod;
@@ -2483,9 +2868,9 @@ async function scanGo(dir, profile) {
2483
2868
  profile.commands.push({ label: "test", command: "go test ./..." });
2484
2869
  profile.commands.push({ label: "lint", command: "go vet ./..." });
2485
2870
  }
2486
- function parseMakefile(text) {
2871
+ function parseMakefile(text2) {
2487
2872
  const targets = [];
2488
- for (const raw of text.split(/\r?\n/)) {
2873
+ for (const raw of text2.split(/\r?\n/)) {
2489
2874
  if (/^\t/.test(raw)) continue;
2490
2875
  const m = raw.match(/^([A-Za-z0-9_.\-]+)\s*:(?!=)/);
2491
2876
  if (m) {
@@ -2495,8 +2880,8 @@ function parseMakefile(text) {
2495
2880
  }
2496
2881
  return targets;
2497
2882
  }
2498
- function parseReadme(text) {
2499
- const lines = text.split(/\r?\n/);
2883
+ function parseReadme(text2) {
2884
+ const lines = text2.split(/\r?\n/);
2500
2885
  let name = null;
2501
2886
  let i = 0;
2502
2887
  for (; i < lines.length; i++) {
@@ -2534,7 +2919,7 @@ async function scanProject(dir) {
2534
2919
  const profile = emptyProfile(basename(dir));
2535
2920
  const { files, dirs } = await listEntries(dir);
2536
2921
  if (files.includes("package.json")) {
2537
- const pkg = parseJson(await readText(join3(dir, "package.json")));
2922
+ const pkg = parseJson(await readText(join4(dir, "package.json")));
2538
2923
  if (pkg) await scanNode(dir, files, dirs, pkg, profile);
2539
2924
  }
2540
2925
  if (files.includes("pyproject.toml") || files.includes("requirements.txt") || files.includes("setup.py")) {
@@ -2547,9 +2932,9 @@ async function scanProject(dir) {
2547
2932
  await scanGo(dir, profile);
2548
2933
  }
2549
2934
  if (files.includes("Makefile") && profile.commands.length === 0) {
2550
- const text = await readText(join3(dir, "Makefile"));
2551
- if (text !== null) {
2552
- for (const t of parseMakefile(text)) {
2935
+ const text2 = await readText(join4(dir, "Makefile"));
2936
+ if (text2 !== null) {
2937
+ for (const t of parseMakefile(text2)) {
2553
2938
  profile.commands.push({ label: t, command: `make ${t}` });
2554
2939
  }
2555
2940
  }
@@ -2557,9 +2942,9 @@ async function scanProject(dir) {
2557
2942
  if (profile.description === null || profile.name === basename(dir)) {
2558
2943
  const readmeName = files.find((f) => /^readme(\.md|\.markdown|\.txt)?$/i.test(f));
2559
2944
  if (readmeName) {
2560
- const text = await readText(join3(dir, readmeName));
2561
- if (text !== null) {
2562
- const parsed = parseReadme(text);
2945
+ const text2 = await readText(join4(dir, readmeName));
2946
+ if (text2 !== null) {
2947
+ const parsed = parseReadme(text2);
2563
2948
  if (profile.name === basename(dir) && parsed.name !== null) profile.name = parsed.name;
2564
2949
  if (profile.description === null && parsed.description !== null) {
2565
2950
  profile.description = parsed.description;
@@ -2570,8 +2955,8 @@ async function scanProject(dir) {
2570
2955
  profile.structure = await detectStructure(dir, dirs);
2571
2956
  const envFile = files.includes(".env.example") ? ".env.example" : files.includes(".env.sample") ? ".env.sample" : null;
2572
2957
  if (envFile) {
2573
- const text = await readText(join3(dir, envFile));
2574
- if (text !== null) profile.envVars = parseEnvNames(text);
2958
+ const text2 = await readText(join4(dir, envFile));
2959
+ if (text2 !== null) profile.envVars = parseEnvNames(text2);
2575
2960
  }
2576
2961
  return profile;
2577
2962
  }
@@ -2580,7 +2965,7 @@ async function scanProject(dir) {
2580
2965
  var OPTIMIZED_NAME = "CLAUDE.optimized.md";
2581
2966
  var PLAYBOOK_NAME = "PLAYBOOK.md";
2582
2967
  var SETTINGS_NAME = "settings.suggested.json";
2583
- function usd3(n) {
2968
+ function usd5(n) {
2584
2969
  return `$${(Math.round(n * 100) / 100).toFixed(2)}`;
2585
2970
  }
2586
2971
  function describeDetection(project) {
@@ -2613,6 +2998,78 @@ function lineDiff(oldText, newText) {
2613
2998
  if (lines.length === 0) lines.push(" (no line-level changes)");
2614
2999
  return lines.join("\n");
2615
3000
  }
3001
+ function asStringArray(value) {
3002
+ return Array.isArray(value) ? value.filter((v) => typeof v === "string") : [];
3003
+ }
3004
+ function unionStrings(existing, additions) {
3005
+ const out = [];
3006
+ const seen = /* @__PURE__ */ new Set();
3007
+ for (const v of existing) {
3008
+ if (!seen.has(v)) {
3009
+ seen.add(v);
3010
+ out.push(v);
3011
+ }
3012
+ }
3013
+ for (const v of additions) {
3014
+ if (!seen.has(v)) {
3015
+ seen.add(v);
3016
+ out.push(v);
3017
+ }
3018
+ }
3019
+ return out;
3020
+ }
3021
+ function isPlainObject(value) {
3022
+ return typeof value === "object" && value !== null && !Array.isArray(value);
3023
+ }
3024
+ async function applyDerivedSettings(target, suggestedJson, force) {
3025
+ const backup = `${target}.bak`;
3026
+ if (await pathExists(backup) && !force) {
3027
+ throw new Error(
3028
+ `A backup already exists at ${backup}. Refusing to overwrite it. Pass --force to replace the existing backup.`
3029
+ );
3030
+ }
3031
+ let existingText = "";
3032
+ let existing = {};
3033
+ if (await pathExists(target)) {
3034
+ existingText = await readFile4(target, "utf8");
3035
+ if (existingText.trim() !== "") {
3036
+ let parsed;
3037
+ try {
3038
+ parsed = JSON.parse(existingText);
3039
+ } catch {
3040
+ throw new Error(
3041
+ `Could not parse ${target} as JSON, so it was left untouched. If it contains comments or trailing commas (JSONC), remove them, or point --apply-settings at a plain JSON file.`
3042
+ );
3043
+ }
3044
+ if (!isPlainObject(parsed)) {
3045
+ throw new Error(
3046
+ `Expected ${target} to hold a JSON object, so it was left untouched. --apply-settings only merges into an object settings file.`
3047
+ );
3048
+ }
3049
+ existing = parsed;
3050
+ }
3051
+ }
3052
+ const suggested = JSON.parse(suggestedJson);
3053
+ const suggestedAllow = asStringArray(suggested.permissions?.allow);
3054
+ const suggestedDeny = asStringArray(suggested.permissions?.deny);
3055
+ const existingPerms = isPlainObject(existing.permissions) ? existing.permissions : {};
3056
+ const mergedPerms = { ...existingPerms };
3057
+ mergedPerms.allow = unionStrings(asStringArray(existingPerms.allow), suggestedAllow);
3058
+ mergedPerms.deny = unionStrings(asStringArray(existingPerms.deny), suggestedDeny);
3059
+ const merged = { ...existing, permissions: mergedPerms };
3060
+ const mergedText = JSON.stringify(merged, null, 2) + "\n";
3061
+ await mkdir(dirname(target), { recursive: true });
3062
+ await writeFile2(backup, existingText, "utf8");
3063
+ await writeFile2(target, mergedText, "utf8");
3064
+ return [
3065
+ `Merged the derived permission allowlist into ${target}`,
3066
+ `Backed up the previous file to ${backup}`,
3067
+ "Only permissions.allow and permissions.deny changed (deduped union, existing entries kept and ordered first). Every other key was left as it was.",
3068
+ "",
3069
+ "Diff (previous vs merged):",
3070
+ lineDiff(existingText, mergedText)
3071
+ ];
3072
+ }
2616
3073
  async function runOptimize(opts) {
2617
3074
  const { logs, claudeMd } = await loadAuditInputs({ path: opts.path, claudeMdPath: opts.claudeMdPath });
2618
3075
  const report = analyzeUploads(logs);
@@ -2623,12 +3080,12 @@ async function runOptimize(opts) {
2623
3080
  const project = await scanProject(projectDir);
2624
3081
  const result = optimize({ report, scores: pillars, fixes, currentClaudeMd: claudeMd, project });
2625
3082
  const recoverable = cacheMissExposureUsd(report);
2626
- const outDir = opts.out || join4(process.cwd(), "costclaw-out");
3083
+ const outDir = opts.out || join5(process.cwd(), "costclaw-out");
2627
3084
  await mkdir(outDir, { recursive: true });
2628
- const playbookPath = join4(outDir, PLAYBOOK_NAME);
2629
- await writeFile(playbookPath, result.playbook, "utf8");
2630
- const settingsPath = join4(outDir, SETTINGS_NAME);
2631
- await writeFile(settingsPath, result.settingsJson, "utf8");
3085
+ const playbookPath = join5(outDir, PLAYBOOK_NAME);
3086
+ await writeFile2(playbookPath, result.playbook, "utf8");
3087
+ const settingsPath = join5(outDir, SETTINGS_NAME);
3088
+ await writeFile2(settingsPath, result.settingsJson, "utf8");
2632
3089
  const lines = [];
2633
3090
  lines.push("CostClaw optimize");
2634
3091
  lines.push("");
@@ -2642,10 +3099,10 @@ async function runOptimize(opts) {
2642
3099
  }
2643
3100
  let original = "";
2644
3101
  if (await pathExists(target)) {
2645
- original = await readFile5(target, "utf8");
3102
+ original = await readFile4(target, "utf8");
2646
3103
  }
2647
- await writeFile(backup, original, "utf8");
2648
- await writeFile(target, result.optimizedClaudeMd, "utf8");
3104
+ await writeFile2(backup, original, "utf8");
3105
+ await writeFile2(target, result.optimizedClaudeMd, "utf8");
2649
3106
  lines.push(`Backed up the original to ${backup}`);
2650
3107
  lines.push(`Wrote the optimized CLAUDE.md to ${target}`);
2651
3108
  lines.push(`Wrote the playbook to ${playbookPath}`);
@@ -2657,20 +3114,27 @@ async function runOptimize(opts) {
2657
3114
  lines.push("Warning: this scaffold has placeholders to fill in. Search it for <!-- ... --> and replace each with your project's real details.");
2658
3115
  lines.push("A suggested settings.json was written to the out dir for review; it is not applied in place.");
2659
3116
  } else {
2660
- const optimizedPath = join4(outDir, OPTIMIZED_NAME);
2661
- await writeFile(optimizedPath, result.optimizedClaudeMd, "utf8");
3117
+ const optimizedPath = join5(outDir, OPTIMIZED_NAME);
3118
+ await writeFile2(optimizedPath, result.optimizedClaudeMd, "utf8");
2662
3119
  lines.push("Dry run (no files of yours were changed).");
2663
3120
  lines.push(`Wrote the optimized CLAUDE.md scaffold to ${optimizedPath}`);
2664
3121
  lines.push(`Wrote the playbook to ${playbookPath}`);
2665
3122
  lines.push(`Wrote a suggested settings.json to ${settingsPath}`);
2666
3123
  lines.push("");
2667
3124
  lines.push(describeDetection(project));
2668
- lines.push(`Recoverable spend (cache-miss exposure): ${usd3(recoverable)}`);
3125
+ lines.push(`Recoverable spend (cache-miss exposure): ${usd5(recoverable)}`);
2669
3126
  lines.push("");
2670
3127
  lines.push("The optimized CLAUDE.md is a scaffold: it has placeholders to fill in.");
2671
3128
  lines.push("Search it for <!-- ... --> and replace each with your project's real details.");
2672
3129
  lines.push("To apply it in place (with a backup and a diff first), rerun with --write <your-CLAUDE.md>.");
2673
- 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 for you.");
3130
+ 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.");
3131
+ 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.");
3132
+ }
3133
+ if (opts.applySettings) {
3134
+ const target = opts.applySettingsPath || join5(projectDir, ".claude", "settings.json");
3135
+ const applyLines = await applyDerivedSettings(target, result.settingsJson, opts.force ?? false);
3136
+ lines.push("");
3137
+ lines.push(...applyLines);
2674
3138
  }
2675
3139
  if (result.notes.length > 0) {
2676
3140
  lines.push("");
@@ -2682,10 +3146,41 @@ async function runOptimize(opts) {
2682
3146
  return { output: lines.join("\n") };
2683
3147
  }
2684
3148
 
3149
+ // src/badge-command.ts
3150
+ import { writeFile as writeFile3 } from "fs/promises";
3151
+ import { resolve as resolve2 } from "path";
3152
+
3153
+ // src/badge.ts
3154
+ var HEIGHT2 = 20;
3155
+ var FONT_SIZE = 11;
3156
+ var PAD_X = 8;
3157
+ var LEFT_LABEL = "costclaw";
3158
+ var LEFT_COLOR = "#822d1d";
3159
+ var CLIP_ID = "costclaw-badge-round";
3160
+ function renderBadge(record) {
3161
+ const scoreLabel = `${record.overallScore}/100`;
3162
+ const leftW = estimateTextWidth(LEFT_LABEL, FONT_SIZE) + PAD_X * 2;
3163
+ const rightW = estimateTextWidth(scoreLabel, FONT_SIZE) + PAD_X * 2;
3164
+ const width = leftW + rightW;
3165
+ const rightColor = bandColorForScore(record.overallScore);
3166
+ const ariaLabel = `costclaw score: ${scoreLabel} (${record.band.label})`;
3167
+ return `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${HEIGHT2}" viewBox="0 0 ${width} ${HEIGHT2}" role="img" aria-label="${esc(ariaLabel)}"><clipPath id="${CLIP_ID}">${rect(0, 0, width, HEIGHT2, "#ffffff", 3)}</clipPath><g clip-path="url(#${CLIP_ID})">` + rect(0, 0, leftW, HEIGHT2, LEFT_COLOR) + rect(leftW, 0, rightW, HEIGHT2, rightColor) + `</g>` + text(leftW / 2, 14, LEFT_LABEL, { size: FONT_SIZE, weight: 600, fill: "#fefaf7", anchor: "middle" }) + text(leftW + rightW / 2, 14, scoreLabel, { size: FONT_SIZE, weight: 700, fill: "#ffffff", anchor: "middle" }) + `</svg>`;
3168
+ }
3169
+
3170
+ // src/badge-command.ts
3171
+ var DEFAULT_BADGE_FILE = "costclaw-badge.svg";
3172
+ async function runBadge(opts) {
3173
+ const { record } = await runAudit({ path: opts.path, claudeMdPath: opts.claudeMdPath });
3174
+ const svg = renderBadge(record);
3175
+ const target = resolve2(opts.out || DEFAULT_BADGE_FILE);
3176
+ await writeFile3(target, svg, "utf8");
3177
+ return { output: `Badge written to ${target}`, record, target };
3178
+ }
3179
+
2685
3180
  // src/license.ts
2686
- import { mkdir as mkdir2, readFile as readFile6, writeFile as writeFile2, rm } from "fs/promises";
2687
- import { join as join5 } from "path";
2688
- import { homedir as homedir3, hostname } from "os";
3181
+ import { mkdir as mkdir2, readFile as readFile5, writeFile as writeFile4, rm } from "fs/promises";
3182
+ import { join as join6 } from "path";
3183
+ import { homedir as homedir4, hostname } from "os";
2689
3184
  import { createPublicKey, verify as cryptoVerify } from "crypto";
2690
3185
  var LICENSE_PRODUCT = "costclaw-optimize";
2691
3186
  var DEFAULT_PUBLIC_KEY_PEM = `-----BEGIN PUBLIC KEY-----
@@ -2710,10 +3205,10 @@ var INVALID_MESSAGE = [
2710
3205
  "costclaw audit stays free."
2711
3206
  ].join("\n");
2712
3207
  function defaultConfigDir() {
2713
- return join5(homedir3(), ".costclaw");
3208
+ return join6(homedir4(), ".costclaw");
2714
3209
  }
2715
3210
  function licenseFile(dir) {
2716
- return join5(dir, "license.json");
3211
+ return join6(dir, "license.json");
2717
3212
  }
2718
3213
  function base64UrlDecode(part) {
2719
3214
  return Buffer.from(part.replace(/-/g, "+").replace(/_/g, "/"), "base64");
@@ -2722,6 +3217,7 @@ function verifyLicenseKey(licenseKey, publicKeyPem = DEFAULT_PUBLIC_KEY_PEM) {
2722
3217
  const parts = licenseKey.trim().split(".");
2723
3218
  if (parts.length !== 3 || parts[0] !== KEY_PREFIX) return null;
2724
3219
  const [prefix, payloadPart, signaturePart] = parts;
3220
+ if (prefix === void 0 || payloadPart === void 0 || signaturePart === void 0) return null;
2725
3221
  try {
2726
3222
  const publicKey = createPublicKey(publicKeyPem);
2727
3223
  const signed = Buffer.from(`${prefix}.${payloadPart}`, "utf8");
@@ -2736,7 +3232,7 @@ function verifyLicenseKey(licenseKey, publicKeyPem = DEFAULT_PUBLIC_KEY_PEM) {
2736
3232
  }
2737
3233
  async function readStoredLicense(dir) {
2738
3234
  try {
2739
- const data = JSON.parse(await readFile6(licenseFile(dir), "utf8"));
3235
+ const data = JSON.parse(await readFile5(licenseFile(dir), "utf8"));
2740
3236
  if (!data || typeof data.licenseKey !== "string") return null;
2741
3237
  return data;
2742
3238
  } catch {
@@ -2745,7 +3241,7 @@ async function readStoredLicense(dir) {
2745
3241
  }
2746
3242
  async function writeStoredLicense(dir, lic) {
2747
3243
  await mkdir2(dir, { recursive: true });
2748
- await writeFile2(licenseFile(dir), JSON.stringify(lic, null, 2) + "\n", "utf8");
3244
+ await writeFile4(licenseFile(dir), JSON.stringify(lic, null, 2) + "\n", "utf8");
2749
3245
  }
2750
3246
  async function clearStoredLicense(dir) {
2751
3247
  await rm(licenseFile(dir), { force: true });
@@ -2797,14 +3293,89 @@ function getFlag(args, name) {
2797
3293
  const i = args.indexOf(name);
2798
3294
  return i >= 0 && i + 1 < args.length ? args[i + 1] : void 0;
2799
3295
  }
3296
+ function optionalPathAfter(args, flag) {
3297
+ const i = args.indexOf(flag);
3298
+ if (i < 0) return void 0;
3299
+ const next = args[i + 1];
3300
+ return next !== void 0 && !next.startsWith("-") ? next : void 0;
3301
+ }
3302
+ function parseAuditFlags(args) {
3303
+ const html = args.includes("--html");
3304
+ const card = args.includes("--card");
3305
+ return {
3306
+ path: getFlag(args, "--path"),
3307
+ claudeMdPath: getFlag(args, "--claude-md"),
3308
+ json: args.includes("--json"),
3309
+ html,
3310
+ htmlPath: html ? optionalPathAfter(args, "--html") : void 0,
3311
+ card,
3312
+ cardPath: card ? optionalPathAfter(args, "--card") : void 0
3313
+ };
3314
+ }
3315
+ function parseBadgeFlags(args) {
3316
+ return {
3317
+ path: getFlag(args, "--path"),
3318
+ claudeMdPath: getFlag(args, "--claude-md"),
3319
+ out: getFlag(args, "--out")
3320
+ };
3321
+ }
3322
+ function cliVersion() {
3323
+ return true ? "0.2.2" : "0.0.0-dev";
3324
+ }
3325
+ function helpText() {
3326
+ return [
3327
+ "CostClaw - privacy-first Claude Code cost and setup audit",
3328
+ "",
3329
+ "Usage:",
3330
+ " costclaw audit [--path <dir>] [--claude-md <file>] [--json] [--html [file]] [--card [file]]",
3331
+ " costclaw badge [--path <dir>] [--claude-md <file>] [--out <file>]",
3332
+ " costclaw optimize [--path <dir>] [--claude-md <file>] [--project <dir>] [--out <dir>] [--write <file>] [--apply-settings [file]] [--force]",
3333
+ " costclaw activate <license-key> [--name <machine-name>]",
3334
+ " costclaw deactivate",
3335
+ " costclaw --version",
3336
+ "",
3337
+ "audit reads your Claude Code logs from ~/.claude/projects (or --path) on this",
3338
+ "machine and prints a cost report plus a six-pillar setup score. It is free.",
3339
+ "--html writes a self-contained report (default: costclaw-report.html) and opens",
3340
+ "it in your browser; the terminal report still prints.",
3341
+ "--card writes a shareable 600x315 score card SVG (default: costclaw-card.svg):",
3342
+ "score, band, recoverable spend, cache hit rate, and your strongest pillar.",
3343
+ "",
3344
+ "badge runs a fresh audit and writes a shields.io-style badge SVG (default:",
3345
+ "costclaw-badge.svg) showing your overall score, colored by its band. Embed it",
3346
+ "in a README with an <img> tag; it is a static, self-contained file.",
3347
+ "",
3348
+ "optimize turns that same audit into two artifacts: an optimized CLAUDE.md",
3349
+ "scaffold and a prioritized fix playbook. It also scans --project <dir>",
3350
+ "(default: the current directory) to auto-fill the scaffold's name, commands,",
3351
+ "structure, and other facts from your real project files. By default it",
3352
+ "dry-runs into ./costclaw-out (override with --out); --write <file> applies the",
3353
+ "optimized CLAUDE.md in place after backing up the original and printing a diff.",
3354
+ "--apply-settings [file] additively merges the derived permission allowlist into",
3355
+ "the project's .claude/settings.json (or [file]); it only touches",
3356
+ "permissions.allow and permissions.deny, backs up the original, and prints a diff.",
3357
+ "optimize needs a one-time license: buy at https://costclaw.io, then run",
3358
+ "costclaw activate <key>. activate and deactivate move that license between",
3359
+ "machines. audit never needs a license.",
3360
+ "",
3361
+ "Everything runs locally. Nothing is uploaded. Activation is a signed license",
3362
+ "key verified on this machine: there is no license server and no network call.",
3363
+ ""
3364
+ ].join("\n");
3365
+ }
2800
3366
  async function main() {
2801
3367
  const [command, ...args] = process.argv.slice(2);
3368
+ if (command === "--version" || command === "-v" || command === "version") {
3369
+ process.stdout.write(cliVersion() + "\n");
3370
+ return;
3371
+ }
2802
3372
  if (command === "audit") {
2803
- const { output } = await runAudit({
2804
- path: getFlag(args, "--path"),
2805
- claudeMdPath: getFlag(args, "--claude-md"),
2806
- json: args.includes("--json")
2807
- });
3373
+ const { output } = await runAudit(parseAuditFlags(args));
3374
+ process.stdout.write(output + "\n");
3375
+ return;
3376
+ }
3377
+ if (command === "badge") {
3378
+ const { output } = await runBadge(parseBadgeFlags(args));
2808
3379
  process.stdout.write(output + "\n");
2809
3380
  return;
2810
3381
  }
@@ -2834,51 +3405,32 @@ Run: costclaw optimize
2834
3405
  process.stderr.write(gate.message + "\n");
2835
3406
  process.exit(1);
2836
3407
  }
2837
- if (gate.offline) {
2838
- process.stderr.write("Could not reach the license server; running on your saved activation.\n");
2839
- }
2840
3408
  const { output } = await runOptimize({
2841
3409
  path: getFlag(args, "--path"),
2842
3410
  claudeMdPath: getFlag(args, "--claude-md"),
2843
3411
  projectDir: getFlag(args, "--project") || process.cwd(),
2844
3412
  out: getFlag(args, "--out"),
2845
3413
  write: getFlag(args, "--write"),
2846
- force: args.includes("--force")
3414
+ force: args.includes("--force"),
3415
+ applySettings: args.includes("--apply-settings"),
3416
+ applySettingsPath: args.includes("--apply-settings") ? optionalPathAfter(args, "--apply-settings") : void 0
2847
3417
  });
2848
3418
  process.stdout.write(output + "\n");
2849
3419
  return;
2850
3420
  }
2851
- process.stderr.write(
2852
- [
2853
- "CostClaw - privacy-first Claude Code cost and setup audit",
2854
- "",
2855
- "Usage:",
2856
- " costclaw audit [--path <dir>] [--claude-md <file>] [--json]",
2857
- " costclaw optimize [--path <dir>] [--claude-md <file>] [--project <dir>] [--out <dir>] [--write <file>] [--force]",
2858
- " costclaw activate <license-key> [--name <machine-name>]",
2859
- " costclaw deactivate",
2860
- "",
2861
- "audit reads your Claude Code logs from ~/.claude/projects (or --path) on this",
2862
- "machine and prints a cost report plus a six-pillar setup score. It is free.",
2863
- "",
2864
- "optimize turns that same audit into two artifacts: an optimized CLAUDE.md",
2865
- "scaffold and a prioritized fix playbook. It also scans --project <dir>",
2866
- "(default: the current directory) to auto-fill the scaffold's name, commands,",
2867
- "structure, and other facts from your real project files. By default it",
2868
- "dry-runs into ./costclaw-out (override with --out); --write <file> applies the",
2869
- "optimized CLAUDE.md in place after backing up the original and printing a diff.",
2870
- "optimize needs a one-time license: buy at https://costclaw.io, then run",
2871
- "costclaw activate <key>. activate and deactivate move that license between",
2872
- "machines. audit never needs a license.",
2873
- "",
2874
- "Everything runs locally. Nothing is uploaded. The only network call is the",
2875
- "license check to Lemon Squeezy, which sends just the key, never your logs.",
2876
- ""
2877
- ].join("\n") + "\n"
2878
- );
3421
+ process.stderr.write(helpText() + "\n");
2879
3422
  process.exit(command ? 1 : 0);
2880
3423
  }
2881
- main().catch((err) => {
2882
- console.error(err instanceof Error ? err.message : String(err));
2883
- process.exit(1);
2884
- });
3424
+ var isEntryPoint = process.argv[1] !== void 0 && import.meta.url === pathToFileURL(process.argv[1]).href;
3425
+ if (isEntryPoint) {
3426
+ main().catch((err) => {
3427
+ console.error(err instanceof Error ? err.message : String(err));
3428
+ process.exit(1);
3429
+ });
3430
+ }
3431
+ export {
3432
+ cliVersion,
3433
+ helpText,
3434
+ parseAuditFlags,
3435
+ parseBadgeFlags
3436
+ };