burnoff 1.1.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.
- package/.github/workflows/burnoff-pr-gate.yml +3 -3
- package/README.md +66 -78
- package/bin/burnoff.mjs +67 -23
- package/hooks/hook-io.mjs +19 -7
- package/hooks/post-tool-use.mjs +33 -26
- package/hooks/pre-tool-use.mjs +43 -41
- package/hooks/session-lifecycle.mjs +40 -0
- package/package.json +7 -5
- package/src/ci/ci-gate.mjs +22 -0
- package/src/ci/pr-cost.mjs +42 -10
- package/src/ci/team-digest.mjs +5 -3
- package/src/cli/audit.mjs +103 -18
- package/src/cli/doctor.mjs +209 -14
- package/src/cli/init.mjs +349 -96
- package/src/cli/startup-audit.mjs +500 -24
- package/src/clients/antigravity.mjs +285 -0
- package/src/clients/claude-code.mjs +180 -0
- package/src/clients/detect.mjs +64 -0
- package/src/config/loader.mjs +11 -4
- package/src/config/paths.mjs +62 -2
- package/src/config/policy.mjs +34 -5
- package/src/config/pricing.mjs +16 -5
- package/src/guards/loop-breaker.mjs +198 -13
- package/src/guards/post-tool-engine.mjs +289 -29
- package/src/guards/pre-tool-engine.mjs +336 -129
- package/src/guards/read-clamp.mjs +78 -18
- package/src/guards/session-hook.mjs +207 -0
- package/src/guards/shell-guard.mjs +583 -73
- package/src/ipc/daemon.mjs +50 -8
- package/src/ipc/fast-client.mjs +62 -5
- package/src/ipc/protocol.mjs +1 -1
- package/src/storage/antigravity-parser.mjs +258 -0
- package/src/storage/file-lock.mjs +13 -4
- package/src/storage/fts5-archive.mjs +4 -4
- package/src/storage/jsonl-parser.mjs +7 -1
- package/src/storage/ledger.mjs +10 -3
- package/src/storage/sqlite-client.mjs +4 -2
- 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,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
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
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(
|
|
60
|
-
const rawCwd =
|
|
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(
|
|
80
|
+
Boolean(canonical.cwd || options.cwd || options.breakerStatePath || options.persistState);
|
|
69
81
|
const canRecordLedger =
|
|
70
82
|
options.recordLedger !== false &&
|
|
71
|
-
Boolean(
|
|
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
|
-
|
|
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
|
-
|
|
84
|
-
|
|
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
|
|
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
|
|
167
|
+
lastUserInput,
|
|
126
168
|
nowMs: options.nowMs
|
|
127
169
|
});
|
|
128
170
|
if (det01.triggered) {
|
|
@@ -134,12 +176,12 @@ 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
|
+
});
|
|
143
185
|
}
|
|
144
186
|
if (canRecordLedger) {
|
|
145
187
|
recordSavingsReceipt(
|
|
@@ -157,12 +199,12 @@ export function runPreToolUseHook(event = {}, options = {}) {
|
|
|
157
199
|
cwdOptions
|
|
158
200
|
);
|
|
159
201
|
}
|
|
160
|
-
return {
|
|
202
|
+
return finalize({
|
|
161
203
|
exitCode: 2,
|
|
162
204
|
stdout: '',
|
|
163
205
|
stderr: det01.reason,
|
|
164
206
|
verdict: det01
|
|
165
|
-
};
|
|
207
|
+
});
|
|
166
208
|
}
|
|
167
209
|
}
|
|
168
210
|
|
|
@@ -172,9 +214,27 @@ export function runPreToolUseHook(event = {}, options = {}) {
|
|
|
172
214
|
toolName,
|
|
173
215
|
filePath: rawPath,
|
|
174
216
|
path: rawPath,
|
|
175
|
-
command
|
|
217
|
+
command,
|
|
218
|
+
mode: guardMode,
|
|
219
|
+
flightMode,
|
|
220
|
+
secretAllow: options.secretAllow ?? guardsCfg.secretAllow ?? []
|
|
176
221
|
});
|
|
177
222
|
if (det02.triggered) {
|
|
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
|
+
}
|
|
178
238
|
if (canRecordLedger) {
|
|
179
239
|
recordSavingsReceipt(
|
|
180
240
|
{
|
|
@@ -191,12 +251,12 @@ export function runPreToolUseHook(event = {}, options = {}) {
|
|
|
191
251
|
cwdOptions
|
|
192
252
|
);
|
|
193
253
|
}
|
|
194
|
-
return {
|
|
254
|
+
return finalize({
|
|
195
255
|
exitCode: 2,
|
|
196
256
|
stdout: '',
|
|
197
257
|
stderr: det02.reason,
|
|
198
258
|
verdict: det02
|
|
199
|
-
};
|
|
259
|
+
});
|
|
200
260
|
}
|
|
201
261
|
}
|
|
202
262
|
|
|
@@ -214,12 +274,12 @@ export function runPreToolUseHook(event = {}, options = {}) {
|
|
|
214
274
|
permissionDecisionReason: det03.reason
|
|
215
275
|
}
|
|
216
276
|
};
|
|
217
|
-
return {
|
|
277
|
+
return finalize({
|
|
218
278
|
exitCode: 0,
|
|
219
279
|
stdout: JSON.stringify(askOut),
|
|
220
280
|
stderr: '',
|
|
221
281
|
verdict: det03
|
|
222
|
-
};
|
|
282
|
+
});
|
|
223
283
|
}
|
|
224
284
|
}
|
|
225
285
|
|
|
@@ -234,10 +294,43 @@ export function runPreToolUseHook(event = {}, options = {}) {
|
|
|
234
294
|
toolName,
|
|
235
295
|
command,
|
|
236
296
|
filePath: rawPath,
|
|
297
|
+
mode: guardMode,
|
|
298
|
+
flightMode,
|
|
237
299
|
maxConsecutiveFailures:
|
|
238
300
|
options.maxConsecutiveFailures ?? guardsCfg.det04Threshold ?? 3
|
|
239
301
|
});
|
|
240
|
-
if (det04.triggered
|
|
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
|
+
}
|
|
241
334
|
if (canRecordLedger) {
|
|
242
335
|
recordSavingsReceipt(
|
|
243
336
|
{
|
|
@@ -254,16 +347,115 @@ export function runPreToolUseHook(event = {}, options = {}) {
|
|
|
254
347
|
cwdOptions
|
|
255
348
|
);
|
|
256
349
|
}
|
|
257
|
-
return {
|
|
350
|
+
return finalize({
|
|
258
351
|
exitCode: 2,
|
|
259
352
|
stdout: '',
|
|
260
353
|
stderr: det04.reason,
|
|
261
354
|
verdict: det04
|
|
262
|
-
};
|
|
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
|
+
}
|
|
263
434
|
}
|
|
264
435
|
}
|
|
265
436
|
|
|
266
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
|
+
);
|
|
267
459
|
const isReadTool = READ_TOOL_REGEX.test(toolName);
|
|
268
460
|
if (isReadTool && rawPath && !/\.(?:ipynb|pdf)$/i.test(rawPath)) {
|
|
269
461
|
const rawStartBound = tIn.offset ?? tIn.StartLine ?? tIn.start_line;
|
|
@@ -289,17 +481,20 @@ export function runPreToolUseHook(event = {}, options = {}) {
|
|
|
289
481
|
: null;
|
|
290
482
|
|
|
291
483
|
let trimmedByInterval = null;
|
|
292
|
-
if (hasExplicitLineSlice && shouldPersistState && rawCwd) {
|
|
484
|
+
if (!isSubagent && hasExplicitLineSlice && shouldPersistState && rawCwd) {
|
|
293
485
|
try {
|
|
294
486
|
const absIntPath = path.isAbsolute(rawPath) ? path.resolve(rawPath) : path.resolve(baseCwd, rawPath);
|
|
295
487
|
if (fs.existsSync(absIntPath)) {
|
|
296
488
|
const stInt = fs.statSync(absIntPath);
|
|
297
489
|
if (stInt.isFile() && stInt.size > 0 && stInt.size <= 1024 * 1024) {
|
|
298
490
|
const normIntKey = absIntPath.replace(/\\/g, '/').toLowerCase();
|
|
299
|
-
const { store: intStore } = loadReadSnapStore(baseCwd, sessionId);
|
|
491
|
+
const { store: intStore } = loadReadSnapStore(baseCwd, sessionId, cwdOptions);
|
|
300
492
|
const entry = intStore.__readIntervals?.[normIntKey];
|
|
493
|
+
const recordedAt = Number(entry?.recordedAt || 0);
|
|
494
|
+
const entryFresh = recordedAt > 0 && nowSnapMs - recordedAt <= readIntervalTtlMs;
|
|
301
495
|
const entryValid =
|
|
302
496
|
entry &&
|
|
497
|
+
entryFresh &&
|
|
303
498
|
Number(entry.mtimeMs) === Number(stInt.mtimeMs) &&
|
|
304
499
|
Number(entry.size) === Number(stInt.size) &&
|
|
305
500
|
Array.isArray(entry.intervals) &&
|
|
@@ -313,56 +508,6 @@ export function runPreToolUseHook(event = {}, options = {}) {
|
|
|
313
508
|
? Math.min(totalFileLines, reqStart + effectiveSliceLimit - 1)
|
|
314
509
|
: totalFileLines;
|
|
315
510
|
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
511
|
if (trimRes.status === 'trimmed') {
|
|
367
512
|
const avgBytesPerLine = totalFileLines > 0 ? stInt.size / totalFileLines : 40;
|
|
368
513
|
const savedTok = Math.max(10, Math.round((trimRes.savedLines * avgBytesPerLine) / 4));
|
|
@@ -411,23 +556,29 @@ export function runPreToolUseHook(event = {}, options = {}) {
|
|
|
411
556
|
});
|
|
412
557
|
|
|
413
558
|
if (shieldVerdict.action === 'clamp') {
|
|
414
|
-
if (shouldPersistState && rawCwd && !shieldVerdict.hugeFileFastClamp) {
|
|
559
|
+
if (!isSubagent && shouldPersistState && rawCwd && !shieldVerdict.hugeFileFastClamp) {
|
|
415
560
|
try {
|
|
416
561
|
const absClampPath = path.isAbsolute(rawPath) ? path.resolve(rawPath) : path.resolve(baseCwd, rawPath);
|
|
417
562
|
if (fs.existsSync(absClampPath) && fs.statSync(absClampPath).isFile()) {
|
|
418
563
|
const stClamp = fs.statSync(absClampPath);
|
|
419
564
|
const clampStart = shieldVerdict.clampOffset || 1;
|
|
420
565
|
const clampEnd = clampStart + shieldVerdict.clampLimit - 1;
|
|
421
|
-
updateReadSnapStoreAtomicSync(
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
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
|
+
);
|
|
431
582
|
}
|
|
432
583
|
} catch (clampIntErr) {
|
|
433
584
|
void clampIntErr; // ignore: non-fatal read interval update after clamp
|
|
@@ -447,7 +598,7 @@ export function runPreToolUseHook(event = {}, options = {}) {
|
|
|
447
598
|
additionalContext: shieldVerdict.reason
|
|
448
599
|
}
|
|
449
600
|
};
|
|
450
|
-
return {
|
|
601
|
+
return finalize({
|
|
451
602
|
exitCode: 0,
|
|
452
603
|
stdout: JSON.stringify(clampOut),
|
|
453
604
|
stderr: '',
|
|
@@ -468,7 +619,7 @@ export function runPreToolUseHook(event = {}, options = {}) {
|
|
|
468
619
|
rawClampedTokens: shieldVerdict.rawClampedTokens,
|
|
469
620
|
savedUSD: shieldVerdict.savedUSD
|
|
470
621
|
}
|
|
471
|
-
};
|
|
622
|
+
});
|
|
472
623
|
}
|
|
473
624
|
|
|
474
625
|
if (shieldVerdict.action === 'deny') {
|
|
@@ -479,7 +630,7 @@ export function runPreToolUseHook(event = {}, options = {}) {
|
|
|
479
630
|
permissionDecisionReason: shieldVerdict.reason
|
|
480
631
|
}
|
|
481
632
|
};
|
|
482
|
-
return {
|
|
633
|
+
return finalize({
|
|
483
634
|
exitCode: 0,
|
|
484
635
|
stdout: JSON.stringify(denyOut),
|
|
485
636
|
stderr: '',
|
|
@@ -494,20 +645,26 @@ export function runPreToolUseHook(event = {}, options = {}) {
|
|
|
494
645
|
savedTokens: shieldVerdict.savedTokens,
|
|
495
646
|
savedUSD: shieldVerdict.savedUSD
|
|
496
647
|
}
|
|
497
|
-
};
|
|
648
|
+
});
|
|
498
649
|
}
|
|
499
650
|
|
|
500
651
|
if (trimmedByInterval) {
|
|
501
|
-
updateReadSnapStoreAtomicSync(
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
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
|
+
);
|
|
511
668
|
if (canRecordLedger) {
|
|
512
669
|
recordInterventionSavings(
|
|
513
670
|
{
|
|
@@ -516,8 +673,7 @@ export function runPreToolUseHook(event = {}, options = {}) {
|
|
|
516
673
|
modelId,
|
|
517
674
|
savedTokens: trimmedByInterval.savedTokens,
|
|
518
675
|
dedupeId:
|
|
519
|
-
|
|
520
|
-
event.toolUseId ||
|
|
676
|
+
canonical.toolUseId ||
|
|
521
677
|
`interval_trim:${sessionId}:${path.basename(trimmedByInterval.absPath)}:${trimmedByInterval.reqStart}:${trimmedByInterval.reqEnd}`,
|
|
522
678
|
detail: `Trimmed overlapping read of ${path.basename(trimmedByInterval.absPath)} to L${trimmedByInterval.offset}-L${trimmedByInterval.offset + trimmedByInterval.limit - 1}`
|
|
523
679
|
},
|
|
@@ -540,7 +696,7 @@ export function runPreToolUseHook(event = {}, options = {}) {
|
|
|
540
696
|
additionalContext: trimReason
|
|
541
697
|
}
|
|
542
698
|
};
|
|
543
|
-
return {
|
|
699
|
+
return finalize({
|
|
544
700
|
exitCode: 0,
|
|
545
701
|
stdout: JSON.stringify(allowOut),
|
|
546
702
|
stderr: '',
|
|
@@ -553,11 +709,11 @@ export function runPreToolUseHook(event = {}, options = {}) {
|
|
|
553
709
|
savedTokens: trimmedByInterval.savedTokens,
|
|
554
710
|
reason: trimReason
|
|
555
711
|
}
|
|
556
|
-
};
|
|
712
|
+
});
|
|
557
713
|
}
|
|
558
714
|
|
|
559
715
|
// Record clean explicit or small full Read interval into read_snapshots_<sid>.json
|
|
560
|
-
if (shouldPersistState && rawCwd) {
|
|
716
|
+
if (!isSubagent && shouldPersistState && rawCwd) {
|
|
561
717
|
try {
|
|
562
718
|
const absRecPath = path.isAbsolute(rawPath) ? path.resolve(rawPath) : path.resolve(baseCwd, rawPath);
|
|
563
719
|
if (fs.existsSync(absRecPath) && fs.statSync(absRecPath).isFile()) {
|
|
@@ -570,16 +726,22 @@ export function runPreToolUseHook(event = {}, options = {}) {
|
|
|
570
726
|
const recEnd = hasExplicitLineSlice && effectiveSliceLimit
|
|
571
727
|
? Math.min(totalRecLines, recStart + effectiveSliceLimit - 1)
|
|
572
728
|
: totalRecLines;
|
|
573
|
-
updateReadSnapStoreAtomicSync(
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
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
|
+
);
|
|
583
745
|
}
|
|
584
746
|
}
|
|
585
747
|
} catch (recErr) {
|
|
@@ -588,6 +750,44 @@ export function runPreToolUseHook(event = {}, options = {}) {
|
|
|
588
750
|
}
|
|
589
751
|
}
|
|
590
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
|
+
|
|
591
791
|
if (advisoryNotice) {
|
|
592
792
|
const advOut = {
|
|
593
793
|
hookSpecificOutput: {
|
|
@@ -596,20 +796,27 @@ export function runPreToolUseHook(event = {}, options = {}) {
|
|
|
596
796
|
additionalContext: advisoryNotice.additionalContext || advisoryNotice.reason
|
|
597
797
|
}
|
|
598
798
|
};
|
|
599
|
-
return {
|
|
799
|
+
return finalize({
|
|
600
800
|
exitCode: 0,
|
|
601
801
|
stdout: JSON.stringify(advOut),
|
|
602
802
|
stderr: '',
|
|
603
803
|
verdict: advisoryNotice
|
|
604
|
-
};
|
|
804
|
+
});
|
|
605
805
|
}
|
|
606
806
|
|
|
607
|
-
return {
|
|
807
|
+
return finalize({
|
|
608
808
|
exitCode: 0,
|
|
609
809
|
stdout: '',
|
|
610
810
|
stderr: '',
|
|
611
811
|
verdict: { triggered: false, decision: 'allow', reason: null }
|
|
612
|
-
};
|
|
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);
|
|
613
820
|
}
|
|
614
821
|
|
|
615
822
|
export default { runPreToolUseHook };
|