burnoff 1.0.0 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.github/workflows/burnoff-pr-gate.yml +75 -0
- package/README.md +100 -14
- package/bin/burnoff.mjs +71 -16
- package/hooks/hook-io.mjs +8 -11
- package/package.json +3 -2
- package/src/ci/ci-gate.mjs +62 -9
- package/src/ci/pr-cost.mjs +167 -14
- package/src/ci/team-digest.mjs +1 -1
- package/src/cli/audit.mjs +74 -5
- package/src/cli/doctor.mjs +22 -12
- package/src/cli/init.mjs +92 -5
- package/src/cli/startup-audit.mjs +2348 -0
- package/src/config/catalog.json +188 -45
- package/src/config/loader.mjs +85 -9
- package/src/config/paths.mjs +30 -0
- package/src/config/policy.mjs +69 -12
- package/src/config/pricing.mjs +1022 -0
- package/src/config/uncached-attribution.mjs +719 -0
- package/src/guards/loop-breaker.mjs +72 -14
- package/src/guards/post-tool-engine.mjs +33 -12
- package/src/guards/pre-tool-engine.mjs +54 -2
- package/src/guards/read-clamp.mjs +73 -59
- package/src/guards/shell-guard.mjs +45 -19
- package/src/storage/atomic-io.mjs +2 -2
- package/src/storage/file-lock.mjs +53 -9
- package/src/storage/fts5-archive.mjs +27 -12
- package/src/storage/jsonl-parser.mjs +202 -19
- package/src/storage/ledger.mjs +7 -9
- package/src/storage/sqlite-client.mjs +31 -9
package/src/ci/pr-cost.mjs
CHANGED
|
@@ -12,6 +12,8 @@ import fs from 'node:fs';
|
|
|
12
12
|
import os from 'node:os';
|
|
13
13
|
import path from 'node:path';
|
|
14
14
|
import { getHomeDir } from '../config/paths.mjs';
|
|
15
|
+
import { DEFAULT_UNMAPPED_CACHED_WEIGHT, valuateCall } from '../config/pricing.mjs';
|
|
16
|
+
import { attributeUncachedTokens } from '../config/uncached-attribution.mjs';
|
|
15
17
|
import { readLedgerEntries } from '../storage/ledger.mjs';
|
|
16
18
|
import {
|
|
17
19
|
discoverClaudeCodeSessions,
|
|
@@ -199,15 +201,46 @@ export function collectGitBranchCommits(
|
|
|
199
201
|
|
|
200
202
|
function extractStepFields(step = {}, cwd = '') {
|
|
201
203
|
const usage = step.tokenUsage || {};
|
|
202
|
-
const inTok =
|
|
203
|
-
|
|
204
|
-
|
|
204
|
+
const inTok = Number(
|
|
205
|
+
step.uncachedTokens ??
|
|
206
|
+
step.uncachedInputTokens ??
|
|
207
|
+
step.freshInputTokens ??
|
|
208
|
+
step.inputTokens ??
|
|
209
|
+
step.input_tokens ??
|
|
210
|
+
usage.freshInputTokens ??
|
|
211
|
+
usage.inputTokens ??
|
|
212
|
+
0
|
|
213
|
+
);
|
|
214
|
+
const cacheWrite5mTok = Number(
|
|
215
|
+
step.cacheWrite5mTokens ??
|
|
216
|
+
step.write5mTokens ??
|
|
217
|
+
step.cache_write_5m_tokens ??
|
|
218
|
+
step.cacheCreationEphemeral5mInputTokens ??
|
|
219
|
+
usage.cacheWrite5mTokens ??
|
|
220
|
+
usage.cacheCreationEphemeral5mInputTokens ??
|
|
221
|
+
0
|
|
222
|
+
);
|
|
223
|
+
const cacheWrite1hTok = Number(
|
|
224
|
+
step.cacheWrite1hTokens ??
|
|
225
|
+
step.write1hTokens ??
|
|
226
|
+
step.cache_write_1h_tokens ??
|
|
227
|
+
step.cacheCreationEphemeral1hInputTokens ??
|
|
228
|
+
usage.cacheWrite1hTokens ??
|
|
229
|
+
usage.cacheCreationEphemeral1hInputTokens ??
|
|
230
|
+
0
|
|
231
|
+
);
|
|
232
|
+
const cacheCreationTok = Number(
|
|
233
|
+
step.cacheCreationTokens ?? step.cache_creation_input_tokens ?? usage.cacheCreationTokens ?? 0
|
|
234
|
+
);
|
|
235
|
+
const cacheWriteTok = Math.max(cacheCreationTok, cacheWrite5mTok + cacheWrite1hTok);
|
|
205
236
|
const cacheReadTok = Number(
|
|
206
237
|
step.cacheReadTokens ?? step.cache_read_input_tokens ?? usage.cacheReadTokens ?? 0
|
|
207
238
|
);
|
|
208
239
|
const outTok =
|
|
209
240
|
Number(step.outputTokens ?? step.output_tokens ?? usage.outputTokens ?? 0) +
|
|
210
241
|
Number(step.thinkingTokens ?? step.thinking_tokens ?? usage.thinkingTokens ?? 0);
|
|
242
|
+
const hasExplicitWaste =
|
|
243
|
+
step.wasteTokens !== undefined || step.wastedTokens !== undefined;
|
|
211
244
|
const wasteTok = Number(step.wasteTokens ?? step.wastedTokens ?? 0);
|
|
212
245
|
const rawTs = step.timestampMs ?? step.createdAt ?? step.created_at ?? step.timestamp ?? null;
|
|
213
246
|
const tsMs = typeof rawTs === 'number' ? rawTs : rawTs ? Date.parse(String(rawTs)) : NaN;
|
|
@@ -239,19 +272,56 @@ function extractStepFields(step = {}, cwd = '') {
|
|
|
239
272
|
(step.decision === 'deny' && RING0_DETECTORS.has(detector));
|
|
240
273
|
|
|
241
274
|
return {
|
|
275
|
+
model: step.model || step.modelId || usage.model || null,
|
|
276
|
+
label: step.label || null,
|
|
277
|
+
sessionId: step.sessionId || step.conv || 'default',
|
|
278
|
+
stepIndex: step.stepIndex ?? null,
|
|
242
279
|
inTok,
|
|
280
|
+
cacheWrite5mTok,
|
|
281
|
+
cacheWrite1hTok,
|
|
282
|
+
cacheCreationTok,
|
|
283
|
+
cacheWriteTok,
|
|
243
284
|
cacheReadTok,
|
|
244
285
|
outTok,
|
|
245
286
|
wasteTok,
|
|
246
|
-
|
|
287
|
+
hasExplicitWaste,
|
|
288
|
+
totalTok: inTok + cacheWriteTok + cacheReadTok + outTok,
|
|
247
289
|
tsMs: Number.isFinite(tsMs) ? tsMs : null,
|
|
290
|
+
hadCompactionBefore: Boolean(step.hadCompactionBefore),
|
|
291
|
+
isCompactSummary: Boolean(step.isCompactSummary),
|
|
292
|
+
isCompactionBoundary: Boolean(step.isCompactionBoundary),
|
|
293
|
+
isSidechain: Boolean(step.isSidechain),
|
|
294
|
+
entrypoint: step.entrypoint || null,
|
|
295
|
+
shapeHash: step.shapeHash || null,
|
|
296
|
+
cacheTtlTier: step.cacheTtlTier || (cacheWrite1hTok > 0 ? '1h' : '5m'),
|
|
248
297
|
filesTouched: Array.from(filesTouched),
|
|
249
298
|
isRing0
|
|
250
299
|
};
|
|
251
300
|
}
|
|
252
301
|
|
|
253
|
-
function computeStepCostUsd(inTok, cacheReadTok, outTok, pricePerMillionUsd = 3.0) {
|
|
254
|
-
return (
|
|
302
|
+
function computeStepCostUsd(inTok, cacheReadTok, outTok, pricePerMillionUsd = 3.0, cacheWriteTok = 0) {
|
|
303
|
+
return (
|
|
304
|
+
(inTok * 1.0 + cacheWriteTok * 1.25 + cacheReadTok * DEFAULT_UNMAPPED_CACHED_WEIGHT + outTok * 5.0) /
|
|
305
|
+
1_000_000
|
|
306
|
+
) * pricePerMillionUsd;
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
function computeStepUsdWithModel(st, pricePerMillionUsd, hasExplicitPriceOverride) {
|
|
310
|
+
if (!hasExplicitPriceOverride && st?.model) {
|
|
311
|
+
const val = valuateCall({
|
|
312
|
+
model: st.model,
|
|
313
|
+
label: st.label,
|
|
314
|
+
timestampMs: st.tsMs,
|
|
315
|
+
uncachedTokens: st.inTok,
|
|
316
|
+
cachedTokens: st.cacheReadTok,
|
|
317
|
+
cacheWrite5mTokens: st.cacheWrite5mTok,
|
|
318
|
+
cacheWrite1hTokens: st.cacheWrite1hTok,
|
|
319
|
+
cacheCreationTokens: st.cacheCreationTok,
|
|
320
|
+
outputTokens: st.outTok
|
|
321
|
+
});
|
|
322
|
+
if (val.totalEstimatedUsd !== null) return val.totalEstimatedUsd;
|
|
323
|
+
}
|
|
324
|
+
return computeStepCostUsd(st.inTok, st.cacheReadTok, st.outTok, pricePerMillionUsd, st.cacheWriteTok);
|
|
255
325
|
}
|
|
256
326
|
|
|
257
327
|
/**
|
|
@@ -262,6 +332,7 @@ export function buildPrCostAttribution(options = {}) {
|
|
|
262
332
|
const homeDir = options.homeDir || getHomeDir();
|
|
263
333
|
const base = String(options.base || 'main');
|
|
264
334
|
const head = String(options.head || 'HEAD');
|
|
335
|
+
const hasExplicitPriceOverride = options.pricePerMillionUsd !== undefined && options.pricePerMillionUsd !== null;
|
|
265
336
|
const pricePerMillionUsd = Number(options.pricePerMillionUsd || 3.0);
|
|
266
337
|
|
|
267
338
|
let commits = Array.isArray(options.commits) ? options.commits : null;
|
|
@@ -280,10 +351,13 @@ export function buildPrCostAttribution(options = {}) {
|
|
|
280
351
|
}
|
|
281
352
|
|
|
282
353
|
const rawSteps = [];
|
|
354
|
+
let sessionCount = 0;
|
|
283
355
|
if (Array.isArray(options.steps)) {
|
|
284
356
|
rawSteps.push(...options.steps);
|
|
357
|
+
sessionCount = Math.max(sessionCount, options.steps.length > 0 ? 1 : 0);
|
|
285
358
|
}
|
|
286
359
|
if (Array.isArray(options.sessions)) {
|
|
360
|
+
sessionCount = Math.max(sessionCount, options.sessions.length);
|
|
287
361
|
for (const sess of options.sessions) {
|
|
288
362
|
if (Array.isArray(sess?.steps)) rawSteps.push(...sess.steps);
|
|
289
363
|
}
|
|
@@ -291,10 +365,16 @@ export function buildPrCostAttribution(options = {}) {
|
|
|
291
365
|
if (!Array.isArray(options.steps) && !Array.isArray(options.sessions) && options.readSessions !== false) {
|
|
292
366
|
const maxSessions = Math.max(1, Number(options.maxSessions ?? 20));
|
|
293
367
|
const discovered = discoverClaudeCodeSessions(homeDir, { cwd }).slice(0, maxSessions);
|
|
368
|
+
sessionCount = discovered.length;
|
|
294
369
|
for (const meta of discovered) {
|
|
295
370
|
const parsed = parseTranscriptIncremental(meta.filePath, { homeDir });
|
|
296
371
|
if (Array.isArray(parsed?.steps)) {
|
|
297
|
-
rawSteps.push(
|
|
372
|
+
rawSteps.push(
|
|
373
|
+
...parsed.steps.map((st) => ({
|
|
374
|
+
...st,
|
|
375
|
+
sessionId: st.sessionId || meta.sessionId || 'default'
|
|
376
|
+
}))
|
|
377
|
+
);
|
|
298
378
|
}
|
|
299
379
|
}
|
|
300
380
|
}
|
|
@@ -333,6 +413,7 @@ export function buildPrCostAttribution(options = {}) {
|
|
|
333
413
|
}
|
|
334
414
|
|
|
335
415
|
const matchingLedger = rawLedger.filter((entry) => {
|
|
416
|
+
if (entry?.cwd && path.resolve(String(entry.cwd)) !== cwd) return false;
|
|
336
417
|
const rawTs = entry.timestamp ?? entry.ts ?? null;
|
|
337
418
|
const tsMs = typeof rawTs === 'number' ? rawTs : rawTs ? Date.parse(String(rawTs)) : NaN;
|
|
338
419
|
if (!Number.isFinite(tsMs) || !validTimestamps.length) return true;
|
|
@@ -340,15 +421,24 @@ export function buildPrCostAttribution(options = {}) {
|
|
|
340
421
|
});
|
|
341
422
|
|
|
342
423
|
const ledgerSavedUsd = matchingLedger.reduce((s, e) => s + Number(e.savedUSD ?? e.savedUsd ?? 0), 0);
|
|
424
|
+
const ledgerRing0Count = matchingLedger.filter(
|
|
425
|
+
(e) =>
|
|
426
|
+
Boolean(e?.ring0Violation) ||
|
|
427
|
+
RING0_DETECTORS.has(String(e?.detectorId || e?.detector || '').toUpperCase()) ||
|
|
428
|
+
String(e?.category || '').toUpperCase() === 'RING0_VIOLATION_BLOCKED'
|
|
429
|
+
).length;
|
|
343
430
|
|
|
344
431
|
const commitBuckets = new Map(sortedCommits.map((_, idx) => [idx, []]));
|
|
345
432
|
const totalBranchLoc = sortedCommits.reduce((s, c) => s + Math.max(1, c.totalLoc || 0), 0);
|
|
346
433
|
|
|
347
434
|
let unmatchedIn = 0;
|
|
435
|
+
let unmatchedWrite = 0;
|
|
348
436
|
let unmatchedCache = 0;
|
|
349
437
|
let unmatchedOut = 0;
|
|
438
|
+
let unmatchedUsd = 0;
|
|
350
439
|
let unmatchedWaste = 0;
|
|
351
440
|
let unmatchedRing0 = 0;
|
|
441
|
+
const matchedAttrSteps = [];
|
|
352
442
|
|
|
353
443
|
for (const st of normalizedSteps) {
|
|
354
444
|
let assignedIdx = -1;
|
|
@@ -380,39 +470,80 @@ export function buildPrCostAttribution(options = {}) {
|
|
|
380
470
|
|
|
381
471
|
if (assignedIdx >= 0) {
|
|
382
472
|
commitBuckets.get(assignedIdx).push(st);
|
|
473
|
+
if (!st.hasExplicitWaste) matchedAttrSteps.push(st);
|
|
383
474
|
} else if (sortedCommits.length > 0 && st.tsMs === null) {
|
|
384
475
|
unmatchedIn += st.inTok;
|
|
476
|
+
unmatchedWrite += st.cacheWriteTok;
|
|
385
477
|
unmatchedCache += st.cacheReadTok;
|
|
386
478
|
unmatchedOut += st.outTok;
|
|
479
|
+
unmatchedUsd += computeStepUsdWithModel(st, pricePerMillionUsd, hasExplicitPriceOverride);
|
|
387
480
|
unmatchedWaste += st.wasteTok;
|
|
388
481
|
if (st.isRing0) unmatchedRing0 += 1;
|
|
482
|
+
if (!st.hasExplicitWaste) matchedAttrSteps.push(st);
|
|
389
483
|
}
|
|
390
484
|
}
|
|
391
485
|
|
|
486
|
+
let inferredPreventableWaste = 0;
|
|
487
|
+
if (matchedAttrSteps.length >= 2) {
|
|
488
|
+
const attrCalls = matchedAttrSteps.map((st, idx) => ({
|
|
489
|
+
conv: st.sessionId || 'default',
|
|
490
|
+
idx: st.stepIndex ?? idx,
|
|
491
|
+
model: st.model || 'claude-sonnet-5-5',
|
|
492
|
+
freshInputTokens: st.inTok,
|
|
493
|
+
cacheCreationTokens: st.cacheWriteTok,
|
|
494
|
+
cacheCreationEphemeral5mInputTokens: st.cacheWrite5mTok,
|
|
495
|
+
cacheCreationEphemeral1hInputTokens: st.cacheWrite1hTok,
|
|
496
|
+
cacheReadTokens: st.cacheReadTok,
|
|
497
|
+
outputTokens: st.outTok,
|
|
498
|
+
createdAt: st.tsMs,
|
|
499
|
+
hadCompactionBefore: st.hadCompactionBefore,
|
|
500
|
+
isCompactSummary: st.isCompactSummary,
|
|
501
|
+
isCompactionBoundary: st.isCompactionBoundary,
|
|
502
|
+
isSidechain: st.isSidechain,
|
|
503
|
+
entrypoint: st.entrypoint,
|
|
504
|
+
shapeHash: st.shapeHash,
|
|
505
|
+
cacheTtlTier: st.cacheTtlTier
|
|
506
|
+
}));
|
|
507
|
+
const wasteAttr = attributeUncachedTokens(attrCalls);
|
|
508
|
+
inferredPreventableWaste =
|
|
509
|
+
Number(wasteAttr?.buckets?.idle_ttl_miss?.tokens || 0) +
|
|
510
|
+
Number(wasteAttr?.buckets?.model_or_effort_switch?.tokens || 0) +
|
|
511
|
+
Number(wasteAttr?.buckets?.unexplained_prefix_reset?.subBuckets?.actionable_prefix_reset?.tokens || 0) +
|
|
512
|
+
Number(wasteAttr?.buckets?.compaction_rebuild?.claude55CompactCacheMiss?.tokens || 0);
|
|
513
|
+
}
|
|
514
|
+
|
|
392
515
|
const fileAggMap = new Map();
|
|
393
516
|
let sumIn = 0;
|
|
517
|
+
let sumWrite = 0;
|
|
394
518
|
let sumCache = 0;
|
|
395
519
|
let sumOut = 0;
|
|
520
|
+
let sumCostUsd = 0;
|
|
396
521
|
let sumWaste = 0;
|
|
397
|
-
let sumRing0 = unmatchedRing0;
|
|
522
|
+
let sumRing0 = unmatchedRing0 + ledgerRing0Count;
|
|
398
523
|
|
|
399
524
|
const commitRows = sortedCommits.map((c, idx) => {
|
|
400
525
|
const bucket = commitBuckets.get(idx) || [];
|
|
401
526
|
const locShare = totalBranchLoc > 0 ? Math.max(1, c.totalLoc || 0) / totalBranchLoc : 0;
|
|
402
527
|
|
|
403
528
|
const cIn = bucket.reduce((s, st) => s + st.inTok, 0) + Math.round(unmatchedIn * locShare);
|
|
529
|
+
const cWrite = bucket.reduce((s, st) => s + st.cacheWriteTok, 0) + Math.round(unmatchedWrite * locShare);
|
|
404
530
|
const cCache = bucket.reduce((s, st) => s + st.cacheReadTok, 0) + Math.round(unmatchedCache * locShare);
|
|
405
531
|
const cOut = bucket.reduce((s, st) => s + st.outTok, 0) + Math.round(unmatchedOut * locShare);
|
|
406
532
|
const cWaste = bucket.reduce((s, st) => s + st.wasteTok, 0) + Math.round(unmatchedWaste * locShare);
|
|
407
533
|
const cRing0 = bucket.filter((st) => st.isRing0).length;
|
|
408
|
-
const cTotal = cIn + cCache + cOut;
|
|
409
|
-
const cDenom = cIn + cCache;
|
|
534
|
+
const cTotal = cIn + cWrite + cCache + cOut;
|
|
535
|
+
const cDenom = cIn + cWrite + cCache;
|
|
410
536
|
const cHitPct = cDenom > 0 ? Math.round((cCache / cDenom) * 100) : 0;
|
|
411
|
-
const
|
|
537
|
+
const rawBucketUsd =
|
|
538
|
+
bucket.reduce((s, st) => s + computeStepUsdWithModel(st, pricePerMillionUsd, hasExplicitPriceOverride), 0) +
|
|
539
|
+
unmatchedUsd * locShare;
|
|
540
|
+
const cCostUsd = Number(rawBucketUsd.toFixed(4));
|
|
412
541
|
|
|
413
542
|
sumIn += cIn;
|
|
543
|
+
sumWrite += cWrite;
|
|
414
544
|
sumCache += cCache;
|
|
415
545
|
sumOut += cOut;
|
|
546
|
+
sumCostUsd += rawBucketUsd;
|
|
416
547
|
sumWaste += cWaste;
|
|
417
548
|
sumRing0 += cRing0;
|
|
418
549
|
|
|
@@ -446,6 +577,7 @@ export function buildPrCostAttribution(options = {}) {
|
|
|
446
577
|
deletions: c.totalDeletions,
|
|
447
578
|
attributedTokens: cTotal,
|
|
448
579
|
inputTokens: cIn,
|
|
580
|
+
cacheWriteTokens: cWrite,
|
|
449
581
|
cacheReadTokens: cCache,
|
|
450
582
|
outputTokens: cOut,
|
|
451
583
|
wasteTokens: cWaste,
|
|
@@ -455,10 +587,29 @@ export function buildPrCostAttribution(options = {}) {
|
|
|
455
587
|
};
|
|
456
588
|
});
|
|
457
589
|
|
|
458
|
-
|
|
459
|
-
|
|
590
|
+
if (inferredPreventableWaste > 0 && commitRows.length > 0) {
|
|
591
|
+
const totalInputForShare = commitRows.reduce((s, r) => s + Math.max(1, r.inputTokens + r.cacheWriteTokens), 0);
|
|
592
|
+
let distributed = 0;
|
|
593
|
+
for (let i = 0; i < commitRows.length; i++) {
|
|
594
|
+
const shareTok =
|
|
595
|
+
i === commitRows.length - 1
|
|
596
|
+
? Math.max(0, inferredPreventableWaste - distributed)
|
|
597
|
+
: Math.round(
|
|
598
|
+
(inferredPreventableWaste * Math.max(1, commitRows[i].inputTokens + commitRows[i].cacheWriteTokens)) /
|
|
599
|
+
totalInputForShare
|
|
600
|
+
);
|
|
601
|
+
commitRows[i].wasteTokens += shareTok;
|
|
602
|
+
distributed += shareTok;
|
|
603
|
+
}
|
|
604
|
+
sumWaste += inferredPreventableWaste;
|
|
605
|
+
} else if (inferredPreventableWaste > 0) {
|
|
606
|
+
sumWaste += inferredPreventableWaste;
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
const totalTokens = sumIn + sumWrite + sumCache + sumOut;
|
|
610
|
+
const cacheDenom = sumIn + sumWrite + sumCache;
|
|
460
611
|
const cacheHitPct = cacheDenom > 0 ? Math.round((sumCache / cacheDenom) * 100) : 0;
|
|
461
|
-
const estimatedCostUsd = Number(
|
|
612
|
+
const estimatedCostUsd = Number(sumCostUsd.toFixed(4));
|
|
462
613
|
const wasteRatioPct = totalTokens > 0 ? Math.round((sumWaste / totalTokens) * 100) : 0;
|
|
463
614
|
const uniqueFiles = new Set(commitRows.flatMap((_, idx) => sortedCommits[idx].files.map((f) => f.filePath)));
|
|
464
615
|
const totalAdditions = sortedCommits.reduce((s, c) => s + c.totalAdditions, 0);
|
|
@@ -501,12 +652,14 @@ export function buildPrCostAttribution(options = {}) {
|
|
|
501
652
|
head,
|
|
502
653
|
fallbackUsed,
|
|
503
654
|
summary: {
|
|
655
|
+
sessionCount,
|
|
504
656
|
totalCommits: commitRows.length,
|
|
505
657
|
totalFilesChanged: uniqueFiles.size,
|
|
506
658
|
totalAdditions,
|
|
507
659
|
totalDeletions,
|
|
508
660
|
totalLoc,
|
|
509
661
|
totalInputTokens: sumIn,
|
|
662
|
+
totalCacheWriteTokens: sumWrite,
|
|
510
663
|
totalCacheReadTokens: sumCache,
|
|
511
664
|
totalOutputTokens: sumOut,
|
|
512
665
|
totalTokens,
|
package/src/ci/team-digest.mjs
CHANGED
|
@@ -112,7 +112,7 @@ export function formatTeamDigest(digest = {}) {
|
|
|
112
112
|
`2. Cache Efficiency: ${s.cacheHitPct ?? 0}% prompt cache hit rate (${((s.totalTokens || 0) / 1000).toFixed(1)}k total tokens).`,
|
|
113
113
|
`3. Top Cost Driver: ${td.label} ($${Number(td.spendUsd || 0).toFixed(2)}, ${((td.tokens || 0) / 1000).toFixed(1)}k tok).`,
|
|
114
114
|
`4. Guard Savings: $${Number(s.avoidedUsd || 0).toFixed(2)} avoided (${((s.avoidedTokens || 0) / 1000).toFixed(1)}k tok across ${s.interventions ?? 0} interventions).`,
|
|
115
|
-
`5. Policy Gate Status: ${s.ring0Violations ?? 0} Ring-0 violations | PR cap <= $${Number(s.maxPrCostUsd
|
|
115
|
+
`5. Policy Gate Status: ${s.ring0Violations ?? 0} Ring-0 violations | PR cap <= $${Number(s.maxPrCostUsd ?? 15).toFixed(2)}.`
|
|
116
116
|
];
|
|
117
117
|
return lines.join('\n') + '\n';
|
|
118
118
|
}
|
package/src/cli/audit.mjs
CHANGED
|
@@ -13,6 +13,8 @@ import {
|
|
|
13
13
|
parseTranscriptIncremental
|
|
14
14
|
} from '../storage/jsonl-parser.mjs';
|
|
15
15
|
import { getSavedQuotaReceiptSummary } from '../storage/ledger.mjs';
|
|
16
|
+
import { attributeUncachedTokens } from '../config/uncached-attribution.mjs';
|
|
17
|
+
import { valuateBatch } from '../config/pricing.mjs';
|
|
16
18
|
|
|
17
19
|
function summarizeParsedSession(meta, parsed, options = {}) {
|
|
18
20
|
const steps = Array.isArray(parsed?.steps) ? parsed.steps : [];
|
|
@@ -25,6 +27,14 @@ function summarizeParsedSession(meta, parsed, options = {}) {
|
|
|
25
27
|
let cliffTurns = 0;
|
|
26
28
|
let unknownModelTurns = 0;
|
|
27
29
|
let lastModel = 'claude-sonnet-5-5';
|
|
30
|
+
const sessionId = meta.sessionId || path.basename(meta.filePath || 'session.jsonl', '.jsonl');
|
|
31
|
+
const entrypoint =
|
|
32
|
+
parsed?.claudeDag?.sessionEntrypoint ||
|
|
33
|
+
parsed?.entrypoint ||
|
|
34
|
+
parsed?.sessionEntrypoint ||
|
|
35
|
+
options.entrypoint ||
|
|
36
|
+
null;
|
|
37
|
+
const attributionCalls = [];
|
|
28
38
|
|
|
29
39
|
for (const step of steps) {
|
|
30
40
|
const u = step?.tokenUsage || step || {};
|
|
@@ -38,9 +48,30 @@ function summarizeParsedSession(meta, parsed, options = {}) {
|
|
|
38
48
|
if (inTok + cwTok + crTok + outTok + thinkTok === 0) continue;
|
|
39
49
|
|
|
40
50
|
if (step.model) lastModel = step.model;
|
|
51
|
+
const effectiveModel = step.model || lastModel;
|
|
52
|
+
attributionCalls.push({
|
|
53
|
+
conv: sessionId,
|
|
54
|
+
idx: step.stepIndex ?? attributionCalls.length,
|
|
55
|
+
model: effectiveModel,
|
|
56
|
+
freshInputTokens: inTok,
|
|
57
|
+
cacheCreationTokens: cwTok,
|
|
58
|
+
cacheCreationEphemeral5mInputTokens: w5m,
|
|
59
|
+
cacheCreationEphemeral1hInputTokens: w1h,
|
|
60
|
+
cacheReadTokens: crTok,
|
|
61
|
+
outputTokens: outTok,
|
|
62
|
+
thinkingTokens: thinkTok,
|
|
63
|
+
createdAt: step.createdAt || null,
|
|
64
|
+
hadCompactionBefore: Boolean(step.hadCompactionBefore),
|
|
65
|
+
isCompactSummary: Boolean(step.isCompactSummary),
|
|
66
|
+
isCompactionBoundary: Boolean(step.isCompactionBoundary),
|
|
67
|
+
isSidechain: Boolean(step.isSidechain),
|
|
68
|
+
entrypoint: step.entrypoint || entrypoint || null,
|
|
69
|
+
shapeHash: step.shapeHash || null,
|
|
70
|
+
cacheTtlTier: step.cacheTtlTier || (w1h > 0 ? '1h' : '5m')
|
|
71
|
+
});
|
|
41
72
|
const costRes = calculateTurnCostUSD(
|
|
42
73
|
{
|
|
43
|
-
model:
|
|
74
|
+
model: effectiveModel,
|
|
44
75
|
inputTokens: inTok,
|
|
45
76
|
cacheWrite5mTokens: w5m,
|
|
46
77
|
cacheWrite1hTokens: w1h,
|
|
@@ -70,8 +101,12 @@ function summarizeParsedSession(meta, parsed, options = {}) {
|
|
|
70
101
|
const cacheDenom = inputTokens + cacheWriteTokens + cacheReadTokens;
|
|
71
102
|
const cacheHitPct = cacheDenom > 0 ? Math.round((cacheReadTokens / cacheDenom) * 100) : 0;
|
|
72
103
|
|
|
104
|
+
const uncachedAttribution = attributeUncachedTokens(attributionCalls, {
|
|
105
|
+
claudeCodeVersion: options.claudeCodeVersion || null
|
|
106
|
+
});
|
|
107
|
+
|
|
73
108
|
return {
|
|
74
|
-
sessionId
|
|
109
|
+
sessionId,
|
|
75
110
|
fileName: path.basename(meta.filePath || ''),
|
|
76
111
|
projectSlug: meta.projectSlug || '',
|
|
77
112
|
sessionTitle: parsed?.sessionTitle || '',
|
|
@@ -90,7 +125,10 @@ function summarizeParsedSession(meta, parsed, options = {}) {
|
|
|
90
125
|
rewindBranches: Array.isArray(parsed?.claudeDag?.rewindBranches)
|
|
91
126
|
? parsed.claudeDag.rewindBranches.length
|
|
92
127
|
: 0,
|
|
93
|
-
|
|
128
|
+
entrypoint,
|
|
129
|
+
mtimeMs: meta.mtimeMs || 0,
|
|
130
|
+
attributionCalls,
|
|
131
|
+
uncachedAttribution
|
|
94
132
|
};
|
|
95
133
|
}
|
|
96
134
|
|
|
@@ -154,16 +192,32 @@ export function auditClaudeSessions(options = {}) {
|
|
|
154
192
|
totals.cacheHitPct = denom > 0 ? Math.round((totals.cacheReadTokens / denom) * 100) : 0;
|
|
155
193
|
|
|
156
194
|
const ledger = getSavedQuotaReceiptSummary({ homeDir });
|
|
195
|
+
const allAttributionCalls = sessions.flatMap((s) => s.attributionCalls || []);
|
|
196
|
+
const valuation = valuateBatch(allAttributionCalls, {
|
|
197
|
+
nowMs: options.nowMs ?? Date.now(),
|
|
198
|
+
days: options.days ?? 7
|
|
199
|
+
});
|
|
200
|
+
const sdkCliSessions = sessions.filter((s) => s.entrypoint === 'sdk-cli').length;
|
|
201
|
+
totals.normalizedQuotaBurnUnits = valuation.totalNormalizedQuotaBurnUnits;
|
|
202
|
+
totals.effectiveQuotaMultiplier = valuation.effectiveQuotaMultiplier;
|
|
203
|
+
totals.sdkCliSessions = sdkCliSessions;
|
|
204
|
+
totals.sdkCliHeuristicApplied = Boolean(valuation.quotaBurnSummary?.sdkCliHeuristicApplied || sdkCliSessions > 0);
|
|
205
|
+
const uncachedAttribution = attributeUncachedTokens(allAttributionCalls, {
|
|
206
|
+
claudeCodeVersion: options.claudeCodeVersion || null
|
|
207
|
+
});
|
|
208
|
+
const cleanSessions = sessions.map(({ attributionCalls: _calls, ...rest }) => rest);
|
|
157
209
|
|
|
158
210
|
return {
|
|
159
211
|
ok: true,
|
|
160
212
|
totals,
|
|
213
|
+
valuation,
|
|
214
|
+
uncachedAttribution,
|
|
161
215
|
ledger: {
|
|
162
216
|
avoidedWriteUSD: ledger.burnoffAvoidedWriteUSD,
|
|
163
217
|
avoidedWriteTokens: ledger.burnoffAvoidedWriteTokens,
|
|
164
218
|
platformCacheUSD: ledger.platformCacheDiscountUSD
|
|
165
219
|
},
|
|
166
|
-
sessions
|
|
220
|
+
sessions: cleanSessions
|
|
167
221
|
};
|
|
168
222
|
}
|
|
169
223
|
|
|
@@ -172,12 +226,27 @@ export function auditClaudeSessions(options = {}) {
|
|
|
172
226
|
*/
|
|
173
227
|
export function formatAuditReport(report = {}) {
|
|
174
228
|
const t = report.totals || {};
|
|
229
|
+
const quotaTag =
|
|
230
|
+
t.normalizedQuotaBurnUnits !== undefined
|
|
231
|
+
? ` | Quota Burn: ${Number(t.normalizedQuotaBurnUnits || 0).toFixed(2)} Q-units (${Number(t.effectiveQuotaMultiplier || 1).toFixed(2)}x)`
|
|
232
|
+
: '';
|
|
175
233
|
const lines = [
|
|
176
234
|
`Burnoff Claude Code Session Audit (${t.sessions ?? 0} sessions, ${t.turns ?? 0} steps)`,
|
|
177
235
|
` Total Tokens : ${(t.totalTokens ?? 0).toLocaleString('en-US')} (cache hit ${t.cacheHitPct ?? 0}%)`,
|
|
178
|
-
` Estimated Cost : $${Number(t.estimatedCostUsd || 0).toFixed(4)} | 200k-cliff turns=${t.cliffTurns ?? 0} | rewind branches=${t.rewindBranches ?? 0}`,
|
|
236
|
+
` Estimated Cost : $${Number(t.estimatedCostUsd || 0).toFixed(4)} | 200k-cliff turns=${t.cliffTurns ?? 0} | rewind branches=${t.rewindBranches ?? 0}${quotaTag}`,
|
|
179
237
|
` Guard Savings : $${Number(report.ledger?.avoidedWriteUSD || 0).toFixed(4)} avoided (${(report.ledger?.avoidedWriteTokens || 0).toLocaleString('en-US')} tok)`
|
|
180
238
|
];
|
|
239
|
+
if (t.sdkCliSessions > 0 || t.sdkCliHeuristicApplied) {
|
|
240
|
+
lines.push(
|
|
241
|
+
` Quota Heuristic: headless sdk-cli (claude -p) observed in ${t.sdkCliSessions || 1} session(s) (~1.8x 5h quota burn heuristic per #97074; observational estimate, not a guaranteed constant).`
|
|
242
|
+
);
|
|
243
|
+
}
|
|
244
|
+
const claude55Miss = report.uncachedAttribution?.buckets?.compaction_rebuild?.claude55CompactCacheMiss;
|
|
245
|
+
if (claude55Miss && claude55Miss.calls > 0) {
|
|
246
|
+
lines.push(
|
|
247
|
+
` Provider Quirk : Claude 5.5 /compact warm-cache miss (#99624): ${claude55Miss.calls} calls, ${claude55Miss.tokens.toLocaleString('en-US')} uncached tok`
|
|
248
|
+
);
|
|
249
|
+
}
|
|
181
250
|
if (Array.isArray(report.sessions) && report.sessions.length > 0) {
|
|
182
251
|
lines.push('', ' Recent Sessions:');
|
|
183
252
|
for (const s of report.sessions.slice(0, 10)) {
|
package/src/cli/doctor.mjs
CHANGED
|
@@ -24,7 +24,7 @@ import {
|
|
|
24
24
|
pruneExpiredFts5LogsSync
|
|
25
25
|
} from '../storage/fts5-archive.mjs';
|
|
26
26
|
import { getSavedQuotaReceiptSummary, rotateMonthlyLedger } from '../storage/ledger.mjs';
|
|
27
|
-
import { openBurnoffDb } from '../storage/sqlite-client.mjs';
|
|
27
|
+
import { openBurnoffDb, resolveFallbackDbPath } from '../storage/sqlite-client.mjs';
|
|
28
28
|
import { sendDaemonRpc, resolveFastIpcPipePath } from '../ipc/fast-client.mjs';
|
|
29
29
|
|
|
30
30
|
function inspectHookWiring(cwd) {
|
|
@@ -36,15 +36,17 @@ function inspectHookWiring(cwd) {
|
|
|
36
36
|
try {
|
|
37
37
|
const parsed = JSON.parse(fs.readFileSync(settingsLocalPath, 'utf8'));
|
|
38
38
|
const hooks = parsed?.hooks || {};
|
|
39
|
-
const containsHook = (groups, targetName) =>
|
|
39
|
+
const containsHook = (groups, targetName, shimToken) =>
|
|
40
40
|
Array.isArray(groups) &&
|
|
41
|
-
groups.some((g) =>
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
41
|
+
groups.some((g) => {
|
|
42
|
+
const checkCmd = (c) => {
|
|
43
|
+
const s = String(c || '');
|
|
44
|
+
return s.includes(targetName) || (s.includes('burnoff-hook-shim.mjs') && s.includes(shimToken));
|
|
45
|
+
};
|
|
46
|
+
return Array.isArray(g?.hooks) ? g.hooks.some((h) => checkCmd(h?.command)) : checkCmd(g?.command);
|
|
47
|
+
});
|
|
48
|
+
preToolHook = containsHook(hooks.PreToolUse, 'pre-tool-use.mjs', ' pre');
|
|
49
|
+
postToolHook = containsHook(hooks.PostToolUse, 'post-tool-use.mjs', ' post');
|
|
48
50
|
} catch (err) {
|
|
49
51
|
void err; // ignore: malformed settings.local.json reported as unwired
|
|
50
52
|
}
|
|
@@ -100,7 +102,13 @@ function reapStaleCacheFiles(dirPath, cutoffMs, skipNames = new Set()) {
|
|
|
100
102
|
}
|
|
101
103
|
for (const entry of entries) {
|
|
102
104
|
if (!entry.isFile()) continue;
|
|
103
|
-
if (
|
|
105
|
+
if (
|
|
106
|
+
skipNames.has(entry.name) ||
|
|
107
|
+
entry.name.startsWith('tool_logs_fts5.db') ||
|
|
108
|
+
entry.name.startsWith('tool_logs_fallback.json')
|
|
109
|
+
) {
|
|
110
|
+
continue;
|
|
111
|
+
}
|
|
104
112
|
const full = path.join(dirPath, entry.name);
|
|
105
113
|
try {
|
|
106
114
|
const st = fs.statSync(full);
|
|
@@ -149,7 +157,7 @@ export async function runDoctor(options = {}) {
|
|
|
149
157
|
if (options.gc) {
|
|
150
158
|
const retentionDays = Number(policy?.postTool?.retentionDays ?? 30);
|
|
151
159
|
let fts5Pruned = { skipped: true, deletedRows: 0, vacuumed: false };
|
|
152
|
-
if (fs.existsSync(fts5DbPath)) {
|
|
160
|
+
if (fs.existsSync(fts5DbPath) || fs.existsSync(resolveFallbackDbPath(fts5DbPath))) {
|
|
153
161
|
let db = null;
|
|
154
162
|
try {
|
|
155
163
|
db = openBurnoffDb(fts5DbPath, { readOnly: false });
|
|
@@ -177,7 +185,9 @@ export async function runDoctor(options = {}) {
|
|
|
177
185
|
};
|
|
178
186
|
}
|
|
179
187
|
|
|
180
|
-
const status = !nodeSupported
|
|
188
|
+
const status = !nodeSupported
|
|
189
|
+
? 'ERROR'
|
|
190
|
+
: (!nativeSqlite || policy.parseError || !hooks.installed ? 'WARN' : 'OK');
|
|
181
191
|
|
|
182
192
|
return {
|
|
183
193
|
ok: nodeSupported,
|