costclaw 0.12.3 → 0.13.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 +323 -322
  2. package/dist/index.js +1435 -380
  3. package/package.json +47 -47
package/dist/index.js CHANGED
@@ -16,68 +16,238 @@ function isPlan(value) {
16
16
 
17
17
  // ../../packages/engine/src/pricing.ts
18
18
  var PRICING_SNAPSHOT_DATE = "2026-09-14";
19
+ var INVALID_USAGE_WARNING = "Invalid usage counters were ignored.";
20
+ var CACHE_SPLIT_CONFLICT_WARNING = "Conflicting cache-write totals were valued from the documented top-level total at the conservative one-hour rate.";
21
+ var CACHE_TTL_ASSUMED_WARNING = "Cache writes without TTL metadata were estimated at the standard five-minute rate.";
22
+ var CACHE_TTL_FALLBACK_WARNING = "Cache writes with unusable TTL metadata were conservatively estimated at the one-hour rate.";
23
+ var UNSUPPORTED_PRICING_WARNING = "Unsupported pricing metadata was ignored and standard current rates were used.";
19
24
  var PRICES_PER_MTOK = Object.freeze({
20
- "claude-fable-5-1": { input: 10, output: 50, cache_write: 12.5, cache_read: 0.25 },
21
- "claude-fable-5": { input: 10, output: 50, cache_write: 12.5, cache_read: 1 },
22
- "claude-opus-5": { input: 5, output: 25, cache_write: 6.25, cache_read: 0.5 },
23
- "claude-opus-4-8": { input: 5, output: 25, cache_write: 6.25, cache_read: 0.5 },
24
- "claude-sonnet-5": { input: 2, output: 10, cache_write: 2.5, cache_read: 0.2 },
25
- "claude-opus-4-7": { input: 5, output: 25, cache_write: 6.25, cache_read: 0.5 },
26
- "claude-opus-4-7[1m]": { input: 5, output: 25, cache_write: 6.25, cache_read: 0.5 },
27
- "claude-opus-4-6": { input: 5, output: 25, cache_write: 6.25, cache_read: 0.5 },
28
- "claude-sonnet-4-6": { input: 3, output: 15, cache_write: 3.75, cache_read: 0.3 },
29
- "claude-sonnet-4-5": { input: 3, output: 15, cache_write: 3.75, cache_read: 0.3 },
30
- "claude-haiku-4-5": { input: 1, output: 5, cache_write: 1.25, cache_read: 0.1 },
31
- "claude-haiku-4-5-20251001": { input: 1, output: 5, cache_write: 1.25, cache_read: 0.1 }
25
+ "claude-fable-5-1": { input: 10, output: 50, cache_write: 12.5, cache_write_1h: 20, cache_read: 0.25 },
26
+ "claude-fable-5": { input: 10, output: 50, cache_write: 12.5, cache_write_1h: 20, cache_read: 1 },
27
+ "claude-mythos-5-1": { input: 10, output: 50, cache_write: 12.5, cache_write_1h: 20, cache_read: 0.25 },
28
+ "claude-mythos-5": { input: 10, output: 50, cache_write: 12.5, cache_write_1h: 20, cache_read: 1 },
29
+ "claude-opus-5": { input: 5, output: 25, cache_write: 6.25, cache_write_1h: 10, cache_read: 0.5 },
30
+ "claude-opus-4-8": { input: 5, output: 25, cache_write: 6.25, cache_write_1h: 10, cache_read: 0.5 },
31
+ "claude-sonnet-5": { input: 2, output: 10, cache_write: 2.5, cache_write_1h: 4, cache_read: 0.2 },
32
+ "claude-opus-4-7": { input: 5, output: 25, cache_write: 6.25, cache_write_1h: 10, cache_read: 0.5 },
33
+ "claude-opus-4-7[1m]": { input: 5, output: 25, cache_write: 6.25, cache_write_1h: 10, cache_read: 0.5 },
34
+ "claude-opus-4-6": { input: 5, output: 25, cache_write: 6.25, cache_write_1h: 10, cache_read: 0.5 },
35
+ "claude-opus-4-5": { input: 5, output: 25, cache_write: 6.25, cache_write_1h: 10, cache_read: 0.5 },
36
+ "claude-opus-4-1": { input: 15, output: 75, cache_write: 18.75, cache_write_1h: 30, cache_read: 1.5 },
37
+ "claude-opus-4": { input: 15, output: 75, cache_write: 18.75, cache_write_1h: 30, cache_read: 1.5 },
38
+ "claude-sonnet-4-6": { input: 3, output: 15, cache_write: 3.75, cache_write_1h: 6, cache_read: 0.3 },
39
+ "claude-sonnet-4-5": { input: 3, output: 15, cache_write: 3.75, cache_write_1h: 6, cache_read: 0.3 },
40
+ "claude-sonnet-4": { input: 3, output: 15, cache_write: 3.75, cache_write_1h: 6, cache_read: 0.3 },
41
+ "claude-haiku-4-5": { input: 1, output: 5, cache_write: 1.25, cache_write_1h: 2, cache_read: 0.1 },
42
+ "claude-haiku-4-5-20251001": { input: 1, output: 5, cache_write: 1.25, cache_write_1h: 2, cache_read: 0.1 },
43
+ "claude-haiku-3-5": { input: 0.8, output: 4, cache_write: 1, cache_write_1h: 1.6, cache_read: 0.08 }
32
44
  });
33
- var FALLBACK = { input: 3, output: 15, cache_write: 3.75, cache_read: 0.3 };
45
+ var FALLBACK = { input: 3, output: 15, cache_write: 3.75, cache_write_1h: 6, cache_read: 0.3 };
46
+ function canonicalModel(model) {
47
+ if (!model) return null;
48
+ const noTag = model.replace(/\[[^\]]*\]$/, "");
49
+ return noTag.replace(/-\d{8}$/, "");
50
+ }
51
+ function lookup(model) {
52
+ if (!model) return null;
53
+ return PRICES_PER_MTOK[model] ?? PRICES_PER_MTOK[model.replace(/\[[^\]]*\]$/, "")] ?? PRICES_PER_MTOK[canonicalModel(model) ?? ""] ?? null;
54
+ }
34
55
  function priceFor(model) {
35
56
  return lookup(model) ?? FALLBACK;
36
57
  }
37
58
  function isKnownModel(model) {
38
59
  return lookup(model) !== null;
39
60
  }
40
- function lookup(model) {
41
- if (!model) return null;
42
- const exact = PRICES_PER_MTOK[model];
43
- if (exact) return exact;
44
- const noTag = model.replace(/\[[^\]]*\]$/, "");
45
- if (PRICES_PER_MTOK[noTag]) return PRICES_PER_MTOK[noTag];
46
- const noDate = noTag.replace(/-\d{8}$/, "");
47
- if (PRICES_PER_MTOK[noDate]) return PRICES_PER_MTOK[noDate];
48
- return null;
61
+ function readCounter(value, present) {
62
+ if (!present) return { value: 0, present: false, invalid: false };
63
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? { value, present: true, invalid: false } : { value: 0, present: true, invalid: true };
64
+ }
65
+ function own(value, key) {
66
+ return Object.prototype.hasOwnProperty.call(value, key);
67
+ }
68
+ function normalizeUsage(raw) {
69
+ const usage = raw && typeof raw === "object" ? raw : {};
70
+ const warnings = /* @__PURE__ */ new Set();
71
+ const input = readCounter(usage.input_tokens, own(usage, "input_tokens"));
72
+ const output = readCounter(usage.output_tokens, own(usage, "output_tokens"));
73
+ const cacheRead = readCounter(usage.cache_read_input_tokens, own(usage, "cache_read_input_tokens"));
74
+ const cacheTop = readCounter(usage.cache_creation_input_tokens, own(usage, "cache_creation_input_tokens"));
75
+ let splitPresent = false;
76
+ let splitMalformed = false;
77
+ let cache5m = { value: 0, present: false, invalid: false };
78
+ let cache1h = { value: 0, present: false, invalid: false };
79
+ const splitProvided = own(usage, "cache_creation");
80
+ if (splitProvided) {
81
+ if (usage.cache_creation && typeof usage.cache_creation === "object" && !Array.isArray(usage.cache_creation)) {
82
+ const split = usage.cache_creation;
83
+ cache5m = readCounter(split.ephemeral_5m_input_tokens, own(split, "ephemeral_5m_input_tokens"));
84
+ cache1h = readCounter(split.ephemeral_1h_input_tokens, own(split, "ephemeral_1h_input_tokens"));
85
+ splitPresent = cache5m.present || cache1h.present;
86
+ } else {
87
+ splitMalformed = true;
88
+ }
89
+ }
90
+ let invalid = input.invalid || output.invalid || cacheRead.invalid || cacheTop.invalid || cache5m.invalid || cache1h.invalid || splitMalformed;
91
+ if (invalid) warnings.add(INVALID_USAGE_WARNING);
92
+ const validSplitSum = cache5m.value + cache1h.value;
93
+ let creationTotal = 0;
94
+ let creation5m = 0;
95
+ let creation1h = 0;
96
+ let conflicting = false;
97
+ if (cacheTop.present && !cacheTop.invalid) {
98
+ creationTotal = cacheTop.value;
99
+ if (splitPresent && !cache5m.invalid && !cache1h.invalid) {
100
+ if (validSplitSum === cacheTop.value) {
101
+ creation5m = cache5m.value;
102
+ creation1h = cache1h.value;
103
+ } else {
104
+ conflicting = true;
105
+ creation1h = cacheTop.value;
106
+ warnings.add(CACHE_SPLIT_CONFLICT_WARNING);
107
+ }
108
+ } else if (splitProvided) {
109
+ creation1h = cacheTop.value;
110
+ warnings.add(CACHE_TTL_FALLBACK_WARNING);
111
+ } else {
112
+ creation5m = cacheTop.value;
113
+ if (cacheTop.value > 0) warnings.add(CACHE_TTL_ASSUMED_WARNING);
114
+ }
115
+ } else if (splitPresent) {
116
+ creationTotal = validSplitSum;
117
+ creation5m = cache5m.value;
118
+ creation1h = cache1h.value;
119
+ }
120
+ let speed = "standard";
121
+ if (usage.speed === "fast") speed = "fast";
122
+ else if (usage.speed != null && usage.speed !== "standard") warnings.add(UNSUPPORTED_PRICING_WARNING);
123
+ let inferenceGeo = "global";
124
+ if (usage.inference_geo === "us") inferenceGeo = "us";
125
+ else if (usage.inference_geo != null && usage.inference_geo !== "global") warnings.add(UNSUPPORTED_PRICING_WARNING);
126
+ let batch = false;
127
+ if (usage.batch === true) batch = true;
128
+ else if (usage.batch != null && usage.batch !== false) warnings.add(UNSUPPORTED_PRICING_WARNING);
129
+ let webSearch = { value: 0, present: false, invalid: false };
130
+ if (own(usage, "server_tool_use")) {
131
+ if (usage.server_tool_use && typeof usage.server_tool_use === "object" && !Array.isArray(usage.server_tool_use)) {
132
+ const server = usage.server_tool_use;
133
+ webSearch = readCounter(server.web_search_requests, own(server, "web_search_requests"));
134
+ } else {
135
+ webSearch = { value: 0, present: true, invalid: true };
136
+ }
137
+ }
138
+ if (webSearch.invalid) {
139
+ invalid = true;
140
+ warnings.add(INVALID_USAGE_WARNING);
141
+ }
142
+ const normalized = {
143
+ input_tokens: input.value,
144
+ output_tokens: output.value,
145
+ cache_creation_input_tokens: creationTotal,
146
+ cache_read_input_tokens: cacheRead.value,
147
+ cache_creation_5m_input_tokens: creation5m,
148
+ cache_creation_1h_input_tokens: creation1h,
149
+ cache_ttl_known: splitPresent || splitProvided,
150
+ web_search_requests: webSearch.value,
151
+ speed,
152
+ inference_geo: inferenceGeo,
153
+ batch
154
+ };
155
+ const billable = normalized.input_tokens > 0 || normalized.output_tokens > 0 || normalized.cache_creation_input_tokens > 0 || normalized.cache_read_input_tokens > 0 || normalized.web_search_requests > 0;
156
+ return { usage: normalized, billable, warnings: [...warnings], invalid, conflicting };
157
+ }
158
+ function pricingMultiplier(model, usage, warnings) {
159
+ let multiplier = 1;
160
+ if (usage.speed === "fast") {
161
+ const base = canonicalModel(model);
162
+ if (base === "claude-opus-5" || base === "claude-opus-4-8") multiplier *= 2;
163
+ else warnings?.add(UNSUPPORTED_PRICING_WARNING);
164
+ }
165
+ if (usage.inference_geo === "us") {
166
+ const base = canonicalModel(model);
167
+ const geoEligible = base != null && (base.startsWith("claude-fable-5") || base.startsWith("claude-mythos-5") || base === "claude-opus-5" || base === "claude-opus-4-8" || base === "claude-opus-4-7" || base === "claude-opus-4-6" || base === "claude-sonnet-5" || base === "claude-sonnet-4-6");
168
+ if (geoEligible) multiplier *= 1.1;
169
+ else warnings?.add(UNSUPPORTED_PRICING_WARNING);
170
+ }
171
+ if (usage.batch) multiplier *= 0.5;
172
+ return multiplier;
173
+ }
174
+ function costForNormalizedUsage(model, usage, warnings) {
175
+ const p = priceFor(model);
176
+ const tokenCost = (usage.input_tokens * p.input + usage.output_tokens * p.output + usage.cache_creation_5m_input_tokens * p.cache_write + usage.cache_creation_1h_input_tokens * p.cache_write_1h + usage.cache_read_input_tokens * p.cache_read) / 1e6;
177
+ return tokenCost * pricingMultiplier(model, usage, warnings) + usage.web_search_requests * 0.01;
49
178
  }
50
- var num = (v) => Number(v) || 0;
51
179
  function costForUsage(model, usage) {
180
+ return costForNormalizedUsage(model, normalizeUsage(usage).usage);
181
+ }
182
+ function cacheSavingsForNormalizedUsage(model, usage) {
183
+ const p = priceFor(model);
184
+ return usage.cache_read_input_tokens * (p.input - p.cache_read) * pricingMultiplier(model, usage) / 1e6;
185
+ }
186
+ function cacheMissExposureForNormalizedUsage(model, usage) {
52
187
  const p = priceFor(model);
53
- const i = num(usage?.input_tokens);
54
- const o = num(usage?.output_tokens);
55
- const cw = num(usage?.cache_creation_input_tokens);
56
- const cr = num(usage?.cache_read_input_tokens);
57
- return (i * p.input + o * p.output + cw * p.cache_write + cr * p.cache_read) / 1e6;
188
+ return (usage.input_tokens * (p.input - p.cache_read) + usage.cache_creation_5m_input_tokens * (p.cache_write - p.cache_read) + usage.cache_creation_1h_input_tokens * (p.cache_write_1h - p.cache_read)) * pricingMultiplier(model, usage) / 1e6;
58
189
  }
59
- function cacheSavingsForUsage(model, usage) {
190
+ function uncachedInputExposureForNormalizedUsage(model, usage) {
60
191
  const p = priceFor(model);
61
- const cr = num(usage?.cache_read_input_tokens);
62
- return cr * (p.input - p.cache_read) / 1e6;
192
+ return usage.input_tokens * (p.input - p.cache_read) * pricingMultiplier(model, usage) / 1e6;
193
+ }
194
+ function cacheWritePremiumForNormalizedUsage(model, usage) {
195
+ const p = priceFor(model);
196
+ return (usage.cache_creation_5m_input_tokens * (p.cache_write - p.cache_read) + usage.cache_creation_1h_input_tokens * (p.cache_write_1h - p.cache_read)) * pricingMultiplier(model, usage) / 1e6;
197
+ }
198
+ function cacheAmortizationShare(totals) {
199
+ const writes = totals.cache_creation_tokens;
200
+ if (!Number.isFinite(writes) || writes <= 0) return 1;
201
+ const reads = Number.isFinite(totals.cache_read_tokens) ? totals.cache_read_tokens : 0;
202
+ return Math.min(1, Math.max(0, reads / writes));
203
+ }
204
+ function uncachedInputExposureForTotals(model, totals) {
205
+ return uncachedInputExposureForNormalizedUsage(model, normalizeUsage(usageForTotals(totals)).usage);
206
+ }
207
+ function cacheWritePremiumForTotals(model, totals) {
208
+ return cacheWritePremiumForNormalizedUsage(model, normalizeUsage(usageForTotals(totals)).usage);
209
+ }
210
+ function recoverableExposureForTotals(model, totals) {
211
+ const unamortized = 1 - cacheAmortizationShare(totals);
212
+ return uncachedInputExposureForTotals(model, totals) + cacheWritePremiumForTotals(model, totals) * unamortized;
63
213
  }
64
214
  function cacheHitRate(totals) {
65
- const denom = num(totals.input_tokens) + num(totals.cache_creation_tokens) + num(totals.cache_read_tokens);
66
- if (!denom) return 0;
67
- return num(totals.cache_read_tokens) / denom;
215
+ const denom = totals.input_tokens + totals.cache_creation_tokens + totals.cache_read_tokens;
216
+ if (!Number.isFinite(denom) || denom <= 0) return 0;
217
+ return totals.cache_read_tokens / denom;
218
+ }
219
+ function usageForTotals(totals) {
220
+ const splitDefined = totals.cache_creation_5m_tokens != null || totals.cache_creation_1h_tokens != null;
221
+ return {
222
+ input_tokens: totals.input_tokens,
223
+ output_tokens: totals.output_tokens,
224
+ cache_creation_input_tokens: totals.cache_creation_tokens,
225
+ cache_read_input_tokens: totals.cache_read_tokens,
226
+ ...splitDefined ? { cache_creation: {
227
+ ephemeral_5m_input_tokens: totals.cache_creation_5m_tokens ?? 0,
228
+ ephemeral_1h_input_tokens: totals.cache_creation_1h_tokens ?? 0
229
+ } } : {}
230
+ };
68
231
  }
69
232
  function costForTotals(model, totals) {
70
- const p = priceFor(model);
71
- return (totals.input_tokens * p.input + totals.output_tokens * p.output + totals.cache_creation_tokens * p.cache_write + totals.cache_read_tokens * p.cache_read) / 1e6;
233
+ return costForUsage(model, usageForTotals(totals));
234
+ }
235
+ function cacheMissExposureForTotals(model, totals) {
236
+ return cacheMissExposureForNormalizedUsage(model, normalizeUsage(usageForTotals(totals)).usage);
237
+ }
238
+ function roundMoneyHalfUp(value, places = 2) {
239
+ if (!Number.isFinite(value) || !Number.isInteger(places) || places < 0 || places > 12) return value;
240
+ const factor = 10 ** places;
241
+ const scaled = Math.abs(value) * factor;
242
+ const tolerance = Number.EPSILON * Math.max(1, scaled) * 2;
243
+ return Math.sign(value) * Math.floor(scaled + 0.5 + tolerance) / factor;
72
244
  }
73
245
  function isOpus(model) {
74
- if (!model) return false;
75
- return model.replace(/\[[^\]]*\]$/, "").startsWith("claude-opus");
246
+ return canonicalModel(model)?.startsWith("claude-opus") ?? false;
76
247
  }
77
248
  function isPremiumModel(model) {
78
- if (!model) return false;
79
- const base = model.replace(/\[[^\]]*\]$/, "");
80
- return base.startsWith("claude-opus") || base.startsWith("claude-fable");
249
+ const base = canonicalModel(model);
250
+ return base?.startsWith("claude-opus") === true || base?.startsWith("claude-fable") === true || base?.startsWith("claude-mythos") === true;
81
251
  }
82
252
 
83
253
  // ../../packages/engine/src/sanitize.ts
@@ -191,19 +361,113 @@ function emptyPromptSignals() {
191
361
  }
192
362
  var isToolUse = (b) => !!b && typeof b === "object" && b.type === "tool_use" && typeof b.name === "string";
193
363
  function extractTools(content) {
194
- const names = [];
195
364
  const events = [];
196
365
  if (Array.isArray(content)) {
197
366
  for (const block of content) {
198
367
  if (isToolUse(block)) {
199
368
  const name = block.name;
200
369
  const input = block.input ?? {};
201
- names.push(name);
202
- events.push({ name, target: targetFor(name, input) });
370
+ events.push({ id: typeof block.id === "string" ? block.id : null, name, target: targetFor(name, input), input });
203
371
  }
204
372
  }
205
373
  }
206
- return { names, events };
374
+ return { events };
375
+ }
376
+ function logicalUsageKey(rec) {
377
+ const requestId = rec.requestId || rec.message?.requestId;
378
+ if (requestId) return `req:${requestId}`;
379
+ const messageId = rec.message?.id;
380
+ return messageId ? `msg:${messageId}` : null;
381
+ }
382
+ var CUMULATIVE_CONFLICT_WARNING = "Conflicting cumulative usage snapshots were not added; the highest coherent snapshot was used.";
383
+ var MODEL_CHANGE_WARNING = "A request changed models across snapshots; one coherent snapshot was valued.";
384
+ function usageVector(u) {
385
+ return [u.input_tokens, u.output_tokens, u.cache_creation_input_tokens, u.cache_read_input_tokens, u.web_search_requests];
386
+ }
387
+ function samePricingMode(a, b) {
388
+ return a.speed === b.speed && a.inference_geo === b.inference_geo && a.batch === b.batch;
389
+ }
390
+ function growsFrom(next, previous) {
391
+ if (next.invalid && !previous.invalid) return false;
392
+ if (next.model !== previous.model || !samePricingMode(next.normalized, previous.normalized)) return false;
393
+ if (previous.normalized.cache_ttl_known && !next.normalized.cache_ttl_known) return false;
394
+ if (previous.normalized.cache_ttl_known && next.normalized.cache_ttl_known && (previous.normalized.cache_creation_5m_input_tokens !== next.normalized.cache_creation_5m_input_tokens || previous.normalized.cache_creation_1h_input_tokens !== next.normalized.cache_creation_1h_input_tokens)) return false;
395
+ const a = usageVector(next.normalized);
396
+ const b = usageVector(previous.normalized);
397
+ return a.every((value, index) => value >= b[index]);
398
+ }
399
+ function sameCandidate(a, b) {
400
+ return a.model === b.model && samePricingMode(a.normalized, b.normalized) && usageVector(a.normalized).every((value, index) => value === usageVector(b.normalized)[index]) && a.normalized.cache_creation_5m_input_tokens === b.normalized.cache_creation_5m_input_tokens && a.normalized.cache_creation_1h_input_tokens === b.normalized.cache_creation_1h_input_tokens;
401
+ }
402
+ function preferredCandidate(a, b) {
403
+ if (a.invalid !== b.invalid) return a.invalid ? b : a;
404
+ if (sameCandidate(a, b) || growsFrom(b, a)) return b;
405
+ if (growsFrom(a, b)) return a;
406
+ const aCost = costForNormalizedUsage(a.model, a.normalized);
407
+ const bCost = costForNormalizedUsage(b.model, b.normalized);
408
+ return bCost >= aCost ? b : a;
409
+ }
410
+ function rebuildSessionUsage(session, fragments, extraWarnings = []) {
411
+ session.usageFragments = fragments;
412
+ session.fragmentsWithUsage = fragments.length;
413
+ session.modelRequests = fragments.length;
414
+ session.totals = emptyTotals();
415
+ session.cost_usd = 0;
416
+ session.cache_savings_usd = 0;
417
+ session.cacheMissExposureUsd = 0;
418
+ session.uncachedInputExposureUsd = 0;
419
+ session.cacheWritePremiumUsd = 0;
420
+ session.modelCostsUsd = {};
421
+ session.unknownModelRequests = {};
422
+ session.pricedRequests = 0;
423
+ session.turnCache = [];
424
+ session.turnCacheExposureUsd = [];
425
+ const buckets = /* @__PURE__ */ new Map();
426
+ const modelCounts = /* @__PURE__ */ new Map();
427
+ let splitKnown = false;
428
+ let cache5mTokens = 0;
429
+ let cache1hTokens = 0;
430
+ for (const fragment of fragments) {
431
+ session.totals.input_tokens += fragment.input_tokens;
432
+ session.totals.output_tokens += fragment.output_tokens;
433
+ session.totals.cache_creation_tokens += fragment.cache_creation_tokens;
434
+ session.totals.cache_read_tokens += fragment.cache_read_tokens;
435
+ splitKnown ||= fragment.cacheTtlKnown;
436
+ cache5mTokens += fragment.cache_creation_5m_tokens;
437
+ cache1hTokens += fragment.cache_creation_1h_tokens;
438
+ session.cost_usd += fragment.costUsd;
439
+ session.cache_savings_usd += fragment.cacheSavingsUsd;
440
+ session.cacheMissExposureUsd += fragment.cacheMissExposureUsd;
441
+ session.uncachedInputExposureUsd += fragment.uncachedInputExposureUsd;
442
+ session.cacheWritePremiumUsd += fragment.cacheWritePremiumUsd;
443
+ const modelKey = fragment.model ?? "unknown";
444
+ session.modelCostsUsd[modelKey] = (session.modelCostsUsd[modelKey] ?? 0) + fragment.costUsd;
445
+ if (fragment.model && isKnownModel(fragment.model)) session.pricedRequests += 1;
446
+ else session.unknownModelRequests[modelKey] = (session.unknownModelRequests[modelKey] ?? 0) + 1;
447
+ if (fragment.model && fragment.model !== "<synthetic>") modelCounts.set(fragment.model, (modelCounts.get(fragment.model) ?? 0) + 1);
448
+ session.turnCache.push({ read: fragment.cache_read_tokens, miss: fragment.input_tokens + fragment.cache_creation_tokens });
449
+ session.turnCacheExposureUsd.push(fragment.cacheMissExposureUsd);
450
+ if (fragment.timestampMs != null) {
451
+ const t = Math.floor(fragment.timestampMs / (15 * 60 * 1e3));
452
+ buckets.set(t, (buckets.get(t) ?? 0) + fragment.costUsd);
453
+ }
454
+ }
455
+ if (splitKnown) {
456
+ session.totals.cache_creation_5m_tokens = cache5mTokens;
457
+ session.totals.cache_creation_1h_tokens = cache1hTokens;
458
+ } else {
459
+ delete session.totals.cache_creation_5m_tokens;
460
+ delete session.totals.cache_creation_1h_tokens;
461
+ }
462
+ session.costBuckets = [...buckets.entries()].sort((a, b) => a[0] - b[0]).map(([t, usd8]) => ({ t, usd: usd8 }));
463
+ let best = null;
464
+ let bestCount = 0;
465
+ for (const [model, count] of modelCounts) if (count > bestCount) {
466
+ best = model;
467
+ bestCount = count;
468
+ }
469
+ session.modelPrimary = best;
470
+ session.accuracyWarnings = [.../* @__PURE__ */ new Set([...session.accuracyWarnings ?? [], ...extraWarnings])];
207
471
  }
208
472
  function parseSession(text2, opts = {}) {
209
473
  const s = {
@@ -229,13 +493,22 @@ function parseSession(text2, opts = {}) {
229
493
  parentSessionId: opts.parentSessionId ?? null,
230
494
  turnCache: [],
231
495
  costBuckets: [],
496
+ modelCostsUsd: {},
497
+ cacheMissExposureUsd: 0,
498
+ uncachedInputExposureUsd: 0,
499
+ cacheWritePremiumUsd: 0,
500
+ accuracyWarnings: [],
501
+ unknownModelRequests: {},
502
+ pricedRequests: 0,
503
+ invalidUsageRecords: 0,
504
+ conflictingUsageRecords: 0,
505
+ usageFragments: [],
506
+ usageLogicalKeys: [],
232
507
  prompting: emptyPromptSignals()
233
508
  };
234
509
  const ps = s.prompting;
235
- const seen = /* @__PURE__ */ new Set();
236
- const buckets = /* @__PURE__ */ new Map();
237
- const BUCKET_MS = 15 * 60 * 1e3;
238
- const modelCounts = /* @__PURE__ */ new Map();
510
+ const usageGroups = /* @__PURE__ */ new Map();
511
+ const seenTools = /* @__PURE__ */ new Set();
239
512
  let cwd = null;
240
513
  let seq = 0;
241
514
  for (const line of text2.split("\n")) {
@@ -270,75 +543,179 @@ function parseSession(text2, opts = {}) {
270
543
  }
271
544
  }
272
545
  } else s.assistantRecords += 1;
273
- const model = rec.message?.model;
274
- if (model && model !== "<synthetic>") modelCounts.set(model, (modelCounts.get(model) ?? 0) + 1);
546
+ const model = rec.message?.model ?? null;
275
547
  if (rec.type === "assistant") {
276
- const { names, events } = extractTools(rec.message?.content);
277
- for (const n of names) {
278
- s.toolUsage[n] = (s.toolUsage[n] ?? 0) + 1;
279
- if (PLAN_TOOLS.has(n)) ps.planEvents += 1;
280
- }
281
- if (Array.isArray(rec.message?.content)) {
282
- for (const b of rec.message.content) {
283
- if (isToolUse(b) && (b.name === "Bash" || b.name === "PowerShell") && typeof b.input?.command === "string" && isVerifyCommand(b.input.command)) ps.verifyRuns += 1;
284
- }
285
- }
548
+ const { events } = extractTools(rec.message?.content);
286
549
  const requestId = rec.requestId || rec.message?.requestId || null;
287
- for (const e of events) s.toolEvents.push({ name: e.name, requestId, target: e.target });
550
+ const rowIdentity = logicalUsageKey(rec) ?? (rec.uuid ? `row:${rec.uuid}` : `row:#${s.jsonlRecords}`);
551
+ for (let index = 0; index < events.length; index += 1) {
552
+ const event = events[index];
553
+ const toolKey = event.id ? `tool:${event.id}` : `${rowIdentity}:${index}:${event.name}:${JSON.stringify(event.input)}`;
554
+ if (seenTools.has(toolKey)) continue;
555
+ seenTools.add(toolKey);
556
+ s.toolUsage[event.name] = (s.toolUsage[event.name] ?? 0) + 1;
557
+ if (PLAN_TOOLS.has(event.name)) ps.planEvents += 1;
558
+ if ((event.name === "Bash" || event.name === "PowerShell") && typeof event.input.command === "string" && isVerifyCommand(event.input.command)) ps.verifyRuns += 1;
559
+ s.toolEvents.push({ name: event.name, requestId, target: event.target });
560
+ }
288
561
  const usage = rec.message?.usage;
289
562
  if (usage) {
290
563
  seq += 1;
291
564
  const key = usageKey(rec, seq);
292
- if (seen.has(key)) {
293
- s.duplicateFragmentsSkipped += 1;
294
- continue;
295
- }
296
- seen.add(key);
297
- s.fragmentsWithUsage += 1;
298
- s.modelRequests += 1;
299
- s.totals.input_tokens += Number(usage.input_tokens) || 0;
300
- s.totals.output_tokens += Number(usage.output_tokens) || 0;
301
- s.totals.cache_creation_tokens += Number(usage.cache_creation_input_tokens) || 0;
302
- s.totals.cache_read_tokens += Number(usage.cache_read_input_tokens) || 0;
303
- const fragmentUsd = costForUsage(model, usage);
304
- s.cost_usd += fragmentUsd;
305
- s.cache_savings_usd += cacheSavingsForUsage(model, usage);
306
- if (rec.timestamp) {
307
- const ms = Date.parse(rec.timestamp);
308
- if (!Number.isNaN(ms)) {
309
- const t = Math.floor(ms / BUCKET_MS);
310
- buckets.set(t, (buckets.get(t) ?? 0) + fragmentUsd);
311
- }
312
- }
313
- s.turnCache.push({
314
- read: Number(usage.cache_read_input_tokens) || 0,
315
- miss: (Number(usage.input_tokens) || 0) + (Number(usage.cache_creation_input_tokens) || 0)
565
+ const logicalKey = logicalUsageKey(rec);
566
+ if (logicalKey && !s.usageLogicalKeys.includes(logicalKey)) s.usageLogicalKeys.push(logicalKey);
567
+ const normalized = normalizeUsage(usage);
568
+ if (normalized.invalid) s.invalidUsageRecords = (s.invalidUsageRecords ?? 0) + 1;
569
+ if (normalized.conflicting) s.conflictingUsageRecords = (s.conflictingUsageRecords ?? 0) + 1;
570
+ s.accuracyWarnings.push(...normalized.warnings);
571
+ if (!normalized.billable) continue;
572
+ const timestampMs = rec.timestamp ? Date.parse(rec.timestamp) : NaN;
573
+ const candidates = usageGroups.get(key) ?? [];
574
+ candidates.push({
575
+ normalized: normalized.usage,
576
+ model,
577
+ logicalKey,
578
+ timestampMs: Number.isNaN(timestampMs) ? null : timestampMs,
579
+ invalid: normalized.invalid
316
580
  });
581
+ usageGroups.set(key, candidates);
317
582
  }
318
583
  }
319
584
  }
320
- s.costBuckets = [...buckets.entries()].sort((a, b) => a[0] - b[0]).map(([t, usd8]) => ({ t, usd: usd8 }));
321
- s.projectSlug = opts.projectSlug ?? projectFromCwd(cwd);
322
- let best = null;
323
- let bestCount = 0;
324
- for (const [m, c] of modelCounts) if (c > bestCount) {
325
- best = m;
326
- bestCount = c;
585
+ const fragments = [];
586
+ for (const candidates of usageGroups.values()) {
587
+ s.duplicateFragmentsSkipped += Math.max(0, candidates.length - 1);
588
+ let accepted = candidates[0];
589
+ let conflict = false;
590
+ let modelChanged = false;
591
+ for (let index = 1; index < candidates.length; index += 1) {
592
+ const candidate = candidates[index];
593
+ if (candidate.model !== accepted.model) modelChanged = true;
594
+ if (!sameCandidate(candidate, accepted) && !growsFrom(candidate, accepted)) conflict = true;
595
+ accepted = preferredCandidate(accepted, candidate);
596
+ }
597
+ if (modelChanged) s.accuracyWarnings.push(MODEL_CHANGE_WARNING);
598
+ if (conflict || modelChanged) {
599
+ s.conflictingUsageRecords = (s.conflictingUsageRecords ?? 0) + 1;
600
+ s.accuracyWarnings.push(CUMULATIVE_CONFLICT_WARNING);
601
+ }
602
+ const pricingWarnings = /* @__PURE__ */ new Set();
603
+ const u = accepted.normalized;
604
+ const fragmentUsd = costForNormalizedUsage(accepted.model, u, pricingWarnings);
605
+ s.accuracyWarnings.push(...pricingWarnings);
606
+ fragments.push({
607
+ logicalKey: accepted.logicalKey,
608
+ model: accepted.model,
609
+ input_tokens: u.input_tokens,
610
+ output_tokens: u.output_tokens,
611
+ cache_creation_tokens: u.cache_creation_input_tokens,
612
+ cache_read_tokens: u.cache_read_input_tokens,
613
+ cache_creation_5m_tokens: u.cache_creation_5m_input_tokens,
614
+ cache_creation_1h_tokens: u.cache_creation_1h_input_tokens,
615
+ cacheTtlKnown: u.cache_ttl_known,
616
+ accountingSignature: JSON.stringify({
617
+ model: accepted.model,
618
+ input: u.input_tokens,
619
+ output: u.output_tokens,
620
+ cache5m: u.cache_creation_5m_input_tokens,
621
+ cache1h: u.cache_creation_1h_input_tokens,
622
+ cacheRead: u.cache_read_input_tokens,
623
+ searches: u.web_search_requests,
624
+ speed: u.speed,
625
+ geo: u.inference_geo,
626
+ batch: u.batch
627
+ }),
628
+ costUsd: fragmentUsd,
629
+ cacheSavingsUsd: cacheSavingsForNormalizedUsage(accepted.model, u),
630
+ cacheMissExposureUsd: cacheMissExposureForNormalizedUsage(accepted.model, u),
631
+ uncachedInputExposureUsd: uncachedInputExposureForNormalizedUsage(accepted.model, u),
632
+ cacheWritePremiumUsd: cacheWritePremiumForNormalizedUsage(accepted.model, u),
633
+ timestampMs: accepted.timestampMs
634
+ });
327
635
  }
328
- s.modelPrimary = best;
636
+ rebuildSessionUsage(s, fragments);
637
+ s.projectSlug = opts.projectSlug ?? projectFromCwd(cwd);
329
638
  if (s.startedAt && s.endedAt) {
330
639
  const ms = Date.parse(s.endedAt) - Date.parse(s.startedAt);
331
- s.durationMinutes = Number.isNaN(ms) ? null : ms / 6e4;
640
+ s.durationMinutes = Number.isNaN(ms) || ms < 0 ? null : ms / 6e4;
332
641
  }
333
642
  return s;
334
643
  }
335
644
 
336
645
  // ../../packages/engine/src/aggregate.ts
337
646
  function addTotals(into, from) {
647
+ const priorCreation = into.cache_creation_tokens;
338
648
  into.input_tokens += from.input_tokens;
339
649
  into.output_tokens += from.output_tokens;
340
650
  into.cache_creation_tokens += from.cache_creation_tokens;
341
651
  into.cache_read_tokens += from.cache_read_tokens;
652
+ const intoHasSplit = into.cache_creation_5m_tokens != null || into.cache_creation_1h_tokens != null;
653
+ const fromHasSplit = from.cache_creation_5m_tokens != null || from.cache_creation_1h_tokens != null;
654
+ if (intoHasSplit || fromHasSplit) {
655
+ into.cache_creation_5m_tokens = (into.cache_creation_5m_tokens ?? priorCreation) + (from.cache_creation_5m_tokens ?? from.cache_creation_tokens);
656
+ into.cache_creation_1h_tokens = (into.cache_creation_1h_tokens ?? 0) + (from.cache_creation_1h_tokens ?? 0);
657
+ }
658
+ }
659
+ function safeModelId(model) {
660
+ return /^[A-Za-z0-9._:\[\]-]{1,100}$/.test(model) ? model : "unknown";
661
+ }
662
+ function buildAccuracy(sessions) {
663
+ const warningSet = /* @__PURE__ */ new Set([
664
+ "Values are estimated at the current list-price snapshot; records without explicit pricing metadata use standard rates."
665
+ ]);
666
+ const unknown = /* @__PURE__ */ new Map();
667
+ let pricedRequests = 0;
668
+ let totalBillableRequests = 0;
669
+ let invalidUsageRecords = 0;
670
+ let conflictingUsageRecords = 0;
671
+ for (const session of sessions) {
672
+ for (const warning of session.accuracyWarnings ?? []) warningSet.add(warning);
673
+ pricedRequests += session.pricedRequests ?? 0;
674
+ totalBillableRequests += session.modelRequests;
675
+ invalidUsageRecords += session.invalidUsageRecords ?? 0;
676
+ conflictingUsageRecords += session.conflictingUsageRecords ?? 0;
677
+ for (const [model, requests] of Object.entries(session.unknownModelRequests ?? {})) {
678
+ const safe = safeModelId(model);
679
+ unknown.set(safe, (unknown.get(safe) ?? 0) + requests);
680
+ }
681
+ }
682
+ const unknownModels = [...unknown.entries()].map(([model, requests]) => ({ model, requests })).sort((a, b) => b.requests - a.requests || a.model.localeCompare(b.model));
683
+ for (const { model } of unknownModels) warningSet.add(`Unknown model ${model} used estimated fallback pricing.`);
684
+ return {
685
+ basis: "current_list_prices",
686
+ estimated: true,
687
+ pricingSnapshotDate: PRICING_SNAPSHOT_DATE,
688
+ accountingVersion: "2",
689
+ warnings: [...warningSet],
690
+ pricedRequests,
691
+ totalBillableRequests,
692
+ unknownModels,
693
+ invalidUsageRecords,
694
+ conflictingUsageRecords
695
+ };
696
+ }
697
+ function unionDurationHours(sessions) {
698
+ const intervals = sessions.flatMap((session) => {
699
+ if (!session.startedAt || !session.endedAt) return [];
700
+ const start2 = Date.parse(session.startedAt);
701
+ const end2 = Date.parse(session.endedAt);
702
+ return Number.isFinite(start2) && Number.isFinite(end2) && end2 > start2 ? [[start2, end2]] : [];
703
+ }).sort((a, b) => a[0] - b[0] || a[1] - b[1]);
704
+ let totalMs = 0;
705
+ let start = 0;
706
+ let end = 0;
707
+ for (const interval of intervals) {
708
+ if (end === 0) {
709
+ [start, end] = interval;
710
+ } else if (interval[0] <= end) {
711
+ end = Math.max(end, interval[1]);
712
+ } else {
713
+ totalMs += end - start;
714
+ [start, end] = interval;
715
+ }
716
+ }
717
+ if (end !== 0) totalMs += end - start;
718
+ return totalMs / 36e5;
342
719
  }
343
720
  function mostFrequent(values) {
344
721
  const counts = /* @__PURE__ */ new Map();
@@ -393,7 +770,7 @@ function buildSummary(projects) {
393
770
  let sessionsCount = 0;
394
771
  let delegatedSessionsCount = 0;
395
772
  let mainCostUsd = 0;
396
- let durationHours = 0;
773
+ const sessions = [];
397
774
  for (const p of projects) {
398
775
  addTotals(totals, p.totals);
399
776
  cost += p.cost_usd;
@@ -401,10 +778,14 @@ function buildSummary(projects) {
401
778
  sessionsCount += p.sessionsCount;
402
779
  delegatedSessionsCount += p.delegatedSessionsCount;
403
780
  for (const s of p.sessions) {
404
- const key = s.modelPrimary || "unknown";
405
- modelBreakdown[key] = (modelBreakdown[key] ?? 0) + s.cost_usd;
781
+ sessions.push(s);
782
+ const fragments = s.modelCostsUsd && Object.keys(s.modelCostsUsd).length > 0 ? s.modelCostsUsd : { [s.modelPrimary || "unknown"]: s.cost_usd };
783
+ for (const [model, modelCost] of Object.entries(fragments)) {
784
+ if (!Number.isFinite(modelCost) || modelCost === 0) continue;
785
+ const key = safeModelId(model);
786
+ modelBreakdown[key] = (modelBreakdown[key] ?? 0) + modelCost;
787
+ }
406
788
  if (s.kind === "main") mainCostUsd += s.cost_usd;
407
- if (s.durationMinutes && s.durationMinutes > 0) durationHours += s.durationMinutes / 60;
408
789
  }
409
790
  }
410
791
  return {
@@ -417,7 +798,8 @@ function buildSummary(projects) {
417
798
  totals,
418
799
  modelBreakdown,
419
800
  cacheHitRate: cacheHitRate(totals),
420
- durationHours
801
+ durationHours: unionDurationHours(sessions),
802
+ accuracy: buildAccuracy(sessions)
421
803
  };
422
804
  }
423
805
 
@@ -475,8 +857,7 @@ function ruleBadCacheHit(ctx) {
475
857
  if (!last) continue;
476
858
  let savings = 0;
477
859
  for (const s of tail) {
478
- const p = priceFor(s.modelPrimary);
479
- savings += (s.totals.cache_creation_tokens + s.totals.input_tokens) * (p.input - p.cache_read) / 1e6;
860
+ savings += s.cacheMissExposureUsd ?? cacheMissExposureForTotals(s.modelPrimary, s.totals);
480
861
  }
481
862
  out.push({
482
863
  ruleId: "BAD_CACHE_HIT",
@@ -635,8 +1016,10 @@ function ruleMarathonSession(ctx) {
635
1016
  if (lateHit >= LATE_FLOOR) continue;
636
1017
  const expectedReads = late.total * earlyHit;
637
1018
  const shortfall = Math.max(0, expectedReads - late.read);
638
- const p = priceFor(s.modelPrimary);
639
- const savings = shortfall * (p.input - p.cache_read) / 1e6;
1019
+ const lateMiss = late.total - late.read;
1020
+ const affectedShare = lateMiss > 0 ? Math.min(1, shortfall / lateMiss) : 0;
1021
+ const lateExposure = s.turnCacheExposureUsd ? s.turnCacheExposureUsd.slice(n - third, n).reduce((sum, value) => sum + value, 0) : shortfall * (priceFor(s.modelPrimary).input - priceFor(s.modelPrimary).cache_read) / 1e6;
1022
+ const savings = s.turnCacheExposureUsd ? lateExposure * affectedShare : lateExposure;
640
1023
  out.push({
641
1024
  ruleId: "MARATHON_SESSION",
642
1025
  severity: severityForSavings(savings),
@@ -741,7 +1124,7 @@ function runOptimizer(ctx) {
741
1124
 
742
1125
  // ../../packages/engine/src/report.ts
743
1126
  function analyzeUploads(files) {
744
- const sessions = files.map(
1127
+ const parsed = files.map(
745
1128
  (f) => parseSession(f.text, {
746
1129
  // Path-encoded slugs are anonymized before grouping so no downstream
747
1130
  // consumer (optimizer prose, synthesize, the AuditRecord) ever sees one.
@@ -750,18 +1133,145 @@ function analyzeUploads(files) {
750
1133
  parentSessionId: f.parentSessionId ?? null
751
1134
  })
752
1135
  );
1136
+ const sessions = deduplicateLogicalRequests(parsed);
753
1137
  const projects = buildProjects(sessions);
754
1138
  const summary = buildSummary(projects);
755
1139
  const findings = runOptimizer({ projects, summary });
756
1140
  return { summary, projects, findings };
757
1141
  }
1142
+ var CROSS_FILE_DUPLICATE_WARNING = "Copied logical requests across uploaded logs were counted once.";
1143
+ var CROSS_FILE_CONFLICT_WARNING = "Conflicting copies of a logical request were not added; the highest coherent valuation was retained.";
1144
+ function ownerRank(session) {
1145
+ return session.kind === "main" ? 0 : session.kind === "subagent" ? 1 : 2;
1146
+ }
1147
+ function deduplicateLogicalRequests(sessions) {
1148
+ const originalCounts = sessions.map((session) => session.usageFragments?.length ?? 0);
1149
+ const groups = /* @__PURE__ */ new Map();
1150
+ for (let sessionIndex = 0; sessionIndex < sessions.length; sessionIndex += 1) {
1151
+ for (const fragment of sessions[sessionIndex].usageFragments ?? []) {
1152
+ if (!fragment.logicalKey) continue;
1153
+ const group = groups.get(fragment.logicalKey) ?? [];
1154
+ group.push({ sessionIndex, fragment });
1155
+ groups.set(fragment.logicalKey, group);
1156
+ }
1157
+ }
1158
+ const assigned = sessions.map(() => []);
1159
+ const ownerIndexes = /* @__PURE__ */ new Map();
1160
+ const dropSessions = sessions.map(() => false);
1161
+ for (const [key, refs] of groups) {
1162
+ if (refs.length === 1) {
1163
+ assigned[refs[0].sessionIndex].push(refs[0].fragment);
1164
+ ownerIndexes.set(key, refs[0].sessionIndex);
1165
+ continue;
1166
+ }
1167
+ const owner = refs.slice().sort((a, b) => ownerRank(sessions[a.sessionIndex]) - ownerRank(sessions[b.sessionIndex]) || a.sessionIndex - b.sessionIndex)[0];
1168
+ ownerIndexes.set(key, owner.sessionIndex);
1169
+ const retained = refs.slice().sort((a, b) => b.fragment.costUsd - a.fragment.costUsd || b.fragment.output_tokens - a.fragment.output_tokens)[0].fragment;
1170
+ assigned[owner.sessionIndex].push(retained);
1171
+ sessions[owner.sessionIndex].duplicateFragmentsSkipped += refs.length - 1;
1172
+ sessions[owner.sessionIndex].accuracyWarnings = [...sessions[owner.sessionIndex].accuracyWarnings ?? [], CROSS_FILE_DUPLICATE_WARNING];
1173
+ const signatures = new Set(refs.map(({ fragment }) => fragment.accountingSignature));
1174
+ if (signatures.size > 1) {
1175
+ sessions[owner.sessionIndex].conflictingUsageRecords = (sessions[owner.sessionIndex].conflictingUsageRecords ?? 0) + 1;
1176
+ sessions[owner.sessionIndex].accuracyWarnings.push(CROSS_FILE_CONFLICT_WARNING);
1177
+ }
1178
+ }
1179
+ for (let sessionIndex = 0; sessionIndex < sessions.length; sessionIndex += 1) {
1180
+ for (const fragment of sessions[sessionIndex].usageFragments ?? []) {
1181
+ if (!fragment.logicalKey) assigned[sessionIndex].push(fragment);
1182
+ }
1183
+ }
1184
+ for (let sessionIndex = 0; sessionIndex < sessions.length; sessionIndex += 1) {
1185
+ const logicalKeys = sessions[sessionIndex].usageLogicalKeys ?? [];
1186
+ const acceptedCopyRemoved = originalCounts[sessionIndex] > 0 && assigned[sessionIndex].length === 0;
1187
+ const invalidCopyOnly = originalCounts[sessionIndex] === 0 && logicalKeys.length > 0 && logicalKeys.every((key) => ownerIndexes.has(key) && ownerIndexes.get(key) !== sessionIndex);
1188
+ if (!acceptedCopyRemoved && !invalidCopyOnly) continue;
1189
+ const removed = sessions[sessionIndex];
1190
+ const ownerIndex = [...(removed.usageFragments ?? []).map((fragment) => fragment.logicalKey), ...logicalKeys].map((key) => key ? ownerIndexes.get(key) : void 0).find((value) => value != null);
1191
+ if (ownerIndex == null || ownerIndex === sessionIndex) continue;
1192
+ const owner = sessions[ownerIndex];
1193
+ owner.accuracyWarnings = [.../* @__PURE__ */ new Set([...owner.accuracyWarnings ?? [], ...removed.accuracyWarnings ?? []])];
1194
+ owner.invalidUsageRecords = (owner.invalidUsageRecords ?? 0) + (removed.invalidUsageRecords ?? 0);
1195
+ owner.conflictingUsageRecords = (owner.conflictingUsageRecords ?? 0) + (removed.conflictingUsageRecords ?? 0);
1196
+ dropSessions[sessionIndex] = true;
1197
+ }
1198
+ for (let sessionIndex = 0; sessionIndex < sessions.length; sessionIndex += 1) {
1199
+ const session = sessions[sessionIndex];
1200
+ rebuildSessionUsage(session, assigned[sessionIndex]);
1201
+ }
1202
+ return sessions.filter((session, index) => !dropSessions[index] && ((session.usageFragments?.length ?? 0) > 0 || originalCounts[index] === 0));
1203
+ }
1204
+ function recoverableExposureForSession(s) {
1205
+ if (s.uncachedInputExposureUsd == null || s.cacheWritePremiumUsd == null) {
1206
+ return recoverableExposureForTotals(s.modelPrimary, s.totals);
1207
+ }
1208
+ return s.uncachedInputExposureUsd + s.cacheWritePremiumUsd * (1 - cacheAmortizationShare(s.totals));
1209
+ }
1210
+ function amortizedCacheWriteForSession(s) {
1211
+ const write = s.cacheWritePremiumUsd ?? cacheWritePremiumForTotals(s.modelPrimary, s.totals);
1212
+ return write * cacheAmortizationShare(s.totals);
1213
+ }
758
1214
  function cacheMissExposureUsd(report) {
759
1215
  let total = 0;
760
1216
  for (const proj of report.projects) {
761
1217
  for (const s of proj.sessions) {
762
1218
  if (s.kind !== "main") continue;
763
- const p = priceFor(s.modelPrimary);
764
- total += (s.totals.input_tokens + s.totals.cache_creation_tokens) * (p.input - p.cache_read) / 1e6;
1219
+ total += recoverableExposureForSession(s);
1220
+ }
1221
+ }
1222
+ return total;
1223
+ }
1224
+ function recoverableTotalUsd(report) {
1225
+ return cacheMissExposureUsd(report) + idleCacheExpiry(report).longIdleUsd;
1226
+ }
1227
+ function coldStartExposureUsd(report) {
1228
+ let total = 0;
1229
+ for (const proj of report.projects) {
1230
+ for (const s of proj.sessions) {
1231
+ if (s.kind !== "main") continue;
1232
+ const first = s.usageFragments?.[0];
1233
+ if (first) total += first.uncachedInputExposureUsd;
1234
+ }
1235
+ }
1236
+ return total;
1237
+ }
1238
+ var CACHE_TTL_MS = 5 * 60 * 1e3;
1239
+ var LONG_IDLE_MS = 60 * 60 * 1e3;
1240
+ function idleCacheExpiry(report) {
1241
+ let usd8 = 0;
1242
+ let events = 0;
1243
+ let longIdleUsd = 0;
1244
+ let longIdleEvents = 0;
1245
+ let maxGapMs = 0;
1246
+ for (const proj of report.projects) {
1247
+ for (const s of proj.sessions) {
1248
+ if (s.kind !== "main") continue;
1249
+ let prevTs = null;
1250
+ for (const f of s.usageFragments ?? []) {
1251
+ const ts = f.timestampMs;
1252
+ if (ts == null) continue;
1253
+ const gap = prevTs == null ? 0 : ts - prevTs;
1254
+ if (prevTs != null && gap > CACHE_TTL_MS && f.cacheWritePremiumUsd > 0) {
1255
+ usd8 += f.cacheWritePremiumUsd;
1256
+ events += 1;
1257
+ if (gap >= LONG_IDLE_MS) {
1258
+ longIdleUsd += f.cacheWritePremiumUsd;
1259
+ longIdleEvents += 1;
1260
+ }
1261
+ if (gap > maxGapMs) maxGapMs = gap;
1262
+ }
1263
+ prevTs = ts;
1264
+ }
1265
+ }
1266
+ }
1267
+ return { usd: usd8, events, longIdleUsd, longIdleEvents, maxGapMinutes: maxGapMs / 6e4 };
1268
+ }
1269
+ function cacheWriteCostUsd(report) {
1270
+ let total = 0;
1271
+ for (const proj of report.projects) {
1272
+ for (const s of proj.sessions) {
1273
+ if (s.kind !== "main") continue;
1274
+ total += amortizedCacheWriteForSession(s);
765
1275
  }
766
1276
  }
767
1277
  return total;
@@ -775,8 +1285,7 @@ function cacheMissByProject(report) {
775
1285
  for (const s of proj.sessions) {
776
1286
  if (s.kind !== "main") continue;
777
1287
  sessionsCount += 1;
778
- const p = priceFor(s.modelPrimary);
779
- usd8 += (s.totals.input_tokens + s.totals.cache_creation_tokens) * (p.input - p.cache_read) / 1e6;
1288
+ usd8 += recoverableExposureForSession(s);
780
1289
  mainTotals.input_tokens += s.totals.input_tokens;
781
1290
  mainTotals.output_tokens += s.totals.output_tokens;
782
1291
  mainTotals.cache_creation_tokens += s.totals.cache_creation_tokens;
@@ -1024,6 +1533,41 @@ function optionScore(question, optionId) {
1024
1533
  const opt = question.options.find((o) => o.id === optionId);
1025
1534
  return opt ? opt.score : null;
1026
1535
  }
1536
+ var CHECK_ACTION = {
1537
+ // CLAUDE.md quality. cmd_size is overridden per file, since trimming and
1538
+ // filling out are opposite instructions.
1539
+ cmd_size: "Keep CLAUDE.md to the durable conventions the agent actually needs and move the rest into docs it can open on demand.",
1540
+ cmd_structure: "Break the file into sections with headings and short bulleted rules so the agent finds the right guidance fast instead of scanning a wall of text.",
1541
+ cmd_stability: "Move dates, TODOs, and 'updated' notes into a separate scratch file. A stable CLAUDE.md keeps the cache warm across sessions instead of resetting it.",
1542
+ cmd_scope: "Limit CLAUDE.md to durable conventions and project facts. Changing notes belong elsewhere so the cached prefix stays constant.",
1543
+ // Context hygiene.
1544
+ cache_hit: "Open each session the same way, same CLAUDE.md and same first reads, so turn two onward reads the prefix at about a tenth of the input price instead of re-buying it.",
1545
+ cache_churn: "You are writing cache faster than you read it back. Stop editing CLAUDE.md mid-session and keep the opening reads identical, so one write serves many turns.",
1546
+ clear_between: "Run /clear or compact when you switch to an unrelated task so stale context stops riding along and inflating every turn.",
1547
+ // Prompting patterns.
1548
+ verify_loop: "End the prompt with the check: 'run the tests after implementing', 'verify the build succeeds', or a screenshot to compare. The loop then closes on its own instead of waiting for you to notice a mistake.",
1549
+ plan_before_code: "For work that touches several files or unfamiliar code, start in plan mode (Shift+Tab) or ask for a plan first, approve it, then implement. Skip the plan when you could describe the diff in one sentence.",
1550
+ prompt_specificity: "Name the file with @, paste the error or screenshot, state the scenario and what 'fixed' looks like. 'fix the login bug' becomes 'login fails after session timeout; check src/auth token refresh; write a failing test, then fix it'.",
1551
+ correction_churn: "When a session needs a third correction, run /clear and write a fresh prompt that includes what you learned. A clean session with a better prompt beats a long one full of failed approaches.",
1552
+ reusable_workflows: "Put any workflow you have typed twice into .claude/skills/<name>/SKILL.md and invoke it with /name. Delegate broad investigation to a subagent so the reading stays out of your main context.",
1553
+ plan_first: "Use plan mode or write a short spec for multi-step tasks. Planning first cuts the reactive tool loops that burn tokens.",
1554
+ success_criteria: "State the done condition or point at a test so the agent can verify its own work instead of guessing and retrying.",
1555
+ tool_thrash: "Give the loop a stop condition. Name the budget in the prompt, 'read at most five files then propose', or narrow the task so the agent is not scanning the repo to find its own footing.",
1556
+ // Session management.
1557
+ short_session_bloat: "Those sessions burned fast for how long they ran. Scope the prompt before you start, and open routine edits on a cheaper model instead of the most expensive one.",
1558
+ session_scope: "Start a fresh session per task and reset between them. Long marathon sessions carry a growing, expensive context.",
1559
+ session_marathon: "Compact or start a fresh session before the context outgrows the cache. The later turns of a long session re-pay for context you already bought.",
1560
+ // Tool and MCP config.
1561
+ permission_allowlist: "Add a settings allowlist for safe, frequent commands to cut approval prompts and the round trips they cost.",
1562
+ mcp_scoped: "Disable MCP servers and tools you do not use. Every loaded tool definition is context you pay for on every turn.",
1563
+ bash_reliance: "Replace shelling out for search and file reads with Grep, Glob, and Read. They are cheaper, cleaner, and easier to permission.",
1564
+ // Cost discipline.
1565
+ recoverable_exposure: "Most of this is input your setup could have served from cache. Keep the opening of each session identical so the prefix is a cache read rather than a repeat purchase.",
1566
+ model_routing: "Send the short, mechanical sessions to a cheaper model and keep the top model for the hard reasoning. Same work, lower bill.",
1567
+ model_choice: "Use a cheaper model for routine edits and reserve the top model for the hard reasoning. Same work, lower bill.",
1568
+ model_fit: "Match the model to the task rather than defaulting to one. Routine edits do not need the reasoning you are paying for.",
1569
+ cost_monitor: "Watch token spend or set a budget so a runaway session is caught early rather than at the monthly bill."
1570
+ };
1027
1571
 
1028
1572
  // ../../packages/engine/src/prompting.ts
1029
1573
  var SUBSTANTIAL_MIN_TURNS = 20;
@@ -1093,7 +1637,7 @@ function aggregatePrompting(report) {
1093
1637
  function clamp2(n, lo = 0, hi = 100) {
1094
1638
  return Math.max(lo, Math.min(hi, n));
1095
1639
  }
1096
- function makeCheck(id, pillar, label, score, basis, signal) {
1640
+ function makeCheck(id, pillar, label, score, basis, signal, actionOverride) {
1097
1641
  const assessed = score !== null;
1098
1642
  return {
1099
1643
  id,
@@ -1103,9 +1647,13 @@ function makeCheck(id, pillar, label, score, basis, signal) {
1103
1647
  score: assessed ? Math.round(score) : null,
1104
1648
  basis,
1105
1649
  signal,
1106
- gap: assessed && score < GAP_THRESHOLD
1650
+ gap: assessed && score < GAP_THRESHOLD,
1651
+ action: actionOverride ?? CHECK_ACTION[id] ?? ""
1107
1652
  };
1108
1653
  }
1654
+ function num(n) {
1655
+ return String(Math.round(n)).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
1656
+ }
1109
1657
  function questionnaireCheck(id, label, answers) {
1110
1658
  const q = questionById(id);
1111
1659
  if (!q) return makeCheck(id, "claude_md", label, null, "Unknown question.", "questionnaire");
@@ -1145,8 +1693,9 @@ function buildChecks(report, cmd2, answers, setup) {
1145
1693
  "claude_md",
1146
1694
  "Size",
1147
1695
  cmd2.present ? cmd2.sizeScore : null,
1148
- cmd2.present ? `Your CLAUDE.md is ${cmd2.chars.toLocaleString()} characters, about ${cmd2.estTokens.toLocaleString()} tokens loaded on every turn.` : "No CLAUDE.md was provided.",
1149
- "claudemd"
1696
+ cmd2.present ? `Your CLAUDE.md is ${num(cmd2.chars)} characters, about ${num(cmd2.estTokens)} tokens loaded on every turn.` : "No CLAUDE.md was provided.",
1697
+ "claudemd",
1698
+ cmd2.present && cmd2.chars > 6e3 ? `Your CLAUDE.md is an estimated ${num(cmd2.estTokens)} tokens, paid on every turn of every session. Cut it to the durable conventions the agent actually needs and move the rest into docs it can open on demand.` : "Add the conventions, commands, and constraints the agent keeps getting wrong so it stops re-deriving them every session."
1150
1699
  )
1151
1700
  );
1152
1701
  checks.push(
@@ -1155,7 +1704,7 @@ function buildChecks(report, cmd2, answers, setup) {
1155
1704
  "claude_md",
1156
1705
  "Structure",
1157
1706
  cmd2.present ? cmd2.structureScore : null,
1158
- cmd2.present ? `${cmd2.headings} heading${cmd2.headings === 1 ? "" : "s"} and ${cmd2.bullets} bullet point${cmd2.bullets === 1 ? "" : "s"} across ${cmd2.chars.toLocaleString()} characters.` : "No CLAUDE.md was provided.",
1707
+ cmd2.present ? `${cmd2.headings} heading${cmd2.headings === 1 ? "" : "s"} and ${cmd2.bullets} bullet point${cmd2.bullets === 1 ? "" : "s"} across ${num(cmd2.chars)} characters.` : "No CLAUDE.md was provided.",
1159
1708
  "claudemd"
1160
1709
  )
1161
1710
  );
@@ -1345,20 +1894,21 @@ function buildChecks(report, cmd2, answers, setup) {
1345
1894
  "tooling",
1346
1895
  "Tool fit",
1347
1896
  tools.total >= 20 ? clamp2(100 - Math.max(0, bashShare - 0.3) * 200) : null,
1348
- tools.total >= 20 ? `Bash was ${(bashShare * 100).toFixed(0)}% of your ${tools.total.toLocaleString()} tool calls; dedicated tools like Grep, Glob, and Read are cheaper and cleaner than shelling out.` : "Too few tool calls to judge tool fit.",
1897
+ tools.total >= 20 ? `Bash was ${(bashShare * 100).toFixed(0)}% of your ${num(tools.total)} tool calls; dedicated tools like Grep, Glob, and Read are cheaper and cleaner than shelling out.` : "Too few tool calls to judge tool fit.",
1349
1898
  "metrics"
1350
1899
  )
1351
1900
  );
1352
- const exposure = cacheMissExposureUsd(report);
1901
+ const exposure = recoverableTotalUsd(report);
1353
1902
  const spend = s.mainCostUsd;
1354
1903
  const exposureShare = spend > 0 ? exposure / spend : 0;
1904
+ const exposureValid = spend > 0 && exposure >= 0 && exposure <= spend + 1e-9;
1355
1905
  checks.push(
1356
1906
  makeCheck(
1357
1907
  "recoverable_exposure",
1358
1908
  "cost_discipline",
1359
- "Recoverable spend",
1360
- spend > 0 ? clamp2(100 - exposureShare * 120) : null,
1361
- spend > 0 ? `$${exposure.toFixed(2)} of your $${spend.toFixed(2)} spend is cache-miss exposure that a stable prefix could largely recover.` : "No spend was found in the logs.",
1909
+ "Cache-miss upper comparison",
1910
+ exposureValid ? clamp2(100 - exposureShare * 120) : null,
1911
+ !spend ? "No spend was found in the logs." : !exposureValid ? "The cache-miss comparison exceeded analyzed spend, so this legacy or hand-built report was not scored." : `$${exposure.toFixed(2)} of your $${spend.toFixed(2)} current-rate valuation is a hypothetical upper comparison if eligible misses became cache reads; it is not guaranteed savings.`,
1362
1912
  "metrics"
1363
1913
  )
1364
1914
  );
@@ -1410,76 +1960,37 @@ function scorePillars(report, cmd2, answers, setup) {
1410
1960
  }
1411
1961
 
1412
1962
  // ../../packages/engine/src/synthesize.ts
1413
- var CHECK_FIX = {
1414
- verify_loop: {
1415
- title: "Give the agent a check it can run",
1416
- action: "End the prompt with the check: 'run the tests after implementing', 'verify the build succeeds', or a screenshot to compare. The loop then closes on its own instead of waiting for you to notice a mistake."
1417
- },
1418
- plan_before_code: {
1419
- title: "Plan before multi-file changes",
1420
- action: "For work that touches several files or unfamiliar code, start in plan mode (Shift+Tab) or ask for a plan first, approve it, then implement. Skip the plan when you could describe the diff in one sentence."
1421
- },
1422
- prompt_specificity: {
1423
- title: "Open with specifics, not a headline",
1424
- action: "Name the file with @, paste the error or screenshot, state the scenario and what 'fixed' looks like. 'fix the login bug' becomes 'login fails after session timeout; check src/auth token refresh; write a failing test, then fix it'."
1425
- },
1426
- correction_churn: {
1427
- title: "Clear and re-prompt after two corrections",
1428
- action: "When a session needs a third correction, run /clear and write a fresh prompt that includes what you learned. A clean session with a better prompt beats a long one full of failed approaches."
1429
- },
1430
- reusable_workflows: {
1431
- title: "Turn repeated prompts into skills",
1432
- action: "Put any workflow you have typed twice into .claude/skills/<name>/SKILL.md and invoke it with /name. Delegate broad investigation to a subagent so the reading stays out of your main context."
1433
- },
1434
- cmd_structure: {
1435
- title: "Give CLAUDE.md clear structure",
1436
- action: "Break the file into sections with headings and short bulleted rules so the agent finds the right guidance fast instead of scanning a wall of text."
1437
- },
1438
- cmd_stability: {
1439
- title: "Remove volatile content from CLAUDE.md",
1440
- action: "Move dates, TODOs, and 'updated' notes into a separate scratch file. A stable CLAUDE.md keeps the cache warm across sessions instead of resetting it."
1441
- },
1442
- cmd_scope: {
1443
- title: "Keep CLAUDE.md to stable facts",
1444
- action: "Limit CLAUDE.md to durable conventions and project facts. Changing notes belong elsewhere so the cached prefix stays constant."
1445
- },
1446
- clear_between: {
1447
- title: "Clear or compact between unrelated tasks",
1448
- action: "Run /clear or compact when you switch to an unrelated task so stale context stops riding along and inflating every turn."
1449
- },
1450
- plan_first: {
1451
- title: "Plan before acting on multi-step work",
1452
- action: "Use plan mode or write a short spec for multi-step tasks. Planning first cuts the reactive tool loops that burn tokens."
1453
- },
1454
- success_criteria: {
1455
- title: "Give the agent success criteria",
1456
- action: "State the done condition or point at a test so the agent can verify its own work instead of guessing and retrying."
1457
- },
1458
- session_scope: {
1459
- title: "Scope sessions to one task",
1460
- action: "Start a fresh session per task and reset between them. Long marathon sessions carry a growing, expensive context."
1461
- },
1462
- mcp_scoped: {
1463
- title: "Trim unused MCP servers and tools",
1464
- action: "Disable MCP servers and tools you do not use. Every loaded tool definition is context you pay for on every turn."
1465
- },
1466
- permission_allowlist: {
1467
- title: "Set a permission allowlist",
1468
- action: "Add a settings allowlist for safe, frequent commands to cut approval prompts and the round trips they cost."
1469
- },
1470
- bash_reliance: {
1471
- title: "Use dedicated tools over Bash",
1472
- action: "Replace shelling out for search and file reads with Grep, Glob, and Read. They are cheaper, cleaner, and easier to permission."
1473
- },
1474
- cost_monitor: {
1475
- title: "Track your spend",
1476
- action: "Watch token spend or set a budget so a runaway session is caught early rather than at the monthly bill."
1477
- },
1478
- model_choice: {
1479
- title: "Match the model to the task",
1480
- action: "Use a cheaper model for routine edits and reserve the top model for the hard reasoning. Same work, lower bill."
1481
- }
1963
+ var CHECK_TITLE = {
1964
+ verify_loop: "Give the agent a check it can run",
1965
+ plan_before_code: "Plan before multi-file changes",
1966
+ prompt_specificity: "Open with specifics, not a headline",
1967
+ correction_churn: "Clear and re-prompt after two corrections",
1968
+ reusable_workflows: "Turn repeated prompts into skills",
1969
+ tool_thrash: "Give the tool loop a stop condition",
1970
+ cmd_structure: "Give CLAUDE.md clear structure",
1971
+ cmd_stability: "Remove volatile content from CLAUDE.md",
1972
+ cmd_scope: "Keep CLAUDE.md to stable facts",
1973
+ cache_hit: "Open each session the same way",
1974
+ cache_churn: "Stop rewriting the cache mid-session",
1975
+ clear_between: "Clear or compact between unrelated tasks",
1976
+ plan_first: "Plan before acting on multi-step work",
1977
+ success_criteria: "Give the agent success criteria",
1978
+ session_scope: "Scope sessions to one task",
1979
+ session_marathon: "End a session before the cache stops helping",
1980
+ short_session_bloat: "Slow down the fastest-burning sessions",
1981
+ mcp_scoped: "Trim unused MCP servers and tools",
1982
+ permission_allowlist: "Set a permission allowlist",
1983
+ bash_reliance: "Use dedicated tools over Bash",
1984
+ cost_monitor: "Track your spend",
1985
+ model_routing: "Match the model to the task",
1986
+ model_choice: "Match the model to the task",
1987
+ model_fit: "Match the model to the task"
1482
1988
  };
1989
+ function checkFix(id) {
1990
+ const title = CHECK_TITLE[id];
1991
+ const action = CHECK_ACTION[id];
1992
+ return title && action ? { title, action } : null;
1993
+ }
1483
1994
  var HEAVY_TOOL_PATTERN_MIN_SESSIONS = 2;
1484
1995
  function severityRank(s) {
1485
1996
  return s === "critical" ? 3 : s === "warn" ? 2 : 1;
@@ -1500,14 +2011,18 @@ function sizeFix(cmd2) {
1500
2011
  };
1501
2012
  }
1502
2013
  function synthesize(report, pillars, cmd2, plan = "api") {
1503
- const headlineWasteUsd = cacheMissExposureUsd(report);
1504
- const headlineWasteLabel = plan === "api" ? "Recoverable spend (cache-miss exposure)" : "Recoverable usage (cache-miss exposure)";
1505
- const spend = report.summary.cost_usd;
2014
+ const headlineWasteUsd = recoverableTotalUsd(report);
2015
+ const cacheRecoverable = cacheMissExposureUsd(report);
2016
+ const headlineWasteLabel = "Recoverable waste (estimate)";
2017
+ const spend = report.summary.mainCostUsd;
1506
2018
  const headlineWasteShare = spend > 0 ? headlineWasteUsd / spend : 0;
1507
- const exposure = headlineWasteUsd;
2019
+ const exposure = cacheRecoverable;
2020
+ const coldStartUsd = coldStartExposureUsd(report);
2021
+ const cacheAddressableUsd = Math.max(0, cacheRecoverable - coldStartUsd);
2022
+ const addressableUsd = Math.max(0, headlineWasteUsd - coldStartUsd);
1508
2023
  const fixes = [];
1509
2024
  const covered = /* @__PURE__ */ new Set();
1510
- const round23 = (n) => Math.round(n * 100) / 100;
2025
+ const round23 = (n) => roundMoneyHalfUp(n);
1511
2026
  const usd8 = (n) => {
1512
2027
  const fixed = round23(n).toFixed(2);
1513
2028
  const dot = fixed.indexOf(".");
@@ -1572,7 +2087,7 @@ function synthesize(report, pillars, cmd2, plan = "api") {
1572
2087
  }
1573
2088
  }
1574
2089
  }
1575
- const exposureMaterial = round23(exposure) > 0;
2090
+ const exposureMaterial = round23(cacheAddressableUsd) > 0 && cacheAddressableUsd > coldStartUsd;
1576
2091
  if (exposureMaterial) {
1577
2092
  const worst = cacheMissByProject(report).filter((r) => r.usd > 0).slice(0, 3).map((r) => r.slug);
1578
2093
  const pct2 = (n) => Math.round(n * 100);
@@ -1583,25 +2098,55 @@ function synthesize(report, pillars, cmd2, plan = "api") {
1583
2098
  action = `Your CLAUDE.md carries ${cmd2.volatileMarkers} volatile markers (dates, TODOs, status notes). Every edit invalidates the cached prefix, so the next session re-pays full price for the whole file. Move the churn into a scratch note the agent opens on demand.`;
1584
2099
  } else if (badCacheBest) {
1585
2100
  action = `The last ${badCacheBest.sessionsConsidered} sessions in ${badCacheBest.slug} reused only ${pct2(badCacheBest.recentHitRate)}% from the cache. Open each session the same way (same CLAUDE.md, same first reads) so turn two onward reads the prefix at about a tenth of the input price.`;
2101
+ } else if (worst.length > 0) {
2102
+ action = `Most of it sits in ${worst[0]}. Open that project the same way every time (same CLAUDE.md, same first reads) so turn two onward reads the prefix at about a tenth of the input price instead of re-paying for it.`;
1586
2103
  } else {
1587
- action = "Keep the start of each session stable (a steady CLAUDE.md and consistent first reads) so the prompt cache is reused across turns and sessions.";
2104
+ action = "";
1588
2105
  }
2106
+ if (action) {
2107
+ fixes.push({
2108
+ id: "cache_recovery",
2109
+ title: "Recover the cache misses a steadier setup would avoid",
2110
+ pillar: "context_hygiene",
2111
+ pillarName: PILLARS.context_hygiene.name,
2112
+ severity: sevForUsd(cacheAddressableUsd),
2113
+ // The fix carries what a change can reach, not the whole headline: the
2114
+ // cold start is in the headline but no fix removes it.
2115
+ wasteUsd: round23(cacheAddressableUsd),
2116
+ problem: sanitizeText(
2117
+ `${usd8(cacheAddressableUsd)} of your ${usd8(spend)} main-session spend went to input your setup could have served from cache, on top of the ${usd8(coldStartUsd)} first turns must pay whatever you do. Biggest contributors: ${worst.length ? worst.join(", ") : "your largest projects"}.`
2118
+ ),
2119
+ action: sanitizeText(action),
2120
+ basis: sanitizeText("Uncached input priced at the gap between the input and cache-read rates, plus cache writes the same session never read back, summed across main sessions. Cache writes that earned reads are excluded: they are the price of having a cache.")
2121
+ });
2122
+ covered.add("cache_hit");
2123
+ covered.add("cache_churn");
2124
+ covered.add("recoverable_exposure");
2125
+ }
2126
+ }
2127
+ const idle = idleCacheExpiry(report);
2128
+ if (round23(idle.longIdleUsd) > 0 && idle.longIdleEvents > 0) {
2129
+ const hours = Math.round(idle.maxGapMinutes / 60);
2130
+ const gapPhrase = hours >= 1 ? ` The longest was about ${hours} ${hours === 1 ? "hour" : "hours"}.` : "";
1589
2131
  fixes.push({
1590
- id: "cache_recovery",
1591
- title: "Recover spend lost to cache misses",
1592
- pillar: "context_hygiene",
1593
- pillarName: PILLARS.context_hygiene.name,
1594
- severity: sevForUsd(exposure),
1595
- wasteUsd: round23(exposure),
2132
+ id: "idle_cache_expiry",
2133
+ title: "Compact before you walk away from a session",
2134
+ pillar: "session_mgmt",
2135
+ pillarName: PILLARS.session_mgmt.name,
2136
+ severity: sevForUsd(idle.longIdleUsd),
2137
+ wasteUsd: round23(idle.longIdleUsd),
1596
2138
  problem: sanitizeText(
1597
- `Up to ${usd8(exposure)} of input spend was paid at full price instead of the cache-read rate. Biggest contributors: ${worst.length ? worst.join(", ") : "your largest projects"}.`
2139
+ `${usd8(idle.longIdleUsd)} went to rebuilding a prompt prefix that had expired during a break of an hour or more, across ${idle.longIdleEvents} ${sWord(idle.longIdleEvents)}.${gapPhrase} Counting shorter pauses too, idle gaps cost ${usd8(idle.usd)} over ${idle.events} turns.`
1598
2140
  ),
1599
- action: sanitizeText(action),
1600
- basis: sanitizeText("Cache-miss exposure summed across projects at the published input minus cache-read delta. Upper bound on recoverable spend.")
2141
+ action: sanitizeText(
2142
+ "The prompt cache lives about five minutes, so a session you come back to hours later re-buys its whole context on the next turn, and the bill is whatever that context weighed when you left. Compact or clear before stepping away, or start a fresh session when you return, so what gets rebuilt is small."
2143
+ ),
2144
+ basis: sanitizeText(
2145
+ "Cache-write premium on turns that followed the previous turn by more than the cache lifetime, summed across main sessions from request timestamps."
2146
+ )
1601
2147
  });
1602
- covered.add("cache_hit");
1603
- covered.add("cache_churn");
1604
- covered.add("recoverable_exposure");
2148
+ covered.add("session_scope");
2149
+ covered.add("session_marathon");
1605
2150
  }
1606
2151
  const singleSessionTools = [];
1607
2152
  for (const [tool, e] of heavyByTool) {
@@ -1675,7 +2220,7 @@ function synthesize(report, pillars, cmd2, plan = "api") {
1675
2220
  wasteUsd: round23(marathonUsd),
1676
2221
  problem: sanitizeText(`${n} long ${sWord(n)} kept growing until the prompt cache stopped helping, re-paying about ${usd8(marathonUsd)} for context in the later turns.`),
1677
2222
  action: sanitizeText("Compact or start a fresh session between tasks so the context stays small and the cache keeps working."),
1678
- basis: sanitizeText("Recoverable estimate from the late-session cache shortfall versus the early-session hit rate.")
2223
+ basis: sanitizeText("Estimated cache-miss exposure from the late-session cache shortfall versus the early-session hit rate; not complete savings.")
1679
2224
  });
1680
2225
  }
1681
2226
  if (workflowUsd > 0) {
@@ -1694,7 +2239,7 @@ function synthesize(report, pillars, cmd2, plan = "api") {
1694
2239
  for (const p of pillars) {
1695
2240
  for (const c of p.checks) {
1696
2241
  if (!c.gap || covered.has(c.id)) continue;
1697
- const tmpl = c.id === "cmd_size" ? sizeFix(cmd2) : CHECK_FIX[c.id];
2242
+ const tmpl = c.id === "cmd_size" ? sizeFix(cmd2) : checkFix(c.id);
1698
2243
  if (!tmpl) continue;
1699
2244
  const severity = (c.score ?? 100) < 40 ? "warn" : "info";
1700
2245
  fixes.push({
@@ -1715,10 +2260,15 @@ function synthesize(report, pillars, cmd2, plan = "api") {
1715
2260
  if (severityRank(b.severity) !== severityRank(a.severity)) return severityRank(b.severity) - severityRank(a.severity);
1716
2261
  return PILLARS[b.pillar].weight - PILLARS[a.pillar].weight;
1717
2262
  });
2263
+ const pctOf = (n) => spend > 0 ? `${(n / spend * 100).toFixed(1)}%` : "0.0%";
2264
+ const verdict = spend <= 0 ? "No main-session spend was found in these logs, so there is nothing to judge yet." : exposureMaterial ? `${usd8(addressableUsd)} of your ${usd8(spend)} main-session spend (${pctOf(addressableUsd)}) is waste a setup change can reach. That is on top of ${usd8(coldStartUsd)} your first turns must pay whatever you do, and it is the number the fixes below go after.` : `Your caching is doing its job. Of ${usd8(spend)} main-session spend, only ${usd8(exposure)} (${pctOf(exposure)}) was recoverable at all, and ${usd8(coldStartUsd)} of that is the cold start every first turn pays. There is no cache change worth making here; look at model routing and tool loops instead.`;
1718
2265
  return {
1719
2266
  headlineWasteUsd,
1720
2267
  headlineWasteLabel,
1721
2268
  headlineWasteShare,
2269
+ coldStartUsd,
2270
+ addressableUsd,
2271
+ verdict,
1722
2272
  fixes
1723
2273
  };
1724
2274
  }
@@ -1798,7 +2348,7 @@ var UNASSESSED_BURN_CLOCK = {
1798
2348
  quietSlot: null,
1799
2349
  activeDays: 0
1800
2350
  };
1801
- function burnClock(report, offsetMinutes = 0) {
2351
+ function burnClock(report, offsetMinutes = 0, timeZone) {
1802
2352
  const merged = /* @__PURE__ */ new Map();
1803
2353
  for (const project of report.projects) {
1804
2354
  for (const session of project.sessions) {
@@ -1806,19 +2356,52 @@ function burnClock(report, offsetMinutes = 0) {
1806
2356
  }
1807
2357
  }
1808
2358
  if (merged.size === 0) return UNASSESSED_BURN_CLOCK;
2359
+ let formatter = null;
2360
+ if (timeZone) {
2361
+ try {
2362
+ formatter = new Intl.DateTimeFormat("en-US-u-ca-gregory-nu-latn", {
2363
+ timeZone,
2364
+ year: "numeric",
2365
+ month: "2-digit",
2366
+ day: "2-digit",
2367
+ weekday: "short",
2368
+ hour: "2-digit",
2369
+ hourCycle: "h23"
2370
+ });
2371
+ } catch {
2372
+ formatter = null;
2373
+ }
2374
+ }
2375
+ const localParts = (t) => {
2376
+ const epochMs = t * 9e5;
2377
+ if (!formatter) {
2378
+ const date = new Date(epochMs + offsetMinutes * 6e4);
2379
+ return {
2380
+ day: date.getUTCDay(),
2381
+ hour: date.getUTCHours(),
2382
+ date: `${date.getUTCFullYear()}-${date.getUTCMonth() + 1}-${date.getUTCDate()}`
2383
+ };
2384
+ }
2385
+ const parts = Object.fromEntries(formatter.formatToParts(epochMs).map((part) => [part.type, part.value]));
2386
+ const dayNames = { Sun: 0, Mon: 1, Tue: 2, Wed: 3, Thu: 4, Fri: 5, Sat: 6 };
2387
+ return {
2388
+ day: dayNames[parts.weekday ?? ""] ?? 0,
2389
+ hour: Number(parts.hour ?? 0),
2390
+ date: `${parts.year}-${parts.month}-${parts.day}`
2391
+ };
2392
+ };
1809
2393
  const activeDaySet = /* @__PURE__ */ new Set();
1810
2394
  for (const t of merged.keys()) {
1811
- const d = new Date(t * 9e5 + offsetMinutes * 6e4);
1812
- activeDaySet.add(`${d.getUTCFullYear()}-${d.getUTCMonth()}-${d.getUTCDate()}`);
2395
+ activeDaySet.add(localParts(t).date);
1813
2396
  }
1814
2397
  if (activeDaySet.size < 7) return { ...UNASSESSED_BURN_CLOCK, activeDays: activeDaySet.size };
1815
2398
  const byDay = [0, 0, 0, 0, 0, 0, 0];
1816
2399
  const byQuarter = [0, 0, 0, 0];
1817
2400
  const slot = Array.from({ length: 7 }, () => [0, 0, 0, 0]);
1818
2401
  for (const [t, usd8] of merged) {
1819
- const d = new Date(t * 9e5 + offsetMinutes * 6e4);
1820
- const day2 = d.getUTCDay();
1821
- const quarter = Math.floor(d.getUTCHours() / 6);
2402
+ const local = localParts(t);
2403
+ const day2 = local.day;
2404
+ const quarter = Math.floor(local.hour / 6);
1822
2405
  byDay[day2] += usd8;
1823
2406
  byQuarter[quarter] += usd8;
1824
2407
  slot[day2][quarter] += usd8;
@@ -1836,6 +2419,197 @@ function burnClock(report, offsetMinutes = 0) {
1836
2419
  return { assessed: true, byDay, byQuarter, topSlot, quietSlot, activeDays: activeDaySet.size };
1837
2420
  }
1838
2421
 
2422
+ // ../../packages/engine/src/select.ts
2423
+ function makeUnit(rawLines, kind) {
2424
+ const text2 = rawLines.join("\n").replace(/\s+$/, "");
2425
+ return { text: text2, tokens: Math.round(text2.length / 4), kind };
2426
+ }
2427
+ var FENCE_RE = /^```/;
2428
+ var BULLET_START_RE = /^(?:[-*]|\d+[.)])\s+/;
2429
+ var INDENTED_RE = /^\s+\S/;
2430
+ function splitUnits(section) {
2431
+ const lines = section.body.split(/\r?\n/);
2432
+ const units = [];
2433
+ let i = 0;
2434
+ while (i < lines.length) {
2435
+ const line = lines[i] ?? "";
2436
+ if (line.trim() === "") {
2437
+ i++;
2438
+ continue;
2439
+ }
2440
+ if (FENCE_RE.test(line.trim())) {
2441
+ const block2 = [line];
2442
+ i++;
2443
+ while (i < lines.length && !FENCE_RE.test((lines[i] ?? "").trim())) {
2444
+ block2.push(lines[i]);
2445
+ i++;
2446
+ }
2447
+ if (i < lines.length) {
2448
+ block2.push(lines[i]);
2449
+ i++;
2450
+ }
2451
+ units.push(makeUnit(block2, "code"));
2452
+ continue;
2453
+ }
2454
+ if (BULLET_START_RE.test(line)) {
2455
+ const block2 = [line];
2456
+ i++;
2457
+ while (i < lines.length) {
2458
+ const next = lines[i] ?? "";
2459
+ if (next.trim() === "") {
2460
+ const after = lines[i + 1] ?? "";
2461
+ if (INDENTED_RE.test(after)) {
2462
+ block2.push(next);
2463
+ i++;
2464
+ continue;
2465
+ }
2466
+ break;
2467
+ }
2468
+ if (INDENTED_RE.test(next)) {
2469
+ block2.push(next);
2470
+ i++;
2471
+ continue;
2472
+ }
2473
+ break;
2474
+ }
2475
+ units.push(makeUnit(block2, "bullet"));
2476
+ continue;
2477
+ }
2478
+ const block = [line];
2479
+ i++;
2480
+ while (i < lines.length) {
2481
+ const next = lines[i] ?? "";
2482
+ if (next.trim() === "" || FENCE_RE.test(next.trim()) || BULLET_START_RE.test(next)) break;
2483
+ block.push(next);
2484
+ i++;
2485
+ }
2486
+ units.push(makeUnit(block, "paragraph"));
2487
+ }
2488
+ return units;
2489
+ }
2490
+ var NORMATIVE_MARKER = /\b(never|always|must|do not|don't|required|only|forbidden|prohibited|before you|after you)\b/i;
2491
+ var CONCRETE_ANCHOR = /`[^`]+`|(?:^|[\s(])\.{0,2}\/[\w./-]*|\b[\w-]+\/[\w./-]+|--[a-z][\w-]*|\b\d+(?:\.\d+)?\b/i;
2492
+ var CONCRETE_ANCHOR_G = new RegExp(CONCRETE_ANCHOR.source, "gi");
2493
+ var IMPERATIVE_VERBS = /* @__PURE__ */ new Set([
2494
+ "run",
2495
+ "use",
2496
+ "keep",
2497
+ "add",
2498
+ "avoid",
2499
+ "prefer",
2500
+ "ensure",
2501
+ "verify",
2502
+ "check",
2503
+ "set",
2504
+ "enable",
2505
+ "disable",
2506
+ "remove",
2507
+ "delete",
2508
+ "write",
2509
+ "read",
2510
+ "call",
2511
+ "treat",
2512
+ "confirm",
2513
+ "install",
2514
+ "configure",
2515
+ "enforce",
2516
+ "apply",
2517
+ "update",
2518
+ "validate",
2519
+ "sanitize",
2520
+ "escape",
2521
+ "format",
2522
+ "commit",
2523
+ "push",
2524
+ "merge",
2525
+ "scope",
2526
+ "limit",
2527
+ "cap",
2528
+ "batch",
2529
+ "invoke",
2530
+ "spawn",
2531
+ "route",
2532
+ "reuse",
2533
+ "cache",
2534
+ "clear",
2535
+ "compact",
2536
+ "state",
2537
+ "branch",
2538
+ "start",
2539
+ "stop",
2540
+ "handle"
2541
+ ]);
2542
+ function firstWord(text2) {
2543
+ const firstLine = text2.split(/\r?\n/)[0] ?? "";
2544
+ const stripped = firstLine.replace(/^\s*(?:[-*]|\d+[.)])\s+/, "").trim();
2545
+ const m = stripped.match(/^[A-Za-z']+/);
2546
+ return m ? m[0].toLowerCase() : "";
2547
+ }
2548
+ function isImperativeDirective(u) {
2549
+ return u.kind !== "code" && IMPERATIVE_VERBS.has(firstWord(u.text));
2550
+ }
2551
+ function classifyUnit(u) {
2552
+ if (NORMATIVE_MARKER.test(u.text) || isImperativeDirective(u)) return "rule";
2553
+ if (u.kind === "code" || CONCRETE_ANCHOR.test(u.text)) return "fact";
2554
+ return "prose";
2555
+ }
2556
+ function anchorScore(u) {
2557
+ if (u.kind === "code") return 1;
2558
+ const matches = u.text.match(CONCRETE_ANCHOR_G);
2559
+ return Math.max(1, matches?.length ?? 0);
2560
+ }
2561
+ function densityDescending(a, b) {
2562
+ const da = anchorScore(a.unit) / a.unit.tokens;
2563
+ const db = anchorScore(b.unit) / b.unit.tokens;
2564
+ if (db !== da) return db - da;
2565
+ return a.order - b.order;
2566
+ }
2567
+ function selectUnits(sections, budgetTokens) {
2568
+ const entries = [];
2569
+ let order = 0;
2570
+ for (const section of sections) {
2571
+ for (const unit of splitUnits(section)) {
2572
+ entries.push({ section, unit, tier: classifyUnit(unit), order: order++ });
2573
+ }
2574
+ }
2575
+ const kept = /* @__PURE__ */ new Set();
2576
+ let used = 0;
2577
+ for (const e of entries) {
2578
+ if (e.tier !== "rule") continue;
2579
+ if (used + e.unit.tokens > budgetTokens) break;
2580
+ kept.add(e);
2581
+ used += e.unit.tokens;
2582
+ }
2583
+ for (const tier of ["fact", "prose"]) {
2584
+ const candidates = entries.filter((e) => e.tier === tier && !kept.has(e)).sort(densityDescending);
2585
+ for (const e of candidates) {
2586
+ if (used + e.unit.tokens > budgetTokens) continue;
2587
+ kept.add(e);
2588
+ used += e.unit.tokens;
2589
+ }
2590
+ }
2591
+ const droppedEntries = entries.filter((e) => !kept.has(e));
2592
+ const droppedTokens = droppedEntries.reduce((sum, e) => sum + e.unit.tokens, 0);
2593
+ const dropped = droppedEntries.map((e) => ({
2594
+ heading: e.section.heading,
2595
+ kind: e.tier,
2596
+ tokens: e.unit.tokens
2597
+ }));
2598
+ const keptSections = [];
2599
+ for (const section of sections) {
2600
+ const keptForSection = entries.filter((e) => e.section === section && kept.has(e)).map((e) => e.unit);
2601
+ if (keptForSection.length === 0) continue;
2602
+ const body = keptForSection.map((u) => u.text).join("\n\n");
2603
+ keptSections.push({
2604
+ heading: section.heading,
2605
+ body,
2606
+ tokens: Math.round(body.length / 4),
2607
+ volatileLines: body.split(/\r?\n/).filter((l) => VOLATILE_MARKER.test(l)).length
2608
+ });
2609
+ }
2610
+ return { kept: keptSections, droppedTokens, dropped };
2611
+ }
2612
+
1839
2613
  // ../../packages/engine/src/optimize.ts
1840
2614
  function usd(n) {
1841
2615
  const rounded = Math.round(n * 100) / 100;
@@ -1930,6 +2704,8 @@ function carriedSections(currentClaudeMd) {
1930
2704
  const out = {
1931
2705
  workflow: null,
1932
2706
  architecture: null,
2707
+ workflowHeading: null,
2708
+ architectureHeading: null,
1933
2709
  other: [],
1934
2710
  droppedVolatile: [],
1935
2711
  replaced: [],
@@ -1948,10 +2724,12 @@ function carriedSections(currentClaudeMd) {
1948
2724
  }
1949
2725
  } else if (out.workflow === null && WORKFLOW_HEADING.test(section.heading)) {
1950
2726
  out.workflow = section.body;
2727
+ out.workflowHeading = section.heading;
1951
2728
  out.carriedTokens += section.tokens;
1952
2729
  out.carriedList.push(section);
1953
2730
  } else if (out.architecture === null && ARCH_HEADING.test(section.heading)) {
1954
2731
  out.architecture = section.body;
2732
+ out.architectureHeading = section.heading;
1955
2733
  out.carriedTokens += section.tokens;
1956
2734
  out.carriedList.push(section);
1957
2735
  } else {
@@ -2519,6 +3297,7 @@ function claudeMdReceiptLine(claudeMdTokens) {
2519
3297
  function buildPlaybook(report, fixes, scores, recoverable, claudeMdTokens, project) {
2520
3298
  const dollarFixes = fixes.filter((f) => f.wasteUsd > 0);
2521
3299
  const warnFixes = fixes.filter((f) => f.wasteUsd <= 0);
3300
+ const coldStart = coldStartExposureUsd(report);
2522
3301
  const parts = [];
2523
3302
  parts.push("# CostClaw fix playbook");
2524
3303
  const projectName = project?.name?.trim();
@@ -2527,9 +3306,9 @@ function buildPlaybook(report, fixes, scores, recoverable, claudeMdTokens, proje
2527
3306
  parts.push(
2528
3307
  [
2529
3308
  ...projectLine ? [projectLine, ""] : [],
2530
- `Total recoverable spend: ${usd(recoverable)} (cache-miss exposure).`,
3309
+ `Recoverable waste estimate: ${usd(recoverable)} at current API list prices, of which ${usd(coldStart)} is the cold start your first turns pay whatever you change.`,
2531
3310
  "",
2532
- "This is the ranked plan from your audit. The priority fixes are ordered by the dollars they recover; the setup warnings follow. CostClaw generates the plan; working through it is what recovers the spend."
3311
+ "This is the ranked plan from your audit. Priority suggestions are ordered by estimated value, followed by rule-based setup warnings. Cache writes that earned their reads back are excluded: paying to build a cache you then read from is the mechanism working, not waste."
2533
3312
  ].join("\n")
2534
3313
  );
2535
3314
  const receipt = claudeMdReceiptLine(claudeMdTokens);
@@ -2780,15 +3559,43 @@ function buildHarnessPrompt(input, carried, claudeMdTokens) {
2780
3559
  parts.push(verify.join("\n"));
2781
3560
  return clean(parts.join("\n\n").trimEnd() + "\n");
2782
3561
  }
3562
+ var CARRIED_BUDGET_FRACTION = 0.6;
3563
+ function clampToOriginalSize(input, recoverable, carried, requestedBudget, claudeMdBefore) {
3564
+ if (claudeMdBefore == null) return requestedBudget;
3565
+ const empty = { ...carried, workflow: null, architecture: null, other: [] };
3566
+ const floorMd = buildClaudeMd(input, recoverable, [], { placeholders: 0 }, empty, []);
3567
+ const floorTokens = Math.round(floorMd.trim().length / 4);
3568
+ const room = claudeMdBefore - floorTokens;
3569
+ if (room <= 0) return requestedBudget;
3570
+ return Math.min(requestedBudget, room);
3571
+ }
3572
+ function tierCounts(sections) {
3573
+ const counts = { rule: 0, fact: 0, prose: 0 };
3574
+ for (const section of sections) {
3575
+ for (const unit of splitUnits(section)) counts[classifyUnit(unit)]++;
3576
+ }
3577
+ return counts;
3578
+ }
2783
3579
  function optimize(input) {
2784
3580
  const recoverable = cacheMissExposureUsd(input.report);
2785
3581
  const notes = [];
2786
3582
  const stats = { placeholders: 0 };
2787
3583
  const carried = carriedSections(input.currentClaudeMd);
2788
3584
  const dispositions = [];
2789
- const optimizedClaudeMd = buildClaudeMd(input, recoverable, notes, stats, carried, dispositions);
3585
+ const claudeMdBefore = input.currentClaudeMd ? Math.round(input.currentClaudeMd.trim().length / 4) : null;
3586
+ const requestedBudget = input.maxTokens ?? Math.round(carried.carriedTokens * CARRIED_BUDGET_FRACTION);
3587
+ const budgetTokens = clampToOriginalSize(input, recoverable, carried, requestedBudget, claudeMdBefore);
3588
+ const selection = selectUnits(carried.carriedList, budgetTokens);
3589
+ const keptByHeading = new Map(selection.kept.map((s) => [s.heading, s]));
3590
+ const carriedForBuild = {
3591
+ ...carried,
3592
+ workflow: carried.workflowHeading ? keptByHeading.get(carried.workflowHeading)?.body ?? null : null,
3593
+ architecture: carried.architectureHeading ? keptByHeading.get(carried.architectureHeading)?.body ?? null : null,
3594
+ other: carried.other.map((s) => keptByHeading.get(s.heading)).filter((s) => s != null)
3595
+ };
3596
+ const optimizedClaudeMd = buildClaudeMd(input, recoverable, notes, stats, carriedForBuild, dispositions);
2790
3597
  const claudeMdTokens = {
2791
- before: input.currentClaudeMd ? Math.round(input.currentClaudeMd.trim().length / 4) : null,
3598
+ before: claudeMdBefore,
2792
3599
  after: Math.round(optimizedClaudeMd.trim().length / 4)
2793
3600
  };
2794
3601
  const carriedTokens = carried.carriedTokens;
@@ -2796,6 +3603,21 @@ function optimize(input) {
2796
3603
  const settingsJson = buildSettings(input.project);
2797
3604
  const harnessPrompt = buildHarnessPrompt(input, carried, claudeMdTokens);
2798
3605
  const { includeMd, includeSections } = buildIncludeMd(optimizedClaudeMd);
3606
+ const totalByTier = tierCounts(carried.carriedList);
3607
+ const droppedByTier = { rule: 0, fact: 0, prose: 0 };
3608
+ for (const d of selection.dropped) droppedByTier[d.kind]++;
3609
+ const keptByTier = {
3610
+ rule: totalByTier.rule - droppedByTier.rule,
3611
+ fact: totalByTier.fact - droppedByTier.fact,
3612
+ prose: totalByTier.prose - droppedByTier.prose
3613
+ };
3614
+ const selectionResult = {
3615
+ budgetTokens,
3616
+ keptTokens: selection.kept.reduce((sum, s) => sum + s.tokens, 0),
3617
+ droppedTokens: selection.droppedTokens,
3618
+ keptByTier,
3619
+ droppedByTier
3620
+ };
2799
3621
  const cleanNotes = notes.map((n) => clean(n));
2800
3622
  const cleanDispositions = dispositions.map((d) => ({ ...d, name: clean(d.name), why: clean(d.why) }));
2801
3623
  if (hasEmDash(optimizedClaudeMd) || hasEmDash(playbook) || hasEmDash(settingsJson) || hasEmDash(harnessPrompt) || hasEmDash(includeMd) || cleanNotes.some(hasEmDash) || cleanDispositions.some((d) => hasEmDash(d.name) || hasEmDash(d.why))) {
@@ -2810,7 +3632,8 @@ function optimize(input) {
2810
3632
  placeholdersRemaining: stats.placeholders,
2811
3633
  claudeMdTokens,
2812
3634
  carriedTokens,
2813
- sectionDispositions: cleanDispositions.map((d) => ({ ...d, name: sanitizeText(d.name), why: sanitizeText(d.why) }))
3635
+ sectionDispositions: cleanDispositions.map((d) => ({ ...d, name: sanitizeText(d.name), why: sanitizeText(d.why) })),
3636
+ selection: selectionResult
2814
3637
  };
2815
3638
  }
2816
3639
  return {
@@ -2824,18 +3647,23 @@ function optimize(input) {
2824
3647
  placeholdersRemaining: stats.placeholders,
2825
3648
  claudeMdTokens,
2826
3649
  carriedTokens,
2827
- sectionDispositions: cleanDispositions
3650
+ sectionDispositions: cleanDispositions,
3651
+ selection: selectionResult
2828
3652
  };
2829
3653
  }
2830
3654
 
2831
3655
  // ../../packages/engine/src/audit.ts
2832
3656
  import { randomUUID } from "crypto";
2833
3657
  function round2(n) {
2834
- return Math.round(n * 100) / 100;
3658
+ return roundMoneyHalfUp(n);
2835
3659
  }
2836
3660
  function round4(n) {
2837
3661
  return Math.round(n * 1e4) / 1e4;
2838
3662
  }
3663
+ function safeModelId2(model) {
3664
+ if (model == null) return null;
3665
+ return /^[A-Za-z0-9._:\[\]-]{1,100}$/.test(model) ? model : "unknown";
3666
+ }
2839
3667
  function toUsageMetrics(report) {
2840
3668
  const s = report.summary;
2841
3669
  const topProjects = report.projects.slice().sort((a, b) => b.cost_usd - a.cost_usd).slice(0, 8).map((p) => ({
@@ -2843,14 +3671,15 @@ function toUsageMetrics(report) {
2843
3671
  costUsd: round2(p.cost_usd),
2844
3672
  sessionsCount: p.sessionsCount,
2845
3673
  cacheHitRate: round4(p.cacheHitRate),
2846
- modelPrimary: p.modelPrimary
3674
+ modelPrimary: safeModelId2(p.modelPrimary)
2847
3675
  }));
2848
3676
  const topSessions = report.projects.flatMap((p) => p.sessions.filter((sess) => sess.kind === "main").map((sess) => ({ projectSlug: p.slug, sess }))).sort((a, b) => b.sess.cost_usd - a.sess.cost_usd).slice(0, 8).map(({ projectSlug, sess }) => ({
2849
3677
  projectSlug,
2850
- sessionUuid: sess.sessionUuid,
3678
+ // Retain the schema field without persisting a private transcript ID.
3679
+ sessionUuid: null,
2851
3680
  costUsd: round2(sess.cost_usd),
2852
3681
  durationMinutes: sess.durationMinutes == null ? null : round2(sess.durationMinutes),
2853
- modelPrimary: sess.modelPrimary,
3682
+ modelPrimary: safeModelId2(sess.modelPrimary),
2854
3683
  cacheHitRate: round4(cacheHitRate(sess.totals))
2855
3684
  }));
2856
3685
  const modelBreakdown = {};
@@ -2867,7 +3696,12 @@ function toUsageMetrics(report) {
2867
3696
  modelBreakdown,
2868
3697
  topProjects,
2869
3698
  topSessions,
2870
- pricingSnapshotDate: PRICING_SNAPSHOT_DATE
3699
+ pricingSnapshotDate: PRICING_SNAPSHOT_DATE,
3700
+ accuracy: s.accuracy ? {
3701
+ ...s.accuracy,
3702
+ warnings: [...s.accuracy.warnings],
3703
+ unknownModels: s.accuracy.unknownModels.map((entry) => ({ ...entry }))
3704
+ } : void 0
2871
3705
  };
2872
3706
  }
2873
3707
  function roundWindows(w) {
@@ -2900,6 +3734,15 @@ function cleanFix(f) {
2900
3734
  wasteUsd: round2(f.wasteUsd)
2901
3735
  };
2902
3736
  }
3737
+ function roundIdle(i) {
3738
+ return {
3739
+ usd: round2(i.usd),
3740
+ events: i.events,
3741
+ longIdleUsd: round2(i.longIdleUsd),
3742
+ longIdleEvents: i.longIdleEvents,
3743
+ maxGapMinutes: Math.round(i.maxGapMinutes)
3744
+ };
3745
+ }
2903
3746
  function cleanCheck(c) {
2904
3747
  return { ...c, basis: sanitizeText(c.basis) };
2905
3748
  }
@@ -2911,7 +3754,7 @@ function buildAudit(input, opts = {}) {
2911
3754
  const cmd2 = analyzeClaudeMd(input.claudeMd);
2912
3755
  const { pillars, overall, band } = scorePillars(report, cmd2, input.questionnaire, input.setup);
2913
3756
  const plan = input.plan ?? "api";
2914
- const { headlineWasteUsd, headlineWasteLabel, headlineWasteShare, fixes } = synthesize(report, pillars, cmd2, plan);
3757
+ const { headlineWasteUsd, headlineWasteLabel, headlineWasteShare, coldStartUsd, addressableUsd, verdict, fixes } = synthesize(report, pillars, cmd2, plan);
2915
3758
  const answered = Object.values(input.questionnaire).filter((v) => typeof v === "string" && v.length > 0).length;
2916
3759
  return {
2917
3760
  schemaVersion: "1",
@@ -2932,8 +3775,13 @@ function buildAudit(input, opts = {}) {
2932
3775
  headlineWasteLabel: sanitizeText(headlineWasteLabel),
2933
3776
  plan,
2934
3777
  headlineWasteShare: round4(headlineWasteShare),
3778
+ coldStartUsd: round2(coldStartUsd),
3779
+ addressableUsd: round2(addressableUsd),
3780
+ cacheWriteCostUsd: round2(cacheWriteCostUsd(report)),
3781
+ verdict: sanitizeText(verdict),
3782
+ idleCacheExpiry: roundIdle(idleCacheExpiry(report)),
2935
3783
  usageWindows: roundWindows(computeWindowStats(report)),
2936
- burnClock: roundBurnClock(burnClock(report, input.tzOffsetMinutes ?? 0)),
3784
+ burnClock: roundBurnClock(burnClock(report, input.tzOffsetMinutes ?? 0, input.timeZone)),
2937
3785
  fixes: fixes.map(cleanFix),
2938
3786
  writer: opts.writer ?? "template",
2939
3787
  paid: false
@@ -2943,7 +3791,7 @@ function buildAudit(input, opts = {}) {
2943
3791
  // ../../packages/engine/src/diff.ts
2944
3792
  var DIFF_SCHEMA_VERSION = "1";
2945
3793
  function round22(n) {
2946
- return Math.round(n * 100) / 100;
3794
+ return roundMoneyHalfUp(n);
2947
3795
  }
2948
3796
  function round42(n) {
2949
3797
  return Math.round(n * 1e4) / 1e4;
@@ -2966,6 +3814,12 @@ function side(r) {
2966
3814
  plan: r.plan
2967
3815
  };
2968
3816
  }
3817
+ function provenanceMismatch(a, b) {
3818
+ if (!a && !b) return void 0;
3819
+ if (!a || !b || a.accountingVersion !== b.accountingVersion) return "accounting changed";
3820
+ if (a.pricingSnapshotDate !== b.pricingSnapshotDate) return "pricing changed";
3821
+ return void 0;
3822
+ }
2969
3823
  function diffAudits(a, b) {
2970
3824
  assertRecord(a);
2971
3825
  assertRecord(b);
@@ -2980,7 +3834,8 @@ function diffAudits(a, b) {
2980
3834
  };
2981
3835
  const newSpendUsd = cm.spendUsd - bm.spendUsd;
2982
3836
  const newSessions = cm.sessionsCount - bm.sessionsCount;
2983
- const comparable = newSpendUsd >= -0.01 && newSessions >= 0 && Object.values(newTokens).every((t) => t >= 0);
3837
+ const comparisonReason = provenanceMismatch(bm.accuracy, cm.accuracy);
3838
+ const comparable = !comparisonReason && newSpendUsd >= -0.01 && newSessions >= 0 && Object.values(newTokens).every((t) => t >= 0);
2984
3839
  const periodMs = Date.parse(cur.createdAt) - Date.parse(base.createdAt);
2985
3840
  const periodDays = round22(Math.max(0, periodMs) / 864e5);
2986
3841
  const pillars = base.pillarScores.map((bp) => {
@@ -3010,6 +3865,7 @@ function diffAudits(a, b) {
3010
3865
  current: side(cur),
3011
3866
  periodDays,
3012
3867
  comparable,
3868
+ ...comparisonReason ? { comparisonReason } : {},
3013
3869
  marginal: comparable ? {
3014
3870
  newSpendUsd: round22(newSpendUsd),
3015
3871
  newSessions,
@@ -3028,6 +3884,13 @@ function diffAudits(a, b) {
3028
3884
  }
3029
3885
  var SINCE_BASELINE_MIN_TOKENS = 1e6;
3030
3886
  function sinceBaseline(baseline, current) {
3887
+ const currentAccuracy = current.usageMetrics.accuracy;
3888
+ if (!baseline.accuracy !== !currentAccuracy || baseline.accuracy && currentAccuracy && baseline.accuracy.accountingVersion !== currentAccuracy.accountingVersion) {
3889
+ return { comparable: false, reason: "accounting method changed" };
3890
+ }
3891
+ if (baseline.accuracy && currentAccuracy && baseline.accuracy.pricingSnapshotDate !== currentAccuracy.pricingSnapshotDate) {
3892
+ return { comparable: false, reason: "pricing changed" };
3893
+ }
3031
3894
  const cur = current.usageMetrics.totalTokens;
3032
3895
  const base = baseline.totals;
3033
3896
  const period = {
@@ -3519,7 +4382,7 @@ function buildUpgradeAll(input) {
3519
4382
 
3520
4383
  // src/audit-command.ts
3521
4384
  import { mkdir as mkdir3, readFile as readFile4, readdir as readdir2, rm as rm2, writeFile as writeFile3 } from "fs/promises";
3522
- import { join as join5, resolve } from "path";
4385
+ import { join as join5, resolve as resolve2 } from "path";
3523
4386
  import { homedir as homedir4 } from "os";
3524
4387
 
3525
4388
  // src/open.ts
@@ -3539,8 +4402,8 @@ function openInBrowser(target) {
3539
4402
 
3540
4403
  // src/read-sessions.ts
3541
4404
  import { readdir } from "fs/promises";
3542
- import { readFileSync, openSync, closeSync, readSync } from "fs";
3543
- import { join, relative, sep } from "path";
4405
+ import { readFileSync, openSync, closeSync, readSync, statSync } from "fs";
4406
+ import { basename, dirname, join, relative, resolve, sep } from "path";
3544
4407
  import { homedir } from "os";
3545
4408
  function defaultProjectsPath() {
3546
4409
  return process.env.CLAUDE_PROJECTS_PATH || join(homedir(), ".claude", "projects");
@@ -3584,6 +4447,45 @@ function lazyLog(full, meta) {
3584
4447
  }
3585
4448
  var CWD_PROBE_BYTES = 65536;
3586
4449
  var CWD_PROBE_LINES = 40;
4450
+ function repoRootFor(startDir) {
4451
+ let dir;
4452
+ try {
4453
+ dir = resolve(startDir);
4454
+ } catch {
4455
+ return null;
4456
+ }
4457
+ for (let depth = 0; depth < 64; depth += 1) {
4458
+ const dotGit = join(dir, ".git");
4459
+ let stat4;
4460
+ try {
4461
+ stat4 = statSync(dotGit);
4462
+ } catch {
4463
+ const parent2 = dirname(dir);
4464
+ if (parent2 === dir) return null;
4465
+ dir = parent2;
4466
+ continue;
4467
+ }
4468
+ if (stat4.isDirectory()) return dir;
4469
+ if (stat4.isFile()) {
4470
+ try {
4471
+ const pointer = readFileSync(dotGit, "utf8").trim();
4472
+ const match = /^gitdir:\s*(.+)$/m.exec(pointer);
4473
+ const gitDir = match?.[1]?.trim();
4474
+ if (gitDir) {
4475
+ const parts = resolve(gitDir).split(/[\\/]+/);
4476
+ const idx = parts.lastIndexOf(".git");
4477
+ if (idx > 0) return parts.slice(0, idx).join(sep);
4478
+ }
4479
+ } catch {
4480
+ }
4481
+ return dir;
4482
+ }
4483
+ const parent = dirname(dir);
4484
+ if (parent === dir) return null;
4485
+ dir = parent;
4486
+ }
4487
+ return null;
4488
+ }
3587
4489
  function projectNameFromLogs(files) {
3588
4490
  for (const full of files.slice(0, 3)) {
3589
4491
  let fd;
@@ -3638,8 +4540,10 @@ async function readSessions(rootPath) {
3638
4540
  }
3639
4541
  const files = await collectJsonl(projPath);
3640
4542
  const probe = projectNameFromLogs(files);
3641
- const projectSlug = probe?.slug ?? dir.name;
3642
- if (probe && !projectDirs.has(probe.slug)) projectDirs.set(probe.slug, probe.cwd);
4543
+ const repoRoot = probe ? repoRootFor(probe.cwd) : null;
4544
+ const resolvedSlug = repoRoot ? basename(repoRoot) : probe?.slug;
4545
+ const projectSlug = resolvedSlug || dir.name;
4546
+ if (probe && !projectDirs.has(projectSlug)) projectDirs.set(projectSlug, repoRoot ?? probe.cwd);
3643
4547
  for (const full of files) {
3644
4548
  const rel = relative(projPath, full).split(sep).join("/");
3645
4549
  const name = `${dir.name}/${rel}`;
@@ -3677,15 +4581,24 @@ function ansi(enabled) {
3677
4581
  // src/format.ts
3678
4582
  function sinceOptimizeLine(meta) {
3679
4583
  const so = meta.sinceOptimize;
3680
- if (!so || !so.result.comparable) return null;
4584
+ if (!so) return null;
4585
+ if (!so.result.comparable) {
4586
+ if (so.result.reason === "accounting method changed") {
4587
+ return `Since optimize (${so.at.slice(0, 10)}): comparison withheld because the accounting method changed. Run optimize again to set a new baseline.`;
4588
+ }
4589
+ if (so.result.reason === "pricing changed") {
4590
+ return `Since optimize (${so.at.slice(0, 10)}): comparison withheld because the pricing snapshot changed. Run optimize again to set a new baseline.`;
4591
+ }
4592
+ return null;
4593
+ }
3681
4594
  const r = so.result;
3682
4595
  const date = so.at.slice(0, 10);
3683
4596
  const move = `${(r.baselineCacheHitRate * 100).toFixed(1)}% -> ${(r.periodCacheHitRate * 100).toFixed(1)}%`;
3684
- const worth = r.recoveredUsd >= 0.01 ? `; worth about ${usd2(r.recoveredUsd)} at Sonnet rates` : "";
4597
+ const worth = r.recoveredUsd >= 0.01 ? `; estimated current Sonnet-rate valuation ${usd2(r.recoveredUsd)}` : "";
3685
4598
  return `Since optimize (${date}): cache hit ${move} on new usage${worth}.`;
3686
4599
  }
3687
4600
  function usd2(n) {
3688
- return `$${(Math.round(n * 100) / 100).toFixed(2)}`;
4601
+ return `$${roundMoneyHalfUp(n).toFixed(2)}`;
3689
4602
  }
3690
4603
  var BURN_DAY_NAMES = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
3691
4604
  var BURN_DAY_ORDER = [1, 2, 3, 4, 5, 6, 0];
@@ -3765,16 +4678,20 @@ function shortModel(id) {
3765
4678
  return m && m[1] ? m[1].toLowerCase() : id;
3766
4679
  }
3767
4680
  function unknownModelNote(breakdown) {
3768
- let unknown = 0;
3769
- let total = 0;
3770
- for (const [model, spend] of Object.entries(breakdown)) {
3771
- if (spend <= 0) continue;
3772
- total += spend;
3773
- if (!isKnownModel(model)) unknown += spend;
4681
+ const unknown = Object.keys(breakdown).filter((model) => !isKnownModel(model));
4682
+ return unknown.length > 0 ? `Models missing from the rate card: ${unknown.join(", ")}. Their current API-equivalent valuation is approximate.` : null;
4683
+ }
4684
+ function accuracyNotes(record) {
4685
+ const accuracy = record.usageMetrics.accuracy;
4686
+ if (!accuracy) {
4687
+ return [unknownModelNote(record.usageMetrics.modelBreakdown)].filter((note) => note !== null);
3774
4688
  }
3775
- if (total <= 0 || unknown / total < 0.01) return null;
3776
- const pct2 = Math.round(unknown / total * 100);
3777
- return `${pct2}% of spend used models missing from the rate card and is priced at approximate (Sonnet) rates.`;
4689
+ const notes = [...accuracy.warnings];
4690
+ if (accuracy.unknownModels.length > 0) {
4691
+ const models = accuracy.unknownModels.map(({ model, requests }) => `${model} (${requests} ${plural(requests, "request")})`).join(", ");
4692
+ notes.push(`Models missing from the rate card: ${models}. Their current API-equivalent valuation is approximate.`);
4693
+ }
4694
+ return [...new Set(notes)];
3778
4695
  }
3779
4696
  function modelMix(breakdown) {
3780
4697
  const merged = /* @__PURE__ */ new Map();
@@ -3800,12 +4717,21 @@ function unassessedLine(pillars) {
3800
4717
  });
3801
4718
  return `Not yet scored: ${parts.join(" ")}`;
3802
4719
  }
4720
+ function weakestGap(p) {
4721
+ let worst = null;
4722
+ for (const c of p.checks) {
4723
+ if (!c.assessed || c.score == null || !c.gap) continue;
4724
+ if (!worst || c.score < worst.score) worst = c;
4725
+ }
4726
+ return worst;
4727
+ }
3803
4728
  function formatAudit(record, meta, color = false) {
3804
4729
  const a = ansi(color);
3805
4730
  const m = record.usageMetrics;
3806
4731
  const subscription = record.plan !== void 0 && record.plan !== "api";
3807
- const share = record.headlineWasteShare ?? (m.spendUsd > 0 ? record.headlineWasteUsd / m.spendUsd : 0);
3808
- const shareText = `${(share * 100).toFixed(1)}%`;
4732
+ const reportedShare = record.headlineWasteShare ?? (m.spendUsd > 0 ? record.headlineWasteUsd / m.spendUsd : 0);
4733
+ const shareIsValid = Number.isFinite(reportedShare) && reportedShare >= 0 && reportedShare <= 1;
4734
+ const shareText = shareIsValid ? `${(reportedShare * 100).toFixed(1)}%` : "unavailable";
3809
4735
  const lines = [];
3810
4736
  lines.push(a.bold("CostClaw audit"));
3811
4737
  const delegated = m.delegatedSessionsCount ?? 0;
@@ -3819,54 +4745,57 @@ function formatAudit(record, meta, color = false) {
3819
4745
  lines.push(a.dim("-".repeat(WRAP_WIDTH)));
3820
4746
  lines.push("");
3821
4747
  lines.push(
3822
- subscription ? `${a.bold(record.headlineWasteLabel + ":")} ${a.brand(shareText + " of analyzed usage")} (${usd2(record.headlineWasteUsd)} at API rates)` : `${a.bold(record.headlineWasteLabel + ":")} ${a.brand(usd2(record.headlineWasteUsd))}`
4748
+ 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))}`
3823
4749
  );
4750
+ if (record.verdict) {
4751
+ lines.push("");
4752
+ pushProse(lines, record.verdict);
4753
+ }
3824
4754
  const receipt = sinceOptimizeLine(meta);
3825
4755
  if (receipt) pushProse(lines, receipt, 0, a.dim);
3826
4756
  lines.push("");
3827
4757
  const mix = modelMix(m.modelBreakdown);
3828
4758
  const statBlock = [
3829
4759
  [
3830
- { k: subscription ? "Usage analyzed (API-equivalent)" : "Spend analyzed", v: usd2(m.spendUsd) },
4760
+ { k: "Current API-equivalent valuation (estimate)", v: usd2(m.spendUsd) },
3831
4761
  { k: "Cache hit", v: `${(m.cacheHitRate * 100).toFixed(1)}%` },
3832
- { k: "Active hours", v: m.durationHours.toFixed(1) }
4762
+ { k: "Session hours (timestamp union)", v: m.durationHours.toFixed(1) }
3833
4763
  ],
3834
4764
  [
3835
4765
  { k: "Pricing snapshot", v: m.pricingSnapshotDate },
3836
4766
  ...mix ? [{ k: "Model spend", v: mix }] : []
3837
- ]
4767
+ ],
4768
+ // Named explicitly because this figure used to sit inside the headline as
4769
+ // if it were waste. It is the cache paying for itself.
4770
+ ...record.cacheWriteCostUsd != null && record.cacheWriteCostUsd > 0 ? [[{ k: "Cache writes that earned their reads (working cost, not waste)", v: usd2(record.cacheWriteCostUsd) }]] : []
3838
4771
  ];
3839
4772
  for (const row of statRows(statBlock, a)) lines.push(row);
3840
- const unknownNote = unknownModelNote(m.modelBreakdown);
3841
- if (unknownNote) pushProse(lines, unknownNote, 0, a.dim);
4773
+ const cautions = accuracyNotes(record);
4774
+ if (cautions.length === 1) pushProse(lines, `Pricing caution: ${cautions[0]}`, 0, a.dim);
4775
+ else if (cautions.length > 1) {
4776
+ pushProse(lines, `Pricing caution: ${cautions[0]} (${cautions.length - 1} more in --json)`, 0, a.dim);
4777
+ }
4778
+ if (!shareIsValid) pushProse(lines, "Pricing caution: this legacy record has an invalid recoverable-waste share; its percentage is unavailable.", 0, a.dim);
3842
4779
  const w = record.usageWindows;
3843
4780
  if (subscription) {
3844
4781
  lines.push("");
3845
4782
  pushProse(
3846
4783
  lines,
3847
- `Plan: ${record.plan}. Dollar figures are API-equivalent token value, not money back; recovering them buys rate-limit headroom (more work per usage window).`,
4784
+ `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.`,
3848
4785
  0,
3849
4786
  a.dim
3850
4787
  );
3851
4788
  if (w?.assessed) {
3852
4789
  lines.push(
3853
- `${a.dim("Usage windows (5h, like your rate limit):")} median ${a.bold(usd2(w.medianWindowUsd))}, busiest ${a.bold(usd2(w.p90WindowUsd))}`
4790
+ `${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))}`
3854
4791
  );
3855
- lines.push(`${a.dim("Busiest week:")} ${a.bold(usd2(w.maxWeekUsd))} ${a.dim("(API-equivalent)")}`);
3856
- if (share >= 0.01 && share < 1) {
3857
- const gain = share / (1 - share);
3858
- const extraMinutes = Math.round(w.p90WindowActiveMinutes * gain);
3859
- lines.push("");
3860
- lines.push(
3861
- `Recovering ${shareText} buys about ${a.bold(`${Math.round(gain * 100)}% more work per window`)}:`
3862
- );
3863
- lines.push(` up to ${a.brand(`~${extraMinutes} extra minutes`)} in a window like your busiest.`);
3864
- }
4792
+ lines.push(`${a.dim("Busiest week:")} ${a.bold(usd2(w.maxWeekUsd))} ${a.dim("(estimated current API-equivalent valuation)")}`);
4793
+ lines.push(`${a.dim("Activity signal:")} 15-minute activity bins, not measured work time.`);
3865
4794
  }
3866
4795
  } else if (meta.planSource === "default") {
3867
- const burn = w?.assessed && w.medianWeekUsd >= 50 ? ` Your median week burns ${usd2(w.medianWeekUsd)} at API rates.` : "";
4796
+ const burn = w?.assessed && w.medianWeekUsd >= 50 ? ` Median weekly estimated current API-equivalent valuation: ${usd2(w.medianWeekUsd)}.` : "";
3868
4797
  lines.push("");
3869
- pushProse(lines, `Dollar figures are API-equivalent rates.${burn}`, 0, a.dim);
4798
+ pushProse(lines, `Dollar figures are estimated current API-equivalent valuations.${burn}`, 0, a.dim);
3870
4799
  pushProse(
3871
4800
  lines,
3872
4801
  "On a Claude subscription? Rerun with --plan max20x (or pro, max5x) to frame results as token efficiency.",
@@ -3876,7 +4805,7 @@ function formatAudit(record, meta, color = false) {
3876
4805
  }
3877
4806
  if (m.topProjects.length > 0) {
3878
4807
  lines.push("");
3879
- lines.push(a.bold("Top projects by spend:"));
4808
+ lines.push(a.bold("Top projects by estimated current API-equivalent valuation:"));
3880
4809
  for (const p of m.topProjects.slice(0, 5)) {
3881
4810
  const name = p.slug.length > 30 ? p.slug.slice(0, 27) + "..." : p.slug;
3882
4811
  const model = p.modelPrimary ? shortModel(p.modelPrimary) : "n/a";
@@ -3890,7 +4819,7 @@ function formatAudit(record, meta, color = false) {
3890
4819
  const bc = record.burnClock;
3891
4820
  if (bc?.assessed) {
3892
4821
  lines.push("");
3893
- lines.push(a.bold("Burn Clock (spend by day):"));
4822
+ lines.push(a.bold("Burn Clock (estimated current API-equivalent valuation by day):"));
3894
4823
  const max = Math.max(...bc.byDay, 0.01);
3895
4824
  for (const day2 of BURN_DAY_ORDER) {
3896
4825
  const v = bc.byDay[day2];
@@ -3906,21 +4835,28 @@ function formatAudit(record, meta, color = false) {
3906
4835
  }
3907
4836
  lines.push("");
3908
4837
  lines.push(
3909
- `${a.bold("Overall setup score:")} ${a.score(record.overallScore, `${record.overallScore} / 100`)} (${a.score(record.overallScore, record.band.label)})`
4838
+ `${a.bold("Rule-based setup score:")} ${a.score(record.overallScore, `${record.overallScore} / 100`)} (${a.score(record.overallScore, record.band.label)}; not an Anthropic grade)`
3910
4839
  );
3911
4840
  for (const p of record.pillarScores) {
3912
4841
  lines.push(` ${p.name.padEnd(22)} ${bar(p.score, a)}`);
4842
+ const weak = weakestGap(p);
4843
+ if (!weak) continue;
4844
+ lines.push(` ${a.dim("Weakest:")} ${weak.label} (${weak.score})`);
4845
+ pushProse(lines, weak.basis, 4, a.dim);
4846
+ if (weak.action) pushProse(lines, `Do this: ${weak.action}`, 4);
4847
+ lines.push("");
3913
4848
  }
3914
4849
  lines.push("");
3915
4850
  const dollarFixes = record.fixes.filter((f) => f.wasteUsd > 0);
3916
4851
  const otherIssues = record.fixes.filter((f) => f.wasteUsd === 0);
3917
- lines.push(a.bold("Top fixes by recoverable spend:"));
4852
+ lines.push(a.bold("Top changes, ranked by what they recover:"));
3918
4853
  if (dollarFixes.length === 0) {
3919
- lines.push(" No directly recoverable dollars found. See issues below.");
4854
+ lines.push(" No recoverable waste was found. See the issues below.");
3920
4855
  } else {
3921
4856
  for (const [i, f] of dollarFixes.entries()) {
3922
4857
  if (i > 0) lines.push("");
3923
- lines.push(` - [${a.brand(usd2(f.wasteUsd))}] ${a.bold(f.title)}`);
4858
+ lines.push(` - [${a.brand(usd2(f.wasteUsd))} estimated valuation] ${a.bold(f.title)}`);
4859
+ if (f.problem) pushProse(lines, f.problem, 6);
3924
4860
  pushProse(lines, f.action, 6);
3925
4861
  if (f.basis) pushProse(lines, `Evidence: ${f.basis}`, 6, a.dim);
3926
4862
  }
@@ -3942,6 +4878,10 @@ function formatAudit(record, meta, color = false) {
3942
4878
  lines.push("");
3943
4879
  lines.push(a.dim(gapLine));
3944
4880
  }
4881
+ lines.push("");
4882
+ 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.";
4883
+ const provenance = m.accuracy ? ` Pricing snapshot: ${m.accuracy.pricingSnapshotDate}; accounting method: v${m.accuracy.accountingVersion}.` : "";
4884
+ pushProse(lines, methodology + provenance, 0, a.dim);
3945
4885
  return lines.join("\n");
3946
4886
  }
3947
4887
 
@@ -3973,14 +4913,14 @@ function estimateTextWidth(s, size) {
3973
4913
 
3974
4914
  // src/html-report.ts
3975
4915
  function usd3(n) {
3976
- return `$${(Math.round(n * 100) / 100).toFixed(2)}`;
4916
+ return `$${roundMoneyHalfUp(n).toFixed(2)}`;
3977
4917
  }
3978
4918
  function truncate(s, max) {
3979
4919
  return s.length > max ? s.slice(0, max - 3) + "..." : s;
3980
4920
  }
3981
4921
  function projectChart(projects) {
3982
4922
  if (projects.length === 0) {
3983
- return `<p class="muted">No project spend to chart.</p>`;
4923
+ return `<p class="muted">No project valuation estimate to chart.</p>`;
3984
4924
  }
3985
4925
  const rowH = 28;
3986
4926
  const gap = 8;
@@ -3999,7 +4939,7 @@ function projectChart(projects) {
3999
4939
  const label = esc(truncate(p.slug, 30));
4000
4940
  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>`;
4001
4941
  }).join("");
4002
- return `<svg viewBox="0 0 ${width} ${height}" width="100%" height="${height}" role="img" aria-label="Top projects by cost" preserveAspectRatio="xMinYMin meet">${rows}</svg>`;
4942
+ 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>`;
4003
4943
  }
4004
4944
  function burnClockChart(bc) {
4005
4945
  const rowH = 22;
@@ -4020,7 +4960,15 @@ function burnClockChart(bc) {
4020
4960
  const label = esc(BURN_DAY_NAMES[day2]);
4021
4961
  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>`;
4022
4962
  }).join("");
4023
- return `<svg viewBox="0 0 ${width} ${height}" width="100%" height="${height}" role="img" aria-label="Spend by day of week" preserveAspectRatio="xMinYMin meet">${rows}</svg>`;
4963
+ 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>`;
4964
+ }
4965
+ function weakestGap2(p) {
4966
+ let worst = null;
4967
+ for (const c of p.checks) {
4968
+ if (!c.assessed || c.score == null || !c.gap) continue;
4969
+ if (!worst || c.score < worst.score) worst = c;
4970
+ }
4971
+ return worst;
4024
4972
  }
4025
4973
  function pillarBars(pillars) {
4026
4974
  return pillars.map((p) => {
@@ -4030,7 +4978,9 @@ function pillarBars(pillars) {
4030
4978
  }
4031
4979
  const score = p.score;
4032
4980
  const color = bandColorForScore(score);
4033
- 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>`;
4981
+ const weak = weakestGap2(p);
4982
+ 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>` : "";
4983
+ 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;
4034
4984
  }).join("");
4035
4985
  }
4036
4986
  function dollarFixCard(f) {
@@ -4058,17 +5008,17 @@ function nextStepsSection(record, meta) {
4058
5008
  steps.push(step(
4059
5009
  n++,
4060
5010
  "Tell costclaw how you pay",
4061
- `<p>On a Claude subscription the dollar figures above are token value, not money back. Declare your plan once and the report reframes everything as usage you win back.</p>` + cmd("npx costclaw audit --plan max20x # or pro, max5x, api")
5011
+ `<p>On a Claude subscription, dollar figures remain estimated current API-equivalent valuations, not money back or measured quota. Declare your plan once to add the subscription caveat.</p>` + cmd("npx costclaw audit --plan max20x # or pro, max5x, api")
4062
5012
  ));
4063
5013
  }
4064
5014
  const waste = record.headlineWasteUsd;
4065
- const wasteLine = waste > 0 ? `This audit found <strong>${esc(usd3(waste))}</strong> of recoverable input spend. ` : "";
5015
+ const wasteLine = waste > 0 ? `This audit estimates <strong>${esc(usd3(waste))}</strong> of recoverable waste at current API list prices. ` : "";
4066
5016
  if (licensed) {
4067
5017
  const who = meta.license?.email ? ` (${esc(meta.license.email)})` : "";
4068
5018
  steps.push(step(
4069
5019
  n++,
4070
5020
  "Apply the fixes with optimize",
4071
- `<p class="ok">License active on this machine${who}.</p><p>${wasteLine}Run optimize inside each project you work in. It scans the project, writes a filled-in CLAUDE.md, a ranked playbook, suggested settings, a work order, and a dashboard into <span class="mono">./costclaw-out</span>, then opens the dashboard.</p>` + cmd("cd <your-project>\nnpx costclaw optimize") + `<p>Happy with the dry run? Apply it in place (both back up the original and print a diff), then hand the work order to your own Claude Code:</p>` + cmd('npx costclaw optimize --write CLAUDE.md --apply-settings\nclaude "Follow costclaw-out/HARNESS-UPGRADE.md"') + `<p class="fine">Moving machines? <span class="mono">costclaw deactivate</span> here, <span class="mono">costclaw activate &lt;key&gt;</span> there.</p>`
5021
+ `<p class="ok">License active on this machine${who}.</p><p>${wasteLine}Run optimize once. With no <span class="mono">--project</span> it ranks every project this audit saw and generates for the top ones, then opens a page listing them. Nothing inside your projects is written yet.</p>` + cmd("npx costclaw optimize") + `<p>Then apply it where you want it. <span class="mono">apply</span> is additive: it writes the generated include to <span class="mono">.claude/costclaw.md</span> and adds one import line to your CLAUDE.md, leaving every line you wrote untouched. <span class="mono">--apply-settings</span> additively merges the suggested permission allowlist, and <span class="mono">--remove</span> undoes all of it.</p>` + cmd('npx costclaw apply <your-project> --apply-settings\nclaude "Follow UPGRADE-ALL.md"') + `<p class="fine">Moving machines? <span class="mono">costclaw deactivate</span> here, <span class="mono">costclaw activate &lt;key&gt;</span> there.</p>`
4072
5022
  ));
4073
5023
  } else {
4074
5024
  steps.push(step(
@@ -4080,7 +5030,7 @@ function nextStepsSection(record, meta) {
4080
5030
  steps.push(step(
4081
5031
  n++,
4082
5032
  "Track the movement",
4083
- `<p>Every audit snapshots the derived record locally. Rerun in a week and compare: new spend, the cache hit rate for just that period, pillar movement, and which fixes resolved.</p>` + cmd("npx costclaw audit\nnpx costclaw diff")
5033
+ `<p>Every audit snapshots the derived record locally. Rerun in a week and compare: new valuation estimates, the cache hit rate for just that period, pillar movement, and which fixes resolved.</p>` + cmd("npx costclaw audit\nnpx costclaw diff")
4084
5034
  ));
4085
5035
  steps.push(step(
4086
5036
  n++,
@@ -4165,6 +5115,11 @@ h2 {
4165
5115
  .score-head .big { font-size: 30px; font-weight: 700; letter-spacing: -0.01em; }
4166
5116
  .score-head .band { font-size: 15px; color: var(--umber); font-weight: 600; }
4167
5117
  .pillar { display: flex; align-items: center; gap: var(--s3); margin: var(--s2) 0; }
5118
+ .p-detail { margin: 0 0 var(--s3) 0; padding: var(--s2) var(--s3); border-left: 2px solid var(--line); }
5119
+ .p-weak { font-size: 13px; font-weight: 600; }
5120
+ .p-basis { margin: 4px 0 0 0; font-size: 13px; color: var(--muted); }
5121
+ .p-action { margin: 4px 0 0 0; font-size: 13px; }
5122
+ .verdict { margin: var(--s2) 0 0 0; font-size: 14px; line-height: 1.5; }
4168
5123
  .p-name { flex: 0 0 190px; font-size: 14px; }
4169
5124
  .p-track { flex: 1; height: 14px; background: var(--track); border-radius: 7px; overflow: hidden; }
4170
5125
  .p-fill { display: block; height: 100%; border-radius: 7px; }
@@ -4253,30 +5208,25 @@ table.ref td:first-child { white-space: nowrap; color: var(--umber); font-size:
4253
5208
  function renderHtml(record, meta) {
4254
5209
  const m = record.usageMetrics;
4255
5210
  const mix = modelMix(m.modelBreakdown);
4256
- const unknownNote = unknownModelNote(m.modelBreakdown);
5211
+ const accuracyNotesForRecord = accuracyNotes(record);
4257
5212
  const mixCells = mix ? mix.split(" / ").map((part) => `<span class="nb">${esc(part)}</span>`).join(" / ") : "";
4258
5213
  const subscription = record.plan !== void 0 && record.plan !== "api";
4259
- const share = record.headlineWasteShare ?? (m.spendUsd > 0 ? record.headlineWasteUsd / m.spendUsd : 0);
4260
- const shareText = `${(share * 100).toFixed(1)}%`;
4261
- const bannerAmount = subscription ? `<div class="amount">${shareText} of analyzed usage</div><div class="amount-sub">${esc(usd3(record.headlineWasteUsd))} at API rates</div>` : `<div class="amount mono">${esc(usd3(record.headlineWasteUsd))}</div>`;
4262
- const spendLabel = subscription ? "Usage analyzed (API-equivalent)" : "Spend analyzed";
5214
+ const reportedShare = record.headlineWasteShare ?? (m.spendUsd > 0 ? record.headlineWasteUsd / m.spendUsd : 0);
5215
+ const shareIsValid = Number.isFinite(reportedShare) && reportedShare >= 0 && reportedShare <= 1;
5216
+ const shareText = shareIsValid ? `${(reportedShare * 100).toFixed(1)}%` : "unavailable";
5217
+ 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>`;
5218
+ const spendLabel = "Current API-equivalent valuation (estimate)";
4263
5219
  const w = record.usageWindows;
4264
- let headroom = "";
4265
- if (subscription && w?.assessed && share >= 0.01 && share < 1) {
4266
- const gain = share / (1 - share);
4267
- const extraMinutes = Math.round(w.p90WindowActiveMinutes * gain);
4268
- headroom = ` Recovering ${shareText} buys about ${Math.round(gain * 100)}% more work per window: up to ~${extraMinutes} extra minutes in a window like your busiest.`;
4269
- }
4270
- const weeklyBurn = !subscription && meta.planSource === "default" && w?.assessed && w.medianWeekUsd >= 50 ? ` Your median week burns ${esc(usd3(w.medianWeekUsd))} at API rates.` : "";
4271
- const planNote = subscription ? `<p class="sub">Plan: ${esc(record.plan)}. Dollar figures are API-equivalent token value, not money back; recovering them buys rate-limit headroom (more work per usage window).${headroom}</p>` : meta.planSource === "default" ? `<p class="sub">Dollar figures are API-equivalent rates.${weeklyBurn} On a Claude subscription? Rerun with --plan max20x (or pro, max5x) to frame results as token efficiency.</p>` : "";
4272
- 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">Busiest 5h window (p90)</div><div class="v">${esc(usd3(w.p90WindowUsd))}</div></div><div class="stat"><div class="k">Busiest week</div><div class="v">${esc(usd3(w.maxWeekUsd))}</div></div></div>` : "";
5220
+ const weeklyBurn = !subscription && meta.planSource === "default" && w?.assessed && w.medianWeekUsd >= 50 ? ` Median weekly estimated current API-equivalent valuation: ${esc(usd3(w.medianWeekUsd))}.` : "";
5221
+ 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>` : "";
5222
+ 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>` : "";
4273
5223
  const dollarFixes = record.fixes.filter((f) => f.wasteUsd > 0).sort((a, b) => b.wasteUsd - a.wasteUsd);
4274
5224
  const otherIssues = record.fixes.filter((f) => f.wasteUsd === 0);
4275
- const dollarSection = dollarFixes.length === 0 ? `<p class="muted">No directly recoverable dollars found. See issues below.</p>` : `<ul class="fixes">${dollarFixes.map(dollarFixCard).join("")}</ul>`;
5225
+ 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>`;
4276
5226
  const otherSection = otherIssues.length === 0 ? "" : `<h2>Other issues to tighten</h2><ul class="fixes">${otherIssues.map(otherFixCard).join("")}</ul>`;
4277
5227
  const bc = record.burnClock;
4278
5228
  const burnSentence = bc?.assessed ? burnClockSentence(bc) : null;
4279
- const burnSection = bc?.assessed ? `<h2>Burn Clock (spend by day)</h2>
5229
+ const burnSection = bc?.assessed ? `<h2>Burn Clock (estimated current API-equivalent valuation by day)</h2>
4280
5230
  <div class="chart">${burnClockChart(bc)}</div>
4281
5231
  ` + (burnSentence ? `<p class="sub">${esc(burnSentence)}</p>
4282
5232
  ` : "") : "";
@@ -4305,33 +5255,40 @@ ${metaBlock}
4305
5255
  <div class="banner">
4306
5256
  <div class="label">${esc(record.headlineWasteLabel)}</div>
4307
5257
  ${bannerAmount}
5258
+ ${record.verdict ? `<p class="verdict">${esc(record.verdict)}</p>` : ""}
4308
5259
  </div>
4309
5260
  ${planNote}
4310
5261
  <div class="stats">
4311
5262
  <div class="stat"><div class="k">${spendLabel}</div><div class="v">${esc(usd3(m.spendUsd))}</div></div>
4312
5263
  <div class="stat"><div class="k">Cache hit rate</div><div class="v">${(m.cacheHitRate * 100).toFixed(1)}%</div></div>
4313
- <div class="stat"><div class="k">Active hours</div><div class="v">${m.durationHours.toFixed(1)}</div></div>
5264
+ <div class="stat"><div class="k">Session hours (timestamp union)</div><div class="v">${m.durationHours.toFixed(1)}</div></div>
4314
5265
  ${mix ? `<div class="stat"><div class="k">Model spend</div><div class="v v-small">${mixCells}</div></div>` : ""}
5266
+ ${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>` : ""}
4315
5267
  </div>
4316
- ${unknownNote ? `<p class="meta">${esc(unknownNote)}</p>` : ""}
5268
+ ${accuracyNotesForRecord.map((note) => `<p class="meta">${esc(`Pricing caution: ${note}`)}</p>`).join("\n")}
5269
+ ${!shareIsValid ? `<p class="meta">Pricing caution: this legacy record has an invalid cache-miss exposure share; its percentage is unavailable.</p>` : ""}
4317
5270
  ${windowTiles}
4318
5271
 
4319
- <h2>Spend by project</h2>
5272
+ <h2>Projects by estimated current API-equivalent valuation</h2>
4320
5273
  <div class="chart">${projectChart(m.topProjects)}</div>
4321
5274
 
4322
5275
  ${burnSection}
4323
- <h2>Setup score</h2>
5276
+ <h2>Rule-based setup score</h2>
4324
5277
  <div class="score-head">
4325
5278
  <span class="big">${record.overallScore} / 100</span>
4326
5279
  <span class="band">${esc(record.band.label)}</span>
4327
5280
  </div>
5281
+ <p class="sub">A transparent heuristic from observed setup signals, not an Anthropic grade.</p>
4328
5282
  ${pillarBars(record.pillarScores)}
4329
5283
 
4330
- <h2>Top fixes by recoverable spend</h2>
5284
+ <h2>Top changes, ranked by what they recover</h2>
4331
5285
  ${dollarSection}
4332
5286
  ${otherSection}
4333
5287
  ${skippedNote}
4334
5288
 
5289
+ <h2>Methodology</h2>
5290
+ <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>
5291
+
4335
5292
  ${nextStepsSection(record, meta)}
4336
5293
 
4337
5294
  <div class="footer">
@@ -4354,7 +5311,7 @@ var PAPER = "#fefaf7";
4354
5311
  var BORDER = "#f0e2da";
4355
5312
  var MUTED = "#7a6a63";
4356
5313
  function usd4(n) {
4357
- return `$${(Math.round(n * 100) / 100).toFixed(2)}`;
5314
+ return `$${roundMoneyHalfUp(n).toFixed(2)}`;
4358
5315
  }
4359
5316
  function strongestPillar(pillars) {
4360
5317
  const assessed = pillars.filter((p) => p.assessed && p.score !== null);
@@ -4368,9 +5325,10 @@ function renderCard(record) {
4368
5325
  const cacheHitPct = `${(record.usageMetrics.cacheHitRate * 100).toFixed(1)}%`;
4369
5326
  const subscription = record.plan !== void 0 && record.plan !== "api";
4370
5327
  const spend = record.usageMetrics.spendUsd;
4371
- const share = record.headlineWasteShare ?? (spend > 0 ? record.headlineWasteUsd / spend : 0);
4372
- const wasteLine = subscription ? `Recoverable usage: ${(share * 100).toFixed(1)}%` : `Recoverable spend: ${usd4(record.headlineWasteUsd)}`;
4373
- const ariaLabel = `CostClaw score ${record.overallScore} of 100, ${record.band.label}`;
5328
+ const reportedShare = record.headlineWasteShare ?? (spend > 0 ? record.headlineWasteUsd / spend : 0);
5329
+ const shareIsValid = Number.isFinite(reportedShare) && reportedShare >= 0 && reportedShare <= 1;
5330
+ const wasteLine = subscription ? `Cache-miss exposure: ${shareIsValid ? `${(reportedShare * 100).toFixed(1)}%` : "unavailable"}` : `Cache-miss exposure: ${usd4(record.headlineWasteUsd)} estimate`;
5331
+ const ariaLabel = `CostClaw rule-based setup score ${record.overallScore} of 100, ${record.band.label}`;
4374
5332
  const scoreText = String(record.overallScore);
4375
5333
  const scoreX = 32;
4376
5334
  const scoreW = estimateTextWidth(scoreText, 72);
@@ -4590,8 +5548,8 @@ async function deactivateLicense(opts = {}) {
4590
5548
  // src/plan-prompt.ts
4591
5549
  import { createInterface } from "readline/promises";
4592
5550
  var PLAN_PROMPT_LINES = [
4593
- "How do you pay for Claude Code? This decides whether the report talks in",
4594
- "dollars or in rate-limit headroom.",
5551
+ "How do you pay for Claude Code? This adds the right caveat to the report's",
5552
+ "estimated current API-equivalent valuations.",
4595
5553
  "",
4596
5554
  " 1) API, pay per token",
4597
5555
  " 2) Pro subscription",
@@ -4689,7 +5647,7 @@ async function loadAuditInputs(opts) {
4689
5647
  let claudeMdSource = null;
4690
5648
  if (opts.claudeMdPath) {
4691
5649
  claudeMd = await readFile4(opts.claudeMdPath, "utf8");
4692
- claudeMdSource = resolve(opts.claudeMdPath);
5650
+ claudeMdSource = resolve2(opts.claudeMdPath);
4693
5651
  } else {
4694
5652
  const fallback = join5(opts.home ?? homedir4(), ".claude", "CLAUDE.md");
4695
5653
  try {
@@ -4718,6 +5676,7 @@ async function runAudit(opts) {
4718
5676
  questionnaire: {},
4719
5677
  setup,
4720
5678
  plan,
5679
+ timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
4721
5680
  tzOffsetMinutes: -(/* @__PURE__ */ new Date()).getTimezoneOffset()
4722
5681
  });
4723
5682
  const baseline = (await readCliConfig(configDir)).lastOptimize;
@@ -4744,14 +5703,14 @@ async function runAudit(opts) {
4744
5703
  const notices = [];
4745
5704
  if (snapshotNotice) notices.push(snapshotNotice);
4746
5705
  if (opts.html) {
4747
- const target = resolve(opts.htmlPath || DEFAULT_HTML_FILE);
5706
+ const target = resolve2(opts.htmlPath || DEFAULT_HTML_FILE);
4748
5707
  const doc = renderHtml(record, { root, sessionCount: logs.length, skipped, claudeMdSource, planSource, sinceOptimize, license });
4749
5708
  await writeFile3(target, doc, "utf8");
4750
5709
  openInBrowser(target);
4751
5710
  notices.push(`HTML report written to ${target}`);
4752
5711
  }
4753
5712
  if (opts.card) {
4754
- const target = resolve(opts.cardPath || DEFAULT_CARD_FILE);
5713
+ const target = resolve2(opts.cardPath || DEFAULT_CARD_FILE);
4755
5714
  const svg = renderCard(record);
4756
5715
  await writeFile3(target, svg, "utf8");
4757
5716
  notices.push(`Score card written to ${target}`);
@@ -4766,24 +5725,24 @@ async function runAudit(opts) {
4766
5725
 
4767
5726
  // src/optimize-command.ts
4768
5727
  import { mkdir as mkdir6, writeFile as writeFile6, readFile as readFile10, stat as stat3 } from "fs/promises";
4769
- import { basename as basename2, join as join10, resolve as resolve5 } from "path";
5728
+ import { basename as basename3, join as join10, resolve as resolve6 } from "path";
4770
5729
  import { homedir as homedir5 } from "os";
4771
5730
 
4772
5731
  // src/claude-md-imports.ts
4773
5732
  import { readFile as readFile5 } from "fs/promises";
4774
- import { dirname, isAbsolute, join as join6, resolve as resolve2 } from "path";
5733
+ import { dirname as dirname2, isAbsolute, join as join6, resolve as resolve3 } from "path";
4775
5734
  var IMPORT_RE = /^@(\S+)\s*$/;
4776
5735
  async function resolveClaudeMdImports(claudeMdPath, text2, home) {
4777
5736
  const out = { imports: [], notes: [] };
4778
5737
  if (!claudeMdPath || !text2) return out;
4779
- const base = dirname(resolve2(claudeMdPath));
5738
+ const base = dirname2(resolve3(claudeMdPath));
4780
5739
  const seen = /* @__PURE__ */ new Set();
4781
5740
  for (const line of text2.split(/\r?\n/)) {
4782
5741
  const m = line.match(IMPORT_RE);
4783
5742
  const raw = m?.[1];
4784
5743
  if (!raw) continue;
4785
5744
  const expanded = raw === "~" || raw.startsWith("~/") ? join6(home, raw.slice(1)) : raw;
4786
- const full = isAbsolute(expanded) ? resolve2(expanded) : resolve2(base, expanded);
5745
+ const full = isAbsolute(expanded) ? resolve3(expanded) : resolve3(base, expanded);
4787
5746
  if (seen.has(full)) continue;
4788
5747
  seen.add(full);
4789
5748
  try {
@@ -4797,7 +5756,7 @@ async function resolveClaudeMdImports(claudeMdPath, text2, home) {
4797
5756
 
4798
5757
  // src/apply-command.ts
4799
5758
  import { mkdir as mkdir4, writeFile as writeFile4, readFile as readFile6, rm as rm3, stat, copyFile } from "fs/promises";
4800
- import { join as join7, dirname as dirname2 } from "path";
5759
+ import { join as join7, dirname as dirname3 } from "path";
4801
5760
  var IMPORT_LINE2 = "@.claude/costclaw.md";
4802
5761
  var INCLUDE_REL = ".claude/costclaw.md";
4803
5762
  var APPLY_DIR_REL = ".claude/costclaw";
@@ -5024,7 +5983,7 @@ async function applyDerivedSettings(target, suggestedJson, force) {
5024
5983
  mergedPerms.deny = unionStrings(asStringArray(existingPerms.deny), suggestedDeny);
5025
5984
  const merged = { ...existing, permissions: mergedPerms };
5026
5985
  const mergedText = JSON.stringify(merged, null, 2) + "\n";
5027
- await mkdir4(dirname2(target), { recursive: true });
5986
+ await mkdir4(dirname3(target), { recursive: true });
5028
5987
  await writeFile4(backup, existingText, "utf8");
5029
5988
  await writeFile4(target, mergedText, "utf8");
5030
5989
  return [
@@ -5114,6 +6073,8 @@ ul.warn li:last-child{border-bottom:0}
5114
6073
  ul.warn b{font-weight:650}
5115
6074
  .pill{display:inline-block;font-size:.7rem;padding:2px 8px;border-radius:99px;border:1px solid var(--line);
5116
6075
  color:var(--ink2);margin-left:8px;vertical-align:1px}
6076
+ .pill.own-apply{border-color:var(--accent);color:var(--accent);font-weight:650}
6077
+ .pill.own-you{font-weight:650}
5117
6078
  .files{display:grid;gap:12px;grid-template-columns:repeat(auto-fit,minmax(250px,1fr))}
5118
6079
  .file{border:1px solid var(--line);border-radius:10px;padding:15px 16px;background:var(--panel);
5119
6080
  display:flex;flex-direction:column;gap:6px}
@@ -5156,18 +6117,23 @@ pre.diff .ctx{color:var(--ink2);display:block}
5156
6117
  margin:0 0 8px;font-weight:600}
5157
6118
  `;
5158
6119
  var TAG_META = {
5159
- carried: { cls: "keep", label: "carried" },
5160
- filled: { cls: "fill", label: "filled" },
5161
- replaced: { cls: "repl", label: "replaced" },
5162
- dropped: { cls: "drop", label: "left out" },
5163
- placeholder: { cls: "hole", label: "placeholder" }
6120
+ carried: { cls: "keep", label: "carried", meaning: "kept word for word from your file" },
6121
+ filled: { cls: "fill", label: "filled", meaning: "an empty section completed from your project" },
6122
+ replaced: { cls: "repl", label: "replaced", meaning: "rewritten from what the scan found on disk" },
6123
+ dropped: { cls: "drop", label: "left out", meaning: "not copied over, reason in the next column" },
6124
+ placeholder: { cls: "hole", label: "placeholder", meaning: "still a blank for you to fill in" }
5164
6125
  };
6126
+ function tagLegend(sections) {
6127
+ const used = new Set(sections.map((s) => s.disposition));
6128
+ const items = Object.keys(TAG_META).filter((k) => used.has(k)).map((k) => `<li><span class="tag ${TAG_META[k].cls}">${TAG_META[k].label}</span> ${esc(TAG_META[k].meaning)}</li>`).join("");
6129
+ return items ? `<ul class="taglegend">${items}</ul>` : "";
6130
+ }
5165
6131
  function renderSectionsTable(sections) {
5166
6132
  const rows = sections.map((s) => {
5167
6133
  const meta = TAG_META[s.disposition];
5168
- return `<tr><td>${esc(s.name)}</td><td><span class="tag ${meta.cls}">${meta.label}</span></td><td>${esc(s.why)}</td></tr>`;
6134
+ return `<tr><td>${esc(s.name)}</td><td><span class="tag ${meta.cls}" title="${esc(meta.meaning)}">${meta.label}</span></td><td>${esc(s.why)}</td></tr>`;
5169
6135
  }).join("");
5170
- return `<p class="note" style="margin-top:0">Every section of your file and what this run did with it. Nothing was deleted silently: dropped sections are named with a reason.</p><div class="scroll"><table><thead><tr><th>Section</th><th>What happened</th><th>Why</th></tr></thead><tbody>${rows}</tbody></table></div>`;
6136
+ return `<p class="note" style="margin-top:0">Every section of your file and what this run did with it. Nothing was deleted silently: dropped sections are named with a reason.</p>` + tagLegend(sections) + `<div class="scroll"><table><thead><tr><th>Section</th><th>What happened</th><th>Why</th></tr></thead><tbody>${rows}</tbody></table></div>`;
5171
6137
  }
5172
6138
  var DIFF_LCS_LIMIT = 3e3;
5173
6139
  function diffLines(before, after) {
@@ -5298,7 +6264,7 @@ function renderSectionsStat(sections) {
5298
6264
  }
5299
6265
  function renderRecoverableStat(input) {
5300
6266
  const pct2 = `${(input.headlineWasteShare * 100).toFixed(1)}%`;
5301
- return `<div class="stat"><span class="l">Recoverable usage</span><span class="v">${esc(pct2)}</span><span class="d">of analyzed usage, about ${esc(usd5(input.headlineWasteUsd))} at API rates. On a subscription that is rate-limit headroom, not money back.</span></div>`;
6267
+ return `<div class="stat"><span class="l">Cache-miss exposure (estimate)</span><span class="v">${esc(pct2)}</span><span class="d">of analyzed token value, ${esc(usd5(input.headlineWasteUsd))} estimated current API-equivalent valuation. Not money back, actual quota, or a promise of more work.</span></div>`;
5302
6268
  }
5303
6269
  function renderReceipt(input) {
5304
6270
  const stats = `<div class="grid g3">${renderTokenStat(input)}${renderSectionsStat(input.sectionDispositions)}${renderRecoverableStat(input)}</div>`;
@@ -5331,11 +6297,11 @@ function renderCacheTable2(report) {
5331
6297
  const tailUsd = tail.reduce((sum, r) => sum + r.usd, 0);
5332
6298
  tailRow = `<tr><td colspan="4" style="color:var(--ink2)">${tail.length} smaller ${plural2(tail.length, "project")} account${tail.length === 1 ? "s" : ""} for the remaining ${esc(usd5(tailUsd))}.</td></tr>`;
5333
6299
  }
5334
- return `<h4 style="margin:20px 0 8px;font-size:.9rem">Where that money is</h4><div class="scroll"><table><thead><tr><th>Project</th><th class="num">Recoverable</th><th class="num">Cache hit</th><th class="num">Main sessions</th></tr></thead><tbody>${rows}${tailRow}</tbody></table></div><p class="note"><b>Why a high hit rate can still leave money on the table:</b> the exposure counts cache writes, not just misses. A project can read its prefix from cache almost every turn and still rebuild that prefix often. This figure is an upper bound on what tighter session starts could recover.</p>`;
6300
+ return `<h4 style="margin:20px 0 8px;font-size:.9rem">Cache-miss exposure by project</h4><div class="scroll"><table><thead><tr><th>Project</th><th class="num">Exposure estimate</th><th class="num">Cache hit</th><th class="num">Main sessions</th></tr></thead><tbody>${rows}${tailRow}</tbody></table></div><p class="note"><b>Why a high hit rate can still leave money on the table:</b> the exposure counts cache writes, not just misses. A project can read its prefix from cache almost every turn and still rebuild that prefix often. This figure is an upper bound on what tighter session starts could recover.</p>`;
5335
6301
  }
5336
6302
  function renderFixes(fixes, report) {
5337
6303
  const dollarFixes = fixes.filter((f) => f.wasteUsd > 0).sort((a, b) => b.wasteUsd - a.wasteUsd);
5338
- if (dollarFixes.length === 0) return `<p class="note">No directly recoverable dollars found.</p>`;
6304
+ if (dollarFixes.length === 0) return `<p class="note">No cache-miss exposure estimate found.</p>`;
5339
6305
  return dollarFixes.map((f, i) => {
5340
6306
  const table = f.id === "cache_recovery" ? renderCacheTable2(report) : "";
5341
6307
  return `<div class="fix"><h3>${i + 1}. ${esc(f.title)} <span class="amt">${esc(usd5(f.wasteUsd))}</span></h3><p>${esc(f.problem)}</p><div class="do"><b>Do this:</b> ${esc(f.action)}</div>${table}</div>`;
@@ -5352,6 +6318,16 @@ function toolWarnings(report) {
5352
6318
  }
5353
6319
  return out.sort((a, b) => b.sessions - a.sessions);
5354
6320
  }
6321
+ var APPLY_WRITES = /* @__PURE__ */ new Set([
6322
+ "check_permission_allowlist",
6323
+ "check_cmd_size",
6324
+ "check_cmd_structure",
6325
+ "check_cmd_stability",
6326
+ "check_cmd_scope"
6327
+ ]);
6328
+ function ownerPill(fixId) {
6329
+ return APPLY_WRITES.has(fixId) ? `<span class="pill own-apply" title="Running apply on this project writes this change.">costclaw applies this</span>` : `<span class="pill own-you" title="No file costclaw writes can change this; the work order turns it into a task for your own Claude Code.">you change this</span>`;
6330
+ }
5355
6331
  function renderSetupWarnings(fixes, report) {
5356
6332
  const warnFixes = fixes.filter((f) => f.wasteUsd <= 0);
5357
6333
  const tool = toolWarnings(report);
@@ -5359,15 +6335,16 @@ function renderSetupWarnings(fixes, report) {
5359
6335
  const single = tool.filter((t) => t.sessions === 1);
5360
6336
  const items = [];
5361
6337
  for (const f of warnFixes) {
5362
- items.push(`<li><b>${esc(f.title)}.</b> ${esc(f.action)} <span class="pill">measured</span></li>`);
6338
+ items.push(`<li><b>${esc(f.title)}.</b> ${esc(f.action)} <span class="pill">measured</span>${ownerPill(f.id)}</li>`);
5363
6339
  }
5364
6340
  for (const t of multi) {
5365
6341
  const sentence = t.action ? ` ${esc(t.action)}` : "";
5366
6342
  items.push(
5367
- `<li><b>${esc(t.title)}.</b>${sentence} <span class="pill">${t.sessions} ${plural2(t.sessions, "session")}</span></li>`
6343
+ `<li><b>${esc(t.title)}.</b>${sentence} <span class="pill">${t.sessions} ${plural2(t.sessions, "session")}</span>${ownerPill("")}</li>`
5368
6344
  );
5369
6345
  }
5370
- const list = items.length > 0 ? `<ul class="warn">${items.join("")}</ul>` : `<p class="note">No setup warnings found.</p>`;
6346
+ const ownerNote = items.length > 0 ? `<p class="note" style="margin-top:0"><b>costclaw applies this</b> means running apply on the project writes it. <b>you change this</b> means no file costclaw writes can fix it; the work order on the index page turns those into tasks you can hand to your own Claude Code.</p>` : "";
6347
+ const list = items.length > 0 ? `${ownerNote}<ul class="warn">${items.join("")}</ul>` : `<p class="note">No setup warnings found.</p>`;
5371
6348
  let disclosure = "";
5372
6349
  if (single.length > 0) {
5373
6350
  const names = [...new Set(single.map((t) => t.tool))].map(esc).join(", ");
@@ -5469,6 +6446,17 @@ pre.review .mark-move{background:color-mix(in srgb,var(--warn) 14%,transparent)}
5469
6446
  pre.review .mark-add{background:color-mix(in srgb,var(--good) 14%,transparent)}
5470
6447
  pre.review .skip{color:var(--ink2);font-style:italic}
5471
6448
  .legend{font-size:.78rem;color:var(--ink2);margin:0 0 10px}
6449
+ .taglegend{list-style:none;padding:0;margin:0 0 12px;display:flex;flex-wrap:wrap;gap:6px 16px;font-size:.78rem;color:var(--ink2)}
6450
+ .taglegend li{display:flex;align-items:center;gap:6px}
6451
+ .changes{margin:0;padding-left:20px;display:flex;flex-direction:column;gap:10px}
6452
+ .changes li{line-height:1.45}
6453
+ .ch-head{display:flex;flex-wrap:wrap;align-items:baseline;gap:6px}
6454
+ .changes .note{margin:2px 0 0}
6455
+ .tag.ch-remove{border-color:#c0504d;color:#c0504d}
6456
+ .tag.ch-move{border-color:#b8860b;color:#b8860b}
6457
+ .tag.ch-add{border-color:var(--accent);color:var(--accent)}
6458
+ .filedrop{margin-top:14px}
6459
+ .filedrop summary{cursor:pointer;font-size:.82rem;color:var(--ink2)}
5472
6460
  .legend b{font-weight:650}
5473
6461
  .legend .sw{display:inline-block;width:10px;height:10px;border-radius:3px;margin:0 4px 0 12px}
5474
6462
  .legend .sw.r{background:color-mix(in srgb,var(--bad) 50%,transparent)}
@@ -5518,6 +6506,35 @@ function renderLines(lines, keepRunMax) {
5518
6506
  flush();
5519
6507
  return `<pre class="review">${out.join("")}</pre>`;
5520
6508
  }
6509
+ var CHANGE_KIND = {
6510
+ remove: { label: "remove", cls: "ch-remove" },
6511
+ move: { label: "move out", cls: "ch-move" },
6512
+ add: { label: "add", cls: "ch-add" }
6513
+ };
6514
+ function renderChangeList(review) {
6515
+ const changes = [...review.changes].sort((a, b) => b.tokens - a.tokens);
6516
+ if (changes.length === 0) {
6517
+ return `<p class="note">Nothing to change in ${esc(review.label)}.</p>`;
6518
+ }
6519
+ const counts = { remove: 0, move: 0, add: 0 };
6520
+ let tokens = 0;
6521
+ for (const c of changes) {
6522
+ counts[c.kind] += 1;
6523
+ if (c.kind !== "add") tokens += c.tokens;
6524
+ }
6525
+ const parts = [];
6526
+ if (counts.remove > 0) parts.push(`${num5(counts.remove)} to remove`);
6527
+ if (counts.move > 0) parts.push(`${num5(counts.move)} to move out`);
6528
+ if (counts.add > 0) parts.push(`${num5(counts.add)} to add`);
6529
+ const saving = tokens > 0 ? ` Removing and moving those takes about ${num5(tokens)} tokens off every turn.` : "";
6530
+ const items = changes.map((c) => {
6531
+ const kind = CHANGE_KIND[c.kind];
6532
+ const dest = c.destination ? ` <span class="note">to ${esc(c.destination)}</span>` : "";
6533
+ const size = c.tokens > 0 ? `<span class="pill">~${num5(c.tokens)} tokens</span>` : "";
6534
+ return `<li><div class="ch-head"><span class="tag ${kind.cls}">${kind.label}</span> <b>${esc(c.instruction)}</b>${dest} ${size}</div><p class="note">${esc(c.heading)}: ${esc(c.reason)}</p></li>`;
6535
+ }).join("");
6536
+ return `<p class="note" style="margin-top:0"><b>${parts.join(", ")}.</b>${saving}</p><ol class="changes">${items}</ol>`;
6537
+ }
5521
6538
  function renderAnnotatedFile(review) {
5522
6539
  const legend = `<p class="legend"><b>Legend</b><span class="sw r"></span>remove<span class="sw m"></span>move out<span class="sw a"></span>add</p>`;
5523
6540
  if (review.missing) {
@@ -5527,7 +6544,8 @@ function renderAnnotatedFile(review) {
5527
6544
  }
5528
6545
  return legend + `<p class="note">${esc(review.label)} does not exist yet. Proposed content:</p>` + renderLines(adds, 0);
5529
6546
  }
5530
- return legend + renderLines(review.lines, review.lines.length > TRUNCATE_OVER_LINES ? KEEP_RUN_MAX : 0);
6547
+ const annotated = legend + renderLines(review.lines, review.lines.length > TRUNCATE_OVER_LINES ? KEEP_RUN_MAX : 0);
6548
+ return renderChangeList(review) + `<details class="filedrop"><summary>Show ${esc(review.label)} line by line (${num5(review.lines.length)} ${plural2(review.lines.length, "line")})</summary>${annotated}</details>`;
5531
6549
  }
5532
6550
  function reviewCountLine(review) {
5533
6551
  const n = review.changes.length;
@@ -5557,15 +6575,36 @@ function indexStatus(appliedAt) {
5557
6575
  if (!appliedAt) return `<span class="state off">not applied</span>`;
5558
6576
  return `<span class="state on">applied ${esc(appliedAt.slice(0, 10))}</span>`;
5559
6577
  }
5560
- function actionForm(token, slug, action, label, primary) {
5561
- return `<form method="post" action="/apply"><input type="hidden" name="token" value="${esc(token)}"><input type="hidden" name="slug" value="${esc(slug)}"><input type="hidden" name="action" value="${esc(action)}"><button type="submit"${primary ? ' class="go"' : ""}>${esc(label)}</button></form>`;
6578
+ function actionForm(token, slug, action, label, primary, hint = "") {
6579
+ return `<form method="post" action="/apply"><input type="hidden" name="token" value="${esc(token)}"><input type="hidden" name="slug" value="${esc(slug)}"><input type="hidden" name="action" value="${esc(action)}"><button type="submit"${primary ? ' class="go"' : ""}${hint ? ` title="${esc(hint)}"` : ""}>${esc(label)}</button></form>`;
5562
6580
  }
5563
6581
  function indexActions(row, serve) {
5564
6582
  const details = `<a href="${esc(row.artifactsHref)}">details</a>`;
5565
6583
  if (!serve) {
5566
6584
  return `<code class="cmd">${esc(row.applyCommand)}</code><p class="note" style="margin-top:6px">${details}</p>`;
5567
6585
  }
5568
- return `<div class="acts">` + actionForm(serve.token, row.slug, "include", "Apply", true) + actionForm(serve.token, row.slug, "remove", "Remove", false) + actionForm(serve.token, row.slug, "settings", "Apply settings", false) + `</div><p class="note" style="margin-top:6px">${details}</p>`;
6586
+ return `<div class="acts">` + actionForm(
6587
+ serve.token,
6588
+ row.slug,
6589
+ "include",
6590
+ "Apply CLAUDE.md",
6591
+ true,
6592
+ "Writes .claude/costclaw.md and adds one import line to this project's CLAUDE.md. Every line you wrote stays."
6593
+ ) + actionForm(
6594
+ serve.token,
6595
+ row.slug,
6596
+ "settings",
6597
+ "Apply permissions",
6598
+ false,
6599
+ "Merges the suggested permission allowlist into this project's settings file. Nothing is removed."
6600
+ ) + actionForm(
6601
+ serve.token,
6602
+ row.slug,
6603
+ "remove",
6604
+ "Undo",
6605
+ false,
6606
+ "Removes the costclaw include and the import line this page added."
6607
+ ) + `</div><p class="note" style="margin-top:6px"><strong>Apply CLAUDE.md</strong> writes <span class="mono">.claude/costclaw.md</span> and one import line. <strong>Apply permissions</strong> merges the allowlist into your settings file. They are independent, both are additive, and <strong>Undo</strong> reverses the first. ${details}</p>`;
5569
6608
  }
5570
6609
  function renderPromptPanel(review) {
5571
6610
  return `<div class="panel"><button class="copy" type="button" onclick="ccCopy(this)">Copy the prompt</button><textarea readonly rows="14" class="prompt">${esc(review.upgradeAll)}</textarea><p class="note">Paste it into Claude Code in any folder, or run the line below. It covers your global CLAUDE.md and every project on this page, so there is one prompt, not one per project.</p><code class="cmd">claude "Follow ${esc(review.upgradeAllPath)}"</code><p class="note">costclaw never calls a model: this work order is deterministic text built from your own audit. Your agent does the editing, with your approval.</p></div>`;
@@ -5594,7 +6633,7 @@ function renderOptimizeIndex(input) {
5594
6633
  const rows = input.rows.map(
5595
6634
  (r) => `<tr><td><b>${esc(r.slug)}</b><span class="rowpath">${esc(r.projectDir)}</span></td><td class="num">${esc(usd5(r.spendUsd))}</td><td class="num">${esc(usd5(r.recoverableUsd))}</td><td>${indexTokens(r.tokens)}</td><td>${indexStatus(r.appliedAt)}</td><td>${indexActions(r, input.serve)}</td></tr>`
5596
6635
  ).join("");
5597
- const body = input.rows.length === 0 ? `<p class="note">No project directories from your audit were found on this machine, so nothing was generated.</p>` : `<div class="scroll"><table><thead><tr><th>Project</th><th class="num">Spend</th><th class="num">Recoverable</th><th>CLAUDE.md tokens</th><th>Status</th><th>Actions</th></tr></thead><tbody>${rows}</tbody></table></div>`;
6636
+ const body = input.rows.length === 0 ? `<p class="note">No project directories from your audit were found on this machine, so nothing was generated.</p>` : `<div class="scroll"><table><thead><tr><th>Project</th><th class="num">Valuation estimate</th><th class="num">Cache-miss exposure estimate</th><th>CLAUDE.md tokens</th><th>Status</th><th>Actions</th></tr></thead><tbody>${rows}</tbody></table></div>`;
5598
6637
  const banner = input.serve?.message ? `<p class="banner">${esc(input.serve.message)}</p>` : "";
5599
6638
  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>` : "";
5600
6639
  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>`;
@@ -5611,7 +6650,7 @@ ${input.review ? `<script>${COPY_SCRIPT}</script>` : ""}
5611
6650
  <div class="wrap">
5612
6651
  <header><p class="kicker">CostClaw optimize &middot; generated locally &middot; nothing left your machine</p>
5613
6652
  <h1>${input.rows.length} ${plural2(input.rows.length, "project")} ready to apply</h1>
5614
- <p class="sub">${esc(usd5(total))} of analyzed spend &middot; ${esc(usd5(recoverable))} recoverable &middot;
6653
+ <p class="sub">${esc(usd5(total))} estimated current API-equivalent valuation &middot; ${esc(usd5(recoverable))} cache-miss exposure estimate &middot;
5615
6654
  artifacts in ${esc(input.root)}/</p></header>
5616
6655
 
5617
6656
  ${banner}${done}
@@ -5637,7 +6676,7 @@ Nothing was written inside any project. No network calls, no telemetry, no model
5637
6676
 
5638
6677
  // src/project-scan.ts
5639
6678
  import { readdir as readdir3, readFile as readFile7, stat as stat2 } from "fs/promises";
5640
- import { join as join8, basename } from "path";
6679
+ import { join as join8, basename as basename2 } from "path";
5641
6680
  var NOISE_DIRS = /* @__PURE__ */ new Set([
5642
6681
  "node_modules",
5643
6682
  ".git",
@@ -6111,7 +7150,7 @@ function parseReadme(text2) {
6111
7150
  return { name, description };
6112
7151
  }
6113
7152
  async function scanProject(dir) {
6114
- const profile = emptyProfile(basename(dir));
7153
+ const profile = emptyProfile(basename2(dir));
6115
7154
  const { files, dirs } = await listEntries(dir);
6116
7155
  if (files.includes("package.json")) {
6117
7156
  const pkg = parseJson(await readText(join8(dir, "package.json")));
@@ -6134,13 +7173,13 @@ async function scanProject(dir) {
6134
7173
  }
6135
7174
  }
6136
7175
  }
6137
- if (profile.description === null || profile.name === basename(dir)) {
7176
+ if (profile.description === null || profile.name === basename2(dir)) {
6138
7177
  const readmeName = files.find((f) => /^readme(\.md|\.markdown|\.txt)?$/i.test(f));
6139
7178
  if (readmeName) {
6140
7179
  const text2 = await readText(join8(dir, readmeName));
6141
7180
  if (text2 !== null) {
6142
7181
  const parsed = parseReadme(text2);
6143
- if (profile.name === basename(dir) && parsed.name !== null) profile.name = parsed.name;
7182
+ if (profile.name === basename2(dir) && parsed.name !== null) profile.name = parsed.name;
6144
7183
  if (profile.description === null && parsed.description !== null) {
6145
7184
  profile.description = parsed.description;
6146
7185
  }
@@ -6160,7 +7199,7 @@ async function scanProject(dir) {
6160
7199
  import { createServer } from "http";
6161
7200
  import { randomBytes } from "crypto";
6162
7201
  import { readFile as readFile8 } from "fs/promises";
6163
- import { extname, resolve as resolve3, sep as sep2 } from "path";
7202
+ import { extname, resolve as resolve4, sep as sep2 } from "path";
6164
7203
  var DEFAULT_IDLE_MS = 30 * 60 * 1e3;
6165
7204
  var MAX_BODY_BYTES = 64 * 1024;
6166
7205
  var DASHBOARD_NAME = "DASHBOARD.html";
@@ -6185,8 +7224,8 @@ function safeArtifactPath(root, urlPath) {
6185
7224
  return null;
6186
7225
  }
6187
7226
  if (decoded.includes("\0")) return null;
6188
- const resolvedRoot = resolve3(root);
6189
- const full = resolve3(resolvedRoot, "." + decoded);
7227
+ const resolvedRoot = resolve4(root);
7228
+ const full = resolve4(resolvedRoot, "." + decoded);
6190
7229
  if (full !== resolvedRoot && !full.startsWith(resolvedRoot + sep2)) return null;
6191
7230
  return full;
6192
7231
  }
@@ -6383,7 +7422,7 @@ async function startApplyServer(opts) {
6383
7422
 
6384
7423
  // src/optimize-manifest.ts
6385
7424
  import { mkdir as mkdir5, readFile as readFile9, writeFile as writeFile5 } from "fs/promises";
6386
- import { join as join9, resolve as resolve4 } from "path";
7425
+ import { join as join9, resolve as resolve5 } from "path";
6387
7426
  var MANIFEST_NAME = "index.json";
6388
7427
  function defaultOptimizeRoot(home) {
6389
7428
  return join9(home, ".costclaw", "optimize");
@@ -6417,7 +7456,7 @@ async function writeManifest(root, m) {
6417
7456
  await writeFile5(join9(root, MANIFEST_NAME), JSON.stringify(m, null, 2) + "\n", "utf8");
6418
7457
  }
6419
7458
  function normalizePath(p) {
6420
- const r = resolve4(p);
7459
+ const r = resolve5(p);
6421
7460
  return process.platform === "win32" ? r.toLowerCase() : r;
6422
7461
  }
6423
7462
  function findEntry(m, projectDir) {
@@ -6491,14 +7530,14 @@ function projectRecoverable(report, slug) {
6491
7530
  return row ? row.usd : null;
6492
7531
  }
6493
7532
  async function generateForProject(ctx, projectDir, artifactsDir) {
6494
- const slug = basename2(resolve5(projectDir));
7533
+ const slug = basename3(resolve6(projectDir));
6495
7534
  let currentClaudeMd = ctx.claudeMdOverride;
6496
7535
  let claudeMdSource = ctx.claudeMdOverride !== void 0 ? ctx.claudeMdFallbackSource : null;
6497
7536
  if (currentClaudeMd === void 0) {
6498
- const own = join10(projectDir, "CLAUDE.md");
6499
- if (await pathExists2(own)) {
6500
- currentClaudeMd = await readFile10(own, "utf8");
6501
- claudeMdSource = own;
7537
+ const own2 = join10(projectDir, "CLAUDE.md");
7538
+ if (await pathExists2(own2)) {
7539
+ currentClaudeMd = await readFile10(own2, "utf8");
7540
+ claudeMdSource = own2;
6502
7541
  }
6503
7542
  }
6504
7543
  const project = await scanProject(projectDir);
@@ -6560,11 +7599,11 @@ async function generateForProject(ctx, projectDir, artifactsDir) {
6560
7599
  const denominator = recoverable !== null ? spend ?? 0 : ctx.report.summary.cost_usd;
6561
7600
  const scopeLabel = recoverable !== null ? `for ${slug}` : "across your audited projects";
6562
7601
  if (ctx.plan === "api") {
6563
- lines.push(`Recoverable spend (cache-miss exposure) ${scopeLabel}: ${usd6(shownRecoverable)}`);
7602
+ lines.push(`Cache-miss exposure (estimate) ${scopeLabel}: ${usd6(shownRecoverable)} estimated current API-equivalent valuation`);
6564
7603
  } else {
6565
7604
  const share = denominator > 0 ? shownRecoverable / denominator * 100 : 0;
6566
7605
  lines.push(
6567
- `Recoverable usage (cache-miss exposure) ${scopeLabel}: ${share.toFixed(1)}% of analyzed usage (${usd6(shownRecoverable)} at API rates)`
7606
+ `Cache-miss exposure (estimate) ${scopeLabel}: ${share.toFixed(1)}% of analyzed token value (${usd6(shownRecoverable)} estimated current API-equivalent valuation; not money back, actual quota, or a promise of more work)`
6568
7607
  );
6569
7608
  }
6570
7609
  const { before, after } = result.claudeMdTokens;
@@ -6599,7 +7638,7 @@ async function generateForProject(ctx, projectDir, artifactsDir) {
6599
7638
  return {
6600
7639
  entry: {
6601
7640
  slug,
6602
- dir: basename2(artifactsDir),
7641
+ dir: basename3(artifactsDir),
6603
7642
  projectDir,
6604
7643
  artifactsDir,
6605
7644
  spendUsd: spend ?? 0,
@@ -6619,8 +7658,8 @@ async function runOptimize(opts) {
6619
7658
  const home = opts.home ?? homedir5();
6620
7659
  let inputsClaudeMdPath = opts.claudeMdPath;
6621
7660
  if (!inputsClaudeMdPath && opts.projectDir) {
6622
- const own = join10(opts.projectDir, "CLAUDE.md");
6623
- if (await pathExists2(own)) inputsClaudeMdPath = own;
7661
+ const own2 = join10(opts.projectDir, "CLAUDE.md");
7662
+ if (await pathExists2(own2)) inputsClaudeMdPath = own2;
6624
7663
  }
6625
7664
  const { logs, claudeMd, claudeMdSource, projectDirs } = await loadAuditInputs({
6626
7665
  path: opts.path,
@@ -6641,7 +7680,13 @@ async function runOptimize(opts) {
6641
7680
  totals: { ...report.summary.totals },
6642
7681
  cacheHitRate: report.summary.cacheHitRate,
6643
7682
  headlineWasteShare: baselineSpend > 0 ? auditRecoverable / baselineSpend : 0,
6644
- spendUsd: baselineSpend
7683
+ spendUsd: baselineSpend,
7684
+ ...report.summary.accuracy ? {
7685
+ accuracy: {
7686
+ pricingSnapshotDate: report.summary.accuracy.pricingSnapshotDate,
7687
+ accountingVersion: report.summary.accuracy.accountingVersion
7688
+ }
7689
+ } : {}
6645
7690
  }
6646
7691
  });
6647
7692
  const single = opts.projectDir !== void 0;
@@ -6837,7 +7882,7 @@ async function runOptimize(opts) {
6837
7882
 
6838
7883
  // src/badge-command.ts
6839
7884
  import { writeFile as writeFile7 } from "fs/promises";
6840
- import { resolve as resolve6 } from "path";
7885
+ import { resolve as resolve7 } from "path";
6841
7886
 
6842
7887
  // src/badge.ts
6843
7888
  var HEIGHT2 = 20;
@@ -6861,7 +7906,7 @@ var DEFAULT_BADGE_FILE = "costclaw-badge.svg";
6861
7906
  async function runBadge(opts) {
6862
7907
  const { record } = await runAudit({ path: opts.path, claudeMdPath: opts.claudeMdPath, home: opts.home });
6863
7908
  const svg = renderBadge(record);
6864
- const target = resolve6(opts.out || DEFAULT_BADGE_FILE);
7909
+ const target = resolve7(opts.out || DEFAULT_BADGE_FILE);
6865
7910
  await writeFile7(target, svg, "utf8");
6866
7911
  return { output: `Badge written to ${target}`, record, target };
6867
7912
  }
@@ -6873,7 +7918,7 @@ import { homedir as homedir6 } from "os";
6873
7918
 
6874
7919
  // src/format-diff.ts
6875
7920
  function usd7(n) {
6876
- return `$${(Math.round(Math.abs(n) * 100) / 100).toFixed(2)}`;
7921
+ return `$${roundMoneyHalfUp(Math.abs(n)).toFixed(2)}`;
6877
7922
  }
6878
7923
  function signedUsd(n) {
6879
7924
  return `${n < 0 ? "-" : "+"}${usd7(n)}`;
@@ -6897,28 +7942,36 @@ function formatDiff(d) {
6897
7942
  if (d.comparable && d.marginal) {
6898
7943
  lines.push("Since the baseline:");
6899
7944
  lines.push(
6900
- ` New spend ${usd7(d.marginal.newSpendUsd)} across ${d.marginal.newSessions} new sessions`
7945
+ ` New valuation (estimate) ${usd7(d.marginal.newSpendUsd)} across ${d.marginal.newSessions} new sessions`
6901
7946
  );
6902
7947
  lines.push(
6903
7948
  ` Marginal cache hit ${pct(d.marginal.marginalCacheHitRate)} (lifetime ${pct(d.current.cacheHitRate)})`
6904
7949
  );
6905
7950
  lines.push(
6906
- ` Recoverable exposure ${signedUsd(d.deltas.recoverableUsd)} (now ${usd7(d.current.recoverableUsd)})`
7951
+ ` Cache-miss exposure (estimate) ${signedUsd(d.deltas.recoverableUsd)} (now ${usd7(d.current.recoverableUsd)})`
6907
7952
  );
6908
7953
  } else {
6909
- lines.push("Note: the current audit covers less history than the baseline (logs moved or");
6910
- lines.push("pruned), so period metrics are omitted.");
7954
+ if (d.comparisonReason === "accounting changed") {
7955
+ lines.push("Note: the accounting method changed between audits, so period metrics are omitted.");
7956
+ lines.push("The difference may include accounting corrections and is not new usage.");
7957
+ } else if (d.comparisonReason === "pricing changed") {
7958
+ lines.push("Note: the pricing snapshot changed between audits, so period metrics are omitted.");
7959
+ lines.push("The difference may include repricing and is not new usage.");
7960
+ } else {
7961
+ lines.push("Note: the current audit covers less history than the baseline (logs moved or");
7962
+ lines.push("pruned), so period metrics are omitted.");
7963
+ }
6911
7964
  lines.push("");
6912
7965
  lines.push(
6913
- `Baseline (${day(d.baseline.createdAt)}): spend ${usd7(d.baseline.spendUsd)}, cache hit ${pct(d.baseline.cacheHitRate)}, recoverable ${usd7(d.baseline.recoverableUsd)}`
7966
+ `Baseline (${day(d.baseline.createdAt)}): valuation estimate ${usd7(d.baseline.spendUsd)}, cache hit ${pct(d.baseline.cacheHitRate)}, cache-miss exposure estimate ${usd7(d.baseline.recoverableUsd)}`
6914
7967
  );
6915
7968
  lines.push(
6916
- `Current (${day(d.current.createdAt)}): spend ${usd7(d.current.spendUsd)}, cache hit ${pct(d.current.cacheHitRate)}, recoverable ${usd7(d.current.recoverableUsd)}`
7969
+ `Current (${day(d.current.createdAt)}): valuation estimate ${usd7(d.current.spendUsd)}, cache hit ${pct(d.current.cacheHitRate)}, cache-miss exposure estimate ${usd7(d.current.recoverableUsd)}`
6917
7970
  );
6918
7971
  }
6919
7972
  lines.push("");
6920
7973
  lines.push(
6921
- `Overall setup score: ${d.baseline.overallScore} -> ${d.current.overallScore} (${signedInt(d.deltas.overallScore)}, ${d.current.band})`
7974
+ `Rule-based setup score: ${d.baseline.overallScore} -> ${d.current.overallScore} (${signedInt(d.deltas.overallScore)}, ${d.current.band}; not an Anthropic grade)`
6922
7975
  );
6923
7976
  for (const p of d.pillars) {
6924
7977
  const before = p.before === null ? "n/a" : String(p.before);
@@ -6929,27 +7982,29 @@ function formatDiff(d) {
6929
7982
  if (d.current.plan && d.current.plan !== "api") {
6930
7983
  lines.push("");
6931
7984
  lines.push(
6932
- `Plan: ${d.current.plan}. Dollar figures are API-equivalent token value on your subscription; recovering them buys rate-limit headroom, not money back.`
7985
+ `Plan: ${d.current.plan}. Dollar figures are estimated current API-equivalent valuations, not money back, actual quota, or a promise of more work.`
6933
7986
  );
6934
7987
  }
6935
7988
  const { resolved, appeared, changed } = d.fixes;
6936
7989
  if (resolved.length > 0) {
6937
7990
  lines.push("");
6938
7991
  lines.push("Fixes resolved since the baseline:");
6939
- for (const f of resolved) lines.push(` - [${usd7(f.wasteUsd)}] ${f.title}`);
7992
+ for (const f of resolved) lines.push(` - [${usd7(f.wasteUsd)} estimated valuation] ${f.title}`);
6940
7993
  }
6941
7994
  if (appeared.length > 0) {
6942
7995
  lines.push("");
6943
7996
  lines.push("New since the baseline:");
6944
- for (const f of appeared) lines.push(` - [${usd7(f.wasteUsd)}] ${f.title}`);
7997
+ for (const f of appeared) lines.push(` - [${usd7(f.wasteUsd)} estimated valuation] ${f.title}`);
6945
7998
  }
6946
7999
  if (changed.length > 0) {
6947
8000
  lines.push("");
6948
8001
  lines.push("Fixes that moved:");
6949
8002
  for (const c of changed) {
6950
- lines.push(` - ${c.title}: ${usd7(c.beforeUsd)} -> ${usd7(c.afterUsd)} (${signedUsd(c.deltaUsd)})`);
8003
+ lines.push(` - ${c.title}: ${usd7(c.beforeUsd)} -> ${usd7(c.afterUsd)} (${signedUsd(c.deltaUsd)} estimated valuation)`);
6951
8004
  }
6952
8005
  }
8006
+ lines.push("");
8007
+ lines.push("Methodology: values use each audit's then-current list-price snapshot and logged token fields. They are not historical billing; a changed rate card can affect baseline comparisons.");
6953
8008
  return lines.join("\n");
6954
8009
  }
6955
8010
 
@@ -7055,7 +8110,7 @@ function parseApplyFlags(args) {
7055
8110
  };
7056
8111
  }
7057
8112
  function cliVersion() {
7058
- return true ? "0.12.3" : "0.0.0-dev";
8113
+ return true ? "0.13.0" : "0.0.0-dev";
7059
8114
  }
7060
8115
  function isHelpRequest(command, args) {
7061
8116
  if (command === void 0) return false;
@@ -7083,17 +8138,17 @@ function helpText() {
7083
8138
  "and opens it in your browser; --no-html skips that, --html <file> picks the",
7084
8139
  "path, and --json runs stay file-free unless --html is passed explicitly.",
7085
8140
  "--card writes a shareable 600x315 score card SVG (default: costclaw-card.svg):",
7086
- "score, band, recoverable spend, cache hit rate, and your strongest pillar.",
8141
+ "rule-based setup score, band, cache-miss exposure estimate, cache hit rate, and your strongest pillar.",
7087
8142
  "--plan <api|pro|max5x|max20x> declares how you pay for Claude. On a",
7088
- "subscription (Pro/Max) the dollar figures are API-equivalent token value, not",
7089
- "money back, so the audit reframes the headline as recoverable usage: the share",
7090
- "of your token consumption (and rate-limit headroom) you could win back. The",
7091
- "value is saved to ~/.costclaw/config.json so later runs remember it;",
8143
+ "subscription (Pro/Max) every dollar figure is an estimated current API-equivalent",
8144
+ "valuation, not money back, actual quota, or a promise of more work. Cache-miss",
8145
+ "exposure is a counterfactual: cold and unique inputs cannot all be cached. The",
8146
+ "plan is saved to ~/.costclaw/config.json so later runs remember it;",
7092
8147
  "--plan api switches back. Pass nothing and the first interactive run asks",
7093
8148
  "once and saves the answer; piped, --json and CI runs are never asked and",
7094
8149
  "assume API rates.",
7095
8150
  "",
7096
- "diff compares two audits and shows the movement: new spend since the baseline,",
8151
+ "diff compares two audits and shows the movement: new valuation estimates since the baseline,",
7097
8152
  "the marginal cache hit rate for just that period, score changes per pillar, and",
7098
8153
  "which fixes were resolved. Every audit run saves a snapshot to",
7099
8154
  "~/.costclaw/history, so plain `costclaw diff` compares your latest two runs;",