costclaw 0.12.2 → 0.12.4

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 +327 -326
  2. package/dist/index.js +770 -270
  3. package/package.json +47 -47
package/dist/index.js CHANGED
@@ -15,68 +15,215 @@ function isPlan(value) {
15
15
  }
16
16
 
17
17
  // ../../packages/engine/src/pricing.ts
18
- var PRICING_SNAPSHOT_DATE = "2026-08-03";
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": { input: 10, output: 50, cache_write: 12.5, cache_read: 1 },
21
- "claude-opus-5": { input: 5, output: 25, cache_write: 6.25, cache_read: 0.5 },
22
- "claude-opus-4-8": { input: 5, output: 25, cache_write: 6.25, cache_read: 0.5 },
23
- "claude-sonnet-5": { input: 3, output: 15, cache_write: 3.75, cache_read: 0.3 },
24
- "claude-opus-4-7": { input: 15, output: 75, cache_write: 18.75, cache_read: 1.5 },
25
- "claude-opus-4-7[1m]": { input: 15, output: 75, cache_write: 18.75, cache_read: 1.5 },
26
- "claude-opus-4-6": { input: 15, output: 75, cache_write: 18.75, cache_read: 1.5 },
27
- "claude-sonnet-4-6": { input: 3, output: 15, cache_write: 3.75, cache_read: 0.3 },
28
- "claude-sonnet-4-5": { input: 3, output: 15, cache_write: 3.75, cache_read: 0.3 },
29
- "claude-haiku-4-5": { input: 1, output: 5, cache_write: 1.25, cache_read: 0.1 },
30
- "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 }
31
44
  });
32
- 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
+ }
33
55
  function priceFor(model) {
34
56
  return lookup(model) ?? FALLBACK;
35
57
  }
36
58
  function isKnownModel(model) {
37
59
  return lookup(model) !== null;
38
60
  }
39
- function lookup(model) {
40
- if (!model) return null;
41
- const exact = PRICES_PER_MTOK[model];
42
- if (exact) return exact;
43
- const noTag = model.replace(/\[[^\]]*\]$/, "");
44
- if (PRICES_PER_MTOK[noTag]) return PRICES_PER_MTOK[noTag];
45
- const noDate = noTag.replace(/-\d{8}$/, "");
46
- if (PRICES_PER_MTOK[noDate]) return PRICES_PER_MTOK[noDate];
47
- 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;
48
178
  }
49
- var num = (v) => Number(v) || 0;
50
179
  function costForUsage(model, usage) {
180
+ return costForNormalizedUsage(model, normalizeUsage(usage).usage);
181
+ }
182
+ function cacheSavingsForNormalizedUsage(model, usage) {
51
183
  const p = priceFor(model);
52
- const i = num(usage?.input_tokens);
53
- const o = num(usage?.output_tokens);
54
- const cw = num(usage?.cache_creation_input_tokens);
55
- const cr = num(usage?.cache_read_input_tokens);
56
- return (i * p.input + o * p.output + cw * p.cache_write + cr * p.cache_read) / 1e6;
184
+ return usage.cache_read_input_tokens * (p.input - p.cache_read) * pricingMultiplier(model, usage) / 1e6;
57
185
  }
58
- function cacheSavingsForUsage(model, usage) {
186
+ function cacheMissExposureForNormalizedUsage(model, usage) {
59
187
  const p = priceFor(model);
60
- const cr = num(usage?.cache_read_input_tokens);
61
- return cr * (p.input - 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;
62
189
  }
63
190
  function cacheHitRate(totals) {
64
- const denom = num(totals.input_tokens) + num(totals.cache_creation_tokens) + num(totals.cache_read_tokens);
65
- if (!denom) return 0;
66
- return num(totals.cache_read_tokens) / denom;
191
+ const denom = totals.input_tokens + totals.cache_creation_tokens + totals.cache_read_tokens;
192
+ if (!Number.isFinite(denom) || denom <= 0) return 0;
193
+ return totals.cache_read_tokens / denom;
194
+ }
195
+ function usageForTotals(totals) {
196
+ const splitDefined = totals.cache_creation_5m_tokens != null || totals.cache_creation_1h_tokens != null;
197
+ return {
198
+ input_tokens: totals.input_tokens,
199
+ output_tokens: totals.output_tokens,
200
+ cache_creation_input_tokens: totals.cache_creation_tokens,
201
+ cache_read_input_tokens: totals.cache_read_tokens,
202
+ ...splitDefined ? { cache_creation: {
203
+ ephemeral_5m_input_tokens: totals.cache_creation_5m_tokens ?? 0,
204
+ ephemeral_1h_input_tokens: totals.cache_creation_1h_tokens ?? 0
205
+ } } : {}
206
+ };
67
207
  }
68
208
  function costForTotals(model, totals) {
69
- const p = priceFor(model);
70
- 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;
209
+ return costForUsage(model, usageForTotals(totals));
210
+ }
211
+ function cacheMissExposureForTotals(model, totals) {
212
+ return cacheMissExposureForNormalizedUsage(model, normalizeUsage(usageForTotals(totals)).usage);
213
+ }
214
+ function roundMoneyHalfUp(value, places = 2) {
215
+ if (!Number.isFinite(value) || !Number.isInteger(places) || places < 0 || places > 12) return value;
216
+ const factor = 10 ** places;
217
+ const scaled = Math.abs(value) * factor;
218
+ const tolerance = Number.EPSILON * Math.max(1, scaled) * 2;
219
+ return Math.sign(value) * Math.floor(scaled + 0.5 + tolerance) / factor;
71
220
  }
72
221
  function isOpus(model) {
73
- if (!model) return false;
74
- return model.replace(/\[[^\]]*\]$/, "").startsWith("claude-opus");
222
+ return canonicalModel(model)?.startsWith("claude-opus") ?? false;
75
223
  }
76
224
  function isPremiumModel(model) {
77
- if (!model) return false;
78
- const base = model.replace(/\[[^\]]*\]$/, "");
79
- return base.startsWith("claude-opus") || base.startsWith("claude-fable");
225
+ const base = canonicalModel(model);
226
+ return base?.startsWith("claude-opus") === true || base?.startsWith("claude-fable") === true || base?.startsWith("claude-mythos") === true;
80
227
  }
81
228
 
82
229
  // ../../packages/engine/src/sanitize.ts
@@ -190,19 +337,109 @@ function emptyPromptSignals() {
190
337
  }
191
338
  var isToolUse = (b) => !!b && typeof b === "object" && b.type === "tool_use" && typeof b.name === "string";
192
339
  function extractTools(content) {
193
- const names = [];
194
340
  const events = [];
195
341
  if (Array.isArray(content)) {
196
342
  for (const block of content) {
197
343
  if (isToolUse(block)) {
198
344
  const name = block.name;
199
345
  const input = block.input ?? {};
200
- names.push(name);
201
- events.push({ name, target: targetFor(name, input) });
346
+ events.push({ id: typeof block.id === "string" ? block.id : null, name, target: targetFor(name, input), input });
202
347
  }
203
348
  }
204
349
  }
205
- return { names, events };
350
+ return { events };
351
+ }
352
+ function logicalUsageKey(rec) {
353
+ const requestId = rec.requestId || rec.message?.requestId;
354
+ if (requestId) return `req:${requestId}`;
355
+ const messageId = rec.message?.id;
356
+ return messageId ? `msg:${messageId}` : null;
357
+ }
358
+ var CUMULATIVE_CONFLICT_WARNING = "Conflicting cumulative usage snapshots were not added; the highest coherent snapshot was used.";
359
+ var MODEL_CHANGE_WARNING = "A request changed models across snapshots; one coherent snapshot was valued.";
360
+ function usageVector(u) {
361
+ return [u.input_tokens, u.output_tokens, u.cache_creation_input_tokens, u.cache_read_input_tokens, u.web_search_requests];
362
+ }
363
+ function samePricingMode(a, b) {
364
+ return a.speed === b.speed && a.inference_geo === b.inference_geo && a.batch === b.batch;
365
+ }
366
+ function growsFrom(next, previous) {
367
+ if (next.invalid && !previous.invalid) return false;
368
+ if (next.model !== previous.model || !samePricingMode(next.normalized, previous.normalized)) return false;
369
+ if (previous.normalized.cache_ttl_known && !next.normalized.cache_ttl_known) return false;
370
+ 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;
371
+ const a = usageVector(next.normalized);
372
+ const b = usageVector(previous.normalized);
373
+ return a.every((value, index) => value >= b[index]);
374
+ }
375
+ function sameCandidate(a, b) {
376
+ 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;
377
+ }
378
+ function preferredCandidate(a, b) {
379
+ if (a.invalid !== b.invalid) return a.invalid ? b : a;
380
+ if (sameCandidate(a, b) || growsFrom(b, a)) return b;
381
+ if (growsFrom(a, b)) return a;
382
+ const aCost = costForNormalizedUsage(a.model, a.normalized);
383
+ const bCost = costForNormalizedUsage(b.model, b.normalized);
384
+ return bCost >= aCost ? b : a;
385
+ }
386
+ function rebuildSessionUsage(session, fragments, extraWarnings = []) {
387
+ session.usageFragments = fragments;
388
+ session.fragmentsWithUsage = fragments.length;
389
+ session.modelRequests = fragments.length;
390
+ session.totals = emptyTotals();
391
+ session.cost_usd = 0;
392
+ session.cache_savings_usd = 0;
393
+ session.cacheMissExposureUsd = 0;
394
+ session.modelCostsUsd = {};
395
+ session.unknownModelRequests = {};
396
+ session.pricedRequests = 0;
397
+ session.turnCache = [];
398
+ session.turnCacheExposureUsd = [];
399
+ const buckets = /* @__PURE__ */ new Map();
400
+ const modelCounts = /* @__PURE__ */ new Map();
401
+ let splitKnown = false;
402
+ let cache5mTokens = 0;
403
+ let cache1hTokens = 0;
404
+ for (const fragment of fragments) {
405
+ session.totals.input_tokens += fragment.input_tokens;
406
+ session.totals.output_tokens += fragment.output_tokens;
407
+ session.totals.cache_creation_tokens += fragment.cache_creation_tokens;
408
+ session.totals.cache_read_tokens += fragment.cache_read_tokens;
409
+ splitKnown ||= fragment.cacheTtlKnown;
410
+ cache5mTokens += fragment.cache_creation_5m_tokens;
411
+ cache1hTokens += fragment.cache_creation_1h_tokens;
412
+ session.cost_usd += fragment.costUsd;
413
+ session.cache_savings_usd += fragment.cacheSavingsUsd;
414
+ session.cacheMissExposureUsd += fragment.cacheMissExposureUsd;
415
+ const modelKey = fragment.model ?? "unknown";
416
+ session.modelCostsUsd[modelKey] = (session.modelCostsUsd[modelKey] ?? 0) + fragment.costUsd;
417
+ if (fragment.model && isKnownModel(fragment.model)) session.pricedRequests += 1;
418
+ else session.unknownModelRequests[modelKey] = (session.unknownModelRequests[modelKey] ?? 0) + 1;
419
+ if (fragment.model && fragment.model !== "<synthetic>") modelCounts.set(fragment.model, (modelCounts.get(fragment.model) ?? 0) + 1);
420
+ session.turnCache.push({ read: fragment.cache_read_tokens, miss: fragment.input_tokens + fragment.cache_creation_tokens });
421
+ session.turnCacheExposureUsd.push(fragment.cacheMissExposureUsd);
422
+ if (fragment.timestampMs != null) {
423
+ const t = Math.floor(fragment.timestampMs / (15 * 60 * 1e3));
424
+ buckets.set(t, (buckets.get(t) ?? 0) + fragment.costUsd);
425
+ }
426
+ }
427
+ if (splitKnown) {
428
+ session.totals.cache_creation_5m_tokens = cache5mTokens;
429
+ session.totals.cache_creation_1h_tokens = cache1hTokens;
430
+ } else {
431
+ delete session.totals.cache_creation_5m_tokens;
432
+ delete session.totals.cache_creation_1h_tokens;
433
+ }
434
+ session.costBuckets = [...buckets.entries()].sort((a, b) => a[0] - b[0]).map(([t, usd8]) => ({ t, usd: usd8 }));
435
+ let best = null;
436
+ let bestCount = 0;
437
+ for (const [model, count] of modelCounts) if (count > bestCount) {
438
+ best = model;
439
+ bestCount = count;
440
+ }
441
+ session.modelPrimary = best;
442
+ session.accuracyWarnings = [.../* @__PURE__ */ new Set([...session.accuracyWarnings ?? [], ...extraWarnings])];
206
443
  }
207
444
  function parseSession(text2, opts = {}) {
208
445
  const s = {
@@ -228,13 +465,20 @@ function parseSession(text2, opts = {}) {
228
465
  parentSessionId: opts.parentSessionId ?? null,
229
466
  turnCache: [],
230
467
  costBuckets: [],
468
+ modelCostsUsd: {},
469
+ cacheMissExposureUsd: 0,
470
+ accuracyWarnings: [],
471
+ unknownModelRequests: {},
472
+ pricedRequests: 0,
473
+ invalidUsageRecords: 0,
474
+ conflictingUsageRecords: 0,
475
+ usageFragments: [],
476
+ usageLogicalKeys: [],
231
477
  prompting: emptyPromptSignals()
232
478
  };
233
479
  const ps = s.prompting;
234
- const seen = /* @__PURE__ */ new Set();
235
- const buckets = /* @__PURE__ */ new Map();
236
- const BUCKET_MS = 15 * 60 * 1e3;
237
- const modelCounts = /* @__PURE__ */ new Map();
480
+ const usageGroups = /* @__PURE__ */ new Map();
481
+ const seenTools = /* @__PURE__ */ new Set();
238
482
  let cwd = null;
239
483
  let seq = 0;
240
484
  for (const line of text2.split("\n")) {
@@ -269,75 +513,177 @@ function parseSession(text2, opts = {}) {
269
513
  }
270
514
  }
271
515
  } else s.assistantRecords += 1;
272
- const model = rec.message?.model;
273
- if (model && model !== "<synthetic>") modelCounts.set(model, (modelCounts.get(model) ?? 0) + 1);
516
+ const model = rec.message?.model ?? null;
274
517
  if (rec.type === "assistant") {
275
- const { names, events } = extractTools(rec.message?.content);
276
- for (const n of names) {
277
- s.toolUsage[n] = (s.toolUsage[n] ?? 0) + 1;
278
- if (PLAN_TOOLS.has(n)) ps.planEvents += 1;
279
- }
280
- if (Array.isArray(rec.message?.content)) {
281
- for (const b of rec.message.content) {
282
- if (isToolUse(b) && (b.name === "Bash" || b.name === "PowerShell") && typeof b.input?.command === "string" && isVerifyCommand(b.input.command)) ps.verifyRuns += 1;
283
- }
284
- }
518
+ const { events } = extractTools(rec.message?.content);
285
519
  const requestId = rec.requestId || rec.message?.requestId || null;
286
- for (const e of events) s.toolEvents.push({ name: e.name, requestId, target: e.target });
520
+ const rowIdentity = logicalUsageKey(rec) ?? (rec.uuid ? `row:${rec.uuid}` : `row:#${s.jsonlRecords}`);
521
+ for (let index = 0; index < events.length; index += 1) {
522
+ const event = events[index];
523
+ const toolKey = event.id ? `tool:${event.id}` : `${rowIdentity}:${index}:${event.name}:${JSON.stringify(event.input)}`;
524
+ if (seenTools.has(toolKey)) continue;
525
+ seenTools.add(toolKey);
526
+ s.toolUsage[event.name] = (s.toolUsage[event.name] ?? 0) + 1;
527
+ if (PLAN_TOOLS.has(event.name)) ps.planEvents += 1;
528
+ if ((event.name === "Bash" || event.name === "PowerShell") && typeof event.input.command === "string" && isVerifyCommand(event.input.command)) ps.verifyRuns += 1;
529
+ s.toolEvents.push({ name: event.name, requestId, target: event.target });
530
+ }
287
531
  const usage = rec.message?.usage;
288
532
  if (usage) {
289
533
  seq += 1;
290
534
  const key = usageKey(rec, seq);
291
- if (seen.has(key)) {
292
- s.duplicateFragmentsSkipped += 1;
293
- continue;
294
- }
295
- seen.add(key);
296
- s.fragmentsWithUsage += 1;
297
- s.modelRequests += 1;
298
- s.totals.input_tokens += Number(usage.input_tokens) || 0;
299
- s.totals.output_tokens += Number(usage.output_tokens) || 0;
300
- s.totals.cache_creation_tokens += Number(usage.cache_creation_input_tokens) || 0;
301
- s.totals.cache_read_tokens += Number(usage.cache_read_input_tokens) || 0;
302
- const fragmentUsd = costForUsage(model, usage);
303
- s.cost_usd += fragmentUsd;
304
- s.cache_savings_usd += cacheSavingsForUsage(model, usage);
305
- if (rec.timestamp) {
306
- const ms = Date.parse(rec.timestamp);
307
- if (!Number.isNaN(ms)) {
308
- const t = Math.floor(ms / BUCKET_MS);
309
- buckets.set(t, (buckets.get(t) ?? 0) + fragmentUsd);
310
- }
311
- }
312
- s.turnCache.push({
313
- read: Number(usage.cache_read_input_tokens) || 0,
314
- miss: (Number(usage.input_tokens) || 0) + (Number(usage.cache_creation_input_tokens) || 0)
535
+ const logicalKey = logicalUsageKey(rec);
536
+ if (logicalKey && !s.usageLogicalKeys.includes(logicalKey)) s.usageLogicalKeys.push(logicalKey);
537
+ const normalized = normalizeUsage(usage);
538
+ if (normalized.invalid) s.invalidUsageRecords = (s.invalidUsageRecords ?? 0) + 1;
539
+ if (normalized.conflicting) s.conflictingUsageRecords = (s.conflictingUsageRecords ?? 0) + 1;
540
+ s.accuracyWarnings.push(...normalized.warnings);
541
+ if (!normalized.billable) continue;
542
+ const timestampMs = rec.timestamp ? Date.parse(rec.timestamp) : NaN;
543
+ const candidates = usageGroups.get(key) ?? [];
544
+ candidates.push({
545
+ normalized: normalized.usage,
546
+ model,
547
+ logicalKey,
548
+ timestampMs: Number.isNaN(timestampMs) ? null : timestampMs,
549
+ invalid: normalized.invalid
315
550
  });
551
+ usageGroups.set(key, candidates);
316
552
  }
317
553
  }
318
554
  }
319
- s.costBuckets = [...buckets.entries()].sort((a, b) => a[0] - b[0]).map(([t, usd8]) => ({ t, usd: usd8 }));
320
- s.projectSlug = opts.projectSlug ?? projectFromCwd(cwd);
321
- let best = null;
322
- let bestCount = 0;
323
- for (const [m, c] of modelCounts) if (c > bestCount) {
324
- best = m;
325
- bestCount = c;
555
+ const fragments = [];
556
+ for (const candidates of usageGroups.values()) {
557
+ s.duplicateFragmentsSkipped += Math.max(0, candidates.length - 1);
558
+ let accepted = candidates[0];
559
+ let conflict = false;
560
+ let modelChanged = false;
561
+ for (let index = 1; index < candidates.length; index += 1) {
562
+ const candidate = candidates[index];
563
+ if (candidate.model !== accepted.model) modelChanged = true;
564
+ if (!sameCandidate(candidate, accepted) && !growsFrom(candidate, accepted)) conflict = true;
565
+ accepted = preferredCandidate(accepted, candidate);
566
+ }
567
+ if (modelChanged) s.accuracyWarnings.push(MODEL_CHANGE_WARNING);
568
+ if (conflict || modelChanged) {
569
+ s.conflictingUsageRecords = (s.conflictingUsageRecords ?? 0) + 1;
570
+ s.accuracyWarnings.push(CUMULATIVE_CONFLICT_WARNING);
571
+ }
572
+ const pricingWarnings = /* @__PURE__ */ new Set();
573
+ const u = accepted.normalized;
574
+ const fragmentUsd = costForNormalizedUsage(accepted.model, u, pricingWarnings);
575
+ s.accuracyWarnings.push(...pricingWarnings);
576
+ fragments.push({
577
+ logicalKey: accepted.logicalKey,
578
+ model: accepted.model,
579
+ input_tokens: u.input_tokens,
580
+ output_tokens: u.output_tokens,
581
+ cache_creation_tokens: u.cache_creation_input_tokens,
582
+ cache_read_tokens: u.cache_read_input_tokens,
583
+ cache_creation_5m_tokens: u.cache_creation_5m_input_tokens,
584
+ cache_creation_1h_tokens: u.cache_creation_1h_input_tokens,
585
+ cacheTtlKnown: u.cache_ttl_known,
586
+ accountingSignature: JSON.stringify({
587
+ model: accepted.model,
588
+ input: u.input_tokens,
589
+ output: u.output_tokens,
590
+ cache5m: u.cache_creation_5m_input_tokens,
591
+ cache1h: u.cache_creation_1h_input_tokens,
592
+ cacheRead: u.cache_read_input_tokens,
593
+ searches: u.web_search_requests,
594
+ speed: u.speed,
595
+ geo: u.inference_geo,
596
+ batch: u.batch
597
+ }),
598
+ costUsd: fragmentUsd,
599
+ cacheSavingsUsd: cacheSavingsForNormalizedUsage(accepted.model, u),
600
+ cacheMissExposureUsd: cacheMissExposureForNormalizedUsage(accepted.model, u),
601
+ timestampMs: accepted.timestampMs
602
+ });
326
603
  }
327
- s.modelPrimary = best;
604
+ rebuildSessionUsage(s, fragments);
605
+ s.projectSlug = opts.projectSlug ?? projectFromCwd(cwd);
328
606
  if (s.startedAt && s.endedAt) {
329
607
  const ms = Date.parse(s.endedAt) - Date.parse(s.startedAt);
330
- s.durationMinutes = Number.isNaN(ms) ? null : ms / 6e4;
608
+ s.durationMinutes = Number.isNaN(ms) || ms < 0 ? null : ms / 6e4;
331
609
  }
332
610
  return s;
333
611
  }
334
612
 
335
613
  // ../../packages/engine/src/aggregate.ts
336
614
  function addTotals(into, from) {
615
+ const priorCreation = into.cache_creation_tokens;
337
616
  into.input_tokens += from.input_tokens;
338
617
  into.output_tokens += from.output_tokens;
339
618
  into.cache_creation_tokens += from.cache_creation_tokens;
340
619
  into.cache_read_tokens += from.cache_read_tokens;
620
+ const intoHasSplit = into.cache_creation_5m_tokens != null || into.cache_creation_1h_tokens != null;
621
+ const fromHasSplit = from.cache_creation_5m_tokens != null || from.cache_creation_1h_tokens != null;
622
+ if (intoHasSplit || fromHasSplit) {
623
+ into.cache_creation_5m_tokens = (into.cache_creation_5m_tokens ?? priorCreation) + (from.cache_creation_5m_tokens ?? from.cache_creation_tokens);
624
+ into.cache_creation_1h_tokens = (into.cache_creation_1h_tokens ?? 0) + (from.cache_creation_1h_tokens ?? 0);
625
+ }
626
+ }
627
+ function safeModelId(model) {
628
+ return /^[A-Za-z0-9._:\[\]-]{1,100}$/.test(model) ? model : "unknown";
629
+ }
630
+ function buildAccuracy(sessions) {
631
+ const warningSet = /* @__PURE__ */ new Set([
632
+ "Values are estimated at the current list-price snapshot; records without explicit pricing metadata use standard rates."
633
+ ]);
634
+ const unknown = /* @__PURE__ */ new Map();
635
+ let pricedRequests = 0;
636
+ let totalBillableRequests = 0;
637
+ let invalidUsageRecords = 0;
638
+ let conflictingUsageRecords = 0;
639
+ for (const session of sessions) {
640
+ for (const warning of session.accuracyWarnings ?? []) warningSet.add(warning);
641
+ pricedRequests += session.pricedRequests ?? 0;
642
+ totalBillableRequests += session.modelRequests;
643
+ invalidUsageRecords += session.invalidUsageRecords ?? 0;
644
+ conflictingUsageRecords += session.conflictingUsageRecords ?? 0;
645
+ for (const [model, requests] of Object.entries(session.unknownModelRequests ?? {})) {
646
+ const safe = safeModelId(model);
647
+ unknown.set(safe, (unknown.get(safe) ?? 0) + requests);
648
+ }
649
+ }
650
+ const unknownModels = [...unknown.entries()].map(([model, requests]) => ({ model, requests })).sort((a, b) => b.requests - a.requests || a.model.localeCompare(b.model));
651
+ for (const { model } of unknownModels) warningSet.add(`Unknown model ${model} used estimated fallback pricing.`);
652
+ return {
653
+ basis: "current_list_prices",
654
+ estimated: true,
655
+ pricingSnapshotDate: PRICING_SNAPSHOT_DATE,
656
+ accountingVersion: "2",
657
+ warnings: [...warningSet],
658
+ pricedRequests,
659
+ totalBillableRequests,
660
+ unknownModels,
661
+ invalidUsageRecords,
662
+ conflictingUsageRecords
663
+ };
664
+ }
665
+ function unionDurationHours(sessions) {
666
+ const intervals = sessions.flatMap((session) => {
667
+ if (!session.startedAt || !session.endedAt) return [];
668
+ const start2 = Date.parse(session.startedAt);
669
+ const end2 = Date.parse(session.endedAt);
670
+ return Number.isFinite(start2) && Number.isFinite(end2) && end2 > start2 ? [[start2, end2]] : [];
671
+ }).sort((a, b) => a[0] - b[0] || a[1] - b[1]);
672
+ let totalMs = 0;
673
+ let start = 0;
674
+ let end = 0;
675
+ for (const interval of intervals) {
676
+ if (end === 0) {
677
+ [start, end] = interval;
678
+ } else if (interval[0] <= end) {
679
+ end = Math.max(end, interval[1]);
680
+ } else {
681
+ totalMs += end - start;
682
+ [start, end] = interval;
683
+ }
684
+ }
685
+ if (end !== 0) totalMs += end - start;
686
+ return totalMs / 36e5;
341
687
  }
342
688
  function mostFrequent(values) {
343
689
  const counts = /* @__PURE__ */ new Map();
@@ -392,7 +738,7 @@ function buildSummary(projects) {
392
738
  let sessionsCount = 0;
393
739
  let delegatedSessionsCount = 0;
394
740
  let mainCostUsd = 0;
395
- let durationHours = 0;
741
+ const sessions = [];
396
742
  for (const p of projects) {
397
743
  addTotals(totals, p.totals);
398
744
  cost += p.cost_usd;
@@ -400,10 +746,14 @@ function buildSummary(projects) {
400
746
  sessionsCount += p.sessionsCount;
401
747
  delegatedSessionsCount += p.delegatedSessionsCount;
402
748
  for (const s of p.sessions) {
403
- const key = s.modelPrimary || "unknown";
404
- modelBreakdown[key] = (modelBreakdown[key] ?? 0) + s.cost_usd;
749
+ sessions.push(s);
750
+ const fragments = s.modelCostsUsd && Object.keys(s.modelCostsUsd).length > 0 ? s.modelCostsUsd : { [s.modelPrimary || "unknown"]: s.cost_usd };
751
+ for (const [model, modelCost] of Object.entries(fragments)) {
752
+ if (!Number.isFinite(modelCost) || modelCost === 0) continue;
753
+ const key = safeModelId(model);
754
+ modelBreakdown[key] = (modelBreakdown[key] ?? 0) + modelCost;
755
+ }
405
756
  if (s.kind === "main") mainCostUsd += s.cost_usd;
406
- if (s.durationMinutes && s.durationMinutes > 0) durationHours += s.durationMinutes / 60;
407
757
  }
408
758
  }
409
759
  return {
@@ -416,7 +766,8 @@ function buildSummary(projects) {
416
766
  totals,
417
767
  modelBreakdown,
418
768
  cacheHitRate: cacheHitRate(totals),
419
- durationHours
769
+ durationHours: unionDurationHours(sessions),
770
+ accuracy: buildAccuracy(sessions)
420
771
  };
421
772
  }
422
773
 
@@ -474,8 +825,7 @@ function ruleBadCacheHit(ctx) {
474
825
  if (!last) continue;
475
826
  let savings = 0;
476
827
  for (const s of tail) {
477
- const p = priceFor(s.modelPrimary);
478
- savings += (s.totals.cache_creation_tokens + s.totals.input_tokens) * (p.input - p.cache_read) / 1e6;
828
+ savings += s.cacheMissExposureUsd ?? cacheMissExposureForTotals(s.modelPrimary, s.totals);
479
829
  }
480
830
  out.push({
481
831
  ruleId: "BAD_CACHE_HIT",
@@ -634,8 +984,10 @@ function ruleMarathonSession(ctx) {
634
984
  if (lateHit >= LATE_FLOOR) continue;
635
985
  const expectedReads = late.total * earlyHit;
636
986
  const shortfall = Math.max(0, expectedReads - late.read);
637
- const p = priceFor(s.modelPrimary);
638
- const savings = shortfall * (p.input - p.cache_read) / 1e6;
987
+ const lateMiss = late.total - late.read;
988
+ const affectedShare = lateMiss > 0 ? Math.min(1, shortfall / lateMiss) : 0;
989
+ 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;
990
+ const savings = s.turnCacheExposureUsd ? lateExposure * affectedShare : lateExposure;
639
991
  out.push({
640
992
  ruleId: "MARATHON_SESSION",
641
993
  severity: severityForSavings(savings),
@@ -740,7 +1092,7 @@ function runOptimizer(ctx) {
740
1092
 
741
1093
  // ../../packages/engine/src/report.ts
742
1094
  function analyzeUploads(files) {
743
- const sessions = files.map(
1095
+ const parsed = files.map(
744
1096
  (f) => parseSession(f.text, {
745
1097
  // Path-encoded slugs are anonymized before grouping so no downstream
746
1098
  // consumer (optimizer prose, synthesize, the AuditRecord) ever sees one.
@@ -749,18 +1101,80 @@ function analyzeUploads(files) {
749
1101
  parentSessionId: f.parentSessionId ?? null
750
1102
  })
751
1103
  );
1104
+ const sessions = deduplicateLogicalRequests(parsed);
752
1105
  const projects = buildProjects(sessions);
753
1106
  const summary = buildSummary(projects);
754
1107
  const findings = runOptimizer({ projects, summary });
755
1108
  return { summary, projects, findings };
756
1109
  }
1110
+ var CROSS_FILE_DUPLICATE_WARNING = "Copied logical requests across uploaded logs were counted once.";
1111
+ var CROSS_FILE_CONFLICT_WARNING = "Conflicting copies of a logical request were not added; the highest coherent valuation was retained.";
1112
+ function ownerRank(session) {
1113
+ return session.kind === "main" ? 0 : session.kind === "subagent" ? 1 : 2;
1114
+ }
1115
+ function deduplicateLogicalRequests(sessions) {
1116
+ const originalCounts = sessions.map((session) => session.usageFragments?.length ?? 0);
1117
+ const groups = /* @__PURE__ */ new Map();
1118
+ for (let sessionIndex = 0; sessionIndex < sessions.length; sessionIndex += 1) {
1119
+ for (const fragment of sessions[sessionIndex].usageFragments ?? []) {
1120
+ if (!fragment.logicalKey) continue;
1121
+ const group = groups.get(fragment.logicalKey) ?? [];
1122
+ group.push({ sessionIndex, fragment });
1123
+ groups.set(fragment.logicalKey, group);
1124
+ }
1125
+ }
1126
+ const assigned = sessions.map(() => []);
1127
+ const ownerIndexes = /* @__PURE__ */ new Map();
1128
+ const dropSessions = sessions.map(() => false);
1129
+ for (const [key, refs] of groups) {
1130
+ if (refs.length === 1) {
1131
+ assigned[refs[0].sessionIndex].push(refs[0].fragment);
1132
+ ownerIndexes.set(key, refs[0].sessionIndex);
1133
+ continue;
1134
+ }
1135
+ const owner = refs.slice().sort((a, b) => ownerRank(sessions[a.sessionIndex]) - ownerRank(sessions[b.sessionIndex]) || a.sessionIndex - b.sessionIndex)[0];
1136
+ ownerIndexes.set(key, owner.sessionIndex);
1137
+ const retained = refs.slice().sort((a, b) => b.fragment.costUsd - a.fragment.costUsd || b.fragment.output_tokens - a.fragment.output_tokens)[0].fragment;
1138
+ assigned[owner.sessionIndex].push(retained);
1139
+ sessions[owner.sessionIndex].duplicateFragmentsSkipped += refs.length - 1;
1140
+ sessions[owner.sessionIndex].accuracyWarnings = [...sessions[owner.sessionIndex].accuracyWarnings ?? [], CROSS_FILE_DUPLICATE_WARNING];
1141
+ const signatures = new Set(refs.map(({ fragment }) => fragment.accountingSignature));
1142
+ if (signatures.size > 1) {
1143
+ sessions[owner.sessionIndex].conflictingUsageRecords = (sessions[owner.sessionIndex].conflictingUsageRecords ?? 0) + 1;
1144
+ sessions[owner.sessionIndex].accuracyWarnings.push(CROSS_FILE_CONFLICT_WARNING);
1145
+ }
1146
+ }
1147
+ for (let sessionIndex = 0; sessionIndex < sessions.length; sessionIndex += 1) {
1148
+ for (const fragment of sessions[sessionIndex].usageFragments ?? []) {
1149
+ if (!fragment.logicalKey) assigned[sessionIndex].push(fragment);
1150
+ }
1151
+ }
1152
+ for (let sessionIndex = 0; sessionIndex < sessions.length; sessionIndex += 1) {
1153
+ const logicalKeys = sessions[sessionIndex].usageLogicalKeys ?? [];
1154
+ const acceptedCopyRemoved = originalCounts[sessionIndex] > 0 && assigned[sessionIndex].length === 0;
1155
+ const invalidCopyOnly = originalCounts[sessionIndex] === 0 && logicalKeys.length > 0 && logicalKeys.every((key) => ownerIndexes.has(key) && ownerIndexes.get(key) !== sessionIndex);
1156
+ if (!acceptedCopyRemoved && !invalidCopyOnly) continue;
1157
+ const removed = sessions[sessionIndex];
1158
+ const ownerIndex = [...(removed.usageFragments ?? []).map((fragment) => fragment.logicalKey), ...logicalKeys].map((key) => key ? ownerIndexes.get(key) : void 0).find((value) => value != null);
1159
+ if (ownerIndex == null || ownerIndex === sessionIndex) continue;
1160
+ const owner = sessions[ownerIndex];
1161
+ owner.accuracyWarnings = [.../* @__PURE__ */ new Set([...owner.accuracyWarnings ?? [], ...removed.accuracyWarnings ?? []])];
1162
+ owner.invalidUsageRecords = (owner.invalidUsageRecords ?? 0) + (removed.invalidUsageRecords ?? 0);
1163
+ owner.conflictingUsageRecords = (owner.conflictingUsageRecords ?? 0) + (removed.conflictingUsageRecords ?? 0);
1164
+ dropSessions[sessionIndex] = true;
1165
+ }
1166
+ for (let sessionIndex = 0; sessionIndex < sessions.length; sessionIndex += 1) {
1167
+ const session = sessions[sessionIndex];
1168
+ rebuildSessionUsage(session, assigned[sessionIndex]);
1169
+ }
1170
+ return sessions.filter((session, index) => !dropSessions[index] && ((session.usageFragments?.length ?? 0) > 0 || originalCounts[index] === 0));
1171
+ }
757
1172
  function cacheMissExposureUsd(report) {
758
1173
  let total = 0;
759
1174
  for (const proj of report.projects) {
760
1175
  for (const s of proj.sessions) {
761
1176
  if (s.kind !== "main") continue;
762
- const p = priceFor(s.modelPrimary);
763
- total += (s.totals.input_tokens + s.totals.cache_creation_tokens) * (p.input - p.cache_read) / 1e6;
1177
+ total += s.cacheMissExposureUsd ?? cacheMissExposureForTotals(s.modelPrimary, s.totals);
764
1178
  }
765
1179
  }
766
1180
  return total;
@@ -774,8 +1188,7 @@ function cacheMissByProject(report) {
774
1188
  for (const s of proj.sessions) {
775
1189
  if (s.kind !== "main") continue;
776
1190
  sessionsCount += 1;
777
- const p = priceFor(s.modelPrimary);
778
- usd8 += (s.totals.input_tokens + s.totals.cache_creation_tokens) * (p.input - p.cache_read) / 1e6;
1191
+ usd8 += s.cacheMissExposureUsd ?? cacheMissExposureForTotals(s.modelPrimary, s.totals);
779
1192
  mainTotals.input_tokens += s.totals.input_tokens;
780
1193
  mainTotals.output_tokens += s.totals.output_tokens;
781
1194
  mainTotals.cache_creation_tokens += s.totals.cache_creation_tokens;
@@ -1351,13 +1764,14 @@ function buildChecks(report, cmd2, answers, setup) {
1351
1764
  const exposure = cacheMissExposureUsd(report);
1352
1765
  const spend = s.mainCostUsd;
1353
1766
  const exposureShare = spend > 0 ? exposure / spend : 0;
1767
+ const exposureValid = spend > 0 && exposure >= 0 && exposure <= spend + 1e-9;
1354
1768
  checks.push(
1355
1769
  makeCheck(
1356
1770
  "recoverable_exposure",
1357
1771
  "cost_discipline",
1358
- "Recoverable spend",
1359
- spend > 0 ? clamp2(100 - exposureShare * 120) : null,
1360
- 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.",
1772
+ "Cache-miss upper comparison",
1773
+ exposureValid ? clamp2(100 - exposureShare * 120) : null,
1774
+ !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.`,
1361
1775
  "metrics"
1362
1776
  )
1363
1777
  );
@@ -1483,14 +1897,14 @@ var HEAVY_TOOL_PATTERN_MIN_SESSIONS = 2;
1483
1897
  function severityRank(s) {
1484
1898
  return s === "critical" ? 3 : s === "warn" ? 2 : 1;
1485
1899
  }
1486
- function num2(n) {
1900
+ function num(n) {
1487
1901
  return String(Math.round(n)).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
1488
1902
  }
1489
1903
  function sizeFix(cmd2) {
1490
1904
  if (cmd2.chars > 6e3) {
1491
1905
  return {
1492
1906
  title: "Trim your CLAUDE.md",
1493
- action: `Your CLAUDE.md is an estimated ${num2(cmd2.estTokens)} tokens (${num2(cmd2.chars)} characters), 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.`
1907
+ action: `Your CLAUDE.md is an estimated ${num(cmd2.estTokens)} tokens (${num(cmd2.chars)} characters), 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.`
1494
1908
  };
1495
1909
  }
1496
1910
  return {
@@ -1500,13 +1914,13 @@ function sizeFix(cmd2) {
1500
1914
  }
1501
1915
  function synthesize(report, pillars, cmd2, plan = "api") {
1502
1916
  const headlineWasteUsd = cacheMissExposureUsd(report);
1503
- const headlineWasteLabel = plan === "api" ? "Recoverable spend (cache-miss exposure)" : "Recoverable usage (cache-miss exposure)";
1917
+ const headlineWasteLabel = "Cache-miss exposure (estimate)";
1504
1918
  const spend = report.summary.cost_usd;
1505
1919
  const headlineWasteShare = spend > 0 ? headlineWasteUsd / spend : 0;
1506
1920
  const exposure = headlineWasteUsd;
1507
1921
  const fixes = [];
1508
1922
  const covered = /* @__PURE__ */ new Set();
1509
- const round23 = (n) => Math.round(n * 100) / 100;
1923
+ const round23 = (n) => roundMoneyHalfUp(n);
1510
1924
  const usd8 = (n) => {
1511
1925
  const fixed = round23(n).toFixed(2);
1512
1926
  const dot = fixed.indexOf(".");
@@ -1587,16 +2001,16 @@ function synthesize(report, pillars, cmd2, plan = "api") {
1587
2001
  }
1588
2002
  fixes.push({
1589
2003
  id: "cache_recovery",
1590
- title: "Recover spend lost to cache misses",
2004
+ title: "Reduce cache-miss exposure",
1591
2005
  pillar: "context_hygiene",
1592
2006
  pillarName: PILLARS.context_hygiene.name,
1593
2007
  severity: sevForUsd(exposure),
1594
2008
  wasteUsd: round23(exposure),
1595
2009
  problem: sanitizeText(
1596
- `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"}.`
2010
+ `${usd8(exposure)} is the estimated current API-equivalent cache-miss exposure if accepted requests could instead use cache reads. Cold and unique inputs cannot all be cached. Biggest contributors: ${worst.length ? worst.join(", ") : "your largest projects"}.`
1597
2011
  ),
1598
2012
  action: sanitizeText(action),
1599
- basis: sanitizeText("Cache-miss exposure summed across projects at the published input minus cache-read delta. Upper bound on recoverable spend.")
2013
+ basis: sanitizeText("Current list-price cache-miss exposure summed across projects. It is a bounded counterfactual, not complete savings or billed spend.")
1600
2014
  });
1601
2015
  covered.add("cache_hit");
1602
2016
  covered.add("cache_churn");
@@ -1674,7 +2088,7 @@ function synthesize(report, pillars, cmd2, plan = "api") {
1674
2088
  wasteUsd: round23(marathonUsd),
1675
2089
  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.`),
1676
2090
  action: sanitizeText("Compact or start a fresh session between tasks so the context stays small and the cache keeps working."),
1677
- basis: sanitizeText("Recoverable estimate from the late-session cache shortfall versus the early-session hit rate.")
2091
+ basis: sanitizeText("Estimated cache-miss exposure from the late-session cache shortfall versus the early-session hit rate; not complete savings.")
1678
2092
  });
1679
2093
  }
1680
2094
  if (workflowUsd > 0) {
@@ -1797,7 +2211,7 @@ var UNASSESSED_BURN_CLOCK = {
1797
2211
  quietSlot: null,
1798
2212
  activeDays: 0
1799
2213
  };
1800
- function burnClock(report, offsetMinutes = 0) {
2214
+ function burnClock(report, offsetMinutes = 0, timeZone) {
1801
2215
  const merged = /* @__PURE__ */ new Map();
1802
2216
  for (const project of report.projects) {
1803
2217
  for (const session of project.sessions) {
@@ -1805,19 +2219,52 @@ function burnClock(report, offsetMinutes = 0) {
1805
2219
  }
1806
2220
  }
1807
2221
  if (merged.size === 0) return UNASSESSED_BURN_CLOCK;
2222
+ let formatter = null;
2223
+ if (timeZone) {
2224
+ try {
2225
+ formatter = new Intl.DateTimeFormat("en-US-u-ca-gregory-nu-latn", {
2226
+ timeZone,
2227
+ year: "numeric",
2228
+ month: "2-digit",
2229
+ day: "2-digit",
2230
+ weekday: "short",
2231
+ hour: "2-digit",
2232
+ hourCycle: "h23"
2233
+ });
2234
+ } catch {
2235
+ formatter = null;
2236
+ }
2237
+ }
2238
+ const localParts = (t) => {
2239
+ const epochMs = t * 9e5;
2240
+ if (!formatter) {
2241
+ const date = new Date(epochMs + offsetMinutes * 6e4);
2242
+ return {
2243
+ day: date.getUTCDay(),
2244
+ hour: date.getUTCHours(),
2245
+ date: `${date.getUTCFullYear()}-${date.getUTCMonth() + 1}-${date.getUTCDate()}`
2246
+ };
2247
+ }
2248
+ const parts = Object.fromEntries(formatter.formatToParts(epochMs).map((part) => [part.type, part.value]));
2249
+ const dayNames = { Sun: 0, Mon: 1, Tue: 2, Wed: 3, Thu: 4, Fri: 5, Sat: 6 };
2250
+ return {
2251
+ day: dayNames[parts.weekday ?? ""] ?? 0,
2252
+ hour: Number(parts.hour ?? 0),
2253
+ date: `${parts.year}-${parts.month}-${parts.day}`
2254
+ };
2255
+ };
1808
2256
  const activeDaySet = /* @__PURE__ */ new Set();
1809
2257
  for (const t of merged.keys()) {
1810
- const d = new Date(t * 9e5 + offsetMinutes * 6e4);
1811
- activeDaySet.add(`${d.getUTCFullYear()}-${d.getUTCMonth()}-${d.getUTCDate()}`);
2258
+ activeDaySet.add(localParts(t).date);
1812
2259
  }
1813
2260
  if (activeDaySet.size < 7) return { ...UNASSESSED_BURN_CLOCK, activeDays: activeDaySet.size };
1814
2261
  const byDay = [0, 0, 0, 0, 0, 0, 0];
1815
2262
  const byQuarter = [0, 0, 0, 0];
1816
2263
  const slot = Array.from({ length: 7 }, () => [0, 0, 0, 0]);
1817
2264
  for (const [t, usd8] of merged) {
1818
- const d = new Date(t * 9e5 + offsetMinutes * 6e4);
1819
- const day2 = d.getUTCDay();
1820
- const quarter = Math.floor(d.getUTCHours() / 6);
2265
+ const local = localParts(t);
2266
+ const day2 = local.day;
2267
+ const quarter = Math.floor(local.hour / 6);
1821
2268
  byDay[day2] += usd8;
1822
2269
  byQuarter[quarter] += usd8;
1823
2270
  slot[day2][quarter] += usd8;
@@ -1846,7 +2293,7 @@ function usd(n) {
1846
2293
  const grouped = whole.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
1847
2294
  return `${neg ? "-" : ""}$${grouped}${cents}`;
1848
2295
  }
1849
- function num3(n) {
2296
+ function num2(n) {
1850
2297
  return String(Math.round(n)).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
1851
2298
  }
1852
2299
  function clean(text2) {
@@ -2513,7 +2960,7 @@ function claudeMdReceiptLine(claudeMdTokens) {
2513
2960
  const grew = delta > 0;
2514
2961
  const pct2 = before > 0 ? ` (${(Math.abs(delta) / before * 100).toFixed(1)}% ${grew ? "larger" : "smaller"})` : "";
2515
2962
  const tail = grew ? "It is re-read on every turn, so the larger file costs a little more every time too." : "It is re-read on every turn, so that saving repeats every session.";
2516
- return `Your optimized CLAUDE.md goes from an estimated ${num3(before)} tokens to ${num3(after)}${pct2}. ${tail}`;
2963
+ return `Your optimized CLAUDE.md goes from an estimated ${num2(before)} tokens to ${num2(after)}${pct2}. ${tail}`;
2517
2964
  }
2518
2965
  function buildPlaybook(report, fixes, scores, recoverable, claudeMdTokens, project) {
2519
2966
  const dollarFixes = fixes.filter((f) => f.wasteUsd > 0);
@@ -2526,9 +2973,9 @@ function buildPlaybook(report, fixes, scores, recoverable, claudeMdTokens, proje
2526
2973
  parts.push(
2527
2974
  [
2528
2975
  ...projectLine ? [projectLine, ""] : [],
2529
- `Total recoverable spend: ${usd(recoverable)} (cache-miss exposure).`,
2976
+ `Cache-miss exposure estimate: ${usd(recoverable)} at current API list prices.`,
2530
2977
  "",
2531
- "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."
2978
+ "This is the ranked plan from your audit. Priority suggestions are ordered by hypothetical value, followed by rule-based setup warnings. Cache-miss exposure is a comparison with cache reads, not a savings guarantee or measured subscription headroom."
2532
2979
  ].join("\n")
2533
2980
  );
2534
2981
  const receipt = claudeMdReceiptLine(claudeMdTokens);
@@ -2656,12 +3103,12 @@ function buildHarnessPrompt(input, carried, claudeMdTokens) {
2656
3103
  if (carried.carriedTokens >= CARRY_HEAVY_TOKENS && worklist.length > 0) {
2657
3104
  const rows = worklist.map((s) => {
2658
3105
  const n2 = s.volatileLines;
2659
- const dated = n2 > 0 ? `, ${num3(n2)} dated ${n2 === 1 ? "line" : "lines"}` : "";
2660
- return `- ${s.heading}: est. ${num3(s.tokens)} tokens${dated}.`;
3106
+ const dated = n2 > 0 ? `, ${num2(n2)} dated ${n2 === 1 ? "line" : "lines"}` : "";
3107
+ return `- ${s.heading}: est. ${num2(s.tokens)} tokens${dated}.`;
2661
3108
  });
2662
3109
  const shown = worklist.reduce((sum, s) => sum + s.tokens, 0);
2663
3110
  const rest = carried.carriedList.length - worklist.length;
2664
- const tail = rest > 0 ? [`The remaining ${num3(rest)} carried ${rest === 1 ? "section accounts" : "sections account"} for the other ${num3(carried.carriedTokens - shown)} tokens.`] : [];
3111
+ const tail = rest > 0 ? [`The remaining ${num2(rest)} carried ${rest === 1 ? "section accounts" : "sections account"} for the other ${num2(carried.carriedTokens - shown)} tokens.`] : [];
2665
3112
  const before = claudeMdTokens.before;
2666
3113
  const saved = before != null && before > 0 ? (before - claudeMdTokens.after) / before : 0;
2667
3114
  const consequence = saved <= 0 ? "that is why the optimized file is no smaller." : saved < 0.2 ? "that is why the optimized file is barely smaller." : "it is the weight that is left.";
@@ -2669,7 +3116,7 @@ function buildHarnessPrompt(input, carried, claudeMdTokens) {
2669
3116
  [
2670
3117
  `## Task ${n++}: Reclaim the carried sections`,
2671
3118
  "",
2672
- `Your CLAUDE.md carries an estimated ${num3(carried.carriedTokens)} tokens of your`,
3119
+ `Your CLAUDE.md carries an estimated ${num2(carried.carriedTokens)} tokens of your`,
2673
3120
  "own prose, paid on every turn of every session.",
2674
3121
  `costclaw does not rewrite your prose, so it passed all of it through untouched:`,
2675
3122
  `${consequence} Doing the actual trimming is this task,`,
@@ -2830,11 +3277,15 @@ function optimize(input) {
2830
3277
  // ../../packages/engine/src/audit.ts
2831
3278
  import { randomUUID } from "crypto";
2832
3279
  function round2(n) {
2833
- return Math.round(n * 100) / 100;
3280
+ return roundMoneyHalfUp(n);
2834
3281
  }
2835
3282
  function round4(n) {
2836
3283
  return Math.round(n * 1e4) / 1e4;
2837
3284
  }
3285
+ function safeModelId2(model) {
3286
+ if (model == null) return null;
3287
+ return /^[A-Za-z0-9._:\[\]-]{1,100}$/.test(model) ? model : "unknown";
3288
+ }
2838
3289
  function toUsageMetrics(report) {
2839
3290
  const s = report.summary;
2840
3291
  const topProjects = report.projects.slice().sort((a, b) => b.cost_usd - a.cost_usd).slice(0, 8).map((p) => ({
@@ -2842,14 +3293,15 @@ function toUsageMetrics(report) {
2842
3293
  costUsd: round2(p.cost_usd),
2843
3294
  sessionsCount: p.sessionsCount,
2844
3295
  cacheHitRate: round4(p.cacheHitRate),
2845
- modelPrimary: p.modelPrimary
3296
+ modelPrimary: safeModelId2(p.modelPrimary)
2846
3297
  }));
2847
3298
  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 }) => ({
2848
3299
  projectSlug,
2849
- sessionUuid: sess.sessionUuid,
3300
+ // Retain the schema field without persisting a private transcript ID.
3301
+ sessionUuid: null,
2850
3302
  costUsd: round2(sess.cost_usd),
2851
3303
  durationMinutes: sess.durationMinutes == null ? null : round2(sess.durationMinutes),
2852
- modelPrimary: sess.modelPrimary,
3304
+ modelPrimary: safeModelId2(sess.modelPrimary),
2853
3305
  cacheHitRate: round4(cacheHitRate(sess.totals))
2854
3306
  }));
2855
3307
  const modelBreakdown = {};
@@ -2866,7 +3318,12 @@ function toUsageMetrics(report) {
2866
3318
  modelBreakdown,
2867
3319
  topProjects,
2868
3320
  topSessions,
2869
- pricingSnapshotDate: PRICING_SNAPSHOT_DATE
3321
+ pricingSnapshotDate: PRICING_SNAPSHOT_DATE,
3322
+ accuracy: s.accuracy ? {
3323
+ ...s.accuracy,
3324
+ warnings: [...s.accuracy.warnings],
3325
+ unknownModels: s.accuracy.unknownModels.map((entry) => ({ ...entry }))
3326
+ } : void 0
2870
3327
  };
2871
3328
  }
2872
3329
  function roundWindows(w) {
@@ -2932,7 +3389,7 @@ function buildAudit(input, opts = {}) {
2932
3389
  plan,
2933
3390
  headlineWasteShare: round4(headlineWasteShare),
2934
3391
  usageWindows: roundWindows(computeWindowStats(report)),
2935
- burnClock: roundBurnClock(burnClock(report, input.tzOffsetMinutes ?? 0)),
3392
+ burnClock: roundBurnClock(burnClock(report, input.tzOffsetMinutes ?? 0, input.timeZone)),
2936
3393
  fixes: fixes.map(cleanFix),
2937
3394
  writer: opts.writer ?? "template",
2938
3395
  paid: false
@@ -2942,7 +3399,7 @@ function buildAudit(input, opts = {}) {
2942
3399
  // ../../packages/engine/src/diff.ts
2943
3400
  var DIFF_SCHEMA_VERSION = "1";
2944
3401
  function round22(n) {
2945
- return Math.round(n * 100) / 100;
3402
+ return roundMoneyHalfUp(n);
2946
3403
  }
2947
3404
  function round42(n) {
2948
3405
  return Math.round(n * 1e4) / 1e4;
@@ -2965,6 +3422,12 @@ function side(r) {
2965
3422
  plan: r.plan
2966
3423
  };
2967
3424
  }
3425
+ function provenanceMismatch(a, b) {
3426
+ if (!a && !b) return void 0;
3427
+ if (!a || !b || a.accountingVersion !== b.accountingVersion) return "accounting changed";
3428
+ if (a.pricingSnapshotDate !== b.pricingSnapshotDate) return "pricing changed";
3429
+ return void 0;
3430
+ }
2968
3431
  function diffAudits(a, b) {
2969
3432
  assertRecord(a);
2970
3433
  assertRecord(b);
@@ -2979,7 +3442,8 @@ function diffAudits(a, b) {
2979
3442
  };
2980
3443
  const newSpendUsd = cm.spendUsd - bm.spendUsd;
2981
3444
  const newSessions = cm.sessionsCount - bm.sessionsCount;
2982
- const comparable = newSpendUsd >= -0.01 && newSessions >= 0 && Object.values(newTokens).every((t) => t >= 0);
3445
+ const comparisonReason = provenanceMismatch(bm.accuracy, cm.accuracy);
3446
+ const comparable = !comparisonReason && newSpendUsd >= -0.01 && newSessions >= 0 && Object.values(newTokens).every((t) => t >= 0);
2983
3447
  const periodMs = Date.parse(cur.createdAt) - Date.parse(base.createdAt);
2984
3448
  const periodDays = round22(Math.max(0, periodMs) / 864e5);
2985
3449
  const pillars = base.pillarScores.map((bp) => {
@@ -3009,6 +3473,7 @@ function diffAudits(a, b) {
3009
3473
  current: side(cur),
3010
3474
  periodDays,
3011
3475
  comparable,
3476
+ ...comparisonReason ? { comparisonReason } : {},
3012
3477
  marginal: comparable ? {
3013
3478
  newSpendUsd: round22(newSpendUsd),
3014
3479
  newSessions,
@@ -3027,6 +3492,13 @@ function diffAudits(a, b) {
3027
3492
  }
3028
3493
  var SINCE_BASELINE_MIN_TOKENS = 1e6;
3029
3494
  function sinceBaseline(baseline, current) {
3495
+ const currentAccuracy = current.usageMetrics.accuracy;
3496
+ if (!baseline.accuracy !== !currentAccuracy || baseline.accuracy && currentAccuracy && baseline.accuracy.accountingVersion !== currentAccuracy.accountingVersion) {
3497
+ return { comparable: false, reason: "accounting method changed" };
3498
+ }
3499
+ if (baseline.accuracy && currentAccuracy && baseline.accuracy.pricingSnapshotDate !== currentAccuracy.pricingSnapshotDate) {
3500
+ return { comparable: false, reason: "pricing changed" };
3501
+ }
3030
3502
  const cur = current.usageMetrics.totalTokens;
3031
3503
  const base = baseline.totals;
3032
3504
  const period = {
@@ -3064,7 +3536,7 @@ var IMPORT_LINE = "@.claude/costclaw.md";
3064
3536
  function estTokens(text2) {
3065
3537
  return Math.round(text2.length / 4);
3066
3538
  }
3067
- function num4(n) {
3539
+ function num3(n) {
3068
3540
  return String(Math.round(n)).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
3069
3541
  }
3070
3542
  function normalize(line) {
@@ -3167,7 +3639,7 @@ function markVolatile(lines, sections, b, destDir) {
3167
3639
  id,
3168
3640
  kind: "move",
3169
3641
  heading: s.heading,
3170
- instruction: `Move the ${num4(dated.length)} dated ${dated.length === 1 ? "line" : "lines"} under "${s.heading}" to ${dest}, then link that file.`,
3642
+ instruction: `Move the ${num3(dated.length)} dated ${dated.length === 1 ? "line" : "lines"} under "${s.heading}" to ${dest}, then link that file.`,
3171
3643
  reason: VOLATILE_WHY,
3172
3644
  tokens: estTokens(dated.map((i) => lines[i] ?? "").join("\n")),
3173
3645
  destination: dest
@@ -3304,8 +3776,8 @@ function reviewProjectClaudeMd(input) {
3304
3776
  id,
3305
3777
  kind: "remove",
3306
3778
  heading: s.heading,
3307
- instruction: all ? `Delete the whole "${s.heading}" section: the include ${IMPORT_LINE} now carries it.` : `Delete the ${num4(covered.length)} covered ${covered.length === 1 ? "line" : "lines"} under "${s.heading}" and keep these ${num4(kept)} lines under the heading: the include ${IMPORT_LINE} does not have them.`,
3308
- reason: `${num4(covered.length)} of ${num4(content.length)} lines appear verbatim in the generated include`,
3779
+ instruction: all ? `Delete the whole "${s.heading}" section: the include ${IMPORT_LINE} now carries it.` : `Delete the ${num3(covered.length)} covered ${covered.length === 1 ? "line" : "lines"} under "${s.heading}" and keep these ${num3(kept)} lines under the heading: the include ${IMPORT_LINE} does not have them.`,
3780
+ reason: `${num3(covered.length)} of ${num3(content.length)} lines appear verbatim in the generated include`,
3309
3781
  tokens: estTokens(covered.map((i) => lines[i] ?? "").join("\n"))
3310
3782
  });
3311
3783
  }
@@ -3429,8 +3901,8 @@ function reviewGlobalClaudeMd(input) {
3429
3901
  id,
3430
3902
  kind: "move",
3431
3903
  heading: "(top)",
3432
- instruction: `Split ${heaviest.label} (about ${num4(estTokens(heaviest.text))} tokens) into docs the agent opens on demand, and keep only the rules that prevent mistakes.`,
3433
- reason: `this file plus its imports is about ${num4(total)} tokens on every turn of every project`,
3904
+ instruction: `Split ${heaviest.label} (about ${num3(estTokens(heaviest.text))} tokens) into docs the agent opens on demand, and keep only the rules that prevent mistakes.`,
3905
+ reason: `this file plus its imports is about ${num3(total)} tokens on every turn of every project`,
3434
3906
  tokens: 0,
3435
3907
  destination: "on-demand docs"
3436
3908
  });
@@ -3450,7 +3922,7 @@ function changeList(review) {
3450
3922
  const out = [];
3451
3923
  review.changes.forEach((c, i) => {
3452
3924
  const where = c.heading === "(top)" ? "file level" : `section "${c.heading}"`;
3453
- const weight = c.tokens > 0 ? `, about ${num4(c.tokens)} tokens` : "";
3925
+ const weight = c.tokens > 0 ? `, about ${num3(c.tokens)} tokens` : "";
3454
3926
  out.push(`${i + 1}. [${c.kind}] ${where}${weight}: ${c.instruction}`);
3455
3927
  out.push(` Why: ${c.reason}`);
3456
3928
  if (c.destination) out.push(` Destination: ${c.destination}`);
@@ -3464,7 +3936,7 @@ function changeList(review) {
3464
3936
  return out;
3465
3937
  }
3466
3938
  function tokenTarget(review, what) {
3467
- return `- ${what}: about ${num4(review.tokens.afterChanges)} tokens per turn after these changes (about ${num4(review.tokens.total)} now).`;
3939
+ return `- ${what}: about ${num3(review.tokens.afterChanges)} tokens per turn after these changes (about ${num3(review.tokens.total)} now).`;
3468
3940
  }
3469
3941
  function buildUpgradeAll(input) {
3470
3942
  const parts = [];
@@ -3487,7 +3959,7 @@ function buildUpgradeAll(input) {
3487
3959
  parts.push([
3488
3960
  `## Global: ${input.global.path}`,
3489
3961
  "",
3490
- input.global.missing ? "This file does not exist yet. Create it with the blocks below and nothing else." : `Loaded on every turn of every project. ${num4(input.global.changes.length)} ${input.global.changes.length === 1 ? "change" : "changes"} proposed.`,
3962
+ input.global.missing ? "This file does not exist yet. Create it with the blocks below and nothing else." : `Loaded on every turn of every project. ${num3(input.global.changes.length)} ${input.global.changes.length === 1 ? "change" : "changes"} proposed.`,
3491
3963
  "",
3492
3964
  ...changeList(input.global)
3493
3965
  ].join("\n"));
@@ -3676,15 +4148,24 @@ function ansi(enabled) {
3676
4148
  // src/format.ts
3677
4149
  function sinceOptimizeLine(meta) {
3678
4150
  const so = meta.sinceOptimize;
3679
- if (!so || !so.result.comparable) return null;
4151
+ if (!so) return null;
4152
+ if (!so.result.comparable) {
4153
+ if (so.result.reason === "accounting method changed") {
4154
+ return `Since optimize (${so.at.slice(0, 10)}): comparison withheld because the accounting method changed. Run optimize again to set a new baseline.`;
4155
+ }
4156
+ if (so.result.reason === "pricing changed") {
4157
+ return `Since optimize (${so.at.slice(0, 10)}): comparison withheld because the pricing snapshot changed. Run optimize again to set a new baseline.`;
4158
+ }
4159
+ return null;
4160
+ }
3680
4161
  const r = so.result;
3681
4162
  const date = so.at.slice(0, 10);
3682
4163
  const move = `${(r.baselineCacheHitRate * 100).toFixed(1)}% -> ${(r.periodCacheHitRate * 100).toFixed(1)}%`;
3683
- const worth = r.recoveredUsd >= 0.01 ? `; worth about ${usd2(r.recoveredUsd)} at Sonnet rates` : "";
4164
+ const worth = r.recoveredUsd >= 0.01 ? `; estimated current Sonnet-rate valuation ${usd2(r.recoveredUsd)}` : "";
3684
4165
  return `Since optimize (${date}): cache hit ${move} on new usage${worth}.`;
3685
4166
  }
3686
4167
  function usd2(n) {
3687
- return `$${(Math.round(n * 100) / 100).toFixed(2)}`;
4168
+ return `$${roundMoneyHalfUp(n).toFixed(2)}`;
3688
4169
  }
3689
4170
  var BURN_DAY_NAMES = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
3690
4171
  var BURN_DAY_ORDER = [1, 2, 3, 4, 5, 6, 0];
@@ -3764,16 +4245,20 @@ function shortModel(id) {
3764
4245
  return m && m[1] ? m[1].toLowerCase() : id;
3765
4246
  }
3766
4247
  function unknownModelNote(breakdown) {
3767
- let unknown = 0;
3768
- let total = 0;
3769
- for (const [model, spend] of Object.entries(breakdown)) {
3770
- if (spend <= 0) continue;
3771
- total += spend;
3772
- if (!isKnownModel(model)) unknown += spend;
4248
+ const unknown = Object.keys(breakdown).filter((model) => !isKnownModel(model));
4249
+ return unknown.length > 0 ? `Models missing from the rate card: ${unknown.join(", ")}. Their current API-equivalent valuation is approximate.` : null;
4250
+ }
4251
+ function accuracyNotes(record) {
4252
+ const accuracy = record.usageMetrics.accuracy;
4253
+ if (!accuracy) {
4254
+ return [unknownModelNote(record.usageMetrics.modelBreakdown)].filter((note) => note !== null);
4255
+ }
4256
+ const notes = [...accuracy.warnings];
4257
+ if (accuracy.unknownModels.length > 0) {
4258
+ const models = accuracy.unknownModels.map(({ model, requests }) => `${model} (${requests} ${plural(requests, "request")})`).join(", ");
4259
+ notes.push(`Models missing from the rate card: ${models}. Their current API-equivalent valuation is approximate.`);
3773
4260
  }
3774
- if (total <= 0 || unknown / total < 0.01) return null;
3775
- const pct2 = Math.round(unknown / total * 100);
3776
- return `${pct2}% of spend used models missing from the rate card and is priced at approximate (Sonnet) rates.`;
4261
+ return [...new Set(notes)];
3777
4262
  }
3778
4263
  function modelMix(breakdown) {
3779
4264
  const merged = /* @__PURE__ */ new Map();
@@ -3803,8 +4288,9 @@ function formatAudit(record, meta, color = false) {
3803
4288
  const a = ansi(color);
3804
4289
  const m = record.usageMetrics;
3805
4290
  const subscription = record.plan !== void 0 && record.plan !== "api";
3806
- const share = record.headlineWasteShare ?? (m.spendUsd > 0 ? record.headlineWasteUsd / m.spendUsd : 0);
3807
- const shareText = `${(share * 100).toFixed(1)}%`;
4291
+ const reportedShare = record.headlineWasteShare ?? (m.spendUsd > 0 ? record.headlineWasteUsd / m.spendUsd : 0);
4292
+ const shareIsValid = Number.isFinite(reportedShare) && reportedShare >= 0 && reportedShare <= 1;
4293
+ const shareText = shareIsValid ? `${(reportedShare * 100).toFixed(1)}%` : "unavailable";
3808
4294
  const lines = [];
3809
4295
  lines.push(a.bold("CostClaw audit"));
3810
4296
  const delegated = m.delegatedSessionsCount ?? 0;
@@ -3818,7 +4304,7 @@ function formatAudit(record, meta, color = false) {
3818
4304
  lines.push(a.dim("-".repeat(WRAP_WIDTH)));
3819
4305
  lines.push("");
3820
4306
  lines.push(
3821
- 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))}`
4307
+ subscription ? `${a.bold(record.headlineWasteLabel + ":")} ${a.brand(shareText + " of analyzed token value")} (${usd2(record.headlineWasteUsd)} estimated current API-equivalent valuation)` : `${a.bold(record.headlineWasteLabel + ":")} ${a.brand(usd2(record.headlineWasteUsd) + " estimated current API-equivalent valuation")}`
3822
4308
  );
3823
4309
  const receipt = sinceOptimizeLine(meta);
3824
4310
  if (receipt) pushProse(lines, receipt, 0, a.dim);
@@ -3826,9 +4312,9 @@ function formatAudit(record, meta, color = false) {
3826
4312
  const mix = modelMix(m.modelBreakdown);
3827
4313
  const statBlock = [
3828
4314
  [
3829
- { k: subscription ? "Usage analyzed (API-equivalent)" : "Spend analyzed", v: usd2(m.spendUsd) },
4315
+ { k: "Current API-equivalent valuation (estimate)", v: usd2(m.spendUsd) },
3830
4316
  { k: "Cache hit", v: `${(m.cacheHitRate * 100).toFixed(1)}%` },
3831
- { k: "Active hours", v: m.durationHours.toFixed(1) }
4317
+ { k: "Session hours (timestamp union)", v: m.durationHours.toFixed(1) }
3832
4318
  ],
3833
4319
  [
3834
4320
  { k: "Pricing snapshot", v: m.pricingSnapshotDate },
@@ -3836,36 +4322,28 @@ function formatAudit(record, meta, color = false) {
3836
4322
  ]
3837
4323
  ];
3838
4324
  for (const row of statRows(statBlock, a)) lines.push(row);
3839
- const unknownNote = unknownModelNote(m.modelBreakdown);
3840
- if (unknownNote) pushProse(lines, unknownNote, 0, a.dim);
4325
+ for (const note of accuracyNotes(record)) pushProse(lines, `Pricing caution: ${note}`, 0, a.dim);
4326
+ if (!shareIsValid) pushProse(lines, "Pricing caution: this legacy record has an invalid cache-miss exposure share; its percentage is unavailable.", 0, a.dim);
3841
4327
  const w = record.usageWindows;
3842
4328
  if (subscription) {
3843
4329
  lines.push("");
3844
4330
  pushProse(
3845
4331
  lines,
3846
- `Plan: ${record.plan}. Dollar figures are API-equivalent token value, not money back; recovering them buys rate-limit headroom (more work per usage window).`,
4332
+ `Plan: ${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.`,
3847
4333
  0,
3848
4334
  a.dim
3849
4335
  );
3850
4336
  if (w?.assessed) {
3851
4337
  lines.push(
3852
- `${a.dim("Usage windows (5h, like your rate limit):")} median ${a.bold(usd2(w.medianWindowUsd))}, busiest ${a.bold(usd2(w.p90WindowUsd))}`
4338
+ `${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))}`
3853
4339
  );
3854
- lines.push(`${a.dim("Busiest week:")} ${a.bold(usd2(w.maxWeekUsd))} ${a.dim("(API-equivalent)")}`);
3855
- if (share >= 0.01 && share < 1) {
3856
- const gain = share / (1 - share);
3857
- const extraMinutes = Math.round(w.p90WindowActiveMinutes * gain);
3858
- lines.push("");
3859
- lines.push(
3860
- `Recovering ${shareText} buys about ${a.bold(`${Math.round(gain * 100)}% more work per window`)}:`
3861
- );
3862
- lines.push(` up to ${a.brand(`~${extraMinutes} extra minutes`)} in a window like your busiest.`);
3863
- }
4340
+ lines.push(`${a.dim("Busiest week:")} ${a.bold(usd2(w.maxWeekUsd))} ${a.dim("(estimated current API-equivalent valuation)")}`);
4341
+ lines.push(`${a.dim("Activity signal:")} 15-minute activity bins, not measured work time.`);
3864
4342
  }
3865
4343
  } else if (meta.planSource === "default") {
3866
- const burn = w?.assessed && w.medianWeekUsd >= 50 ? ` Your median week burns ${usd2(w.medianWeekUsd)} at API rates.` : "";
4344
+ const burn = w?.assessed && w.medianWeekUsd >= 50 ? ` Median weekly estimated current API-equivalent valuation: ${usd2(w.medianWeekUsd)}.` : "";
3867
4345
  lines.push("");
3868
- pushProse(lines, `Dollar figures are API-equivalent rates.${burn}`, 0, a.dim);
4346
+ pushProse(lines, `Dollar figures are estimated current API-equivalent valuations.${burn}`, 0, a.dim);
3869
4347
  pushProse(
3870
4348
  lines,
3871
4349
  "On a Claude subscription? Rerun with --plan max20x (or pro, max5x) to frame results as token efficiency.",
@@ -3875,7 +4353,7 @@ function formatAudit(record, meta, color = false) {
3875
4353
  }
3876
4354
  if (m.topProjects.length > 0) {
3877
4355
  lines.push("");
3878
- lines.push(a.bold("Top projects by spend:"));
4356
+ lines.push(a.bold("Top projects by estimated current API-equivalent valuation:"));
3879
4357
  for (const p of m.topProjects.slice(0, 5)) {
3880
4358
  const name = p.slug.length > 30 ? p.slug.slice(0, 27) + "..." : p.slug;
3881
4359
  const model = p.modelPrimary ? shortModel(p.modelPrimary) : "n/a";
@@ -3889,7 +4367,7 @@ function formatAudit(record, meta, color = false) {
3889
4367
  const bc = record.burnClock;
3890
4368
  if (bc?.assessed) {
3891
4369
  lines.push("");
3892
- lines.push(a.bold("Burn Clock (spend by day):"));
4370
+ lines.push(a.bold("Burn Clock (estimated current API-equivalent valuation by day):"));
3893
4371
  const max = Math.max(...bc.byDay, 0.01);
3894
4372
  for (const day2 of BURN_DAY_ORDER) {
3895
4373
  const v = bc.byDay[day2];
@@ -3905,7 +4383,7 @@ function formatAudit(record, meta, color = false) {
3905
4383
  }
3906
4384
  lines.push("");
3907
4385
  lines.push(
3908
- `${a.bold("Overall setup score:")} ${a.score(record.overallScore, `${record.overallScore} / 100`)} (${a.score(record.overallScore, record.band.label)})`
4386
+ `${a.bold("Rule-based setup score:")} ${a.score(record.overallScore, `${record.overallScore} / 100`)} (${a.score(record.overallScore, record.band.label)}; not an Anthropic grade)`
3909
4387
  );
3910
4388
  for (const p of record.pillarScores) {
3911
4389
  lines.push(` ${p.name.padEnd(22)} ${bar(p.score, a)}`);
@@ -3913,13 +4391,13 @@ function formatAudit(record, meta, color = false) {
3913
4391
  lines.push("");
3914
4392
  const dollarFixes = record.fixes.filter((f) => f.wasteUsd > 0);
3915
4393
  const otherIssues = record.fixes.filter((f) => f.wasteUsd === 0);
3916
- lines.push(a.bold("Top fixes by recoverable spend:"));
4394
+ lines.push(a.bold("Top changes ranked by estimated cache-miss exposure:"));
3917
4395
  if (dollarFixes.length === 0) {
3918
- lines.push(" No directly recoverable dollars found. See issues below.");
4396
+ lines.push(" No cache-miss exposure estimate found. See issues below.");
3919
4397
  } else {
3920
4398
  for (const [i, f] of dollarFixes.entries()) {
3921
4399
  if (i > 0) lines.push("");
3922
- lines.push(` - [${a.brand(usd2(f.wasteUsd))}] ${a.bold(f.title)}`);
4400
+ lines.push(` - [${a.brand(usd2(f.wasteUsd))} estimated valuation] ${a.bold(f.title)}`);
3923
4401
  pushProse(lines, f.action, 6);
3924
4402
  if (f.basis) pushProse(lines, `Evidence: ${f.basis}`, 6, a.dim);
3925
4403
  }
@@ -3941,6 +4419,10 @@ function formatAudit(record, meta, color = false) {
3941
4419
  lines.push("");
3942
4420
  lines.push(a.dim(gapLine));
3943
4421
  }
4422
+ lines.push("");
4423
+ const methodology = "Methodology: 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.";
4424
+ const provenance = m.accuracy ? ` Pricing snapshot: ${m.accuracy.pricingSnapshotDate}; accounting method: v${m.accuracy.accountingVersion}.` : "";
4425
+ pushProse(lines, methodology + provenance, 0, a.dim);
3944
4426
  return lines.join("\n");
3945
4427
  }
3946
4428
 
@@ -3972,14 +4454,14 @@ function estimateTextWidth(s, size) {
3972
4454
 
3973
4455
  // src/html-report.ts
3974
4456
  function usd3(n) {
3975
- return `$${(Math.round(n * 100) / 100).toFixed(2)}`;
4457
+ return `$${roundMoneyHalfUp(n).toFixed(2)}`;
3976
4458
  }
3977
4459
  function truncate(s, max) {
3978
4460
  return s.length > max ? s.slice(0, max - 3) + "..." : s;
3979
4461
  }
3980
4462
  function projectChart(projects) {
3981
4463
  if (projects.length === 0) {
3982
- return `<p class="muted">No project spend to chart.</p>`;
4464
+ return `<p class="muted">No project valuation estimate to chart.</p>`;
3983
4465
  }
3984
4466
  const rowH = 28;
3985
4467
  const gap = 8;
@@ -3998,7 +4480,7 @@ function projectChart(projects) {
3998
4480
  const label = esc(truncate(p.slug, 30));
3999
4481
  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>`;
4000
4482
  }).join("");
4001
- return `<svg viewBox="0 0 ${width} ${height}" width="100%" height="${height}" role="img" aria-label="Top projects by cost" preserveAspectRatio="xMinYMin meet">${rows}</svg>`;
4483
+ 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>`;
4002
4484
  }
4003
4485
  function burnClockChart(bc) {
4004
4486
  const rowH = 22;
@@ -4019,7 +4501,7 @@ function burnClockChart(bc) {
4019
4501
  const label = esc(BURN_DAY_NAMES[day2]);
4020
4502
  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>`;
4021
4503
  }).join("");
4022
- 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>`;
4504
+ 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>`;
4023
4505
  }
4024
4506
  function pillarBars(pillars) {
4025
4507
  return pillars.map((p) => {
@@ -4057,11 +4539,11 @@ function nextStepsSection(record, meta) {
4057
4539
  steps.push(step(
4058
4540
  n++,
4059
4541
  "Tell costclaw how you pay",
4060
- `<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")
4542
+ `<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")
4061
4543
  ));
4062
4544
  }
4063
4545
  const waste = record.headlineWasteUsd;
4064
- const wasteLine = waste > 0 ? `This audit found <strong>${esc(usd3(waste))}</strong> of recoverable input spend. ` : "";
4546
+ const wasteLine = waste > 0 ? `This audit estimates <strong>${esc(usd3(waste))}</strong> of cache-miss exposure at current API list prices. ` : "";
4065
4547
  if (licensed) {
4066
4548
  const who = meta.license?.email ? ` (${esc(meta.license.email)})` : "";
4067
4549
  steps.push(step(
@@ -4079,7 +4561,7 @@ function nextStepsSection(record, meta) {
4079
4561
  steps.push(step(
4080
4562
  n++,
4081
4563
  "Track the movement",
4082
- `<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")
4564
+ `<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")
4083
4565
  ));
4084
4566
  steps.push(step(
4085
4567
  n++,
@@ -4252,30 +4734,25 @@ table.ref td:first-child { white-space: nowrap; color: var(--umber); font-size:
4252
4734
  function renderHtml(record, meta) {
4253
4735
  const m = record.usageMetrics;
4254
4736
  const mix = modelMix(m.modelBreakdown);
4255
- const unknownNote = unknownModelNote(m.modelBreakdown);
4737
+ const accuracyNotesForRecord = accuracyNotes(record);
4256
4738
  const mixCells = mix ? mix.split(" / ").map((part) => `<span class="nb">${esc(part)}</span>`).join(" / ") : "";
4257
4739
  const subscription = record.plan !== void 0 && record.plan !== "api";
4258
- const share = record.headlineWasteShare ?? (m.spendUsd > 0 ? record.headlineWasteUsd / m.spendUsd : 0);
4259
- const shareText = `${(share * 100).toFixed(1)}%`;
4260
- 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>`;
4261
- const spendLabel = subscription ? "Usage analyzed (API-equivalent)" : "Spend analyzed";
4740
+ const reportedShare = record.headlineWasteShare ?? (m.spendUsd > 0 ? record.headlineWasteUsd / m.spendUsd : 0);
4741
+ const shareIsValid = Number.isFinite(reportedShare) && reportedShare >= 0 && reportedShare <= 1;
4742
+ const shareText = shareIsValid ? `${(reportedShare * 100).toFixed(1)}%` : "unavailable";
4743
+ 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>`;
4744
+ const spendLabel = "Current API-equivalent valuation (estimate)";
4262
4745
  const w = record.usageWindows;
4263
- let headroom = "";
4264
- if (subscription && w?.assessed && share >= 0.01 && share < 1) {
4265
- const gain = share / (1 - share);
4266
- const extraMinutes = Math.round(w.p90WindowActiveMinutes * gain);
4267
- headroom = ` Recovering ${shareText} buys about ${Math.round(gain * 100)}% more work per window: up to ~${extraMinutes} extra minutes in a window like your busiest.`;
4268
- }
4269
- const weeklyBurn = !subscription && meta.planSource === "default" && w?.assessed && w.medianWeekUsd >= 50 ? ` Your median week burns ${esc(usd3(w.medianWeekUsd))} at API rates.` : "";
4270
- 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>` : "";
4271
- 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>` : "";
4746
+ const weeklyBurn = !subscription && meta.planSource === "default" && w?.assessed && w.medianWeekUsd >= 50 ? ` Median weekly estimated current API-equivalent valuation: ${esc(usd3(w.medianWeekUsd))}.` : "";
4747
+ 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>` : "";
4748
+ 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>` : "";
4272
4749
  const dollarFixes = record.fixes.filter((f) => f.wasteUsd > 0).sort((a, b) => b.wasteUsd - a.wasteUsd);
4273
4750
  const otherIssues = record.fixes.filter((f) => f.wasteUsd === 0);
4274
- 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>`;
4751
+ const dollarSection = dollarFixes.length === 0 ? `<p class="muted">No cache-miss exposure estimate found. See issues below.</p>` : `<ul class="fixes">${dollarFixes.map(dollarFixCard).join("")}</ul>`;
4275
4752
  const otherSection = otherIssues.length === 0 ? "" : `<h2>Other issues to tighten</h2><ul class="fixes">${otherIssues.map(otherFixCard).join("")}</ul>`;
4276
4753
  const bc = record.burnClock;
4277
4754
  const burnSentence = bc?.assessed ? burnClockSentence(bc) : null;
4278
- const burnSection = bc?.assessed ? `<h2>Burn Clock (spend by day)</h2>
4755
+ const burnSection = bc?.assessed ? `<h2>Burn Clock (estimated current API-equivalent valuation by day)</h2>
4279
4756
  <div class="chart">${burnClockChart(bc)}</div>
4280
4757
  ` + (burnSentence ? `<p class="sub">${esc(burnSentence)}</p>
4281
4758
  ` : "") : "";
@@ -4309,28 +4786,33 @@ ${planNote}
4309
4786
  <div class="stats">
4310
4787
  <div class="stat"><div class="k">${spendLabel}</div><div class="v">${esc(usd3(m.spendUsd))}</div></div>
4311
4788
  <div class="stat"><div class="k">Cache hit rate</div><div class="v">${(m.cacheHitRate * 100).toFixed(1)}%</div></div>
4312
- <div class="stat"><div class="k">Active hours</div><div class="v">${m.durationHours.toFixed(1)}</div></div>
4789
+ <div class="stat"><div class="k">Session hours (timestamp union)</div><div class="v">${m.durationHours.toFixed(1)}</div></div>
4313
4790
  ${mix ? `<div class="stat"><div class="k">Model spend</div><div class="v v-small">${mixCells}</div></div>` : ""}
4314
4791
  </div>
4315
- ${unknownNote ? `<p class="meta">${esc(unknownNote)}</p>` : ""}
4792
+ ${accuracyNotesForRecord.map((note) => `<p class="meta">${esc(`Pricing caution: ${note}`)}</p>`).join("\n")}
4793
+ ${!shareIsValid ? `<p class="meta">Pricing caution: this legacy record has an invalid cache-miss exposure share; its percentage is unavailable.</p>` : ""}
4316
4794
  ${windowTiles}
4317
4795
 
4318
- <h2>Spend by project</h2>
4796
+ <h2>Projects by estimated current API-equivalent valuation</h2>
4319
4797
  <div class="chart">${projectChart(m.topProjects)}</div>
4320
4798
 
4321
4799
  ${burnSection}
4322
- <h2>Setup score</h2>
4800
+ <h2>Rule-based setup score</h2>
4323
4801
  <div class="score-head">
4324
4802
  <span class="big">${record.overallScore} / 100</span>
4325
4803
  <span class="band">${esc(record.band.label)}</span>
4326
4804
  </div>
4805
+ <p class="sub">A transparent heuristic from observed setup signals, not an Anthropic grade.</p>
4327
4806
  ${pillarBars(record.pillarScores)}
4328
4807
 
4329
- <h2>Top fixes by recoverable spend</h2>
4808
+ <h2>Top changes ranked by estimated cache-miss exposure</h2>
4330
4809
  ${dollarSection}
4331
4810
  ${otherSection}
4332
4811
  ${skippedNote}
4333
4812
 
4813
+ <h2>Methodology</h2>
4814
+ <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>
4815
+
4334
4816
  ${nextStepsSection(record, meta)}
4335
4817
 
4336
4818
  <div class="footer">
@@ -4353,7 +4835,7 @@ var PAPER = "#fefaf7";
4353
4835
  var BORDER = "#f0e2da";
4354
4836
  var MUTED = "#7a6a63";
4355
4837
  function usd4(n) {
4356
- return `$${(Math.round(n * 100) / 100).toFixed(2)}`;
4838
+ return `$${roundMoneyHalfUp(n).toFixed(2)}`;
4357
4839
  }
4358
4840
  function strongestPillar(pillars) {
4359
4841
  const assessed = pillars.filter((p) => p.assessed && p.score !== null);
@@ -4367,9 +4849,10 @@ function renderCard(record) {
4367
4849
  const cacheHitPct = `${(record.usageMetrics.cacheHitRate * 100).toFixed(1)}%`;
4368
4850
  const subscription = record.plan !== void 0 && record.plan !== "api";
4369
4851
  const spend = record.usageMetrics.spendUsd;
4370
- const share = record.headlineWasteShare ?? (spend > 0 ? record.headlineWasteUsd / spend : 0);
4371
- const wasteLine = subscription ? `Recoverable usage: ${(share * 100).toFixed(1)}%` : `Recoverable spend: ${usd4(record.headlineWasteUsd)}`;
4372
- const ariaLabel = `CostClaw score ${record.overallScore} of 100, ${record.band.label}`;
4852
+ const reportedShare = record.headlineWasteShare ?? (spend > 0 ? record.headlineWasteUsd / spend : 0);
4853
+ const shareIsValid = Number.isFinite(reportedShare) && reportedShare >= 0 && reportedShare <= 1;
4854
+ const wasteLine = subscription ? `Cache-miss exposure: ${shareIsValid ? `${(reportedShare * 100).toFixed(1)}%` : "unavailable"}` : `Cache-miss exposure: ${usd4(record.headlineWasteUsd)} estimate`;
4855
+ const ariaLabel = `CostClaw rule-based setup score ${record.overallScore} of 100, ${record.band.label}`;
4373
4856
  const scoreText = String(record.overallScore);
4374
4857
  const scoreX = 32;
4375
4858
  const scoreW = estimateTextWidth(scoreText, 72);
@@ -4589,8 +5072,8 @@ async function deactivateLicense(opts = {}) {
4589
5072
  // src/plan-prompt.ts
4590
5073
  import { createInterface } from "readline/promises";
4591
5074
  var PLAN_PROMPT_LINES = [
4592
- "How do you pay for Claude Code? This decides whether the report talks in",
4593
- "dollars or in rate-limit headroom.",
5075
+ "How do you pay for Claude Code? This adds the right caveat to the report's",
5076
+ "estimated current API-equivalent valuations.",
4594
5077
  "",
4595
5078
  " 1) API, pay per token",
4596
5079
  " 2) Pro subscription",
@@ -4717,6 +5200,7 @@ async function runAudit(opts) {
4717
5200
  questionnaire: {},
4718
5201
  setup,
4719
5202
  plan,
5203
+ timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
4720
5204
  tzOffsetMinutes: -(/* @__PURE__ */ new Date()).getTimezoneOffset()
4721
5205
  });
4722
5206
  const baseline = (await readCliConfig(configDir)).lastOptimize;
@@ -5059,7 +5543,7 @@ function approxTokens(n) {
5059
5543
  function plural2(n, noun) {
5060
5544
  return n === 1 ? noun : `${noun}s`;
5061
5545
  }
5062
- function num5(n) {
5546
+ function num4(n) {
5063
5547
  return String(Math.round(n)).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
5064
5548
  }
5065
5549
  var STYLE2 = `
@@ -5297,7 +5781,7 @@ function renderSectionsStat(sections) {
5297
5781
  }
5298
5782
  function renderRecoverableStat(input) {
5299
5783
  const pct2 = `${(input.headlineWasteShare * 100).toFixed(1)}%`;
5300
- 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>`;
5784
+ 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>`;
5301
5785
  }
5302
5786
  function renderReceipt(input) {
5303
5787
  const stats = `<div class="grid g3">${renderTokenStat(input)}${renderSectionsStat(input.sectionDispositions)}${renderRecoverableStat(input)}</div>`;
@@ -5330,11 +5814,11 @@ function renderCacheTable2(report) {
5330
5814
  const tailUsd = tail.reduce((sum, r) => sum + r.usd, 0);
5331
5815
  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>`;
5332
5816
  }
5333
- 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>`;
5817
+ 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>`;
5334
5818
  }
5335
5819
  function renderFixes(fixes, report) {
5336
5820
  const dollarFixes = fixes.filter((f) => f.wasteUsd > 0).sort((a, b) => b.wasteUsd - a.wasteUsd);
5337
- if (dollarFixes.length === 0) return `<p class="note">No directly recoverable dollars found.</p>`;
5821
+ if (dollarFixes.length === 0) return `<p class="note">No cache-miss exposure estimate found.</p>`;
5338
5822
  return dollarFixes.map((f, i) => {
5339
5823
  const table = f.id === "cache_recovery" ? renderCacheTable2(report) : "";
5340
5824
  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>`;
@@ -5398,7 +5882,7 @@ function renderCarriedDisclosure(sections, carriedTokens) {
5398
5882
  const carried = sections.filter((s) => s.disposition === "carried");
5399
5883
  if (carried.length === 0) return "";
5400
5884
  const names = carried.map((s) => esc(s.name)).join(" &middot; ");
5401
- const weight = carriedTokens > 0 ? `, about ${num5(carriedTokens)} tokens` : "";
5885
+ const weight = carriedTokens > 0 ? `, about ${num4(carriedTokens)} tokens` : "";
5402
5886
  const note = carriedTokens > 0 ? `<p class="note">Carried through as written. costclaw does not rewrite your prose, so this is where the remaining weight sits. HARNESS-UPGRADE.md ranks these sections and flags their dated lines for you to move into docs/.</p>` : "";
5403
5887
  return `<details style="margin-top:34px"><summary>All ${carried.length} ${plural2(carried.length, "section")} carried across from your existing CLAUDE.md${weight}</summary><div class="cols">${names}</div>${note}</details>`;
5404
5888
  }
@@ -5429,7 +5913,7 @@ ${renderReceipt(input)}
5429
5913
  <h2>Your CLAUDE.md, before and after<span class="n">what actually changed</span></h2>
5430
5914
  <div class="panel">${renderComparisonTabs(input)}</div>
5431
5915
  ${input.review ? `
5432
- <h2>What to change in your CLAUDE.md<span class="n">${num5(input.review.changes.length)} proposed ${plural2(input.review.changes.length, "change")}</span></h2>
5916
+ <h2>What to change in your CLAUDE.md<span class="n">${num4(input.review.changes.length)} proposed ${plural2(input.review.changes.length, "change")}</span></h2>
5433
5917
  <div class="panel">${renderAnnotatedFile(input.review)}</div>` : ""}
5434
5918
 
5435
5919
  <h2>Fixes, ranked by what they recover</h2>
@@ -5497,7 +5981,7 @@ function renderLines(lines, keepRunMax) {
5497
5981
  const tail = run.slice(run.length - half);
5498
5982
  for (const i of head) out.push(lineHtml(lines[i], i + 1));
5499
5983
  out.push(
5500
- `<span class="ln skip"><span class="g"></span>... ${num5(run.length - head.length - tail.length)} unchanged lines ...</span>`
5984
+ `<span class="ln skip"><span class="g"></span>... ${num4(run.length - head.length - tail.length)} unchanged lines ...</span>`
5501
5985
  );
5502
5986
  for (const i of tail) out.push(lineHtml(lines[i], i + 1));
5503
5987
  } else {
@@ -5531,7 +6015,7 @@ function renderAnnotatedFile(review) {
5531
6015
  function reviewCountLine(review) {
5532
6016
  const n = review.changes.length;
5533
6017
  if (n === 0) return `No changes proposed for ${esc(review.label)}.`;
5534
- return `<b>${num5(n)} proposed ${plural2(n, "change")}</b> to ${esc(review.label)}`;
6018
+ return `<b>${num4(n)} proposed ${plural2(n, "change")}</b> to ${esc(review.label)}`;
5535
6019
  }
5536
6020
  var INDEX_STYLE = `
5537
6021
  .rowpath{display:block;font-size:.76rem;color:var(--ink2);font-family:var(--mono);word-break:break-all}
@@ -5572,8 +6056,8 @@ function renderPromptPanel(review) {
5572
6056
  function renderGlobalPanel(review) {
5573
6057
  const t = review.tokens;
5574
6058
  const importCount = review.importCount;
5575
- const imported = importCount > 0 ? ` plus ${num5(importCount)} imported ${plural2(importCount, "file")}` : "";
5576
- const weight = `<p class="revhead"><b>${esc(review.label)}</b>${imported}: about ${num5(t.total)} tokens on every turn of every project, about ${num5(t.afterChanges)} after these changes. ${reviewCountLine(review)}.</p>`;
6059
+ const imported = importCount > 0 ? ` plus ${num4(importCount)} imported ${plural2(importCount, "file")}` : "";
6060
+ const weight = `<p class="revhead"><b>${esc(review.label)}</b>${imported}: about ${num4(t.total)} tokens on every turn of every project, about ${num4(t.afterChanges)} after these changes. ${reviewCountLine(review)}.</p>`;
5577
6061
  return `<div class="panel">${weight}${renderAnnotatedFile(review)}</div>`;
5578
6062
  }
5579
6063
  function renderProjectPanels(input, review) {
@@ -5582,7 +6066,7 @@ function renderProjectPanels(input, review) {
5582
6066
  const r = review.projects.get(row.slug);
5583
6067
  if (!r) return;
5584
6068
  out.push(
5585
- `<details${i === 0 ? " open" : ""}><summary>${esc(row.slug)}: ${num5(r.changes.length)} proposed ${plural2(r.changes.length, "change")}</summary><div class="panel" style="margin-top:10px"><p class="revhead">${reviewCountLine(r)}. About ${num5(r.tokens.total)} tokens per turn, about ${num5(r.tokens.afterChanges)} after these changes.</p>` + renderAnnotatedFile(r) + `<div style="margin-top:14px">${indexActions(row, input.serve)}</div></div></details>`
6069
+ `<details${i === 0 ? " open" : ""}><summary>${esc(row.slug)}: ${num4(r.changes.length)} proposed ${plural2(r.changes.length, "change")}</summary><div class="panel" style="margin-top:10px"><p class="revhead">${reviewCountLine(r)}. About ${num4(r.tokens.total)} tokens per turn, about ${num4(r.tokens.afterChanges)} after these changes.</p>` + renderAnnotatedFile(r) + `<div style="margin-top:14px">${indexActions(row, input.serve)}</div></div></details>`
5586
6070
  );
5587
6071
  });
5588
6072
  return out.join("");
@@ -5593,7 +6077,7 @@ function renderOptimizeIndex(input) {
5593
6077
  const rows = input.rows.map(
5594
6078
  (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>`
5595
6079
  ).join("");
5596
- 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>`;
6080
+ 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>`;
5597
6081
  const banner = input.serve?.message ? `<p class="banner">${esc(input.serve.message)}</p>` : "";
5598
6082
  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>` : "";
5599
6083
  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>`;
@@ -5610,7 +6094,7 @@ ${input.review ? `<script>${COPY_SCRIPT}</script>` : ""}
5610
6094
  <div class="wrap">
5611
6095
  <header><p class="kicker">CostClaw optimize &middot; generated locally &middot; nothing left your machine</p>
5612
6096
  <h1>${input.rows.length} ${plural2(input.rows.length, "project")} ready to apply</h1>
5613
- <p class="sub">${esc(usd5(total))} of analyzed spend &middot; ${esc(usd5(recoverable))} recoverable &middot;
6097
+ <p class="sub">${esc(usd5(total))} estimated current API-equivalent valuation &middot; ${esc(usd5(recoverable))} cache-miss exposure estimate &middot;
5614
6098
  artifacts in ${esc(input.root)}/</p></header>
5615
6099
 
5616
6100
  ${banner}${done}
@@ -6453,7 +6937,7 @@ var DEFAULT_LIMIT = 10;
6453
6937
  function usd6(n) {
6454
6938
  return `$${(Math.round(n * 100) / 100).toFixed(2)}`;
6455
6939
  }
6456
- function num6(n) {
6940
+ function num5(n) {
6457
6941
  return String(Math.round(n)).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
6458
6942
  }
6459
6943
  function describeDetection(project) {
@@ -6494,10 +6978,10 @@ async function generateForProject(ctx, projectDir, artifactsDir) {
6494
6978
  let currentClaudeMd = ctx.claudeMdOverride;
6495
6979
  let claudeMdSource = ctx.claudeMdOverride !== void 0 ? ctx.claudeMdFallbackSource : null;
6496
6980
  if (currentClaudeMd === void 0) {
6497
- const own = join10(projectDir, "CLAUDE.md");
6498
- if (await pathExists2(own)) {
6499
- currentClaudeMd = await readFile10(own, "utf8");
6500
- claudeMdSource = own;
6981
+ const own2 = join10(projectDir, "CLAUDE.md");
6982
+ if (await pathExists2(own2)) {
6983
+ currentClaudeMd = await readFile10(own2, "utf8");
6984
+ claudeMdSource = own2;
6501
6985
  }
6502
6986
  }
6503
6987
  const project = await scanProject(projectDir);
@@ -6559,11 +7043,11 @@ async function generateForProject(ctx, projectDir, artifactsDir) {
6559
7043
  const denominator = recoverable !== null ? spend ?? 0 : ctx.report.summary.cost_usd;
6560
7044
  const scopeLabel = recoverable !== null ? `for ${slug}` : "across your audited projects";
6561
7045
  if (ctx.plan === "api") {
6562
- lines.push(`Recoverable spend (cache-miss exposure) ${scopeLabel}: ${usd6(shownRecoverable)}`);
7046
+ lines.push(`Cache-miss exposure (estimate) ${scopeLabel}: ${usd6(shownRecoverable)} estimated current API-equivalent valuation`);
6563
7047
  } else {
6564
7048
  const share = denominator > 0 ? shownRecoverable / denominator * 100 : 0;
6565
7049
  lines.push(
6566
- `Recoverable usage (cache-miss exposure) ${scopeLabel}: ${share.toFixed(1)}% of analyzed usage (${usd6(shownRecoverable)} at API rates)`
7050
+ `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)`
6567
7051
  );
6568
7052
  }
6569
7053
  const { before, after } = result.claudeMdTokens;
@@ -6571,11 +7055,11 @@ async function generateForProject(ctx, projectDir, artifactsDir) {
6571
7055
  const pct2 = before > 0 ? (Math.abs(after - before) / before * 100).toFixed(1) : "0.0";
6572
7056
  const dir = after > before ? "larger" : "smaller";
6573
7057
  lines.push(
6574
- `Your CLAUDE.md: an estimated ${num6(before)} tokens to ${num6(after)} (${pct2}% ${dir}), paid on every turn.`
7058
+ `Your CLAUDE.md: an estimated ${num5(before)} tokens to ${num5(after)} (${pct2}% ${dir}), paid on every turn.`
6575
7059
  );
6576
7060
  if (result.carriedTokens >= after / 2) {
6577
7061
  lines.push(
6578
- `About ${num6(result.carriedTokens)} of those tokens are your own prose, carried through as written.`,
7062
+ `About ${num5(result.carriedTokens)} of those tokens are your own prose, carried through as written.`,
6579
7063
  "costclaw does not rewrite prose, so trimming it is judgment work: HARNESS-UPGRADE.md",
6580
7064
  "ranks your heaviest sections and flags the dated lines to move into docs/."
6581
7065
  );
@@ -6590,7 +7074,7 @@ async function generateForProject(ctx, projectDir, artifactsDir) {
6590
7074
  for (const note of result.notes) lines.push(` - ${note}`);
6591
7075
  if (review.changes.length > 0) {
6592
7076
  const n = review.changes.length;
6593
- lines.push(`Review: ${num6(n)} proposed ${n === 1 ? "change" : "changes"} to ${review.label}`);
7077
+ lines.push(`Review: ${num5(n)} proposed ${n === 1 ? "change" : "changes"} to ${review.label}`);
6594
7078
  }
6595
7079
  lines.push(`Artifacts: ${artifactsDir}`);
6596
7080
  lines.push(`Apply: ${applyCommand}`);
@@ -6618,8 +7102,8 @@ async function runOptimize(opts) {
6618
7102
  const home = opts.home ?? homedir5();
6619
7103
  let inputsClaudeMdPath = opts.claudeMdPath;
6620
7104
  if (!inputsClaudeMdPath && opts.projectDir) {
6621
- const own = join10(opts.projectDir, "CLAUDE.md");
6622
- if (await pathExists2(own)) inputsClaudeMdPath = own;
7105
+ const own2 = join10(opts.projectDir, "CLAUDE.md");
7106
+ if (await pathExists2(own2)) inputsClaudeMdPath = own2;
6623
7107
  }
6624
7108
  const { logs, claudeMd, claudeMdSource, projectDirs } = await loadAuditInputs({
6625
7109
  path: opts.path,
@@ -6640,7 +7124,13 @@ async function runOptimize(opts) {
6640
7124
  totals: { ...report.summary.totals },
6641
7125
  cacheHitRate: report.summary.cacheHitRate,
6642
7126
  headlineWasteShare: baselineSpend > 0 ? auditRecoverable / baselineSpend : 0,
6643
- spendUsd: baselineSpend
7127
+ spendUsd: baselineSpend,
7128
+ ...report.summary.accuracy ? {
7129
+ accuracy: {
7130
+ pricingSnapshotDate: report.summary.accuracy.pricingSnapshotDate,
7131
+ accountingVersion: report.summary.accuracy.accountingVersion
7132
+ }
7133
+ } : {}
6644
7134
  }
6645
7135
  });
6646
7136
  const single = opts.projectDir !== void 0;
@@ -6783,7 +7273,7 @@ async function runOptimize(opts) {
6783
7273
  const projectChanges = outcomes.reduce((sum, o) => sum + o.review.changes.length, 0);
6784
7274
  lines.push("");
6785
7275
  lines.push(
6786
- `Your CLAUDE.md review: ${num6(globalReview.changes.length)} ${globalReview.changes.length === 1 ? "change" : "changes"} to ${globalLabel}, ${num6(projectChanges)} across your ${outcomes.length === 1 ? "project" : "projects"}.`
7276
+ `Your CLAUDE.md review: ${num5(globalReview.changes.length)} ${globalReview.changes.length === 1 ? "change" : "changes"} to ${globalLabel}, ${num5(projectChanges)} across your ${outcomes.length === 1 ? "project" : "projects"}.`
6787
7277
  );
6788
7278
  lines.push("One prompt applies all of it. Hand this to your own Claude Code:");
6789
7279
  lines.push(` claude "Follow ${upgradeAllPath}"`);
@@ -6872,7 +7362,7 @@ import { homedir as homedir6 } from "os";
6872
7362
 
6873
7363
  // src/format-diff.ts
6874
7364
  function usd7(n) {
6875
- return `$${(Math.round(Math.abs(n) * 100) / 100).toFixed(2)}`;
7365
+ return `$${roundMoneyHalfUp(Math.abs(n)).toFixed(2)}`;
6876
7366
  }
6877
7367
  function signedUsd(n) {
6878
7368
  return `${n < 0 ? "-" : "+"}${usd7(n)}`;
@@ -6896,28 +7386,36 @@ function formatDiff(d) {
6896
7386
  if (d.comparable && d.marginal) {
6897
7387
  lines.push("Since the baseline:");
6898
7388
  lines.push(
6899
- ` New spend ${usd7(d.marginal.newSpendUsd)} across ${d.marginal.newSessions} new sessions`
7389
+ ` New valuation (estimate) ${usd7(d.marginal.newSpendUsd)} across ${d.marginal.newSessions} new sessions`
6900
7390
  );
6901
7391
  lines.push(
6902
7392
  ` Marginal cache hit ${pct(d.marginal.marginalCacheHitRate)} (lifetime ${pct(d.current.cacheHitRate)})`
6903
7393
  );
6904
7394
  lines.push(
6905
- ` Recoverable exposure ${signedUsd(d.deltas.recoverableUsd)} (now ${usd7(d.current.recoverableUsd)})`
7395
+ ` Cache-miss exposure (estimate) ${signedUsd(d.deltas.recoverableUsd)} (now ${usd7(d.current.recoverableUsd)})`
6906
7396
  );
6907
7397
  } else {
6908
- lines.push("Note: the current audit covers less history than the baseline (logs moved or");
6909
- lines.push("pruned), so period metrics are omitted.");
7398
+ if (d.comparisonReason === "accounting changed") {
7399
+ lines.push("Note: the accounting method changed between audits, so period metrics are omitted.");
7400
+ lines.push("The difference may include accounting corrections and is not new usage.");
7401
+ } else if (d.comparisonReason === "pricing changed") {
7402
+ lines.push("Note: the pricing snapshot changed between audits, so period metrics are omitted.");
7403
+ lines.push("The difference may include repricing and is not new usage.");
7404
+ } else {
7405
+ lines.push("Note: the current audit covers less history than the baseline (logs moved or");
7406
+ lines.push("pruned), so period metrics are omitted.");
7407
+ }
6910
7408
  lines.push("");
6911
7409
  lines.push(
6912
- `Baseline (${day(d.baseline.createdAt)}): spend ${usd7(d.baseline.spendUsd)}, cache hit ${pct(d.baseline.cacheHitRate)}, recoverable ${usd7(d.baseline.recoverableUsd)}`
7410
+ `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)}`
6913
7411
  );
6914
7412
  lines.push(
6915
- `Current (${day(d.current.createdAt)}): spend ${usd7(d.current.spendUsd)}, cache hit ${pct(d.current.cacheHitRate)}, recoverable ${usd7(d.current.recoverableUsd)}`
7413
+ `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)}`
6916
7414
  );
6917
7415
  }
6918
7416
  lines.push("");
6919
7417
  lines.push(
6920
- `Overall setup score: ${d.baseline.overallScore} -> ${d.current.overallScore} (${signedInt(d.deltas.overallScore)}, ${d.current.band})`
7418
+ `Rule-based setup score: ${d.baseline.overallScore} -> ${d.current.overallScore} (${signedInt(d.deltas.overallScore)}, ${d.current.band}; not an Anthropic grade)`
6921
7419
  );
6922
7420
  for (const p of d.pillars) {
6923
7421
  const before = p.before === null ? "n/a" : String(p.before);
@@ -6928,27 +7426,29 @@ function formatDiff(d) {
6928
7426
  if (d.current.plan && d.current.plan !== "api") {
6929
7427
  lines.push("");
6930
7428
  lines.push(
6931
- `Plan: ${d.current.plan}. Dollar figures are API-equivalent token value on your subscription; recovering them buys rate-limit headroom, not money back.`
7429
+ `Plan: ${d.current.plan}. Dollar figures are estimated current API-equivalent valuations, not money back, actual quota, or a promise of more work.`
6932
7430
  );
6933
7431
  }
6934
7432
  const { resolved, appeared, changed } = d.fixes;
6935
7433
  if (resolved.length > 0) {
6936
7434
  lines.push("");
6937
7435
  lines.push("Fixes resolved since the baseline:");
6938
- for (const f of resolved) lines.push(` - [${usd7(f.wasteUsd)}] ${f.title}`);
7436
+ for (const f of resolved) lines.push(` - [${usd7(f.wasteUsd)} estimated valuation] ${f.title}`);
6939
7437
  }
6940
7438
  if (appeared.length > 0) {
6941
7439
  lines.push("");
6942
7440
  lines.push("New since the baseline:");
6943
- for (const f of appeared) lines.push(` - [${usd7(f.wasteUsd)}] ${f.title}`);
7441
+ for (const f of appeared) lines.push(` - [${usd7(f.wasteUsd)} estimated valuation] ${f.title}`);
6944
7442
  }
6945
7443
  if (changed.length > 0) {
6946
7444
  lines.push("");
6947
7445
  lines.push("Fixes that moved:");
6948
7446
  for (const c of changed) {
6949
- lines.push(` - ${c.title}: ${usd7(c.beforeUsd)} -> ${usd7(c.afterUsd)} (${signedUsd(c.deltaUsd)})`);
7447
+ lines.push(` - ${c.title}: ${usd7(c.beforeUsd)} -> ${usd7(c.afterUsd)} (${signedUsd(c.deltaUsd)} estimated valuation)`);
6950
7448
  }
6951
7449
  }
7450
+ lines.push("");
7451
+ 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.");
6952
7452
  return lines.join("\n");
6953
7453
  }
6954
7454
 
@@ -7054,7 +7554,7 @@ function parseApplyFlags(args) {
7054
7554
  };
7055
7555
  }
7056
7556
  function cliVersion() {
7057
- return true ? "0.12.2" : "0.0.0-dev";
7557
+ return true ? "0.12.4" : "0.0.0-dev";
7058
7558
  }
7059
7559
  function isHelpRequest(command, args) {
7060
7560
  if (command === void 0) return false;
@@ -7082,17 +7582,17 @@ function helpText() {
7082
7582
  "and opens it in your browser; --no-html skips that, --html <file> picks the",
7083
7583
  "path, and --json runs stay file-free unless --html is passed explicitly.",
7084
7584
  "--card writes a shareable 600x315 score card SVG (default: costclaw-card.svg):",
7085
- "score, band, recoverable spend, cache hit rate, and your strongest pillar.",
7585
+ "rule-based setup score, band, cache-miss exposure estimate, cache hit rate, and your strongest pillar.",
7086
7586
  "--plan <api|pro|max5x|max20x> declares how you pay for Claude. On a",
7087
- "subscription (Pro/Max) the dollar figures are API-equivalent token value, not",
7088
- "money back, so the audit reframes the headline as recoverable usage: the share",
7089
- "of your token consumption (and rate-limit headroom) you could win back. The",
7090
- "value is saved to ~/.costclaw/config.json so later runs remember it;",
7587
+ "subscription (Pro/Max) every dollar figure is an estimated current API-equivalent",
7588
+ "valuation, not money back, actual quota, or a promise of more work. Cache-miss",
7589
+ "exposure is a counterfactual: cold and unique inputs cannot all be cached. The",
7590
+ "plan is saved to ~/.costclaw/config.json so later runs remember it;",
7091
7591
  "--plan api switches back. Pass nothing and the first interactive run asks",
7092
7592
  "once and saves the answer; piped, --json and CI runs are never asked and",
7093
7593
  "assume API rates.",
7094
7594
  "",
7095
- "diff compares two audits and shows the movement: new spend since the baseline,",
7595
+ "diff compares two audits and shows the movement: new valuation estimates since the baseline,",
7096
7596
  "the marginal cache hit rate for just that period, score changes per pillar, and",
7097
7597
  "which fixes were resolved. Every audit run saves a snapshot to",
7098
7598
  "~/.costclaw/history, so plain `costclaw diff` compares your latest two runs;",