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
package/src/cli/audit.mjs CHANGED
@@ -19,10 +19,12 @@ import {
19
19
  } from '../storage/antigravity-parser.mjs';
20
20
  import { getSavedQuotaReceiptSummary } from '../storage/ledger.mjs';
21
21
  import { attributeUncachedTokens } from '../config/uncached-attribution.mjs';
22
+ import { detectHarnessQuirks } from '../config/harness-quirks.mjs';
22
23
  import { valuateBatch } from '../config/pricing.mjs';
23
24
  import {
24
25
  discoverAntigravityConversationDbs,
25
26
  readAntigravityConversationDbMetrics,
27
+ mergeAntigravitySessionSources,
26
28
  discoverLocalOtelFiles,
27
29
  parseOtelGenAiSpans,
28
30
  extractStepTimingMetrics,
@@ -36,8 +38,10 @@ function summarizeParsedSession(meta, parsed, options = {}) {
36
38
  let cacheReadTokens = 0;
37
39
  let outputTokens = 0;
38
40
  let thinkingTokens = 0;
41
+ let thinkingTokensEstimated = false;
39
42
  let billedOutputTokens = 0;
40
43
  let estimatedCostUsd = 0;
44
+ let thinkingCostUsd = 0;
41
45
  let cliffTurns = 0;
42
46
  let unknownModelTurns = 0;
43
47
  let lastModel = 'claude-sonnet-5-5';
@@ -81,6 +85,15 @@ function summarizeParsedSession(meta, parsed, options = {}) {
81
85
  isSidechain: Boolean(step.isSidechain),
82
86
  entrypoint: step.entrypoint || entrypoint || null,
83
87
  shapeHash: step.shapeHash || null,
88
+ toolCallsInTurn: Number(
89
+ step.toolCallsInTurn ??
90
+ step.toolUseCount ??
91
+ (Array.isArray(step.toolCalls) ? step.toolCalls.length : 0)
92
+ ),
93
+ contentBlocksSinceBreakpoint: Number(
94
+ step.contentBlocksSinceBreakpoint ?? step.contentBlockCount ?? 0
95
+ ),
96
+ appendedPositionsSincePrevCall: Number(step.appendedPositionsSincePrevCall ?? 0),
84
97
  cacheTtlTier: step.cacheTtlTier || (w1h > 0 ? '1h' : '5m')
85
98
  });
86
99
  const costRes = calculateTurnCostUSD(
@@ -94,7 +107,10 @@ function summarizeParsedSession(meta, parsed, options = {}) {
94
107
  outputTokens: outTok,
95
108
  thinkingTokens: thinkTok
96
109
  },
97
- options
110
+ {
111
+ ...options,
112
+ eventTimestampUtc: step.createdAt ?? options.eventTimestampUtc ?? null
113
+ }
98
114
  );
99
115
 
100
116
  inputTokens += inTok;
@@ -102,12 +118,16 @@ function summarizeParsedSession(meta, parsed, options = {}) {
102
118
  cacheReadTokens += crTok;
103
119
  outputTokens += outTok;
104
120
  thinkingTokens += thinkTok;
121
+ if (step.thinkingTokensEstimated) thinkingTokensEstimated = true;
105
122
  billedOutputTokens += Number(costRes?.tokens?.totalOutput ?? outTok);
106
123
 
107
124
  if (costRes.unknownModel) {
108
125
  unknownModelTurns += 1;
109
126
  } else {
110
127
  estimatedCostUsd += Number(costRes.costsUSD.totalActualSpendUSD || 0);
128
+ if (thinkTok > 0 && Number.isFinite(costRes.rates?.outputPer1M)) {
129
+ thinkingCostUsd += (thinkTok / 1_000_000) * costRes.rates.outputPer1M;
130
+ }
111
131
  if (costRes.cliffTriggered) cliffTurns += 1;
112
132
  }
113
133
  }
@@ -124,6 +144,10 @@ function summarizeParsedSession(meta, parsed, options = {}) {
124
144
 
125
145
  return {
126
146
  sessionId,
147
+ client: meta.client || parsed?.client || 'claude-code',
148
+ counterSource: parsed?.counterSource || 'transcript_jsonl',
149
+ trajectoryType: parsed?.trajectoryType ?? null,
150
+ notices: Array.isArray(parsed?.mergeNotices) ? parsed.mergeNotices : [],
127
151
  fileName: path.basename(meta.filePath || ''),
128
152
  projectSlug: meta.projectSlug || '',
129
153
  sessionTitle: parsed?.sessionTitle || '',
@@ -134,9 +158,11 @@ function summarizeParsedSession(meta, parsed, options = {}) {
134
158
  cacheReadTokens,
135
159
  outputTokens,
136
160
  thinkingTokens,
161
+ thinkingTokensEstimated,
137
162
  totalTokens,
138
163
  cacheHitPct,
139
164
  estimatedCostUsd: Number(estimatedCostUsd.toFixed(4)),
165
+ thinkingCostUsd: Number(thinkingCostUsd.toFixed(4)),
140
166
  cliffTurns,
141
167
  unknownModelTurns,
142
168
  rewindBranches: Array.isArray(parsed?.claudeDag?.rewindBranches)
@@ -150,6 +176,7 @@ function summarizeParsedSession(meta, parsed, options = {}) {
150
176
  medianTtftMs: sessionTelemetry.medianTtftMs,
151
177
  medianTokensPerSec: sessionTelemetry.medianTokensPerSec
152
178
  },
179
+ _steps: steps,
153
180
  _stepTimings: stepTimings,
154
181
  attributionCalls,
155
182
  uncachedAttribution
@@ -190,16 +217,68 @@ export function auditClaudeSessions(options = {}) {
190
217
  .slice(0, limit);
191
218
  }
192
219
 
220
+ let dbPaths = [];
221
+ if (Array.isArray(options.antigravityDbPath)) {
222
+ dbPaths = options.antigravityDbPath.filter(Boolean);
223
+ } else if (typeof options.antigravityDbPath === 'string' && options.antigravityDbPath.trim()) {
224
+ dbPaths = [options.antigravityDbPath.trim()];
225
+ } else if (options.antigravityDbDir || includeAg) {
226
+ dbPaths = discoverAntigravityConversationDbs({
227
+ homeDir,
228
+ conversationDirs: options.antigravityDbDir ? [options.antigravityDbDir] : null,
229
+ maxDbs: options.sessionPath ? 1000 : Math.max(limit, 50)
230
+ });
231
+ }
232
+ const agDbBySessionId = new Map();
233
+ for (const dp of dbPaths) {
234
+ agDbBySessionId.set(path.basename(dp, '.db'), path.resolve(dp));
235
+ }
236
+
193
237
  const sessions = [];
238
+ const mergedDbPaths = new Set();
239
+ const counterSources = { sqlite_db: 0, transcript_jsonl: 0, transcript_fallback: 0 };
240
+ const allNotices = [];
241
+ let antigravityDbsScanned = 0;
242
+
194
243
  for (const meta of candidates) {
195
244
  const useAg = meta.client === 'antigravity' || isAntigravityTranscriptFile(meta.filePath);
196
- const parsed = useAg
245
+ let parsed = useAg
197
246
  ? parseAntigravityTranscript(meta.filePath, { sessionId: meta.sessionId })
198
247
  : parseTranscriptIncremental(meta.filePath, {
199
248
  homeDir: explicitHomeDir,
200
- tailBytes: options.tailBytes
249
+ tailBytes: options.tailBytes,
250
+ readOnly: Boolean(options.readOnly)
201
251
  });
202
- sessions.push(summarizeParsedSession(meta, parsed, options));
252
+ if (useAg) {
253
+ const resolvedSid = parsed?.sessionId || meta.sessionId;
254
+ const matchedDbPath = agDbBySessionId.get(resolvedSid) || agDbBySessionId.get(meta.sessionId) || null;
255
+ let dbResult = null;
256
+ if (matchedDbPath) {
257
+ mergedDbPaths.add(path.resolve(matchedDbPath));
258
+ dbResult = readAntigravityConversationDbMetrics(matchedDbPath);
259
+ if (dbResult.ok) antigravityDbsScanned += 1;
260
+ }
261
+ const merged = mergeAntigravitySessionSources({
262
+ sessionId: resolvedSid,
263
+ dbResult,
264
+ transcriptParsed: parsed
265
+ });
266
+ parsed = {
267
+ ...parsed,
268
+ steps: merged.steps,
269
+ counterSource: merged.counterSource,
270
+ trajectoryType: merged.trajectoryType,
271
+ mergeNotices: merged.notices
272
+ };
273
+ if (Array.isArray(merged.notices) && merged.notices.length > 0) {
274
+ allNotices.push(...merged.notices);
275
+ }
276
+ }
277
+ const summarized = summarizeParsedSession(meta, parsed, options);
278
+ if (summarized.counterSource in counterSources) {
279
+ counterSources[summarized.counterSource] += 1;
280
+ }
281
+ sessions.push(summarized);
203
282
  }
204
283
 
205
284
  const totals = sessions.reduce(
@@ -211,8 +290,10 @@ export function auditClaudeSessions(options = {}) {
211
290
  acc.cacheReadTokens += s.cacheReadTokens;
212
291
  acc.outputTokens += s.outputTokens;
213
292
  acc.thinkingTokens += s.thinkingTokens;
293
+ acc.thinkingTokensEstimated = Boolean(acc.thinkingTokensEstimated || s.thinkingTokensEstimated);
214
294
  acc.totalTokens += s.totalTokens;
215
295
  acc.estimatedCostUsd = Number((acc.estimatedCostUsd + s.estimatedCostUsd).toFixed(4));
296
+ acc.thinkingCostUsd = Number((acc.thinkingCostUsd + (s.thinkingCostUsd || 0)).toFixed(4));
216
297
  acc.cliffTurns += s.cliffTurns;
217
298
  acc.rewindBranches += s.rewindBranches;
218
299
  return acc;
@@ -225,13 +306,20 @@ export function auditClaudeSessions(options = {}) {
225
306
  cacheReadTokens: 0,
226
307
  outputTokens: 0,
227
308
  thinkingTokens: 0,
309
+ thinkingTokensEstimated: false,
228
310
  totalTokens: 0,
229
311
  cacheHitPct: 0,
230
312
  estimatedCostUsd: 0,
313
+ thinkingCostUsd: 0,
314
+ thinkingCostSharePct: 0,
231
315
  cliffTurns: 0,
232
316
  rewindBranches: 0
233
317
  }
234
318
  );
319
+ totals.thinkingCostSharePct =
320
+ totals.estimatedCostUsd > 0
321
+ ? Number(((totals.thinkingCostUsd / totals.estimatedCostUsd) * 100).toFixed(1))
322
+ : 0;
235
323
  const denom = totals.inputTokens + totals.cacheWriteTokens + totals.cacheReadTokens;
236
324
  totals.cacheHitPct = denom > 0 ? Math.round((totals.cacheReadTokens / denom) * 100) : 0;
237
325
 
@@ -247,7 +335,21 @@ export function auditClaudeSessions(options = {}) {
247
335
  totals.sdkCliSessions = sdkCliSessions;
248
336
  totals.sdkCliHeuristicApplied = Boolean(valuation.quotaBurnSummary?.sdkCliHeuristicApplied || sdkCliSessions > 0);
249
337
  const uncachedAttribution = attributeUncachedTokens(allAttributionCalls, {
250
- claudeCodeVersion: options.claudeCodeVersion || null
338
+ claudeCodeVersion: options.claudeCodeVersion || null,
339
+ disableExperimentalBetas: Boolean(options.disableExperimentalBetas),
340
+ env: options.env || null
341
+ });
342
+ if (Array.isArray(uncachedAttribution.notices) && uncachedAttribution.notices.length > 0) {
343
+ allNotices.push(...uncachedAttribution.notices);
344
+ }
345
+ const harnessQuirks = detectHarnessQuirks({
346
+ sessions: sessions.map((s) => ({ ...s, steps: s._steps || [] })),
347
+ uncachedAttribution,
348
+ antigravityVersion: options.antigravityVersion || null,
349
+ env: options.env || null,
350
+ hookPayloads: options.hookPayloads || null,
351
+ geminiMdBytes: options.geminiMdBytes ?? null,
352
+ geminiMdTokens: options.geminiMdTokens ?? null
251
353
  });
252
354
 
253
355
  const otelFiles =
@@ -259,22 +361,16 @@ export function auditClaudeSessions(options = {}) {
259
361
  otelSpans.push(...parseOtelGenAiSpans(otelFile).spans);
260
362
  }
261
363
 
262
- let dbPaths = [];
263
- if (Array.isArray(options.antigravityDbPath)) {
264
- dbPaths = options.antigravityDbPath.filter(Boolean);
265
- } else if (typeof options.antigravityDbPath === 'string' && options.antigravityDbPath.trim()) {
266
- dbPaths = [options.antigravityDbPath.trim()];
267
- } else if (options.antigravityDbDir || (includeAg && !options.sessionPath)) {
268
- dbPaths = discoverAntigravityConversationDbs({
269
- homeDir,
270
- conversationDirs: options.antigravityDbDir ? [options.antigravityDbDir] : null,
271
- maxDbs: Math.min(limit, 50)
272
- });
273
- }
274
364
  const antigravityDbSteps = [];
275
- let antigravityDbsScanned = 0;
365
+ const unmergedLimit = Math.min(limit, 50);
366
+ let unmergedScanned = 0;
276
367
  for (const dbPath of dbPaths) {
277
- const dbRes = readAntigravityConversationDbMetrics(dbPath);
368
+ const resolvedDb = path.resolve(dbPath);
369
+ if (mergedDbPaths.has(resolvedDb)) continue;
370
+ if (options.sessionPath && !options.antigravityDbPath && !options.antigravityDbDir) continue;
371
+ if (unmergedScanned >= unmergedLimit) break;
372
+ unmergedScanned += 1;
373
+ const dbRes = readAntigravityConversationDbMetrics(resolvedDb);
278
374
  if (dbRes.ok) {
279
375
  antigravityDbsScanned += 1;
280
376
  antigravityDbSteps.push(...dbRes.steps);
@@ -290,11 +386,14 @@ export function auditClaudeSessions(options = {}) {
290
386
  antigravityDbsScanned
291
387
  });
292
388
 
293
- const cleanSessions = sessions.map(({ attributionCalls: _calls, _stepTimings: _timings, ...rest }) => rest);
389
+ const cleanSessions = sessions.map(({ attributionCalls: _calls, _stepTimings: _timings, _steps: _rawSteps, ...rest }) => rest);
294
390
 
295
391
  return {
296
392
  ok: true,
297
393
  totals,
394
+ counterSources,
395
+ notices: allNotices,
396
+ harnessQuirks,
298
397
  telemetry,
299
398
  valuation,
300
399
  uncachedAttribution,
@@ -317,11 +416,24 @@ export function formatAuditReport(report = {}) {
317
416
  ? ` | Quota Burn: ${Number(t.normalizedQuotaBurnUnits || 0).toFixed(2)} Q-units (${Number(t.effectiveQuotaMultiplier || 1).toFixed(2)}x)`
318
417
  : '';
319
418
  const lines = [
320
- `Burnoff Claude Code Session Audit (${t.sessions ?? 0} sessions, ${t.turns ?? 0} steps)`,
419
+ `Burnoff Session Audit (${t.sessions ?? 0} sessions, ${t.turns ?? 0} steps)`,
321
420
  ` Total Tokens : ${(t.totalTokens ?? 0).toLocaleString('en-US')} (cache hit ${t.cacheHitPct ?? 0}%)`,
322
421
  ` Estimated Cost : $${Number(t.estimatedCostUsd || 0).toFixed(4)} | 200k-cliff turns=${t.cliffTurns ?? 0} | rewind branches=${t.rewindBranches ?? 0}${quotaTag}`,
323
422
  ` Guard Savings : $${Number(report.ledger?.avoidedWriteUSD || 0).toFixed(4)} avoided (${(report.ledger?.avoidedWriteTokens || 0).toLocaleString('en-US')} tok)`
324
423
  ];
424
+ if (Number(t.thinkingTokens || 0) > 0) {
425
+ const estSuffix = t.thinkingTokensEstimated ? 'est. upper bound; ' : '';
426
+ const prefixTilde = t.thinkingTokensEstimated ? '~' : '';
427
+ lines.push(
428
+ ` Thinking Spend : ${prefixTilde}${Number(t.thinkingTokens || 0).toLocaleString('en-US')} tok (${estSuffix}~$${Number(t.thinkingCostUsd || 0).toFixed(4)}, ${Number(t.thinkingCostSharePct || 0)}% of est. cost at output rate)`
429
+ );
430
+ }
431
+ const cs = report.counterSources;
432
+ if (cs && (cs.sqlite_db > 0 || cs.transcript_fallback > 0)) {
433
+ lines.push(
434
+ ` Data Sources : sqlite_db=${cs.sqlite_db || 0}, transcript_jsonl=${cs.transcript_jsonl || 0}, transcript_fallback=${cs.transcript_fallback || 0}`
435
+ );
436
+ }
325
437
  const perf = report.telemetry;
326
438
  if (perf) {
327
439
  const perfParts = [];
@@ -356,15 +468,20 @@ export function formatAuditReport(report = {}) {
356
468
  const thrash = buckets.model_or_effort_switch?.orchestratorThrash;
357
469
  if (thrash && thrash.calls > 0) {
358
470
  lines.push(
359
- ` Provider Quirk : Orchestrator/model ping-pong thrash (${thrash.issueRef || '#1638'}): ${thrash.calls} calls, ${thrash.tokens.toLocaleString('en-US')} uncached tok — ${thrash.guidance}`
471
+ ` Provider Quirk : Orchestrator/model ping-pong thrash (${thrash.issueRef || '#1638'}): ${thrash.calls} calls, ${thrash.tokens.toLocaleString('en-US')} uncached tok -- ${thrash.guidance}`
360
472
  );
361
473
  }
474
+ if (Array.isArray(report.harnessQuirks?.findings) && report.harnessQuirks.findings.length > 0) {
475
+ for (const f of report.harnessQuirks.findings) {
476
+ lines.push(` Harness Quirk : [${f.ruleId}] ${f.message}`);
477
+ }
478
+ }
362
479
  if (Number(report.uncachedAttribution?.totalUncachedTokens || 0) > 0) {
363
480
  const driverLines = [];
364
481
  const idleMiss = buckets.idle_ttl_miss;
365
482
  if (idleMiss && idleMiss.tokens > 0) {
366
483
  driverLines.push(
367
- ` - idle_ttl_miss: ${idleMiss.calls} calls, ${idleMiss.tokens.toLocaleString('en-US')} tok (${idleMiss.sharePct}%, ~$${Number(idleMiss.estimatedUsd || 0).toFixed(2)}) — consider 1h cache TTL for >5m review pauses`
484
+ ` - idle_ttl_miss: ${idleMiss.calls} calls, ${idleMiss.tokens.toLocaleString('en-US')} tok (${idleMiss.sharePct}%, ~$${Number(idleMiss.estimatedUsd || 0).toFixed(2)}) -- consider 1h cache TTL for >5m review pauses`
368
485
  );
369
486
  }
370
487
  const modelSwitch = buckets.model_or_effort_switch;
@@ -372,26 +489,54 @@ export function formatAuditReport(report = {}) {
372
489
  driverLines.push(
373
490
  ` - model_or_effort_switch: ${modelSwitch.calls} calls, ${modelSwitch.tokens.toLocaleString('en-US')} tok (${modelSwitch.sharePct}%, ~$${Number(modelSwitch.estimatedUsd || 0).toFixed(2)})`
374
491
  );
492
+ if (modelSwitch.routerPingPong?.events > 0) {
493
+ driverLines.push(
494
+ ` * router_ping_pong: ${modelSwitch.routerPingPong.events} detour(s), ${modelSwitch.routerPingPong.tokens.toLocaleString('en-US')} tok -- ${modelSwitch.routerPingPong.guidance}`
495
+ );
496
+ }
497
+ }
498
+ const appendFloor = buckets.incremental_tail?.subBuckets?.provider_append_floor;
499
+ if (appendFloor && appendFloor.tokens > 0) {
500
+ driverLines.push(
501
+ ` - provider_append_floor (attributed to upstream): ${appendFloor.calls} calls, ${appendFloor.tokens.toLocaleString('en-US')} tok (~$${Number(appendFloor.estimatedUsd || 0).toFixed(2)})`
502
+ );
375
503
  }
376
504
  const unexplained = buckets.unexplained_prefix_reset;
377
505
  if (unexplained && unexplained.tokens > 0) {
378
506
  const act = unexplained.subBuckets?.actionable_prefix_reset;
507
+ const lookbackMiss = unexplained.subBuckets?.likely_lookback_miss;
379
508
  const up = unexplained.subBuckets?.upstream_provider_eviction;
380
509
  let emittedSub = false;
381
510
  if (act && act.tokens > 0) {
382
- const likelyHint = Array.isArray(unexplained.likelyCauses) && unexplained.likelyCauses.length > 0
383
- ? ` (e.g., ${unexplained.likelyCauses[0]})`
384
- : '';
511
+ const diagHint = unexplained.examples?.[0]?.diagnosis;
512
+ const likelyHint = diagHint
513
+ ? ` (${diagHint})`
514
+ : Array.isArray(unexplained.likelyCauses) && unexplained.likelyCauses.length > 0
515
+ ? ` (e.g., ${unexplained.likelyCauses[0]})`
516
+ : '';
385
517
  driverLines.push(
386
518
  ` - unexplained_prefix_reset (actionable): ${act.calls} calls, ${act.tokens.toLocaleString('en-US')} tok (${act.shareOfBucketPct ?? unexplained.sharePct}%, ~$${Number(act.estimatedUsd || 0).toFixed(2)})${likelyHint}`
387
519
  );
388
520
  emittedSub = true;
389
521
  }
522
+ if (lookbackMiss && lookbackMiss.tokens > 0) {
523
+ const adviceHint = lookbackMiss.advice ? ` -- ${lookbackMiss.advice}` : '';
524
+ driverLines.push(
525
+ ` - unexplained_prefix_reset (likely_lookback_miss, heuristic): ${lookbackMiss.calls} calls, ${lookbackMiss.tokens.toLocaleString('en-US')} tok (${lookbackMiss.shareOfBucketPct ?? unexplained.sharePct}%, ~$${Number(lookbackMiss.estimatedUsd || 0).toFixed(2)})${adviceHint}`
526
+ );
527
+ emittedSub = true;
528
+ }
390
529
  if (up && up.tokens > 0) {
391
- const adviceHint = up.advice ? ` — ${up.advice}` : '';
530
+ const adviceHint = up.advice ? ` -- ${up.advice}` : '';
392
531
  driverLines.push(
393
- ` - unexplained_prefix_reset (upstream eviction): ${up.calls} calls, ${up.tokens.toLocaleString('en-US')} tok (${up.shareOfBucketPct ?? unexplained.sharePct}%, ~$${Number(up.estimatedUsd || 0).toFixed(2)})${adviceHint}`
532
+ ` - unexplained_prefix_reset (upstream eviction): ${up.calls} calls, ${up.tokens.toLocaleString('en-US')} tok (${up.shareOfBucketPct ?? unexplained.sharePct}%, ~$${Number(up.estimatedUsd || 0).toFixed(2)}; attributed to upstream)${adviceHint}`
394
533
  );
534
+ const lookback = unexplained.truncationSummary?.anthropic_20_block_lookback;
535
+ if (lookback && lookback.calls > 0) {
536
+ driverLines.push(
537
+ ` * anthropic_20_block_lookback: ${lookback.calls} cold rebuild(s), ${lookback.tokens.toLocaleString('en-US')} tok (>20 blocks/tool uses between cache breakpoints)`
538
+ );
539
+ }
395
540
  emittedSub = true;
396
541
  }
397
542
  if (!emittedSub) {
@@ -406,6 +551,12 @@ export function formatAuditReport(report = {}) {
406
551
  ` - compaction_rebuild: ${compaction.calls} calls, ${compaction.tokens.toLocaleString('en-US')} tok (${compaction.sharePct}%, ~$${Number(compaction.estimatedUsd || 0).toFixed(2)})`
407
552
  );
408
553
  }
554
+ const subThresh = report.uncachedAttribution?.subThresholdSummary;
555
+ if (subThresh && subThresh.calls > 0) {
556
+ driverLines.push(
557
+ ` - sub_threshold_prefix: ${subThresh.calls} turns across ${subThresh.sessions} session(s) stayed below model minCacheableTokens -- ${subThresh.guidance}`
558
+ );
559
+ }
409
560
  if (driverLines.length > 0) {
410
561
  lines.push('', ' Uncached Drivers:', ...driverLines);
411
562
  }
@@ -237,7 +237,8 @@ function inspectAntigravityHookWiring(cwd, homeDir = getHomeDir(), options = {})
237
237
  };
238
238
  if (installed && !options.skipAntigravityProbe) {
239
239
  const active = project.installed ? project : global;
240
- const probeCwd = path.dirname(active.path);
240
+ // Antigravity spawns hook commands from the workspace root, so probe from there (not from .agents/).
241
+ const probeCwd = cwd;
241
242
  const probes = [
242
243
  ...active.preCommands.map((cmd) => probeAntigravityHookCommand(cmd, probeCwd, 'PreToolUse')),
243
244
  ...active.postCommands.map((cmd) => probeAntigravityHookCommand(cmd, probeCwd, 'PostToolUse'))
@@ -275,17 +276,34 @@ function inspectAntigravityHookWiring(cwd, homeDir = getHomeDir(), options = {})
275
276
  };
276
277
  }
277
278
 
278
- function inspectHookWiring(cwd) {
279
+ function claudeSettingsWireBurnoff(settingsPath) {
280
+ try {
281
+ if (!fs.existsSync(settingsPath)) return false;
282
+ const hooks = JSON.parse(fs.readFileSync(settingsPath, 'utf8'))?.hooks || {};
283
+ const text = JSON.stringify(hooks);
284
+ return text.includes('pre-tool-use.mjs') || text.includes('burnoff-hook-shim.mjs');
285
+ } catch {
286
+ return false; // ignore: malformed settings are reported as unwired
287
+ }
288
+ }
289
+
290
+ function inspectHookWiring(cwd, homeDir = getHomeDir()) {
279
291
  const settingsLocalPath = path.join(cwd, '.claude', 'settings.local.json');
292
+ const globalSettingsPath = path.join(homeDir, '.claude', 'settings.json');
293
+ // Project settings win; fall back to a global Claude install (~/.claude/settings.json).
294
+ const useGlobal =
295
+ !claudeSettingsWireBurnoff(settingsLocalPath) && claudeSettingsWireBurnoff(globalSettingsPath);
296
+ const activeSettingsPath = useGlobal ? globalSettingsPath : settingsLocalPath;
297
+ const scope = useGlobal ? 'global' : 'project';
280
298
  let preToolHook = false;
281
299
  let postToolHook = false;
282
300
  let postToolFailureHook = false;
283
301
  let sessionStartHook = false;
284
302
  let preCompactHook = false;
285
303
 
286
- if (fs.existsSync(settingsLocalPath)) {
304
+ if (fs.existsSync(activeSettingsPath)) {
287
305
  try {
288
- const parsed = JSON.parse(fs.readFileSync(settingsLocalPath, 'utf8'));
306
+ const parsed = JSON.parse(fs.readFileSync(activeSettingsPath, 'utf8'));
289
307
  const hooks = parsed?.hooks || {};
290
308
  const containsHook = (groups, targetName, shimToken) =>
291
309
  Array.isArray(groups) &&
@@ -333,6 +351,8 @@ function inspectHookWiring(cwd) {
333
351
 
334
352
  return {
335
353
  settingsLocalPath,
354
+ settingsPath: activeSettingsPath,
355
+ scope,
336
356
  installed: preToolHook && postToolHook,
337
357
  preToolHook,
338
358
  postToolHook,
@@ -397,7 +417,7 @@ export async function runDoctor(options = {}) {
397
417
  const nodeSupported = isSupportedNodeVersion(nodeVersion);
398
418
  const nativeSqlite = hasNativeNodeSqlite(nodeVersion);
399
419
  const policy = loadBurnoffPolicy(cwd);
400
- const hooks = inspectHookWiring(cwd);
420
+ const hooks = inspectHookWiring(cwd, homeDir);
401
421
  const antigravityHooks = inspectAntigravityHookWiring(cwd, homeDir, options);
402
422
  const fts5DbPath = getDefaultToolLogsDbPath(explicitHomeDir);
403
423
  const fts5Stats = getFts5CompressionStats(fts5DbPath, { homeDir: explicitHomeDir });
@@ -504,6 +524,7 @@ export async function runDoctor(options = {}) {
504
524
  sourcePath: policy.sourcePath,
505
525
  exists: policy.exists,
506
526
  parseError: Boolean(policy.parseError),
527
+ parseErrorMessage: policy.parseErrorMessage || null,
507
528
  guardMode: policy.guards?.mode || 'guard',
508
529
  postOutputMode: resolvePostOutputMode(policy.postTool),
509
530
  strictTestIntegrity: Boolean(policy.guards?.strictTestIntegrity),
@@ -541,7 +562,7 @@ export async function runDoctor(options = {}) {
541
562
  */
542
563
  export function formatDoctorReport(report = {}) {
543
564
  const claudeLine = report.hooks?.installed
544
- ? `installed (.claude/settings.local.json) [PostToolUseFailure=${report.hooks.postToolFailureHook ? 'ok' : 'missing'}]`
565
+ ? `installed (${report.hooks.scope === 'global' ? '~/.claude/settings.json' : '.claude/settings.local.json'}) [PostToolUseFailure=${report.hooks.postToolFailureHook ? 'ok' : 'missing'}]`
545
566
  : 'not installed';
546
567
  const agBase = report.antigravityHooks?.project?.installed
547
568
  ? 'installed (.agents/hooks.json)'
@@ -566,6 +587,11 @@ export function formatDoctorReport(report = {}) {
566
587
  ` Ledger : $${Number(report.ledger?.avoidedWriteUSD || 0).toFixed(4)} avoided | $${Number(report.ledger?.platformCacheUSD || 0).toFixed(4)} cache discount (${report.ledger?.entryCount ?? 0} receipts)`,
567
588
  ` Atomic I/O : ${report.atomicIo?.renameRetries ?? 0} rename retries, ${report.atomicIo?.renameExhausted ?? 0} exhausted`
568
589
  ];
590
+ if (report.policy?.parseError) {
591
+ lines.push(
592
+ ` Policy parse error: ${report.policy.parseErrorMessage || 'malformed .burnoff.yaml'} (policy defaults are in effect)`
593
+ );
594
+ }
569
595
  if (report.gc?.performed) {
570
596
  lines.push(
571
597
  ` GC : pruned=${report.gc.fts5Pruned?.deletedRows ?? 0} FTS5 rows, reaped=${report.gc.reapedCacheFiles} cache files (${report.gc.reclaimedBytes} bytes), rotated=${report.gc.ledgerRotation?.rotatedCount ?? 0} ledger entries`
@@ -8,6 +8,9 @@ import fs from 'node:fs';
8
8
  import path from 'node:path';
9
9
  import { getHomeDir, hasNativeNodeSqlite } from '../config/paths.mjs';
10
10
  import { getDatabaseSyncClass } from '../storage/sqlite-client.mjs';
11
+ import { readBoundedTailUtf8 } from '../storage/jsonl-parser.mjs';
12
+
13
+ const HOOK_HEALTH_MAX_TRANSCRIPT_BYTES = 4 * 1024 * 1024;
11
14
 
12
15
  export const BURNOFF_COMMAND_RE =
13
16
  /hooks[\\/](?:pre-tool-use|post-tool-use|session-lifecycle)\.mjs|burnoff-hook-shim\.mjs|hook-shim\.mjs|\bburnoff\b/i;
@@ -256,6 +259,11 @@ export function scanAntigravityHookFailures({
256
259
  let db = null;
257
260
  try {
258
261
  db = new DatabaseSyncClass(file, { readOnly: true });
262
+ try {
263
+ db.exec?.('PRAGMA busy_timeout = 3000;');
264
+ } catch {
265
+ // ignore: mock or immutable DB without PRAGMA support
266
+ }
259
267
  out.databases += 1;
260
268
  const rows = db.prepare('SELECT error_details FROM steps WHERE status = 7 AND error_details IS NOT NULL').all();
261
269
  for (const row of rows) {
@@ -317,7 +325,7 @@ export function checkHookHealth({
317
325
  for (const { file } of files) {
318
326
  let lines;
319
327
  try {
320
- lines = fs.readFileSync(file, 'utf8').split(/\r?\n/);
328
+ lines = readBoundedTailUtf8(file, HOOK_HEALTH_MAX_TRANSCRIPT_BYTES).split(/\r?\n/);
321
329
  } catch {
322
330
  continue; // ignore: unreadable transcript skipped
323
331
  }