costclaw 0.16.2 → 0.17.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 +29 -8
  2. package/dist/index.js +805 -598
  3. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -281,27 +281,7 @@ function sanitizeText(input) {
281
281
  return out;
282
282
  }
283
283
 
284
- // ../../packages/engine/src/parser.ts
285
- function safeParse(line) {
286
- try {
287
- return JSON.parse(line);
288
- } catch {
289
- return null;
290
- }
291
- }
292
- function usageKey(rec, seq) {
293
- const requestId = rec.requestId || rec.message?.requestId;
294
- if (requestId) return `req:${requestId}`;
295
- const messageId = rec.message?.id;
296
- if (messageId) return `msg:${messageId}`;
297
- if (rec.uuid) return `row:${rec.uuid}`;
298
- return `row:#${seq}`;
299
- }
300
- function projectFromCwd(cwd) {
301
- if (!cwd) return null;
302
- const parts = cwd.split(/[\\/]+/).filter(Boolean);
303
- return parts.length ? parts[parts.length - 1] : null;
304
- }
284
+ // ../../packages/engine/src/targets.ts
305
285
  function commandTarget(command) {
306
286
  let s = command.trim();
307
287
  const hop = /^(?:cd|Set-Location|pushd)\s+(?:"[^"]*"|'[^']*'|\S+)\s*(?:&&|;)\s*/i;
@@ -327,6 +307,28 @@ function targetFor(name, input) {
327
307
  if (name === "Agent") return s(input.subagent_type ?? input.description, 60);
328
308
  return null;
329
309
  }
310
+
311
+ // ../../packages/engine/src/parser.ts
312
+ function safeParse(line) {
313
+ try {
314
+ return JSON.parse(line);
315
+ } catch {
316
+ return null;
317
+ }
318
+ }
319
+ function usageKey(rec, seq) {
320
+ const requestId = rec.requestId || rec.message?.requestId;
321
+ if (requestId) return `req:${requestId}`;
322
+ const messageId = rec.message?.id;
323
+ if (messageId) return `msg:${messageId}`;
324
+ if (rec.uuid) return `row:${rec.uuid}`;
325
+ return `row:#${seq}`;
326
+ }
327
+ function projectFromCwd(cwd) {
328
+ if (!cwd) return null;
329
+ const parts = cwd.split(/[\\/]+/).filter(Boolean);
330
+ return parts.length ? parts[parts.length - 1] : null;
331
+ }
330
332
  var PLAN_TOOLS = /* @__PURE__ */ new Set(["EnterPlanMode", "ExitPlanMode", "TodoWrite", "TaskCreate", "Skill", "Workflow"]);
331
333
  var VERIFY_RE = /^(?:(?:npm|pnpm|yarn|bun|deno|npx|python3?|py|make|dotnet|mvn|gradle|cargo|go)(?:\s+\S+)*?\s+(?:test|tests|vitest|jest|pytest|typecheck|tsc|lint|build|check|verify|clippy|vet)(?:[:\s]|$)|(?:pytest|tsc|vitest|jest|eslint|ruff|mypy|golangci-lint)(?:\s|$))/i;
332
334
  var CORRECTION_RE = /^(?:no[,.!\s]|nope\b|wrong\b|that'?s (?:not|wrong)|not what i|undo\b|revert\b|stop\b|don'?t\b|why did you|you broke|still (?:broken|failing|wrong|not))/i;
@@ -4781,144 +4783,82 @@ function ansi(enabled) {
4781
4783
  };
4782
4784
  }
4783
4785
 
4784
- // src/format.ts
4785
- function sinceOptimizeLine(meta) {
4786
- const so = meta.sinceOptimize;
4787
- if (!so) return null;
4788
- if (!so.result.comparable) {
4789
- if (so.result.reason === "accounting method changed") {
4790
- return `Since optimize (${so.at.slice(0, 10)}): comparison withheld because the accounting method changed. Run optimize again to set a new baseline.`;
4791
- }
4792
- if (so.result.reason === "pricing changed") {
4793
- return `Since optimize (${so.at.slice(0, 10)}): comparison withheld because the pricing snapshot changed. Run optimize again to set a new baseline.`;
4794
- }
4795
- return null;
4796
- }
4797
- const r = so.result;
4798
- const date = so.at.slice(0, 10);
4799
- const move = `${(r.baselineCacheHitRate * 100).toFixed(1)}% -> ${(r.periodCacheHitRate * 100).toFixed(1)}%`;
4800
- const worth = r.recoveredUsd >= 0.01 ? `; estimated current Sonnet-rate valuation ${usd2(r.recoveredUsd)}` : "";
4801
- return `Since optimize (${date}): cache hit ${move} on new usage${worth}.`;
4802
- }
4803
- function usd2(n) {
4804
- return `$${roundMoneyHalfUp(n).toFixed(2)}`;
4805
- }
4806
- var BURN_DAY_NAMES = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
4807
- var BURN_DAY_ORDER = [1, 2, 3, 4, 5, 6, 0];
4808
- var BURN_QUARTER_NAMES = ["night", "morning", "afternoon", "evening"];
4809
- function burnSlotLabel(day2, quarter) {
4810
- return `${BURN_DAY_NAMES[day2]} ${BURN_QUARTER_NAMES[quarter]}`;
4811
- }
4812
- function burnClockSentence(bc) {
4813
- const spendDays = bc.byDay.filter((v) => v > 0);
4814
- if (spendDays.length === 0) return null;
4815
- let topDay = 0;
4816
- for (let d = 0; d < bc.byDay.length; d += 1) {
4817
- if ((bc.byDay[d] ?? 0) > (bc.byDay[topDay] ?? 0)) topDay = d;
4818
- }
4819
- const topUsd = bc.byDay[topDay] ?? 0;
4820
- const average = spendDays.reduce((sum, v) => sum + v, 0) / spendDays.length;
4821
- let sentence = `${BURN_DAY_NAMES[topDay]} is your most expensive day (${usd2(topUsd)})`;
4822
- if (spendDays.length >= 2 && average > 0) {
4823
- sentence += `, about ${(topUsd / average).toFixed(1)}x an average day across ${bc.activeDays} active days`;
4824
- }
4825
- sentence += ".";
4826
- const top = bc.topSlot;
4827
- if (top) sentence += ` Peak stretch: ${burnSlotLabel(top.day, top.quarter)}.`;
4828
- return sentence;
4829
- }
4830
- var WRAP_WIDTH = 92;
4831
- function wrapLines(text2, indent = 0) {
4832
- const pad = " ".repeat(indent);
4833
- const words = text2.split(/\s+/).filter((w) => w.length > 0);
4834
- const out = [];
4835
- let line = "";
4836
- for (const word of words) {
4837
- const candidate = line.length > 0 ? `${line} ${word}` : word;
4838
- if (line.length > 0 && pad.length + candidate.length > WRAP_WIDTH) {
4839
- out.push(pad + line);
4840
- line = word;
4841
- } else {
4842
- line = candidate;
4843
- }
4844
- }
4845
- if (line.length > 0) out.push(pad + line);
4846
- if (out.length < 2) return out.length > 0 ? out : [pad];
4847
- const last = (out[out.length - 1] ?? "").trim();
4848
- const prevWords = (out[out.length - 2] ?? "").trim().split(" ");
4849
- const borrowed = prevWords[prevWords.length - 1];
4850
- if (borrowed !== void 0 && prevWords.length >= 3 && !last.includes(" ") && pad.length + borrowed.length + 1 + last.length <= WRAP_WIDTH) {
4851
- out[out.length - 2] = pad + prevWords.slice(0, -1).join(" ");
4852
- out[out.length - 1] = `${pad}${borrowed} ${last}`;
4853
- }
4854
- return out;
4855
- }
4856
- function pushProse(lines, text2, indent = 0, style = (s) => s) {
4857
- for (const line of wrapLines(text2, indent)) lines.push(style(line));
4786
+ // src/svg.ts
4787
+ var SYSTEM_FONT = "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif";
4788
+ function esc(s) {
4789
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
4858
4790
  }
4859
- function plural(n, noun) {
4860
- return n === 1 ? noun : `${noun}s`;
4791
+ function bandColorForScore(score) {
4792
+ if (score < 40) return "#c0392b";
4793
+ if (score < 60) return "#e07a5f";
4794
+ if (score < 75) return "#d99a2b";
4795
+ if (score < 90) return "#5f8f4f";
4796
+ return "#3f7d4e";
4861
4797
  }
4862
- function statRows(rows, a) {
4863
- const plain = (c) => `${c.k}: ${c.v}`;
4864
- const leadWidth = Math.max(...rows.map((r) => r[0] ? plain(r[0]).length : 0));
4865
- const gap = " ";
4866
- return rows.map(
4867
- (row) => row.map((c, i) => {
4868
- const styled = `${a.dim(c.k + ":")} ${a.bold(c.v)}`;
4869
- const padding = i === 0 ? Math.max(0, leadWidth - plain(c).length) : 0;
4870
- return styled + " ".repeat(padding);
4871
- }).join(gap).trimEnd()
4872
- );
4798
+ function rect(x, y, w, h, fill, rx = 0) {
4799
+ return `<rect x="${x}" y="${y}" width="${w}" height="${h}" rx="${rx}" fill="${fill}"></rect>`;
4873
4800
  }
4874
- function bar(score, a, width = 20) {
4875
- if (score === null) return a.dim("n/a");
4876
- const filled = Math.round(score / 100 * width);
4877
- return `[${a.score(score, "#".repeat(filled))}${a.dim(".".repeat(width - filled))}] ${a.bold(String(score))}`;
4801
+ function text(x, y, s, opts = {}) {
4802
+ const size = opts.size ?? 13;
4803
+ const weight = opts.weight ?? 400;
4804
+ const fill = opts.fill ?? "#251d1a";
4805
+ const anchor = opts.anchor ?? "start";
4806
+ return `<text x="${x}" y="${y}" font-family="${SYSTEM_FONT}" font-size="${size}" font-weight="${weight}" fill="${fill}" text-anchor="${anchor}">${esc(s)}</text>`;
4878
4807
  }
4879
- function shortModel(id) {
4880
- const m = /(opus|sonnet|haiku|fable)/i.exec(id);
4881
- return m && m[1] ? m[1].toLowerCase() : id;
4808
+ function estimateTextWidth(s, size) {
4809
+ return Math.round(s.length * size * 0.62);
4882
4810
  }
4883
- function unknownModelNote(breakdown) {
4884
- const unknown = Object.keys(breakdown).filter((model) => !isKnownModel(model));
4885
- return unknown.length > 0 ? `Models missing from the rate card: ${unknown.join(", ")}. Their current API-equivalent valuation is approximate.` : null;
4811
+
4812
+ // src/html-report.ts
4813
+ function usd2(n) {
4814
+ return `$${roundMoneyHalfUp(n).toFixed(2)}`;
4886
4815
  }
4887
- function accuracyNotes(record) {
4888
- const accuracy = record.usageMetrics.accuracy;
4889
- if (!accuracy) {
4890
- return [unknownModelNote(record.usageMetrics.modelBreakdown)].filter((note) => note !== null);
4891
- }
4892
- const notes = [...accuracy.warnings];
4893
- if (accuracy.unknownModels.length > 0) {
4894
- const models = accuracy.unknownModels.map(({ model, requests }) => `${model} (${requests} ${plural(requests, "request")})`).join(", ");
4895
- notes.push(`Models missing from the rate card: ${models}. Their current API-equivalent valuation is approximate.`);
4896
- }
4897
- return [...new Set(notes)];
4816
+ function truncate(s, max) {
4817
+ return s.length > max ? s.slice(0, max - 3) + "..." : s;
4898
4818
  }
4899
- function modelMix(breakdown) {
4900
- const merged = /* @__PURE__ */ new Map();
4901
- for (const [model, spend] of Object.entries(breakdown)) {
4902
- if (spend <= 0) continue;
4903
- const key = shortModel(model);
4904
- merged.set(key, (merged.get(key) ?? 0) + spend);
4819
+ function projectChart(projects) {
4820
+ if (projects.length === 0) {
4821
+ return `<p class="muted">No project valuation estimate to chart.</p>`;
4905
4822
  }
4906
- const total = [...merged.values()].reduce((a, b) => a + b, 0);
4907
- if (total <= 0) return null;
4908
- const parts = [...merged.entries()].sort((a, b) => b[1] - a[1]).map(([name, spend]) => [name, Math.round(spend / total * 100)]).filter(([, pct2]) => pct2 >= 1).map(([name, pct2]) => `${name} ${pct2}%`);
4909
- return parts.length > 0 ? parts.join(" / ") : null;
4823
+ const rowH = 28;
4824
+ const gap = 8;
4825
+ const labelW = 200;
4826
+ const valW = 90;
4827
+ const barMax = 400;
4828
+ const barH = 14;
4829
+ const width = labelW + barMax + valW;
4830
+ const height = projects.length * (rowH + gap) - gap;
4831
+ const maxCost = Math.max(...projects.map((p) => p.costUsd), 0.01);
4832
+ const rows = projects.map((p, i) => {
4833
+ const y = i * (rowH + gap);
4834
+ const w = Math.max(barH, Math.round(p.costUsd / maxCost * barMax));
4835
+ const mid = y + rowH / 2;
4836
+ const barY = mid - barH / 2;
4837
+ const label = esc(truncate(p.slug, 30));
4838
+ return `<text x="0" y="${mid}" class="c-lbl" dominant-baseline="middle">${label}</text><rect x="${labelW}" y="${barY}" width="${barMax}" height="${barH}" rx="${barH / 2}" fill="#f5ece6"></rect><rect x="${labelW}" y="${barY}" width="${w}" height="${barH}" rx="${barH / 2}" fill="#e07a5f"></rect><text x="${width}" y="${mid}" class="c-val" text-anchor="end" dominant-baseline="middle">${esc(usd2(p.costUsd))}</text>`;
4839
+ }).join("");
4840
+ return `<svg viewBox="0 0 ${width} ${height}" width="100%" height="${height}" role="img" aria-label="Top projects by estimated current API-equivalent valuation" preserveAspectRatio="xMinYMin meet">${rows}</svg>`;
4910
4841
  }
4911
- function unassessedLine(pillars) {
4912
- const gaps = pillars.filter((p) => !p.assessed);
4913
- if (gaps.length === 0) return null;
4914
- const parts = gaps.map((p) => {
4915
- const reason = p.checks.find((c) => !c.assessed)?.basis;
4916
- const hint = p.id === "claude_md" ? " Pass --claude-md <file> to score it." : "";
4917
- const partial = p.checks.filter((c) => c.assessed && c.score !== null).map((c) => `${c.label} alone scores ${c.score}`).join(", ");
4918
- const tail = partial ? ` ${partial}.` : "";
4919
- return reason ? `${p.name} (${reason}${hint}${tail})` : p.name;
4920
- });
4921
- return `Not yet scored: ${parts.join(" ")}`;
4842
+ function burnClockChart(bc) {
4843
+ const rowH = 22;
4844
+ const gap = 6;
4845
+ const labelW = 90;
4846
+ const valW = 70;
4847
+ const barMax = 300;
4848
+ const barH = 12;
4849
+ const width = labelW + barMax + valW;
4850
+ const height = BURN_DAY_ORDER.length * (rowH + gap) - gap;
4851
+ const max = Math.max(...bc.byDay, 0.01);
4852
+ const rows = BURN_DAY_ORDER.map((day2, i) => {
4853
+ const y = i * (rowH + gap);
4854
+ const v = bc.byDay[day2];
4855
+ const w = Math.max(barH, Math.round(v / max * barMax));
4856
+ const mid = y + rowH / 2;
4857
+ const barY = mid - barH / 2;
4858
+ const label = esc(BURN_DAY_NAMES[day2]);
4859
+ return `<text x="0" y="${mid}" class="c-lbl" dominant-baseline="middle">${label}</text><rect x="${labelW}" y="${barY}" width="${barMax}" height="${barH}" rx="${barH / 2}" fill="#f5ece6"></rect><rect x="${labelW}" y="${barY}" width="${w}" height="${barH}" rx="${barH / 2}" fill="#e07a5f"></rect><text x="${width}" y="${mid}" class="c-val" text-anchor="end" dominant-baseline="middle">${esc(usd2(v))}</text>`;
4860
+ }).join("");
4861
+ return `<svg viewBox="0 0 ${width} ${height}" width="100%" height="${height}" role="img" aria-label="Estimated current API-equivalent valuation by day of week" preserveAspectRatio="xMinYMin meet">${rows}</svg>`;
4922
4862
  }
4923
4863
  function weakestGap(p) {
4924
4864
  let worst = null;
@@ -4928,251 +4868,6 @@ function weakestGap(p) {
4928
4868
  }
4929
4869
  return worst;
4930
4870
  }
4931
- function formatAudit(record, meta, color = false) {
4932
- const a = ansi(color);
4933
- const m = record.usageMetrics;
4934
- const subscription = record.plan !== void 0 && record.plan !== "api";
4935
- const reportedShare = record.headlineWasteShare ?? (m.spendUsd > 0 ? record.headlineWasteUsd / m.spendUsd : 0);
4936
- const shareIsValid = Number.isFinite(reportedShare) && reportedShare >= 0 && reportedShare <= 1;
4937
- const shareText = shareIsValid ? `${(reportedShare * 100).toFixed(1)}%` : "unavailable";
4938
- const lines = [];
4939
- lines.push(a.bold("CostClaw audit"));
4940
- const delegated = m.delegatedSessionsCount ?? 0;
4941
- pushProse(
4942
- lines,
4943
- `Source: ${meta.root} (${m.sessionsCount} ${plural(m.sessionsCount, "session")}${delegated > 0 ? ` +${delegated} delegated` : ""} across ${m.projectsCount} ${plural(m.projectsCount, "project")})`,
4944
- 0,
4945
- a.dim
4946
- );
4947
- if (meta.claudeMdSource) pushProse(lines, `CLAUDE.md: ${meta.claudeMdSource}`, 0, a.dim);
4948
- lines.push(a.dim("-".repeat(WRAP_WIDTH)));
4949
- lines.push("");
4950
- lines.push(
4951
- subscription ? `${a.bold(record.headlineWasteLabel + ":")} ${a.brand(shareText + " of analyzed token value")} (${usd2(record.headlineWasteUsd)} API-equivalent)` : `${a.bold(record.headlineWasteLabel + ":")} ${a.brand(usd2(record.headlineWasteUsd))}`
4952
- );
4953
- if (record.verdict) {
4954
- lines.push("");
4955
- pushProse(lines, record.verdict);
4956
- }
4957
- const receipt = sinceOptimizeLine(meta);
4958
- if (receipt) pushProse(lines, receipt, 0, a.dim);
4959
- lines.push("");
4960
- const mix = modelMix(m.modelBreakdown);
4961
- const statBlock = [
4962
- [
4963
- { k: "Current API-equivalent valuation (estimate)", v: usd2(m.spendUsd) },
4964
- { k: "Cache hit", v: `${(m.cacheHitRate * 100).toFixed(1)}%` },
4965
- { k: "Session hours (timestamp union)", v: m.durationHours.toFixed(1) }
4966
- ],
4967
- [
4968
- { k: "Pricing snapshot", v: m.pricingSnapshotDate },
4969
- ...mix ? [{ k: "Model spend", v: mix }] : []
4970
- ],
4971
- // Named explicitly because this figure used to sit inside the headline as
4972
- // if it were waste. It is the cache paying for itself.
4973
- ...record.cacheWriteCostUsd != null && record.cacheWriteCostUsd > 0 ? [[{ k: "Cache writes that earned their reads (working cost, not waste)", v: usd2(record.cacheWriteCostUsd) }]] : []
4974
- ];
4975
- for (const row of statRows(statBlock, a)) lines.push(row);
4976
- const cautions = accuracyNotes(record);
4977
- if (cautions.length === 1) pushProse(lines, `Pricing caution: ${cautions[0]}`, 0, a.dim);
4978
- else if (cautions.length > 1) {
4979
- pushProse(lines, `Pricing caution: ${cautions[0]} (${cautions.length - 1} more in --json)`, 0, a.dim);
4980
- }
4981
- if (!shareIsValid) pushProse(lines, "Pricing caution: this legacy record has an invalid recoverable-waste share; its percentage is unavailable.", 0, a.dim);
4982
- const w = record.usageWindows;
4983
- if (subscription) {
4984
- lines.push("");
4985
- pushProse(
4986
- lines,
4987
- `Plan: ${record.plan}. Dollar figures are estimated current API-equivalent valuations, not money back, actual quota, or a promise of more work. Recoverable waste is a counterfactual: a session's first turn has no cache to read from.`,
4988
- 0,
4989
- a.dim
4990
- );
4991
- if (w?.assessed) {
4992
- lines.push(
4993
- `${a.dim("Usage windows (estimated current API-equivalent valuation):")} median ${a.bold(usd2(w.medianWindowUsd))}, 90th percentile ${a.bold(usd2(w.p90WindowUsd))}, busiest (maximum) ${a.bold(usd2(w.maxWindowUsd))}`
4994
- );
4995
- lines.push(`${a.dim("Busiest week:")} ${a.bold(usd2(w.maxWeekUsd))} ${a.dim("(estimated current API-equivalent valuation)")}`);
4996
- lines.push(`${a.dim("Activity signal:")} 15-minute activity bins, not measured work time.`);
4997
- }
4998
- } else if (meta.planSource === "default") {
4999
- const burn = w?.assessed && w.medianWeekUsd >= 50 ? ` Median weekly estimated current API-equivalent valuation: ${usd2(w.medianWeekUsd)}.` : "";
5000
- lines.push("");
5001
- pushProse(lines, `Dollar figures are estimated current API-equivalent valuations.${burn}`, 0, a.dim);
5002
- pushProse(
5003
- lines,
5004
- "On a Claude subscription? Rerun with --plan max20x (or pro, max5x) to frame results as token efficiency.",
5005
- 0,
5006
- a.dim
5007
- );
5008
- }
5009
- if (m.topProjects.length > 0) {
5010
- lines.push("");
5011
- lines.push(a.bold("Top projects by estimated current API-equivalent valuation:"));
5012
- for (const p of m.topProjects.slice(0, 5)) {
5013
- const name = p.slug.length > 30 ? p.slug.slice(0, 27) + "..." : p.slug;
5014
- const model = p.modelPrimary ? shortModel(p.modelPrimary) : "n/a";
5015
- const sessions = `${String(p.sessionsCount).padStart(4)} ${plural(p.sessionsCount, "session")}`;
5016
- const cache = `cache ${(p.cacheHitRate * 100).toFixed(1)}%`;
5017
- lines.push(
5018
- ` ${name.padEnd(32)}${a.bold(usd2(p.costUsd).padStart(10))} ${sessions.padEnd(16)}${a.dim(`${cache.padEnd(15)}${model}`)}`
5019
- );
5020
- }
5021
- }
5022
- const bc = record.burnClock;
5023
- if (bc?.assessed) {
5024
- lines.push("");
5025
- lines.push(a.bold("Burn Clock (estimated current API-equivalent valuation by day):"));
5026
- const max = Math.max(...bc.byDay, 0.01);
5027
- for (const day2 of BURN_DAY_ORDER) {
5028
- const v = bc.byDay[day2];
5029
- const filled = Math.round(v / max * 20);
5030
- const barStr = `[${a.brand("#".repeat(filled))}${a.dim(".".repeat(20 - filled))}]`;
5031
- lines.push(` ${BURN_DAY_NAMES[day2].padEnd(10)} ${barStr} ${a.bold(usd2(v).padStart(9))}`);
5032
- }
5033
- const sentence = burnClockSentence(bc);
5034
- if (sentence) {
5035
- lines.push("");
5036
- pushProse(lines, sentence);
5037
- }
5038
- }
5039
- lines.push("");
5040
- lines.push(
5041
- `${a.bold("Rule-based setup score:")} ${a.score(record.overallScore, `${record.overallScore} / 100`)} (${a.score(record.overallScore, record.band.label)}; not an Anthropic grade)`
5042
- );
5043
- for (const p of record.pillarScores) {
5044
- lines.push(` ${p.name.padEnd(22)} ${bar(p.score, a)}`);
5045
- const weak = weakestGap(p);
5046
- if (!weak) continue;
5047
- lines.push(` ${a.dim("Weakest:")} ${weak.label} (${weak.score})`);
5048
- pushProse(lines, weak.basis, 4, a.dim);
5049
- if (weak.action) pushProse(lines, `Do this: ${weak.action}`, 4);
5050
- lines.push("");
5051
- }
5052
- lines.push("");
5053
- const dollarFixes = record.fixes.filter((f) => f.wasteUsd > 0);
5054
- const otherIssues = record.fixes.filter((f) => f.wasteUsd === 0);
5055
- lines.push(a.bold("Top changes, ranked by what they recover:"));
5056
- if (dollarFixes.length === 0) {
5057
- lines.push(" No recoverable waste was found. See the issues below.");
5058
- } else {
5059
- for (const [i, f] of dollarFixes.entries()) {
5060
- if (i > 0) lines.push("");
5061
- lines.push(` - [${a.brand(usd2(f.wasteUsd))} estimated valuation] ${a.bold(f.title)}`);
5062
- if (f.problem) pushProse(lines, f.problem, 6);
5063
- pushProse(lines, f.action, 6);
5064
- if (f.basis) pushProse(lines, `Evidence: ${f.basis}`, 6, a.dim);
5065
- }
5066
- }
5067
- if (otherIssues.length > 0) {
5068
- lines.push("");
5069
- lines.push(a.bold("Other issues to tighten:"));
5070
- for (const f of otherIssues) {
5071
- lines.push(` - ${f.title}`);
5072
- if (f.basis) pushProse(lines, `Evidence: ${f.basis}`, 6, a.dim);
5073
- }
5074
- }
5075
- if (meta.skipped.length > 0) {
5076
- lines.push("");
5077
- pushProse(lines, `Note: ${meta.skipped.length} file(s) could not be read and were skipped.`, 0, a.dim);
5078
- }
5079
- const gapLine = unassessedLine(record.pillarScores);
5080
- if (gapLine) {
5081
- lines.push("");
5082
- lines.push(a.dim(gapLine));
5083
- }
5084
- lines.push("");
5085
- const methodology = "Methodology: amounts are list-price estimates from logged token fields using the current pricing snapshot. Recoverable waste counts uncached input plus cache writes a session never read back; cache writes that earned their reads are excluded, because paying to build a cache you then read from is the mechanism working.";
5086
- const provenance = m.accuracy ? ` Pricing snapshot: ${m.accuracy.pricingSnapshotDate}; accounting method: v${m.accuracy.accountingVersion}.` : "";
5087
- pushProse(lines, methodology + provenance, 0, a.dim);
5088
- return lines.join("\n");
5089
- }
5090
-
5091
- // src/svg.ts
5092
- var SYSTEM_FONT = "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif";
5093
- function esc(s) {
5094
- return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
5095
- }
5096
- function bandColorForScore(score) {
5097
- if (score < 40) return "#c0392b";
5098
- if (score < 60) return "#e07a5f";
5099
- if (score < 75) return "#d99a2b";
5100
- if (score < 90) return "#5f8f4f";
5101
- return "#3f7d4e";
5102
- }
5103
- function rect(x, y, w, h, fill, rx = 0) {
5104
- return `<rect x="${x}" y="${y}" width="${w}" height="${h}" rx="${rx}" fill="${fill}"></rect>`;
5105
- }
5106
- function text(x, y, s, opts = {}) {
5107
- const size = opts.size ?? 13;
5108
- const weight = opts.weight ?? 400;
5109
- const fill = opts.fill ?? "#251d1a";
5110
- const anchor = opts.anchor ?? "start";
5111
- return `<text x="${x}" y="${y}" font-family="${SYSTEM_FONT}" font-size="${size}" font-weight="${weight}" fill="${fill}" text-anchor="${anchor}">${esc(s)}</text>`;
5112
- }
5113
- function estimateTextWidth(s, size) {
5114
- return Math.round(s.length * size * 0.62);
5115
- }
5116
-
5117
- // src/html-report.ts
5118
- function usd3(n) {
5119
- return `$${roundMoneyHalfUp(n).toFixed(2)}`;
5120
- }
5121
- function truncate(s, max) {
5122
- return s.length > max ? s.slice(0, max - 3) + "..." : s;
5123
- }
5124
- function projectChart(projects) {
5125
- if (projects.length === 0) {
5126
- return `<p class="muted">No project valuation estimate to chart.</p>`;
5127
- }
5128
- const rowH = 28;
5129
- const gap = 8;
5130
- const labelW = 200;
5131
- const valW = 90;
5132
- const barMax = 400;
5133
- const barH = 14;
5134
- const width = labelW + barMax + valW;
5135
- const height = projects.length * (rowH + gap) - gap;
5136
- const maxCost = Math.max(...projects.map((p) => p.costUsd), 0.01);
5137
- const rows = projects.map((p, i) => {
5138
- const y = i * (rowH + gap);
5139
- const w = Math.max(barH, Math.round(p.costUsd / maxCost * barMax));
5140
- const mid = y + rowH / 2;
5141
- const barY = mid - barH / 2;
5142
- const label = esc(truncate(p.slug, 30));
5143
- return `<text x="0" y="${mid}" class="c-lbl" dominant-baseline="middle">${label}</text><rect x="${labelW}" y="${barY}" width="${barMax}" height="${barH}" rx="${barH / 2}" fill="#f5ece6"></rect><rect x="${labelW}" y="${barY}" width="${w}" height="${barH}" rx="${barH / 2}" fill="#e07a5f"></rect><text x="${width}" y="${mid}" class="c-val" text-anchor="end" dominant-baseline="middle">${esc(usd3(p.costUsd))}</text>`;
5144
- }).join("");
5145
- return `<svg viewBox="0 0 ${width} ${height}" width="100%" height="${height}" role="img" aria-label="Top projects by estimated current API-equivalent valuation" preserveAspectRatio="xMinYMin meet">${rows}</svg>`;
5146
- }
5147
- function burnClockChart(bc) {
5148
- const rowH = 22;
5149
- const gap = 6;
5150
- const labelW = 90;
5151
- const valW = 70;
5152
- const barMax = 300;
5153
- const barH = 12;
5154
- const width = labelW + barMax + valW;
5155
- const height = BURN_DAY_ORDER.length * (rowH + gap) - gap;
5156
- const max = Math.max(...bc.byDay, 0.01);
5157
- const rows = BURN_DAY_ORDER.map((day2, i) => {
5158
- const y = i * (rowH + gap);
5159
- const v = bc.byDay[day2];
5160
- const w = Math.max(barH, Math.round(v / max * barMax));
5161
- const mid = y + rowH / 2;
5162
- const barY = mid - barH / 2;
5163
- const label = esc(BURN_DAY_NAMES[day2]);
5164
- return `<text x="0" y="${mid}" class="c-lbl" dominant-baseline="middle">${label}</text><rect x="${labelW}" y="${barY}" width="${barMax}" height="${barH}" rx="${barH / 2}" fill="#f5ece6"></rect><rect x="${labelW}" y="${barY}" width="${w}" height="${barH}" rx="${barH / 2}" fill="#e07a5f"></rect><text x="${width}" y="${mid}" class="c-val" text-anchor="end" dominant-baseline="middle">${esc(usd3(v))}</text>`;
5165
- }).join("");
5166
- return `<svg viewBox="0 0 ${width} ${height}" width="100%" height="${height}" role="img" aria-label="Estimated current API-equivalent valuation by day of week" preserveAspectRatio="xMinYMin meet">${rows}</svg>`;
5167
- }
5168
- function weakestGap2(p) {
5169
- let worst = null;
5170
- for (const c of p.checks) {
5171
- if (!c.assessed || c.score == null || !c.gap) continue;
5172
- if (!worst || c.score < worst.score) worst = c;
5173
- }
5174
- return worst;
5175
- }
5176
4871
  function pillarBars(pillars) {
5177
4872
  return pillars.map((p) => {
5178
4873
  const name = esc(p.name);
@@ -5181,13 +4876,13 @@ function pillarBars(pillars) {
5181
4876
  }
5182
4877
  const score = p.score;
5183
4878
  const color = bandColorForScore(score);
5184
- const weak = weakestGap2(p);
4879
+ const weak = weakestGap(p);
5185
4880
  const detail = weak ? `<div class="p-detail"><div class="p-weak">Weakest: ${esc(weak.label)} (${weak.score})</div><p class="p-basis">${esc(weak.basis)}</p>` + (weak.action ? `<p class="p-action"><strong>Do this:</strong> ${esc(weak.action)}</p>` : "") + `</div>` : "";
5186
4881
  return `<div class="pillar"><span class="p-name">${name}</span><span class="p-track"><span class="p-fill" style="width:${score}%;background:${color}"></span></span><span class="p-score">${score}</span></div>` + detail;
5187
4882
  }).join("");
5188
4883
  }
5189
4884
  function dollarFixCard(f) {
5190
- return `<li class="fix"><div class="fix-head"><span class="fix-amt">${esc(usd3(f.wasteUsd))}</span><span class="fix-title">${esc(f.title)}</span></div><p class="fix-problem">${esc(f.problem)}</p><p class="fix-action">${esc(f.action)}</p>` + (f.basis ? `<p class="fix-basis">${esc(f.basis)}</p>` : "") + `</li>`;
4885
+ return `<li class="fix"><div class="fix-head"><span class="fix-amt">${esc(usd2(f.wasteUsd))}</span><span class="fix-title">${esc(f.title)}</span></div><p class="fix-problem">${esc(f.problem)}</p><p class="fix-action">${esc(f.action)}</p>` + (f.basis ? `<p class="fix-basis">${esc(f.basis)}</p>` : "") + `</li>`;
5191
4886
  }
5192
4887
  function otherFixCard(f) {
5193
4888
  return `<li class="fix other"><div class="fix-head"><span class="fix-title">${esc(f.title)}</span></div><p class="fix-action">${esc(f.action)}</p>` + (f.basis ? `<p class="fix-basis">${esc(f.basis)}</p>` : "") + `</li>`;
@@ -5215,7 +4910,7 @@ function nextStepsSection(record, meta) {
5215
4910
  ));
5216
4911
  }
5217
4912
  const waste = record.headlineWasteUsd;
5218
- const wasteLine = waste > 0 ? `This audit estimates <strong>${esc(usd3(waste))}</strong> of recoverable waste at current API list prices. ` : "";
4913
+ const wasteLine = waste > 0 ? `This audit estimates <strong>${esc(usd2(waste))}</strong> of recoverable waste at current API list prices. ` : "";
5219
4914
  if (licensed) {
5220
4915
  const who = meta.license?.email ? ` (${esc(meta.license.email)})` : "";
5221
4916
  steps.push(step(
@@ -5407,102 +5102,429 @@ table.ref td:first-child { white-space: nowrap; color: var(--umber); font-size:
5407
5102
  .banner .amount { font-size: 32px; }
5408
5103
  .p-name { flex: 0 0 130px; font-size: 13px; }
5409
5104
  }
5410
- `;
5411
- function renderHtml(record, meta) {
5412
- const m = record.usageMetrics;
5413
- const mix = modelMix(m.modelBreakdown);
5414
- const accuracyNotesForRecord = accuracyNotes(record);
5415
- const mixCells = mix ? mix.split(" / ").map((part) => `<span class="nb">${esc(part)}</span>`).join(" / ") : "";
5416
- const subscription = record.plan !== void 0 && record.plan !== "api";
5417
- const reportedShare = record.headlineWasteShare ?? (m.spendUsd > 0 ? record.headlineWasteUsd / m.spendUsd : 0);
5418
- const shareIsValid = Number.isFinite(reportedShare) && reportedShare >= 0 && reportedShare <= 1;
5419
- const shareText = shareIsValid ? `${(reportedShare * 100).toFixed(1)}%` : "unavailable";
5420
- const bannerAmount = subscription ? `<div class="amount">${shareText} of analyzed token value</div><div class="amount-sub">${esc(usd3(record.headlineWasteUsd))} estimated current API-equivalent valuation</div>` : `<div class="amount mono">${esc(usd3(record.headlineWasteUsd))}</div><div class="amount-sub">estimated current API-equivalent valuation</div>`;
5421
- const spendLabel = "Current API-equivalent valuation (estimate)";
5422
- const w = record.usageWindows;
5423
- const weeklyBurn = !subscription && meta.planSource === "default" && w?.assessed && w.medianWeekUsd >= 50 ? ` Median weekly estimated current API-equivalent valuation: ${esc(usd3(w.medianWeekUsd))}.` : "";
5424
- const planNote = subscription ? `<p class="sub">Plan: ${esc(record.plan)}. Dollar figures are estimated current API-equivalent valuations, not money back, actual quota, or a promise of more work. Cache-miss exposure is a counterfactual: cold and unique inputs cannot all be cached.</p>` : meta.planSource === "default" ? `<p class="sub">Dollar figures are estimated current API-equivalent valuations.${weeklyBurn} On a Claude subscription? Rerun with --plan max20x (or pro, max5x) to frame results as token efficiency.</p>` : "";
5425
- const windowTiles = subscription && w?.assessed ? `<div class="stats"><div class="stat"><div class="k">Median 5h window</div><div class="v">${esc(usd3(w.medianWindowUsd))}</div></div><div class="stat"><div class="k">90th-percentile 5h window</div><div class="v">${esc(usd3(w.p90WindowUsd))}</div></div><div class="stat"><div class="k">Busiest 5h window (maximum)</div><div class="v">${esc(usd3(w.maxWindowUsd))}</div></div></div>` : "";
5426
- const dollarFixes = record.fixes.filter((f) => f.wasteUsd > 0).sort((a, b) => b.wasteUsd - a.wasteUsd);
5427
- const otherIssues = record.fixes.filter((f) => f.wasteUsd === 0);
5428
- const dollarSection = dollarFixes.length === 0 ? `<p class="muted">No recoverable waste was found. See the issues below.</p>` : `<ul class="fixes">${dollarFixes.map(dollarFixCard).join("")}</ul>`;
5429
- const otherSection = otherIssues.length === 0 ? "" : `<h2>Other issues to tighten</h2><ul class="fixes">${otherIssues.map(otherFixCard).join("")}</ul>`;
5430
- const bc = record.burnClock;
5431
- const burnSentence = bc?.assessed ? burnClockSentence(bc) : null;
5432
- const burnSection = bc?.assessed ? `<h2>Burn Clock (estimated current API-equivalent valuation by day)</h2>
5433
- <div class="chart">${burnClockChart(bc)}</div>
5434
- ` + (burnSentence ? `<p class="sub">${esc(burnSentence)}</p>
5435
- ` : "") : "";
5436
- const skippedNote = meta.skipped.length > 0 ? `<p class="sub">Note: ${meta.skipped.length} file(s) could not be read and were skipped.</p>` : "";
5437
- const receipt = sinceOptimizeLine(meta);
5438
- const metaBlock = [
5439
- `Source: ${esc(meta.root)} (${m.sessionsCount} ${plural(m.sessionsCount, "session")}${(m.delegatedSessionsCount ?? 0) > 0 ? ` +${m.delegatedSessionsCount} delegated` : ""} across ${m.projectsCount} ${plural(m.projectsCount, "project")})`,
5440
- meta.claudeMdSource ? `CLAUDE.md: ${esc(meta.claudeMdSource)}` : "",
5441
- `Pricing snapshot: ${esc(m.pricingSnapshotDate)}`,
5442
- receipt ? `<strong>${esc(receipt)}</strong>` : ""
5443
- ].filter((line) => line.length > 0).map((line) => `<p class="meta">${line}</p>`).join("\n");
5444
- return `<!doctype html>
5445
- <html lang="en">
5446
- <head>
5447
- <meta charset="utf-8" />
5448
- <meta name="viewport" content="width=device-width, initial-scale=1" />
5449
- <title>CostClaw audit report</title>
5450
- <style>${STYLE}</style>
5451
- </head>
5452
- <body>
5453
- <div class="wrap">
5454
- <div class="mark" aria-hidden="true"></div>
5455
- <h1>CostClaw audit</h1>
5456
- ${metaBlock}
5457
-
5458
- <div class="banner">
5459
- <div class="label">${esc(record.headlineWasteLabel)}</div>
5460
- ${bannerAmount}
5461
- ${record.verdict ? `<p class="verdict">${esc(record.verdict)}</p>` : ""}
5462
- </div>
5463
- ${planNote}
5464
- <div class="stats">
5465
- <div class="stat"><div class="k">${spendLabel}</div><div class="v">${esc(usd3(m.spendUsd))}</div></div>
5466
- <div class="stat"><div class="k">Cache hit rate</div><div class="v">${(m.cacheHitRate * 100).toFixed(1)}%</div></div>
5467
- <div class="stat"><div class="k">Session hours (timestamp union)</div><div class="v">${m.durationHours.toFixed(1)}</div></div>
5468
- ${mix ? `<div class="stat"><div class="k">Model spend</div><div class="v v-small">${mixCells}</div></div>` : ""}
5469
- ${record.cacheWriteCostUsd != null && record.cacheWriteCostUsd > 0 ? `<div class="stat"><div class="k">Cache writes that earned their reads</div><div class="v">${esc(usd3(record.cacheWriteCostUsd))}</div><div class="k">working cost, not waste</div></div>` : ""}
5470
- </div>
5471
- ${accuracyNotesForRecord.map((note) => `<p class="meta">${esc(`Pricing caution: ${note}`)}</p>`).join("\n")}
5472
- ${!shareIsValid ? `<p class="meta">Pricing caution: this legacy record has an invalid cache-miss exposure share; its percentage is unavailable.</p>` : ""}
5473
- ${windowTiles}
5474
-
5475
- <h2>Projects by estimated current API-equivalent valuation</h2>
5476
- <div class="chart">${projectChart(m.topProjects)}</div>
5477
-
5478
- ${burnSection}
5479
- <h2>Rule-based setup score</h2>
5480
- <div class="score-head">
5481
- <span class="big">${record.overallScore} / 100</span>
5482
- <span class="band">${esc(record.band.label)}</span>
5483
- </div>
5484
- <p class="sub">A transparent heuristic from observed setup signals, not an Anthropic grade.</p>
5485
- ${pillarBars(record.pillarScores)}
5486
-
5487
- <h2>Top changes, ranked by what they recover</h2>
5488
- ${dollarSection}
5489
- ${otherSection}
5490
- ${skippedNote}
5491
-
5492
- <h2>Methodology</h2>
5493
- <p class="sub">Amounts are list-price estimates from logged token fields using the current pricing snapshot. Cache-miss exposure is a bounded counterfactual, not savings or a billing reconciliation. Activity windows use 15-minute activity bins and do not measure work time.${m.accuracy ? ` Pricing snapshot: ${esc(m.accuracy.pricingSnapshotDate)}; accounting method: v${esc(m.accuracy.accountingVersion)}.` : ""}</p>
5494
-
5495
- ${nextStepsSection(record, meta)}
5496
-
5497
- <div class="footer">
5498
- <strong>This report was generated locally on your machine.</strong> Nothing was uploaded:
5499
- your prompts, file contents, and paths never left this computer.
5500
- <div class="gen">Generated <span class="mono">${esc(record.createdAt)}</span>.</div>
5501
- </div>
5502
- </div>
5503
- </body>
5504
- </html>
5505
- `;
5105
+ `;
5106
+ function renderHtml(record, meta) {
5107
+ const m = record.usageMetrics;
5108
+ const mix = modelMix(m.modelBreakdown);
5109
+ const accuracyNotesForRecord = accuracyNotes(record);
5110
+ const mixCells = mix ? mix.split(" / ").map((part) => `<span class="nb">${esc(part)}</span>`).join(" / ") : "";
5111
+ const subscription = record.plan !== void 0 && record.plan !== "api";
5112
+ const reportedShare = record.headlineWasteShare ?? (m.spendUsd > 0 ? record.headlineWasteUsd / m.spendUsd : 0);
5113
+ const shareIsValid = Number.isFinite(reportedShare) && reportedShare >= 0 && reportedShare <= 1;
5114
+ const shareText = shareIsValid ? `${(reportedShare * 100).toFixed(1)}%` : "unavailable";
5115
+ const bannerAmount = subscription ? `<div class="amount">${shareText} of analyzed token value</div><div class="amount-sub">${esc(usd2(record.headlineWasteUsd))} estimated current API-equivalent valuation</div>` : `<div class="amount mono">${esc(usd2(record.headlineWasteUsd))}</div><div class="amount-sub">estimated current API-equivalent valuation</div>`;
5116
+ const spendLabel = "Current API-equivalent valuation (estimate)";
5117
+ const w = record.usageWindows;
5118
+ const weeklyBurn = !subscription && meta.planSource === "default" && w?.assessed && w.medianWeekUsd >= 50 ? ` Median weekly estimated current API-equivalent valuation: ${esc(usd2(w.medianWeekUsd))}.` : "";
5119
+ const planNote = subscription ? `<p class="sub">Plan: ${esc(record.plan)}. Dollar figures are estimated current API-equivalent valuations, not money back, actual quota, or a promise of more work. Cache-miss exposure is a counterfactual: cold and unique inputs cannot all be cached.</p>` : meta.planSource === "default" ? `<p class="sub">Dollar figures are estimated current API-equivalent valuations.${weeklyBurn} On a Claude subscription? Rerun with --plan max20x (or pro, max5x) to frame results as token efficiency.</p>` : "";
5120
+ const windowTiles = subscription && w?.assessed ? `<div class="stats"><div class="stat"><div class="k">Median 5h window</div><div class="v">${esc(usd2(w.medianWindowUsd))}</div></div><div class="stat"><div class="k">90th-percentile 5h window</div><div class="v">${esc(usd2(w.p90WindowUsd))}</div></div><div class="stat"><div class="k">Busiest 5h window (maximum)</div><div class="v">${esc(usd2(w.maxWindowUsd))}</div></div></div>` : "";
5121
+ const dollarFixes = record.fixes.filter((f) => f.wasteUsd > 0).sort((a, b) => b.wasteUsd - a.wasteUsd);
5122
+ const otherIssues = record.fixes.filter((f) => f.wasteUsd === 0);
5123
+ const dollarSection = dollarFixes.length === 0 ? `<p class="muted">No recoverable waste was found. See the issues below.</p>` : `<ul class="fixes">${dollarFixes.map(dollarFixCard).join("")}</ul>`;
5124
+ const otherSection = otherIssues.length === 0 ? "" : `<h2>Other issues to tighten</h2><ul class="fixes">${otherIssues.map(otherFixCard).join("")}</ul>`;
5125
+ const bc = record.burnClock;
5126
+ const burnSentence = bc?.assessed ? burnClockSentence(bc) : null;
5127
+ const burnSection = bc?.assessed ? `<h2>Burn Clock (estimated current API-equivalent valuation by day)</h2>
5128
+ <div class="chart">${burnClockChart(bc)}</div>
5129
+ ` + (burnSentence ? `<p class="sub">${esc(burnSentence)}</p>
5130
+ ` : "") : "";
5131
+ const skippedNote = meta.skipped.length > 0 ? `<p class="sub">Note: ${meta.skipped.length} file(s) could not be read and were skipped.</p>` : "";
5132
+ const receipt = sinceOptimizeLine(meta);
5133
+ const metaBlock = [
5134
+ `Source: ${esc(meta.root)} (${m.sessionsCount} ${plural(m.sessionsCount, "session")}${(m.delegatedSessionsCount ?? 0) > 0 ? ` +${m.delegatedSessionsCount} delegated` : ""} across ${m.projectsCount} ${plural(m.projectsCount, "project")})`,
5135
+ meta.claudeMdSource ? `CLAUDE.md: ${esc(meta.claudeMdSource)}` : "",
5136
+ `Pricing snapshot: ${esc(m.pricingSnapshotDate)}`,
5137
+ receipt ? `<strong>${esc(receipt)}</strong>` : ""
5138
+ ].filter((line) => line.length > 0).map((line) => `<p class="meta">${line}</p>`).join("\n");
5139
+ return `<!doctype html>
5140
+ <html lang="en">
5141
+ <head>
5142
+ <meta charset="utf-8" />
5143
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
5144
+ <title>CostClaw audit report</title>
5145
+ <style>${STYLE}</style>
5146
+ </head>
5147
+ <body>
5148
+ <div class="wrap">
5149
+ <div class="mark" aria-hidden="true"></div>
5150
+ <h1>CostClaw audit</h1>
5151
+ ${metaBlock}
5152
+
5153
+ <div class="banner">
5154
+ <div class="label">${esc(record.headlineWasteLabel)}</div>
5155
+ ${bannerAmount}
5156
+ ${record.verdict ? `<p class="verdict">${esc(record.verdict)}</p>` : ""}
5157
+ </div>
5158
+ ${planNote}
5159
+ <div class="stats">
5160
+ <div class="stat"><div class="k">${spendLabel}</div><div class="v">${esc(usd2(m.spendUsd))}</div></div>
5161
+ <div class="stat"><div class="k">Cache hit rate</div><div class="v">${(m.cacheHitRate * 100).toFixed(1)}%</div></div>
5162
+ <div class="stat"><div class="k">Session hours (timestamp union)</div><div class="v">${m.durationHours.toFixed(1)}</div></div>
5163
+ ${mix ? `<div class="stat"><div class="k">Model spend</div><div class="v v-small">${mixCells}</div></div>` : ""}
5164
+ ${record.cacheWriteCostUsd != null && record.cacheWriteCostUsd > 0 ? `<div class="stat"><div class="k">Cache writes that earned their reads</div><div class="v">${esc(usd2(record.cacheWriteCostUsd))}</div><div class="k">working cost, not waste</div></div>` : ""}
5165
+ </div>
5166
+ ${accuracyNotesForRecord.map((note) => `<p class="meta">${esc(`Pricing caution: ${note}`)}</p>`).join("\n")}
5167
+ ${!shareIsValid ? `<p class="meta">Pricing caution: this legacy record has an invalid cache-miss exposure share; its percentage is unavailable.</p>` : ""}
5168
+ ${windowTiles}
5169
+
5170
+ <h2>Projects by estimated current API-equivalent valuation</h2>
5171
+ <div class="chart">${projectChart(m.topProjects)}</div>
5172
+
5173
+ ${burnSection}
5174
+ <h2>Rule-based setup score</h2>
5175
+ <div class="score-head">
5176
+ <span class="big">${record.overallScore} / 100</span>
5177
+ <span class="band">${esc(record.band.label)}</span>
5178
+ </div>
5179
+ <p class="sub">A transparent heuristic from observed setup signals, not an Anthropic grade.</p>
5180
+ ${pillarBars(record.pillarScores)}
5181
+
5182
+ <h2>Top changes, ranked by what they recover</h2>
5183
+ ${dollarSection}
5184
+ ${otherSection}
5185
+ ${skippedNote}
5186
+
5187
+ <h2>Methodology</h2>
5188
+ <p class="sub">Amounts are list-price estimates from logged token fields using the current pricing snapshot. Cache-miss exposure is a bounded counterfactual, not savings or a billing reconciliation. Activity windows use 15-minute activity bins and do not measure work time.${m.accuracy ? ` Pricing snapshot: ${esc(m.accuracy.pricingSnapshotDate)}; accounting method: v${esc(m.accuracy.accountingVersion)}.` : ""}</p>
5189
+
5190
+ ${nextStepsSection(record, meta)}
5191
+
5192
+ <div class="footer">
5193
+ <strong>This report was generated locally on your machine.</strong> Nothing was uploaded:
5194
+ your prompts, file contents, and paths never left this computer.
5195
+ <div class="gen">Generated <span class="mono">${esc(record.createdAt)}</span>.</div>
5196
+ </div>
5197
+ </div>
5198
+ </body>
5199
+ </html>
5200
+ `;
5201
+ }
5202
+
5203
+ // src/format.ts
5204
+ function sinceOptimizeLine(meta) {
5205
+ const so = meta.sinceOptimize;
5206
+ if (!so) return null;
5207
+ if (!so.result.comparable) {
5208
+ if (so.result.reason === "accounting method changed") {
5209
+ return `Since optimize (${so.at.slice(0, 10)}): comparison withheld because the accounting method changed. Run optimize again to set a new baseline.`;
5210
+ }
5211
+ if (so.result.reason === "pricing changed") {
5212
+ return `Since optimize (${so.at.slice(0, 10)}): comparison withheld because the pricing snapshot changed. Run optimize again to set a new baseline.`;
5213
+ }
5214
+ return null;
5215
+ }
5216
+ const r = so.result;
5217
+ const date = so.at.slice(0, 10);
5218
+ const move = `${(r.baselineCacheHitRate * 100).toFixed(1)}% -> ${(r.periodCacheHitRate * 100).toFixed(1)}%`;
5219
+ const worth = r.recoveredUsd >= 0.01 ? `; estimated current Sonnet-rate valuation ${usd3(r.recoveredUsd)}` : "";
5220
+ return `Since optimize (${date}): cache hit ${move} on new usage${worth}.`;
5221
+ }
5222
+ function usd3(n) {
5223
+ return `$${roundMoneyHalfUp(n).toFixed(2)}`;
5224
+ }
5225
+ var BURN_DAY_NAMES = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
5226
+ var BURN_DAY_ORDER = [1, 2, 3, 4, 5, 6, 0];
5227
+ var BURN_QUARTER_NAMES = ["night", "morning", "afternoon", "evening"];
5228
+ function burnSlotLabel(day2, quarter) {
5229
+ return `${BURN_DAY_NAMES[day2]} ${BURN_QUARTER_NAMES[quarter]}`;
5230
+ }
5231
+ function burnClockSentence(bc) {
5232
+ const spendDays = bc.byDay.filter((v) => v > 0);
5233
+ if (spendDays.length === 0) return null;
5234
+ let topDay = 0;
5235
+ for (let d = 0; d < bc.byDay.length; d += 1) {
5236
+ if ((bc.byDay[d] ?? 0) > (bc.byDay[topDay] ?? 0)) topDay = d;
5237
+ }
5238
+ const topUsd = bc.byDay[topDay] ?? 0;
5239
+ const average = spendDays.reduce((sum, v) => sum + v, 0) / spendDays.length;
5240
+ let sentence = `${BURN_DAY_NAMES[topDay]} is your most expensive day (${usd3(topUsd)})`;
5241
+ if (spendDays.length >= 2 && average > 0) {
5242
+ sentence += `, about ${(topUsd / average).toFixed(1)}x an average day across ${bc.activeDays} active days`;
5243
+ }
5244
+ sentence += ".";
5245
+ const top = bc.topSlot;
5246
+ if (top) sentence += ` Peak stretch: ${burnSlotLabel(top.day, top.quarter)}.`;
5247
+ return sentence;
5248
+ }
5249
+ var WRAP_WIDTH = 92;
5250
+ function wrapLines(text2, indent = 0) {
5251
+ const pad = " ".repeat(indent);
5252
+ const words = text2.split(/\s+/).filter((w) => w.length > 0);
5253
+ const out = [];
5254
+ let line = "";
5255
+ for (const word of words) {
5256
+ const candidate = line.length > 0 ? `${line} ${word}` : word;
5257
+ if (line.length > 0 && pad.length + candidate.length > WRAP_WIDTH) {
5258
+ out.push(pad + line);
5259
+ line = word;
5260
+ } else {
5261
+ line = candidate;
5262
+ }
5263
+ }
5264
+ if (line.length > 0) out.push(pad + line);
5265
+ if (out.length < 2) return out.length > 0 ? out : [pad];
5266
+ const last = (out[out.length - 1] ?? "").trim();
5267
+ const prevWords = (out[out.length - 2] ?? "").trim().split(" ");
5268
+ const borrowed = prevWords[prevWords.length - 1];
5269
+ if (borrowed !== void 0 && prevWords.length >= 3 && !last.includes(" ") && pad.length + borrowed.length + 1 + last.length <= WRAP_WIDTH) {
5270
+ out[out.length - 2] = pad + prevWords.slice(0, -1).join(" ");
5271
+ out[out.length - 1] = `${pad}${borrowed} ${last}`;
5272
+ }
5273
+ return out;
5274
+ }
5275
+ function pushProse(lines, text2, indent = 0, style = (s) => s) {
5276
+ for (const line of wrapLines(text2, indent)) lines.push(style(line));
5277
+ }
5278
+ function plural(n, noun) {
5279
+ return n === 1 ? noun : `${noun}s`;
5280
+ }
5281
+ function statRows(rows, a) {
5282
+ const plain = (c) => `${c.k}: ${c.v}`;
5283
+ const leadWidth = Math.max(...rows.map((r) => r[0] ? plain(r[0]).length : 0));
5284
+ const gap = " ";
5285
+ return rows.map(
5286
+ (row) => row.map((c, i) => {
5287
+ const styled = `${a.dim(c.k + ":")} ${a.bold(c.v)}`;
5288
+ const padding = i === 0 ? Math.max(0, leadWidth - plain(c).length) : 0;
5289
+ return styled + " ".repeat(padding);
5290
+ }).join(gap).trimEnd()
5291
+ );
5292
+ }
5293
+ function bar(score, a, width = 20) {
5294
+ if (score === null) return a.dim("n/a");
5295
+ const filled = Math.round(score / 100 * width);
5296
+ return `[${a.score(score, "#".repeat(filled))}${a.dim(".".repeat(width - filled))}] ${a.bold(String(score))}`;
5297
+ }
5298
+ function shortModel(id) {
5299
+ const m = /(opus|sonnet|haiku|fable)/i.exec(id);
5300
+ return m && m[1] ? m[1].toLowerCase() : id;
5301
+ }
5302
+ function unknownModelNote(breakdown) {
5303
+ const unknown = Object.keys(breakdown).filter((model) => !isKnownModel(model));
5304
+ return unknown.length > 0 ? `Models missing from the rate card: ${unknown.join(", ")}. Their current API-equivalent valuation is approximate.` : null;
5305
+ }
5306
+ function accuracyNotes(record) {
5307
+ const accuracy = record.usageMetrics.accuracy;
5308
+ if (!accuracy) {
5309
+ return [unknownModelNote(record.usageMetrics.modelBreakdown)].filter((note) => note !== null);
5310
+ }
5311
+ const notes = [...accuracy.warnings];
5312
+ if (accuracy.unknownModels.length > 0) {
5313
+ const models = accuracy.unknownModels.map(({ model, requests }) => `${model} (${requests} ${plural(requests, "request")})`).join(", ");
5314
+ notes.push(`Models missing from the rate card: ${models}. Their current API-equivalent valuation is approximate.`);
5315
+ }
5316
+ return [...new Set(notes)];
5317
+ }
5318
+ function modelMix(breakdown) {
5319
+ const merged = /* @__PURE__ */ new Map();
5320
+ for (const [model, spend] of Object.entries(breakdown)) {
5321
+ if (spend <= 0) continue;
5322
+ const key = shortModel(model);
5323
+ merged.set(key, (merged.get(key) ?? 0) + spend);
5324
+ }
5325
+ const total = [...merged.values()].reduce((a, b) => a + b, 0);
5326
+ if (total <= 0) return null;
5327
+ const parts = [...merged.entries()].sort((a, b) => b[1] - a[1]).map(([name, spend]) => [name, Math.round(spend / total * 100)]).filter(([, pct2]) => pct2 >= 1).map(([name, pct2]) => `${name} ${pct2}%`);
5328
+ return parts.length > 0 ? parts.join(" / ") : null;
5329
+ }
5330
+ function unassessedLine(pillars) {
5331
+ const gaps = pillars.filter((p) => !p.assessed);
5332
+ if (gaps.length === 0) return null;
5333
+ const parts = gaps.map((p) => {
5334
+ const reason = p.checks.find((c) => !c.assessed)?.basis;
5335
+ const hint = p.id === "claude_md" ? " Pass --claude-md <file> to score it." : "";
5336
+ const partial = p.checks.filter((c) => c.assessed && c.score !== null).map((c) => `${c.label} alone scores ${c.score}`).join(", ");
5337
+ const tail = partial ? ` ${partial}.` : "";
5338
+ return reason ? `${p.name} (${reason}${hint}${tail})` : p.name;
5339
+ });
5340
+ return `Not yet scored: ${parts.join(" ")}`;
5341
+ }
5342
+ function weakestGap2(p) {
5343
+ let worst = null;
5344
+ for (const c of p.checks) {
5345
+ if (!c.assessed || c.score == null || !c.gap) continue;
5346
+ if (!worst || c.score < worst.score) worst = c;
5347
+ }
5348
+ return worst;
5349
+ }
5350
+ function formatAudit(record, meta, color = false) {
5351
+ const a = ansi(color);
5352
+ const m = record.usageMetrics;
5353
+ const subscription = record.plan !== void 0 && record.plan !== "api";
5354
+ const reportedShare = record.headlineWasteShare ?? (m.spendUsd > 0 ? record.headlineWasteUsd / m.spendUsd : 0);
5355
+ const shareIsValid = Number.isFinite(reportedShare) && reportedShare >= 0 && reportedShare <= 1;
5356
+ const shareText = shareIsValid ? `${(reportedShare * 100).toFixed(1)}%` : "unavailable";
5357
+ const lines = [];
5358
+ lines.push(a.bold("CostClaw audit"));
5359
+ const delegated = m.delegatedSessionsCount ?? 0;
5360
+ pushProse(
5361
+ lines,
5362
+ `Source: ${meta.root} (${m.sessionsCount} ${plural(m.sessionsCount, "session")}${delegated > 0 ? ` +${delegated} delegated` : ""} across ${m.projectsCount} ${plural(m.projectsCount, "project")})`,
5363
+ 0,
5364
+ a.dim
5365
+ );
5366
+ if (meta.claudeMdSource) pushProse(lines, `CLAUDE.md: ${meta.claudeMdSource}`, 0, a.dim);
5367
+ lines.push(a.dim("-".repeat(WRAP_WIDTH)));
5368
+ lines.push("");
5369
+ lines.push(
5370
+ subscription ? `${a.bold(record.headlineWasteLabel + ":")} ${a.brand(shareText + " of analyzed token value")} (${usd3(record.headlineWasteUsd)} API-equivalent)` : `${a.bold(record.headlineWasteLabel + ":")} ${a.brand(usd3(record.headlineWasteUsd))}`
5371
+ );
5372
+ if (record.verdict) {
5373
+ lines.push("");
5374
+ pushProse(lines, record.verdict);
5375
+ }
5376
+ const receipt = sinceOptimizeLine(meta);
5377
+ if (receipt) pushProse(lines, receipt, 0, a.dim);
5378
+ lines.push("");
5379
+ const mix = modelMix(m.modelBreakdown);
5380
+ const statBlock = [
5381
+ [
5382
+ { k: "Current API-equivalent valuation (estimate)", v: usd3(m.spendUsd) },
5383
+ { k: "Cache hit", v: `${(m.cacheHitRate * 100).toFixed(1)}%` },
5384
+ { k: "Session hours (timestamp union)", v: m.durationHours.toFixed(1) }
5385
+ ],
5386
+ [
5387
+ { k: "Pricing snapshot", v: m.pricingSnapshotDate },
5388
+ ...mix ? [{ k: "Model spend", v: mix }] : []
5389
+ ],
5390
+ // Named explicitly because this figure used to sit inside the headline as
5391
+ // if it were waste. It is the cache paying for itself.
5392
+ ...record.cacheWriteCostUsd != null && record.cacheWriteCostUsd > 0 ? [[{ k: "Cache writes that earned their reads (working cost, not waste)", v: usd3(record.cacheWriteCostUsd) }]] : []
5393
+ ];
5394
+ for (const row of statRows(statBlock, a)) lines.push(row);
5395
+ const cautions = accuracyNotes(record);
5396
+ if (cautions.length === 1) pushProse(lines, `Pricing caution: ${cautions[0]}`, 0, a.dim);
5397
+ else if (cautions.length > 1) {
5398
+ pushProse(lines, `Pricing caution: ${cautions[0]} (${cautions.length - 1} more in --json)`, 0, a.dim);
5399
+ }
5400
+ if (!shareIsValid) pushProse(lines, "Pricing caution: this legacy record has an invalid recoverable-waste share; its percentage is unavailable.", 0, a.dim);
5401
+ const w = record.usageWindows;
5402
+ if (subscription) {
5403
+ lines.push("");
5404
+ pushProse(
5405
+ lines,
5406
+ `Plan: ${record.plan}. Dollar figures are estimated current API-equivalent valuations, not money back, actual quota, or a promise of more work. Recoverable waste is a counterfactual: a session's first turn has no cache to read from.`,
5407
+ 0,
5408
+ a.dim
5409
+ );
5410
+ if (w?.assessed) {
5411
+ lines.push(
5412
+ `${a.dim("Usage windows (estimated current API-equivalent valuation):")} median ${a.bold(usd3(w.medianWindowUsd))}, 90th percentile ${a.bold(usd3(w.p90WindowUsd))}, busiest (maximum) ${a.bold(usd3(w.maxWindowUsd))}`
5413
+ );
5414
+ lines.push(`${a.dim("Busiest week:")} ${a.bold(usd3(w.maxWeekUsd))} ${a.dim("(estimated current API-equivalent valuation)")}`);
5415
+ lines.push(`${a.dim("Activity signal:")} 15-minute activity bins, not measured work time.`);
5416
+ }
5417
+ } else if (meta.planSource === "default") {
5418
+ const burn = w?.assessed && w.medianWeekUsd >= 50 ? ` Median weekly estimated current API-equivalent valuation: ${usd3(w.medianWeekUsd)}.` : "";
5419
+ lines.push("");
5420
+ pushProse(lines, `Dollar figures are estimated current API-equivalent valuations.${burn}`, 0, a.dim);
5421
+ pushProse(
5422
+ lines,
5423
+ "On a Claude subscription? Rerun with --plan max20x (or pro, max5x) to frame results as token efficiency.",
5424
+ 0,
5425
+ a.dim
5426
+ );
5427
+ }
5428
+ if (m.topProjects.length > 0) {
5429
+ lines.push("");
5430
+ lines.push(a.bold("Top projects by estimated current API-equivalent valuation:"));
5431
+ for (const p of m.topProjects.slice(0, 5)) {
5432
+ const name = p.slug.length > 30 ? p.slug.slice(0, 27) + "..." : p.slug;
5433
+ const model = p.modelPrimary ? shortModel(p.modelPrimary) : "n/a";
5434
+ const sessions = `${String(p.sessionsCount).padStart(4)} ${plural(p.sessionsCount, "session")}`;
5435
+ const cache = `cache ${(p.cacheHitRate * 100).toFixed(1)}%`;
5436
+ lines.push(
5437
+ ` ${name.padEnd(32)}${a.bold(usd3(p.costUsd).padStart(10))} ${sessions.padEnd(16)}${a.dim(`${cache.padEnd(15)}${model}`)}`
5438
+ );
5439
+ }
5440
+ }
5441
+ const bc = record.burnClock;
5442
+ if (bc?.assessed) {
5443
+ lines.push("");
5444
+ lines.push(a.bold("Burn Clock (estimated current API-equivalent valuation by day):"));
5445
+ const max = Math.max(...bc.byDay, 0.01);
5446
+ for (const day2 of BURN_DAY_ORDER) {
5447
+ const v = bc.byDay[day2];
5448
+ const filled = Math.round(v / max * 20);
5449
+ const barStr = `[${a.brand("#".repeat(filled))}${a.dim(".".repeat(20 - filled))}]`;
5450
+ lines.push(` ${BURN_DAY_NAMES[day2].padEnd(10)} ${barStr} ${a.bold(usd3(v).padStart(9))}`);
5451
+ }
5452
+ const sentence = burnClockSentence(bc);
5453
+ if (sentence) {
5454
+ lines.push("");
5455
+ pushProse(lines, sentence);
5456
+ }
5457
+ }
5458
+ lines.push("");
5459
+ lines.push(
5460
+ `${a.bold("Rule-based setup score:")} ${a.score(record.overallScore, `${record.overallScore} / 100`)} (${a.score(record.overallScore, record.band.label)}; not an Anthropic grade)`
5461
+ );
5462
+ for (const p of record.pillarScores) {
5463
+ lines.push(` ${p.name.padEnd(22)} ${bar(p.score, a)}`);
5464
+ const weak = weakestGap2(p);
5465
+ if (!weak) continue;
5466
+ lines.push(` ${a.dim("Weakest:")} ${weak.label} (${weak.score})`);
5467
+ pushProse(lines, weak.basis, 4, a.dim);
5468
+ if (weak.action) pushProse(lines, `Do this: ${weak.action}`, 4);
5469
+ lines.push("");
5470
+ }
5471
+ lines.push("");
5472
+ const dollarFixes = record.fixes.filter((f) => f.wasteUsd > 0);
5473
+ const otherIssues = record.fixes.filter((f) => f.wasteUsd === 0);
5474
+ lines.push(a.bold("Top changes, ranked by what they recover:"));
5475
+ if (dollarFixes.length === 0) {
5476
+ lines.push(" No recoverable waste was found. See the issues below.");
5477
+ } else {
5478
+ for (const [i, f] of dollarFixes.entries()) {
5479
+ if (i > 0) lines.push("");
5480
+ lines.push(` - [${a.brand(usd3(f.wasteUsd))} estimated valuation] ${a.bold(f.title)}`);
5481
+ if (f.problem) pushProse(lines, f.problem, 6);
5482
+ pushProse(lines, f.action, 6);
5483
+ if (f.basis) pushProse(lines, `Evidence: ${f.basis}`, 6, a.dim);
5484
+ }
5485
+ }
5486
+ if (otherIssues.length > 0) {
5487
+ lines.push("");
5488
+ lines.push(a.bold("Other issues to tighten:"));
5489
+ for (const f of otherIssues) {
5490
+ lines.push(` - ${f.title}`);
5491
+ if (f.basis) pushProse(lines, `Evidence: ${f.basis}`, 6, a.dim);
5492
+ }
5493
+ }
5494
+ if (meta.skipped.length > 0) {
5495
+ lines.push("");
5496
+ pushProse(lines, `Note: ${meta.skipped.length} file(s) could not be read and were skipped.`, 0, a.dim);
5497
+ }
5498
+ const gapLine = unassessedLine(record.pillarScores);
5499
+ if (gapLine) {
5500
+ lines.push("");
5501
+ lines.push(a.dim(gapLine));
5502
+ }
5503
+ lines.push("");
5504
+ const methodology = "Methodology: amounts are list-price estimates from logged token fields using the current pricing snapshot. Recoverable waste counts uncached input plus cache writes a session never read back; cache writes that earned their reads are excluded, because paying to build a cache you then read from is the mechanism working.";
5505
+ const provenance = m.accuracy ? ` Pricing snapshot: ${m.accuracy.pricingSnapshotDate}; accounting method: v${m.accuracy.accountingVersion}.` : "";
5506
+ pushProse(lines, methodology + provenance, 0, a.dim);
5507
+ const next = optimizeLines(record, meta, a);
5508
+ if (next.length > 0) lines.push("", ...next);
5509
+ return lines.join("\n");
5510
+ }
5511
+ function optimizeLines(record, meta, a) {
5512
+ if (!meta.license) return [];
5513
+ const projects = Math.min(10, record.usageMetrics.projectsCount);
5514
+ const scope = projects > 1 ? `up to ${projects} of your projects, ranked by spend,` : "your project";
5515
+ if (meta.license.active) {
5516
+ return [`${a.bold("Next:")} npx costclaw optimize ${a.dim(`(generates the files for ${scope.replace(/,$/, "")})`)}`];
5517
+ }
5518
+ const out = [a.bold(`Turn this audit into files: costclaw optimize (${LICENSE_PRICE} one-time)`)];
5519
+ const top = (record.fixes.find((f) => f.wasteUsd > 0) ?? record.fixes[0])?.title;
5520
+ pushProse(
5521
+ out,
5522
+ `For ${scope} it writes a CLAUDE.md draft built from that repo, a fix playbook${top ? ` that starts with "${top}"` : ""}, and a suggested permission allowlist. Generated on your machine; nothing is uploaded. The audit stays free.`,
5523
+ 2
5524
+ );
5525
+ out.push(` ${a.dim("Buy:")} ${CHECKOUT_URL}`);
5526
+ out.push(` ${a.dim("Details:")} ${PRICING_URL}`);
5527
+ return out;
5506
5528
  }
5507
5529
 
5508
5530
  // src/card.ts
@@ -5674,7 +5696,10 @@ import { createHmac, timingSafeEqual } from "crypto";
5674
5696
  var NOT_ACTIVATED_MESSAGE = [
5675
5697
  "costclaw optimize needs a license.",
5676
5698
  "",
5677
- "Buy a one-time license at https://costclaw.io, then run:",
5699
+ `Buy a ${LICENSE_PRICE} one-time license (the key is emailed in about a minute):`,
5700
+ ` ${CHECKOUT_URL}`,
5701
+ "",
5702
+ "Then run:",
5678
5703
  " costclaw activate <your-license-key>",
5679
5704
  "",
5680
5705
  "costclaw audit is free and does not need a license."
@@ -5902,7 +5927,7 @@ async function runAudit(opts) {
5902
5927
  `);
5903
5928
  }
5904
5929
  const color = !opts.json && process.stdout.isTTY === true && !process.env["NO_COLOR"];
5905
- let output = opts.json ? JSON.stringify(record, null, 2) : formatAudit(record, { root, sessionCount: logs.length, skipped, claudeMdSource, planSource, sinceOptimize }, color);
5930
+ let output = opts.json ? JSON.stringify(record, null, 2) : formatAudit(record, { root, sessionCount: logs.length, skipped, claudeMdSource, planSource, sinceOptimize, license }, color);
5906
5931
  const notices = [];
5907
5932
  if (snapshotNotice) notices.push(snapshotNotice);
5908
5933
  if (opts.html) {
@@ -5958,6 +5983,7 @@ async function resolveClaudeMdImports(claudeMdPath, text2, home) {
5958
5983
  }
5959
5984
 
5960
5985
  // src/apply-command.ts
5986
+ import { constants } from "fs";
5961
5987
  import { mkdir as mkdir4, writeFile as writeFile4, readFile as readFile6, rm as rm3, stat, copyFile } from "fs/promises";
5962
5988
  import { join as join7, dirname as dirname3, basename as basename2 } from "path";
5963
5989
  import { homedir as homedir5 } from "os";
@@ -5987,10 +6013,15 @@ function stamp(now) {
5987
6013
  async function backupFile(target, now = /* @__PURE__ */ new Date()) {
5988
6014
  if (!await pathExists(target)) return null;
5989
6015
  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;
6016
+ for (let n = 1; ; n++) {
6017
+ const path = n === 1 ? base : `${base}-${n}`;
6018
+ try {
6019
+ await copyFile(target, path, constants.COPYFILE_EXCL);
6020
+ return path;
6021
+ } catch (error) {
6022
+ if (error.code !== "EEXIST") throw error;
6023
+ }
6024
+ }
5994
6025
  }
5995
6026
  async function readIncludeSections(artifactsDir) {
5996
6027
  const path = join7(artifactsDir, INCLUDE_SECTIONS_ARTIFACT);
@@ -6359,6 +6390,110 @@ async function applyDerivedSettings(target, suggestedJson) {
6359
6390
  };
6360
6391
  }
6361
6392
 
6393
+ // src/apply-state.ts
6394
+ var APPLIED_MODES = Object.freeze(["include", "settings"]);
6395
+ var APPLY_STATES = ["not_applied", "include", "settings", "applied_unknown"];
6396
+ var APPLY_INITIAL_STATE = "not_applied";
6397
+ var APPLY_LEGACY_STATES = Object.freeze(["applied_unknown"]);
6398
+ var APPLY_TRANSITIONS = Object.freeze({
6399
+ not_applied: ["include", "settings"],
6400
+ include: ["include", "settings", "not_applied"],
6401
+ settings: ["settings", "not_applied"],
6402
+ applied_unknown: ["applied_unknown", "settings", "not_applied"]
6403
+ });
6404
+ var APPLY_TERMINAL_STATES = Object.freeze(
6405
+ APPLY_STATES.filter((s) => APPLY_TRANSITIONS[s].length === 0)
6406
+ );
6407
+ var APPLY_ACTIONS = ["include", "settings", "remove"];
6408
+ function isApplyAction(value) {
6409
+ return value !== void 0 && APPLY_ACTIONS.includes(value);
6410
+ }
6411
+ var APPLY_STATE_LABELS = Object.freeze({
6412
+ not_applied: "not applied",
6413
+ include: "applied, no permissions",
6414
+ settings: "applied + permissions",
6415
+ applied_unknown: "applied"
6416
+ });
6417
+ var APPLY_ACTION_LABELS = Object.freeze({
6418
+ include: "Apply",
6419
+ settings: "Apply + permissions",
6420
+ remove: "Undo"
6421
+ });
6422
+ function applyStatusText(state, appliedAt) {
6423
+ if (state === "not_applied") return APPLY_STATE_LABELS.not_applied;
6424
+ const date = appliedAt ? ` ${appliedAt.slice(0, 10)}` : "";
6425
+ const what = state === "settings" ? " + permissions" : state === "include" ? ", no permissions" : "";
6426
+ return `applied${date}${what}`;
6427
+ }
6428
+ function nextStates(current) {
6429
+ return APPLY_TRANSITIONS[current];
6430
+ }
6431
+ function canTransition(current, requested) {
6432
+ return APPLY_TRANSITIONS[current].includes(requested);
6433
+ }
6434
+ function applyTarget(current, action) {
6435
+ if (action === "remove") return "not_applied";
6436
+ if (action === "settings") return "settings";
6437
+ return current === "not_applied" ? "include" : current;
6438
+ }
6439
+ function allowedActions(current) {
6440
+ return APPLY_ACTIONS.filter((a) => canTransition(current, applyTarget(current, a)));
6441
+ }
6442
+ var IllegalTransitionError = class extends Error {
6443
+ code = "illegal_transition";
6444
+ current;
6445
+ requested;
6446
+ allowed;
6447
+ allowedActions;
6448
+ constructor(current, requested) {
6449
+ const allowed = nextStates(current);
6450
+ super(
6451
+ `illegal_transition: ${current} -> ${requested} is not allowed (allowed: ${APPLY_TERMINAL_STATES.includes(current) ? "none" : allowed.join(", ")})`
6452
+ );
6453
+ this.name = "IllegalTransitionError";
6454
+ this.current = current;
6455
+ this.requested = requested;
6456
+ this.allowed = allowed;
6457
+ this.allowedActions = allowedActions(current);
6458
+ }
6459
+ toJSON() {
6460
+ return {
6461
+ error: this.code,
6462
+ current: this.current,
6463
+ requested: this.requested,
6464
+ allowed: [...this.allowed],
6465
+ allowed_actions: [...this.allowedActions],
6466
+ message: this.message
6467
+ };
6468
+ }
6469
+ };
6470
+ function assertTransition(current, requested) {
6471
+ if (!canTransition(current, requested)) throw new IllegalTransitionError(current, requested);
6472
+ }
6473
+ function applyStateOf(e) {
6474
+ if (!e.appliedAt) return APPLY_INITIAL_STATE;
6475
+ const mode = e.appliedMode;
6476
+ if (mode !== void 0 && APPLIED_MODES.includes(mode)) return mode;
6477
+ return "applied_unknown";
6478
+ }
6479
+ function recordApply(entry, action, now = /* @__PURE__ */ new Date()) {
6480
+ const from = applyStateOf(entry);
6481
+ const to = applyTarget(from, action);
6482
+ assertTransition(from, to);
6483
+ if (to === "not_applied") {
6484
+ delete entry.appliedAt;
6485
+ delete entry.appliedMode;
6486
+ return to;
6487
+ }
6488
+ entry.appliedAt = now.toISOString();
6489
+ if (!APPLY_LEGACY_STATES.includes(to)) entry.appliedMode = to;
6490
+ return to;
6491
+ }
6492
+ function applyFieldsOf(e) {
6493
+ if (!e?.appliedAt) return {};
6494
+ return { appliedAt: e.appliedAt, ...e.appliedMode ? { appliedMode: e.appliedMode } : {} };
6495
+ }
6496
+
6362
6497
  // src/line-align.ts
6363
6498
  var MAX_LINES = 4e3;
6364
6499
  function splitLines(text2) {
@@ -7059,6 +7194,7 @@ var INDEX_STYLE = `
7059
7194
  background:var(--panel);color:var(--ink);cursor:pointer}
7060
7195
  .acts button:hover{border-color:var(--accent)}
7061
7196
  .acts button.go{background:var(--accent);border-color:var(--accent);color:#fff;font-weight:600}
7197
+ .acts button:disabled{opacity:.45;cursor:not-allowed;border-color:var(--line)}
7062
7198
  td code.cmd{margin-top:0;font-size:.78rem;white-space:pre-wrap;word-break:break-all}
7063
7199
  .banner{background:color-mix(in srgb,var(--good) 14%,transparent);border:1px solid var(--line);
7064
7200
  border-radius:10px;padding:12px 14px;margin:0 0 22px;font-size:.9rem}
@@ -7137,20 +7273,40 @@ function indexTokens(tokens) {
7137
7273
  if (tokens.before === null) return `${esc(approxTokens(tokens.after))} (new file)`;
7138
7274
  return `${esc(approxTokens(tokens.before))} to ${esc(approxTokens(tokens.after))}`;
7139
7275
  }
7140
- function indexStatus(appliedAt, mode) {
7141
- if (!appliedAt) return `<span class="state off">not applied</span>`;
7142
- const what = mode === "settings" ? " + permissions" : mode === "include" ? ", no permissions" : "";
7143
- return `<span class="state on">applied ${esc(appliedAt.slice(0, 10))}${esc(what)}</span>`;
7276
+ function indexStatus(row) {
7277
+ const state = applyStateOf(row);
7278
+ const cls = state === "not_applied" ? "off" : "on";
7279
+ return `<span class="state ${cls}">${esc(applyStatusText(state, row.appliedAt))}</span>`;
7280
+ }
7281
+ var APPLY_ACTION_TITLES = {
7282
+ include: "Writes .claude/costclaw.md, adds one import line to this project's CLAUDE.md, and copies the playbook and work order into .claude/costclaw/.",
7283
+ settings: "Everything Apply does, and also merges the suggested permission allowlist into this project's settings, backing up the original first.",
7284
+ remove: "Removes the costclaw include and the import line."
7285
+ };
7286
+ function actionTitle(action, state, allowed) {
7287
+ if (!allowed) {
7288
+ return action === "remove" ? "Nothing to undo: this project is not applied." : `Not available: this project is ${applyStatusText(state)}.`;
7289
+ }
7290
+ if (action === "remove" && (state === "settings" || state === "applied_unknown")) {
7291
+ return `${APPLY_ACTION_TITLES.remove} Any permissions merged into .claude/settings.json stay.`;
7292
+ }
7293
+ return APPLY_ACTION_TITLES[action];
7144
7294
  }
7145
- function applyButtons(slug) {
7146
- return `<div class="acts"><button type="submit" name="action" value="include:${esc(slug)}" class="go" title="Writes .claude/costclaw.md, adds one import line to this project's CLAUDE.md, and copies the playbook and work order into .claude/costclaw/.">Apply</button><button type="submit" name="action" value="settings:${esc(slug)}" title="Everything Apply does, and also merges the suggested permission allowlist into this project's settings, backing up the original first.">Apply + permissions</button><button type="submit" name="action" value="remove:${esc(slug)}" title="Removes the costclaw include and the import line.">Undo</button></div>`;
7295
+ function applyButtons(row) {
7296
+ const state = applyStateOf(row);
7297
+ const allowed = allowedActions(state);
7298
+ const buttons = APPLY_ACTIONS.map((action) => {
7299
+ const ok = allowed.includes(action);
7300
+ return `<button type="submit" name="action" value="${action}:${esc(row.slug)}"` + (action === "include" ? ` class="go"` : "") + (ok ? "" : " disabled") + ` title="${esc(actionTitle(action, state, ok))}">${esc(APPLY_ACTION_LABELS[action])}</button>`;
7301
+ }).join("");
7302
+ return `<div class="acts" data-state="${state}" data-allowed="${allowed.join(" ")}">${buttons}</div>`;
7147
7303
  }
7148
7304
  function indexActions(row, serve) {
7149
7305
  const details = `<a href="${esc(row.artifactsHref)}">details</a>`;
7150
7306
  if (!serve) {
7151
7307
  return `<code class="cmd">${esc(row.applyCommand)}</code><p class="note" style="margin-top:6px">${details}</p>`;
7152
7308
  }
7153
- return applyButtons(row.slug) + `<p class="note" style="margin-top:6px"><b>Apply</b> writes <span class="mono">.claude/costclaw.md</span>, adds one <span class="mono">@.claude/costclaw.md</span> line to this project's CLAUDE.md, and copies the playbook and work order into <span class="mono">.claude/costclaw/</span>. Every line you wrote stays. <b>Apply + permissions</b> does all of that <em>and</em> merges the suggested allowlist into this project's settings, so it is the same button plus one step. ${details}</p>`;
7309
+ return applyButtons(row) + `<p class="note" style="margin-top:6px"><b>Apply</b> writes <span class="mono">.claude/costclaw.md</span>, adds one <span class="mono">@.claude/costclaw.md</span> line to this project's CLAUDE.md, and copies the playbook and work order into <span class="mono">.claude/costclaw/</span>. Every line you wrote stays. <b>Apply + permissions</b> does all of that <em>and</em> merges the suggested allowlist into this project's settings, so it is the same button plus one step. ${details}</p>`;
7154
7310
  }
7155
7311
  function renderStartHere(review, projectCount) {
7156
7312
  const covers = projectCount === 1 ? "your global CLAUDE.md and this project" : `your global CLAUDE.md and all ${num5(projectCount)} projects`;
@@ -7178,17 +7334,18 @@ function renderOptimizeIndex(input) {
7178
7334
  const total = input.rows.reduce((sum, r) => sum + r.spendUsd, 0);
7179
7335
  const recoverable = input.rows.reduce((sum, r) => sum + r.recoverableUsd, 0);
7180
7336
  const rows = input.rows.map(
7181
- (r) => `<tr>` + (input.serve ? `<td class="pick"><input type="checkbox" name="slug" value="${esc(r.slug)}" checked aria-label="Include ${esc(r.slug)}"></td>` : "") + `<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, r.appliedMode)}</td><td>${indexActions(r, input.serve)}</td></tr>`
7337
+ (r) => `<tr>` + (input.serve ? `<td class="pick"><input type="checkbox" name="slug" value="${esc(r.slug)}" checked aria-label="Include ${esc(r.slug)}"></td>` : "") + `<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)}</td><td>${indexActions(r, input.serve)}</td></tr>`
7182
7338
  ).join("");
7183
7339
  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>` + (input.serve ? `<th class="pick" title="Uncheck a project to leave it out of Apply everything">Include</th>` : "") + `<th>Project</th><th class="num">Valuation estimate</th><th class="num">Recoverable</th><th>CLAUDE.md tokens</th><th>Status</th><th>Actions</th></tr></thead><tbody>${rows}</tbody></table></div>`;
7184
7340
  const serve = input.serve;
7185
- const applied = input.rows.filter((r) => r.appliedAt).length;
7341
+ const applied = input.rows.filter((r) => allowedActions(applyStateOf(r)).includes("remove")).length;
7186
7342
  const priorRun = serve?.lastRun;
7187
7343
  const oneButton = serve ? `<div class="path best oneclick"><span class="badge">One click</span><h3>Apply everything</h3><p>Writes the generated include and one import line into ${num5(input.rows.length)} ${plural2(input.rows.length, "project")}. It never edits a line you wrote, and the Revert button puts it all back.</p><div class="acts"><button type="submit" name="action" value="apply-all" class="go big">Apply everything</button>` + // Only one Revert on the page: the What changed panel owns it right after
7188
7344
  // a run, and this card carries it when a previous session left files behind.
7189
7345
  (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>` : "";
7190
7346
  const run = priorRun;
7191
- 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>` : "";
7347
+ const keptPermissions = run?.changes.some((c) => c.from === "settings" || c.from === "applied_unknown") ?? false;
7348
+ 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 ? keptPermissions ? `<p class="note">Removed the include, the import line and .claude/costclaw/. Permissions merged into .claude/settings.json were kept; the settings.json.bak-* file beside it is the copy from before the merge.</p>` : `<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>` : "";
7192
7349
  const banner = input.serve?.message ? `<p class="banner">${esc(input.serve.message)}</p>` : "";
7193
7350
  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>` : "";
7194
7351
  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>`;
@@ -7758,8 +7915,71 @@ async function scanProject(dir) {
7758
7915
  // src/serve.ts
7759
7916
  import { createServer } from "http";
7760
7917
  import { randomBytes } from "crypto";
7761
- import { readFile as readFile8 } from "fs/promises";
7762
- import { extname, resolve as resolve4, sep as sep2 } from "path";
7918
+ import { readFile as readFile9 } from "fs/promises";
7919
+ import { extname, resolve as resolve5, sep as sep2 } from "path";
7920
+
7921
+ // src/optimize-manifest.ts
7922
+ import { mkdir as mkdir5, readFile as readFile8, writeFile as writeFile5 } from "fs/promises";
7923
+ import { join as join9, resolve as resolve4 } from "path";
7924
+ var MANIFEST_NAME = "index.json";
7925
+ function defaultOptimizeRoot(home) {
7926
+ return join9(home, ".costclaw", "optimize");
7927
+ }
7928
+ function isRecord(value) {
7929
+ return typeof value === "object" && value !== null && !Array.isArray(value);
7930
+ }
7931
+ async function readManifest(root) {
7932
+ let text2;
7933
+ try {
7934
+ text2 = await readFile8(join9(root, MANIFEST_NAME), "utf8");
7935
+ } catch {
7936
+ return null;
7937
+ }
7938
+ let parsed;
7939
+ try {
7940
+ parsed = JSON.parse(text2);
7941
+ } catch {
7942
+ return null;
7943
+ }
7944
+ if (!isRecord(parsed) || !Array.isArray(parsed["projects"])) return null;
7945
+ const projects = parsed["projects"].filter((p) => isRecord(p) && typeof p["projectDir"] === "string");
7946
+ return {
7947
+ generatedAt: typeof parsed["generatedAt"] === "string" ? parsed["generatedAt"] : "",
7948
+ root: typeof parsed["root"] === "string" ? parsed["root"] : root,
7949
+ projects
7950
+ };
7951
+ }
7952
+ async function writeManifest(root, m) {
7953
+ await mkdir5(root, { recursive: true });
7954
+ await writeFile5(join9(root, MANIFEST_NAME), JSON.stringify(m, null, 2) + "\n", "utf8");
7955
+ }
7956
+ function normalizePath(p) {
7957
+ const r = resolve4(p);
7958
+ return process.platform === "win32" ? r.toLowerCase() : r;
7959
+ }
7960
+ function findEntry(m, projectDir) {
7961
+ const want = normalizePath(projectDir);
7962
+ return m.projects.find((p) => normalizePath(p.projectDir) === want);
7963
+ }
7964
+ function fnv1a(text2) {
7965
+ let h = 2166136261;
7966
+ for (let i = 0; i < text2.length; i++) {
7967
+ h ^= text2.charCodeAt(i);
7968
+ h = Math.imul(h, 16777619) >>> 0;
7969
+ }
7970
+ return h.toString(16).padStart(8, "0");
7971
+ }
7972
+ function safeDirName(slug) {
7973
+ const cleaned = slug.replace(/[^A-Za-z0-9._-]+/g, "-").replace(/^[-.]+|[-.]+$/g, "");
7974
+ return cleaned.length > 0 ? cleaned : "project";
7975
+ }
7976
+ function artifactDirName(slug, projectDir, taken) {
7977
+ const base = safeDirName(slug);
7978
+ if (!taken.has(base)) return base;
7979
+ return `${base}-${fnv1a(normalizePath(projectDir))}`;
7980
+ }
7981
+
7982
+ // src/serve.ts
7763
7983
  var DEFAULT_IDLE_MS = 30 * 60 * 1e3;
7764
7984
  var MAX_BODY_BYTES = 64 * 1024;
7765
7985
  var DASHBOARD_NAME = "DASHBOARD.html";
@@ -7784,8 +8004,8 @@ function safeArtifactPath(root, urlPath) {
7784
8004
  return null;
7785
8005
  }
7786
8006
  if (decoded.includes("\0")) return null;
7787
- const resolvedRoot = resolve4(root);
7788
- const full = resolve4(resolvedRoot, "." + decoded);
8007
+ const resolvedRoot = resolve5(root);
8008
+ const full = resolve5(resolvedRoot, "." + decoded);
7789
8009
  if (full !== resolvedRoot && !full.startsWith(resolvedRoot + sep2)) return null;
7790
8010
  return full;
7791
8011
  }
@@ -7815,9 +8035,6 @@ function rowsFromManifest(manifest) {
7815
8035
  applyCommand: `costclaw apply ${e.projectDir}`
7816
8036
  }));
7817
8037
  }
7818
- function isApplyAction(value) {
7819
- return value === "include" || value === "remove" || value === "settings";
7820
- }
7821
8038
  var CONTENT_TYPES = {
7822
8039
  ".html": "text/html; charset=utf-8",
7823
8040
  ".md": "text/plain; charset=utf-8",
@@ -7846,6 +8063,10 @@ function sendText(res, status, text2) {
7846
8063
  res.writeHead(status, { "content-type": "text/plain; charset=utf-8" });
7847
8064
  res.end(text2);
7848
8065
  }
8066
+ function sendJson(res, status, value) {
8067
+ res.writeHead(status, { "content-type": "application/json; charset=utf-8" });
8068
+ res.end(JSON.stringify(value));
8069
+ }
7849
8070
  async function startApplyServer(opts) {
7850
8071
  const token = randomBytes(16).toString("hex");
7851
8072
  const idleMs = opts.idleMs ?? DEFAULT_IDLE_MS;
@@ -7871,7 +8092,19 @@ async function startApplyServer(opts) {
7871
8092
  await new Promise((res) => server.close(() => res()));
7872
8093
  resolveClosed();
7873
8094
  }
8095
+ async function syncApplyState() {
8096
+ const disk = await readManifest(opts.root);
8097
+ if (!disk) return;
8098
+ for (const entry of manifest.projects) {
8099
+ const match = findEntry(disk, entry.projectDir);
8100
+ if (!match) continue;
8101
+ delete entry.appliedAt;
8102
+ delete entry.appliedMode;
8103
+ Object.assign(entry, applyFieldsOf(match));
8104
+ }
8105
+ }
7874
8106
  async function handleIndex(req, res, search) {
8107
+ await syncApplyState();
7875
8108
  const msg = search.get("msg");
7876
8109
  const html = renderOptimizeIndex({
7877
8110
  version: opts.version,
@@ -7888,6 +8121,7 @@ async function startApplyServer(opts) {
7888
8121
  res.end(html);
7889
8122
  }
7890
8123
  async function handleApply(req, res) {
8124
+ await syncApplyState();
7891
8125
  let body;
7892
8126
  try {
7893
8127
  body = await readBody(req, MAX_BODY_BYTES);
@@ -7909,13 +8143,14 @@ async function startApplyServer(opts) {
7909
8143
  for (const entry of manifest.projects) {
7910
8144
  if (!picked.has(entry.slug)) continue;
7911
8145
  if (raw === "revert-all") {
7912
- if (entry.appliedAt) targets.push({ entry, action: "remove" });
8146
+ if (allowedActions(applyStateOf(entry)).includes("remove")) targets.push({ entry, action: "remove" });
7913
8147
  } else {
7914
8148
  targets.push({ entry, action: withSettings ? "settings" : "include" });
7915
8149
  }
7916
8150
  }
7917
8151
  if (targets.length === 0) {
7918
- res.writeHead(303, { Location: `/?msg=${encodeURIComponent("Nothing selected.")}` });
8152
+ const msg2 = raw === "revert-all" && picked.size > 0 ? "Nothing to revert: none of the selected projects is applied." : "Nothing selected.";
8153
+ res.writeHead(303, { Location: `/?msg=${encodeURIComponent(msg2)}` });
7919
8154
  res.end();
7920
8155
  return;
7921
8156
  }
@@ -7932,22 +8167,26 @@ async function startApplyServer(opts) {
7932
8167
  sendText(res, 400, "Unknown project");
7933
8168
  return;
7934
8169
  }
8170
+ const from = applyStateOf(entry);
8171
+ try {
8172
+ assertTransition(from, applyTarget(from, verb2));
8173
+ } catch (err) {
8174
+ if (!(err instanceof IllegalTransitionError)) throw err;
8175
+ sendJson(res, 409, err.toJSON());
8176
+ return;
8177
+ }
7935
8178
  targets.push({ entry, action: verb2 });
7936
8179
  }
7937
8180
  const changes = [];
7938
8181
  const errors = [];
7939
8182
  for (const { entry, action } of targets) {
7940
8183
  const href = `${entry.dir}/${DASHBOARD_NAME}`;
8184
+ const from = applyStateOf(entry);
7941
8185
  try {
8186
+ assertTransition(from, applyTarget(from, action));
7942
8187
  const { lines, files } = await opts.apply(entry, action);
7943
- if (action === "remove") {
7944
- delete entry.appliedAt;
7945
- delete entry.appliedMode;
7946
- } else {
7947
- entry.appliedAt = (/* @__PURE__ */ new Date()).toISOString();
7948
- entry.appliedMode = action;
7949
- }
7950
- changes.push({ slug: entry.slug, lines, files, href });
8188
+ recordApply(entry, action);
8189
+ changes.push({ slug: entry.slug, lines, files, href, from });
7951
8190
  } catch (err) {
7952
8191
  const text2 = `Error: ${err instanceof Error ? err.message : String(err)}`;
7953
8192
  errors.push(text2);
@@ -7984,7 +8223,7 @@ async function startApplyServer(opts) {
7984
8223
  return;
7985
8224
  }
7986
8225
  try {
7987
- const data = await readFile8(filePath);
8226
+ const data = await readFile9(filePath);
7988
8227
  res.writeHead(200, { "content-type": contentTypeFor(filePath) });
7989
8228
  res.end(data);
7990
8229
  } catch {
@@ -8038,67 +8277,6 @@ async function startApplyServer(opts) {
8038
8277
  };
8039
8278
  }
8040
8279
 
8041
- // src/optimize-manifest.ts
8042
- import { mkdir as mkdir5, readFile as readFile9, writeFile as writeFile5 } from "fs/promises";
8043
- import { join as join9, resolve as resolve5 } from "path";
8044
- var MANIFEST_NAME = "index.json";
8045
- function defaultOptimizeRoot(home) {
8046
- return join9(home, ".costclaw", "optimize");
8047
- }
8048
- function isRecord(value) {
8049
- return typeof value === "object" && value !== null && !Array.isArray(value);
8050
- }
8051
- async function readManifest(root) {
8052
- let text2;
8053
- try {
8054
- text2 = await readFile9(join9(root, MANIFEST_NAME), "utf8");
8055
- } catch {
8056
- return null;
8057
- }
8058
- let parsed;
8059
- try {
8060
- parsed = JSON.parse(text2);
8061
- } catch {
8062
- return null;
8063
- }
8064
- if (!isRecord(parsed) || !Array.isArray(parsed["projects"])) return null;
8065
- const projects = parsed["projects"].filter((p) => isRecord(p) && typeof p["projectDir"] === "string");
8066
- return {
8067
- generatedAt: typeof parsed["generatedAt"] === "string" ? parsed["generatedAt"] : "",
8068
- root: typeof parsed["root"] === "string" ? parsed["root"] : root,
8069
- projects
8070
- };
8071
- }
8072
- async function writeManifest(root, m) {
8073
- await mkdir5(root, { recursive: true });
8074
- await writeFile5(join9(root, MANIFEST_NAME), JSON.stringify(m, null, 2) + "\n", "utf8");
8075
- }
8076
- function normalizePath(p) {
8077
- const r = resolve5(p);
8078
- return process.platform === "win32" ? r.toLowerCase() : r;
8079
- }
8080
- function findEntry(m, projectDir) {
8081
- const want = normalizePath(projectDir);
8082
- return m.projects.find((p) => normalizePath(p.projectDir) === want);
8083
- }
8084
- function fnv1a(text2) {
8085
- let h = 2166136261;
8086
- for (let i = 0; i < text2.length; i++) {
8087
- h ^= text2.charCodeAt(i);
8088
- h = Math.imul(h, 16777619) >>> 0;
8089
- }
8090
- return h.toString(16).padStart(8, "0");
8091
- }
8092
- function safeDirName(slug) {
8093
- const cleaned = slug.replace(/[^A-Za-z0-9._-]+/g, "-").replace(/^[-.]+|[-.]+$/g, "");
8094
- return cleaned.length > 0 ? cleaned : "project";
8095
- }
8096
- function artifactDirName(slug, projectDir, taken) {
8097
- const base = safeDirName(slug);
8098
- if (!taken.has(base)) return base;
8099
- return `${base}-${fnv1a(normalizePath(projectDir))}`;
8100
- }
8101
-
8102
8280
  // src/optimize-command.ts
8103
8281
  var OPTIMIZED_NAME2 = "CLAUDE.optimized.md";
8104
8282
  var PLAYBOOK_NAME2 = "PLAYBOOK.md";
@@ -8393,8 +8571,7 @@ async function runOptimize(opts) {
8393
8571
  const previous = await readManifest(manifestRoot);
8394
8572
  const merged = entries.map((e) => {
8395
8573
  const old = previous ? findEntry(previous, e.projectDir) : void 0;
8396
- if (!old?.appliedAt) return e;
8397
- return { ...e, appliedAt: old.appliedAt, ...old.appliedMode ? { appliedMode: old.appliedMode } : {} };
8574
+ return { ...e, ...applyFieldsOf(old) };
8398
8575
  });
8399
8576
  if (single && previous) {
8400
8577
  const sofar = { generatedAt: "", root: manifestRoot, projects: merged };
@@ -8783,8 +8960,13 @@ function parseApplyFlags(args) {
8783
8960
  global: args.includes("--global")
8784
8961
  };
8785
8962
  }
8963
+ function projectApplyAction(flags) {
8964
+ if (flags.global || flags.mode === "replace") return void 0;
8965
+ if (flags.mode === "remove") return "remove";
8966
+ return flags.applySettings ? "settings" : "include";
8967
+ }
8786
8968
  function cliVersion() {
8787
- return true ? "0.16.2" : "0.0.0-dev";
8969
+ return true ? "0.17.0" : "0.0.0-dev";
8788
8970
  }
8789
8971
  function isHelpRequest(command, args) {
8790
8972
  if (command === void 0) return false;
@@ -8800,7 +8982,7 @@ function helpText() {
8800
8982
  " costclaw diff [<baseline.json> <current.json>] [--json]",
8801
8983
  " costclaw badge [--path <dir>] [--claude-md <file>] [--out <file>]",
8802
8984
  " costclaw optimize [--path <dir>] [--claude-md <file>] [--project <dir>] [--out <dir>] [--limit <n>] [--no-dashboard] [--no-serve] [--force]",
8803
- " costclaw apply [<dir>] [--remove] [--replace] [--apply-settings [file]] [--from <dir>]",
8985
+ " costclaw apply [<dir>] [--remove] [--replace] [--apply-settings [file]] [--from <dir>] [--force]",
8804
8986
  " costclaw apply --global [--replace] [--remove] [--from <dir>]",
8805
8987
  " costclaw activate <license-key> [--name <machine-name>]",
8806
8988
  " costclaw deactivate",
@@ -8862,7 +9044,9 @@ function helpText() {
8862
9044
  "looking one up by project; without it, apply finds artifacts from the last",
8863
9045
  "optimize run, or generates them cold if none exist yet. Anything apply",
8864
9046
  "overwrites is backed up first to <file>.bak-YYYYMMDD-HHMMSS, so every run",
8865
- "keeps its own copy and no earlier backup is ever replaced.",
9047
+ "keeps its own copy and no earlier backup is ever replaced. --remove refuses",
9048
+ "(exit 2) a project index.json records as not applied; --force removes the",
9049
+ "costclaw files anyway.",
8866
9050
  "",
8867
9051
  "apply --global does the same for ~/.claude/CLAUDE.md, the one file loaded on",
8868
9052
  "every turn of every project. It writes the sections your audit earned to",
@@ -8988,6 +9172,24 @@ Run: costclaw optimize
8988
9172
  process.stdout.write(outcome2.lines.join("\n") + "\n");
8989
9173
  return;
8990
9174
  }
9175
+ const action = projectApplyAction(flags);
9176
+ if (action && !(flags.force && action === "remove")) {
9177
+ const tracked = await readManifest(root);
9178
+ const entry = tracked ? findEntry(tracked, flags.projectDir) : void 0;
9179
+ if (entry) {
9180
+ const from = applyStateOf(entry);
9181
+ try {
9182
+ assertTransition(from, applyTarget(from, action));
9183
+ } catch (err) {
9184
+ if (!(err instanceof IllegalTransitionError)) throw err;
9185
+ const hint = action === "remove" ? `Nothing is recorded as applied for ${flags.projectDir}. If costclaw files are still there, rerun with --force to remove them anyway.
9186
+ ` : "";
9187
+ process.stderr.write(`${err.message}
9188
+ ${hint}`);
9189
+ process.exit(2);
9190
+ }
9191
+ }
9192
+ }
8991
9193
  let artifactsDir = flags.from;
8992
9194
  if (!artifactsDir) {
8993
9195
  const manifest = await readManifest(root);
@@ -9013,12 +9215,16 @@ Run: costclaw optimize
9013
9215
  applySettingsPath: flags.applySettingsPath
9014
9216
  });
9015
9217
  process.stdout.write(outcome.lines.join("\n") + "\n");
9016
- if (flags.mode === "include") {
9218
+ if (action) {
9017
9219
  const manifest = await readManifest(root);
9018
9220
  const entry = manifest ? findEntry(manifest, flags.projectDir) : void 0;
9019
- if (manifest && entry) {
9020
- entry.appliedAt = (/* @__PURE__ */ new Date()).toISOString();
9221
+ if (manifest && entry && canTransition(applyStateOf(entry), applyTarget(applyStateOf(entry), action))) {
9222
+ const state = recordApply(entry, action);
9021
9223
  await writeManifest(root, manifest);
9224
+ process.stdout.write(
9225
+ `State: ${APPLY_STATE_LABELS[state]} (${state}). Allowed next: ${allowedActions(state).join(", ")}
9226
+ `
9227
+ );
9022
9228
  }
9023
9229
  }
9024
9230
  return;
@@ -9050,5 +9256,6 @@ export {
9050
9256
  parseApplyFlags,
9051
9257
  parseAuditFlags,
9052
9258
  parseBadgeFlags,
9053
- planFlag
9259
+ planFlag,
9260
+ projectApplyAction
9054
9261
  };