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.
- package/.claude-plugin/plugin.json +1 -1
- package/.github/workflows/burnoff-pr-gate.yml +3 -3
- package/.github/workflows/burnoff-startup-lint.yml +2 -2
- package/README.md +213 -209
- package/bin/burnoff.mjs +1 -1
- package/commands/burnoff.md +1 -1
- package/docs/CLAUDE_CODE_PLUGIN.md +6 -6
- package/docs/DESIGN_PARTNER_INTAKE.md +3 -3
- package/hooks/hook-io.mjs +691 -599
- package/package.json +1 -1
- package/scripts/bench-hooks.mjs +252 -0
- package/src/cli/doctor.mjs +583 -462
- package/src/cli/hook-health.mjs +429 -0
- package/src/cli/init.mjs +668 -646
- package/src/clients/antigravity.mjs +285 -285
- package/src/config/policy.mjs +307 -306
- package/src/guards/credential-scrubber.mjs +185 -0
- package/src/guards/loop-breaker.mjs +797 -793
- package/src/guards/post-tool-engine.mjs +875 -854
- package/src/guards/pre-tool-engine.mjs +973 -978
- package/src/guards/read-clamp.mjs +826 -804
- package/src/guards/shell-guard.mjs +1705 -1676
- package/src/guards/structural-boundaries.mjs +175 -0
- package/src/ipc/fast-client.mjs +255 -255
- package/src/storage/fts5-archive.mjs +734 -733
|
@@ -1,793 +1,797 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @file src/guards/loop-breaker.mjs
|
|
3
|
-
* Runaway Consecutive Failure Breaker (`DET-04`), Atomic Breaker State Store,
|
|
4
|
-
* and Concurrent Multi-Agent File-Scope Lockfile & Quota Hard Brake (`DET-20`).
|
|
5
|
-
*/
|
|
6
|
-
|
|
7
|
-
import fs from 'node:fs';
|
|
8
|
-
import path from 'node:path';
|
|
9
|
-
import { withFileLockSync } from '../storage/file-lock.mjs';
|
|
10
|
-
import { atomicWriteJsonSync, sleepSync } from '../storage/atomic-io.mjs';
|
|
11
|
-
import { getBurnoffRuntimeDir, getHomeDir, getWorkspaceStateDir } from '../config/paths.mjs';
|
|
12
|
-
import { isVerificationShellCommand, normalizeEditThrashPath } from './phase5-detectors.mjs';
|
|
13
|
-
|
|
14
|
-
export const DEFAULT_MAX_CONSECUTIVE_FAILURES = 3;
|
|
15
|
-
export const DEFAULT_SCOPE_LOCK_TTL_MS = 15 * 60 * 1000;
|
|
16
|
-
export const SUBAGENT_TOOL_REGEX = /^(?:Task|Agent|invoke_subagent)$/i;
|
|
17
|
-
export const DEFAULT_SUBAGENT_MAX_BURST_COUNT = 4;
|
|
18
|
-
export const DEFAULT_SUBAGENT_BURST_WINDOW_SEC = 60;
|
|
19
|
-
export const DEFAULT_SUBAGENT_MAX_PROMPT_CHARS = 8000;
|
|
20
|
-
const DET04_EXEMPT_READ_TOOLS = /^(?:Read|Grep|Glob)$/i;
|
|
21
|
-
const EDIT_THRASH_TOOL_RE =
|
|
22
|
-
/^(?:Edit|Write|MultiEdit|NotebookEdit|edit_file|write_file|write_to_file|replace_file_content|multi_replace_file_content)$/i;
|
|
23
|
-
const EDIT_THRASH_STORAGE_TTL_MS = 60 * 60 * 1000;
|
|
24
|
-
const EDIT_THRASH_MAX_FILES = 24;
|
|
25
|
-
const EDIT_THRASH_MAX_TIMESTAMPS = 16;
|
|
26
|
-
const EXEMPT_MCP_CONFIG_BASENAME_RE = /^(?:\.mcp\.json|mcp_config\.json)$/i;
|
|
27
|
-
|
|
28
|
-
function readJsonSafe(filePath, fallback = null) {
|
|
29
|
-
if (!filePath) return fallback;
|
|
30
|
-
for (let attempt = 0; attempt < 12; attempt += 1) {
|
|
31
|
-
try {
|
|
32
|
-
if (!fs.existsSync(filePath)) return fallback;
|
|
33
|
-
return JSON.parse(fs.readFileSync(filePath, 'utf8'));
|
|
34
|
-
} catch (err) {
|
|
35
|
-
if (
|
|
36
|
-
attempt < 11 &&
|
|
37
|
-
(err?.code === 'EPERM' || err?.code === 'EBUSY' || err?.code === 'EACCES')
|
|
38
|
-
) {
|
|
39
|
-
sleepSync(5);
|
|
40
|
-
continue;
|
|
41
|
-
}
|
|
42
|
-
return fallback;
|
|
43
|
-
}
|
|
44
|
-
}
|
|
45
|
-
return fallback;
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
function getEffectiveCwd(options = {}) {
|
|
49
|
-
return options?.cwd ? path.resolve(String(options.cwd)) : process.cwd();
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
export function computeToolFailureKey({ toolName = '', command = '', filePath = '' } = {}) {
|
|
53
|
-
const normTool = String(toolName || '').trim() || 'unknown';
|
|
54
|
-
const rawCmd = String(command || '').trim();
|
|
55
|
-
if (rawCmd) {
|
|
56
|
-
const normalizedCmd = rawCmd
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
return `${normTool}:${
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
const
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
const
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
if (options?.
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
if (options?.
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
return
|
|
158
|
-
}
|
|
159
|
-
|
|
160
|
-
export function
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
}
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
const
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
const
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
}
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
} else {
|
|
333
|
-
regexStr +=
|
|
334
|
-
}
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
}
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
if (
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
}
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
return path.
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
const
|
|
385
|
-
typeof entry.
|
|
386
|
-
? entry.
|
|
387
|
-
: 0;
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
const
|
|
426
|
-
const
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
const
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
scopes
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
}
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
const
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
}
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
}
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
const
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
);
|
|
565
|
-
const
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
const
|
|
677
|
-
|
|
678
|
-
const
|
|
679
|
-
const
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
const
|
|
683
|
-
const
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
const
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
parts.push(`
|
|
717
|
-
}
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
`
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
}
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
1
|
+
/**
|
|
2
|
+
* @file src/guards/loop-breaker.mjs
|
|
3
|
+
* Runaway Consecutive Failure Breaker (`DET-04`), Atomic Breaker State Store,
|
|
4
|
+
* and Concurrent Multi-Agent File-Scope Lockfile & Quota Hard Brake (`DET-20`).
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import fs from 'node:fs';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
import { withFileLockSync } from '../storage/file-lock.mjs';
|
|
10
|
+
import { atomicWriteJsonSync, sleepSync } from '../storage/atomic-io.mjs';
|
|
11
|
+
import { getBurnoffRuntimeDir, getHomeDir, getWorkspaceStateDir } from '../config/paths.mjs';
|
|
12
|
+
import { isVerificationShellCommand, normalizeEditThrashPath } from './phase5-detectors.mjs';
|
|
13
|
+
|
|
14
|
+
export const DEFAULT_MAX_CONSECUTIVE_FAILURES = 3;
|
|
15
|
+
export const DEFAULT_SCOPE_LOCK_TTL_MS = 15 * 60 * 1000;
|
|
16
|
+
export const SUBAGENT_TOOL_REGEX = /^(?:Task|Agent|invoke_subagent)$/i;
|
|
17
|
+
export const DEFAULT_SUBAGENT_MAX_BURST_COUNT = 4;
|
|
18
|
+
export const DEFAULT_SUBAGENT_BURST_WINDOW_SEC = 60;
|
|
19
|
+
export const DEFAULT_SUBAGENT_MAX_PROMPT_CHARS = 8000;
|
|
20
|
+
const DET04_EXEMPT_READ_TOOLS = /^(?:Read|Grep|Glob)$/i;
|
|
21
|
+
const EDIT_THRASH_TOOL_RE =
|
|
22
|
+
/^(?:Edit|Write|MultiEdit|NotebookEdit|edit_file|write_file|write_to_file|replace_file_content|multi_replace_file_content)$/i;
|
|
23
|
+
const EDIT_THRASH_STORAGE_TTL_MS = 60 * 60 * 1000;
|
|
24
|
+
const EDIT_THRASH_MAX_FILES = 24;
|
|
25
|
+
const EDIT_THRASH_MAX_TIMESTAMPS = 16;
|
|
26
|
+
const EXEMPT_MCP_CONFIG_BASENAME_RE = /^(?:\.mcp\.json|mcp_config\.json)$/i;
|
|
27
|
+
|
|
28
|
+
function readJsonSafe(filePath, fallback = null) {
|
|
29
|
+
if (!filePath) return fallback;
|
|
30
|
+
for (let attempt = 0; attempt < 12; attempt += 1) {
|
|
31
|
+
try {
|
|
32
|
+
if (!fs.existsSync(filePath)) return fallback;
|
|
33
|
+
return JSON.parse(fs.readFileSync(filePath, 'utf8'));
|
|
34
|
+
} catch (err) {
|
|
35
|
+
if (
|
|
36
|
+
attempt < 11 &&
|
|
37
|
+
(err?.code === 'EPERM' || err?.code === 'EBUSY' || err?.code === 'EACCES')
|
|
38
|
+
) {
|
|
39
|
+
sleepSync(5);
|
|
40
|
+
continue;
|
|
41
|
+
}
|
|
42
|
+
return fallback;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return fallback;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function getEffectiveCwd(options = {}) {
|
|
49
|
+
return options?.cwd ? path.resolve(String(options.cwd)) : process.cwd();
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function computeToolFailureKey({ toolName = '', command = '', filePath = '' } = {}) {
|
|
53
|
+
const normTool = String(toolName || '').trim() || 'unknown';
|
|
54
|
+
const rawCmd = String(command || '').trim();
|
|
55
|
+
if (rawCmd) {
|
|
56
|
+
const normalizedCmd = rawCmd
|
|
57
|
+
.replace(/\s+/g, ' ')
|
|
58
|
+
.replace(/(?:\s*;\s*echo\s+(?:\$\?|\$LASTEXITCODE|\$status)|\s*\|\|\s*true)\s*$/i, '')
|
|
59
|
+
.trim()
|
|
60
|
+
.slice(0, 240);
|
|
61
|
+
return `${normTool}:${normalizedCmd}`;
|
|
62
|
+
}
|
|
63
|
+
const rawFile = String(filePath || '').trim();
|
|
64
|
+
if (rawFile) {
|
|
65
|
+
return `${normTool}:${rawFile.replace(/\\/g, '/')}`;
|
|
66
|
+
}
|
|
67
|
+
return normTool;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* DET-04: Consecutive Tool Failure Breaker (`>= maxConsecutiveFailures` -> gate next attempt).
|
|
72
|
+
*/
|
|
73
|
+
export function evaluateDet04ConsecutiveFailures(params = {}) {
|
|
74
|
+
const toolName = String(params.toolName || '');
|
|
75
|
+
const command = String(params.command || '');
|
|
76
|
+
if (DET04_EXEMPT_READ_TOOLS.test(toolName) || /\bgit\s+stash\b/i.test(command)) {
|
|
77
|
+
return {
|
|
78
|
+
detectorId: 'DET-04',
|
|
79
|
+
triggered: false,
|
|
80
|
+
decision: 'allow',
|
|
81
|
+
consecutiveFailures: 0,
|
|
82
|
+
lastFailedToolKey: params.lastFailedToolKey || null,
|
|
83
|
+
reason: null
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const hasIncomingIdentity = Boolean(
|
|
88
|
+
params.toolKey || params.toolName || params.command || params.filePath
|
|
89
|
+
);
|
|
90
|
+
const incomingKey =
|
|
91
|
+
params.toolKey ||
|
|
92
|
+
computeToolFailureKey({
|
|
93
|
+
toolName,
|
|
94
|
+
command,
|
|
95
|
+
filePath: params.filePath
|
|
96
|
+
});
|
|
97
|
+
const sameTool =
|
|
98
|
+
!params.lastFailedToolKey ||
|
|
99
|
+
!hasIncomingIdentity ||
|
|
100
|
+
incomingKey === params.lastFailedToolKey;
|
|
101
|
+
const count = sameTool ? Math.max(0, Number(params.consecutiveFailures || 0)) : 0;
|
|
102
|
+
const threshold = Math.max(1, Number(params.maxConsecutiveFailures ?? params.threshold ?? DEFAULT_MAX_CONSECUTIVE_FAILURES));
|
|
103
|
+
const toolSuffix = params.toolName ? ` on ${params.toolName}` : '';
|
|
104
|
+
const rawMode = String(params.mode ?? params.flightMode ?? 'guard').trim().toUpperCase();
|
|
105
|
+
const isStrictAutoMode = rawMode === 'STRICT' || rawMode === 'AUTO' || rawMode === 'AUTO_PILOT';
|
|
106
|
+
|
|
107
|
+
if (count >= threshold) {
|
|
108
|
+
return {
|
|
109
|
+
detectorId: 'DET-04',
|
|
110
|
+
triggered: true,
|
|
111
|
+
decision: isStrictAutoMode ? 'deny' : 'ask',
|
|
112
|
+
consecutiveFailures: count,
|
|
113
|
+
lastFailedToolKey: params.lastFailedToolKey || incomingKey || null,
|
|
114
|
+
reason: `[Burnoff DET-04 Consecutive Failure Breaker] ${count} consecutive identical tool failures detected${toolSuffix}. Confirm retry or re-verify assumptions before continuing.`
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
return {
|
|
119
|
+
detectorId: 'DET-04',
|
|
120
|
+
triggered: false,
|
|
121
|
+
decision: 'allow',
|
|
122
|
+
consecutiveFailures: count,
|
|
123
|
+
lastFailedToolKey: params.lastFailedToolKey || null,
|
|
124
|
+
reason: null
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Sanitizes a session ID for `burnoff_breaker_state_<sessionId>.json`.
|
|
130
|
+
* Rejects non-string values so objects never stringify into `_object_Object_`.
|
|
131
|
+
*/
|
|
132
|
+
export function sanitizeBreakerSessionId(sessionId = 'default') {
|
|
133
|
+
if (typeof sessionId !== 'string') return 'default';
|
|
134
|
+
const trimmed = sessionId.trim();
|
|
135
|
+
if (!trimmed) return 'default';
|
|
136
|
+
return trimmed.replace(/[^a-zA-Z0-9._-]/g, '_').slice(0, 80) || 'default';
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Resolves `<cwd>/.claude/cache/burnoff_breaker_state_<sessionId>.json` (or `BURNOFF_HOME/runtime/` when no cwd is given).
|
|
141
|
+
*/
|
|
142
|
+
export function getBreakerStateFilePath(sessionId = 'default', options = {}) {
|
|
143
|
+
if (options?.breakerStatePath) {
|
|
144
|
+
return path.resolve(String(options.breakerStatePath));
|
|
145
|
+
}
|
|
146
|
+
const safeSid = sanitizeBreakerSessionId(sessionId);
|
|
147
|
+
if (options?.client === 'antigravity') {
|
|
148
|
+
const wsCwd = options?.cwd ? path.resolve(String(options.cwd)) : getEffectiveCwd(options);
|
|
149
|
+
return path.join(getWorkspaceStateDir(wsCwd, options.homeDir), `burnoff_breaker_state_${safeSid}.json`);
|
|
150
|
+
}
|
|
151
|
+
if (options?.cwd) {
|
|
152
|
+
return path.join(path.resolve(String(options.cwd)), '.claude', 'cache', `burnoff_breaker_state_${safeSid}.json`);
|
|
153
|
+
}
|
|
154
|
+
if (options?.useRuntimeDir) {
|
|
155
|
+
return path.join(getBurnoffRuntimeDir(options.homeDir || null), `burnoff_breaker_state_${safeSid}.json`);
|
|
156
|
+
}
|
|
157
|
+
return path.join(getEffectiveCwd(options), '.claude', 'cache', `burnoff_breaker_state_${safeSid}.json`);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
export function readBreakerStateSnapshot(sessionId = 'default', options = {}) {
|
|
161
|
+
return readJsonSafe(getBreakerStateFilePath(sessionId, options), null);
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
export function writeBreakerStateSnapshot(sessionId = 'default', snapshot = {}, options = {}) {
|
|
165
|
+
const filePath = getBreakerStateFilePath(sessionId, options);
|
|
166
|
+
atomicWriteJsonSync(filePath, snapshot, options);
|
|
167
|
+
return true;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* Performs a locked read-modify-write update on a session's breaker snapshot.
|
|
172
|
+
*/
|
|
173
|
+
export function updateBreakerStateAtomicSync(sessionId = 'default', mutatorFn, options = {}) {
|
|
174
|
+
if (typeof mutatorFn !== 'function') {
|
|
175
|
+
throw new TypeError('updateBreakerStateAtomicSync requires a mutator function');
|
|
176
|
+
}
|
|
177
|
+
const filePath = getBreakerStateFilePath(sessionId, options);
|
|
178
|
+
return withFileLockSync(
|
|
179
|
+
filePath,
|
|
180
|
+
() => {
|
|
181
|
+
const prior = readJsonSafe(filePath, null);
|
|
182
|
+
const next = mutatorFn(prior);
|
|
183
|
+
if (next && typeof next === 'object') {
|
|
184
|
+
atomicWriteJsonSync(filePath, next, {
|
|
185
|
+
...options,
|
|
186
|
+
maxRetries: Math.max(10, Number(options?.maxRetries || 10))
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
return next;
|
|
190
|
+
},
|
|
191
|
+
options
|
|
192
|
+
);
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* Atomically records a completed tool outcome (`failed` true/false and optional `git stash` timestamp).
|
|
197
|
+
*/
|
|
198
|
+
export function recordToolOutcomeAtomicSync(
|
|
199
|
+
sessionId = 'default',
|
|
200
|
+
{ toolName = '', command = '', filePath = '', failed = false, nowMs = Date.now() } = {},
|
|
201
|
+
options = {}
|
|
202
|
+
) {
|
|
203
|
+
const isStashPush =
|
|
204
|
+
!failed &&
|
|
205
|
+
Boolean(command) &&
|
|
206
|
+
/\bgit\s+stash\b/i.test(String(command)) &&
|
|
207
|
+
!/\bgit\s+stash\s+(?:pop|drop|clear|apply|list|show)\b/i.test(String(command));
|
|
208
|
+
const toolKey = computeToolFailureKey({ toolName, command, filePath });
|
|
209
|
+
|
|
210
|
+
return updateBreakerStateAtomicSync(
|
|
211
|
+
sessionId,
|
|
212
|
+
(prior) => {
|
|
213
|
+
const base = prior && typeof prior === 'object' ? { ...prior } : {};
|
|
214
|
+
const prevFailures = Math.max(0, Number(base.consecutiveFailures || 0));
|
|
215
|
+
const sameTool = !base.lastFailedToolKey || base.lastFailedToolKey === toolKey;
|
|
216
|
+
const nextFailures = failed ? (sameTool ? prevFailures + 1 : 1) : 0;
|
|
217
|
+
const next = {
|
|
218
|
+
...base,
|
|
219
|
+
schemaVersion: '1.0.0',
|
|
220
|
+
sessionId: String(sessionId || 'default'),
|
|
221
|
+
consecutiveFailures: nextFailures,
|
|
222
|
+
lastFailedToolKey: failed ? toolKey : null,
|
|
223
|
+
updatedAt: nowMs
|
|
224
|
+
};
|
|
225
|
+
if (isStashPush) {
|
|
226
|
+
next.lastGitStashAtMs = nowMs;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
// DET-09: Track successful same-file edits and reset on passing verification runs.
|
|
230
|
+
const prevThrash =
|
|
231
|
+
base.editThrashHistory && typeof base.editThrashHistory === 'object'
|
|
232
|
+
? { ...base.editThrashHistory }
|
|
233
|
+
: {};
|
|
234
|
+
if (!failed && command && isVerificationShellCommand(command)) {
|
|
235
|
+
next.editThrashHistory = {};
|
|
236
|
+
} else if (
|
|
237
|
+
!failed &&
|
|
238
|
+
EDIT_THRASH_TOOL_RE.test(String(toolName || '')) &&
|
|
239
|
+
filePath &&
|
|
240
|
+
!EXEMPT_MCP_CONFIG_BASENAME_RE.test(path.basename(String(filePath).trim()))
|
|
241
|
+
) {
|
|
242
|
+
const normKey = normalizeEditThrashPath(filePath, options?.cwd || '');
|
|
243
|
+
if (normKey) {
|
|
244
|
+
const cutoff = nowMs - EDIT_THRASH_STORAGE_TTL_MS;
|
|
245
|
+
const prunedHistory = {};
|
|
246
|
+
const keys = Object.keys(prevThrash).slice(-EDIT_THRASH_MAX_FILES);
|
|
247
|
+
for (const k of keys) {
|
|
248
|
+
const list = Array.isArray(prevThrash[k])
|
|
249
|
+
? prevThrash[k]
|
|
250
|
+
.map((v) => Number(v))
|
|
251
|
+
.filter((v) => Number.isFinite(v) && v >= cutoff && v <= nowMs)
|
|
252
|
+
: [];
|
|
253
|
+
if (list.length > 0) {
|
|
254
|
+
prunedHistory[k] = list.slice(-EDIT_THRASH_MAX_TIMESTAMPS);
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
const currentList = prunedHistory[normKey] ? [...prunedHistory[normKey]] : [];
|
|
258
|
+
currentList.push(nowMs);
|
|
259
|
+
prunedHistory[normKey] = currentList.slice(-EDIT_THRASH_MAX_TIMESTAMPS);
|
|
260
|
+
|
|
261
|
+
const finalKeys = Object.keys(prunedHistory);
|
|
262
|
+
if (finalKeys.length > EDIT_THRASH_MAX_FILES) {
|
|
263
|
+
for (const dropKey of finalKeys.slice(0, finalKeys.length - EDIT_THRASH_MAX_FILES)) {
|
|
264
|
+
if (dropKey !== normKey) delete prunedHistory[dropKey];
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
next.editThrashHistory = prunedHistory;
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
return next;
|
|
271
|
+
},
|
|
272
|
+
options
|
|
273
|
+
);
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
export function recordGitStashTimestampAtomicSync(sessionId = 'default', nowMs = Date.now(), options = {}) {
|
|
277
|
+
return updateBreakerStateAtomicSync(
|
|
278
|
+
sessionId,
|
|
279
|
+
(prior) => ({
|
|
280
|
+
...(prior && typeof prior === 'object' ? prior : {}),
|
|
281
|
+
schemaVersion: '1.0.0',
|
|
282
|
+
sessionId: String(sessionId || 'default'),
|
|
283
|
+
lastGitStashAtMs: Number(nowMs || Date.now()),
|
|
284
|
+
updatedAt: Number(nowMs || Date.now())
|
|
285
|
+
}),
|
|
286
|
+
options
|
|
287
|
+
);
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/**
|
|
291
|
+
* Normalizes a file path or glob pattern to POSIX forward slashes.
|
|
292
|
+
*/
|
|
293
|
+
export function normalizeScopePath(rawPath = '', cwd = '') {
|
|
294
|
+
let cleaned = String(rawPath || '').trim().replace(/\\/g, '/');
|
|
295
|
+
if (!cleaned) return '';
|
|
296
|
+
|
|
297
|
+
if (cwd) {
|
|
298
|
+
const normCwd = String(cwd).trim().replace(/\\/g, '/').replace(/\/+$/, '');
|
|
299
|
+
if (normCwd && cleaned.toLowerCase().startsWith(normCwd.toLowerCase() + '/')) {
|
|
300
|
+
cleaned = cleaned.slice(normCwd.length + 1);
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
return cleaned.replace(/^(\.\/)+/, '').replace(/\/+/g, '/');
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/**
|
|
308
|
+
* Converts a scope glob pattern (supporting dotfiles like `.github/*`, `.claude/**`, `.env*`) into a RegExp.
|
|
309
|
+
*/
|
|
310
|
+
export function globToDotfileRegex(pattern = '') {
|
|
311
|
+
const norm = normalizeScopePath(pattern);
|
|
312
|
+
if (!norm) return /^$/;
|
|
313
|
+
|
|
314
|
+
if (norm.endsWith('/')) {
|
|
315
|
+
const escapedDir = norm.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*');
|
|
316
|
+
return new RegExp(`^${escapedDir}.+$`, 'i');
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
let regexStr = '^';
|
|
320
|
+
for (let i = 0; i < norm.length; i++) {
|
|
321
|
+
const ch = norm[i];
|
|
322
|
+
if (ch === '*') {
|
|
323
|
+
if (norm[i + 1] === '*') {
|
|
324
|
+
regexStr += '.*';
|
|
325
|
+
i += 1;
|
|
326
|
+
if (norm[i + 1] === '/') {
|
|
327
|
+
i += 1;
|
|
328
|
+
}
|
|
329
|
+
} else {
|
|
330
|
+
regexStr += '[^/]*';
|
|
331
|
+
}
|
|
332
|
+
} else if (ch === '?') {
|
|
333
|
+
regexStr += '[^/]';
|
|
334
|
+
} else if ('.+^${}()|[]\\'.includes(ch)) {
|
|
335
|
+
regexStr += `\\${ch}`;
|
|
336
|
+
} else {
|
|
337
|
+
regexStr += ch;
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
regexStr += '$';
|
|
341
|
+
return new RegExp(regexStr, 'i');
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
export function matchesScopePattern(targetFilePath, scopePattern, cwd = '') {
|
|
345
|
+
const normTarget = normalizeScopePath(targetFilePath, cwd);
|
|
346
|
+
const normPattern = normalizeScopePath(scopePattern, cwd);
|
|
347
|
+
if (!normTarget || !normPattern) return false;
|
|
348
|
+
|
|
349
|
+
if (normTarget.toLowerCase() === normPattern.toLowerCase()) {
|
|
350
|
+
return true;
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
if (normPattern.endsWith('/*') && !normPattern.endsWith('/**')) {
|
|
354
|
+
const prefix = normPattern.slice(0, -1).toLowerCase();
|
|
355
|
+
if (normTarget.toLowerCase().startsWith(prefix)) {
|
|
356
|
+
return true;
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
return globToDotfileRegex(normPattern).test(normTarget);
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
export function getScopeLocksPath(options = {}) {
|
|
364
|
+
if (options?.locksFilePath) return path.resolve(String(options.locksFilePath));
|
|
365
|
+
if (options?.client === 'antigravity') {
|
|
366
|
+
return path.join(getWorkspaceStateDir(getEffectiveCwd(options), options.homeDir), 'active_scopes.json');
|
|
367
|
+
}
|
|
368
|
+
return path.join(getEffectiveCwd(options), '.claude', 'locks', 'active_scopes.json');
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
function normalizeScopeLockEntry(entry) {
|
|
372
|
+
if (!entry || typeof entry !== 'object') return null;
|
|
373
|
+
const ownerId = String(
|
|
374
|
+
entry.ownerId || entry.agent_id || entry.session_id || entry.sessionId || ''
|
|
375
|
+
).trim();
|
|
376
|
+
const rawScopes = Array.isArray(entry.scopes)
|
|
377
|
+
? entry.scopes
|
|
378
|
+
: Array.isArray(entry.files_locked)
|
|
379
|
+
? entry.files_locked
|
|
380
|
+
: [];
|
|
381
|
+
const scopes = rawScopes.map((s) => String(s || '').trim()).filter(Boolean);
|
|
382
|
+
if (!ownerId || scopes.length === 0) return null;
|
|
383
|
+
|
|
384
|
+
const acquiredAt =
|
|
385
|
+
typeof entry.acquiredAt === 'number' && Number.isFinite(entry.acquiredAt)
|
|
386
|
+
? entry.acquiredAt
|
|
387
|
+
: 0;
|
|
388
|
+
const expiresAt =
|
|
389
|
+
typeof entry.expiresAt === 'number' && Number.isFinite(entry.expiresAt)
|
|
390
|
+
? entry.expiresAt
|
|
391
|
+
: 0;
|
|
392
|
+
|
|
393
|
+
return { ownerId, scopes, acquiredAt, expiresAt };
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
function parseLocksFromRaw(raw, nowMs) {
|
|
397
|
+
const locks = [];
|
|
398
|
+
const seen = new Set();
|
|
399
|
+
for (const item of Array.isArray(raw?.locks) ? raw.locks : []) {
|
|
400
|
+
const norm = normalizeScopeLockEntry(item);
|
|
401
|
+
if (!norm) continue;
|
|
402
|
+
if (norm.expiresAt && norm.expiresAt <= nowMs) continue;
|
|
403
|
+
const key = `${norm.ownerId}::${norm.scopes.join('|')}`;
|
|
404
|
+
if (seen.has(key)) continue;
|
|
405
|
+
seen.add(key);
|
|
406
|
+
locks.push(norm);
|
|
407
|
+
}
|
|
408
|
+
return locks;
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
export function readActiveScopeLocks(options = {}) {
|
|
412
|
+
const nowMs = options.nowMs ?? Date.now();
|
|
413
|
+
const filePath = getScopeLocksPath(options);
|
|
414
|
+
const raw = readJsonSafe(filePath, { schemaVersion: '1.0.0', locks: [] });
|
|
415
|
+
return {
|
|
416
|
+
version: 1,
|
|
417
|
+
schemaVersion: '1.0.0',
|
|
418
|
+
locks: parseLocksFromRaw(raw, nowMs)
|
|
419
|
+
};
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
export function acquireScopeLock(params = {}, options = {}) {
|
|
423
|
+
const nowMs = options.nowMs ?? Date.now();
|
|
424
|
+
const cwd = getEffectiveCwd(options);
|
|
425
|
+
const ownerId = String(params.ownerId || 'default').trim();
|
|
426
|
+
const requestedScopes = Array.isArray(params.scopes)
|
|
427
|
+
? params.scopes.map((s) => normalizeScopePath(s, cwd)).filter(Boolean)
|
|
428
|
+
: [];
|
|
429
|
+
const ttlMs = Number(params.ttlMs ?? DEFAULT_SCOPE_LOCK_TTL_MS);
|
|
430
|
+
const filePath = getScopeLocksPath(options);
|
|
431
|
+
|
|
432
|
+
return withFileLockSync(
|
|
433
|
+
filePath,
|
|
434
|
+
() => {
|
|
435
|
+
const currentLocks = parseLocksFromRaw(readJsonSafe(filePath, { locks: [] }), nowMs);
|
|
436
|
+
for (const existing of currentLocks) {
|
|
437
|
+
if (existing.ownerId === ownerId) continue;
|
|
438
|
+
for (const existingScope of existing.scopes) {
|
|
439
|
+
for (const reqScope of requestedScopes) {
|
|
440
|
+
if (
|
|
441
|
+
matchesScopePattern(reqScope, existingScope, cwd) ||
|
|
442
|
+
matchesScopePattern(existingScope, reqScope, cwd)
|
|
443
|
+
) {
|
|
444
|
+
return {
|
|
445
|
+
acquired: false,
|
|
446
|
+
conflict: {
|
|
447
|
+
ownerId: existing.ownerId,
|
|
448
|
+
conflictingScope: existingScope,
|
|
449
|
+
requestedScope: reqScope,
|
|
450
|
+
expiresAt: existing.expiresAt
|
|
451
|
+
}
|
|
452
|
+
};
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
const mergeOwnerScopes = Boolean(params.mergeOwnerScopes ?? options.mergeOwnerScopes);
|
|
459
|
+
const existingOwner = mergeOwnerScopes
|
|
460
|
+
? currentLocks.find((l) => l.ownerId === ownerId)
|
|
461
|
+
: null;
|
|
462
|
+
const mergedScopes = existingOwner
|
|
463
|
+
? [...new Set([...(existingOwner.scopes || []), ...requestedScopes])]
|
|
464
|
+
: requestedScopes;
|
|
465
|
+
const nextRecord = {
|
|
466
|
+
ownerId,
|
|
467
|
+
scopes: mergedScopes,
|
|
468
|
+
acquiredAt: existingOwner?.acquiredAt || nowMs,
|
|
469
|
+
expiresAt: nowMs + ttlMs
|
|
470
|
+
};
|
|
471
|
+
const nextLocks = [
|
|
472
|
+
...currentLocks.filter((l) => l.ownerId !== ownerId),
|
|
473
|
+
nextRecord
|
|
474
|
+
];
|
|
475
|
+
atomicWriteJsonSync(
|
|
476
|
+
filePath,
|
|
477
|
+
{
|
|
478
|
+
version: 1,
|
|
479
|
+
schemaVersion: '1.0.0',
|
|
480
|
+
updatedAt: nowMs,
|
|
481
|
+
locks: nextLocks
|
|
482
|
+
},
|
|
483
|
+
options
|
|
484
|
+
);
|
|
485
|
+
return { acquired: true, lock: nextRecord, conflict: null };
|
|
486
|
+
},
|
|
487
|
+
{
|
|
488
|
+
...options,
|
|
489
|
+
fallbackValue: { ok: false, acquired: false, skippedByLockTimeout: true, conflict: null }
|
|
490
|
+
}
|
|
491
|
+
);
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
export function releaseScopeLock(ownerId, options = {}) {
|
|
495
|
+
const nowMs = options.nowMs ?? Date.now();
|
|
496
|
+
const cwd = getEffectiveCwd(options);
|
|
497
|
+
const filePath = getScopeLocksPath(options);
|
|
498
|
+
const targetOwner = String(ownerId || '').trim();
|
|
499
|
+
const targetScope = options.scope ? normalizeScopePath(options.scope, cwd) : '';
|
|
500
|
+
|
|
501
|
+
return withFileLockSync(
|
|
502
|
+
filePath,
|
|
503
|
+
() => {
|
|
504
|
+
const currentLocks = parseLocksFromRaw(readJsonSafe(filePath, { locks: [] }), nowMs);
|
|
505
|
+
let nextLocks;
|
|
506
|
+
if (targetScope) {
|
|
507
|
+
nextLocks = [];
|
|
508
|
+
for (const lock of currentLocks) {
|
|
509
|
+
if (lock.ownerId !== targetOwner) {
|
|
510
|
+
nextLocks.push(lock);
|
|
511
|
+
continue;
|
|
512
|
+
}
|
|
513
|
+
const remainingScopes = (lock.scopes || []).filter(
|
|
514
|
+
(s) => normalizeScopePath(s, cwd).toLowerCase() !== targetScope.toLowerCase()
|
|
515
|
+
);
|
|
516
|
+
if (remainingScopes.length > 0) {
|
|
517
|
+
nextLocks.push({ ...lock, scopes: remainingScopes });
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
} else {
|
|
521
|
+
nextLocks = currentLocks.filter((l) => l.ownerId !== targetOwner);
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
if (nextLocks.length === 0) {
|
|
525
|
+
if (fs.existsSync(filePath)) {
|
|
526
|
+
try {
|
|
527
|
+
fs.unlinkSync(filePath);
|
|
528
|
+
} catch (err) {
|
|
529
|
+
if (err?.code !== 'ENOENT') {
|
|
530
|
+
void err; // ignore: lock file unlink best-effort when empty
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
return { released: true, remainingLocks: 0 };
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
atomicWriteJsonSync(
|
|
538
|
+
filePath,
|
|
539
|
+
{
|
|
540
|
+
version: 1,
|
|
541
|
+
schemaVersion: '1.0.0',
|
|
542
|
+
updatedAt: nowMs,
|
|
543
|
+
locks: nextLocks
|
|
544
|
+
},
|
|
545
|
+
options
|
|
546
|
+
);
|
|
547
|
+
return { released: true, remainingLocks: nextLocks.length };
|
|
548
|
+
},
|
|
549
|
+
{
|
|
550
|
+
...options,
|
|
551
|
+
fallbackValue: { ok: false, released: false, skippedByLockTimeout: true, remainingLocks: 0 }
|
|
552
|
+
}
|
|
553
|
+
);
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
/**
|
|
557
|
+
* DET-20: Checks rate-limit/spend exhaustion and active concurrent file-scope locks.
|
|
558
|
+
*/
|
|
559
|
+
export function evaluateScopeAndQuotaBrake(params = {}, options = {}) {
|
|
560
|
+
const nowMs = options.nowMs ?? params.nowMs ?? Date.now();
|
|
561
|
+
const cwd = options.cwd || process.cwd();
|
|
562
|
+
const ownerId = String(
|
|
563
|
+
params.ownerId || params.agentId || params.agent_id || params.sessionId || params.session_id || 'default'
|
|
564
|
+
).trim();
|
|
565
|
+
const targetFilePath = normalizeScopePath(
|
|
566
|
+
params.targetFilePath || params.filePath || params.file_path || params.path || '',
|
|
567
|
+
cwd
|
|
568
|
+
);
|
|
569
|
+
const rateLimits = params.rateLimits || {};
|
|
570
|
+
|
|
571
|
+
const fiveHour = rateLimits.fiveHour || rateLimits.five_hour || null;
|
|
572
|
+
const spendLimit = rateLimits.spendLimit || rateLimits.spend_limit || null;
|
|
573
|
+
|
|
574
|
+
if (fiveHour) {
|
|
575
|
+
const remPct =
|
|
576
|
+
typeof fiveHour.remaining_pct === 'number'
|
|
577
|
+
? fiveHour.remaining_pct
|
|
578
|
+
: typeof fiveHour.limit === 'number' && fiveHour.limit > 0
|
|
579
|
+
? ((fiveHour.limit - Number(fiveHour.used || 0)) / fiveHour.limit) * 100
|
|
580
|
+
: 100;
|
|
581
|
+
if (remPct <= 0) {
|
|
582
|
+
return {
|
|
583
|
+
detectorId: 'DET-20',
|
|
584
|
+
triggered: true,
|
|
585
|
+
decision: 'deny',
|
|
586
|
+
subType: 'QUOTA_FIVE_HOUR_EXHAUSTED',
|
|
587
|
+
reason: '[Burnoff DET-20 Quota Hard Brake] 5-hour rate limit window is exhausted (0% remaining). Halting tool execution to prevent failed turn loops.'
|
|
588
|
+
};
|
|
589
|
+
}
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
if (spendLimit) {
|
|
593
|
+
const remUsd =
|
|
594
|
+
typeof spendLimit.remaining_usd === 'number'
|
|
595
|
+
? spendLimit.remaining_usd
|
|
596
|
+
: typeof spendLimit.limit_usd === 'number'
|
|
597
|
+
? spendLimit.limit_usd - Number(spendLimit.spent_usd || 0)
|
|
598
|
+
: Infinity;
|
|
599
|
+
if (remUsd <= 0) {
|
|
600
|
+
return {
|
|
601
|
+
detectorId: 'DET-20',
|
|
602
|
+
triggered: true,
|
|
603
|
+
decision: 'deny',
|
|
604
|
+
subType: 'QUOTA_SPEND_LIMIT_EXHAUSTED',
|
|
605
|
+
reason: '[Burnoff DET-20 Quota Hard Brake] Session USD spend limit reached ($0.00 remaining). Halting tool execution.'
|
|
606
|
+
};
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
if (targetFilePath) {
|
|
611
|
+
const isRead = Boolean(params.isRead || /^(read|read_file|view_file)$/i.test(String(params.toolName || '')));
|
|
612
|
+
const state = readActiveScopeLocks({ ...options, nowMs });
|
|
613
|
+
for (const lock of state.locks) {
|
|
614
|
+
if (lock.ownerId === ownerId) continue;
|
|
615
|
+
for (const scopePattern of lock.scopes || []) {
|
|
616
|
+
if (matchesScopePattern(targetFilePath, scopePattern, cwd)) {
|
|
617
|
+
if (isRead) {
|
|
618
|
+
return {
|
|
619
|
+
detectorId: 'DET-20',
|
|
620
|
+
triggered: true,
|
|
621
|
+
decision: 'allow',
|
|
622
|
+
advisory: true,
|
|
623
|
+
subType: 'DUPLICATE_READ_SCOPE',
|
|
624
|
+
conflictingOwner: lock.ownerId,
|
|
625
|
+
conflictingScope: scopePattern,
|
|
626
|
+
targetFilePath,
|
|
627
|
+
additionalContext: `[Burnoff DET-20 Concurrent Read Notice] File "${targetFilePath}" is claimed by active worker "${lock.ownerId}" (scope "${scopePattern}"). Keep reads bounded.`,
|
|
628
|
+
reason: `[Burnoff DET-20 Concurrent Read Notice] File "${targetFilePath}" is claimed by active worker "${lock.ownerId}" (scope "${scopePattern}").`
|
|
629
|
+
};
|
|
630
|
+
}
|
|
631
|
+
return {
|
|
632
|
+
detectorId: 'DET-20',
|
|
633
|
+
triggered: true,
|
|
634
|
+
decision: 'deny',
|
|
635
|
+
subType: 'SCOPE_LOCK_CONFLICT',
|
|
636
|
+
conflictingOwner: lock.ownerId,
|
|
637
|
+
conflictingScope: scopePattern,
|
|
638
|
+
targetFilePath,
|
|
639
|
+
reason:
|
|
640
|
+
`[Burnoff DET-20 Concurrent Scope Lock] File "${targetFilePath}" is locked by active worker "${lock.ownerId}" ` +
|
|
641
|
+
`(scope "${scopePattern}"). Wait for lock release before editing.`
|
|
642
|
+
};
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
return {
|
|
649
|
+
detectorId: 'DET-20',
|
|
650
|
+
triggered: false,
|
|
651
|
+
decision: 'allow',
|
|
652
|
+
subType: null,
|
|
653
|
+
reason: null
|
|
654
|
+
};
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
/**
|
|
658
|
+
* DET-05: Subagent Fan-Out & Prompt-Bloat Guard (`Task|Agent|invoke_subagent`).
|
|
659
|
+
* Flags rapid parallel subagent bursts or oversized child prompts that multiply prefill cost.
|
|
660
|
+
*/
|
|
661
|
+
export function evaluateDet05SubagentFanout(params = {}) {
|
|
662
|
+
const toolName = String(params.toolName || '');
|
|
663
|
+
if (!SUBAGENT_TOOL_REGEX.test(toolName)) {
|
|
664
|
+
return {
|
|
665
|
+
detectorId: 'DET-05',
|
|
666
|
+
triggered: false,
|
|
667
|
+
decision: 'allow',
|
|
668
|
+
subType: null,
|
|
669
|
+
burstCount: 0,
|
|
670
|
+
promptChars: 0,
|
|
671
|
+
reason: null,
|
|
672
|
+
additionalContext: null
|
|
673
|
+
};
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
const nowMs = Number.isFinite(Number(params.nowMs)) ? Number(params.nowMs) : Date.now();
|
|
677
|
+
const maxBurstCount = Math.max(1, Number(params.maxBurstCount ?? DEFAULT_SUBAGENT_MAX_BURST_COUNT));
|
|
678
|
+
const burstWindowSec = Math.max(1, Number(params.burstWindowSec ?? DEFAULT_SUBAGENT_BURST_WINDOW_SEC));
|
|
679
|
+
const maxPromptChars = Math.max(256, Number(params.maxPromptChars ?? DEFAULT_SUBAGENT_MAX_PROMPT_CHARS));
|
|
680
|
+
const windowStartMs = nowMs - burstWindowSec * 1000;
|
|
681
|
+
|
|
682
|
+
const recentRaw = Array.isArray(params.recentSpawnTimestampsMs) ? params.recentSpawnTimestampsMs : [];
|
|
683
|
+
const pruned = recentRaw
|
|
684
|
+
.map((ts) => Number(ts))
|
|
685
|
+
.filter((ts) => Number.isFinite(ts) && ts >= windowStartMs && ts <= nowMs);
|
|
686
|
+
const burstCount = pruned.length + 1;
|
|
687
|
+
const promptChars = String(params.promptText || '').length;
|
|
688
|
+
|
|
689
|
+
const burstExceeded = burstCount > maxBurstCount;
|
|
690
|
+
const promptExceeded = promptChars > maxPromptChars;
|
|
691
|
+
|
|
692
|
+
if (!burstExceeded && !promptExceeded) {
|
|
693
|
+
return {
|
|
694
|
+
detectorId: 'DET-05',
|
|
695
|
+
triggered: false,
|
|
696
|
+
decision: 'allow',
|
|
697
|
+
subType: null,
|
|
698
|
+
burstCount,
|
|
699
|
+
promptChars,
|
|
700
|
+
reason: null,
|
|
701
|
+
additionalContext: null
|
|
702
|
+
};
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
const subType =
|
|
706
|
+
burstExceeded && promptExceeded
|
|
707
|
+
? 'BOTH'
|
|
708
|
+
: burstExceeded
|
|
709
|
+
? 'BURST_FANOUT'
|
|
710
|
+
: 'OVERSIZED_PROMPT';
|
|
711
|
+
const action = String(params.action || 'advisory').trim().toLowerCase();
|
|
712
|
+
const decision = action === 'deny' ? 'deny' : 'allow';
|
|
713
|
+
|
|
714
|
+
const parts = [];
|
|
715
|
+
if (burstExceeded) {
|
|
716
|
+
parts.push(`burst spawn ${burstCount} > ${maxBurstCount} within ${burstWindowSec}s`);
|
|
717
|
+
}
|
|
718
|
+
if (promptExceeded) {
|
|
719
|
+
const estTok = Math.ceil(promptChars / 4);
|
|
720
|
+
parts.push(`child prompt ${promptChars.toLocaleString('en-US')} chars (~${estTok.toLocaleString('en-US')} est. tok) > ${maxPromptChars.toLocaleString('en-US')} chars`);
|
|
721
|
+
}
|
|
722
|
+
const reason =
|
|
723
|
+
`[Burnoff DET-05 Subagent Fan-Out Guard] ${parts.join(' and ')} on ${toolName}. ` +
|
|
724
|
+
`Pass narrow targeted task slices instead of full parent transcripts and keep parallel fan-out bounded.`;
|
|
725
|
+
|
|
726
|
+
return {
|
|
727
|
+
detectorId: 'DET-05',
|
|
728
|
+
triggered: true,
|
|
729
|
+
decision,
|
|
730
|
+
subType,
|
|
731
|
+
burstCount,
|
|
732
|
+
promptChars,
|
|
733
|
+
reason,
|
|
734
|
+
additionalContext: decision === 'allow' ? reason : null
|
|
735
|
+
};
|
|
736
|
+
}
|
|
737
|
+
|
|
738
|
+
/**
|
|
739
|
+
* Atomically records a subagent spawn timestamp within the active burst window.
|
|
740
|
+
*/
|
|
741
|
+
export function recordSubagentSpawnAtomicSync(
|
|
742
|
+
sessionId = 'default',
|
|
743
|
+
{ nowMs = Date.now(), burstWindowSec = DEFAULT_SUBAGENT_BURST_WINDOW_SEC } = {},
|
|
744
|
+
options = {}
|
|
745
|
+
) {
|
|
746
|
+
const ts = Number.isFinite(Number(nowMs)) ? Number(nowMs) : Date.now();
|
|
747
|
+
const winMs = Math.max(1, Number(burstWindowSec || DEFAULT_SUBAGENT_BURST_WINDOW_SEC)) * 1000;
|
|
748
|
+
const cutoff = ts - winMs;
|
|
749
|
+
return updateBreakerStateAtomicSync(
|
|
750
|
+
sessionId,
|
|
751
|
+
(prior) => {
|
|
752
|
+
const base = prior && typeof prior === 'object' ? { ...prior } : {};
|
|
753
|
+
const existing = Array.isArray(base.subagentSpawnTimestampsMs)
|
|
754
|
+
? base.subagentSpawnTimestampsMs
|
|
755
|
+
.map((v) => Number(v))
|
|
756
|
+
.filter((v) => Number.isFinite(v) && v >= cutoff && v <= ts)
|
|
757
|
+
: [];
|
|
758
|
+
existing.push(ts);
|
|
759
|
+
return {
|
|
760
|
+
...base,
|
|
761
|
+
schemaVersion: '1.0.0',
|
|
762
|
+
sessionId: String(sessionId || 'default'),
|
|
763
|
+
subagentSpawnTimestampsMs: existing.slice(-32),
|
|
764
|
+
updatedAt: ts
|
|
765
|
+
};
|
|
766
|
+
},
|
|
767
|
+
options
|
|
768
|
+
);
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
export default {
|
|
772
|
+
DEFAULT_MAX_CONSECUTIVE_FAILURES,
|
|
773
|
+
DEFAULT_SCOPE_LOCK_TTL_MS,
|
|
774
|
+
SUBAGENT_TOOL_REGEX,
|
|
775
|
+
DEFAULT_SUBAGENT_MAX_BURST_COUNT,
|
|
776
|
+
DEFAULT_SUBAGENT_BURST_WINDOW_SEC,
|
|
777
|
+
DEFAULT_SUBAGENT_MAX_PROMPT_CHARS,
|
|
778
|
+
computeToolFailureKey,
|
|
779
|
+
evaluateDet04ConsecutiveFailures,
|
|
780
|
+
evaluateDet05SubagentFanout,
|
|
781
|
+
recordSubagentSpawnAtomicSync,
|
|
782
|
+
sanitizeBreakerSessionId,
|
|
783
|
+
getBreakerStateFilePath,
|
|
784
|
+
readBreakerStateSnapshot,
|
|
785
|
+
writeBreakerStateSnapshot,
|
|
786
|
+
updateBreakerStateAtomicSync,
|
|
787
|
+
recordToolOutcomeAtomicSync,
|
|
788
|
+
recordGitStashTimestampAtomicSync,
|
|
789
|
+
normalizeScopePath,
|
|
790
|
+
globToDotfileRegex,
|
|
791
|
+
matchesScopePattern,
|
|
792
|
+
getScopeLocksPath,
|
|
793
|
+
readActiveScopeLocks,
|
|
794
|
+
acquireScopeLock,
|
|
795
|
+
releaseScopeLock,
|
|
796
|
+
evaluateScopeAndQuotaBrake
|
|
797
|
+
};
|