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