burnoff 1.0.0 → 1.2.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 (41) hide show
  1. package/.github/workflows/burnoff-pr-gate.yml +75 -0
  2. package/README.md +94 -20
  3. package/bin/burnoff.mjs +129 -30
  4. package/hooks/hook-io.mjs +27 -18
  5. package/hooks/post-tool-use.mjs +33 -26
  6. package/hooks/pre-tool-use.mjs +43 -41
  7. package/hooks/session-lifecycle.mjs +40 -0
  8. package/package.json +8 -5
  9. package/src/ci/ci-gate.mjs +84 -9
  10. package/src/ci/pr-cost.mjs +207 -22
  11. package/src/ci/team-digest.mjs +6 -4
  12. package/src/cli/audit.mjs +177 -23
  13. package/src/cli/doctor.mjs +230 -25
  14. package/src/cli/init.mjs +415 -75
  15. package/src/cli/startup-audit.mjs +2824 -0
  16. package/src/clients/antigravity.mjs +285 -0
  17. package/src/clients/claude-code.mjs +180 -0
  18. package/src/clients/detect.mjs +64 -0
  19. package/src/config/catalog.json +188 -45
  20. package/src/config/loader.mjs +96 -13
  21. package/src/config/paths.mjs +92 -2
  22. package/src/config/policy.mjs +103 -17
  23. package/src/config/pricing.mjs +1033 -0
  24. package/src/config/uncached-attribution.mjs +719 -0
  25. package/src/guards/loop-breaker.mjs +267 -24
  26. package/src/guards/post-tool-engine.mjs +316 -35
  27. package/src/guards/pre-tool-engine.mjs +389 -130
  28. package/src/guards/read-clamp.mjs +149 -75
  29. package/src/guards/session-hook.mjs +207 -0
  30. package/src/guards/shell-guard.mjs +610 -74
  31. package/src/ipc/daemon.mjs +50 -8
  32. package/src/ipc/fast-client.mjs +62 -5
  33. package/src/ipc/protocol.mjs +1 -1
  34. package/src/storage/antigravity-parser.mjs +258 -0
  35. package/src/storage/atomic-io.mjs +2 -2
  36. package/src/storage/file-lock.mjs +66 -13
  37. package/src/storage/fts5-archive.mjs +31 -16
  38. package/src/storage/jsonl-parser.mjs +209 -20
  39. package/src/storage/ledger.mjs +15 -10
  40. package/src/storage/sqlite-client.mjs +35 -11
  41. package/hooks/hooks.json +0 -12
package/src/cli/audit.mjs CHANGED
@@ -12,7 +12,14 @@ import {
12
12
  discoverClaudeCodeSessions,
13
13
  parseTranscriptIncremental
14
14
  } from '../storage/jsonl-parser.mjs';
15
+ import {
16
+ discoverAntigravityTranscripts,
17
+ isAntigravityTranscriptFile,
18
+ parseAntigravityTranscript
19
+ } from '../storage/antigravity-parser.mjs';
15
20
  import { getSavedQuotaReceiptSummary } from '../storage/ledger.mjs';
21
+ import { attributeUncachedTokens } from '../config/uncached-attribution.mjs';
22
+ import { valuateBatch } from '../config/pricing.mjs';
16
23
 
17
24
  function summarizeParsedSession(meta, parsed, options = {}) {
18
25
  const steps = Array.isArray(parsed?.steps) ? parsed.steps : [];
@@ -21,10 +28,19 @@ function summarizeParsedSession(meta, parsed, options = {}) {
21
28
  let cacheReadTokens = 0;
22
29
  let outputTokens = 0;
23
30
  let thinkingTokens = 0;
31
+ let billedOutputTokens = 0;
24
32
  let estimatedCostUsd = 0;
25
33
  let cliffTurns = 0;
26
34
  let unknownModelTurns = 0;
27
35
  let lastModel = 'claude-sonnet-5-5';
36
+ const sessionId = meta.sessionId || path.basename(meta.filePath || 'session.jsonl', '.jsonl');
37
+ const entrypoint =
38
+ parsed?.claudeDag?.sessionEntrypoint ||
39
+ parsed?.entrypoint ||
40
+ parsed?.sessionEntrypoint ||
41
+ options.entrypoint ||
42
+ null;
43
+ const attributionCalls = [];
28
44
 
29
45
  for (const step of steps) {
30
46
  const u = step?.tokenUsage || step || {};
@@ -38,9 +54,30 @@ function summarizeParsedSession(meta, parsed, options = {}) {
38
54
  if (inTok + cwTok + crTok + outTok + thinkTok === 0) continue;
39
55
 
40
56
  if (step.model) lastModel = step.model;
57
+ const effectiveModel = step.model || lastModel;
58
+ attributionCalls.push({
59
+ conv: sessionId,
60
+ idx: step.stepIndex ?? attributionCalls.length,
61
+ model: effectiveModel,
62
+ freshInputTokens: inTok,
63
+ cacheCreationTokens: cwTok,
64
+ cacheCreationEphemeral5mInputTokens: w5m,
65
+ cacheCreationEphemeral1hInputTokens: w1h,
66
+ cacheReadTokens: crTok,
67
+ outputTokens: outTok,
68
+ thinkingTokens: thinkTok,
69
+ createdAt: step.createdAt || null,
70
+ hadCompactionBefore: Boolean(step.hadCompactionBefore),
71
+ isCompactSummary: Boolean(step.isCompactSummary),
72
+ isCompactionBoundary: Boolean(step.isCompactionBoundary),
73
+ isSidechain: Boolean(step.isSidechain),
74
+ entrypoint: step.entrypoint || entrypoint || null,
75
+ shapeHash: step.shapeHash || null,
76
+ cacheTtlTier: step.cacheTtlTier || (w1h > 0 ? '1h' : '5m')
77
+ });
41
78
  const costRes = calculateTurnCostUSD(
42
79
  {
43
- model: step.model || lastModel,
80
+ model: effectiveModel,
44
81
  inputTokens: inTok,
45
82
  cacheWrite5mTokens: w5m,
46
83
  cacheWrite1hTokens: w1h,
@@ -57,6 +94,7 @@ function summarizeParsedSession(meta, parsed, options = {}) {
57
94
  cacheReadTokens += crTok;
58
95
  outputTokens += outTok;
59
96
  thinkingTokens += thinkTok;
97
+ billedOutputTokens += Number(costRes?.tokens?.totalOutput ?? outTok);
60
98
 
61
99
  if (costRes.unknownModel) {
62
100
  unknownModelTurns += 1;
@@ -66,12 +104,16 @@ function summarizeParsedSession(meta, parsed, options = {}) {
66
104
  }
67
105
  }
68
106
 
69
- const totalTokens = inputTokens + cacheWriteTokens + cacheReadTokens + outputTokens + thinkingTokens;
107
+ const totalTokens = inputTokens + cacheWriteTokens + cacheReadTokens + billedOutputTokens;
70
108
  const cacheDenom = inputTokens + cacheWriteTokens + cacheReadTokens;
71
109
  const cacheHitPct = cacheDenom > 0 ? Math.round((cacheReadTokens / cacheDenom) * 100) : 0;
72
110
 
111
+ const uncachedAttribution = attributeUncachedTokens(attributionCalls, {
112
+ claudeCodeVersion: options.claudeCodeVersion || null
113
+ });
114
+
73
115
  return {
74
- sessionId: meta.sessionId || path.basename(meta.filePath || 'session.jsonl', '.jsonl'),
116
+ sessionId,
75
117
  fileName: path.basename(meta.filePath || ''),
76
118
  projectSlug: meta.projectSlug || '',
77
119
  sessionTitle: parsed?.sessionTitle || '',
@@ -90,33 +132,56 @@ function summarizeParsedSession(meta, parsed, options = {}) {
90
132
  rewindBranches: Array.isArray(parsed?.claudeDag?.rewindBranches)
91
133
  ? parsed.claudeDag.rewindBranches.length
92
134
  : 0,
93
- mtimeMs: meta.mtimeMs || 0
135
+ entrypoint,
136
+ mtimeMs: meta.mtimeMs || 0,
137
+ attributionCalls,
138
+ uncachedAttribution
94
139
  };
95
140
  }
96
141
 
97
142
  /**
98
- * Audits local Claude Code JSONL transcripts (or a single `--session <path>` file).
143
+ * Audits local Claude Code and/or Google Antigravity JSONL transcripts (or a single `--session <path>` file).
99
144
  */
100
145
  export function auditClaudeSessions(options = {}) {
101
- const homeDir = options.homeDir || getHomeDir();
146
+ const explicitHomeDir = typeof options.homeDir === 'string' && options.homeDir.trim()
147
+ ? options.homeDir.trim()
148
+ : null;
149
+ const homeDir = explicitHomeDir || getHomeDir();
102
150
  const limit = Math.max(1, Number(options.limit ?? 20));
103
- const candidates = options.sessionPath
104
- ? [
105
- {
106
- filePath: path.resolve(options.sessionPath),
107
- sessionId: path.basename(options.sessionPath, '.jsonl'),
108
- projectSlug: '',
109
- mtimeMs: 0
110
- }
111
- ]
112
- : discoverClaudeCodeSessions(homeDir, options).slice(0, limit);
151
+ let candidates;
152
+ if (options.sessionPath) {
153
+ const abs = path.resolve(options.sessionPath);
154
+ const isAg = isAntigravityTranscriptFile(abs);
155
+ candidates = [
156
+ {
157
+ filePath: abs,
158
+ sessionId: path.basename(options.sessionPath, '.jsonl'),
159
+ projectSlug: isAg ? 'antigravity' : '',
160
+ client: isAg ? 'antigravity' : 'claude-code',
161
+ mtimeMs: 0
162
+ }
163
+ ];
164
+ } else {
165
+ const clientOpt = String(options.client || 'auto').trim().toLowerCase();
166
+ const includeClaude = clientOpt !== 'antigravity' && clientOpt !== 'ag';
167
+ const includeAg =
168
+ clientOpt === 'antigravity' || clientOpt === 'ag' || clientOpt === 'both' || clientOpt === 'auto';
169
+ const claudeList = includeClaude ? discoverClaudeCodeSessions(homeDir, options) : [];
170
+ const agList = includeAg ? discoverAntigravityTranscripts({ homeDir, cwd: options.cwd }) : [];
171
+ candidates = [...claudeList, ...agList]
172
+ .sort((a, b) => (b.mtimeMs || 0) - (a.mtimeMs || 0))
173
+ .slice(0, limit);
174
+ }
113
175
 
114
176
  const sessions = [];
115
177
  for (const meta of candidates) {
116
- const parsed = parseTranscriptIncremental(meta.filePath, {
117
- homeDir,
118
- tailBytes: options.tailBytes
119
- });
178
+ const useAg = meta.client === 'antigravity' || isAntigravityTranscriptFile(meta.filePath);
179
+ const parsed = useAg
180
+ ? parseAntigravityTranscript(meta.filePath, { sessionId: meta.sessionId })
181
+ : parseTranscriptIncremental(meta.filePath, {
182
+ homeDir: explicitHomeDir,
183
+ tailBytes: options.tailBytes
184
+ });
120
185
  sessions.push(summarizeParsedSession(meta, parsed, options));
121
186
  }
122
187
 
@@ -153,17 +218,33 @@ export function auditClaudeSessions(options = {}) {
153
218
  const denom = totals.inputTokens + totals.cacheWriteTokens + totals.cacheReadTokens;
154
219
  totals.cacheHitPct = denom > 0 ? Math.round((totals.cacheReadTokens / denom) * 100) : 0;
155
220
 
156
- const ledger = getSavedQuotaReceiptSummary({ homeDir });
221
+ const ledger = getSavedQuotaReceiptSummary({ homeDir: explicitHomeDir });
222
+ const allAttributionCalls = sessions.flatMap((s) => s.attributionCalls || []);
223
+ const valuation = valuateBatch(allAttributionCalls, {
224
+ nowMs: options.nowMs ?? Date.now(),
225
+ days: options.days ?? 7
226
+ });
227
+ const sdkCliSessions = sessions.filter((s) => s.entrypoint === 'sdk-cli').length;
228
+ totals.normalizedQuotaBurnUnits = valuation.totalNormalizedQuotaBurnUnits;
229
+ totals.effectiveQuotaMultiplier = valuation.effectiveQuotaMultiplier;
230
+ totals.sdkCliSessions = sdkCliSessions;
231
+ totals.sdkCliHeuristicApplied = Boolean(valuation.quotaBurnSummary?.sdkCliHeuristicApplied || sdkCliSessions > 0);
232
+ const uncachedAttribution = attributeUncachedTokens(allAttributionCalls, {
233
+ claudeCodeVersion: options.claudeCodeVersion || null
234
+ });
235
+ const cleanSessions = sessions.map(({ attributionCalls: _calls, ...rest }) => rest);
157
236
 
158
237
  return {
159
238
  ok: true,
160
239
  totals,
240
+ valuation,
241
+ uncachedAttribution,
161
242
  ledger: {
162
243
  avoidedWriteUSD: ledger.burnoffAvoidedWriteUSD,
163
244
  avoidedWriteTokens: ledger.burnoffAvoidedWriteTokens,
164
245
  platformCacheUSD: ledger.platformCacheDiscountUSD
165
246
  },
166
- sessions
247
+ sessions: cleanSessions
167
248
  };
168
249
  }
169
250
 
@@ -172,12 +253,85 @@ export function auditClaudeSessions(options = {}) {
172
253
  */
173
254
  export function formatAuditReport(report = {}) {
174
255
  const t = report.totals || {};
256
+ const quotaTag =
257
+ t.normalizedQuotaBurnUnits !== undefined
258
+ ? ` | Quota Burn: ${Number(t.normalizedQuotaBurnUnits || 0).toFixed(2)} Q-units (${Number(t.effectiveQuotaMultiplier || 1).toFixed(2)}x)`
259
+ : '';
175
260
  const lines = [
176
261
  `Burnoff Claude Code Session Audit (${t.sessions ?? 0} sessions, ${t.turns ?? 0} steps)`,
177
262
  ` 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}`,
263
+ ` Estimated Cost : $${Number(t.estimatedCostUsd || 0).toFixed(4)} | 200k-cliff turns=${t.cliffTurns ?? 0} | rewind branches=${t.rewindBranches ?? 0}${quotaTag}`,
179
264
  ` Guard Savings : $${Number(report.ledger?.avoidedWriteUSD || 0).toFixed(4)} avoided (${(report.ledger?.avoidedWriteTokens || 0).toLocaleString('en-US')} tok)`
180
265
  ];
266
+ if (t.sdkCliSessions > 0 || t.sdkCliHeuristicApplied) {
267
+ lines.push(
268
+ ` 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).`
269
+ );
270
+ }
271
+ const claude55Miss = report.uncachedAttribution?.buckets?.compaction_rebuild?.claude55CompactCacheMiss;
272
+ if (claude55Miss && claude55Miss.calls > 0) {
273
+ lines.push(
274
+ ` Provider Quirk : Claude 5.5 /compact warm-cache miss (#99624): ${claude55Miss.calls} calls, ${claude55Miss.tokens.toLocaleString('en-US')} uncached tok`
275
+ );
276
+ }
277
+ const buckets = report.uncachedAttribution?.buckets || {};
278
+ const thrash = buckets.model_or_effort_switch?.orchestratorThrash;
279
+ if (thrash && thrash.calls > 0) {
280
+ lines.push(
281
+ ` Provider Quirk : Orchestrator/model ping-pong thrash (${thrash.issueRef || '#1638'}): ${thrash.calls} calls, ${thrash.tokens.toLocaleString('en-US')} uncached tok — ${thrash.guidance}`
282
+ );
283
+ }
284
+ if (Number(report.uncachedAttribution?.totalUncachedTokens || 0) > 0) {
285
+ const driverLines = [];
286
+ const idleMiss = buckets.idle_ttl_miss;
287
+ if (idleMiss && idleMiss.tokens > 0) {
288
+ driverLines.push(
289
+ ` - 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`
290
+ );
291
+ }
292
+ const modelSwitch = buckets.model_or_effort_switch;
293
+ if (modelSwitch && modelSwitch.tokens > 0) {
294
+ driverLines.push(
295
+ ` - model_or_effort_switch: ${modelSwitch.calls} calls, ${modelSwitch.tokens.toLocaleString('en-US')} tok (${modelSwitch.sharePct}%, ~$${Number(modelSwitch.estimatedUsd || 0).toFixed(2)})`
296
+ );
297
+ }
298
+ const unexplained = buckets.unexplained_prefix_reset;
299
+ if (unexplained && unexplained.tokens > 0) {
300
+ const act = unexplained.subBuckets?.actionable_prefix_reset;
301
+ const up = unexplained.subBuckets?.upstream_provider_eviction;
302
+ let emittedSub = false;
303
+ if (act && act.tokens > 0) {
304
+ const likelyHint = Array.isArray(unexplained.likelyCauses) && unexplained.likelyCauses.length > 0
305
+ ? ` (e.g., ${unexplained.likelyCauses[0]})`
306
+ : '';
307
+ driverLines.push(
308
+ ` - unexplained_prefix_reset (actionable): ${act.calls} calls, ${act.tokens.toLocaleString('en-US')} tok (${act.shareOfBucketPct ?? unexplained.sharePct}%, ~$${Number(act.estimatedUsd || 0).toFixed(2)})${likelyHint}`
309
+ );
310
+ emittedSub = true;
311
+ }
312
+ if (up && up.tokens > 0) {
313
+ const adviceHint = up.advice ? ` — ${up.advice}` : '';
314
+ driverLines.push(
315
+ ` - 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}`
316
+ );
317
+ emittedSub = true;
318
+ }
319
+ if (!emittedSub) {
320
+ driverLines.push(
321
+ ` - unexplained_prefix_reset: ${unexplained.calls} calls, ${unexplained.tokens.toLocaleString('en-US')} tok (${unexplained.sharePct}%, ~$${Number(unexplained.estimatedUsd || 0).toFixed(2)})`
322
+ );
323
+ }
324
+ }
325
+ const compaction = buckets.compaction_rebuild;
326
+ if (compaction && compaction.tokens > 0) {
327
+ driverLines.push(
328
+ ` - compaction_rebuild: ${compaction.calls} calls, ${compaction.tokens.toLocaleString('en-US')} tok (${compaction.sharePct}%, ~$${Number(compaction.estimatedUsd || 0).toFixed(2)})`
329
+ );
330
+ }
331
+ if (driverLines.length > 0) {
332
+ lines.push('', ' Uncached Drivers:', ...driverLines);
333
+ }
334
+ }
181
335
  if (Array.isArray(report.sessions) && report.sessions.length > 0) {
182
336
  lines.push('', ' Recent Sessions:');
183
337
  for (const s of report.sessions.slice(0, 10)) {
@@ -7,6 +7,7 @@
7
7
 
8
8
  import fs from 'node:fs';
9
9
  import path from 'node:path';
10
+ import { spawnSync } from 'node:child_process';
10
11
  import {
11
12
  MIN_NODE_VERSION,
12
13
  NATIVE_SQLITE_NODE_VERSION,
@@ -24,27 +25,181 @@ import {
24
25
  pruneExpiredFts5LogsSync
25
26
  } from '../storage/fts5-archive.mjs';
26
27
  import { getSavedQuotaReceiptSummary, rotateMonthlyLedger } from '../storage/ledger.mjs';
27
- import { openBurnoffDb } from '../storage/sqlite-client.mjs';
28
+ import { openBurnoffDb, resolveFallbackDbPath } from '../storage/sqlite-client.mjs';
28
29
  import { sendDaemonRpc, resolveFastIpcPipePath } from '../ipc/fast-client.mjs';
29
30
 
31
+ function extractFirstCommand(groups) {
32
+ if (!Array.isArray(groups)) return null;
33
+ for (const g of groups) {
34
+ if (Array.isArray(g?.hooks)) {
35
+ for (const h of g.hooks) {
36
+ if (typeof h?.command === 'string' && h.command.trim()) {
37
+ return h.command.trim();
38
+ }
39
+ }
40
+ } else if (typeof g?.command === 'string' && g.command.trim()) {
41
+ return g.command.trim();
42
+ }
43
+ }
44
+ return null;
45
+ }
46
+
47
+ function probeAntigravityHookCommand(command, probeCwd, projectCwd) {
48
+ if (!command) {
49
+ return { checked: false, ok: false, command: null, decision: null, exitCode: null, error: 'missing command' };
50
+ }
51
+ const probePayload = JSON.stringify({
52
+ conversationId: 'burnoff-doctor-probe',
53
+ cwd: projectCwd,
54
+ hookEventName: 'PreToolUse',
55
+ toolCall: {
56
+ id: 'doctor-probe',
57
+ name: 'read_file',
58
+ args: {
59
+ AbsolutePath: path.join(projectCwd, 'package.json'),
60
+ StartLine: 1,
61
+ EndLine: 5
62
+ }
63
+ }
64
+ });
65
+ const run = spawnSync(command, {
66
+ shell: true,
67
+ cwd: probeCwd,
68
+ input: probePayload,
69
+ encoding: 'utf8',
70
+ timeout: 4000,
71
+ windowsHide: true
72
+ });
73
+ if (run.error) {
74
+ return {
75
+ checked: true,
76
+ ok: false,
77
+ command,
78
+ decision: null,
79
+ exitCode: run.status ?? null,
80
+ error: run.error.message || String(run.error)
81
+ };
82
+ }
83
+ const stdout = String(run.stdout || '').trim();
84
+ if (run.status !== 0) {
85
+ return {
86
+ checked: true,
87
+ ok: false,
88
+ command,
89
+ decision: null,
90
+ exitCode: run.status,
91
+ error: String(run.stderr || stdout || `Exited with status ${run.status}`).trim()
92
+ };
93
+ }
94
+ try {
95
+ const parsed = JSON.parse(stdout);
96
+ const ok = Boolean(parsed && typeof parsed === 'object' && typeof parsed.decision === 'string');
97
+ return {
98
+ checked: true,
99
+ ok,
100
+ command,
101
+ decision: parsed?.decision || null,
102
+ exitCode: run.status,
103
+ error: ok ? null : 'Missing JSON decision field in stdout'
104
+ };
105
+ } catch (parseErr) {
106
+ return {
107
+ checked: true,
108
+ ok: false,
109
+ command,
110
+ decision: null,
111
+ exitCode: run.status,
112
+ error: `Invalid JSON stdout: ${parseErr?.message || String(parseErr)}`
113
+ };
114
+ }
115
+ }
116
+
117
+ function inspectAntigravityHookWiring(cwd, homeDir = getHomeDir(), options = {}) {
118
+ const projectHooksPath = path.join(cwd, '.agents', 'hooks.json');
119
+ const globalHooksPath = path.join(homeDir, '.gemini', 'config', 'hooks.json');
120
+ const inspectFile = (filePath) => {
121
+ if (!filePath || !fs.existsSync(filePath)) {
122
+ return { path: filePath, installed: false, preToolHook: false, postToolHook: false, enabled: false, preCommand: null };
123
+ }
124
+ try {
125
+ const parsed = JSON.parse(fs.readFileSync(filePath, 'utf8'));
126
+ const entry = parsed?.burnoff;
127
+ if (!entry || typeof entry !== 'object') {
128
+ return { path: filePath, installed: false, preToolHook: false, postToolHook: false, enabled: false, preCommand: null };
129
+ }
130
+ const enabled = entry.enabled !== false;
131
+ const containsHook = (groups, targetName, shimToken) =>
132
+ Array.isArray(groups) &&
133
+ groups.some((g) => {
134
+ const checkCmd = (c) => {
135
+ const s = String(c || '');
136
+ return s.includes(targetName) || (s.includes('hook-shim.mjs') && s.includes(shimToken));
137
+ };
138
+ return Array.isArray(g?.hooks) ? g.hooks.some((h) => checkCmd(h?.command)) : checkCmd(g?.command);
139
+ });
140
+ const preToolHook = containsHook(entry.PreToolUse, 'pre-tool-use.mjs', ' pre');
141
+ const postToolHook = containsHook(entry.PostToolUse, 'post-tool-use.mjs', ' post');
142
+ const preCommand = extractFirstCommand(entry.PreToolUse);
143
+ return {
144
+ path: filePath,
145
+ installed: enabled && preToolHook && postToolHook,
146
+ enabled,
147
+ preToolHook,
148
+ postToolHook,
149
+ preCommand
150
+ };
151
+ } catch (err) {
152
+ void err; // ignore: malformed hooks.json reported as unwired
153
+ return { path: filePath, installed: false, preToolHook: false, postToolHook: false, enabled: false, preCommand: null };
154
+ }
155
+ };
156
+
157
+ const project = inspectFile(projectHooksPath);
158
+ const global = inspectFile(globalHooksPath);
159
+ const installed = project.installed || global.installed;
160
+
161
+ let healthCheck = { checked: false, ok: false, command: null, decision: null, exitCode: null, error: null };
162
+ if (installed && !options.skipAntigravityProbe) {
163
+ const active = project.installed ? project : global;
164
+ const agentsDir = path.join(cwd, '.agents');
165
+ const probeCwd = fs.existsSync(agentsDir) ? agentsDir : cwd;
166
+ healthCheck = probeAntigravityHookCommand(active.preCommand, probeCwd, cwd);
167
+ }
168
+
169
+ return {
170
+ installed,
171
+ project,
172
+ global,
173
+ healthCheck
174
+ };
175
+ }
176
+
30
177
  function inspectHookWiring(cwd) {
31
178
  const settingsLocalPath = path.join(cwd, '.claude', 'settings.local.json');
32
179
  let preToolHook = false;
33
180
  let postToolHook = false;
181
+ let postToolFailureHook = false;
182
+ let sessionStartHook = false;
183
+ let preCompactHook = false;
34
184
 
35
185
  if (fs.existsSync(settingsLocalPath)) {
36
186
  try {
37
187
  const parsed = JSON.parse(fs.readFileSync(settingsLocalPath, 'utf8'));
38
188
  const hooks = parsed?.hooks || {};
39
- const containsHook = (groups, targetName) =>
189
+ const containsHook = (groups, targetName, shimToken) =>
40
190
  Array.isArray(groups) &&
41
- groups.some((g) =>
42
- Array.isArray(g?.hooks)
43
- ? g.hooks.some((h) => String(h?.command || '').includes(targetName))
44
- : String(g?.command || '').includes(targetName)
45
- );
46
- preToolHook = containsHook(hooks.PreToolUse, 'pre-tool-use.mjs');
47
- postToolHook = containsHook(hooks.PostToolUse, 'post-tool-use.mjs');
191
+ groups.some((g) => {
192
+ const checkCmd = (c) => {
193
+ const s = String(c || '');
194
+ return s.includes(targetName) || (s.includes('burnoff-hook-shim.mjs') && s.includes(shimToken));
195
+ };
196
+ return Array.isArray(g?.hooks) ? g.hooks.some((h) => checkCmd(h?.command)) : checkCmd(g?.command);
197
+ });
198
+ preToolHook = containsHook(hooks.PreToolUse, 'pre-tool-use.mjs', ' pre');
199
+ postToolHook = containsHook(hooks.PostToolUse, 'post-tool-use.mjs', ' post');
200
+ postToolFailureHook = containsHook(hooks.PostToolUseFailure, 'post-tool-use.mjs', ' post');
201
+ sessionStartHook = containsHook(hooks.SessionStart, 'session-lifecycle.mjs', ' session');
202
+ preCompactHook = containsHook(hooks.PreCompact, 'session-lifecycle.mjs', ' session');
48
203
  } catch (err) {
49
204
  void err; // ignore: malformed settings.local.json reported as unwired
50
205
  }
@@ -80,6 +235,9 @@ function inspectHookWiring(cwd) {
80
235
  installed: preToolHook && postToolHook,
81
236
  preToolHook,
82
237
  postToolHook,
238
+ postToolFailureHook,
239
+ sessionStartHook,
240
+ preCompactHook,
83
241
  excludePath,
84
242
  gitExcludeProtected
85
243
  };
@@ -100,7 +258,13 @@ function reapStaleCacheFiles(dirPath, cutoffMs, skipNames = new Set()) {
100
258
  }
101
259
  for (const entry of entries) {
102
260
  if (!entry.isFile()) continue;
103
- if (skipNames.has(entry.name) || entry.name.startsWith('tool_logs_fts5.db')) continue;
261
+ if (
262
+ skipNames.has(entry.name) ||
263
+ entry.name.startsWith('tool_logs_fts5.db') ||
264
+ entry.name.startsWith('tool_logs_fallback.json')
265
+ ) {
266
+ continue;
267
+ }
104
268
  const full = path.join(dirPath, entry.name);
105
269
  try {
106
270
  const st = fs.statSync(full);
@@ -121,7 +285,10 @@ function reapStaleCacheFiles(dirPath, cutoffMs, skipNames = new Set()) {
121
285
  */
122
286
  export async function runDoctor(options = {}) {
123
287
  const cwd = path.resolve(options.cwd || process.cwd());
124
- const homeDir = options.homeDir || getHomeDir();
288
+ const explicitHomeDir = typeof options.homeDir === 'string' && options.homeDir.trim()
289
+ ? options.homeDir.trim()
290
+ : null;
291
+ const homeDir = explicitHomeDir || getHomeDir();
125
292
  const nodeVersion = options.nodeVersion || process.versions.node;
126
293
  const nowMs = Number(options.nowMs || Date.now());
127
294
  const maxCacheAgeDays = Math.max(1, Number(options.maxCacheAgeDays ?? 14));
@@ -130,18 +297,19 @@ export async function runDoctor(options = {}) {
130
297
  const nativeSqlite = hasNativeNodeSqlite(nodeVersion);
131
298
  const policy = loadBurnoffPolicy(cwd);
132
299
  const hooks = inspectHookWiring(cwd);
133
- const fts5DbPath = getDefaultToolLogsDbPath(homeDir);
134
- const fts5Stats = getFts5CompressionStats(fts5DbPath, { homeDir });
135
- const ledgerSummary = getSavedQuotaReceiptSummary({ homeDir, nowMs });
300
+ const antigravityHooks = inspectAntigravityHookWiring(cwd, homeDir, options);
301
+ const fts5DbPath = getDefaultToolLogsDbPath(explicitHomeDir);
302
+ const fts5Stats = getFts5CompressionStats(fts5DbPath, { homeDir: explicitHomeDir });
303
+ const ledgerSummary = getSavedQuotaReceiptSummary({ homeDir: explicitHomeDir, nowMs });
136
304
  const atomicIo = getAtomicIoMetrics();
137
305
 
138
306
  let daemonPing = null;
139
- const ipcPath = resolveFastIpcPipePath({ cwd, homeDir, ipcPath: options.ipcPath });
307
+ const ipcPath = resolveFastIpcPipePath({ cwd, homeDir: explicitHomeDir, ipcPath: options.ipcPath });
140
308
  if (!options.skipDaemonCheck) {
141
309
  daemonPing = await sendDaemonRpc(
142
310
  'daemon.ping',
143
311
  {},
144
- { cwd, homeDir, ipcPath: options.ipcPath, requestTimeoutMs: 80 }
312
+ { cwd, homeDir: explicitHomeDir, ipcPath: options.ipcPath, requestTimeoutMs: 80 }
145
313
  );
146
314
  }
147
315
 
@@ -149,7 +317,7 @@ export async function runDoctor(options = {}) {
149
317
  if (options.gc) {
150
318
  const retentionDays = Number(policy?.postTool?.retentionDays ?? 30);
151
319
  let fts5Pruned = { skipped: true, deletedRows: 0, vacuumed: false };
152
- if (fs.existsSync(fts5DbPath)) {
320
+ if (fs.existsSync(fts5DbPath) || fs.existsSync(resolveFallbackDbPath(fts5DbPath))) {
153
321
  let db = null;
154
322
  try {
155
323
  db = openBurnoffDb(fts5DbPath, { readOnly: false });
@@ -161,29 +329,51 @@ export async function runDoctor(options = {}) {
161
329
  }
162
330
  }
163
331
  const cutoffMs = nowMs - maxCacheAgeDays * 24 * 60 * 60 * 1000;
164
- const homeCacheReaped = reapStaleCacheFiles(getBurnoffCacheDir(homeDir), cutoffMs);
332
+ const homeCacheReaped = reapStaleCacheFiles(getBurnoffCacheDir(explicitHomeDir), cutoffMs);
165
333
  const wsCacheReaped = reapStaleCacheFiles(path.join(cwd, '.claude', 'cache'), cutoffMs);
166
334
  const wsArtifactsReaped = reapStaleCacheFiles(path.join(cwd, '.claude', 'cache', 'artifacts'), cutoffMs);
167
- const ledgerRotation = rotateMonthlyLedger({ homeDir, nowMs });
335
+ const stateRootDir = path.join(getBurnoffHomeDir(explicitHomeDir), 'state');
336
+ let agStateRemoved = 0;
337
+ let agStateBytes = 0;
338
+ if (fs.existsSync(stateRootDir)) {
339
+ try {
340
+ for (const ent of fs.readdirSync(stateRootDir, { withFileTypes: true })) {
341
+ if (ent.isDirectory()) {
342
+ const sub = reapStaleCacheFiles(path.join(stateRootDir, ent.name), cutoffMs);
343
+ agStateRemoved += sub.removedFiles;
344
+ agStateBytes += sub.reclaimedBytes;
345
+ }
346
+ }
347
+ } catch (err) {
348
+ void err; // ignore: unreadable state root during gc
349
+ }
350
+ }
351
+ const ledgerRotation = rotateMonthlyLedger({ homeDir: explicitHomeDir, nowMs });
168
352
  gcResult = {
169
353
  performed: true,
170
354
  maxCacheAgeDays,
171
355
  fts5Pruned,
172
356
  reapedCacheFiles:
173
- homeCacheReaped.removedFiles + wsCacheReaped.removedFiles + wsArtifactsReaped.removedFiles,
357
+ homeCacheReaped.removedFiles + wsCacheReaped.removedFiles + wsArtifactsReaped.removedFiles + agStateRemoved,
174
358
  reclaimedBytes:
175
- homeCacheReaped.reclaimedBytes + wsCacheReaped.reclaimedBytes + wsArtifactsReaped.reclaimedBytes,
359
+ homeCacheReaped.reclaimedBytes + wsCacheReaped.reclaimedBytes + wsArtifactsReaped.reclaimedBytes + agStateBytes,
176
360
  ledgerRotation
177
361
  };
178
362
  }
179
363
 
180
- const status = !nodeSupported ? 'ERROR' : (!nativeSqlite || policy.parseError ? 'WARN' : 'OK');
364
+ const anyHooksInstalled = hooks.installed || antigravityHooks.installed;
365
+ const hooksDegraded =
366
+ (hooks.installed && !hooks.postToolFailureHook) ||
367
+ (antigravityHooks.installed && antigravityHooks.healthCheck?.checked && !antigravityHooks.healthCheck.ok);
368
+ const status = !nodeSupported
369
+ ? 'ERROR'
370
+ : (!nativeSqlite || policy.parseError || !anyHooksInstalled || hooksDegraded ? 'WARN' : 'OK');
181
371
 
182
372
  return {
183
373
  ok: nodeSupported,
184
374
  status,
185
375
  cwd,
186
- burnoffHome: getBurnoffHomeDir(homeDir),
376
+ burnoffHome: getBurnoffHomeDir(explicitHomeDir),
187
377
  node: {
188
378
  version: nodeVersion,
189
379
  supported: nodeSupported,
@@ -203,6 +393,7 @@ export async function runDoctor(options = {}) {
203
393
  neverClampCodeOffCliff: Boolean(policy.readClamp?.neverClampCodeOffCliff)
204
394
  },
205
395
  hooks,
396
+ antigravityHooks,
206
397
  daemon: {
207
398
  ipcPath,
208
399
  running: Boolean(daemonPing?.pong),
@@ -211,7 +402,7 @@ export async function runDoctor(options = {}) {
211
402
  },
212
403
  fts5: {
213
404
  dbPath: fts5DbPath,
214
- exists: fs.existsSync(fts5DbPath),
405
+ exists: fs.existsSync(fts5DbPath) || fs.existsSync(resolveFallbackDbPath(fts5DbPath)),
215
406
  ...fts5Stats
216
407
  },
217
408
  ledger: {
@@ -231,13 +422,27 @@ export async function runDoctor(options = {}) {
231
422
  * Formats a `runDoctor()` report for terminal output.
232
423
  */
233
424
  export function formatDoctorReport(report = {}) {
425
+ const claudeLine = report.hooks?.installed
426
+ ? `installed (.claude/settings.local.json) [PostToolUseFailure=${report.hooks.postToolFailureHook ? 'ok' : 'missing'}]`
427
+ : 'not installed';
428
+ const agBase = report.antigravityHooks?.project?.installed
429
+ ? 'installed (.agents/hooks.json)'
430
+ : report.antigravityHooks?.global?.installed
431
+ ? 'installed (~/.gemini/config/hooks.json)'
432
+ : 'not installed';
433
+ const agProbe = report.antigravityHooks?.healthCheck?.checked
434
+ ? (report.antigravityHooks.healthCheck.ok
435
+ ? ' [probe=ok]'
436
+ : ` [probe=failed: ${report.antigravityHooks.healthCheck.error || 'error'}]`)
437
+ : '';
234
438
  const lines = [
235
439
  `Burnoff Doctor: ${report.status || 'UNKNOWN'}`,
236
440
  ` Node.js : v${report.node?.version || 'unknown'} (${report.node?.supported ? 'supported' : `requires >=${report.node?.minVersion}`})`,
237
441
  ` SQLite FTS5 : ${report.sqlite?.mode || 'unknown'}`,
238
442
  ` Burnoff Home : ${report.burnoffHome || ''}`,
239
443
  ` Policy : ${report.policy?.exists ? report.policy.sourcePath : 'defaults (no .burnoff.yaml)'} [mode=${report.policy?.guardMode || 'guard'}]`,
240
- ` Claude Hooks : ${report.hooks?.installed ? 'installed (.claude/settings.local.json)' : 'not installed'} | git exclude=${report.hooks?.gitExcludeProtected ? 'yes' : 'no'}`,
444
+ ` Claude Hooks : ${claudeLine} | git exclude=${report.hooks?.gitExcludeProtected ? 'yes' : 'no'}`,
445
+ ` Antigravity : ${agBase}${agProbe}`,
241
446
  ` Warm Daemon : ${report.daemon?.running ? `running (pid=${report.daemon.pid})` : 'stopped (cold fallback active)'}`,
242
447
  ` FTS5 Archive : ${report.fts5?.logCount ?? 0} logs (~${report.fts5?.formattedSavedK || '0.0k'} tok compressed)`,
243
448
  ` Ledger : $${Number(report.ledger?.avoidedWriteUSD || 0).toFixed(4)} avoided | $${Number(report.ledger?.platformCacheUSD || 0).toFixed(4)} cache discount (${report.ledger?.entryCount ?? 0} receipts)`,