costclaw 0.12.3 → 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.
- package/README.md +327 -326
- package/dist/index.js +769 -270
- package/package.json +47 -47
package/dist/index.js
CHANGED
|
@@ -16,68 +16,214 @@ function isPlan(value) {
|
|
|
16
16
|
|
|
17
17
|
// ../../packages/engine/src/pricing.ts
|
|
18
18
|
var PRICING_SNAPSHOT_DATE = "2026-09-14";
|
|
19
|
+
var INVALID_USAGE_WARNING = "Invalid usage counters were ignored.";
|
|
20
|
+
var CACHE_SPLIT_CONFLICT_WARNING = "Conflicting cache-write totals were valued from the documented top-level total at the conservative one-hour rate.";
|
|
21
|
+
var CACHE_TTL_ASSUMED_WARNING = "Cache writes without TTL metadata were estimated at the standard five-minute rate.";
|
|
22
|
+
var CACHE_TTL_FALLBACK_WARNING = "Cache writes with unusable TTL metadata were conservatively estimated at the one-hour rate.";
|
|
23
|
+
var UNSUPPORTED_PRICING_WARNING = "Unsupported pricing metadata was ignored and standard current rates were used.";
|
|
19
24
|
var PRICES_PER_MTOK = Object.freeze({
|
|
20
|
-
"claude-fable-5-1": { input: 10, output: 50, cache_write: 12.5, cache_read: 0.25 },
|
|
21
|
-
"claude-fable-5": { input: 10, output: 50, cache_write: 12.5, cache_read: 1 },
|
|
22
|
-
"claude-
|
|
23
|
-
"claude-
|
|
24
|
-
"claude-
|
|
25
|
-
"claude-opus-4-
|
|
26
|
-
"claude-
|
|
27
|
-
"claude-opus-4-
|
|
28
|
-
"claude-
|
|
29
|
-
"claude-
|
|
30
|
-
"claude-
|
|
31
|
-
"claude-
|
|
25
|
+
"claude-fable-5-1": { input: 10, output: 50, cache_write: 12.5, cache_write_1h: 20, cache_read: 0.25 },
|
|
26
|
+
"claude-fable-5": { input: 10, output: 50, cache_write: 12.5, cache_write_1h: 20, cache_read: 1 },
|
|
27
|
+
"claude-mythos-5-1": { input: 10, output: 50, cache_write: 12.5, cache_write_1h: 20, cache_read: 0.25 },
|
|
28
|
+
"claude-mythos-5": { input: 10, output: 50, cache_write: 12.5, cache_write_1h: 20, cache_read: 1 },
|
|
29
|
+
"claude-opus-5": { input: 5, output: 25, cache_write: 6.25, cache_write_1h: 10, cache_read: 0.5 },
|
|
30
|
+
"claude-opus-4-8": { input: 5, output: 25, cache_write: 6.25, cache_write_1h: 10, cache_read: 0.5 },
|
|
31
|
+
"claude-sonnet-5": { input: 2, output: 10, cache_write: 2.5, cache_write_1h: 4, cache_read: 0.2 },
|
|
32
|
+
"claude-opus-4-7": { input: 5, output: 25, cache_write: 6.25, cache_write_1h: 10, cache_read: 0.5 },
|
|
33
|
+
"claude-opus-4-7[1m]": { input: 5, output: 25, cache_write: 6.25, cache_write_1h: 10, cache_read: 0.5 },
|
|
34
|
+
"claude-opus-4-6": { input: 5, output: 25, cache_write: 6.25, cache_write_1h: 10, cache_read: 0.5 },
|
|
35
|
+
"claude-opus-4-5": { input: 5, output: 25, cache_write: 6.25, cache_write_1h: 10, cache_read: 0.5 },
|
|
36
|
+
"claude-opus-4-1": { input: 15, output: 75, cache_write: 18.75, cache_write_1h: 30, cache_read: 1.5 },
|
|
37
|
+
"claude-opus-4": { input: 15, output: 75, cache_write: 18.75, cache_write_1h: 30, cache_read: 1.5 },
|
|
38
|
+
"claude-sonnet-4-6": { input: 3, output: 15, cache_write: 3.75, cache_write_1h: 6, cache_read: 0.3 },
|
|
39
|
+
"claude-sonnet-4-5": { input: 3, output: 15, cache_write: 3.75, cache_write_1h: 6, cache_read: 0.3 },
|
|
40
|
+
"claude-sonnet-4": { input: 3, output: 15, cache_write: 3.75, cache_write_1h: 6, cache_read: 0.3 },
|
|
41
|
+
"claude-haiku-4-5": { input: 1, output: 5, cache_write: 1.25, cache_write_1h: 2, cache_read: 0.1 },
|
|
42
|
+
"claude-haiku-4-5-20251001": { input: 1, output: 5, cache_write: 1.25, cache_write_1h: 2, cache_read: 0.1 },
|
|
43
|
+
"claude-haiku-3-5": { input: 0.8, output: 4, cache_write: 1, cache_write_1h: 1.6, cache_read: 0.08 }
|
|
32
44
|
});
|
|
33
|
-
var FALLBACK = { input: 3, output: 15, cache_write: 3.75, cache_read: 0.3 };
|
|
45
|
+
var FALLBACK = { input: 3, output: 15, cache_write: 3.75, cache_write_1h: 6, cache_read: 0.3 };
|
|
46
|
+
function canonicalModel(model) {
|
|
47
|
+
if (!model) return null;
|
|
48
|
+
const noTag = model.replace(/\[[^\]]*\]$/, "");
|
|
49
|
+
return noTag.replace(/-\d{8}$/, "");
|
|
50
|
+
}
|
|
51
|
+
function lookup(model) {
|
|
52
|
+
if (!model) return null;
|
|
53
|
+
return PRICES_PER_MTOK[model] ?? PRICES_PER_MTOK[model.replace(/\[[^\]]*\]$/, "")] ?? PRICES_PER_MTOK[canonicalModel(model) ?? ""] ?? null;
|
|
54
|
+
}
|
|
34
55
|
function priceFor(model) {
|
|
35
56
|
return lookup(model) ?? FALLBACK;
|
|
36
57
|
}
|
|
37
58
|
function isKnownModel(model) {
|
|
38
59
|
return lookup(model) !== null;
|
|
39
60
|
}
|
|
40
|
-
function
|
|
41
|
-
if (!
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
61
|
+
function readCounter(value, present) {
|
|
62
|
+
if (!present) return { value: 0, present: false, invalid: false };
|
|
63
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? { value, present: true, invalid: false } : { value: 0, present: true, invalid: true };
|
|
64
|
+
}
|
|
65
|
+
function own(value, key) {
|
|
66
|
+
return Object.prototype.hasOwnProperty.call(value, key);
|
|
67
|
+
}
|
|
68
|
+
function normalizeUsage(raw) {
|
|
69
|
+
const usage = raw && typeof raw === "object" ? raw : {};
|
|
70
|
+
const warnings = /* @__PURE__ */ new Set();
|
|
71
|
+
const input = readCounter(usage.input_tokens, own(usage, "input_tokens"));
|
|
72
|
+
const output = readCounter(usage.output_tokens, own(usage, "output_tokens"));
|
|
73
|
+
const cacheRead = readCounter(usage.cache_read_input_tokens, own(usage, "cache_read_input_tokens"));
|
|
74
|
+
const cacheTop = readCounter(usage.cache_creation_input_tokens, own(usage, "cache_creation_input_tokens"));
|
|
75
|
+
let splitPresent = false;
|
|
76
|
+
let splitMalformed = false;
|
|
77
|
+
let cache5m = { value: 0, present: false, invalid: false };
|
|
78
|
+
let cache1h = { value: 0, present: false, invalid: false };
|
|
79
|
+
const splitProvided = own(usage, "cache_creation");
|
|
80
|
+
if (splitProvided) {
|
|
81
|
+
if (usage.cache_creation && typeof usage.cache_creation === "object" && !Array.isArray(usage.cache_creation)) {
|
|
82
|
+
const split = usage.cache_creation;
|
|
83
|
+
cache5m = readCounter(split.ephemeral_5m_input_tokens, own(split, "ephemeral_5m_input_tokens"));
|
|
84
|
+
cache1h = readCounter(split.ephemeral_1h_input_tokens, own(split, "ephemeral_1h_input_tokens"));
|
|
85
|
+
splitPresent = cache5m.present || cache1h.present;
|
|
86
|
+
} else {
|
|
87
|
+
splitMalformed = true;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
let invalid = input.invalid || output.invalid || cacheRead.invalid || cacheTop.invalid || cache5m.invalid || cache1h.invalid || splitMalformed;
|
|
91
|
+
if (invalid) warnings.add(INVALID_USAGE_WARNING);
|
|
92
|
+
const validSplitSum = cache5m.value + cache1h.value;
|
|
93
|
+
let creationTotal = 0;
|
|
94
|
+
let creation5m = 0;
|
|
95
|
+
let creation1h = 0;
|
|
96
|
+
let conflicting = false;
|
|
97
|
+
if (cacheTop.present && !cacheTop.invalid) {
|
|
98
|
+
creationTotal = cacheTop.value;
|
|
99
|
+
if (splitPresent && !cache5m.invalid && !cache1h.invalid) {
|
|
100
|
+
if (validSplitSum === cacheTop.value) {
|
|
101
|
+
creation5m = cache5m.value;
|
|
102
|
+
creation1h = cache1h.value;
|
|
103
|
+
} else {
|
|
104
|
+
conflicting = true;
|
|
105
|
+
creation1h = cacheTop.value;
|
|
106
|
+
warnings.add(CACHE_SPLIT_CONFLICT_WARNING);
|
|
107
|
+
}
|
|
108
|
+
} else if (splitProvided) {
|
|
109
|
+
creation1h = cacheTop.value;
|
|
110
|
+
warnings.add(CACHE_TTL_FALLBACK_WARNING);
|
|
111
|
+
} else {
|
|
112
|
+
creation5m = cacheTop.value;
|
|
113
|
+
if (cacheTop.value > 0) warnings.add(CACHE_TTL_ASSUMED_WARNING);
|
|
114
|
+
}
|
|
115
|
+
} else if (splitPresent) {
|
|
116
|
+
creationTotal = validSplitSum;
|
|
117
|
+
creation5m = cache5m.value;
|
|
118
|
+
creation1h = cache1h.value;
|
|
119
|
+
}
|
|
120
|
+
let speed = "standard";
|
|
121
|
+
if (usage.speed === "fast") speed = "fast";
|
|
122
|
+
else if (usage.speed != null && usage.speed !== "standard") warnings.add(UNSUPPORTED_PRICING_WARNING);
|
|
123
|
+
let inferenceGeo = "global";
|
|
124
|
+
if (usage.inference_geo === "us") inferenceGeo = "us";
|
|
125
|
+
else if (usage.inference_geo != null && usage.inference_geo !== "global") warnings.add(UNSUPPORTED_PRICING_WARNING);
|
|
126
|
+
let batch = false;
|
|
127
|
+
if (usage.batch === true) batch = true;
|
|
128
|
+
else if (usage.batch != null && usage.batch !== false) warnings.add(UNSUPPORTED_PRICING_WARNING);
|
|
129
|
+
let webSearch = { value: 0, present: false, invalid: false };
|
|
130
|
+
if (own(usage, "server_tool_use")) {
|
|
131
|
+
if (usage.server_tool_use && typeof usage.server_tool_use === "object" && !Array.isArray(usage.server_tool_use)) {
|
|
132
|
+
const server = usage.server_tool_use;
|
|
133
|
+
webSearch = readCounter(server.web_search_requests, own(server, "web_search_requests"));
|
|
134
|
+
} else {
|
|
135
|
+
webSearch = { value: 0, present: true, invalid: true };
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
if (webSearch.invalid) {
|
|
139
|
+
invalid = true;
|
|
140
|
+
warnings.add(INVALID_USAGE_WARNING);
|
|
141
|
+
}
|
|
142
|
+
const normalized = {
|
|
143
|
+
input_tokens: input.value,
|
|
144
|
+
output_tokens: output.value,
|
|
145
|
+
cache_creation_input_tokens: creationTotal,
|
|
146
|
+
cache_read_input_tokens: cacheRead.value,
|
|
147
|
+
cache_creation_5m_input_tokens: creation5m,
|
|
148
|
+
cache_creation_1h_input_tokens: creation1h,
|
|
149
|
+
cache_ttl_known: splitPresent || splitProvided,
|
|
150
|
+
web_search_requests: webSearch.value,
|
|
151
|
+
speed,
|
|
152
|
+
inference_geo: inferenceGeo,
|
|
153
|
+
batch
|
|
154
|
+
};
|
|
155
|
+
const billable = normalized.input_tokens > 0 || normalized.output_tokens > 0 || normalized.cache_creation_input_tokens > 0 || normalized.cache_read_input_tokens > 0 || normalized.web_search_requests > 0;
|
|
156
|
+
return { usage: normalized, billable, warnings: [...warnings], invalid, conflicting };
|
|
157
|
+
}
|
|
158
|
+
function pricingMultiplier(model, usage, warnings) {
|
|
159
|
+
let multiplier = 1;
|
|
160
|
+
if (usage.speed === "fast") {
|
|
161
|
+
const base = canonicalModel(model);
|
|
162
|
+
if (base === "claude-opus-5" || base === "claude-opus-4-8") multiplier *= 2;
|
|
163
|
+
else warnings?.add(UNSUPPORTED_PRICING_WARNING);
|
|
164
|
+
}
|
|
165
|
+
if (usage.inference_geo === "us") {
|
|
166
|
+
const base = canonicalModel(model);
|
|
167
|
+
const geoEligible = base != null && (base.startsWith("claude-fable-5") || base.startsWith("claude-mythos-5") || base === "claude-opus-5" || base === "claude-opus-4-8" || base === "claude-opus-4-7" || base === "claude-opus-4-6" || base === "claude-sonnet-5" || base === "claude-sonnet-4-6");
|
|
168
|
+
if (geoEligible) multiplier *= 1.1;
|
|
169
|
+
else warnings?.add(UNSUPPORTED_PRICING_WARNING);
|
|
170
|
+
}
|
|
171
|
+
if (usage.batch) multiplier *= 0.5;
|
|
172
|
+
return multiplier;
|
|
173
|
+
}
|
|
174
|
+
function costForNormalizedUsage(model, usage, warnings) {
|
|
175
|
+
const p = priceFor(model);
|
|
176
|
+
const tokenCost = (usage.input_tokens * p.input + usage.output_tokens * p.output + usage.cache_creation_5m_input_tokens * p.cache_write + usage.cache_creation_1h_input_tokens * p.cache_write_1h + usage.cache_read_input_tokens * p.cache_read) / 1e6;
|
|
177
|
+
return tokenCost * pricingMultiplier(model, usage, warnings) + usage.web_search_requests * 0.01;
|
|
49
178
|
}
|
|
50
|
-
var num = (v) => Number(v) || 0;
|
|
51
179
|
function costForUsage(model, usage) {
|
|
180
|
+
return costForNormalizedUsage(model, normalizeUsage(usage).usage);
|
|
181
|
+
}
|
|
182
|
+
function cacheSavingsForNormalizedUsage(model, usage) {
|
|
52
183
|
const p = priceFor(model);
|
|
53
|
-
|
|
54
|
-
const o = num(usage?.output_tokens);
|
|
55
|
-
const cw = num(usage?.cache_creation_input_tokens);
|
|
56
|
-
const cr = num(usage?.cache_read_input_tokens);
|
|
57
|
-
return (i * p.input + o * p.output + cw * p.cache_write + cr * p.cache_read) / 1e6;
|
|
184
|
+
return usage.cache_read_input_tokens * (p.input - p.cache_read) * pricingMultiplier(model, usage) / 1e6;
|
|
58
185
|
}
|
|
59
|
-
function
|
|
186
|
+
function cacheMissExposureForNormalizedUsage(model, usage) {
|
|
60
187
|
const p = priceFor(model);
|
|
61
|
-
|
|
62
|
-
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;
|
|
63
189
|
}
|
|
64
190
|
function cacheHitRate(totals) {
|
|
65
|
-
const denom =
|
|
66
|
-
if (!denom) return 0;
|
|
67
|
-
return
|
|
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
|
+
};
|
|
68
207
|
}
|
|
69
208
|
function costForTotals(model, totals) {
|
|
70
|
-
|
|
71
|
-
|
|
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;
|
|
72
220
|
}
|
|
73
221
|
function isOpus(model) {
|
|
74
|
-
|
|
75
|
-
return model.replace(/\[[^\]]*\]$/, "").startsWith("claude-opus");
|
|
222
|
+
return canonicalModel(model)?.startsWith("claude-opus") ?? false;
|
|
76
223
|
}
|
|
77
224
|
function isPremiumModel(model) {
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
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;
|
|
81
227
|
}
|
|
82
228
|
|
|
83
229
|
// ../../packages/engine/src/sanitize.ts
|
|
@@ -191,19 +337,109 @@ function emptyPromptSignals() {
|
|
|
191
337
|
}
|
|
192
338
|
var isToolUse = (b) => !!b && typeof b === "object" && b.type === "tool_use" && typeof b.name === "string";
|
|
193
339
|
function extractTools(content) {
|
|
194
|
-
const names = [];
|
|
195
340
|
const events = [];
|
|
196
341
|
if (Array.isArray(content)) {
|
|
197
342
|
for (const block of content) {
|
|
198
343
|
if (isToolUse(block)) {
|
|
199
344
|
const name = block.name;
|
|
200
345
|
const input = block.input ?? {};
|
|
201
|
-
|
|
202
|
-
events.push({ name, target: targetFor(name, input) });
|
|
346
|
+
events.push({ id: typeof block.id === "string" ? block.id : null, name, target: targetFor(name, input), input });
|
|
203
347
|
}
|
|
204
348
|
}
|
|
205
349
|
}
|
|
206
|
-
return {
|
|
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])];
|
|
207
443
|
}
|
|
208
444
|
function parseSession(text2, opts = {}) {
|
|
209
445
|
const s = {
|
|
@@ -229,13 +465,20 @@ function parseSession(text2, opts = {}) {
|
|
|
229
465
|
parentSessionId: opts.parentSessionId ?? null,
|
|
230
466
|
turnCache: [],
|
|
231
467
|
costBuckets: [],
|
|
468
|
+
modelCostsUsd: {},
|
|
469
|
+
cacheMissExposureUsd: 0,
|
|
470
|
+
accuracyWarnings: [],
|
|
471
|
+
unknownModelRequests: {},
|
|
472
|
+
pricedRequests: 0,
|
|
473
|
+
invalidUsageRecords: 0,
|
|
474
|
+
conflictingUsageRecords: 0,
|
|
475
|
+
usageFragments: [],
|
|
476
|
+
usageLogicalKeys: [],
|
|
232
477
|
prompting: emptyPromptSignals()
|
|
233
478
|
};
|
|
234
479
|
const ps = s.prompting;
|
|
235
|
-
const
|
|
236
|
-
const
|
|
237
|
-
const BUCKET_MS = 15 * 60 * 1e3;
|
|
238
|
-
const modelCounts = /* @__PURE__ */ new Map();
|
|
480
|
+
const usageGroups = /* @__PURE__ */ new Map();
|
|
481
|
+
const seenTools = /* @__PURE__ */ new Set();
|
|
239
482
|
let cwd = null;
|
|
240
483
|
let seq = 0;
|
|
241
484
|
for (const line of text2.split("\n")) {
|
|
@@ -270,75 +513,177 @@ function parseSession(text2, opts = {}) {
|
|
|
270
513
|
}
|
|
271
514
|
}
|
|
272
515
|
} else s.assistantRecords += 1;
|
|
273
|
-
const model = rec.message?.model;
|
|
274
|
-
if (model && model !== "<synthetic>") modelCounts.set(model, (modelCounts.get(model) ?? 0) + 1);
|
|
516
|
+
const model = rec.message?.model ?? null;
|
|
275
517
|
if (rec.type === "assistant") {
|
|
276
|
-
const {
|
|
277
|
-
for (const n of names) {
|
|
278
|
-
s.toolUsage[n] = (s.toolUsage[n] ?? 0) + 1;
|
|
279
|
-
if (PLAN_TOOLS.has(n)) ps.planEvents += 1;
|
|
280
|
-
}
|
|
281
|
-
if (Array.isArray(rec.message?.content)) {
|
|
282
|
-
for (const b of rec.message.content) {
|
|
283
|
-
if (isToolUse(b) && (b.name === "Bash" || b.name === "PowerShell") && typeof b.input?.command === "string" && isVerifyCommand(b.input.command)) ps.verifyRuns += 1;
|
|
284
|
-
}
|
|
285
|
-
}
|
|
518
|
+
const { events } = extractTools(rec.message?.content);
|
|
286
519
|
const requestId = rec.requestId || rec.message?.requestId || null;
|
|
287
|
-
|
|
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
|
+
}
|
|
288
531
|
const usage = rec.message?.usage;
|
|
289
532
|
if (usage) {
|
|
290
533
|
seq += 1;
|
|
291
534
|
const key = usageKey(rec, seq);
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
s.
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
const ms = Date.parse(rec.timestamp);
|
|
308
|
-
if (!Number.isNaN(ms)) {
|
|
309
|
-
const t = Math.floor(ms / BUCKET_MS);
|
|
310
|
-
buckets.set(t, (buckets.get(t) ?? 0) + fragmentUsd);
|
|
311
|
-
}
|
|
312
|
-
}
|
|
313
|
-
s.turnCache.push({
|
|
314
|
-
read: Number(usage.cache_read_input_tokens) || 0,
|
|
315
|
-
miss: (Number(usage.input_tokens) || 0) + (Number(usage.cache_creation_input_tokens) || 0)
|
|
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
|
|
316
550
|
});
|
|
551
|
+
usageGroups.set(key, candidates);
|
|
317
552
|
}
|
|
318
553
|
}
|
|
319
554
|
}
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
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
|
+
});
|
|
327
603
|
}
|
|
328
|
-
s
|
|
604
|
+
rebuildSessionUsage(s, fragments);
|
|
605
|
+
s.projectSlug = opts.projectSlug ?? projectFromCwd(cwd);
|
|
329
606
|
if (s.startedAt && s.endedAt) {
|
|
330
607
|
const ms = Date.parse(s.endedAt) - Date.parse(s.startedAt);
|
|
331
|
-
s.durationMinutes = Number.isNaN(ms) ? null : ms / 6e4;
|
|
608
|
+
s.durationMinutes = Number.isNaN(ms) || ms < 0 ? null : ms / 6e4;
|
|
332
609
|
}
|
|
333
610
|
return s;
|
|
334
611
|
}
|
|
335
612
|
|
|
336
613
|
// ../../packages/engine/src/aggregate.ts
|
|
337
614
|
function addTotals(into, from) {
|
|
615
|
+
const priorCreation = into.cache_creation_tokens;
|
|
338
616
|
into.input_tokens += from.input_tokens;
|
|
339
617
|
into.output_tokens += from.output_tokens;
|
|
340
618
|
into.cache_creation_tokens += from.cache_creation_tokens;
|
|
341
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;
|
|
342
687
|
}
|
|
343
688
|
function mostFrequent(values) {
|
|
344
689
|
const counts = /* @__PURE__ */ new Map();
|
|
@@ -393,7 +738,7 @@ function buildSummary(projects) {
|
|
|
393
738
|
let sessionsCount = 0;
|
|
394
739
|
let delegatedSessionsCount = 0;
|
|
395
740
|
let mainCostUsd = 0;
|
|
396
|
-
|
|
741
|
+
const sessions = [];
|
|
397
742
|
for (const p of projects) {
|
|
398
743
|
addTotals(totals, p.totals);
|
|
399
744
|
cost += p.cost_usd;
|
|
@@ -401,10 +746,14 @@ function buildSummary(projects) {
|
|
|
401
746
|
sessionsCount += p.sessionsCount;
|
|
402
747
|
delegatedSessionsCount += p.delegatedSessionsCount;
|
|
403
748
|
for (const s of p.sessions) {
|
|
404
|
-
|
|
405
|
-
|
|
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
|
+
}
|
|
406
756
|
if (s.kind === "main") mainCostUsd += s.cost_usd;
|
|
407
|
-
if (s.durationMinutes && s.durationMinutes > 0) durationHours += s.durationMinutes / 60;
|
|
408
757
|
}
|
|
409
758
|
}
|
|
410
759
|
return {
|
|
@@ -417,7 +766,8 @@ function buildSummary(projects) {
|
|
|
417
766
|
totals,
|
|
418
767
|
modelBreakdown,
|
|
419
768
|
cacheHitRate: cacheHitRate(totals),
|
|
420
|
-
durationHours
|
|
769
|
+
durationHours: unionDurationHours(sessions),
|
|
770
|
+
accuracy: buildAccuracy(sessions)
|
|
421
771
|
};
|
|
422
772
|
}
|
|
423
773
|
|
|
@@ -475,8 +825,7 @@ function ruleBadCacheHit(ctx) {
|
|
|
475
825
|
if (!last) continue;
|
|
476
826
|
let savings = 0;
|
|
477
827
|
for (const s of tail) {
|
|
478
|
-
|
|
479
|
-
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);
|
|
480
829
|
}
|
|
481
830
|
out.push({
|
|
482
831
|
ruleId: "BAD_CACHE_HIT",
|
|
@@ -635,8 +984,10 @@ function ruleMarathonSession(ctx) {
|
|
|
635
984
|
if (lateHit >= LATE_FLOOR) continue;
|
|
636
985
|
const expectedReads = late.total * earlyHit;
|
|
637
986
|
const shortfall = Math.max(0, expectedReads - late.read);
|
|
638
|
-
const
|
|
639
|
-
const
|
|
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;
|
|
640
991
|
out.push({
|
|
641
992
|
ruleId: "MARATHON_SESSION",
|
|
642
993
|
severity: severityForSavings(savings),
|
|
@@ -741,7 +1092,7 @@ function runOptimizer(ctx) {
|
|
|
741
1092
|
|
|
742
1093
|
// ../../packages/engine/src/report.ts
|
|
743
1094
|
function analyzeUploads(files) {
|
|
744
|
-
const
|
|
1095
|
+
const parsed = files.map(
|
|
745
1096
|
(f) => parseSession(f.text, {
|
|
746
1097
|
// Path-encoded slugs are anonymized before grouping so no downstream
|
|
747
1098
|
// consumer (optimizer prose, synthesize, the AuditRecord) ever sees one.
|
|
@@ -750,18 +1101,80 @@ function analyzeUploads(files) {
|
|
|
750
1101
|
parentSessionId: f.parentSessionId ?? null
|
|
751
1102
|
})
|
|
752
1103
|
);
|
|
1104
|
+
const sessions = deduplicateLogicalRequests(parsed);
|
|
753
1105
|
const projects = buildProjects(sessions);
|
|
754
1106
|
const summary = buildSummary(projects);
|
|
755
1107
|
const findings = runOptimizer({ projects, summary });
|
|
756
1108
|
return { summary, projects, findings };
|
|
757
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
|
+
}
|
|
758
1172
|
function cacheMissExposureUsd(report) {
|
|
759
1173
|
let total = 0;
|
|
760
1174
|
for (const proj of report.projects) {
|
|
761
1175
|
for (const s of proj.sessions) {
|
|
762
1176
|
if (s.kind !== "main") continue;
|
|
763
|
-
|
|
764
|
-
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);
|
|
765
1178
|
}
|
|
766
1179
|
}
|
|
767
1180
|
return total;
|
|
@@ -775,8 +1188,7 @@ function cacheMissByProject(report) {
|
|
|
775
1188
|
for (const s of proj.sessions) {
|
|
776
1189
|
if (s.kind !== "main") continue;
|
|
777
1190
|
sessionsCount += 1;
|
|
778
|
-
|
|
779
|
-
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);
|
|
780
1192
|
mainTotals.input_tokens += s.totals.input_tokens;
|
|
781
1193
|
mainTotals.output_tokens += s.totals.output_tokens;
|
|
782
1194
|
mainTotals.cache_creation_tokens += s.totals.cache_creation_tokens;
|
|
@@ -1352,13 +1764,14 @@ function buildChecks(report, cmd2, answers, setup) {
|
|
|
1352
1764
|
const exposure = cacheMissExposureUsd(report);
|
|
1353
1765
|
const spend = s.mainCostUsd;
|
|
1354
1766
|
const exposureShare = spend > 0 ? exposure / spend : 0;
|
|
1767
|
+
const exposureValid = spend > 0 && exposure >= 0 && exposure <= spend + 1e-9;
|
|
1355
1768
|
checks.push(
|
|
1356
1769
|
makeCheck(
|
|
1357
1770
|
"recoverable_exposure",
|
|
1358
1771
|
"cost_discipline",
|
|
1359
|
-
"
|
|
1360
|
-
|
|
1361
|
-
spend
|
|
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.`,
|
|
1362
1775
|
"metrics"
|
|
1363
1776
|
)
|
|
1364
1777
|
);
|
|
@@ -1484,14 +1897,14 @@ var HEAVY_TOOL_PATTERN_MIN_SESSIONS = 2;
|
|
|
1484
1897
|
function severityRank(s) {
|
|
1485
1898
|
return s === "critical" ? 3 : s === "warn" ? 2 : 1;
|
|
1486
1899
|
}
|
|
1487
|
-
function
|
|
1900
|
+
function num(n) {
|
|
1488
1901
|
return String(Math.round(n)).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
|
|
1489
1902
|
}
|
|
1490
1903
|
function sizeFix(cmd2) {
|
|
1491
1904
|
if (cmd2.chars > 6e3) {
|
|
1492
1905
|
return {
|
|
1493
1906
|
title: "Trim your CLAUDE.md",
|
|
1494
|
-
action: `Your CLAUDE.md is an estimated ${
|
|
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.`
|
|
1495
1908
|
};
|
|
1496
1909
|
}
|
|
1497
1910
|
return {
|
|
@@ -1501,13 +1914,13 @@ function sizeFix(cmd2) {
|
|
|
1501
1914
|
}
|
|
1502
1915
|
function synthesize(report, pillars, cmd2, plan = "api") {
|
|
1503
1916
|
const headlineWasteUsd = cacheMissExposureUsd(report);
|
|
1504
|
-
const headlineWasteLabel =
|
|
1917
|
+
const headlineWasteLabel = "Cache-miss exposure (estimate)";
|
|
1505
1918
|
const spend = report.summary.cost_usd;
|
|
1506
1919
|
const headlineWasteShare = spend > 0 ? headlineWasteUsd / spend : 0;
|
|
1507
1920
|
const exposure = headlineWasteUsd;
|
|
1508
1921
|
const fixes = [];
|
|
1509
1922
|
const covered = /* @__PURE__ */ new Set();
|
|
1510
|
-
const round23 = (n) =>
|
|
1923
|
+
const round23 = (n) => roundMoneyHalfUp(n);
|
|
1511
1924
|
const usd8 = (n) => {
|
|
1512
1925
|
const fixed = round23(n).toFixed(2);
|
|
1513
1926
|
const dot = fixed.indexOf(".");
|
|
@@ -1588,16 +2001,16 @@ function synthesize(report, pillars, cmd2, plan = "api") {
|
|
|
1588
2001
|
}
|
|
1589
2002
|
fixes.push({
|
|
1590
2003
|
id: "cache_recovery",
|
|
1591
|
-
title: "
|
|
2004
|
+
title: "Reduce cache-miss exposure",
|
|
1592
2005
|
pillar: "context_hygiene",
|
|
1593
2006
|
pillarName: PILLARS.context_hygiene.name,
|
|
1594
2007
|
severity: sevForUsd(exposure),
|
|
1595
2008
|
wasteUsd: round23(exposure),
|
|
1596
2009
|
problem: sanitizeText(
|
|
1597
|
-
|
|
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"}.`
|
|
1598
2011
|
),
|
|
1599
2012
|
action: sanitizeText(action),
|
|
1600
|
-
basis: sanitizeText("
|
|
2013
|
+
basis: sanitizeText("Current list-price cache-miss exposure summed across projects. It is a bounded counterfactual, not complete savings or billed spend.")
|
|
1601
2014
|
});
|
|
1602
2015
|
covered.add("cache_hit");
|
|
1603
2016
|
covered.add("cache_churn");
|
|
@@ -1675,7 +2088,7 @@ function synthesize(report, pillars, cmd2, plan = "api") {
|
|
|
1675
2088
|
wasteUsd: round23(marathonUsd),
|
|
1676
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.`),
|
|
1677
2090
|
action: sanitizeText("Compact or start a fresh session between tasks so the context stays small and the cache keeps working."),
|
|
1678
|
-
basis: sanitizeText("
|
|
2091
|
+
basis: sanitizeText("Estimated cache-miss exposure from the late-session cache shortfall versus the early-session hit rate; not complete savings.")
|
|
1679
2092
|
});
|
|
1680
2093
|
}
|
|
1681
2094
|
if (workflowUsd > 0) {
|
|
@@ -1798,7 +2211,7 @@ var UNASSESSED_BURN_CLOCK = {
|
|
|
1798
2211
|
quietSlot: null,
|
|
1799
2212
|
activeDays: 0
|
|
1800
2213
|
};
|
|
1801
|
-
function burnClock(report, offsetMinutes = 0) {
|
|
2214
|
+
function burnClock(report, offsetMinutes = 0, timeZone) {
|
|
1802
2215
|
const merged = /* @__PURE__ */ new Map();
|
|
1803
2216
|
for (const project of report.projects) {
|
|
1804
2217
|
for (const session of project.sessions) {
|
|
@@ -1806,19 +2219,52 @@ function burnClock(report, offsetMinutes = 0) {
|
|
|
1806
2219
|
}
|
|
1807
2220
|
}
|
|
1808
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
|
+
};
|
|
1809
2256
|
const activeDaySet = /* @__PURE__ */ new Set();
|
|
1810
2257
|
for (const t of merged.keys()) {
|
|
1811
|
-
|
|
1812
|
-
activeDaySet.add(`${d.getUTCFullYear()}-${d.getUTCMonth()}-${d.getUTCDate()}`);
|
|
2258
|
+
activeDaySet.add(localParts(t).date);
|
|
1813
2259
|
}
|
|
1814
2260
|
if (activeDaySet.size < 7) return { ...UNASSESSED_BURN_CLOCK, activeDays: activeDaySet.size };
|
|
1815
2261
|
const byDay = [0, 0, 0, 0, 0, 0, 0];
|
|
1816
2262
|
const byQuarter = [0, 0, 0, 0];
|
|
1817
2263
|
const slot = Array.from({ length: 7 }, () => [0, 0, 0, 0]);
|
|
1818
2264
|
for (const [t, usd8] of merged) {
|
|
1819
|
-
const
|
|
1820
|
-
const day2 =
|
|
1821
|
-
const quarter = Math.floor(
|
|
2265
|
+
const local = localParts(t);
|
|
2266
|
+
const day2 = local.day;
|
|
2267
|
+
const quarter = Math.floor(local.hour / 6);
|
|
1822
2268
|
byDay[day2] += usd8;
|
|
1823
2269
|
byQuarter[quarter] += usd8;
|
|
1824
2270
|
slot[day2][quarter] += usd8;
|
|
@@ -1847,7 +2293,7 @@ function usd(n) {
|
|
|
1847
2293
|
const grouped = whole.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
|
|
1848
2294
|
return `${neg ? "-" : ""}$${grouped}${cents}`;
|
|
1849
2295
|
}
|
|
1850
|
-
function
|
|
2296
|
+
function num2(n) {
|
|
1851
2297
|
return String(Math.round(n)).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
|
|
1852
2298
|
}
|
|
1853
2299
|
function clean(text2) {
|
|
@@ -2514,7 +2960,7 @@ function claudeMdReceiptLine(claudeMdTokens) {
|
|
|
2514
2960
|
const grew = delta > 0;
|
|
2515
2961
|
const pct2 = before > 0 ? ` (${(Math.abs(delta) / before * 100).toFixed(1)}% ${grew ? "larger" : "smaller"})` : "";
|
|
2516
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.";
|
|
2517
|
-
return `Your optimized CLAUDE.md goes from an estimated ${
|
|
2963
|
+
return `Your optimized CLAUDE.md goes from an estimated ${num2(before)} tokens to ${num2(after)}${pct2}. ${tail}`;
|
|
2518
2964
|
}
|
|
2519
2965
|
function buildPlaybook(report, fixes, scores, recoverable, claudeMdTokens, project) {
|
|
2520
2966
|
const dollarFixes = fixes.filter((f) => f.wasteUsd > 0);
|
|
@@ -2527,9 +2973,9 @@ function buildPlaybook(report, fixes, scores, recoverable, claudeMdTokens, proje
|
|
|
2527
2973
|
parts.push(
|
|
2528
2974
|
[
|
|
2529
2975
|
...projectLine ? [projectLine, ""] : [],
|
|
2530
|
-
`
|
|
2976
|
+
`Cache-miss exposure estimate: ${usd(recoverable)} at current API list prices.`,
|
|
2531
2977
|
"",
|
|
2532
|
-
"This is the ranked plan from your audit.
|
|
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."
|
|
2533
2979
|
].join("\n")
|
|
2534
2980
|
);
|
|
2535
2981
|
const receipt = claudeMdReceiptLine(claudeMdTokens);
|
|
@@ -2657,12 +3103,12 @@ function buildHarnessPrompt(input, carried, claudeMdTokens) {
|
|
|
2657
3103
|
if (carried.carriedTokens >= CARRY_HEAVY_TOKENS && worklist.length > 0) {
|
|
2658
3104
|
const rows = worklist.map((s) => {
|
|
2659
3105
|
const n2 = s.volatileLines;
|
|
2660
|
-
const dated = n2 > 0 ? `, ${
|
|
2661
|
-
return `- ${s.heading}: est. ${
|
|
3106
|
+
const dated = n2 > 0 ? `, ${num2(n2)} dated ${n2 === 1 ? "line" : "lines"}` : "";
|
|
3107
|
+
return `- ${s.heading}: est. ${num2(s.tokens)} tokens${dated}.`;
|
|
2662
3108
|
});
|
|
2663
3109
|
const shown = worklist.reduce((sum, s) => sum + s.tokens, 0);
|
|
2664
3110
|
const rest = carried.carriedList.length - worklist.length;
|
|
2665
|
-
const tail = rest > 0 ? [`The remaining ${
|
|
3111
|
+
const tail = rest > 0 ? [`The remaining ${num2(rest)} carried ${rest === 1 ? "section accounts" : "sections account"} for the other ${num2(carried.carriedTokens - shown)} tokens.`] : [];
|
|
2666
3112
|
const before = claudeMdTokens.before;
|
|
2667
3113
|
const saved = before != null && before > 0 ? (before - claudeMdTokens.after) / before : 0;
|
|
2668
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.";
|
|
@@ -2670,7 +3116,7 @@ function buildHarnessPrompt(input, carried, claudeMdTokens) {
|
|
|
2670
3116
|
[
|
|
2671
3117
|
`## Task ${n++}: Reclaim the carried sections`,
|
|
2672
3118
|
"",
|
|
2673
|
-
`Your CLAUDE.md carries an estimated ${
|
|
3119
|
+
`Your CLAUDE.md carries an estimated ${num2(carried.carriedTokens)} tokens of your`,
|
|
2674
3120
|
"own prose, paid on every turn of every session.",
|
|
2675
3121
|
`costclaw does not rewrite your prose, so it passed all of it through untouched:`,
|
|
2676
3122
|
`${consequence} Doing the actual trimming is this task,`,
|
|
@@ -2831,11 +3277,15 @@ function optimize(input) {
|
|
|
2831
3277
|
// ../../packages/engine/src/audit.ts
|
|
2832
3278
|
import { randomUUID } from "crypto";
|
|
2833
3279
|
function round2(n) {
|
|
2834
|
-
return
|
|
3280
|
+
return roundMoneyHalfUp(n);
|
|
2835
3281
|
}
|
|
2836
3282
|
function round4(n) {
|
|
2837
3283
|
return Math.round(n * 1e4) / 1e4;
|
|
2838
3284
|
}
|
|
3285
|
+
function safeModelId2(model) {
|
|
3286
|
+
if (model == null) return null;
|
|
3287
|
+
return /^[A-Za-z0-9._:\[\]-]{1,100}$/.test(model) ? model : "unknown";
|
|
3288
|
+
}
|
|
2839
3289
|
function toUsageMetrics(report) {
|
|
2840
3290
|
const s = report.summary;
|
|
2841
3291
|
const topProjects = report.projects.slice().sort((a, b) => b.cost_usd - a.cost_usd).slice(0, 8).map((p) => ({
|
|
@@ -2843,14 +3293,15 @@ function toUsageMetrics(report) {
|
|
|
2843
3293
|
costUsd: round2(p.cost_usd),
|
|
2844
3294
|
sessionsCount: p.sessionsCount,
|
|
2845
3295
|
cacheHitRate: round4(p.cacheHitRate),
|
|
2846
|
-
modelPrimary: p.modelPrimary
|
|
3296
|
+
modelPrimary: safeModelId2(p.modelPrimary)
|
|
2847
3297
|
}));
|
|
2848
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 }) => ({
|
|
2849
3299
|
projectSlug,
|
|
2850
|
-
|
|
3300
|
+
// Retain the schema field without persisting a private transcript ID.
|
|
3301
|
+
sessionUuid: null,
|
|
2851
3302
|
costUsd: round2(sess.cost_usd),
|
|
2852
3303
|
durationMinutes: sess.durationMinutes == null ? null : round2(sess.durationMinutes),
|
|
2853
|
-
modelPrimary: sess.modelPrimary,
|
|
3304
|
+
modelPrimary: safeModelId2(sess.modelPrimary),
|
|
2854
3305
|
cacheHitRate: round4(cacheHitRate(sess.totals))
|
|
2855
3306
|
}));
|
|
2856
3307
|
const modelBreakdown = {};
|
|
@@ -2867,7 +3318,12 @@ function toUsageMetrics(report) {
|
|
|
2867
3318
|
modelBreakdown,
|
|
2868
3319
|
topProjects,
|
|
2869
3320
|
topSessions,
|
|
2870
|
-
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
|
|
2871
3327
|
};
|
|
2872
3328
|
}
|
|
2873
3329
|
function roundWindows(w) {
|
|
@@ -2933,7 +3389,7 @@ function buildAudit(input, opts = {}) {
|
|
|
2933
3389
|
plan,
|
|
2934
3390
|
headlineWasteShare: round4(headlineWasteShare),
|
|
2935
3391
|
usageWindows: roundWindows(computeWindowStats(report)),
|
|
2936
|
-
burnClock: roundBurnClock(burnClock(report, input.tzOffsetMinutes ?? 0)),
|
|
3392
|
+
burnClock: roundBurnClock(burnClock(report, input.tzOffsetMinutes ?? 0, input.timeZone)),
|
|
2937
3393
|
fixes: fixes.map(cleanFix),
|
|
2938
3394
|
writer: opts.writer ?? "template",
|
|
2939
3395
|
paid: false
|
|
@@ -2943,7 +3399,7 @@ function buildAudit(input, opts = {}) {
|
|
|
2943
3399
|
// ../../packages/engine/src/diff.ts
|
|
2944
3400
|
var DIFF_SCHEMA_VERSION = "1";
|
|
2945
3401
|
function round22(n) {
|
|
2946
|
-
return
|
|
3402
|
+
return roundMoneyHalfUp(n);
|
|
2947
3403
|
}
|
|
2948
3404
|
function round42(n) {
|
|
2949
3405
|
return Math.round(n * 1e4) / 1e4;
|
|
@@ -2966,6 +3422,12 @@ function side(r) {
|
|
|
2966
3422
|
plan: r.plan
|
|
2967
3423
|
};
|
|
2968
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
|
+
}
|
|
2969
3431
|
function diffAudits(a, b) {
|
|
2970
3432
|
assertRecord(a);
|
|
2971
3433
|
assertRecord(b);
|
|
@@ -2980,7 +3442,8 @@ function diffAudits(a, b) {
|
|
|
2980
3442
|
};
|
|
2981
3443
|
const newSpendUsd = cm.spendUsd - bm.spendUsd;
|
|
2982
3444
|
const newSessions = cm.sessionsCount - bm.sessionsCount;
|
|
2983
|
-
const
|
|
3445
|
+
const comparisonReason = provenanceMismatch(bm.accuracy, cm.accuracy);
|
|
3446
|
+
const comparable = !comparisonReason && newSpendUsd >= -0.01 && newSessions >= 0 && Object.values(newTokens).every((t) => t >= 0);
|
|
2984
3447
|
const periodMs = Date.parse(cur.createdAt) - Date.parse(base.createdAt);
|
|
2985
3448
|
const periodDays = round22(Math.max(0, periodMs) / 864e5);
|
|
2986
3449
|
const pillars = base.pillarScores.map((bp) => {
|
|
@@ -3010,6 +3473,7 @@ function diffAudits(a, b) {
|
|
|
3010
3473
|
current: side(cur),
|
|
3011
3474
|
periodDays,
|
|
3012
3475
|
comparable,
|
|
3476
|
+
...comparisonReason ? { comparisonReason } : {},
|
|
3013
3477
|
marginal: comparable ? {
|
|
3014
3478
|
newSpendUsd: round22(newSpendUsd),
|
|
3015
3479
|
newSessions,
|
|
@@ -3028,6 +3492,13 @@ function diffAudits(a, b) {
|
|
|
3028
3492
|
}
|
|
3029
3493
|
var SINCE_BASELINE_MIN_TOKENS = 1e6;
|
|
3030
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
|
+
}
|
|
3031
3502
|
const cur = current.usageMetrics.totalTokens;
|
|
3032
3503
|
const base = baseline.totals;
|
|
3033
3504
|
const period = {
|
|
@@ -3065,7 +3536,7 @@ var IMPORT_LINE = "@.claude/costclaw.md";
|
|
|
3065
3536
|
function estTokens(text2) {
|
|
3066
3537
|
return Math.round(text2.length / 4);
|
|
3067
3538
|
}
|
|
3068
|
-
function
|
|
3539
|
+
function num3(n) {
|
|
3069
3540
|
return String(Math.round(n)).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
|
|
3070
3541
|
}
|
|
3071
3542
|
function normalize(line) {
|
|
@@ -3168,7 +3639,7 @@ function markVolatile(lines, sections, b, destDir) {
|
|
|
3168
3639
|
id,
|
|
3169
3640
|
kind: "move",
|
|
3170
3641
|
heading: s.heading,
|
|
3171
|
-
instruction: `Move the ${
|
|
3642
|
+
instruction: `Move the ${num3(dated.length)} dated ${dated.length === 1 ? "line" : "lines"} under "${s.heading}" to ${dest}, then link that file.`,
|
|
3172
3643
|
reason: VOLATILE_WHY,
|
|
3173
3644
|
tokens: estTokens(dated.map((i) => lines[i] ?? "").join("\n")),
|
|
3174
3645
|
destination: dest
|
|
@@ -3305,8 +3776,8 @@ function reviewProjectClaudeMd(input) {
|
|
|
3305
3776
|
id,
|
|
3306
3777
|
kind: "remove",
|
|
3307
3778
|
heading: s.heading,
|
|
3308
|
-
instruction: all ? `Delete the whole "${s.heading}" section: the include ${IMPORT_LINE} now carries it.` : `Delete the ${
|
|
3309
|
-
reason: `${
|
|
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`,
|
|
3310
3781
|
tokens: estTokens(covered.map((i) => lines[i] ?? "").join("\n"))
|
|
3311
3782
|
});
|
|
3312
3783
|
}
|
|
@@ -3430,8 +3901,8 @@ function reviewGlobalClaudeMd(input) {
|
|
|
3430
3901
|
id,
|
|
3431
3902
|
kind: "move",
|
|
3432
3903
|
heading: "(top)",
|
|
3433
|
-
instruction: `Split ${heaviest.label} (about ${
|
|
3434
|
-
reason: `this file plus its imports is about ${
|
|
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`,
|
|
3435
3906
|
tokens: 0,
|
|
3436
3907
|
destination: "on-demand docs"
|
|
3437
3908
|
});
|
|
@@ -3451,7 +3922,7 @@ function changeList(review) {
|
|
|
3451
3922
|
const out = [];
|
|
3452
3923
|
review.changes.forEach((c, i) => {
|
|
3453
3924
|
const where = c.heading === "(top)" ? "file level" : `section "${c.heading}"`;
|
|
3454
|
-
const weight = c.tokens > 0 ? `, about ${
|
|
3925
|
+
const weight = c.tokens > 0 ? `, about ${num3(c.tokens)} tokens` : "";
|
|
3455
3926
|
out.push(`${i + 1}. [${c.kind}] ${where}${weight}: ${c.instruction}`);
|
|
3456
3927
|
out.push(` Why: ${c.reason}`);
|
|
3457
3928
|
if (c.destination) out.push(` Destination: ${c.destination}`);
|
|
@@ -3465,7 +3936,7 @@ function changeList(review) {
|
|
|
3465
3936
|
return out;
|
|
3466
3937
|
}
|
|
3467
3938
|
function tokenTarget(review, what) {
|
|
3468
|
-
return `- ${what}: about ${
|
|
3939
|
+
return `- ${what}: about ${num3(review.tokens.afterChanges)} tokens per turn after these changes (about ${num3(review.tokens.total)} now).`;
|
|
3469
3940
|
}
|
|
3470
3941
|
function buildUpgradeAll(input) {
|
|
3471
3942
|
const parts = [];
|
|
@@ -3488,7 +3959,7 @@ function buildUpgradeAll(input) {
|
|
|
3488
3959
|
parts.push([
|
|
3489
3960
|
`## Global: ${input.global.path}`,
|
|
3490
3961
|
"",
|
|
3491
|
-
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. ${
|
|
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.`,
|
|
3492
3963
|
"",
|
|
3493
3964
|
...changeList(input.global)
|
|
3494
3965
|
].join("\n"));
|
|
@@ -3677,15 +4148,24 @@ function ansi(enabled) {
|
|
|
3677
4148
|
// src/format.ts
|
|
3678
4149
|
function sinceOptimizeLine(meta) {
|
|
3679
4150
|
const so = meta.sinceOptimize;
|
|
3680
|
-
if (!so
|
|
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
|
+
}
|
|
3681
4161
|
const r = so.result;
|
|
3682
4162
|
const date = so.at.slice(0, 10);
|
|
3683
4163
|
const move = `${(r.baselineCacheHitRate * 100).toFixed(1)}% -> ${(r.periodCacheHitRate * 100).toFixed(1)}%`;
|
|
3684
|
-
const worth = r.recoveredUsd >= 0.01 ? `;
|
|
4164
|
+
const worth = r.recoveredUsd >= 0.01 ? `; estimated current Sonnet-rate valuation ${usd2(r.recoveredUsd)}` : "";
|
|
3685
4165
|
return `Since optimize (${date}): cache hit ${move} on new usage${worth}.`;
|
|
3686
4166
|
}
|
|
3687
4167
|
function usd2(n) {
|
|
3688
|
-
return `$${(
|
|
4168
|
+
return `$${roundMoneyHalfUp(n).toFixed(2)}`;
|
|
3689
4169
|
}
|
|
3690
4170
|
var BURN_DAY_NAMES = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
|
|
3691
4171
|
var BURN_DAY_ORDER = [1, 2, 3, 4, 5, 6, 0];
|
|
@@ -3765,16 +4245,20 @@ function shortModel(id) {
|
|
|
3765
4245
|
return m && m[1] ? m[1].toLowerCase() : id;
|
|
3766
4246
|
}
|
|
3767
4247
|
function unknownModelNote(breakdown) {
|
|
3768
|
-
|
|
3769
|
-
|
|
3770
|
-
|
|
3771
|
-
|
|
3772
|
-
|
|
3773
|
-
|
|
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.`);
|
|
3774
4260
|
}
|
|
3775
|
-
|
|
3776
|
-
const pct2 = Math.round(unknown / total * 100);
|
|
3777
|
-
return `${pct2}% of spend used models missing from the rate card and is priced at approximate (Sonnet) rates.`;
|
|
4261
|
+
return [...new Set(notes)];
|
|
3778
4262
|
}
|
|
3779
4263
|
function modelMix(breakdown) {
|
|
3780
4264
|
const merged = /* @__PURE__ */ new Map();
|
|
@@ -3804,8 +4288,9 @@ function formatAudit(record, meta, color = false) {
|
|
|
3804
4288
|
const a = ansi(color);
|
|
3805
4289
|
const m = record.usageMetrics;
|
|
3806
4290
|
const subscription = record.plan !== void 0 && record.plan !== "api";
|
|
3807
|
-
const
|
|
3808
|
-
const
|
|
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";
|
|
3809
4294
|
const lines = [];
|
|
3810
4295
|
lines.push(a.bold("CostClaw audit"));
|
|
3811
4296
|
const delegated = m.delegatedSessionsCount ?? 0;
|
|
@@ -3819,7 +4304,7 @@ function formatAudit(record, meta, color = false) {
|
|
|
3819
4304
|
lines.push(a.dim("-".repeat(WRAP_WIDTH)));
|
|
3820
4305
|
lines.push("");
|
|
3821
4306
|
lines.push(
|
|
3822
|
-
subscription ? `${a.bold(record.headlineWasteLabel + ":")} ${a.brand(shareText + " of analyzed
|
|
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")}`
|
|
3823
4308
|
);
|
|
3824
4309
|
const receipt = sinceOptimizeLine(meta);
|
|
3825
4310
|
if (receipt) pushProse(lines, receipt, 0, a.dim);
|
|
@@ -3827,9 +4312,9 @@ function formatAudit(record, meta, color = false) {
|
|
|
3827
4312
|
const mix = modelMix(m.modelBreakdown);
|
|
3828
4313
|
const statBlock = [
|
|
3829
4314
|
[
|
|
3830
|
-
{ k:
|
|
4315
|
+
{ k: "Current API-equivalent valuation (estimate)", v: usd2(m.spendUsd) },
|
|
3831
4316
|
{ k: "Cache hit", v: `${(m.cacheHitRate * 100).toFixed(1)}%` },
|
|
3832
|
-
{ k: "
|
|
4317
|
+
{ k: "Session hours (timestamp union)", v: m.durationHours.toFixed(1) }
|
|
3833
4318
|
],
|
|
3834
4319
|
[
|
|
3835
4320
|
{ k: "Pricing snapshot", v: m.pricingSnapshotDate },
|
|
@@ -3837,36 +4322,28 @@ function formatAudit(record, meta, color = false) {
|
|
|
3837
4322
|
]
|
|
3838
4323
|
];
|
|
3839
4324
|
for (const row of statRows(statBlock, a)) lines.push(row);
|
|
3840
|
-
const
|
|
3841
|
-
if (
|
|
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);
|
|
3842
4327
|
const w = record.usageWindows;
|
|
3843
4328
|
if (subscription) {
|
|
3844
4329
|
lines.push("");
|
|
3845
4330
|
pushProse(
|
|
3846
4331
|
lines,
|
|
3847
|
-
`Plan: ${record.plan}. Dollar figures are API-equivalent
|
|
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.`,
|
|
3848
4333
|
0,
|
|
3849
4334
|
a.dim
|
|
3850
4335
|
);
|
|
3851
4336
|
if (w?.assessed) {
|
|
3852
4337
|
lines.push(
|
|
3853
|
-
`${a.dim("Usage windows (
|
|
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))}`
|
|
3854
4339
|
);
|
|
3855
|
-
lines.push(`${a.dim("Busiest week:")} ${a.bold(usd2(w.maxWeekUsd))} ${a.dim("(API-equivalent)")}`);
|
|
3856
|
-
|
|
3857
|
-
const gain = share / (1 - share);
|
|
3858
|
-
const extraMinutes = Math.round(w.p90WindowActiveMinutes * gain);
|
|
3859
|
-
lines.push("");
|
|
3860
|
-
lines.push(
|
|
3861
|
-
`Recovering ${shareText} buys about ${a.bold(`${Math.round(gain * 100)}% more work per window`)}:`
|
|
3862
|
-
);
|
|
3863
|
-
lines.push(` up to ${a.brand(`~${extraMinutes} extra minutes`)} in a window like your busiest.`);
|
|
3864
|
-
}
|
|
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.`);
|
|
3865
4342
|
}
|
|
3866
4343
|
} else if (meta.planSource === "default") {
|
|
3867
|
-
const burn = w?.assessed && w.medianWeekUsd >= 50 ? `
|
|
4344
|
+
const burn = w?.assessed && w.medianWeekUsd >= 50 ? ` Median weekly estimated current API-equivalent valuation: ${usd2(w.medianWeekUsd)}.` : "";
|
|
3868
4345
|
lines.push("");
|
|
3869
|
-
pushProse(lines, `Dollar figures are API-equivalent
|
|
4346
|
+
pushProse(lines, `Dollar figures are estimated current API-equivalent valuations.${burn}`, 0, a.dim);
|
|
3870
4347
|
pushProse(
|
|
3871
4348
|
lines,
|
|
3872
4349
|
"On a Claude subscription? Rerun with --plan max20x (or pro, max5x) to frame results as token efficiency.",
|
|
@@ -3876,7 +4353,7 @@ function formatAudit(record, meta, color = false) {
|
|
|
3876
4353
|
}
|
|
3877
4354
|
if (m.topProjects.length > 0) {
|
|
3878
4355
|
lines.push("");
|
|
3879
|
-
lines.push(a.bold("Top projects by
|
|
4356
|
+
lines.push(a.bold("Top projects by estimated current API-equivalent valuation:"));
|
|
3880
4357
|
for (const p of m.topProjects.slice(0, 5)) {
|
|
3881
4358
|
const name = p.slug.length > 30 ? p.slug.slice(0, 27) + "..." : p.slug;
|
|
3882
4359
|
const model = p.modelPrimary ? shortModel(p.modelPrimary) : "n/a";
|
|
@@ -3890,7 +4367,7 @@ function formatAudit(record, meta, color = false) {
|
|
|
3890
4367
|
const bc = record.burnClock;
|
|
3891
4368
|
if (bc?.assessed) {
|
|
3892
4369
|
lines.push("");
|
|
3893
|
-
lines.push(a.bold("Burn Clock (
|
|
4370
|
+
lines.push(a.bold("Burn Clock (estimated current API-equivalent valuation by day):"));
|
|
3894
4371
|
const max = Math.max(...bc.byDay, 0.01);
|
|
3895
4372
|
for (const day2 of BURN_DAY_ORDER) {
|
|
3896
4373
|
const v = bc.byDay[day2];
|
|
@@ -3906,7 +4383,7 @@ function formatAudit(record, meta, color = false) {
|
|
|
3906
4383
|
}
|
|
3907
4384
|
lines.push("");
|
|
3908
4385
|
lines.push(
|
|
3909
|
-
`${a.bold("
|
|
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)`
|
|
3910
4387
|
);
|
|
3911
4388
|
for (const p of record.pillarScores) {
|
|
3912
4389
|
lines.push(` ${p.name.padEnd(22)} ${bar(p.score, a)}`);
|
|
@@ -3914,13 +4391,13 @@ function formatAudit(record, meta, color = false) {
|
|
|
3914
4391
|
lines.push("");
|
|
3915
4392
|
const dollarFixes = record.fixes.filter((f) => f.wasteUsd > 0);
|
|
3916
4393
|
const otherIssues = record.fixes.filter((f) => f.wasteUsd === 0);
|
|
3917
|
-
lines.push(a.bold("Top
|
|
4394
|
+
lines.push(a.bold("Top changes ranked by estimated cache-miss exposure:"));
|
|
3918
4395
|
if (dollarFixes.length === 0) {
|
|
3919
|
-
lines.push(" No
|
|
4396
|
+
lines.push(" No cache-miss exposure estimate found. See issues below.");
|
|
3920
4397
|
} else {
|
|
3921
4398
|
for (const [i, f] of dollarFixes.entries()) {
|
|
3922
4399
|
if (i > 0) lines.push("");
|
|
3923
|
-
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)}`);
|
|
3924
4401
|
pushProse(lines, f.action, 6);
|
|
3925
4402
|
if (f.basis) pushProse(lines, `Evidence: ${f.basis}`, 6, a.dim);
|
|
3926
4403
|
}
|
|
@@ -3942,6 +4419,10 @@ function formatAudit(record, meta, color = false) {
|
|
|
3942
4419
|
lines.push("");
|
|
3943
4420
|
lines.push(a.dim(gapLine));
|
|
3944
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);
|
|
3945
4426
|
return lines.join("\n");
|
|
3946
4427
|
}
|
|
3947
4428
|
|
|
@@ -3973,14 +4454,14 @@ function estimateTextWidth(s, size) {
|
|
|
3973
4454
|
|
|
3974
4455
|
// src/html-report.ts
|
|
3975
4456
|
function usd3(n) {
|
|
3976
|
-
return `$${(
|
|
4457
|
+
return `$${roundMoneyHalfUp(n).toFixed(2)}`;
|
|
3977
4458
|
}
|
|
3978
4459
|
function truncate(s, max) {
|
|
3979
4460
|
return s.length > max ? s.slice(0, max - 3) + "..." : s;
|
|
3980
4461
|
}
|
|
3981
4462
|
function projectChart(projects) {
|
|
3982
4463
|
if (projects.length === 0) {
|
|
3983
|
-
return `<p class="muted">No project
|
|
4464
|
+
return `<p class="muted">No project valuation estimate to chart.</p>`;
|
|
3984
4465
|
}
|
|
3985
4466
|
const rowH = 28;
|
|
3986
4467
|
const gap = 8;
|
|
@@ -3999,7 +4480,7 @@ function projectChart(projects) {
|
|
|
3999
4480
|
const label = esc(truncate(p.slug, 30));
|
|
4000
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>`;
|
|
4001
4482
|
}).join("");
|
|
4002
|
-
return `<svg viewBox="0 0 ${width} ${height}" width="100%" height="${height}" role="img" aria-label="Top projects by
|
|
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>`;
|
|
4003
4484
|
}
|
|
4004
4485
|
function burnClockChart(bc) {
|
|
4005
4486
|
const rowH = 22;
|
|
@@ -4020,7 +4501,7 @@ function burnClockChart(bc) {
|
|
|
4020
4501
|
const label = esc(BURN_DAY_NAMES[day2]);
|
|
4021
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>`;
|
|
4022
4503
|
}).join("");
|
|
4023
|
-
return `<svg viewBox="0 0 ${width} ${height}" width="100%" height="${height}" role="img" aria-label="
|
|
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>`;
|
|
4024
4505
|
}
|
|
4025
4506
|
function pillarBars(pillars) {
|
|
4026
4507
|
return pillars.map((p) => {
|
|
@@ -4058,11 +4539,11 @@ function nextStepsSection(record, meta) {
|
|
|
4058
4539
|
steps.push(step(
|
|
4059
4540
|
n++,
|
|
4060
4541
|
"Tell costclaw how you pay",
|
|
4061
|
-
`<p>On a Claude subscription
|
|
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")
|
|
4062
4543
|
));
|
|
4063
4544
|
}
|
|
4064
4545
|
const waste = record.headlineWasteUsd;
|
|
4065
|
-
const wasteLine = waste > 0 ? `This audit
|
|
4546
|
+
const wasteLine = waste > 0 ? `This audit estimates <strong>${esc(usd3(waste))}</strong> of cache-miss exposure at current API list prices. ` : "";
|
|
4066
4547
|
if (licensed) {
|
|
4067
4548
|
const who = meta.license?.email ? ` (${esc(meta.license.email)})` : "";
|
|
4068
4549
|
steps.push(step(
|
|
@@ -4080,7 +4561,7 @@ function nextStepsSection(record, meta) {
|
|
|
4080
4561
|
steps.push(step(
|
|
4081
4562
|
n++,
|
|
4082
4563
|
"Track the movement",
|
|
4083
|
-
`<p>Every audit snapshots the derived record locally. Rerun in a week and compare: new
|
|
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")
|
|
4084
4565
|
));
|
|
4085
4566
|
steps.push(step(
|
|
4086
4567
|
n++,
|
|
@@ -4253,30 +4734,25 @@ table.ref td:first-child { white-space: nowrap; color: var(--umber); font-size:
|
|
|
4253
4734
|
function renderHtml(record, meta) {
|
|
4254
4735
|
const m = record.usageMetrics;
|
|
4255
4736
|
const mix = modelMix(m.modelBreakdown);
|
|
4256
|
-
const
|
|
4737
|
+
const accuracyNotesForRecord = accuracyNotes(record);
|
|
4257
4738
|
const mixCells = mix ? mix.split(" / ").map((part) => `<span class="nb">${esc(part)}</span>`).join(" / ") : "";
|
|
4258
4739
|
const subscription = record.plan !== void 0 && record.plan !== "api";
|
|
4259
|
-
const
|
|
4260
|
-
const
|
|
4261
|
-
const
|
|
4262
|
-
const
|
|
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)";
|
|
4263
4745
|
const w = record.usageWindows;
|
|
4264
|
-
|
|
4265
|
-
|
|
4266
|
-
|
|
4267
|
-
const extraMinutes = Math.round(w.p90WindowActiveMinutes * gain);
|
|
4268
|
-
headroom = ` Recovering ${shareText} buys about ${Math.round(gain * 100)}% more work per window: up to ~${extraMinutes} extra minutes in a window like your busiest.`;
|
|
4269
|
-
}
|
|
4270
|
-
const weeklyBurn = !subscription && meta.planSource === "default" && w?.assessed && w.medianWeekUsd >= 50 ? ` Your median week burns ${esc(usd3(w.medianWeekUsd))} at API rates.` : "";
|
|
4271
|
-
const planNote = subscription ? `<p class="sub">Plan: ${esc(record.plan)}. Dollar figures are API-equivalent token value, not money back; recovering them buys rate-limit headroom (more work per usage window).${headroom}</p>` : meta.planSource === "default" ? `<p class="sub">Dollar figures are API-equivalent rates.${weeklyBurn} On a Claude subscription? Rerun with --plan max20x (or pro, max5x) to frame results as token efficiency.</p>` : "";
|
|
4272
|
-
const windowTiles = subscription && w?.assessed ? `<div class="stats"><div class="stat"><div class="k">Median 5h window</div><div class="v">${esc(usd3(w.medianWindowUsd))}</div></div><div class="stat"><div class="k">Busiest 5h window (p90)</div><div class="v">${esc(usd3(w.p90WindowUsd))}</div></div><div class="stat"><div class="k">Busiest week</div><div class="v">${esc(usd3(w.maxWeekUsd))}</div></div></div>` : "";
|
|
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>` : "";
|
|
4273
4749
|
const dollarFixes = record.fixes.filter((f) => f.wasteUsd > 0).sort((a, b) => b.wasteUsd - a.wasteUsd);
|
|
4274
4750
|
const otherIssues = record.fixes.filter((f) => f.wasteUsd === 0);
|
|
4275
|
-
const dollarSection = dollarFixes.length === 0 ? `<p class="muted">No
|
|
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>`;
|
|
4276
4752
|
const otherSection = otherIssues.length === 0 ? "" : `<h2>Other issues to tighten</h2><ul class="fixes">${otherIssues.map(otherFixCard).join("")}</ul>`;
|
|
4277
4753
|
const bc = record.burnClock;
|
|
4278
4754
|
const burnSentence = bc?.assessed ? burnClockSentence(bc) : null;
|
|
4279
|
-
const burnSection = bc?.assessed ? `<h2>Burn Clock (
|
|
4755
|
+
const burnSection = bc?.assessed ? `<h2>Burn Clock (estimated current API-equivalent valuation by day)</h2>
|
|
4280
4756
|
<div class="chart">${burnClockChart(bc)}</div>
|
|
4281
4757
|
` + (burnSentence ? `<p class="sub">${esc(burnSentence)}</p>
|
|
4282
4758
|
` : "") : "";
|
|
@@ -4310,28 +4786,33 @@ ${planNote}
|
|
|
4310
4786
|
<div class="stats">
|
|
4311
4787
|
<div class="stat"><div class="k">${spendLabel}</div><div class="v">${esc(usd3(m.spendUsd))}</div></div>
|
|
4312
4788
|
<div class="stat"><div class="k">Cache hit rate</div><div class="v">${(m.cacheHitRate * 100).toFixed(1)}%</div></div>
|
|
4313
|
-
<div class="stat"><div class="k">
|
|
4789
|
+
<div class="stat"><div class="k">Session hours (timestamp union)</div><div class="v">${m.durationHours.toFixed(1)}</div></div>
|
|
4314
4790
|
${mix ? `<div class="stat"><div class="k">Model spend</div><div class="v v-small">${mixCells}</div></div>` : ""}
|
|
4315
4791
|
</div>
|
|
4316
|
-
${
|
|
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>` : ""}
|
|
4317
4794
|
${windowTiles}
|
|
4318
4795
|
|
|
4319
|
-
<h2>
|
|
4796
|
+
<h2>Projects by estimated current API-equivalent valuation</h2>
|
|
4320
4797
|
<div class="chart">${projectChart(m.topProjects)}</div>
|
|
4321
4798
|
|
|
4322
4799
|
${burnSection}
|
|
4323
|
-
<h2>
|
|
4800
|
+
<h2>Rule-based setup score</h2>
|
|
4324
4801
|
<div class="score-head">
|
|
4325
4802
|
<span class="big">${record.overallScore} / 100</span>
|
|
4326
4803
|
<span class="band">${esc(record.band.label)}</span>
|
|
4327
4804
|
</div>
|
|
4805
|
+
<p class="sub">A transparent heuristic from observed setup signals, not an Anthropic grade.</p>
|
|
4328
4806
|
${pillarBars(record.pillarScores)}
|
|
4329
4807
|
|
|
4330
|
-
<h2>Top
|
|
4808
|
+
<h2>Top changes ranked by estimated cache-miss exposure</h2>
|
|
4331
4809
|
${dollarSection}
|
|
4332
4810
|
${otherSection}
|
|
4333
4811
|
${skippedNote}
|
|
4334
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
|
+
|
|
4335
4816
|
${nextStepsSection(record, meta)}
|
|
4336
4817
|
|
|
4337
4818
|
<div class="footer">
|
|
@@ -4354,7 +4835,7 @@ var PAPER = "#fefaf7";
|
|
|
4354
4835
|
var BORDER = "#f0e2da";
|
|
4355
4836
|
var MUTED = "#7a6a63";
|
|
4356
4837
|
function usd4(n) {
|
|
4357
|
-
return `$${(
|
|
4838
|
+
return `$${roundMoneyHalfUp(n).toFixed(2)}`;
|
|
4358
4839
|
}
|
|
4359
4840
|
function strongestPillar(pillars) {
|
|
4360
4841
|
const assessed = pillars.filter((p) => p.assessed && p.score !== null);
|
|
@@ -4368,9 +4849,10 @@ function renderCard(record) {
|
|
|
4368
4849
|
const cacheHitPct = `${(record.usageMetrics.cacheHitRate * 100).toFixed(1)}%`;
|
|
4369
4850
|
const subscription = record.plan !== void 0 && record.plan !== "api";
|
|
4370
4851
|
const spend = record.usageMetrics.spendUsd;
|
|
4371
|
-
const
|
|
4372
|
-
const
|
|
4373
|
-
const
|
|
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}`;
|
|
4374
4856
|
const scoreText = String(record.overallScore);
|
|
4375
4857
|
const scoreX = 32;
|
|
4376
4858
|
const scoreW = estimateTextWidth(scoreText, 72);
|
|
@@ -4590,8 +5072,8 @@ async function deactivateLicense(opts = {}) {
|
|
|
4590
5072
|
// src/plan-prompt.ts
|
|
4591
5073
|
import { createInterface } from "readline/promises";
|
|
4592
5074
|
var PLAN_PROMPT_LINES = [
|
|
4593
|
-
"How do you pay for Claude Code? This
|
|
4594
|
-
"
|
|
5075
|
+
"How do you pay for Claude Code? This adds the right caveat to the report's",
|
|
5076
|
+
"estimated current API-equivalent valuations.",
|
|
4595
5077
|
"",
|
|
4596
5078
|
" 1) API, pay per token",
|
|
4597
5079
|
" 2) Pro subscription",
|
|
@@ -4718,6 +5200,7 @@ async function runAudit(opts) {
|
|
|
4718
5200
|
questionnaire: {},
|
|
4719
5201
|
setup,
|
|
4720
5202
|
plan,
|
|
5203
|
+
timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
|
|
4721
5204
|
tzOffsetMinutes: -(/* @__PURE__ */ new Date()).getTimezoneOffset()
|
|
4722
5205
|
});
|
|
4723
5206
|
const baseline = (await readCliConfig(configDir)).lastOptimize;
|
|
@@ -5060,7 +5543,7 @@ function approxTokens(n) {
|
|
|
5060
5543
|
function plural2(n, noun) {
|
|
5061
5544
|
return n === 1 ? noun : `${noun}s`;
|
|
5062
5545
|
}
|
|
5063
|
-
function
|
|
5546
|
+
function num4(n) {
|
|
5064
5547
|
return String(Math.round(n)).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
|
|
5065
5548
|
}
|
|
5066
5549
|
var STYLE2 = `
|
|
@@ -5298,7 +5781,7 @@ function renderSectionsStat(sections) {
|
|
|
5298
5781
|
}
|
|
5299
5782
|
function renderRecoverableStat(input) {
|
|
5300
5783
|
const pct2 = `${(input.headlineWasteShare * 100).toFixed(1)}%`;
|
|
5301
|
-
return `<div class="stat"><span class="l">
|
|
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>`;
|
|
5302
5785
|
}
|
|
5303
5786
|
function renderReceipt(input) {
|
|
5304
5787
|
const stats = `<div class="grid g3">${renderTokenStat(input)}${renderSectionsStat(input.sectionDispositions)}${renderRecoverableStat(input)}</div>`;
|
|
@@ -5331,11 +5814,11 @@ function renderCacheTable2(report) {
|
|
|
5331
5814
|
const tailUsd = tail.reduce((sum, r) => sum + r.usd, 0);
|
|
5332
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>`;
|
|
5333
5816
|
}
|
|
5334
|
-
return `<h4 style="margin:20px 0 8px;font-size:.9rem">
|
|
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>`;
|
|
5335
5818
|
}
|
|
5336
5819
|
function renderFixes(fixes, report) {
|
|
5337
5820
|
const dollarFixes = fixes.filter((f) => f.wasteUsd > 0).sort((a, b) => b.wasteUsd - a.wasteUsd);
|
|
5338
|
-
if (dollarFixes.length === 0) return `<p class="note">No
|
|
5821
|
+
if (dollarFixes.length === 0) return `<p class="note">No cache-miss exposure estimate found.</p>`;
|
|
5339
5822
|
return dollarFixes.map((f, i) => {
|
|
5340
5823
|
const table = f.id === "cache_recovery" ? renderCacheTable2(report) : "";
|
|
5341
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>`;
|
|
@@ -5399,7 +5882,7 @@ function renderCarriedDisclosure(sections, carriedTokens) {
|
|
|
5399
5882
|
const carried = sections.filter((s) => s.disposition === "carried");
|
|
5400
5883
|
if (carried.length === 0) return "";
|
|
5401
5884
|
const names = carried.map((s) => esc(s.name)).join(" · ");
|
|
5402
|
-
const weight = carriedTokens > 0 ? `, about ${
|
|
5885
|
+
const weight = carriedTokens > 0 ? `, about ${num4(carriedTokens)} tokens` : "";
|
|
5403
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>` : "";
|
|
5404
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>`;
|
|
5405
5888
|
}
|
|
@@ -5430,7 +5913,7 @@ ${renderReceipt(input)}
|
|
|
5430
5913
|
<h2>Your CLAUDE.md, before and after<span class="n">what actually changed</span></h2>
|
|
5431
5914
|
<div class="panel">${renderComparisonTabs(input)}</div>
|
|
5432
5915
|
${input.review ? `
|
|
5433
|
-
<h2>What to change in your CLAUDE.md<span class="n">${
|
|
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>
|
|
5434
5917
|
<div class="panel">${renderAnnotatedFile(input.review)}</div>` : ""}
|
|
5435
5918
|
|
|
5436
5919
|
<h2>Fixes, ranked by what they recover</h2>
|
|
@@ -5498,7 +5981,7 @@ function renderLines(lines, keepRunMax) {
|
|
|
5498
5981
|
const tail = run.slice(run.length - half);
|
|
5499
5982
|
for (const i of head) out.push(lineHtml(lines[i], i + 1));
|
|
5500
5983
|
out.push(
|
|
5501
|
-
`<span class="ln skip"><span class="g"></span>... ${
|
|
5984
|
+
`<span class="ln skip"><span class="g"></span>... ${num4(run.length - head.length - tail.length)} unchanged lines ...</span>`
|
|
5502
5985
|
);
|
|
5503
5986
|
for (const i of tail) out.push(lineHtml(lines[i], i + 1));
|
|
5504
5987
|
} else {
|
|
@@ -5532,7 +6015,7 @@ function renderAnnotatedFile(review) {
|
|
|
5532
6015
|
function reviewCountLine(review) {
|
|
5533
6016
|
const n = review.changes.length;
|
|
5534
6017
|
if (n === 0) return `No changes proposed for ${esc(review.label)}.`;
|
|
5535
|
-
return `<b>${
|
|
6018
|
+
return `<b>${num4(n)} proposed ${plural2(n, "change")}</b> to ${esc(review.label)}`;
|
|
5536
6019
|
}
|
|
5537
6020
|
var INDEX_STYLE = `
|
|
5538
6021
|
.rowpath{display:block;font-size:.76rem;color:var(--ink2);font-family:var(--mono);word-break:break-all}
|
|
@@ -5573,8 +6056,8 @@ function renderPromptPanel(review) {
|
|
|
5573
6056
|
function renderGlobalPanel(review) {
|
|
5574
6057
|
const t = review.tokens;
|
|
5575
6058
|
const importCount = review.importCount;
|
|
5576
|
-
const imported = importCount > 0 ? ` plus ${
|
|
5577
|
-
const weight = `<p class="revhead"><b>${esc(review.label)}</b>${imported}: about ${
|
|
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>`;
|
|
5578
6061
|
return `<div class="panel">${weight}${renderAnnotatedFile(review)}</div>`;
|
|
5579
6062
|
}
|
|
5580
6063
|
function renderProjectPanels(input, review) {
|
|
@@ -5583,7 +6066,7 @@ function renderProjectPanels(input, review) {
|
|
|
5583
6066
|
const r = review.projects.get(row.slug);
|
|
5584
6067
|
if (!r) return;
|
|
5585
6068
|
out.push(
|
|
5586
|
-
`<details${i === 0 ? " open" : ""}><summary>${esc(row.slug)}: ${
|
|
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>`
|
|
5587
6070
|
);
|
|
5588
6071
|
});
|
|
5589
6072
|
return out.join("");
|
|
@@ -5594,7 +6077,7 @@ function renderOptimizeIndex(input) {
|
|
|
5594
6077
|
const rows = input.rows.map(
|
|
5595
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>`
|
|
5596
6079
|
).join("");
|
|
5597
|
-
const body = input.rows.length === 0 ? `<p class="note">No project directories from your audit were found on this machine, so nothing was generated.</p>` : `<div class="scroll"><table><thead><tr><th>Project</th><th class="num">
|
|
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>`;
|
|
5598
6081
|
const banner = input.serve?.message ? `<p class="banner">${esc(input.serve.message)}</p>` : "";
|
|
5599
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>` : "";
|
|
5600
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>`;
|
|
@@ -5611,7 +6094,7 @@ ${input.review ? `<script>${COPY_SCRIPT}</script>` : ""}
|
|
|
5611
6094
|
<div class="wrap">
|
|
5612
6095
|
<header><p class="kicker">CostClaw optimize · generated locally · nothing left your machine</p>
|
|
5613
6096
|
<h1>${input.rows.length} ${plural2(input.rows.length, "project")} ready to apply</h1>
|
|
5614
|
-
<p class="sub">${esc(usd5(total))}
|
|
6097
|
+
<p class="sub">${esc(usd5(total))} estimated current API-equivalent valuation · ${esc(usd5(recoverable))} cache-miss exposure estimate ·
|
|
5615
6098
|
artifacts in ${esc(input.root)}/</p></header>
|
|
5616
6099
|
|
|
5617
6100
|
${banner}${done}
|
|
@@ -6454,7 +6937,7 @@ var DEFAULT_LIMIT = 10;
|
|
|
6454
6937
|
function usd6(n) {
|
|
6455
6938
|
return `$${(Math.round(n * 100) / 100).toFixed(2)}`;
|
|
6456
6939
|
}
|
|
6457
|
-
function
|
|
6940
|
+
function num5(n) {
|
|
6458
6941
|
return String(Math.round(n)).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
|
|
6459
6942
|
}
|
|
6460
6943
|
function describeDetection(project) {
|
|
@@ -6495,10 +6978,10 @@ async function generateForProject(ctx, projectDir, artifactsDir) {
|
|
|
6495
6978
|
let currentClaudeMd = ctx.claudeMdOverride;
|
|
6496
6979
|
let claudeMdSource = ctx.claudeMdOverride !== void 0 ? ctx.claudeMdFallbackSource : null;
|
|
6497
6980
|
if (currentClaudeMd === void 0) {
|
|
6498
|
-
const
|
|
6499
|
-
if (await pathExists2(
|
|
6500
|
-
currentClaudeMd = await readFile10(
|
|
6501
|
-
claudeMdSource =
|
|
6981
|
+
const own2 = join10(projectDir, "CLAUDE.md");
|
|
6982
|
+
if (await pathExists2(own2)) {
|
|
6983
|
+
currentClaudeMd = await readFile10(own2, "utf8");
|
|
6984
|
+
claudeMdSource = own2;
|
|
6502
6985
|
}
|
|
6503
6986
|
}
|
|
6504
6987
|
const project = await scanProject(projectDir);
|
|
@@ -6560,11 +7043,11 @@ async function generateForProject(ctx, projectDir, artifactsDir) {
|
|
|
6560
7043
|
const denominator = recoverable !== null ? spend ?? 0 : ctx.report.summary.cost_usd;
|
|
6561
7044
|
const scopeLabel = recoverable !== null ? `for ${slug}` : "across your audited projects";
|
|
6562
7045
|
if (ctx.plan === "api") {
|
|
6563
|
-
lines.push(`
|
|
7046
|
+
lines.push(`Cache-miss exposure (estimate) ${scopeLabel}: ${usd6(shownRecoverable)} estimated current API-equivalent valuation`);
|
|
6564
7047
|
} else {
|
|
6565
7048
|
const share = denominator > 0 ? shownRecoverable / denominator * 100 : 0;
|
|
6566
7049
|
lines.push(
|
|
6567
|
-
`
|
|
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)`
|
|
6568
7051
|
);
|
|
6569
7052
|
}
|
|
6570
7053
|
const { before, after } = result.claudeMdTokens;
|
|
@@ -6572,11 +7055,11 @@ async function generateForProject(ctx, projectDir, artifactsDir) {
|
|
|
6572
7055
|
const pct2 = before > 0 ? (Math.abs(after - before) / before * 100).toFixed(1) : "0.0";
|
|
6573
7056
|
const dir = after > before ? "larger" : "smaller";
|
|
6574
7057
|
lines.push(
|
|
6575
|
-
`Your CLAUDE.md: an estimated ${
|
|
7058
|
+
`Your CLAUDE.md: an estimated ${num5(before)} tokens to ${num5(after)} (${pct2}% ${dir}), paid on every turn.`
|
|
6576
7059
|
);
|
|
6577
7060
|
if (result.carriedTokens >= after / 2) {
|
|
6578
7061
|
lines.push(
|
|
6579
|
-
`About ${
|
|
7062
|
+
`About ${num5(result.carriedTokens)} of those tokens are your own prose, carried through as written.`,
|
|
6580
7063
|
"costclaw does not rewrite prose, so trimming it is judgment work: HARNESS-UPGRADE.md",
|
|
6581
7064
|
"ranks your heaviest sections and flags the dated lines to move into docs/."
|
|
6582
7065
|
);
|
|
@@ -6591,7 +7074,7 @@ async function generateForProject(ctx, projectDir, artifactsDir) {
|
|
|
6591
7074
|
for (const note of result.notes) lines.push(` - ${note}`);
|
|
6592
7075
|
if (review.changes.length > 0) {
|
|
6593
7076
|
const n = review.changes.length;
|
|
6594
|
-
lines.push(`Review: ${
|
|
7077
|
+
lines.push(`Review: ${num5(n)} proposed ${n === 1 ? "change" : "changes"} to ${review.label}`);
|
|
6595
7078
|
}
|
|
6596
7079
|
lines.push(`Artifacts: ${artifactsDir}`);
|
|
6597
7080
|
lines.push(`Apply: ${applyCommand}`);
|
|
@@ -6619,8 +7102,8 @@ async function runOptimize(opts) {
|
|
|
6619
7102
|
const home = opts.home ?? homedir5();
|
|
6620
7103
|
let inputsClaudeMdPath = opts.claudeMdPath;
|
|
6621
7104
|
if (!inputsClaudeMdPath && opts.projectDir) {
|
|
6622
|
-
const
|
|
6623
|
-
if (await pathExists2(
|
|
7105
|
+
const own2 = join10(opts.projectDir, "CLAUDE.md");
|
|
7106
|
+
if (await pathExists2(own2)) inputsClaudeMdPath = own2;
|
|
6624
7107
|
}
|
|
6625
7108
|
const { logs, claudeMd, claudeMdSource, projectDirs } = await loadAuditInputs({
|
|
6626
7109
|
path: opts.path,
|
|
@@ -6641,7 +7124,13 @@ async function runOptimize(opts) {
|
|
|
6641
7124
|
totals: { ...report.summary.totals },
|
|
6642
7125
|
cacheHitRate: report.summary.cacheHitRate,
|
|
6643
7126
|
headlineWasteShare: baselineSpend > 0 ? auditRecoverable / baselineSpend : 0,
|
|
6644
|
-
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
|
+
} : {}
|
|
6645
7134
|
}
|
|
6646
7135
|
});
|
|
6647
7136
|
const single = opts.projectDir !== void 0;
|
|
@@ -6784,7 +7273,7 @@ async function runOptimize(opts) {
|
|
|
6784
7273
|
const projectChanges = outcomes.reduce((sum, o) => sum + o.review.changes.length, 0);
|
|
6785
7274
|
lines.push("");
|
|
6786
7275
|
lines.push(
|
|
6787
|
-
`Your CLAUDE.md review: ${
|
|
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"}.`
|
|
6788
7277
|
);
|
|
6789
7278
|
lines.push("One prompt applies all of it. Hand this to your own Claude Code:");
|
|
6790
7279
|
lines.push(` claude "Follow ${upgradeAllPath}"`);
|
|
@@ -6873,7 +7362,7 @@ import { homedir as homedir6 } from "os";
|
|
|
6873
7362
|
|
|
6874
7363
|
// src/format-diff.ts
|
|
6875
7364
|
function usd7(n) {
|
|
6876
|
-
return `$${(Math.
|
|
7365
|
+
return `$${roundMoneyHalfUp(Math.abs(n)).toFixed(2)}`;
|
|
6877
7366
|
}
|
|
6878
7367
|
function signedUsd(n) {
|
|
6879
7368
|
return `${n < 0 ? "-" : "+"}${usd7(n)}`;
|
|
@@ -6897,28 +7386,36 @@ function formatDiff(d) {
|
|
|
6897
7386
|
if (d.comparable && d.marginal) {
|
|
6898
7387
|
lines.push("Since the baseline:");
|
|
6899
7388
|
lines.push(
|
|
6900
|
-
` New
|
|
7389
|
+
` New valuation (estimate) ${usd7(d.marginal.newSpendUsd)} across ${d.marginal.newSessions} new sessions`
|
|
6901
7390
|
);
|
|
6902
7391
|
lines.push(
|
|
6903
7392
|
` Marginal cache hit ${pct(d.marginal.marginalCacheHitRate)} (lifetime ${pct(d.current.cacheHitRate)})`
|
|
6904
7393
|
);
|
|
6905
7394
|
lines.push(
|
|
6906
|
-
`
|
|
7395
|
+
` Cache-miss exposure (estimate) ${signedUsd(d.deltas.recoverableUsd)} (now ${usd7(d.current.recoverableUsd)})`
|
|
6907
7396
|
);
|
|
6908
7397
|
} else {
|
|
6909
|
-
|
|
6910
|
-
|
|
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
|
+
}
|
|
6911
7408
|
lines.push("");
|
|
6912
7409
|
lines.push(
|
|
6913
|
-
`Baseline (${day(d.baseline.createdAt)}):
|
|
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)}`
|
|
6914
7411
|
);
|
|
6915
7412
|
lines.push(
|
|
6916
|
-
`Current (${day(d.current.createdAt)}):
|
|
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)}`
|
|
6917
7414
|
);
|
|
6918
7415
|
}
|
|
6919
7416
|
lines.push("");
|
|
6920
7417
|
lines.push(
|
|
6921
|
-
`
|
|
7418
|
+
`Rule-based setup score: ${d.baseline.overallScore} -> ${d.current.overallScore} (${signedInt(d.deltas.overallScore)}, ${d.current.band}; not an Anthropic grade)`
|
|
6922
7419
|
);
|
|
6923
7420
|
for (const p of d.pillars) {
|
|
6924
7421
|
const before = p.before === null ? "n/a" : String(p.before);
|
|
@@ -6929,27 +7426,29 @@ function formatDiff(d) {
|
|
|
6929
7426
|
if (d.current.plan && d.current.plan !== "api") {
|
|
6930
7427
|
lines.push("");
|
|
6931
7428
|
lines.push(
|
|
6932
|
-
`Plan: ${d.current.plan}. Dollar figures are API-equivalent
|
|
7429
|
+
`Plan: ${d.current.plan}. Dollar figures are estimated current API-equivalent valuations, not money back, actual quota, or a promise of more work.`
|
|
6933
7430
|
);
|
|
6934
7431
|
}
|
|
6935
7432
|
const { resolved, appeared, changed } = d.fixes;
|
|
6936
7433
|
if (resolved.length > 0) {
|
|
6937
7434
|
lines.push("");
|
|
6938
7435
|
lines.push("Fixes resolved since the baseline:");
|
|
6939
|
-
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}`);
|
|
6940
7437
|
}
|
|
6941
7438
|
if (appeared.length > 0) {
|
|
6942
7439
|
lines.push("");
|
|
6943
7440
|
lines.push("New since the baseline:");
|
|
6944
|
-
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}`);
|
|
6945
7442
|
}
|
|
6946
7443
|
if (changed.length > 0) {
|
|
6947
7444
|
lines.push("");
|
|
6948
7445
|
lines.push("Fixes that moved:");
|
|
6949
7446
|
for (const c of changed) {
|
|
6950
|
-
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)`);
|
|
6951
7448
|
}
|
|
6952
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.");
|
|
6953
7452
|
return lines.join("\n");
|
|
6954
7453
|
}
|
|
6955
7454
|
|
|
@@ -7055,7 +7554,7 @@ function parseApplyFlags(args) {
|
|
|
7055
7554
|
};
|
|
7056
7555
|
}
|
|
7057
7556
|
function cliVersion() {
|
|
7058
|
-
return true ? "0.12.
|
|
7557
|
+
return true ? "0.12.4" : "0.0.0-dev";
|
|
7059
7558
|
}
|
|
7060
7559
|
function isHelpRequest(command, args) {
|
|
7061
7560
|
if (command === void 0) return false;
|
|
@@ -7083,17 +7582,17 @@ function helpText() {
|
|
|
7083
7582
|
"and opens it in your browser; --no-html skips that, --html <file> picks the",
|
|
7084
7583
|
"path, and --json runs stay file-free unless --html is passed explicitly.",
|
|
7085
7584
|
"--card writes a shareable 600x315 score card SVG (default: costclaw-card.svg):",
|
|
7086
|
-
"score, band,
|
|
7585
|
+
"rule-based setup score, band, cache-miss exposure estimate, cache hit rate, and your strongest pillar.",
|
|
7087
7586
|
"--plan <api|pro|max5x|max20x> declares how you pay for Claude. On a",
|
|
7088
|
-
"subscription (Pro/Max)
|
|
7089
|
-
"money back,
|
|
7090
|
-
"
|
|
7091
|
-
"
|
|
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;",
|
|
7092
7591
|
"--plan api switches back. Pass nothing and the first interactive run asks",
|
|
7093
7592
|
"once and saves the answer; piped, --json and CI runs are never asked and",
|
|
7094
7593
|
"assume API rates.",
|
|
7095
7594
|
"",
|
|
7096
|
-
"diff compares two audits and shows the movement: new
|
|
7595
|
+
"diff compares two audits and shows the movement: new valuation estimates since the baseline,",
|
|
7097
7596
|
"the marginal cache hit rate for just that period, score changes per pillar, and",
|
|
7098
7597
|
"which fixes were resolved. Every audit run saves a snapshot to",
|
|
7099
7598
|
"~/.costclaw/history, so plain `costclaw diff` compares your latest two runs;",
|