costclaw 0.9.1 → 0.12.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 +326 -274
  2. package/dist/index.js +1895 -387
  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() {
@@ -832,7 +833,7 @@ function analyzeClaudeMd(text2) {
832
833
  };
833
834
  }
834
835
  const chars = raw.length;
835
- const estTokens = Math.round(chars / 4);
836
+ const estTokens2 = Math.round(chars / 4);
836
837
  const headings = (raw.match(/^#{1,6}\s/gm) || []).length;
837
838
  const bullets = (raw.match(/^\s*[-*]\s/gm) || []).length;
838
839
  const dateMarkers = (raw.match(/\b\d{4}-\d{2}-\d{2}\b/g) || []).length;
@@ -841,7 +842,7 @@ function analyzeClaudeMd(text2) {
841
842
  return {
842
843
  present: true,
843
844
  chars,
844
- estTokens,
845
+ estTokens: estTokens2,
845
846
  headings,
846
847
  bullets,
847
848
  volatileMarkers,
@@ -1887,6 +1888,7 @@ function carriedIntro(currentClaudeMd) {
1887
1888
  }
1888
1889
  return { title, intro, introDropped };
1889
1890
  }
1891
+ var SECTION_HEADING_RE = /^##\s+(.+?)\s*$/;
1890
1892
  function parseSections(md) {
1891
1893
  const lines = md.split(/\r?\n/);
1892
1894
  const sections = [];
@@ -1901,7 +1903,7 @@ function parseSections(md) {
1901
1903
  };
1902
1904
  };
1903
1905
  for (const line of lines) {
1904
- const m = line.match(/^##\s+(.+?)\s*$/);
1906
+ const m = line.match(SECTION_HEADING_RE);
1905
1907
  if (m) {
1906
1908
  if (current) sections.push(finish(current));
1907
1909
  current = { heading: m[1], body: [] };
@@ -2363,6 +2365,27 @@ function buildClaudeMd(input, recoverable, notes, stats, carried, dispositions)
2363
2365
  }
2364
2366
  return clean(parts.join("\n\n").trimEnd() + "\n");
2365
2367
  }
2368
+ var INCLUDE_HEADING = [...REGENERATED_HEADING, /^token discipline\b/i];
2369
+ function isPlaceholderOnly(body) {
2370
+ return /^<!--[^]*?-->$/.test(body.trim());
2371
+ }
2372
+ function buildIncludeMd(optimizedClaudeMd) {
2373
+ const sections = parseSections(optimizedClaudeMd).filter(
2374
+ (s) => INCLUDE_HEADING.some((re) => re.test(s.heading)) && !isPlaceholderOnly(s.body)
2375
+ );
2376
+ const header = [
2377
+ "<!--",
2378
+ " Generated by CostClaw (https://costclaw.io). Regenerated on every",
2379
+ " `costclaw apply`; edit your CLAUDE.md, not this file.",
2380
+ " Imported from CLAUDE.md by the line: @.claude/costclaw.md",
2381
+ " Undo: costclaw apply . --remove",
2382
+ "-->"
2383
+ ].join("\n");
2384
+ const parts = [header, ...sections.map((s) => `## ${s.heading}
2385
+
2386
+ ${s.body}`)];
2387
+ return { includeMd: clean(parts.join("\n\n").trimEnd() + "\n"), includeSections: sections.map((s) => s.heading) };
2388
+ }
2366
2389
  function joinAnd(items) {
2367
2390
  if (items.length === 0) return "";
2368
2391
  if (items.length === 1) return items[0];
@@ -2577,8 +2600,9 @@ function buildHarnessPrompt(input, carried, claudeMdTokens) {
2577
2600
  [
2578
2601
  "You are Claude Code, working in this repository. costclaw generated this",
2579
2602
  "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."
2603
+ "project; every task is grounded in that evidence. The files named below",
2604
+ "sit in the same folder as this work order. Execute the tasks in order",
2605
+ "and report what changed at the end."
2582
2606
  ].join("\n")
2583
2607
  );
2584
2608
  parts.push(
@@ -2596,30 +2620,34 @@ function buildHarnessPrompt(input, carried, claudeMdTokens) {
2596
2620
  );
2597
2621
  parts.push(
2598
2622
  [
2599
- "## Task 1: Merge the optimized CLAUDE.md",
2623
+ "## Task 1: Slim your CLAUDE.md",
2624
+ "",
2625
+ "If `.claude/costclaw.md` does not exist yet, run `npx costclaw apply .`",
2626
+ "first. It writes the generated sections (see `costclaw.md` here) to",
2627
+ "`.claude/costclaw.md` and adds `@.claude/costclaw.md` to CLAUDE.md.",
2600
2628
  "",
2601
- "Merge `costclaw-out/CLAUDE.optimized.md` into `./CLAUDE.md`:",
2629
+ "Then, in `./CLAUDE.md`:",
2630
+ "- For each section the include now covers (Commands, Project structure,",
2631
+ " Code style, Testing, Environment): compare yours with the include. If a",
2632
+ " fact of yours is missing from the include, keep that line in CLAUDE.md",
2633
+ " under its heading (the include is regenerated, never edit it). Otherwise",
2634
+ " delete your copy so each section appears once.",
2635
+ "- Move the volatile sections listed below into docs/ and link them.",
2636
+ "- Strip any generator HTML comment blocks.",
2637
+ "- Show the diff before writing.",
2602
2638
  "",
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."
2639
+ "Only `apply --replace` swaps the whole file; do not do that here."
2611
2640
  ].join("\n")
2612
2641
  );
2613
2642
  parts.push(
2614
2643
  [
2615
2644
  "## Task 2: Permission allowlist",
2616
2645
  "",
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."
2646
+ "Review `settings.suggested.json` (read-only tools plus this project's",
2647
+ "safe commands; denies secret reads and destructive ops). Merge the",
2648
+ "rules you agree with additively into `.claude/settings.json`, keeping",
2649
+ "every existing entry. `npx costclaw apply . --apply-settings`",
2650
+ "performs the mechanical merge with a backup and a diff if you prefer."
2623
2651
  ].join("\n")
2624
2652
  );
2625
2653
  let n = 3;
@@ -2729,7 +2757,12 @@ function buildHarnessPrompt(input, carried, claudeMdTokens) {
2729
2757
  const lintCmd = project?.commands.find((c) => c.label === "lint")?.command;
2730
2758
  if (testCmd) verify.push(`- Run \`${testCmd}\` and read the output.`);
2731
2759
  if (lintCmd) verify.push(`- Run \`${lintCmd}\` and read the output.`);
2732
- verify.push("- Confirm no generator comment blocks are left in CLAUDE.md.");
2760
+ verify.push(
2761
+ "- Confirm CLAUDE.md contains the line `@.claude/costclaw.md` and that the",
2762
+ " regenerated sections (Commands, Project structure, Code style, Testing,",
2763
+ " Environment) appear once across CLAUDE.md and the include.",
2764
+ "- Confirm no generator comment blocks are left in CLAUDE.md."
2765
+ );
2733
2766
  if (carried.carriedTokens >= CARRY_HEAVY_TOKENS) {
2734
2767
  verify.push(
2735
2768
  "- Confirm every line moved out of CLAUDE.md landed in a file under",
@@ -2760,14 +2793,17 @@ function optimize(input) {
2760
2793
  const playbook = buildPlaybook(input.report, input.fixes, input.scores, recoverable, claudeMdTokens, input.project);
2761
2794
  const settingsJson = buildSettings(input.project);
2762
2795
  const harnessPrompt = buildHarnessPrompt(input, carried, claudeMdTokens);
2796
+ const { includeMd, includeSections } = buildIncludeMd(optimizedClaudeMd);
2763
2797
  const cleanNotes = notes.map((n) => clean(n));
2764
2798
  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))) {
2799
+ if (hasEmDash(optimizedClaudeMd) || hasEmDash(playbook) || hasEmDash(settingsJson) || hasEmDash(harnessPrompt) || hasEmDash(includeMd) || cleanNotes.some(hasEmDash) || cleanDispositions.some((d) => hasEmDash(d.name) || hasEmDash(d.why))) {
2766
2800
  return {
2767
2801
  optimizedClaudeMd: sanitizeText(optimizedClaudeMd),
2768
2802
  playbook: sanitizeText(playbook),
2769
2803
  settingsJson: sanitizeText(settingsJson),
2770
2804
  harnessPrompt: sanitizeText(harnessPrompt),
2805
+ includeMd: sanitizeText(includeMd),
2806
+ includeSections,
2771
2807
  notes: cleanNotes.map(sanitizeText),
2772
2808
  placeholdersRemaining: stats.placeholders,
2773
2809
  claudeMdTokens,
@@ -2780,6 +2816,8 @@ function optimize(input) {
2780
2816
  playbook,
2781
2817
  settingsJson,
2782
2818
  harnessPrompt,
2819
+ includeMd,
2820
+ includeSections,
2783
2821
  notes: cleanNotes,
2784
2822
  placeholdersRemaining: stats.placeholders,
2785
2823
  claudeMdTokens,
@@ -3020,6 +3058,463 @@ var MAX_FILE_BYTES = 25 * 1024 * 1024;
3020
3058
  var MAX_TOTAL_BYTES = 60 * 1024 * 1024;
3021
3059
  var MAX_CLAUDEMD_BYTES = 1 * 1024 * 1024;
3022
3060
 
3061
+ // ../../packages/engine/src/review.ts
3062
+ var IMPORT_LINE = "@.claude/costclaw.md";
3063
+ function estTokens(text2) {
3064
+ return Math.round(text2.length / 4);
3065
+ }
3066
+ function num4(n) {
3067
+ return String(Math.round(n)).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
3068
+ }
3069
+ function normalize(line) {
3070
+ return line.trim().replace(/\s+/g, " ").toLowerCase();
3071
+ }
3072
+ function slugifyHeading(heading) {
3073
+ const slug = heading.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
3074
+ return slug.length > 0 ? slug : "notes";
3075
+ }
3076
+ function indexSections(lines) {
3077
+ const top = [];
3078
+ const sections = [];
3079
+ let current = null;
3080
+ for (let i = 0; i < lines.length; i++) {
3081
+ const line = lines[i] ?? "";
3082
+ const m = line.match(SECTION_HEADING_RE);
3083
+ if (m) {
3084
+ current = { heading: (m[1] ?? "").trim(), headingLine: i, bodyLines: [] };
3085
+ sections.push(current);
3086
+ } else if (current) {
3087
+ current.bodyLines.push(i);
3088
+ } else {
3089
+ top.push(i);
3090
+ }
3091
+ }
3092
+ return { top, sections };
3093
+ }
3094
+ function bodyText(lines, idx) {
3095
+ return idx.map((i) => lines[i] ?? "").join("\n").trim();
3096
+ }
3097
+ var ReviewBuilder = class {
3098
+ marks = /* @__PURE__ */ new Map();
3099
+ changes = [];
3100
+ adds = [];
3101
+ seq = 0;
3102
+ nextId(prefix) {
3103
+ this.seq += 1;
3104
+ return `${prefix}-${this.seq}`;
3105
+ }
3106
+ /** First mark on a line wins, so two rules never claim the same line. */
3107
+ mark(indexes, mark, reason, changeId) {
3108
+ for (const i of indexes) if (!this.marks.has(i)) this.marks.set(i, { mark, reason, changeId });
3109
+ }
3110
+ change(c) {
3111
+ this.changes.push({ ...c, instruction: sanitizeText(c.instruction), reason: sanitizeText(c.reason) });
3112
+ }
3113
+ /** An add carries its own lines: there is no existing line to mark. */
3114
+ add(change) {
3115
+ this.change(change);
3116
+ for (const line of (change.text ?? "").replace(/\s+$/, "").split("\n")) {
3117
+ this.adds.push({ text: line, mark: "add", reason: change.reason, changeId: change.id });
3118
+ }
3119
+ }
3120
+ };
3121
+ function markGeneratorComments(lines, b) {
3122
+ for (let i = 0; i < lines.length; i++) {
3123
+ if (!/<!--\s*costclaw/i.test(lines[i] ?? "")) continue;
3124
+ const block = [];
3125
+ let j = i;
3126
+ for (; j < lines.length; j++) {
3127
+ block.push(j);
3128
+ if ((lines[j] ?? "").includes("-->")) break;
3129
+ }
3130
+ const id = b.nextId("gen");
3131
+ b.mark(block, "remove", "generator comment", id);
3132
+ b.change({
3133
+ id,
3134
+ kind: "remove",
3135
+ heading: "(top)",
3136
+ instruction: "Delete this generator comment block: costclaw rewrites it on every run, so it steers nothing.",
3137
+ reason: "a generated marker block, not a rule",
3138
+ tokens: estTokens(block.map((k) => lines[k] ?? "").join("\n"))
3139
+ });
3140
+ i = j;
3141
+ }
3142
+ }
3143
+ var VOLATILE_WHY = "dated or status text busts the prompt cache on every edit";
3144
+ function markVolatile(lines, sections, b, destDir) {
3145
+ for (const s of sections) {
3146
+ const dest = `${destDir}${slugifyHeading(s.heading)}.md`;
3147
+ if (VOLATILE_HEADING.test(s.heading)) {
3148
+ const id2 = b.nextId("vol");
3149
+ b.mark([s.headingLine, ...s.bodyLines], "move", "status section", id2);
3150
+ b.change({
3151
+ id: id2,
3152
+ kind: "move",
3153
+ heading: s.heading,
3154
+ instruction: `Move the whole "${s.heading}" section to ${dest} and link it from the file it left.`,
3155
+ reason: VOLATILE_WHY,
3156
+ tokens: estTokens(bodyText(lines, s.bodyLines)),
3157
+ destination: dest
3158
+ });
3159
+ continue;
3160
+ }
3161
+ const dated = s.bodyLines.filter((i) => VOLATILE_MARKER.test(lines[i] ?? ""));
3162
+ if (dated.length === 0) continue;
3163
+ const id = b.nextId("dated");
3164
+ b.mark(dated, "move", "dated line", id);
3165
+ b.change({
3166
+ id,
3167
+ kind: "move",
3168
+ heading: s.heading,
3169
+ instruction: `Move the ${num4(dated.length)} dated ${dated.length === 1 ? "line" : "lines"} under "${s.heading}" to ${dest}, then link that file.`,
3170
+ reason: VOLATILE_WHY,
3171
+ tokens: estTokens(dated.map((i) => lines[i] ?? "").join("\n")),
3172
+ destination: dest
3173
+ });
3174
+ }
3175
+ }
3176
+ function importAdd() {
3177
+ return {
3178
+ heading: "(top)",
3179
+ text: `${IMPORT_LINE}
3180
+ `,
3181
+ reason: "the generated sections live in their own file, imported once"
3182
+ };
3183
+ }
3184
+ function tokenDisciplineAdd() {
3185
+ return {
3186
+ heading: "Token discipline",
3187
+ text: [
3188
+ "## Token discipline",
3189
+ "",
3190
+ "- State a stop condition before any search or edit loop, then stop at it.",
3191
+ "- Read the narrowest thing that answers the question: a range, not a file;",
3192
+ " one file, not a tree.",
3193
+ "- Do not re-read a file you just wrote.",
3194
+ ""
3195
+ ].join("\n"),
3196
+ reason: "the audit found tool loops running far past a sane bound"
3197
+ };
3198
+ }
3199
+ function modelRoutingAdd() {
3200
+ return {
3201
+ heading: "Model routing",
3202
+ text: [
3203
+ "## Model routing",
3204
+ "",
3205
+ "- Short, mechanical tasks (a lookup, a rename, a formatting pass) run on the",
3206
+ " cheap model. Premium models are for hard reasoning and final review.",
3207
+ "- Say which model a task needs when it is not obvious.",
3208
+ ""
3209
+ ].join("\n"),
3210
+ reason: "the audit found short, trivial sessions running on a premium model"
3211
+ };
3212
+ }
3213
+ function sessionHygieneAdd() {
3214
+ return {
3215
+ heading: "Session hygiene",
3216
+ text: [
3217
+ "## Session hygiene",
3218
+ "",
3219
+ "- Run /compact before the context outgrows the cache, not after.",
3220
+ "- Run /clear between unrelated tasks: a fresh session is cheaper than a",
3221
+ " long one carrying a dead context.",
3222
+ ""
3223
+ ].join("\n"),
3224
+ reason: "the audit found long sessions whose per-turn cache decayed"
3225
+ };
3226
+ }
3227
+ function stopConditionsAdd(tools) {
3228
+ return {
3229
+ heading: "Stop conditions",
3230
+ text: [
3231
+ "## Stop conditions",
3232
+ "",
3233
+ `- Before a loop with ${tools.join(", ")}, state the bound out loud (how many`,
3234
+ " calls, or what result ends it), then honor it.",
3235
+ "- If the bound is hit without an answer, stop and report what is missing",
3236
+ " instead of widening the search.",
3237
+ ""
3238
+ ].join("\n"),
3239
+ reason: `the audit found ${tools.join(", ")} firing far past a sane loop bound`
3240
+ };
3241
+ }
3242
+ function hasHeading(sections, heading) {
3243
+ return sections.some((s) => normalize(s.heading) === normalize(heading));
3244
+ }
3245
+ function applyAdds(blocks, sections, lines, b) {
3246
+ for (const block of blocks) {
3247
+ if (block.heading === "(top)") {
3248
+ if (lines.some((l) => l.trim() === block.text.trim())) continue;
3249
+ } else if (hasHeading(sections, block.heading)) continue;
3250
+ const id = b.nextId("add");
3251
+ b.add({
3252
+ id,
3253
+ kind: "add",
3254
+ heading: block.heading,
3255
+ instruction: block.heading === "(top)" ? `Add the line \`${IMPORT_LINE}\` to CLAUDE.md (\`npx costclaw apply <dir>\` does it for you).` : `Add this "${block.heading}" section at the end of the file, exactly as written.`,
3256
+ reason: block.reason,
3257
+ tokens: estTokens(block.text),
3258
+ text: block.text
3259
+ });
3260
+ }
3261
+ }
3262
+ function assemble(scope, label, lines, b, tokens, importCount = 0) {
3263
+ const reviewed = lines.map((text2, i) => {
3264
+ const m = b.marks.get(i);
3265
+ return m ? { text: text2, mark: m.mark, reason: m.reason, changeId: m.changeId } : { text: text2, mark: "keep" };
3266
+ });
3267
+ const sum = (kind) => b.changes.filter((c) => c.kind === kind).reduce((s, c) => s + c.tokens, 0);
3268
+ const total = tokens.file + tokens.imports;
3269
+ return {
3270
+ scope,
3271
+ label,
3272
+ missing: false,
3273
+ lines: [...reviewed, ...b.adds],
3274
+ changes: b.changes,
3275
+ tokens: { ...tokens, total, afterChanges: Math.max(0, total - sum("remove") - sum("move") + sum("add")) },
3276
+ importCount
3277
+ };
3278
+ }
3279
+ function reviewProjectClaudeMd(input) {
3280
+ const has = (id) => input.report.findings.some((f) => f.ruleId === id);
3281
+ const blocks = [importAdd()];
3282
+ if (has("HEAVY_TOOL_LOOPS") || has("REDUNDANT_TARGET_THRASH")) blocks.push(tokenDisciplineAdd());
3283
+ if (input.text === null || input.text.trim() === "") {
3284
+ const b2 = new ReviewBuilder();
3285
+ applyAdds(blocks, [], [], b2);
3286
+ return { ...assemble("project", input.label, [], b2, { file: 0, imports: 0 }), missing: true };
3287
+ }
3288
+ const lines = input.text.split(/\r?\n/);
3289
+ const { sections } = indexSections(lines);
3290
+ const b = new ReviewBuilder();
3291
+ const includeLines = new Set(input.includeMd.split(/\r?\n/).map(normalize).filter((l) => l.length > 0));
3292
+ for (const s of sections) {
3293
+ if (!INCLUDE_HEADING.some((re) => re.test(s.heading))) continue;
3294
+ const content = s.bodyLines.filter((i) => (lines[i] ?? "").trim().length > 0);
3295
+ if (content.length === 0) continue;
3296
+ const covered = content.filter((i) => includeLines.has(normalize(lines[i] ?? "")));
3297
+ if (covered.length === 0) continue;
3298
+ const id = b.nextId("inc");
3299
+ const all = covered.length === content.length;
3300
+ const kept = content.length - covered.length;
3301
+ b.mark(all ? [s.headingLine, ...s.bodyLines] : covered, "remove", "covered by the include", id);
3302
+ b.change({
3303
+ id,
3304
+ kind: "remove",
3305
+ heading: s.heading,
3306
+ instruction: all ? `Delete the whole "${s.heading}" section: the include ${IMPORT_LINE} now carries it.` : `Delete the ${num4(covered.length)} covered ${covered.length === 1 ? "line" : "lines"} under "${s.heading}" and keep these ${num4(kept)} lines under the heading: the include ${IMPORT_LINE} does not have them.`,
3307
+ reason: `${num4(covered.length)} of ${num4(content.length)} lines appear verbatim in the generated include`,
3308
+ tokens: estTokens(covered.map((i) => lines[i] ?? "").join("\n"))
3309
+ });
3310
+ }
3311
+ const globals = new Map(input.globalSections.map((s) => [normalize(s.heading), normalize(s.body)]));
3312
+ for (const s of sections) {
3313
+ if (b.marks.has(s.headingLine)) continue;
3314
+ const g = globals.get(normalize(s.heading));
3315
+ if (g === void 0 || g !== normalize(bodyText(lines, s.bodyLines))) continue;
3316
+ const id = b.nextId("dup");
3317
+ b.mark([s.headingLine, ...s.bodyLines], "remove", "duplicates the global file", id);
3318
+ b.change({
3319
+ id,
3320
+ kind: "remove",
3321
+ heading: s.heading,
3322
+ instruction: `Delete the "${s.heading}" section from this file: it is identical to the one in the global CLAUDE.md.`,
3323
+ reason: "the global CLAUDE.md is loaded in this project too, so this copy is paid twice",
3324
+ tokens: estTokens(bodyText(lines, s.bodyLines))
3325
+ });
3326
+ }
3327
+ markGeneratorComments(lines, b);
3328
+ markVolatile(lines, sections, b, "docs/");
3329
+ applyAdds(blocks, sections, lines, b);
3330
+ return assemble("project", input.label, lines, b, { file: estTokens(input.text.trim()), imports: 0 });
3331
+ }
3332
+ var IMPORT_WEIGHT_LIMIT = 6e3;
3333
+ var SLUG_MIN = 4;
3334
+ function paragraphs(lines, idx) {
3335
+ const out = [];
3336
+ let cur = [];
3337
+ for (const i of idx) {
3338
+ if ((lines[i] ?? "").trim() === "") {
3339
+ if (cur.length > 0) out.push(cur);
3340
+ cur = [];
3341
+ } else cur.push(i);
3342
+ }
3343
+ if (cur.length > 0) out.push(cur);
3344
+ return out;
3345
+ }
3346
+ function escapeRe(text2) {
3347
+ return text2.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
3348
+ }
3349
+ function namedSlugs(text2, slugs) {
3350
+ const found = [];
3351
+ for (const slug of slugs) {
3352
+ if (slug.length < SLUG_MIN || found.includes(slug)) continue;
3353
+ const re = new RegExp(`(^|[^a-z0-9])${escapeRe(slug)}([^a-z0-9]|$)`, "i");
3354
+ if (re.test(text2)) found.push(slug);
3355
+ }
3356
+ return found;
3357
+ }
3358
+ function reviewGlobalClaudeMd(input) {
3359
+ const has = (id) => input.report.findings.some((f) => f.ruleId === id);
3360
+ const heavyTools = [...new Set(input.report.findings.filter((f) => f.ruleId === "HEAVY_TOOL_LOOPS").map((f) => String(f.evidence?.["tool"] ?? "")).filter((t) => t.length > 0))].sort();
3361
+ const blocks = [];
3362
+ if (has("HEAVY_TOOL_LOOPS") || has("REDUNDANT_TARGET_THRASH")) blocks.push(tokenDisciplineAdd());
3363
+ if (has("MODEL_MISROUTE")) blocks.push(modelRoutingAdd());
3364
+ if (has("MARATHON_SESSION")) blocks.push(sessionHygieneAdd());
3365
+ if (heavyTools.length > 0) blocks.push(stopConditionsAdd(heavyTools));
3366
+ const importTokens = input.imports.reduce((s, i) => s + estTokens(i.text), 0);
3367
+ if (input.text === null || input.text.trim() === "") {
3368
+ const b2 = new ReviewBuilder();
3369
+ applyAdds(blocks, [], [], b2);
3370
+ return {
3371
+ ...assemble("global", input.label, [], b2, { file: 0, imports: importTokens }, input.imports.length),
3372
+ missing: true
3373
+ };
3374
+ }
3375
+ const lines = input.text.split(/\r?\n/);
3376
+ const { top, sections } = indexSections(lines);
3377
+ const b = new ReviewBuilder();
3378
+ markGeneratorComments(lines, b);
3379
+ markVolatile(lines, sections, b, "~/.claude/notes/");
3380
+ const blocksToScan = [
3381
+ { heading: "(top)", idx: top },
3382
+ ...sections.map((s) => ({ heading: s.heading, idx: s.bodyLines }))
3383
+ ];
3384
+ for (const block of blocksToScan) {
3385
+ for (const para of paragraphs(lines, block.idx)) {
3386
+ if (para.some((i) => b.marks.has(i))) continue;
3387
+ const text2 = para.map((i) => lines[i] ?? "").join("\n");
3388
+ const named = namedSlugs(text2, input.projectSlugs);
3389
+ if (named.length !== 1) continue;
3390
+ const slug = named[0] ?? "";
3391
+ const dest = `${slug}/CLAUDE.md`;
3392
+ const id = b.nextId("one");
3393
+ b.mark(para, "move", `only about ${slug}`, id);
3394
+ b.change({
3395
+ id,
3396
+ kind: "move",
3397
+ heading: block.heading,
3398
+ instruction: `Move this paragraph to ${dest}: it names only ${slug}.`,
3399
+ reason: "a single project's rule in the global file is loaded on every turn of every other project",
3400
+ tokens: estTokens(text2),
3401
+ destination: dest
3402
+ });
3403
+ }
3404
+ }
3405
+ const byBody = /* @__PURE__ */ new Map();
3406
+ for (const s of input.projectSections) {
3407
+ const key = `${normalize(s.heading)}|${normalize(s.body)}`;
3408
+ byBody.set(key, [...byBody.get(key) ?? [], s.label]);
3409
+ }
3410
+ for (const s of sections) {
3411
+ const labels = byBody.get(`${normalize(s.heading)}|${normalize(bodyText(lines, s.bodyLines))}`);
3412
+ if (!labels || labels.length === 0) continue;
3413
+ const id = b.nextId("proj-dup");
3414
+ b.change({
3415
+ id,
3416
+ kind: "remove",
3417
+ heading: s.heading,
3418
+ instruction: `Keep this section here and delete the identical copy from ${labels.join(", ")}.`,
3419
+ reason: "the global file is loaded in those projects too, so the copy is paid twice",
3420
+ tokens: 0
3421
+ });
3422
+ }
3423
+ const heaviest = [...input.imports].sort((x, y) => estTokens(y.text) - estTokens(x.text))[0];
3424
+ const total = estTokens(input.text.trim()) + importTokens;
3425
+ if (total > IMPORT_WEIGHT_LIMIT && heaviest) {
3426
+ const id = b.nextId("weight");
3427
+ b.change({
3428
+ id,
3429
+ kind: "move",
3430
+ heading: "(top)",
3431
+ instruction: `Split ${heaviest.label} (about ${num4(estTokens(heaviest.text))} tokens) into docs the agent opens on demand, and keep only the rules that prevent mistakes.`,
3432
+ reason: `this file plus its imports is about ${num4(total)} tokens on every turn of every project`,
3433
+ tokens: 0,
3434
+ destination: "on-demand docs"
3435
+ });
3436
+ }
3437
+ applyAdds(blocks, sections, lines, b);
3438
+ return assemble(
3439
+ "global",
3440
+ input.label,
3441
+ lines,
3442
+ b,
3443
+ { file: estTokens(input.text.trim()), imports: importTokens },
3444
+ input.imports.length
3445
+ );
3446
+ }
3447
+ function changeList(review) {
3448
+ if (review.changes.length === 0) return ["No changes proposed."];
3449
+ const out = [];
3450
+ review.changes.forEach((c, i) => {
3451
+ const where = c.heading === "(top)" ? "file level" : `section "${c.heading}"`;
3452
+ const weight = c.tokens > 0 ? `, about ${num4(c.tokens)} tokens` : "";
3453
+ out.push(`${i + 1}. [${c.kind}] ${where}${weight}: ${c.instruction}`);
3454
+ out.push(` Why: ${c.reason}`);
3455
+ if (c.destination) out.push(` Destination: ${c.destination}`);
3456
+ if (c.text) {
3457
+ out.push("", " Insert exactly this block:", "", " ```markdown");
3458
+ for (const line of c.text.replace(/\s+$/, "").split("\n")) out.push(` ${line}`);
3459
+ out.push(" ```");
3460
+ }
3461
+ out.push("");
3462
+ });
3463
+ return out;
3464
+ }
3465
+ function tokenTarget(review, what) {
3466
+ return `- ${what}: about ${num4(review.tokens.afterChanges)} tokens per turn after these changes (about ${num4(review.tokens.total)} now).`;
3467
+ }
3468
+ function buildUpgradeAll(input) {
3469
+ const parts = [];
3470
+ parts.push("# CostClaw setup upgrade");
3471
+ parts.push([
3472
+ "You are Claude Code. costclaw generated this work order locally from an audit",
3473
+ "of real usage logs plus a scan of each project; every change below is grounded",
3474
+ "in that evidence. Work through the sections in order and report what changed.",
3475
+ `Generated ${input.generatedAt}.`
3476
+ ].join("\n"));
3477
+ parts.push([
3478
+ "## Ground rules",
3479
+ "",
3480
+ "- Never invent project facts. When a merge choice is unclear, ask.",
3481
+ "- Show a diff before writing any human-written file, and back it up first.",
3482
+ "- Move content, do not delete it: history goes to docs/, rules stay.",
3483
+ '- Keep every file lean by the test "would removing this make the agent make a',
3484
+ ' mistake?" There is no target number of lines.'
3485
+ ].join("\n"));
3486
+ parts.push([
3487
+ `## Global: ${input.global.path}`,
3488
+ "",
3489
+ input.global.missing ? "This file does not exist yet. Create it with the blocks below and nothing else." : `Loaded on every turn of every project. ${num4(input.global.changes.length)} ${input.global.changes.length === 1 ? "change" : "changes"} proposed.`,
3490
+ "",
3491
+ ...changeList(input.global)
3492
+ ].join("\n"));
3493
+ for (const p of input.projects) {
3494
+ parts.push([
3495
+ `## Project: ${p.slug} (${p.projectDir})`,
3496
+ "",
3497
+ `First run \`${p.applyCommand}\`: it writes the generated sections to`,
3498
+ "`.claude/costclaw.md` and adds one `@.claude/costclaw.md` import line, leaving",
3499
+ "every line you wrote alone. Then, in that project's CLAUDE.md:",
3500
+ "",
3501
+ ...changeList(p.review)
3502
+ ].join("\n"));
3503
+ }
3504
+ const verify = ["## Verify", ""];
3505
+ verify.push("- Every section marked remove appears exactly once across the file and its include.");
3506
+ verify.push("- Every moved block exists at its destination and is linked from the file it left.");
3507
+ verify.push("- Every added block appears once, with no duplicate heading.");
3508
+ verify.push(tokenTarget(input.global, input.global.path));
3509
+ for (const p of input.projects) verify.push(tokenTarget(p.review, `${p.slug}/CLAUDE.md`));
3510
+ verify.push(
3511
+ '- After about a week of normal usage, run `npx costclaw audit`: the "Since optimize"',
3512
+ " line measures the cache-hit movement these changes are meant to produce."
3513
+ );
3514
+ parts.push(verify.join("\n"));
3515
+ return sanitizeText(parts.join("\n\n").trimEnd() + "\n");
3516
+ }
3517
+
3023
3518
  // src/audit-command.ts
3024
3519
  import { mkdir as mkdir3, readFile as readFile4, readdir as readdir2, rm as rm2, writeFile as writeFile3 } from "fs/promises";
3025
3520
  import { join as join5, resolve } from "path";
@@ -3111,7 +3606,7 @@ function projectNameFromLogs(files) {
3111
3606
  if (typeof rec.cwd === "string" && rec.cwd) {
3112
3607
  const parts = rec.cwd.split(/[\\/]+/).filter(Boolean);
3113
3608
  const base = parts.at(-1);
3114
- if (base) return base;
3609
+ if (base) return { slug: base, cwd: rec.cwd };
3115
3610
  }
3116
3611
  }
3117
3612
  } finally {
@@ -3123,13 +3618,14 @@ function projectNameFromLogs(files) {
3123
3618
  async function readSessions(rootPath) {
3124
3619
  const logs = [];
3125
3620
  const skipped = [];
3126
- let projectDirs;
3621
+ const projectDirs = /* @__PURE__ */ new Map();
3622
+ let entries;
3127
3623
  try {
3128
- projectDirs = await readdir(rootPath, { withFileTypes: true });
3624
+ entries = await readdir(rootPath, { withFileTypes: true });
3129
3625
  } catch {
3130
- return { logs, skipped };
3626
+ return { logs, skipped, projectDirs };
3131
3627
  }
3132
- for (const dir of projectDirs) {
3628
+ for (const dir of entries) {
3133
3629
  if (!dir.isDirectory()) continue;
3134
3630
  const projPath = join(rootPath, dir.name);
3135
3631
  try {
@@ -3139,7 +3635,9 @@ async function readSessions(rootPath) {
3139
3635
  continue;
3140
3636
  }
3141
3637
  const files = await collectJsonl(projPath);
3142
- const projectSlug = projectNameFromLogs(files) ?? dir.name;
3638
+ const probe = projectNameFromLogs(files);
3639
+ const projectSlug = probe?.slug ?? dir.name;
3640
+ if (probe && !projectDirs.has(probe.slug)) projectDirs.set(probe.slug, probe.cwd);
3143
3641
  for (const full of files) {
3144
3642
  const rel = relative(projPath, full).split(sep).join("/");
3145
3643
  const name = `${dir.name}/${rel}`;
@@ -3152,7 +3650,7 @@ async function readSessions(rootPath) {
3152
3650
  }
3153
3651
  }
3154
3652
  }
3155
- return { logs, skipped };
3653
+ return { logs, skipped, projectDirs };
3156
3654
  }
3157
3655
 
3158
3656
  // src/ansi.ts
@@ -4087,26 +4585,101 @@ async function deactivateLicense(opts = {}) {
4087
4585
  await clearStoredLicense(configDir);
4088
4586
  }
4089
4587
 
4588
+ // src/plan-prompt.ts
4589
+ import { createInterface } from "readline/promises";
4590
+ var PLAN_PROMPT_LINES = [
4591
+ "How do you pay for Claude Code? This decides whether the report talks in",
4592
+ "dollars or in rate-limit headroom.",
4593
+ "",
4594
+ " 1) API, pay per token",
4595
+ " 2) Pro subscription",
4596
+ " 3) Max 5x subscription",
4597
+ " 4) Max 20x subscription",
4598
+ ""
4599
+ ];
4600
+ var BY_NUMBER = ["api", "pro", "max5x", "max20x"];
4601
+ function isCI(env) {
4602
+ const value = env["CI"];
4603
+ if (!value) return false;
4604
+ return value !== "false" && value !== "0";
4605
+ }
4606
+ function shouldAskForPlan(gate) {
4607
+ if (gate.flag || gate.savedPlan) return false;
4608
+ if (gate.json) return false;
4609
+ if (!gate.stdinIsTTY || !gate.stdoutIsTTY) return false;
4610
+ return !isCI(gate.env);
4611
+ }
4612
+ function parsePlan(answer) {
4613
+ const value = answer.trim().toLowerCase();
4614
+ if (!value) return void 0;
4615
+ const index = Number(value);
4616
+ if (Number.isInteger(index) && index >= 1 && index <= BY_NUMBER.length) return BY_NUMBER[index - 1];
4617
+ return PLANS.includes(value) ? value : void 0;
4618
+ }
4619
+ async function askForPlan(ask, write) {
4620
+ write(PLAN_PROMPT_LINES.join("\n") + "\n");
4621
+ for (let attempt = 0; attempt < 2; attempt += 1) {
4622
+ let answer;
4623
+ try {
4624
+ answer = await ask();
4625
+ } catch {
4626
+ return void 0;
4627
+ }
4628
+ const plan = parsePlan(answer);
4629
+ if (plan) return plan;
4630
+ if (attempt === 0) write("Pick 1, 2, 3 or 4.\n");
4631
+ }
4632
+ return void 0;
4633
+ }
4634
+ async function askForPlanOnStdin() {
4635
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
4636
+ try {
4637
+ return await askForPlan(() => rl.question("Plan [1-4]: "), (text2) => process.stdout.write(text2));
4638
+ } finally {
4639
+ rl.close();
4640
+ }
4641
+ }
4642
+
4090
4643
  // src/audit-command.ts
4091
- async function resolvePlan(configDir, flag) {
4092
- if (flag) {
4644
+ async function resolvePlan(configDir, flag, ask) {
4645
+ const persist = async (plan) => {
4093
4646
  try {
4094
- await saveCliConfig(configDir, { plan: flag });
4647
+ await saveCliConfig(configDir, { plan });
4095
4648
  } catch (err) {
4096
4649
  process.stderr.write(`Could not save the plan setting: ${err instanceof Error ? err.message : String(err)}
4097
4650
  `);
4098
4651
  }
4652
+ };
4653
+ if (flag) {
4654
+ await persist(flag);
4099
4655
  return { plan: flag, planSource: "flag" };
4100
4656
  }
4101
4657
  const saved = (await readCliConfig(configDir)).plan;
4102
- return saved ? { plan: saved, planSource: "config" } : { plan: "api", planSource: "default" };
4658
+ if (saved) return { plan: saved, planSource: "config" };
4659
+ const prompt = ask?.prompt;
4660
+ if (prompt && shouldAskForPlan({
4661
+ flag,
4662
+ savedPlan: saved,
4663
+ json: ask?.json,
4664
+ stdinIsTTY: process.stdin.isTTY === true,
4665
+ stdoutIsTTY: process.stdout.isTTY === true,
4666
+ env: process.env
4667
+ })) {
4668
+ const answered = await prompt();
4669
+ if (answered) {
4670
+ await persist(answered);
4671
+ return { plan: answered, planSource: "asked" };
4672
+ }
4673
+ process.stdout.write("Assuming API rates. Rerun with --plan pro, max5x or max20x to reframe.\n\n");
4674
+ }
4675
+ return { plan: "api", planSource: "default" };
4103
4676
  }
4104
4677
  var DEFAULT_HTML_FILE = "costclaw-report.html";
4105
4678
  var DEFAULT_CARD_FILE = "costclaw-card.svg";
4106
4679
  var SNAPSHOT_KEEP = 50;
4107
4680
  async function loadAuditInputs(opts) {
4108
4681
  const root = opts.path || defaultProjectsPath();
4109
- const { logs, skipped } = await readSessions(root);
4682
+ const { logs, skipped, projectDirs } = await readSessions(root);
4110
4683
  if (logs.length === 0) {
4111
4684
  throw new Error(`No .jsonl sessions found under ${root}. Set CLAUDE_PROJECTS_PATH or pass --path <dir>.`);
4112
4685
  }
@@ -4123,7 +4696,7 @@ async function loadAuditInputs(opts) {
4123
4696
  } catch {
4124
4697
  }
4125
4698
  }
4126
- return { logs, claudeMd, claudeMdSource, root, skipped };
4699
+ return { logs, claudeMd, claudeMdSource, root, skipped, projectDirs };
4127
4700
  }
4128
4701
  async function runAudit(opts) {
4129
4702
  const { logs, claudeMd, claudeMdSource, root, skipped } = await loadAuditInputs({
@@ -4133,7 +4706,10 @@ async function runAudit(opts) {
4133
4706
  });
4134
4707
  const setup = await readSetup();
4135
4708
  const configDir = join5(opts.home ?? homedir4(), ".costclaw");
4136
- const { plan, planSource } = await resolvePlan(configDir, opts.plan);
4709
+ const { plan, planSource } = await resolvePlan(configDir, opts.plan, {
4710
+ json: opts.json,
4711
+ prompt: opts.promptForPlan ?? askForPlanOnStdin
4712
+ });
4137
4713
  const record = buildAudit({
4138
4714
  logs,
4139
4715
  claudeMd,
@@ -4187,92 +4763,360 @@ async function runAudit(opts) {
4187
4763
  }
4188
4764
 
4189
4765
  // src/optimize-command.ts
4190
- import { mkdir as mkdir4, writeFile as writeFile4, readFile as readFile6, stat as stat2 } from "fs/promises";
4191
- import { join as join7, dirname } from "path";
4766
+ import { mkdir as mkdir6, writeFile as writeFile6, readFile as readFile10, stat as stat3 } from "fs/promises";
4767
+ import { basename as basename2, join as join10, resolve as resolve5 } from "path";
4192
4768
  import { homedir as homedir5 } from "os";
4193
4769
 
4194
- // src/optimize-dashboard.ts
4195
- function usd5(n) {
4196
- const rounded = Math.round(n * 100) / 100;
4197
- const neg = rounded < 0;
4198
- const fixed = Math.abs(rounded).toFixed(2);
4199
- const dot = fixed.indexOf(".");
4200
- const whole = fixed.slice(0, dot);
4201
- const cents = fixed.slice(dot);
4202
- const grouped = whole.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
4203
- return `${neg ? "-" : ""}$${grouped}${cents}`;
4770
+ // src/claude-md-imports.ts
4771
+ import { readFile as readFile5 } from "fs/promises";
4772
+ import { dirname, isAbsolute, join as join6, resolve as resolve2 } from "path";
4773
+ var IMPORT_RE = /^@(\S+)\s*$/;
4774
+ async function resolveClaudeMdImports(claudeMdPath, text2, home) {
4775
+ const out = { imports: [], notes: [] };
4776
+ if (!claudeMdPath || !text2) return out;
4777
+ const base = dirname(resolve2(claudeMdPath));
4778
+ const seen = /* @__PURE__ */ new Set();
4779
+ for (const line of text2.split(/\r?\n/)) {
4780
+ const m = line.match(IMPORT_RE);
4781
+ const raw = m?.[1];
4782
+ if (!raw) continue;
4783
+ const expanded = raw === "~" || raw.startsWith("~/") ? join6(home, raw.slice(1)) : raw;
4784
+ const full = isAbsolute(expanded) ? resolve2(expanded) : resolve2(base, expanded);
4785
+ if (seen.has(full)) continue;
4786
+ seen.add(full);
4787
+ try {
4788
+ out.imports.push({ label: full, text: await readFile5(full, "utf8") });
4789
+ } catch {
4790
+ out.notes.push(`Skipped the import ${raw}: ${full} could not be read.`);
4791
+ }
4792
+ }
4793
+ return out;
4204
4794
  }
4205
- function fmtTokens(n) {
4206
- const rounded = Math.round(n);
4207
- const neg = rounded < 0;
4208
- const grouped = Math.abs(rounded).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
4209
- return `${neg ? "-" : ""}${grouped}`;
4795
+
4796
+ // src/apply-command.ts
4797
+ import { mkdir as mkdir4, writeFile as writeFile4, readFile as readFile6, rm as rm3, stat, copyFile } from "fs/promises";
4798
+ import { join as join7, dirname as dirname2 } from "path";
4799
+ var IMPORT_LINE2 = "@.claude/costclaw.md";
4800
+ var INCLUDE_REL = ".claude/costclaw.md";
4801
+ var APPLY_DIR_REL = ".claude/costclaw";
4802
+ var COMPANIONS = ["PLAYBOOK.md", "HARNESS-UPGRADE.md", "settings.suggested.json"];
4803
+ var INCLUDE_ARTIFACT = "costclaw.md";
4804
+ var OPTIMIZED_ARTIFACT = "CLAUDE.optimized.md";
4805
+ async function pathExists(p) {
4806
+ try {
4807
+ await stat(p);
4808
+ return true;
4809
+ } catch {
4810
+ return false;
4811
+ }
4210
4812
  }
4211
- function approxTokens(n) {
4212
- return `~${fmtTokens(n)}`;
4813
+ function ensureImportLine(claudeMd) {
4814
+ if (claudeMd === null) return { text: `${IMPORT_LINE2}
4815
+ `, added: true };
4816
+ const has = claudeMd.split(/\r?\n/).some((l) => l.trim() === IMPORT_LINE2);
4817
+ if (has) return { text: claudeMd, added: false };
4818
+ const base = claudeMd.replace(/\s*$/, "");
4819
+ return { text: base.length === 0 ? `${IMPORT_LINE2}
4820
+ ` : `${base}
4821
+
4822
+ ${IMPORT_LINE2}
4823
+ `, added: true };
4824
+ }
4825
+ function stripImportLine(claudeMd) {
4826
+ const lines = claudeMd.split(/\r?\n/);
4827
+ const i = lines.findIndex((l) => l.trim() === IMPORT_LINE2);
4828
+ if (i < 0) return { text: claudeMd, removed: false };
4829
+ lines.splice(i, 1);
4830
+ if (i > 0 && lines[i - 1] === "") lines.splice(i - 1, 1);
4831
+ let text2 = lines.join("\n");
4832
+ if (!text2.endsWith("\n")) text2 += "\n";
4833
+ return { text: text2 === "\n" ? "" : text2, removed: true };
4834
+ }
4835
+ async function runInclude(opts) {
4836
+ const { projectDir, artifactsDir } = opts;
4837
+ const includeSrc = join7(artifactsDir, INCLUDE_ARTIFACT);
4838
+ if (!await pathExists(includeSrc)) {
4839
+ throw new Error(`Artifacts not found in ${artifactsDir}; run costclaw optimize first`);
4840
+ }
4841
+ const includeMd = await readFile6(includeSrc, "utf8");
4842
+ const claudeDir = join7(projectDir, ".claude");
4843
+ await mkdir4(claudeDir, { recursive: true });
4844
+ const includeDest = join7(projectDir, INCLUDE_REL);
4845
+ await writeFile4(includeDest, includeMd, "utf8");
4846
+ const wrote = [includeDest];
4847
+ const lines = [`Wrote ${INCLUDE_REL}`];
4848
+ const claudeMdPath = join7(projectDir, "CLAUDE.md");
4849
+ const existing = await pathExists(claudeMdPath) ? await readFile6(claudeMdPath, "utf8") : null;
4850
+ const { text: text2, added } = ensureImportLine(existing);
4851
+ if (added) {
4852
+ await writeFile4(claudeMdPath, text2, "utf8");
4853
+ wrote.push(claudeMdPath);
4854
+ lines.push(`Added "${IMPORT_LINE2}" to CLAUDE.md`);
4855
+ } else {
4856
+ lines.push("CLAUDE.md already imports it");
4857
+ }
4858
+ const companionDir = join7(projectDir, APPLY_DIR_REL);
4859
+ await mkdir4(companionDir, { recursive: true });
4860
+ for (const name of COMPANIONS) {
4861
+ const src = join7(artifactsDir, name);
4862
+ if (await pathExists(src)) {
4863
+ const dest = join7(companionDir, name);
4864
+ await copyFile(src, dest);
4865
+ wrote.push(dest);
4866
+ }
4867
+ }
4868
+ lines.push(`Copied the playbook, work order and suggested settings to ${APPLY_DIR_REL}/`);
4869
+ lines.push(`Undo: costclaw apply ${projectDir} --remove`);
4870
+ lines.push('Next: claude "Follow .claude/costclaw/HARNESS-UPGRADE.md"');
4871
+ if (opts.applySettings) {
4872
+ const settingsSrc = join7(artifactsDir, "settings.suggested.json");
4873
+ const suggestedJson = await readFile6(settingsSrc, "utf8");
4874
+ const target = opts.applySettingsPath ?? join7(projectDir, ".claude", "settings.json");
4875
+ const settingsLines = await applyDerivedSettings(target, suggestedJson, opts.force ?? false);
4876
+ lines.push(...settingsLines);
4877
+ wrote.push(target);
4878
+ }
4879
+ return { lines, wrote, removed: [] };
4880
+ }
4881
+ async function runRemove(opts) {
4882
+ const { projectDir } = opts;
4883
+ const includeDest = join7(projectDir, INCLUDE_REL);
4884
+ const companionDir = join7(projectDir, APPLY_DIR_REL);
4885
+ const removed = [];
4886
+ if (await pathExists(includeDest)) {
4887
+ await rm3(includeDest, { force: true });
4888
+ removed.push(includeDest);
4889
+ }
4890
+ if (await pathExists(companionDir)) {
4891
+ await rm3(companionDir, { recursive: true, force: true });
4892
+ removed.push(companionDir);
4893
+ }
4894
+ const lines = [`Removed ${INCLUDE_REL} and ${APPLY_DIR_REL}/`];
4895
+ const claudeMdPath = join7(projectDir, "CLAUDE.md");
4896
+ if (await pathExists(claudeMdPath)) {
4897
+ const existing = await readFile6(claudeMdPath, "utf8");
4898
+ const { text: text2, removed: didRemove } = stripImportLine(existing);
4899
+ if (didRemove) {
4900
+ if (text2 === "") {
4901
+ await rm3(claudeMdPath, { force: true });
4902
+ removed.push(claudeMdPath);
4903
+ lines.push("Removed CLAUDE.md (it held only the import line)");
4904
+ } else {
4905
+ await writeFile4(claudeMdPath, text2, "utf8");
4906
+ lines.push(`Removed "${IMPORT_LINE2}" from CLAUDE.md`);
4907
+ }
4908
+ }
4909
+ }
4910
+ return { lines, wrote: [], removed };
4213
4911
  }
4214
- function plural2(n, noun) {
4215
- return n === 1 ? noun : `${noun}s`;
4912
+ async function runReplace(opts) {
4913
+ const { projectDir, artifactsDir, force } = opts;
4914
+ if (!await pathExists(join7(projectDir, ".git"))) {
4915
+ throw new Error(
4916
+ "apply --replace needs a git repository so the change can be undone with git checkout -- CLAUDE.md. Use the default include mode instead."
4917
+ );
4918
+ }
4919
+ const optimizedSrc = join7(artifactsDir, OPTIMIZED_ARTIFACT);
4920
+ if (!await pathExists(optimizedSrc)) {
4921
+ throw new Error(`Artifacts not found in ${artifactsDir}; run costclaw optimize first`);
4922
+ }
4923
+ const optimized = await readFile6(optimizedSrc, "utf8");
4924
+ const claudeMdPath = join7(projectDir, "CLAUDE.md");
4925
+ const backup = `${claudeMdPath}.bak`;
4926
+ if (await pathExists(backup) && !force) {
4927
+ throw new Error(
4928
+ `A backup already exists at ${backup}. Refusing to overwrite it. Pass --force to replace the existing backup.`
4929
+ );
4930
+ }
4931
+ const original = await pathExists(claudeMdPath) ? await readFile6(claudeMdPath, "utf8") : "";
4932
+ await writeFile4(backup, original, "utf8");
4933
+ await writeFile4(claudeMdPath, optimized, "utf8");
4934
+ const lines = [
4935
+ `Backed up the original to ${backup}`,
4936
+ `Wrote the optimized CLAUDE.md to ${claudeMdPath}`,
4937
+ "",
4938
+ "Diff (old vs new):",
4939
+ lineDiff(original, optimized),
4940
+ "",
4941
+ "Undo: git checkout -- CLAUDE.md (or restore CLAUDE.md.bak)"
4942
+ ];
4943
+ return { lines, wrote: [claudeMdPath, backup], removed: [] };
4216
4944
  }
4217
- function num4(n) {
4218
- return String(Math.round(n)).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
4945
+ async function runApply(opts) {
4946
+ if (opts.mode === "replace") return runReplace(opts);
4947
+ if (opts.mode === "remove") return runRemove(opts);
4948
+ return runInclude(opts);
4219
4949
  }
4220
- var STYLE2 = `
4221
- :root{
4222
- --bg:#faf9f7; --panel:#fff; --ink:#1a1a19; --ink2:#5c5a55; --line:#e3e0da;
4223
- --accent:#8a5a2b; --good:#2f6f4f; --warn:#8a6a1f; --bad:#8a3a2b;
4224
- --mono:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;
4225
- --sans:ui-sans-serif,system-ui,-apple-system,Segoe UI,Roboto,sans-serif;
4950
+ function lineDiff(oldText, newText) {
4951
+ const oldLines = oldText.split(/\r?\n/);
4952
+ const newLines = newText.split(/\r?\n/);
4953
+ const oldSet = new Set(oldLines);
4954
+ const newSet = new Set(newLines);
4955
+ const lines = [];
4956
+ for (const line of oldLines) {
4957
+ if (!newSet.has(line)) lines.push(`- ${line}`);
4958
+ }
4959
+ for (const line of newLines) {
4960
+ if (!oldSet.has(line)) lines.push(`+ ${line}`);
4961
+ }
4962
+ if (lines.length === 0) lines.push(" (no line-level changes)");
4963
+ return lines.join("\n");
4226
4964
  }
4227
- @media (prefers-color-scheme:dark){:root:not([data-theme="light"]){
4228
- --bg:#15151a; --panel:#1d1d23; --ink:#f0eeea; --ink2:#a8a49c; --line:#33323a;
4229
- --accent:#d9a05b; --good:#6fbf8f; --warn:#d9b95b; --bad:#e08a72;
4230
- }}
4231
- *{box-sizing:border-box}
4232
- body{margin:0;background:var(--bg);color:var(--ink);font:16px/1.55 var(--sans);
4233
- -webkit-font-smoothing:antialiased}
4234
- .wrap{max-width:1080px;margin:0 auto;padding:40px 24px 96px}
4235
- header{border-bottom:1px solid var(--line);padding-bottom:24px;margin-bottom:32px}
4236
- .kicker{font-size:.72rem;letter-spacing:.13em;text-transform:uppercase;color:var(--ink2);margin:0 0 10px}
4237
- h1{font-size:clamp(1.6rem,3.6vw,2.3rem);margin:0 0 6px;letter-spacing:-.02em;font-weight:750}
4238
- .sub{color:var(--ink2);margin:0;font-size:.95rem}
4239
- h2{font-size:1.06rem;letter-spacing:-.01em;margin:40px 0 14px;font-weight:700}
4240
- h2 .n{color:var(--ink2);font-weight:400;font-size:.85rem;margin-left:8px}
4241
- .panel{background:var(--panel);border:1px solid var(--line);border-radius:12px;padding:20px 22px}
4242
- .grid{display:grid;gap:16px}
4243
- .g3{grid-template-columns:repeat(auto-fit,minmax(210px,1fr))}
4244
- .g2{grid-template-columns:repeat(auto-fit,minmax(300px,1fr))}
4245
- .stat{font-variant-numeric:tabular-nums}
4246
- .stat .v{font-size:1.65rem;font-weight:750;letter-spacing:-.02em;display:block}
4247
- .stat .l{color:var(--ink2);font-size:.8rem;text-transform:uppercase;letter-spacing:.07em}
4248
- .stat .d{font-size:.83rem;margin-top:6px;color:var(--ink2)}
4249
- .win{color:var(--good);font-weight:650}
4250
- .bar{height:26px;border-radius:6px;background:linear-gradient(90deg,var(--accent) 0%,var(--accent) 100%);
4251
- position:relative;overflow:hidden}
4252
- .bar .cut{position:absolute;inset:0 0 0 95.6%;background:var(--good);opacity:.85}
4253
- .barlabels{display:flex;justify-content:space-between;font-size:.78rem;color:var(--ink2);margin-top:6px;
4254
- font-variant-numeric:tabular-nums}
4255
- table{width:100%;border-collapse:collapse;font-size:.9rem;font-variant-numeric:tabular-nums}
4256
- th,td{text-align:left;padding:9px 10px;border-bottom:1px solid var(--line)}
4257
- th{font-size:.74rem;text-transform:uppercase;letter-spacing:.07em;color:var(--ink2);font-weight:600}
4258
- td.num,th.num{text-align:right}
4259
- .scroll{overflow-x:auto}
4260
- .fix{border-left:3px solid var(--accent);padding:2px 0 2px 16px;margin:0 0 22px}
4261
- .fix h3{margin:0 0 4px;font-size:1rem}
4262
- .fix .amt{font-family:var(--mono);color:var(--accent);font-weight:700}
4263
- .fix p{margin:8px 0 0;font-size:.93rem}
4264
- .fix .do{background:color-mix(in srgb,var(--accent) 8%,transparent);border-radius:8px;padding:11px 13px;margin-top:10px}
4265
- ul.warn{list-style:none;padding:0;margin:0}
4266
- ul.warn li{padding:10px 0;border-bottom:1px solid var(--line);font-size:.92rem}
4267
- ul.warn li:last-child{border-bottom:0}
4268
- ul.warn b{font-weight:650}
4269
- .pill{display:inline-block;font-size:.7rem;padding:2px 8px;border-radius:99px;border:1px solid var(--line);
4270
- color:var(--ink2);margin-left:8px;vertical-align:1px}
4271
- .files{display:grid;gap:12px;grid-template-columns:repeat(auto-fit,minmax(250px,1fr))}
4272
- .file{border:1px solid var(--line);border-radius:10px;padding:15px 16px;background:var(--panel);
4273
- display:flex;flex-direction:column;gap:6px}
4274
- .file .nm{font-family:var(--mono);font-size:.86rem;font-weight:650;color:var(--accent)}
4275
- .file .ds{font-size:.84rem;color:var(--ink2)}
4965
+ function asStringArray(value) {
4966
+ return Array.isArray(value) ? value.filter((v) => typeof v === "string") : [];
4967
+ }
4968
+ function unionStrings(existing, additions) {
4969
+ const out = [];
4970
+ const seen = /* @__PURE__ */ new Set();
4971
+ for (const v of existing) {
4972
+ if (!seen.has(v)) {
4973
+ seen.add(v);
4974
+ out.push(v);
4975
+ }
4976
+ }
4977
+ for (const v of additions) {
4978
+ if (!seen.has(v)) {
4979
+ seen.add(v);
4980
+ out.push(v);
4981
+ }
4982
+ }
4983
+ return out;
4984
+ }
4985
+ function isPlainObject(value) {
4986
+ return typeof value === "object" && value !== null && !Array.isArray(value);
4987
+ }
4988
+ async function applyDerivedSettings(target, suggestedJson, force) {
4989
+ const backup = `${target}.bak`;
4990
+ if (await pathExists(backup) && !force) {
4991
+ throw new Error(
4992
+ `A backup already exists at ${backup}. Refusing to overwrite it. Pass --force to replace the existing backup.`
4993
+ );
4994
+ }
4995
+ let existingText = "";
4996
+ let existing = {};
4997
+ if (await pathExists(target)) {
4998
+ existingText = await readFile6(target, "utf8");
4999
+ if (existingText.trim() !== "") {
5000
+ let parsed;
5001
+ try {
5002
+ parsed = JSON.parse(existingText);
5003
+ } catch {
5004
+ throw new Error(
5005
+ `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.`
5006
+ );
5007
+ }
5008
+ if (!isPlainObject(parsed)) {
5009
+ throw new Error(
5010
+ `Expected ${target} to hold a JSON object, so it was left untouched. --apply-settings only merges into an object settings file.`
5011
+ );
5012
+ }
5013
+ existing = parsed;
5014
+ }
5015
+ }
5016
+ const suggested = JSON.parse(suggestedJson);
5017
+ const suggestedAllow = asStringArray(suggested.permissions?.allow);
5018
+ const suggestedDeny = asStringArray(suggested.permissions?.deny);
5019
+ const existingPerms = isPlainObject(existing.permissions) ? existing.permissions : {};
5020
+ const mergedPerms = { ...existingPerms };
5021
+ mergedPerms.allow = unionStrings(asStringArray(existingPerms.allow), suggestedAllow);
5022
+ mergedPerms.deny = unionStrings(asStringArray(existingPerms.deny), suggestedDeny);
5023
+ const merged = { ...existing, permissions: mergedPerms };
5024
+ const mergedText = JSON.stringify(merged, null, 2) + "\n";
5025
+ await mkdir4(dirname2(target), { recursive: true });
5026
+ await writeFile4(backup, existingText, "utf8");
5027
+ await writeFile4(target, mergedText, "utf8");
5028
+ return [
5029
+ `Merged the derived permission allowlist into ${target}`,
5030
+ `Backed up the previous file to ${backup}`,
5031
+ "Only permissions.allow and permissions.deny changed (deduped union, existing entries kept and ordered first). Every other key was left as it was.",
5032
+ "",
5033
+ "Diff (previous vs merged):",
5034
+ lineDiff(existingText, mergedText)
5035
+ ];
5036
+ }
5037
+
5038
+ // src/optimize-dashboard.ts
5039
+ function usd5(n) {
5040
+ const rounded = Math.round(n * 100) / 100;
5041
+ const neg = rounded < 0;
5042
+ const fixed = Math.abs(rounded).toFixed(2);
5043
+ const dot = fixed.indexOf(".");
5044
+ const whole = fixed.slice(0, dot);
5045
+ const cents = fixed.slice(dot);
5046
+ const grouped = whole.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
5047
+ return `${neg ? "-" : ""}$${grouped}${cents}`;
5048
+ }
5049
+ function fmtTokens(n) {
5050
+ const rounded = Math.round(n);
5051
+ const neg = rounded < 0;
5052
+ const grouped = Math.abs(rounded).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
5053
+ return `${neg ? "-" : ""}${grouped}`;
5054
+ }
5055
+ function approxTokens(n) {
5056
+ return `~${fmtTokens(n)}`;
5057
+ }
5058
+ function plural2(n, noun) {
5059
+ return n === 1 ? noun : `${noun}s`;
5060
+ }
5061
+ function num5(n) {
5062
+ return String(Math.round(n)).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
5063
+ }
5064
+ var STYLE2 = `
5065
+ :root{
5066
+ --bg:#faf9f7; --panel:#fff; --ink:#1a1a19; --ink2:#5c5a55; --line:#e3e0da;
5067
+ --accent:#8a5a2b; --good:#2f6f4f; --warn:#8a6a1f; --bad:#8a3a2b;
5068
+ --mono:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;
5069
+ --sans:ui-sans-serif,system-ui,-apple-system,Segoe UI,Roboto,sans-serif;
5070
+ }
5071
+ @media (prefers-color-scheme:dark){:root:not([data-theme="light"]){
5072
+ --bg:#15151a; --panel:#1d1d23; --ink:#f0eeea; --ink2:#a8a49c; --line:#33323a;
5073
+ --accent:#d9a05b; --good:#6fbf8f; --warn:#d9b95b; --bad:#e08a72;
5074
+ }}
5075
+ *{box-sizing:border-box}
5076
+ body{margin:0;background:var(--bg);color:var(--ink);font:16px/1.55 var(--sans);
5077
+ -webkit-font-smoothing:antialiased}
5078
+ .wrap{max-width:1080px;margin:0 auto;padding:40px 24px 96px}
5079
+ header{border-bottom:1px solid var(--line);padding-bottom:24px;margin-bottom:32px}
5080
+ .kicker{font-size:.72rem;letter-spacing:.13em;text-transform:uppercase;color:var(--ink2);margin:0 0 10px}
5081
+ h1{font-size:clamp(1.6rem,3.6vw,2.3rem);margin:0 0 6px;letter-spacing:-.02em;font-weight:750}
5082
+ .sub{color:var(--ink2);margin:0;font-size:.95rem}
5083
+ h2{font-size:1.06rem;letter-spacing:-.01em;margin:40px 0 14px;font-weight:700}
5084
+ h2 .n{color:var(--ink2);font-weight:400;font-size:.85rem;margin-left:8px}
5085
+ .panel{background:var(--panel);border:1px solid var(--line);border-radius:12px;padding:20px 22px}
5086
+ .grid{display:grid;gap:16px}
5087
+ .g3{grid-template-columns:repeat(auto-fit,minmax(210px,1fr))}
5088
+ .g2{grid-template-columns:repeat(auto-fit,minmax(300px,1fr))}
5089
+ .stat{font-variant-numeric:tabular-nums}
5090
+ .stat .v{font-size:1.65rem;font-weight:750;letter-spacing:-.02em;display:block}
5091
+ .stat .l{color:var(--ink2);font-size:.8rem;text-transform:uppercase;letter-spacing:.07em}
5092
+ .stat .d{font-size:.83rem;margin-top:6px;color:var(--ink2)}
5093
+ .win{color:var(--good);font-weight:650}
5094
+ .bar{height:26px;border-radius:6px;background:linear-gradient(90deg,var(--accent) 0%,var(--accent) 100%);
5095
+ position:relative;overflow:hidden}
5096
+ .bar .cut{position:absolute;inset:0 0 0 95.6%;background:var(--good);opacity:.85}
5097
+ .barlabels{display:flex;justify-content:space-between;font-size:.78rem;color:var(--ink2);margin-top:6px;
5098
+ font-variant-numeric:tabular-nums}
5099
+ table{width:100%;border-collapse:collapse;font-size:.9rem;font-variant-numeric:tabular-nums}
5100
+ th,td{text-align:left;padding:9px 10px;border-bottom:1px solid var(--line)}
5101
+ th{font-size:.74rem;text-transform:uppercase;letter-spacing:.07em;color:var(--ink2);font-weight:600}
5102
+ td.num,th.num{text-align:right}
5103
+ .scroll{overflow-x:auto}
5104
+ .fix{border-left:3px solid var(--accent);padding:2px 0 2px 16px;margin:0 0 22px}
5105
+ .fix h3{margin:0 0 4px;font-size:1rem}
5106
+ .fix .amt{font-family:var(--mono);color:var(--accent);font-weight:700}
5107
+ .fix p{margin:8px 0 0;font-size:.93rem}
5108
+ .fix .do{background:color-mix(in srgb,var(--accent) 8%,transparent);border-radius:8px;padding:11px 13px;margin-top:10px}
5109
+ ul.warn{list-style:none;padding:0;margin:0}
5110
+ ul.warn li{padding:10px 0;border-bottom:1px solid var(--line);font-size:.92rem}
5111
+ ul.warn li:last-child{border-bottom:0}
5112
+ ul.warn b{font-weight:650}
5113
+ .pill{display:inline-block;font-size:.7rem;padding:2px 8px;border-radius:99px;border:1px solid var(--line);
5114
+ color:var(--ink2);margin-left:8px;vertical-align:1px}
5115
+ .files{display:grid;gap:12px;grid-template-columns:repeat(auto-fit,minmax(250px,1fr))}
5116
+ .file{border:1px solid var(--line);border-radius:10px;padding:15px 16px;background:var(--panel);
5117
+ display:flex;flex-direction:column;gap:6px}
5118
+ .file .nm{font-family:var(--mono);font-size:.86rem;font-weight:650;color:var(--accent)}
5119
+ .file .ds{font-size:.84rem;color:var(--ink2)}
4276
5120
  .file a{margin-top:auto;font-size:.83rem;color:var(--ink);text-decoration:none;border-bottom:1px solid var(--line);
4277
5121
  align-self:flex-start;padding-bottom:1px}
4278
5122
  .file a:hover{border-color:var(--accent)}
@@ -4533,22 +5377,27 @@ var OPTIMIZED_NAME = "CLAUDE.optimized.md";
4533
5377
  var PLAYBOOK_NAME = "PLAYBOOK.md";
4534
5378
  var SETTINGS_NAME = "settings.suggested.json";
4535
5379
  var HARNESS_NAME = "HARNESS-UPGRADE.md";
5380
+ var INCLUDE_NAME = "costclaw.md";
4536
5381
  function renderArtifactCards(input) {
4537
5382
  const { before, after } = input.claudeMdTokens;
4538
5383
  const lighter = before !== null && after < before ? ` and ${fmtTokens(before - after)} tokens lighter` : "";
4539
5384
  const placeholders = `${input.placeholdersRemaining} ${plural2(input.placeholdersRemaining, "placeholder")} to fill.`;
4540
5385
  const claudeDesc = before === null ? `A new CLAUDE.md scaffold for your project. ${placeholders}` : `Your CLAUDE.md, restructured${lighter}. ${placeholders}`;
4541
5386
  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>`;
4542
- 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>`;
5387
+ 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(
5388
+ INCLUDE_NAME,
5389
+ "The generated sections as a standalone include. apply writes it to .claude/costclaw.md and adds one @ line to your CLAUDE.md."
5390
+ ) + `</div>`;
4543
5391
  }
4544
5392
  function renderApplyCta(input) {
4545
- 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>`;
5393
+ 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>` : "";
5394
+ 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>`;
4546
5395
  }
4547
5396
  function renderCarriedDisclosure(sections, carriedTokens) {
4548
5397
  const carried = sections.filter((s) => s.disposition === "carried");
4549
5398
  if (carried.length === 0) return "";
4550
5399
  const names = carried.map((s) => esc(s.name)).join(" &middot; ");
4551
- const weight = carriedTokens > 0 ? `, about ${num4(carriedTokens)} tokens` : "";
5400
+ const weight = carriedTokens > 0 ? `, about ${num5(carriedTokens)} tokens` : "";
4552
5401
  const note = carriedTokens > 0 ? `<p class="note">Carried through as written. costclaw does not rewrite your prose, so this is where the remaining weight sits. HARNESS-UPGRADE.md ranks these sections and flags their dated lines for you to move into docs/.</p>` : "";
4553
5402
  return `<details style="margin-top:34px"><summary>All ${carried.length} ${plural2(carried.length, "section")} carried across from your existing CLAUDE.md${weight}</summary><div class="cols">${names}</div>${note}</details>`;
4554
5403
  }
@@ -4557,7 +5406,7 @@ function renderHeader(input) {
4557
5406
  const stack = input.stack.map((s) => s.trim()).filter((s) => s.length > 0);
4558
5407
  if (stack.length > 0) parts.push(esc(stack.join(", ")));
4559
5408
  parts.push(`${input.commandsCount} ${plural2(input.commandsCount, "command")} detected`);
4560
- parts.push(`4 artifacts written to ${esc(input.artifactsDir)}/`);
5409
+ parts.push(`5 artifacts written to ${esc(input.artifactsDir)}/`);
4561
5410
  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>`;
4562
5411
  }
4563
5412
  function renderOptimizeDashboard(input) {
@@ -4567,7 +5416,7 @@ function renderOptimizeDashboard(input) {
4567
5416
  <meta charset="utf-8">
4568
5417
  <meta name="viewport" content="width=device-width,initial-scale=1">
4569
5418
  <title>CostClaw optimize: ${esc(input.projectName)}</title>
4570
- <style>${STYLE2}</style>
5419
+ <style>${STYLE2}${input.review ? REVIEW_STYLE : ""}</style>
4571
5420
  </head>
4572
5421
  <body>
4573
5422
  <div class="wrap">
@@ -4578,6 +5427,9 @@ ${renderReceipt(input)}
4578
5427
 
4579
5428
  <h2>Your CLAUDE.md, before and after<span class="n">what actually changed</span></h2>
4580
5429
  <div class="panel">${renderComparisonTabs(input)}</div>
5430
+ ${input.review ? `
5431
+ <h2>What to change in your CLAUDE.md<span class="n">${num5(input.review.changes.length)} proposed ${plural2(input.review.changes.length, "change")}</span></h2>
5432
+ <div class="panel">${renderAnnotatedFile(input.review)}</div>` : ""}
4581
5433
 
4582
5434
  <h2>Fixes, ranked by what they recover</h2>
4583
5435
  ${renderFixes(input.fixes, input.report)}
@@ -4585,7 +5437,7 @@ ${renderFixes(input.fixes, input.report)}
4585
5437
  <h2>Setup warnings<span class="n">no direct dollar figure, still costly</span></h2>
4586
5438
  ${renderSetupWarnings(input.fixes, input.report)}
4587
5439
 
4588
- <h2>Your four artifacts</h2>
5440
+ <h2>Your five artifacts</h2>
4589
5441
  ${renderArtifactCards(input)}
4590
5442
 
4591
5443
  <h2>Apply it</h2>
@@ -4596,6 +5448,185 @@ ${renderCarriedDisclosure(input.sectionDispositions, input.carriedTokens)}
4596
5448
  <footer>Generated locally by CostClaw v${esc(input.version)}. Dry run: none of your files were changed.
4597
5449
  No network calls, no telemetry, no model calls.</footer>
4598
5450
 
5451
+ </div>
5452
+ </body>
5453
+ </html>
5454
+ `;
5455
+ }
5456
+ var KEEP_RUN_MAX = 12;
5457
+ var TRUNCATE_OVER_LINES = 800;
5458
+ var REVIEW_STYLE = `
5459
+ pre.review{font-family:var(--mono);font-size:.78rem;line-height:1.55;margin:0;padding:14px 0;
5460
+ background:color-mix(in srgb,var(--ink) 4%,transparent);border-radius:8px;overflow-x:auto}
5461
+ pre.review .ln{display:block;padding:0 14px;white-space:pre-wrap;word-break:break-word}
5462
+ pre.review .g{display:inline-block;width:3.2em;color:var(--ink2);user-select:none;text-align:right;margin-right:10px}
5463
+ pre.review .why{color:var(--ink2);font-size:.72rem;margin-left:10px}
5464
+ pre.review .mark-remove{background:color-mix(in srgb,var(--bad) 14%,transparent)}
5465
+ pre.review .mark-remove .t{text-decoration:line-through}
5466
+ pre.review .mark-move{background:color-mix(in srgb,var(--warn) 14%,transparent)}
5467
+ pre.review .mark-add{background:color-mix(in srgb,var(--good) 14%,transparent)}
5468
+ pre.review .skip{color:var(--ink2);font-style:italic}
5469
+ .legend{font-size:.78rem;color:var(--ink2);margin:0 0 10px}
5470
+ .legend b{font-weight:650}
5471
+ .legend .sw{display:inline-block;width:10px;height:10px;border-radius:3px;margin:0 4px 0 12px}
5472
+ .legend .sw.r{background:color-mix(in srgb,var(--bad) 50%,transparent)}
5473
+ .legend .sw.m{background:color-mix(in srgb,var(--warn) 50%,transparent)}
5474
+ .legend .sw.a{background:color-mix(in srgb,var(--good) 50%,transparent)}
5475
+ textarea.prompt{width:100%;min-height:190px;font-family:var(--mono);font-size:.76rem;line-height:1.5;
5476
+ border:1px solid var(--line);border-radius:8px;padding:12px;background:var(--bg);color:var(--ink);resize:vertical}
5477
+ button.copy{font:inherit;font-size:.84rem;padding:7px 14px;border-radius:7px;border:1px solid var(--accent);
5478
+ background:var(--accent);color:#fff;font-weight:600;cursor:pointer;margin-bottom:10px}
5479
+ .revhead{font-size:.86rem;color:var(--ink2);margin:0 0 12px}
5480
+ .revhead b{color:var(--ink);font-weight:650}
5481
+ `;
5482
+ var COPY_SCRIPT = 'function ccCopy(b){var t=b.parentNode.querySelector("textarea");t.select();if(navigator.clipboard){navigator.clipboard.writeText(t.value)}else{document.execCommand("copy")}b.textContent="Copied";}';
5483
+ function lineHtml(line, gutter) {
5484
+ const why = line.reason ? `<span class="why">${esc(line.reason)}</span>` : "";
5485
+ const cls = line.mark === "keep" ? "mark-keep" : `mark-${line.mark}`;
5486
+ return `<span class="ln ${cls}"><span class="g">${esc(gutter === null ? "+" : String(gutter))}</span><span class="t">${esc(line.text)}</span>${why}</span>`;
5487
+ }
5488
+ function renderLines(lines, keepRunMax) {
5489
+ const out = [];
5490
+ let run = [];
5491
+ const flush = () => {
5492
+ if (run.length === 0) return;
5493
+ const half = Math.floor(keepRunMax / 2);
5494
+ if (keepRunMax > 0 && run.length > keepRunMax) {
5495
+ const head = run.slice(0, half);
5496
+ const tail = run.slice(run.length - half);
5497
+ for (const i of head) out.push(lineHtml(lines[i], i + 1));
5498
+ out.push(
5499
+ `<span class="ln skip"><span class="g"></span>... ${num5(run.length - head.length - tail.length)} unchanged lines ...</span>`
5500
+ );
5501
+ for (const i of tail) out.push(lineHtml(lines[i], i + 1));
5502
+ } else {
5503
+ for (const i of run) out.push(lineHtml(lines[i], i + 1));
5504
+ }
5505
+ run = [];
5506
+ };
5507
+ for (let i = 0; i < lines.length; i++) {
5508
+ const l = lines[i];
5509
+ if (l.mark === "keep") {
5510
+ run.push(i);
5511
+ continue;
5512
+ }
5513
+ flush();
5514
+ out.push(lineHtml(l, l.mark === "add" ? null : i + 1));
5515
+ }
5516
+ flush();
5517
+ return `<pre class="review">${out.join("")}</pre>`;
5518
+ }
5519
+ function renderAnnotatedFile(review) {
5520
+ const legend = `<p class="legend"><b>Legend</b><span class="sw r"></span>remove<span class="sw m"></span>move out<span class="sw a"></span>add</p>`;
5521
+ if (review.missing) {
5522
+ const adds = review.lines.filter((l) => l.mark === "add");
5523
+ if (adds.length === 0) {
5524
+ return `<p class="note">${esc(review.label)} does not exist yet, and nothing needs adding.</p>`;
5525
+ }
5526
+ return legend + `<p class="note">${esc(review.label)} does not exist yet. Proposed content:</p>` + renderLines(adds, 0);
5527
+ }
5528
+ return legend + renderLines(review.lines, review.lines.length > TRUNCATE_OVER_LINES ? KEEP_RUN_MAX : 0);
5529
+ }
5530
+ function reviewCountLine(review) {
5531
+ const n = review.changes.length;
5532
+ if (n === 0) return `No changes proposed for ${esc(review.label)}.`;
5533
+ return `<b>${num5(n)} proposed ${plural2(n, "change")}</b> to ${esc(review.label)}`;
5534
+ }
5535
+ var INDEX_STYLE = `
5536
+ .rowpath{display:block;font-size:.76rem;color:var(--ink2);font-family:var(--mono);word-break:break-all}
5537
+ .acts{display:flex;gap:8px;flex-wrap:wrap}
5538
+ .acts form{margin:0}
5539
+ .acts button{font:inherit;font-size:.82rem;padding:6px 12px;border-radius:7px;border:1px solid var(--line);
5540
+ background:var(--panel);color:var(--ink);cursor:pointer}
5541
+ .acts button:hover{border-color:var(--accent)}
5542
+ .acts button.go{background:var(--accent);border-color:var(--accent);color:#fff;font-weight:600}
5543
+ td code.cmd{margin-top:0;font-size:.78rem;white-space:pre-wrap;word-break:break-all}
5544
+ .banner{background:color-mix(in srgb,var(--good) 14%,transparent);border:1px solid var(--line);
5545
+ border-radius:10px;padding:12px 14px;margin:0 0 22px;font-size:.9rem}
5546
+ .state{font-size:.82rem}
5547
+ .state.on{color:var(--good);font-weight:650}
5548
+ .state.off{color:var(--ink2)}
5549
+ `;
5550
+ function indexTokens(tokens) {
5551
+ if (tokens.before === null) return `${esc(approxTokens(tokens.after))} (new file)`;
5552
+ return `${esc(approxTokens(tokens.before))} to ${esc(approxTokens(tokens.after))}`;
5553
+ }
5554
+ function indexStatus(appliedAt) {
5555
+ if (!appliedAt) return `<span class="state off">not applied</span>`;
5556
+ return `<span class="state on">applied ${esc(appliedAt.slice(0, 10))}</span>`;
5557
+ }
5558
+ function actionForm(token, slug, action, label, primary) {
5559
+ 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>`;
5560
+ }
5561
+ function indexActions(row, serve) {
5562
+ const details = `<a href="${esc(row.artifactsHref)}">details</a>`;
5563
+ if (!serve) {
5564
+ return `<code class="cmd">${esc(row.applyCommand)}</code><p class="note" style="margin-top:6px">${details}</p>`;
5565
+ }
5566
+ 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>`;
5567
+ }
5568
+ function renderPromptPanel(review) {
5569
+ return `<div class="panel"><button class="copy" type="button" onclick="ccCopy(this)">Copy the prompt</button><textarea readonly rows="14" class="prompt">${esc(review.upgradeAll)}</textarea><p class="note">Paste it into Claude Code in any folder, or run the line below. It covers your global CLAUDE.md and every project on this page, so there is one prompt, not one per project.</p><code class="cmd">claude "Follow ${esc(review.upgradeAllPath)}"</code><p class="note">costclaw never calls a model: this work order is deterministic text built from your own audit. Your agent does the editing, with your approval.</p></div>`;
5570
+ }
5571
+ function renderGlobalPanel(review) {
5572
+ const t = review.tokens;
5573
+ const importCount = review.importCount;
5574
+ const imported = importCount > 0 ? ` plus ${num5(importCount)} imported ${plural2(importCount, "file")}` : "";
5575
+ const weight = `<p class="revhead"><b>${esc(review.label)}</b>${imported}: about ${num5(t.total)} tokens on every turn of every project, about ${num5(t.afterChanges)} after these changes. ${reviewCountLine(review)}.</p>`;
5576
+ return `<div class="panel">${weight}${renderAnnotatedFile(review)}</div>`;
5577
+ }
5578
+ function renderProjectPanels(input, review) {
5579
+ const out = [];
5580
+ input.rows.forEach((row, i) => {
5581
+ const r = review.projects.get(row.slug);
5582
+ if (!r) return;
5583
+ out.push(
5584
+ `<details${i === 0 ? " open" : ""}><summary>${esc(row.slug)}: ${num5(r.changes.length)} proposed ${plural2(r.changes.length, "change")}</summary><div class="panel" style="margin-top:10px"><p class="revhead">${reviewCountLine(r)}. About ${num5(r.tokens.total)} tokens per turn, about ${num5(r.tokens.afterChanges)} after these changes.</p>` + renderAnnotatedFile(r) + `<div style="margin-top:14px">${indexActions(row, input.serve)}</div></div></details>`
5585
+ );
5586
+ });
5587
+ return out.join("");
5588
+ }
5589
+ function renderOptimizeIndex(input) {
5590
+ const total = input.rows.reduce((sum, r) => sum + r.spendUsd, 0);
5591
+ const recoverable = input.rows.reduce((sum, r) => sum + r.recoverableUsd, 0);
5592
+ const rows = input.rows.map(
5593
+ (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>`
5594
+ ).join("");
5595
+ 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>`;
5596
+ const banner = input.serve?.message ? `<p class="banner">${esc(input.serve.message)}</p>` : "";
5597
+ 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>` : "";
5598
+ 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>`;
5599
+ return `<!doctype html>
5600
+ <html lang="en">
5601
+ <head>
5602
+ <meta charset="utf-8">
5603
+ <meta name="viewport" content="width=device-width,initial-scale=1">
5604
+ <title>CostClaw optimize: ${input.rows.length} ${plural2(input.rows.length, "project")}</title>
5605
+ <style>${STYLE2}${INDEX_STYLE}${input.review ? REVIEW_STYLE : ""}</style>
5606
+ ${input.review ? `<script>${COPY_SCRIPT}</script>` : ""}
5607
+ </head>
5608
+ <body>
5609
+ <div class="wrap">
5610
+ <header><p class="kicker">CostClaw optimize &middot; generated locally &middot; nothing left your machine</p>
5611
+ <h1>${input.rows.length} ${plural2(input.rows.length, "project")} ready to apply</h1>
5612
+ <p class="sub">${esc(usd5(total))} of analyzed spend &middot; ${esc(usd5(recoverable))} recoverable &middot;
5613
+ artifacts in ${esc(input.root)}/</p></header>
5614
+
5615
+ ${banner}${done}
5616
+ ${input.review ? `<h2>Your upgrade prompt<span class="n">one paste applies all of it</span></h2>
5617
+ ${renderPromptPanel(input.review)}
5618
+
5619
+ <h2>Global CLAUDE.md<span class="n">loaded on every turn of every project</span></h2>
5620
+ ${renderGlobalPanel(input.review.global)}` : ""}
5621
+
5622
+ <h2>Your projects<span class="n">ranked by spend</span></h2>
5623
+ ${body}
5624
+ ${how}
5625
+ ${input.review ? renderProjectPanels(input, input.review) : ""}
5626
+
5627
+ <footer>Generated locally by CostClaw v${esc(input.version)} on ${esc(input.generatedAt)}.
5628
+ Nothing was written inside any project. No network calls, no telemetry, no model calls.</footer>
5629
+
4599
5630
  </div>
4600
5631
  </body>
4601
5632
  </html>
@@ -4603,8 +5634,8 @@ No network calls, no telemetry, no model calls.</footer>
4603
5634
  }
4604
5635
 
4605
5636
  // src/project-scan.ts
4606
- import { readdir as readdir3, readFile as readFile5, stat } from "fs/promises";
4607
- import { join as join6, basename } from "path";
5637
+ import { readdir as readdir3, readFile as readFile7, stat as stat2 } from "fs/promises";
5638
+ import { join as join8, basename } from "path";
4608
5639
  var NOISE_DIRS = /* @__PURE__ */ new Set([
4609
5640
  "node_modules",
4610
5641
  ".git",
@@ -4633,7 +5664,7 @@ var DIR_NOTES = {
4633
5664
  };
4634
5665
  async function readText(p) {
4635
5666
  try {
4636
- return await readFile5(p, "utf8");
5667
+ return await readFile7(p, "utf8");
4637
5668
  } catch {
4638
5669
  return null;
4639
5670
  }
@@ -4743,7 +5774,7 @@ async function containsTestFiles(dir) {
4743
5774
  const top = await listEntries(dir);
4744
5775
  if (top.files.some((f) => TEST_FILE.test(f))) return true;
4745
5776
  for (const sub of top.dirs) {
4746
- const inner = await listEntries(join6(dir, sub));
5777
+ const inner = await listEntries(join8(dir, sub));
4747
5778
  if (inner.files.some((f) => TEST_FILE.test(f))) return true;
4748
5779
  }
4749
5780
  return false;
@@ -4753,14 +5784,14 @@ async function detectTestsLocation(dir, files, dirs) {
4753
5784
  if (candidates.length > 0) {
4754
5785
  const withTests = [];
4755
5786
  for (const c of candidates) {
4756
- if (await containsTestFiles(join6(dir, c))) withTests.push(c);
5787
+ if (await containsTestFiles(join8(dir, c))) withTests.push(c);
4757
5788
  }
4758
5789
  const chosen = withTests.length > 0 ? withTests : candidates;
4759
5790
  return `tests in ${chosen.map((c) => `${c}/`).join(" and ")}`;
4760
5791
  }
4761
5792
  if (files.some((f) => TEST_FILE.test(f))) return "tests alongside source (*.test.* / *.spec.*)";
4762
5793
  if (dirs.includes("src")) {
4763
- const sub = await listEntries(join6(dir, "src"));
5794
+ const sub = await listEntries(join8(dir, "src"));
4764
5795
  if (sub.files.some((f) => TEST_FILE.test(f))) {
4765
5796
  return "tests alongside source (*.test.* / *.spec.*)";
4766
5797
  }
@@ -4843,7 +5874,7 @@ async function scanNode(dir, files, dirs, pkg, profile) {
4843
5874
  if (oneFileCmd !== null && "test" in scripts) {
4844
5875
  profile.commands.push({ label: "test one file", command: oneFileCmd });
4845
5876
  }
4846
- const tsconfig = parseJson(await readText(join6(dir, "tsconfig.json")));
5877
+ const tsconfig = parseJson(await readText(join8(dir, "tsconfig.json")));
4847
5878
  if (tsconfig) {
4848
5879
  const co = tsconfig.compilerOptions;
4849
5880
  if (co && co.strict === true) pushUnique(profile.codeStyle, "TypeScript strict mode");
@@ -4946,7 +5977,7 @@ async function scanPython(dir, files, profile) {
4946
5977
  const deps = [];
4947
5978
  const tables = /* @__PURE__ */ new Set();
4948
5979
  let hasPoetry = false;
4949
- const pyprojectText = await readText(join6(dir, "pyproject.toml"));
5980
+ const pyprojectText = await readText(join8(dir, "pyproject.toml"));
4950
5981
  if (pyprojectText !== null) {
4951
5982
  const parsed = parsePyproject(pyprojectText);
4952
5983
  name = parsed.name;
@@ -4956,7 +5987,7 @@ async function scanPython(dir, files, profile) {
4956
5987
  hasPoetry = parsed.hasPoetry;
4957
5988
  }
4958
5989
  if (files.includes("requirements.txt")) {
4959
- const reqText = await readText(join6(dir, "requirements.txt"));
5990
+ const reqText = await readText(join8(dir, "requirements.txt"));
4960
5991
  if (reqText !== null) for (const d of pyDepsFromRequirements(reqText)) pushUnique(deps, d);
4961
5992
  }
4962
5993
  if (name !== null && name.trim() !== "") profile.name = name;
@@ -4990,7 +6021,7 @@ async function scanPython(dir, files, profile) {
4990
6021
  }
4991
6022
  }
4992
6023
  async function scanRust(dir, profile) {
4993
- const text2 = await readText(join6(dir, "Cargo.toml"));
6024
+ const text2 = await readText(join8(dir, "Cargo.toml"));
4994
6025
  pushUnique(profile.stack, "Rust");
4995
6026
  profile.packageManager = "cargo";
4996
6027
  if (text2 !== null) {
@@ -5016,7 +6047,7 @@ async function scanRust(dir, profile) {
5016
6047
  profile.commands.push({ label: "lint", command: "cargo clippy" });
5017
6048
  }
5018
6049
  async function scanGo(dir, profile) {
5019
- const text2 = await readText(join6(dir, "go.mod"));
6050
+ const text2 = await readText(join8(dir, "go.mod"));
5020
6051
  pushUnique(profile.stack, "Go");
5021
6052
  profile.packageManager = "go";
5022
6053
  if (text2 !== null) {
@@ -5081,7 +6112,7 @@ async function scanProject(dir) {
5081
6112
  const profile = emptyProfile(basename(dir));
5082
6113
  const { files, dirs } = await listEntries(dir);
5083
6114
  if (files.includes("package.json")) {
5084
- const pkg = parseJson(await readText(join6(dir, "package.json")));
6115
+ const pkg = parseJson(await readText(join8(dir, "package.json")));
5085
6116
  if (pkg) await scanNode(dir, files, dirs, pkg, profile);
5086
6117
  }
5087
6118
  if (files.includes("pyproject.toml") || files.includes("requirements.txt") || files.includes("setup.py")) {
@@ -5094,7 +6125,7 @@ async function scanProject(dir) {
5094
6125
  await scanGo(dir, profile);
5095
6126
  }
5096
6127
  if (files.includes("Makefile") && profile.commands.length === 0) {
5097
- const text2 = await readText(join6(dir, "Makefile"));
6128
+ const text2 = await readText(join8(dir, "Makefile"));
5098
6129
  if (text2 !== null) {
5099
6130
  for (const t of parseMakefile(text2)) {
5100
6131
  profile.commands.push({ label: t, command: `make ${t}` });
@@ -5104,7 +6135,7 @@ async function scanProject(dir) {
5104
6135
  if (profile.description === null || profile.name === basename(dir)) {
5105
6136
  const readmeName = files.find((f) => /^readme(\.md|\.markdown|\.txt)?$/i.test(f));
5106
6137
  if (readmeName) {
5107
- const text2 = await readText(join6(dir, readmeName));
6138
+ const text2 = await readText(join8(dir, readmeName));
5108
6139
  if (text2 !== null) {
5109
6140
  const parsed = parseReadme(text2);
5110
6141
  if (profile.name === basename(dir) && parsed.name !== null) profile.name = parsed.name;
@@ -5117,21 +6148,313 @@ async function scanProject(dir) {
5117
6148
  profile.structure = await detectStructure(dir, dirs);
5118
6149
  const envFile = files.includes(".env.example") ? ".env.example" : files.includes(".env.sample") ? ".env.sample" : null;
5119
6150
  if (envFile) {
5120
- const text2 = await readText(join6(dir, envFile));
6151
+ const text2 = await readText(join8(dir, envFile));
5121
6152
  if (text2 !== null) profile.envVars = parseEnvNames(text2);
5122
6153
  }
5123
6154
  return profile;
5124
6155
  }
5125
6156
 
6157
+ // src/serve.ts
6158
+ import { createServer } from "http";
6159
+ import { randomBytes } from "crypto";
6160
+ import { readFile as readFile8 } from "fs/promises";
6161
+ import { extname, resolve as resolve3, sep as sep2 } from "path";
6162
+ var DEFAULT_IDLE_MS = 30 * 60 * 1e3;
6163
+ var MAX_BODY_BYTES = 64 * 1024;
6164
+ var DASHBOARD_NAME = "DASHBOARD.html";
6165
+ function parseForm(body) {
6166
+ const out = {};
6167
+ for (const pair of body.split("&")) {
6168
+ if (pair === "") continue;
6169
+ const eq = pair.indexOf("=");
6170
+ const rawKey = eq < 0 ? pair : pair.slice(0, eq);
6171
+ const rawValue = eq < 0 ? "" : pair.slice(eq + 1);
6172
+ const key = decodeURIComponent(rawKey.replace(/\+/g, " "));
6173
+ const value = decodeURIComponent(rawValue.replace(/\+/g, " "));
6174
+ out[key] = value;
6175
+ }
6176
+ return out;
6177
+ }
6178
+ function safeArtifactPath(root, urlPath) {
6179
+ let decoded;
6180
+ try {
6181
+ decoded = decodeURIComponent(urlPath);
6182
+ } catch {
6183
+ return null;
6184
+ }
6185
+ if (decoded.includes("\0")) return null;
6186
+ const resolvedRoot = resolve3(root);
6187
+ const full = resolve3(resolvedRoot, "." + decoded);
6188
+ if (full !== resolvedRoot && !full.startsWith(resolvedRoot + sep2)) return null;
6189
+ return full;
6190
+ }
6191
+ function rowsFromManifest(manifest) {
6192
+ return manifest.projects.map((e) => ({
6193
+ slug: e.slug,
6194
+ projectDir: e.projectDir,
6195
+ artifactsHref: `${e.dir}/${DASHBOARD_NAME}`,
6196
+ spendUsd: e.spendUsd,
6197
+ recoverableUsd: e.recoverableUsd,
6198
+ tokens: e.tokens,
6199
+ ...e.appliedAt ? { appliedAt: e.appliedAt } : {},
6200
+ applyCommand: `costclaw apply ${e.projectDir}`
6201
+ }));
6202
+ }
6203
+ function isApplyAction(value) {
6204
+ return value === "include" || value === "remove" || value === "settings";
6205
+ }
6206
+ var CONTENT_TYPES = {
6207
+ ".html": "text/html; charset=utf-8",
6208
+ ".md": "text/plain; charset=utf-8",
6209
+ ".json": "application/json; charset=utf-8"
6210
+ };
6211
+ function contentTypeFor(path) {
6212
+ return CONTENT_TYPES[extname(path).toLowerCase()] ?? "application/octet-stream";
6213
+ }
6214
+ function readBody(req, limitBytes) {
6215
+ return new Promise((resolvePromise, reject) => {
6216
+ const chunks = [];
6217
+ let size = 0;
6218
+ req.on("data", (chunk) => {
6219
+ size += chunk.length;
6220
+ if (size > limitBytes) {
6221
+ reject(new Error("payload too large"));
6222
+ return;
6223
+ }
6224
+ chunks.push(chunk);
6225
+ });
6226
+ req.on("end", () => resolvePromise(Buffer.concat(chunks).toString("utf8")));
6227
+ req.on("error", reject);
6228
+ });
6229
+ }
6230
+ function sendText(res, status, text2) {
6231
+ res.writeHead(status, { "content-type": "text/plain; charset=utf-8" });
6232
+ res.end(text2);
6233
+ }
6234
+ async function startApplyServer(opts) {
6235
+ const token = randomBytes(16).toString("hex");
6236
+ const idleMs = opts.idleMs ?? DEFAULT_IDLE_MS;
6237
+ const manifest = opts.manifest;
6238
+ let closedAlready = false;
6239
+ let resolveClosed;
6240
+ const closedPromise = new Promise((res) => {
6241
+ resolveClosed = res;
6242
+ });
6243
+ let idleTimer;
6244
+ function resetIdle() {
6245
+ clearTimeout(idleTimer);
6246
+ idleTimer = setTimeout(() => {
6247
+ void close();
6248
+ }, idleMs);
6249
+ idleTimer.unref();
6250
+ }
6251
+ async function close() {
6252
+ if (closedAlready) return;
6253
+ closedAlready = true;
6254
+ clearTimeout(idleTimer);
6255
+ await new Promise((res) => server.close(() => res()));
6256
+ resolveClosed();
6257
+ }
6258
+ async function handleIndex(req, res, search) {
6259
+ const msg = search.get("msg");
6260
+ const html = renderOptimizeIndex({
6261
+ version: opts.version,
6262
+ generatedAt: manifest.generatedAt,
6263
+ root: opts.root,
6264
+ rows: rowsFromManifest(manifest),
6265
+ serve: { token, ...msg ? { message: msg } : {} }
6266
+ });
6267
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
6268
+ res.end(html);
6269
+ }
6270
+ async function handleApply(req, res) {
6271
+ let body;
6272
+ try {
6273
+ body = await readBody(req, MAX_BODY_BYTES);
6274
+ } catch {
6275
+ sendText(res, 400, "Payload too large");
6276
+ return;
6277
+ }
6278
+ const form = parseForm(body);
6279
+ if (form["token"] !== token) {
6280
+ sendText(res, 403, "Forbidden");
6281
+ return;
6282
+ }
6283
+ const action = form["action"];
6284
+ if (!isApplyAction(action)) {
6285
+ sendText(res, 400, "Unknown action");
6286
+ return;
6287
+ }
6288
+ const entry = manifest.projects.find((p) => p.slug === form["slug"]);
6289
+ if (!entry) {
6290
+ sendText(res, 400, "Unknown project");
6291
+ return;
6292
+ }
6293
+ let msg;
6294
+ try {
6295
+ const lines = await opts.apply(entry, action);
6296
+ if (action === "remove") delete entry.appliedAt;
6297
+ else entry.appliedAt = (/* @__PURE__ */ new Date()).toISOString();
6298
+ if (opts.onManifestChange) await opts.onManifestChange(manifest);
6299
+ msg = lines[0] ?? "Done.";
6300
+ } catch (err) {
6301
+ msg = `Error: ${err instanceof Error ? err.message : String(err)}`;
6302
+ }
6303
+ res.writeHead(303, { Location: `/?msg=${encodeURIComponent(msg)}` });
6304
+ res.end();
6305
+ }
6306
+ async function handleDone(req, res) {
6307
+ let body;
6308
+ try {
6309
+ body = await readBody(req, MAX_BODY_BYTES);
6310
+ } catch {
6311
+ body = "";
6312
+ }
6313
+ const form = parseForm(body);
6314
+ if (form["token"] !== token) {
6315
+ sendText(res, 403, "Forbidden");
6316
+ return;
6317
+ }
6318
+ sendText(res, 200, "You can close this tab.");
6319
+ void close();
6320
+ }
6321
+ async function handleStatic(pathname, res) {
6322
+ const filePath = safeArtifactPath(opts.root, pathname);
6323
+ if (!filePath) {
6324
+ sendText(res, 404, "Not found");
6325
+ return;
6326
+ }
6327
+ try {
6328
+ const data = await readFile8(filePath);
6329
+ res.writeHead(200, { "content-type": contentTypeFor(filePath) });
6330
+ res.end(data);
6331
+ } catch {
6332
+ sendText(res, 404, "Not found");
6333
+ }
6334
+ }
6335
+ async function handle(req, res) {
6336
+ const url = new URL(req.url ?? "/", "http://127.0.0.1");
6337
+ const method = req.method ?? "GET";
6338
+ if (url.pathname === "/" && method === "GET") {
6339
+ await handleIndex(req, res, url.searchParams);
6340
+ return;
6341
+ }
6342
+ if (url.pathname === "/apply" && method === "POST") {
6343
+ await handleApply(req, res);
6344
+ return;
6345
+ }
6346
+ if (url.pathname === "/done" && method === "POST") {
6347
+ await handleDone(req, res);
6348
+ return;
6349
+ }
6350
+ if (method === "GET") {
6351
+ await handleStatic(url.pathname, res);
6352
+ return;
6353
+ }
6354
+ sendText(res, 404, "Not found");
6355
+ }
6356
+ const server = createServer((req, res) => {
6357
+ resetIdle();
6358
+ handle(req, res).catch((err) => {
6359
+ if (!res.headersSent) {
6360
+ res.writeHead(500, { "content-type": "text/plain; charset=utf-8" });
6361
+ }
6362
+ res.end(`Internal error: ${err instanceof Error ? err.message : String(err)}`);
6363
+ });
6364
+ });
6365
+ await new Promise((res, reject) => {
6366
+ server.once("error", reject);
6367
+ server.listen(0, "127.0.0.1", () => res());
6368
+ });
6369
+ resetIdle();
6370
+ const address = server.address();
6371
+ if (address === null || typeof address === "string") {
6372
+ throw new Error("failed to bind the loopback apply server");
6373
+ }
6374
+ return {
6375
+ url: `http://127.0.0.1:${address.port}`,
6376
+ port: address.port,
6377
+ close,
6378
+ closed: closedPromise
6379
+ };
6380
+ }
6381
+
6382
+ // src/optimize-manifest.ts
6383
+ import { mkdir as mkdir5, readFile as readFile9, writeFile as writeFile5 } from "fs/promises";
6384
+ import { join as join9, resolve as resolve4 } from "path";
6385
+ var MANIFEST_NAME = "index.json";
6386
+ function defaultOptimizeRoot(home) {
6387
+ return join9(home, ".costclaw", "optimize");
6388
+ }
6389
+ function isRecord(value) {
6390
+ return typeof value === "object" && value !== null && !Array.isArray(value);
6391
+ }
6392
+ async function readManifest(root) {
6393
+ let text2;
6394
+ try {
6395
+ text2 = await readFile9(join9(root, MANIFEST_NAME), "utf8");
6396
+ } catch {
6397
+ return null;
6398
+ }
6399
+ let parsed;
6400
+ try {
6401
+ parsed = JSON.parse(text2);
6402
+ } catch {
6403
+ return null;
6404
+ }
6405
+ if (!isRecord(parsed) || !Array.isArray(parsed["projects"])) return null;
6406
+ const projects = parsed["projects"].filter((p) => isRecord(p) && typeof p["projectDir"] === "string");
6407
+ return {
6408
+ generatedAt: typeof parsed["generatedAt"] === "string" ? parsed["generatedAt"] : "",
6409
+ root: typeof parsed["root"] === "string" ? parsed["root"] : root,
6410
+ projects
6411
+ };
6412
+ }
6413
+ async function writeManifest(root, m) {
6414
+ await mkdir5(root, { recursive: true });
6415
+ await writeFile5(join9(root, MANIFEST_NAME), JSON.stringify(m, null, 2) + "\n", "utf8");
6416
+ }
6417
+ function normalizePath(p) {
6418
+ const r = resolve4(p);
6419
+ return process.platform === "win32" ? r.toLowerCase() : r;
6420
+ }
6421
+ function findEntry(m, projectDir) {
6422
+ const want = normalizePath(projectDir);
6423
+ return m.projects.find((p) => normalizePath(p.projectDir) === want);
6424
+ }
6425
+ function fnv1a(text2) {
6426
+ let h = 2166136261;
6427
+ for (let i = 0; i < text2.length; i++) {
6428
+ h ^= text2.charCodeAt(i);
6429
+ h = Math.imul(h, 16777619) >>> 0;
6430
+ }
6431
+ return h.toString(16).padStart(8, "0");
6432
+ }
6433
+ function safeDirName(slug) {
6434
+ const cleaned = slug.replace(/[^A-Za-z0-9._-]+/g, "-").replace(/^[-.]+|[-.]+$/g, "");
6435
+ return cleaned.length > 0 ? cleaned : "project";
6436
+ }
6437
+ function artifactDirName(slug, projectDir, taken) {
6438
+ const base = safeDirName(slug);
6439
+ if (!taken.has(base)) return base;
6440
+ return `${base}-${fnv1a(normalizePath(projectDir))}`;
6441
+ }
6442
+
5126
6443
  // src/optimize-command.ts
5127
6444
  var OPTIMIZED_NAME2 = "CLAUDE.optimized.md";
5128
6445
  var PLAYBOOK_NAME2 = "PLAYBOOK.md";
5129
6446
  var SETTINGS_NAME2 = "settings.suggested.json";
5130
6447
  var HARNESS_NAME2 = "HARNESS-UPGRADE.md";
5131
- var DASHBOARD_NAME = "DASHBOARD.html";
6448
+ var DASHBOARD_NAME2 = "DASHBOARD.html";
6449
+ var UPGRADE_ALL_NAME = "UPGRADE-ALL.md";
6450
+ var INCLUDE_NAME2 = "costclaw.md";
6451
+ var DEFAULT_LIMIT = 10;
5132
6452
  function usd6(n) {
5133
6453
  return `$${(Math.round(n * 100) / 100).toFixed(2)}`;
5134
6454
  }
6455
+ function num6(n) {
6456
+ return String(Math.round(n)).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
6457
+ }
5135
6458
  function describeDetection(project) {
5136
6459
  const name = project.name?.trim() || "unnamed project";
5137
6460
  const n = project.commands.length;
@@ -5146,276 +6469,373 @@ function unscannedWarning(projectDir) {
5146
6469
  return [
5147
6470
  `Warning: the scan found no stack and no commands in ${projectDir}.`,
5148
6471
  "Are you in the right folder? optimize fills the scaffold from a project's own files,",
5149
- "so run it from inside a project, or point it at one with --project <dir>."
6472
+ "so point it at a project with --project <dir>."
5150
6473
  ];
5151
6474
  }
5152
- async function pathExists(p) {
6475
+ async function pathExists2(p) {
5153
6476
  try {
5154
- await stat2(p);
6477
+ await stat3(p);
5155
6478
  return true;
5156
6479
  } catch {
5157
6480
  return false;
5158
6481
  }
5159
6482
  }
5160
- function lineDiff(oldText, newText) {
5161
- const oldLines = oldText.split(/\r?\n/);
5162
- const newLines = newText.split(/\r?\n/);
5163
- const oldSet = new Set(oldLines);
5164
- const newSet = new Set(newLines);
5165
- const lines = [];
5166
- for (const line of oldLines) {
5167
- if (!newSet.has(line)) lines.push(`- ${line}`);
5168
- }
5169
- for (const line of newLines) {
5170
- if (!oldSet.has(line)) lines.push(`+ ${line}`);
5171
- }
5172
- if (lines.length === 0) lines.push(" (no line-level changes)");
5173
- return lines.join("\n");
6483
+ function projectSpend(report, slug) {
6484
+ const p = report.projects.find((x) => x.slug === slug);
6485
+ return p ? p.cost_usd : null;
5174
6486
  }
5175
- function asStringArray(value) {
5176
- return Array.isArray(value) ? value.filter((v) => typeof v === "string") : [];
6487
+ function projectRecoverable(report, slug) {
6488
+ const row = cacheMissByProject(report).find((r) => r.slug === slug);
6489
+ return row ? row.usd : null;
5177
6490
  }
5178
- function unionStrings(existing, additions) {
5179
- const out = [];
5180
- const seen = /* @__PURE__ */ new Set();
5181
- for (const v of existing) {
5182
- if (!seen.has(v)) {
5183
- seen.add(v);
5184
- out.push(v);
6491
+ async function generateForProject(ctx, projectDir, artifactsDir) {
6492
+ const slug = basename2(resolve5(projectDir));
6493
+ let currentClaudeMd = ctx.claudeMdOverride;
6494
+ let claudeMdSource = ctx.claudeMdOverride !== void 0 ? ctx.claudeMdFallbackSource : null;
6495
+ if (currentClaudeMd === void 0) {
6496
+ const own = join10(projectDir, "CLAUDE.md");
6497
+ if (await pathExists2(own)) {
6498
+ currentClaudeMd = await readFile10(own, "utf8");
6499
+ claudeMdSource = own;
5185
6500
  }
5186
6501
  }
5187
- for (const v of additions) {
5188
- if (!seen.has(v)) {
5189
- seen.add(v);
5190
- out.push(v);
6502
+ const project = await scanProject(projectDir);
6503
+ const result = optimize({
6504
+ report: ctx.report,
6505
+ scores: ctx.pillars,
6506
+ fixes: ctx.fixes,
6507
+ currentClaudeMd,
6508
+ project
6509
+ });
6510
+ await mkdir6(artifactsDir, { recursive: true });
6511
+ await writeFile6(join10(artifactsDir, OPTIMIZED_NAME2), result.optimizedClaudeMd, "utf8");
6512
+ await writeFile6(join10(artifactsDir, PLAYBOOK_NAME2), result.playbook, "utf8");
6513
+ await writeFile6(join10(artifactsDir, SETTINGS_NAME2), result.settingsJson, "utf8");
6514
+ await writeFile6(join10(artifactsDir, HARNESS_NAME2), result.harnessPrompt, "utf8");
6515
+ await writeFile6(join10(artifactsDir, INCLUDE_NAME2), result.includeMd, "utf8");
6516
+ const review = reviewProjectClaudeMd({
6517
+ text: currentClaudeMd ?? null,
6518
+ report: ctx.report,
6519
+ includeSections: result.includeSections,
6520
+ includeMd: result.includeMd,
6521
+ globalSections: ctx.globalSections,
6522
+ label: claudeMdSource ?? join10(projectDir, "CLAUDE.md")
6523
+ });
6524
+ const spend = projectSpend(ctx.report, slug);
6525
+ const recoverable = projectRecoverable(ctx.report, slug);
6526
+ const applyCommand = `costclaw apply ${projectDir}`;
6527
+ if (ctx.dashboard) {
6528
+ const auditSpend = ctx.report.summary.cost_usd;
6529
+ const auditRecoverable2 = cacheMissExposureUsd(ctx.report);
6530
+ const html = renderOptimizeDashboard({
6531
+ version: ctx.version,
6532
+ projectName: project.name ?? slug,
6533
+ stack: project.stack,
6534
+ commandsCount: project.commands.length,
6535
+ artifactsDir,
6536
+ currentClaudeMd: currentClaudeMd ?? null,
6537
+ optimizedClaudeMd: result.optimizedClaudeMd,
6538
+ claudeMdTokens: result.claudeMdTokens,
6539
+ carriedTokens: result.carriedTokens,
6540
+ sectionDispositions: result.sectionDispositions,
6541
+ placeholdersRemaining: result.placeholdersRemaining,
6542
+ fixes: ctx.fixes,
6543
+ report: ctx.report,
6544
+ headlineWasteShare: auditSpend > 0 ? auditRecoverable2 / auditSpend : 0,
6545
+ headlineWasteUsd: auditRecoverable2,
6546
+ applyCommand,
6547
+ review
6548
+ });
6549
+ await writeFile6(join10(artifactsDir, DASHBOARD_NAME2), html, "utf8");
6550
+ }
6551
+ const lines = ctx.lines;
6552
+ lines.push(slug);
6553
+ if (looksUnscanned(project)) lines.push(...unscannedWarning(projectDir));
6554
+ lines.push(describeDetection(project));
6555
+ if (claudeMdSource) lines.push(`Existing CLAUDE.md: ${claudeMdSource}`);
6556
+ const auditRecoverable = cacheMissExposureUsd(ctx.report);
6557
+ const shownRecoverable = recoverable ?? auditRecoverable;
6558
+ const denominator = recoverable !== null ? spend ?? 0 : ctx.report.summary.cost_usd;
6559
+ const scopeLabel = recoverable !== null ? `for ${slug}` : "across your audited projects";
6560
+ if (ctx.plan === "api") {
6561
+ lines.push(`Recoverable spend (cache-miss exposure) ${scopeLabel}: ${usd6(shownRecoverable)}`);
6562
+ } else {
6563
+ const share = denominator > 0 ? shownRecoverable / denominator * 100 : 0;
6564
+ lines.push(
6565
+ `Recoverable usage (cache-miss exposure) ${scopeLabel}: ${share.toFixed(1)}% of analyzed usage (${usd6(shownRecoverable)} at API rates)`
6566
+ );
6567
+ }
6568
+ const { before, after } = result.claudeMdTokens;
6569
+ if (before != null && before !== after) {
6570
+ const pct2 = before > 0 ? (Math.abs(after - before) / before * 100).toFixed(1) : "0.0";
6571
+ const dir = after > before ? "larger" : "smaller";
6572
+ lines.push(
6573
+ `Your CLAUDE.md: an estimated ${num6(before)} tokens to ${num6(after)} (${pct2}% ${dir}), paid on every turn.`
6574
+ );
6575
+ if (result.carriedTokens >= after / 2) {
6576
+ lines.push(
6577
+ `About ${num6(result.carriedTokens)} of those tokens are your own prose, carried through as written.`,
6578
+ "costclaw does not rewrite prose, so trimming it is judgment work: HARNESS-UPGRADE.md",
6579
+ "ranks your heaviest sections and flags the dated lines to move into docs/."
6580
+ );
5191
6581
  }
5192
6582
  }
5193
- return out;
5194
- }
5195
- function isPlainObject(value) {
5196
- return typeof value === "object" && value !== null && !Array.isArray(value);
5197
- }
5198
- async function applyDerivedSettings(target, suggestedJson, force) {
5199
- const backup = `${target}.bak`;
5200
- if (await pathExists(backup) && !force) {
5201
- throw new Error(
5202
- `A backup already exists at ${backup}. Refusing to overwrite it. Pass --force to replace the existing backup.`
6583
+ if (result.placeholdersRemaining > 0) {
6584
+ const n = result.placeholdersRemaining;
6585
+ lines.push(
6586
+ `${n} section${n === 1 ? "" : "s"} left as placeholder${n === 1 ? "" : "s"} (no evidence to fill ${n === 1 ? "it" : "them"}); search the scaffold for <!-- ... -->.`
5203
6587
  );
5204
6588
  }
5205
- let existingText = "";
5206
- let existing = {};
5207
- if (await pathExists(target)) {
5208
- existingText = await readFile6(target, "utf8");
5209
- if (existingText.trim() !== "") {
5210
- let parsed;
5211
- try {
5212
- parsed = JSON.parse(existingText);
5213
- } catch {
5214
- throw new Error(
5215
- `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.`
5216
- );
5217
- }
5218
- if (!isPlainObject(parsed)) {
5219
- throw new Error(
5220
- `Expected ${target} to hold a JSON object, so it was left untouched. --apply-settings only merges into an object settings file.`
5221
- );
5222
- }
5223
- existing = parsed;
5224
- }
6589
+ for (const note of result.notes) lines.push(` - ${note}`);
6590
+ if (review.changes.length > 0) {
6591
+ const n = review.changes.length;
6592
+ lines.push(`Review: ${num6(n)} proposed ${n === 1 ? "change" : "changes"} to ${review.label}`);
5225
6593
  }
5226
- const suggested = JSON.parse(suggestedJson);
5227
- const suggestedAllow = asStringArray(suggested.permissions?.allow);
5228
- const suggestedDeny = asStringArray(suggested.permissions?.deny);
5229
- const existingPerms = isPlainObject(existing.permissions) ? existing.permissions : {};
5230
- const mergedPerms = { ...existingPerms };
5231
- mergedPerms.allow = unionStrings(asStringArray(existingPerms.allow), suggestedAllow);
5232
- mergedPerms.deny = unionStrings(asStringArray(existingPerms.deny), suggestedDeny);
5233
- const merged = { ...existing, permissions: mergedPerms };
5234
- const mergedText = JSON.stringify(merged, null, 2) + "\n";
5235
- await mkdir4(dirname(target), { recursive: true });
5236
- await writeFile4(backup, existingText, "utf8");
5237
- await writeFile4(target, mergedText, "utf8");
5238
- return [
5239
- `Merged the derived permission allowlist into ${target}`,
5240
- `Backed up the previous file to ${backup}`,
5241
- "Only permissions.allow and permissions.deny changed (deduped union, existing entries kept and ordered first). Every other key was left as it was.",
5242
- "",
5243
- "Diff (previous vs merged):",
5244
- lineDiff(existingText, mergedText)
5245
- ];
6594
+ lines.push(`Artifacts: ${artifactsDir}`);
6595
+ lines.push(`Apply: ${applyCommand}`);
6596
+ lines.push("");
6597
+ return {
6598
+ entry: {
6599
+ slug,
6600
+ dir: basename2(artifactsDir),
6601
+ projectDir,
6602
+ artifactsDir,
6603
+ spendUsd: spend ?? 0,
6604
+ recoverableUsd: recoverable ?? 0,
6605
+ tokens: result.claudeMdTokens,
6606
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString()
6607
+ },
6608
+ review,
6609
+ sections: (currentClaudeMd ? parseSections(currentClaudeMd) : []).map((sec) => ({
6610
+ label: `${slug}/CLAUDE.md`,
6611
+ heading: sec.heading,
6612
+ body: sec.body
6613
+ }))
6614
+ };
5246
6615
  }
5247
6616
  async function runOptimize(opts) {
5248
- const projectDir = opts.projectDir || process.cwd();
5249
- let claudeMdPath = opts.claudeMdPath;
5250
- if (!claudeMdPath) {
5251
- const projectClaudeMd = join7(projectDir, "CLAUDE.md");
5252
- if (await pathExists(projectClaudeMd)) claudeMdPath = projectClaudeMd;
6617
+ const home = opts.home ?? homedir5();
6618
+ let inputsClaudeMdPath = opts.claudeMdPath;
6619
+ if (!inputsClaudeMdPath && opts.projectDir) {
6620
+ const own = join10(opts.projectDir, "CLAUDE.md");
6621
+ if (await pathExists2(own)) inputsClaudeMdPath = own;
5253
6622
  }
5254
- const { logs, claudeMd, claudeMdSource } = await loadAuditInputs({ path: opts.path, claudeMdPath });
6623
+ const { logs, claudeMd, claudeMdSource, projectDirs } = await loadAuditInputs({
6624
+ path: opts.path,
6625
+ claudeMdPath: inputsClaudeMdPath,
6626
+ home: opts.home
6627
+ });
5255
6628
  const report = analyzeUploads(logs);
5256
6629
  const cmd2 = analyzeClaudeMd(claudeMd);
5257
6630
  const { pillars } = scorePillars(report, cmd2, {});
5258
- const configDir = join7(opts.home ?? homedir5(), ".costclaw");
6631
+ const configDir = join10(home, ".costclaw");
5259
6632
  const { plan } = await resolvePlan(configDir, opts.plan);
5260
6633
  const { fixes } = synthesize(report, pillars, cmd2, plan);
5261
- const project = await scanProject(projectDir);
5262
- const result = optimize({ report, scores: pillars, fixes, currentClaudeMd: claudeMd, project });
5263
- const recoverable = cacheMissExposureUsd(report);
6634
+ const auditRecoverable = cacheMissExposureUsd(report);
5264
6635
  const baselineSpend = report.summary.cost_usd;
5265
6636
  await saveCliConfig(configDir, {
5266
6637
  lastOptimize: {
5267
6638
  at: (/* @__PURE__ */ new Date()).toISOString(),
5268
6639
  totals: { ...report.summary.totals },
5269
6640
  cacheHitRate: report.summary.cacheHitRate,
5270
- headlineWasteShare: baselineSpend > 0 ? recoverable / baselineSpend : 0,
6641
+ headlineWasteShare: baselineSpend > 0 ? auditRecoverable / baselineSpend : 0,
5271
6642
  spendUsd: baselineSpend
5272
6643
  }
5273
6644
  });
5274
- const outDir = opts.out || join7(process.cwd(), "costclaw-out");
5275
- await mkdir4(outDir, { recursive: true });
5276
- const playbookPath = join7(outDir, PLAYBOOK_NAME2);
5277
- await writeFile4(playbookPath, result.playbook, "utf8");
5278
- const settingsPath = join7(outDir, SETTINGS_NAME2);
5279
- await writeFile4(settingsPath, result.settingsJson, "utf8");
5280
- const harnessPath = join7(outDir, HARNESS_NAME2);
5281
- await writeFile4(harnessPath, result.harnessPrompt, "utf8");
5282
- const wantDashboard = opts.dashboard !== false;
5283
- let dashboardPath = null;
5284
- if (wantDashboard) {
5285
- const spend = report.summary.cost_usd;
5286
- const html = renderOptimizeDashboard({
5287
- version: opts.version ?? "",
5288
- projectName: project.name ?? "your project",
5289
- stack: project.stack,
5290
- commandsCount: project.commands.length,
5291
- artifactsDir: outDir,
5292
- currentClaudeMd: claudeMd ?? null,
5293
- optimizedClaudeMd: result.optimizedClaudeMd,
5294
- claudeMdTokens: result.claudeMdTokens,
5295
- carriedTokens: result.carriedTokens,
5296
- sectionDispositions: result.sectionDispositions,
5297
- placeholdersRemaining: result.placeholdersRemaining,
5298
- fixes,
5299
- report,
5300
- headlineWasteShare: spend > 0 ? recoverable / spend : 0,
5301
- headlineWasteUsd: recoverable
6645
+ const single = opts.projectDir !== void 0;
6646
+ const manifestRoot = single ? defaultOptimizeRoot(home) : opts.out ?? defaultOptimizeRoot(home);
6647
+ const targets = [];
6648
+ let skippedMissing = 0;
6649
+ let overLimit = 0;
6650
+ const limit = opts.limit && opts.limit > 0 ? opts.limit : DEFAULT_LIMIT;
6651
+ if (opts.projectDir !== void 0) {
6652
+ targets.push({
6653
+ projectDir: opts.projectDir,
6654
+ artifactsDir: opts.out ?? join10(opts.projectDir, "costclaw-out")
5302
6655
  });
5303
- dashboardPath = join7(outDir, DASHBOARD_NAME);
5304
- await writeFile4(dashboardPath, html, "utf8");
5305
- }
5306
- const lines = [];
5307
- lines.push("CostClaw optimize");
5308
- lines.push("");
5309
- if (looksUnscanned(project)) {
5310
- lines.push(...unscannedWarning(projectDir));
5311
- lines.push("");
5312
- }
5313
- if (opts.write) {
5314
- const target = opts.write;
5315
- const backup = `${target}.bak`;
5316
- if (await pathExists(backup) && !opts.force) {
5317
- throw new Error(
5318
- `A backup already exists at ${backup}. Refusing to overwrite it. Pass --force to replace the existing backup.`
5319
- );
5320
- }
5321
- let original = "";
5322
- if (await pathExists(target)) {
5323
- original = await readFile6(target, "utf8");
5324
- }
5325
- await writeFile4(backup, original, "utf8");
5326
- await writeFile4(target, result.optimizedClaudeMd, "utf8");
5327
- lines.push(`Backed up the original to ${backup}`);
5328
- lines.push(`Wrote the optimized CLAUDE.md to ${target}`);
5329
- lines.push(`Wrote the playbook to ${playbookPath}`);
5330
- lines.push(`Wrote a suggested settings.json to ${settingsPath}`);
5331
- lines.push(`Wrote the Claude Code work order to ${harnessPath}`);
5332
- lines.push("");
5333
- lines.push("Diff (old vs new):");
5334
- lines.push(lineDiff(original, result.optimizedClaudeMd));
5335
- lines.push("");
5336
- if (result.placeholdersRemaining > 0) {
5337
- lines.push("Warning: this scaffold has placeholders to fill in. Search it for <!-- ... --> and replace each with your project's real details.");
5338
- }
5339
- lines.push("A suggested settings.json was written to the out dir for review; it is not applied in place.");
5340
6656
  } else {
5341
- const optimizedPath = join7(outDir, OPTIMIZED_NAME2);
5342
- await writeFile4(optimizedPath, result.optimizedClaudeMd, "utf8");
5343
- lines.push("Dry run (no files of yours were changed).");
5344
- lines.push(`Wrote the optimized CLAUDE.md scaffold to ${optimizedPath}`);
5345
- lines.push(`Wrote the playbook to ${playbookPath}`);
5346
- lines.push(`Wrote a suggested settings.json to ${settingsPath}`);
5347
- lines.push(`Wrote the Claude Code work order to ${harnessPath}`);
5348
- lines.push("");
5349
- lines.push(describeDetection(project));
5350
- if (claudeMdSource) lines.push(`Existing CLAUDE.md: ${claudeMdSource}`);
5351
- if (plan === "api") {
5352
- lines.push(`Recoverable spend (cache-miss exposure): ${usd6(recoverable)}`);
5353
- } else {
5354
- const spend = report.summary.cost_usd;
5355
- const share = spend > 0 ? recoverable / spend * 100 : 0;
5356
- lines.push(
5357
- `Recoverable usage (cache-miss exposure): ${share.toFixed(1)}% of analyzed usage (${usd6(recoverable)} at API rates)`
5358
- );
5359
- }
5360
- const { before, after } = result.claudeMdTokens;
5361
- if (before != null && before !== after) {
5362
- const pct2 = before > 0 ? (Math.abs(after - before) / before * 100).toFixed(1) : "0.0";
5363
- const dir = after > before ? "larger" : "smaller";
5364
- const g = (n) => String(Math.round(n)).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
5365
- lines.push(
5366
- `Your CLAUDE.md: an estimated ${g(before)} tokens to ${g(after)} (${pct2}% ${dir}), paid on every turn.`
5367
- );
5368
- if (result.carriedTokens >= after / 2) {
5369
- lines.push(
5370
- `About ${g(result.carriedTokens)} of those tokens are your own prose, carried through as written.`,
5371
- "costclaw does not rewrite prose, so trimming it is judgment work: HARNESS-UPGRADE.md",
5372
- "ranks your heaviest sections and flags the dated lines to move into docs/."
5373
- );
6657
+ const ranked = [...report.projects].sort((a, b) => b.cost_usd - a.cost_usd);
6658
+ const taken = /* @__PURE__ */ new Set();
6659
+ for (const p of ranked) {
6660
+ const dir = projectDirs.get(p.slug);
6661
+ if (!dir || !await pathExists2(dir)) {
6662
+ skippedMissing++;
6663
+ continue;
6664
+ }
6665
+ if (targets.length >= limit) {
6666
+ overLimit++;
6667
+ continue;
5374
6668
  }
6669
+ const name = artifactDirName(p.slug, dir, taken);
6670
+ taken.add(name);
6671
+ targets.push({ projectDir: dir, artifactsDir: join10(manifestRoot, name) });
5375
6672
  }
5376
- lines.push("");
5377
- if (result.placeholdersRemaining > 0) {
5378
- const n = result.placeholdersRemaining;
5379
- lines.push(`The optimized CLAUDE.md has ${n} section${n === 1 ? "" : "s"} left as placeholders (no evidence to fill them).`);
5380
- lines.push("Search it for <!-- ... --> and replace each with your project's real details.");
5381
- } else {
5382
- lines.push("Every section was filled from your project and your existing CLAUDE.md; nothing is left as a placeholder.");
5383
- lines.push("Review it (the notes below say what changed), then apply it.");
6673
+ }
6674
+ const lines = ["CostClaw optimize", ""];
6675
+ if (!single) {
6676
+ lines.push(
6677
+ `Generated for ${targets.length} ${targets.length === 1 ? "project" : "projects"} from your audit, ranked by spend.`,
6678
+ "Nothing was written inside any project: that only happens on costclaw apply.",
6679
+ ""
6680
+ );
6681
+ } else {
6682
+ lines.push("Generated (nothing of yours was changed).", "");
6683
+ }
6684
+ const globalClaudeMd = opts.claudeMdPath ? void 0 : claudeMd;
6685
+ const globalPath = opts.claudeMdPath ? null : claudeMdSource;
6686
+ const { imports, notes: importNotes } = await resolveClaudeMdImports(globalPath, globalClaudeMd, home);
6687
+ const globalSections = globalClaudeMd ? parseSections(globalClaudeMd).map((sec) => ({ heading: sec.heading, body: sec.body })) : [];
6688
+ const ctx = {
6689
+ report,
6690
+ pillars,
6691
+ fixes,
6692
+ plan,
6693
+ globalClaudeMd,
6694
+ claudeMdOverride: opts.claudeMdPath ? claudeMd : void 0,
6695
+ claudeMdFallbackSource: claudeMdSource,
6696
+ version: opts.version ?? "",
6697
+ dashboard: opts.dashboard !== false,
6698
+ globalSections,
6699
+ lines
6700
+ };
6701
+ const outcomes = [];
6702
+ for (const t of targets) {
6703
+ outcomes.push(await generateForProject(ctx, t.projectDir, t.artifactsDir));
6704
+ }
6705
+ const entries = outcomes.map((o) => o.entry);
6706
+ const previous = await readManifest(manifestRoot);
6707
+ const merged = entries.map((e) => {
6708
+ const old = previous ? findEntry(previous, e.projectDir) : void 0;
6709
+ return old?.appliedAt ? { ...e, appliedAt: old.appliedAt } : e;
6710
+ });
6711
+ if (single && previous) {
6712
+ const sofar = { generatedAt: "", root: manifestRoot, projects: merged };
6713
+ for (const old of previous.projects) {
6714
+ if (!findEntry(sofar, old.projectDir)) merged.push(old);
5384
6715
  }
5385
- lines.push("To apply it in place (with a backup and a diff first), rerun with --write <your-CLAUDE.md>.");
5386
- 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.");
5387
- 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.");
5388
- lines.push("");
5389
- lines.push("To apply everything with AI judgment, hand the work order to your own Claude Code:");
5390
- lines.push(' claude "Follow costclaw-out/HARNESS-UPGRADE.md"');
5391
- 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.");
5392
6716
  }
5393
- if (opts.applySettings) {
5394
- const target = opts.applySettingsPath || join7(projectDir, ".claude", "settings.json");
5395
- const applyLines = await applyDerivedSettings(target, result.settingsJson, opts.force ?? false);
5396
- lines.push("");
5397
- lines.push(...applyLines);
6717
+ const manifest = {
6718
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
6719
+ root: manifestRoot,
6720
+ projects: merged
6721
+ };
6722
+ await writeManifest(manifestRoot, manifest);
6723
+ const globalLabel = globalPath ?? join10(home, ".claude", "CLAUDE.md");
6724
+ const globalReview = reviewGlobalClaudeMd({
6725
+ text: globalClaudeMd ?? null,
6726
+ imports,
6727
+ report,
6728
+ projectSections: outcomes.flatMap((o) => o.sections),
6729
+ projectSlugs: report.projects.map((p) => p.slug),
6730
+ label: globalLabel
6731
+ });
6732
+ const reviewsBySlug = new Map(outcomes.map((o) => [o.entry.slug, o.review]));
6733
+ const upgradeAll = buildUpgradeAll({
6734
+ generatedAt: manifest.generatedAt,
6735
+ global: { ...globalReview, path: globalLabel },
6736
+ projects: outcomes.map((o) => ({
6737
+ slug: o.entry.slug,
6738
+ projectDir: o.entry.projectDir,
6739
+ review: o.review,
6740
+ applyCommand: `npx costclaw apply ${o.entry.projectDir}`
6741
+ }))
6742
+ });
6743
+ const upgradeRoot = single ? targets[0]?.artifactsDir ?? manifestRoot : manifestRoot;
6744
+ const upgradeAllPath = join10(upgradeRoot, UPGRADE_ALL_NAME);
6745
+ await mkdir6(upgradeRoot, { recursive: true });
6746
+ await writeFile6(upgradeAllPath, upgradeAll, "utf8");
6747
+ let indexHtmlPath = null;
6748
+ if (!single && ctx.dashboard) {
6749
+ const rows = merged.map((e) => ({
6750
+ slug: e.slug,
6751
+ projectDir: e.projectDir,
6752
+ artifactsHref: `${e.dir}/${DASHBOARD_NAME2}`,
6753
+ spendUsd: e.spendUsd,
6754
+ recoverableUsd: e.recoverableUsd,
6755
+ tokens: e.tokens,
6756
+ ...e.appliedAt ? { appliedAt: e.appliedAt } : {},
6757
+ applyCommand: `costclaw apply ${e.projectDir}`
6758
+ }));
6759
+ const html = renderOptimizeIndex({
6760
+ version: ctx.version,
6761
+ generatedAt: manifest.generatedAt,
6762
+ root: manifestRoot,
6763
+ rows,
6764
+ review: { global: globalReview, projects: reviewsBySlug, upgradeAll, upgradeAllPath }
6765
+ });
6766
+ indexHtmlPath = join10(manifestRoot, DASHBOARD_NAME2);
6767
+ await writeFile6(indexHtmlPath, html, "utf8");
5398
6768
  }
5399
- if (result.notes.length > 0) {
5400
- lines.push("");
5401
- lines.push("Notes:");
5402
- for (const note of result.notes) lines.push(` - ${note}`);
6769
+ if (!single) {
6770
+ lines.push(
6771
+ `${entries.length} ${entries.length === 1 ? "project" : "projects"} generated, ${skippedMissing} skipped (folder not found).`
6772
+ );
6773
+ if (overLimit > 0) {
6774
+ lines.push(`${overLimit} more were left out by the limit of ${limit}; pass --limit N to include more.`);
6775
+ }
5403
6776
  }
6777
+ lines.push(
6778
+ `The ${SETTINGS_NAME2} in each artifacts folder is a conservative permission allowlist derived from what you already run.`,
6779
+ "Review it, then merge it with costclaw apply <project-dir> --apply-settings. It is never applied unless you ask."
6780
+ );
6781
+ const top = entries[0];
6782
+ const projectChanges = outcomes.reduce((sum, o) => sum + o.review.changes.length, 0);
6783
+ lines.push("");
6784
+ lines.push(
6785
+ `Your CLAUDE.md review: ${num6(globalReview.changes.length)} ${globalReview.changes.length === 1 ? "change" : "changes"} to ${globalLabel}, ${num6(projectChanges)} across your ${outcomes.length === 1 ? "project" : "projects"}.`
6786
+ );
6787
+ lines.push("One prompt applies all of it. Hand this to your own Claude Code:");
6788
+ lines.push(` claude "Follow ${upgradeAllPath}"`);
6789
+ lines.push(
6790
+ `It slims each CLAUDE.md, moves the dated lines out, applies the permissions you approve, and fixes the audit's harness-level findings. Per-project detail stays in each ${HARNESS_NAME2}. costclaw itself never calls a model.`
6791
+ );
6792
+ for (const note of importNotes) lines.push(` - ${note}`);
5404
6793
  lines.push("");
6794
+ lines.push(`Manifest: ${join10(manifestRoot, "index.json")}`);
5405
6795
  lines.push("Baseline recorded: your next audits will show cache-hit progress since this optimize.");
5406
6796
  lines.push("Nothing left your machine.");
5407
- if (dashboardPath) {
6797
+ const openPath = indexHtmlPath ?? (ctx.dashboard && top ? join10(top.artifactsDir, DASHBOARD_NAME2) : null);
6798
+ if (openPath) {
5408
6799
  lines.push("");
5409
- lines.push(`Opening the summary dashboard: ${dashboardPath}`);
5410
- 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.");
5411
- openInBrowser(dashboardPath);
6800
+ const canServe = opts.serve !== false && !process.env["VITEST"] && !process.env["CI"] && !process.env["COSTCLAW_NO_OPEN"] && manifest.projects.length > 0;
6801
+ if (!canServe) {
6802
+ lines.push(`Opening the summary dashboard: ${openPath}`);
6803
+ lines.push(
6804
+ 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."
6805
+ );
6806
+ } else {
6807
+ lines.push(`Summary dashboard saved to: ${openPath}`);
6808
+ }
6809
+ if (canServe) {
6810
+ const srv = await startApplyServer({
6811
+ root: manifestRoot,
6812
+ manifest,
6813
+ version: ctx.version,
6814
+ apply: async (entry, action) => {
6815
+ const outcome = await runApply({
6816
+ projectDir: entry.projectDir,
6817
+ mode: action === "remove" ? "remove" : "include",
6818
+ artifactsDir: entry.artifactsDir,
6819
+ applySettings: action === "settings"
6820
+ });
6821
+ return outcome.lines;
6822
+ },
6823
+ onManifestChange: (m) => writeManifest(manifestRoot, m)
6824
+ });
6825
+ lines.push(
6826
+ `Apply page: ${srv.url} (Apply/Remove buttons; press Ctrl+C or click Done when finished; closes after 30 idle minutes)`
6827
+ );
6828
+ openInBrowser(srv.url);
6829
+ } else {
6830
+ openInBrowser(openPath);
6831
+ }
5412
6832
  }
5413
- return { output: lines.join("\n") };
6833
+ return { output: lines.join("\n"), root: manifestRoot, manifest, indexHtmlPath, upgradeAllPath };
5414
6834
  }
5415
6835
 
5416
6836
  // src/badge-command.ts
5417
- import { writeFile as writeFile5 } from "fs/promises";
5418
- import { resolve as resolve2 } from "path";
6837
+ import { writeFile as writeFile7 } from "fs/promises";
6838
+ import { resolve as resolve6 } from "path";
5419
6839
 
5420
6840
  // src/badge.ts
5421
6841
  var HEIGHT2 = 20;
@@ -5439,14 +6859,14 @@ var DEFAULT_BADGE_FILE = "costclaw-badge.svg";
5439
6859
  async function runBadge(opts) {
5440
6860
  const { record } = await runAudit({ path: opts.path, claudeMdPath: opts.claudeMdPath, home: opts.home });
5441
6861
  const svg = renderBadge(record);
5442
- const target = resolve2(opts.out || DEFAULT_BADGE_FILE);
5443
- await writeFile5(target, svg, "utf8");
6862
+ const target = resolve6(opts.out || DEFAULT_BADGE_FILE);
6863
+ await writeFile7(target, svg, "utf8");
5444
6864
  return { output: `Badge written to ${target}`, record, target };
5445
6865
  }
5446
6866
 
5447
6867
  // src/diff-command.ts
5448
- import { readdir as readdir4, readFile as readFile7 } from "fs/promises";
5449
- import { join as join8 } from "path";
6868
+ import { readdir as readdir4, readFile as readFile11 } from "fs/promises";
6869
+ import { join as join11 } from "path";
5450
6870
  import { homedir as homedir6 } from "os";
5451
6871
 
5452
6872
  // src/format-diff.ts
@@ -5535,7 +6955,7 @@ function formatDiff(d) {
5535
6955
  async function readRecord(path) {
5536
6956
  let text2;
5537
6957
  try {
5538
- text2 = await readFile7(path, "utf8");
6958
+ text2 = await readFile11(path, "utf8");
5539
6959
  } catch {
5540
6960
  throw new Error(`Could not read ${path}.`);
5541
6961
  }
@@ -5551,7 +6971,7 @@ async function runDiff(opts) {
5551
6971
  let pathA = opts.fileA;
5552
6972
  let pathB = opts.fileB;
5553
6973
  if (!pathA || !pathB) {
5554
- const dir = join8(opts.home ?? homedir6(), ".costclaw", "history");
6974
+ const dir = join11(opts.home ?? homedir6(), ".costclaw", "history");
5555
6975
  let files = [];
5556
6976
  try {
5557
6977
  files = (await readdir4(dir)).filter((f) => f.endsWith(".json")).sort();
@@ -5562,8 +6982,8 @@ async function runDiff(opts) {
5562
6982
  "Need two audits to diff. Run costclaw audit now and again after you have made changes; each run saves a snapshot."
5563
6983
  );
5564
6984
  }
5565
- pathA = join8(dir, files[files.length - 2]);
5566
- pathB = join8(dir, files[files.length - 1]);
6985
+ pathA = join11(dir, files[files.length - 2]);
6986
+ pathB = join11(dir, files[files.length - 1]);
5567
6987
  }
5568
6988
  const diff = diffAudits(await readRecord(pathA), await readRecord(pathB));
5569
6989
  const output = opts.json ? JSON.stringify(diff, null, 2) : formatDiff(diff);
@@ -5616,8 +7036,24 @@ function parseBadgeFlags(args) {
5616
7036
  out: getFlag(args, "--out")
5617
7037
  };
5618
7038
  }
7039
+ function parseApplyFlags(args) {
7040
+ const from = getFlag(args, "--from");
7041
+ const applySettings = args.includes("--apply-settings");
7042
+ const applySettingsPath = applySettings ? optionalPathAfter(args, "--apply-settings") : void 0;
7043
+ const consumed = new Set([from, applySettingsPath].filter((v) => v !== void 0));
7044
+ const positional = args.find((a) => !a.startsWith("-") && !consumed.has(a));
7045
+ const mode = args.includes("--remove") ? "remove" : args.includes("--replace") ? "replace" : "include";
7046
+ return {
7047
+ projectDir: positional ?? process.cwd(),
7048
+ mode,
7049
+ from,
7050
+ applySettings,
7051
+ applySettingsPath,
7052
+ force: args.includes("--force")
7053
+ };
7054
+ }
5619
7055
  function cliVersion() {
5620
- return true ? "0.9.1" : "0.0.0-dev";
7056
+ return true ? "0.12.0" : "0.0.0-dev";
5621
7057
  }
5622
7058
  function isHelpRequest(command, args) {
5623
7059
  if (command === void 0) return false;
@@ -5632,7 +7068,8 @@ function helpText() {
5632
7068
  " costclaw audit [--path <dir>] [--claude-md <file>] [--plan <plan>] [--json] [--html [file]] [--no-html] [--card [file]]",
5633
7069
  " costclaw diff [<baseline.json> <current.json>] [--json]",
5634
7070
  " costclaw badge [--path <dir>] [--claude-md <file>] [--out <file>]",
5635
- " costclaw optimize [--path <dir>] [--claude-md <file>] [--project <dir>] [--out <dir>] [--write <file>] [--apply-settings [file]] [--no-dashboard] [--force]",
7071
+ " costclaw optimize [--path <dir>] [--claude-md <file>] [--project <dir>] [--out <dir>] [--limit <n>] [--no-dashboard] [--no-serve] [--force]",
7072
+ " costclaw apply [<dir>] [--remove] [--replace] [--apply-settings [file]] [--from <dir>] [--force]",
5636
7073
  " costclaw activate <license-key> [--name <machine-name>]",
5637
7074
  " costclaw deactivate",
5638
7075
  " costclaw --version",
@@ -5650,7 +7087,9 @@ function helpText() {
5650
7087
  "money back, so the audit reframes the headline as recoverable usage: the share",
5651
7088
  "of your token consumption (and rate-limit headroom) you could win back. The",
5652
7089
  "value is saved to ~/.costclaw/config.json so later runs remember it;",
5653
- "--plan api switches back.",
7090
+ "--plan api switches back. Pass nothing and the first interactive run asks",
7091
+ "once and saves the answer; piped, --json and CI runs are never asked and",
7092
+ "assume API rates.",
5654
7093
  "",
5655
7094
  "diff compares two audits and shows the movement: new spend since the baseline,",
5656
7095
  "the marginal cache hit rate for just that period, score changes per pillar, and",
@@ -5662,20 +7101,37 @@ function helpText() {
5662
7101
  "costclaw-badge.svg) showing your overall score, colored by its band. Embed it",
5663
7102
  "in a README with an <img> tag; it is a static, self-contained file.",
5664
7103
  "",
5665
- "optimize turns that same audit into two artifacts: an optimized CLAUDE.md",
5666
- "scaffold and a prioritized fix playbook. It also scans --project <dir>",
5667
- "(default: the current directory) to auto-fill the scaffold's name, commands,",
5668
- "structure, and other facts from your real project files. By default it",
5669
- "dry-runs into ./costclaw-out (override with --out); --write <file> applies the",
5670
- "optimized CLAUDE.md in place after backing up the original and printing a diff.",
5671
- "--apply-settings [file] additively merges the derived permission allowlist into",
5672
- "the project's .claude/settings.json (or [file]); it only touches",
5673
- "permissions.allow and permissions.deny, backs up the original, and prints a diff.",
5674
- "It also writes DASHBOARD.html and opens it: one page that browses every artifact,",
5675
- "the ranked fixes, and a before and after of your CLAUDE.md. --no-dashboard skips it.",
5676
- "optimize needs a one-time license: buy at https://costclaw.io, then run",
5677
- "costclaw activate <key>. activate and deactivate move that license between",
5678
- "machines. audit never needs a license.",
7104
+ "optimize generates, for every project your audit saw, five artifacts: an",
7105
+ "optimized CLAUDE.md scaffold, a prioritized fix playbook, a conservative,",
7106
+ "project-derived settings.suggested.json permission allowlist, a",
7107
+ "HARNESS-UPGRADE.md work order for your own Claude Code, and costclaw.md (the",
7108
+ "generated sections as a standalone include). It never writes inside a",
7109
+ "project; only costclaw apply does that, on an explicit command.",
7110
+ "By default it runs globally: it ranks your audited projects by spend,",
7111
+ "generates for the top ones (cap 10, override with --limit N) into",
7112
+ "~/.costclaw/optimize/<project>/, and writes one DASHBOARD.html index plus a",
7113
+ "local apply page you can click through instead of the command line",
7114
+ "(Ctrl+C, its Done button, or --no-serve to skip it). --project <dir> keeps",
7115
+ "the single-project run, writing into ./costclaw-out (or --out <dir>)",
7116
+ "instead. --no-dashboard skips the HTML.",
7117
+ "",
7118
+ "apply [<dir>] (default: the current directory) is the only command that",
7119
+ "writes inside a project, and only additively: it writes the generated",
7120
+ "sections to .claude/costclaw.md and adds one @.claude/costclaw.md import",
7121
+ "line to your CLAUDE.md, leaving every line you wrote untouched. --remove",
7122
+ "undoes that. --replace is the old wholesale rewrite, now gated behind a git",
7123
+ "repository so the undo is `git checkout -- CLAUDE.md` (it still keeps a",
7124
+ ".bak too). --apply-settings [file] additively merges the derived permission",
7125
+ "allowlist into .claude/settings.json (or [file]); it only touches",
7126
+ "permissions.allow and permissions.deny, backs up the original, and prints a",
7127
+ "diff. --from <dir> points apply at a specific artifacts folder instead of",
7128
+ "looking one up by project; without it, apply finds artifacts from the last",
7129
+ "optimize run, or generates them cold if none exist yet. --force allows",
7130
+ "overwriting an existing .bak backup for --replace and --apply-settings.",
7131
+ "",
7132
+ "optimize and apply need a one-time license: buy at https://costclaw.io, then",
7133
+ "run costclaw activate <key>. activate and deactivate move that license",
7134
+ "between machines. audit never needs a license.",
5679
7135
  "",
5680
7136
  "Everything runs locally. Nothing is uploaded. Activation is a signed license",
5681
7137
  "key verified on this machine: there is no license server and no network call.",
@@ -5733,6 +7189,14 @@ Run: costclaw optimize
5733
7189
  return;
5734
7190
  }
5735
7191
  if (command === "optimize") {
7192
+ if (args.includes("--write")) {
7193
+ process.stderr.write("--write moved: run costclaw apply <dir> --replace\n");
7194
+ process.exit(1);
7195
+ }
7196
+ if (args.includes("--apply-settings")) {
7197
+ process.stderr.write("--apply-settings moved: run costclaw apply <dir> --apply-settings\n");
7198
+ process.exit(1);
7199
+ }
5736
7200
  const gate = await checkLicense();
5737
7201
  if (!gate.ok) {
5738
7202
  process.stderr.write(gate.message + "\n");
@@ -5742,18 +7206,61 @@ Run: costclaw optimize
5742
7206
  path: getFlag(args, "--path"),
5743
7207
  claudeMdPath: getFlag(args, "--claude-md"),
5744
7208
  plan: planFlag(args),
5745
- projectDir: getFlag(args, "--project") || process.cwd(),
7209
+ projectDir: getFlag(args, "--project"),
5746
7210
  out: getFlag(args, "--out"),
5747
- write: getFlag(args, "--write"),
7211
+ limit: Number(getFlag(args, "--limit")) || void 0,
5748
7212
  force: args.includes("--force"),
5749
7213
  dashboard: !args.includes("--no-dashboard"),
5750
- version: cliVersion(),
5751
- applySettings: args.includes("--apply-settings"),
5752
- applySettingsPath: args.includes("--apply-settings") ? optionalPathAfter(args, "--apply-settings") : void 0
7214
+ serve: !args.includes("--no-serve"),
7215
+ version: cliVersion()
5753
7216
  });
5754
7217
  process.stdout.write(output + "\n");
5755
7218
  return;
5756
7219
  }
7220
+ if (command === "apply") {
7221
+ const gate = await checkLicense();
7222
+ if (!gate.ok) {
7223
+ process.stderr.write(gate.message + "\n");
7224
+ process.exit(1);
7225
+ }
7226
+ const flags = parseApplyFlags(args);
7227
+ const root = defaultOptimizeRoot(homedir7());
7228
+ let artifactsDir = flags.from;
7229
+ if (!artifactsDir) {
7230
+ const manifest = await readManifest(root);
7231
+ artifactsDir = manifest ? findEntry(manifest, flags.projectDir)?.artifactsDir : void 0;
7232
+ }
7233
+ if (!artifactsDir) {
7234
+ const run = await runOptimize({
7235
+ projectDir: flags.projectDir,
7236
+ serve: false,
7237
+ dashboard: false,
7238
+ version: cliVersion()
7239
+ });
7240
+ artifactsDir = findEntry(run.manifest, flags.projectDir)?.artifactsDir;
7241
+ }
7242
+ if (!artifactsDir) {
7243
+ throw new Error(`Could not find or generate artifacts for ${flags.projectDir}`);
7244
+ }
7245
+ const outcome = await runApply({
7246
+ projectDir: flags.projectDir,
7247
+ mode: flags.mode,
7248
+ artifactsDir,
7249
+ applySettings: flags.applySettings,
7250
+ applySettingsPath: flags.applySettingsPath,
7251
+ force: flags.force
7252
+ });
7253
+ process.stdout.write(outcome.lines.join("\n") + "\n");
7254
+ if (flags.mode === "include") {
7255
+ const manifest = await readManifest(root);
7256
+ const entry = manifest ? findEntry(manifest, flags.projectDir) : void 0;
7257
+ if (manifest && entry) {
7258
+ entry.appliedAt = (/* @__PURE__ */ new Date()).toISOString();
7259
+ await writeManifest(root, manifest);
7260
+ }
7261
+ }
7262
+ return;
7263
+ }
5757
7264
  process.stderr.write(helpText() + "\n");
5758
7265
  process.exit(command ? 1 : 0);
5759
7266
  }
@@ -5768,6 +7275,7 @@ export {
5768
7275
  cliVersion,
5769
7276
  helpText,
5770
7277
  isHelpRequest,
7278
+ parseApplyFlags,
5771
7279
  parseAuditFlags,
5772
7280
  parseBadgeFlags,
5773
7281
  planFlag