costclaw 0.15.1 → 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 +257 -44
  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";
@@ -6048,6 +6048,12 @@ function ensureImportLine(claudeMd) {
6048
6048
  function stripImportLine(claudeMd) {
6049
6049
  return stripLine(claudeMd, IMPORT_LINE2);
6050
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
+ }
6051
6057
  async function runInclude(opts) {
6052
6058
  const { projectDir, artifactsDir } = opts;
6053
6059
  const includeSrc = join7(artifactsDir, INCLUDE_ARTIFACT);
@@ -6058,8 +6064,12 @@ async function runInclude(opts) {
6058
6064
  const claudeDir = join7(projectDir, ".claude");
6059
6065
  await mkdir4(claudeDir, { recursive: true });
6060
6066
  const includeDest = join7(projectDir, INCLUDE_REL);
6067
+ const includeBefore = await contentOrNull(includeDest);
6061
6068
  await writeFile4(includeDest, includeMd, "utf8");
6062
6069
  const wrote = [includeDest];
6070
+ const files = [];
6071
+ const includeChange = changed(includeDest, INCLUDE_REL, includeBefore, includeMd);
6072
+ if (includeChange) files.push(includeChange);
6063
6073
  const lines = [`Wrote ${INCLUDE_REL}`, ...describeIncludeSections(await readIncludeSections(artifactsDir))];
6064
6074
  const claudeMdPath = join7(projectDir, "CLAUDE.md");
6065
6075
  const existing = await pathExists(claudeMdPath) ? await readFile6(claudeMdPath, "utf8") : null;
@@ -6067,6 +6077,7 @@ async function runInclude(opts) {
6067
6077
  if (added) {
6068
6078
  await writeFile4(claudeMdPath, text2, "utf8");
6069
6079
  wrote.push(claudeMdPath);
6080
+ files.push({ path: claudeMdPath, label: "CLAUDE.md", before: existing, after: text2 });
6070
6081
  lines.push(`Added "${IMPORT_LINE2}" to CLAUDE.md`);
6071
6082
  } else {
6072
6083
  lines.push("CLAUDE.md already imports it");
@@ -6088,20 +6099,24 @@ async function runInclude(opts) {
6088
6099
  const settingsSrc = join7(artifactsDir, "settings.suggested.json");
6089
6100
  const suggestedJson = await readFile6(settingsSrc, "utf8");
6090
6101
  const target = opts.applySettingsPath ?? join7(projectDir, ".claude", "settings.json");
6091
- const settingsLines = await applyDerivedSettings(target, suggestedJson);
6092
- lines.push(...settingsLines);
6102
+ const settings = await applyDerivedSettings(target, suggestedJson);
6103
+ lines.push(...settings.lines);
6093
6104
  wrote.push(target);
6105
+ if (settings.file) files.push(settings.file);
6094
6106
  }
6095
- return { lines, wrote, removed: [] };
6107
+ return { lines, wrote, removed: [], files };
6096
6108
  }
6097
6109
  async function runRemove(opts) {
6098
6110
  const { projectDir } = opts;
6099
6111
  const includeDest = join7(projectDir, INCLUDE_REL);
6100
6112
  const companionDir = join7(projectDir, APPLY_DIR_REL);
6101
6113
  const removed = [];
6102
- if (await pathExists(includeDest)) {
6114
+ const files = [];
6115
+ const includeBefore = await contentOrNull(includeDest);
6116
+ if (includeBefore !== null) {
6103
6117
  await rm3(includeDest, { force: true });
6104
6118
  removed.push(includeDest);
6119
+ files.push({ path: includeDest, label: INCLUDE_REL, before: includeBefore, after: null });
6105
6120
  }
6106
6121
  if (await pathExists(companionDir)) {
6107
6122
  await rm3(companionDir, { recursive: true, force: true });
@@ -6116,14 +6131,16 @@ async function runRemove(opts) {
6116
6131
  if (text2 === "") {
6117
6132
  await rm3(claudeMdPath, { force: true });
6118
6133
  removed.push(claudeMdPath);
6134
+ files.push({ path: claudeMdPath, label: "CLAUDE.md", before: existing, after: null });
6119
6135
  lines.push("Removed CLAUDE.md (it held only the import line)");
6120
6136
  } else {
6121
6137
  await writeFile4(claudeMdPath, text2, "utf8");
6138
+ files.push({ path: claudeMdPath, label: "CLAUDE.md", before: existing, after: text2 });
6122
6139
  lines.push(`Removed "${IMPORT_LINE2}" from CLAUDE.md`);
6123
6140
  }
6124
6141
  }
6125
6142
  }
6126
- return { lines, wrote: [], removed };
6143
+ return { lines, wrote: [], removed, files };
6127
6144
  }
6128
6145
  async function runReplace(opts) {
6129
6146
  const { projectDir, artifactsDir } = opts;
@@ -6150,7 +6167,12 @@ async function runReplace(opts) {
6150
6167
  "",
6151
6168
  backup ? `Undo: git checkout -- CLAUDE.md (or restore ${backup})` : "Undo: git checkout -- CLAUDE.md"
6152
6169
  ];
6153
- return { lines, wrote: backup ? [claudeMdPath, backup] : [claudeMdPath], 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
+ };
6154
6176
  }
6155
6177
  async function runApply(opts) {
6156
6178
  if (opts.global) return runGlobal(opts);
@@ -6165,20 +6187,25 @@ async function runGlobal(opts) {
6165
6187
  if (opts.mode === "remove") {
6166
6188
  const removed = [];
6167
6189
  const lines2 = [];
6168
- if (await pathExists(includeDest)) {
6190
+ const files2 = [];
6191
+ const includeBefore = await contentOrNull(includeDest);
6192
+ if (includeBefore !== null) {
6169
6193
  await rm3(includeDest, { force: true });
6170
6194
  removed.push(includeDest);
6195
+ files2.push({ path: includeDest, label: GLOBAL_INCLUDE_REL, before: includeBefore, after: null });
6171
6196
  lines2.push(`Removed ${GLOBAL_INCLUDE_REL}`);
6172
6197
  }
6173
- if (await pathExists(claudeMdPath)) {
6174
- 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);
6175
6201
  if (didRemove) {
6176
6202
  await writeFile4(claudeMdPath, text2, "utf8");
6203
+ files2.push({ path: claudeMdPath, label: "~/.claude/CLAUDE.md", before: mdBefore, after: text2 });
6177
6204
  lines2.push(`Removed "${GLOBAL_IMPORT_LINE}" from ${claudeMdPath}`);
6178
6205
  }
6179
6206
  }
6180
6207
  if (lines2.length === 0) lines2.push("Nothing to remove: the global include was not applied.");
6181
- return { lines: lines2, wrote: [], removed };
6208
+ return { lines: lines2, wrote: [], removed, files: files2 };
6182
6209
  }
6183
6210
  const includeSrc = join7(opts.artifactsDir, GLOBAL_INCLUDE_ARTIFACT);
6184
6211
  const optimizedSrc = join7(opts.artifactsDir, GLOBAL_OPTIMIZED_ARTIFACT);
@@ -6192,10 +6219,15 @@ async function runGlobal(opts) {
6192
6219
  const backup = await backupFile(claudeMdPath);
6193
6220
  const wrote = [];
6194
6221
  const lines = [];
6222
+ const files = [];
6195
6223
  await mkdir4(dirname3(claudeMdPath), { recursive: true });
6196
6224
  if (hasInclude) {
6197
- 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");
6198
6228
  wrote.push(includeDest);
6229
+ const c = changed(includeDest, GLOBAL_INCLUDE_REL, includeBefore, includeAfter);
6230
+ if (c) files.push(c);
6199
6231
  lines.push(`Wrote ${GLOBAL_INCLUDE_REL}`);
6200
6232
  } else {
6201
6233
  lines.push("Your audit produced no global sections to add, so no include file was written.");
@@ -6211,6 +6243,7 @@ async function runGlobal(opts) {
6211
6243
  }
6212
6244
  await writeFile4(claudeMdPath, optimized, "utf8");
6213
6245
  wrote.push(claudeMdPath);
6246
+ files.push({ path: claudeMdPath, label: "~/.claude/CLAUDE.md", before: original, after: optimized });
6214
6247
  lines.push(
6215
6248
  `Rewrote ${claudeMdPath} with every reviewed removal applied`,
6216
6249
  "",
@@ -6222,6 +6255,7 @@ async function runGlobal(opts) {
6222
6255
  if (added) {
6223
6256
  await writeFile4(claudeMdPath, text2, "utf8");
6224
6257
  wrote.push(claudeMdPath);
6258
+ files.push({ path: claudeMdPath, label: "~/.claude/CLAUDE.md", before: original, after: text2 });
6225
6259
  lines.push(`Added "${GLOBAL_IMPORT_LINE}" to ${claudeMdPath}`);
6226
6260
  } else {
6227
6261
  lines.push("Your global CLAUDE.md already imports it");
@@ -6232,7 +6266,7 @@ async function runGlobal(opts) {
6232
6266
  }
6233
6267
  if (backup) lines.push(`Backed up the original to ${backup}`);
6234
6268
  lines.push("Undo: costclaw apply --global --remove");
6235
- return { lines, wrote, removed: [] };
6269
+ return { lines, wrote, removed: [], files };
6236
6270
  }
6237
6271
  function lineDiff(oldText, newText) {
6238
6272
  const oldLines = oldText.split(/\r?\n/);
@@ -6306,14 +6340,91 @@ async function applyDerivedSettings(target, suggestedJson) {
6306
6340
  await mkdir4(dirname3(target), { recursive: true });
6307
6341
  const backup = await backupFile(target);
6308
6342
  await writeFile4(target, mergedText, "utf8");
6309
- return [
6310
- `Merged the derived permission allowlist into ${target}`,
6311
- ...backup ? [`Backed up the previous file to ${backup}`] : [],
6312
- "Only permissions.allow and permissions.deny changed (deduped union, existing entries kept and ordered first). Every other key was left as it was.",
6313
- "",
6314
- "Diff (previous vs merged):",
6315
- lineDiff(existingText, mergedText)
6316
- ];
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;
6317
6428
  }
6318
6429
 
6319
6430
  // src/optimize-dashboard.ts
@@ -6403,6 +6514,30 @@ ul.warn b{font-weight:650}
6403
6514
  .file a{margin-top:auto;font-size:.83rem;color:var(--ink);text-decoration:none;border-bottom:1px solid var(--line);
6404
6515
  align-self:flex-start;padding-bottom:1px}
6405
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}
6406
6541
  .cta{background:var(--panel);border:1px solid var(--line);border-left:3px solid var(--good);
6407
6542
  border-radius:10px;padding:18px 20px}
6408
6543
  code.cmd{display:block;font-family:var(--mono);font-size:.86rem;background:color-mix(in srgb,var(--ink) 6%,transparent);
@@ -6685,12 +6820,24 @@ var PLAYBOOK_NAME = "PLAYBOOK.md";
6685
6820
  var SETTINGS_NAME = "settings.suggested.json";
6686
6821
  var HARNESS_NAME = "HARNESS-UPGRADE.md";
6687
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
+ }
6688
6835
  function renderArtifactCards(input) {
6689
6836
  const { before, after } = input.claudeMdTokens;
6690
6837
  const lighter = before !== null && after < before ? ` and ${fmtTokens(before - after)} tokens lighter` : "";
6691
6838
  const placeholders = `${input.placeholdersRemaining} ${plural2(input.placeholdersRemaining, "placeholder")} to fill.`;
6692
6839
  const claudeDesc = before === null ? `A new CLAUDE.md scaffold for your project. ${placeholders}` : `Your CLAUDE.md, restructured${lighter}. ${placeholders}`;
6693
- 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]);
6694
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(
6695
6842
  INCLUDE_NAME,
6696
6843
  "The generated sections as a standalone include. apply writes it to .claude/costclaw.md and adds one @ line to your CLAUDE.md."
@@ -6912,7 +7059,66 @@ td code.cmd{margin-top:0;font-size:.78rem;white-space:pre-wrap;word-break:break-
6912
7059
  .state{font-size:.82rem}
6913
7060
  .state.on{color:var(--good);font-weight:650}
6914
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}
6915
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
+ }
6916
7122
  function indexTokens(tokens) {
6917
7123
  if (tokens.before === null) return `${esc(approxTokens(tokens.after))} (new file)`;
6918
7124
  return `${esc(approxTokens(tokens.before))} to ${esc(approxTokens(tokens.after))}`;
@@ -6968,9 +7174,7 @@ function renderOptimizeIndex(input) {
6968
7174
  // a run, and this card carries it when a previous session left files behind.
6969
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>` : "";
6970
7176
  const run = priorRun;
6971
- const changed = run ? `<h2>What changed<span class="n">${run.reverted ? "reverted" : "written just now"}</span></h2><div class="panel changed">` + run.changes.map(
6972
- (c) => `<div class="chg"><b>${esc(c.slug)}</b><ul>` + c.lines.map((l) => `<li>${esc(l)}</li>`).join("") + `</ul></div>`
6973
- ).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>` : "";
6974
7178
  const banner = input.serve?.message ? `<p class="banner">${esc(input.serve.message)}</p>` : "";
6975
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>` : "";
6976
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>`;
@@ -6993,7 +7197,7 @@ artifacts in ${esc(input.root)}/</p></header>
6993
7197
  ${banner}${done}
6994
7198
  ${serve ? `<form method="post" action="/apply">
6995
7199
  <input type="hidden" name="token" value="${esc(serve.token)}">` : ""}
6996
- ${changed}
7200
+ ${changed2}
6997
7201
  ${oneButton}
6998
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>
6999
7203
  ${renderStartHere(input.review, input.rows.length)}` : ""}
@@ -7018,7 +7222,7 @@ Nothing was written inside any project. No network calls, no telemetry, no model
7018
7222
 
7019
7223
  // src/project-scan.ts
7020
7224
  import { readdir as readdir3, readFile as readFile7, stat as stat2 } from "fs/promises";
7021
- import { join as join8, basename as basename2 } from "path";
7225
+ import { join as join8, basename as basename3 } from "path";
7022
7226
  var NOISE_DIRS = /* @__PURE__ */ new Set([
7023
7227
  "node_modules",
7024
7228
  ".git",
@@ -7492,7 +7696,7 @@ function parseReadme(text2) {
7492
7696
  return { name, description };
7493
7697
  }
7494
7698
  async function scanProject(dir) {
7495
- const profile = emptyProfile(basename2(dir));
7699
+ const profile = emptyProfile(basename3(dir));
7496
7700
  const { files, dirs } = await listEntries(dir);
7497
7701
  if (files.includes("package.json")) {
7498
7702
  const pkg = parseJson(await readText(join8(dir, "package.json")));
@@ -7515,13 +7719,13 @@ async function scanProject(dir) {
7515
7719
  }
7516
7720
  }
7517
7721
  }
7518
- if (profile.description === null || profile.name === basename2(dir)) {
7722
+ if (profile.description === null || profile.name === basename3(dir)) {
7519
7723
  const readmeName = files.find((f) => /^readme(\.md|\.markdown|\.txt)?$/i.test(f));
7520
7724
  if (readmeName) {
7521
7725
  const text2 = await readText(join8(dir, readmeName));
7522
7726
  if (text2 !== null) {
7523
7727
  const parsed = parseReadme(text2);
7524
- 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;
7525
7729
  if (profile.description === null && parsed.description !== null) {
7526
7730
  profile.description = parsed.description;
7527
7731
  }
@@ -7720,7 +7924,7 @@ async function startApplyServer(opts) {
7720
7924
  const errors = [];
7721
7925
  for (const { entry, action } of targets) {
7722
7926
  try {
7723
- const lines = await opts.apply(entry, action);
7927
+ const { lines, files } = await opts.apply(entry, action);
7724
7928
  if (action === "remove") {
7725
7929
  delete entry.appliedAt;
7726
7930
  delete entry.appliedMode;
@@ -7728,11 +7932,11 @@ async function startApplyServer(opts) {
7728
7932
  entry.appliedAt = (/* @__PURE__ */ new Date()).toISOString();
7729
7933
  entry.appliedMode = action;
7730
7934
  }
7731
- changes.push({ slug: entry.slug, lines });
7935
+ changes.push({ slug: entry.slug, lines, files });
7732
7936
  } catch (err) {
7733
7937
  const text2 = `Error: ${err instanceof Error ? err.message : String(err)}`;
7734
7938
  errors.push(text2);
7735
- changes.push({ slug: entry.slug, lines: [text2] });
7939
+ changes.push({ slug: entry.slug, lines: [text2], files: [] });
7736
7940
  }
7737
7941
  }
7738
7942
  if (opts.onManifestChange) await opts.onManifestChange(manifest);
@@ -7933,7 +8137,7 @@ function projectRecoverable(report, slug) {
7933
8137
  return row ? row.usd : null;
7934
8138
  }
7935
8139
  async function generateForProject(ctx, projectDir, artifactsDir) {
7936
- const slug = basename3(resolve6(projectDir));
8140
+ const slug = basename4(resolve6(projectDir));
7937
8141
  let currentClaudeMd = ctx.claudeMdOverride;
7938
8142
  let claudeMdSource = ctx.claudeMdOverride !== void 0 ? ctx.claudeMdFallbackSource : null;
7939
8143
  if (currentClaudeMd === void 0) {
@@ -7993,7 +8197,16 @@ async function generateForProject(ctx, projectDir, artifactsDir) {
7993
8197
  headlineWasteShare: auditSpend > 0 ? auditRecoverable2 / auditSpend : 0,
7994
8198
  headlineWasteUsd: auditRecoverable2,
7995
8199
  applyCommand,
7996
- 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
+ }
7997
8210
  });
7998
8211
  await writeFile6(join10(artifactsDir, DASHBOARD_NAME2), html, "utf8");
7999
8212
  }
@@ -8050,7 +8263,7 @@ async function generateForProject(ctx, projectDir, artifactsDir) {
8050
8263
  return {
8051
8264
  entry: {
8052
8265
  slug,
8053
- dir: basename3(artifactsDir),
8266
+ dir: basename4(artifactsDir),
8054
8267
  projectDir,
8055
8268
  artifactsDir,
8056
8269
  spendUsd: spend ?? 0,
@@ -8310,7 +8523,7 @@ async function runOptimize(opts) {
8310
8523
  artifactsDir: entry.artifactsDir,
8311
8524
  applySettings: action === "settings"
8312
8525
  });
8313
- return outcome.lines;
8526
+ return { lines: outcome.lines, files: outcome.files };
8314
8527
  },
8315
8528
  onManifestChange: (m) => writeManifest(manifestRoot, m)
8316
8529
  });
@@ -8430,7 +8643,7 @@ function formatDiff(d) {
8430
8643
  `Plan: ${d.current.plan}. Dollar figures are estimated current API-equivalent valuations, not money back, actual quota, or a promise of more work.`
8431
8644
  );
8432
8645
  }
8433
- const { resolved, appeared, changed } = d.fixes;
8646
+ const { resolved, appeared, changed: changed2 } = d.fixes;
8434
8647
  if (resolved.length > 0) {
8435
8648
  lines.push("");
8436
8649
  lines.push("Fixes resolved since the baseline:");
@@ -8441,10 +8654,10 @@ function formatDiff(d) {
8441
8654
  lines.push("New since the baseline:");
8442
8655
  for (const f of appeared) lines.push(` - [${usd7(f.wasteUsd)} estimated valuation] ${f.title}`);
8443
8656
  }
8444
- if (changed.length > 0) {
8657
+ if (changed2.length > 0) {
8445
8658
  lines.push("");
8446
8659
  lines.push("Fixes that moved:");
8447
- for (const c of changed) {
8660
+ for (const c of changed2) {
8448
8661
  lines.push(` - ${c.title}: ${usd7(c.beforeUsd)} -> ${usd7(c.afterUsd)} (${signedUsd(c.deltaUsd)} estimated valuation)`);
8449
8662
  }
8450
8663
  }
@@ -8556,7 +8769,7 @@ function parseApplyFlags(args) {
8556
8769
  };
8557
8770
  }
8558
8771
  function cliVersion() {
8559
- return true ? "0.15.1" : "0.0.0-dev";
8772
+ return true ? "0.16.1" : "0.0.0-dev";
8560
8773
  }
8561
8774
  function isHelpRequest(command, args) {
8562
8775
  if (command === void 0) return false;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "costclaw",
3
- "version": "0.15.1",
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": {