burnoff 1.3.0 → 1.4.1

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.
@@ -1,462 +1,583 @@
1
- /**
2
- * @file src/cli/doctor.mjs
3
- * Burnoff local diagnostics & garbage collection (`burnoff doctor [--gc]`).
4
- * Checks Node/SQLite support, `.burnoff.yaml` policy, `.claude/settings.local.json` hooks,
5
- * warm daemon status, FTS5 archive health, ledger summary, and `atomic-io` retry metrics.
6
- */
7
-
8
- import fs from 'node:fs';
9
- import path from 'node:path';
10
- import { spawnSync } from 'node:child_process';
11
- import {
12
- MIN_NODE_VERSION,
13
- NATIVE_SQLITE_NODE_VERSION,
14
- isSupportedNodeVersion,
15
- hasNativeNodeSqlite,
16
- getHomeDir,
17
- getBurnoffHomeDir,
18
- getBurnoffCacheDir
19
- } from '../config/paths.mjs';
20
- import { loadBurnoffPolicy } from '../config/policy.mjs';
21
- import { getAtomicIoMetrics } from '../storage/atomic-io.mjs';
22
- import {
23
- getDefaultToolLogsDbPath,
24
- getFts5CompressionStats,
25
- pruneExpiredFts5LogsSync
26
- } from '../storage/fts5-archive.mjs';
27
- import { getSavedQuotaReceiptSummary, rotateMonthlyLedger } from '../storage/ledger.mjs';
28
- import { openBurnoffDb, resolveFallbackDbPath } from '../storage/sqlite-client.mjs';
29
- import { sendDaemonRpc, resolveFastIpcPipePath } from '../ipc/fast-client.mjs';
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
-
177
- function inspectHookWiring(cwd) {
178
- const settingsLocalPath = path.join(cwd, '.claude', 'settings.local.json');
179
- let preToolHook = false;
180
- let postToolHook = false;
181
- let postToolFailureHook = false;
182
- let sessionStartHook = false;
183
- let preCompactHook = false;
184
-
185
- if (fs.existsSync(settingsLocalPath)) {
186
- try {
187
- const parsed = JSON.parse(fs.readFileSync(settingsLocalPath, 'utf8'));
188
- const hooks = parsed?.hooks || {};
189
- const containsHook = (groups, targetName, shimToken) =>
190
- Array.isArray(groups) &&
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');
203
- } catch (err) {
204
- void err; // ignore: malformed settings.local.json reported as unwired
205
- }
206
- }
207
-
208
- let gitExcludeProtected = false;
209
- const dotGit = path.join(cwd, '.git');
210
- let excludePath = null;
211
- if (fs.existsSync(dotGit)) {
212
- try {
213
- const st = fs.statSync(dotGit);
214
- let gitDir = st.isDirectory() ? dotGit : null;
215
- if (!gitDir && st.isFile()) {
216
- const m = fs.readFileSync(dotGit, 'utf8').match(/^gitdir:\s*(.+)$/im);
217
- if (m && m[1]) {
218
- gitDir = path.isAbsolute(m[1].trim()) ? m[1].trim() : path.resolve(cwd, m[1].trim());
219
- }
220
- }
221
- if (gitDir) {
222
- excludePath = path.join(gitDir, 'info', 'exclude');
223
- if (fs.existsSync(excludePath)) {
224
- const text = fs.readFileSync(excludePath, 'utf8');
225
- gitExcludeProtected = text.includes('.claude/settings.local.json');
226
- }
227
- }
228
- } catch (err) {
229
- void err; // ignore: unreadable git metadata leaves exclude status false
230
- }
231
- }
232
-
233
- return {
234
- settingsLocalPath,
235
- installed: preToolHook && postToolHook,
236
- preToolHook,
237
- postToolHook,
238
- postToolFailureHook,
239
- sessionStartHook,
240
- preCompactHook,
241
- excludePath,
242
- gitExcludeProtected
243
- };
244
- }
245
-
246
- function reapStaleCacheFiles(dirPath, cutoffMs, skipNames = new Set()) {
247
- let removedFiles = 0;
248
- let reclaimedBytes = 0;
249
- if (!dirPath || !fs.existsSync(dirPath)) {
250
- return { removedFiles, reclaimedBytes };
251
- }
252
- let entries = [];
253
- try {
254
- entries = fs.readdirSync(dirPath, { withFileTypes: true });
255
- } catch (err) {
256
- void err; // ignore: missing or unreadable cache directory
257
- return { removedFiles, reclaimedBytes };
258
- }
259
- for (const entry of entries) {
260
- if (!entry.isFile()) 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
- }
268
- const full = path.join(dirPath, entry.name);
269
- try {
270
- const st = fs.statSync(full);
271
- if (st.mtimeMs < cutoffMs) {
272
- fs.unlinkSync(full);
273
- removedFiles += 1;
274
- reclaimedBytes += st.size;
275
- }
276
- } catch (err) {
277
- void err; // ignore: file locked or concurrently removed
278
- }
279
- }
280
- return { removedFiles, reclaimedBytes };
281
- }
282
-
283
- /**
284
- * Runs local Burnoff diagnostics and optional `--gc` cache/FTS5/ledger maintenance.
285
- */
286
- export async function runDoctor(options = {}) {
287
- const cwd = path.resolve(options.cwd || process.cwd());
288
- const explicitHomeDir = typeof options.homeDir === 'string' && options.homeDir.trim()
289
- ? options.homeDir.trim()
290
- : null;
291
- const homeDir = explicitHomeDir || getHomeDir();
292
- const nodeVersion = options.nodeVersion || process.versions.node;
293
- const nowMs = Number(options.nowMs || Date.now());
294
- const maxCacheAgeDays = Math.max(1, Number(options.maxCacheAgeDays ?? 14));
295
-
296
- const nodeSupported = isSupportedNodeVersion(nodeVersion);
297
- const nativeSqlite = hasNativeNodeSqlite(nodeVersion);
298
- const policy = loadBurnoffPolicy(cwd);
299
- const hooks = inspectHookWiring(cwd);
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 });
304
- const atomicIo = getAtomicIoMetrics();
305
-
306
- let daemonPing = null;
307
- const ipcPath = resolveFastIpcPipePath({ cwd, homeDir: explicitHomeDir, ipcPath: options.ipcPath });
308
- if (!options.skipDaemonCheck) {
309
- daemonPing = await sendDaemonRpc(
310
- 'daemon.ping',
311
- {},
312
- { cwd, homeDir: explicitHomeDir, ipcPath: options.ipcPath, requestTimeoutMs: 80 }
313
- );
314
- }
315
-
316
- let gcResult = null;
317
- if (options.gc) {
318
- const retentionDays = Number(policy?.postTool?.retentionDays ?? 30);
319
- let fts5Pruned = { skipped: true, deletedRows: 0, vacuumed: false };
320
- if (fs.existsSync(fts5DbPath) || fs.existsSync(resolveFallbackDbPath(fts5DbPath))) {
321
- let db = null;
322
- try {
323
- db = openBurnoffDb(fts5DbPath, { readOnly: false });
324
- fts5Pruned = pruneExpiredFts5LogsSync(db, nowMs, retentionDays, { force: true });
325
- } finally {
326
- if (db) {
327
- try { db.close(); } catch (err) { void err; /* ignore: db close guard */ }
328
- }
329
- }
330
- }
331
- const cutoffMs = nowMs - maxCacheAgeDays * 24 * 60 * 60 * 1000;
332
- const homeCacheReaped = reapStaleCacheFiles(getBurnoffCacheDir(explicitHomeDir), cutoffMs);
333
- const wsCacheReaped = reapStaleCacheFiles(path.join(cwd, '.claude', 'cache'), cutoffMs);
334
- const wsArtifactsReaped = reapStaleCacheFiles(path.join(cwd, '.claude', 'cache', 'artifacts'), cutoffMs);
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 });
352
- gcResult = {
353
- performed: true,
354
- maxCacheAgeDays,
355
- fts5Pruned,
356
- reapedCacheFiles:
357
- homeCacheReaped.removedFiles + wsCacheReaped.removedFiles + wsArtifactsReaped.removedFiles + agStateRemoved,
358
- reclaimedBytes:
359
- homeCacheReaped.reclaimedBytes + wsCacheReaped.reclaimedBytes + wsArtifactsReaped.reclaimedBytes + agStateBytes,
360
- ledgerRotation
361
- };
362
- }
363
-
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');
371
-
372
- return {
373
- ok: nodeSupported,
374
- status,
375
- cwd,
376
- burnoffHome: getBurnoffHomeDir(explicitHomeDir),
377
- node: {
378
- version: nodeVersion,
379
- supported: nodeSupported,
380
- minVersion: MIN_NODE_VERSION,
381
- recommendedSqliteVersion: NATIVE_SQLITE_NODE_VERSION
382
- },
383
- sqlite: {
384
- nativeFts5: nativeSqlite,
385
- mode: nativeSqlite ? 'node:sqlite' : 'jsonl_fallback'
386
- },
387
- policy: {
388
- sourcePath: policy.sourcePath,
389
- exists: policy.exists,
390
- parseError: Boolean(policy.parseError),
391
- guardMode: policy.guards?.mode || 'guard',
392
- strictTestIntegrity: Boolean(policy.guards?.strictTestIntegrity),
393
- neverClampCodeOffCliff: Boolean(policy.readClamp?.neverClampCodeOffCliff)
394
- },
395
- hooks,
396
- antigravityHooks,
397
- daemon: {
398
- ipcPath,
399
- running: Boolean(daemonPing?.pong),
400
- pid: daemonPing?.pid || null,
401
- requestCount: daemonPing?.requestCount ?? 0
402
- },
403
- fts5: {
404
- dbPath: fts5DbPath,
405
- exists: fs.existsSync(fts5DbPath) || fs.existsSync(resolveFallbackDbPath(fts5DbPath)),
406
- ...fts5Stats
407
- },
408
- ledger: {
409
- avoidedWriteTokens: ledgerSummary.burnoffAvoidedWriteTokens,
410
- avoidedWriteUSD: ledgerSummary.burnoffAvoidedWriteUSD,
411
- platformCacheTokens: ledgerSummary.platformCacheDiscountTokens,
412
- platformCacheUSD: ledgerSummary.platformCacheDiscountUSD,
413
- realizedPromptBillUSD: ledgerSummary.realizedPromptBillUSD,
414
- entryCount: ledgerSummary.entryCount
415
- },
416
- atomicIo,
417
- gc: gcResult
418
- };
419
- }
420
-
421
- /**
422
- * Formats a `runDoctor()` report for terminal output.
423
- */
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
- : '';
438
- const lines = [
439
- `Burnoff Doctor: ${report.status || 'UNKNOWN'}`,
440
- ` Node.js : v${report.node?.version || 'unknown'} (${report.node?.supported ? 'supported' : `requires >=${report.node?.minVersion}`})`,
441
- ` SQLite FTS5 : ${report.sqlite?.mode || 'unknown'}`,
442
- ` Burnoff Home : ${report.burnoffHome || ''}`,
443
- ` Policy : ${report.policy?.exists ? report.policy.sourcePath : 'defaults (no .burnoff.yaml)'} [mode=${report.policy?.guardMode || 'guard'}]`,
444
- ` Claude Hooks : ${claudeLine} | git exclude=${report.hooks?.gitExcludeProtected ? 'yes' : 'no'}`,
445
- ` Antigravity : ${agBase}${agProbe}`,
446
- ` Warm Daemon : ${report.daemon?.running ? `running (pid=${report.daemon.pid})` : 'stopped (cold fallback active)'}`,
447
- ` FTS5 Archive : ${report.fts5?.logCount ?? 0} logs (~${report.fts5?.formattedSavedK || '0.0k'} tok compressed)`,
448
- ` Ledger : $${Number(report.ledger?.avoidedWriteUSD || 0).toFixed(4)} avoided | $${Number(report.ledger?.platformCacheUSD || 0).toFixed(4)} cache discount (${report.ledger?.entryCount ?? 0} receipts)`,
449
- ` Atomic I/O : ${report.atomicIo?.renameRetries ?? 0} rename retries, ${report.atomicIo?.renameExhausted ?? 0} exhausted`
450
- ];
451
- if (report.gc?.performed) {
452
- lines.push(
453
- ` 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`
454
- );
455
- }
456
- return lines.join('\n') + '\n';
457
- }
458
-
459
- export default {
460
- runDoctor,
461
- formatDoctorReport
462
- };
1
+ /**
2
+ * @file src/cli/doctor.mjs
3
+ * Burnoff local diagnostics & garbage collection (`burnoff doctor [--gc]`).
4
+ * Checks Node/SQLite support, `.burnoff.yaml` policy, `.claude/settings.local.json` hooks,
5
+ * warm daemon status, FTS5 archive health, ledger summary, and `atomic-io` retry metrics.
6
+ */
7
+
8
+ import fs from 'node:fs';
9
+ import path from 'node:path';
10
+ import { spawnSync } from 'node:child_process';
11
+ import {
12
+ MIN_NODE_VERSION,
13
+ NATIVE_SQLITE_NODE_VERSION,
14
+ isSupportedNodeVersion,
15
+ hasNativeNodeSqlite,
16
+ getHomeDir,
17
+ getBurnoffHomeDir,
18
+ getBurnoffCacheDir
19
+ } from '../config/paths.mjs';
20
+ import { loadBurnoffPolicy } from '../config/policy.mjs';
21
+ import { getAtomicIoMetrics } from '../storage/atomic-io.mjs';
22
+ import {
23
+ getDefaultToolLogsDbPath,
24
+ getFts5CompressionStats,
25
+ pruneExpiredFts5LogsSync
26
+ } from '../storage/fts5-archive.mjs';
27
+ import { getSavedQuotaReceiptSummary, rotateMonthlyLedger } from '../storage/ledger.mjs';
28
+ import { openBurnoffDb, resolveFallbackDbPath } from '../storage/sqlite-client.mjs';
29
+ import { sendDaemonRpc, resolveFastIpcPipePath } from '../ipc/fast-client.mjs';
30
+ import { resolvePostOutputMode } from '../guards/post-tool-engine.mjs';
31
+ import { hasQuotedAntigravityPath } from './init.mjs';
32
+ import { checkHookHealth, formatHookHealthLines } from './hook-health.mjs';
33
+
34
+ function extractAllCommands(groups) {
35
+ const cmds = [];
36
+ if (!Array.isArray(groups)) return cmds;
37
+ for (const g of groups) {
38
+ if (Array.isArray(g?.hooks)) {
39
+ for (const h of g.hooks) {
40
+ if (typeof h?.command === 'string' && h.command.trim()) {
41
+ cmds.push(h.command.trim());
42
+ }
43
+ }
44
+ } else if (typeof g?.command === 'string' && g.command.trim()) {
45
+ cmds.push(g.command.trim());
46
+ }
47
+ }
48
+ return cmds;
49
+ }
50
+
51
+ function probeAntigravityHookCommand(command, probeCwd, hookEventName = 'PreToolUse') {
52
+ if (!command) {
53
+ return {
54
+ checked: false,
55
+ ok: false,
56
+ hookEventName,
57
+ command: null,
58
+ decision: null,
59
+ exitCode: null,
60
+ error: 'missing command'
61
+ };
62
+ }
63
+ if (hasQuotedAntigravityPath(command)) {
64
+ return {
65
+ checked: true,
66
+ ok: false,
67
+ hookEventName,
68
+ command,
69
+ decision: null,
70
+ exitCode: null,
71
+ error: 'Quoted path in Antigravity hook command (Antigravity splits on whitespace without a shell)'
72
+ };
73
+ }
74
+ const tokens = String(command).trim().split(/\s+/).filter(Boolean);
75
+ if (tokens.length === 0) {
76
+ return {
77
+ checked: true,
78
+ ok: false,
79
+ hookEventName,
80
+ command,
81
+ decision: null,
82
+ exitCode: null,
83
+ error: 'empty hook command'
84
+ };
85
+ }
86
+ const run = spawnSync(tokens[0], tokens.slice(1), {
87
+ shell: false,
88
+ cwd: probeCwd,
89
+ input: '{}',
90
+ env: { ...process.env, BURNOFF_CLIENT: 'antigravity' },
91
+ encoding: 'utf8',
92
+ timeout: 4000,
93
+ windowsHide: true
94
+ });
95
+ if (run.error) {
96
+ return {
97
+ checked: true,
98
+ ok: false,
99
+ hookEventName,
100
+ command,
101
+ decision: null,
102
+ exitCode: run.status ?? null,
103
+ error: run.error.message || String(run.error)
104
+ };
105
+ }
106
+ const stdout = String(run.stdout || '').trim();
107
+ if (run.status !== 0) {
108
+ return {
109
+ checked: true,
110
+ ok: false,
111
+ hookEventName,
112
+ command,
113
+ decision: null,
114
+ exitCode: run.status,
115
+ error: String(run.stderr || stdout || `Exited with status ${run.status}`).trim()
116
+ };
117
+ }
118
+ try {
119
+ const parsed = JSON.parse(stdout);
120
+ if (hookEventName === 'PostToolUse') {
121
+ const ok = Boolean(parsed && typeof parsed === 'object' && !Array.isArray(parsed));
122
+ return {
123
+ checked: true,
124
+ ok,
125
+ hookEventName,
126
+ command,
127
+ decision: null,
128
+ exitCode: run.status,
129
+ error: ok ? null : 'Expected JSON object stdout for PostToolUse'
130
+ };
131
+ }
132
+ const ok = Boolean(parsed && typeof parsed === 'object' && typeof parsed.decision === 'string');
133
+ return {
134
+ checked: true,
135
+ ok,
136
+ hookEventName,
137
+ command,
138
+ decision: parsed?.decision || null,
139
+ exitCode: run.status,
140
+ error: ok ? null : 'Missing JSON decision field in stdout'
141
+ };
142
+ } catch (parseErr) {
143
+ return {
144
+ checked: true,
145
+ ok: false,
146
+ hookEventName,
147
+ command,
148
+ decision: null,
149
+ exitCode: run.status,
150
+ error: `Invalid JSON stdout: ${parseErr?.message || String(parseErr)}`
151
+ };
152
+ }
153
+ }
154
+
155
+ function inspectAntigravityHookWiring(cwd, homeDir = getHomeDir(), options = {}) {
156
+ const projectHooksPath = path.join(cwd, '.agents', 'hooks.json');
157
+ const globalHooksPath = path.join(homeDir, '.gemini', 'config', 'hooks.json');
158
+ const inspectFile = (filePath) => {
159
+ if (!filePath || !fs.existsSync(filePath)) {
160
+ return {
161
+ path: filePath,
162
+ installed: false,
163
+ preToolHook: false,
164
+ postToolHook: false,
165
+ enabled: false,
166
+ preCommand: null,
167
+ preCommands: [],
168
+ postCommands: []
169
+ };
170
+ }
171
+ try {
172
+ const parsed = JSON.parse(fs.readFileSync(filePath, 'utf8'));
173
+ const entry = parsed?.burnoff;
174
+ if (!entry || typeof entry !== 'object') {
175
+ return {
176
+ path: filePath,
177
+ installed: false,
178
+ preToolHook: false,
179
+ postToolHook: false,
180
+ enabled: false,
181
+ preCommand: null,
182
+ preCommands: [],
183
+ postCommands: []
184
+ };
185
+ }
186
+ const enabled = entry.enabled !== false;
187
+ const containsHook = (groups, targetName, shimToken) =>
188
+ Array.isArray(groups) &&
189
+ groups.some((g) => {
190
+ const checkCmd = (c) => {
191
+ const s = String(c || '');
192
+ return s.includes(targetName) || (s.includes('hook-shim.mjs') && s.includes(shimToken));
193
+ };
194
+ return Array.isArray(g?.hooks) ? g.hooks.some((h) => checkCmd(h?.command)) : checkCmd(g?.command);
195
+ });
196
+ const preToolHook = containsHook(entry.PreToolUse, 'pre-tool-use.mjs', ' pre');
197
+ const postToolHook = containsHook(entry.PostToolUse, 'post-tool-use.mjs', ' post');
198
+ const preCommands = extractAllCommands(entry.PreToolUse);
199
+ const postCommands = extractAllCommands(entry.PostToolUse);
200
+ return {
201
+ path: filePath,
202
+ installed: enabled && preToolHook && postToolHook,
203
+ enabled,
204
+ preToolHook,
205
+ postToolHook,
206
+ preCommand: preCommands[0] || null,
207
+ preCommands,
208
+ postCommands
209
+ };
210
+ } catch (err) {
211
+ void err; // ignore: malformed hooks.json reported as unwired
212
+ return {
213
+ path: filePath,
214
+ installed: false,
215
+ preToolHook: false,
216
+ postToolHook: false,
217
+ enabled: false,
218
+ preCommand: null,
219
+ preCommands: [],
220
+ postCommands: []
221
+ };
222
+ }
223
+ };
224
+
225
+ const project = inspectFile(projectHooksPath);
226
+ const global = inspectFile(globalHooksPath);
227
+ const installed = project.installed || global.installed;
228
+
229
+ let healthCheck = {
230
+ checked: false,
231
+ ok: false,
232
+ command: null,
233
+ decision: null,
234
+ exitCode: null,
235
+ error: null,
236
+ probes: []
237
+ };
238
+ if (installed && !options.skipAntigravityProbe) {
239
+ const active = project.installed ? project : global;
240
+ const probeCwd = path.dirname(active.path);
241
+ const probes = [
242
+ ...active.preCommands.map((cmd) => probeAntigravityHookCommand(cmd, probeCwd, 'PreToolUse')),
243
+ ...active.postCommands.map((cmd) => probeAntigravityHookCommand(cmd, probeCwd, 'PostToolUse'))
244
+ ];
245
+ if (probes.length === 0) {
246
+ healthCheck = {
247
+ checked: true,
248
+ ok: false,
249
+ command: null,
250
+ decision: null,
251
+ exitCode: null,
252
+ error: 'missing command',
253
+ probes: []
254
+ };
255
+ } else {
256
+ const firstFailed = probes.find((p) => !p.ok);
257
+ const firstPre = probes.find((p) => p.hookEventName === 'PreToolUse') || probes[0];
258
+ healthCheck = {
259
+ checked: true,
260
+ ok: !firstFailed,
261
+ command: (firstFailed || firstPre).command,
262
+ decision: firstPre?.decision || null,
263
+ exitCode: (firstFailed || firstPre).exitCode,
264
+ error: firstFailed ? firstFailed.error : null,
265
+ probes
266
+ };
267
+ }
268
+ }
269
+
270
+ return {
271
+ installed,
272
+ project,
273
+ global,
274
+ healthCheck
275
+ };
276
+ }
277
+
278
+ function inspectHookWiring(cwd) {
279
+ const settingsLocalPath = path.join(cwd, '.claude', 'settings.local.json');
280
+ let preToolHook = false;
281
+ let postToolHook = false;
282
+ let postToolFailureHook = false;
283
+ let sessionStartHook = false;
284
+ let preCompactHook = false;
285
+
286
+ if (fs.existsSync(settingsLocalPath)) {
287
+ try {
288
+ const parsed = JSON.parse(fs.readFileSync(settingsLocalPath, 'utf8'));
289
+ const hooks = parsed?.hooks || {};
290
+ const containsHook = (groups, targetName, shimToken) =>
291
+ Array.isArray(groups) &&
292
+ groups.some((g) => {
293
+ const checkCmd = (c) => {
294
+ const s = String(c || '');
295
+ return s.includes(targetName) || (s.includes('burnoff-hook-shim.mjs') && s.includes(shimToken));
296
+ };
297
+ return Array.isArray(g?.hooks) ? g.hooks.some((h) => checkCmd(h?.command)) : checkCmd(g?.command);
298
+ });
299
+ preToolHook = containsHook(hooks.PreToolUse, 'pre-tool-use.mjs', ' pre');
300
+ postToolHook = containsHook(hooks.PostToolUse, 'post-tool-use.mjs', ' post');
301
+ postToolFailureHook = containsHook(hooks.PostToolUseFailure, 'post-tool-use.mjs', ' post');
302
+ sessionStartHook = containsHook(hooks.SessionStart, 'session-lifecycle.mjs', ' session');
303
+ preCompactHook = containsHook(hooks.PreCompact, 'session-lifecycle.mjs', ' session');
304
+ } catch (err) {
305
+ void err; // ignore: malformed settings.local.json reported as unwired
306
+ }
307
+ }
308
+
309
+ let gitExcludeProtected = false;
310
+ const dotGit = path.join(cwd, '.git');
311
+ let excludePath = null;
312
+ if (fs.existsSync(dotGit)) {
313
+ try {
314
+ const st = fs.statSync(dotGit);
315
+ let gitDir = st.isDirectory() ? dotGit : null;
316
+ if (!gitDir && st.isFile()) {
317
+ const m = fs.readFileSync(dotGit, 'utf8').match(/^gitdir:\s*(.+)$/im);
318
+ if (m && m[1]) {
319
+ gitDir = path.isAbsolute(m[1].trim()) ? m[1].trim() : path.resolve(cwd, m[1].trim());
320
+ }
321
+ }
322
+ if (gitDir) {
323
+ excludePath = path.join(gitDir, 'info', 'exclude');
324
+ if (fs.existsSync(excludePath)) {
325
+ const text = fs.readFileSync(excludePath, 'utf8');
326
+ gitExcludeProtected = text.includes('.claude/settings.local.json');
327
+ }
328
+ }
329
+ } catch (err) {
330
+ void err; // ignore: unreadable git metadata leaves exclude status false
331
+ }
332
+ }
333
+
334
+ return {
335
+ settingsLocalPath,
336
+ installed: preToolHook && postToolHook,
337
+ preToolHook,
338
+ postToolHook,
339
+ postToolFailureHook,
340
+ sessionStartHook,
341
+ preCompactHook,
342
+ excludePath,
343
+ gitExcludeProtected
344
+ };
345
+ }
346
+
347
+ function reapStaleCacheFiles(dirPath, cutoffMs, skipNames = new Set()) {
348
+ let removedFiles = 0;
349
+ let reclaimedBytes = 0;
350
+ if (!dirPath || !fs.existsSync(dirPath)) {
351
+ return { removedFiles, reclaimedBytes };
352
+ }
353
+ let entries = [];
354
+ try {
355
+ entries = fs.readdirSync(dirPath, { withFileTypes: true });
356
+ } catch (err) {
357
+ void err; // ignore: missing or unreadable cache directory
358
+ return { removedFiles, reclaimedBytes };
359
+ }
360
+ for (const entry of entries) {
361
+ if (!entry.isFile()) continue;
362
+ if (
363
+ skipNames.has(entry.name) ||
364
+ entry.name.startsWith('tool_logs_fts5.db') ||
365
+ entry.name.startsWith('tool_logs_fallback.json')
366
+ ) {
367
+ continue;
368
+ }
369
+ const full = path.join(dirPath, entry.name);
370
+ try {
371
+ const st = fs.statSync(full);
372
+ if (st.mtimeMs < cutoffMs) {
373
+ fs.unlinkSync(full);
374
+ removedFiles += 1;
375
+ reclaimedBytes += st.size;
376
+ }
377
+ } catch (err) {
378
+ void err; // ignore: file locked or concurrently removed
379
+ }
380
+ }
381
+ return { removedFiles, reclaimedBytes };
382
+ }
383
+
384
+ /**
385
+ * Runs local Burnoff diagnostics and optional `--gc` cache/FTS5/ledger maintenance.
386
+ */
387
+ export async function runDoctor(options = {}) {
388
+ const cwd = path.resolve(options.cwd || process.cwd());
389
+ const explicitHomeDir = typeof options.homeDir === 'string' && options.homeDir.trim()
390
+ ? options.homeDir.trim()
391
+ : null;
392
+ const homeDir = explicitHomeDir || getHomeDir();
393
+ const nodeVersion = options.nodeVersion || process.versions.node;
394
+ const nowMs = Number(options.nowMs || Date.now());
395
+ const maxCacheAgeDays = Math.max(1, Number(options.maxCacheAgeDays ?? 14));
396
+
397
+ const nodeSupported = isSupportedNodeVersion(nodeVersion);
398
+ const nativeSqlite = hasNativeNodeSqlite(nodeVersion);
399
+ const policy = loadBurnoffPolicy(cwd);
400
+ const hooks = inspectHookWiring(cwd);
401
+ const antigravityHooks = inspectAntigravityHookWiring(cwd, homeDir, options);
402
+ const fts5DbPath = getDefaultToolLogsDbPath(explicitHomeDir);
403
+ const fts5Stats = getFts5CompressionStats(fts5DbPath, { homeDir: explicitHomeDir });
404
+ const ledgerSummary = getSavedQuotaReceiptSummary({ homeDir: explicitHomeDir, nowMs });
405
+ const atomicIo = getAtomicIoMetrics();
406
+ const hookHealth =
407
+ options.skipHookHealth === true
408
+ ? null
409
+ : checkHookHealth({
410
+ homeDir,
411
+ days: options.hookHealthDays ?? 7,
412
+ claudeProjectsDir: options.claudeProjectsDir ?? null,
413
+ conversationsDir: options.conversationsDir ?? null,
414
+ DatabaseSyncClass: options.DatabaseSyncClass
415
+ });
416
+
417
+ let daemonPing = null;
418
+ const ipcPath = resolveFastIpcPipePath({ cwd, homeDir: explicitHomeDir, ipcPath: options.ipcPath });
419
+ if (!options.skipDaemonCheck) {
420
+ daemonPing = await sendDaemonRpc(
421
+ 'daemon.ping',
422
+ {},
423
+ { cwd, homeDir: explicitHomeDir, ipcPath: options.ipcPath, requestTimeoutMs: 80 }
424
+ );
425
+ }
426
+
427
+ let gcResult = null;
428
+ if (options.gc) {
429
+ const retentionDays = Number(policy?.postTool?.retentionDays ?? 30);
430
+ let fts5Pruned = { skipped: true, deletedRows: 0, vacuumed: false };
431
+ if (fs.existsSync(fts5DbPath) || fs.existsSync(resolveFallbackDbPath(fts5DbPath))) {
432
+ let db = null;
433
+ try {
434
+ db = openBurnoffDb(fts5DbPath, { readOnly: false });
435
+ fts5Pruned = pruneExpiredFts5LogsSync(db, nowMs, retentionDays, { force: true });
436
+ } finally {
437
+ if (db) {
438
+ try { db.close(); } catch (err) { void err; /* ignore: db close guard */ }
439
+ }
440
+ }
441
+ }
442
+ const cutoffMs = nowMs - maxCacheAgeDays * 24 * 60 * 60 * 1000;
443
+ const homeCacheReaped = reapStaleCacheFiles(getBurnoffCacheDir(explicitHomeDir), cutoffMs);
444
+ const wsCacheReaped = reapStaleCacheFiles(path.join(cwd, '.claude', 'cache'), cutoffMs);
445
+ const wsArtifactsReaped = reapStaleCacheFiles(path.join(cwd, '.claude', 'cache', 'artifacts'), cutoffMs);
446
+ const stateRootDir = path.join(getBurnoffHomeDir(explicitHomeDir), 'state');
447
+ let agStateRemoved = 0;
448
+ let agStateBytes = 0;
449
+ if (fs.existsSync(stateRootDir)) {
450
+ try {
451
+ for (const ent of fs.readdirSync(stateRootDir, { withFileTypes: true })) {
452
+ if (ent.isDirectory()) {
453
+ const sub = reapStaleCacheFiles(path.join(stateRootDir, ent.name), cutoffMs);
454
+ agStateRemoved += sub.removedFiles;
455
+ agStateBytes += sub.reclaimedBytes;
456
+ }
457
+ }
458
+ } catch (err) {
459
+ void err; // ignore: unreadable state root during gc
460
+ }
461
+ }
462
+ const ledgerRotation = rotateMonthlyLedger({ homeDir: explicitHomeDir, nowMs });
463
+ gcResult = {
464
+ performed: true,
465
+ maxCacheAgeDays,
466
+ fts5Pruned,
467
+ reapedCacheFiles:
468
+ homeCacheReaped.removedFiles + wsCacheReaped.removedFiles + wsArtifactsReaped.removedFiles + agStateRemoved,
469
+ reclaimedBytes:
470
+ homeCacheReaped.reclaimedBytes + wsCacheReaped.reclaimedBytes + wsArtifactsReaped.reclaimedBytes + agStateBytes,
471
+ ledgerRotation
472
+ };
473
+ }
474
+
475
+ const anyHooksInstalled = hooks.installed || antigravityHooks.installed;
476
+ const hookHealthFailed = Boolean(
477
+ hookHealth &&
478
+ ((hookHealth.claudeCode?.errors || 0) > 0 || (hookHealth.antigravity?.failures || 0) > 0)
479
+ );
480
+ const hooksDegraded =
481
+ (hooks.installed && !hooks.postToolFailureHook) ||
482
+ (antigravityHooks.installed && antigravityHooks.healthCheck?.checked && !antigravityHooks.healthCheck.ok) ||
483
+ hookHealthFailed;
484
+ const status = !nodeSupported
485
+ ? 'ERROR'
486
+ : (!nativeSqlite || policy.parseError || !anyHooksInstalled || hooksDegraded ? 'WARN' : 'OK');
487
+
488
+ return {
489
+ ok: nodeSupported,
490
+ status,
491
+ cwd,
492
+ burnoffHome: getBurnoffHomeDir(explicitHomeDir),
493
+ node: {
494
+ version: nodeVersion,
495
+ supported: nodeSupported,
496
+ minVersion: MIN_NODE_VERSION,
497
+ recommendedSqliteVersion: NATIVE_SQLITE_NODE_VERSION
498
+ },
499
+ sqlite: {
500
+ nativeFts5: nativeSqlite,
501
+ mode: nativeSqlite ? 'node:sqlite' : 'jsonl_fallback'
502
+ },
503
+ policy: {
504
+ sourcePath: policy.sourcePath,
505
+ exists: policy.exists,
506
+ parseError: Boolean(policy.parseError),
507
+ guardMode: policy.guards?.mode || 'guard',
508
+ postOutputMode: resolvePostOutputMode(policy.postTool),
509
+ strictTestIntegrity: Boolean(policy.guards?.strictTestIntegrity),
510
+ neverClampCodeOffCliff: Boolean(policy.readClamp?.neverClampCodeOffCliff)
511
+ },
512
+ hooks,
513
+ antigravityHooks,
514
+ hookHealth,
515
+ daemon: {
516
+ ipcPath,
517
+ running: Boolean(daemonPing?.pong),
518
+ pid: daemonPing?.pid || null,
519
+ requestCount: daemonPing?.requestCount ?? 0
520
+ },
521
+ fts5: {
522
+ dbPath: fts5DbPath,
523
+ exists: fs.existsSync(fts5DbPath) || fs.existsSync(resolveFallbackDbPath(fts5DbPath)),
524
+ ...fts5Stats
525
+ },
526
+ ledger: {
527
+ avoidedWriteTokens: ledgerSummary.burnoffAvoidedWriteTokens,
528
+ avoidedWriteUSD: ledgerSummary.burnoffAvoidedWriteUSD,
529
+ platformCacheTokens: ledgerSummary.platformCacheDiscountTokens,
530
+ platformCacheUSD: ledgerSummary.platformCacheDiscountUSD,
531
+ realizedPromptBillUSD: ledgerSummary.realizedPromptBillUSD,
532
+ entryCount: ledgerSummary.entryCount
533
+ },
534
+ atomicIo,
535
+ gc: gcResult
536
+ };
537
+ }
538
+
539
+ /**
540
+ * Formats a `runDoctor()` report for terminal output.
541
+ */
542
+ export function formatDoctorReport(report = {}) {
543
+ const claudeLine = report.hooks?.installed
544
+ ? `installed (.claude/settings.local.json) [PostToolUseFailure=${report.hooks.postToolFailureHook ? 'ok' : 'missing'}]`
545
+ : 'not installed';
546
+ const agBase = report.antigravityHooks?.project?.installed
547
+ ? 'installed (.agents/hooks.json)'
548
+ : report.antigravityHooks?.global?.installed
549
+ ? 'installed (~/.gemini/config/hooks.json)'
550
+ : 'not installed';
551
+ const agProbe = report.antigravityHooks?.healthCheck?.checked
552
+ ? (report.antigravityHooks.healthCheck.ok
553
+ ? ' [probe=ok]'
554
+ : ` [probe=failed: ${report.antigravityHooks.healthCheck.error || 'error'}]`)
555
+ : '';
556
+ const lines = [
557
+ `Burnoff Doctor: ${report.status || 'UNKNOWN'}`,
558
+ ` Node.js : v${report.node?.version || 'unknown'} (${report.node?.supported ? 'supported' : `requires >=${report.node?.minVersion}`})`,
559
+ ` SQLite FTS5 : ${report.sqlite?.mode || 'unknown'}`,
560
+ ` Burnoff Home : ${report.burnoffHome || ''}`,
561
+ ` Policy : ${report.policy?.exists ? report.policy.sourcePath : 'defaults (no .burnoff.yaml)'} [mode=${report.policy?.guardMode || 'guard'}, postOutputMode=${report.policy?.postOutputMode || 'replace'}]`,
562
+ ` Claude Hooks : ${claudeLine} | git exclude=${report.hooks?.gitExcludeProtected ? 'yes' : 'no'}`,
563
+ ` Antigravity : ${agBase}${agProbe}`,
564
+ ` Warm Daemon : ${report.daemon?.running ? `running (pid=${report.daemon.pid})` : 'stopped (cold fallback active)'}`,
565
+ ` FTS5 Archive : ${report.fts5?.logCount ?? 0} logs (~${report.fts5?.formattedSavedK || '0.0k'} tok compressed)`,
566
+ ` Ledger : $${Number(report.ledger?.avoidedWriteUSD || 0).toFixed(4)} avoided | $${Number(report.ledger?.platformCacheUSD || 0).toFixed(4)} cache discount (${report.ledger?.entryCount ?? 0} receipts)`,
567
+ ` Atomic I/O : ${report.atomicIo?.renameRetries ?? 0} rename retries, ${report.atomicIo?.renameExhausted ?? 0} exhausted`
568
+ ];
569
+ if (report.gc?.performed) {
570
+ lines.push(
571
+ ` 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`
572
+ );
573
+ }
574
+ if (report.hookHealth) {
575
+ lines.push(...formatHookHealthLines(report.hookHealth));
576
+ }
577
+ return lines.join('\n') + '\n';
578
+ }
579
+
580
+ export default {
581
+ runDoctor,
582
+ formatDoctorReport
583
+ };