burnoff 1.4.0 → 1.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/hooks/hook-io.mjs CHANGED
@@ -1,599 +1,691 @@
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
- import { getWorkspaceStateDir } from '../src/config/paths.mjs';
11
-
12
- const BOUNDED_READ_TOOL_RE = /^(?:Read|read_file|view_file)$/i;
13
- const SENSITIVE_SEGMENT_RE =
14
- /(?:^|[\\/])(?:\.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;
15
- const BINARY_OR_MULTIMODAL_EXT_RE =
16
- /\.(?: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;
17
- const TRAVERSAL_SEGMENT_RE = /(?:^|[\\/])\.\.(?:[\\/]|$)/;
18
-
19
- export function isCliEntrypoint(importMetaUrl, argv1 = globalThis.process?.argv?.[1]) {
20
- if (!importMetaUrl || !argv1) return false;
21
- try {
22
- const modulePath = fileURLToPath(importMetaUrl);
23
- const targetPath = path.resolve(String(argv1));
24
- try {
25
- return fs.realpathSync(modulePath) === fs.realpathSync(targetPath);
26
- } catch {
27
- return path.normalize(modulePath) === path.normalize(targetPath);
28
- }
29
- } catch {
30
- return false;
31
- }
32
- }
33
-
34
- export function readStdinJson(options = {}) {
35
- if (globalThis.process?.stdin?.isTTY) return {};
36
- let raw = '';
37
- try {
38
- raw = fs.readFileSync(0, 'utf8').trim();
39
- } catch {
40
- return {};
41
- }
42
- if (!raw) return {};
43
- try {
44
- const parsed = JSON.parse(raw);
45
- if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
46
- if (options?.allowMalformed) return {};
47
- throw new SyntaxError('Stdin JSON payload must be a JSON object');
48
- }
49
- return parsed;
50
- } catch (err) {
51
- if (options?.allowMalformed) return {};
52
- throw err;
53
- }
54
- }
55
-
56
- export function readStdinJsonAsync(
57
- timeoutMs = 2000,
58
- stdinStream = globalThis.process?.stdin,
59
- options = {}
60
- ) {
61
- return new Promise((resolve, reject) => {
62
- if (!stdinStream || stdinStream.isTTY) {
63
- resolve({});
64
- return;
65
- }
66
-
67
- let raw = '';
68
- let settled = false;
69
-
70
- const cleanupStream = () => {
71
- clearTimeout(timer);
72
- try {
73
- stdinStream.removeListener('data', onData);
74
- stdinStream.removeListener('end', onEnd);
75
- stdinStream.removeListener('error', onError);
76
- if (typeof stdinStream.pause === 'function') stdinStream.pause();
77
- if (typeof stdinStream.unref === 'function') stdinStream.unref();
78
- } catch (err) {
79
- void err; // ignore: best-effort stdin stream cleanup
80
- }
81
- };
82
-
83
- const finishResolve = (parsedValue) => {
84
- if (settled) return;
85
- settled = true;
86
- cleanupStream();
87
- resolve(parsedValue);
88
- };
89
-
90
- const finishReject = (err) => {
91
- if (settled) return;
92
- settled = true;
93
- cleanupStream();
94
- reject(err);
95
- };
96
-
97
- const settleFromRaw = () => {
98
- const trimmed = raw.trim();
99
- if (!trimmed) {
100
- finishResolve({});
101
- return;
102
- }
103
- try {
104
- const obj = JSON.parse(trimmed);
105
- if (!obj || typeof obj !== 'object' || Array.isArray(obj)) {
106
- if (options?.allowMalformed) {
107
- finishResolve({});
108
- return;
109
- }
110
- finishReject(new SyntaxError('Malformed stdin JSON payload: expected JSON object'));
111
- return;
112
- }
113
- finishResolve(obj);
114
- } catch (err) {
115
- if (options?.allowMalformed) {
116
- finishResolve({});
117
- return;
118
- }
119
- finishReject(
120
- new SyntaxError(`Malformed stdin JSON payload: ${err?.message || String(err)}`)
121
- );
122
- }
123
- };
124
-
125
- const onData = (chunk) => {
126
- raw += typeof chunk === 'string' ? chunk : Buffer.from(chunk).toString('utf8');
127
- };
128
- const onEnd = () => settleFromRaw();
129
- const onError = () => finishResolve({});
130
-
131
- const timer = setTimeout(() => {
132
- settleFromRaw();
133
- }, Math.max(10, Number(timeoutMs) || 2000));
134
-
135
- if (typeof timer.unref === 'function') {
136
- timer.unref();
137
- }
138
-
139
- try {
140
- if (typeof stdinStream.setEncoding === 'function') {
141
- stdinStream.setEncoding('utf8');
142
- }
143
- stdinStream.on('data', onData);
144
- stdinStream.on('end', onEnd);
145
- stdinStream.on('error', onError);
146
- if (typeof stdinStream.resume === 'function') {
147
- stdinStream.resume();
148
- }
149
- } catch {
150
- finishResolve({});
151
- }
152
- });
153
- }
154
-
155
- export function readStdinFastWithMeta({ maxTimeoutMs = 2000, chunkDeadlineMs = 2000, settleMs = 2 } = {}) {
156
- if (process.stdin.isTTY || process.stdin.readableEnded) {
157
- return Promise.resolve({ data: {}, empty: true, timedOut: false, malformed: false });
158
- }
159
- return new Promise((resolve) => {
160
- let raw = '';
161
- let settled = false;
162
- let sawChunk = false;
163
- let settleTimer = null;
164
- const startedAt = Date.now();
165
- const hardCapMs = Math.max(maxTimeoutMs, chunkDeadlineMs);
166
-
167
- const finish = (meta) => {
168
- if (settled) return;
169
- settled = true;
170
- clearTimeout(maxTimer);
171
- if (settleTimer) clearTimeout(settleTimer);
172
- try {
173
- process.stdin.pause();
174
- } catch (err) {
175
- void err; // ignore: stdin pause failure on settle
176
- }
177
- resolve(meta);
178
- };
179
-
180
- const tryParse = (timedOut = false) => {
181
- const trimmed = raw.trim();
182
- if (!trimmed) {
183
- return { data: {}, empty: true, timedOut, malformed: false };
184
- }
185
- try {
186
- return { data: JSON.parse(trimmed), empty: false, timedOut, malformed: false };
187
- } catch (err) {
188
- try {
189
- process.stderr.write(
190
- `[Burnoff hook] Malformed stdin JSON; failing open (${err?.message || 'parse error'}).\n`
191
- );
192
- } catch (writeErr) {
193
- void writeErr; // ignore: best-effort stderr diagnostic
194
- }
195
- return { data: {}, empty: false, timedOut, malformed: true };
196
- }
197
- };
198
-
199
- let maxTimer = setTimeout(() => finish(tryParse(true)), maxTimeoutMs);
200
- process.stdin.setEncoding('utf8');
201
- process.stdin.on('data', (chunk) => {
202
- raw += chunk;
203
- if (!sawChunk && raw.length > 0) {
204
- sawChunk = true;
205
- clearTimeout(maxTimer);
206
- const remaining = Math.max(10, hardCapMs - (Date.now() - startedAt));
207
- maxTimer = setTimeout(() => finish(tryParse(true)), remaining);
208
- }
209
- if (settleTimer) clearTimeout(settleTimer);
210
- if (raw.trim().endsWith('}')) {
211
- settleTimer = setTimeout(() => {
212
- try {
213
- finish({ data: JSON.parse(raw), empty: false, timedOut: false, malformed: false });
214
- } catch {
215
- // wait for remaining chunks
216
- }
217
- }, settleMs);
218
- }
219
- });
220
- process.stdin.on('end', () => finish(tryParse(false)));
221
- process.stdin.on('error', () => finish({ data: {}, empty: true, timedOut: false, malformed: true }));
222
- });
223
- }
224
-
225
- export function readStdinFast(options = {}) {
226
- return readStdinFastWithMeta(options).then((meta) => meta.data);
227
- }
228
-
229
- export function exitPassThrough(exitFn = globalThis.process?.exit) {
230
- exitFn?.(0);
231
- }
232
-
233
- export function exitDiagnosticZero(reason, hookEventName = 'Hook', ioOverride = {}) {
234
- const writeStderr =
235
- ioOverride.stderrWrite ||
236
- ioOverride.writeStderr ||
237
- ((s) => globalThis.process?.stderr?.write?.(s));
238
- const exitFn = ioOverride.exitFn || globalThis.process?.exit;
239
- const msg = String(reason || 'Unexpected hook diagnostic').trim();
240
- writeStderr(`[Burnoff ${hookEventName} Diagnostic] ${msg}\n`);
241
- exitFn?.(0);
242
- }
243
-
244
- export function exitHardBlockStderr(reason, hookEventName = 'PreToolUse', ioOverride = {}) {
245
- const writeStderr =
246
- ioOverride.stderrWrite ||
247
- ioOverride.writeStderr ||
248
- ((s) => globalThis.process?.stderr?.write?.(s));
249
- const exitFn = ioOverride.exitFn || globalThis.process?.exit;
250
-
251
- if (hookEventName === 'WorktreeCreate' || hookEventName === 'PermissionRequest') {
252
- exitPassThrough(exitFn);
253
- return;
254
- }
255
- const msg = String(reason || 'Blocked by Burnoff circuit breaker').trim();
256
- writeStderr(`${msg}\n`);
257
- exitFn?.(2);
258
- }
259
-
260
- export function exitWithStdoutJson(payload, ioOverride = {}) {
261
- const writeStdout =
262
- ioOverride.stdoutWrite ||
263
- ioOverride.writeStdout ||
264
- ((s) => globalThis.process?.stdout?.write?.(s));
265
- const exitFn = ioOverride.exitFn || globalThis.process?.exit;
266
- const serialized = typeof payload === 'string' ? payload : JSON.stringify(payload);
267
- writeStdout(`${serialized}\n`);
268
- exitFn?.(0);
269
- }
270
-
271
- export function exitWithHookSpecificOutput(hookSpecificOutput, ioOverride = {}) {
272
- exitWithStdoutJson({ hookSpecificOutput }, ioOverride);
273
- }
274
-
275
- export function writeHookStdoutJsonAndExit(payload = {}) {
276
- let line = '{}\n';
277
- try {
278
- line = `${JSON.stringify(payload ?? {})}\n`;
279
- } catch {
280
- line = '{}\n';
281
- }
282
- try {
283
- fs.writeSync(1, Buffer.from(line, 'utf8'));
284
- } catch (err) {
285
- void err; // ignore: EPIPE/EBADF when caller closed stdout
286
- }
287
- process.exit(0);
288
- }
289
-
290
- let _cliHookGuardsInstalled = false;
291
-
292
- export function installCliHookProcessGuards(getFallbackPayload = () => ({})) {
293
- if (_cliHookGuardsInstalled) return;
294
- _cliHookGuardsInstalled = true;
295
-
296
- try {
297
- process.stdout?.on?.('error', () => {
298
- // ignore: closed stdout EPIPE
299
- });
300
- } catch (err) {
301
- void err; // ignore: non-fatal stdout guard setup
302
- }
303
-
304
- const formatArg = (a) => {
305
- if (typeof a === 'string') return a;
306
- if (a instanceof Error) return a.stack || a.message || String(a);
307
- try {
308
- return JSON.stringify(a);
309
- } catch {
310
- return String(a);
311
- }
312
- };
313
- const redirectToStderr = (...args) => {
314
- try {
315
- process.stderr.write(`${args.map(formatArg).join(' ')}\n`);
316
- } catch (err) {
317
- void err; // ignore: stderr write guard
318
- }
319
- };
320
- console.log = redirectToStderr;
321
- console.info = redirectToStderr;
322
- console.debug = redirectToStderr;
323
-
324
- let failingOpen = false;
325
- const failOpen = (kind, err) => {
326
- if (failingOpen) return;
327
- failingOpen = true;
328
- try {
329
- const msg = String(err?.stack || err?.message || err || 'unknown error').slice(0, 400);
330
- process.stderr.write(`[Burnoff hook] ${kind}; failing open: ${msg}\n`);
331
- } catch (writeErr) {
332
- void writeErr; // ignore: stderr write guard
333
- }
334
- let fallback = {};
335
- try {
336
- fallback = typeof getFallbackPayload === 'function' ? getFallbackPayload() : {};
337
- } catch {
338
- fallback = {};
339
- }
340
- writeHookStdoutJsonAndExit(fallback);
341
- };
342
-
343
- process.on('uncaughtException', (err) => failOpen('uncaughtException', err));
344
- process.on('unhandledRejection', (err) => failOpen('unhandledRejection', err));
345
- }
346
-
347
- export function recordHookTrace(eventName, payload = {}, details = {}) {
348
- const tracePath = details.tracePath || globalThis.process?.env?.BURNOFF_HOOK_TRACE_PATH || '';
349
- if (!tracePath) return;
350
- const entry = {
351
- ts: Date.now(),
352
- event: String(eventName || 'Hook'),
353
- tool: String(payload?.tool_name || payload?.toolName || ''),
354
- outcome: String(details.outcome || 'pass_through'),
355
- path: String(details.path || 'core'),
356
- exitCode: Number.isFinite(Number(details.exitCode)) ? Number(details.exitCode) : 0
357
- };
358
- if (details.error) {
359
- entry.error = String(details.error).replace(/\s+/g, ' ').slice(0, 160);
360
- }
361
- const line = `${JSON.stringify(entry)}\n`;
362
- try {
363
- fs.appendFileSync(tracePath, line, 'utf8');
364
- } catch (err) {
365
- if (err?.code === 'ENOENT') {
366
- try {
367
- fs.mkdirSync(path.dirname(tracePath), { recursive: true });
368
- fs.appendFileSync(tracePath, line, 'utf8');
369
- } catch (retryErr) {
370
- void retryErr; // ignore: optional hook trace write must never break hook execution
371
- }
372
- } else {
373
- void err; // ignore: optional hook trace write must never break hook execution
374
- }
375
- }
376
- }
377
-
378
- /**
379
- * Conservative fast-path check for explicitly bounded workspace source file reads.
380
- * Returns `false` whenever any active guard, lock, breaker failure state, policy file,
381
- * or read-interval overlap could require full evaluation.
382
- */
383
- export function canFastAllowBoundedRead(payload = {}, { cwd = '', homeDir = null } = {}) {
384
- if (!payload || typeof payload !== 'object') return false;
385
- if (payload.shieldForceActive || payload.shieldConfig || payload.consecutiveFailures) {
386
- return false;
387
- }
388
-
389
- const toolName = String(payload.tool_name || payload.toolName || payload.toolCall?.name || '');
390
- if (!BOUNDED_READ_TOOL_RE.test(toolName)) return false;
391
-
392
- const tIn = payload.tool_input || payload.toolInput || payload.args || payload.toolArgs || payload.toolCall?.args || {};
393
- if (!tIn || typeof tIn !== 'object') return false;
394
-
395
- const hasUpperLimit =
396
- (tIn.limit !== undefined && tIn.limit !== null) ||
397
- ((tIn.StartLine !== undefined || tIn.start_line !== undefined) &&
398
- (tIn.EndLine !== undefined || tIn.end_line !== undefined));
399
- if (!hasUpperLimit) return false;
400
-
401
- const limitNum = Number(tIn.limit);
402
- const startNum = Number(tIn.StartLine ?? tIn.start_line);
403
- const endNum = Number(tIn.EndLine ?? tIn.end_line);
404
- if (
405
- (tIn.limit !== undefined && tIn.limit !== null && (!Number.isFinite(limitNum) || limitNum <= 0 || limitNum > 150)) ||
406
- (Number.isFinite(startNum) && Number.isFinite(endNum) && (endNum < startNum || endNum - startNum + 1 > 150))
407
- ) {
408
- return false;
409
- }
410
-
411
- const rawPath = String(
412
- tIn.file_path || tIn.Path || tIn.AbsolutePath || tIn.path || tIn.TargetFile || ''
413
- ).trim();
414
- if (!rawPath || rawPath.includes('\0') || TRAVERSAL_SEGMENT_RE.test(rawPath)) {
415
- return false;
416
- }
417
- if (SENSITIVE_SEGMENT_RE.test(rawPath) || BINARY_OR_MULTIMODAL_EXT_RE.test(rawPath)) {
418
- return false;
419
- }
420
-
421
- const rawCwd =
422
- cwd ||
423
- payload.cwd ||
424
- (Array.isArray(payload.workspacePaths) && payload.workspacePaths[0]) ||
425
- payload.workspacePath ||
426
- process.cwd();
427
- const baseCwd = path.resolve(String(rawCwd || process.cwd()));
428
-
429
- if (path.isAbsolute(rawPath)) {
430
- const resolvedTarget = path.resolve(rawPath);
431
- const rel = path.relative(baseCwd, resolvedTarget);
432
- if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) {
433
- return false;
434
- }
435
- if (SENSITIVE_SEGMENT_RE.test(rel) || BINARY_OR_MULTIMODAL_EXT_RE.test(rel)) {
436
- return false;
437
- }
438
- }
439
-
440
- if (
441
- fs.existsSync(path.join(baseCwd, '.burnoff.yaml')) ||
442
- fs.existsSync(path.join(baseCwd, '.burnoff.yml'))
443
- ) {
444
- return false;
445
- }
446
-
447
- const wsStateDir = getWorkspaceStateDir(baseCwd, homeDir);
448
- if (
449
- fs.existsSync(path.join(baseCwd, '.claude', 'locks', 'active_scopes.json')) ||
450
- fs.existsSync(path.join(wsStateDir, 'active_scopes.json'))
451
- ) {
452
- return false;
453
- }
454
-
455
- const sessionId = String(payload.session_id || payload.sessionId || payload.conversationId || 'default');
456
- const safeSid = sessionId.replace(/[^a-zA-Z0-9._-]/g, '_').slice(0, 80) || 'default';
457
- if (
458
- fs.existsSync(path.join(baseCwd, '.claude', 'cache', `burnoff_breaker_state_${safeSid}.json`)) ||
459
- fs.existsSync(path.join(wsStateDir, `burnoff_breaker_state_${safeSid}.json`))
460
- ) {
461
- return false;
462
- }
463
-
464
- const snapCandidates = [
465
- path.join(baseCwd, '.claude', 'cache', `read_snapshots_${safeSid.slice(0, 64)}.json`),
466
- path.join(wsStateDir, `read_snapshots_${safeSid.slice(0, 64)}.json`)
467
- ];
468
- for (const snapPath of snapCandidates) {
469
- if (!fs.existsSync(snapPath)) continue;
470
- try {
471
- const snap = JSON.parse(fs.readFileSync(snapPath, 'utf8'));
472
- const absTarget = path.isAbsolute(rawPath) ? path.resolve(rawPath) : path.resolve(baseCwd, rawPath);
473
- const normKey = absTarget.replace(/\\/g, '/').toLowerCase();
474
- const entry = snap?.__readIntervals?.[normKey];
475
- if (entry && Array.isArray(entry.intervals) && entry.intervals.length > 0) {
476
- const reqStart = Math.max(1, Math.floor(Number(tIn.offset ?? tIn.StartLine ?? tIn.start_line ?? 1)));
477
- const reqLimit = Number(tIn.limit);
478
- const reqEnd =
479
- Number.isFinite(reqLimit) && reqLimit > 0
480
- ? reqStart + Math.floor(reqLimit) - 1
481
- : Math.max(reqStart, Math.floor(Number(tIn.EndLine ?? tIn.end_line ?? reqStart)));
482
- const hasOverlap = entry.intervals.some(
483
- (iv) => Array.isArray(iv) && iv.length >= 2 && reqStart <= iv[1] && reqEnd >= iv[0]
484
- );
485
- if (hasOverlap) {
486
- return false;
487
- }
488
- }
489
- } catch {
490
- return false;
491
- }
492
- }
493
-
494
- return true;
495
- }
496
-
497
- export function tryTier1PreToolFastPath(event = {}, options = {}) {
498
- const toolName = String(event?.tool_name || event?.toolName || '');
499
- const tier1Active = Boolean(
500
- options?.tier1Active ||
501
- event?.tier1Active ||
502
- globalThis.process?.env?.BURNOFF_TIER1_ACTIVE === '1'
503
- );
504
- if (tier1Active && /^(?:Grep|Glob)$/i.test(toolName)) {
505
- return {
506
- exitCode: 0,
507
- stdout: '',
508
- stderr: '',
509
- fastPath: 'tier1_active',
510
- verdict: { triggered: false, decision: 'allow', reason: 'Handled via Tier-1 fast path' }
511
- };
512
- }
513
- return null;
514
- }
515
-
516
- function extractFastPostToolText(event = {}) {
517
- const resp = event.tool_response ?? event.tool_output ?? event.toolOutput ?? event.output;
518
- if (typeof resp === 'string') return resp;
519
- if (resp && typeof resp === 'object') {
520
- const parts = [resp.stdout, resp.stderr, resp.output, resp.content, resp.error]
521
- .filter((x) => typeof x === 'string' && x.length > 0);
522
- if (parts.length > 0) return parts.join('\n');
523
- return '';
524
- }
525
- return resp !== undefined && resp !== null ? String(resp) : '';
526
- }
527
-
528
- function didFastToolExecutionFail(event = {}) {
529
- if (
530
- event.is_error === true ||
531
- event.isError === true ||
532
- event.succeeded === false ||
533
- Boolean(event.tool_error || event.error) ||
534
- (typeof event.exit_code === 'number' && event.exit_code !== 0) ||
535
- (typeof event.exitCode === 'number' && event.exitCode !== 0)
536
- ) {
537
- return true;
538
- }
539
- const resp = event.tool_response;
540
- if (resp && typeof resp === 'object') {
541
- if (
542
- resp.is_error === true ||
543
- resp.isError === true ||
544
- resp.succeeded === false ||
545
- resp.status === 'error' ||
546
- resp.status === 'failed' ||
547
- Boolean(resp.error) ||
548
- (typeof resp.exit_code === 'number' && resp.exit_code !== 0) ||
549
- (typeof resp.exitCode === 'number' && resp.exitCode !== 0) ||
550
- (typeof resp.returncode === 'number' && resp.returncode !== 0)
551
- ) {
552
- return true;
553
- }
554
- }
555
- return false;
556
- }
557
-
558
- export function tryTier1PostToolFastPath(event = {}, options = {}) {
559
- const toolName = String(event?.tool_name || event?.toolName || 'Bash');
560
- const tier1Active = Boolean(
561
- options?.tier1Active ||
562
- event?.tier1Active ||
563
- globalThis.process?.env?.BURNOFF_TIER1_ACTIVE === '1'
564
- );
565
- if (
566
- tier1Active &&
567
- /^(?:Grep|Glob)$/i.test(toolName) &&
568
- extractFastPostToolText(event).length < 16_000 &&
569
- !didFastToolExecutionFail(event)
570
- ) {
571
- return {
572
- exitCode: 0,
573
- stdout: '',
574
- stderr: '',
575
- fastPath: 'tier1_active',
576
- sanitized: { modified: false, offloaded: false, savedTokens: 0 }
577
- };
578
- }
579
- return null;
580
- }
581
-
582
- export default {
583
- isCliEntrypoint,
584
- readStdinJson,
585
- readStdinJsonAsync,
586
- readStdinFastWithMeta,
587
- readStdinFast,
588
- exitPassThrough,
589
- exitDiagnosticZero,
590
- exitHardBlockStderr,
591
- exitWithStdoutJson,
592
- exitWithHookSpecificOutput,
593
- writeHookStdoutJsonAndExit,
594
- installCliHookProcessGuards,
595
- recordHookTrace,
596
- canFastAllowBoundedRead,
597
- tryTier1PreToolFastPath,
598
- tryTier1PostToolFastPath
599
- };
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
+ import { getWorkspaceStateDir } from '../src/config/paths.mjs';
11
+
12
+ const BOUNDED_READ_TOOL_RE = /^(?:Read|read_file|view_file)$/i;
13
+ const SENSITIVE_SEGMENT_RE =
14
+ /(?:^|[\\/])(?:\.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;
15
+ const BINARY_OR_MULTIMODAL_EXT_RE =
16
+ /\.(?: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;
17
+ const TRAVERSAL_SEGMENT_RE = /(?:^|[\\/])\.\.(?:[\\/]|$)/;
18
+
19
+ export function isCliEntrypoint(importMetaUrl, argv1 = globalThis.process?.argv?.[1]) {
20
+ if (!importMetaUrl || !argv1) return false;
21
+ try {
22
+ const modulePath = fileURLToPath(importMetaUrl);
23
+ const targetPath = path.resolve(String(argv1));
24
+ try {
25
+ return fs.realpathSync(modulePath) === fs.realpathSync(targetPath);
26
+ } catch {
27
+ return path.normalize(modulePath) === path.normalize(targetPath);
28
+ }
29
+ } catch {
30
+ return false;
31
+ }
32
+ }
33
+
34
+ export function readStdinJson(options = {}) {
35
+ if (globalThis.process?.stdin?.isTTY) return {};
36
+ let raw = '';
37
+ try {
38
+ raw = fs.readFileSync(0, 'utf8').trim();
39
+ } catch {
40
+ return {};
41
+ }
42
+ if (!raw) return {};
43
+ try {
44
+ const parsed = JSON.parse(raw);
45
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
46
+ if (options?.allowMalformed) return {};
47
+ throw new SyntaxError('Stdin JSON payload must be a JSON object');
48
+ }
49
+ return parsed;
50
+ } catch (err) {
51
+ if (options?.allowMalformed) return {};
52
+ throw err;
53
+ }
54
+ }
55
+
56
+ export function readStdinJsonAsync(
57
+ timeoutMs = 2000,
58
+ stdinStream = globalThis.process?.stdin,
59
+ options = {}
60
+ ) {
61
+ return new Promise((resolve, reject) => {
62
+ if (!stdinStream || stdinStream.isTTY) {
63
+ resolve({});
64
+ return;
65
+ }
66
+
67
+ let raw = '';
68
+ let settled = false;
69
+
70
+ const cleanupStream = () => {
71
+ clearTimeout(timer);
72
+ try {
73
+ stdinStream.removeListener('data', onData);
74
+ stdinStream.removeListener('end', onEnd);
75
+ stdinStream.removeListener('error', onError);
76
+ if (typeof stdinStream.pause === 'function') stdinStream.pause();
77
+ if (typeof stdinStream.unref === 'function') stdinStream.unref();
78
+ } catch (err) {
79
+ void err; // ignore: best-effort stdin stream cleanup
80
+ }
81
+ };
82
+
83
+ const finishResolve = (parsedValue) => {
84
+ if (settled) return;
85
+ settled = true;
86
+ cleanupStream();
87
+ resolve(parsedValue);
88
+ };
89
+
90
+ const finishReject = (err) => {
91
+ if (settled) return;
92
+ settled = true;
93
+ cleanupStream();
94
+ reject(err);
95
+ };
96
+
97
+ const settleFromRaw = () => {
98
+ const trimmed = raw.trim();
99
+ if (!trimmed) {
100
+ finishResolve({});
101
+ return;
102
+ }
103
+ try {
104
+ const obj = JSON.parse(trimmed);
105
+ if (!obj || typeof obj !== 'object' || Array.isArray(obj)) {
106
+ if (options?.allowMalformed) {
107
+ finishResolve({});
108
+ return;
109
+ }
110
+ finishReject(new SyntaxError('Malformed stdin JSON payload: expected JSON object'));
111
+ return;
112
+ }
113
+ finishResolve(obj);
114
+ } catch (err) {
115
+ if (options?.allowMalformed) {
116
+ finishResolve({});
117
+ return;
118
+ }
119
+ finishReject(
120
+ new SyntaxError(`Malformed stdin JSON payload: ${err?.message || String(err)}`)
121
+ );
122
+ }
123
+ };
124
+
125
+ const onData = (chunk) => {
126
+ raw += typeof chunk === 'string' ? chunk : Buffer.from(chunk).toString('utf8');
127
+ };
128
+ const onEnd = () => settleFromRaw();
129
+ const onError = () => finishResolve({});
130
+
131
+ const timer = setTimeout(() => {
132
+ settleFromRaw();
133
+ }, Math.max(10, Number(timeoutMs) || 2000));
134
+
135
+ if (typeof timer.unref === 'function') {
136
+ timer.unref();
137
+ }
138
+
139
+ try {
140
+ if (typeof stdinStream.setEncoding === 'function') {
141
+ stdinStream.setEncoding('utf8');
142
+ }
143
+ stdinStream.on('data', onData);
144
+ stdinStream.on('end', onEnd);
145
+ stdinStream.on('error', onError);
146
+ if (typeof stdinStream.resume === 'function') {
147
+ stdinStream.resume();
148
+ }
149
+ } catch {
150
+ finishResolve({});
151
+ }
152
+ });
153
+ }
154
+
155
+ export function readStdinFastWithMeta({ maxTimeoutMs = 2000, chunkDeadlineMs = 2000, settleMs = 2 } = {}) {
156
+ if (process.stdin.isTTY || process.stdin.readableEnded) {
157
+ return Promise.resolve({ data: {}, empty: true, timedOut: false, malformed: false });
158
+ }
159
+ return new Promise((resolve) => {
160
+ let raw = '';
161
+ let settled = false;
162
+ let sawChunk = false;
163
+ let settleTimer = null;
164
+ const startedAt = Date.now();
165
+ const hardCapMs = Math.max(maxTimeoutMs, chunkDeadlineMs);
166
+
167
+ const finish = (meta) => {
168
+ if (settled) return;
169
+ settled = true;
170
+ clearTimeout(maxTimer);
171
+ if (settleTimer) clearTimeout(settleTimer);
172
+ try {
173
+ process.stdin.pause();
174
+ } catch (err) {
175
+ void err; // ignore: stdin pause failure on settle
176
+ }
177
+ resolve(meta);
178
+ };
179
+
180
+ const tryParse = (timedOut = false) => {
181
+ const trimmed = raw.trim();
182
+ if (!trimmed) {
183
+ return { data: {}, empty: true, timedOut, malformed: false };
184
+ }
185
+ try {
186
+ return { data: JSON.parse(trimmed), empty: false, timedOut, malformed: false };
187
+ } catch (err) {
188
+ try {
189
+ process.stderr.write(
190
+ `[Burnoff hook] Malformed stdin JSON; failing open (${err?.message || 'parse error'}).\n`
191
+ );
192
+ } catch (writeErr) {
193
+ void writeErr; // ignore: best-effort stderr diagnostic
194
+ }
195
+ return { data: {}, empty: false, timedOut, malformed: true };
196
+ }
197
+ };
198
+
199
+ let maxTimer = setTimeout(() => finish(tryParse(true)), maxTimeoutMs);
200
+ process.stdin.setEncoding('utf8');
201
+ process.stdin.on('data', (chunk) => {
202
+ raw += chunk;
203
+ if (!sawChunk && raw.length > 0) {
204
+ sawChunk = true;
205
+ clearTimeout(maxTimer);
206
+ const remaining = Math.max(10, hardCapMs - (Date.now() - startedAt));
207
+ maxTimer = setTimeout(() => finish(tryParse(true)), remaining);
208
+ }
209
+ if (settleTimer) clearTimeout(settleTimer);
210
+ if (raw.trim().endsWith('}')) {
211
+ settleTimer = setTimeout(() => {
212
+ try {
213
+ finish({ data: JSON.parse(raw), empty: false, timedOut: false, malformed: false });
214
+ } catch {
215
+ // wait for remaining chunks
216
+ }
217
+ }, settleMs);
218
+ }
219
+ });
220
+ process.stdin.on('end', () => finish(tryParse(false)));
221
+ process.stdin.on('error', () => finish({ data: {}, empty: true, timedOut: false, malformed: true }));
222
+ });
223
+ }
224
+
225
+ export function readStdinFast(options = {}) {
226
+ return readStdinFastWithMeta(options).then((meta) => meta.data);
227
+ }
228
+
229
+ export function exitPassThrough(exitFn = globalThis.process?.exit) {
230
+ exitFn?.(0);
231
+ }
232
+
233
+ export function exitDiagnosticZero(reason, hookEventName = 'Hook', ioOverride = {}) {
234
+ const writeStderr =
235
+ ioOverride.stderrWrite ||
236
+ ioOverride.writeStderr ||
237
+ ((s) => globalThis.process?.stderr?.write?.(s));
238
+ const exitFn = ioOverride.exitFn || globalThis.process?.exit;
239
+ const msg = String(reason || 'Unexpected hook diagnostic').trim();
240
+ writeStderr(`[Burnoff ${hookEventName} Diagnostic] ${msg}\n`);
241
+ exitFn?.(0);
242
+ }
243
+
244
+ export function exitHardBlockStderr(reason, hookEventName = 'PreToolUse', ioOverride = {}) {
245
+ const writeStderr =
246
+ ioOverride.stderrWrite ||
247
+ ioOverride.writeStderr ||
248
+ ((s) => globalThis.process?.stderr?.write?.(s));
249
+ const exitFn = ioOverride.exitFn || globalThis.process?.exit;
250
+
251
+ if (hookEventName === 'WorktreeCreate' || hookEventName === 'PermissionRequest') {
252
+ exitPassThrough(exitFn);
253
+ return;
254
+ }
255
+ const msg = String(reason || 'Blocked by Burnoff circuit breaker').trim();
256
+ writeStderr(`${msg}\n`);
257
+ exitFn?.(2);
258
+ }
259
+
260
+ export function exitWithStdoutJson(payload, ioOverride = {}) {
261
+ const writeStdout =
262
+ ioOverride.stdoutWrite ||
263
+ ioOverride.writeStdout ||
264
+ ((s) => globalThis.process?.stdout?.write?.(s));
265
+ const exitFn = ioOverride.exitFn || globalThis.process?.exit;
266
+ const serialized = typeof payload === 'string' ? payload : JSON.stringify(payload);
267
+ writeStdout(`${serialized}\n`);
268
+ exitFn?.(0);
269
+ }
270
+
271
+ export function exitWithHookSpecificOutput(hookSpecificOutput, ioOverride = {}) {
272
+ exitWithStdoutJson({ hookSpecificOutput }, ioOverride);
273
+ }
274
+
275
+ export function writeHookStdoutJsonAndExit(payload = {}) {
276
+ let line = '{}\n';
277
+ try {
278
+ line = `${JSON.stringify(payload ?? {})}\n`;
279
+ } catch {
280
+ line = '{}\n';
281
+ }
282
+ try {
283
+ fs.writeSync(1, Buffer.from(line, 'utf8'));
284
+ } catch (err) {
285
+ void err; // ignore: EPIPE/EBADF when caller closed stdout
286
+ }
287
+ process.exit(0);
288
+ }
289
+
290
+ let _cliHookGuardsInstalled = false;
291
+
292
+ export function installCliHookProcessGuards(getFallbackPayload = () => ({})) {
293
+ if (_cliHookGuardsInstalled) return;
294
+ _cliHookGuardsInstalled = true;
295
+
296
+ try {
297
+ process.stdout?.on?.('error', () => {
298
+ // ignore: closed stdout EPIPE
299
+ });
300
+ } catch (err) {
301
+ void err; // ignore: non-fatal stdout guard setup
302
+ }
303
+
304
+ const formatArg = (a) => {
305
+ if (typeof a === 'string') return a;
306
+ if (a instanceof Error) return a.stack || a.message || String(a);
307
+ try {
308
+ return JSON.stringify(a);
309
+ } catch {
310
+ return String(a);
311
+ }
312
+ };
313
+ const redirectToStderr = (...args) => {
314
+ try {
315
+ process.stderr.write(`${args.map(formatArg).join(' ')}\n`);
316
+ } catch (err) {
317
+ void err; // ignore: stderr write guard
318
+ }
319
+ };
320
+ console.log = redirectToStderr;
321
+ console.info = redirectToStderr;
322
+ console.debug = redirectToStderr;
323
+
324
+ let failingOpen = false;
325
+ const failOpen = (kind, err) => {
326
+ if (failingOpen) return;
327
+ failingOpen = true;
328
+ try {
329
+ const msg = String(err?.stack || err?.message || err || 'unknown error').slice(0, 400);
330
+ process.stderr.write(`[Burnoff hook] ${kind}; failing open: ${msg}\n`);
331
+ } catch (writeErr) {
332
+ void writeErr; // ignore: stderr write guard
333
+ }
334
+ let fallback = {};
335
+ try {
336
+ fallback = typeof getFallbackPayload === 'function' ? getFallbackPayload() : {};
337
+ } catch {
338
+ fallback = {};
339
+ }
340
+ writeHookStdoutJsonAndExit(fallback);
341
+ };
342
+
343
+ process.on('uncaughtException', (err) => failOpen('uncaughtException', err));
344
+ process.on('unhandledRejection', (err) => failOpen('unhandledRejection', err));
345
+ }
346
+
347
+ export function recordHookTrace(eventName, payload = {}, details = {}) {
348
+ const tracePath = details.tracePath || globalThis.process?.env?.BURNOFF_HOOK_TRACE_PATH || '';
349
+ if (!tracePath) return;
350
+ const entry = {
351
+ ts: Date.now(),
352
+ event: String(eventName || 'Hook'),
353
+ tool: String(payload?.tool_name || payload?.toolName || ''),
354
+ outcome: String(details.outcome || 'pass_through'),
355
+ path: String(details.path || 'core'),
356
+ exitCode: Number.isFinite(Number(details.exitCode)) ? Number(details.exitCode) : 0
357
+ };
358
+ if (details.error) {
359
+ entry.error = String(details.error).replace(/\s+/g, ' ').slice(0, 160);
360
+ }
361
+ const line = `${JSON.stringify(entry)}\n`;
362
+ try {
363
+ fs.appendFileSync(tracePath, line, 'utf8');
364
+ } catch (err) {
365
+ if (err?.code === 'ENOENT') {
366
+ try {
367
+ fs.mkdirSync(path.dirname(tracePath), { recursive: true });
368
+ fs.appendFileSync(tracePath, line, 'utf8');
369
+ } catch (retryErr) {
370
+ void retryErr; // ignore: optional hook trace write must never break hook execution
371
+ }
372
+ } else {
373
+ void err; // ignore: optional hook trace write must never break hook execution
374
+ }
375
+ }
376
+ }
377
+
378
+ /**
379
+ * Conservative fast-path check for explicitly bounded workspace source file reads.
380
+ * Returns `false` whenever any active guard, lock, breaker failure state, policy file,
381
+ * or read-interval overlap could require full evaluation.
382
+ */
383
+ export function canFastAllowBoundedRead(payload = {}, { cwd = '', homeDir = null } = {}) {
384
+ if (!payload || typeof payload !== 'object') return false;
385
+ if (payload.shieldForceActive || payload.shieldConfig || payload.consecutiveFailures) {
386
+ return false;
387
+ }
388
+
389
+ const toolName = String(payload.tool_name || payload.toolName || payload.toolCall?.name || '');
390
+ if (!BOUNDED_READ_TOOL_RE.test(toolName)) return false;
391
+
392
+ const tIn = payload.tool_input || payload.toolInput || payload.args || payload.toolArgs || payload.toolCall?.args || {};
393
+ if (!tIn || typeof tIn !== 'object') return false;
394
+
395
+ const hasUpperLimit =
396
+ (tIn.limit !== undefined && tIn.limit !== null) ||
397
+ ((tIn.StartLine !== undefined || tIn.start_line !== undefined) &&
398
+ (tIn.EndLine !== undefined || tIn.end_line !== undefined));
399
+ if (!hasUpperLimit) return false;
400
+
401
+ const limitNum = Number(tIn.limit);
402
+ const startNum = Number(tIn.StartLine ?? tIn.start_line);
403
+ const endNum = Number(tIn.EndLine ?? tIn.end_line);
404
+ if (
405
+ (tIn.limit !== undefined && tIn.limit !== null && (!Number.isFinite(limitNum) || limitNum <= 0 || limitNum > 150)) ||
406
+ (Number.isFinite(startNum) && Number.isFinite(endNum) && (endNum < startNum || endNum - startNum + 1 > 150))
407
+ ) {
408
+ return false;
409
+ }
410
+
411
+ const rawPath = String(
412
+ tIn.file_path || tIn.Path || tIn.AbsolutePath || tIn.path || tIn.TargetFile || ''
413
+ ).trim();
414
+ if (!rawPath || rawPath.includes('\0') || TRAVERSAL_SEGMENT_RE.test(rawPath)) {
415
+ return false;
416
+ }
417
+ if (SENSITIVE_SEGMENT_RE.test(rawPath) || BINARY_OR_MULTIMODAL_EXT_RE.test(rawPath)) {
418
+ return false;
419
+ }
420
+
421
+ const rawCwd =
422
+ cwd ||
423
+ payload.cwd ||
424
+ (Array.isArray(payload.workspacePaths) && payload.workspacePaths[0]) ||
425
+ payload.workspacePath ||
426
+ process.cwd();
427
+ const baseCwd = path.resolve(String(rawCwd || process.cwd()));
428
+
429
+ if (path.isAbsolute(rawPath)) {
430
+ const resolvedTarget = path.resolve(rawPath);
431
+ const rel = path.relative(baseCwd, resolvedTarget);
432
+ if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) {
433
+ return false;
434
+ }
435
+ if (SENSITIVE_SEGMENT_RE.test(rel) || BINARY_OR_MULTIMODAL_EXT_RE.test(rel)) {
436
+ return false;
437
+ }
438
+ }
439
+
440
+ if (
441
+ fs.existsSync(path.join(baseCwd, '.burnoff.yaml')) ||
442
+ fs.existsSync(path.join(baseCwd, '.burnoff.yml'))
443
+ ) {
444
+ return false;
445
+ }
446
+
447
+ const wsStateDir = getWorkspaceStateDir(baseCwd, homeDir);
448
+ if (
449
+ fs.existsSync(path.join(baseCwd, '.claude', 'locks', 'active_scopes.json')) ||
450
+ fs.existsSync(path.join(wsStateDir, 'active_scopes.json'))
451
+ ) {
452
+ return false;
453
+ }
454
+
455
+ const sessionId = String(payload.session_id || payload.sessionId || payload.conversationId || 'default');
456
+ const safeSid = sessionId.replace(/[^a-zA-Z0-9._-]/g, '_').slice(0, 80) || 'default';
457
+ if (
458
+ fs.existsSync(path.join(baseCwd, '.claude', 'cache', `burnoff_breaker_state_${safeSid}.json`)) ||
459
+ fs.existsSync(path.join(wsStateDir, `burnoff_breaker_state_${safeSid}.json`))
460
+ ) {
461
+ return false;
462
+ }
463
+
464
+ const snapCandidates = [
465
+ path.join(baseCwd, '.claude', 'cache', `read_snapshots_${safeSid.slice(0, 64)}.json`),
466
+ path.join(wsStateDir, `read_snapshots_${safeSid.slice(0, 64)}.json`)
467
+ ];
468
+ for (const snapPath of snapCandidates) {
469
+ if (!fs.existsSync(snapPath)) continue;
470
+ try {
471
+ const snap = JSON.parse(fs.readFileSync(snapPath, 'utf8'));
472
+ const absTarget = path.isAbsolute(rawPath) ? path.resolve(rawPath) : path.resolve(baseCwd, rawPath);
473
+ const normKey = absTarget.replace(/\\/g, '/').toLowerCase();
474
+ const entry = snap?.__readIntervals?.[normKey];
475
+ if (entry && Array.isArray(entry.intervals) && entry.intervals.length > 0) {
476
+ const reqStart = Math.max(1, Math.floor(Number(tIn.offset ?? tIn.StartLine ?? tIn.start_line ?? 1)));
477
+ const reqLimit = Number(tIn.limit);
478
+ const reqEnd =
479
+ Number.isFinite(reqLimit) && reqLimit > 0
480
+ ? reqStart + Math.floor(reqLimit) - 1
481
+ : Math.max(reqStart, Math.floor(Number(tIn.EndLine ?? tIn.end_line ?? reqStart)));
482
+ const hasOverlap = entry.intervals.some(
483
+ (iv) => Array.isArray(iv) && iv.length >= 2 && reqStart <= iv[1] && reqEnd >= iv[0]
484
+ );
485
+ if (hasOverlap) {
486
+ return false;
487
+ }
488
+ }
489
+ } catch {
490
+ return false;
491
+ }
492
+ }
493
+
494
+ return true;
495
+ }
496
+
497
+ const READ_ONLY_FAST_ALLOW_TOOL_RE = /^(?:Grep|Glob|WebFetch)$/i;
498
+ const READ_ONLY_TOOL_ALIASES = Object.freeze({
499
+ grep_search: 'Grep',
500
+ find_by_name: 'Glob',
501
+ list_dir: 'Glob',
502
+ read_url_content: 'WebFetch'
503
+ });
504
+ const READ_ONLY_SENSITIVE_TARGET_RE =
505
+ /(?:\.env(?:\b|\.(?!example\b|sample\b|template\b|dist\b))|\.en(?:[?*[\]]|[a-z]*[?*])|id_rsa|id_ed25519|id_ecdsa|id_dsa|\.pem\b|\.key\b|credentials|\.aws|\.ssh|\.npmrc|\.pypirc|\.netrc|secret|private)/i;
506
+ const READ_ONLY_TARGET_FIELDS = [
507
+ 'file_path',
508
+ 'path',
509
+ 'glob',
510
+ 'pattern',
511
+ 'SearchPath',
512
+ 'SearchDirectory',
513
+ 'DirectoryPath',
514
+ 'Query',
515
+ 'Pattern',
516
+ 'target_directory',
517
+ 'directory'
518
+ ];
519
+
520
+ function resolveFastToolName(event = {}) {
521
+ const raw = String(event?.tool_name || event?.toolName || event?.toolCall?.name || '').trim();
522
+ if (!raw) return '';
523
+ return READ_ONLY_TOOL_ALIASES[raw.toLowerCase()] || raw;
524
+ }
525
+
526
+ function resolveFastToolInput(event = {}) {
527
+ if (event?.tool_input && typeof event.tool_input === 'object') return event.tool_input;
528
+ if (event?.toolInput && typeof event.toolInput === 'object') return event.toolInput;
529
+ if (event?.toolCall?.args && typeof event.toolCall.args === 'object') return event.toolCall.args;
530
+ if (event?.args && typeof event.args === 'object') return event.args;
531
+ return {};
532
+ }
533
+
534
+ export function shouldInspectReadOnlyTools(event = {}, options = {}) {
535
+ if (options?.inspectReadOnlyTools === true) return true;
536
+ if (options?.policy?.guards?.inspectReadOnlyTools === true) return true;
537
+ if (globalThis.process?.env?.BURNOFF_INSPECT_READONLY_TOOLS === '1') return true;
538
+
539
+ const firstWs =
540
+ Array.isArray(event?.workspacePaths) && event.workspacePaths[0]
541
+ ? String(event.workspacePaths[0])
542
+ : '';
543
+ const rawCwd = String(event?.cwd || options?.cwd || event?.toolCall?.args?.Cwd || firstWs || '').trim();
544
+ if (!rawCwd) return false;
545
+
546
+ for (const name of ['.burnoff.yaml', '.burnoff.yml']) {
547
+ const candidate = path.join(rawCwd, name);
548
+ try {
549
+ if (!fs.existsSync(candidate)) continue;
550
+ const content = fs.readFileSync(candidate, 'utf8');
551
+ if (/^\s*inspectReadOnlyTools\s*:\s*true\b/m.test(content)) {
552
+ return true;
553
+ }
554
+ return false;
555
+ } catch {
556
+ // ignore: unreadable policy config falls back to default fast-allow
557
+ }
558
+ }
559
+ return false;
560
+ }
561
+
562
+ export function hasSensitiveReadOnlyTarget(toolName = '', toolInput = {}) {
563
+ if (!/^(?:Grep|Glob)$/i.test(String(toolName || ''))) return false;
564
+ if (!toolInput || typeof toolInput !== 'object') return false;
565
+ for (const field of READ_ONLY_TARGET_FIELDS) {
566
+ const val = toolInput[field];
567
+ if (typeof val === 'string' && val.trim() && READ_ONLY_SENSITIVE_TARGET_RE.test(val)) {
568
+ return true;
569
+ }
570
+ }
571
+ return false;
572
+ }
573
+
574
+ export function tryTier1PreToolFastPath(event = {}, options = {}) {
575
+ const toolName = resolveFastToolName(event);
576
+ if (!READ_ONLY_FAST_ALLOW_TOOL_RE.test(toolName)) {
577
+ return null;
578
+ }
579
+ if (shouldInspectReadOnlyTools(event, options)) {
580
+ return null;
581
+ }
582
+ const toolInput = resolveFastToolInput(event);
583
+ if (hasSensitiveReadOnlyTarget(toolName, toolInput)) {
584
+ return null;
585
+ }
586
+ const tier1Active = Boolean(
587
+ options?.tier1Active ||
588
+ event?.tier1Active ||
589
+ globalThis.process?.env?.BURNOFF_TIER1_ACTIVE === '1'
590
+ );
591
+ return {
592
+ exitCode: 0,
593
+ stdout: '',
594
+ stderr: '',
595
+ fastPath: tier1Active ? 'tier1_active' : 'readonly_fast_allow',
596
+ verdict: {
597
+ triggered: false,
598
+ decision: 'allow',
599
+ reason: tier1Active
600
+ ? 'Handled via Tier-1 fast path'
601
+ : 'Read-only tool fast-allowed by PreToolUse Tier-1 fast path'
602
+ }
603
+ };
604
+ }
605
+
606
+ function extractFastPostToolText(event = {}) {
607
+ const resp = event.tool_response ?? event.tool_output ?? event.toolOutput ?? event.output;
608
+ if (typeof resp === 'string') return resp;
609
+ if (resp && typeof resp === 'object') {
610
+ const parts = [resp.stdout, resp.stderr, resp.output, resp.content, resp.error]
611
+ .filter((x) => typeof x === 'string' && x.length > 0);
612
+ if (parts.length > 0) return parts.join('\n');
613
+ return '';
614
+ }
615
+ return resp !== undefined && resp !== null ? String(resp) : '';
616
+ }
617
+
618
+ function didFastToolExecutionFail(event = {}) {
619
+ if (
620
+ event.is_error === true ||
621
+ event.isError === true ||
622
+ event.succeeded === false ||
623
+ Boolean(event.tool_error || event.error) ||
624
+ (typeof event.exit_code === 'number' && event.exit_code !== 0) ||
625
+ (typeof event.exitCode === 'number' && event.exitCode !== 0)
626
+ ) {
627
+ return true;
628
+ }
629
+ const resp = event.tool_response;
630
+ if (resp && typeof resp === 'object') {
631
+ if (
632
+ resp.is_error === true ||
633
+ resp.isError === true ||
634
+ resp.succeeded === false ||
635
+ resp.status === 'error' ||
636
+ resp.status === 'failed' ||
637
+ Boolean(resp.error) ||
638
+ (typeof resp.exit_code === 'number' && resp.exit_code !== 0) ||
639
+ (typeof resp.exitCode === 'number' && resp.exitCode !== 0) ||
640
+ (typeof resp.returncode === 'number' && resp.returncode !== 0)
641
+ ) {
642
+ return true;
643
+ }
644
+ }
645
+ return false;
646
+ }
647
+
648
+ export function tryTier1PostToolFastPath(event = {}, options = {}) {
649
+ const toolName = String(event?.tool_name || event?.toolName || 'Bash');
650
+ const tier1Active = Boolean(
651
+ options?.tier1Active ||
652
+ event?.tier1Active ||
653
+ globalThis.process?.env?.BURNOFF_TIER1_ACTIVE === '1'
654
+ );
655
+ if (
656
+ tier1Active &&
657
+ /^(?:Grep|Glob)$/i.test(toolName) &&
658
+ extractFastPostToolText(event).length < 16_000 &&
659
+ !didFastToolExecutionFail(event)
660
+ ) {
661
+ return {
662
+ exitCode: 0,
663
+ stdout: '',
664
+ stderr: '',
665
+ fastPath: 'tier1_active',
666
+ sanitized: { modified: false, offloaded: false, savedTokens: 0 }
667
+ };
668
+ }
669
+ return null;
670
+ }
671
+
672
+ export default {
673
+ isCliEntrypoint,
674
+ readStdinJson,
675
+ readStdinJsonAsync,
676
+ readStdinFastWithMeta,
677
+ readStdinFast,
678
+ exitPassThrough,
679
+ exitDiagnosticZero,
680
+ exitHardBlockStderr,
681
+ exitWithStdoutJson,
682
+ exitWithHookSpecificOutput,
683
+ writeHookStdoutJsonAndExit,
684
+ installCliHookProcessGuards,
685
+ recordHookTrace,
686
+ canFastAllowBoundedRead,
687
+ shouldInspectReadOnlyTools,
688
+ hasSensitiveReadOnlyTarget,
689
+ tryTier1PreToolFastPath,
690
+ tryTier1PostToolFastPath
691
+ };