burnoff 1.1.0 → 1.3.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 (45) hide show
  1. package/.claude-plugin/plugin.json +11 -0
  2. package/.github/workflows/burnoff-pr-gate.yml +3 -3
  3. package/.github/workflows/burnoff-startup-lint.yml +37 -0
  4. package/README.md +90 -75
  5. package/bin/burnoff.mjs +185 -24
  6. package/commands/burnoff.md +16 -0
  7. package/docs/CLAUDE_CODE_PLUGIN.md +67 -0
  8. package/docs/DESIGN_PARTNER_INTAKE.md +44 -0
  9. package/hooks/hook-io.mjs +19 -7
  10. package/hooks/post-tool-use.mjs +33 -26
  11. package/hooks/pre-tool-use.mjs +43 -41
  12. package/hooks/session-lifecycle.mjs +40 -0
  13. package/package.json +15 -7
  14. package/scripts/burnoff-statusline.mjs +84 -0
  15. package/src/ci/ci-gate.mjs +22 -0
  16. package/src/ci/pr-cost.mjs +42 -10
  17. package/src/ci/team-digest.mjs +5 -3
  18. package/src/cli/audit.mjs +103 -18
  19. package/src/cli/doctor.mjs +209 -14
  20. package/src/cli/init.mjs +349 -96
  21. package/src/cli/startup-audit.mjs +712 -62
  22. package/src/clients/antigravity.mjs +285 -0
  23. package/src/clients/claude-code.mjs +180 -0
  24. package/src/clients/detect.mjs +64 -0
  25. package/src/config/loader.mjs +11 -4
  26. package/src/config/paths.mjs +62 -2
  27. package/src/config/policy.mjs +34 -5
  28. package/src/config/pricing.mjs +16 -5
  29. package/src/guards/loop-breaker.mjs +198 -13
  30. package/src/guards/post-tool-engine.mjs +289 -29
  31. package/src/guards/pre-tool-engine.mjs +382 -151
  32. package/src/guards/read-clamp.mjs +78 -18
  33. package/src/guards/session-hook.mjs +207 -0
  34. package/src/guards/shell-guard.mjs +583 -73
  35. package/src/guards/snooze.mjs +360 -0
  36. package/src/ipc/daemon.mjs +50 -8
  37. package/src/ipc/fast-client.mjs +62 -5
  38. package/src/ipc/protocol.mjs +1 -1
  39. package/src/storage/antigravity-parser.mjs +258 -0
  40. package/src/storage/file-lock.mjs +13 -4
  41. package/src/storage/fts5-archive.mjs +4 -4
  42. package/src/storage/jsonl-parser.mjs +7 -1
  43. package/src/storage/ledger.mjs +10 -3
  44. package/src/storage/sqlite-client.mjs +4 -2
  45. package/hooks/hooks.json +0 -12
@@ -7,6 +7,7 @@
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
13
  import { recordInterventionSavings, recordSavingsReceipt } from '../storage/ledger.mjs';
@@ -17,20 +18,31 @@ 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,
28
35
  recordReadIntervalEntry,
29
36
  updateReadSnapStoreAtomicSync
30
37
  } from './read-clamp.mjs';
38
+ import {
39
+ consumeMatchingAskSnoozeAtomicSync,
40
+ matchesSnoozeEntry
41
+ } from './snooze.mjs';
31
42
 
32
43
  const READ_TOOL_REGEX = /^(?:Read|read_file|view_file)$/i;
33
44
  const EDIT_WRITE_OR_READ_REGEX = /^(?:Edit|Write|MultiEdit|NotebookEdit|Read|Grep|Glob|read_file|view_file|grep_search)$/i;
45
+ const EDIT_WRITE_SCOPE_LOCK_REGEX = /^(?:Edit|Write|MultiEdit|NotebookEdit)$/i;
34
46
 
35
47
  function isTier1ActiveFastPath(toolName, event, options) {
36
48
  const tier1Active = Boolean(
@@ -41,47 +53,145 @@ function isTier1ActiveFastPath(toolName, event, options) {
41
53
  return tier1Active && /^(?:Grep|Glob)$/i.test(toolName);
42
54
  }
43
55
 
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 || '');
56
+ function evaluatePreToolUseCore(event = {}, options = {}) {
57
+ const { client, adapter, canonical } =
58
+ event && event.__canonical === true
59
+ ? { client: event.client || 'claude-code', adapter: getClientAdapter(event.client || 'claude-code'), canonical: event }
60
+ : normalizeHookEvent(event, options);
61
+
62
+ const finalize = (res) => (client === 'antigravity' ? adapter.renderPre(res) : res);
63
+
64
+ const toolName = String(canonical.toolName || '');
49
65
  if (isTier1ActiveFastPath(toolName, event, options)) {
50
- return {
66
+ return finalize({
51
67
  exitCode: 0,
52
68
  stdout: '',
53
69
  stderr: '',
54
70
  fastPath: 'tier1_active',
55
71
  verdict: { triggered: false, decision: 'allow', reason: 'Handled via Tier-1 fast path' }
56
- };
72
+ });
57
73
  }
58
74
 
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;
75
+ const sessionId = String(canonical.sessionId || 'default');
76
+ const rawCwd = canonical.cwd || options.cwd || '';
77
+ const cwdOptions = { ...(rawCwd ? { ...options, cwd: rawCwd } : options), client };
62
78
  const baseCwd = rawCwd ? path.resolve(String(rawCwd)) : process.cwd();
63
79
  const policy = options.policy || loadBurnoffPolicy(baseCwd);
64
80
  const guardsCfg = policy.guards || {};
65
81
 
66
82
  const shouldPersistState =
67
83
  options.persistState !== false &&
68
- Boolean(event.cwd || options.cwd || options.breakerStatePath || options.persistState);
84
+ Boolean(canonical.cwd || options.cwd || options.breakerStatePath || options.persistState);
69
85
  const canRecordLedger =
70
86
  options.recordLedger !== false &&
71
- Boolean(event.cwd || options.cwd || options.ledgerPath || options.recordLedger);
87
+ Boolean(canonical.cwd || options.cwd || options.ledgerPath || options.recordLedger);
72
88
 
73
89
  const priorSnap = shouldPersistState
74
90
  ? readBreakerStateSnapshot(sessionId, cwdOptions)
75
91
  : null;
76
92
 
77
- const tIn = event.tool_input || event.toolInput || event.args || {};
93
+ if (policy?.exists && policy?.parseError && !priorSnap?.policyParseErrorWarned) {
94
+ const writeStderr =
95
+ options.stderrWrite || ((msg) => globalThis.process?.stderr?.write?.(msg));
96
+ const errDetail = policy.parseErrorMessage ? `: ${policy.parseErrorMessage}` : '';
97
+ writeStderr(
98
+ `[Burnoff Policy Warning] Failed to parse ${path.basename(policy.sourcePath || '.burnoff.yaml')}${errDetail}; falling back to safe defaults.\n`
99
+ );
100
+ if (shouldPersistState) {
101
+ try {
102
+ updateBreakerStateAtomicSync(
103
+ sessionId,
104
+ (prior) => ({
105
+ ...(prior && typeof prior === 'object' ? prior : {}),
106
+ schemaVersion: '1.0.0',
107
+ sessionId,
108
+ policyParseErrorWarned: true,
109
+ updatedAt: options.nowMs ?? Date.now()
110
+ }),
111
+ cwdOptions
112
+ );
113
+ } catch (warnErr) {
114
+ void warnErr; // ignore: best-effort parseError warning state persistence
115
+ }
116
+ }
117
+ }
118
+
119
+ const tIn = canonical.toolInput || {};
78
120
  const command = String(tIn.command || tIn.CommandLine || tIn.cmd || event.command || '');
79
121
  const rawPath = String(
80
122
  tIn.file_path || tIn.notebook_path || tIn.filePath || tIn.path || tIn.Path || tIn.TargetFile || event.filePath || ''
81
123
  ).trim();
82
- const modelId =
83
- (typeof event.model === 'string' ? event.model : event.model?.id || event.modelId || event.model_id) ||
84
- 'claude-sonnet-5-5';
124
+ const modelId = canonical.model || 'claude-sonnet-5-5';
125
+ const lastUserInput = canonical.lastUserInput || '';
126
+ const guardMode = event.mode ?? options.mode ?? guardsCfg.mode ?? 'guard';
127
+ const flightMode = event.flightMode ?? options.flightMode;
128
+ const ownerId = String(
129
+ canonical.agentId || event.ownerId || event.agentId || event.subagentId || sessionId
130
+ );
131
+
132
+ // Resolves interactive `ask` verdicts against active session/workspace snoozes.
133
+ // Security invariant: NEVER invoke for `deny` / `exitCode: 2` verdicts.
134
+ const evaluateAskWithSnooze = (verdict, targetText = '') => {
135
+ const evalNowMs = options.nowMs ?? Date.now();
136
+ let match = null;
137
+ if (Array.isArray(options.snoozes)) {
138
+ const memHit = options.snoozes.find((entry) =>
139
+ matchesSnoozeEntry(entry, { detectorId: verdict.detectorId, target: targetText, nowMs: evalNowMs })
140
+ );
141
+ if (memHit) {
142
+ if (memHit.remaining !== null && memHit.remaining !== undefined) {
143
+ memHit.remaining = Math.max(0, Number(memHit.remaining) - 1);
144
+ }
145
+ match = { matched: true, source: 'memory', grant: memHit };
146
+ }
147
+ } else if (shouldPersistState) {
148
+ match = consumeMatchingAskSnoozeAtomicSync(
149
+ {
150
+ sessionId,
151
+ detectorId: verdict.detectorId,
152
+ target: targetText,
153
+ nowMs: evalNowMs
154
+ },
155
+ cwdOptions
156
+ );
157
+ }
158
+
159
+ if (match?.matched) {
160
+ return {
161
+ snoozed: true,
162
+ response: finalize({
163
+ exitCode: 0,
164
+ stdout: '',
165
+ stderr: '',
166
+ snoozed: true,
167
+ verdict: {
168
+ ...verdict,
169
+ decision: 'allow',
170
+ snoozed: true,
171
+ snoozeGrantId: match.grant?.id || null,
172
+ reason: `[Burnoff Snoozed ${verdict.detectorId}] Allowed via active ${match.source || 'session'} grant.`
173
+ }
174
+ })
175
+ };
176
+ }
177
+
178
+ const askOut = {
179
+ hookSpecificOutput: {
180
+ hookEventName: 'PreToolUse',
181
+ permissionDecision: 'ask',
182
+ permissionDecisionReason: verdict.reason
183
+ }
184
+ };
185
+ return {
186
+ snoozed: false,
187
+ response: finalize({
188
+ exitCode: 0,
189
+ stdout: JSON.stringify(askOut),
190
+ stderr: '',
191
+ verdict
192
+ })
193
+ };
194
+ };
85
195
 
86
196
  let advisoryNotice = null;
87
197
 
@@ -93,19 +203,19 @@ export function runPreToolUseHook(event = {}, options = {}) {
93
203
  targetFilePath: EDIT_WRITE_OR_READ_REGEX.test(toolName) ? rawPath : '',
94
204
  isRead: isReadOp,
95
205
  toolName,
96
- ownerId: event.ownerId || event.agentId || event.subagentId || sessionId,
206
+ ownerId,
97
207
  rateLimits: event.rateLimits || options.rateLimits || {}
98
208
  },
99
209
  cwdOptions
100
210
  );
101
211
  if (det20.triggered) {
102
212
  if (det20.decision === 'deny') {
103
- return {
213
+ return finalize({
104
214
  exitCode: 2,
105
215
  stdout: '',
106
216
  stderr: det20.reason,
107
217
  verdict: det20
108
- };
218
+ });
109
219
  }
110
220
  advisoryNotice = det20;
111
221
  }
@@ -122,24 +232,12 @@ export function runPreToolUseHook(event = {}, options = {}) {
122
232
  event.recentGitStashAtMs ?? options.recentGitStashAtMs ?? priorSnap?.lastGitStashAtMs ?? null,
123
233
  strictTestIntegrity:
124
234
  options.strictTestIntegrity ?? event.strictTestIntegrity ?? guardsCfg.strictTestIntegrity ?? false,
125
- lastUserInput: event.prompt || event.lastUserInput || '',
235
+ lastUserInput,
126
236
  nowMs: options.nowMs
127
237
  });
128
238
  if (det01.triggered) {
129
239
  if (det01.decision === 'ask') {
130
- const askOut = {
131
- hookSpecificOutput: {
132
- hookEventName: 'PreToolUse',
133
- permissionDecision: 'ask',
134
- permissionDecisionReason: det01.reason
135
- }
136
- };
137
- return {
138
- exitCode: 0,
139
- stdout: JSON.stringify(askOut),
140
- stderr: '',
141
- verdict: det01
142
- };
240
+ return evaluateAskWithSnooze(det01, command).response;
143
241
  }
144
242
  if (canRecordLedger) {
145
243
  recordSavingsReceipt(
@@ -157,12 +255,12 @@ export function runPreToolUseHook(event = {}, options = {}) {
157
255
  cwdOptions
158
256
  );
159
257
  }
160
- return {
258
+ return finalize({
161
259
  exitCode: 2,
162
260
  stdout: '',
163
261
  stderr: det01.reason,
164
262
  verdict: det01
165
- };
263
+ });
166
264
  }
167
265
  }
168
266
 
@@ -172,9 +270,15 @@ export function runPreToolUseHook(event = {}, options = {}) {
172
270
  toolName,
173
271
  filePath: rawPath,
174
272
  path: rawPath,
175
- command
273
+ command,
274
+ mode: guardMode,
275
+ flightMode,
276
+ secretAllow: options.secretAllow ?? guardsCfg.secretAllow ?? []
176
277
  });
177
278
  if (det02.triggered) {
279
+ if (det02.decision === 'ask') {
280
+ return evaluateAskWithSnooze(det02, rawPath || command).response;
281
+ }
178
282
  if (canRecordLedger) {
179
283
  recordSavingsReceipt(
180
284
  {
@@ -191,12 +295,12 @@ export function runPreToolUseHook(event = {}, options = {}) {
191
295
  cwdOptions
192
296
  );
193
297
  }
194
- return {
298
+ return finalize({
195
299
  exitCode: 2,
196
300
  stdout: '',
197
301
  stderr: det02.reason,
198
302
  verdict: det02
199
- };
303
+ });
200
304
  }
201
305
  }
202
306
 
@@ -207,19 +311,7 @@ export function runPreToolUseHook(event = {}, options = {}) {
207
311
  filePath: rawPath
208
312
  });
209
313
  if (det03.triggered && det03.decision === 'ask') {
210
- const askOut = {
211
- hookSpecificOutput: {
212
- hookEventName: 'PreToolUse',
213
- permissionDecision: 'ask',
214
- permissionDecisionReason: det03.reason
215
- }
216
- };
217
- return {
218
- exitCode: 0,
219
- stdout: JSON.stringify(askOut),
220
- stderr: '',
221
- verdict: det03
222
- };
314
+ return evaluateAskWithSnooze(det03, rawPath).response;
223
315
  }
224
316
  }
225
317
 
@@ -234,10 +326,35 @@ export function runPreToolUseHook(event = {}, options = {}) {
234
326
  toolName,
235
327
  command,
236
328
  filePath: rawPath,
329
+ mode: guardMode,
330
+ flightMode,
237
331
  maxConsecutiveFailures:
238
332
  options.maxConsecutiveFailures ?? guardsCfg.det04Threshold ?? 3
239
333
  });
240
- if (det04.triggered && det04.decision === 'deny') {
334
+ if (det04.triggered) {
335
+ if (det04.decision === 'ask') {
336
+ const evaluated = evaluateAskWithSnooze(det04, rawPath || command);
337
+ if (evaluated.snoozed) {
338
+ return evaluated.response;
339
+ }
340
+ if (canRecordLedger) {
341
+ recordSavingsReceipt(
342
+ {
343
+ sessionId,
344
+ cwd: baseCwd,
345
+ category: 'LOOP_TURN_PREVENTED',
346
+ detectorId: det04.detectorId,
347
+ ring0Violation: false,
348
+ modelId,
349
+ savedTokens: 0,
350
+ savedUSD: 0,
351
+ detail: det04.reason
352
+ },
353
+ cwdOptions
354
+ );
355
+ }
356
+ return evaluated.response;
357
+ }
241
358
  if (canRecordLedger) {
242
359
  recordSavingsReceipt(
243
360
  {
@@ -254,16 +371,115 @@ export function runPreToolUseHook(event = {}, options = {}) {
254
371
  cwdOptions
255
372
  );
256
373
  }
257
- return {
374
+ return finalize({
258
375
  exitCode: 2,
259
376
  stdout: '',
260
377
  stderr: det04.reason,
261
378
  verdict: det04
262
- };
379
+ });
380
+ }
381
+ }
382
+
383
+ // 5b. DET-05: Subagent Fan-Out & Prompt-Bloat Guard
384
+ if (guardsCfg.subagentFanoutEnabled !== false && SUBAGENT_TOOL_REGEX.test(toolName)) {
385
+ const subagentPromptText = String(
386
+ tIn.prompt || tIn.Prompt || tIn.instructions || tIn.description || ''
387
+ );
388
+ const burstWindowSec = Number(
389
+ options.subagentBurstWindowSec ?? guardsCfg.subagentBurstWindowSec ?? 60
390
+ );
391
+ const nowSubagentMs = options.nowMs ?? Date.now();
392
+ const det05 = evaluateDet05SubagentFanout({
393
+ toolName,
394
+ promptText: subagentPromptText,
395
+ recentSpawnTimestampsMs:
396
+ event.recentSpawnTimestampsMs ??
397
+ options.recentSpawnTimestampsMs ??
398
+ priorSnap?.subagentSpawnTimestampsMs ??
399
+ [],
400
+ maxBurstCount:
401
+ options.subagentMaxBurstCount ?? guardsCfg.subagentMaxBurstCount ?? 4,
402
+ burstWindowSec,
403
+ maxPromptChars:
404
+ options.subagentMaxPromptChars ?? guardsCfg.subagentMaxPromptChars ?? 8000,
405
+ action:
406
+ options.subagentFanoutAction ?? guardsCfg.subagentFanoutAction ?? 'advisory',
407
+ nowMs: nowSubagentMs
408
+ });
409
+
410
+ if (det05.triggered && det05.decision === 'deny') {
411
+ if (canRecordLedger) {
412
+ recordSavingsReceipt(
413
+ {
414
+ sessionId,
415
+ cwd: baseCwd,
416
+ category: 'SUBAGENT_FANOUT_BLOCKED',
417
+ detectorId: det05.detectorId,
418
+ ring0Violation: false,
419
+ modelId,
420
+ savedTokens: 0,
421
+ savedUSD: 0,
422
+ detail: det05.reason
423
+ },
424
+ cwdOptions
425
+ );
426
+ }
427
+ return finalize({
428
+ exitCode: 2,
429
+ stdout: '',
430
+ stderr: det05.reason,
431
+ verdict: det05
432
+ });
433
+ }
434
+
435
+ if (shouldPersistState) {
436
+ recordSubagentSpawnAtomicSync(
437
+ sessionId,
438
+ { nowMs: nowSubagentMs, burstWindowSec },
439
+ cwdOptions
440
+ );
441
+ }
442
+
443
+ if (det05.triggered) {
444
+ if (advisoryNotice) {
445
+ advisoryNotice = {
446
+ ...advisoryNotice,
447
+ additionalContext: [
448
+ advisoryNotice.additionalContext || advisoryNotice.reason,
449
+ det05.additionalContext || det05.reason
450
+ ]
451
+ .filter(Boolean)
452
+ .join('\n'),
453
+ reason: [advisoryNotice.reason, det05.reason].filter(Boolean).join('\n')
454
+ };
455
+ } else {
456
+ advisoryNotice = det05;
457
+ }
263
458
  }
264
459
  }
265
460
 
266
461
  // 6. Bounded Read Guard & Per-File Read-Interval Cache (`updatedInput`)
462
+ const isSubagent = Boolean(
463
+ canonical.isSidechain ||
464
+ canonical.agentId ||
465
+ canonical.parentToolUseId ||
466
+ event.isSidechain ||
467
+ event.is_sidechain ||
468
+ event.agent_id ||
469
+ event.agentId ||
470
+ event.parent_tool_use_id ||
471
+ event.parentToolUseId
472
+ );
473
+ const nowSnapMs = options.nowMs ?? Date.now();
474
+ const readIntervalTtlMs = Math.max(
475
+ 1000,
476
+ Number(
477
+ options.readIntervalTtlMs ??
478
+ policy.readClamp?.intervalTtlMs ??
479
+ guardsCfg.readIntervalTtlMs ??
480
+ DEFAULT_READ_INTERVAL_TTL_MS
481
+ )
482
+ );
267
483
  const isReadTool = READ_TOOL_REGEX.test(toolName);
268
484
  if (isReadTool && rawPath && !/\.(?:ipynb|pdf)$/i.test(rawPath)) {
269
485
  const rawStartBound = tIn.offset ?? tIn.StartLine ?? tIn.start_line;
@@ -289,17 +505,20 @@ export function runPreToolUseHook(event = {}, options = {}) {
289
505
  : null;
290
506
 
291
507
  let trimmedByInterval = null;
292
- if (hasExplicitLineSlice && shouldPersistState && rawCwd) {
508
+ if (!isSubagent && hasExplicitLineSlice && shouldPersistState && rawCwd) {
293
509
  try {
294
510
  const absIntPath = path.isAbsolute(rawPath) ? path.resolve(rawPath) : path.resolve(baseCwd, rawPath);
295
511
  if (fs.existsSync(absIntPath)) {
296
512
  const stInt = fs.statSync(absIntPath);
297
513
  if (stInt.isFile() && stInt.size > 0 && stInt.size <= 1024 * 1024) {
298
514
  const normIntKey = absIntPath.replace(/\\/g, '/').toLowerCase();
299
- const { store: intStore } = loadReadSnapStore(baseCwd, sessionId);
515
+ const { store: intStore } = loadReadSnapStore(baseCwd, sessionId, cwdOptions);
300
516
  const entry = intStore.__readIntervals?.[normIntKey];
517
+ const recordedAt = Number(entry?.recordedAt || 0);
518
+ const entryFresh = recordedAt > 0 && nowSnapMs - recordedAt <= readIntervalTtlMs;
301
519
  const entryValid =
302
520
  entry &&
521
+ entryFresh &&
303
522
  Number(entry.mtimeMs) === Number(stInt.mtimeMs) &&
304
523
  Number(entry.size) === Number(stInt.size) &&
305
524
  Array.isArray(entry.intervals) &&
@@ -313,56 +532,6 @@ export function runPreToolUseHook(event = {}, options = {}) {
313
532
  ? Math.min(totalFileLines, reqStart + effectiveSliceLimit - 1)
314
533
  : totalFileLines;
315
534
  const trimRes = trimRequestedRangeAgainstIntervals(reqStart, reqEnd, entry.intervals);
316
- if (trimRes.status === 'full_covered') {
317
- const avgBytesPerLine = totalFileLines > 0 ? stInt.size / totalFileLines : 40;
318
- const savedTok = Math.max(10, Math.round((trimRes.savedLines * avgBytesPerLine) / 4));
319
- const updatedInput = { ...tIn };
320
- delete updatedInput.StartLine;
321
- delete updatedInput.EndLine;
322
- updatedInput.offset = trimRes.anchorOffset;
323
- updatedInput.limit = trimRes.anchorLimit;
324
- if (canRecordLedger) {
325
- recordInterventionSavings(
326
- {
327
- sessionId,
328
- category: 'BOUNDED_READ_ENFORCED',
329
- modelId,
330
- savedTokens: savedTok,
331
- dedupeId:
332
- event.tool_use_id ||
333
- event.toolUseId ||
334
- `interval_anchor:${sessionId}:${path.basename(absIntPath)}:${reqStart}:${reqEnd}`,
335
- detail: `Read-interval cache anchor on ${path.basename(absIntPath)} L${reqStart}-L${reqEnd}`
336
- },
337
- cwdOptions
338
- );
339
- }
340
- const reasonMsg =
341
- `[Burnoff Read-Interval Cache] L${reqStart}..L${reqEnd} of ${path.basename(absIntPath)} (${totalFileLines} lines) ` +
342
- `already loaded cleanly; anchored to L${trimRes.anchorOffset}..L${trimRes.anchorOffset + trimRes.anchorLimit - 1}.`;
343
- const allowOut = {
344
- hookSpecificOutput: {
345
- hookEventName: 'PreToolUse',
346
- permissionDecision: 'allow',
347
- updatedInput,
348
- additionalContext: reasonMsg
349
- }
350
- };
351
- return {
352
- exitCode: 0,
353
- stdout: JSON.stringify(allowOut),
354
- stderr: '',
355
- verdict: {
356
- triggered: true,
357
- detectorId: 'DET-06',
358
- subType: 'READ_INTERVAL_ANCHOR',
359
- decision: 'allow',
360
- updatedInput,
361
- savedTokens: savedTok,
362
- reason: reasonMsg
363
- }
364
- };
365
- }
366
535
  if (trimRes.status === 'trimmed') {
367
536
  const avgBytesPerLine = totalFileLines > 0 ? stInt.size / totalFileLines : 40;
368
537
  const savedTok = Math.max(10, Math.round((trimRes.savedLines * avgBytesPerLine) / 4));
@@ -411,23 +580,29 @@ export function runPreToolUseHook(event = {}, options = {}) {
411
580
  });
412
581
 
413
582
  if (shieldVerdict.action === 'clamp') {
414
- if (shouldPersistState && rawCwd && !shieldVerdict.hugeFileFastClamp) {
583
+ if (!isSubagent && shouldPersistState && rawCwd && !shieldVerdict.hugeFileFastClamp) {
415
584
  try {
416
585
  const absClampPath = path.isAbsolute(rawPath) ? path.resolve(rawPath) : path.resolve(baseCwd, rawPath);
417
586
  if (fs.existsSync(absClampPath) && fs.statSync(absClampPath).isFile()) {
418
587
  const stClamp = fs.statSync(absClampPath);
419
588
  const clampStart = shieldVerdict.clampOffset || 1;
420
589
  const clampEnd = clampStart + shieldVerdict.clampLimit - 1;
421
- updateReadSnapStoreAtomicSync(baseCwd, sessionId, (store) => {
422
- recordReadIntervalEntry(
423
- store,
424
- absClampPath.replace(/\\/g, '/').toLowerCase(),
425
- stClamp,
426
- clampStart,
427
- clampEnd
428
- );
429
- return store;
430
- });
590
+ updateReadSnapStoreAtomicSync(
591
+ baseCwd,
592
+ sessionId,
593
+ (store) => {
594
+ recordReadIntervalEntry(
595
+ store,
596
+ absClampPath.replace(/\\/g, '/').toLowerCase(),
597
+ stClamp,
598
+ clampStart,
599
+ clampEnd,
600
+ nowSnapMs
601
+ );
602
+ return store;
603
+ },
604
+ cwdOptions
605
+ );
431
606
  }
432
607
  } catch (clampIntErr) {
433
608
  void clampIntErr; // ignore: non-fatal read interval update after clamp
@@ -447,7 +622,7 @@ export function runPreToolUseHook(event = {}, options = {}) {
447
622
  additionalContext: shieldVerdict.reason
448
623
  }
449
624
  };
450
- return {
625
+ return finalize({
451
626
  exitCode: 0,
452
627
  stdout: JSON.stringify(clampOut),
453
628
  stderr: '',
@@ -468,7 +643,7 @@ export function runPreToolUseHook(event = {}, options = {}) {
468
643
  rawClampedTokens: shieldVerdict.rawClampedTokens,
469
644
  savedUSD: shieldVerdict.savedUSD
470
645
  }
471
- };
646
+ });
472
647
  }
473
648
 
474
649
  if (shieldVerdict.action === 'deny') {
@@ -479,7 +654,7 @@ export function runPreToolUseHook(event = {}, options = {}) {
479
654
  permissionDecisionReason: shieldVerdict.reason
480
655
  }
481
656
  };
482
- return {
657
+ return finalize({
483
658
  exitCode: 0,
484
659
  stdout: JSON.stringify(denyOut),
485
660
  stderr: '',
@@ -494,20 +669,26 @@ export function runPreToolUseHook(event = {}, options = {}) {
494
669
  savedTokens: shieldVerdict.savedTokens,
495
670
  savedUSD: shieldVerdict.savedUSD
496
671
  }
497
- };
672
+ });
498
673
  }
499
674
 
500
675
  if (trimmedByInterval) {
501
- updateReadSnapStoreAtomicSync(baseCwd, sessionId, (store) => {
502
- recordReadIntervalEntry(
503
- store,
504
- trimmedByInterval.normKey,
505
- trimmedByInterval.statObj,
506
- trimmedByInterval.offset,
507
- trimmedByInterval.offset + trimmedByInterval.limit - 1
508
- );
509
- return store;
510
- });
676
+ updateReadSnapStoreAtomicSync(
677
+ baseCwd,
678
+ sessionId,
679
+ (store) => {
680
+ recordReadIntervalEntry(
681
+ store,
682
+ trimmedByInterval.normKey,
683
+ trimmedByInterval.statObj,
684
+ trimmedByInterval.offset,
685
+ trimmedByInterval.offset + trimmedByInterval.limit - 1,
686
+ nowSnapMs
687
+ );
688
+ return store;
689
+ },
690
+ cwdOptions
691
+ );
511
692
  if (canRecordLedger) {
512
693
  recordInterventionSavings(
513
694
  {
@@ -516,8 +697,7 @@ export function runPreToolUseHook(event = {}, options = {}) {
516
697
  modelId,
517
698
  savedTokens: trimmedByInterval.savedTokens,
518
699
  dedupeId:
519
- event.tool_use_id ||
520
- event.toolUseId ||
700
+ canonical.toolUseId ||
521
701
  `interval_trim:${sessionId}:${path.basename(trimmedByInterval.absPath)}:${trimmedByInterval.reqStart}:${trimmedByInterval.reqEnd}`,
522
702
  detail: `Trimmed overlapping read of ${path.basename(trimmedByInterval.absPath)} to L${trimmedByInterval.offset}-L${trimmedByInterval.offset + trimmedByInterval.limit - 1}`
523
703
  },
@@ -540,7 +720,7 @@ export function runPreToolUseHook(event = {}, options = {}) {
540
720
  additionalContext: trimReason
541
721
  }
542
722
  };
543
- return {
723
+ return finalize({
544
724
  exitCode: 0,
545
725
  stdout: JSON.stringify(allowOut),
546
726
  stderr: '',
@@ -553,11 +733,11 @@ export function runPreToolUseHook(event = {}, options = {}) {
553
733
  savedTokens: trimmedByInterval.savedTokens,
554
734
  reason: trimReason
555
735
  }
556
- };
736
+ });
557
737
  }
558
738
 
559
739
  // Record clean explicit or small full Read interval into read_snapshots_<sid>.json
560
- if (shouldPersistState && rawCwd) {
740
+ if (!isSubagent && shouldPersistState && rawCwd) {
561
741
  try {
562
742
  const absRecPath = path.isAbsolute(rawPath) ? path.resolve(rawPath) : path.resolve(baseCwd, rawPath);
563
743
  if (fs.existsSync(absRecPath) && fs.statSync(absRecPath).isFile()) {
@@ -570,16 +750,22 @@ export function runPreToolUseHook(event = {}, options = {}) {
570
750
  const recEnd = hasExplicitLineSlice && effectiveSliceLimit
571
751
  ? Math.min(totalRecLines, recStart + effectiveSliceLimit - 1)
572
752
  : totalRecLines;
573
- updateReadSnapStoreAtomicSync(baseCwd, sessionId, (store) => {
574
- recordReadIntervalEntry(
575
- store,
576
- absRecPath.replace(/\\/g, '/').toLowerCase(),
577
- stRec,
578
- recStart,
579
- recEnd
580
- );
581
- return store;
582
- });
753
+ updateReadSnapStoreAtomicSync(
754
+ baseCwd,
755
+ sessionId,
756
+ (store) => {
757
+ recordReadIntervalEntry(
758
+ store,
759
+ absRecPath.replace(/\\/g, '/').toLowerCase(),
760
+ stRec,
761
+ recStart,
762
+ recEnd,
763
+ nowSnapMs
764
+ );
765
+ return store;
766
+ },
767
+ cwdOptions
768
+ );
583
769
  }
584
770
  }
585
771
  } catch (recErr) {
@@ -588,6 +774,44 @@ export function runPreToolUseHook(event = {}, options = {}) {
588
774
  }
589
775
  }
590
776
 
777
+ // Acquire DET-20 concurrent scope lock when allowing Edit/Write/MultiEdit/NotebookEdit
778
+ if (
779
+ EDIT_WRITE_SCOPE_LOCK_REGEX.test(toolName) &&
780
+ rawPath &&
781
+ shouldPersistState &&
782
+ guardsCfg.scopeLockEnabled !== false
783
+ ) {
784
+ const scopeLockRes = acquireScopeLock(
785
+ {
786
+ ownerId,
787
+ scopes: [rawPath],
788
+ ttlMs: Number(options.scopeLockTtlMs ?? guardsCfg.scopeLockTtlMs ?? 120_000),
789
+ mergeOwnerScopes: true
790
+ },
791
+ { ...cwdOptions, nowMs: options.nowMs ?? Date.now() }
792
+ );
793
+ if (scopeLockRes && scopeLockRes.acquired === false && scopeLockRes.conflict) {
794
+ const conflictVerdict = {
795
+ detectorId: 'DET-20',
796
+ triggered: true,
797
+ decision: 'deny',
798
+ subType: 'SCOPE_LOCK_CONFLICT',
799
+ conflictingOwner: scopeLockRes.conflict.ownerId,
800
+ conflictingScope: scopeLockRes.conflict.conflictingScope,
801
+ targetFilePath: rawPath,
802
+ reason:
803
+ `[Burnoff DET-20 Concurrent Scope Lock] File "${rawPath}" is locked by active worker "${scopeLockRes.conflict.ownerId}" ` +
804
+ `(scope "${scopeLockRes.conflict.conflictingScope}"). Wait for lock release before editing.`
805
+ };
806
+ return finalize({
807
+ exitCode: 2,
808
+ stdout: '',
809
+ stderr: conflictVerdict.reason,
810
+ verdict: conflictVerdict
811
+ });
812
+ }
813
+ }
814
+
591
815
  if (advisoryNotice) {
592
816
  const advOut = {
593
817
  hookSpecificOutput: {
@@ -596,20 +820,27 @@ export function runPreToolUseHook(event = {}, options = {}) {
596
820
  additionalContext: advisoryNotice.additionalContext || advisoryNotice.reason
597
821
  }
598
822
  };
599
- return {
823
+ return finalize({
600
824
  exitCode: 0,
601
825
  stdout: JSON.stringify(advOut),
602
826
  stderr: '',
603
827
  verdict: advisoryNotice
604
- };
828
+ });
605
829
  }
606
830
 
607
- return {
831
+ return finalize({
608
832
  exitCode: 0,
609
833
  stdout: '',
610
834
  stderr: '',
611
835
  verdict: { triggered: false, decision: 'allow', reason: null }
612
- };
836
+ });
837
+ }
838
+
839
+ /**
840
+ * Evaluates a `PreToolUse` hook event and returns the host-formatted exit/stdout contract.
841
+ */
842
+ export function runPreToolUseHook(event = {}, options = {}) {
843
+ return evaluatePreToolUseCore(event, options);
613
844
  }
614
845
 
615
846
  export default { runPreToolUseHook };