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.
package/src/cli/init.mjs CHANGED
@@ -1,646 +1,668 @@
1
- /**
2
- * @file src/cli/init.mjs
3
- * Safe, idempotent Claude Code hook installer (`init` / `uninstall`).
4
- * Targets `.claude/settings.local.json` and `<gitDir>/info/exclude` exclusively
5
- * so `.claude/settings.json`, `.gitignore`, and `git status` stay spotless.
6
- */
7
-
8
- import fs from 'node:fs';
9
- import path from 'node:path';
10
- import { fileURLToPath } from 'node:url';
11
- import { getHomeDir } from '../config/paths.mjs';
12
- import { atomicWriteFileSync, atomicWriteJsonSync } from '../storage/atomic-io.mjs';
13
-
14
- const __dirname = path.dirname(fileURLToPath(import.meta.url));
15
- export const PACKAGE_ROOT = path.resolve(__dirname, '../..');
16
-
17
- export const PRE_TOOL_MATCHER =
18
- 'Bash|PowerShell|Edit|MultiEdit|Write|NotebookEdit|Read|Grep|Glob|Task|Agent|WebFetch|mcp__.*';
19
- export const POST_TOOL_MATCHER =
20
- 'Bash|PowerShell|Edit|MultiEdit|Write|NotebookEdit|Task|Agent|WebFetch|mcp__.*';
21
- export const SESSION_START_MATCHER = 'startup|resume|clear|compact';
22
- export const ANTIGRAVITY_PRE_TOOL_MATCHER =
23
- 'run_command|read_file|view_file|write_file|write_to_file|edit_file|replace_file_content|multi_replace_file_content|grep_search|find_by_name|list_dir|invoke_subagent|read_url_content|call_mcp_tool|mcp_.*';
24
- export const ANTIGRAVITY_POST_TOOL_MATCHER =
25
- 'run_command|read_file|view_file|write_file|write_to_file|edit_file|replace_file_content|multi_replace_file_content|grep_search|find_by_name|invoke_subagent|read_url_content|call_mcp_tool|mcp_.*';
26
-
27
- const EXCLUDE_START_MARKER = '# burnoff-managed:start';
28
- const EXCLUDE_END_MARKER = '# burnoff-managed:end';
29
- const CLAUDE_EXCLUDE_PATTERNS = Object.freeze([
30
- '.claude/settings.local.json',
31
- '.claude/burnoff-hook-shim.mjs',
32
- '.claude/cache/',
33
- '.claude/locks/',
34
- '.burnoff/'
35
- ]);
36
- const ANTIGRAVITY_EXCLUDE_PATTERNS = Object.freeze([
37
- '.burnoff/'
38
- ]);
39
-
40
- export function isEphemeralNpxPath(pkgRoot = PACKAGE_ROOT) {
41
- const norm = String(pkgRoot || '').replace(/\\/g, '/');
42
- return /(?:^|\/)_npx(?:\/|$)|(?:^|\/)npm-cache\/_npx(?:\/|$)/i.test(norm);
43
- }
44
-
45
- function normalizeCommandPath(filePath) {
46
- return path.resolve(filePath).replace(/\\/g, '/');
47
- }
48
-
49
- function isBurnoffCommand(command = '') {
50
- const cmd = String(command || '').replace(/\\/g, '/');
51
- if (!cmd) return false;
52
- if (/\.claude\/burnoff-hook-shim\.mjs/i.test(cmd)) return true;
53
- return (
54
- /(?:^|[/"'\s])hooks\/(?:(?:pre|post)-tool-use|session-lifecycle)\.mjs(?:["'\s]|$)/i.test(cmd) &&
55
- (/burnoff/i.test(cmd) ||
56
- cmd.includes(normalizeCommandPath(path.join(PACKAGE_ROOT, 'hooks'))))
57
- );
58
- }
59
-
60
- function resolveGitDir(cwd) {
61
- const repoDir = path.resolve(cwd || process.cwd());
62
- const dotGit = path.join(repoDir, '.git');
63
- if (!fs.existsSync(dotGit)) return null;
64
- try {
65
- const stat = fs.statSync(dotGit);
66
- if (stat.isDirectory()) return dotGit;
67
- if (stat.isFile()) {
68
- const content = fs.readFileSync(dotGit, 'utf8');
69
- const m = content.match(/^gitdir:\s*(.+)$/im);
70
- if (m && m[1]) {
71
- const target = m[1].trim();
72
- return path.isAbsolute(target) ? target : path.resolve(repoDir, target);
73
- }
74
- }
75
- } catch (err) {
76
- void err; // ignore: unreadable .git metadata skips info/exclude management
77
- }
78
- return null;
79
- }
80
-
81
- function buildExcludeBlock(patterns = CLAUDE_EXCLUDE_PATTERNS) {
82
- return [EXCLUDE_START_MARKER, ...patterns, EXCLUDE_END_MARKER].join('\n');
83
- }
84
-
85
- function upsertExcludeBlock(existingContent = '', patterns = CLAUDE_EXCLUDE_PATTERNS) {
86
- const block = buildExcludeBlock(patterns);
87
- const blockRe = new RegExp(
88
- `${EXCLUDE_START_MARKER}[\\s\\S]*?${EXCLUDE_END_MARKER}\\r?\\n?`,
89
- 'g'
90
- );
91
- const stripped = String(existingContent || '').replace(blockRe, '').replace(/\s+$/, '');
92
- if (!stripped) return `${block}\n`;
93
- return `${stripped}\n\n${block}\n`;
94
- }
95
-
96
- function removeExcludeBlock(existingContent = '') {
97
- const blockRe = new RegExp(
98
- `(?:\\r?\\n)*${EXCLUDE_START_MARKER}[\\s\\S]*?${EXCLUDE_END_MARKER}\\r?\\n?`,
99
- 'g'
100
- );
101
- const next = String(existingContent || '').replace(blockRe, '').replace(/\s+$/, '');
102
- return next ? `${next}\n` : '';
103
- }
104
-
105
- function filterOutBurnoffMatcherGroups(groups) {
106
- if (!Array.isArray(groups)) return [];
107
- const kept = [];
108
- for (const group of groups) {
109
- if (!group || typeof group !== 'object') continue;
110
- if (!Array.isArray(group.hooks)) {
111
- if (!isBurnoffCommand(group.command)) kept.push(group);
112
- continue;
113
- }
114
- const remainingHooks = group.hooks.filter((h) => !isBurnoffCommand(h?.command));
115
- if (remainingHooks.length > 0) {
116
- kept.push({ ...group, hooks: remainingHooks });
117
- }
118
- }
119
- return kept;
120
- }
121
-
122
- function readJsonObjectSafe(filePath) {
123
- if (!fs.existsSync(filePath)) return {};
124
- try {
125
- const parsed = JSON.parse(fs.readFileSync(filePath, 'utf8'));
126
- if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
127
- return parsed;
128
- }
129
- } catch (err) {
130
- void err; // ignore: malformed settings.local.json replaced cleanly
131
- }
132
- return {};
133
- }
134
-
135
- function buildHookShimSource(fallbackPackageRoot) {
136
- const fallback = normalizeCommandPath(fallbackPackageRoot);
137
- return `import fs from 'node:fs';
138
- import path from 'node:path';
139
- import { createRequire } from 'node:module';
140
- import { fileURLToPath, pathToFileURL } from 'node:url';
141
-
142
- const hookArgMap = {
143
- post: 'post-tool-use.mjs',
144
- session: 'session-lifecycle.mjs',
145
- pre: 'pre-tool-use.mjs'
146
- };
147
- const hookArg = hookArgMap[process.argv[2]] || 'pre-tool-use.mjs';
148
- const cwd = process.cwd();
149
- const parentDir = path.dirname(cwd);
150
- const shimDir = path.dirname(fileURLToPath(import.meta.url));
151
- const candidates = [
152
- path.join(cwd, 'node_modules', 'burnoff', 'hooks', hookArg),
153
- path.join(parentDir, 'node_modules', 'burnoff', 'hooks', hookArg),
154
- path.join(shimDir, '..', 'node_modules', 'burnoff', 'hooks', hookArg)
155
- ];
156
-
157
- for (const baseDir of [cwd, parentDir, path.join(shimDir, '..')]) {
158
- try {
159
- const req = createRequire(path.join(baseDir, 'package.json'));
160
- const pkgPath = req.resolve('burnoff/package.json');
161
- candidates.push(path.join(path.dirname(pkgPath), 'hooks', hookArg));
162
- } catch {
163
- // ignore: local/global resolution miss falls back to bundled path
164
- }
165
- }
166
-
167
- candidates.push(path.join(${JSON.stringify(fallback)}, 'hooks', hookArg));
168
-
169
- const resolved = candidates.find((p) => {
170
- try {
171
- return fs.existsSync(p);
172
- } catch {
173
- return false;
174
- }
175
- });
176
-
177
- if (!resolved) {
178
- process.stderr.write(
179
- '[burnoff] Hook target missing (ephemeral npx cache cleared). Install persistently: npm i -D burnoff or npm i -g burnoff.\\n'
180
- );
181
- process.exit(0);
182
- }
183
-
184
- await import(pathToFileURL(resolved).href);
185
- `;
186
- }
187
-
188
- /**
189
- * Builds Claude Code `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `SessionStart`,
190
- * and `PreCompact` hook definitions pointing to Burnoff's fast-shell hooks.
191
- */
192
- export function buildClaudeHooksConfig(options = {}) {
193
- const root = path.resolve(options.packageRoot || PACKAGE_ROOT);
194
- const preCmd = options.shimPath
195
- ? `node "${normalizeCommandPath(options.shimPath)}" pre`
196
- : `node "${normalizeCommandPath(path.join(root, 'hooks', 'pre-tool-use.mjs'))}"`;
197
- const postCmd = options.shimPath
198
- ? `node "${normalizeCommandPath(options.shimPath)}" post`
199
- : `node "${normalizeCommandPath(path.join(root, 'hooks', 'post-tool-use.mjs'))}"`;
200
- const sessionCmd = options.shimPath
201
- ? `node "${normalizeCommandPath(options.shimPath)}" session`
202
- : `node "${normalizeCommandPath(path.join(root, 'hooks', 'session-lifecycle.mjs'))}"`;
203
- const timeout = Number.isFinite(Number(options.timeout)) ? Number(options.timeout) : 5;
204
-
205
- return {
206
- PreToolUse: [
207
- {
208
- matcher: options.preMatcher || PRE_TOOL_MATCHER,
209
- hooks: [
210
- {
211
- type: 'command',
212
- command: preCmd,
213
- timeout
214
- }
215
- ]
216
- }
217
- ],
218
- PostToolUse: [
219
- {
220
- matcher: options.postMatcher || POST_TOOL_MATCHER,
221
- hooks: [
222
- {
223
- type: 'command',
224
- command: postCmd,
225
- timeout
226
- }
227
- ]
228
- }
229
- ],
230
- PostToolUseFailure: [
231
- {
232
- matcher: options.postMatcher || POST_TOOL_MATCHER,
233
- hooks: [
234
- {
235
- type: 'command',
236
- command: postCmd,
237
- timeout
238
- }
239
- ]
240
- }
241
- ],
242
- SessionStart: [
243
- {
244
- matcher: options.sessionStartMatcher || SESSION_START_MATCHER,
245
- hooks: [
246
- {
247
- type: 'command',
248
- command: sessionCmd,
249
- timeout
250
- }
251
- ]
252
- }
253
- ],
254
- PreCompact: [
255
- {
256
- hooks: [
257
- {
258
- type: 'command',
259
- command: sessionCmd,
260
- timeout
261
- }
262
- ]
263
- }
264
- ]
265
- };
266
- }
267
-
268
- function resolveAntigravityHookCommand(hookFileName, shimArg, options = {}) {
269
- const root = path.resolve(options.packageRoot || PACKAGE_ROOT);
270
-
271
- if (options.shimPath) {
272
- const shimAbs = path.resolve(options.shimPath);
273
- return `node "${normalizeCommandPath(shimAbs)}" ${shimArg}`;
274
- }
275
-
276
- return `node "${normalizeCommandPath(path.join(root, 'hooks', hookFileName))}"`;
277
- }
278
-
279
- /**
280
- * Builds Google Antigravity `hooks.json` `"burnoff"` entry supporting both Antigravity 2.0 and IDE v1.
281
- */
282
- export function buildAntigravityHooksConfig(options = {}) {
283
- const preCmd = resolveAntigravityHookCommand('pre-tool-use.mjs', 'pre', options);
284
- const postCmd = resolveAntigravityHookCommand('post-tool-use.mjs', 'post', options);
285
- const timeout = Number.isFinite(Number(options.timeout)) ? Number(options.timeout) : 5;
286
-
287
- return {
288
- enabled: true,
289
- PreToolUse: [
290
- {
291
- matcher: options.preMatcher || ANTIGRAVITY_PRE_TOOL_MATCHER,
292
- hooks: [
293
- {
294
- type: 'command',
295
- command: preCmd,
296
- timeout
297
- }
298
- ]
299
- }
300
- ],
301
- PostToolUse: [
302
- {
303
- matcher: options.postMatcher || ANTIGRAVITY_POST_TOOL_MATCHER,
304
- hooks: [
305
- {
306
- type: 'command',
307
- command: postCmd,
308
- timeout
309
- }
310
- ]
311
- }
312
- ]
313
- };
314
- }
315
-
316
- export function resolveInitClients(clientOpt = 'claude', { cwd = process.cwd(), homeDir = getHomeDir() } = {}) {
317
- const raw = String(clientOpt || 'claude').trim().toLowerCase();
318
- if (raw === 'antigravity' || raw === 'ag') return ['antigravity'];
319
- if (raw === 'both' || raw === 'all') return ['claude', 'antigravity'];
320
- if (raw === 'auto') {
321
- const detected = [];
322
- if (fs.existsSync(path.join(cwd, '.claude'))) detected.push('claude');
323
- if (
324
- fs.existsSync(path.join(cwd, '.agents')) ||
325
- fs.existsSync(path.join(homeDir, '.gemini', 'config'))
326
- ) {
327
- detected.push('antigravity');
328
- }
329
- return detected.length > 0 ? detected : ['claude'];
330
- }
331
- return ['claude'];
332
- }
333
-
334
- /**
335
- * Installs Burnoff hooks for Claude Code (`.claude/settings.local.json`) and/or
336
- * Google Antigravity (`.agents/hooks.json` or `--global` `~/.gemini/config/hooks.json`).
337
- */
338
- export function initBurnoff(options = {}) {
339
- const cwd = path.resolve(options.cwd || process.cwd());
340
- const homeDir = options.homeDir || getHomeDir();
341
- const dryRun = Boolean(options.dryRun);
342
- const isGlobal = Boolean(options.global);
343
- const pkgRoot = path.resolve(options.packageRoot || PACKAGE_ROOT);
344
- const ephemeralNpx = isEphemeralNpxPath(pkgRoot);
345
- const useShim = Boolean(options.useShim || ephemeralNpx);
346
- const clients = resolveInitClients(options.client || 'claude', { cwd, homeDir });
347
- const installClaude = clients.includes('claude');
348
- const installAntigravity = clients.includes('antigravity');
349
-
350
- const warnings = [];
351
- const shimPath = installClaude && useShim ? path.join(cwd, '.claude', 'burnoff-hook-shim.mjs') : null;
352
- const agShimPath =
353
- installAntigravity && useShim
354
- ? (shimPath || path.join(cwd, '.burnoff', 'hook-shim.mjs'))
355
- : null;
356
-
357
- if (ephemeralNpx) {
358
- warnings.push(
359
- `Ephemeral npx cache path detected; wrote ${agShimPath && !shimPath ? '.burnoff/hook-shim.mjs' : '.claude/burnoff-hook-shim.mjs'}. Install persistently with "npm i -D burnoff" or "npm i -g burnoff".`
360
- );
361
- }
362
-
363
- let settingsPath = path.join(cwd, '.claude', 'settings.local.json');
364
- let hooks = null;
365
- if (installClaude) {
366
- hooks = buildClaudeHooksConfig({
367
- ...options,
368
- packageRoot: pkgRoot,
369
- ...(shimPath ? { shimPath } : {})
370
- });
371
-
372
- const current = readJsonObjectSafe(settingsPath);
373
- const existingHooks =
374
- current.hooks && typeof current.hooks === 'object' && !Array.isArray(current.hooks)
375
- ? { ...current.hooks }
376
- : {};
377
-
378
- const prevPre = filterOutBurnoffMatcherGroups(existingHooks.PreToolUse);
379
- const prevPost = filterOutBurnoffMatcherGroups(existingHooks.PostToolUse);
380
- const prevPostFail = filterOutBurnoffMatcherGroups(existingHooks.PostToolUseFailure);
381
- const prevSessionStart = filterOutBurnoffMatcherGroups(existingHooks.SessionStart);
382
- const prevPreCompact = filterOutBurnoffMatcherGroups(existingHooks.PreCompact);
383
-
384
- const nextSettings = {
385
- ...current,
386
- hooks: {
387
- ...existingHooks,
388
- PreToolUse: [...prevPre, ...hooks.PreToolUse],
389
- PostToolUse: [...prevPost, ...hooks.PostToolUse],
390
- PostToolUseFailure: [...prevPostFail, ...hooks.PostToolUseFailure],
391
- SessionStart: [...prevSessionStart, ...hooks.SessionStart],
392
- PreCompact: [...prevPreCompact, ...hooks.PreCompact]
393
- }
394
- };
395
-
396
- if (!dryRun) {
397
- if (shimPath) {
398
- atomicWriteFileSync(shimPath, buildHookShimSource(pkgRoot), { encoding: 'utf8' });
399
- }
400
- atomicWriteJsonSync(settingsPath, nextSettings);
401
- }
402
- }
403
-
404
- let antigravityHooksPath = null;
405
- let antigravityHooks = null;
406
- if (installAntigravity) {
407
- antigravityHooksPath = isGlobal
408
- ? path.join(homeDir, '.gemini', 'config', 'hooks.json')
409
- : path.join(cwd, '.agents', 'hooks.json');
410
- antigravityHooks = buildAntigravityHooksConfig({
411
- ...options,
412
- cwd,
413
- global: isGlobal,
414
- packageRoot: pkgRoot,
415
- ...(agShimPath ? { shimPath: agShimPath } : {})
416
- });
417
-
418
- const currentAg = readJsonObjectSafe(antigravityHooksPath);
419
- const nextAg = {
420
- ...currentAg,
421
- burnoff: antigravityHooks
422
- };
423
-
424
- if (!dryRun) {
425
- if (agShimPath && agShimPath !== shimPath) {
426
- atomicWriteFileSync(agShimPath, buildHookShimSource(pkgRoot), { encoding: 'utf8' });
427
- }
428
- atomicWriteJsonSync(antigravityHooksPath, nextAg);
429
- }
430
- }
431
-
432
- let excludePath = null;
433
- let excludeUpdated = false;
434
- const gitDir = !isGlobal || installClaude ? resolveGitDir(cwd) : null;
435
- if (gitDir) {
436
- excludePath = path.join(gitDir, 'info', 'exclude');
437
- const prevExclude = fs.existsSync(excludePath) ? fs.readFileSync(excludePath, 'utf8') : '';
438
- const patterns = installClaude ? CLAUDE_EXCLUDE_PATTERNS : ANTIGRAVITY_EXCLUDE_PATTERNS;
439
- const nextExclude = upsertExcludeBlock(prevExclude, patterns);
440
- if (nextExclude !== prevExclude) {
441
- excludeUpdated = true;
442
- if (!dryRun) {
443
- atomicWriteFileSync(excludePath, nextExclude, { encoding: 'utf8' });
444
- }
445
- }
446
- }
447
-
448
- return {
449
- ok: true,
450
- dryRun,
451
- cwd,
452
- clients,
453
- global: isGlobal,
454
- settingsPath,
455
- antigravityHooksPath,
456
- shimPath: shimPath || agShimPath,
457
- ephemeralNpx,
458
- warnings,
459
- excludePath,
460
- excludeUpdated,
461
- hooks,
462
- antigravityHooks
463
- };
464
- }
465
-
466
- /**
467
- * Removes Burnoff hooks for Claude Code and/or Google Antigravity and cleans `<gitDir>/info/exclude`.
468
- */
469
- export function uninstallBurnoff(options = {}) {
470
- const cwd = path.resolve(options.cwd || process.cwd());
471
- const homeDir = options.homeDir || getHomeDir();
472
- const dryRun = Boolean(options.dryRun);
473
- const isGlobal = Boolean(options.global);
474
- const clients = options.client
475
- ? resolveInitClients(options.client, { cwd, homeDir })
476
- : ['claude', 'antigravity'];
477
- const uninstallClaude = clients.includes('claude');
478
- const uninstallAntigravity = clients.includes('antigravity');
479
-
480
- const settingsPath = path.join(cwd, '.claude', 'settings.local.json');
481
- let removedSettings = false;
482
- let updatedSettings = false;
483
-
484
- if (uninstallClaude) {
485
- const shimPath = path.join(cwd, '.claude', 'burnoff-hook-shim.mjs');
486
- if (fs.existsSync(shimPath) && !dryRun) {
487
- try {
488
- fs.unlinkSync(shimPath);
489
- } catch (err) {
490
- void err; // ignore: shim unlink best-effort
491
- }
492
- }
493
-
494
- if (fs.existsSync(settingsPath)) {
495
- const current = readJsonObjectSafe(settingsPath);
496
- const nextHooks =
497
- current.hooks && typeof current.hooks === 'object' && !Array.isArray(current.hooks)
498
- ? { ...current.hooks }
499
- : {};
500
-
501
- if (nextHooks.PreToolUse) {
502
- const keptPre = filterOutBurnoffMatcherGroups(nextHooks.PreToolUse);
503
- if (keptPre.length > 0) nextHooks.PreToolUse = keptPre;
504
- else delete nextHooks.PreToolUse;
505
- }
506
- if (nextHooks.PostToolUse) {
507
- const keptPost = filterOutBurnoffMatcherGroups(nextHooks.PostToolUse);
508
- if (keptPost.length > 0) nextHooks.PostToolUse = keptPost;
509
- else delete nextHooks.PostToolUse;
510
- }
511
- if (nextHooks.PostToolUseFailure) {
512
- const keptPostFail = filterOutBurnoffMatcherGroups(nextHooks.PostToolUseFailure);
513
- if (keptPostFail.length > 0) nextHooks.PostToolUseFailure = keptPostFail;
514
- else delete nextHooks.PostToolUseFailure;
515
- }
516
- if (nextHooks.SessionStart) {
517
- const keptSessionStart = filterOutBurnoffMatcherGroups(nextHooks.SessionStart);
518
- if (keptSessionStart.length > 0) nextHooks.SessionStart = keptSessionStart;
519
- else delete nextHooks.SessionStart;
520
- }
521
- if (nextHooks.PreCompact) {
522
- const keptPreCompact = filterOutBurnoffMatcherGroups(nextHooks.PreCompact);
523
- if (keptPreCompact.length > 0) nextHooks.PreCompact = keptPreCompact;
524
- else delete nextHooks.PreCompact;
525
- }
526
-
527
- const nextSettings = { ...current };
528
- if (Object.keys(nextHooks).length > 0) {
529
- nextSettings.hooks = nextHooks;
530
- } else {
531
- delete nextSettings.hooks;
532
- }
533
-
534
- if (Object.keys(nextSettings).length === 0) {
535
- removedSettings = true;
536
- if (!dryRun) {
537
- fs.unlinkSync(settingsPath);
538
- const claudeDir = path.dirname(settingsPath);
539
- try {
540
- if (fs.existsSync(claudeDir) && fs.readdirSync(claudeDir).length === 0) {
541
- fs.rmdirSync(claudeDir);
542
- }
543
- } catch (err) {
544
- void err; // ignore: non-empty or locked .claude directory left intact
545
- }
546
- }
547
- } else {
548
- updatedSettings = true;
549
- if (!dryRun) {
550
- atomicWriteJsonSync(settingsPath, nextSettings);
551
- }
552
- }
553
- }
554
- }
555
-
556
- const antigravityHooksPath = isGlobal
557
- ? path.join(homeDir, '.gemini', 'config', 'hooks.json')
558
- : path.join(cwd, '.agents', 'hooks.json');
559
- let removedAntigravityHooks = false;
560
- let updatedAntigravityHooks = false;
561
-
562
- if (uninstallAntigravity) {
563
- const agShimPath = path.join(cwd, '.burnoff', 'hook-shim.mjs');
564
- if (fs.existsSync(agShimPath) && !dryRun) {
565
- try {
566
- fs.unlinkSync(agShimPath);
567
- } catch (err) {
568
- void err; // ignore: Antigravity shim unlink best-effort
569
- }
570
- }
571
-
572
- if (fs.existsSync(antigravityHooksPath)) {
573
- const currentAg = readJsonObjectSafe(antigravityHooksPath);
574
- if (Object.prototype.hasOwnProperty.call(currentAg, 'burnoff')) {
575
- const nextAg = { ...currentAg };
576
- delete nextAg.burnoff;
577
- if (Object.keys(nextAg).length === 0) {
578
- removedAntigravityHooks = true;
579
- if (!dryRun) {
580
- fs.unlinkSync(antigravityHooksPath);
581
- const agDir = path.dirname(antigravityHooksPath);
582
- try {
583
- if (!isGlobal && fs.existsSync(agDir) && fs.readdirSync(agDir).length === 0) {
584
- fs.rmdirSync(agDir);
585
- }
586
- } catch (err) {
587
- void err; // ignore: non-empty or locked .agents directory left intact
588
- }
589
- }
590
- } else {
591
- updatedAntigravityHooks = true;
592
- if (!dryRun) {
593
- atomicWriteJsonSync(antigravityHooksPath, nextAg);
594
- }
595
- }
596
- }
597
- }
598
- }
599
-
600
- let excludePath = null;
601
- let excludeUpdated = false;
602
- const gitDir = resolveGitDir(cwd);
603
- if (gitDir) {
604
- excludePath = path.join(gitDir, 'info', 'exclude');
605
- if (fs.existsSync(excludePath)) {
606
- const prevExclude = fs.readFileSync(excludePath, 'utf8');
607
- const nextExclude = removeExcludeBlock(prevExclude);
608
- if (nextExclude !== prevExclude) {
609
- excludeUpdated = true;
610
- if (!dryRun) {
611
- atomicWriteFileSync(excludePath, nextExclude, { encoding: 'utf8' });
612
- }
613
- }
614
- }
615
- }
616
-
617
- return {
618
- ok: true,
619
- dryRun,
620
- cwd,
621
- clients,
622
- global: isGlobal,
623
- settingsPath,
624
- removedSettings,
625
- updatedSettings,
626
- antigravityHooksPath,
627
- removedAntigravityHooks,
628
- updatedAntigravityHooks,
629
- excludePath,
630
- excludeUpdated
631
- };
632
- }
633
-
634
- export default {
635
- PACKAGE_ROOT,
636
- PRE_TOOL_MATCHER,
637
- POST_TOOL_MATCHER,
638
- SESSION_START_MATCHER,
639
- ANTIGRAVITY_PRE_TOOL_MATCHER,
640
- ANTIGRAVITY_POST_TOOL_MATCHER,
641
- buildClaudeHooksConfig,
642
- buildAntigravityHooksConfig,
643
- resolveInitClients,
644
- initBurnoff,
645
- uninstallBurnoff
646
- };
1
+ /**
2
+ * @file src/cli/init.mjs
3
+ * Safe, idempotent Claude Code hook installer (`init` / `uninstall`).
4
+ * Targets `.claude/settings.local.json` and `<gitDir>/info/exclude` exclusively
5
+ * so `.claude/settings.json`, `.gitignore`, and `git status` stay spotless.
6
+ */
7
+
8
+ import fs from 'node:fs';
9
+ import path from 'node:path';
10
+ import { fileURLToPath } from 'node:url';
11
+ import { getHomeDir } from '../config/paths.mjs';
12
+ import { atomicWriteFileSync, atomicWriteJsonSync } from '../storage/atomic-io.mjs';
13
+
14
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
15
+ export const PACKAGE_ROOT = path.resolve(__dirname, '../..');
16
+
17
+ export const PRE_TOOL_MATCHER =
18
+ 'Bash|PowerShell|Edit|MultiEdit|Write|NotebookEdit|Read|Grep|Glob|Task|Agent|WebFetch|mcp__.*';
19
+ export const POST_TOOL_MATCHER =
20
+ 'Bash|PowerShell|Edit|MultiEdit|Write|NotebookEdit|Task|Agent|WebFetch|mcp__.*';
21
+ export const SESSION_START_MATCHER = 'startup|resume|clear|compact';
22
+ export const ANTIGRAVITY_PRE_TOOL_MATCHER =
23
+ 'run_command|read_file|view_file|write_file|write_to_file|edit_file|replace_file_content|multi_replace_file_content|grep_search|find_by_name|list_dir|invoke_subagent|read_url_content|call_mcp_tool|mcp_.*';
24
+ export const ANTIGRAVITY_POST_TOOL_MATCHER =
25
+ 'run_command|read_file|view_file|write_file|write_to_file|edit_file|replace_file_content|multi_replace_file_content|grep_search|find_by_name|invoke_subagent|read_url_content|call_mcp_tool|mcp_.*';
26
+
27
+ const EXCLUDE_START_MARKER = '# burnoff-managed:start';
28
+ const EXCLUDE_END_MARKER = '# burnoff-managed:end';
29
+ const CLAUDE_EXCLUDE_PATTERNS = Object.freeze([
30
+ '.claude/settings.local.json',
31
+ '.claude/burnoff-hook-shim.mjs',
32
+ '.claude/cache/',
33
+ '.claude/locks/',
34
+ '.burnoff/'
35
+ ]);
36
+ const ANTIGRAVITY_EXCLUDE_PATTERNS = Object.freeze([
37
+ '.burnoff/'
38
+ ]);
39
+
40
+ export function isEphemeralNpxPath(pkgRoot = PACKAGE_ROOT) {
41
+ const norm = String(pkgRoot || '').replace(/\\/g, '/');
42
+ return /(?:^|\/)_npx(?:\/|$)|(?:^|\/)npm-cache\/_npx(?:\/|$)/i.test(norm);
43
+ }
44
+
45
+ function normalizeCommandPath(filePath) {
46
+ return path.resolve(filePath).replace(/\\/g, '/');
47
+ }
48
+
49
+ function isBurnoffCommand(command = '') {
50
+ const cmd = String(command || '').replace(/\\/g, '/');
51
+ if (!cmd) return false;
52
+ if (/\.claude\/burnoff-hook-shim\.mjs/i.test(cmd)) return true;
53
+ return (
54
+ /(?:^|[/"'\s])hooks\/(?:(?:pre|post)-tool-use|session-lifecycle)\.mjs(?:["'\s]|$)/i.test(cmd) &&
55
+ (/burnoff/i.test(cmd) ||
56
+ cmd.includes(normalizeCommandPath(path.join(PACKAGE_ROOT, 'hooks'))))
57
+ );
58
+ }
59
+
60
+ function resolveGitDir(cwd) {
61
+ const repoDir = path.resolve(cwd || process.cwd());
62
+ const dotGit = path.join(repoDir, '.git');
63
+ if (!fs.existsSync(dotGit)) return null;
64
+ try {
65
+ const stat = fs.statSync(dotGit);
66
+ if (stat.isDirectory()) return dotGit;
67
+ if (stat.isFile()) {
68
+ const content = fs.readFileSync(dotGit, 'utf8');
69
+ const m = content.match(/^gitdir:\s*(.+)$/im);
70
+ if (m && m[1]) {
71
+ const target = m[1].trim();
72
+ return path.isAbsolute(target) ? target : path.resolve(repoDir, target);
73
+ }
74
+ }
75
+ } catch (err) {
76
+ void err; // ignore: unreadable .git metadata skips info/exclude management
77
+ }
78
+ return null;
79
+ }
80
+
81
+ function buildExcludeBlock(patterns = CLAUDE_EXCLUDE_PATTERNS) {
82
+ return [EXCLUDE_START_MARKER, ...patterns, EXCLUDE_END_MARKER].join('\n');
83
+ }
84
+
85
+ function upsertExcludeBlock(existingContent = '', patterns = CLAUDE_EXCLUDE_PATTERNS) {
86
+ const block = buildExcludeBlock(patterns);
87
+ const blockRe = new RegExp(
88
+ `${EXCLUDE_START_MARKER}[\\s\\S]*?${EXCLUDE_END_MARKER}\\r?\\n?`,
89
+ 'g'
90
+ );
91
+ const stripped = String(existingContent || '').replace(blockRe, '').replace(/\s+$/, '');
92
+ if (!stripped) return `${block}\n`;
93
+ return `${stripped}\n\n${block}\n`;
94
+ }
95
+
96
+ function removeExcludeBlock(existingContent = '') {
97
+ const blockRe = new RegExp(
98
+ `(?:\\r?\\n)*${EXCLUDE_START_MARKER}[\\s\\S]*?${EXCLUDE_END_MARKER}\\r?\\n?`,
99
+ 'g'
100
+ );
101
+ const next = String(existingContent || '').replace(blockRe, '').replace(/\s+$/, '');
102
+ return next ? `${next}\n` : '';
103
+ }
104
+
105
+ function filterOutBurnoffMatcherGroups(groups) {
106
+ if (!Array.isArray(groups)) return [];
107
+ const kept = [];
108
+ for (const group of groups) {
109
+ if (!group || typeof group !== 'object') continue;
110
+ if (!Array.isArray(group.hooks)) {
111
+ if (!isBurnoffCommand(group.command)) kept.push(group);
112
+ continue;
113
+ }
114
+ const remainingHooks = group.hooks.filter((h) => !isBurnoffCommand(h?.command));
115
+ if (remainingHooks.length > 0) {
116
+ kept.push({ ...group, hooks: remainingHooks });
117
+ }
118
+ }
119
+ return kept;
120
+ }
121
+
122
+ function readJsonObjectSafe(filePath) {
123
+ if (!fs.existsSync(filePath)) return {};
124
+ try {
125
+ const parsed = JSON.parse(fs.readFileSync(filePath, 'utf8'));
126
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
127
+ return parsed;
128
+ }
129
+ } catch (err) {
130
+ void err; // ignore: malformed settings.local.json replaced cleanly
131
+ }
132
+ return {};
133
+ }
134
+
135
+ function buildHookShimSource(fallbackPackageRoot) {
136
+ const fallback = normalizeCommandPath(fallbackPackageRoot);
137
+ return `import fs from 'node:fs';
138
+ import path from 'node:path';
139
+ import { createRequire } from 'node:module';
140
+ import { fileURLToPath, pathToFileURL } from 'node:url';
141
+
142
+ const hookArgMap = {
143
+ post: 'post-tool-use.mjs',
144
+ session: 'session-lifecycle.mjs',
145
+ pre: 'pre-tool-use.mjs'
146
+ };
147
+ const hookArg = hookArgMap[process.argv[2]] || 'pre-tool-use.mjs';
148
+ const cwd = process.cwd();
149
+ const parentDir = path.dirname(cwd);
150
+ const shimDir = path.dirname(fileURLToPath(import.meta.url));
151
+ const candidates = [
152
+ path.join(cwd, 'node_modules', 'burnoff', 'hooks', hookArg),
153
+ path.join(parentDir, 'node_modules', 'burnoff', 'hooks', hookArg),
154
+ path.join(shimDir, '..', 'node_modules', 'burnoff', 'hooks', hookArg)
155
+ ];
156
+
157
+ for (const baseDir of [cwd, parentDir, path.join(shimDir, '..')]) {
158
+ try {
159
+ const req = createRequire(path.join(baseDir, 'package.json'));
160
+ const pkgPath = req.resolve('burnoff/package.json');
161
+ candidates.push(path.join(path.dirname(pkgPath), 'hooks', hookArg));
162
+ } catch {
163
+ // ignore: local/global resolution miss falls back to bundled path
164
+ }
165
+ }
166
+
167
+ candidates.push(path.join(${JSON.stringify(fallback)}, 'hooks', hookArg));
168
+
169
+ const resolved = candidates.find((p) => {
170
+ try {
171
+ return fs.existsSync(p);
172
+ } catch {
173
+ return false;
174
+ }
175
+ });
176
+
177
+ if (!resolved) {
178
+ process.stderr.write(
179
+ '[burnoff] Hook target missing (ephemeral npx cache cleared). Install persistently: npm i -D burnoff or npm i -g burnoff.\\n'
180
+ );
181
+ process.exit(0);
182
+ }
183
+
184
+ await import(pathToFileURL(resolved).href);
185
+ `;
186
+ }
187
+
188
+ /**
189
+ * Builds Claude Code `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `SessionStart`,
190
+ * and `PreCompact` hook definitions pointing to Burnoff's fast-shell hooks.
191
+ */
192
+ export function buildClaudeHooksConfig(options = {}) {
193
+ const root = path.resolve(options.packageRoot || PACKAGE_ROOT);
194
+ const preCmd = options.shimPath
195
+ ? `node "${normalizeCommandPath(options.shimPath)}" pre`
196
+ : `node "${normalizeCommandPath(path.join(root, 'hooks', 'pre-tool-use.mjs'))}"`;
197
+ const postCmd = options.shimPath
198
+ ? `node "${normalizeCommandPath(options.shimPath)}" post`
199
+ : `node "${normalizeCommandPath(path.join(root, 'hooks', 'post-tool-use.mjs'))}"`;
200
+ const sessionCmd = options.shimPath
201
+ ? `node "${normalizeCommandPath(options.shimPath)}" session`
202
+ : `node "${normalizeCommandPath(path.join(root, 'hooks', 'session-lifecycle.mjs'))}"`;
203
+ const timeout = Number.isFinite(Number(options.timeout)) ? Number(options.timeout) : 5;
204
+
205
+ return {
206
+ PreToolUse: [
207
+ {
208
+ matcher: options.preMatcher || PRE_TOOL_MATCHER,
209
+ hooks: [
210
+ {
211
+ type: 'command',
212
+ command: preCmd,
213
+ timeout
214
+ }
215
+ ]
216
+ }
217
+ ],
218
+ PostToolUse: [
219
+ {
220
+ matcher: options.postMatcher || POST_TOOL_MATCHER,
221
+ hooks: [
222
+ {
223
+ type: 'command',
224
+ command: postCmd,
225
+ timeout
226
+ }
227
+ ]
228
+ }
229
+ ],
230
+ PostToolUseFailure: [
231
+ {
232
+ matcher: options.postMatcher || POST_TOOL_MATCHER,
233
+ hooks: [
234
+ {
235
+ type: 'command',
236
+ command: postCmd,
237
+ timeout
238
+ }
239
+ ]
240
+ }
241
+ ],
242
+ SessionStart: [
243
+ {
244
+ matcher: options.sessionStartMatcher || SESSION_START_MATCHER,
245
+ hooks: [
246
+ {
247
+ type: 'command',
248
+ command: sessionCmd,
249
+ timeout
250
+ }
251
+ ]
252
+ }
253
+ ],
254
+ PreCompact: [
255
+ {
256
+ hooks: [
257
+ {
258
+ type: 'command',
259
+ command: sessionCmd,
260
+ timeout
261
+ }
262
+ ]
263
+ }
264
+ ]
265
+ };
266
+ }
267
+
268
+ /**
269
+ * Returns true if an Antigravity hook command contains single or double quotes.
270
+ * Antigravity splits hook commands on whitespace without a shell, passing quotes literally.
271
+ */
272
+ export function hasQuotedAntigravityPath(command = '') {
273
+ return /["']/.test(String(command || ''));
274
+ }
275
+
276
+ function resolveAntigravityHookCommand(hookFileName, shimArg, options = {}) {
277
+ const root = path.resolve(options.packageRoot || PACKAGE_ROOT);
278
+ const absTarget = options.shimPath
279
+ ? path.resolve(options.shimPath)
280
+ : path.join(root, 'hooks', hookFileName);
281
+ const suffix = options.shimPath ? ` ${shimArg}` : '';
282
+ const normAbs = normalizeCommandPath(absTarget);
283
+
284
+ if (!/\s/.test(normAbs) && !/^\/(?:sessions|mnt|workspaces?)\//i.test(normAbs)) {
285
+ return `node ${normAbs}${suffix}`;
286
+ }
287
+
288
+ const homeDir = options.homeDir || getHomeDir();
289
+ const cwd = path.resolve(options.cwd || process.cwd());
290
+ const hooksDir = path.resolve(
291
+ options.hooksDir ||
292
+ (options.global ? path.join(homeDir, '.gemini', 'config') : path.join(cwd, '.agents'))
293
+ );
294
+ const relPath = path.relative(hooksDir, absTarget).replace(/\\/g, '/');
295
+ return `node ${relPath}${suffix}`;
296
+ }
297
+
298
+ /**
299
+ * Builds Google Antigravity `hooks.json` `"burnoff"` entry supporting both Antigravity 2.0 and IDE v1.
300
+ */
301
+ export function buildAntigravityHooksConfig(options = {}) {
302
+ const preCmd = resolveAntigravityHookCommand('pre-tool-use.mjs', 'pre', options);
303
+ const postCmd = resolveAntigravityHookCommand('post-tool-use.mjs', 'post', options);
304
+ const timeout = Number.isFinite(Number(options.timeout)) ? Number(options.timeout) : 5;
305
+
306
+ return {
307
+ enabled: true,
308
+ PreToolUse: [
309
+ {
310
+ matcher: options.preMatcher || ANTIGRAVITY_PRE_TOOL_MATCHER,
311
+ hooks: [
312
+ {
313
+ type: 'command',
314
+ command: preCmd,
315
+ timeout
316
+ }
317
+ ]
318
+ }
319
+ ],
320
+ PostToolUse: [
321
+ {
322
+ matcher: options.postMatcher || ANTIGRAVITY_POST_TOOL_MATCHER,
323
+ hooks: [
324
+ {
325
+ type: 'command',
326
+ command: postCmd,
327
+ timeout
328
+ }
329
+ ]
330
+ }
331
+ ]
332
+ };
333
+ }
334
+
335
+ export function resolveInitClients(clientOpt = 'claude', { cwd = process.cwd(), homeDir = getHomeDir() } = {}) {
336
+ const raw = String(clientOpt || 'claude').trim().toLowerCase();
337
+ if (raw === 'antigravity' || raw === 'ag') return ['antigravity'];
338
+ if (raw === 'both' || raw === 'all') return ['claude', 'antigravity'];
339
+ if (raw === 'auto') {
340
+ const detected = [];
341
+ if (fs.existsSync(path.join(cwd, '.claude'))) detected.push('claude');
342
+ if (
343
+ fs.existsSync(path.join(cwd, '.agents')) ||
344
+ fs.existsSync(path.join(homeDir, '.gemini', 'config'))
345
+ ) {
346
+ detected.push('antigravity');
347
+ }
348
+ return detected.length > 0 ? detected : ['claude'];
349
+ }
350
+ return ['claude'];
351
+ }
352
+
353
+ /**
354
+ * Installs Burnoff hooks for Claude Code (`.claude/settings.local.json`) and/or
355
+ * Google Antigravity (`.agents/hooks.json` or `--global` `~/.gemini/config/hooks.json`).
356
+ */
357
+ export function initBurnoff(options = {}) {
358
+ const cwd = path.resolve(options.cwd || process.cwd());
359
+ const homeDir = options.homeDir || getHomeDir();
360
+ const dryRun = Boolean(options.dryRun);
361
+ const isGlobal = Boolean(options.global);
362
+ const pkgRoot = path.resolve(options.packageRoot || PACKAGE_ROOT);
363
+ const ephemeralNpx = isEphemeralNpxPath(pkgRoot);
364
+ const useShim = Boolean(options.useShim || ephemeralNpx);
365
+ const clients = resolveInitClients(options.client || 'claude', { cwd, homeDir });
366
+ const installClaude = clients.includes('claude');
367
+ const installAntigravity = clients.includes('antigravity');
368
+
369
+ const warnings = [];
370
+ const shimPath = installClaude && useShim ? path.join(cwd, '.claude', 'burnoff-hook-shim.mjs') : null;
371
+ const agShimPath =
372
+ installAntigravity && useShim
373
+ ? (shimPath || path.join(cwd, '.burnoff', 'hook-shim.mjs'))
374
+ : null;
375
+
376
+ if (ephemeralNpx) {
377
+ warnings.push(
378
+ `Ephemeral npx cache path detected; wrote ${agShimPath && !shimPath ? '.burnoff/hook-shim.mjs' : '.claude/burnoff-hook-shim.mjs'}. Install persistently with "npm i -D burnoff" or "npm i -g burnoff".`
379
+ );
380
+ }
381
+
382
+ let settingsPath = path.join(cwd, '.claude', 'settings.local.json');
383
+ let hooks = null;
384
+ if (installClaude) {
385
+ hooks = buildClaudeHooksConfig({
386
+ ...options,
387
+ packageRoot: pkgRoot,
388
+ ...(shimPath ? { shimPath } : {})
389
+ });
390
+
391
+ const current = readJsonObjectSafe(settingsPath);
392
+ const existingHooks =
393
+ current.hooks && typeof current.hooks === 'object' && !Array.isArray(current.hooks)
394
+ ? { ...current.hooks }
395
+ : {};
396
+
397
+ const prevPre = filterOutBurnoffMatcherGroups(existingHooks.PreToolUse);
398
+ const prevPost = filterOutBurnoffMatcherGroups(existingHooks.PostToolUse);
399
+ const prevPostFail = filterOutBurnoffMatcherGroups(existingHooks.PostToolUseFailure);
400
+ const prevSessionStart = filterOutBurnoffMatcherGroups(existingHooks.SessionStart);
401
+ const prevPreCompact = filterOutBurnoffMatcherGroups(existingHooks.PreCompact);
402
+
403
+ const nextSettings = {
404
+ ...current,
405
+ hooks: {
406
+ ...existingHooks,
407
+ PreToolUse: [...prevPre, ...hooks.PreToolUse],
408
+ PostToolUse: [...prevPost, ...hooks.PostToolUse],
409
+ PostToolUseFailure: [...prevPostFail, ...hooks.PostToolUseFailure],
410
+ SessionStart: [...prevSessionStart, ...hooks.SessionStart],
411
+ PreCompact: [...prevPreCompact, ...hooks.PreCompact]
412
+ }
413
+ };
414
+
415
+ if (!dryRun) {
416
+ if (shimPath) {
417
+ atomicWriteFileSync(shimPath, buildHookShimSource(pkgRoot), { encoding: 'utf8' });
418
+ }
419
+ atomicWriteJsonSync(settingsPath, nextSettings);
420
+ }
421
+ }
422
+
423
+ let antigravityHooksPath = null;
424
+ let antigravityHooks = null;
425
+ if (installAntigravity) {
426
+ antigravityHooksPath = isGlobal
427
+ ? path.join(homeDir, '.gemini', 'config', 'hooks.json')
428
+ : path.join(cwd, '.agents', 'hooks.json');
429
+ antigravityHooks = buildAntigravityHooksConfig({
430
+ ...options,
431
+ cwd,
432
+ homeDir,
433
+ hooksDir: path.dirname(antigravityHooksPath),
434
+ global: isGlobal,
435
+ packageRoot: pkgRoot,
436
+ ...(agShimPath ? { shimPath: agShimPath } : {})
437
+ });
438
+
439
+ const currentAg = readJsonObjectSafe(antigravityHooksPath);
440
+ const nextAg = {
441
+ ...currentAg,
442
+ burnoff: antigravityHooks
443
+ };
444
+
445
+ if (!dryRun) {
446
+ if (agShimPath && agShimPath !== shimPath) {
447
+ atomicWriteFileSync(agShimPath, buildHookShimSource(pkgRoot), { encoding: 'utf8' });
448
+ }
449
+ atomicWriteJsonSync(antigravityHooksPath, nextAg);
450
+ }
451
+ }
452
+
453
+ let excludePath = null;
454
+ let excludeUpdated = false;
455
+ const gitDir = !isGlobal || installClaude ? resolveGitDir(cwd) : null;
456
+ if (gitDir) {
457
+ excludePath = path.join(gitDir, 'info', 'exclude');
458
+ const prevExclude = fs.existsSync(excludePath) ? fs.readFileSync(excludePath, 'utf8') : '';
459
+ const patterns = installClaude ? CLAUDE_EXCLUDE_PATTERNS : ANTIGRAVITY_EXCLUDE_PATTERNS;
460
+ const nextExclude = upsertExcludeBlock(prevExclude, patterns);
461
+ if (nextExclude !== prevExclude) {
462
+ excludeUpdated = true;
463
+ if (!dryRun) {
464
+ atomicWriteFileSync(excludePath, nextExclude, { encoding: 'utf8' });
465
+ }
466
+ }
467
+ }
468
+
469
+ return {
470
+ ok: true,
471
+ dryRun,
472
+ cwd,
473
+ clients,
474
+ global: isGlobal,
475
+ settingsPath,
476
+ antigravityHooksPath,
477
+ shimPath: shimPath || agShimPath,
478
+ ephemeralNpx,
479
+ warnings,
480
+ excludePath,
481
+ excludeUpdated,
482
+ hooks,
483
+ antigravityHooks
484
+ };
485
+ }
486
+
487
+ /**
488
+ * Removes Burnoff hooks for Claude Code and/or Google Antigravity and cleans `<gitDir>/info/exclude`.
489
+ */
490
+ export function uninstallBurnoff(options = {}) {
491
+ const cwd = path.resolve(options.cwd || process.cwd());
492
+ const homeDir = options.homeDir || getHomeDir();
493
+ const dryRun = Boolean(options.dryRun);
494
+ const isGlobal = Boolean(options.global);
495
+ const clients = options.client
496
+ ? resolveInitClients(options.client, { cwd, homeDir })
497
+ : ['claude', 'antigravity'];
498
+ const uninstallClaude = clients.includes('claude');
499
+ const uninstallAntigravity = clients.includes('antigravity');
500
+
501
+ const settingsPath = path.join(cwd, '.claude', 'settings.local.json');
502
+ let removedSettings = false;
503
+ let updatedSettings = false;
504
+
505
+ if (uninstallClaude) {
506
+ const shimPath = path.join(cwd, '.claude', 'burnoff-hook-shim.mjs');
507
+ if (fs.existsSync(shimPath) && !dryRun) {
508
+ try {
509
+ fs.unlinkSync(shimPath);
510
+ } catch (err) {
511
+ void err; // ignore: shim unlink best-effort
512
+ }
513
+ }
514
+
515
+ if (fs.existsSync(settingsPath)) {
516
+ const current = readJsonObjectSafe(settingsPath);
517
+ const nextHooks =
518
+ current.hooks && typeof current.hooks === 'object' && !Array.isArray(current.hooks)
519
+ ? { ...current.hooks }
520
+ : {};
521
+
522
+ if (nextHooks.PreToolUse) {
523
+ const keptPre = filterOutBurnoffMatcherGroups(nextHooks.PreToolUse);
524
+ if (keptPre.length > 0) nextHooks.PreToolUse = keptPre;
525
+ else delete nextHooks.PreToolUse;
526
+ }
527
+ if (nextHooks.PostToolUse) {
528
+ const keptPost = filterOutBurnoffMatcherGroups(nextHooks.PostToolUse);
529
+ if (keptPost.length > 0) nextHooks.PostToolUse = keptPost;
530
+ else delete nextHooks.PostToolUse;
531
+ }
532
+ if (nextHooks.PostToolUseFailure) {
533
+ const keptPostFail = filterOutBurnoffMatcherGroups(nextHooks.PostToolUseFailure);
534
+ if (keptPostFail.length > 0) nextHooks.PostToolUseFailure = keptPostFail;
535
+ else delete nextHooks.PostToolUseFailure;
536
+ }
537
+ if (nextHooks.SessionStart) {
538
+ const keptSessionStart = filterOutBurnoffMatcherGroups(nextHooks.SessionStart);
539
+ if (keptSessionStart.length > 0) nextHooks.SessionStart = keptSessionStart;
540
+ else delete nextHooks.SessionStart;
541
+ }
542
+ if (nextHooks.PreCompact) {
543
+ const keptPreCompact = filterOutBurnoffMatcherGroups(nextHooks.PreCompact);
544
+ if (keptPreCompact.length > 0) nextHooks.PreCompact = keptPreCompact;
545
+ else delete nextHooks.PreCompact;
546
+ }
547
+
548
+ const nextSettings = { ...current };
549
+ if (Object.keys(nextHooks).length > 0) {
550
+ nextSettings.hooks = nextHooks;
551
+ } else {
552
+ delete nextSettings.hooks;
553
+ }
554
+
555
+ if (Object.keys(nextSettings).length === 0) {
556
+ removedSettings = true;
557
+ if (!dryRun) {
558
+ fs.unlinkSync(settingsPath);
559
+ const claudeDir = path.dirname(settingsPath);
560
+ try {
561
+ if (fs.existsSync(claudeDir) && fs.readdirSync(claudeDir).length === 0) {
562
+ fs.rmdirSync(claudeDir);
563
+ }
564
+ } catch (err) {
565
+ void err; // ignore: non-empty or locked .claude directory left intact
566
+ }
567
+ }
568
+ } else {
569
+ updatedSettings = true;
570
+ if (!dryRun) {
571
+ atomicWriteJsonSync(settingsPath, nextSettings);
572
+ }
573
+ }
574
+ }
575
+ }
576
+
577
+ const antigravityHooksPath = isGlobal
578
+ ? path.join(homeDir, '.gemini', 'config', 'hooks.json')
579
+ : path.join(cwd, '.agents', 'hooks.json');
580
+ let removedAntigravityHooks = false;
581
+ let updatedAntigravityHooks = false;
582
+
583
+ if (uninstallAntigravity) {
584
+ const agShimPath = path.join(cwd, '.burnoff', 'hook-shim.mjs');
585
+ if (fs.existsSync(agShimPath) && !dryRun) {
586
+ try {
587
+ fs.unlinkSync(agShimPath);
588
+ } catch (err) {
589
+ void err; // ignore: Antigravity shim unlink best-effort
590
+ }
591
+ }
592
+
593
+ if (fs.existsSync(antigravityHooksPath)) {
594
+ const currentAg = readJsonObjectSafe(antigravityHooksPath);
595
+ if (Object.prototype.hasOwnProperty.call(currentAg, 'burnoff')) {
596
+ const nextAg = { ...currentAg };
597
+ delete nextAg.burnoff;
598
+ if (Object.keys(nextAg).length === 0) {
599
+ removedAntigravityHooks = true;
600
+ if (!dryRun) {
601
+ fs.unlinkSync(antigravityHooksPath);
602
+ const agDir = path.dirname(antigravityHooksPath);
603
+ try {
604
+ if (!isGlobal && fs.existsSync(agDir) && fs.readdirSync(agDir).length === 0) {
605
+ fs.rmdirSync(agDir);
606
+ }
607
+ } catch (err) {
608
+ void err; // ignore: non-empty or locked .agents directory left intact
609
+ }
610
+ }
611
+ } else {
612
+ updatedAntigravityHooks = true;
613
+ if (!dryRun) {
614
+ atomicWriteJsonSync(antigravityHooksPath, nextAg);
615
+ }
616
+ }
617
+ }
618
+ }
619
+ }
620
+
621
+ let excludePath = null;
622
+ let excludeUpdated = false;
623
+ const gitDir = resolveGitDir(cwd);
624
+ if (gitDir) {
625
+ excludePath = path.join(gitDir, 'info', 'exclude');
626
+ if (fs.existsSync(excludePath)) {
627
+ const prevExclude = fs.readFileSync(excludePath, 'utf8');
628
+ const nextExclude = removeExcludeBlock(prevExclude);
629
+ if (nextExclude !== prevExclude) {
630
+ excludeUpdated = true;
631
+ if (!dryRun) {
632
+ atomicWriteFileSync(excludePath, nextExclude, { encoding: 'utf8' });
633
+ }
634
+ }
635
+ }
636
+ }
637
+
638
+ return {
639
+ ok: true,
640
+ dryRun,
641
+ cwd,
642
+ clients,
643
+ global: isGlobal,
644
+ settingsPath,
645
+ removedSettings,
646
+ updatedSettings,
647
+ antigravityHooksPath,
648
+ removedAntigravityHooks,
649
+ updatedAntigravityHooks,
650
+ excludePath,
651
+ excludeUpdated
652
+ };
653
+ }
654
+
655
+ export default {
656
+ PACKAGE_ROOT,
657
+ PRE_TOOL_MATCHER,
658
+ POST_TOOL_MATCHER,
659
+ SESSION_START_MATCHER,
660
+ ANTIGRAVITY_PRE_TOOL_MATCHER,
661
+ ANTIGRAVITY_POST_TOOL_MATCHER,
662
+ buildClaudeHooksConfig,
663
+ buildAntigravityHooksConfig,
664
+ hasQuotedAntigravityPath,
665
+ resolveInitClients,
666
+ initBurnoff,
667
+ uninstallBurnoff
668
+ };