burnoff 1.4.1 → 2.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.
Files changed (62) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/.github/workflows/burnoff-pr-gate.yml +5 -3
  3. package/.github/workflows/burnoff-startup-lint.yml +2 -2
  4. package/CHANGELOG.md +74 -0
  5. package/README.md +187 -213
  6. package/SECURITY.md +38 -0
  7. package/bin/burnoff.mjs +307 -32
  8. package/commands/burnoff.md +6 -4
  9. package/docs/CLAUDE_CODE_PLUGIN.md +29 -28
  10. package/docs/DESIGN_PARTNER_INTAKE.md +3 -3
  11. package/hooks/hook-io.mjs +216 -11
  12. package/hooks/hooks.json +44 -0
  13. package/hooks/post-tool-use.mjs +3 -1
  14. package/hooks/pre-tool-use.mjs +47 -8
  15. package/hooks/session-lifecycle.mjs +24 -3
  16. package/hooks/user-prompt-submit.mjs +98 -0
  17. package/package.json +6 -4
  18. package/scripts/bench-hooks.mjs +34 -3
  19. package/scripts/bench-savings.mjs +318 -0
  20. package/scripts/burnoff-statusline.mjs +138 -6
  21. package/src/ci/ci-gate.mjs +199 -13
  22. package/src/ci/pr-cost.mjs +417 -45
  23. package/src/ci/pr-summary.mjs +467 -0
  24. package/src/cli/audit.mjs +179 -28
  25. package/src/cli/doctor.mjs +32 -6
  26. package/src/cli/hook-health.mjs +9 -1
  27. package/src/cli/init.mjs +226 -39
  28. package/src/cli/preview.mjs +299 -0
  29. package/src/cli/startup-audit/formatter.mjs +248 -0
  30. package/src/cli/startup-audit/jsonc.mjs +601 -0
  31. package/src/cli/startup-audit/mcp-audit.mjs +735 -0
  32. package/src/cli/startup-audit/rules-hygiene.mjs +645 -0
  33. package/src/cli/startup-audit/telemetry-scan.mjs +975 -0
  34. package/src/cli/startup-audit.mjs +451 -2471
  35. package/src/clients/claude-code.mjs +41 -4
  36. package/src/config/catalog.json +295 -0
  37. package/src/config/effort.mjs +145 -0
  38. package/src/config/harness-quirks.mjs +340 -0
  39. package/src/config/loader.mjs +27 -2
  40. package/src/config/policy.mjs +81 -9
  41. package/src/config/pricing.mjs +247 -19
  42. package/src/config/semver.mjs +25 -0
  43. package/src/config/uncached-attribution.mjs +280 -41
  44. package/src/guards/compaction-baton.mjs +248 -0
  45. package/src/guards/loop-breaker.mjs +328 -47
  46. package/src/guards/model-switch-hook.mjs +126 -0
  47. package/src/guards/phase5-detectors.mjs +275 -21
  48. package/src/guards/post-tool-engine.mjs +333 -11
  49. package/src/guards/pre-tool-engine.mjs +607 -45
  50. package/src/guards/prefix-guard.mjs +609 -0
  51. package/src/guards/prompt-guard.mjs +309 -0
  52. package/src/guards/read-clamp.mjs +192 -8
  53. package/src/guards/session-hook.mjs +149 -7
  54. package/src/guards/shell-guard.mjs +56 -5
  55. package/src/guards/snooze.mjs +169 -5
  56. package/src/ipc/daemon.mjs +76 -0
  57. package/src/ipc/fast-client.mjs +165 -4
  58. package/src/ipc/protocol.mjs +16 -3
  59. package/src/storage/antigravity-parser.mjs +16 -2
  60. package/src/storage/file-lock.mjs +16 -3
  61. package/src/storage/jsonl-parser.mjs +133 -22
  62. package/src/storage/telemetry-metrics.mjs +254 -4
@@ -12,7 +12,7 @@ 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, resolveModelRateCard, valuateCall } from '../config/pricing.mjs';
15
+ import { DEFAULT_UNMAPPED_CACHED_WEIGHT, resolveModelRateCard, resolveSubscriptionQuotaWeight, valuateCall } from '../config/pricing.mjs';
16
16
  import { attributeUncachedTokens } from '../config/uncached-attribution.mjs';
17
17
  import { readLedgerEntries } from '../storage/ledger.mjs';
18
18
  import {
@@ -23,6 +23,26 @@ import {
23
23
  discoverAntigravityTranscripts,
24
24
  parseAntigravityTranscript
25
25
  } from '../storage/antigravity-parser.mjs';
26
+ import {
27
+ discoverAntigravityConversationDbs,
28
+ readAntigravityConversationDbMetrics,
29
+ mergeAntigravitySessionSources
30
+ } from '../storage/telemetry-metrics.mjs';
31
+ import {
32
+ PR_SUMMARY_FORMAT,
33
+ DEFAULT_PR_SUMMARY_REL_PATH,
34
+ buildPrSummary,
35
+ writePrSummary,
36
+ readPrSummary
37
+ } from './pr-summary.mjs';
38
+
39
+ export {
40
+ PR_SUMMARY_FORMAT,
41
+ DEFAULT_PR_SUMMARY_REL_PATH,
42
+ buildPrSummary,
43
+ writePrSummary,
44
+ readPrSummary
45
+ };
26
46
 
27
47
  export const PR_ATTRIBUTION_FORMAT = 'burnoff-pr-attribution/v1';
28
48
 
@@ -107,6 +127,38 @@ function readProviderUsageExportUsd(providerUsagePath) {
107
127
  return found ? Number(total.toFixed(4)) : null;
108
128
  }
109
129
 
130
+ function applyProviderUsageToReport(report, providerUsagePath) {
131
+ if (!providerUsagePath) return { ok: true, report };
132
+ try {
133
+ const rawProviderUsd = readProviderUsageExportUsd(providerUsagePath);
134
+ if (typeof rawProviderUsd === 'number' && Number.isFinite(rawProviderUsd)) {
135
+ const estimatedCostUsd = Number(report?.summary?.estimatedCostUsd || 0);
136
+ const reconciledCostUsd = Number(rawProviderUsd.toFixed(4));
137
+ const attributionVariancePct =
138
+ reconciledCostUsd > 0
139
+ ? Number((((estimatedCostUsd - reconciledCostUsd) / reconciledCostUsd) * 100).toFixed(2))
140
+ : 0;
141
+ return {
142
+ ok: true,
143
+ report: {
144
+ ...report,
145
+ summary: {
146
+ ...(report.summary || {}),
147
+ reconciledCostUsd,
148
+ attributionVariancePct
149
+ }
150
+ }
151
+ };
152
+ }
153
+ return { ok: true, report };
154
+ } catch (err) {
155
+ return {
156
+ ok: false,
157
+ error: err?.message || String(err)
158
+ };
159
+ }
160
+ }
161
+
110
162
  function parseGitLogNumstat(rawText = '', cwd = '') {
111
163
  const commits = [];
112
164
  let current = null;
@@ -154,9 +206,45 @@ function parseGitLogNumstat(rawText = '', cwd = '') {
154
206
  /**
155
207
  * Runs local read-only `git log <base>..<head> --numstat` cleanly without shell expansion.
156
208
  */
209
+ /**
210
+ * Parses an export `--since` value: a relative duration (`90m`, `12h`, `7d`, `2w`), an ISO date/datetime,
211
+ * or (legacy) a git revision that resolves to a commit. Anything else is `invalid`.
212
+ */
213
+ export function parseSinceOption(rawSince, nowMs = Date.now(), { cwd } = {}) {
214
+ const raw = String(rawSince ?? '').trim();
215
+ if (!raw) return { kind: 'none' };
216
+ const rel = raw.match(/^(\d+)\s*(m|h|d|w)$/i);
217
+ if (rel) {
218
+ const unitMs = { m: 60_000, h: 3_600_000, d: 86_400_000, w: 604_800_000 }[rel[2].toLowerCase()];
219
+ const sinceMs = nowMs - Number(rel[1]) * unitMs;
220
+ return { kind: 'time', sinceMs, sinceIso: new Date(sinceMs).toISOString() };
221
+ }
222
+ if (/^\d{4}-\d{2}-\d{2}(?:[T ].*)?$/.test(raw)) {
223
+ const ms = Date.parse(raw);
224
+ if (Number.isFinite(ms)) return { kind: 'time', sinceMs: ms, sinceIso: new Date(ms).toISOString() };
225
+ return { kind: 'invalid', error: `Invalid --since date "${raw}"` };
226
+ }
227
+ if (/^[\w./@^~-]+$/.test(raw) && !raw.startsWith('-')) {
228
+ try {
229
+ execFileSync('git', ['rev-parse', '--verify', '--quiet', `${raw}^{commit}`], {
230
+ cwd: path.resolve(cwd || process.cwd()),
231
+ encoding: 'utf8',
232
+ stdio: ['ignore', 'pipe', 'ignore']
233
+ });
234
+ return { kind: 'rev', rev: raw };
235
+ } catch {
236
+ // ignore: not a resolvable git revision, reported as invalid below
237
+ }
238
+ }
239
+ return {
240
+ kind: 'invalid',
241
+ error: `Invalid --since value "${raw}" (expected a duration like 7d or 12h, an ISO date like 2026-11-20, or a git revision)`
242
+ };
243
+ }
244
+
157
245
  export function collectGitBranchCommits(
158
246
  cwd,
159
- { base = 'main', head = 'HEAD', maxCommits = 100, fallbackToRecent = true } = {}
247
+ { base = 'main', head = 'HEAD', maxCommits = 100, since = null, fallbackToRecent = !since } = {}
160
248
  ) {
161
249
  const repoDir = path.resolve(cwd || process.cwd());
162
250
  const formatArg = '--format=COMMIT|%H|%aI|%an|%s';
@@ -169,11 +257,12 @@ export function collectGitBranchCommits(
169
257
  });
170
258
 
171
259
  try {
172
- const raw = runGit([`${base}..${head}`]);
260
+ const raw = since ? runGit([head, `--since=${since}`]) : runGit([`${base}..${head}`]);
173
261
  return {
174
262
  ok: true,
175
263
  base,
176
264
  head,
265
+ ...(since ? { since } : {}),
177
266
  fallbackUsed: false,
178
267
  commits: parseGitLogNumstat(raw, repoDir)
179
268
  };
@@ -303,7 +392,21 @@ function extractStepFields(step = {}, cwd = '') {
303
392
  isCompactionBoundary: Boolean(step.isCompactionBoundary),
304
393
  isSidechain: Boolean(step.isSidechain),
305
394
  entrypoint: step.entrypoint || null,
395
+ effort: step.effort || '',
396
+ thinkingEffort: step.thinkingEffort || '',
397
+ acpCustomAgent: Boolean(step.acpCustomAgent || step.acpAgent),
398
+ clientVersion: step.clientVersion || null,
306
399
  shapeHash: step.shapeHash || null,
400
+ toolsetHash: step.toolsetHash || null,
401
+ hadToolsetChange: Boolean(step.hadToolsetChange),
402
+ hadMcpReload: Boolean(step.hadMcpReload),
403
+ hadHookEdit: Boolean(step.hadHookEdit),
404
+ disableExperimentalBetas: Boolean(
405
+ step.disableExperimentalBetas ||
406
+ step.claudeCodeDisableExperimentalBetas ||
407
+ step.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS === '1' ||
408
+ step.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS === 'true'
409
+ ),
307
410
  cacheTtlTier: step.cacheTtlTier || (cacheWrite1hTok > 0 ? '1h' : '5m'),
308
411
  filesTouched: Array.from(filesTouched),
309
412
  isRing0
@@ -317,22 +420,50 @@ function computeStepCostUsd(inTok, cacheReadTok, outTok, pricePerMillionUsd = 3.
317
420
  ) * pricePerMillionUsd;
318
421
  }
319
422
 
320
- function computeStepUsdWithModel(st, pricePerMillionUsd, hasExplicitPriceOverride) {
321
- if (!hasExplicitPriceOverride && st?.model) {
322
- const val = valuateCall({
323
- model: st.model,
324
- label: st.label,
325
- timestampMs: st.tsMs,
326
- uncachedTokens: st.inTok,
327
- cachedTokens: st.cacheReadTok,
328
- cacheWrite5mTokens: st.cacheWrite5mTok,
329
- cacheWrite1hTokens: st.cacheWrite1hTok,
330
- cacheCreationTokens: st.cacheCreationTok,
331
- outputTokens: st.outTok
332
- });
333
- if (val.totalEstimatedUsd !== null) return val.totalEstimatedUsd;
423
+ function computeStepValuation(st, pricePerMillionUsd, hasExplicitPriceOverride) {
424
+ const val = valuateCall({
425
+ model: st?.model || null,
426
+ label: st?.label || null,
427
+ timestampMs: st?.tsMs ?? null,
428
+ uncachedTokens: st?.inTok || 0,
429
+ cachedTokens: st?.cacheReadTok || 0,
430
+ cacheWrite5mTokens: st?.cacheWrite5mTok || 0,
431
+ cacheWrite1hTokens: st?.cacheWrite1hTok || 0,
432
+ cacheCreationTokens: st?.cacheCreationTok || 0,
433
+ outputTokens: st?.outTok || 0,
434
+ entrypoint: st?.entrypoint || null,
435
+ effort: st?.effort || '',
436
+ thinkingEffort: st?.thinkingEffort || '',
437
+ acpCustomAgent: Boolean(st?.acpCustomAgent),
438
+ clientVersion: st?.clientVersion || null
439
+ });
440
+ if (!hasExplicitPriceOverride && st?.model && val.totalEstimatedUsd !== null) {
441
+ return {
442
+ usd: val.totalEstimatedUsd,
443
+ quotaUnits:
444
+ val.normalizedQuotaBurnUnits ??
445
+ Number((val.totalEstimatedUsd * (val.quotaWeight?.combinedQuotaMultiplier || 1)).toFixed(6)),
446
+ quotaWeight: val.quotaWeight
447
+ };
334
448
  }
335
- return computeStepCostUsd(st.inTok, st.cacheReadTok, st.outTok, pricePerMillionUsd, st.cacheWriteTok);
449
+ const usd = computeStepCostUsd(
450
+ st?.inTok || 0,
451
+ st?.cacheReadTok || 0,
452
+ st?.outTok || 0,
453
+ pricePerMillionUsd,
454
+ st?.cacheWriteTok || 0
455
+ );
456
+ const quotaWeight = resolveSubscriptionQuotaWeight({
457
+ model: st?.model || '',
458
+ label: st?.label || '',
459
+ effort: st?.effort || '',
460
+ thinkingEffort: st?.thinkingEffort || '',
461
+ entrypoint: st?.entrypoint || null,
462
+ acpCustomAgent: Boolean(st?.acpCustomAgent),
463
+ clientVersion: st?.clientVersion || null
464
+ });
465
+ const quotaUnits = Number((usd * (quotaWeight?.combinedQuotaMultiplier || 1)).toFixed(6));
466
+ return { usd, quotaUnits, quotaWeight };
336
467
  }
337
468
 
338
469
  /**
@@ -346,16 +477,44 @@ export function buildPrCostAttribution(options = {}) {
346
477
  const homeDir = explicitHomeDir || getHomeDir();
347
478
  const base = String(options.base || 'main');
348
479
  const head = String(options.head || 'HEAD');
480
+
481
+ if (typeof options.summaryPath === 'string' && options.summaryPath.trim()) {
482
+ const sumRes = readPrSummary(options.summaryPath.trim(), {
483
+ cwd,
484
+ head,
485
+ wasteRatioBasis: options.wasteRatioBasis
486
+ });
487
+ if (!sumRes.ok) {
488
+ return { ok: false, error: sumRes.error, code: sumRes.code, base, head };
489
+ }
490
+ const applied = applyProviderUsageToReport(sumRes.report, options.providerUsagePath);
491
+ if (!applied.ok) {
492
+ return { ok: false, error: applied.error, base, head };
493
+ }
494
+ return applied.report;
495
+ }
496
+
349
497
  const hasExplicitPriceOverride = options.pricePerMillionUsd !== undefined && options.pricePerMillionUsd !== null;
350
498
  const pricePerMillionUsd = Number(options.pricePerMillionUsd || 3.0);
351
499
 
500
+ const sinceInfo =
501
+ typeof options.since === 'string' && options.since.trim()
502
+ ? parseSinceOption(options.since, Date.now(), { cwd })
503
+ : { kind: 'none' };
504
+ if (sinceInfo.kind === 'invalid') {
505
+ return { ok: false, error: sinceInfo.error, base, head };
506
+ }
507
+ const sinceMs = sinceInfo.kind === 'time' ? sinceInfo.sinceMs : null;
508
+ const effectiveBase = sinceInfo.kind === 'rev' ? sinceInfo.rev : base;
509
+
352
510
  let commits = Array.isArray(options.commits) ? options.commits : null;
353
511
  let fallbackUsed = false;
354
512
  if (!commits) {
355
513
  const gitRes = collectGitBranchCommits(cwd, {
356
- base,
514
+ base: effectiveBase,
357
515
  head,
358
- fallbackToRecent: options.fallbackToRecent !== false
516
+ since: sinceInfo.kind === 'time' ? sinceInfo.sinceIso : null,
517
+ fallbackToRecent: options.fallbackToRecent !== false && sinceInfo.kind === 'none'
359
518
  });
360
519
  if (!gitRes.ok) {
361
520
  return { ok: false, error: gitRes.error, base, head };
@@ -365,6 +524,7 @@ export function buildPrCostAttribution(options = {}) {
365
524
  }
366
525
 
367
526
  const rawSteps = [];
527
+ const sessionMergeNotices = [];
368
528
  let sessionCount = 0;
369
529
  if (Array.isArray(options.steps)) {
370
530
  rawSteps.push(...options.steps);
@@ -386,6 +546,18 @@ export function buildPrCostAttribution(options = {}) {
386
546
  const agDiscovered = includeAg ? discoverAntigravityTranscripts({ homeDir, cwd }).slice(0, maxSessions) : [];
387
547
  sessionCount = claudeDiscovered.length + agDiscovered.length;
388
548
 
549
+ const agDbMap = new Map();
550
+ if (agDiscovered.length > 0) {
551
+ const dbPaths = discoverAntigravityConversationDbs({
552
+ homeDir,
553
+ conversationDirs: options.antigravityDbDir ? [options.antigravityDbDir] : null,
554
+ maxDbs: 1000
555
+ });
556
+ for (const dp of dbPaths) {
557
+ agDbMap.set(path.basename(dp, '.db'), dp);
558
+ }
559
+ }
560
+
389
561
  for (const meta of claudeDiscovered) {
390
562
  const parsed = parseTranscriptIncremental(meta.filePath, { homeDir: explicitHomeDir });
391
563
  if (Array.isArray(parsed?.steps)) {
@@ -400,9 +572,19 @@ export function buildPrCostAttribution(options = {}) {
400
572
 
401
573
  for (const meta of agDiscovered) {
402
574
  const parsed = parseAntigravityTranscript(meta.filePath, { sessionId: meta.sessionId });
403
- if (Array.isArray(parsed?.steps)) {
575
+ const dbPath = agDbMap.get(meta.sessionId) || null;
576
+ const dbResult = dbPath ? readAntigravityConversationDbMetrics(dbPath) : null;
577
+ const merged = mergeAntigravitySessionSources({
578
+ sessionId: meta.sessionId,
579
+ dbResult,
580
+ transcriptParsed: parsed
581
+ });
582
+ if (Array.isArray(merged.notices) && merged.notices.length > 0) {
583
+ sessionMergeNotices.push(...merged.notices);
584
+ }
585
+ if (Array.isArray(merged.steps)) {
404
586
  rawSteps.push(
405
- ...parsed.steps.map((st) => ({
587
+ ...merged.steps.map((st) => ({
406
588
  ...st,
407
589
  sessionId: st.sessionId || meta.sessionId || 'default'
408
590
  }))
@@ -410,7 +592,10 @@ export function buildPrCostAttribution(options = {}) {
410
592
  }
411
593
  }
412
594
  }
413
- const normalizedSteps = rawSteps.map((s) => extractStepFields(s, cwd));
595
+ // When a time window is active, drop steps known to predate it (steps without timestamps are kept).
596
+ const normalizedSteps = rawSteps
597
+ .map((s) => extractStepFields(s, cwd))
598
+ .filter((s) => sinceMs === null || !Number.isFinite(s.tsMs) || s.tsMs >= sinceMs);
414
599
 
415
600
  const rawLedger = Array.isArray(options.ledgerEntries)
416
601
  ? options.ledgerEntries
@@ -468,9 +653,26 @@ export function buildPrCostAttribution(options = {}) {
468
653
  let unmatchedCache = 0;
469
654
  let unmatchedOut = 0;
470
655
  let unmatchedUsd = 0;
656
+ let unmatchedQuotaUnits = 0;
471
657
  let unmatchedWaste = 0;
472
658
  let unmatchedRing0 = 0;
473
659
  const matchedAttrSteps = [];
660
+ const elevatedModels = new Set();
661
+ let sdkCliCalls = 0;
662
+ let acpCustomAgentCalls = 0;
663
+
664
+ const recordQuotaWeight = (qw) => {
665
+ if (!qw) return;
666
+ if ((qw.subscriptionQuotaWeightPerUsd || 1) > 1 && qw.modelId) {
667
+ elevatedModels.add(qw.modelId);
668
+ }
669
+ if (Array.isArray(qw.invocationTags) && qw.invocationTags.includes('sdk_cli_1.8x_heuristic')) {
670
+ sdkCliCalls += 1;
671
+ }
672
+ if (Array.isArray(qw.invocationTags) && qw.invocationTags.includes('acp_custom_agent_4x')) {
673
+ acpCustomAgentCalls += 1;
674
+ }
675
+ };
474
676
 
475
677
  for (const st of normalizedSteps) {
476
678
  let assignedIdx = -1;
@@ -504,23 +706,27 @@ export function buildPrCostAttribution(options = {}) {
504
706
  commitBuckets.get(assignedIdx).push(st);
505
707
  if (!st.hasExplicitWaste) matchedAttrSteps.push(st);
506
708
  } else if (sortedCommits.length > 0 && st.tsMs === null) {
709
+ const val = computeStepValuation(st, pricePerMillionUsd, hasExplicitPriceOverride);
507
710
  unmatchedIn += st.inTok;
508
711
  unmatchedWrite += st.cacheWriteTok;
509
712
  unmatchedCache += st.cacheReadTok;
510
713
  unmatchedOut += st.outTok;
511
- unmatchedUsd += computeStepUsdWithModel(st, pricePerMillionUsd, hasExplicitPriceOverride);
714
+ unmatchedUsd += val.usd;
715
+ unmatchedQuotaUnits += val.quotaUnits;
716
+ recordQuotaWeight(val.quotaWeight);
512
717
  unmatchedWaste += st.wasteTok;
513
718
  if (st.isRing0) unmatchedRing0 += 1;
514
719
  if (!st.hasExplicitWaste) matchedAttrSteps.push(st);
515
720
  }
516
721
  }
517
722
 
518
- let inferredPreventableWaste = 0;
519
- if (matchedAttrSteps.length >= 2) {
723
+ let wasteAttr = null;
724
+ if (matchedAttrSteps.length >= 1) {
520
725
  const attrCalls = matchedAttrSteps.map((st, idx) => ({
521
726
  conv: st.sessionId || 'default',
522
727
  idx: st.stepIndex ?? idx,
523
728
  model: st.model || 'claude-sonnet-5-5',
729
+ label: st.label || null,
524
730
  freshInputTokens: st.inTok,
525
731
  cacheCreationTokens: st.cacheWriteTok,
526
732
  cacheCreationEphemeral5mInputTokens: st.cacheWrite5mTok,
@@ -534,14 +740,19 @@ export function buildPrCostAttribution(options = {}) {
534
740
  isSidechain: st.isSidechain,
535
741
  entrypoint: st.entrypoint,
536
742
  shapeHash: st.shapeHash,
743
+ toolsetHash: st.toolsetHash,
744
+ hadToolsetChange: st.hadToolsetChange,
745
+ hadMcpReload: st.hadMcpReload,
746
+ hadHookEdit: st.hadHookEdit,
747
+ appendedPositionsSincePrevCall: Number(st.appendedPositionsSincePrevCall ?? 0),
748
+ disableExperimentalBetas: st.disableExperimentalBetas,
537
749
  cacheTtlTier: st.cacheTtlTier
538
750
  }));
539
- const wasteAttr = attributeUncachedTokens(attrCalls);
540
- inferredPreventableWaste =
541
- Number(wasteAttr?.buckets?.idle_ttl_miss?.tokens || 0) +
542
- Number(wasteAttr?.buckets?.model_or_effort_switch?.tokens || 0) +
543
- Number(wasteAttr?.buckets?.unexplained_prefix_reset?.subBuckets?.actionable_prefix_reset?.tokens || 0) +
544
- Number(wasteAttr?.buckets?.compaction_rebuild?.claude55CompactCacheMiss?.tokens || 0);
751
+ wasteAttr = attributeUncachedTokens(attrCalls, {
752
+ claudeCodeVersion: options.claudeCodeVersion || null,
753
+ disableExperimentalBetas: Boolean(options.disableExperimentalBetas),
754
+ env: options.env || null
755
+ });
545
756
  }
546
757
 
547
758
  const fileAggMap = new Map();
@@ -550,6 +761,7 @@ export function buildPrCostAttribution(options = {}) {
550
761
  let sumCache = 0;
551
762
  let sumOut = 0;
552
763
  let sumCostUsd = 0;
764
+ let sumQuotaUnits = 0;
553
765
  let sumWaste = 0;
554
766
  let sumRing0 = unmatchedRing0 + ledgerRing0Count;
555
767
 
@@ -566,16 +778,25 @@ export function buildPrCostAttribution(options = {}) {
566
778
  const cTotal = cIn + cWrite + cCache + cOut;
567
779
  const cDenom = cIn + cWrite + cCache;
568
780
  const cHitPct = cDenom > 0 ? Math.round((cCache / cDenom) * 100) : 0;
569
- const rawBucketUsd =
570
- bucket.reduce((s, st) => s + computeStepUsdWithModel(st, pricePerMillionUsd, hasExplicitPriceOverride), 0) +
571
- unmatchedUsd * locShare;
781
+ let bucketUsdSum = 0;
782
+ let bucketQuotaSum = 0;
783
+ for (const st of bucket) {
784
+ const val = computeStepValuation(st, pricePerMillionUsd, hasExplicitPriceOverride);
785
+ bucketUsdSum += val.usd;
786
+ bucketQuotaSum += val.quotaUnits;
787
+ recordQuotaWeight(val.quotaWeight);
788
+ }
789
+ const rawBucketUsd = bucketUsdSum + unmatchedUsd * locShare;
790
+ const rawBucketQuotaUnits = bucketQuotaSum + unmatchedQuotaUnits * locShare;
572
791
  const cCostUsd = Number(rawBucketUsd.toFixed(4));
792
+ const cQuotaUnits = Number(rawBucketQuotaUnits.toFixed(4));
573
793
 
574
794
  sumIn += cIn;
575
795
  sumWrite += cWrite;
576
796
  sumCache += cCache;
577
797
  sumOut += cOut;
578
798
  sumCostUsd += rawBucketUsd;
799
+ sumQuotaUnits += rawBucketQuotaUnits;
579
800
  sumWaste += cWaste;
580
801
  sumRing0 += cRing0;
581
802
 
@@ -615,34 +836,81 @@ export function buildPrCostAttribution(options = {}) {
615
836
  wasteTokens: cWaste,
616
837
  cacheHitPct: cHitPct,
617
838
  estimatedCostUsd: cCostUsd,
839
+ estimatedQuotaUnits: cQuotaUnits,
618
840
  ring0Violations: cRing0
619
841
  };
620
842
  });
621
843
 
622
- if (inferredPreventableWaste > 0 && commitRows.length > 0) {
844
+ const explicitWasteTokens = sumWaste;
845
+ const wasteSummary = wasteAttr?.wasteSummary || {};
846
+ const attrActionableWaste = Number(wasteSummary.actionableWasteTokens || 0);
847
+ const attrExcludedUpstream = Number(wasteSummary.excludedUpstreamTokens || 0);
848
+ const attrGrossWaste = Number(wasteSummary.grossWasteTokens || 0);
849
+ const wasteRatioBasis = String(options.wasteRatioBasis || 'actionable').trim().toLowerCase() === 'gross'
850
+ ? 'gross'
851
+ : 'actionable';
852
+ const grossWasteTokens = explicitWasteTokens + attrGrossWaste;
853
+ const excludedUpstreamTokens = attrExcludedUpstream;
854
+ const actionableWasteTokens = explicitWasteTokens + attrActionableWaste;
855
+ const selectedInferredWaste = wasteRatioBasis === 'gross' ? attrGrossWaste : attrActionableWaste;
856
+
857
+ if (selectedInferredWaste > 0 && commitRows.length > 0) {
623
858
  const totalInputForShare = commitRows.reduce((s, r) => s + Math.max(1, r.inputTokens + r.cacheWriteTokens), 0);
624
859
  let distributed = 0;
625
860
  for (let i = 0; i < commitRows.length; i++) {
626
861
  const shareTok =
627
862
  i === commitRows.length - 1
628
- ? Math.max(0, inferredPreventableWaste - distributed)
863
+ ? Math.max(0, selectedInferredWaste - distributed)
629
864
  : Math.round(
630
- (inferredPreventableWaste * Math.max(1, commitRows[i].inputTokens + commitRows[i].cacheWriteTokens)) /
865
+ (selectedInferredWaste * Math.max(1, commitRows[i].inputTokens + commitRows[i].cacheWriteTokens)) /
631
866
  totalInputForShare
632
867
  );
633
868
  commitRows[i].wasteTokens += shareTok;
634
869
  distributed += shareTok;
635
870
  }
636
- sumWaste += inferredPreventableWaste;
637
- } else if (inferredPreventableWaste > 0) {
638
- sumWaste += inferredPreventableWaste;
871
+ sumWaste = explicitWasteTokens + selectedInferredWaste;
872
+ } else if (selectedInferredWaste > 0) {
873
+ sumWaste = explicitWasteTokens + selectedInferredWaste;
639
874
  }
640
875
 
641
876
  const totalTokens = sumIn + sumWrite + sumCache + sumOut;
877
+
878
+ if (
879
+ sessionCount === 0 &&
880
+ totalTokens === 0 &&
881
+ !Array.isArray(options.steps) &&
882
+ !Array.isArray(options.sessions) &&
883
+ options.autoLoadSummary !== false
884
+ ) {
885
+ const defaultSummaryAbs = path.join(cwd, DEFAULT_PR_SUMMARY_REL_PATH);
886
+ if (fs.existsSync(defaultSummaryAbs)) {
887
+ const sumRes = readPrSummary(defaultSummaryAbs, {
888
+ cwd,
889
+ head,
890
+ wasteRatioBasis: options.wasteRatioBasis
891
+ });
892
+ if (!sumRes.ok) {
893
+ return { ok: false, error: sumRes.error, code: sumRes.code, base, head };
894
+ }
895
+ const applied = applyProviderUsageToReport(sumRes.report, options.providerUsagePath);
896
+ if (!applied.ok) {
897
+ return { ok: false, error: applied.error, base, head };
898
+ }
899
+ return applied.report;
900
+ }
901
+ }
902
+
642
903
  const cacheDenom = sumIn + sumWrite + sumCache;
643
904
  const cacheHitPct = cacheDenom > 0 ? Math.round((sumCache / cacheDenom) * 100) : 0;
644
905
  const estimatedCostUsd = Number(sumCostUsd.toFixed(4));
645
- const wasteRatioPct = totalTokens > 0 ? Math.round((sumWaste / totalTokens) * 100) : 0;
906
+ const estimatedQuotaUnits = Number(sumQuotaUnits.toFixed(4));
907
+ const quotaWeightsDisclosure =
908
+ acpCustomAgentCalls > 0
909
+ ? 'est.; weights: Carbon/Argon 3.0x, sdk-cli 1.8x heuristic, ACP --agent 4.0x, baseline 1.0x'
910
+ : 'est.; weights: Carbon/Argon 3.0x, sdk-cli 1.8x heuristic, baseline 1.0x';
911
+ const grossWasteRatioPct = totalTokens > 0 ? Math.round((grossWasteTokens / totalTokens) * 100) : 0;
912
+ const actionableWasteRatioPct = totalTokens > 0 ? Math.round((actionableWasteTokens / totalTokens) * 100) : 0;
913
+ const wasteRatioPct = wasteRatioBasis === 'gross' ? grossWasteRatioPct : actionableWasteRatioPct;
646
914
  const uniqueFiles = new Set(commitRows.flatMap((_, idx) => sortedCommits[idx].files.map((f) => f.filePath)));
647
915
  const totalAdditions = sortedCommits.reduce((s, c) => s + c.totalAdditions, 0);
648
916
  const totalDeletions = sortedCommits.reduce((s, c) => s + c.totalDeletions, 0);
@@ -676,12 +944,23 @@ export function buildPrCostAttribution(options = {}) {
676
944
  }
677
945
  }
678
946
 
947
+ const combinedNotices = [];
948
+ const seenNoticeKeys = new Set();
949
+ for (const n of [...(Array.isArray(wasteAttr?.notices) ? wasteAttr.notices : []), ...sessionMergeNotices]) {
950
+ if (!n || !n.code) continue;
951
+ const key = `${n.code}:${n.sessionId || ''}`;
952
+ if (seenNoticeKeys.has(key)) continue;
953
+ seenNoticeKeys.add(key);
954
+ combinedNotices.push(n);
955
+ }
956
+
679
957
  return {
680
958
  ok: true,
681
959
  format: PR_ATTRIBUTION_FORMAT,
682
960
  generatedAt: new Date().toISOString(),
683
- base,
961
+ base: effectiveBase,
684
962
  head,
963
+ ...(sinceInfo.kind === 'time' ? { since: sinceInfo.sinceIso } : {}),
685
964
  fallbackUsed,
686
965
  summary: {
687
966
  sessionCount,
@@ -700,27 +979,102 @@ export function buildPrCostAttribution(options = {}) {
700
979
  reconciledCostUsd,
701
980
  attributionVariancePct,
702
981
  estimatedSavedUsd: Number(ledgerSavedUsd.toFixed(4)),
982
+ estimatedQuotaUnits,
983
+ quotaUnitLabel: 'Q-units',
984
+ quotaWeightsDisclosure,
985
+ quotaBreakdown: {
986
+ unit: 'Q-units',
987
+ estimated: true,
988
+ totalQuotaUnits: estimatedQuotaUnits,
989
+ effectiveMultiplier: estimatedCostUsd > 0 ? Number((sumQuotaUnits / estimatedCostUsd).toFixed(2)) : 1,
990
+ elevatedModels: [...elevatedModels].sort(),
991
+ sdkCliCalls,
992
+ acpCustomAgentCalls
993
+ },
994
+ wasteRatioBasis,
995
+ grossWasteTokens,
996
+ grossWasteRatioPct,
997
+ excludedUpstreamTokens,
998
+ excludedUpstreamSharePct: Number(wasteSummary.excludedUpstreamSharePct || 0),
999
+ appendFloorTokens: Number(wasteSummary.appendFloorTokens || 0),
1000
+ upstreamEvictionTokens: Number(wasteSummary.upstreamEvictionTokens || 0),
1001
+ evictionByPattern: wasteSummary.evictionByPattern || {},
1002
+ actionableWasteTokens,
1003
+ actionableWasteRatioPct,
703
1004
  estimatedWasteTokens: sumWaste,
704
1005
  wasteRatioPct,
705
1006
  ring0Violations: sumRing0,
706
1007
  usdPer100Loc
707
1008
  },
1009
+ notices: combinedNotices,
1010
+ uncachedAttribution: wasteAttr,
708
1011
  commits: commitRows,
709
1012
  topCostFiles
710
1013
  };
711
1014
  }
712
1015
 
1016
+ function csvCell(value) {
1017
+ const s = value === null || value === undefined ? '' : String(value);
1018
+ return /[",\r\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
1019
+ }
1020
+
1021
+ /**
1022
+ * Flattens a PR attribution report into CSV: one `commit` row per commit plus a trailing `summary` row.
1023
+ */
1024
+ export function formatPrAttributionCsv(report = {}) {
1025
+ const isPrimitive = (v) => v === null || ['string', 'number', 'boolean'].includes(typeof v);
1026
+ const commitRows = (Array.isArray(report.commits) ? report.commits : []).map((c) => ({ row_type: 'commit', ...c }));
1027
+ const summaryRow = { row_type: 'summary', ...(report.summary || {}) };
1028
+ const rows = [...commitRows, summaryRow];
1029
+ const columns = ['row_type'];
1030
+ for (const row of rows) {
1031
+ for (const [key, value] of Object.entries(row)) {
1032
+ if (isPrimitive(value) && !columns.includes(key)) columns.push(key);
1033
+ }
1034
+ }
1035
+ const lines = [columns.map(csvCell).join(',')];
1036
+ for (const row of rows) {
1037
+ lines.push(columns.map((col) => csvCell(isPrimitive(row[col]) ? row[col] : '')).join(','));
1038
+ }
1039
+ return lines.join('\n') + '\n';
1040
+ }
1041
+
1042
+ function formatUpstreamBreakdownTag(s = {}) {
1043
+ const parts = [];
1044
+ if (Number(s.appendFloorTokens || 0) > 0) {
1045
+ parts.push(`append_floor: ${(s.appendFloorTokens / 1000).toFixed(1)}k`);
1046
+ }
1047
+ const patterns = s.evictionByPattern && typeof s.evictionByPattern === 'object' ? Object.entries(s.evictionByPattern) : [];
1048
+ if (patterns.length > 0) {
1049
+ parts.push(patterns.map(([k, v]) => `${k}: ${v}`).join(', '));
1050
+ }
1051
+ return parts.length > 0 ? ` [${parts.join('; ')}]` : '';
1052
+ }
1053
+
713
1054
  /**
714
1055
  * Formats PR cost attribution as clean PR comment Markdown with zero local paths.
715
1056
  */
716
1057
  export function formatPrAttributionMarkdown(report = {}) {
717
1058
  const s = report.summary || {};
1059
+ const basis = s.wasteRatioBasis || 'actionable';
1060
+ const hasWasteBreakdown =
1061
+ typeof s.grossWasteTokens === 'number' || typeof s.actionableWasteTokens === 'number';
1062
+ const grossTok = s.grossWasteTokens ?? s.estimatedWasteTokens ?? 0;
1063
+ const grossPct = s.grossWasteRatioPct ?? s.wasteRatioPct ?? 0;
1064
+ const exclTok = s.excludedUpstreamTokens ?? 0;
1065
+ const actTok = s.actionableWasteTokens ?? s.estimatedWasteTokens ?? 0;
1066
+ const actPct = s.actionableWasteRatioPct ?? s.wasteRatioPct ?? 0;
718
1067
  const lines = [
719
1068
  `### Burnoff PR Token & Cost Attribution (\`${report.base || 'main'}..${report.head || 'HEAD'}\`)`,
720
1069
  '',
721
1070
  '| Metric | Value |',
722
1071
  '| :--- | :--- |',
723
1072
  `| **Commits / Files Changed** | \`${s.totalCommits ?? 0}\` commits · \`${s.totalFilesChanged ?? 0}\` files (\`+${s.totalAdditions ?? 0} / -${s.totalDeletions ?? 0}\`) |`,
1073
+ ...(report.source === 'pr-summary'
1074
+ ? [
1075
+ `| **Attribution Source** | \`pr-summary\` (\`${report.summarySourcePath || DEFAULT_PR_SUMMARY_REL_PATH}\`, \`sha256:${String(report.summaryDigest || '').slice(0, 12)}\`) |`
1076
+ ]
1077
+ : []),
724
1078
  `| **Total Attributed Tokens** | \`${((s.totalTokens || 0) / 1000).toFixed(1)}k\` |`,
725
1079
  `| **Cache Hit Rate** | \`${s.cacheHitPct ?? 0}%\` |`,
726
1080
  `| **Estimated PR AI Cost** | \`$${Number(s.estimatedCostUsd || 0).toFixed(4)}\` (\`$${Number(s.usdPer100Loc || 0).toFixed(4)} / 100 LOC\`) |`,
@@ -729,11 +1083,24 @@ export function formatPrAttributionMarkdown(report = {}) {
729
1083
  `| **Provider Reconciled Cost** | \`$${s.reconciledCostUsd.toFixed(4)}\` (\`${(s.attributionVariancePct || 0) >= 0 ? '+' : ''}${s.attributionVariancePct ?? 0}%\` variance) |`
730
1084
  ]
731
1085
  : []),
732
- `| **Preventable Waste Ratio** | \`${s.wasteRatioPct ?? 0}%\` (\`${((s.estimatedWasteTokens || 0) / 1000).toFixed(1)}k\` tok) |`,
1086
+ `| **Estimated Quota Burn** | \`${Number(s.estimatedQuotaUnits || 0).toFixed(2)} Q-units\` (${s.quotaWeightsDisclosure || 'est.; weights: Carbon/Argon 3.0x, sdk-cli 1.8x heuristic, baseline 1.0x'}) |`,
1087
+ `| **Preventable Waste Ratio** | \`${s.wasteRatioPct ?? 0}%\` (\`${((s.estimatedWasteTokens || 0) / 1000).toFixed(1)}k\` tok, basis: \`${basis}\`) |`,
1088
+ ...(hasWasteBreakdown
1089
+ ? [
1090
+ `| **Waste Breakdown (Gross / Upstream / Actionable)** | Gross \`${grossPct}%\` (\`${(grossTok / 1000).toFixed(1)}k\`) · Attributed to Upstream \`${(exclTok / 1000).toFixed(1)}k\`${formatUpstreamBreakdownTag(s)} · Actionable \`${actPct}%\` (\`${(actTok / 1000).toFixed(1)}k\`) |`
1091
+ ]
1092
+ : []),
733
1093
  `| **Estimated Saved USD** | \`$${Number(s.estimatedSavedUsd || 0).toFixed(4)}\` |`,
734
1094
  `| **Ring-0 Violations** | \`${s.ring0Violations ?? 0}\` |`
735
1095
  ];
736
1096
 
1097
+ if (Array.isArray(report.notices) && report.notices.length > 0) {
1098
+ lines.push('', '#### Notices', '');
1099
+ for (const n of report.notices) {
1100
+ lines.push(`- **${n.code}**: ${n.message}`);
1101
+ }
1102
+ }
1103
+
737
1104
  const cleanFiles = (Array.isArray(report.topCostFiles) ? report.topCostFiles : [])
738
1105
  .map((f) => ({ ...f, filePath: sanitizeRelativeRepoPath(f.filePath) }))
739
1106
  .filter((f) => f.filePath && !isExcludedLocalToolPath(f.filePath));
@@ -760,8 +1127,13 @@ export function formatPrAttributionMarkdown(report = {}) {
760
1127
 
761
1128
  export default {
762
1129
  PR_ATTRIBUTION_FORMAT,
1130
+ PR_SUMMARY_FORMAT,
1131
+ DEFAULT_PR_SUMMARY_REL_PATH,
763
1132
  sanitizeRelativeRepoPath,
764
1133
  collectGitBranchCommits,
765
1134
  buildPrCostAttribution,
766
- formatPrAttributionMarkdown
1135
+ formatPrAttributionMarkdown,
1136
+ buildPrSummary,
1137
+ writePrSummary,
1138
+ readPrSummary
767
1139
  };