burnoff 1.4.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.
@@ -0,0 +1,429 @@
1
+ /**
2
+ * @file src/cli/hook-health.mjs
3
+ * Read-only 7-day Burnoff hook health audit across Claude Code transcript attachments,
4
+ * opt-in hook trace logs, and Antigravity conversation SQLite DBs (`burnoff doctor`).
5
+ */
6
+
7
+ import fs from 'node:fs';
8
+ import path from 'node:path';
9
+ import { getHomeDir, hasNativeNodeSqlite } from '../config/paths.mjs';
10
+ import { getDatabaseSyncClass } from '../storage/sqlite-client.mjs';
11
+
12
+ export const BURNOFF_COMMAND_RE =
13
+ /hooks[\\/](?:pre-tool-use|post-tool-use|session-lifecycle)\.mjs|burnoff-hook-shim\.mjs|hook-shim\.mjs|\bburnoff\b/i;
14
+
15
+ /**
16
+ * Returns true when a hook command or error string belongs to Burnoff.
17
+ */
18
+ export function isBurnoffHookCommand(command = '') {
19
+ return BURNOFF_COMMAND_RE.test(String(command || ''));
20
+ }
21
+
22
+ function readVarintNumber(buf, startOffset, endOffset) {
23
+ let result = 0;
24
+ let shift = 0;
25
+ let offset = startOffset;
26
+ while (offset < endOffset) {
27
+ const byte = buf[offset++];
28
+ if (shift < 49) {
29
+ result += (byte & 0x7f) * (2 ** shift);
30
+ }
31
+ if ((byte & 0x80) === 0) {
32
+ return { value: result, nextOffset: offset, ok: true };
33
+ }
34
+ shift += 7;
35
+ if (shift > 63) {
36
+ return { value: 0, nextOffset: endOffset, ok: false };
37
+ }
38
+ }
39
+ return { value: 0, nextOffset: endOffset, ok: false };
40
+ }
41
+
42
+ function extractProtobufFieldBytes(rawBlob, targetField = 2) {
43
+ if (!rawBlob) return null;
44
+ const buf = Buffer.isBuffer(rawBlob)
45
+ ? rawBlob
46
+ : rawBlob instanceof Uint8Array
47
+ ? Buffer.from(rawBlob.buffer, rawBlob.byteOffset, rawBlob.byteLength)
48
+ : null;
49
+ if (!buf || buf.length === 0) return null;
50
+
51
+ let offset = 0;
52
+ const endOffset = buf.length;
53
+ while (offset < endOffset) {
54
+ const tagRes = readVarintNumber(buf, offset, endOffset);
55
+ if (!tagRes.ok || tagRes.value <= 0) break;
56
+ offset = tagRes.nextOffset;
57
+ const fieldNumber = Math.floor(tagRes.value / 8);
58
+ const wireType = tagRes.value % 8;
59
+
60
+ if (wireType === 0) {
61
+ const valRes = readVarintNumber(buf, offset, endOffset);
62
+ if (!valRes.ok) break;
63
+ offset = valRes.nextOffset;
64
+ } else if (wireType === 1) {
65
+ offset += 8;
66
+ } else if (wireType === 2) {
67
+ const lenRes = readVarintNumber(buf, offset, endOffset);
68
+ if (!lenRes.ok) break;
69
+ const start = lenRes.nextOffset;
70
+ const stop = Math.min(endOffset, start + lenRes.value);
71
+ if (fieldNumber === targetField) {
72
+ return buf.subarray(start, stop);
73
+ }
74
+ offset = stop;
75
+ } else if (wireType === 5) {
76
+ offset += 4;
77
+ } else {
78
+ break;
79
+ }
80
+ }
81
+ return null;
82
+ }
83
+
84
+ /**
85
+ * Scans one Claude Code JSONL transcript's lines for Burnoff hook `attachment` entries.
86
+ */
87
+ export function scanClaudeTranscriptHooks(lines = []) {
88
+ const out = { runs: 0, errors: 0, byEvent: {}, errorSamples: [], durationsMs: [] };
89
+ for (const line of lines) {
90
+ if (!line || !line.includes('"attachment"')) continue;
91
+ let obj;
92
+ try {
93
+ obj = JSON.parse(line);
94
+ } catch {
95
+ continue; // ignore: skip malformed transcript JSONL line
96
+ }
97
+ const att = obj?.attachment;
98
+ if (obj?.type !== 'attachment' || !att || !String(att.type || '').startsWith('hook_')) {
99
+ continue;
100
+ }
101
+ if (att.type === 'hook_additional_context') continue;
102
+ if (!isBurnoffHookCommand(att.command)) continue;
103
+
104
+ out.runs += 1;
105
+ const ev = String(att.hookName || att.hookEvent || 'unknown');
106
+ out.byEvent[ev] = (out.byEvent[ev] || 0) + 1;
107
+ if (Number.isFinite(Number(att.durationMs))) {
108
+ out.durationsMs.push(Number(att.durationMs));
109
+ }
110
+ const failed =
111
+ att.type !== 'hook_success' ||
112
+ (att.exitCode !== undefined && Number(att.exitCode) !== 0);
113
+ if (failed) {
114
+ out.errors += 1;
115
+ if (out.errorSamples.length < 3) {
116
+ const snippet = String(att.stderr || att.content || att.type)
117
+ .replace(/\s+/g, ' ')
118
+ .slice(0, 160);
119
+ out.errorSamples.push(`${ev}: ${snippet}`);
120
+ }
121
+ }
122
+ }
123
+ return out;
124
+ }
125
+
126
+ /**
127
+ * Scans Burnoff opt-in hook trace JSONL lines for pass-through, active, and error invocations.
128
+ */
129
+ export function scanBurnoffHookTrace(lines = []) {
130
+ const out = { runs: 0, errors: 0, passThroughs: 0, active: 0, byEvent: {}, errorSamples: [] };
131
+ for (const line of lines) {
132
+ const trimmed = String(line || '').trim();
133
+ if (!trimmed) continue;
134
+ let rec;
135
+ try {
136
+ rec = JSON.parse(trimmed);
137
+ } catch {
138
+ continue; // ignore: skip malformed hook trace JSONL line
139
+ }
140
+ if (!rec || typeof rec !== 'object' || typeof rec.event !== 'string' || !rec.event.trim()) {
141
+ continue;
142
+ }
143
+ out.runs += 1;
144
+ const ev = rec.tool ? `${rec.event}:${rec.tool}` : String(rec.event);
145
+ out.byEvent[ev] = (out.byEvent[ev] || 0) + 1;
146
+ const outcome = String(rec.outcome || 'pass_through');
147
+ const code = rec.exitCode !== undefined ? Number(rec.exitCode) : 0;
148
+ const hasUnexpectedExitCode =
149
+ rec.exitCode !== undefined && Number.isFinite(code) && code !== 0 && code !== 2;
150
+
151
+ if (outcome === 'pass_through' && !hasUnexpectedExitCode) {
152
+ out.passThroughs += 1;
153
+ } else if (outcome === 'error' || hasUnexpectedExitCode) {
154
+ out.errors += 1;
155
+ if (out.errorSamples.length < 3) {
156
+ const msg = String(rec.error || (hasUnexpectedExitCode ? `exit_${code}` : 'hook_error')).slice(0, 160);
157
+ out.errorSamples.push(`${ev}: ${msg}`);
158
+ }
159
+ } else {
160
+ out.active += 1;
161
+ }
162
+ }
163
+ return out;
164
+ }
165
+
166
+ /**
167
+ * Merges transcript attachment hook stats with opt-in trace stats without double-counting.
168
+ */
169
+ export function mergeHookRunStats(transcriptStats, traceStats) {
170
+ if (!transcriptStats && !traceStats) return null;
171
+ const tBy = transcriptStats?.byEvent || {};
172
+ const trBy = traceStats?.byEvent || {};
173
+ const byEvent = {};
174
+ for (const k of new Set([...Object.keys(tBy), ...Object.keys(trBy)])) {
175
+ byEvent[k] = Math.max(Number(tBy[k] || 0), Number(trBy[k] || 0));
176
+ }
177
+ const transcriptRuns = Number(transcriptStats?.runs || 0);
178
+ const traceRuns = Number(traceStats?.runs || 0);
179
+ const byEventSum = Object.values(byEvent).reduce((a, b) => a + b, 0);
180
+ const runs = Math.max(transcriptRuns, traceRuns, byEventSum);
181
+ const errors = Math.max(Number(transcriptStats?.errors || 0), Number(traceStats?.errors || 0));
182
+ const errorSamples = [];
183
+ const seenErrs = new Set();
184
+ for (const s of [...(transcriptStats?.errorSamples || []), ...(traceStats?.errorSamples || [])]) {
185
+ if (errorSamples.length >= 3) break;
186
+ if (!seenErrs.has(s)) {
187
+ seenErrs.add(s);
188
+ errorSamples.push(s);
189
+ }
190
+ }
191
+ return {
192
+ runs,
193
+ errors,
194
+ byEvent,
195
+ errorSamples,
196
+ transcriptRuns,
197
+ traceRuns,
198
+ passThroughRuns: Number(traceStats?.passThroughs || 0)
199
+ };
200
+ }
201
+
202
+ function median(xs) {
203
+ if (!xs.length) return null;
204
+ const sorted = [...xs].sort((a, b) => a - b);
205
+ return sorted[Math.floor(sorted.length / 2)];
206
+ }
207
+
208
+ function listRecentFiles(dirs, ext, sinceMs, limit) {
209
+ const dirList = Array.isArray(dirs) ? dirs : [dirs];
210
+ const found = [];
211
+ const seen = new Set();
212
+ const walk = (d, depth) => {
213
+ if (!d || !fs.existsSync(d)) return;
214
+ let ents;
215
+ try {
216
+ ents = fs.readdirSync(d, { withFileTypes: true });
217
+ } catch {
218
+ return; // ignore: unreadable directory skipped
219
+ }
220
+ for (const e of ents) {
221
+ const full = path.resolve(d, e.name);
222
+ if (e.isDirectory() && depth < 2) {
223
+ walk(full, depth + 1);
224
+ } else if (e.isFile() && e.name.toLowerCase().endsWith(ext) && !seen.has(full)) {
225
+ seen.add(full);
226
+ try {
227
+ const m = fs.statSync(full).mtimeMs;
228
+ if (m >= sinceMs) found.push({ file: full, mtimeMs: m });
229
+ } catch {
230
+ // ignore: unreadable file stat skipped
231
+ }
232
+ }
233
+ }
234
+ };
235
+ for (const dir of dirList) {
236
+ walk(dir, 0);
237
+ }
238
+ return found.sort((a, b) => b.mtimeMs - a.mtimeMs).slice(0, limit);
239
+ }
240
+
241
+ /**
242
+ * Scans Antigravity conversation SQLite DBs strictly read-only for failed Burnoff hook executions.
243
+ */
244
+ export function scanAntigravityHookFailures({
245
+ dir = null,
246
+ dirs = null,
247
+ sinceMs = 0,
248
+ DatabaseSyncClass = null,
249
+ limit = 200
250
+ } = {}) {
251
+ const out = { databases: 0, failures: 0, errorSamples: [] };
252
+ const targetDirs = Array.isArray(dirs) ? dirs : dir ? [dir] : [];
253
+ if (!DatabaseSyncClass || targetDirs.length === 0) return out;
254
+
255
+ for (const { file } of listRecentFiles(targetDirs, '.db', sinceMs, limit)) {
256
+ let db = null;
257
+ try {
258
+ db = new DatabaseSyncClass(file, { readOnly: true });
259
+ out.databases += 1;
260
+ const rows = db.prepare('SELECT error_details FROM steps WHERE status = 7 AND error_details IS NOT NULL').all();
261
+ for (const row of rows) {
262
+ const fieldBytes = extractProtobufFieldBytes(row.error_details, 2);
263
+ const msg = fieldBytes
264
+ ? Buffer.from(fieldBytes).toString('utf8')
265
+ : typeof row.error_details === 'string'
266
+ ? row.error_details
267
+ : '';
268
+ if (!msg || !/hook/i.test(msg) || /denied by (?:a )?pre-tool hook/i.test(msg) || !isBurnoffHookCommand(msg)) {
269
+ continue;
270
+ }
271
+ out.failures += 1;
272
+ if (out.errorSamples.length < 3) {
273
+ out.errorSamples.push(msg.replace(/\s+/g, ' ').slice(0, 160));
274
+ }
275
+ }
276
+ } catch {
277
+ // ignore: locked, encrypted, or incompatible DB fails open
278
+ } finally {
279
+ try {
280
+ db?.close();
281
+ } catch {
282
+ // ignore: db close guard
283
+ }
284
+ }
285
+ }
286
+ return out;
287
+ }
288
+
289
+ /**
290
+ * Audits Burnoff hook execution health over the past `days` (default 7) across Claude Code and Antigravity.
291
+ */
292
+ export function checkHookHealth({
293
+ homeDir = getHomeDir(),
294
+ days = 7,
295
+ claudeProjectsDir = null,
296
+ conversationsDir = null,
297
+ DatabaseSyncClass = undefined,
298
+ maxTranscripts = 30
299
+ } = {}) {
300
+ const windowDays = Math.max(1, Number(days) || 7);
301
+ const sinceMs = Date.now() - windowDays * 86_400_000;
302
+ const ccDir = claudeProjectsDir || path.join(homeDir, '.claude', 'projects');
303
+ const files = fs.existsSync(ccDir) ? listRecentFiles(ccDir, '.jsonl', sinceMs, maxTranscripts) : [];
304
+ const cc = {
305
+ sessions: files.length,
306
+ sessionsWithBurnoff: 0,
307
+ runs: 0,
308
+ errors: 0,
309
+ byEvent: {},
310
+ errorSamples: [],
311
+ medianDurationMs: null,
312
+ postToolFailureSeen: false,
313
+ postToolFailureWarning: false
314
+ };
315
+ const durations = [];
316
+
317
+ for (const { file } of files) {
318
+ let lines;
319
+ try {
320
+ lines = fs.readFileSync(file, 'utf8').split(/\r?\n/);
321
+ } catch {
322
+ continue; // ignore: unreadable transcript skipped
323
+ }
324
+ const stats = scanClaudeTranscriptHooks(lines);
325
+ if (stats.runs > 0) cc.sessionsWithBurnoff += 1;
326
+ cc.runs += stats.runs;
327
+ cc.errors += stats.errors;
328
+ for (const [k, v] of Object.entries(stats.byEvent)) {
329
+ cc.byEvent[k] = (cc.byEvent[k] || 0) + v;
330
+ }
331
+ for (const errSample of stats.errorSamples) {
332
+ if (cc.errorSamples.length < 3) cc.errorSamples.push(errSample);
333
+ }
334
+ durations.push(...stats.durationsMs);
335
+ }
336
+ cc.medianDurationMs = median(durations);
337
+ cc.postToolFailureSeen = Boolean(
338
+ Object.entries(cc.byEvent).some(([k, count]) => /^PostToolUseFailure$/i.test(k) && count > 0)
339
+ );
340
+ cc.postToolFailureWarning = cc.runs > 0 && !cc.postToolFailureSeen;
341
+
342
+ const DbCtor =
343
+ DatabaseSyncClass === undefined
344
+ ? (hasNativeNodeSqlite() ? getDatabaseSyncClass() : null)
345
+ : DatabaseSyncClass;
346
+
347
+ const agDirs = conversationsDir
348
+ ? [conversationsDir]
349
+ : [
350
+ path.join(homeDir, '.gemini', 'antigravity', 'conversations'),
351
+ path.join(homeDir, '.gemini', 'antigravity-cli', 'conversations'),
352
+ path.join(homeDir, '.gemini', 'antigravity-ide', 'conversations')
353
+ ];
354
+ const ag = scanAntigravityHookFailures({
355
+ dirs: agDirs,
356
+ sinceMs,
357
+ DatabaseSyncClass: DbCtor
358
+ });
359
+
360
+ const statusFor = (sessions, ran, errors) =>
361
+ errors > 0 ? 'WARN' : ran > 0 ? 'OK' : sessions > 0 ? 'NOT_SEEN' : 'NO_DATA';
362
+
363
+ return {
364
+ days: windowDays,
365
+ claudeCode: {
366
+ ...cc,
367
+ status: statusFor(cc.sessions, cc.runs, cc.errors)
368
+ },
369
+ antigravity: {
370
+ ...ag,
371
+ status: ag.failures > 0 ? 'WARN' : ag.databases > 0 ? 'OK' : 'NO_DATA'
372
+ }
373
+ };
374
+ }
375
+
376
+ /**
377
+ * Formats 7-day hook health audit lines for `formatDoctorReport()`.
378
+ */
379
+ export function formatHookHealthLines(health) {
380
+ if (!health || typeof health !== 'object') return [];
381
+ const badge = (s) => (s === 'OK' ? 'PASS' : s === 'NO_DATA' ? 'INFO' : 'WARN');
382
+ const cc = health.claudeCode || {};
383
+ const ag = health.antigravity || {};
384
+ const lines = [];
385
+
386
+ const eventParts = Object.entries(cc.byEvent || {})
387
+ .filter(([, count]) => Number(count) > 0)
388
+ .map(([ev, count]) => `${ev}=${count}`);
389
+ const eventSuffix = eventParts.length > 0 ? ` [${eventParts.join(', ')}]` : '';
390
+
391
+ const ccDetail =
392
+ cc.status === 'NO_DATA'
393
+ ? `no Claude Code sessions in the last ${health.days}d`
394
+ : cc.status === 'NOT_SEEN'
395
+ ? `${cc.sessions} recent session(s), no Burnoff hook run recorded; run \`npx burnoff init --client claude\``
396
+ : `${cc.runs} hook run(s) in ${cc.sessionsWithBurnoff}/${cc.sessions} session(s), ${cc.errors} error(s)${cc.medianDurationMs !== null ? `, median ${cc.medianDurationMs} ms` : ''}${eventSuffix}`;
397
+ lines.push(` Hook Audit CC : [${badge(cc.status)}] ${ccDetail}`);
398
+
399
+ if (cc.postToolFailureWarning) {
400
+ lines.push(
401
+ ' - [WARN] PostToolUseFailure not seen in recent hook runs (verify PostToolUseFailure wiring)'
402
+ );
403
+ }
404
+ for (const sample of cc.errorSamples || []) {
405
+ lines.push(` - ${sample}`);
406
+ }
407
+
408
+ const agDetail =
409
+ ag.status === 'NO_DATA'
410
+ ? `no Antigravity conversations in the last ${health.days}d`
411
+ : `${ag.failures} Burnoff hook failure(s) in ${ag.databases} conversation(s)`;
412
+ lines.push(` Hook Audit AG : [${badge(ag.status)}] ${agDetail}`);
413
+ for (const sample of ag.errorSamples || []) {
414
+ lines.push(` - ${sample}`);
415
+ }
416
+
417
+ return lines;
418
+ }
419
+
420
+ export default {
421
+ BURNOFF_COMMAND_RE,
422
+ isBurnoffHookCommand,
423
+ scanClaudeTranscriptHooks,
424
+ scanBurnoffHookTrace,
425
+ mergeHookRunStats,
426
+ scanAntigravityHookFailures,
427
+ checkHookHealth,
428
+ formatHookHealthLines
429
+ };