burnoff 1.0.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/.github/workflows/burnoff-pr-gate.yml +75 -0
  2. package/README.md +94 -20
  3. package/bin/burnoff.mjs +129 -30
  4. package/hooks/hook-io.mjs +27 -18
  5. package/hooks/post-tool-use.mjs +33 -26
  6. package/hooks/pre-tool-use.mjs +43 -41
  7. package/hooks/session-lifecycle.mjs +40 -0
  8. package/package.json +8 -5
  9. package/src/ci/ci-gate.mjs +84 -9
  10. package/src/ci/pr-cost.mjs +207 -22
  11. package/src/ci/team-digest.mjs +6 -4
  12. package/src/cli/audit.mjs +177 -23
  13. package/src/cli/doctor.mjs +230 -25
  14. package/src/cli/init.mjs +415 -75
  15. package/src/cli/startup-audit.mjs +2824 -0
  16. package/src/clients/antigravity.mjs +285 -0
  17. package/src/clients/claude-code.mjs +180 -0
  18. package/src/clients/detect.mjs +64 -0
  19. package/src/config/catalog.json +188 -45
  20. package/src/config/loader.mjs +96 -13
  21. package/src/config/paths.mjs +92 -2
  22. package/src/config/policy.mjs +103 -17
  23. package/src/config/pricing.mjs +1033 -0
  24. package/src/config/uncached-attribution.mjs +719 -0
  25. package/src/guards/loop-breaker.mjs +267 -24
  26. package/src/guards/post-tool-engine.mjs +316 -35
  27. package/src/guards/pre-tool-engine.mjs +389 -130
  28. package/src/guards/read-clamp.mjs +149 -75
  29. package/src/guards/session-hook.mjs +207 -0
  30. package/src/guards/shell-guard.mjs +610 -74
  31. package/src/ipc/daemon.mjs +50 -8
  32. package/src/ipc/fast-client.mjs +62 -5
  33. package/src/ipc/protocol.mjs +1 -1
  34. package/src/storage/antigravity-parser.mjs +258 -0
  35. package/src/storage/atomic-io.mjs +2 -2
  36. package/src/storage/file-lock.mjs +66 -13
  37. package/src/storage/fts5-archive.mjs +31 -16
  38. package/src/storage/jsonl-parser.mjs +209 -20
  39. package/src/storage/ledger.mjs +15 -10
  40. package/src/storage/sqlite-client.mjs +35 -11
  41. package/hooks/hooks.json +0 -12
@@ -7,9 +7,10 @@
7
7
 
8
8
  import fs from 'node:fs';
9
9
  import path from 'node:path';
10
+ import { getClientAdapter, normalizeHookEvent } from '../clients/detect.mjs';
10
11
  import { loadBurnoffPolicy } from '../config/policy.mjs';
11
12
  import { computeTotalPromptTokens } from '../config/loader.mjs';
12
- import { recordInterventionSavings } from '../storage/ledger.mjs';
13
+ import { recordInterventionSavings, recordSavingsReceipt } from '../storage/ledger.mjs';
13
14
  import {
14
15
  SHELL_TOOL_REGEX,
15
16
  evaluateDet01GitAndShellSafety,
@@ -17,11 +18,17 @@ import {
17
18
  evaluateDet03ProtectedFilesAskGate
18
19
  } from './shell-guard.mjs';
19
20
  import {
21
+ SUBAGENT_TOOL_REGEX,
22
+ acquireScopeLock,
20
23
  evaluateDet04ConsecutiveFailures,
24
+ evaluateDet05SubagentFanout,
21
25
  evaluateScopeAndQuotaBrake,
22
- readBreakerStateSnapshot
26
+ readBreakerStateSnapshot,
27
+ recordSubagentSpawnAtomicSync,
28
+ updateBreakerStateAtomicSync
23
29
  } from './loop-breaker.mjs';
24
30
  import {
31
+ DEFAULT_READ_INTERVAL_TTL_MS,
25
32
  evaluateShieldReadGuard,
26
33
  loadReadSnapStore,
27
34
  trimRequestedRangeAgainstIntervals,
@@ -31,6 +38,7 @@ import {
31
38
 
32
39
  const READ_TOOL_REGEX = /^(?:Read|read_file|view_file)$/i;
33
40
  const EDIT_WRITE_OR_READ_REGEX = /^(?:Edit|Write|MultiEdit|NotebookEdit|Read|Grep|Glob|read_file|view_file|grep_search)$/i;
41
+ const EDIT_WRITE_SCOPE_LOCK_REGEX = /^(?:Edit|Write|MultiEdit|NotebookEdit)$/i;
34
42
 
35
43
  function isTier1ActiveFastPath(toolName, event, options) {
36
44
  const tier1Active = Boolean(
@@ -41,47 +49,81 @@ function isTier1ActiveFastPath(toolName, event, options) {
41
49
  return tier1Active && /^(?:Grep|Glob)$/i.test(toolName);
42
50
  }
43
51
 
44
- /**
45
- * Evaluates a `PreToolUse` hook event and returns Claude Code's structured exit/stdout contract.
46
- */
47
- export function runPreToolUseHook(event = {}, options = {}) {
48
- const toolName = String(event.tool_name || event.toolName || '');
52
+ function evaluatePreToolUseCore(event = {}, options = {}) {
53
+ const { client, adapter, canonical } =
54
+ event && event.__canonical === true
55
+ ? { client: event.client || 'claude-code', adapter: getClientAdapter(event.client || 'claude-code'), canonical: event }
56
+ : normalizeHookEvent(event, options);
57
+
58
+ const finalize = (res) => (client === 'antigravity' ? adapter.renderPre(res) : res);
59
+
60
+ const toolName = String(canonical.toolName || '');
49
61
  if (isTier1ActiveFastPath(toolName, event, options)) {
50
- return {
62
+ return finalize({
51
63
  exitCode: 0,
52
64
  stdout: '',
53
65
  stderr: '',
54
66
  fastPath: 'tier1_active',
55
67
  verdict: { triggered: false, decision: 'allow', reason: 'Handled via Tier-1 fast path' }
56
- };
68
+ });
57
69
  }
58
70
 
59
- const sessionId = String(event.session_id || event.sessionId || 'default');
60
- const rawCwd = event.cwd || options.cwd || '';
61
- const cwdOptions = rawCwd ? { ...options, cwd: rawCwd } : options;
71
+ const sessionId = String(canonical.sessionId || 'default');
72
+ const rawCwd = canonical.cwd || options.cwd || '';
73
+ const cwdOptions = { ...(rawCwd ? { ...options, cwd: rawCwd } : options), client };
62
74
  const baseCwd = rawCwd ? path.resolve(String(rawCwd)) : process.cwd();
63
75
  const policy = options.policy || loadBurnoffPolicy(baseCwd);
64
76
  const guardsCfg = policy.guards || {};
65
77
 
66
78
  const shouldPersistState =
67
79
  options.persistState !== false &&
68
- Boolean(event.cwd || options.cwd || options.breakerStatePath || options.persistState);
80
+ Boolean(canonical.cwd || options.cwd || options.breakerStatePath || options.persistState);
69
81
  const canRecordLedger =
70
82
  options.recordLedger !== false &&
71
- Boolean(event.cwd || options.cwd || options.ledgerPath || options.recordLedger);
83
+ Boolean(canonical.cwd || options.cwd || options.ledgerPath || options.recordLedger);
72
84
 
73
85
  const priorSnap = shouldPersistState
74
86
  ? readBreakerStateSnapshot(sessionId, cwdOptions)
75
87
  : null;
76
88
 
77
- const tIn = event.tool_input || event.toolInput || event.args || {};
89
+ if (policy?.exists && policy?.parseError && !priorSnap?.policyParseErrorWarned) {
90
+ const writeStderr =
91
+ options.stderrWrite || ((msg) => globalThis.process?.stderr?.write?.(msg));
92
+ const errDetail = policy.parseErrorMessage ? `: ${policy.parseErrorMessage}` : '';
93
+ writeStderr(
94
+ `[Burnoff Policy Warning] Failed to parse ${path.basename(policy.sourcePath || '.burnoff.yaml')}${errDetail}; falling back to safe defaults.\n`
95
+ );
96
+ if (shouldPersistState) {
97
+ try {
98
+ updateBreakerStateAtomicSync(
99
+ sessionId,
100
+ (prior) => ({
101
+ ...(prior && typeof prior === 'object' ? prior : {}),
102
+ schemaVersion: '1.0.0',
103
+ sessionId,
104
+ policyParseErrorWarned: true,
105
+ updatedAt: options.nowMs ?? Date.now()
106
+ }),
107
+ cwdOptions
108
+ );
109
+ } catch (warnErr) {
110
+ void warnErr; // ignore: best-effort parseError warning state persistence
111
+ }
112
+ }
113
+ }
114
+
115
+ const tIn = canonical.toolInput || {};
78
116
  const command = String(tIn.command || tIn.CommandLine || tIn.cmd || event.command || '');
79
117
  const rawPath = String(
80
118
  tIn.file_path || tIn.notebook_path || tIn.filePath || tIn.path || tIn.Path || tIn.TargetFile || event.filePath || ''
81
119
  ).trim();
82
- const modelId =
83
- (typeof event.model === 'string' ? event.model : event.model?.id || event.modelId || event.model_id) ||
84
- 'claude-sonnet-4-6';
120
+ const modelId = canonical.model || 'claude-sonnet-5-5';
121
+ const lastUserInput = canonical.lastUserInput || '';
122
+ const guardMode = event.mode ?? options.mode ?? guardsCfg.mode ?? 'guard';
123
+ const flightMode = event.flightMode ?? options.flightMode;
124
+ const ownerId = String(
125
+ canonical.agentId || event.ownerId || event.agentId || event.subagentId || sessionId
126
+ );
85
127
 
86
128
  let advisoryNotice = null;
87
129
 
@@ -93,19 +135,19 @@ export function runPreToolUseHook(event = {}, options = {}) {
93
135
  targetFilePath: EDIT_WRITE_OR_READ_REGEX.test(toolName) ? rawPath : '',
94
136
  isRead: isReadOp,
95
137
  toolName,
96
- ownerId: event.ownerId || event.agentId || event.subagentId || sessionId,
138
+ ownerId,
97
139
  rateLimits: event.rateLimits || options.rateLimits || {}
98
140
  },
99
141
  cwdOptions
100
142
  );
101
143
  if (det20.triggered) {
102
144
  if (det20.decision === 'deny') {
103
- return {
145
+ return finalize({
104
146
  exitCode: 2,
105
147
  stdout: '',
106
148
  stderr: det20.reason,
107
149
  verdict: det20
108
- };
150
+ });
109
151
  }
110
152
  advisoryNotice = det20;
111
153
  }
@@ -122,7 +164,7 @@ export function runPreToolUseHook(event = {}, options = {}) {
122
164
  event.recentGitStashAtMs ?? options.recentGitStashAtMs ?? priorSnap?.lastGitStashAtMs ?? null,
123
165
  strictTestIntegrity:
124
166
  options.strictTestIntegrity ?? event.strictTestIntegrity ?? guardsCfg.strictTestIntegrity ?? false,
125
- lastUserInput: event.prompt || event.lastUserInput || '',
167
+ lastUserInput,
126
168
  nowMs: options.nowMs
127
169
  });
128
170
  if (det01.triggered) {
@@ -134,19 +176,35 @@ export function runPreToolUseHook(event = {}, options = {}) {
134
176
  permissionDecisionReason: det01.reason
135
177
  }
136
178
  };
137
- return {
179
+ return finalize({
138
180
  exitCode: 0,
139
181
  stdout: JSON.stringify(askOut),
140
182
  stderr: '',
141
183
  verdict: det01
142
- };
184
+ });
185
+ }
186
+ if (canRecordLedger) {
187
+ recordSavingsReceipt(
188
+ {
189
+ sessionId,
190
+ cwd: baseCwd,
191
+ category: 'RING0_VIOLATION_BLOCKED',
192
+ detectorId: det01.detectorId,
193
+ ring0Violation: true,
194
+ modelId,
195
+ savedTokens: 0,
196
+ savedUSD: 0,
197
+ detail: det01.reason
198
+ },
199
+ cwdOptions
200
+ );
143
201
  }
144
- return {
202
+ return finalize({
145
203
  exitCode: 2,
146
204
  stdout: '',
147
205
  stderr: det01.reason,
148
206
  verdict: det01
149
- };
207
+ });
150
208
  }
151
209
  }
152
210
 
@@ -156,15 +214,49 @@ export function runPreToolUseHook(event = {}, options = {}) {
156
214
  toolName,
157
215
  filePath: rawPath,
158
216
  path: rawPath,
159
- command
217
+ command,
218
+ mode: guardMode,
219
+ flightMode,
220
+ secretAllow: options.secretAllow ?? guardsCfg.secretAllow ?? []
160
221
  });
161
222
  if (det02.triggered) {
162
- return {
223
+ if (det02.decision === 'ask') {
224
+ const askOut = {
225
+ hookSpecificOutput: {
226
+ hookEventName: 'PreToolUse',
227
+ permissionDecision: 'ask',
228
+ permissionDecisionReason: det02.reason
229
+ }
230
+ };
231
+ return finalize({
232
+ exitCode: 0,
233
+ stdout: JSON.stringify(askOut),
234
+ stderr: '',
235
+ verdict: det02
236
+ });
237
+ }
238
+ if (canRecordLedger) {
239
+ recordSavingsReceipt(
240
+ {
241
+ sessionId,
242
+ cwd: baseCwd,
243
+ category: 'RING0_VIOLATION_BLOCKED',
244
+ detectorId: det02.detectorId,
245
+ ring0Violation: true,
246
+ modelId,
247
+ savedTokens: 0,
248
+ savedUSD: 0,
249
+ detail: det02.reason
250
+ },
251
+ cwdOptions
252
+ );
253
+ }
254
+ return finalize({
163
255
  exitCode: 2,
164
256
  stdout: '',
165
257
  stderr: det02.reason,
166
258
  verdict: det02
167
- };
259
+ });
168
260
  }
169
261
  }
170
262
 
@@ -182,12 +274,12 @@ export function runPreToolUseHook(event = {}, options = {}) {
182
274
  permissionDecisionReason: det03.reason
183
275
  }
184
276
  };
185
- return {
277
+ return finalize({
186
278
  exitCode: 0,
187
279
  stdout: JSON.stringify(askOut),
188
280
  stderr: '',
189
281
  verdict: det03
190
- };
282
+ });
191
283
  }
192
284
  }
193
285
 
@@ -200,20 +292,170 @@ export function runPreToolUseHook(event = {}, options = {}) {
200
292
  consecutiveFailures,
201
293
  lastFailedToolKey: priorSnap?.lastFailedToolKey || null,
202
294
  toolName,
295
+ command,
296
+ filePath: rawPath,
297
+ mode: guardMode,
298
+ flightMode,
203
299
  maxConsecutiveFailures:
204
300
  options.maxConsecutiveFailures ?? guardsCfg.det04Threshold ?? 3
205
301
  });
206
- if (det04.triggered && det04.decision === 'deny') {
207
- return {
302
+ if (det04.triggered) {
303
+ if (det04.decision === 'ask') {
304
+ if (canRecordLedger) {
305
+ recordSavingsReceipt(
306
+ {
307
+ sessionId,
308
+ cwd: baseCwd,
309
+ category: 'LOOP_TURN_PREVENTED',
310
+ detectorId: det04.detectorId,
311
+ ring0Violation: false,
312
+ modelId,
313
+ savedTokens: 0,
314
+ savedUSD: 0,
315
+ detail: det04.reason
316
+ },
317
+ cwdOptions
318
+ );
319
+ }
320
+ const askOut = {
321
+ hookSpecificOutput: {
322
+ hookEventName: 'PreToolUse',
323
+ permissionDecision: 'ask',
324
+ permissionDecisionReason: det04.reason
325
+ }
326
+ };
327
+ return finalize({
328
+ exitCode: 0,
329
+ stdout: JSON.stringify(askOut),
330
+ stderr: '',
331
+ verdict: det04
332
+ });
333
+ }
334
+ if (canRecordLedger) {
335
+ recordSavingsReceipt(
336
+ {
337
+ sessionId,
338
+ cwd: baseCwd,
339
+ category: 'RING0_VIOLATION_BLOCKED',
340
+ detectorId: det04.detectorId,
341
+ ring0Violation: true,
342
+ modelId,
343
+ savedTokens: 0,
344
+ savedUSD: 0,
345
+ detail: det04.reason
346
+ },
347
+ cwdOptions
348
+ );
349
+ }
350
+ return finalize({
208
351
  exitCode: 2,
209
352
  stdout: '',
210
353
  stderr: det04.reason,
211
354
  verdict: det04
212
- };
355
+ });
356
+ }
357
+ }
358
+
359
+ // 5b. DET-05: Subagent Fan-Out & Prompt-Bloat Guard
360
+ if (guardsCfg.subagentFanoutEnabled !== false && SUBAGENT_TOOL_REGEX.test(toolName)) {
361
+ const subagentPromptText = String(
362
+ tIn.prompt || tIn.Prompt || tIn.instructions || tIn.description || ''
363
+ );
364
+ const burstWindowSec = Number(
365
+ options.subagentBurstWindowSec ?? guardsCfg.subagentBurstWindowSec ?? 60
366
+ );
367
+ const nowSubagentMs = options.nowMs ?? Date.now();
368
+ const det05 = evaluateDet05SubagentFanout({
369
+ toolName,
370
+ promptText: subagentPromptText,
371
+ recentSpawnTimestampsMs:
372
+ event.recentSpawnTimestampsMs ??
373
+ options.recentSpawnTimestampsMs ??
374
+ priorSnap?.subagentSpawnTimestampsMs ??
375
+ [],
376
+ maxBurstCount:
377
+ options.subagentMaxBurstCount ?? guardsCfg.subagentMaxBurstCount ?? 4,
378
+ burstWindowSec,
379
+ maxPromptChars:
380
+ options.subagentMaxPromptChars ?? guardsCfg.subagentMaxPromptChars ?? 8000,
381
+ action:
382
+ options.subagentFanoutAction ?? guardsCfg.subagentFanoutAction ?? 'advisory',
383
+ nowMs: nowSubagentMs
384
+ });
385
+
386
+ if (det05.triggered && det05.decision === 'deny') {
387
+ if (canRecordLedger) {
388
+ recordSavingsReceipt(
389
+ {
390
+ sessionId,
391
+ cwd: baseCwd,
392
+ category: 'SUBAGENT_FANOUT_BLOCKED',
393
+ detectorId: det05.detectorId,
394
+ ring0Violation: false,
395
+ modelId,
396
+ savedTokens: 0,
397
+ savedUSD: 0,
398
+ detail: det05.reason
399
+ },
400
+ cwdOptions
401
+ );
402
+ }
403
+ return finalize({
404
+ exitCode: 2,
405
+ stdout: '',
406
+ stderr: det05.reason,
407
+ verdict: det05
408
+ });
409
+ }
410
+
411
+ if (shouldPersistState) {
412
+ recordSubagentSpawnAtomicSync(
413
+ sessionId,
414
+ { nowMs: nowSubagentMs, burstWindowSec },
415
+ cwdOptions
416
+ );
417
+ }
418
+
419
+ if (det05.triggered) {
420
+ if (advisoryNotice) {
421
+ advisoryNotice = {
422
+ ...advisoryNotice,
423
+ additionalContext: [
424
+ advisoryNotice.additionalContext || advisoryNotice.reason,
425
+ det05.additionalContext || det05.reason
426
+ ]
427
+ .filter(Boolean)
428
+ .join('\n'),
429
+ reason: [advisoryNotice.reason, det05.reason].filter(Boolean).join('\n')
430
+ };
431
+ } else {
432
+ advisoryNotice = det05;
433
+ }
213
434
  }
214
435
  }
215
436
 
216
437
  // 6. Bounded Read Guard & Per-File Read-Interval Cache (`updatedInput`)
438
+ const isSubagent = Boolean(
439
+ canonical.isSidechain ||
440
+ canonical.agentId ||
441
+ canonical.parentToolUseId ||
442
+ event.isSidechain ||
443
+ event.is_sidechain ||
444
+ event.agent_id ||
445
+ event.agentId ||
446
+ event.parent_tool_use_id ||
447
+ event.parentToolUseId
448
+ );
449
+ const nowSnapMs = options.nowMs ?? Date.now();
450
+ const readIntervalTtlMs = Math.max(
451
+ 1000,
452
+ Number(
453
+ options.readIntervalTtlMs ??
454
+ policy.readClamp?.intervalTtlMs ??
455
+ guardsCfg.readIntervalTtlMs ??
456
+ DEFAULT_READ_INTERVAL_TTL_MS
457
+ )
458
+ );
217
459
  const isReadTool = READ_TOOL_REGEX.test(toolName);
218
460
  if (isReadTool && rawPath && !/\.(?:ipynb|pdf)$/i.test(rawPath)) {
219
461
  const rawStartBound = tIn.offset ?? tIn.StartLine ?? tIn.start_line;
@@ -239,17 +481,20 @@ export function runPreToolUseHook(event = {}, options = {}) {
239
481
  : null;
240
482
 
241
483
  let trimmedByInterval = null;
242
- if (hasExplicitLineSlice && shouldPersistState && rawCwd) {
484
+ if (!isSubagent && hasExplicitLineSlice && shouldPersistState && rawCwd) {
243
485
  try {
244
486
  const absIntPath = path.isAbsolute(rawPath) ? path.resolve(rawPath) : path.resolve(baseCwd, rawPath);
245
487
  if (fs.existsSync(absIntPath)) {
246
488
  const stInt = fs.statSync(absIntPath);
247
489
  if (stInt.isFile() && stInt.size > 0 && stInt.size <= 1024 * 1024) {
248
490
  const normIntKey = absIntPath.replace(/\\/g, '/').toLowerCase();
249
- const { store: intStore } = loadReadSnapStore(baseCwd, sessionId);
491
+ const { store: intStore } = loadReadSnapStore(baseCwd, sessionId, cwdOptions);
250
492
  const entry = intStore.__readIntervals?.[normIntKey];
493
+ const recordedAt = Number(entry?.recordedAt || 0);
494
+ const entryFresh = recordedAt > 0 && nowSnapMs - recordedAt <= readIntervalTtlMs;
251
495
  const entryValid =
252
496
  entry &&
497
+ entryFresh &&
253
498
  Number(entry.mtimeMs) === Number(stInt.mtimeMs) &&
254
499
  Number(entry.size) === Number(stInt.size) &&
255
500
  Array.isArray(entry.intervals) &&
@@ -263,56 +508,6 @@ export function runPreToolUseHook(event = {}, options = {}) {
263
508
  ? Math.min(totalFileLines, reqStart + effectiveSliceLimit - 1)
264
509
  : totalFileLines;
265
510
  const trimRes = trimRequestedRangeAgainstIntervals(reqStart, reqEnd, entry.intervals);
266
- if (trimRes.status === 'full_covered') {
267
- const avgBytesPerLine = totalFileLines > 0 ? stInt.size / totalFileLines : 40;
268
- const savedTok = Math.max(10, Math.round((trimRes.savedLines * avgBytesPerLine) / 4));
269
- const updatedInput = { ...tIn };
270
- delete updatedInput.StartLine;
271
- delete updatedInput.EndLine;
272
- updatedInput.offset = trimRes.anchorOffset;
273
- updatedInput.limit = trimRes.anchorLimit;
274
- if (canRecordLedger) {
275
- recordInterventionSavings(
276
- {
277
- sessionId,
278
- category: 'BOUNDED_READ_ENFORCED',
279
- modelId,
280
- savedTokens: savedTok,
281
- dedupeId:
282
- event.tool_use_id ||
283
- event.toolUseId ||
284
- `interval_anchor:${sessionId}:${path.basename(absIntPath)}:${reqStart}:${reqEnd}`,
285
- detail: `Read-interval cache anchor on ${path.basename(absIntPath)} L${reqStart}-L${reqEnd}`
286
- },
287
- cwdOptions
288
- );
289
- }
290
- const reasonMsg =
291
- `[Burnoff Read-Interval Cache] L${reqStart}..L${reqEnd} of ${path.basename(absIntPath)} (${totalFileLines} lines) ` +
292
- `already loaded cleanly; anchored to L${trimRes.anchorOffset}..L${trimRes.anchorOffset + trimRes.anchorLimit - 1}.`;
293
- const allowOut = {
294
- hookSpecificOutput: {
295
- hookEventName: 'PreToolUse',
296
- permissionDecision: 'allow',
297
- updatedInput,
298
- additionalContext: reasonMsg
299
- }
300
- };
301
- return {
302
- exitCode: 0,
303
- stdout: JSON.stringify(allowOut),
304
- stderr: '',
305
- verdict: {
306
- triggered: true,
307
- detectorId: 'DET-06',
308
- subType: 'READ_INTERVAL_ANCHOR',
309
- decision: 'allow',
310
- updatedInput,
311
- savedTokens: savedTok,
312
- reason: reasonMsg
313
- }
314
- };
315
- }
316
511
  if (trimRes.status === 'trimmed') {
317
512
  const avgBytesPerLine = totalFileLines > 0 ? stInt.size / totalFileLines : 40;
318
513
  const savedTok = Math.max(10, Math.round((trimRes.savedLines * avgBytesPerLine) / 4));
@@ -346,12 +541,14 @@ export function runPreToolUseHook(event = {}, options = {}) {
346
541
  const shieldVerdict = evaluateShieldReadGuard({
347
542
  sessionId,
348
543
  cwd: baseCwd,
544
+ homeDir: options.homeDir,
349
545
  filePath: rawPath,
350
546
  hasSliceBounds: hasExplicitLineSlice || hasLineBounds,
351
547
  sliceOffset: effectiveSliceOffset,
352
548
  sliceLimit: effectiveSliceLimit,
353
549
  currentPromptTokens: promptTok,
354
550
  modelId,
551
+ policy,
355
552
  shieldConfig: options.shieldConfig,
356
553
  forceActive: Boolean(options.shieldForceActive),
357
554
  recordLedger: canRecordLedger,
@@ -359,23 +556,29 @@ export function runPreToolUseHook(event = {}, options = {}) {
359
556
  });
360
557
 
361
558
  if (shieldVerdict.action === 'clamp') {
362
- if (shouldPersistState && rawCwd && !shieldVerdict.hugeFileFastClamp) {
559
+ if (!isSubagent && shouldPersistState && rawCwd && !shieldVerdict.hugeFileFastClamp) {
363
560
  try {
364
561
  const absClampPath = path.isAbsolute(rawPath) ? path.resolve(rawPath) : path.resolve(baseCwd, rawPath);
365
562
  if (fs.existsSync(absClampPath) && fs.statSync(absClampPath).isFile()) {
366
563
  const stClamp = fs.statSync(absClampPath);
367
564
  const clampStart = shieldVerdict.clampOffset || 1;
368
565
  const clampEnd = clampStart + shieldVerdict.clampLimit - 1;
369
- updateReadSnapStoreAtomicSync(baseCwd, sessionId, (store) => {
370
- recordReadIntervalEntry(
371
- store,
372
- absClampPath.replace(/\\/g, '/').toLowerCase(),
373
- stClamp,
374
- clampStart,
375
- clampEnd
376
- );
377
- return store;
378
- });
566
+ updateReadSnapStoreAtomicSync(
567
+ baseCwd,
568
+ sessionId,
569
+ (store) => {
570
+ recordReadIntervalEntry(
571
+ store,
572
+ absClampPath.replace(/\\/g, '/').toLowerCase(),
573
+ stClamp,
574
+ clampStart,
575
+ clampEnd,
576
+ nowSnapMs
577
+ );
578
+ return store;
579
+ },
580
+ cwdOptions
581
+ );
379
582
  }
380
583
  } catch (clampIntErr) {
381
584
  void clampIntErr; // ignore: non-fatal read interval update after clamp
@@ -395,7 +598,7 @@ export function runPreToolUseHook(event = {}, options = {}) {
395
598
  additionalContext: shieldVerdict.reason
396
599
  }
397
600
  };
398
- return {
601
+ return finalize({
399
602
  exitCode: 0,
400
603
  stdout: JSON.stringify(clampOut),
401
604
  stderr: '',
@@ -416,7 +619,7 @@ export function runPreToolUseHook(event = {}, options = {}) {
416
619
  rawClampedTokens: shieldVerdict.rawClampedTokens,
417
620
  savedUSD: shieldVerdict.savedUSD
418
621
  }
419
- };
622
+ });
420
623
  }
421
624
 
422
625
  if (shieldVerdict.action === 'deny') {
@@ -427,7 +630,7 @@ export function runPreToolUseHook(event = {}, options = {}) {
427
630
  permissionDecisionReason: shieldVerdict.reason
428
631
  }
429
632
  };
430
- return {
633
+ return finalize({
431
634
  exitCode: 0,
432
635
  stdout: JSON.stringify(denyOut),
433
636
  stderr: '',
@@ -442,20 +645,26 @@ export function runPreToolUseHook(event = {}, options = {}) {
442
645
  savedTokens: shieldVerdict.savedTokens,
443
646
  savedUSD: shieldVerdict.savedUSD
444
647
  }
445
- };
648
+ });
446
649
  }
447
650
 
448
651
  if (trimmedByInterval) {
449
- updateReadSnapStoreAtomicSync(baseCwd, sessionId, (store) => {
450
- recordReadIntervalEntry(
451
- store,
452
- trimmedByInterval.normKey,
453
- trimmedByInterval.statObj,
454
- trimmedByInterval.offset,
455
- trimmedByInterval.offset + trimmedByInterval.limit - 1
456
- );
457
- return store;
458
- });
652
+ updateReadSnapStoreAtomicSync(
653
+ baseCwd,
654
+ sessionId,
655
+ (store) => {
656
+ recordReadIntervalEntry(
657
+ store,
658
+ trimmedByInterval.normKey,
659
+ trimmedByInterval.statObj,
660
+ trimmedByInterval.offset,
661
+ trimmedByInterval.offset + trimmedByInterval.limit - 1,
662
+ nowSnapMs
663
+ );
664
+ return store;
665
+ },
666
+ cwdOptions
667
+ );
459
668
  if (canRecordLedger) {
460
669
  recordInterventionSavings(
461
670
  {
@@ -464,8 +673,7 @@ export function runPreToolUseHook(event = {}, options = {}) {
464
673
  modelId,
465
674
  savedTokens: trimmedByInterval.savedTokens,
466
675
  dedupeId:
467
- event.tool_use_id ||
468
- event.toolUseId ||
676
+ canonical.toolUseId ||
469
677
  `interval_trim:${sessionId}:${path.basename(trimmedByInterval.absPath)}:${trimmedByInterval.reqStart}:${trimmedByInterval.reqEnd}`,
470
678
  detail: `Trimmed overlapping read of ${path.basename(trimmedByInterval.absPath)} to L${trimmedByInterval.offset}-L${trimmedByInterval.offset + trimmedByInterval.limit - 1}`
471
679
  },
@@ -488,7 +696,7 @@ export function runPreToolUseHook(event = {}, options = {}) {
488
696
  additionalContext: trimReason
489
697
  }
490
698
  };
491
- return {
699
+ return finalize({
492
700
  exitCode: 0,
493
701
  stdout: JSON.stringify(allowOut),
494
702
  stderr: '',
@@ -501,11 +709,11 @@ export function runPreToolUseHook(event = {}, options = {}) {
501
709
  savedTokens: trimmedByInterval.savedTokens,
502
710
  reason: trimReason
503
711
  }
504
- };
712
+ });
505
713
  }
506
714
 
507
715
  // Record clean explicit or small full Read interval into read_snapshots_<sid>.json
508
- if (shouldPersistState && rawCwd) {
716
+ if (!isSubagent && shouldPersistState && rawCwd) {
509
717
  try {
510
718
  const absRecPath = path.isAbsolute(rawPath) ? path.resolve(rawPath) : path.resolve(baseCwd, rawPath);
511
719
  if (fs.existsSync(absRecPath) && fs.statSync(absRecPath).isFile()) {
@@ -518,16 +726,22 @@ export function runPreToolUseHook(event = {}, options = {}) {
518
726
  const recEnd = hasExplicitLineSlice && effectiveSliceLimit
519
727
  ? Math.min(totalRecLines, recStart + effectiveSliceLimit - 1)
520
728
  : totalRecLines;
521
- updateReadSnapStoreAtomicSync(baseCwd, sessionId, (store) => {
522
- recordReadIntervalEntry(
523
- store,
524
- absRecPath.replace(/\\/g, '/').toLowerCase(),
525
- stRec,
526
- recStart,
527
- recEnd
528
- );
529
- return store;
530
- });
729
+ updateReadSnapStoreAtomicSync(
730
+ baseCwd,
731
+ sessionId,
732
+ (store) => {
733
+ recordReadIntervalEntry(
734
+ store,
735
+ absRecPath.replace(/\\/g, '/').toLowerCase(),
736
+ stRec,
737
+ recStart,
738
+ recEnd,
739
+ nowSnapMs
740
+ );
741
+ return store;
742
+ },
743
+ cwdOptions
744
+ );
531
745
  }
532
746
  }
533
747
  } catch (recErr) {
@@ -536,6 +750,44 @@ export function runPreToolUseHook(event = {}, options = {}) {
536
750
  }
537
751
  }
538
752
 
753
+ // Acquire DET-20 concurrent scope lock when allowing Edit/Write/MultiEdit/NotebookEdit
754
+ if (
755
+ EDIT_WRITE_SCOPE_LOCK_REGEX.test(toolName) &&
756
+ rawPath &&
757
+ shouldPersistState &&
758
+ guardsCfg.scopeLockEnabled !== false
759
+ ) {
760
+ const scopeLockRes = acquireScopeLock(
761
+ {
762
+ ownerId,
763
+ scopes: [rawPath],
764
+ ttlMs: Number(options.scopeLockTtlMs ?? guardsCfg.scopeLockTtlMs ?? 120_000),
765
+ mergeOwnerScopes: true
766
+ },
767
+ { ...cwdOptions, nowMs: options.nowMs ?? Date.now() }
768
+ );
769
+ if (scopeLockRes && scopeLockRes.acquired === false && scopeLockRes.conflict) {
770
+ const conflictVerdict = {
771
+ detectorId: 'DET-20',
772
+ triggered: true,
773
+ decision: 'deny',
774
+ subType: 'SCOPE_LOCK_CONFLICT',
775
+ conflictingOwner: scopeLockRes.conflict.ownerId,
776
+ conflictingScope: scopeLockRes.conflict.conflictingScope,
777
+ targetFilePath: rawPath,
778
+ reason:
779
+ `[Burnoff DET-20 Concurrent Scope Lock] File "${rawPath}" is locked by active worker "${scopeLockRes.conflict.ownerId}" ` +
780
+ `(scope "${scopeLockRes.conflict.conflictingScope}"). Wait for lock release before editing.`
781
+ };
782
+ return finalize({
783
+ exitCode: 2,
784
+ stdout: '',
785
+ stderr: conflictVerdict.reason,
786
+ verdict: conflictVerdict
787
+ });
788
+ }
789
+ }
790
+
539
791
  if (advisoryNotice) {
540
792
  const advOut = {
541
793
  hookSpecificOutput: {
@@ -544,20 +796,27 @@ export function runPreToolUseHook(event = {}, options = {}) {
544
796
  additionalContext: advisoryNotice.additionalContext || advisoryNotice.reason
545
797
  }
546
798
  };
547
- return {
799
+ return finalize({
548
800
  exitCode: 0,
549
801
  stdout: JSON.stringify(advOut),
550
802
  stderr: '',
551
803
  verdict: advisoryNotice
552
- };
804
+ });
553
805
  }
554
806
 
555
- return {
807
+ return finalize({
556
808
  exitCode: 0,
557
809
  stdout: '',
558
810
  stderr: '',
559
811
  verdict: { triggered: false, decision: 'allow', reason: null }
560
- };
812
+ });
813
+ }
814
+
815
+ /**
816
+ * Evaluates a `PreToolUse` hook event and returns the host-formatted exit/stdout contract.
817
+ */
818
+ export function runPreToolUseHook(event = {}, options = {}) {
819
+ return evaluatePreToolUseCore(event, options);
561
820
  }
562
821
 
563
822
  export default { runPreToolUseHook };