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.
- package/LICENSE +21 -0
- package/README.md +93 -2
- package/bin/burnoff.mjs +406 -0
- package/hooks/hook-io.mjs +590 -0
- package/hooks/hooks.json +12 -0
- package/hooks/post-tool-use.mjs +118 -0
- package/hooks/pre-tool-use.mjs +149 -0
- package/package.json +42 -4
- package/src/ci/ci-gate.mjs +270 -0
- package/src/ci/pr-cost.mjs +582 -0
- package/src/ci/team-digest.mjs +123 -0
- package/src/cli/audit.mjs +196 -0
- package/src/cli/doctor.mjs +257 -0
- package/src/cli/init.mjs +306 -0
- package/src/config/catalog.json +874 -0
- package/src/config/loader.mjs +626 -0
- package/src/config/paths.mjs +196 -0
- package/src/config/policy.mjs +208 -0
- package/src/guards/loop-breaker.mjs +501 -0
- package/src/guards/post-tool-engine.mjs +573 -0
- package/src/guards/pre-tool-engine.mjs +563 -0
- package/src/guards/read-clamp.mjs +730 -0
- package/src/guards/shell-guard.mjs +1140 -0
- package/src/ipc/daemon.mjs +273 -0
- package/src/ipc/fast-client.mjs +198 -0
- package/src/ipc/protocol.mjs +142 -0
- package/src/storage/atomic-io.mjs +151 -0
- package/src/storage/file-lock.mjs +206 -0
- package/src/storage/fts5-archive.mjs +718 -0
- package/src/storage/jsonl-parser.mjs +760 -0
- package/src/storage/ledger.mjs +1150 -0
- package/src/storage/sqlite-client.mjs +566 -0
|
@@ -0,0 +1,590 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file hooks/hook-io.mjs
|
|
3
|
+
* Zero-dependency stdin/stdout JSON helper, `realpathSync` entrypoint resolver,
|
|
4
|
+
* conservative bounded-read fast-path check, and Claude Code hook exit-code contract.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import fs from 'node:fs';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
import { fileURLToPath } from 'node:url';
|
|
10
|
+
|
|
11
|
+
const BOUNDED_READ_TOOL_RE = /^(?:default_api:)?(?:Read|read_file|view_file)$/i;
|
|
12
|
+
const SENSITIVE_SEGMENT_RE =
|
|
13
|
+
/(?:^|[\\/])(?:\.env(?:\.[^\\/]*)?|\.git|\.ssh|\.aws|\.gnupg|\.npmrc|\.pypirc|\.netrc|id_rsa(?:\..*)?|id_dsa(?:\..*)?|id_ecdsa(?:\..*)?|id_ed25519(?:\..*)?|oauth_creds\.json|credentials\.json|[^\\/]*(?:secret|credential|token)[^\\/]*|CLAUDE\.md|AGENTS\.md)(?:[\\/]|$)/i;
|
|
14
|
+
const BINARY_OR_MULTIMODAL_EXT_RE =
|
|
15
|
+
/\.(?:pem|key|pfx|p12|kdbx|keystore|jks|crt|cer|der|ipynb|pdf|png|jpe?g|gif|webp|bmp|ico|mp4|mov|wav|mp3|zip|tar|gz|7z|sqlite3?|db)$/i;
|
|
16
|
+
const TRAVERSAL_SEGMENT_RE = /(?:^|[\\/])\.\.(?:[\\/]|$)/;
|
|
17
|
+
|
|
18
|
+
export function isCliEntrypoint(importMetaUrl, argv1 = globalThis.process?.argv?.[1]) {
|
|
19
|
+
if (!importMetaUrl || !argv1) return false;
|
|
20
|
+
try {
|
|
21
|
+
const modulePath = fileURLToPath(importMetaUrl);
|
|
22
|
+
const targetPath = path.resolve(String(argv1));
|
|
23
|
+
try {
|
|
24
|
+
return fs.realpathSync(modulePath) === fs.realpathSync(targetPath);
|
|
25
|
+
} catch {
|
|
26
|
+
return path.normalize(modulePath) === path.normalize(targetPath);
|
|
27
|
+
}
|
|
28
|
+
} catch {
|
|
29
|
+
return false;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function readStdinJson(options = {}) {
|
|
34
|
+
if (globalThis.process?.stdin?.isTTY) return {};
|
|
35
|
+
let raw = '';
|
|
36
|
+
try {
|
|
37
|
+
raw = fs.readFileSync(0, 'utf8').trim();
|
|
38
|
+
} catch {
|
|
39
|
+
return {};
|
|
40
|
+
}
|
|
41
|
+
if (!raw) return {};
|
|
42
|
+
try {
|
|
43
|
+
const parsed = JSON.parse(raw);
|
|
44
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
|
45
|
+
if (options?.allowMalformed) return {};
|
|
46
|
+
throw new SyntaxError('Stdin JSON payload must be a JSON object');
|
|
47
|
+
}
|
|
48
|
+
return parsed;
|
|
49
|
+
} catch (err) {
|
|
50
|
+
if (options?.allowMalformed) return {};
|
|
51
|
+
throw err;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function readStdinJsonAsync(
|
|
56
|
+
timeoutMs = 2000,
|
|
57
|
+
stdinStream = globalThis.process?.stdin,
|
|
58
|
+
options = {}
|
|
59
|
+
) {
|
|
60
|
+
return new Promise((resolve, reject) => {
|
|
61
|
+
if (!stdinStream || stdinStream.isTTY) {
|
|
62
|
+
resolve({});
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
let raw = '';
|
|
67
|
+
let settled = false;
|
|
68
|
+
|
|
69
|
+
const cleanupStream = () => {
|
|
70
|
+
clearTimeout(timer);
|
|
71
|
+
try {
|
|
72
|
+
stdinStream.removeListener('data', onData);
|
|
73
|
+
stdinStream.removeListener('end', onEnd);
|
|
74
|
+
stdinStream.removeListener('error', onError);
|
|
75
|
+
if (typeof stdinStream.pause === 'function') stdinStream.pause();
|
|
76
|
+
if (typeof stdinStream.unref === 'function') stdinStream.unref();
|
|
77
|
+
} catch (err) {
|
|
78
|
+
void err; // ignore: best-effort stdin stream cleanup
|
|
79
|
+
}
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
const finishResolve = (parsedValue) => {
|
|
83
|
+
if (settled) return;
|
|
84
|
+
settled = true;
|
|
85
|
+
cleanupStream();
|
|
86
|
+
resolve(parsedValue);
|
|
87
|
+
};
|
|
88
|
+
|
|
89
|
+
const finishReject = (err) => {
|
|
90
|
+
if (settled) return;
|
|
91
|
+
settled = true;
|
|
92
|
+
cleanupStream();
|
|
93
|
+
reject(err);
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
const settleFromRaw = () => {
|
|
97
|
+
const trimmed = raw.trim();
|
|
98
|
+
if (!trimmed) {
|
|
99
|
+
finishResolve({});
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
try {
|
|
103
|
+
const obj = JSON.parse(trimmed);
|
|
104
|
+
if (!obj || typeof obj !== 'object' || Array.isArray(obj)) {
|
|
105
|
+
if (options?.allowMalformed) {
|
|
106
|
+
finishResolve({});
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
finishReject(new SyntaxError('Malformed stdin JSON payload: expected JSON object'));
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
finishResolve(obj);
|
|
113
|
+
} catch (err) {
|
|
114
|
+
if (options?.allowMalformed) {
|
|
115
|
+
finishResolve({});
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
finishReject(
|
|
119
|
+
new SyntaxError(`Malformed stdin JSON payload: ${err?.message || String(err)}`)
|
|
120
|
+
);
|
|
121
|
+
}
|
|
122
|
+
};
|
|
123
|
+
|
|
124
|
+
const onData = (chunk) => {
|
|
125
|
+
raw += typeof chunk === 'string' ? chunk : Buffer.from(chunk).toString('utf8');
|
|
126
|
+
};
|
|
127
|
+
const onEnd = () => settleFromRaw();
|
|
128
|
+
const onError = () => finishResolve({});
|
|
129
|
+
|
|
130
|
+
const timer = setTimeout(() => {
|
|
131
|
+
settleFromRaw();
|
|
132
|
+
}, Math.max(10, Number(timeoutMs) || 2000));
|
|
133
|
+
|
|
134
|
+
if (typeof timer.unref === 'function') {
|
|
135
|
+
timer.unref();
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
try {
|
|
139
|
+
if (typeof stdinStream.setEncoding === 'function') {
|
|
140
|
+
stdinStream.setEncoding('utf8');
|
|
141
|
+
}
|
|
142
|
+
stdinStream.on('data', onData);
|
|
143
|
+
stdinStream.on('end', onEnd);
|
|
144
|
+
stdinStream.on('error', onError);
|
|
145
|
+
if (typeof stdinStream.resume === 'function') {
|
|
146
|
+
stdinStream.resume();
|
|
147
|
+
}
|
|
148
|
+
} catch {
|
|
149
|
+
finishResolve({});
|
|
150
|
+
}
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
export function readStdinFastWithMeta({ maxTimeoutMs = 2000, chunkDeadlineMs = 2000, settleMs = 2 } = {}) {
|
|
155
|
+
if (process.stdin.isTTY || process.stdin.readableEnded) {
|
|
156
|
+
return Promise.resolve({ data: {}, empty: true, timedOut: false, malformed: false });
|
|
157
|
+
}
|
|
158
|
+
return new Promise((resolve) => {
|
|
159
|
+
let raw = '';
|
|
160
|
+
let settled = false;
|
|
161
|
+
let sawChunk = false;
|
|
162
|
+
let settleTimer = null;
|
|
163
|
+
const startedAt = Date.now();
|
|
164
|
+
const hardCapMs = Math.max(maxTimeoutMs, chunkDeadlineMs);
|
|
165
|
+
|
|
166
|
+
const finish = (meta) => {
|
|
167
|
+
if (settled) return;
|
|
168
|
+
settled = true;
|
|
169
|
+
clearTimeout(maxTimer);
|
|
170
|
+
if (settleTimer) clearTimeout(settleTimer);
|
|
171
|
+
try {
|
|
172
|
+
process.stdin.pause();
|
|
173
|
+
} catch (err) {
|
|
174
|
+
void err; // ignore: stdin pause failure on settle
|
|
175
|
+
}
|
|
176
|
+
resolve(meta);
|
|
177
|
+
};
|
|
178
|
+
|
|
179
|
+
const tryParse = (timedOut = false) => {
|
|
180
|
+
const trimmed = raw.trim();
|
|
181
|
+
if (!trimmed) {
|
|
182
|
+
return { data: {}, empty: true, timedOut, malformed: false };
|
|
183
|
+
}
|
|
184
|
+
try {
|
|
185
|
+
return { data: JSON.parse(trimmed), empty: false, timedOut, malformed: false };
|
|
186
|
+
} catch (err) {
|
|
187
|
+
try {
|
|
188
|
+
process.stderr.write(
|
|
189
|
+
`[Burnoff hook] Malformed stdin JSON; failing open (${err?.message || 'parse error'}).\n`
|
|
190
|
+
);
|
|
191
|
+
} catch (writeErr) {
|
|
192
|
+
void writeErr; // ignore: best-effort stderr diagnostic
|
|
193
|
+
}
|
|
194
|
+
return { data: {}, empty: false, timedOut, malformed: true };
|
|
195
|
+
}
|
|
196
|
+
};
|
|
197
|
+
|
|
198
|
+
let maxTimer = setTimeout(() => finish(tryParse(true)), maxTimeoutMs);
|
|
199
|
+
process.stdin.setEncoding('utf8');
|
|
200
|
+
process.stdin.on('data', (chunk) => {
|
|
201
|
+
raw += chunk;
|
|
202
|
+
if (!sawChunk && raw.length > 0) {
|
|
203
|
+
sawChunk = true;
|
|
204
|
+
clearTimeout(maxTimer);
|
|
205
|
+
const remaining = Math.max(10, hardCapMs - (Date.now() - startedAt));
|
|
206
|
+
maxTimer = setTimeout(() => finish(tryParse(true)), remaining);
|
|
207
|
+
}
|
|
208
|
+
if (settleTimer) clearTimeout(settleTimer);
|
|
209
|
+
if (raw.trim().endsWith('}')) {
|
|
210
|
+
settleTimer = setTimeout(() => {
|
|
211
|
+
try {
|
|
212
|
+
finish({ data: JSON.parse(raw), empty: false, timedOut: false, malformed: false });
|
|
213
|
+
} catch {
|
|
214
|
+
// wait for remaining chunks
|
|
215
|
+
}
|
|
216
|
+
}, settleMs);
|
|
217
|
+
}
|
|
218
|
+
});
|
|
219
|
+
process.stdin.on('end', () => finish(tryParse(false)));
|
|
220
|
+
process.stdin.on('error', () => finish({ data: {}, empty: true, timedOut: false, malformed: true }));
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
export function readStdinFast(options = {}) {
|
|
225
|
+
return readStdinFastWithMeta(options).then((meta) => meta.data);
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
export function exitPassThrough(exitFn = globalThis.process?.exit) {
|
|
229
|
+
exitFn?.(0);
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
export function exitDiagnosticZero(reason, hookEventName = 'Hook', ioOverride = {}) {
|
|
233
|
+
const writeStderr =
|
|
234
|
+
ioOverride.stderrWrite ||
|
|
235
|
+
ioOverride.writeStderr ||
|
|
236
|
+
((s) => globalThis.process?.stderr?.write?.(s));
|
|
237
|
+
const exitFn = ioOverride.exitFn || globalThis.process?.exit;
|
|
238
|
+
const msg = String(reason || 'Unexpected hook diagnostic').trim();
|
|
239
|
+
writeStderr(`[Burnoff ${hookEventName} Diagnostic] ${msg}\n`);
|
|
240
|
+
exitFn?.(0);
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
export function exitHardBlockStderr(reason, hookEventName = 'PreToolUse', ioOverride = {}) {
|
|
244
|
+
const writeStderr =
|
|
245
|
+
ioOverride.stderrWrite ||
|
|
246
|
+
ioOverride.writeStderr ||
|
|
247
|
+
((s) => globalThis.process?.stderr?.write?.(s));
|
|
248
|
+
const exitFn = ioOverride.exitFn || globalThis.process?.exit;
|
|
249
|
+
|
|
250
|
+
if (hookEventName === 'WorktreeCreate' || hookEventName === 'PermissionRequest') {
|
|
251
|
+
exitPassThrough(exitFn);
|
|
252
|
+
return;
|
|
253
|
+
}
|
|
254
|
+
const msg = String(reason || 'Blocked by Burnoff circuit breaker').trim();
|
|
255
|
+
writeStderr(`${msg}\n`);
|
|
256
|
+
exitFn?.(2);
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
export function exitWithStdoutJson(payload, ioOverride = {}) {
|
|
260
|
+
const writeStdout =
|
|
261
|
+
ioOverride.stdoutWrite ||
|
|
262
|
+
ioOverride.writeStdout ||
|
|
263
|
+
((s) => globalThis.process?.stdout?.write?.(s));
|
|
264
|
+
const exitFn = ioOverride.exitFn || globalThis.process?.exit;
|
|
265
|
+
const serialized = typeof payload === 'string' ? payload : JSON.stringify(payload);
|
|
266
|
+
writeStdout(`${serialized}\n`);
|
|
267
|
+
exitFn?.(0);
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
export function exitWithHookSpecificOutput(hookSpecificOutput, ioOverride = {}) {
|
|
271
|
+
exitWithStdoutJson({ hookSpecificOutput }, ioOverride);
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
export function writeHookStdoutJsonAndExit(payload = {}) {
|
|
275
|
+
let line = '{}\n';
|
|
276
|
+
try {
|
|
277
|
+
line = `${JSON.stringify(payload ?? {})}\n`;
|
|
278
|
+
} catch {
|
|
279
|
+
line = '{}\n';
|
|
280
|
+
}
|
|
281
|
+
try {
|
|
282
|
+
fs.writeSync(1, Buffer.from(line, 'utf8'));
|
|
283
|
+
} catch (err) {
|
|
284
|
+
void err; // ignore: EPIPE/EBADF when caller closed stdout
|
|
285
|
+
}
|
|
286
|
+
process.exit(0);
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
let _cliHookGuardsInstalled = false;
|
|
290
|
+
|
|
291
|
+
export function installCliHookProcessGuards(getFallbackPayload = () => ({})) {
|
|
292
|
+
if (_cliHookGuardsInstalled) return;
|
|
293
|
+
_cliHookGuardsInstalled = true;
|
|
294
|
+
|
|
295
|
+
try {
|
|
296
|
+
process.stdout?.on?.('error', () => {
|
|
297
|
+
// ignore: closed stdout EPIPE
|
|
298
|
+
});
|
|
299
|
+
} catch (err) {
|
|
300
|
+
void err; // ignore: non-fatal stdout guard setup
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
const formatArg = (a) => {
|
|
304
|
+
if (typeof a === 'string') return a;
|
|
305
|
+
if (a instanceof Error) return a.stack || a.message || String(a);
|
|
306
|
+
try {
|
|
307
|
+
return JSON.stringify(a);
|
|
308
|
+
} catch {
|
|
309
|
+
return String(a);
|
|
310
|
+
}
|
|
311
|
+
};
|
|
312
|
+
const redirectToStderr = (...args) => {
|
|
313
|
+
try {
|
|
314
|
+
process.stderr.write(`${args.map(formatArg).join(' ')}\n`);
|
|
315
|
+
} catch (err) {
|
|
316
|
+
void err; // ignore: stderr write guard
|
|
317
|
+
}
|
|
318
|
+
};
|
|
319
|
+
console.log = redirectToStderr;
|
|
320
|
+
console.info = redirectToStderr;
|
|
321
|
+
console.debug = redirectToStderr;
|
|
322
|
+
|
|
323
|
+
let failingOpen = false;
|
|
324
|
+
const failOpen = (kind, err) => {
|
|
325
|
+
if (failingOpen) return;
|
|
326
|
+
failingOpen = true;
|
|
327
|
+
try {
|
|
328
|
+
const msg = String(err?.stack || err?.message || err || 'unknown error').slice(0, 400);
|
|
329
|
+
process.stderr.write(`[Burnoff hook] ${kind}; failing open: ${msg}\n`);
|
|
330
|
+
} catch (writeErr) {
|
|
331
|
+
void writeErr; // ignore: stderr write guard
|
|
332
|
+
}
|
|
333
|
+
let fallback = {};
|
|
334
|
+
try {
|
|
335
|
+
fallback = typeof getFallbackPayload === 'function' ? getFallbackPayload() : {};
|
|
336
|
+
} catch {
|
|
337
|
+
fallback = {};
|
|
338
|
+
}
|
|
339
|
+
writeHookStdoutJsonAndExit(fallback);
|
|
340
|
+
};
|
|
341
|
+
|
|
342
|
+
process.on('uncaughtException', (err) => failOpen('uncaughtException', err));
|
|
343
|
+
process.on('unhandledRejection', (err) => failOpen('unhandledRejection', err));
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
export function recordHookTrace(eventName, payload = {}, details = {}) {
|
|
347
|
+
const tracePath = details.tracePath || globalThis.process?.env?.BURNOFF_HOOK_TRACE_PATH || '';
|
|
348
|
+
if (!tracePath) return;
|
|
349
|
+
const entry = {
|
|
350
|
+
ts: Date.now(),
|
|
351
|
+
event: String(eventName || 'Hook'),
|
|
352
|
+
tool: String(payload?.tool_name || payload?.toolName || ''),
|
|
353
|
+
outcome: String(details.outcome || 'pass_through'),
|
|
354
|
+
path: String(details.path || 'core'),
|
|
355
|
+
exitCode: Number.isFinite(Number(details.exitCode)) ? Number(details.exitCode) : 0
|
|
356
|
+
};
|
|
357
|
+
if (details.error) {
|
|
358
|
+
entry.error = String(details.error).replace(/\s+/g, ' ').slice(0, 160);
|
|
359
|
+
}
|
|
360
|
+
const line = `${JSON.stringify(entry)}\n`;
|
|
361
|
+
try {
|
|
362
|
+
fs.appendFileSync(tracePath, line, 'utf8');
|
|
363
|
+
} catch (err) {
|
|
364
|
+
if (err?.code === 'ENOENT') {
|
|
365
|
+
try {
|
|
366
|
+
fs.mkdirSync(path.dirname(tracePath), { recursive: true });
|
|
367
|
+
fs.appendFileSync(tracePath, line, 'utf8');
|
|
368
|
+
} catch (retryErr) {
|
|
369
|
+
void retryErr; // ignore: optional hook trace write must never break hook execution
|
|
370
|
+
}
|
|
371
|
+
} else {
|
|
372
|
+
void err; // ignore: optional hook trace write must never break hook execution
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
/**
|
|
378
|
+
* Conservative fast-path check for explicitly bounded workspace source file reads.
|
|
379
|
+
* Returns `false` whenever any active guard, lock, breaker failure state, policy file,
|
|
380
|
+
* or read-interval overlap could require full evaluation.
|
|
381
|
+
*/
|
|
382
|
+
export function canFastAllowBoundedRead(payload = {}, { cwd = '' } = {}) {
|
|
383
|
+
if (!payload || typeof payload !== 'object') return false;
|
|
384
|
+
if (payload.shieldForceActive || payload.shieldConfig || payload.consecutiveFailures) {
|
|
385
|
+
return false;
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
const toolName = String(payload.tool_name || payload.toolName || payload.toolCall?.name || '');
|
|
389
|
+
if (!BOUNDED_READ_TOOL_RE.test(toolName)) return false;
|
|
390
|
+
|
|
391
|
+
const tIn = payload.tool_input || payload.toolInput || payload.args || payload.toolArgs || payload.toolCall?.args || {};
|
|
392
|
+
if (!tIn || typeof tIn !== 'object') return false;
|
|
393
|
+
|
|
394
|
+
const hasBounds =
|
|
395
|
+
(tIn.StartLine !== undefined && tIn.StartLine !== null) ||
|
|
396
|
+
(tIn.start_line !== undefined && tIn.start_line !== null) ||
|
|
397
|
+
(tIn.EndLine !== undefined && tIn.EndLine !== null) ||
|
|
398
|
+
(tIn.end_line !== undefined && tIn.end_line !== null) ||
|
|
399
|
+
(tIn.offset !== undefined && tIn.offset !== null) ||
|
|
400
|
+
(tIn.limit !== undefined && tIn.limit !== null);
|
|
401
|
+
if (!hasBounds) return false;
|
|
402
|
+
|
|
403
|
+
const limitNum = Number(tIn.limit);
|
|
404
|
+
const startNum = Number(tIn.StartLine ?? tIn.start_line);
|
|
405
|
+
const endNum = Number(tIn.EndLine ?? tIn.end_line);
|
|
406
|
+
if (
|
|
407
|
+
(Number.isFinite(limitNum) && limitNum > 150) ||
|
|
408
|
+
(Number.isFinite(startNum) && Number.isFinite(endNum) && endNum - startNum + 1 > 150)
|
|
409
|
+
) {
|
|
410
|
+
return false;
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
const rawPath = String(
|
|
414
|
+
tIn.file_path || tIn.Path || tIn.AbsolutePath || tIn.path || tIn.TargetFile || ''
|
|
415
|
+
).trim();
|
|
416
|
+
if (!rawPath || rawPath.includes('\0') || TRAVERSAL_SEGMENT_RE.test(rawPath)) {
|
|
417
|
+
return false;
|
|
418
|
+
}
|
|
419
|
+
if (SENSITIVE_SEGMENT_RE.test(rawPath) || BINARY_OR_MULTIMODAL_EXT_RE.test(rawPath)) {
|
|
420
|
+
return false;
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
const rawCwd =
|
|
424
|
+
cwd ||
|
|
425
|
+
payload.cwd ||
|
|
426
|
+
(Array.isArray(payload.workspacePaths) && payload.workspacePaths[0]) ||
|
|
427
|
+
payload.workspacePath ||
|
|
428
|
+
process.cwd();
|
|
429
|
+
const baseCwd = path.resolve(String(rawCwd || process.cwd()));
|
|
430
|
+
|
|
431
|
+
if (path.isAbsolute(rawPath)) {
|
|
432
|
+
const resolvedTarget = path.resolve(rawPath);
|
|
433
|
+
const rel = path.relative(baseCwd, resolvedTarget);
|
|
434
|
+
if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) {
|
|
435
|
+
return false;
|
|
436
|
+
}
|
|
437
|
+
if (SENSITIVE_SEGMENT_RE.test(rel) || BINARY_OR_MULTIMODAL_EXT_RE.test(rel)) {
|
|
438
|
+
return false;
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
if (
|
|
443
|
+
fs.existsSync(path.join(baseCwd, '.burnoff.yaml')) ||
|
|
444
|
+
fs.existsSync(path.join(baseCwd, '.burnoff.yml'))
|
|
445
|
+
) {
|
|
446
|
+
return false;
|
|
447
|
+
}
|
|
448
|
+
if (fs.existsSync(path.join(baseCwd, '.claude', 'locks', 'active_scopes.json'))) {
|
|
449
|
+
return false;
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
const sessionId = String(payload.session_id || payload.sessionId || 'default');
|
|
453
|
+
const safeSid = sessionId.replace(/[^a-zA-Z0-9._-]/g, '_').slice(0, 80) || 'default';
|
|
454
|
+
const breakerPath = path.join(baseCwd, '.claude', 'cache', `burnoff_breaker_state_${safeSid}.json`);
|
|
455
|
+
if (fs.existsSync(breakerPath)) {
|
|
456
|
+
return false;
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
const snapPath = path.join(baseCwd, '.claude', 'cache', `read_snapshots_${safeSid.slice(0, 64)}.json`);
|
|
460
|
+
if (fs.existsSync(snapPath)) {
|
|
461
|
+
try {
|
|
462
|
+
const snap = JSON.parse(fs.readFileSync(snapPath, 'utf8'));
|
|
463
|
+
const absTarget = path.isAbsolute(rawPath) ? path.resolve(rawPath) : path.resolve(baseCwd, rawPath);
|
|
464
|
+
const normKey = absTarget.replace(/\\/g, '/').toLowerCase();
|
|
465
|
+
const entry = snap?.__readIntervals?.[normKey];
|
|
466
|
+
if (entry && Array.isArray(entry.intervals) && entry.intervals.length > 0) {
|
|
467
|
+
const reqStart = Math.max(1, Math.floor(Number(tIn.offset ?? tIn.StartLine ?? tIn.start_line ?? 1)));
|
|
468
|
+
const reqLimit = Number(tIn.limit);
|
|
469
|
+
const reqEnd =
|
|
470
|
+
Number.isFinite(reqLimit) && reqLimit > 0
|
|
471
|
+
? reqStart + Math.floor(reqLimit) - 1
|
|
472
|
+
: Math.max(reqStart, Math.floor(Number(tIn.EndLine ?? tIn.end_line ?? reqStart)));
|
|
473
|
+
const hasOverlap = entry.intervals.some(
|
|
474
|
+
(iv) => Array.isArray(iv) && iv.length >= 2 && reqStart <= iv[1] && reqEnd >= iv[0]
|
|
475
|
+
);
|
|
476
|
+
if (hasOverlap) {
|
|
477
|
+
return false;
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
} catch {
|
|
481
|
+
return false;
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
return true;
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
export function tryTier1PreToolFastPath(event = {}, options = {}) {
|
|
489
|
+
const toolName = String(event?.tool_name || event?.toolName || '');
|
|
490
|
+
const tier1Active = Boolean(
|
|
491
|
+
options?.tier1Active ||
|
|
492
|
+
event?.tier1Active ||
|
|
493
|
+
globalThis.process?.env?.BURNOFF_TIER1_ACTIVE === '1'
|
|
494
|
+
);
|
|
495
|
+
if (tier1Active && /^(?:Grep|Glob)$/i.test(toolName)) {
|
|
496
|
+
return {
|
|
497
|
+
exitCode: 0,
|
|
498
|
+
stdout: '',
|
|
499
|
+
stderr: '',
|
|
500
|
+
fastPath: 'tier1_active',
|
|
501
|
+
verdict: { triggered: false, decision: 'allow', reason: 'Handled via Tier-1 fast path' }
|
|
502
|
+
};
|
|
503
|
+
}
|
|
504
|
+
return null;
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
function extractFastPostToolText(event = {}) {
|
|
508
|
+
const resp = event.tool_response ?? event.tool_output ?? event.toolOutput ?? event.output;
|
|
509
|
+
if (typeof resp === 'string') return resp;
|
|
510
|
+
if (resp && typeof resp === 'object') {
|
|
511
|
+
const parts = [resp.stdout, resp.stderr, resp.output, resp.content, resp.error]
|
|
512
|
+
.filter((x) => typeof x === 'string' && x.length > 0);
|
|
513
|
+
if (parts.length > 0) return parts.join('\n');
|
|
514
|
+
return '';
|
|
515
|
+
}
|
|
516
|
+
return resp !== undefined && resp !== null ? String(resp) : '';
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
function didFastToolExecutionFail(event = {}) {
|
|
520
|
+
if (
|
|
521
|
+
event.is_error === true ||
|
|
522
|
+
event.isError === true ||
|
|
523
|
+
event.succeeded === false ||
|
|
524
|
+
Boolean(event.tool_error || event.error) ||
|
|
525
|
+
(typeof event.exit_code === 'number' && event.exit_code !== 0) ||
|
|
526
|
+
(typeof event.exitCode === 'number' && event.exitCode !== 0)
|
|
527
|
+
) {
|
|
528
|
+
return true;
|
|
529
|
+
}
|
|
530
|
+
const resp = event.tool_response;
|
|
531
|
+
if (resp && typeof resp === 'object') {
|
|
532
|
+
if (
|
|
533
|
+
resp.is_error === true ||
|
|
534
|
+
resp.isError === true ||
|
|
535
|
+
resp.succeeded === false ||
|
|
536
|
+
resp.status === 'error' ||
|
|
537
|
+
resp.status === 'failed' ||
|
|
538
|
+
Boolean(resp.error) ||
|
|
539
|
+
(typeof resp.exit_code === 'number' && resp.exit_code !== 0) ||
|
|
540
|
+
(typeof resp.exitCode === 'number' && resp.exitCode !== 0) ||
|
|
541
|
+
(typeof resp.returncode === 'number' && resp.returncode !== 0)
|
|
542
|
+
) {
|
|
543
|
+
return true;
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
return false;
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
export function tryTier1PostToolFastPath(event = {}, options = {}) {
|
|
550
|
+
const toolName = String(event?.tool_name || event?.toolName || 'Bash');
|
|
551
|
+
const tier1Active = Boolean(
|
|
552
|
+
options?.tier1Active ||
|
|
553
|
+
event?.tier1Active ||
|
|
554
|
+
globalThis.process?.env?.BURNOFF_TIER1_ACTIVE === '1'
|
|
555
|
+
);
|
|
556
|
+
if (
|
|
557
|
+
tier1Active &&
|
|
558
|
+
/^(?:Grep|Glob)$/i.test(toolName) &&
|
|
559
|
+
extractFastPostToolText(event).length < 16_000 &&
|
|
560
|
+
!didFastToolExecutionFail(event)
|
|
561
|
+
) {
|
|
562
|
+
return {
|
|
563
|
+
exitCode: 0,
|
|
564
|
+
stdout: '',
|
|
565
|
+
stderr: '',
|
|
566
|
+
fastPath: 'tier1_active',
|
|
567
|
+
sanitized: { modified: false, offloaded: false, savedTokens: 0 }
|
|
568
|
+
};
|
|
569
|
+
}
|
|
570
|
+
return null;
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
export default {
|
|
574
|
+
isCliEntrypoint,
|
|
575
|
+
readStdinJson,
|
|
576
|
+
readStdinJsonAsync,
|
|
577
|
+
readStdinFastWithMeta,
|
|
578
|
+
readStdinFast,
|
|
579
|
+
exitPassThrough,
|
|
580
|
+
exitDiagnosticZero,
|
|
581
|
+
exitHardBlockStderr,
|
|
582
|
+
exitWithStdoutJson,
|
|
583
|
+
exitWithHookSpecificOutput,
|
|
584
|
+
writeHookStdoutJsonAndExit,
|
|
585
|
+
installCliHookProcessGuards,
|
|
586
|
+
recordHookTrace,
|
|
587
|
+
canFastAllowBoundedRead,
|
|
588
|
+
tryTier1PreToolFastPath,
|
|
589
|
+
tryTier1PostToolFastPath
|
|
590
|
+
};
|
package/hooks/hooks.json
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
{
|
|
2
|
+
"hooks": {
|
|
3
|
+
"PreToolUse": [
|
|
4
|
+
{ "matcher": "Bash|PowerShell|Edit|MultiEdit|Write|NotebookEdit|Read|Grep|Glob|Task|Agent|WebFetch|mcp__.*",
|
|
5
|
+
"hooks": [{ "type": "command", "command": "node \"hooks/pre-tool-use.mjs\"", "timeout": 5 }] }
|
|
6
|
+
],
|
|
7
|
+
"PostToolUse": [
|
|
8
|
+
{ "matcher": "Bash|PowerShell|Grep|Glob|Task|Agent|WebFetch|mcp__.*",
|
|
9
|
+
"hooks": [{ "type": "command", "command": "node \"hooks/post-tool-use.mjs\"", "timeout": 5 }] }
|
|
10
|
+
]
|
|
11
|
+
}
|
|
12
|
+
}
|