burnoff 1.3.0 → 1.4.1

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