burnoff 0.0.0-stage → 1.0.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,306 @@
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/cache/',
26
+ '.claude/locks/',
27
+ '.burnoff-ci/'
28
+ ]);
29
+
30
+ function normalizeCommandPath(filePath) {
31
+ return path.resolve(filePath).replace(/\\/g, '/');
32
+ }
33
+
34
+ function isBurnoffCommand(command = '') {
35
+ const cmd = String(command || '').replace(/\\/g, '/');
36
+ if (!cmd) return false;
37
+ return (
38
+ /(?:^|[/"'\s])hooks\/(?:pre|post)-tool-use\.mjs(?:["'\s]|$)/i.test(cmd) &&
39
+ (/burnoff/i.test(cmd) ||
40
+ cmd.includes(normalizeCommandPath(path.join(PACKAGE_ROOT, 'hooks'))))
41
+ );
42
+ }
43
+
44
+ function resolveGitDir(cwd) {
45
+ const repoDir = path.resolve(cwd || process.cwd());
46
+ const dotGit = path.join(repoDir, '.git');
47
+ if (!fs.existsSync(dotGit)) return null;
48
+ try {
49
+ const stat = fs.statSync(dotGit);
50
+ if (stat.isDirectory()) return dotGit;
51
+ if (stat.isFile()) {
52
+ const content = fs.readFileSync(dotGit, 'utf8');
53
+ const m = content.match(/^gitdir:\s*(.+)$/im);
54
+ if (m && m[1]) {
55
+ const target = m[1].trim();
56
+ return path.isAbsolute(target) ? target : path.resolve(repoDir, target);
57
+ }
58
+ }
59
+ } catch (err) {
60
+ void err; // ignore: unreadable .git metadata skips info/exclude management
61
+ }
62
+ return null;
63
+ }
64
+
65
+ function buildExcludeBlock() {
66
+ return [EXCLUDE_START_MARKER, ...EXCLUDE_PATTERNS, EXCLUDE_END_MARKER].join('\n');
67
+ }
68
+
69
+ function upsertExcludeBlock(existingContent = '') {
70
+ const block = buildExcludeBlock();
71
+ const blockRe = new RegExp(
72
+ `${EXCLUDE_START_MARKER}[\\s\\S]*?${EXCLUDE_END_MARKER}\\r?\\n?`,
73
+ 'g'
74
+ );
75
+ const stripped = String(existingContent || '').replace(blockRe, '').replace(/\s+$/, '');
76
+ if (!stripped) return `${block}\n`;
77
+ return `${stripped}\n\n${block}\n`;
78
+ }
79
+
80
+ function removeExcludeBlock(existingContent = '') {
81
+ const blockRe = new RegExp(
82
+ `(?:\\r?\\n)*${EXCLUDE_START_MARKER}[\\s\\S]*?${EXCLUDE_END_MARKER}\\r?\\n?`,
83
+ 'g'
84
+ );
85
+ const next = String(existingContent || '').replace(blockRe, '').replace(/\s+$/, '');
86
+ return next ? `${next}\n` : '';
87
+ }
88
+
89
+ function filterOutBurnoffMatcherGroups(groups) {
90
+ if (!Array.isArray(groups)) return [];
91
+ const kept = [];
92
+ for (const group of groups) {
93
+ if (!group || typeof group !== 'object') continue;
94
+ if (!Array.isArray(group.hooks)) {
95
+ if (!isBurnoffCommand(group.command)) kept.push(group);
96
+ continue;
97
+ }
98
+ const remainingHooks = group.hooks.filter((h) => !isBurnoffCommand(h?.command));
99
+ if (remainingHooks.length > 0) {
100
+ kept.push({ ...group, hooks: remainingHooks });
101
+ }
102
+ }
103
+ return kept;
104
+ }
105
+
106
+ function readJsonObjectSafe(filePath) {
107
+ if (!fs.existsSync(filePath)) return {};
108
+ try {
109
+ const parsed = JSON.parse(fs.readFileSync(filePath, 'utf8'));
110
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
111
+ return parsed;
112
+ }
113
+ } catch (err) {
114
+ void err; // ignore: malformed settings.local.json replaced cleanly
115
+ }
116
+ return {};
117
+ }
118
+
119
+ /**
120
+ * Builds Claude Code `PreToolUse` and `PostToolUse` hook definitions pointing to Burnoff's fast-shell hooks.
121
+ */
122
+ export function buildClaudeHooksConfig(options = {}) {
123
+ const root = path.resolve(options.packageRoot || PACKAGE_ROOT);
124
+ const prePath = normalizeCommandPath(path.join(root, 'hooks', 'pre-tool-use.mjs'));
125
+ const postPath = normalizeCommandPath(path.join(root, 'hooks', 'post-tool-use.mjs'));
126
+ const timeout = Number.isFinite(Number(options.timeout)) ? Number(options.timeout) : 5;
127
+
128
+ return {
129
+ PreToolUse: [
130
+ {
131
+ matcher: options.preMatcher || PRE_TOOL_MATCHER,
132
+ hooks: [
133
+ {
134
+ type: 'command',
135
+ command: `node "${prePath}"`,
136
+ timeout
137
+ }
138
+ ]
139
+ }
140
+ ],
141
+ PostToolUse: [
142
+ {
143
+ matcher: options.postMatcher || POST_TOOL_MATCHER,
144
+ hooks: [
145
+ {
146
+ type: 'command',
147
+ command: `node "${postPath}"`,
148
+ timeout
149
+ }
150
+ ]
151
+ }
152
+ ]
153
+ };
154
+ }
155
+
156
+ /**
157
+ * Installs Burnoff hooks into `<cwd>/.claude/settings.local.json` and adds local state paths
158
+ * to `<gitDir>/info/exclude` without touching `.claude/settings.json` or `.gitignore`.
159
+ */
160
+ export function initBurnoff(options = {}) {
161
+ const cwd = path.resolve(options.cwd || process.cwd());
162
+ const dryRun = Boolean(options.dryRun);
163
+ const settingsPath = path.join(cwd, '.claude', 'settings.local.json');
164
+ const hooks = buildClaudeHooksConfig(options);
165
+
166
+ const current = readJsonObjectSafe(settingsPath);
167
+ const existingHooks =
168
+ current.hooks && typeof current.hooks === 'object' && !Array.isArray(current.hooks)
169
+ ? { ...current.hooks }
170
+ : {};
171
+
172
+ const prevPre = filterOutBurnoffMatcherGroups(existingHooks.PreToolUse);
173
+ const prevPost = filterOutBurnoffMatcherGroups(existingHooks.PostToolUse);
174
+
175
+ const nextSettings = {
176
+ ...current,
177
+ hooks: {
178
+ ...existingHooks,
179
+ PreToolUse: [...prevPre, ...hooks.PreToolUse],
180
+ PostToolUse: [...prevPost, ...hooks.PostToolUse]
181
+ }
182
+ };
183
+
184
+ if (!dryRun) {
185
+ atomicWriteJsonSync(settingsPath, nextSettings);
186
+ }
187
+
188
+ let excludePath = null;
189
+ let excludeUpdated = false;
190
+ const gitDir = resolveGitDir(cwd);
191
+ if (gitDir) {
192
+ excludePath = path.join(gitDir, 'info', 'exclude');
193
+ const prevExclude = fs.existsSync(excludePath) ? fs.readFileSync(excludePath, 'utf8') : '';
194
+ const nextExclude = upsertExcludeBlock(prevExclude);
195
+ if (nextExclude !== prevExclude) {
196
+ excludeUpdated = true;
197
+ if (!dryRun) {
198
+ atomicWriteFileSync(excludePath, nextExclude, { encoding: 'utf8' });
199
+ }
200
+ }
201
+ }
202
+
203
+ return {
204
+ ok: true,
205
+ dryRun,
206
+ cwd,
207
+ settingsPath,
208
+ excludePath,
209
+ excludeUpdated,
210
+ hooks
211
+ };
212
+ }
213
+
214
+ /**
215
+ * Removes Burnoff hooks from `<cwd>/.claude/settings.local.json` and cleans `<gitDir>/info/exclude`.
216
+ */
217
+ export function uninstallBurnoff(options = {}) {
218
+ const cwd = path.resolve(options.cwd || process.cwd());
219
+ const dryRun = Boolean(options.dryRun);
220
+ const settingsPath = path.join(cwd, '.claude', 'settings.local.json');
221
+ let removedSettings = false;
222
+ let updatedSettings = false;
223
+
224
+ if (fs.existsSync(settingsPath)) {
225
+ const current = readJsonObjectSafe(settingsPath);
226
+ const nextHooks =
227
+ current.hooks && typeof current.hooks === 'object' && !Array.isArray(current.hooks)
228
+ ? { ...current.hooks }
229
+ : {};
230
+
231
+ if (nextHooks.PreToolUse) {
232
+ const keptPre = filterOutBurnoffMatcherGroups(nextHooks.PreToolUse);
233
+ if (keptPre.length > 0) nextHooks.PreToolUse = keptPre;
234
+ else delete nextHooks.PreToolUse;
235
+ }
236
+ if (nextHooks.PostToolUse) {
237
+ const keptPost = filterOutBurnoffMatcherGroups(nextHooks.PostToolUse);
238
+ if (keptPost.length > 0) nextHooks.PostToolUse = keptPost;
239
+ else delete nextHooks.PostToolUse;
240
+ }
241
+
242
+ const nextSettings = { ...current };
243
+ if (Object.keys(nextHooks).length > 0) {
244
+ nextSettings.hooks = nextHooks;
245
+ } else {
246
+ delete nextSettings.hooks;
247
+ }
248
+
249
+ if (Object.keys(nextSettings).length === 0) {
250
+ removedSettings = true;
251
+ if (!dryRun) {
252
+ fs.unlinkSync(settingsPath);
253
+ const claudeDir = path.dirname(settingsPath);
254
+ try {
255
+ if (fs.existsSync(claudeDir) && fs.readdirSync(claudeDir).length === 0) {
256
+ fs.rmdirSync(claudeDir);
257
+ }
258
+ } catch (err) {
259
+ void err; // ignore: non-empty or locked .claude directory left intact
260
+ }
261
+ }
262
+ } else {
263
+ updatedSettings = true;
264
+ if (!dryRun) {
265
+ atomicWriteJsonSync(settingsPath, nextSettings);
266
+ }
267
+ }
268
+ }
269
+
270
+ let excludePath = null;
271
+ let excludeUpdated = false;
272
+ const gitDir = resolveGitDir(cwd);
273
+ if (gitDir) {
274
+ excludePath = path.join(gitDir, 'info', 'exclude');
275
+ if (fs.existsSync(excludePath)) {
276
+ const prevExclude = fs.readFileSync(excludePath, 'utf8');
277
+ const nextExclude = removeExcludeBlock(prevExclude);
278
+ if (nextExclude !== prevExclude) {
279
+ excludeUpdated = true;
280
+ if (!dryRun) {
281
+ atomicWriteFileSync(excludePath, nextExclude, { encoding: 'utf8' });
282
+ }
283
+ }
284
+ }
285
+ }
286
+
287
+ return {
288
+ ok: true,
289
+ dryRun,
290
+ cwd,
291
+ settingsPath,
292
+ removedSettings,
293
+ updatedSettings,
294
+ excludePath,
295
+ excludeUpdated
296
+ };
297
+ }
298
+
299
+ export default {
300
+ PACKAGE_ROOT,
301
+ PRE_TOOL_MATCHER,
302
+ POST_TOOL_MATCHER,
303
+ buildClaudeHooksConfig,
304
+ initBurnoff,
305
+ uninstallBurnoff
306
+ };