burnoff 0.0.0-stage → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,393 @@
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 { atomicWriteFileSync, atomicWriteJsonSync } from '../storage/atomic-io.mjs';
12
+
13
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
14
+ export const PACKAGE_ROOT = path.resolve(__dirname, '../..');
15
+
16
+ export const PRE_TOOL_MATCHER =
17
+ 'Bash|PowerShell|Edit|MultiEdit|Write|NotebookEdit|Read|Grep|Glob|Task|Agent|WebFetch|mcp__.*';
18
+ export const POST_TOOL_MATCHER =
19
+ 'Bash|PowerShell|Grep|Glob|Task|Agent|WebFetch|mcp__.*';
20
+
21
+ const EXCLUDE_START_MARKER = '# burnoff-managed:start';
22
+ const EXCLUDE_END_MARKER = '# burnoff-managed:end';
23
+ const EXCLUDE_PATTERNS = Object.freeze([
24
+ '.claude/settings.local.json',
25
+ '.claude/burnoff-hook-shim.mjs',
26
+ '.claude/cache/',
27
+ '.claude/locks/',
28
+ '.burnoff/',
29
+ '.burnoff-ci/'
30
+ ]);
31
+
32
+ export function isEphemeralNpxPath(pkgRoot = PACKAGE_ROOT) {
33
+ const norm = String(pkgRoot || '').replace(/\\/g, '/');
34
+ return /(?:^|\/)_npx(?:\/|$)|(?:^|\/)npm-cache\/_npx(?:\/|$)/i.test(norm);
35
+ }
36
+
37
+ function normalizeCommandPath(filePath) {
38
+ return path.resolve(filePath).replace(/\\/g, '/');
39
+ }
40
+
41
+ function isBurnoffCommand(command = '') {
42
+ const cmd = String(command || '').replace(/\\/g, '/');
43
+ if (!cmd) return false;
44
+ if (/\.claude\/burnoff-hook-shim\.mjs/i.test(cmd)) return true;
45
+ return (
46
+ /(?:^|[/"'\s])hooks\/(?:pre|post)-tool-use\.mjs(?:["'\s]|$)/i.test(cmd) &&
47
+ (/burnoff/i.test(cmd) ||
48
+ cmd.includes(normalizeCommandPath(path.join(PACKAGE_ROOT, 'hooks'))))
49
+ );
50
+ }
51
+
52
+ function resolveGitDir(cwd) {
53
+ const repoDir = path.resolve(cwd || process.cwd());
54
+ const dotGit = path.join(repoDir, '.git');
55
+ if (!fs.existsSync(dotGit)) return null;
56
+ try {
57
+ const stat = fs.statSync(dotGit);
58
+ if (stat.isDirectory()) return dotGit;
59
+ if (stat.isFile()) {
60
+ const content = fs.readFileSync(dotGit, 'utf8');
61
+ const m = content.match(/^gitdir:\s*(.+)$/im);
62
+ if (m && m[1]) {
63
+ const target = m[1].trim();
64
+ return path.isAbsolute(target) ? target : path.resolve(repoDir, target);
65
+ }
66
+ }
67
+ } catch (err) {
68
+ void err; // ignore: unreadable .git metadata skips info/exclude management
69
+ }
70
+ return null;
71
+ }
72
+
73
+ function buildExcludeBlock() {
74
+ return [EXCLUDE_START_MARKER, ...EXCLUDE_PATTERNS, EXCLUDE_END_MARKER].join('\n');
75
+ }
76
+
77
+ function upsertExcludeBlock(existingContent = '') {
78
+ const block = buildExcludeBlock();
79
+ const blockRe = new RegExp(
80
+ `${EXCLUDE_START_MARKER}[\\s\\S]*?${EXCLUDE_END_MARKER}\\r?\\n?`,
81
+ 'g'
82
+ );
83
+ const stripped = String(existingContent || '').replace(blockRe, '').replace(/\s+$/, '');
84
+ if (!stripped) return `${block}\n`;
85
+ return `${stripped}\n\n${block}\n`;
86
+ }
87
+
88
+ function removeExcludeBlock(existingContent = '') {
89
+ const blockRe = new RegExp(
90
+ `(?:\\r?\\n)*${EXCLUDE_START_MARKER}[\\s\\S]*?${EXCLUDE_END_MARKER}\\r?\\n?`,
91
+ 'g'
92
+ );
93
+ const next = String(existingContent || '').replace(blockRe, '').replace(/\s+$/, '');
94
+ return next ? `${next}\n` : '';
95
+ }
96
+
97
+ function filterOutBurnoffMatcherGroups(groups) {
98
+ if (!Array.isArray(groups)) return [];
99
+ const kept = [];
100
+ for (const group of groups) {
101
+ if (!group || typeof group !== 'object') continue;
102
+ if (!Array.isArray(group.hooks)) {
103
+ if (!isBurnoffCommand(group.command)) kept.push(group);
104
+ continue;
105
+ }
106
+ const remainingHooks = group.hooks.filter((h) => !isBurnoffCommand(h?.command));
107
+ if (remainingHooks.length > 0) {
108
+ kept.push({ ...group, hooks: remainingHooks });
109
+ }
110
+ }
111
+ return kept;
112
+ }
113
+
114
+ function readJsonObjectSafe(filePath) {
115
+ if (!fs.existsSync(filePath)) return {};
116
+ try {
117
+ const parsed = JSON.parse(fs.readFileSync(filePath, 'utf8'));
118
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
119
+ return parsed;
120
+ }
121
+ } catch (err) {
122
+ void err; // ignore: malformed settings.local.json replaced cleanly
123
+ }
124
+ return {};
125
+ }
126
+
127
+ function buildHookShimSource(fallbackPackageRoot) {
128
+ const fallback = normalizeCommandPath(fallbackPackageRoot);
129
+ return `import fs from 'node:fs';
130
+ import path from 'node:path';
131
+ import { createRequire } from 'node:module';
132
+ import { pathToFileURL } from 'node:url';
133
+
134
+ const hookArg = process.argv[2] === 'post' ? 'post-tool-use.mjs' : 'pre-tool-use.mjs';
135
+ const cwd = process.cwd();
136
+ const candidates = [
137
+ path.join(cwd, 'node_modules', 'burnoff', 'hooks', hookArg)
138
+ ];
139
+
140
+ try {
141
+ const req = createRequire(path.join(cwd, 'package.json'));
142
+ const pkgPath = req.resolve('burnoff/package.json');
143
+ candidates.push(path.join(path.dirname(pkgPath), 'hooks', hookArg));
144
+ } catch {
145
+ // ignore: local/global resolution miss falls back to bundled path
146
+ }
147
+
148
+ candidates.push(path.join(${JSON.stringify(fallback)}, 'hooks', hookArg));
149
+
150
+ const resolved = candidates.find((p) => {
151
+ try {
152
+ return fs.existsSync(p);
153
+ } catch {
154
+ return false;
155
+ }
156
+ });
157
+
158
+ if (!resolved) {
159
+ process.stderr.write(
160
+ '[burnoff] Hook target missing (ephemeral npx cache cleared). Install persistently: npm i -D burnoff or npm i -g burnoff.\\n'
161
+ );
162
+ process.exit(0);
163
+ }
164
+
165
+ await import(pathToFileURL(resolved).href);
166
+ `;
167
+ }
168
+
169
+ /**
170
+ * Builds Claude Code `PreToolUse` and `PostToolUse` hook definitions pointing to Burnoff's fast-shell hooks.
171
+ */
172
+ export function buildClaudeHooksConfig(options = {}) {
173
+ const root = path.resolve(options.packageRoot || PACKAGE_ROOT);
174
+ const preCmd = options.shimPath
175
+ ? `node "${normalizeCommandPath(options.shimPath)}" pre`
176
+ : `node "${normalizeCommandPath(path.join(root, 'hooks', 'pre-tool-use.mjs'))}"`;
177
+ const postCmd = options.shimPath
178
+ ? `node "${normalizeCommandPath(options.shimPath)}" post`
179
+ : `node "${normalizeCommandPath(path.join(root, 'hooks', 'post-tool-use.mjs'))}"`;
180
+ const timeout = Number.isFinite(Number(options.timeout)) ? Number(options.timeout) : 5;
181
+
182
+ return {
183
+ PreToolUse: [
184
+ {
185
+ matcher: options.preMatcher || PRE_TOOL_MATCHER,
186
+ hooks: [
187
+ {
188
+ type: 'command',
189
+ command: preCmd,
190
+ timeout
191
+ }
192
+ ]
193
+ }
194
+ ],
195
+ PostToolUse: [
196
+ {
197
+ matcher: options.postMatcher || POST_TOOL_MATCHER,
198
+ hooks: [
199
+ {
200
+ type: 'command',
201
+ command: postCmd,
202
+ timeout
203
+ }
204
+ ]
205
+ }
206
+ ]
207
+ };
208
+ }
209
+
210
+ /**
211
+ * Installs Burnoff hooks into `<cwd>/.claude/settings.local.json` and adds local state paths
212
+ * to `<gitDir>/info/exclude` without touching `.claude/settings.json` or `.gitignore`.
213
+ */
214
+ export function initBurnoff(options = {}) {
215
+ const cwd = path.resolve(options.cwd || process.cwd());
216
+ const dryRun = Boolean(options.dryRun);
217
+ const pkgRoot = path.resolve(options.packageRoot || PACKAGE_ROOT);
218
+ const ephemeralNpx = isEphemeralNpxPath(pkgRoot);
219
+ const useShim = Boolean(options.useShim || ephemeralNpx);
220
+ const shimPath = useShim ? path.join(cwd, '.claude', 'burnoff-hook-shim.mjs') : null;
221
+ const warnings = [];
222
+ if (ephemeralNpx) {
223
+ warnings.push(
224
+ 'Ephemeral npx cache path detected; wrote .claude/burnoff-hook-shim.mjs. Install persistently with "npm i -D burnoff" or "npm i -g burnoff".'
225
+ );
226
+ }
227
+ const settingsPath = path.join(cwd, '.claude', 'settings.local.json');
228
+ const hooks = buildClaudeHooksConfig({
229
+ ...options,
230
+ packageRoot: pkgRoot,
231
+ ...(shimPath ? { shimPath } : {})
232
+ });
233
+
234
+ const current = readJsonObjectSafe(settingsPath);
235
+ const existingHooks =
236
+ current.hooks && typeof current.hooks === 'object' && !Array.isArray(current.hooks)
237
+ ? { ...current.hooks }
238
+ : {};
239
+
240
+ const prevPre = filterOutBurnoffMatcherGroups(existingHooks.PreToolUse);
241
+ const prevPost = filterOutBurnoffMatcherGroups(existingHooks.PostToolUse);
242
+
243
+ const nextSettings = {
244
+ ...current,
245
+ hooks: {
246
+ ...existingHooks,
247
+ PreToolUse: [...prevPre, ...hooks.PreToolUse],
248
+ PostToolUse: [...prevPost, ...hooks.PostToolUse]
249
+ }
250
+ };
251
+
252
+ if (!dryRun) {
253
+ if (shimPath) {
254
+ atomicWriteFileSync(shimPath, buildHookShimSource(pkgRoot), { encoding: 'utf8' });
255
+ }
256
+ atomicWriteJsonSync(settingsPath, nextSettings);
257
+ }
258
+
259
+ let excludePath = null;
260
+ let excludeUpdated = false;
261
+ const gitDir = resolveGitDir(cwd);
262
+ if (gitDir) {
263
+ excludePath = path.join(gitDir, 'info', 'exclude');
264
+ const prevExclude = fs.existsSync(excludePath) ? fs.readFileSync(excludePath, 'utf8') : '';
265
+ const nextExclude = upsertExcludeBlock(prevExclude);
266
+ if (nextExclude !== prevExclude) {
267
+ excludeUpdated = true;
268
+ if (!dryRun) {
269
+ atomicWriteFileSync(excludePath, nextExclude, { encoding: 'utf8' });
270
+ }
271
+ }
272
+ }
273
+
274
+ return {
275
+ ok: true,
276
+ dryRun,
277
+ cwd,
278
+ settingsPath,
279
+ shimPath,
280
+ ephemeralNpx,
281
+ warnings,
282
+ excludePath,
283
+ excludeUpdated,
284
+ hooks
285
+ };
286
+ }
287
+
288
+ /**
289
+ * Removes Burnoff hooks from `<cwd>/.claude/settings.local.json` and cleans `<gitDir>/info/exclude`.
290
+ */
291
+ export function uninstallBurnoff(options = {}) {
292
+ const cwd = path.resolve(options.cwd || process.cwd());
293
+ const dryRun = Boolean(options.dryRun);
294
+ const settingsPath = path.join(cwd, '.claude', 'settings.local.json');
295
+ let removedSettings = false;
296
+ let updatedSettings = false;
297
+
298
+ const shimPath = path.join(cwd, '.claude', 'burnoff-hook-shim.mjs');
299
+ let removedShim = false;
300
+ if (fs.existsSync(shimPath)) {
301
+ removedShim = true;
302
+ if (!dryRun) {
303
+ try {
304
+ fs.unlinkSync(shimPath);
305
+ } catch (err) {
306
+ void err; // ignore: shim unlink best-effort
307
+ }
308
+ }
309
+ }
310
+
311
+ if (fs.existsSync(settingsPath)) {
312
+ const current = readJsonObjectSafe(settingsPath);
313
+ const nextHooks =
314
+ current.hooks && typeof current.hooks === 'object' && !Array.isArray(current.hooks)
315
+ ? { ...current.hooks }
316
+ : {};
317
+
318
+ if (nextHooks.PreToolUse) {
319
+ const keptPre = filterOutBurnoffMatcherGroups(nextHooks.PreToolUse);
320
+ if (keptPre.length > 0) nextHooks.PreToolUse = keptPre;
321
+ else delete nextHooks.PreToolUse;
322
+ }
323
+ if (nextHooks.PostToolUse) {
324
+ const keptPost = filterOutBurnoffMatcherGroups(nextHooks.PostToolUse);
325
+ if (keptPost.length > 0) nextHooks.PostToolUse = keptPost;
326
+ else delete nextHooks.PostToolUse;
327
+ }
328
+
329
+ const nextSettings = { ...current };
330
+ if (Object.keys(nextHooks).length > 0) {
331
+ nextSettings.hooks = nextHooks;
332
+ } else {
333
+ delete nextSettings.hooks;
334
+ }
335
+
336
+ if (Object.keys(nextSettings).length === 0) {
337
+ removedSettings = true;
338
+ if (!dryRun) {
339
+ fs.unlinkSync(settingsPath);
340
+ const claudeDir = path.dirname(settingsPath);
341
+ try {
342
+ if (fs.existsSync(claudeDir) && fs.readdirSync(claudeDir).length === 0) {
343
+ fs.rmdirSync(claudeDir);
344
+ }
345
+ } catch (err) {
346
+ void err; // ignore: non-empty or locked .claude directory left intact
347
+ }
348
+ }
349
+ } else {
350
+ updatedSettings = true;
351
+ if (!dryRun) {
352
+ atomicWriteJsonSync(settingsPath, nextSettings);
353
+ }
354
+ }
355
+ }
356
+
357
+ let excludePath = null;
358
+ let excludeUpdated = false;
359
+ const gitDir = resolveGitDir(cwd);
360
+ if (gitDir) {
361
+ excludePath = path.join(gitDir, 'info', 'exclude');
362
+ if (fs.existsSync(excludePath)) {
363
+ const prevExclude = fs.readFileSync(excludePath, 'utf8');
364
+ const nextExclude = removeExcludeBlock(prevExclude);
365
+ if (nextExclude !== prevExclude) {
366
+ excludeUpdated = true;
367
+ if (!dryRun) {
368
+ atomicWriteFileSync(excludePath, nextExclude, { encoding: 'utf8' });
369
+ }
370
+ }
371
+ }
372
+ }
373
+
374
+ return {
375
+ ok: true,
376
+ dryRun,
377
+ cwd,
378
+ settingsPath,
379
+ removedSettings,
380
+ updatedSettings,
381
+ excludePath,
382
+ excludeUpdated
383
+ };
384
+ }
385
+
386
+ export default {
387
+ PACKAGE_ROOT,
388
+ PRE_TOOL_MATCHER,
389
+ POST_TOOL_MATCHER,
390
+ buildClaudeHooksConfig,
391
+ initBurnoff,
392
+ uninstallBurnoff
393
+ };