costclaw 0.15.0 → 0.16.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +284 -80
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -3938,7 +3938,7 @@ function diffAudits(a, b) {
3938
3938
  const curFixes = new Map(cur.fixes.map((f) => [f.id, f]));
3939
3939
  const resolved = base.fixes.filter((f) => !curFixes.has(f.id)).map((f) => ({ id: f.id, title: f.title, wasteUsd: round22(f.wasteUsd) }));
3940
3940
  const appeared = cur.fixes.filter((f) => !baseFixes.has(f.id)).map((f) => ({ id: f.id, title: f.title, wasteUsd: round22(f.wasteUsd) }));
3941
- const changed = cur.fixes.filter((f) => baseFixes.has(f.id)).map((f) => {
3941
+ const changed2 = cur.fixes.filter((f) => baseFixes.has(f.id)).map((f) => {
3942
3942
  const beforeUsd = round22(baseFixes.get(f.id).wasteUsd);
3943
3943
  const afterUsd = round22(f.wasteUsd);
3944
3944
  return { id: f.id, title: f.title, beforeUsd, afterUsd, deltaUsd: round22(afterUsd - beforeUsd) };
@@ -3963,7 +3963,7 @@ function diffAudits(a, b) {
3963
3963
  cacheHitRatePoints: round42(cm.cacheHitRate - bm.cacheHitRate)
3964
3964
  },
3965
3965
  pillars,
3966
- fixes: { resolved, appeared, changed }
3966
+ fixes: { resolved, appeared, changed: changed2 }
3967
3967
  };
3968
3968
  }
3969
3969
  var SINCE_BASELINE_MIN_TOKENS = 1e6;
@@ -5928,7 +5928,7 @@ async function runAudit(opts) {
5928
5928
 
5929
5929
  // src/optimize-command.ts
5930
5930
  import { mkdir as mkdir6, writeFile as writeFile6, readFile as readFile10, stat as stat3 } from "fs/promises";
5931
- import { basename as basename3, join as join10, resolve as resolve6 } from "path";
5931
+ import { basename as basename4, join as join10, resolve as resolve6 } from "path";
5932
5932
  import { homedir as homedir6 } from "os";
5933
5933
 
5934
5934
  // src/claude-md-imports.ts
@@ -5959,7 +5959,7 @@ async function resolveClaudeMdImports(claudeMdPath, text2, home) {
5959
5959
 
5960
5960
  // src/apply-command.ts
5961
5961
  import { mkdir as mkdir4, writeFile as writeFile4, readFile as readFile6, rm as rm3, stat, copyFile } from "fs/promises";
5962
- import { join as join7, dirname as dirname3 } from "path";
5962
+ import { join as join7, dirname as dirname3, basename as basename2 } from "path";
5963
5963
  import { homedir as homedir5 } from "os";
5964
5964
  var IMPORT_LINE2 = "@.claude/costclaw.md";
5965
5965
  var INCLUDE_REL = ".claude/costclaw.md";
@@ -5980,6 +5980,18 @@ async function pathExists(p) {
5980
5980
  return false;
5981
5981
  }
5982
5982
  }
5983
+ function stamp(now) {
5984
+ const p = (n, w = 2) => String(n).padStart(w, "0");
5985
+ return `${now.getFullYear()}${p(now.getMonth() + 1)}${p(now.getDate())}-${p(now.getHours())}${p(now.getMinutes())}${p(now.getSeconds())}`;
5986
+ }
5987
+ async function backupFile(target, now = /* @__PURE__ */ new Date()) {
5988
+ if (!await pathExists(target)) return null;
5989
+ const base = `${target}.bak-${stamp(now)}`;
5990
+ let path = base;
5991
+ for (let n = 2; await pathExists(path); n++) path = `${base}-${n}`;
5992
+ await copyFile(target, path);
5993
+ return path;
5994
+ }
5983
5995
  async function readIncludeSections(artifactsDir) {
5984
5996
  const path = join7(artifactsDir, INCLUDE_SECTIONS_ARTIFACT);
5985
5997
  if (!await pathExists(path)) return null;
@@ -6036,6 +6048,12 @@ function ensureImportLine(claudeMd) {
6036
6048
  function stripImportLine(claudeMd) {
6037
6049
  return stripLine(claudeMd, IMPORT_LINE2);
6038
6050
  }
6051
+ async function contentOrNull(path) {
6052
+ return await pathExists(path) ? await readFile6(path, "utf8") : null;
6053
+ }
6054
+ function changed(path, label, before, after) {
6055
+ return before === after ? null : { path, label, before, after };
6056
+ }
6039
6057
  async function runInclude(opts) {
6040
6058
  const { projectDir, artifactsDir } = opts;
6041
6059
  const includeSrc = join7(artifactsDir, INCLUDE_ARTIFACT);
@@ -6046,8 +6064,12 @@ async function runInclude(opts) {
6046
6064
  const claudeDir = join7(projectDir, ".claude");
6047
6065
  await mkdir4(claudeDir, { recursive: true });
6048
6066
  const includeDest = join7(projectDir, INCLUDE_REL);
6067
+ const includeBefore = await contentOrNull(includeDest);
6049
6068
  await writeFile4(includeDest, includeMd, "utf8");
6050
6069
  const wrote = [includeDest];
6070
+ const files = [];
6071
+ const includeChange = changed(includeDest, INCLUDE_REL, includeBefore, includeMd);
6072
+ if (includeChange) files.push(includeChange);
6051
6073
  const lines = [`Wrote ${INCLUDE_REL}`, ...describeIncludeSections(await readIncludeSections(artifactsDir))];
6052
6074
  const claudeMdPath = join7(projectDir, "CLAUDE.md");
6053
6075
  const existing = await pathExists(claudeMdPath) ? await readFile6(claudeMdPath, "utf8") : null;
@@ -6055,6 +6077,7 @@ async function runInclude(opts) {
6055
6077
  if (added) {
6056
6078
  await writeFile4(claudeMdPath, text2, "utf8");
6057
6079
  wrote.push(claudeMdPath);
6080
+ files.push({ path: claudeMdPath, label: "CLAUDE.md", before: existing, after: text2 });
6058
6081
  lines.push(`Added "${IMPORT_LINE2}" to CLAUDE.md`);
6059
6082
  } else {
6060
6083
  lines.push("CLAUDE.md already imports it");
@@ -6076,20 +6099,24 @@ async function runInclude(opts) {
6076
6099
  const settingsSrc = join7(artifactsDir, "settings.suggested.json");
6077
6100
  const suggestedJson = await readFile6(settingsSrc, "utf8");
6078
6101
  const target = opts.applySettingsPath ?? join7(projectDir, ".claude", "settings.json");
6079
- const settingsLines = await applyDerivedSettings(target, suggestedJson, opts.force ?? false);
6080
- lines.push(...settingsLines);
6102
+ const settings = await applyDerivedSettings(target, suggestedJson);
6103
+ lines.push(...settings.lines);
6081
6104
  wrote.push(target);
6105
+ if (settings.file) files.push(settings.file);
6082
6106
  }
6083
- return { lines, wrote, removed: [] };
6107
+ return { lines, wrote, removed: [], files };
6084
6108
  }
6085
6109
  async function runRemove(opts) {
6086
6110
  const { projectDir } = opts;
6087
6111
  const includeDest = join7(projectDir, INCLUDE_REL);
6088
6112
  const companionDir = join7(projectDir, APPLY_DIR_REL);
6089
6113
  const removed = [];
6090
- if (await pathExists(includeDest)) {
6114
+ const files = [];
6115
+ const includeBefore = await contentOrNull(includeDest);
6116
+ if (includeBefore !== null) {
6091
6117
  await rm3(includeDest, { force: true });
6092
6118
  removed.push(includeDest);
6119
+ files.push({ path: includeDest, label: INCLUDE_REL, before: includeBefore, after: null });
6093
6120
  }
6094
6121
  if (await pathExists(companionDir)) {
6095
6122
  await rm3(companionDir, { recursive: true, force: true });
@@ -6104,17 +6131,19 @@ async function runRemove(opts) {
6104
6131
  if (text2 === "") {
6105
6132
  await rm3(claudeMdPath, { force: true });
6106
6133
  removed.push(claudeMdPath);
6134
+ files.push({ path: claudeMdPath, label: "CLAUDE.md", before: existing, after: null });
6107
6135
  lines.push("Removed CLAUDE.md (it held only the import line)");
6108
6136
  } else {
6109
6137
  await writeFile4(claudeMdPath, text2, "utf8");
6138
+ files.push({ path: claudeMdPath, label: "CLAUDE.md", before: existing, after: text2 });
6110
6139
  lines.push(`Removed "${IMPORT_LINE2}" from CLAUDE.md`);
6111
6140
  }
6112
6141
  }
6113
6142
  }
6114
- return { lines, wrote: [], removed };
6143
+ return { lines, wrote: [], removed, files };
6115
6144
  }
6116
6145
  async function runReplace(opts) {
6117
- const { projectDir, artifactsDir, force } = opts;
6146
+ const { projectDir, artifactsDir } = opts;
6118
6147
  if (!await pathExists(join7(projectDir, ".git"))) {
6119
6148
  throw new Error(
6120
6149
  "apply --replace needs a git repository so the change can be undone with git checkout -- CLAUDE.md. Use the default include mode instead."
@@ -6126,25 +6155,24 @@ async function runReplace(opts) {
6126
6155
  }
6127
6156
  const optimized = await readFile6(optimizedSrc, "utf8");
6128
6157
  const claudeMdPath = join7(projectDir, "CLAUDE.md");
6129
- const backup = `${claudeMdPath}.bak`;
6130
- if (await pathExists(backup) && !force) {
6131
- throw new Error(
6132
- `A backup already exists at ${backup}. Refusing to overwrite it. Pass --force to replace the existing backup.`
6133
- );
6134
- }
6135
6158
  const original = await pathExists(claudeMdPath) ? await readFile6(claudeMdPath, "utf8") : "";
6136
- await writeFile4(backup, original, "utf8");
6159
+ const backup = await backupFile(claudeMdPath);
6137
6160
  await writeFile4(claudeMdPath, optimized, "utf8");
6138
6161
  const lines = [
6139
- `Backed up the original to ${backup}`,
6162
+ ...backup ? [`Backed up the original to ${backup}`] : [],
6140
6163
  `Wrote the optimized CLAUDE.md to ${claudeMdPath}`,
6141
6164
  "",
6142
6165
  "Diff (old vs new):",
6143
6166
  lineDiff(original, optimized),
6144
6167
  "",
6145
- "Undo: git checkout -- CLAUDE.md (or restore CLAUDE.md.bak)"
6168
+ backup ? `Undo: git checkout -- CLAUDE.md (or restore ${backup})` : "Undo: git checkout -- CLAUDE.md"
6146
6169
  ];
6147
- return { lines, wrote: [claudeMdPath, backup], removed: [] };
6170
+ return {
6171
+ lines,
6172
+ wrote: backup ? [claudeMdPath, backup] : [claudeMdPath],
6173
+ removed: [],
6174
+ files: [{ path: claudeMdPath, label: "CLAUDE.md", before: original === "" ? null : original, after: optimized }]
6175
+ };
6148
6176
  }
6149
6177
  async function runApply(opts) {
6150
6178
  if (opts.global) return runGlobal(opts);
@@ -6159,20 +6187,25 @@ async function runGlobal(opts) {
6159
6187
  if (opts.mode === "remove") {
6160
6188
  const removed = [];
6161
6189
  const lines2 = [];
6162
- if (await pathExists(includeDest)) {
6190
+ const files2 = [];
6191
+ const includeBefore = await contentOrNull(includeDest);
6192
+ if (includeBefore !== null) {
6163
6193
  await rm3(includeDest, { force: true });
6164
6194
  removed.push(includeDest);
6195
+ files2.push({ path: includeDest, label: GLOBAL_INCLUDE_REL, before: includeBefore, after: null });
6165
6196
  lines2.push(`Removed ${GLOBAL_INCLUDE_REL}`);
6166
6197
  }
6167
- if (await pathExists(claudeMdPath)) {
6168
- const { text: text2, removed: didRemove } = stripLine(await readFile6(claudeMdPath, "utf8"), GLOBAL_IMPORT_LINE);
6198
+ const mdBefore = await contentOrNull(claudeMdPath);
6199
+ if (mdBefore !== null) {
6200
+ const { text: text2, removed: didRemove } = stripLine(mdBefore, GLOBAL_IMPORT_LINE);
6169
6201
  if (didRemove) {
6170
6202
  await writeFile4(claudeMdPath, text2, "utf8");
6203
+ files2.push({ path: claudeMdPath, label: "~/.claude/CLAUDE.md", before: mdBefore, after: text2 });
6171
6204
  lines2.push(`Removed "${GLOBAL_IMPORT_LINE}" from ${claudeMdPath}`);
6172
6205
  }
6173
6206
  }
6174
6207
  if (lines2.length === 0) lines2.push("Nothing to remove: the global include was not applied.");
6175
- return { lines: lines2, wrote: [], removed };
6208
+ return { lines: lines2, wrote: [], removed, files: files2 };
6176
6209
  }
6177
6210
  const includeSrc = join7(opts.artifactsDir, GLOBAL_INCLUDE_ARTIFACT);
6178
6211
  const optimizedSrc = join7(opts.artifactsDir, GLOBAL_OPTIMIZED_ARTIFACT);
@@ -6183,21 +6216,18 @@ async function runGlobal(opts) {
6183
6216
  );
6184
6217
  }
6185
6218
  const original = await pathExists(claudeMdPath) ? await readFile6(claudeMdPath, "utf8") : null;
6186
- const backup = `${claudeMdPath}.bak`;
6187
- if (original !== null) {
6188
- if (await pathExists(backup) && !opts.force) {
6189
- throw new Error(
6190
- `A backup already exists at ${backup}. Refusing to overwrite it. Pass --force to replace the existing backup.`
6191
- );
6192
- }
6193
- await writeFile4(backup, original, "utf8");
6194
- }
6219
+ const backup = await backupFile(claudeMdPath);
6195
6220
  const wrote = [];
6196
6221
  const lines = [];
6222
+ const files = [];
6197
6223
  await mkdir4(dirname3(claudeMdPath), { recursive: true });
6198
6224
  if (hasInclude) {
6199
- await writeFile4(includeDest, await readFile6(includeSrc, "utf8"), "utf8");
6225
+ const includeAfter = await readFile6(includeSrc, "utf8");
6226
+ const includeBefore = await contentOrNull(includeDest);
6227
+ await writeFile4(includeDest, includeAfter, "utf8");
6200
6228
  wrote.push(includeDest);
6229
+ const c = changed(includeDest, GLOBAL_INCLUDE_REL, includeBefore, includeAfter);
6230
+ if (c) files.push(c);
6201
6231
  lines.push(`Wrote ${GLOBAL_INCLUDE_REL}`);
6202
6232
  } else {
6203
6233
  lines.push("Your audit produced no global sections to add, so no include file was written.");
@@ -6213,6 +6243,7 @@ async function runGlobal(opts) {
6213
6243
  }
6214
6244
  await writeFile4(claudeMdPath, optimized, "utf8");
6215
6245
  wrote.push(claudeMdPath);
6246
+ files.push({ path: claudeMdPath, label: "~/.claude/CLAUDE.md", before: original, after: optimized });
6216
6247
  lines.push(
6217
6248
  `Rewrote ${claudeMdPath} with every reviewed removal applied`,
6218
6249
  "",
@@ -6224,6 +6255,7 @@ async function runGlobal(opts) {
6224
6255
  if (added) {
6225
6256
  await writeFile4(claudeMdPath, text2, "utf8");
6226
6257
  wrote.push(claudeMdPath);
6258
+ files.push({ path: claudeMdPath, label: "~/.claude/CLAUDE.md", before: original, after: text2 });
6227
6259
  lines.push(`Added "${GLOBAL_IMPORT_LINE}" to ${claudeMdPath}`);
6228
6260
  } else {
6229
6261
  lines.push("Your global CLAUDE.md already imports it");
@@ -6232,9 +6264,9 @@ async function runGlobal(opts) {
6232
6264
  "Every line you wrote is untouched. To also drop the sections the review marked remove, rerun with --replace."
6233
6265
  );
6234
6266
  }
6235
- if (original !== null) lines.push(`Backed up the original to ${backup}`);
6267
+ if (backup) lines.push(`Backed up the original to ${backup}`);
6236
6268
  lines.push("Undo: costclaw apply --global --remove");
6237
- return { lines, wrote, removed: [] };
6269
+ return { lines, wrote, removed: [], files };
6238
6270
  }
6239
6271
  function lineDiff(oldText, newText) {
6240
6272
  const oldLines = oldText.split(/\r?\n/);
@@ -6274,13 +6306,7 @@ function unionStrings(existing, additions) {
6274
6306
  function isPlainObject(value) {
6275
6307
  return typeof value === "object" && value !== null && !Array.isArray(value);
6276
6308
  }
6277
- async function applyDerivedSettings(target, suggestedJson, force) {
6278
- const backup = `${target}.bak`;
6279
- if (await pathExists(backup) && !force) {
6280
- throw new Error(
6281
- `A backup already exists at ${backup}. Refusing to overwrite it. Pass --force to replace the existing backup.`
6282
- );
6283
- }
6309
+ async function applyDerivedSettings(target, suggestedJson) {
6284
6310
  let existingText = "";
6285
6311
  let existing = {};
6286
6312
  if (await pathExists(target)) {
@@ -6312,16 +6338,93 @@ async function applyDerivedSettings(target, suggestedJson, force) {
6312
6338
  const merged = { ...existing, permissions: mergedPerms };
6313
6339
  const mergedText = JSON.stringify(merged, null, 2) + "\n";
6314
6340
  await mkdir4(dirname3(target), { recursive: true });
6315
- await writeFile4(backup, existingText, "utf8");
6341
+ const backup = await backupFile(target);
6316
6342
  await writeFile4(target, mergedText, "utf8");
6317
- return [
6318
- `Merged the derived permission allowlist into ${target}`,
6319
- `Backed up the previous file to ${backup}`,
6320
- "Only permissions.allow and permissions.deny changed (deduped union, existing entries kept and ordered first). Every other key was left as it was.",
6321
- "",
6322
- "Diff (previous vs merged):",
6323
- lineDiff(existingText, mergedText)
6324
- ];
6343
+ return {
6344
+ lines: [
6345
+ `Merged the derived permission allowlist into ${target}`,
6346
+ ...backup ? [`Backed up the previous file to ${backup}`] : [],
6347
+ "Only permissions.allow and permissions.deny changed (deduped union, existing entries kept and ordered first). Every other key was left as it was.",
6348
+ "",
6349
+ "Diff (previous vs merged):",
6350
+ lineDiff(existingText, mergedText)
6351
+ ],
6352
+ file: changed(target, basename2(target), existingText === "" ? null : existingText, mergedText)
6353
+ };
6354
+ }
6355
+
6356
+ // src/line-align.ts
6357
+ var MAX_LINES = 4e3;
6358
+ function splitLines(text2) {
6359
+ if (text2 === null) return [];
6360
+ const lines = text2.split(/\r?\n/);
6361
+ if (lines.length > 0 && lines[lines.length - 1] === "") lines.pop();
6362
+ return lines;
6363
+ }
6364
+ function alignLines(before, after) {
6365
+ const a = splitLines(before);
6366
+ const b = splitLines(after);
6367
+ if (a.length > MAX_LINES || b.length > MAX_LINES) {
6368
+ const rows2 = [
6369
+ ...a.map((text2, i2) => ({ kind: "remove", left: text2, right: null, leftNo: i2 + 1, rightNo: null })),
6370
+ ...b.map((text2, i2) => ({ kind: "add", left: null, right: text2, leftNo: null, rightNo: i2 + 1 }))
6371
+ ];
6372
+ return { rows: rows2, added: b.length, removed: a.length, truncated: true };
6373
+ }
6374
+ const lcs = Array.from({ length: a.length + 1 }, () => new Array(b.length + 1).fill(0));
6375
+ for (let i2 = a.length - 1; i2 >= 0; i2--) {
6376
+ for (let j2 = b.length - 1; j2 >= 0; j2--) {
6377
+ lcs[i2][j2] = a[i2] === b[j2] ? lcs[i2 + 1][j2 + 1] + 1 : Math.max(lcs[i2 + 1][j2], lcs[i2][j2 + 1]);
6378
+ }
6379
+ }
6380
+ const rows = [];
6381
+ let added = 0;
6382
+ let removed = 0;
6383
+ let i = 0;
6384
+ let j = 0;
6385
+ while (i < a.length && j < b.length) {
6386
+ if (a[i] === b[j]) {
6387
+ rows.push({ kind: "same", left: a[i], right: b[j], leftNo: i + 1, rightNo: j + 1 });
6388
+ i++;
6389
+ j++;
6390
+ } else if (lcs[i + 1][j] >= lcs[i][j + 1]) {
6391
+ rows.push({ kind: "remove", left: a[i], right: null, leftNo: i + 1, rightNo: null });
6392
+ removed++;
6393
+ i++;
6394
+ } else {
6395
+ rows.push({ kind: "add", left: null, right: b[j], leftNo: null, rightNo: j + 1 });
6396
+ added++;
6397
+ j++;
6398
+ }
6399
+ }
6400
+ for (; i < a.length; i++) {
6401
+ rows.push({ kind: "remove", left: a[i], right: null, leftNo: i + 1, rightNo: null });
6402
+ removed++;
6403
+ }
6404
+ for (; j < b.length; j++) {
6405
+ rows.push({ kind: "add", left: null, right: b[j], leftNo: null, rightNo: j + 1 });
6406
+ added++;
6407
+ }
6408
+ return { rows, added, removed, truncated: false };
6409
+ }
6410
+ function collapseUnchanged(rows, context = 3) {
6411
+ const keep = /* @__PURE__ */ new Set();
6412
+ for (let i = 0; i < rows.length; i++) {
6413
+ if (rows[i].kind === "same") continue;
6414
+ for (let k = Math.max(0, i - context); k <= Math.min(rows.length - 1, i + context); k++) keep.add(k);
6415
+ }
6416
+ const out = [];
6417
+ let gap = false;
6418
+ for (let i = 0; i < rows.length; i++) {
6419
+ if (keep.has(i)) {
6420
+ out.push(rows[i]);
6421
+ gap = false;
6422
+ } else if (!gap) {
6423
+ out.push(null);
6424
+ gap = true;
6425
+ }
6426
+ }
6427
+ return out;
6325
6428
  }
6326
6429
 
6327
6430
  // src/optimize-dashboard.ts
@@ -6411,6 +6514,30 @@ ul.warn b{font-weight:650}
6411
6514
  .file a{margin-top:auto;font-size:.83rem;color:var(--ink);text-decoration:none;border-bottom:1px solid var(--line);
6412
6515
  align-self:flex-start;padding-bottom:1px}
6413
6516
  .file a:hover{border-color:var(--accent)}
6517
+
6518
+ /* A file card that opens in place instead of navigating to raw markdown. */
6519
+ details.viewer{padding:0}
6520
+ /* An opened file takes the whole row. Left in its grid column it would stretch
6521
+ every sibling card to the height of the file and read as a broken layout. */
6522
+ details.viewer[open]{grid-column:1/-1}
6523
+ details.viewer>summary{cursor:pointer;list-style:none;padding:15px 16px;display:flex;flex-direction:column;
6524
+ gap:6px;border-radius:10px}
6525
+ details.viewer>summary::-webkit-details-marker{display:none}
6526
+ /* Closed, the action row sits at the card's bottom so the grid's cards line up.
6527
+ Open, that same auto margin would leave a band of empty space above the file. */
6528
+ details.viewer .acts2{margin-top:auto;display:flex;align-items:baseline;gap:12px}
6529
+ details.viewer[open]>summary .acts2{margin-top:0}
6530
+ details.viewer .open,details.viewer .shut{font-size:.83rem;border-bottom:1px solid var(--line);padding-bottom:1px}
6531
+ details.viewer>summary:hover .open,details.viewer>summary:hover .shut{border-color:var(--accent)}
6532
+ details.viewer .shut{display:none}
6533
+ details.viewer[open]>summary .open{display:none}
6534
+ details.viewer[open]>summary .shut{display:inline}
6535
+ details.viewer .raw{font-size:.74rem;color:var(--ink2);margin-top:0;align-self:baseline}
6536
+ details.viewer>.note{margin:0 16px 8px}
6537
+ /* Scrollable and selectable: the point is to read and copy from it in place. */
6538
+ .filebody{margin:0;padding:12px 16px;max-height:60vh;overflow:auto;white-space:pre-wrap;word-break:break-word;
6539
+ font-family:var(--mono);font-size:.76rem;line-height:1.55;border-top:1px solid var(--line);
6540
+ background:color-mix(in srgb,var(--ink) 3%,transparent);border-radius:0 0 10px 10px}
6414
6541
  .cta{background:var(--panel);border:1px solid var(--line);border-left:3px solid var(--good);
6415
6542
  border-radius:10px;padding:18px 20px}
6416
6543
  code.cmd{display:block;font-family:var(--mono);font-size:.86rem;background:color-mix(in srgb,var(--ink) 6%,transparent);
@@ -6693,12 +6820,24 @@ var PLAYBOOK_NAME = "PLAYBOOK.md";
6693
6820
  var SETTINGS_NAME = "settings.suggested.json";
6694
6821
  var HARNESS_NAME = "HARNESS-UPGRADE.md";
6695
6822
  var INCLUDE_NAME = "costclaw.md";
6823
+ var VIEWER_MAX_LINES = 600;
6824
+ function renderFileCard(name, desc, text2) {
6825
+ const head = `<span class="nm">${esc(name)}</span><span class="ds">${esc(desc)}</span>`;
6826
+ if (text2 === void 0) {
6827
+ return `<div class="file">${head}<a href="${esc(name)}">Open file</a></div>`;
6828
+ }
6829
+ const lines = text2.replace(/\s*$/, "").split("\n");
6830
+ const clipped = lines.length > VIEWER_MAX_LINES;
6831
+ const shown = clipped ? lines.slice(0, VIEWER_MAX_LINES) : lines;
6832
+ const note = clipped ? `<p class="note">Showing the first ${num5(VIEWER_MAX_LINES)} of ${num5(lines.length)} lines. Open the raw file for the rest.</p>` : "";
6833
+ return `<details class="file viewer"><summary>${head}<span class="acts2"><span class="open">Open</span><span class="shut">Close</span><a href="${esc(name)}" class="raw">raw</a></span></summary>` + note + `<pre class="filebody">${esc(shown.join("\n"))}</pre></details>`;
6834
+ }
6696
6835
  function renderArtifactCards(input) {
6697
6836
  const { before, after } = input.claudeMdTokens;
6698
6837
  const lighter = before !== null && after < before ? ` and ${fmtTokens(before - after)} tokens lighter` : "";
6699
6838
  const placeholders = `${input.placeholdersRemaining} ${plural2(input.placeholdersRemaining, "placeholder")} to fill.`;
6700
6839
  const claudeDesc = before === null ? `A new CLAUDE.md scaffold for your project. ${placeholders}` : `Your CLAUDE.md, restructured${lighter}. ${placeholders}`;
6701
- 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>`;
6840
+ const card = (name, desc) => renderFileCard(name, desc, input.artifactText?.[name]);
6702
6841
  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(
6703
6842
  INCLUDE_NAME,
6704
6843
  "The generated sections as a standalone include. apply writes it to .claude/costclaw.md and adds one @ line to your CLAUDE.md."
@@ -6920,7 +7059,66 @@ td code.cmd{margin-top:0;font-size:.78rem;white-space:pre-wrap;word-break:break-
6920
7059
  .state{font-size:.82rem}
6921
7060
  .state.on{color:var(--good);font-weight:650}
6922
7061
  .state.off{color:var(--ink2)}
7062
+
7063
+ /* What changed: one collapsible block per project, each holding real diffs. */
7064
+ details.chg{border:1px solid var(--line);border-radius:10px;margin:0 0 10px;background:var(--panel)}
7065
+ details.chg>summary{cursor:pointer;padding:10px 14px;list-style:none;display:flex;align-items:baseline;
7066
+ gap:10px;flex-wrap:wrap;border-radius:10px}
7067
+ details.chg>summary::-webkit-details-marker{display:none}
7068
+ details.chg>summary::before{content:"\\25B8";color:var(--ink2);font-size:.8rem;display:inline-block;
7069
+ transition:transform .12s ease}
7070
+ details.chg[open]>summary::before{transform:rotate(90deg)}
7071
+ details.chg>summary:hover{border-color:var(--accent)}
7072
+ details.chg>ul{margin:0;padding:0 18px 10px 40px;font-size:.88rem}
7073
+ .chgstat{font-size:.78rem;color:var(--ink2);font-family:var(--mono)}
7074
+ .plus{color:var(--good);font-weight:650}
7075
+ .minus{color:var(--bad);font-weight:650}
7076
+ .filediff{margin:0 14px 14px;border:1px solid var(--line);border-radius:9px;overflow:hidden}
7077
+ .fhead{display:flex;align-items:center;gap:10px;flex-wrap:wrap;padding:8px 12px;
7078
+ border-bottom:1px solid var(--line);background:color-mix(in srgb,var(--ink) 4%,transparent)}
7079
+ .fhead code{font-size:.82rem}
7080
+ .tag{font-size:.7rem;text-transform:uppercase;letter-spacing:.04em;padding:2px 7px;border-radius:999px;
7081
+ border:1px solid var(--line);color:var(--ink2)}
7082
+ .tag.created{color:var(--good);border-color:color-mix(in srgb,var(--good) 45%,var(--line))}
7083
+ .tag.removed{color:var(--bad);border-color:color-mix(in srgb,var(--bad) 45%,var(--line))}
7084
+ table.sbs{width:100%;border-collapse:collapse;table-layout:fixed;font-family:var(--mono);font-size:.76rem}
7085
+ table.sbs th{text-align:left;font-family:var(--sans);font-size:.72rem;color:var(--ink2);font-weight:600;
7086
+ padding:6px 10px;border-bottom:1px solid var(--line)}
7087
+ table.sbs td{padding:1px 8px;vertical-align:top;white-space:pre-wrap;word-break:break-word;
7088
+ border-bottom:1px solid color-mix(in srgb,var(--line) 40%,transparent)}
7089
+ table.sbs col.cn{width:46px}
7090
+ table.sbs col.cs{width:auto}
7091
+ table.sbs td.ln{text-align:right;color:var(--ink2);user-select:none;opacity:.7}
7092
+ table.sbs tr.add td.r{background:color-mix(in srgb,var(--good) 16%,transparent)}
7093
+ table.sbs tr.remove td.l{background:color-mix(in srgb,var(--bad) 16%,transparent)}
7094
+ table.sbs tr.gap td{text-align:center;color:var(--ink2);letter-spacing:.3em;padding:3px 0;opacity:.6}
6923
7095
  `;
7096
+ function renderProjectChange(c) {
7097
+ const cut = c.lines.findIndex((l) => /^Diff \(/.test(l.trim()));
7098
+ const summary = (cut < 0 ? c.lines : c.lines.slice(0, cut)).filter((l) => l.trim().length > 0);
7099
+ const files = c.files ?? [];
7100
+ const totals = files.map((f) => alignLines(f.before, f.after));
7101
+ const added = totals.reduce((s, t) => s + t.added, 0);
7102
+ const removed = totals.reduce((s, t) => s + t.removed, 0);
7103
+ const head = `<summary><b>${esc(c.slug)}</b>` + (files.length > 0 ? `<span class="chgstat">${files.length} ${plural2(files.length, "file")} <span class="plus">+${added}</span> <span class="minus">-${removed}</span></span>` : `<span class="chgstat">no file changed</span>`) + `</summary>`;
7104
+ const body = `<ul>${summary.map((l) => `<li>${esc(l)}</li>`).join("")}</ul>` + files.map((f, i) => renderFileDiff(f, totals[i])).join("");
7105
+ return `<details class="chg"${files.length === 0 ? " open" : ""}>${head}${body}</details>`;
7106
+ }
7107
+ function renderFileDiff(file, align) {
7108
+ const state = file.before === null ? "created" : file.after === null ? "removed" : "changed";
7109
+ const rows = collapseUnchanged(align.rows).map((r) => {
7110
+ if (r === null) {
7111
+ return `<tr class="gap"><td colspan="4">&middot; &middot; &middot;</td></tr>`;
7112
+ }
7113
+ const cls = r.kind === "same" ? "" : ` class="${r.kind}"`;
7114
+ return `<tr${cls}><td class="ln">${r.leftNo ?? ""}</td><td class="side l">${r.left === null ? "" : esc(r.left)}</td><td class="ln">${r.rightNo ?? ""}</td><td class="side r">${r.right === null ? "" : esc(r.right)}</td></tr>`;
7115
+ }).join("");
7116
+ return `<div class="filediff"><div class="fhead"><code>${esc(file.label)}</code><span class="tag ${state}">${state}</span><span class="chgstat"><span class="plus">+${align.added}</span> <span class="minus">-${align.removed}</span></span></div>` + (align.truncated ? `<p class="note">This file is too large to pair line by line, so the two sides are listed in full instead.</p>` : "") + // table-layout:fixed takes its widths from the first row, and the first row
7117
+ // is the header, whose cells are colspan'd across the two number columns.
7118
+ // Without an explicit colgroup the browser splits four equal columns and the
7119
+ // gutters eat half the width.
7120
+ `<table class="sbs"><colgroup><col class="cn"><col class="cs"><col class="cn"><col class="cs"></colgroup><thead><tr><th colspan="2">Before</th><th colspan="2">After</th></tr></thead><tbody>${rows}</tbody></table><p class="note">${esc(file.path)}</p></div>`;
7121
+ }
6924
7122
  function indexTokens(tokens) {
6925
7123
  if (tokens.before === null) return `${esc(approxTokens(tokens.after))} (new file)`;
6926
7124
  return `${esc(approxTokens(tokens.before))} to ${esc(approxTokens(tokens.after))}`;
@@ -6976,9 +7174,7 @@ function renderOptimizeIndex(input) {
6976
7174
  // a run, and this card carries it when a previous session left files behind.
6977
7175
  (applied > 0 && !priorRun ? `<button type="submit" name="action" value="revert-all">Revert everything</button>` : "") + `</div><label class="opt"><input type="checkbox" name="settings" value="1" checked> also merge the suggested permission allowlist (backs up your settings first)</label><p class="note">Uncheck any project in the table below to leave it out.</p></div>` : "";
6978
7176
  const run = priorRun;
6979
- const changed = run ? `<h2>What changed<span class="n">${run.reverted ? "reverted" : "written just now"}</span></h2><div class="panel changed">` + run.changes.map(
6980
- (c) => `<div class="chg"><b>${esc(c.slug)}</b><ul>` + c.lines.map((l) => `<li>${esc(l)}</li>`).join("") + `</ul></div>`
6981
- ).join("") + (run.reverted ? `<p class="note">Everything costclaw added has been removed.</p>` : `<div class="acts" style="margin-top:12px"><button type="submit" name="action" value="revert-all" class="go">Revert everything</button></div><p class="note">Reverts every project checked in the table below.</p>`) + `</div>` : "";
7177
+ const changed2 = run ? `<h2>What changed<span class="n">${run.reverted ? "reverted" : "written just now"}</span></h2><div class="panel changed">` + run.changes.map((c) => renderProjectChange(c)).join("") + (run.reverted ? `<p class="note">Everything costclaw added has been removed.</p>` : `<div class="acts" style="margin-top:12px"><button type="submit" name="action" value="revert-all" class="go">Revert everything</button></div><p class="note">Reverts every project checked in the table below.</p>`) + `</div>` : "";
6982
7178
  const banner = input.serve?.message ? `<p class="banner">${esc(input.serve.message)}</p>` : "";
6983
7179
  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>` : "";
6984
7180
  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>`;
@@ -7001,7 +7197,7 @@ artifacts in ${esc(input.root)}/</p></header>
7001
7197
  ${banner}${done}
7002
7198
  ${serve ? `<form method="post" action="/apply">
7003
7199
  <input type="hidden" name="token" value="${esc(serve.token)}">` : ""}
7004
- ${changed}
7200
+ ${changed2}
7005
7201
  ${oneButton}
7006
7202
  ${input.review ? `<h2>${serve ? "Or hand it to your own Claude" : "Start here"}<span class="n">${serve ? "it knows your project" : "two ways to do this, pick one"}</span></h2>
7007
7203
  ${renderStartHere(input.review, input.rows.length)}` : ""}
@@ -7026,7 +7222,7 @@ Nothing was written inside any project. No network calls, no telemetry, no model
7026
7222
 
7027
7223
  // src/project-scan.ts
7028
7224
  import { readdir as readdir3, readFile as readFile7, stat as stat2 } from "fs/promises";
7029
- import { join as join8, basename as basename2 } from "path";
7225
+ import { join as join8, basename as basename3 } from "path";
7030
7226
  var NOISE_DIRS = /* @__PURE__ */ new Set([
7031
7227
  "node_modules",
7032
7228
  ".git",
@@ -7500,7 +7696,7 @@ function parseReadme(text2) {
7500
7696
  return { name, description };
7501
7697
  }
7502
7698
  async function scanProject(dir) {
7503
- const profile = emptyProfile(basename2(dir));
7699
+ const profile = emptyProfile(basename3(dir));
7504
7700
  const { files, dirs } = await listEntries(dir);
7505
7701
  if (files.includes("package.json")) {
7506
7702
  const pkg = parseJson(await readText(join8(dir, "package.json")));
@@ -7523,13 +7719,13 @@ async function scanProject(dir) {
7523
7719
  }
7524
7720
  }
7525
7721
  }
7526
- if (profile.description === null || profile.name === basename2(dir)) {
7722
+ if (profile.description === null || profile.name === basename3(dir)) {
7527
7723
  const readmeName = files.find((f) => /^readme(\.md|\.markdown|\.txt)?$/i.test(f));
7528
7724
  if (readmeName) {
7529
7725
  const text2 = await readText(join8(dir, readmeName));
7530
7726
  if (text2 !== null) {
7531
7727
  const parsed = parseReadme(text2);
7532
- if (profile.name === basename2(dir) && parsed.name !== null) profile.name = parsed.name;
7728
+ if (profile.name === basename3(dir) && parsed.name !== null) profile.name = parsed.name;
7533
7729
  if (profile.description === null && parsed.description !== null) {
7534
7730
  profile.description = parsed.description;
7535
7731
  }
@@ -7728,7 +7924,7 @@ async function startApplyServer(opts) {
7728
7924
  const errors = [];
7729
7925
  for (const { entry, action } of targets) {
7730
7926
  try {
7731
- const lines = await opts.apply(entry, action);
7927
+ const { lines, files } = await opts.apply(entry, action);
7732
7928
  if (action === "remove") {
7733
7929
  delete entry.appliedAt;
7734
7930
  delete entry.appliedMode;
@@ -7736,11 +7932,11 @@ async function startApplyServer(opts) {
7736
7932
  entry.appliedAt = (/* @__PURE__ */ new Date()).toISOString();
7737
7933
  entry.appliedMode = action;
7738
7934
  }
7739
- changes.push({ slug: entry.slug, lines });
7935
+ changes.push({ slug: entry.slug, lines, files });
7740
7936
  } catch (err) {
7741
7937
  const text2 = `Error: ${err instanceof Error ? err.message : String(err)}`;
7742
7938
  errors.push(text2);
7743
- changes.push({ slug: entry.slug, lines: [text2] });
7939
+ changes.push({ slug: entry.slug, lines: [text2], files: [] });
7744
7940
  }
7745
7941
  }
7746
7942
  if (opts.onManifestChange) await opts.onManifestChange(manifest);
@@ -7941,7 +8137,7 @@ function projectRecoverable(report, slug) {
7941
8137
  return row ? row.usd : null;
7942
8138
  }
7943
8139
  async function generateForProject(ctx, projectDir, artifactsDir) {
7944
- const slug = basename3(resolve6(projectDir));
8140
+ const slug = basename4(resolve6(projectDir));
7945
8141
  let currentClaudeMd = ctx.claudeMdOverride;
7946
8142
  let claudeMdSource = ctx.claudeMdOverride !== void 0 ? ctx.claudeMdFallbackSource : null;
7947
8143
  if (currentClaudeMd === void 0) {
@@ -8001,7 +8197,16 @@ async function generateForProject(ctx, projectDir, artifactsDir) {
8001
8197
  headlineWasteShare: auditSpend > 0 ? auditRecoverable2 / auditSpend : 0,
8002
8198
  headlineWasteUsd: auditRecoverable2,
8003
8199
  applyCommand,
8004
- review
8200
+ review,
8201
+ // The generated text itself, so each file card opens in place instead of
8202
+ // navigating the reader away to the browser's raw-markdown rendering.
8203
+ artifactText: {
8204
+ [OPTIMIZED_NAME2]: result.optimizedClaudeMd,
8205
+ [PLAYBOOK_NAME2]: result.playbook,
8206
+ [SETTINGS_NAME2]: result.settingsJson,
8207
+ [HARNESS_NAME2]: result.harnessPrompt,
8208
+ [INCLUDE_NAME2]: result.includeMd
8209
+ }
8005
8210
  });
8006
8211
  await writeFile6(join10(artifactsDir, DASHBOARD_NAME2), html, "utf8");
8007
8212
  }
@@ -8058,7 +8263,7 @@ async function generateForProject(ctx, projectDir, artifactsDir) {
8058
8263
  return {
8059
8264
  entry: {
8060
8265
  slug,
8061
- dir: basename3(artifactsDir),
8266
+ dir: basename4(artifactsDir),
8062
8267
  projectDir,
8063
8268
  artifactsDir,
8064
8269
  spendUsd: spend ?? 0,
@@ -8318,7 +8523,7 @@ async function runOptimize(opts) {
8318
8523
  artifactsDir: entry.artifactsDir,
8319
8524
  applySettings: action === "settings"
8320
8525
  });
8321
- return outcome.lines;
8526
+ return { lines: outcome.lines, files: outcome.files };
8322
8527
  },
8323
8528
  onManifestChange: (m) => writeManifest(manifestRoot, m)
8324
8529
  });
@@ -8438,7 +8643,7 @@ function formatDiff(d) {
8438
8643
  `Plan: ${d.current.plan}. Dollar figures are estimated current API-equivalent valuations, not money back, actual quota, or a promise of more work.`
8439
8644
  );
8440
8645
  }
8441
- const { resolved, appeared, changed } = d.fixes;
8646
+ const { resolved, appeared, changed: changed2 } = d.fixes;
8442
8647
  if (resolved.length > 0) {
8443
8648
  lines.push("");
8444
8649
  lines.push("Fixes resolved since the baseline:");
@@ -8449,10 +8654,10 @@ function formatDiff(d) {
8449
8654
  lines.push("New since the baseline:");
8450
8655
  for (const f of appeared) lines.push(` - [${usd7(f.wasteUsd)} estimated valuation] ${f.title}`);
8451
8656
  }
8452
- if (changed.length > 0) {
8657
+ if (changed2.length > 0) {
8453
8658
  lines.push("");
8454
8659
  lines.push("Fixes that moved:");
8455
- for (const c of changed) {
8660
+ for (const c of changed2) {
8456
8661
  lines.push(` - ${c.title}: ${usd7(c.beforeUsd)} -> ${usd7(c.afterUsd)} (${signedUsd(c.deltaUsd)} estimated valuation)`);
8457
8662
  }
8458
8663
  }
@@ -8564,7 +8769,7 @@ function parseApplyFlags(args) {
8564
8769
  };
8565
8770
  }
8566
8771
  function cliVersion() {
8567
- return true ? "0.15.0" : "0.0.0-dev";
8772
+ return true ? "0.16.1" : "0.0.0-dev";
8568
8773
  }
8569
8774
  function isHelpRequest(command, args) {
8570
8775
  if (command === void 0) return false;
@@ -8580,8 +8785,8 @@ function helpText() {
8580
8785
  " costclaw diff [<baseline.json> <current.json>] [--json]",
8581
8786
  " costclaw badge [--path <dir>] [--claude-md <file>] [--out <file>]",
8582
8787
  " costclaw optimize [--path <dir>] [--claude-md <file>] [--project <dir>] [--out <dir>] [--limit <n>] [--no-dashboard] [--no-serve] [--force]",
8583
- " costclaw apply [<dir>] [--remove] [--replace] [--apply-settings [file]] [--from <dir>] [--force]",
8584
- " costclaw apply --global [--replace] [--remove] [--from <dir>] [--force]",
8788
+ " costclaw apply [<dir>] [--remove] [--replace] [--apply-settings [file]] [--from <dir>]",
8789
+ " costclaw apply --global [--replace] [--remove] [--from <dir>]",
8585
8790
  " costclaw activate <license-key> [--name <machine-name>]",
8586
8791
  " costclaw deactivate",
8587
8792
  " costclaw --version",
@@ -8640,8 +8845,9 @@ function helpText() {
8640
8845
  "permissions.allow and permissions.deny, backs up the original, and prints a",
8641
8846
  "diff. --from <dir> points apply at a specific artifacts folder instead of",
8642
8847
  "looking one up by project; without it, apply finds artifacts from the last",
8643
- "optimize run, or generates them cold if none exist yet. --force allows",
8644
- "overwriting an existing .bak backup for --replace and --apply-settings.",
8848
+ "optimize run, or generates them cold if none exist yet. Anything apply",
8849
+ "overwrites is backed up first to <file>.bak-YYYYMMDD-HHMMSS, so every run",
8850
+ "keeps its own copy and no earlier backup is ever replaced.",
8645
8851
  "",
8646
8852
  "apply --global does the same for ~/.claude/CLAUDE.md, the one file loaded on",
8647
8853
  "every turn of every project. It writes the sections your audit earned to",
@@ -8762,8 +8968,7 @@ Run: costclaw optimize
8762
8968
  projectDir: flags.projectDir,
8763
8969
  mode: flags.mode,
8764
8970
  artifactsDir: globalDir,
8765
- global: true,
8766
- force: flags.force
8971
+ global: true
8767
8972
  });
8768
8973
  process.stdout.write(outcome2.lines.join("\n") + "\n");
8769
8974
  return;
@@ -8790,8 +8995,7 @@ Run: costclaw optimize
8790
8995
  mode: flags.mode,
8791
8996
  artifactsDir,
8792
8997
  applySettings: flags.applySettings,
8793
- applySettingsPath: flags.applySettingsPath,
8794
- force: flags.force
8998
+ applySettingsPath: flags.applySettingsPath
8795
8999
  });
8796
9000
  process.stdout.write(outcome.lines.join("\n") + "\n");
8797
9001
  if (flags.mode === "include") {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "costclaw",
3
- "version": "0.15.0",
3
+ "version": "0.16.1",
4
4
  "description": "Local Claude Code usage estimates, cache analysis, and rule-based setup checks. Your prompts stay on your machine.",
5
5
  "type": "module",
6
6
  "bin": {