costclaw 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +51 -20
  2. package/dist/index.js +1354 -474
  3. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -2,6 +2,7 @@
2
2
 
3
3
  // src/index.ts
4
4
  import { pathToFileURL } from "url";
5
+ import { homedir as homedir7 } from "os";
5
6
 
6
7
  // ../../packages/engine/src/types.ts
7
8
  function emptyTotals() {
@@ -1133,7 +1134,7 @@ function hasAnyDuration(report) {
1133
1134
  }
1134
1135
  return false;
1135
1136
  }
1136
- function buildChecks(report, cmd, answers, setup) {
1137
+ function buildChecks(report, cmd2, answers, setup) {
1137
1138
  const checks = [];
1138
1139
  const s = report.summary;
1139
1140
  checks.push(
@@ -1141,8 +1142,8 @@ function buildChecks(report, cmd, answers, setup) {
1141
1142
  "cmd_size",
1142
1143
  "claude_md",
1143
1144
  "Size",
1144
- cmd.present ? cmd.sizeScore : null,
1145
- cmd.present ? `Your CLAUDE.md is ${cmd.chars.toLocaleString()} characters, about ${cmd.estTokens.toLocaleString()} tokens loaded on every turn.` : "No CLAUDE.md was provided.",
1145
+ cmd2.present ? cmd2.sizeScore : null,
1146
+ cmd2.present ? `Your CLAUDE.md is ${cmd2.chars.toLocaleString()} characters, about ${cmd2.estTokens.toLocaleString()} tokens loaded on every turn.` : "No CLAUDE.md was provided.",
1146
1147
  "claudemd"
1147
1148
  )
1148
1149
  );
@@ -1151,8 +1152,8 @@ function buildChecks(report, cmd, answers, setup) {
1151
1152
  "cmd_structure",
1152
1153
  "claude_md",
1153
1154
  "Structure",
1154
- cmd.present ? cmd.structureScore : null,
1155
- 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.",
1155
+ cmd2.present ? cmd2.structureScore : null,
1156
+ cmd2.present ? `${cmd2.headings} heading${cmd2.headings === 1 ? "" : "s"} and ${cmd2.bullets} bullet point${cmd2.bullets === 1 ? "" : "s"} across ${cmd2.chars.toLocaleString()} characters.` : "No CLAUDE.md was provided.",
1156
1157
  "claudemd"
1157
1158
  )
1158
1159
  );
@@ -1161,8 +1162,8 @@ function buildChecks(report, cmd, answers, setup) {
1161
1162
  "cmd_stability",
1162
1163
  "claude_md",
1163
1164
  "Cache stability",
1164
- cmd.present ? cmd.stabilityScore : null,
1165
- 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.",
1165
+ cmd2.present ? cmd2.stabilityScore : null,
1166
+ cmd2.present ? `${cmd2.volatileMarkers} volatile marker${cmd2.volatileMarkers === 1 ? "" : "s"} (dates, TODOs, "updated" notes) that change between sessions and reset the cache.` : "No CLAUDE.md was provided.",
1166
1167
  "claudemd"
1167
1168
  )
1168
1169
  );
@@ -1384,8 +1385,8 @@ function buildChecks(report, cmd, answers, setup) {
1384
1385
  checks.push(questionnaireCheck("model_choice", "Model fit", answers));
1385
1386
  return checks;
1386
1387
  }
1387
- function scorePillars(report, cmd, answers, setup) {
1388
- const checks = buildChecks(report, cmd, answers, setup);
1388
+ function scorePillars(report, cmd2, answers, setup) {
1389
+ const checks = buildChecks(report, cmd2, answers, setup);
1389
1390
  const pillars = PILLAR_ORDER.map((id) => {
1390
1391
  const cfg = PILLARS[id];
1391
1392
  const pillarChecks = checks.filter((c) => c.pillar === id);
@@ -1484,11 +1485,11 @@ function severityRank(s) {
1484
1485
  function num2(n) {
1485
1486
  return String(Math.round(n)).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
1486
1487
  }
1487
- function sizeFix(cmd) {
1488
- if (cmd.chars > 6e3) {
1488
+ function sizeFix(cmd2) {
1489
+ if (cmd2.chars > 6e3) {
1489
1490
  return {
1490
1491
  title: "Trim your CLAUDE.md",
1491
- action: `Your CLAUDE.md is an estimated ${num2(cmd.estTokens)} tokens (${num2(cmd.chars)} characters), paid on every turn of every session. Cut it to the durable conventions the agent actually needs and move the rest into docs it can open on demand.`
1492
+ action: `Your CLAUDE.md is an estimated ${num2(cmd2.estTokens)} tokens (${num2(cmd2.chars)} characters), paid on every turn of every session. Cut it to the durable conventions the agent actually needs and move the rest into docs it can open on demand.`
1492
1493
  };
1493
1494
  }
1494
1495
  return {
@@ -1496,7 +1497,7 @@ function sizeFix(cmd) {
1496
1497
  action: "Your CLAUDE.md is thin. Add the conventions, commands, and constraints the agent keeps getting wrong so it stops re-deriving them every session."
1497
1498
  };
1498
1499
  }
1499
- function synthesize(report, pillars, cmd, plan = "api") {
1500
+ function synthesize(report, pillars, cmd2, plan = "api") {
1500
1501
  const headlineWasteUsd = cacheMissExposureUsd(report);
1501
1502
  const headlineWasteLabel = plan === "api" ? "Recoverable spend (cache-miss exposure)" : "Recoverable usage (cache-miss exposure)";
1502
1503
  const spend = report.summary.cost_usd;
@@ -1576,8 +1577,8 @@ function synthesize(report, pillars, cmd, plan = "api") {
1576
1577
  let action;
1577
1578
  if (marathonBest && marathonUsd >= 0.25 * exposure && marathonBest.lateHit < marathonBest.earlyHit) {
1578
1579
  action = `The longest sessions started at ${pct2(marathonBest.earlyHit)}% cache reuse and finished at ${pct2(marathonBest.lateHit)}%. Compact or start a fresh session before the context outgrows the cache: the later turns re-pay for context you already bought.`;
1579
- } else if (cmd.present && cmd.stabilityScore != null && cmd.stabilityScore < GAP_THRESHOLD && cmd.volatileMarkers >= 5) {
1580
- action = `Your CLAUDE.md carries ${cmd.volatileMarkers} volatile markers (dates, TODOs, status notes). Every edit invalidates the cached prefix, so the next session re-pays full price for the whole file. Move the churn into a scratch note the agent opens on demand.`;
1580
+ } else if (cmd2.present && cmd2.stabilityScore != null && cmd2.stabilityScore < GAP_THRESHOLD && cmd2.volatileMarkers >= 5) {
1581
+ action = `Your CLAUDE.md carries ${cmd2.volatileMarkers} volatile markers (dates, TODOs, status notes). Every edit invalidates the cached prefix, so the next session re-pays full price for the whole file. Move the churn into a scratch note the agent opens on demand.`;
1581
1582
  } else if (badCacheBest) {
1582
1583
  action = `The last ${badCacheBest.sessionsConsidered} sessions in ${badCacheBest.slug} reused only ${pct2(badCacheBest.recentHitRate)}% from the cache. Open each session the same way (same CLAUDE.md, same first reads) so turn two onward reads the prefix at about a tenth of the input price.`;
1583
1584
  } else {
@@ -1691,7 +1692,7 @@ function synthesize(report, pillars, cmd, plan = "api") {
1691
1692
  for (const p of pillars) {
1692
1693
  for (const c of p.checks) {
1693
1694
  if (!c.gap || covered.has(c.id)) continue;
1694
- const tmpl = c.id === "cmd_size" ? sizeFix(cmd) : CHECK_FIX[c.id];
1695
+ const tmpl = c.id === "cmd_size" ? sizeFix(cmd2) : CHECK_FIX[c.id];
1695
1696
  if (!tmpl) continue;
1696
1697
  const severity = (c.score ?? 100) < 40 ? "warn" : "info";
1697
1698
  fixes.push({
@@ -1991,7 +1992,7 @@ var NOTE_MAX = 80;
1991
1992
  function extractCommandNotes(body) {
1992
1993
  const notes = /* @__PURE__ */ new Map();
1993
1994
  if (!body) return notes;
1994
- const keyOf = (cmd) => cmd.trim().replace(/\s+/g, " ");
1995
+ const keyOf = (cmd2) => cmd2.trim().replace(/\s+/g, " ");
1995
1996
  for (const raw of body.split("\n")) {
1996
1997
  const line = raw.trim();
1997
1998
  if (!line || line.startsWith("```") || line.startsWith("#")) continue;
@@ -2363,6 +2364,27 @@ function buildClaudeMd(input, recoverable, notes, stats, carried, dispositions)
2363
2364
  }
2364
2365
  return clean(parts.join("\n\n").trimEnd() + "\n");
2365
2366
  }
2367
+ var INCLUDE_HEADING = [...REGENERATED_HEADING, /^token discipline\b/i];
2368
+ function isPlaceholderOnly(body) {
2369
+ return /^<!--[^]*?-->$/.test(body.trim());
2370
+ }
2371
+ function buildIncludeMd(optimizedClaudeMd) {
2372
+ const sections = parseSections(optimizedClaudeMd).filter(
2373
+ (s) => INCLUDE_HEADING.some((re) => re.test(s.heading)) && !isPlaceholderOnly(s.body)
2374
+ );
2375
+ const header = [
2376
+ "<!--",
2377
+ " Generated by CostClaw (https://costclaw.io). Regenerated on every",
2378
+ " `costclaw apply`; edit your CLAUDE.md, not this file.",
2379
+ " Imported from CLAUDE.md by the line: @.claude/costclaw.md",
2380
+ " Undo: costclaw apply . --remove",
2381
+ "-->"
2382
+ ].join("\n");
2383
+ const parts = [header, ...sections.map((s) => `## ${s.heading}
2384
+
2385
+ ${s.body}`)];
2386
+ return { includeMd: clean(parts.join("\n\n").trimEnd() + "\n"), includeSections: sections.map((s) => s.heading) };
2387
+ }
2366
2388
  function joinAnd(items) {
2367
2389
  if (items.length === 0) return "";
2368
2390
  if (items.length === 1) return items[0];
@@ -2551,9 +2573,9 @@ function buildSettings(project) {
2551
2573
  const projectAllow = /* @__PURE__ */ new Set();
2552
2574
  for (const c of project?.commands ?? []) {
2553
2575
  if (!SAFE_COMMAND_LABELS.has(c.label)) continue;
2554
- const cmd = c.command.trim();
2555
- if (!cmd || cmd.includes("<")) continue;
2556
- projectAllow.add(`Bash(${cmd}:*)`);
2576
+ const cmd2 = c.command.trim();
2577
+ if (!cmd2 || cmd2.includes("<")) continue;
2578
+ projectAllow.add(`Bash(${cmd2}:*)`);
2557
2579
  }
2558
2580
  const allow = [...BASE_ALLOW, ...[...projectAllow].sort()];
2559
2581
  const settings = { permissions: { allow, deny: [...BASE_DENY] } };
@@ -2577,8 +2599,9 @@ function buildHarnessPrompt(input, carried, claudeMdTokens) {
2577
2599
  [
2578
2600
  "You are Claude Code, working in this repository. costclaw generated this",
2579
2601
  "work order from a local audit of real usage logs plus a scan of this",
2580
- "project; every task is grounded in that evidence. Execute the tasks in",
2581
- "order and report what changed at the end."
2602
+ "project; every task is grounded in that evidence. The files named below",
2603
+ "sit in the same folder as this work order. Execute the tasks in order",
2604
+ "and report what changed at the end."
2582
2605
  ].join("\n")
2583
2606
  );
2584
2607
  parts.push(
@@ -2596,30 +2619,34 @@ function buildHarnessPrompt(input, carried, claudeMdTokens) {
2596
2619
  );
2597
2620
  parts.push(
2598
2621
  [
2599
- "## Task 1: Merge the optimized CLAUDE.md",
2622
+ "## Task 1: Slim your CLAUDE.md",
2623
+ "",
2624
+ "If `.claude/costclaw.md` does not exist yet, run `npx costclaw apply .`",
2625
+ "first. It writes the generated sections (see `costclaw.md` here) to",
2626
+ "`.claude/costclaw.md` and adds `@.claude/costclaw.md` to CLAUDE.md.",
2600
2627
  "",
2601
- "Merge `costclaw-out/CLAUDE.optimized.md` into `./CLAUDE.md`:",
2628
+ "Then, in `./CLAUDE.md`:",
2629
+ "- For each section the include now covers (Commands, Project structure,",
2630
+ " Code style, Testing, Environment): compare yours with the include. If a",
2631
+ " fact of yours is missing from the include, keep that line in CLAUDE.md",
2632
+ " under its heading (the include is regenerated, never edit it). Otherwise",
2633
+ " delete your copy so each section appears once.",
2634
+ "- Move the volatile sections listed below into docs/ and link them.",
2635
+ "- Strip any generator HTML comment blocks.",
2636
+ "- Show the diff before writing.",
2602
2637
  "",
2603
- "- Conflicting facts: the existing CLAUDE.md wins (it is the human's).",
2604
- "- Structure and curation: the optimized file wins (section set, command",
2605
- " curation, dropped filler).",
2606
- "- Commands: start from the optimized curated list with its annotations;",
2607
- " re-add a dropped script only when the workflow genuinely needs it",
2608
- " pinned in an always-loaded file.",
2609
- "- Strip the generator's HTML comment blocks from the final file.",
2610
- "- Back up, show the diff, then write."
2638
+ "Only `apply --replace` swaps the whole file; do not do that here."
2611
2639
  ].join("\n")
2612
2640
  );
2613
2641
  parts.push(
2614
2642
  [
2615
2643
  "## Task 2: Permission allowlist",
2616
2644
  "",
2617
- "Review `costclaw-out/settings.suggested.json` (read-only tools plus",
2618
- "this project's safe commands; denies secret reads and destructive",
2619
- "ops). Merge the rules you agree with additively into",
2620
- "`.claude/settings.json`, keeping every existing entry.",
2621
- "`npx costclaw optimize --apply-settings` performs the mechanical merge",
2622
- "with a backup and a diff if you prefer."
2645
+ "Review `settings.suggested.json` (read-only tools plus this project's",
2646
+ "safe commands; denies secret reads and destructive ops). Merge the",
2647
+ "rules you agree with additively into `.claude/settings.json`, keeping",
2648
+ "every existing entry. `npx costclaw apply . --apply-settings`",
2649
+ "performs the mechanical merge with a backup and a diff if you prefer."
2623
2650
  ].join("\n")
2624
2651
  );
2625
2652
  let n = 3;
@@ -2729,7 +2756,12 @@ function buildHarnessPrompt(input, carried, claudeMdTokens) {
2729
2756
  const lintCmd = project?.commands.find((c) => c.label === "lint")?.command;
2730
2757
  if (testCmd) verify.push(`- Run \`${testCmd}\` and read the output.`);
2731
2758
  if (lintCmd) verify.push(`- Run \`${lintCmd}\` and read the output.`);
2732
- verify.push("- Confirm no generator comment blocks are left in CLAUDE.md.");
2759
+ verify.push(
2760
+ "- Confirm CLAUDE.md contains the line `@.claude/costclaw.md` and that the",
2761
+ " regenerated sections (Commands, Project structure, Code style, Testing,",
2762
+ " Environment) appear once across CLAUDE.md and the include.",
2763
+ "- Confirm no generator comment blocks are left in CLAUDE.md."
2764
+ );
2733
2765
  if (carried.carriedTokens >= CARRY_HEAVY_TOKENS) {
2734
2766
  verify.push(
2735
2767
  "- Confirm every line moved out of CLAUDE.md landed in a file under",
@@ -2760,14 +2792,17 @@ function optimize(input) {
2760
2792
  const playbook = buildPlaybook(input.report, input.fixes, input.scores, recoverable, claudeMdTokens, input.project);
2761
2793
  const settingsJson = buildSettings(input.project);
2762
2794
  const harnessPrompt = buildHarnessPrompt(input, carried, claudeMdTokens);
2795
+ const { includeMd, includeSections } = buildIncludeMd(optimizedClaudeMd);
2763
2796
  const cleanNotes = notes.map((n) => clean(n));
2764
2797
  const cleanDispositions = dispositions.map((d) => ({ ...d, name: clean(d.name), why: clean(d.why) }));
2765
- if (hasEmDash(optimizedClaudeMd) || hasEmDash(playbook) || hasEmDash(settingsJson) || hasEmDash(harnessPrompt) || cleanNotes.some(hasEmDash) || cleanDispositions.some((d) => hasEmDash(d.name) || hasEmDash(d.why))) {
2798
+ if (hasEmDash(optimizedClaudeMd) || hasEmDash(playbook) || hasEmDash(settingsJson) || hasEmDash(harnessPrompt) || hasEmDash(includeMd) || cleanNotes.some(hasEmDash) || cleanDispositions.some((d) => hasEmDash(d.name) || hasEmDash(d.why))) {
2766
2799
  return {
2767
2800
  optimizedClaudeMd: sanitizeText(optimizedClaudeMd),
2768
2801
  playbook: sanitizeText(playbook),
2769
2802
  settingsJson: sanitizeText(settingsJson),
2770
2803
  harnessPrompt: sanitizeText(harnessPrompt),
2804
+ includeMd: sanitizeText(includeMd),
2805
+ includeSections,
2771
2806
  notes: cleanNotes.map(sanitizeText),
2772
2807
  placeholdersRemaining: stats.placeholders,
2773
2808
  claudeMdTokens,
@@ -2780,6 +2815,8 @@ function optimize(input) {
2780
2815
  playbook,
2781
2816
  settingsJson,
2782
2817
  harnessPrompt,
2818
+ includeMd,
2819
+ includeSections,
2783
2820
  notes: cleanNotes,
2784
2821
  placeholdersRemaining: stats.placeholders,
2785
2822
  claudeMdTokens,
@@ -2868,10 +2905,10 @@ function cleanPillar(p) {
2868
2905
  }
2869
2906
  function buildAudit(input, opts = {}) {
2870
2907
  const report = analyzeUploads(input.logs);
2871
- const cmd = analyzeClaudeMd(input.claudeMd);
2872
- const { pillars, overall, band } = scorePillars(report, cmd, input.questionnaire, input.setup);
2908
+ const cmd2 = analyzeClaudeMd(input.claudeMd);
2909
+ const { pillars, overall, band } = scorePillars(report, cmd2, input.questionnaire, input.setup);
2873
2910
  const plan = input.plan ?? "api";
2874
- const { headlineWasteUsd, headlineWasteLabel, headlineWasteShare, fixes } = synthesize(report, pillars, cmd, plan);
2911
+ const { headlineWasteUsd, headlineWasteLabel, headlineWasteShare, fixes } = synthesize(report, pillars, cmd2, plan);
2875
2912
  const answered = Object.values(input.questionnaire).filter((v) => typeof v === "string" && v.length > 0).length;
2876
2913
  return {
2877
2914
  schemaVersion: "1",
@@ -2880,8 +2917,8 @@ function buildAudit(input, opts = {}) {
2880
2917
  contactEmail: input.contactEmail?.trim() || null,
2881
2918
  inputsSummary: {
2882
2919
  logFiles: input.logs.length,
2883
- hasClaudeMd: cmd.present,
2884
- claudeMdChars: cmd.chars,
2920
+ hasClaudeMd: cmd2.present,
2921
+ claudeMdChars: cmd2.chars,
2885
2922
  questionnaireAnswered: answered
2886
2923
  },
2887
2924
  usageMetrics: toUsageMetrics(report),
@@ -3021,9 +3058,9 @@ var MAX_TOTAL_BYTES = 60 * 1024 * 1024;
3021
3058
  var MAX_CLAUDEMD_BYTES = 1 * 1024 * 1024;
3022
3059
 
3023
3060
  // src/audit-command.ts
3024
- import { mkdir as mkdir2, readFile as readFile3, readdir as readdir2, rm, writeFile as writeFile2 } from "fs/promises";
3025
- import { join as join4, resolve } from "path";
3026
- import { homedir as homedir3 } from "os";
3061
+ import { mkdir as mkdir3, readFile as readFile4, readdir as readdir2, rm as rm2, writeFile as writeFile3 } from "fs/promises";
3062
+ import { join as join5, resolve } from "path";
3063
+ import { homedir as homedir4 } from "os";
3027
3064
 
3028
3065
  // src/open.ts
3029
3066
  import { spawn } from "child_process";
@@ -3031,8 +3068,8 @@ function openInBrowser(target) {
3031
3068
  if (process.env["VITEST"] || process.env["CI"] || process.env["COSTCLAW_NO_OPEN"]) return;
3032
3069
  try {
3033
3070
  const platform = process.platform;
3034
- const [cmd, args] = platform === "win32" ? ["cmd", ["/c", "start", "", target]] : platform === "darwin" ? ["open", [target]] : ["xdg-open", [target]];
3035
- const child = spawn(cmd, args, { detached: true, stdio: "ignore" });
3071
+ const [cmd2, args] = platform === "win32" ? ["cmd", ["/c", "start", "", target]] : platform === "darwin" ? ["open", [target]] : ["xdg-open", [target]];
3072
+ const child = spawn(cmd2, args, { detached: true, stdio: "ignore" });
3036
3073
  child.on("error", () => {
3037
3074
  });
3038
3075
  child.unref();
@@ -3111,7 +3148,7 @@ function projectNameFromLogs(files) {
3111
3148
  if (typeof rec.cwd === "string" && rec.cwd) {
3112
3149
  const parts = rec.cwd.split(/[\\/]+/).filter(Boolean);
3113
3150
  const base = parts.at(-1);
3114
- if (base) return base;
3151
+ if (base) return { slug: base, cwd: rec.cwd };
3115
3152
  }
3116
3153
  }
3117
3154
  } finally {
@@ -3123,13 +3160,14 @@ function projectNameFromLogs(files) {
3123
3160
  async function readSessions(rootPath) {
3124
3161
  const logs = [];
3125
3162
  const skipped = [];
3126
- let projectDirs;
3163
+ const projectDirs = /* @__PURE__ */ new Map();
3164
+ let entries;
3127
3165
  try {
3128
- projectDirs = await readdir(rootPath, { withFileTypes: true });
3166
+ entries = await readdir(rootPath, { withFileTypes: true });
3129
3167
  } catch {
3130
- return { logs, skipped };
3168
+ return { logs, skipped, projectDirs };
3131
3169
  }
3132
- for (const dir of projectDirs) {
3170
+ for (const dir of entries) {
3133
3171
  if (!dir.isDirectory()) continue;
3134
3172
  const projPath = join(rootPath, dir.name);
3135
3173
  try {
@@ -3139,7 +3177,9 @@ async function readSessions(rootPath) {
3139
3177
  continue;
3140
3178
  }
3141
3179
  const files = await collectJsonl(projPath);
3142
- const projectSlug = projectNameFromLogs(files) ?? dir.name;
3180
+ const probe = projectNameFromLogs(files);
3181
+ const projectSlug = probe?.slug ?? dir.name;
3182
+ if (probe && !projectDirs.has(probe.slug)) projectDirs.set(probe.slug, probe.cwd);
3143
3183
  for (const full of files) {
3144
3184
  const rel = relative(projPath, full).split(sep).join("/");
3145
3185
  const name = `${dir.name}/${rel}`;
@@ -3152,7 +3192,7 @@ async function readSessions(rootPath) {
3152
3192
  }
3153
3193
  }
3154
3194
  }
3155
- return { logs, skipped };
3195
+ return { logs, skipped, projectDirs };
3156
3196
  }
3157
3197
 
3158
3198
  // src/ansi.ts
@@ -3539,6 +3579,61 @@ function dollarFixCard(f) {
3539
3579
  function otherFixCard(f) {
3540
3580
  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>`;
3541
3581
  }
3582
+ var SITE_URL = "https://costclaw.io";
3583
+ var PRICING_URL = "https://costclaw.io/#pricing";
3584
+ var CHECKOUT_URL = "https://buy.stripe.com/00wfZhgCH3X62v0cX9ew807";
3585
+ var SUPPORT_EMAIL = "wes@dashclaw.io";
3586
+ var LICENSE_PRICE = "$39";
3587
+ function cmd(c) {
3588
+ return `<pre class="cmd"><code>${esc(c)}</code></pre>`;
3589
+ }
3590
+ function step(n, title, body) {
3591
+ return `<li class="step"><div class="step-n">${n}</div><div class="step-body"><h3>${esc(title)}</h3>${body}</div></li>`;
3592
+ }
3593
+ function nextStepsSection(record, meta) {
3594
+ const licensed = meta.license?.active === true;
3595
+ const steps = [];
3596
+ let n = 1;
3597
+ if (meta.planSource === "default") {
3598
+ steps.push(step(
3599
+ n++,
3600
+ "Tell costclaw how you pay",
3601
+ `<p>On a Claude subscription the dollar figures above are token value, not money back. Declare your plan once and the report reframes everything as usage you win back.</p>` + cmd("npx costclaw audit --plan max20x # or pro, max5x, api")
3602
+ ));
3603
+ }
3604
+ const waste = record.headlineWasteUsd;
3605
+ const wasteLine = waste > 0 ? `This audit found <strong>${esc(usd3(waste))}</strong> of recoverable input spend. ` : "";
3606
+ if (licensed) {
3607
+ const who = meta.license?.email ? ` (${esc(meta.license.email)})` : "";
3608
+ steps.push(step(
3609
+ n++,
3610
+ "Apply the fixes with optimize",
3611
+ `<p class="ok">License active on this machine${who}.</p><p>${wasteLine}Run optimize inside each project you work in. It scans the project, writes a filled-in CLAUDE.md, a ranked playbook, suggested settings, a work order, and a dashboard into <span class="mono">./costclaw-out</span>, then opens the dashboard.</p>` + cmd("cd <your-project>\nnpx costclaw optimize") + `<p>Happy with the dry run? Apply it in place (both back up the original and print a diff), then hand the work order to your own Claude Code:</p>` + cmd('npx costclaw optimize --write CLAUDE.md --apply-settings\nclaude "Follow costclaw-out/HARNESS-UPGRADE.md"') + `<p class="fine">Moving machines? <span class="mono">costclaw deactivate</span> here, <span class="mono">costclaw activate &lt;key&gt;</span> there.</p>`
3612
+ ));
3613
+ } else {
3614
+ steps.push(step(
3615
+ n++,
3616
+ "Apply the fixes with optimize",
3617
+ `<p>${wasteLine}<strong>costclaw optimize</strong> turns this audit into the files that recover it: a filled-in CLAUDE.md, a ranked fix playbook, a suggested <span class="mono">settings.json</span> allowlist, a work order your own Claude Code applies, and a dashboard showing your CLAUDE.md before and after.</p><div class="offer"><div class="offer-price"><span class="big">${esc(LICENSE_PRICE)}</span> one-time</div><ul class="offer-list"><li>Key emailed in about a minute</li><li>Verified offline on your machine, no license server</li><li>Every project, unlimited runs</li><li>Move it between machines with activate and deactivate</li></ul><a class="buy" href="${CHECKOUT_URL}">Buy the optimize license</a><p class="fine">Then, once the key arrives:</p>` + cmd("npx costclaw activate <key>\ncd <your-project>\nnpx costclaw optimize") + `<p class="fine">Questions or a key that will not activate: <a href="mailto:${SUPPORT_EMAIL}">${SUPPORT_EMAIL}</a>. The audit stays free either way.</p></div>`
3618
+ ));
3619
+ }
3620
+ steps.push(step(
3621
+ n++,
3622
+ "Track the movement",
3623
+ `<p>Every audit snapshots the derived record locally. Rerun in a week and compare: new spend, the cache hit rate for just that period, pillar movement, and which fixes resolved.</p>` + cmd("npx costclaw audit\nnpx costclaw diff")
3624
+ ));
3625
+ steps.push(step(
3626
+ n++,
3627
+ "Share the score",
3628
+ `<p>A 600x315 score card for a post, and a shields-style badge for a README. Both are static SVGs with only derived numbers.</p>` + cmd("npx costclaw audit --card\nnpx costclaw badge")
3629
+ ));
3630
+ const reference = `<table class="ref"><tbody><tr><td class="mono">costclaw audit</td><td>Cost report, setup score, ranked fixes, this HTML report. Free.</td></tr><tr><td class="mono">costclaw audit --plan &lt;p&gt;</td><td>Declare api, pro, max5x, or max20x; remembered for later runs.</td></tr><tr><td class="mono">costclaw diff</td><td>Compare the latest two audits, or two --json records. Free.</td></tr><tr><td class="mono">costclaw badge</td><td>Fresh audit plus a README badge SVG. Free.</td></tr><tr><td class="mono">costclaw optimize</td><td>Write the optimized CLAUDE.md, playbook, settings, work order, and dashboard. Licensed.</td></tr><tr><td class="mono">costclaw activate / deactivate</td><td>Install or move the license on this machine. Offline.</td></tr><tr><td class="mono">costclaw --help</td><td>Every flag, per command.</td></tr></tbody></table>`;
3631
+ return `<h2>What to do next</h2>
3632
+ <ol class="steps">${steps.join("")}</ol>
3633
+ <h3 class="ref-head">Command reference</h3>
3634
+ ${reference}
3635
+ <p class="sub">Docs and pricing: <a href="${SITE_URL}">${SITE_URL.replace("https://", "")}</a>. A hosted dashboard with history and team views is in progress; the waitlist is on the <a href="${PRICING_URL}">pricing section</a>. It will only ever receive the derived record, never your logs.</p>`;
3636
+ }
3542
3637
  var STYLE = `
3543
3638
  :root {
3544
3639
  color-scheme: light;
@@ -3647,8 +3742,49 @@ ul.fixes { list-style: none; margin: 0; padding: 0; }
3647
3742
  .footer .gen { margin: var(--s2) 0 0; }
3648
3743
  /* The timestamp is one token; never let it break across lines. */
3649
3744
  .footer .gen .mono { white-space: nowrap; }
3745
+ /* Next-steps ramp */
3746
+ ol.steps { list-style: none; margin: 0; padding: 0; counter-reset: none; }
3747
+ .step {
3748
+ display: flex; gap: var(--s4); background: var(--card); border: 1px solid var(--line);
3749
+ border-radius: 10px; padding: var(--s4) var(--s5); margin: 0 0 var(--s3);
3750
+ }
3751
+ .step-n {
3752
+ flex: 0 0 28px; height: 28px; border-radius: 14px; background: var(--umber); color: var(--paper);
3753
+ font-family: var(--mono); font-weight: 700; font-size: 14px; display: flex; align-items: center; justify-content: center;
3754
+ }
3755
+ .step-body { flex: 1; min-width: 0; }
3756
+ .step-body h3 { font-size: 15px; margin: 3px 0 var(--s2); }
3757
+ .step-body p { margin: var(--s2) 0 0; font-size: 14px; max-width: 74ch; }
3758
+ .step-body .ok { color: #1f6b3a; font-weight: 600; }
3759
+ .step-body .fine { font-size: 13px; color: var(--muted); }
3760
+ .cmd {
3761
+ margin: var(--s3) 0 0; padding: var(--s3) var(--s4); background: #2a211d; color: #f4ebe5;
3762
+ border-radius: 8px; font-family: var(--mono); font-size: 13px; line-height: 1.6;
3763
+ overflow-x: auto; white-space: pre;
3764
+ }
3765
+ .cmd code { font-family: inherit; }
3766
+ .offer {
3767
+ margin: var(--s4) 0 0; padding: var(--s4) var(--s5); border: 1px solid var(--line);
3768
+ border-left: 4px solid var(--clay); border-radius: 10px; background: var(--paper);
3769
+ }
3770
+ .offer-price { font-size: 14px; color: var(--muted); }
3771
+ .offer-price .big { font-size: 28px; font-weight: 700; color: var(--umber); font-family: var(--mono); margin-right: var(--s2); }
3772
+ .offer-list { margin: var(--s3) 0 0; padding-left: 18px; font-size: 14px; }
3773
+ .offer-list li { margin: 2px 0; }
3774
+ .buy {
3775
+ display: inline-block; margin: var(--s4) 0 0; padding: 10px 18px; border-radius: 8px;
3776
+ background: linear-gradient(135deg, var(--umber), var(--clay)); color: var(--paper);
3777
+ font-weight: 700; text-decoration: none; font-size: 14px;
3778
+ }
3779
+ .buy:hover { filter: brightness(1.05); }
3780
+ a { color: var(--umber); }
3781
+ .ref-head { font-size: 14px; color: var(--muted); text-transform: uppercase; letter-spacing: 0.06em; margin: var(--s6) 0 var(--s3); }
3782
+ table.ref { width: 100%; border-collapse: collapse; font-size: 14px; }
3783
+ table.ref td { padding: var(--s2) var(--s3); border-top: 1px solid var(--line); vertical-align: top; }
3784
+ table.ref td:first-child { white-space: nowrap; color: var(--umber); font-size: 13px; }
3650
3785
  @media (max-width: 560px) {
3651
3786
  .wrap { padding: var(--s6) var(--s4) var(--s8); }
3787
+ table.ref td:first-child { white-space: normal; }
3652
3788
  h1 { font-size: 24px; }
3653
3789
  .banner .amount { font-size: 32px; }
3654
3790
  .p-name { flex: 0 0 130px; font-size: 13px; }
@@ -3736,6 +3872,8 @@ ${dollarSection}
3736
3872
  ${otherSection}
3737
3873
  ${skippedNote}
3738
3874
 
3875
+ ${nextStepsSection(record, meta)}
3876
+
3739
3877
  <div class="footer">
3740
3878
  <strong>This report was generated locally on your machine.</strong> Nothing was uploaded:
3741
3879
  your prompts, file contents, and paths never left this computer.
@@ -3870,6 +4008,125 @@ async function saveCliConfig(dir, patch) {
3870
4008
  await writeFile(configFile(dir), JSON.stringify(merged, null, 2), "utf8");
3871
4009
  }
3872
4010
 
4011
+ // src/license.ts
4012
+ import { mkdir as mkdir2, readFile as readFile3, writeFile as writeFile2, rm } from "fs/promises";
4013
+ import { join as join4 } from "path";
4014
+ import { homedir as homedir3, hostname } from "os";
4015
+
4016
+ // ../../packages/license/src/keys.ts
4017
+ var LICENSE_PRODUCT = "costclaw-optimize";
4018
+ var KEY_PREFIX = "CC1";
4019
+ var DEFAULT_PUBLIC_KEY_PEM = `-----BEGIN PUBLIC KEY-----
4020
+ MCowBQYDK2VwAyEAXKdEIiMqeB4HIUb8si3LxRPBnrDpCIJrWvJWUCQLROg=
4021
+ -----END PUBLIC KEY-----`;
4022
+
4023
+ // ../../packages/license/src/verify.ts
4024
+ import { createPublicKey, verify as cryptoVerify } from "crypto";
4025
+ function base64UrlDecode(part) {
4026
+ return Buffer.from(part.replace(/-/g, "+").replace(/_/g, "/"), "base64");
4027
+ }
4028
+ function verifyLicenseKey(licenseKey, publicKeyPem = DEFAULT_PUBLIC_KEY_PEM) {
4029
+ const parts = licenseKey.trim().split(".");
4030
+ if (parts.length !== 3 || parts[0] !== KEY_PREFIX) return null;
4031
+ const [prefix, payloadPart, signaturePart] = parts;
4032
+ if (prefix === void 0 || payloadPart === void 0 || signaturePart === void 0) return null;
4033
+ try {
4034
+ const publicKey = createPublicKey(publicKeyPem);
4035
+ const signed = Buffer.from(`${prefix}.${payloadPart}`, "utf8");
4036
+ const signature = base64UrlDecode(signaturePart);
4037
+ if (!cryptoVerify(null, signed, publicKey, signature)) return null;
4038
+ const payload = JSON.parse(base64UrlDecode(payloadPart).toString("utf8"));
4039
+ if (payload.p !== LICENSE_PRODUCT) return null;
4040
+ return payload;
4041
+ } catch {
4042
+ return null;
4043
+ }
4044
+ }
4045
+
4046
+ // ../../packages/license/src/mint.ts
4047
+ import { createPrivateKey, sign } from "crypto";
4048
+
4049
+ // ../../packages/license/src/stripe.ts
4050
+ import { createHmac, timingSafeEqual } from "crypto";
4051
+
4052
+ // src/license.ts
4053
+ var NOT_ACTIVATED_MESSAGE = [
4054
+ "costclaw optimize needs a license.",
4055
+ "",
4056
+ "Buy a one-time license at https://costclaw.io, then run:",
4057
+ " costclaw activate <your-license-key>",
4058
+ "",
4059
+ "costclaw audit is free and does not need a license."
4060
+ ].join("\n");
4061
+ var INVALID_MESSAGE = [
4062
+ "The saved CostClaw license is not valid for this version.",
4063
+ "",
4064
+ "Re-activate with the key from your purchase email:",
4065
+ " costclaw activate <your-license-key>",
4066
+ "",
4067
+ "Key missing or not working? Email wes@dashclaw.io with your order number.",
4068
+ "costclaw audit stays free."
4069
+ ].join("\n");
4070
+ function defaultConfigDir() {
4071
+ return join4(homedir3(), ".costclaw");
4072
+ }
4073
+ function licenseFile(dir) {
4074
+ return join4(dir, "license.json");
4075
+ }
4076
+ async function readStoredLicense(dir) {
4077
+ try {
4078
+ const data = JSON.parse(await readFile3(licenseFile(dir), "utf8"));
4079
+ if (!data || typeof data.licenseKey !== "string") return null;
4080
+ return data;
4081
+ } catch {
4082
+ return null;
4083
+ }
4084
+ }
4085
+ async function writeStoredLicense(dir, lic) {
4086
+ await mkdir2(dir, { recursive: true });
4087
+ await writeFile2(licenseFile(dir), JSON.stringify(lic, null, 2) + "\n", "utf8");
4088
+ }
4089
+ async function clearStoredLicense(dir) {
4090
+ await rm(licenseFile(dir), { force: true });
4091
+ }
4092
+ async function activateLicense(licenseKey, opts = {}) {
4093
+ const key = licenseKey.trim();
4094
+ if (!key) throw new Error("Provide your license key: costclaw activate <key>");
4095
+ const configDir = opts.configDir ?? defaultConfigDir();
4096
+ const payload = verifyLicenseKey(key, opts.publicKeyPem);
4097
+ if (!payload) {
4098
+ throw new Error(
4099
+ "Could not activate this license key: it is not a valid CostClaw optimize license.\nCopy the whole key from your purchase email, or buy one at https://costclaw.io."
4100
+ );
4101
+ }
4102
+ const stored = {
4103
+ licenseKey: key,
4104
+ instanceId: "local",
4105
+ instanceName: opts.instanceName?.trim() || hostname(),
4106
+ email: payload.e,
4107
+ activatedAt: (/* @__PURE__ */ new Date()).toISOString()
4108
+ };
4109
+ await writeStoredLicense(configDir, stored);
4110
+ return stored;
4111
+ }
4112
+ async function checkLicense(opts = {}) {
4113
+ const configDir = opts.configDir ?? defaultConfigDir();
4114
+ const stored = await readStoredLicense(configDir);
4115
+ if (!stored) return { ok: false, message: NOT_ACTIVATED_MESSAGE };
4116
+ const payload = verifyLicenseKey(stored.licenseKey, opts.publicKeyPem);
4117
+ if (payload) {
4118
+ return { ok: true, email: payload.e ?? stored.email };
4119
+ }
4120
+ await clearStoredLicense(configDir);
4121
+ return { ok: false, message: INVALID_MESSAGE };
4122
+ }
4123
+ async function deactivateLicense(opts = {}) {
4124
+ const configDir = opts.configDir ?? defaultConfigDir();
4125
+ const stored = await readStoredLicense(configDir);
4126
+ if (!stored) throw new Error("No license is active on this machine, so there is nothing to deactivate.");
4127
+ await clearStoredLicense(configDir);
4128
+ }
4129
+
3873
4130
  // src/audit-command.ts
3874
4131
  async function resolvePlan(configDir, flag) {
3875
4132
  if (flag) {
@@ -3889,24 +4146,24 @@ var DEFAULT_CARD_FILE = "costclaw-card.svg";
3889
4146
  var SNAPSHOT_KEEP = 50;
3890
4147
  async function loadAuditInputs(opts) {
3891
4148
  const root = opts.path || defaultProjectsPath();
3892
- const { logs, skipped } = await readSessions(root);
4149
+ const { logs, skipped, projectDirs } = await readSessions(root);
3893
4150
  if (logs.length === 0) {
3894
4151
  throw new Error(`No .jsonl sessions found under ${root}. Set CLAUDE_PROJECTS_PATH or pass --path <dir>.`);
3895
4152
  }
3896
4153
  let claudeMd;
3897
4154
  let claudeMdSource = null;
3898
4155
  if (opts.claudeMdPath) {
3899
- claudeMd = await readFile3(opts.claudeMdPath, "utf8");
4156
+ claudeMd = await readFile4(opts.claudeMdPath, "utf8");
3900
4157
  claudeMdSource = resolve(opts.claudeMdPath);
3901
4158
  } else {
3902
- const fallback = join4(opts.home ?? homedir3(), ".claude", "CLAUDE.md");
4159
+ const fallback = join5(opts.home ?? homedir4(), ".claude", "CLAUDE.md");
3903
4160
  try {
3904
- claudeMd = await readFile3(fallback, "utf8");
4161
+ claudeMd = await readFile4(fallback, "utf8");
3905
4162
  claudeMdSource = fallback;
3906
4163
  } catch {
3907
4164
  }
3908
4165
  }
3909
- return { logs, claudeMd, claudeMdSource, root, skipped };
4166
+ return { logs, claudeMd, claudeMdSource, root, skipped, projectDirs };
3910
4167
  }
3911
4168
  async function runAudit(opts) {
3912
4169
  const { logs, claudeMd, claudeMdSource, root, skipped } = await loadAuditInputs({
@@ -3915,7 +4172,7 @@ async function runAudit(opts) {
3915
4172
  home: opts.home
3916
4173
  });
3917
4174
  const setup = await readSetup();
3918
- const configDir = join4(opts.home ?? homedir3(), ".costclaw");
4175
+ const configDir = join5(opts.home ?? homedir4(), ".costclaw");
3919
4176
  const { plan, planSource } = await resolvePlan(configDir, opts.plan);
3920
4177
  const record = buildAudit({
3921
4178
  logs,
@@ -3927,15 +4184,17 @@ async function runAudit(opts) {
3927
4184
  });
3928
4185
  const baseline = (await readCliConfig(configDir)).lastOptimize;
3929
4186
  const sinceOptimize = baseline ? { at: baseline.at, result: sinceBaseline(baseline, record) } : void 0;
4187
+ const gate = await checkLicense({ configDir });
4188
+ const license = gate.ok ? { active: true, ...gate.email ? { email: gate.email } : {} } : { active: false };
3930
4189
  let snapshotNotice = null;
3931
4190
  try {
3932
- const historyDir = join4(opts.home ?? homedir3(), ".costclaw", "history");
3933
- await mkdir2(historyDir, { recursive: true });
4191
+ const historyDir = join5(opts.home ?? homedir4(), ".costclaw", "history");
4192
+ await mkdir3(historyDir, { recursive: true });
3934
4193
  const name = record.createdAt.replace(/[:.]/g, "-") + ".json";
3935
- await writeFile2(join4(historyDir, name), JSON.stringify(record, null, 2), "utf8");
4194
+ await writeFile3(join5(historyDir, name), JSON.stringify(record, null, 2), "utf8");
3936
4195
  const snapshots = (await readdir2(historyDir)).filter((f) => f.endsWith(".json")).sort();
3937
4196
  for (const stale of snapshots.slice(0, Math.max(0, snapshots.length - SNAPSHOT_KEEP))) {
3938
- await rm(join4(historyDir, stale), { force: true });
4197
+ await rm2(join5(historyDir, stale), { force: true });
3939
4198
  }
3940
4199
  snapshotNotice = "Snapshot saved for costclaw diff.";
3941
4200
  } catch (err) {
@@ -3948,15 +4207,15 @@ async function runAudit(opts) {
3948
4207
  if (snapshotNotice) notices.push(snapshotNotice);
3949
4208
  if (opts.html) {
3950
4209
  const target = resolve(opts.htmlPath || DEFAULT_HTML_FILE);
3951
- const doc = renderHtml(record, { root, sessionCount: logs.length, skipped, claudeMdSource, planSource, sinceOptimize });
3952
- await writeFile2(target, doc, "utf8");
4210
+ const doc = renderHtml(record, { root, sessionCount: logs.length, skipped, claudeMdSource, planSource, sinceOptimize, license });
4211
+ await writeFile3(target, doc, "utf8");
3953
4212
  openInBrowser(target);
3954
4213
  notices.push(`HTML report written to ${target}`);
3955
4214
  }
3956
4215
  if (opts.card) {
3957
4216
  const target = resolve(opts.cardPath || DEFAULT_CARD_FILE);
3958
4217
  const svg = renderCard(record);
3959
- await writeFile2(target, svg, "utf8");
4218
+ await writeFile3(target, svg, "utf8");
3960
4219
  notices.push(`Score card written to ${target}`);
3961
4220
  }
3962
4221
  if (opts.json) {
@@ -3968,9 +4227,251 @@ async function runAudit(opts) {
3968
4227
  }
3969
4228
 
3970
4229
  // src/optimize-command.ts
3971
- import { mkdir as mkdir3, writeFile as writeFile3, readFile as readFile5, stat as stat2 } from "fs/promises";
4230
+ import { mkdir as mkdir6, writeFile as writeFile6, readFile as readFile9, stat as stat3 } from "fs/promises";
4231
+ import { basename as basename2, join as join9, resolve as resolve4 } from "path";
4232
+ import { homedir as homedir5 } from "os";
4233
+
4234
+ // src/apply-command.ts
4235
+ import { mkdir as mkdir4, writeFile as writeFile4, readFile as readFile5, rm as rm3, stat, copyFile } from "fs/promises";
3972
4236
  import { join as join6, dirname } from "path";
3973
- import { homedir as homedir4 } from "os";
4237
+ var IMPORT_LINE = "@.claude/costclaw.md";
4238
+ var INCLUDE_REL = ".claude/costclaw.md";
4239
+ var APPLY_DIR_REL = ".claude/costclaw";
4240
+ var COMPANIONS = ["PLAYBOOK.md", "HARNESS-UPGRADE.md", "settings.suggested.json"];
4241
+ var INCLUDE_ARTIFACT = "costclaw.md";
4242
+ var OPTIMIZED_ARTIFACT = "CLAUDE.optimized.md";
4243
+ async function pathExists(p) {
4244
+ try {
4245
+ await stat(p);
4246
+ return true;
4247
+ } catch {
4248
+ return false;
4249
+ }
4250
+ }
4251
+ function ensureImportLine(claudeMd) {
4252
+ if (claudeMd === null) return { text: `${IMPORT_LINE}
4253
+ `, added: true };
4254
+ const has = claudeMd.split(/\r?\n/).some((l) => l.trim() === IMPORT_LINE);
4255
+ if (has) return { text: claudeMd, added: false };
4256
+ const base = claudeMd.replace(/\s*$/, "");
4257
+ return { text: base.length === 0 ? `${IMPORT_LINE}
4258
+ ` : `${base}
4259
+
4260
+ ${IMPORT_LINE}
4261
+ `, added: true };
4262
+ }
4263
+ function stripImportLine(claudeMd) {
4264
+ const lines = claudeMd.split(/\r?\n/);
4265
+ const i = lines.findIndex((l) => l.trim() === IMPORT_LINE);
4266
+ if (i < 0) return { text: claudeMd, removed: false };
4267
+ lines.splice(i, 1);
4268
+ if (i > 0 && lines[i - 1] === "") lines.splice(i - 1, 1);
4269
+ let text2 = lines.join("\n");
4270
+ if (!text2.endsWith("\n")) text2 += "\n";
4271
+ return { text: text2 === "\n" ? "" : text2, removed: true };
4272
+ }
4273
+ async function runInclude(opts) {
4274
+ const { projectDir, artifactsDir } = opts;
4275
+ const includeSrc = join6(artifactsDir, INCLUDE_ARTIFACT);
4276
+ if (!await pathExists(includeSrc)) {
4277
+ throw new Error(`Artifacts not found in ${artifactsDir}; run costclaw optimize first`);
4278
+ }
4279
+ const includeMd = await readFile5(includeSrc, "utf8");
4280
+ const claudeDir = join6(projectDir, ".claude");
4281
+ await mkdir4(claudeDir, { recursive: true });
4282
+ const includeDest = join6(projectDir, INCLUDE_REL);
4283
+ await writeFile4(includeDest, includeMd, "utf8");
4284
+ const wrote = [includeDest];
4285
+ const lines = [`Wrote ${INCLUDE_REL}`];
4286
+ const claudeMdPath = join6(projectDir, "CLAUDE.md");
4287
+ const existing = await pathExists(claudeMdPath) ? await readFile5(claudeMdPath, "utf8") : null;
4288
+ const { text: text2, added } = ensureImportLine(existing);
4289
+ if (added) {
4290
+ await writeFile4(claudeMdPath, text2, "utf8");
4291
+ wrote.push(claudeMdPath);
4292
+ lines.push(`Added "${IMPORT_LINE}" to CLAUDE.md`);
4293
+ } else {
4294
+ lines.push("CLAUDE.md already imports it");
4295
+ }
4296
+ const companionDir = join6(projectDir, APPLY_DIR_REL);
4297
+ await mkdir4(companionDir, { recursive: true });
4298
+ for (const name of COMPANIONS) {
4299
+ const src = join6(artifactsDir, name);
4300
+ if (await pathExists(src)) {
4301
+ const dest = join6(companionDir, name);
4302
+ await copyFile(src, dest);
4303
+ wrote.push(dest);
4304
+ }
4305
+ }
4306
+ lines.push(`Copied the playbook, work order and suggested settings to ${APPLY_DIR_REL}/`);
4307
+ lines.push(`Undo: costclaw apply ${projectDir} --remove`);
4308
+ lines.push('Next: claude "Follow .claude/costclaw/HARNESS-UPGRADE.md"');
4309
+ if (opts.applySettings) {
4310
+ const settingsSrc = join6(artifactsDir, "settings.suggested.json");
4311
+ const suggestedJson = await readFile5(settingsSrc, "utf8");
4312
+ const target = opts.applySettingsPath ?? join6(projectDir, ".claude", "settings.json");
4313
+ const settingsLines = await applyDerivedSettings(target, suggestedJson, opts.force ?? false);
4314
+ lines.push(...settingsLines);
4315
+ wrote.push(target);
4316
+ }
4317
+ return { lines, wrote, removed: [] };
4318
+ }
4319
+ async function runRemove(opts) {
4320
+ const { projectDir } = opts;
4321
+ const includeDest = join6(projectDir, INCLUDE_REL);
4322
+ const companionDir = join6(projectDir, APPLY_DIR_REL);
4323
+ const removed = [];
4324
+ if (await pathExists(includeDest)) {
4325
+ await rm3(includeDest, { force: true });
4326
+ removed.push(includeDest);
4327
+ }
4328
+ if (await pathExists(companionDir)) {
4329
+ await rm3(companionDir, { recursive: true, force: true });
4330
+ removed.push(companionDir);
4331
+ }
4332
+ const lines = [`Removed ${INCLUDE_REL} and ${APPLY_DIR_REL}/`];
4333
+ const claudeMdPath = join6(projectDir, "CLAUDE.md");
4334
+ if (await pathExists(claudeMdPath)) {
4335
+ const existing = await readFile5(claudeMdPath, "utf8");
4336
+ const { text: text2, removed: didRemove } = stripImportLine(existing);
4337
+ if (didRemove) {
4338
+ if (text2 === "") {
4339
+ await rm3(claudeMdPath, { force: true });
4340
+ removed.push(claudeMdPath);
4341
+ lines.push("Removed CLAUDE.md (it held only the import line)");
4342
+ } else {
4343
+ await writeFile4(claudeMdPath, text2, "utf8");
4344
+ lines.push(`Removed "${IMPORT_LINE}" from CLAUDE.md`);
4345
+ }
4346
+ }
4347
+ }
4348
+ return { lines, wrote: [], removed };
4349
+ }
4350
+ async function runReplace(opts) {
4351
+ const { projectDir, artifactsDir, force } = opts;
4352
+ if (!await pathExists(join6(projectDir, ".git"))) {
4353
+ throw new Error(
4354
+ "apply --replace needs a git repository so the change can be undone with git checkout -- CLAUDE.md. Use the default include mode instead."
4355
+ );
4356
+ }
4357
+ const optimizedSrc = join6(artifactsDir, OPTIMIZED_ARTIFACT);
4358
+ if (!await pathExists(optimizedSrc)) {
4359
+ throw new Error(`Artifacts not found in ${artifactsDir}; run costclaw optimize first`);
4360
+ }
4361
+ const optimized = await readFile5(optimizedSrc, "utf8");
4362
+ const claudeMdPath = join6(projectDir, "CLAUDE.md");
4363
+ const backup = `${claudeMdPath}.bak`;
4364
+ if (await pathExists(backup) && !force) {
4365
+ throw new Error(
4366
+ `A backup already exists at ${backup}. Refusing to overwrite it. Pass --force to replace the existing backup.`
4367
+ );
4368
+ }
4369
+ const original = await pathExists(claudeMdPath) ? await readFile5(claudeMdPath, "utf8") : "";
4370
+ await writeFile4(backup, original, "utf8");
4371
+ await writeFile4(claudeMdPath, optimized, "utf8");
4372
+ const lines = [
4373
+ `Backed up the original to ${backup}`,
4374
+ `Wrote the optimized CLAUDE.md to ${claudeMdPath}`,
4375
+ "",
4376
+ "Diff (old vs new):",
4377
+ lineDiff(original, optimized),
4378
+ "",
4379
+ "Undo: git checkout -- CLAUDE.md (or restore CLAUDE.md.bak)"
4380
+ ];
4381
+ return { lines, wrote: [claudeMdPath, backup], removed: [] };
4382
+ }
4383
+ async function runApply(opts) {
4384
+ if (opts.mode === "replace") return runReplace(opts);
4385
+ if (opts.mode === "remove") return runRemove(opts);
4386
+ return runInclude(opts);
4387
+ }
4388
+ function lineDiff(oldText, newText) {
4389
+ const oldLines = oldText.split(/\r?\n/);
4390
+ const newLines = newText.split(/\r?\n/);
4391
+ const oldSet = new Set(oldLines);
4392
+ const newSet = new Set(newLines);
4393
+ const lines = [];
4394
+ for (const line of oldLines) {
4395
+ if (!newSet.has(line)) lines.push(`- ${line}`);
4396
+ }
4397
+ for (const line of newLines) {
4398
+ if (!oldSet.has(line)) lines.push(`+ ${line}`);
4399
+ }
4400
+ if (lines.length === 0) lines.push(" (no line-level changes)");
4401
+ return lines.join("\n");
4402
+ }
4403
+ function asStringArray(value) {
4404
+ return Array.isArray(value) ? value.filter((v) => typeof v === "string") : [];
4405
+ }
4406
+ function unionStrings(existing, additions) {
4407
+ const out = [];
4408
+ const seen = /* @__PURE__ */ new Set();
4409
+ for (const v of existing) {
4410
+ if (!seen.has(v)) {
4411
+ seen.add(v);
4412
+ out.push(v);
4413
+ }
4414
+ }
4415
+ for (const v of additions) {
4416
+ if (!seen.has(v)) {
4417
+ seen.add(v);
4418
+ out.push(v);
4419
+ }
4420
+ }
4421
+ return out;
4422
+ }
4423
+ function isPlainObject(value) {
4424
+ return typeof value === "object" && value !== null && !Array.isArray(value);
4425
+ }
4426
+ async function applyDerivedSettings(target, suggestedJson, force) {
4427
+ const backup = `${target}.bak`;
4428
+ if (await pathExists(backup) && !force) {
4429
+ throw new Error(
4430
+ `A backup already exists at ${backup}. Refusing to overwrite it. Pass --force to replace the existing backup.`
4431
+ );
4432
+ }
4433
+ let existingText = "";
4434
+ let existing = {};
4435
+ if (await pathExists(target)) {
4436
+ existingText = await readFile5(target, "utf8");
4437
+ if (existingText.trim() !== "") {
4438
+ let parsed;
4439
+ try {
4440
+ parsed = JSON.parse(existingText);
4441
+ } catch {
4442
+ throw new Error(
4443
+ `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.`
4444
+ );
4445
+ }
4446
+ if (!isPlainObject(parsed)) {
4447
+ throw new Error(
4448
+ `Expected ${target} to hold a JSON object, so it was left untouched. --apply-settings only merges into an object settings file.`
4449
+ );
4450
+ }
4451
+ existing = parsed;
4452
+ }
4453
+ }
4454
+ const suggested = JSON.parse(suggestedJson);
4455
+ const suggestedAllow = asStringArray(suggested.permissions?.allow);
4456
+ const suggestedDeny = asStringArray(suggested.permissions?.deny);
4457
+ const existingPerms = isPlainObject(existing.permissions) ? existing.permissions : {};
4458
+ const mergedPerms = { ...existingPerms };
4459
+ mergedPerms.allow = unionStrings(asStringArray(existingPerms.allow), suggestedAllow);
4460
+ mergedPerms.deny = unionStrings(asStringArray(existingPerms.deny), suggestedDeny);
4461
+ const merged = { ...existing, permissions: mergedPerms };
4462
+ const mergedText = JSON.stringify(merged, null, 2) + "\n";
4463
+ await mkdir4(dirname(target), { recursive: true });
4464
+ await writeFile4(backup, existingText, "utf8");
4465
+ await writeFile4(target, mergedText, "utf8");
4466
+ return [
4467
+ `Merged the derived permission allowlist into ${target}`,
4468
+ `Backed up the previous file to ${backup}`,
4469
+ "Only permissions.allow and permissions.deny changed (deduped union, existing entries kept and ordered first). Every other key was left as it was.",
4470
+ "",
4471
+ "Diff (previous vs merged):",
4472
+ lineDiff(existingText, mergedText)
4473
+ ];
4474
+ }
3974
4475
 
3975
4476
  // src/optimize-dashboard.ts
3976
4477
  function usd5(n) {
@@ -4314,16 +4815,21 @@ var OPTIMIZED_NAME = "CLAUDE.optimized.md";
4314
4815
  var PLAYBOOK_NAME = "PLAYBOOK.md";
4315
4816
  var SETTINGS_NAME = "settings.suggested.json";
4316
4817
  var HARNESS_NAME = "HARNESS-UPGRADE.md";
4818
+ var INCLUDE_NAME = "costclaw.md";
4317
4819
  function renderArtifactCards(input) {
4318
4820
  const { before, after } = input.claudeMdTokens;
4319
4821
  const lighter = before !== null && after < before ? ` and ${fmtTokens(before - after)} tokens lighter` : "";
4320
4822
  const placeholders = `${input.placeholdersRemaining} ${plural2(input.placeholdersRemaining, "placeholder")} to fill.`;
4321
4823
  const claudeDesc = before === null ? `A new CLAUDE.md scaffold for your project. ${placeholders}` : `Your CLAUDE.md, restructured${lighter}. ${placeholders}`;
4322
4824
  const card = (name, desc) => `<div class="file"><span class="nm">${esc(name)}</span><span class="ds">${esc(desc)}</span><a href="${esc(name)}">Open file</a></div>`;
4323
- return `<div class="files">` + card(OPTIMIZED_NAME, claudeDesc) + card(PLAYBOOK_NAME, "The ranked plan above, as a file you can keep or paste into an issue.") + card(SETTINGS_NAME, "A conservative permission allowlist derived from what you already run. Never applied unless you ask.") + card(HARNESS_NAME, "A work order for your own Claude Code. It merges the CLAUDE.md and applies what you approve.") + `</div>`;
4825
+ return `<div class="files">` + card(OPTIMIZED_NAME, claudeDesc) + card(PLAYBOOK_NAME, "The ranked plan above, as a file you can keep or paste into an issue.") + card(SETTINGS_NAME, "A conservative permission allowlist derived from what you already run. Never applied unless you ask.") + card(HARNESS_NAME, "A work order for your own Claude Code. It merges the CLAUDE.md and applies what you approve.") + card(
4826
+ INCLUDE_NAME,
4827
+ "The generated sections as a standalone include. apply writes it to .claude/costclaw.md and adds one @ line to your CLAUDE.md."
4828
+ ) + `</div>`;
4324
4829
  }
4325
4830
  function renderApplyCta(input) {
4326
- return `<div class="cta"><b>Hand the work order to your own Claude Code.</b> It merges the optimized CLAUDE.md (your facts win, the optimized structure wins), applies the permissions you approve, and fixes the harness-level findings above.<code class="cmd">claude "Follow ${esc(input.artifactsDir)}/${HARNESS_NAME}"</code><p class="note">CostClaw itself never calls a model. That is the privacy line: every number on this page came from logs already on your disk.</p></div>`;
4831
+ const applyBlock = input.applyCommand ? `<p style="margin:0">Apply the generated sections as an include (your CLAUDE.md keeps every line you wrote; undo with --remove):</p><code class="cmd">${esc(input.applyCommand)}</code><p style="margin:16px 0 0"></p>` : "";
4832
+ return `<div class="cta">` + applyBlock + `<b>Hand the work order to your own Claude Code.</b> It merges the optimized CLAUDE.md (your facts win, the optimized structure wins), applies the permissions you approve, and fixes the harness-level findings above.<code class="cmd">claude "Follow ${esc(input.artifactsDir)}/${HARNESS_NAME}"</code><p class="note">CostClaw itself never calls a model. That is the privacy line: every number on this page came from logs already on your disk.</p></div>`;
4327
4833
  }
4328
4834
  function renderCarriedDisclosure(sections, carriedTokens) {
4329
4835
  const carried = sections.filter((s) => s.disposition === "carried");
@@ -4338,7 +4844,7 @@ function renderHeader(input) {
4338
4844
  const stack = input.stack.map((s) => s.trim()).filter((s) => s.length > 0);
4339
4845
  if (stack.length > 0) parts.push(esc(stack.join(", ")));
4340
4846
  parts.push(`${input.commandsCount} ${plural2(input.commandsCount, "command")} detected`);
4341
- parts.push(`4 artifacts written to ${esc(input.artifactsDir)}/`);
4847
+ parts.push(`5 artifacts written to ${esc(input.artifactsDir)}/`);
4342
4848
  return `<header><p class="kicker">CostClaw optimize &middot; dry run &middot; nothing left your machine</p><h1>${esc(input.projectName)}</h1><p class="sub">${parts.join(" &middot; ")}</p></header>`;
4343
4849
  }
4344
4850
  function renderOptimizeDashboard(input) {
@@ -4366,7 +4872,7 @@ ${renderFixes(input.fixes, input.report)}
4366
4872
  <h2>Setup warnings<span class="n">no direct dollar figure, still costly</span></h2>
4367
4873
  ${renderSetupWarnings(input.fixes, input.report)}
4368
4874
 
4369
- <h2>Your four artifacts</h2>
4875
+ <h2>Your five artifacts</h2>
4370
4876
  ${renderArtifactCards(input)}
4371
4877
 
4372
4878
  <h2>Apply it</h2>
@@ -4382,19 +4888,90 @@ No network calls, no telemetry, no model calls.</footer>
4382
4888
  </html>
4383
4889
  `;
4384
4890
  }
4385
-
4386
- // src/project-scan.ts
4387
- import { readdir as readdir3, readFile as readFile4, stat } from "fs/promises";
4388
- import { join as join5, basename } from "path";
4389
- var NOISE_DIRS = /* @__PURE__ */ new Set([
4390
- "node_modules",
4391
- ".git",
4392
- "dist",
4393
- "build",
4394
- ".next",
4395
- "out",
4396
- ".venv",
4397
- "venv",
4891
+ var INDEX_STYLE = `
4892
+ .rowpath{display:block;font-size:.76rem;color:var(--ink2);font-family:var(--mono);word-break:break-all}
4893
+ .acts{display:flex;gap:8px;flex-wrap:wrap}
4894
+ .acts form{margin:0}
4895
+ .acts button{font:inherit;font-size:.82rem;padding:6px 12px;border-radius:7px;border:1px solid var(--line);
4896
+ background:var(--panel);color:var(--ink);cursor:pointer}
4897
+ .acts button:hover{border-color:var(--accent)}
4898
+ .acts button.go{background:var(--accent);border-color:var(--accent);color:#fff;font-weight:600}
4899
+ td code.cmd{margin-top:0;font-size:.78rem;white-space:pre-wrap;word-break:break-all}
4900
+ .banner{background:color-mix(in srgb,var(--good) 14%,transparent);border:1px solid var(--line);
4901
+ border-radius:10px;padding:12px 14px;margin:0 0 22px;font-size:.9rem}
4902
+ .state{font-size:.82rem}
4903
+ .state.on{color:var(--good);font-weight:650}
4904
+ .state.off{color:var(--ink2)}
4905
+ `;
4906
+ function indexTokens(tokens) {
4907
+ if (tokens.before === null) return `${esc(approxTokens(tokens.after))} (new file)`;
4908
+ return `${esc(approxTokens(tokens.before))} to ${esc(approxTokens(tokens.after))}`;
4909
+ }
4910
+ function indexStatus(appliedAt) {
4911
+ if (!appliedAt) return `<span class="state off">not applied</span>`;
4912
+ return `<span class="state on">applied ${esc(appliedAt.slice(0, 10))}</span>`;
4913
+ }
4914
+ function actionForm(token, slug, action, label, primary) {
4915
+ return `<form method="post" action="/apply"><input type="hidden" name="token" value="${esc(token)}"><input type="hidden" name="slug" value="${esc(slug)}"><input type="hidden" name="action" value="${esc(action)}"><button type="submit"${primary ? ' class="go"' : ""}>${esc(label)}</button></form>`;
4916
+ }
4917
+ function indexActions(row, serve) {
4918
+ const details = `<a href="${esc(row.artifactsHref)}">details</a>`;
4919
+ if (!serve) {
4920
+ return `<code class="cmd">${esc(row.applyCommand)}</code><p class="note" style="margin-top:6px">${details}</p>`;
4921
+ }
4922
+ return `<div class="acts">` + actionForm(serve.token, row.slug, "include", "Apply", true) + actionForm(serve.token, row.slug, "remove", "Remove", false) + actionForm(serve.token, row.slug, "settings", "Apply settings", false) + `</div><p class="note" style="margin-top:6px">${details}</p>`;
4923
+ }
4924
+ function renderOptimizeIndex(input) {
4925
+ const total = input.rows.reduce((sum, r) => sum + r.spendUsd, 0);
4926
+ const recoverable = input.rows.reduce((sum, r) => sum + r.recoverableUsd, 0);
4927
+ const rows = input.rows.map(
4928
+ (r) => `<tr><td><b>${esc(r.slug)}</b><span class="rowpath">${esc(r.projectDir)}</span></td><td class="num">${esc(usd5(r.spendUsd))}</td><td class="num">${esc(usd5(r.recoverableUsd))}</td><td>${indexTokens(r.tokens)}</td><td>${indexStatus(r.appliedAt)}</td><td>${indexActions(r, input.serve)}</td></tr>`
4929
+ ).join("");
4930
+ const body = input.rows.length === 0 ? `<p class="note">No project directories from your audit were found on this machine, so nothing was generated.</p>` : `<div class="scroll"><table><thead><tr><th>Project</th><th class="num">Spend</th><th class="num">Recoverable</th><th>CLAUDE.md tokens</th><th>Status</th><th>Actions</th></tr></thead><tbody>${rows}</tbody></table></div>`;
4931
+ const banner = input.serve?.message ? `<p class="banner">${esc(input.serve.message)}</p>` : "";
4932
+ const done = input.serve ? `<div class="acts" style="margin:0 0 22px"><form method="post" action="/done"><input type="hidden" name="token" value="${esc(input.serve.token)}"><button type="submit">Done</button></form></div>` : "";
4933
+ const how = input.serve ? `<p class="note">Apply writes <code>.claude/costclaw.md</code> and adds one <code>@.claude/costclaw.md</code> line to that project's CLAUDE.md. Every line you wrote stays where it is. Remove undoes both.</p>` : `<p class="note">Run the line on a project's row to apply it. It writes <code>.claude/costclaw.md</code> and adds one <code>@.claude/costclaw.md</code> line to that project's CLAUDE.md; every line you wrote stays where it is. Undo with <code>--remove</code>.</p>`;
4934
+ return `<!doctype html>
4935
+ <html lang="en">
4936
+ <head>
4937
+ <meta charset="utf-8">
4938
+ <meta name="viewport" content="width=device-width,initial-scale=1">
4939
+ <title>CostClaw optimize: ${input.rows.length} ${plural2(input.rows.length, "project")}</title>
4940
+ <style>${STYLE2}${INDEX_STYLE}</style>
4941
+ </head>
4942
+ <body>
4943
+ <div class="wrap">
4944
+ <header><p class="kicker">CostClaw optimize &middot; generated locally &middot; nothing left your machine</p>
4945
+ <h1>${input.rows.length} ${plural2(input.rows.length, "project")} ready to apply</h1>
4946
+ <p class="sub">${esc(usd5(total))} of analyzed spend &middot; ${esc(usd5(recoverable))} recoverable &middot;
4947
+ artifacts in ${esc(input.root)}/</p></header>
4948
+
4949
+ ${banner}${done}
4950
+ <h2>Your projects<span class="n">ranked by spend</span></h2>
4951
+ ${body}
4952
+ ${how}
4953
+
4954
+ <footer>Generated locally by CostClaw v${esc(input.version)} on ${esc(input.generatedAt)}.
4955
+ Nothing was written inside any project. No network calls, no telemetry, no model calls.</footer>
4956
+
4957
+ </div>
4958
+ </body>
4959
+ </html>
4960
+ `;
4961
+ }
4962
+
4963
+ // src/project-scan.ts
4964
+ import { readdir as readdir3, readFile as readFile6, stat as stat2 } from "fs/promises";
4965
+ import { join as join7, basename } from "path";
4966
+ var NOISE_DIRS = /* @__PURE__ */ new Set([
4967
+ "node_modules",
4968
+ ".git",
4969
+ "dist",
4970
+ "build",
4971
+ ".next",
4972
+ "out",
4973
+ ".venv",
4974
+ "venv",
4398
4975
  "target",
4399
4976
  "coverage",
4400
4977
  ".cache"
@@ -4414,7 +4991,7 @@ var DIR_NOTES = {
4414
4991
  };
4415
4992
  async function readText(p) {
4416
4993
  try {
4417
- return await readFile4(p, "utf8");
4994
+ return await readFile6(p, "utf8");
4418
4995
  } catch {
4419
4996
  return null;
4420
4997
  }
@@ -4524,7 +5101,7 @@ async function containsTestFiles(dir) {
4524
5101
  const top = await listEntries(dir);
4525
5102
  if (top.files.some((f) => TEST_FILE.test(f))) return true;
4526
5103
  for (const sub of top.dirs) {
4527
- const inner = await listEntries(join5(dir, sub));
5104
+ const inner = await listEntries(join7(dir, sub));
4528
5105
  if (inner.files.some((f) => TEST_FILE.test(f))) return true;
4529
5106
  }
4530
5107
  return false;
@@ -4534,14 +5111,14 @@ async function detectTestsLocation(dir, files, dirs) {
4534
5111
  if (candidates.length > 0) {
4535
5112
  const withTests = [];
4536
5113
  for (const c of candidates) {
4537
- if (await containsTestFiles(join5(dir, c))) withTests.push(c);
5114
+ if (await containsTestFiles(join7(dir, c))) withTests.push(c);
4538
5115
  }
4539
5116
  const chosen = withTests.length > 0 ? withTests : candidates;
4540
5117
  return `tests in ${chosen.map((c) => `${c}/`).join(" and ")}`;
4541
5118
  }
4542
5119
  if (files.some((f) => TEST_FILE.test(f))) return "tests alongside source (*.test.* / *.spec.*)";
4543
5120
  if (dirs.includes("src")) {
4544
- const sub = await listEntries(join5(dir, "src"));
5121
+ const sub = await listEntries(join7(dir, "src"));
4545
5122
  if (sub.files.some((f) => TEST_FILE.test(f))) {
4546
5123
  return "tests alongside source (*.test.* / *.spec.*)";
4547
5124
  }
@@ -4624,7 +5201,7 @@ async function scanNode(dir, files, dirs, pkg, profile) {
4624
5201
  if (oneFileCmd !== null && "test" in scripts) {
4625
5202
  profile.commands.push({ label: "test one file", command: oneFileCmd });
4626
5203
  }
4627
- const tsconfig = parseJson(await readText(join5(dir, "tsconfig.json")));
5204
+ const tsconfig = parseJson(await readText(join7(dir, "tsconfig.json")));
4628
5205
  if (tsconfig) {
4629
5206
  const co = tsconfig.compilerOptions;
4630
5207
  if (co && co.strict === true) pushUnique(profile.codeStyle, "TypeScript strict mode");
@@ -4727,7 +5304,7 @@ async function scanPython(dir, files, profile) {
4727
5304
  const deps = [];
4728
5305
  const tables = /* @__PURE__ */ new Set();
4729
5306
  let hasPoetry = false;
4730
- const pyprojectText = await readText(join5(dir, "pyproject.toml"));
5307
+ const pyprojectText = await readText(join7(dir, "pyproject.toml"));
4731
5308
  if (pyprojectText !== null) {
4732
5309
  const parsed = parsePyproject(pyprojectText);
4733
5310
  name = parsed.name;
@@ -4737,7 +5314,7 @@ async function scanPython(dir, files, profile) {
4737
5314
  hasPoetry = parsed.hasPoetry;
4738
5315
  }
4739
5316
  if (files.includes("requirements.txt")) {
4740
- const reqText = await readText(join5(dir, "requirements.txt"));
5317
+ const reqText = await readText(join7(dir, "requirements.txt"));
4741
5318
  if (reqText !== null) for (const d of pyDepsFromRequirements(reqText)) pushUnique(deps, d);
4742
5319
  }
4743
5320
  if (name !== null && name.trim() !== "") profile.name = name;
@@ -4771,7 +5348,7 @@ async function scanPython(dir, files, profile) {
4771
5348
  }
4772
5349
  }
4773
5350
  async function scanRust(dir, profile) {
4774
- const text2 = await readText(join5(dir, "Cargo.toml"));
5351
+ const text2 = await readText(join7(dir, "Cargo.toml"));
4775
5352
  pushUnique(profile.stack, "Rust");
4776
5353
  profile.packageManager = "cargo";
4777
5354
  if (text2 !== null) {
@@ -4797,7 +5374,7 @@ async function scanRust(dir, profile) {
4797
5374
  profile.commands.push({ label: "lint", command: "cargo clippy" });
4798
5375
  }
4799
5376
  async function scanGo(dir, profile) {
4800
- const text2 = await readText(join5(dir, "go.mod"));
5377
+ const text2 = await readText(join7(dir, "go.mod"));
4801
5378
  pushUnique(profile.stack, "Go");
4802
5379
  profile.packageManager = "go";
4803
5380
  if (text2 !== null) {
@@ -4862,7 +5439,7 @@ async function scanProject(dir) {
4862
5439
  const profile = emptyProfile(basename(dir));
4863
5440
  const { files, dirs } = await listEntries(dir);
4864
5441
  if (files.includes("package.json")) {
4865
- const pkg = parseJson(await readText(join5(dir, "package.json")));
5442
+ const pkg = parseJson(await readText(join7(dir, "package.json")));
4866
5443
  if (pkg) await scanNode(dir, files, dirs, pkg, profile);
4867
5444
  }
4868
5445
  if (files.includes("pyproject.toml") || files.includes("requirements.txt") || files.includes("setup.py")) {
@@ -4875,7 +5452,7 @@ async function scanProject(dir) {
4875
5452
  await scanGo(dir, profile);
4876
5453
  }
4877
5454
  if (files.includes("Makefile") && profile.commands.length === 0) {
4878
- const text2 = await readText(join5(dir, "Makefile"));
5455
+ const text2 = await readText(join7(dir, "Makefile"));
4879
5456
  if (text2 !== null) {
4880
5457
  for (const t of parseMakefile(text2)) {
4881
5458
  profile.commands.push({ label: t, command: `make ${t}` });
@@ -4885,7 +5462,7 @@ async function scanProject(dir) {
4885
5462
  if (profile.description === null || profile.name === basename(dir)) {
4886
5463
  const readmeName = files.find((f) => /^readme(\.md|\.markdown|\.txt)?$/i.test(f));
4887
5464
  if (readmeName) {
4888
- const text2 = await readText(join5(dir, readmeName));
5465
+ const text2 = await readText(join7(dir, readmeName));
4889
5466
  if (text2 !== null) {
4890
5467
  const parsed = parseReadme(text2);
4891
5468
  if (profile.name === basename(dir) && parsed.name !== null) profile.name = parsed.name;
@@ -4898,21 +5475,312 @@ async function scanProject(dir) {
4898
5475
  profile.structure = await detectStructure(dir, dirs);
4899
5476
  const envFile = files.includes(".env.example") ? ".env.example" : files.includes(".env.sample") ? ".env.sample" : null;
4900
5477
  if (envFile) {
4901
- const text2 = await readText(join5(dir, envFile));
5478
+ const text2 = await readText(join7(dir, envFile));
4902
5479
  if (text2 !== null) profile.envVars = parseEnvNames(text2);
4903
5480
  }
4904
5481
  return profile;
4905
5482
  }
4906
5483
 
5484
+ // src/serve.ts
5485
+ import { createServer } from "http";
5486
+ import { randomBytes } from "crypto";
5487
+ import { readFile as readFile7 } from "fs/promises";
5488
+ import { extname, resolve as resolve2, sep as sep2 } from "path";
5489
+ var DEFAULT_IDLE_MS = 30 * 60 * 1e3;
5490
+ var MAX_BODY_BYTES = 64 * 1024;
5491
+ var DASHBOARD_NAME = "DASHBOARD.html";
5492
+ function parseForm(body) {
5493
+ const out = {};
5494
+ for (const pair of body.split("&")) {
5495
+ if (pair === "") continue;
5496
+ const eq = pair.indexOf("=");
5497
+ const rawKey = eq < 0 ? pair : pair.slice(0, eq);
5498
+ const rawValue = eq < 0 ? "" : pair.slice(eq + 1);
5499
+ const key = decodeURIComponent(rawKey.replace(/\+/g, " "));
5500
+ const value = decodeURIComponent(rawValue.replace(/\+/g, " "));
5501
+ out[key] = value;
5502
+ }
5503
+ return out;
5504
+ }
5505
+ function safeArtifactPath(root, urlPath) {
5506
+ let decoded;
5507
+ try {
5508
+ decoded = decodeURIComponent(urlPath);
5509
+ } catch {
5510
+ return null;
5511
+ }
5512
+ if (decoded.includes("\0")) return null;
5513
+ const resolvedRoot = resolve2(root);
5514
+ const full = resolve2(resolvedRoot, "." + decoded);
5515
+ if (full !== resolvedRoot && !full.startsWith(resolvedRoot + sep2)) return null;
5516
+ return full;
5517
+ }
5518
+ function rowsFromManifest(manifest) {
5519
+ return manifest.projects.map((e) => ({
5520
+ slug: e.slug,
5521
+ projectDir: e.projectDir,
5522
+ artifactsHref: `${e.dir}/${DASHBOARD_NAME}`,
5523
+ spendUsd: e.spendUsd,
5524
+ recoverableUsd: e.recoverableUsd,
5525
+ tokens: e.tokens,
5526
+ ...e.appliedAt ? { appliedAt: e.appliedAt } : {},
5527
+ applyCommand: `costclaw apply ${e.projectDir}`
5528
+ }));
5529
+ }
5530
+ function isApplyAction(value) {
5531
+ return value === "include" || value === "remove" || value === "settings";
5532
+ }
5533
+ var CONTENT_TYPES = {
5534
+ ".html": "text/html; charset=utf-8",
5535
+ ".md": "text/plain; charset=utf-8",
5536
+ ".json": "application/json; charset=utf-8"
5537
+ };
5538
+ function contentTypeFor(path) {
5539
+ return CONTENT_TYPES[extname(path).toLowerCase()] ?? "application/octet-stream";
5540
+ }
5541
+ function readBody(req, limitBytes) {
5542
+ return new Promise((resolvePromise, reject) => {
5543
+ const chunks = [];
5544
+ let size = 0;
5545
+ req.on("data", (chunk) => {
5546
+ size += chunk.length;
5547
+ if (size > limitBytes) {
5548
+ reject(new Error("payload too large"));
5549
+ return;
5550
+ }
5551
+ chunks.push(chunk);
5552
+ });
5553
+ req.on("end", () => resolvePromise(Buffer.concat(chunks).toString("utf8")));
5554
+ req.on("error", reject);
5555
+ });
5556
+ }
5557
+ function sendText(res, status, text2) {
5558
+ res.writeHead(status, { "content-type": "text/plain; charset=utf-8" });
5559
+ res.end(text2);
5560
+ }
5561
+ async function startApplyServer(opts) {
5562
+ const token = randomBytes(16).toString("hex");
5563
+ const idleMs = opts.idleMs ?? DEFAULT_IDLE_MS;
5564
+ const manifest = opts.manifest;
5565
+ let closedAlready = false;
5566
+ let resolveClosed;
5567
+ const closedPromise = new Promise((res) => {
5568
+ resolveClosed = res;
5569
+ });
5570
+ let idleTimer;
5571
+ function resetIdle() {
5572
+ clearTimeout(idleTimer);
5573
+ idleTimer = setTimeout(() => {
5574
+ void close();
5575
+ }, idleMs);
5576
+ idleTimer.unref();
5577
+ }
5578
+ async function close() {
5579
+ if (closedAlready) return;
5580
+ closedAlready = true;
5581
+ clearTimeout(idleTimer);
5582
+ await new Promise((res) => server.close(() => res()));
5583
+ resolveClosed();
5584
+ }
5585
+ async function handleIndex(req, res, search) {
5586
+ const msg = search.get("msg");
5587
+ const html = renderOptimizeIndex({
5588
+ version: opts.version,
5589
+ generatedAt: manifest.generatedAt,
5590
+ root: opts.root,
5591
+ rows: rowsFromManifest(manifest),
5592
+ serve: { token, ...msg ? { message: msg } : {} }
5593
+ });
5594
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
5595
+ res.end(html);
5596
+ }
5597
+ async function handleApply(req, res) {
5598
+ let body;
5599
+ try {
5600
+ body = await readBody(req, MAX_BODY_BYTES);
5601
+ } catch {
5602
+ sendText(res, 400, "Payload too large");
5603
+ return;
5604
+ }
5605
+ const form = parseForm(body);
5606
+ if (form["token"] !== token) {
5607
+ sendText(res, 403, "Forbidden");
5608
+ return;
5609
+ }
5610
+ const action = form["action"];
5611
+ if (!isApplyAction(action)) {
5612
+ sendText(res, 400, "Unknown action");
5613
+ return;
5614
+ }
5615
+ const entry = manifest.projects.find((p) => p.slug === form["slug"]);
5616
+ if (!entry) {
5617
+ sendText(res, 400, "Unknown project");
5618
+ return;
5619
+ }
5620
+ let msg;
5621
+ try {
5622
+ const lines = await opts.apply(entry, action);
5623
+ if (action === "remove") delete entry.appliedAt;
5624
+ else entry.appliedAt = (/* @__PURE__ */ new Date()).toISOString();
5625
+ if (opts.onManifestChange) await opts.onManifestChange(manifest);
5626
+ msg = lines[0] ?? "Done.";
5627
+ } catch (err) {
5628
+ msg = `Error: ${err instanceof Error ? err.message : String(err)}`;
5629
+ }
5630
+ res.writeHead(303, { Location: `/?msg=${encodeURIComponent(msg)}` });
5631
+ res.end();
5632
+ }
5633
+ async function handleDone(req, res) {
5634
+ let body;
5635
+ try {
5636
+ body = await readBody(req, MAX_BODY_BYTES);
5637
+ } catch {
5638
+ body = "";
5639
+ }
5640
+ const form = parseForm(body);
5641
+ if (form["token"] !== token) {
5642
+ sendText(res, 403, "Forbidden");
5643
+ return;
5644
+ }
5645
+ sendText(res, 200, "You can close this tab.");
5646
+ void close();
5647
+ }
5648
+ async function handleStatic(pathname, res) {
5649
+ const filePath = safeArtifactPath(opts.root, pathname);
5650
+ if (!filePath) {
5651
+ sendText(res, 404, "Not found");
5652
+ return;
5653
+ }
5654
+ try {
5655
+ const data = await readFile7(filePath);
5656
+ res.writeHead(200, { "content-type": contentTypeFor(filePath) });
5657
+ res.end(data);
5658
+ } catch {
5659
+ sendText(res, 404, "Not found");
5660
+ }
5661
+ }
5662
+ async function handle(req, res) {
5663
+ const url = new URL(req.url ?? "/", "http://127.0.0.1");
5664
+ const method = req.method ?? "GET";
5665
+ if (url.pathname === "/" && method === "GET") {
5666
+ await handleIndex(req, res, url.searchParams);
5667
+ return;
5668
+ }
5669
+ if (url.pathname === "/apply" && method === "POST") {
5670
+ await handleApply(req, res);
5671
+ return;
5672
+ }
5673
+ if (url.pathname === "/done" && method === "POST") {
5674
+ await handleDone(req, res);
5675
+ return;
5676
+ }
5677
+ if (method === "GET") {
5678
+ await handleStatic(url.pathname, res);
5679
+ return;
5680
+ }
5681
+ sendText(res, 404, "Not found");
5682
+ }
5683
+ const server = createServer((req, res) => {
5684
+ resetIdle();
5685
+ handle(req, res).catch((err) => {
5686
+ if (!res.headersSent) {
5687
+ res.writeHead(500, { "content-type": "text/plain; charset=utf-8" });
5688
+ }
5689
+ res.end(`Internal error: ${err instanceof Error ? err.message : String(err)}`);
5690
+ });
5691
+ });
5692
+ await new Promise((res, reject) => {
5693
+ server.once("error", reject);
5694
+ server.listen(0, "127.0.0.1", () => res());
5695
+ });
5696
+ resetIdle();
5697
+ const address = server.address();
5698
+ if (address === null || typeof address === "string") {
5699
+ throw new Error("failed to bind the loopback apply server");
5700
+ }
5701
+ return {
5702
+ url: `http://127.0.0.1:${address.port}`,
5703
+ port: address.port,
5704
+ close,
5705
+ closed: closedPromise
5706
+ };
5707
+ }
5708
+
5709
+ // src/optimize-manifest.ts
5710
+ import { mkdir as mkdir5, readFile as readFile8, writeFile as writeFile5 } from "fs/promises";
5711
+ import { join as join8, resolve as resolve3 } from "path";
5712
+ var MANIFEST_NAME = "index.json";
5713
+ function defaultOptimizeRoot(home) {
5714
+ return join8(home, ".costclaw", "optimize");
5715
+ }
5716
+ function isRecord(value) {
5717
+ return typeof value === "object" && value !== null && !Array.isArray(value);
5718
+ }
5719
+ async function readManifest(root) {
5720
+ let text2;
5721
+ try {
5722
+ text2 = await readFile8(join8(root, MANIFEST_NAME), "utf8");
5723
+ } catch {
5724
+ return null;
5725
+ }
5726
+ let parsed;
5727
+ try {
5728
+ parsed = JSON.parse(text2);
5729
+ } catch {
5730
+ return null;
5731
+ }
5732
+ if (!isRecord(parsed) || !Array.isArray(parsed["projects"])) return null;
5733
+ const projects = parsed["projects"].filter((p) => isRecord(p) && typeof p["projectDir"] === "string");
5734
+ return {
5735
+ generatedAt: typeof parsed["generatedAt"] === "string" ? parsed["generatedAt"] : "",
5736
+ root: typeof parsed["root"] === "string" ? parsed["root"] : root,
5737
+ projects
5738
+ };
5739
+ }
5740
+ async function writeManifest(root, m) {
5741
+ await mkdir5(root, { recursive: true });
5742
+ await writeFile5(join8(root, MANIFEST_NAME), JSON.stringify(m, null, 2) + "\n", "utf8");
5743
+ }
5744
+ function normalizePath(p) {
5745
+ const r = resolve3(p);
5746
+ return process.platform === "win32" ? r.toLowerCase() : r;
5747
+ }
5748
+ function findEntry(m, projectDir) {
5749
+ const want = normalizePath(projectDir);
5750
+ return m.projects.find((p) => normalizePath(p.projectDir) === want);
5751
+ }
5752
+ function fnv1a(text2) {
5753
+ let h = 2166136261;
5754
+ for (let i = 0; i < text2.length; i++) {
5755
+ h ^= text2.charCodeAt(i);
5756
+ h = Math.imul(h, 16777619) >>> 0;
5757
+ }
5758
+ return h.toString(16).padStart(8, "0");
5759
+ }
5760
+ function safeDirName(slug) {
5761
+ const cleaned = slug.replace(/[^A-Za-z0-9._-]+/g, "-").replace(/^[-.]+|[-.]+$/g, "");
5762
+ return cleaned.length > 0 ? cleaned : "project";
5763
+ }
5764
+ function artifactDirName(slug, projectDir, taken) {
5765
+ const base = safeDirName(slug);
5766
+ if (!taken.has(base)) return base;
5767
+ return `${base}-${fnv1a(normalizePath(projectDir))}`;
5768
+ }
5769
+
4907
5770
  // src/optimize-command.ts
4908
5771
  var OPTIMIZED_NAME2 = "CLAUDE.optimized.md";
4909
5772
  var PLAYBOOK_NAME2 = "PLAYBOOK.md";
4910
5773
  var SETTINGS_NAME2 = "settings.suggested.json";
4911
5774
  var HARNESS_NAME2 = "HARNESS-UPGRADE.md";
4912
- var DASHBOARD_NAME = "DASHBOARD.html";
5775
+ var DASHBOARD_NAME2 = "DASHBOARD.html";
5776
+ var INCLUDE_NAME2 = "costclaw.md";
5777
+ var DEFAULT_LIMIT = 10;
4913
5778
  function usd6(n) {
4914
5779
  return `$${(Math.round(n * 100) / 100).toFixed(2)}`;
4915
5780
  }
5781
+ function num5(n) {
5782
+ return String(Math.round(n)).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
5783
+ }
4916
5784
  function describeDetection(project) {
4917
5785
  const name = project.name?.trim() || "unnamed project";
4918
5786
  const n = project.commands.length;
@@ -4927,276 +5795,321 @@ function unscannedWarning(projectDir) {
4927
5795
  return [
4928
5796
  `Warning: the scan found no stack and no commands in ${projectDir}.`,
4929
5797
  "Are you in the right folder? optimize fills the scaffold from a project's own files,",
4930
- "so run it from inside a project, or point it at one with --project <dir>."
5798
+ "so point it at a project with --project <dir>."
4931
5799
  ];
4932
5800
  }
4933
- async function pathExists(p) {
5801
+ async function pathExists2(p) {
4934
5802
  try {
4935
- await stat2(p);
5803
+ await stat3(p);
4936
5804
  return true;
4937
5805
  } catch {
4938
5806
  return false;
4939
5807
  }
4940
5808
  }
4941
- function lineDiff(oldText, newText) {
4942
- const oldLines = oldText.split(/\r?\n/);
4943
- const newLines = newText.split(/\r?\n/);
4944
- const oldSet = new Set(oldLines);
4945
- const newSet = new Set(newLines);
4946
- const lines = [];
4947
- for (const line of oldLines) {
4948
- if (!newSet.has(line)) lines.push(`- ${line}`);
4949
- }
4950
- for (const line of newLines) {
4951
- if (!oldSet.has(line)) lines.push(`+ ${line}`);
4952
- }
4953
- if (lines.length === 0) lines.push(" (no line-level changes)");
4954
- return lines.join("\n");
5809
+ function projectSpend(report, slug) {
5810
+ const p = report.projects.find((x) => x.slug === slug);
5811
+ return p ? p.cost_usd : null;
4955
5812
  }
4956
- function asStringArray(value) {
4957
- return Array.isArray(value) ? value.filter((v) => typeof v === "string") : [];
5813
+ function projectRecoverable(report, slug) {
5814
+ const row = cacheMissByProject(report).find((r) => r.slug === slug);
5815
+ return row ? row.usd : null;
4958
5816
  }
4959
- function unionStrings(existing, additions) {
4960
- const out = [];
4961
- const seen = /* @__PURE__ */ new Set();
4962
- for (const v of existing) {
4963
- if (!seen.has(v)) {
4964
- seen.add(v);
4965
- out.push(v);
4966
- }
4967
- }
4968
- for (const v of additions) {
4969
- if (!seen.has(v)) {
4970
- seen.add(v);
4971
- out.push(v);
5817
+ async function generateForProject(ctx, projectDir, artifactsDir) {
5818
+ const slug = basename2(resolve4(projectDir));
5819
+ let currentClaudeMd = ctx.claudeMdOverride;
5820
+ let claudeMdSource = ctx.claudeMdOverride !== void 0 ? ctx.claudeMdFallbackSource : null;
5821
+ if (currentClaudeMd === void 0) {
5822
+ const own = join9(projectDir, "CLAUDE.md");
5823
+ if (await pathExists2(own)) {
5824
+ currentClaudeMd = await readFile9(own, "utf8");
5825
+ claudeMdSource = own;
5826
+ } else {
5827
+ currentClaudeMd = ctx.globalClaudeMd;
5828
+ claudeMdSource = ctx.globalClaudeMd === void 0 ? null : ctx.claudeMdFallbackSource;
4972
5829
  }
4973
5830
  }
4974
- return out;
4975
- }
4976
- function isPlainObject(value) {
4977
- return typeof value === "object" && value !== null && !Array.isArray(value);
4978
- }
4979
- async function applyDerivedSettings(target, suggestedJson, force) {
4980
- const backup = `${target}.bak`;
4981
- if (await pathExists(backup) && !force) {
4982
- throw new Error(
4983
- `A backup already exists at ${backup}. Refusing to overwrite it. Pass --force to replace the existing backup.`
5831
+ const project = await scanProject(projectDir);
5832
+ const result = optimize({
5833
+ report: ctx.report,
5834
+ scores: ctx.pillars,
5835
+ fixes: ctx.fixes,
5836
+ currentClaudeMd,
5837
+ project
5838
+ });
5839
+ await mkdir6(artifactsDir, { recursive: true });
5840
+ await writeFile6(join9(artifactsDir, OPTIMIZED_NAME2), result.optimizedClaudeMd, "utf8");
5841
+ await writeFile6(join9(artifactsDir, PLAYBOOK_NAME2), result.playbook, "utf8");
5842
+ await writeFile6(join9(artifactsDir, SETTINGS_NAME2), result.settingsJson, "utf8");
5843
+ await writeFile6(join9(artifactsDir, HARNESS_NAME2), result.harnessPrompt, "utf8");
5844
+ await writeFile6(join9(artifactsDir, INCLUDE_NAME2), result.includeMd, "utf8");
5845
+ const spend = projectSpend(ctx.report, slug);
5846
+ const recoverable = projectRecoverable(ctx.report, slug);
5847
+ const applyCommand = `costclaw apply ${projectDir}`;
5848
+ if (ctx.dashboard) {
5849
+ const auditSpend = ctx.report.summary.cost_usd;
5850
+ const auditRecoverable2 = cacheMissExposureUsd(ctx.report);
5851
+ const html = renderOptimizeDashboard({
5852
+ version: ctx.version,
5853
+ projectName: project.name ?? slug,
5854
+ stack: project.stack,
5855
+ commandsCount: project.commands.length,
5856
+ artifactsDir,
5857
+ currentClaudeMd: currentClaudeMd ?? null,
5858
+ optimizedClaudeMd: result.optimizedClaudeMd,
5859
+ claudeMdTokens: result.claudeMdTokens,
5860
+ carriedTokens: result.carriedTokens,
5861
+ sectionDispositions: result.sectionDispositions,
5862
+ placeholdersRemaining: result.placeholdersRemaining,
5863
+ fixes: ctx.fixes,
5864
+ report: ctx.report,
5865
+ headlineWasteShare: auditSpend > 0 ? auditRecoverable2 / auditSpend : 0,
5866
+ headlineWasteUsd: auditRecoverable2,
5867
+ applyCommand
5868
+ });
5869
+ await writeFile6(join9(artifactsDir, DASHBOARD_NAME2), html, "utf8");
5870
+ }
5871
+ const lines = ctx.lines;
5872
+ lines.push(slug);
5873
+ if (looksUnscanned(project)) lines.push(...unscannedWarning(projectDir));
5874
+ lines.push(describeDetection(project));
5875
+ if (claudeMdSource) lines.push(`Existing CLAUDE.md: ${claudeMdSource}`);
5876
+ const auditRecoverable = cacheMissExposureUsd(ctx.report);
5877
+ const shownRecoverable = recoverable ?? auditRecoverable;
5878
+ const denominator = recoverable !== null ? spend ?? 0 : ctx.report.summary.cost_usd;
5879
+ const scopeLabel = recoverable !== null ? `for ${slug}` : "across your audited projects";
5880
+ if (ctx.plan === "api") {
5881
+ lines.push(`Recoverable spend (cache-miss exposure) ${scopeLabel}: ${usd6(shownRecoverable)}`);
5882
+ } else {
5883
+ const share = denominator > 0 ? shownRecoverable / denominator * 100 : 0;
5884
+ lines.push(
5885
+ `Recoverable usage (cache-miss exposure) ${scopeLabel}: ${share.toFixed(1)}% of analyzed usage (${usd6(shownRecoverable)} at API rates)`
4984
5886
  );
4985
5887
  }
4986
- let existingText = "";
4987
- let existing = {};
4988
- if (await pathExists(target)) {
4989
- existingText = await readFile5(target, "utf8");
4990
- if (existingText.trim() !== "") {
4991
- let parsed;
4992
- try {
4993
- parsed = JSON.parse(existingText);
4994
- } catch {
4995
- throw new Error(
4996
- `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.`
4997
- );
4998
- }
4999
- if (!isPlainObject(parsed)) {
5000
- throw new Error(
5001
- `Expected ${target} to hold a JSON object, so it was left untouched. --apply-settings only merges into an object settings file.`
5002
- );
5003
- }
5004
- existing = parsed;
5888
+ const { before, after } = result.claudeMdTokens;
5889
+ if (before != null && before !== after) {
5890
+ const pct2 = before > 0 ? (Math.abs(after - before) / before * 100).toFixed(1) : "0.0";
5891
+ const dir = after > before ? "larger" : "smaller";
5892
+ lines.push(
5893
+ `Your CLAUDE.md: an estimated ${num5(before)} tokens to ${num5(after)} (${pct2}% ${dir}), paid on every turn.`
5894
+ );
5895
+ if (result.carriedTokens >= after / 2) {
5896
+ lines.push(
5897
+ `About ${num5(result.carriedTokens)} of those tokens are your own prose, carried through as written.`,
5898
+ "costclaw does not rewrite prose, so trimming it is judgment work: HARNESS-UPGRADE.md",
5899
+ "ranks your heaviest sections and flags the dated lines to move into docs/."
5900
+ );
5005
5901
  }
5006
5902
  }
5007
- const suggested = JSON.parse(suggestedJson);
5008
- const suggestedAllow = asStringArray(suggested.permissions?.allow);
5009
- const suggestedDeny = asStringArray(suggested.permissions?.deny);
5010
- const existingPerms = isPlainObject(existing.permissions) ? existing.permissions : {};
5011
- const mergedPerms = { ...existingPerms };
5012
- mergedPerms.allow = unionStrings(asStringArray(existingPerms.allow), suggestedAllow);
5013
- mergedPerms.deny = unionStrings(asStringArray(existingPerms.deny), suggestedDeny);
5014
- const merged = { ...existing, permissions: mergedPerms };
5015
- const mergedText = JSON.stringify(merged, null, 2) + "\n";
5016
- await mkdir3(dirname(target), { recursive: true });
5017
- await writeFile3(backup, existingText, "utf8");
5018
- await writeFile3(target, mergedText, "utf8");
5019
- return [
5020
- `Merged the derived permission allowlist into ${target}`,
5021
- `Backed up the previous file to ${backup}`,
5022
- "Only permissions.allow and permissions.deny changed (deduped union, existing entries kept and ordered first). Every other key was left as it was.",
5023
- "",
5024
- "Diff (previous vs merged):",
5025
- lineDiff(existingText, mergedText)
5026
- ];
5903
+ if (result.placeholdersRemaining > 0) {
5904
+ const n = result.placeholdersRemaining;
5905
+ lines.push(
5906
+ `${n} section${n === 1 ? "" : "s"} left as placeholder${n === 1 ? "" : "s"} (no evidence to fill ${n === 1 ? "it" : "them"}); search the scaffold for <!-- ... -->.`
5907
+ );
5908
+ }
5909
+ for (const note of result.notes) lines.push(` - ${note}`);
5910
+ lines.push(`Artifacts: ${artifactsDir}`);
5911
+ lines.push(`Apply: ${applyCommand}`);
5912
+ lines.push("");
5913
+ return {
5914
+ slug,
5915
+ dir: basename2(artifactsDir),
5916
+ projectDir,
5917
+ artifactsDir,
5918
+ spendUsd: spend ?? 0,
5919
+ recoverableUsd: recoverable ?? 0,
5920
+ tokens: result.claudeMdTokens,
5921
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString()
5922
+ };
5027
5923
  }
5028
5924
  async function runOptimize(opts) {
5029
- const projectDir = opts.projectDir || process.cwd();
5030
- let claudeMdPath = opts.claudeMdPath;
5031
- if (!claudeMdPath) {
5032
- const projectClaudeMd = join6(projectDir, "CLAUDE.md");
5033
- if (await pathExists(projectClaudeMd)) claudeMdPath = projectClaudeMd;
5925
+ const home = opts.home ?? homedir5();
5926
+ let inputsClaudeMdPath = opts.claudeMdPath;
5927
+ if (!inputsClaudeMdPath && opts.projectDir) {
5928
+ const own = join9(opts.projectDir, "CLAUDE.md");
5929
+ if (await pathExists2(own)) inputsClaudeMdPath = own;
5034
5930
  }
5035
- const { logs, claudeMd, claudeMdSource } = await loadAuditInputs({ path: opts.path, claudeMdPath });
5931
+ const { logs, claudeMd, claudeMdSource, projectDirs } = await loadAuditInputs({
5932
+ path: opts.path,
5933
+ claudeMdPath: inputsClaudeMdPath,
5934
+ home: opts.home
5935
+ });
5036
5936
  const report = analyzeUploads(logs);
5037
- const cmd = analyzeClaudeMd(claudeMd);
5038
- const { pillars } = scorePillars(report, cmd, {});
5039
- const configDir = join6(opts.home ?? homedir4(), ".costclaw");
5937
+ const cmd2 = analyzeClaudeMd(claudeMd);
5938
+ const { pillars } = scorePillars(report, cmd2, {});
5939
+ const configDir = join9(home, ".costclaw");
5040
5940
  const { plan } = await resolvePlan(configDir, opts.plan);
5041
- const { fixes } = synthesize(report, pillars, cmd, plan);
5042
- const project = await scanProject(projectDir);
5043
- const result = optimize({ report, scores: pillars, fixes, currentClaudeMd: claudeMd, project });
5044
- const recoverable = cacheMissExposureUsd(report);
5941
+ const { fixes } = synthesize(report, pillars, cmd2, plan);
5942
+ const auditRecoverable = cacheMissExposureUsd(report);
5045
5943
  const baselineSpend = report.summary.cost_usd;
5046
5944
  await saveCliConfig(configDir, {
5047
5945
  lastOptimize: {
5048
5946
  at: (/* @__PURE__ */ new Date()).toISOString(),
5049
5947
  totals: { ...report.summary.totals },
5050
5948
  cacheHitRate: report.summary.cacheHitRate,
5051
- headlineWasteShare: baselineSpend > 0 ? recoverable / baselineSpend : 0,
5949
+ headlineWasteShare: baselineSpend > 0 ? auditRecoverable / baselineSpend : 0,
5052
5950
  spendUsd: baselineSpend
5053
5951
  }
5054
5952
  });
5055
- const outDir = opts.out || join6(process.cwd(), "costclaw-out");
5056
- await mkdir3(outDir, { recursive: true });
5057
- const playbookPath = join6(outDir, PLAYBOOK_NAME2);
5058
- await writeFile3(playbookPath, result.playbook, "utf8");
5059
- const settingsPath = join6(outDir, SETTINGS_NAME2);
5060
- await writeFile3(settingsPath, result.settingsJson, "utf8");
5061
- const harnessPath = join6(outDir, HARNESS_NAME2);
5062
- await writeFile3(harnessPath, result.harnessPrompt, "utf8");
5063
- const wantDashboard = opts.dashboard !== false;
5064
- let dashboardPath = null;
5065
- if (wantDashboard) {
5066
- const spend = report.summary.cost_usd;
5067
- const html = renderOptimizeDashboard({
5068
- version: opts.version ?? "",
5069
- projectName: project.name ?? "your project",
5070
- stack: project.stack,
5071
- commandsCount: project.commands.length,
5072
- artifactsDir: outDir,
5073
- currentClaudeMd: claudeMd ?? null,
5074
- optimizedClaudeMd: result.optimizedClaudeMd,
5075
- claudeMdTokens: result.claudeMdTokens,
5076
- carriedTokens: result.carriedTokens,
5077
- sectionDispositions: result.sectionDispositions,
5078
- placeholdersRemaining: result.placeholdersRemaining,
5079
- fixes,
5080
- report,
5081
- headlineWasteShare: spend > 0 ? recoverable / spend : 0,
5082
- headlineWasteUsd: recoverable
5953
+ const single = opts.projectDir !== void 0;
5954
+ const manifestRoot = single ? defaultOptimizeRoot(home) : opts.out ?? defaultOptimizeRoot(home);
5955
+ const targets = [];
5956
+ let skippedMissing = 0;
5957
+ let overLimit = 0;
5958
+ const limit = opts.limit && opts.limit > 0 ? opts.limit : DEFAULT_LIMIT;
5959
+ if (opts.projectDir !== void 0) {
5960
+ targets.push({
5961
+ projectDir: opts.projectDir,
5962
+ artifactsDir: opts.out ?? join9(opts.projectDir, "costclaw-out")
5083
5963
  });
5084
- dashboardPath = join6(outDir, DASHBOARD_NAME);
5085
- await writeFile3(dashboardPath, html, "utf8");
5964
+ } else {
5965
+ const ranked = [...report.projects].sort((a, b) => b.cost_usd - a.cost_usd);
5966
+ const taken = /* @__PURE__ */ new Set();
5967
+ for (const p of ranked) {
5968
+ const dir = projectDirs.get(p.slug);
5969
+ if (!dir || !await pathExists2(dir)) {
5970
+ skippedMissing++;
5971
+ continue;
5972
+ }
5973
+ if (targets.length >= limit) {
5974
+ overLimit++;
5975
+ continue;
5976
+ }
5977
+ const name = artifactDirName(p.slug, dir, taken);
5978
+ taken.add(name);
5979
+ targets.push({ projectDir: dir, artifactsDir: join9(manifestRoot, name) });
5980
+ }
5086
5981
  }
5087
- const lines = [];
5088
- lines.push("CostClaw optimize");
5089
- lines.push("");
5090
- if (looksUnscanned(project)) {
5091
- lines.push(...unscannedWarning(projectDir));
5092
- lines.push("");
5982
+ const lines = ["CostClaw optimize", ""];
5983
+ if (!single) {
5984
+ lines.push(
5985
+ `Generated for ${targets.length} ${targets.length === 1 ? "project" : "projects"} from your audit, ranked by spend.`,
5986
+ "Nothing was written inside any project: that only happens on costclaw apply.",
5987
+ ""
5988
+ );
5989
+ } else {
5990
+ lines.push("Generated (nothing of yours was changed).", "");
5093
5991
  }
5094
- if (opts.write) {
5095
- const target = opts.write;
5096
- const backup = `${target}.bak`;
5097
- if (await pathExists(backup) && !opts.force) {
5098
- throw new Error(
5099
- `A backup already exists at ${backup}. Refusing to overwrite it. Pass --force to replace the existing backup.`
5100
- );
5992
+ const ctx = {
5993
+ report,
5994
+ pillars,
5995
+ fixes,
5996
+ plan,
5997
+ globalClaudeMd: opts.claudeMdPath ? void 0 : claudeMd,
5998
+ claudeMdOverride: opts.claudeMdPath ? claudeMd : void 0,
5999
+ claudeMdFallbackSource: claudeMdSource,
6000
+ version: opts.version ?? "",
6001
+ dashboard: opts.dashboard !== false,
6002
+ lines
6003
+ };
6004
+ const entries = [];
6005
+ for (const t of targets) {
6006
+ entries.push(await generateForProject(ctx, t.projectDir, t.artifactsDir));
6007
+ }
6008
+ const previous = await readManifest(manifestRoot);
6009
+ const merged = entries.map((e) => {
6010
+ const old = previous ? findEntry(previous, e.projectDir) : void 0;
6011
+ return old?.appliedAt ? { ...e, appliedAt: old.appliedAt } : e;
6012
+ });
6013
+ if (single && previous) {
6014
+ const sofar = { generatedAt: "", root: manifestRoot, projects: merged };
6015
+ for (const old of previous.projects) {
6016
+ if (!findEntry(sofar, old.projectDir)) merged.push(old);
5101
6017
  }
5102
- let original = "";
5103
- if (await pathExists(target)) {
5104
- original = await readFile5(target, "utf8");
6018
+ }
6019
+ const manifest = {
6020
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
6021
+ root: manifestRoot,
6022
+ projects: merged
6023
+ };
6024
+ await writeManifest(manifestRoot, manifest);
6025
+ let indexHtmlPath = null;
6026
+ if (!single && ctx.dashboard) {
6027
+ const rows = merged.map((e) => ({
6028
+ slug: e.slug,
6029
+ projectDir: e.projectDir,
6030
+ artifactsHref: `${e.dir}/${DASHBOARD_NAME2}`,
6031
+ spendUsd: e.spendUsd,
6032
+ recoverableUsd: e.recoverableUsd,
6033
+ tokens: e.tokens,
6034
+ ...e.appliedAt ? { appliedAt: e.appliedAt } : {},
6035
+ applyCommand: `costclaw apply ${e.projectDir}`
6036
+ }));
6037
+ const html = renderOptimizeIndex({
6038
+ version: ctx.version,
6039
+ generatedAt: manifest.generatedAt,
6040
+ root: manifestRoot,
6041
+ rows
6042
+ });
6043
+ indexHtmlPath = join9(manifestRoot, DASHBOARD_NAME2);
6044
+ await writeFile6(indexHtmlPath, html, "utf8");
6045
+ }
6046
+ if (!single) {
6047
+ lines.push(
6048
+ `${entries.length} ${entries.length === 1 ? "project" : "projects"} generated, ${skippedMissing} skipped (folder not found).`
6049
+ );
6050
+ if (overLimit > 0) {
6051
+ lines.push(`${overLimit} more were left out by the limit of ${limit}; pass --limit N to include more.`);
5105
6052
  }
5106
- await writeFile3(backup, original, "utf8");
5107
- await writeFile3(target, result.optimizedClaudeMd, "utf8");
5108
- lines.push(`Backed up the original to ${backup}`);
5109
- lines.push(`Wrote the optimized CLAUDE.md to ${target}`);
5110
- lines.push(`Wrote the playbook to ${playbookPath}`);
5111
- lines.push(`Wrote a suggested settings.json to ${settingsPath}`);
5112
- lines.push(`Wrote the Claude Code work order to ${harnessPath}`);
5113
- lines.push("");
5114
- lines.push("Diff (old vs new):");
5115
- lines.push(lineDiff(original, result.optimizedClaudeMd));
6053
+ }
6054
+ lines.push(
6055
+ `The ${SETTINGS_NAME2} in each artifacts folder is a conservative permission allowlist derived from what you already run.`,
6056
+ "Review it, then merge it with costclaw apply <project-dir> --apply-settings. It is never applied unless you ask."
6057
+ );
6058
+ const top = entries[0];
6059
+ if (top) {
5116
6060
  lines.push("");
5117
- if (result.placeholdersRemaining > 0) {
5118
- lines.push("Warning: this scaffold has placeholders to fill in. Search it for <!-- ... --> and replace each with your project's real details.");
5119
- }
5120
- lines.push("A suggested settings.json was written to the out dir for review; it is not applied in place.");
5121
- } else {
5122
- const optimizedPath = join6(outDir, OPTIMIZED_NAME2);
5123
- await writeFile3(optimizedPath, result.optimizedClaudeMd, "utf8");
5124
- lines.push("Dry run (no files of yours were changed).");
5125
- lines.push(`Wrote the optimized CLAUDE.md scaffold to ${optimizedPath}`);
5126
- lines.push(`Wrote the playbook to ${playbookPath}`);
5127
- lines.push(`Wrote a suggested settings.json to ${settingsPath}`);
5128
- lines.push(`Wrote the Claude Code work order to ${harnessPath}`);
6061
+ lines.push("To apply everything with AI judgment, hand the work order to your own Claude Code:");
6062
+ lines.push(` claude "Follow ${join9(top.artifactsDir, HARNESS_NAME2)}"`);
6063
+ lines.push(
6064
+ "It slims the CLAUDE.md, applies the permissions you approve, and fixes the audit's harness-level findings. costclaw itself never calls a model."
6065
+ );
6066
+ }
6067
+ lines.push("");
6068
+ lines.push(`Manifest: ${join9(manifestRoot, "index.json")}`);
6069
+ lines.push("Baseline recorded: your next audits will show cache-hit progress since this optimize.");
6070
+ lines.push("Nothing left your machine.");
6071
+ const openPath = indexHtmlPath ?? (ctx.dashboard && top ? join9(top.artifactsDir, DASHBOARD_NAME2) : null);
6072
+ if (openPath) {
5129
6073
  lines.push("");
5130
- lines.push(describeDetection(project));
5131
- if (claudeMdSource) lines.push(`Existing CLAUDE.md: ${claudeMdSource}`);
5132
- if (plan === "api") {
5133
- lines.push(`Recoverable spend (cache-miss exposure): ${usd6(recoverable)}`);
5134
- } else {
5135
- const spend = report.summary.cost_usd;
5136
- const share = spend > 0 ? recoverable / spend * 100 : 0;
6074
+ const canServe = opts.serve !== false && !process.env["VITEST"] && !process.env["CI"] && !process.env["COSTCLAW_NO_OPEN"] && manifest.projects.length > 0;
6075
+ if (!canServe) {
6076
+ lines.push(`Opening the summary dashboard: ${openPath}`);
5137
6077
  lines.push(
5138
- `Recoverable usage (cache-miss exposure): ${share.toFixed(1)}% of analyzed usage (${usd6(recoverable)} at API rates)`
6078
+ indexHtmlPath ? "It lists every project with its receipt and the apply line. Pass --no-dashboard to skip it." : "It browses all of this in one page, including a before and after of your CLAUDE.md. Pass --no-dashboard to skip it."
5139
6079
  );
6080
+ } else {
6081
+ lines.push(`Summary dashboard saved to: ${openPath}`);
5140
6082
  }
5141
- const { before, after } = result.claudeMdTokens;
5142
- if (before != null && before !== after) {
5143
- const pct2 = before > 0 ? (Math.abs(after - before) / before * 100).toFixed(1) : "0.0";
5144
- const dir = after > before ? "larger" : "smaller";
5145
- const g = (n) => String(Math.round(n)).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
6083
+ if (canServe) {
6084
+ const srv = await startApplyServer({
6085
+ root: manifestRoot,
6086
+ manifest,
6087
+ version: ctx.version,
6088
+ apply: async (entry, action) => {
6089
+ const outcome = await runApply({
6090
+ projectDir: entry.projectDir,
6091
+ mode: action === "remove" ? "remove" : "include",
6092
+ artifactsDir: entry.artifactsDir,
6093
+ applySettings: action === "settings"
6094
+ });
6095
+ return outcome.lines;
6096
+ },
6097
+ onManifestChange: (m) => writeManifest(manifestRoot, m)
6098
+ });
5146
6099
  lines.push(
5147
- `Your CLAUDE.md: an estimated ${g(before)} tokens to ${g(after)} (${pct2}% ${dir}), paid on every turn.`
6100
+ `Apply page: ${srv.url} (Apply/Remove buttons; press Ctrl+C or click Done when finished; closes after 30 idle minutes)`
5148
6101
  );
5149
- if (result.carriedTokens >= after / 2) {
5150
- lines.push(
5151
- `About ${g(result.carriedTokens)} of those tokens are your own prose, carried through as written.`,
5152
- "costclaw does not rewrite prose, so trimming it is judgment work: HARNESS-UPGRADE.md",
5153
- "ranks your heaviest sections and flags the dated lines to move into docs/."
5154
- );
5155
- }
5156
- }
5157
- lines.push("");
5158
- if (result.placeholdersRemaining > 0) {
5159
- const n = result.placeholdersRemaining;
5160
- lines.push(`The optimized CLAUDE.md has ${n} section${n === 1 ? "" : "s"} left as placeholders (no evidence to fill them).`);
5161
- lines.push("Search it for <!-- ... --> and replace each with your project's real details.");
6102
+ openInBrowser(srv.url);
5162
6103
  } else {
5163
- lines.push("Every section was filled from your project and your existing CLAUDE.md; nothing is left as a placeholder.");
5164
- lines.push("Review it (the notes below say what changed), then apply it.");
6104
+ openInBrowser(openPath);
5165
6105
  }
5166
- lines.push("To apply it in place (with a backup and a diff first), rerun with --write <your-CLAUDE.md>.");
5167
- 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.");
5168
- 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.");
5169
- lines.push("");
5170
- lines.push("To apply everything with AI judgment, hand the work order to your own Claude Code:");
5171
- lines.push(' claude "Follow costclaw-out/HARNESS-UPGRADE.md"');
5172
- lines.push("It merges the CLAUDE.md, applies the permissions you approve, and fixes the audit's harness-level findings. costclaw itself never calls a model.");
5173
- }
5174
- if (opts.applySettings) {
5175
- const target = opts.applySettingsPath || join6(projectDir, ".claude", "settings.json");
5176
- const applyLines = await applyDerivedSettings(target, result.settingsJson, opts.force ?? false);
5177
- lines.push("");
5178
- lines.push(...applyLines);
5179
- }
5180
- if (result.notes.length > 0) {
5181
- lines.push("");
5182
- lines.push("Notes:");
5183
- for (const note of result.notes) lines.push(` - ${note}`);
5184
6106
  }
5185
- lines.push("");
5186
- lines.push("Baseline recorded: your next audits will show cache-hit progress since this optimize.");
5187
- lines.push("Nothing left your machine.");
5188
- if (dashboardPath) {
5189
- lines.push("");
5190
- lines.push(`Opening the summary dashboard: ${dashboardPath}`);
5191
- lines.push("It browses all of this in one page, including a before and after of your CLAUDE.md. Pass --no-dashboard to skip it.");
5192
- openInBrowser(dashboardPath);
5193
- }
5194
- return { output: lines.join("\n") };
6107
+ return { output: lines.join("\n"), root: manifestRoot, manifest, indexHtmlPath };
5195
6108
  }
5196
6109
 
5197
6110
  // src/badge-command.ts
5198
- import { writeFile as writeFile4 } from "fs/promises";
5199
- import { resolve as resolve2 } from "path";
6111
+ import { writeFile as writeFile7 } from "fs/promises";
6112
+ import { resolve as resolve5 } from "path";
5200
6113
 
5201
6114
  // src/badge.ts
5202
6115
  var HEIGHT2 = 20;
@@ -5220,15 +6133,15 @@ var DEFAULT_BADGE_FILE = "costclaw-badge.svg";
5220
6133
  async function runBadge(opts) {
5221
6134
  const { record } = await runAudit({ path: opts.path, claudeMdPath: opts.claudeMdPath, home: opts.home });
5222
6135
  const svg = renderBadge(record);
5223
- const target = resolve2(opts.out || DEFAULT_BADGE_FILE);
5224
- await writeFile4(target, svg, "utf8");
6136
+ const target = resolve5(opts.out || DEFAULT_BADGE_FILE);
6137
+ await writeFile7(target, svg, "utf8");
5225
6138
  return { output: `Badge written to ${target}`, record, target };
5226
6139
  }
5227
6140
 
5228
6141
  // src/diff-command.ts
5229
- import { readdir as readdir4, readFile as readFile6 } from "fs/promises";
5230
- import { join as join7 } from "path";
5231
- import { homedir as homedir5 } from "os";
6142
+ import { readdir as readdir4, readFile as readFile10 } from "fs/promises";
6143
+ import { join as join10 } from "path";
6144
+ import { homedir as homedir6 } from "os";
5232
6145
 
5233
6146
  // src/format-diff.ts
5234
6147
  function usd7(n) {
@@ -5316,7 +6229,7 @@ function formatDiff(d) {
5316
6229
  async function readRecord(path) {
5317
6230
  let text2;
5318
6231
  try {
5319
- text2 = await readFile6(path, "utf8");
6232
+ text2 = await readFile10(path, "utf8");
5320
6233
  } catch {
5321
6234
  throw new Error(`Could not read ${path}.`);
5322
6235
  }
@@ -5332,7 +6245,7 @@ async function runDiff(opts) {
5332
6245
  let pathA = opts.fileA;
5333
6246
  let pathB = opts.fileB;
5334
6247
  if (!pathA || !pathB) {
5335
- const dir = join7(opts.home ?? homedir5(), ".costclaw", "history");
6248
+ const dir = join10(opts.home ?? homedir6(), ".costclaw", "history");
5336
6249
  let files = [];
5337
6250
  try {
5338
6251
  files = (await readdir4(dir)).filter((f) => f.endsWith(".json")).sort();
@@ -5343,133 +6256,14 @@ async function runDiff(opts) {
5343
6256
  "Need two audits to diff. Run costclaw audit now and again after you have made changes; each run saves a snapshot."
5344
6257
  );
5345
6258
  }
5346
- pathA = join7(dir, files[files.length - 2]);
5347
- pathB = join7(dir, files[files.length - 1]);
6259
+ pathA = join10(dir, files[files.length - 2]);
6260
+ pathB = join10(dir, files[files.length - 1]);
5348
6261
  }
5349
6262
  const diff = diffAudits(await readRecord(pathA), await readRecord(pathB));
5350
6263
  const output = opts.json ? JSON.stringify(diff, null, 2) : formatDiff(diff);
5351
6264
  return { output, diff };
5352
6265
  }
5353
6266
 
5354
- // src/license.ts
5355
- import { mkdir as mkdir4, readFile as readFile7, writeFile as writeFile5, rm as rm2 } from "fs/promises";
5356
- import { join as join8 } from "path";
5357
- import { homedir as homedir6, hostname } from "os";
5358
-
5359
- // ../../packages/license/src/keys.ts
5360
- var LICENSE_PRODUCT = "costclaw-optimize";
5361
- var KEY_PREFIX = "CC1";
5362
- var DEFAULT_PUBLIC_KEY_PEM = `-----BEGIN PUBLIC KEY-----
5363
- MCowBQYDK2VwAyEAXKdEIiMqeB4HIUb8si3LxRPBnrDpCIJrWvJWUCQLROg=
5364
- -----END PUBLIC KEY-----`;
5365
-
5366
- // ../../packages/license/src/verify.ts
5367
- import { createPublicKey, verify as cryptoVerify } from "crypto";
5368
- function base64UrlDecode(part) {
5369
- return Buffer.from(part.replace(/-/g, "+").replace(/_/g, "/"), "base64");
5370
- }
5371
- function verifyLicenseKey(licenseKey, publicKeyPem = DEFAULT_PUBLIC_KEY_PEM) {
5372
- const parts = licenseKey.trim().split(".");
5373
- if (parts.length !== 3 || parts[0] !== KEY_PREFIX) return null;
5374
- const [prefix, payloadPart, signaturePart] = parts;
5375
- if (prefix === void 0 || payloadPart === void 0 || signaturePart === void 0) return null;
5376
- try {
5377
- const publicKey = createPublicKey(publicKeyPem);
5378
- const signed = Buffer.from(`${prefix}.${payloadPart}`, "utf8");
5379
- const signature = base64UrlDecode(signaturePart);
5380
- if (!cryptoVerify(null, signed, publicKey, signature)) return null;
5381
- const payload = JSON.parse(base64UrlDecode(payloadPart).toString("utf8"));
5382
- if (payload.p !== LICENSE_PRODUCT) return null;
5383
- return payload;
5384
- } catch {
5385
- return null;
5386
- }
5387
- }
5388
-
5389
- // ../../packages/license/src/mint.ts
5390
- import { createPrivateKey, sign } from "crypto";
5391
-
5392
- // ../../packages/license/src/stripe.ts
5393
- import { createHmac, timingSafeEqual } from "crypto";
5394
-
5395
- // src/license.ts
5396
- var NOT_ACTIVATED_MESSAGE = [
5397
- "costclaw optimize needs a license.",
5398
- "",
5399
- "Buy a one-time license at https://costclaw.io, then run:",
5400
- " costclaw activate <your-license-key>",
5401
- "",
5402
- "costclaw audit is free and does not need a license."
5403
- ].join("\n");
5404
- var INVALID_MESSAGE = [
5405
- "The saved CostClaw license is not valid for this version.",
5406
- "",
5407
- "Re-activate with the key from your purchase email:",
5408
- " costclaw activate <your-license-key>",
5409
- "",
5410
- "Key missing or not working? Email wes@dashclaw.io with your order number.",
5411
- "costclaw audit stays free."
5412
- ].join("\n");
5413
- function defaultConfigDir() {
5414
- return join8(homedir6(), ".costclaw");
5415
- }
5416
- function licenseFile(dir) {
5417
- return join8(dir, "license.json");
5418
- }
5419
- async function readStoredLicense(dir) {
5420
- try {
5421
- const data = JSON.parse(await readFile7(licenseFile(dir), "utf8"));
5422
- if (!data || typeof data.licenseKey !== "string") return null;
5423
- return data;
5424
- } catch {
5425
- return null;
5426
- }
5427
- }
5428
- async function writeStoredLicense(dir, lic) {
5429
- await mkdir4(dir, { recursive: true });
5430
- await writeFile5(licenseFile(dir), JSON.stringify(lic, null, 2) + "\n", "utf8");
5431
- }
5432
- async function clearStoredLicense(dir) {
5433
- await rm2(licenseFile(dir), { force: true });
5434
- }
5435
- async function activateLicense(licenseKey, opts = {}) {
5436
- const key = licenseKey.trim();
5437
- if (!key) throw new Error("Provide your license key: costclaw activate <key>");
5438
- const configDir = opts.configDir ?? defaultConfigDir();
5439
- const payload = verifyLicenseKey(key, opts.publicKeyPem);
5440
- if (!payload) {
5441
- throw new Error(
5442
- "Could not activate this license key: it is not a valid CostClaw optimize license.\nCopy the whole key from your purchase email, or buy one at https://costclaw.io."
5443
- );
5444
- }
5445
- const stored = {
5446
- licenseKey: key,
5447
- instanceId: "local",
5448
- instanceName: opts.instanceName?.trim() || hostname(),
5449
- email: payload.e,
5450
- activatedAt: (/* @__PURE__ */ new Date()).toISOString()
5451
- };
5452
- await writeStoredLicense(configDir, stored);
5453
- return stored;
5454
- }
5455
- async function checkLicense(opts = {}) {
5456
- const configDir = opts.configDir ?? defaultConfigDir();
5457
- const stored = await readStoredLicense(configDir);
5458
- if (!stored) return { ok: false, message: NOT_ACTIVATED_MESSAGE };
5459
- const payload = verifyLicenseKey(stored.licenseKey, opts.publicKeyPem);
5460
- if (payload) {
5461
- return { ok: true, email: payload.e ?? stored.email };
5462
- }
5463
- await clearStoredLicense(configDir);
5464
- return { ok: false, message: INVALID_MESSAGE };
5465
- }
5466
- async function deactivateLicense(opts = {}) {
5467
- const configDir = opts.configDir ?? defaultConfigDir();
5468
- const stored = await readStoredLicense(configDir);
5469
- if (!stored) throw new Error("No license is active on this machine, so there is nothing to deactivate.");
5470
- await clearStoredLicense(configDir);
5471
- }
5472
-
5473
6267
  // src/index.ts
5474
6268
  process.on("unhandledRejection", (reason) => {
5475
6269
  console.error("Unhandled rejection:", reason);
@@ -5516,8 +6310,24 @@ function parseBadgeFlags(args) {
5516
6310
  out: getFlag(args, "--out")
5517
6311
  };
5518
6312
  }
6313
+ function parseApplyFlags(args) {
6314
+ const from = getFlag(args, "--from");
6315
+ const applySettings = args.includes("--apply-settings");
6316
+ const applySettingsPath = applySettings ? optionalPathAfter(args, "--apply-settings") : void 0;
6317
+ const consumed = new Set([from, applySettingsPath].filter((v) => v !== void 0));
6318
+ const positional = args.find((a) => !a.startsWith("-") && !consumed.has(a));
6319
+ const mode = args.includes("--remove") ? "remove" : args.includes("--replace") ? "replace" : "include";
6320
+ return {
6321
+ projectDir: positional ?? process.cwd(),
6322
+ mode,
6323
+ from,
6324
+ applySettings,
6325
+ applySettingsPath,
6326
+ force: args.includes("--force")
6327
+ };
6328
+ }
5519
6329
  function cliVersion() {
5520
- return true ? "0.9.0" : "0.0.0-dev";
6330
+ return true ? "0.10.0" : "0.0.0-dev";
5521
6331
  }
5522
6332
  function isHelpRequest(command, args) {
5523
6333
  if (command === void 0) return false;
@@ -5532,7 +6342,8 @@ function helpText() {
5532
6342
  " costclaw audit [--path <dir>] [--claude-md <file>] [--plan <plan>] [--json] [--html [file]] [--no-html] [--card [file]]",
5533
6343
  " costclaw diff [<baseline.json> <current.json>] [--json]",
5534
6344
  " costclaw badge [--path <dir>] [--claude-md <file>] [--out <file>]",
5535
- " costclaw optimize [--path <dir>] [--claude-md <file>] [--project <dir>] [--out <dir>] [--write <file>] [--apply-settings [file]] [--no-dashboard] [--force]",
6345
+ " costclaw optimize [--path <dir>] [--claude-md <file>] [--project <dir>] [--out <dir>] [--limit <n>] [--no-dashboard] [--no-serve] [--force]",
6346
+ " costclaw apply [<dir>] [--remove] [--replace] [--apply-settings [file]] [--from <dir>] [--force]",
5536
6347
  " costclaw activate <license-key> [--name <machine-name>]",
5537
6348
  " costclaw deactivate",
5538
6349
  " costclaw --version",
@@ -5562,20 +6373,37 @@ function helpText() {
5562
6373
  "costclaw-badge.svg) showing your overall score, colored by its band. Embed it",
5563
6374
  "in a README with an <img> tag; it is a static, self-contained file.",
5564
6375
  "",
5565
- "optimize turns that same audit into two artifacts: an optimized CLAUDE.md",
5566
- "scaffold and a prioritized fix playbook. It also scans --project <dir>",
5567
- "(default: the current directory) to auto-fill the scaffold's name, commands,",
5568
- "structure, and other facts from your real project files. By default it",
5569
- "dry-runs into ./costclaw-out (override with --out); --write <file> applies the",
5570
- "optimized CLAUDE.md in place after backing up the original and printing a diff.",
5571
- "--apply-settings [file] additively merges the derived permission allowlist into",
5572
- "the project's .claude/settings.json (or [file]); it only touches",
5573
- "permissions.allow and permissions.deny, backs up the original, and prints a diff.",
5574
- "It also writes DASHBOARD.html and opens it: one page that browses every artifact,",
5575
- "the ranked fixes, and a before and after of your CLAUDE.md. --no-dashboard skips it.",
5576
- "optimize needs a one-time license: buy at https://costclaw.io, then run",
5577
- "costclaw activate <key>. activate and deactivate move that license between",
5578
- "machines. audit never needs a license.",
6376
+ "optimize generates, for every project your audit saw, five artifacts: an",
6377
+ "optimized CLAUDE.md scaffold, a prioritized fix playbook, a conservative,",
6378
+ "project-derived settings.suggested.json permission allowlist, a",
6379
+ "HARNESS-UPGRADE.md work order for your own Claude Code, and costclaw.md (the",
6380
+ "generated sections as a standalone include). It never writes inside a",
6381
+ "project; only costclaw apply does that, on an explicit command.",
6382
+ "By default it runs globally: it ranks your audited projects by spend,",
6383
+ "generates for the top ones (cap 10, override with --limit N) into",
6384
+ "~/.costclaw/optimize/<project>/, and writes one DASHBOARD.html index plus a",
6385
+ "local apply page you can click through instead of the command line",
6386
+ "(Ctrl+C, its Done button, or --no-serve to skip it). --project <dir> keeps",
6387
+ "the single-project run, writing into ./costclaw-out (or --out <dir>)",
6388
+ "instead. --no-dashboard skips the HTML.",
6389
+ "",
6390
+ "apply [<dir>] (default: the current directory) is the only command that",
6391
+ "writes inside a project, and only additively: it writes the generated",
6392
+ "sections to .claude/costclaw.md and adds one @.claude/costclaw.md import",
6393
+ "line to your CLAUDE.md, leaving every line you wrote untouched. --remove",
6394
+ "undoes that. --replace is the old wholesale rewrite, now gated behind a git",
6395
+ "repository so the undo is `git checkout -- CLAUDE.md` (it still keeps a",
6396
+ ".bak too). --apply-settings [file] additively merges the derived permission",
6397
+ "allowlist into .claude/settings.json (or [file]); it only touches",
6398
+ "permissions.allow and permissions.deny, backs up the original, and prints a",
6399
+ "diff. --from <dir> points apply at a specific artifacts folder instead of",
6400
+ "looking one up by project; without it, apply finds artifacts from the last",
6401
+ "optimize run, or generates them cold if none exist yet. --force allows",
6402
+ "overwriting an existing .bak backup for --replace and --apply-settings.",
6403
+ "",
6404
+ "optimize and apply need a one-time license: buy at https://costclaw.io, then",
6405
+ "run costclaw activate <key>. activate and deactivate move that license",
6406
+ "between machines. audit never needs a license.",
5579
6407
  "",
5580
6408
  "Everything runs locally. Nothing is uploaded. Activation is a signed license",
5581
6409
  "key verified on this machine: there is no license server and no network call.",
@@ -5633,6 +6461,14 @@ Run: costclaw optimize
5633
6461
  return;
5634
6462
  }
5635
6463
  if (command === "optimize") {
6464
+ if (args.includes("--write")) {
6465
+ process.stderr.write("--write moved: run costclaw apply <dir> --replace\n");
6466
+ process.exit(1);
6467
+ }
6468
+ if (args.includes("--apply-settings")) {
6469
+ process.stderr.write("--apply-settings moved: run costclaw apply <dir> --apply-settings\n");
6470
+ process.exit(1);
6471
+ }
5636
6472
  const gate = await checkLicense();
5637
6473
  if (!gate.ok) {
5638
6474
  process.stderr.write(gate.message + "\n");
@@ -5642,18 +6478,61 @@ Run: costclaw optimize
5642
6478
  path: getFlag(args, "--path"),
5643
6479
  claudeMdPath: getFlag(args, "--claude-md"),
5644
6480
  plan: planFlag(args),
5645
- projectDir: getFlag(args, "--project") || process.cwd(),
6481
+ projectDir: getFlag(args, "--project"),
5646
6482
  out: getFlag(args, "--out"),
5647
- write: getFlag(args, "--write"),
6483
+ limit: Number(getFlag(args, "--limit")) || void 0,
5648
6484
  force: args.includes("--force"),
5649
6485
  dashboard: !args.includes("--no-dashboard"),
5650
- version: cliVersion(),
5651
- applySettings: args.includes("--apply-settings"),
5652
- applySettingsPath: args.includes("--apply-settings") ? optionalPathAfter(args, "--apply-settings") : void 0
6486
+ serve: !args.includes("--no-serve"),
6487
+ version: cliVersion()
5653
6488
  });
5654
6489
  process.stdout.write(output + "\n");
5655
6490
  return;
5656
6491
  }
6492
+ if (command === "apply") {
6493
+ const gate = await checkLicense();
6494
+ if (!gate.ok) {
6495
+ process.stderr.write(gate.message + "\n");
6496
+ process.exit(1);
6497
+ }
6498
+ const flags = parseApplyFlags(args);
6499
+ const root = defaultOptimizeRoot(homedir7());
6500
+ let artifactsDir = flags.from;
6501
+ if (!artifactsDir) {
6502
+ const manifest = await readManifest(root);
6503
+ artifactsDir = manifest ? findEntry(manifest, flags.projectDir)?.artifactsDir : void 0;
6504
+ }
6505
+ if (!artifactsDir) {
6506
+ const run = await runOptimize({
6507
+ projectDir: flags.projectDir,
6508
+ serve: false,
6509
+ dashboard: false,
6510
+ version: cliVersion()
6511
+ });
6512
+ artifactsDir = findEntry(run.manifest, flags.projectDir)?.artifactsDir;
6513
+ }
6514
+ if (!artifactsDir) {
6515
+ throw new Error(`Could not find or generate artifacts for ${flags.projectDir}`);
6516
+ }
6517
+ const outcome = await runApply({
6518
+ projectDir: flags.projectDir,
6519
+ mode: flags.mode,
6520
+ artifactsDir,
6521
+ applySettings: flags.applySettings,
6522
+ applySettingsPath: flags.applySettingsPath,
6523
+ force: flags.force
6524
+ });
6525
+ process.stdout.write(outcome.lines.join("\n") + "\n");
6526
+ if (flags.mode === "include") {
6527
+ const manifest = await readManifest(root);
6528
+ const entry = manifest ? findEntry(manifest, flags.projectDir) : void 0;
6529
+ if (manifest && entry) {
6530
+ entry.appliedAt = (/* @__PURE__ */ new Date()).toISOString();
6531
+ await writeManifest(root, manifest);
6532
+ }
6533
+ }
6534
+ return;
6535
+ }
5657
6536
  process.stderr.write(helpText() + "\n");
5658
6537
  process.exit(command ? 1 : 0);
5659
6538
  }
@@ -5668,6 +6547,7 @@ export {
5668
6547
  cliVersion,
5669
6548
  helpText,
5670
6549
  isHelpRequest,
6550
+ parseApplyFlags,
5671
6551
  parseAuditFlags,
5672
6552
  parseBadgeFlags,
5673
6553
  planFlag