burnoff 1.3.0 → 1.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,846 +1,973 @@
1
- /**
2
- * @file src/guards/pre-tool-engine.mjs
3
- * Pure ESM orchestrator for Claude Code `PreToolUse` evaluation.
4
- * Enforces `.burnoff.yaml` policy, `DET-01`..`DET-04` + `DET-20` guards,
5
- * read-interval overlap trimming, and bounded `Read` (`updatedInput`) clamping.
6
- */
7
-
8
- import fs from 'node:fs';
9
- import path from 'node:path';
10
- import { getClientAdapter, normalizeHookEvent } from '../clients/detect.mjs';
11
- import { loadBurnoffPolicy } from '../config/policy.mjs';
12
- import { computeTotalPromptTokens } from '../config/loader.mjs';
13
- import { recordInterventionSavings, recordSavingsReceipt } from '../storage/ledger.mjs';
14
- import {
15
- SHELL_TOOL_REGEX,
16
- evaluateDet01GitAndShellSafety,
17
- evaluateDet02SecretBoundary,
18
- evaluateDet03ProtectedFilesAskGate
19
- } from './shell-guard.mjs';
20
- import {
21
- SUBAGENT_TOOL_REGEX,
22
- acquireScopeLock,
23
- evaluateDet04ConsecutiveFailures,
24
- evaluateDet05SubagentFanout,
25
- evaluateScopeAndQuotaBrake,
26
- readBreakerStateSnapshot,
27
- recordSubagentSpawnAtomicSync,
28
- updateBreakerStateAtomicSync
29
- } from './loop-breaker.mjs';
30
- import {
31
- DEFAULT_READ_INTERVAL_TTL_MS,
32
- evaluateShieldReadGuard,
33
- loadReadSnapStore,
34
- trimRequestedRangeAgainstIntervals,
35
- recordReadIntervalEntry,
36
- updateReadSnapStoreAtomicSync
37
- } from './read-clamp.mjs';
38
- import {
39
- consumeMatchingAskSnoozeAtomicSync,
40
- matchesSnoozeEntry
41
- } from './snooze.mjs';
42
-
43
- const READ_TOOL_REGEX = /^(?:Read|read_file|view_file)$/i;
44
- const EDIT_WRITE_OR_READ_REGEX = /^(?:Edit|Write|MultiEdit|NotebookEdit|Read|Grep|Glob|read_file|view_file|grep_search)$/i;
45
- const EDIT_WRITE_SCOPE_LOCK_REGEX = /^(?:Edit|Write|MultiEdit|NotebookEdit)$/i;
46
-
47
- function isTier1ActiveFastPath(toolName, event, options) {
48
- const tier1Active = Boolean(
49
- options?.tier1Active ||
50
- event?.tier1Active ||
51
- globalThis.process?.env?.BURNOFF_TIER1_ACTIVE === '1'
52
- );
53
- return tier1Active && /^(?:Grep|Glob)$/i.test(toolName);
54
- }
55
-
56
- function evaluatePreToolUseCore(event = {}, options = {}) {
57
- const { client, adapter, canonical } =
58
- event && event.__canonical === true
59
- ? { client: event.client || 'claude-code', adapter: getClientAdapter(event.client || 'claude-code'), canonical: event }
60
- : normalizeHookEvent(event, options);
61
-
62
- const finalize = (res) => (client === 'antigravity' ? adapter.renderPre(res) : res);
63
-
64
- const toolName = String(canonical.toolName || '');
65
- if (isTier1ActiveFastPath(toolName, event, options)) {
66
- return finalize({
67
- exitCode: 0,
68
- stdout: '',
69
- stderr: '',
70
- fastPath: 'tier1_active',
71
- verdict: { triggered: false, decision: 'allow', reason: 'Handled via Tier-1 fast path' }
72
- });
73
- }
74
-
75
- const sessionId = String(canonical.sessionId || 'default');
76
- const rawCwd = canonical.cwd || options.cwd || '';
77
- const cwdOptions = { ...(rawCwd ? { ...options, cwd: rawCwd } : options), client };
78
- const baseCwd = rawCwd ? path.resolve(String(rawCwd)) : process.cwd();
79
- const policy = options.policy || loadBurnoffPolicy(baseCwd);
80
- const guardsCfg = policy.guards || {};
81
-
82
- const shouldPersistState =
83
- options.persistState !== false &&
84
- Boolean(canonical.cwd || options.cwd || options.breakerStatePath || options.persistState);
85
- const canRecordLedger =
86
- options.recordLedger !== false &&
87
- Boolean(canonical.cwd || options.cwd || options.ledgerPath || options.recordLedger);
88
-
89
- const priorSnap = shouldPersistState
90
- ? readBreakerStateSnapshot(sessionId, cwdOptions)
91
- : null;
92
-
93
- if (policy?.exists && policy?.parseError && !priorSnap?.policyParseErrorWarned) {
94
- const writeStderr =
95
- options.stderrWrite || ((msg) => globalThis.process?.stderr?.write?.(msg));
96
- const errDetail = policy.parseErrorMessage ? `: ${policy.parseErrorMessage}` : '';
97
- writeStderr(
98
- `[Burnoff Policy Warning] Failed to parse ${path.basename(policy.sourcePath || '.burnoff.yaml')}${errDetail}; falling back to safe defaults.\n`
99
- );
100
- if (shouldPersistState) {
101
- try {
102
- updateBreakerStateAtomicSync(
103
- sessionId,
104
- (prior) => ({
105
- ...(prior && typeof prior === 'object' ? prior : {}),
106
- schemaVersion: '1.0.0',
107
- sessionId,
108
- policyParseErrorWarned: true,
109
- updatedAt: options.nowMs ?? Date.now()
110
- }),
111
- cwdOptions
112
- );
113
- } catch (warnErr) {
114
- void warnErr; // ignore: best-effort parseError warning state persistence
115
- }
116
- }
117
- }
118
-
119
- const tIn = canonical.toolInput || {};
120
- const command = String(tIn.command || tIn.CommandLine || tIn.cmd || event.command || '');
121
- const rawPath = String(
122
- tIn.file_path || tIn.notebook_path || tIn.filePath || tIn.path || tIn.Path || tIn.TargetFile || event.filePath || ''
123
- ).trim();
124
- const modelId = canonical.model || 'claude-sonnet-5-5';
125
- const lastUserInput = canonical.lastUserInput || '';
126
- const guardMode = event.mode ?? options.mode ?? guardsCfg.mode ?? 'guard';
127
- const flightMode = event.flightMode ?? options.flightMode;
128
- const ownerId = String(
129
- canonical.agentId || event.ownerId || event.agentId || event.subagentId || sessionId
130
- );
131
-
132
- // Resolves interactive `ask` verdicts against active session/workspace snoozes.
133
- // Security invariant: NEVER invoke for `deny` / `exitCode: 2` verdicts.
134
- const evaluateAskWithSnooze = (verdict, targetText = '') => {
135
- const evalNowMs = options.nowMs ?? Date.now();
136
- let match = null;
137
- if (Array.isArray(options.snoozes)) {
138
- const memHit = options.snoozes.find((entry) =>
139
- matchesSnoozeEntry(entry, { detectorId: verdict.detectorId, target: targetText, nowMs: evalNowMs })
140
- );
141
- if (memHit) {
142
- if (memHit.remaining !== null && memHit.remaining !== undefined) {
143
- memHit.remaining = Math.max(0, Number(memHit.remaining) - 1);
144
- }
145
- match = { matched: true, source: 'memory', grant: memHit };
146
- }
147
- } else if (shouldPersistState) {
148
- match = consumeMatchingAskSnoozeAtomicSync(
149
- {
150
- sessionId,
151
- detectorId: verdict.detectorId,
152
- target: targetText,
153
- nowMs: evalNowMs
154
- },
155
- cwdOptions
156
- );
157
- }
158
-
159
- if (match?.matched) {
160
- return {
161
- snoozed: true,
162
- response: finalize({
163
- exitCode: 0,
164
- stdout: '',
165
- stderr: '',
166
- snoozed: true,
167
- verdict: {
168
- ...verdict,
169
- decision: 'allow',
170
- snoozed: true,
171
- snoozeGrantId: match.grant?.id || null,
172
- reason: `[Burnoff Snoozed ${verdict.detectorId}] Allowed via active ${match.source || 'session'} grant.`
173
- }
174
- })
175
- };
176
- }
177
-
178
- const askOut = {
179
- hookSpecificOutput: {
180
- hookEventName: 'PreToolUse',
181
- permissionDecision: 'ask',
182
- permissionDecisionReason: verdict.reason
183
- }
184
- };
185
- return {
186
- snoozed: false,
187
- response: finalize({
188
- exitCode: 0,
189
- stdout: JSON.stringify(askOut),
190
- stderr: '',
191
- verdict
192
- })
193
- };
194
- };
195
-
196
- let advisoryNotice = null;
197
-
198
- // 1. DET-20: Concurrent file-scope locks & quota hard brakes
199
- if (guardsCfg.scopeLockEnabled !== false) {
200
- const isReadOp = READ_TOOL_REGEX.test(toolName);
201
- const det20 = evaluateScopeAndQuotaBrake(
202
- {
203
- targetFilePath: EDIT_WRITE_OR_READ_REGEX.test(toolName) ? rawPath : '',
204
- isRead: isReadOp,
205
- toolName,
206
- ownerId,
207
- rateLimits: event.rateLimits || options.rateLimits || {}
208
- },
209
- cwdOptions
210
- );
211
- if (det20.triggered) {
212
- if (det20.decision === 'deny') {
213
- return finalize({
214
- exitCode: 2,
215
- stdout: '',
216
- stderr: det20.reason,
217
- verdict: det20
218
- });
219
- }
220
- advisoryNotice = det20;
221
- }
222
- }
223
-
224
- // 2. DET-01: Destructive Shell & Git Safety
225
- if (guardsCfg.det01Enabled !== false && SHELL_TOOL_REGEX.test(toolName) && command) {
226
- const det01 = evaluateDet01GitAndShellSafety({
227
- toolName,
228
- command,
229
- mode: event.mode ?? options.mode ?? guardsCfg.mode ?? 'guard',
230
- flightMode: event.flightMode ?? options.flightMode,
231
- recentGitStashAtMs:
232
- event.recentGitStashAtMs ?? options.recentGitStashAtMs ?? priorSnap?.lastGitStashAtMs ?? null,
233
- strictTestIntegrity:
234
- options.strictTestIntegrity ?? event.strictTestIntegrity ?? guardsCfg.strictTestIntegrity ?? false,
235
- lastUserInput,
236
- nowMs: options.nowMs
237
- });
238
- if (det01.triggered) {
239
- if (det01.decision === 'ask') {
240
- return evaluateAskWithSnooze(det01, command).response;
241
- }
242
- if (canRecordLedger) {
243
- recordSavingsReceipt(
244
- {
245
- sessionId,
246
- cwd: baseCwd,
247
- category: 'RING0_VIOLATION_BLOCKED',
248
- detectorId: det01.detectorId,
249
- ring0Violation: true,
250
- modelId,
251
- savedTokens: 0,
252
- savedUSD: 0,
253
- detail: det01.reason
254
- },
255
- cwdOptions
256
- );
257
- }
258
- return finalize({
259
- exitCode: 2,
260
- stdout: '',
261
- stderr: det01.reason,
262
- verdict: det01
263
- });
264
- }
265
- }
266
-
267
- // 3. DET-02: Secret & Credential Boundary
268
- if (guardsCfg.det02Enabled !== false) {
269
- const det02 = evaluateDet02SecretBoundary({
270
- toolName,
271
- filePath: rawPath,
272
- path: rawPath,
273
- command,
274
- mode: guardMode,
275
- flightMode,
276
- secretAllow: options.secretAllow ?? guardsCfg.secretAllow ?? []
277
- });
278
- if (det02.triggered) {
279
- if (det02.decision === 'ask') {
280
- return evaluateAskWithSnooze(det02, rawPath || command).response;
281
- }
282
- if (canRecordLedger) {
283
- recordSavingsReceipt(
284
- {
285
- sessionId,
286
- cwd: baseCwd,
287
- category: 'RING0_VIOLATION_BLOCKED',
288
- detectorId: det02.detectorId,
289
- ring0Violation: true,
290
- modelId,
291
- savedTokens: 0,
292
- savedUSD: 0,
293
- detail: det02.reason
294
- },
295
- cwdOptions
296
- );
297
- }
298
- return finalize({
299
- exitCode: 2,
300
- stdout: '',
301
- stderr: det02.reason,
302
- verdict: det02
303
- });
304
- }
305
- }
306
-
307
- // 4. DET-03: Protected Migration, Lockfile & Workflow Ask Gate
308
- if (guardsCfg.det03Enabled !== false) {
309
- const det03 = evaluateDet03ProtectedFilesAskGate({
310
- toolName,
311
- filePath: rawPath
312
- });
313
- if (det03.triggered && det03.decision === 'ask') {
314
- return evaluateAskWithSnooze(det03, rawPath).response;
315
- }
316
- }
317
-
318
- // 5. DET-04: Consecutive Failure Loop Breaker
319
- if (guardsCfg.det04Enabled !== false) {
320
- const consecutiveFailures = Number(
321
- event.consecutiveFailures ?? options.consecutiveFailures ?? priorSnap?.consecutiveFailures ?? 0
322
- );
323
- const det04 = evaluateDet04ConsecutiveFailures({
324
- consecutiveFailures,
325
- lastFailedToolKey: priorSnap?.lastFailedToolKey || null,
326
- toolName,
327
- command,
328
- filePath: rawPath,
329
- mode: guardMode,
330
- flightMode,
331
- maxConsecutiveFailures:
332
- options.maxConsecutiveFailures ?? guardsCfg.det04Threshold ?? 3
333
- });
334
- if (det04.triggered) {
335
- if (det04.decision === 'ask') {
336
- const evaluated = evaluateAskWithSnooze(det04, rawPath || command);
337
- if (evaluated.snoozed) {
338
- return evaluated.response;
339
- }
340
- if (canRecordLedger) {
341
- recordSavingsReceipt(
342
- {
343
- sessionId,
344
- cwd: baseCwd,
345
- category: 'LOOP_TURN_PREVENTED',
346
- detectorId: det04.detectorId,
347
- ring0Violation: false,
348
- modelId,
349
- savedTokens: 0,
350
- savedUSD: 0,
351
- detail: det04.reason
352
- },
353
- cwdOptions
354
- );
355
- }
356
- return evaluated.response;
357
- }
358
- if (canRecordLedger) {
359
- recordSavingsReceipt(
360
- {
361
- sessionId,
362
- cwd: baseCwd,
363
- category: 'RING0_VIOLATION_BLOCKED',
364
- detectorId: det04.detectorId,
365
- ring0Violation: true,
366
- modelId,
367
- savedTokens: 0,
368
- savedUSD: 0,
369
- detail: det04.reason
370
- },
371
- cwdOptions
372
- );
373
- }
374
- return finalize({
375
- exitCode: 2,
376
- stdout: '',
377
- stderr: det04.reason,
378
- verdict: det04
379
- });
380
- }
381
- }
382
-
383
- // 5b. DET-05: Subagent Fan-Out & Prompt-Bloat Guard
384
- if (guardsCfg.subagentFanoutEnabled !== false && SUBAGENT_TOOL_REGEX.test(toolName)) {
385
- const subagentPromptText = String(
386
- tIn.prompt || tIn.Prompt || tIn.instructions || tIn.description || ''
387
- );
388
- const burstWindowSec = Number(
389
- options.subagentBurstWindowSec ?? guardsCfg.subagentBurstWindowSec ?? 60
390
- );
391
- const nowSubagentMs = options.nowMs ?? Date.now();
392
- const det05 = evaluateDet05SubagentFanout({
393
- toolName,
394
- promptText: subagentPromptText,
395
- recentSpawnTimestampsMs:
396
- event.recentSpawnTimestampsMs ??
397
- options.recentSpawnTimestampsMs ??
398
- priorSnap?.subagentSpawnTimestampsMs ??
399
- [],
400
- maxBurstCount:
401
- options.subagentMaxBurstCount ?? guardsCfg.subagentMaxBurstCount ?? 4,
402
- burstWindowSec,
403
- maxPromptChars:
404
- options.subagentMaxPromptChars ?? guardsCfg.subagentMaxPromptChars ?? 8000,
405
- action:
406
- options.subagentFanoutAction ?? guardsCfg.subagentFanoutAction ?? 'advisory',
407
- nowMs: nowSubagentMs
408
- });
409
-
410
- if (det05.triggered && det05.decision === 'deny') {
411
- if (canRecordLedger) {
412
- recordSavingsReceipt(
413
- {
414
- sessionId,
415
- cwd: baseCwd,
416
- category: 'SUBAGENT_FANOUT_BLOCKED',
417
- detectorId: det05.detectorId,
418
- ring0Violation: false,
419
- modelId,
420
- savedTokens: 0,
421
- savedUSD: 0,
422
- detail: det05.reason
423
- },
424
- cwdOptions
425
- );
426
- }
427
- return finalize({
428
- exitCode: 2,
429
- stdout: '',
430
- stderr: det05.reason,
431
- verdict: det05
432
- });
433
- }
434
-
435
- if (shouldPersistState) {
436
- recordSubagentSpawnAtomicSync(
437
- sessionId,
438
- { nowMs: nowSubagentMs, burstWindowSec },
439
- cwdOptions
440
- );
441
- }
442
-
443
- if (det05.triggered) {
444
- if (advisoryNotice) {
445
- advisoryNotice = {
446
- ...advisoryNotice,
447
- additionalContext: [
448
- advisoryNotice.additionalContext || advisoryNotice.reason,
449
- det05.additionalContext || det05.reason
450
- ]
451
- .filter(Boolean)
452
- .join('\n'),
453
- reason: [advisoryNotice.reason, det05.reason].filter(Boolean).join('\n')
454
- };
455
- } else {
456
- advisoryNotice = det05;
457
- }
458
- }
459
- }
460
-
461
- // 6. Bounded Read Guard & Per-File Read-Interval Cache (`updatedInput`)
462
- const isSubagent = Boolean(
463
- canonical.isSidechain ||
464
- canonical.agentId ||
465
- canonical.parentToolUseId ||
466
- event.isSidechain ||
467
- event.is_sidechain ||
468
- event.agent_id ||
469
- event.agentId ||
470
- event.parent_tool_use_id ||
471
- event.parentToolUseId
472
- );
473
- const nowSnapMs = options.nowMs ?? Date.now();
474
- const readIntervalTtlMs = Math.max(
475
- 1000,
476
- Number(
477
- options.readIntervalTtlMs ??
478
- policy.readClamp?.intervalTtlMs ??
479
- guardsCfg.readIntervalTtlMs ??
480
- DEFAULT_READ_INTERVAL_TTL_MS
481
- )
482
- );
483
- const isReadTool = READ_TOOL_REGEX.test(toolName);
484
- if (isReadTool && rawPath && !/\.(?:ipynb|pdf)$/i.test(rawPath)) {
485
- const rawStartBound = tIn.offset ?? tIn.StartLine ?? tIn.start_line;
486
- const rawEndBound = tIn.EndLine ?? tIn.end_line;
487
- const rawLimitBound = tIn.limit;
488
- const hasLineBounds =
489
- rawStartBound !== undefined ||
490
- rawEndBound !== undefined ||
491
- rawLimitBound !== undefined ||
492
- tIn.pages !== undefined;
493
- const hasExplicitLineSlice =
494
- rawStartBound !== undefined || rawEndBound !== undefined || rawLimitBound !== undefined;
495
-
496
- let effectiveSliceOffset = hasExplicitLineSlice
497
- ? Math.max(1, Math.floor(Number(rawStartBound) || 1))
498
- : null;
499
- let effectiveSliceLimit = hasExplicitLineSlice
500
- ? rawLimitBound !== undefined && Number.isFinite(Number(rawLimitBound))
501
- ? Math.max(1, Math.floor(Number(rawLimitBound)))
502
- : rawEndBound !== undefined && Number.isFinite(Number(rawEndBound))
503
- ? Math.max(1, Math.floor(Number(rawEndBound)) - effectiveSliceOffset + 1)
504
- : null
505
- : null;
506
-
507
- let trimmedByInterval = null;
508
- if (!isSubagent && hasExplicitLineSlice && shouldPersistState && rawCwd) {
509
- try {
510
- const absIntPath = path.isAbsolute(rawPath) ? path.resolve(rawPath) : path.resolve(baseCwd, rawPath);
511
- if (fs.existsSync(absIntPath)) {
512
- const stInt = fs.statSync(absIntPath);
513
- if (stInt.isFile() && stInt.size > 0 && stInt.size <= 1024 * 1024) {
514
- const normIntKey = absIntPath.replace(/\\/g, '/').toLowerCase();
515
- const { store: intStore } = loadReadSnapStore(baseCwd, sessionId, cwdOptions);
516
- const entry = intStore.__readIntervals?.[normIntKey];
517
- const recordedAt = Number(entry?.recordedAt || 0);
518
- const entryFresh = recordedAt > 0 && nowSnapMs - recordedAt <= readIntervalTtlMs;
519
- const entryValid =
520
- entry &&
521
- entryFresh &&
522
- Number(entry.mtimeMs) === Number(stInt.mtimeMs) &&
523
- Number(entry.size) === Number(stInt.size) &&
524
- Array.isArray(entry.intervals) &&
525
- entry.intervals.length > 0;
526
- if (entryValid) {
527
- const rawIntSrc = fs.readFileSync(absIntPath, 'utf8');
528
- const totalFileLines =
529
- rawIntSrc.length === 0 ? 0 : rawIntSrc.replace(/\r\n/g, '\n').split('\n').length;
530
- const reqStart = effectiveSliceOffset || 1;
531
- const reqEnd = effectiveSliceLimit
532
- ? Math.min(totalFileLines, reqStart + effectiveSliceLimit - 1)
533
- : totalFileLines;
534
- const trimRes = trimRequestedRangeAgainstIntervals(reqStart, reqEnd, entry.intervals);
535
- if (trimRes.status === 'trimmed') {
536
- const avgBytesPerLine = totalFileLines > 0 ? stInt.size / totalFileLines : 40;
537
- const savedTok = Math.max(10, Math.round((trimRes.savedLines * avgBytesPerLine) / 4));
538
- effectiveSliceOffset = trimRes.offset;
539
- effectiveSliceLimit = trimRes.limit;
540
- trimmedByInterval = {
541
- reqStart,
542
- reqEnd,
543
- offset: trimRes.offset,
544
- limit: trimRes.limit,
545
- savedTokens: savedTok,
546
- absPath: absIntPath,
547
- normKey: normIntKey,
548
- statObj: stInt
549
- };
550
- }
551
- }
552
- }
553
- }
554
- } catch (intErr) {
555
- void intErr; // ignore: non-fatal read-interval lookup falls through to Read guard
556
- }
557
- }
558
-
559
- const eventUsage = event.usage || event.context_window?.current_usage || null;
560
- const promptTok = Math.max(
561
- computeTotalPromptTokens(event),
562
- eventUsage ? computeTotalPromptTokens(eventUsage) : 0
563
- );
564
-
565
- const shieldVerdict = evaluateShieldReadGuard({
566
- sessionId,
567
- cwd: baseCwd,
568
- homeDir: options.homeDir,
569
- filePath: rawPath,
570
- hasSliceBounds: hasExplicitLineSlice || hasLineBounds,
571
- sliceOffset: effectiveSliceOffset,
572
- sliceLimit: effectiveSliceLimit,
573
- currentPromptTokens: promptTok,
574
- modelId,
575
- policy,
576
- shieldConfig: options.shieldConfig,
577
- forceActive: Boolean(options.shieldForceActive),
578
- recordLedger: canRecordLedger,
579
- ledgerPath: options.ledgerPath
580
- });
581
-
582
- if (shieldVerdict.action === 'clamp') {
583
- if (!isSubagent && shouldPersistState && rawCwd && !shieldVerdict.hugeFileFastClamp) {
584
- try {
585
- const absClampPath = path.isAbsolute(rawPath) ? path.resolve(rawPath) : path.resolve(baseCwd, rawPath);
586
- if (fs.existsSync(absClampPath) && fs.statSync(absClampPath).isFile()) {
587
- const stClamp = fs.statSync(absClampPath);
588
- const clampStart = shieldVerdict.clampOffset || 1;
589
- const clampEnd = clampStart + shieldVerdict.clampLimit - 1;
590
- updateReadSnapStoreAtomicSync(
591
- baseCwd,
592
- sessionId,
593
- (store) => {
594
- recordReadIntervalEntry(
595
- store,
596
- absClampPath.replace(/\\/g, '/').toLowerCase(),
597
- stClamp,
598
- clampStart,
599
- clampEnd,
600
- nowSnapMs
601
- );
602
- return store;
603
- },
604
- cwdOptions
605
- );
606
- }
607
- } catch (clampIntErr) {
608
- void clampIntErr; // ignore: non-fatal read interval update after clamp
609
- }
610
- }
611
-
612
- const updatedInput = { ...tIn };
613
- delete updatedInput.StartLine;
614
- delete updatedInput.EndLine;
615
- updatedInput.offset = shieldVerdict.clampOffset || 1;
616
- updatedInput.limit = shieldVerdict.clampLimit;
617
- const clampOut = {
618
- hookSpecificOutput: {
619
- hookEventName: 'PreToolUse',
620
- permissionDecision: 'allow',
621
- updatedInput,
622
- additionalContext: shieldVerdict.reason
623
- }
624
- };
625
- return finalize({
626
- exitCode: 0,
627
- stdout: JSON.stringify(clampOut),
628
- stderr: '',
629
- verdict: {
630
- triggered: true,
631
- detectorId: shieldVerdict.detectorId,
632
- triggerReason: shieldVerdict.triggerReason,
633
- decision: 'allow',
634
- updatedInput,
635
- clampOffset: updatedInput.offset,
636
- clampLimit: updatedInput.limit,
637
- hugeFileFastClamp: Boolean(shieldVerdict.hugeFileFastClamp),
638
- reason: shieldVerdict.reason,
639
- fileBytes: shieldVerdict.fileBytes,
640
- maxBytes: shieldVerdict.maxBytes,
641
- clampedBytes: shieldVerdict.clampedBytes,
642
- savedTokens: shieldVerdict.savedTokens,
643
- rawClampedTokens: shieldVerdict.rawClampedTokens,
644
- savedUSD: shieldVerdict.savedUSD
645
- }
646
- });
647
- }
648
-
649
- if (shieldVerdict.action === 'deny') {
650
- const denyOut = {
651
- hookSpecificOutput: {
652
- hookEventName: 'PreToolUse',
653
- permissionDecision: 'deny',
654
- permissionDecisionReason: shieldVerdict.reason
655
- }
656
- };
657
- return finalize({
658
- exitCode: 0,
659
- stdout: JSON.stringify(denyOut),
660
- stderr: '',
661
- verdict: {
662
- triggered: true,
663
- detectorId: shieldVerdict.detectorId,
664
- triggerReason: shieldVerdict.triggerReason,
665
- decision: 'deny',
666
- reason: shieldVerdict.reason,
667
- fileBytes: shieldVerdict.fileBytes,
668
- maxBytes: shieldVerdict.maxBytes,
669
- savedTokens: shieldVerdict.savedTokens,
670
- savedUSD: shieldVerdict.savedUSD
671
- }
672
- });
673
- }
674
-
675
- if (trimmedByInterval) {
676
- updateReadSnapStoreAtomicSync(
677
- baseCwd,
678
- sessionId,
679
- (store) => {
680
- recordReadIntervalEntry(
681
- store,
682
- trimmedByInterval.normKey,
683
- trimmedByInterval.statObj,
684
- trimmedByInterval.offset,
685
- trimmedByInterval.offset + trimmedByInterval.limit - 1,
686
- nowSnapMs
687
- );
688
- return store;
689
- },
690
- cwdOptions
691
- );
692
- if (canRecordLedger) {
693
- recordInterventionSavings(
694
- {
695
- sessionId,
696
- category: 'BOUNDED_READ_ENFORCED',
697
- modelId,
698
- savedTokens: trimmedByInterval.savedTokens,
699
- dedupeId:
700
- canonical.toolUseId ||
701
- `interval_trim:${sessionId}:${path.basename(trimmedByInterval.absPath)}:${trimmedByInterval.reqStart}:${trimmedByInterval.reqEnd}`,
702
- detail: `Trimmed overlapping read of ${path.basename(trimmedByInterval.absPath)} to L${trimmedByInterval.offset}-L${trimmedByInterval.offset + trimmedByInterval.limit - 1}`
703
- },
704
- cwdOptions
705
- );
706
- }
707
- const updatedInput = { ...tIn };
708
- delete updatedInput.StartLine;
709
- delete updatedInput.EndLine;
710
- updatedInput.offset = trimmedByInterval.offset;
711
- updatedInput.limit = trimmedByInterval.limit;
712
- const trimReason =
713
- `[Burnoff Read-Interval Trim] L${trimmedByInterval.reqStart}..L${trimmedByInterval.reqEnd} overlapped already-loaded lines ` +
714
- `of ${path.basename(trimmedByInterval.absPath)}; trimmed to unread L${trimmedByInterval.offset}..L${trimmedByInterval.offset + trimmedByInterval.limit - 1}.`;
715
- const allowOut = {
716
- hookSpecificOutput: {
717
- hookEventName: 'PreToolUse',
718
- permissionDecision: 'allow',
719
- updatedInput,
720
- additionalContext: trimReason
721
- }
722
- };
723
- return finalize({
724
- exitCode: 0,
725
- stdout: JSON.stringify(allowOut),
726
- stderr: '',
727
- verdict: {
728
- triggered: true,
729
- detectorId: 'DET-06',
730
- subType: 'READ_INTERVAL_TRIM',
731
- decision: 'allow',
732
- updatedInput,
733
- savedTokens: trimmedByInterval.savedTokens,
734
- reason: trimReason
735
- }
736
- });
737
- }
738
-
739
- // Record clean explicit or small full Read interval into read_snapshots_<sid>.json
740
- if (!isSubagent && shouldPersistState && rawCwd) {
741
- try {
742
- const absRecPath = path.isAbsolute(rawPath) ? path.resolve(rawPath) : path.resolve(baseCwd, rawPath);
743
- if (fs.existsSync(absRecPath) && fs.statSync(absRecPath).isFile()) {
744
- const stRec = fs.statSync(absRecPath);
745
- if (stRec.size > 0 && stRec.size <= 1024 * 1024) {
746
- const rawRecSrc = fs.readFileSync(absRecPath, 'utf8');
747
- const totalRecLines =
748
- rawRecSrc.length === 0 ? 0 : rawRecSrc.replace(/\r\n/g, '\n').split('\n').length;
749
- const recStart = hasExplicitLineSlice ? (effectiveSliceOffset || 1) : 1;
750
- const recEnd = hasExplicitLineSlice && effectiveSliceLimit
751
- ? Math.min(totalRecLines, recStart + effectiveSliceLimit - 1)
752
- : totalRecLines;
753
- updateReadSnapStoreAtomicSync(
754
- baseCwd,
755
- sessionId,
756
- (store) => {
757
- recordReadIntervalEntry(
758
- store,
759
- absRecPath.replace(/\\/g, '/').toLowerCase(),
760
- stRec,
761
- recStart,
762
- recEnd,
763
- nowSnapMs
764
- );
765
- return store;
766
- },
767
- cwdOptions
768
- );
769
- }
770
- }
771
- } catch (recErr) {
772
- void recErr; // ignore: non-fatal read snapshot record
773
- }
774
- }
775
- }
776
-
777
- // Acquire DET-20 concurrent scope lock when allowing Edit/Write/MultiEdit/NotebookEdit
778
- if (
779
- EDIT_WRITE_SCOPE_LOCK_REGEX.test(toolName) &&
780
- rawPath &&
781
- shouldPersistState &&
782
- guardsCfg.scopeLockEnabled !== false
783
- ) {
784
- const scopeLockRes = acquireScopeLock(
785
- {
786
- ownerId,
787
- scopes: [rawPath],
788
- ttlMs: Number(options.scopeLockTtlMs ?? guardsCfg.scopeLockTtlMs ?? 120_000),
789
- mergeOwnerScopes: true
790
- },
791
- { ...cwdOptions, nowMs: options.nowMs ?? Date.now() }
792
- );
793
- if (scopeLockRes && scopeLockRes.acquired === false && scopeLockRes.conflict) {
794
- const conflictVerdict = {
795
- detectorId: 'DET-20',
796
- triggered: true,
797
- decision: 'deny',
798
- subType: 'SCOPE_LOCK_CONFLICT',
799
- conflictingOwner: scopeLockRes.conflict.ownerId,
800
- conflictingScope: scopeLockRes.conflict.conflictingScope,
801
- targetFilePath: rawPath,
802
- reason:
803
- `[Burnoff DET-20 Concurrent Scope Lock] File "${rawPath}" is locked by active worker "${scopeLockRes.conflict.ownerId}" ` +
804
- `(scope "${scopeLockRes.conflict.conflictingScope}"). Wait for lock release before editing.`
805
- };
806
- return finalize({
807
- exitCode: 2,
808
- stdout: '',
809
- stderr: conflictVerdict.reason,
810
- verdict: conflictVerdict
811
- });
812
- }
813
- }
814
-
815
- if (advisoryNotice) {
816
- const advOut = {
817
- hookSpecificOutput: {
818
- hookEventName: 'PreToolUse',
819
- permissionDecision: 'allow',
820
- additionalContext: advisoryNotice.additionalContext || advisoryNotice.reason
821
- }
822
- };
823
- return finalize({
824
- exitCode: 0,
825
- stdout: JSON.stringify(advOut),
826
- stderr: '',
827
- verdict: advisoryNotice
828
- });
829
- }
830
-
831
- return finalize({
832
- exitCode: 0,
833
- stdout: '',
834
- stderr: '',
835
- verdict: { triggered: false, decision: 'allow', reason: null }
836
- });
837
- }
838
-
839
- /**
840
- * Evaluates a `PreToolUse` hook event and returns the host-formatted exit/stdout contract.
841
- */
842
- export function runPreToolUseHook(event = {}, options = {}) {
843
- return evaluatePreToolUseCore(event, options);
844
- }
845
-
846
- export default { runPreToolUseHook };
1
+ /**
2
+ * @file src/guards/pre-tool-engine.mjs
3
+ * Pure ESM orchestrator for Claude Code `PreToolUse` evaluation.
4
+ * Enforces `.burnoff.yaml` policy, `DET-01`..`DET-04` + `DET-20` guards,
5
+ * read-interval overlap trimming, and bounded `Read` (`updatedInput`) clamping.
6
+ */
7
+
8
+ import fs from 'node:fs';
9
+ import path from 'node:path';
10
+ import { getClientAdapter, normalizeHookEvent } from '../clients/detect.mjs';
11
+ import { tryTier1PreToolFastPath } from '../../hooks/hook-io.mjs';
12
+ import { loadBurnoffPolicy } from '../config/policy.mjs';
13
+ import { computeTotalPromptTokens } from '../config/loader.mjs';
14
+ import { recordInterventionSavings, recordSavingsReceipt } from '../storage/ledger.mjs';
15
+ import {
16
+ SHELL_TOOL_REGEX,
17
+ evaluateDet01GitAndShellSafety,
18
+ evaluateDet02SecretBoundary,
19
+ evaluateDet03ProtectedFilesAskGate
20
+ } from './shell-guard.mjs';
21
+ import {
22
+ SUBAGENT_TOOL_REGEX,
23
+ acquireScopeLock,
24
+ evaluateDet04ConsecutiveFailures,
25
+ evaluateDet05SubagentFanout,
26
+ evaluateScopeAndQuotaBrake,
27
+ readBreakerStateSnapshot,
28
+ recordSubagentSpawnAtomicSync,
29
+ updateBreakerStateAtomicSync
30
+ } from './loop-breaker.mjs';
31
+ import {
32
+ DEFAULT_READ_INTERVAL_TTL_MS,
33
+ evaluateShieldReadGuard,
34
+ loadReadSnapStore,
35
+ trimRequestedRangeAgainstIntervals,
36
+ recordReadIntervalEntry,
37
+ updateReadSnapStoreAtomicSync
38
+ } from './read-clamp.mjs';
39
+ import {
40
+ consumeMatchingAskSnoozeAtomicSync,
41
+ matchesSnoozeEntry
42
+ } from './snooze.mjs';
43
+ import {
44
+ PHASE5_DEFAULTS,
45
+ evaluateDet07CommandOutputGuard,
46
+ evaluateDet08EditIntegrityGuard,
47
+ evaluateDet09EditThrash
48
+ } from './phase5-detectors.mjs';
49
+
50
+ const READ_TOOL_REGEX = /^(?:Read|read_file|view_file)$/i;
51
+ const EDIT_WRITE_OR_READ_REGEX = /^(?:Edit|Write|MultiEdit|NotebookEdit|Read|Grep|Glob|read_file|view_file|grep_search)$/i;
52
+ const EDIT_WRITE_SCOPE_LOCK_REGEX = /^(?:Edit|Write|MultiEdit|NotebookEdit)$/i;
53
+
54
+ function evaluatePreToolUseCore(event = {}, options = {}) {
55
+ const { client, adapter, canonical } =
56
+ event && event.__canonical === true
57
+ ? { client: event.client || 'claude-code', adapter: getClientAdapter(event.client || 'claude-code'), canonical: event }
58
+ : normalizeHookEvent(event, options);
59
+
60
+ const finalize = (res) => (client === 'antigravity' ? adapter.renderPre(res) : res);
61
+
62
+ const toolName = String(canonical.toolName || '');
63
+ const fastAllowRes = tryTier1PreToolFastPath(
64
+ {
65
+ ...event,
66
+ toolName,
67
+ toolInput: canonical.toolInput,
68
+ cwd: canonical.cwd || options.cwd || ''
69
+ },
70
+ options
71
+ );
72
+ if (fastAllowRes) {
73
+ return finalize(fastAllowRes);
74
+ }
75
+
76
+ const sessionId = String(canonical.sessionId || 'default');
77
+ const rawCwd = canonical.cwd || options.cwd || '';
78
+ const cwdOptions = { ...(rawCwd ? { ...options, cwd: rawCwd } : options), client };
79
+ const baseCwd = rawCwd ? path.resolve(String(rawCwd)) : process.cwd();
80
+ const policy = options.policy || loadBurnoffPolicy(baseCwd);
81
+ const guardsCfg = policy.guards || {};
82
+
83
+ const shouldPersistState =
84
+ options.persistState !== false &&
85
+ Boolean(canonical.cwd || options.cwd || options.breakerStatePath || options.persistState);
86
+ const canRecordLedger =
87
+ options.recordLedger !== false &&
88
+ Boolean(canonical.cwd || options.cwd || options.ledgerPath || options.recordLedger);
89
+
90
+ const priorSnap = shouldPersistState
91
+ ? readBreakerStateSnapshot(sessionId, cwdOptions)
92
+ : null;
93
+
94
+ if (policy?.exists && policy?.parseError && !priorSnap?.policyParseErrorWarned) {
95
+ const writeStderr =
96
+ options.stderrWrite || ((msg) => globalThis.process?.stderr?.write?.(msg));
97
+ const errDetail = policy.parseErrorMessage ? `: ${policy.parseErrorMessage}` : '';
98
+ writeStderr(
99
+ `[Burnoff Policy Warning] Failed to parse ${path.basename(policy.sourcePath || '.burnoff.yaml')}${errDetail}; falling back to safe defaults.\n`
100
+ );
101
+ if (shouldPersistState) {
102
+ try {
103
+ updateBreakerStateAtomicSync(
104
+ sessionId,
105
+ (prior) => ({
106
+ ...(prior && typeof prior === 'object' ? prior : {}),
107
+ schemaVersion: '1.0.0',
108
+ sessionId,
109
+ policyParseErrorWarned: true,
110
+ updatedAt: options.nowMs ?? Date.now()
111
+ }),
112
+ cwdOptions
113
+ );
114
+ } catch (warnErr) {
115
+ void warnErr; // ignore: best-effort parseError warning state persistence
116
+ }
117
+ }
118
+ }
119
+
120
+ const tIn = canonical.toolInput || {};
121
+ const command = String(tIn.command || tIn.CommandLine || tIn.cmd || event.command || '');
122
+ const rawPath = String(
123
+ tIn.file_path || tIn.notebook_path || tIn.filePath || tIn.path || tIn.Path || tIn.TargetFile || event.filePath || ''
124
+ ).trim();
125
+ const modelId = canonical.model || 'claude-sonnet-5-5';
126
+ const lastUserInput = canonical.lastUserInput || '';
127
+ const guardMode = event.mode ?? options.mode ?? guardsCfg.mode ?? 'guard';
128
+ const flightMode = event.flightMode ?? options.flightMode;
129
+ const ownerId = String(
130
+ canonical.agentId || event.ownerId || event.agentId || event.subagentId || sessionId
131
+ );
132
+
133
+ // Resolves interactive `ask` verdicts against active session/workspace snoozes.
134
+ // Security invariant: NEVER invoke for `deny` / `exitCode: 2` verdicts.
135
+ const evaluateAskWithSnooze = (verdict, targetText = '') => {
136
+ const evalNowMs = options.nowMs ?? Date.now();
137
+ let match = null;
138
+ if (Array.isArray(options.snoozes)) {
139
+ const memHit = options.snoozes.find((entry) =>
140
+ matchesSnoozeEntry(entry, { detectorId: verdict.detectorId, target: targetText, nowMs: evalNowMs })
141
+ );
142
+ if (memHit) {
143
+ if (memHit.remaining !== null && memHit.remaining !== undefined) {
144
+ memHit.remaining = Math.max(0, Number(memHit.remaining) - 1);
145
+ }
146
+ match = { matched: true, source: 'memory', grant: memHit };
147
+ }
148
+ } else if (shouldPersistState) {
149
+ match = consumeMatchingAskSnoozeAtomicSync(
150
+ {
151
+ sessionId,
152
+ detectorId: verdict.detectorId,
153
+ target: targetText,
154
+ nowMs: evalNowMs
155
+ },
156
+ cwdOptions
157
+ );
158
+ }
159
+
160
+ if (match?.matched) {
161
+ return {
162
+ snoozed: true,
163
+ response: finalize({
164
+ exitCode: 0,
165
+ stdout: '',
166
+ stderr: '',
167
+ snoozed: true,
168
+ verdict: {
169
+ ...verdict,
170
+ decision: 'allow',
171
+ snoozed: true,
172
+ snoozeGrantId: match.grant?.id || null,
173
+ reason: `[Burnoff Snoozed ${verdict.detectorId}] Allowed via active ${match.source || 'session'} grant.`
174
+ }
175
+ })
176
+ };
177
+ }
178
+
179
+ const askOut = {
180
+ hookSpecificOutput: {
181
+ hookEventName: 'PreToolUse',
182
+ permissionDecision: 'ask',
183
+ permissionDecisionReason: verdict.reason
184
+ }
185
+ };
186
+ return {
187
+ snoozed: false,
188
+ response: finalize({
189
+ exitCode: 0,
190
+ stdout: JSON.stringify(askOut),
191
+ stderr: '',
192
+ verdict
193
+ })
194
+ };
195
+ };
196
+
197
+ let advisoryNotice = null;
198
+ const appendAdvisory = (existing, nextVerdict) => {
199
+ if (!existing) return nextVerdict;
200
+ return {
201
+ ...existing,
202
+ additionalContext: [
203
+ existing.additionalContext || existing.reason,
204
+ nextVerdict.additionalContext || nextVerdict.reason
205
+ ]
206
+ .filter(Boolean)
207
+ .join('\n'),
208
+ reason: [existing.reason, nextVerdict.reason].filter(Boolean).join('\n')
209
+ };
210
+ };
211
+
212
+ const handlePhase5Verdict = (verdict, snoozeTarget, ledgerCategory) => {
213
+ if (!verdict || !verdict.triggered) return null;
214
+ if (verdict.decision === 'allow') {
215
+ advisoryNotice = appendAdvisory(advisoryNotice, verdict);
216
+ return null;
217
+ }
218
+ if (verdict.decision === 'ask') {
219
+ const evaluated = evaluateAskWithSnooze(verdict, snoozeTarget);
220
+ if (evaluated.snoozed) {
221
+ return evaluated.response;
222
+ }
223
+ if (canRecordLedger) {
224
+ recordSavingsReceipt(
225
+ {
226
+ sessionId,
227
+ cwd: baseCwd,
228
+ category: ledgerCategory,
229
+ detectorId: verdict.detectorId,
230
+ ring0Violation: false,
231
+ modelId,
232
+ savedTokens: 0,
233
+ savedUSD: 0,
234
+ detail: verdict.reason
235
+ },
236
+ cwdOptions
237
+ );
238
+ }
239
+ return evaluated.response;
240
+ }
241
+ if (canRecordLedger) {
242
+ recordSavingsReceipt(
243
+ {
244
+ sessionId,
245
+ cwd: baseCwd,
246
+ category: ledgerCategory,
247
+ detectorId: verdict.detectorId,
248
+ ring0Violation: false,
249
+ modelId,
250
+ savedTokens: 0,
251
+ savedUSD: 0,
252
+ detail: verdict.reason
253
+ },
254
+ cwdOptions
255
+ );
256
+ }
257
+ return finalize({
258
+ exitCode: 2,
259
+ stdout: '',
260
+ stderr: verdict.reason,
261
+ verdict
262
+ });
263
+ };
264
+
265
+ // 1. DET-20: Concurrent file-scope locks & quota hard brakes
266
+ if (guardsCfg.scopeLockEnabled !== false) {
267
+ const isReadOp = READ_TOOL_REGEX.test(toolName);
268
+ const det20 = evaluateScopeAndQuotaBrake(
269
+ {
270
+ targetFilePath: EDIT_WRITE_OR_READ_REGEX.test(toolName) ? rawPath : '',
271
+ isRead: isReadOp,
272
+ toolName,
273
+ ownerId,
274
+ rateLimits: event.rateLimits || options.rateLimits || {}
275
+ },
276
+ cwdOptions
277
+ );
278
+ if (det20.triggered) {
279
+ if (det20.decision === 'deny') {
280
+ return finalize({
281
+ exitCode: 2,
282
+ stdout: '',
283
+ stderr: det20.reason,
284
+ verdict: det20
285
+ });
286
+ }
287
+ advisoryNotice = det20;
288
+ }
289
+ }
290
+
291
+ // 2. DET-01: Destructive Shell & Git Safety
292
+ if (guardsCfg.det01Enabled !== false && SHELL_TOOL_REGEX.test(toolName) && command) {
293
+ const det01 = evaluateDet01GitAndShellSafety({
294
+ toolName,
295
+ command,
296
+ mode: event.mode ?? options.mode ?? guardsCfg.mode ?? 'guard',
297
+ flightMode: event.flightMode ?? options.flightMode,
298
+ recentGitStashAtMs:
299
+ event.recentGitStashAtMs ?? options.recentGitStashAtMs ?? priorSnap?.lastGitStashAtMs ?? null,
300
+ strictTestIntegrity:
301
+ options.strictTestIntegrity ?? event.strictTestIntegrity ?? guardsCfg.strictTestIntegrity ?? false,
302
+ lastUserInput,
303
+ nowMs: options.nowMs
304
+ });
305
+ if (det01.triggered) {
306
+ if (det01.decision === 'ask') {
307
+ return evaluateAskWithSnooze(det01, command).response;
308
+ }
309
+ if (canRecordLedger) {
310
+ recordSavingsReceipt(
311
+ {
312
+ sessionId,
313
+ cwd: baseCwd,
314
+ category: 'RING0_VIOLATION_BLOCKED',
315
+ detectorId: det01.detectorId,
316
+ ring0Violation: true,
317
+ modelId,
318
+ savedTokens: 0,
319
+ savedUSD: 0,
320
+ detail: det01.reason
321
+ },
322
+ cwdOptions
323
+ );
324
+ }
325
+ return finalize({
326
+ exitCode: 2,
327
+ stdout: '',
328
+ stderr: det01.reason,
329
+ verdict: det01
330
+ });
331
+ }
332
+ }
333
+
334
+ // 3. DET-02: Secret & Credential Boundary
335
+ if (guardsCfg.det02Enabled !== false) {
336
+ const det02 = evaluateDet02SecretBoundary({
337
+ toolName,
338
+ filePath: rawPath,
339
+ path: rawPath,
340
+ command,
341
+ mode: guardMode,
342
+ flightMode,
343
+ secretAllow: options.secretAllow ?? guardsCfg.secretAllow ?? []
344
+ });
345
+ if (det02.triggered) {
346
+ if (det02.decision === 'ask') {
347
+ return evaluateAskWithSnooze(det02, rawPath || command).response;
348
+ }
349
+ if (canRecordLedger) {
350
+ recordSavingsReceipt(
351
+ {
352
+ sessionId,
353
+ cwd: baseCwd,
354
+ category: 'RING0_VIOLATION_BLOCKED',
355
+ detectorId: det02.detectorId,
356
+ ring0Violation: true,
357
+ modelId,
358
+ savedTokens: 0,
359
+ savedUSD: 0,
360
+ detail: det02.reason
361
+ },
362
+ cwdOptions
363
+ );
364
+ }
365
+ return finalize({
366
+ exitCode: 2,
367
+ stdout: '',
368
+ stderr: det02.reason,
369
+ verdict: det02
370
+ });
371
+ }
372
+ }
373
+
374
+ // 4. DET-03: Protected Migration, Lockfile & Workflow Ask Gate
375
+ if (guardsCfg.det03Enabled !== false) {
376
+ const det03 = evaluateDet03ProtectedFilesAskGate({
377
+ toolName,
378
+ filePath: rawPath
379
+ });
380
+ if (det03.triggered && det03.decision === 'ask') {
381
+ return evaluateAskWithSnooze(det03, rawPath).response;
382
+ }
383
+ }
384
+
385
+ // 5. DET-04: Consecutive Failure Loop Breaker
386
+ if (guardsCfg.det04Enabled !== false) {
387
+ const consecutiveFailures = Number(
388
+ event.consecutiveFailures ?? options.consecutiveFailures ?? priorSnap?.consecutiveFailures ?? 0
389
+ );
390
+ const det04 = evaluateDet04ConsecutiveFailures({
391
+ consecutiveFailures,
392
+ lastFailedToolKey: priorSnap?.lastFailedToolKey || null,
393
+ toolName,
394
+ command,
395
+ filePath: rawPath,
396
+ mode: guardMode,
397
+ flightMode,
398
+ maxConsecutiveFailures:
399
+ options.maxConsecutiveFailures ?? guardsCfg.det04Threshold ?? 3
400
+ });
401
+ if (det04.triggered) {
402
+ if (det04.decision === 'ask') {
403
+ const evaluated = evaluateAskWithSnooze(det04, rawPath || command);
404
+ if (evaluated.snoozed) {
405
+ return evaluated.response;
406
+ }
407
+ if (canRecordLedger) {
408
+ recordSavingsReceipt(
409
+ {
410
+ sessionId,
411
+ cwd: baseCwd,
412
+ category: 'LOOP_TURN_PREVENTED',
413
+ detectorId: det04.detectorId,
414
+ ring0Violation: false,
415
+ modelId,
416
+ savedTokens: 0,
417
+ savedUSD: 0,
418
+ detail: det04.reason
419
+ },
420
+ cwdOptions
421
+ );
422
+ }
423
+ return evaluated.response;
424
+ }
425
+ if (canRecordLedger) {
426
+ recordSavingsReceipt(
427
+ {
428
+ sessionId,
429
+ cwd: baseCwd,
430
+ category: 'RING0_VIOLATION_BLOCKED',
431
+ detectorId: det04.detectorId,
432
+ ring0Violation: true,
433
+ modelId,
434
+ savedTokens: 0,
435
+ savedUSD: 0,
436
+ detail: det04.reason
437
+ },
438
+ cwdOptions
439
+ );
440
+ }
441
+ return finalize({
442
+ exitCode: 2,
443
+ stdout: '',
444
+ stderr: det04.reason,
445
+ verdict: det04
446
+ });
447
+ }
448
+ }
449
+
450
+ // 5b. DET-05: Subagent Fan-Out & Prompt-Bloat Guard
451
+ if (guardsCfg.subagentFanoutEnabled !== false && SUBAGENT_TOOL_REGEX.test(toolName)) {
452
+ const subagentPromptText = String(
453
+ tIn.prompt || tIn.Prompt || tIn.instructions || tIn.description || ''
454
+ );
455
+ const burstWindowSec = Number(
456
+ options.subagentBurstWindowSec ?? guardsCfg.subagentBurstWindowSec ?? 60
457
+ );
458
+ const nowSubagentMs = options.nowMs ?? Date.now();
459
+ const det05 = evaluateDet05SubagentFanout({
460
+ toolName,
461
+ promptText: subagentPromptText,
462
+ recentSpawnTimestampsMs:
463
+ event.recentSpawnTimestampsMs ??
464
+ options.recentSpawnTimestampsMs ??
465
+ priorSnap?.subagentSpawnTimestampsMs ??
466
+ [],
467
+ maxBurstCount:
468
+ options.subagentMaxBurstCount ?? guardsCfg.subagentMaxBurstCount ?? 4,
469
+ burstWindowSec,
470
+ maxPromptChars:
471
+ options.subagentMaxPromptChars ?? guardsCfg.subagentMaxPromptChars ?? 8000,
472
+ action:
473
+ options.subagentFanoutAction ?? guardsCfg.subagentFanoutAction ?? 'advisory',
474
+ nowMs: nowSubagentMs
475
+ });
476
+
477
+ if (det05.triggered && det05.decision === 'deny') {
478
+ if (canRecordLedger) {
479
+ recordSavingsReceipt(
480
+ {
481
+ sessionId,
482
+ cwd: baseCwd,
483
+ category: 'SUBAGENT_FANOUT_BLOCKED',
484
+ detectorId: det05.detectorId,
485
+ ring0Violation: false,
486
+ modelId,
487
+ savedTokens: 0,
488
+ savedUSD: 0,
489
+ detail: det05.reason
490
+ },
491
+ cwdOptions
492
+ );
493
+ }
494
+ return finalize({
495
+ exitCode: 2,
496
+ stdout: '',
497
+ stderr: det05.reason,
498
+ verdict: det05
499
+ });
500
+ }
501
+
502
+ if (shouldPersistState) {
503
+ recordSubagentSpawnAtomicSync(
504
+ sessionId,
505
+ { nowMs: nowSubagentMs, burstWindowSec },
506
+ cwdOptions
507
+ );
508
+ }
509
+
510
+ if (det05.triggered) {
511
+ advisoryNotice = appendAdvisory(advisoryNotice, det05);
512
+ }
513
+ }
514
+
515
+ // 5c. DET-07: Bash Stdout-Flood & Read-Clamp Bypass Guard
516
+ if (guardsCfg.det07Enabled !== false && SHELL_TOOL_REGEX.test(toolName) && command) {
517
+ const det07 = evaluateDet07CommandOutputGuard({
518
+ toolName,
519
+ command,
520
+ cwd: baseCwd,
521
+ mode: guardMode,
522
+ flightMode,
523
+ action: options.det07Action ?? guardsCfg.det07Action ?? PHASE5_DEFAULTS.det07Action,
524
+ maxBytes:
525
+ options.det07ReadBypassMaxBytes ??
526
+ guardsCfg.det07ReadBypassMaxBytes ??
527
+ policy.readClamp?.maxBytes ??
528
+ PHASE5_DEFAULTS.det07ReadBypassMaxBytes,
529
+ maxLines:
530
+ options.det07ReadBypassMaxLines ??
531
+ guardsCfg.det07ReadBypassMaxLines ??
532
+ policy.readClamp?.maxLines ??
533
+ PHASE5_DEFAULTS.det07ReadBypassMaxLines,
534
+ neverClampExt: policy.readClamp?.neverClampExt ?? [],
535
+ neverClampCodeOffCliff: policy.readClamp?.neverClampCodeOffCliff ?? true
536
+ });
537
+ const det07Response = handlePhase5Verdict(det07, command, 'STDOUT_FLOOD_GUARDED');
538
+ if (det07Response) return det07Response;
539
+ }
540
+
541
+ // 5d. DET-08: Edit-Time Test-Weakening & Empty-Catch Guard (runs before DET-20 lock)
542
+ if (guardsCfg.det08Enabled !== false && EDIT_WRITE_SCOPE_LOCK_REGEX.test(toolName) && rawPath) {
543
+ const det08 = evaluateDet08EditIntegrityGuard({
544
+ toolName,
545
+ filePath: rawPath,
546
+ toolInput: tIn,
547
+ cwd: baseCwd,
548
+ mode: guardMode,
549
+ flightMode,
550
+ action: options.det08Action ?? guardsCfg.det08Action ?? PHASE5_DEFAULTS.det08Action,
551
+ checkTestSkip:
552
+ options.det08CheckTestSkip ?? guardsCfg.det08CheckTestSkip ?? PHASE5_DEFAULTS.det08CheckTestSkip,
553
+ checkEmptyCatch:
554
+ options.det08CheckEmptyCatch ?? guardsCfg.det08CheckEmptyCatch ?? PHASE5_DEFAULTS.det08CheckEmptyCatch
555
+ });
556
+ const det08Response = handlePhase5Verdict(det08, rawPath, 'EDIT_INTEGRITY_GUARDED');
557
+ if (det08Response) return det08Response;
558
+ }
559
+
560
+ // 5e. DET-09: Same-File Rapid Edit-Thrash Breaker (runs before DET-20 lock)
561
+ if (guardsCfg.det09Enabled !== false && EDIT_WRITE_SCOPE_LOCK_REGEX.test(toolName) && rawPath) {
562
+ const det09 = evaluateDet09EditThrash({
563
+ toolName,
564
+ filePath: rawPath,
565
+ cwd: baseCwd,
566
+ editThrashHistory:
567
+ event.editThrashHistory ??
568
+ options.editThrashHistory ??
569
+ priorSnap?.editThrashHistory ??
570
+ {},
571
+ maxEditsPerFile:
572
+ options.det09MaxEditsPerFile ??
573
+ guardsCfg.det09MaxEditsPerFile ??
574
+ PHASE5_DEFAULTS.det09MaxEditsPerFile,
575
+ windowSec:
576
+ options.det09WindowSec ??
577
+ guardsCfg.det09WindowSec ??
578
+ PHASE5_DEFAULTS.det09WindowSec,
579
+ mode: guardMode,
580
+ flightMode,
581
+ action: options.det09Action ?? guardsCfg.det09Action ?? PHASE5_DEFAULTS.det09Action,
582
+ nowMs: options.nowMs ?? Date.now()
583
+ });
584
+ const det09Response = handlePhase5Verdict(det09, rawPath, 'EDIT_THRASH_GUARDED');
585
+ if (det09Response) return det09Response;
586
+ }
587
+
588
+ // 6. Bounded Read Guard & Per-File Read-Interval Cache (`updatedInput`)
589
+ const isSubagent = Boolean(
590
+ canonical.isSidechain ||
591
+ canonical.agentId ||
592
+ canonical.parentToolUseId ||
593
+ event.isSidechain ||
594
+ event.is_sidechain ||
595
+ event.agent_id ||
596
+ event.agentId ||
597
+ event.parent_tool_use_id ||
598
+ event.parentToolUseId
599
+ );
600
+ const nowSnapMs = options.nowMs ?? Date.now();
601
+ const readIntervalTtlMs = Math.max(
602
+ 1000,
603
+ Number(
604
+ options.readIntervalTtlMs ??
605
+ policy.readClamp?.intervalTtlMs ??
606
+ guardsCfg.readIntervalTtlMs ??
607
+ DEFAULT_READ_INTERVAL_TTL_MS
608
+ )
609
+ );
610
+ const isReadTool = READ_TOOL_REGEX.test(toolName);
611
+ if (isReadTool && rawPath && !/\.(?:ipynb|pdf)$/i.test(rawPath)) {
612
+ const rawStartBound = tIn.offset ?? tIn.StartLine ?? tIn.start_line;
613
+ const rawEndBound = tIn.EndLine ?? tIn.end_line;
614
+ const rawLimitBound = tIn.limit;
615
+ const hasLineBounds =
616
+ rawStartBound !== undefined ||
617
+ rawEndBound !== undefined ||
618
+ rawLimitBound !== undefined ||
619
+ tIn.pages !== undefined;
620
+ const hasExplicitLineSlice =
621
+ rawStartBound !== undefined || rawEndBound !== undefined || rawLimitBound !== undefined;
622
+
623
+ let effectiveSliceOffset = hasExplicitLineSlice
624
+ ? Math.max(1, Math.floor(Number(rawStartBound) || 1))
625
+ : null;
626
+ let effectiveSliceLimit = hasExplicitLineSlice
627
+ ? rawLimitBound !== undefined && Number.isFinite(Number(rawLimitBound))
628
+ ? Math.max(1, Math.floor(Number(rawLimitBound)))
629
+ : rawEndBound !== undefined && Number.isFinite(Number(rawEndBound))
630
+ ? Math.max(1, Math.floor(Number(rawEndBound)) - effectiveSliceOffset + 1)
631
+ : null
632
+ : null;
633
+
634
+ let trimmedByInterval = null;
635
+ if (!isSubagent && hasExplicitLineSlice && shouldPersistState && rawCwd) {
636
+ try {
637
+ const absIntPath = path.isAbsolute(rawPath) ? path.resolve(rawPath) : path.resolve(baseCwd, rawPath);
638
+ if (fs.existsSync(absIntPath)) {
639
+ const stInt = fs.statSync(absIntPath);
640
+ if (stInt.isFile() && stInt.size > 0 && stInt.size <= 1024 * 1024) {
641
+ const normIntKey = absIntPath.replace(/\\/g, '/').toLowerCase();
642
+ const { store: intStore } = loadReadSnapStore(baseCwd, sessionId, cwdOptions);
643
+ const entry = intStore.__readIntervals?.[normIntKey];
644
+ const recordedAt = Number(entry?.recordedAt || 0);
645
+ const entryFresh = recordedAt > 0 && nowSnapMs - recordedAt <= readIntervalTtlMs;
646
+ const entryValid =
647
+ entry &&
648
+ entryFresh &&
649
+ Number(entry.mtimeMs) === Number(stInt.mtimeMs) &&
650
+ Number(entry.size) === Number(stInt.size) &&
651
+ Array.isArray(entry.intervals) &&
652
+ entry.intervals.length > 0;
653
+ if (entryValid) {
654
+ const rawIntSrc = fs.readFileSync(absIntPath, 'utf8');
655
+ const totalFileLines =
656
+ rawIntSrc.length === 0 ? 0 : rawIntSrc.replace(/\r\n/g, '\n').split('\n').length;
657
+ const reqStart = effectiveSliceOffset || 1;
658
+ const reqEnd = effectiveSliceLimit
659
+ ? Math.min(totalFileLines, reqStart + effectiveSliceLimit - 1)
660
+ : totalFileLines;
661
+ const trimRes = trimRequestedRangeAgainstIntervals(reqStart, reqEnd, entry.intervals);
662
+ if (trimRes.status === 'trimmed') {
663
+ const avgBytesPerLine = totalFileLines > 0 ? stInt.size / totalFileLines : 40;
664
+ const savedTok = Math.max(10, Math.round((trimRes.savedLines * avgBytesPerLine) / 4));
665
+ effectiveSliceOffset = trimRes.offset;
666
+ effectiveSliceLimit = trimRes.limit;
667
+ trimmedByInterval = {
668
+ reqStart,
669
+ reqEnd,
670
+ offset: trimRes.offset,
671
+ limit: trimRes.limit,
672
+ savedTokens: savedTok,
673
+ absPath: absIntPath,
674
+ normKey: normIntKey,
675
+ statObj: stInt
676
+ };
677
+ }
678
+ }
679
+ }
680
+ }
681
+ } catch (intErr) {
682
+ void intErr; // ignore: non-fatal read-interval lookup falls through to Read guard
683
+ }
684
+ }
685
+
686
+ const eventUsage = event.usage || event.context_window?.current_usage || null;
687
+ const promptTok = Math.max(
688
+ computeTotalPromptTokens(event),
689
+ eventUsage ? computeTotalPromptTokens(eventUsage) : 0
690
+ );
691
+
692
+ const shieldVerdict = evaluateShieldReadGuard({
693
+ sessionId,
694
+ cwd: baseCwd,
695
+ homeDir: options.homeDir,
696
+ filePath: rawPath,
697
+ hasSliceBounds: hasExplicitLineSlice || hasLineBounds,
698
+ sliceOffset: effectiveSliceOffset,
699
+ sliceLimit: effectiveSliceLimit,
700
+ currentPromptTokens: promptTok,
701
+ modelId,
702
+ policy,
703
+ shieldConfig: options.shieldConfig,
704
+ forceActive: Boolean(options.shieldForceActive),
705
+ recordLedger: canRecordLedger,
706
+ ledgerPath: options.ledgerPath
707
+ });
708
+
709
+ if (shieldVerdict.action === 'clamp') {
710
+ if (!isSubagent && shouldPersistState && rawCwd && !shieldVerdict.hugeFileFastClamp) {
711
+ try {
712
+ const absClampPath = path.isAbsolute(rawPath) ? path.resolve(rawPath) : path.resolve(baseCwd, rawPath);
713
+ if (fs.existsSync(absClampPath) && fs.statSync(absClampPath).isFile()) {
714
+ const stClamp = fs.statSync(absClampPath);
715
+ const clampStart = shieldVerdict.clampOffset || 1;
716
+ const clampEnd = clampStart + shieldVerdict.clampLimit - 1;
717
+ updateReadSnapStoreAtomicSync(
718
+ baseCwd,
719
+ sessionId,
720
+ (store) => {
721
+ recordReadIntervalEntry(
722
+ store,
723
+ absClampPath.replace(/\\/g, '/').toLowerCase(),
724
+ stClamp,
725
+ clampStart,
726
+ clampEnd,
727
+ nowSnapMs
728
+ );
729
+ return store;
730
+ },
731
+ cwdOptions
732
+ );
733
+ }
734
+ } catch (clampIntErr) {
735
+ void clampIntErr; // ignore: non-fatal read interval update after clamp
736
+ }
737
+ }
738
+
739
+ const updatedInput = { ...tIn };
740
+ delete updatedInput.StartLine;
741
+ delete updatedInput.EndLine;
742
+ updatedInput.offset = shieldVerdict.clampOffset || 1;
743
+ updatedInput.limit = shieldVerdict.clampLimit;
744
+ const clampOut = {
745
+ hookSpecificOutput: {
746
+ hookEventName: 'PreToolUse',
747
+ permissionDecision: 'allow',
748
+ updatedInput,
749
+ additionalContext: shieldVerdict.reason
750
+ }
751
+ };
752
+ return finalize({
753
+ exitCode: 0,
754
+ stdout: JSON.stringify(clampOut),
755
+ stderr: '',
756
+ verdict: {
757
+ triggered: true,
758
+ detectorId: shieldVerdict.detectorId,
759
+ triggerReason: shieldVerdict.triggerReason,
760
+ decision: 'allow',
761
+ updatedInput,
762
+ clampOffset: updatedInput.offset,
763
+ clampLimit: updatedInput.limit,
764
+ hugeFileFastClamp: Boolean(shieldVerdict.hugeFileFastClamp),
765
+ reason: shieldVerdict.reason,
766
+ fileBytes: shieldVerdict.fileBytes,
767
+ maxBytes: shieldVerdict.maxBytes,
768
+ clampedBytes: shieldVerdict.clampedBytes,
769
+ savedTokens: shieldVerdict.savedTokens,
770
+ rawClampedTokens: shieldVerdict.rawClampedTokens,
771
+ savedUSD: shieldVerdict.savedUSD
772
+ }
773
+ });
774
+ }
775
+
776
+ if (shieldVerdict.action === 'deny') {
777
+ const denyOut = {
778
+ hookSpecificOutput: {
779
+ hookEventName: 'PreToolUse',
780
+ permissionDecision: 'deny',
781
+ permissionDecisionReason: shieldVerdict.reason
782
+ }
783
+ };
784
+ return finalize({
785
+ exitCode: 0,
786
+ stdout: JSON.stringify(denyOut),
787
+ stderr: '',
788
+ verdict: {
789
+ triggered: true,
790
+ detectorId: shieldVerdict.detectorId,
791
+ triggerReason: shieldVerdict.triggerReason,
792
+ decision: 'deny',
793
+ reason: shieldVerdict.reason,
794
+ fileBytes: shieldVerdict.fileBytes,
795
+ maxBytes: shieldVerdict.maxBytes,
796
+ savedTokens: shieldVerdict.savedTokens,
797
+ savedUSD: shieldVerdict.savedUSD
798
+ }
799
+ });
800
+ }
801
+
802
+ if (trimmedByInterval) {
803
+ updateReadSnapStoreAtomicSync(
804
+ baseCwd,
805
+ sessionId,
806
+ (store) => {
807
+ recordReadIntervalEntry(
808
+ store,
809
+ trimmedByInterval.normKey,
810
+ trimmedByInterval.statObj,
811
+ trimmedByInterval.offset,
812
+ trimmedByInterval.offset + trimmedByInterval.limit - 1,
813
+ nowSnapMs
814
+ );
815
+ return store;
816
+ },
817
+ cwdOptions
818
+ );
819
+ if (canRecordLedger) {
820
+ recordInterventionSavings(
821
+ {
822
+ sessionId,
823
+ category: 'BOUNDED_READ_ENFORCED',
824
+ modelId,
825
+ savedTokens: trimmedByInterval.savedTokens,
826
+ dedupeId:
827
+ canonical.toolUseId ||
828
+ `interval_trim:${sessionId}:${path.basename(trimmedByInterval.absPath)}:${trimmedByInterval.reqStart}:${trimmedByInterval.reqEnd}`,
829
+ detail: `Trimmed overlapping read of ${path.basename(trimmedByInterval.absPath)} to L${trimmedByInterval.offset}-L${trimmedByInterval.offset + trimmedByInterval.limit - 1}`
830
+ },
831
+ cwdOptions
832
+ );
833
+ }
834
+ const updatedInput = { ...tIn };
835
+ delete updatedInput.StartLine;
836
+ delete updatedInput.EndLine;
837
+ updatedInput.offset = trimmedByInterval.offset;
838
+ updatedInput.limit = trimmedByInterval.limit;
839
+ const trimReason =
840
+ `[Burnoff Read-Interval Trim] L${trimmedByInterval.reqStart}..L${trimmedByInterval.reqEnd} overlapped already-loaded lines ` +
841
+ `of ${path.basename(trimmedByInterval.absPath)}; trimmed to unread L${trimmedByInterval.offset}..L${trimmedByInterval.offset + trimmedByInterval.limit - 1}.`;
842
+ const allowOut = {
843
+ hookSpecificOutput: {
844
+ hookEventName: 'PreToolUse',
845
+ permissionDecision: 'allow',
846
+ updatedInput,
847
+ additionalContext: trimReason
848
+ }
849
+ };
850
+ return finalize({
851
+ exitCode: 0,
852
+ stdout: JSON.stringify(allowOut),
853
+ stderr: '',
854
+ verdict: {
855
+ triggered: true,
856
+ detectorId: 'DET-06',
857
+ subType: 'READ_INTERVAL_TRIM',
858
+ decision: 'allow',
859
+ updatedInput,
860
+ savedTokens: trimmedByInterval.savedTokens,
861
+ reason: trimReason
862
+ }
863
+ });
864
+ }
865
+
866
+ // Record clean explicit or small full Read interval into read_snapshots_<sid>.json
867
+ if (!isSubagent && shouldPersistState && rawCwd) {
868
+ try {
869
+ const absRecPath = path.isAbsolute(rawPath) ? path.resolve(rawPath) : path.resolve(baseCwd, rawPath);
870
+ if (fs.existsSync(absRecPath) && fs.statSync(absRecPath).isFile()) {
871
+ const stRec = fs.statSync(absRecPath);
872
+ if (stRec.size > 0 && stRec.size <= 1024 * 1024) {
873
+ const rawRecSrc = fs.readFileSync(absRecPath, 'utf8');
874
+ const totalRecLines =
875
+ rawRecSrc.length === 0 ? 0 : rawRecSrc.replace(/\r\n/g, '\n').split('\n').length;
876
+ const recStart = hasExplicitLineSlice ? (effectiveSliceOffset || 1) : 1;
877
+ const recEnd = hasExplicitLineSlice && effectiveSliceLimit
878
+ ? Math.min(totalRecLines, recStart + effectiveSliceLimit - 1)
879
+ : totalRecLines;
880
+ updateReadSnapStoreAtomicSync(
881
+ baseCwd,
882
+ sessionId,
883
+ (store) => {
884
+ recordReadIntervalEntry(
885
+ store,
886
+ absRecPath.replace(/\\/g, '/').toLowerCase(),
887
+ stRec,
888
+ recStart,
889
+ recEnd,
890
+ nowSnapMs
891
+ );
892
+ return store;
893
+ },
894
+ cwdOptions
895
+ );
896
+ }
897
+ }
898
+ } catch (recErr) {
899
+ void recErr; // ignore: non-fatal read snapshot record
900
+ }
901
+ }
902
+ }
903
+
904
+ // Acquire DET-20 concurrent scope lock when allowing Edit/Write/MultiEdit/NotebookEdit
905
+ if (
906
+ EDIT_WRITE_SCOPE_LOCK_REGEX.test(toolName) &&
907
+ rawPath &&
908
+ shouldPersistState &&
909
+ guardsCfg.scopeLockEnabled !== false
910
+ ) {
911
+ const scopeLockRes = acquireScopeLock(
912
+ {
913
+ ownerId,
914
+ scopes: [rawPath],
915
+ ttlMs: Number(options.scopeLockTtlMs ?? guardsCfg.scopeLockTtlMs ?? 120_000),
916
+ mergeOwnerScopes: true
917
+ },
918
+ { ...cwdOptions, nowMs: options.nowMs ?? Date.now() }
919
+ );
920
+ if (scopeLockRes && scopeLockRes.acquired === false && scopeLockRes.conflict) {
921
+ const conflictVerdict = {
922
+ detectorId: 'DET-20',
923
+ triggered: true,
924
+ decision: 'deny',
925
+ subType: 'SCOPE_LOCK_CONFLICT',
926
+ conflictingOwner: scopeLockRes.conflict.ownerId,
927
+ conflictingScope: scopeLockRes.conflict.conflictingScope,
928
+ targetFilePath: rawPath,
929
+ reason:
930
+ `[Burnoff DET-20 Concurrent Scope Lock] File "${rawPath}" is locked by active worker "${scopeLockRes.conflict.ownerId}" ` +
931
+ `(scope "${scopeLockRes.conflict.conflictingScope}"). Wait for lock release before editing.`
932
+ };
933
+ return finalize({
934
+ exitCode: 2,
935
+ stdout: '',
936
+ stderr: conflictVerdict.reason,
937
+ verdict: conflictVerdict
938
+ });
939
+ }
940
+ }
941
+
942
+ if (advisoryNotice) {
943
+ const advOut = {
944
+ hookSpecificOutput: {
945
+ hookEventName: 'PreToolUse',
946
+ permissionDecision: 'allow',
947
+ additionalContext: advisoryNotice.additionalContext || advisoryNotice.reason
948
+ }
949
+ };
950
+ return finalize({
951
+ exitCode: 0,
952
+ stdout: JSON.stringify(advOut),
953
+ stderr: '',
954
+ verdict: advisoryNotice
955
+ });
956
+ }
957
+
958
+ return finalize({
959
+ exitCode: 0,
960
+ stdout: '',
961
+ stderr: '',
962
+ verdict: { triggered: false, decision: 'allow', reason: null }
963
+ });
964
+ }
965
+
966
+ /**
967
+ * Evaluates a `PreToolUse` hook event and returns the host-formatted exit/stdout contract.
968
+ */
969
+ export function runPreToolUseHook(event = {}, options = {}) {
970
+ return evaluatePreToolUseCore(event, options);
971
+ }
972
+
973
+ export default { runPreToolUseHook };