burnoff 1.1.0 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.github/workflows/burnoff-pr-gate.yml +3 -3
- package/README.md +66 -78
- package/bin/burnoff.mjs +67 -23
- package/hooks/hook-io.mjs +19 -7
- package/hooks/post-tool-use.mjs +33 -26
- package/hooks/pre-tool-use.mjs +43 -41
- package/hooks/session-lifecycle.mjs +40 -0
- package/package.json +7 -5
- package/src/ci/ci-gate.mjs +22 -0
- package/src/ci/pr-cost.mjs +42 -10
- package/src/ci/team-digest.mjs +5 -3
- package/src/cli/audit.mjs +103 -18
- package/src/cli/doctor.mjs +209 -14
- package/src/cli/init.mjs +349 -96
- package/src/cli/startup-audit.mjs +500 -24
- package/src/clients/antigravity.mjs +285 -0
- package/src/clients/claude-code.mjs +180 -0
- package/src/clients/detect.mjs +64 -0
- package/src/config/loader.mjs +11 -4
- package/src/config/paths.mjs +62 -2
- package/src/config/policy.mjs +34 -5
- package/src/config/pricing.mjs +16 -5
- package/src/guards/loop-breaker.mjs +198 -13
- package/src/guards/post-tool-engine.mjs +289 -29
- package/src/guards/pre-tool-engine.mjs +336 -129
- package/src/guards/read-clamp.mjs +78 -18
- package/src/guards/session-hook.mjs +207 -0
- package/src/guards/shell-guard.mjs +583 -73
- package/src/ipc/daemon.mjs +50 -8
- package/src/ipc/fast-client.mjs +62 -5
- package/src/ipc/protocol.mjs +1 -1
- package/src/storage/antigravity-parser.mjs +258 -0
- package/src/storage/file-lock.mjs +13 -4
- package/src/storage/fts5-archive.mjs +4 -4
- package/src/storage/jsonl-parser.mjs +7 -1
- package/src/storage/ledger.mjs +10 -3
- package/src/storage/sqlite-client.mjs +4 -2
- package/hooks/hooks.json +0 -12
package/src/config/policy.mjs
CHANGED
|
@@ -9,14 +9,21 @@ export const DEFAULT_POLICY = Object.freeze({
|
|
|
9
9
|
det03Enabled: true,
|
|
10
10
|
det04Enabled: true,
|
|
11
11
|
det04Threshold: 3,
|
|
12
|
+
secretAllow: Object.freeze([]),
|
|
12
13
|
strictTestIntegrity: false,
|
|
13
|
-
scopeLockEnabled: true
|
|
14
|
+
scopeLockEnabled: true,
|
|
15
|
+
subagentFanoutEnabled: true,
|
|
16
|
+
subagentFanoutAction: 'advisory',
|
|
17
|
+
subagentMaxBurstCount: 4,
|
|
18
|
+
subagentBurstWindowSec: 60,
|
|
19
|
+
subagentMaxPromptChars: 8000
|
|
14
20
|
}),
|
|
15
21
|
readClamp: Object.freeze({
|
|
16
22
|
enabled: true,
|
|
17
23
|
maxLines: 250,
|
|
18
24
|
maxBytes: 16384,
|
|
19
25
|
neverClampCodeOffCliff: true,
|
|
26
|
+
neverClampExt: Object.freeze([]),
|
|
20
27
|
headProbeMaxBytes: 8388608,
|
|
21
28
|
codeRealizationDiscount: 0.27
|
|
22
29
|
}),
|
|
@@ -39,8 +46,14 @@ export const DEFAULT_POLICY = Object.freeze({
|
|
|
39
46
|
|
|
40
47
|
function cloneDefaultPolicy() {
|
|
41
48
|
return {
|
|
42
|
-
guards: {
|
|
43
|
-
|
|
49
|
+
guards: {
|
|
50
|
+
...DEFAULT_POLICY.guards,
|
|
51
|
+
secretAllow: [...DEFAULT_POLICY.guards.secretAllow]
|
|
52
|
+
},
|
|
53
|
+
readClamp: {
|
|
54
|
+
...DEFAULT_POLICY.readClamp,
|
|
55
|
+
neverClampExt: [...DEFAULT_POLICY.readClamp.neverClampExt]
|
|
56
|
+
},
|
|
44
57
|
postTool: { ...DEFAULT_POLICY.postTool },
|
|
45
58
|
ciBudgetGate: { ...DEFAULT_POLICY.ciBudgetGate }
|
|
46
59
|
};
|
|
@@ -168,6 +181,21 @@ function mergePolicy(base, override) {
|
|
|
168
181
|
result[section] = { ...result[section], ...override[section] };
|
|
169
182
|
}
|
|
170
183
|
}
|
|
184
|
+
if (Array.isArray(result.guards.secretAllow)) {
|
|
185
|
+
result.guards.secretAllow = result.guards.secretAllow
|
|
186
|
+
.map((item) => String(item || '').trim())
|
|
187
|
+
.filter(Boolean);
|
|
188
|
+
} else {
|
|
189
|
+
result.guards.secretAllow = [];
|
|
190
|
+
}
|
|
191
|
+
if (Array.isArray(result.readClamp.neverClampExt)) {
|
|
192
|
+
result.readClamp.neverClampExt = result.readClamp.neverClampExt
|
|
193
|
+
.map((item) => String(item || '').trim().toLowerCase())
|
|
194
|
+
.filter(Boolean)
|
|
195
|
+
.map((ext) => (ext.startsWith('.') ? ext : `.${ext}`));
|
|
196
|
+
} else {
|
|
197
|
+
result.readClamp.neverClampExt = [];
|
|
198
|
+
}
|
|
171
199
|
for (const [k, v] of Object.entries(override)) {
|
|
172
200
|
if (!(k in result)) {
|
|
173
201
|
result[k] = v;
|
|
@@ -233,13 +261,14 @@ export function loadBurnoffPolicy(cwd = process.cwd()) {
|
|
|
233
261
|
if (POLICY_CACHE.size > 64) POLICY_CACHE.clear();
|
|
234
262
|
POLICY_CACHE.set(baseDir, { ts: nowMs, mtimeMs, value });
|
|
235
263
|
return value;
|
|
236
|
-
} catch {
|
|
264
|
+
} catch (err) {
|
|
237
265
|
const value = {
|
|
238
266
|
...cloneDefaultPolicy(),
|
|
239
267
|
rawCiBudgetGate: {},
|
|
240
268
|
sourcePath: candidate,
|
|
241
269
|
exists: true,
|
|
242
|
-
parseError: true
|
|
270
|
+
parseError: true,
|
|
271
|
+
parseErrorMessage: err?.message || 'Invalid YAML syntax'
|
|
243
272
|
};
|
|
244
273
|
if (POLICY_CACHE.size > 64) POLICY_CACHE.clear();
|
|
245
274
|
POLICY_CACHE.set(baseDir, { ts: nowMs, mtimeMs, value });
|
package/src/config/pricing.mjs
CHANGED
|
@@ -210,7 +210,7 @@ export const RATE_CARD_MODELS = Object.freeze({
|
|
|
210
210
|
modelId: 'claude-opus-5-5',
|
|
211
211
|
label: 'Claude Opus 5.5',
|
|
212
212
|
cachedReadWeight: 0.05,
|
|
213
|
-
minCacheableTokens:
|
|
213
|
+
minCacheableTokens: 512,
|
|
214
214
|
sharedPoolCeiling: 1000000,
|
|
215
215
|
cliffThresholdTokens: null,
|
|
216
216
|
outputIncludesThinking: true,
|
|
@@ -227,7 +227,7 @@ export const RATE_CARD_MODELS = Object.freeze({
|
|
|
227
227
|
modelId: 'claude-sonnet-5-5',
|
|
228
228
|
label: 'Claude Sonnet 5.5',
|
|
229
229
|
cachedReadWeight: 0.05,
|
|
230
|
-
minCacheableTokens:
|
|
230
|
+
minCacheableTokens: 512,
|
|
231
231
|
sharedPoolCeiling: 1000000,
|
|
232
232
|
cliffThresholdTokens: null,
|
|
233
233
|
outputIncludesThinking: true,
|
|
@@ -278,7 +278,7 @@ export const RATE_CARD_MODELS = Object.freeze({
|
|
|
278
278
|
modelId: 'claude-haiku-5-5',
|
|
279
279
|
label: 'Claude Haiku 5.5',
|
|
280
280
|
cachedReadWeight: 0.10,
|
|
281
|
-
minCacheableTokens:
|
|
281
|
+
minCacheableTokens: 512,
|
|
282
282
|
sharedPoolCeiling: 1000000,
|
|
283
283
|
cliffThresholdTokens: 100000,
|
|
284
284
|
outputIncludesThinking: true,
|
|
@@ -430,7 +430,7 @@ function cleanModelString(raw = '') {
|
|
|
430
430
|
.toLowerCase()
|
|
431
431
|
.replace(/\[[12]m\]/gi, '')
|
|
432
432
|
.replace(/\s*\((?:low|medium|med|high|xhigh|extra[\s-]*high|max|minimal|auto|fast|thinking|standard|extended[\s-]*thinking)(?:\s*[,/|]\s*(?:low|medium|med|high|xhigh|extra[\s-]*high|max|minimal|auto|fast|thinking|standard|extended[\s-]*thinking))*\)\s*$/i, '')
|
|
433
|
-
.replace(/^(?:google|anthropic|openai)\//i, '')
|
|
433
|
+
.replace(/^(?:google|anthropic|openai|models)\//i, '')
|
|
434
434
|
.replace(/[()]+/g, ' ')
|
|
435
435
|
.replace(/\s+/g, '-')
|
|
436
436
|
.replace(/-+/g, '-')
|
|
@@ -720,7 +720,8 @@ export function valuateCall(call = {}) {
|
|
|
720
720
|
const remainingWrite = Math.max(0, genericWrite - (write5mTokens + write1hTokens));
|
|
721
721
|
const effWrite5m = write5mTokens + (call.cacheTtlTier === '1h' ? 0 : remainingWrite);
|
|
722
722
|
const effWrite1h = write1hTokens + (call.cacheTtlTier === '1h' ? remainingWrite : 0);
|
|
723
|
-
const
|
|
723
|
+
const rawOutputTokens = readNum(call, ['outputTokens', 'output', 'output_tokens']);
|
|
724
|
+
const thinkingTokens = readNum(call, ['thinkingTokens', 'thinking_tokens']);
|
|
724
725
|
const promptTokens = Math.max(
|
|
725
726
|
readNum(call, ['promptTokens', 'totalPromptTokens']),
|
|
726
727
|
uncachedTokens + cachedTokens + effWrite5m + effWrite1h
|
|
@@ -736,6 +737,12 @@ export function valuateCall(call = {}) {
|
|
|
736
737
|
serviceTier: call.serviceTier || call.service_tier || 'standard'
|
|
737
738
|
});
|
|
738
739
|
|
|
740
|
+
const includesThinking =
|
|
741
|
+
call.outputIncludesThinking !== undefined
|
|
742
|
+
? Boolean(call.outputIncludesThinking)
|
|
743
|
+
: card.outputIncludesThinking !== false;
|
|
744
|
+
const outputTokens = includesThinking ? rawOutputTokens : rawOutputTokens + thinkingTokens;
|
|
745
|
+
|
|
739
746
|
const quotaWeight = resolveSubscriptionQuotaWeight({
|
|
740
747
|
model: call.model || call.modelId || call.rawModel || '',
|
|
741
748
|
label: call.label || '',
|
|
@@ -766,6 +773,8 @@ export function valuateCall(call = {}) {
|
|
|
766
773
|
write5mTokens: effWrite5m,
|
|
767
774
|
write1hTokens: effWrite1h,
|
|
768
775
|
outputTokens,
|
|
776
|
+
thinkingTokens,
|
|
777
|
+
outputIncludesThinking: includesThinking,
|
|
769
778
|
promptTokens,
|
|
770
779
|
uncachedEquivalentInputUnits,
|
|
771
780
|
cachedEquivalentUnits,
|
|
@@ -810,6 +819,8 @@ export function valuateCall(call = {}) {
|
|
|
810
819
|
write5mTokens: effWrite5m,
|
|
811
820
|
write1hTokens: effWrite1h,
|
|
812
821
|
outputTokens,
|
|
822
|
+
thinkingTokens,
|
|
823
|
+
outputIncludesThinking: includesThinking,
|
|
813
824
|
promptTokens,
|
|
814
825
|
uncachedEquivalentInputUnits,
|
|
815
826
|
cachedEquivalentUnits,
|
|
@@ -8,10 +8,14 @@ import fs from 'node:fs';
|
|
|
8
8
|
import path from 'node:path';
|
|
9
9
|
import { withFileLockSync } from '../storage/file-lock.mjs';
|
|
10
10
|
import { atomicWriteJsonSync, sleepSync } from '../storage/atomic-io.mjs';
|
|
11
|
-
import { getBurnoffRuntimeDir, getHomeDir } from '../config/paths.mjs';
|
|
11
|
+
import { getBurnoffRuntimeDir, getHomeDir, getWorkspaceStateDir } from '../config/paths.mjs';
|
|
12
12
|
|
|
13
13
|
export const DEFAULT_MAX_CONSECUTIVE_FAILURES = 3;
|
|
14
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;
|
|
15
19
|
const DET04_EXEMPT_READ_TOOLS = /^(?:Read|Grep|Glob)$/i;
|
|
16
20
|
|
|
17
21
|
function readJsonSafe(filePath, fallback = null) {
|
|
@@ -42,8 +46,8 @@ export function computeToolFailureKey({ toolName = '', command = '', filePath =
|
|
|
42
46
|
const normTool = String(toolName || '').trim() || 'unknown';
|
|
43
47
|
const rawCmd = String(command || '').trim();
|
|
44
48
|
if (rawCmd) {
|
|
45
|
-
const
|
|
46
|
-
return `${normTool}:${
|
|
49
|
+
const normalizedCmd = rawCmd.replace(/\s+/g, ' ').slice(0, 240);
|
|
50
|
+
return `${normTool}:${normalizedCmd}`;
|
|
47
51
|
}
|
|
48
52
|
const rawFile = String(filePath || '').trim();
|
|
49
53
|
if (rawFile) {
|
|
@@ -53,7 +57,7 @@ export function computeToolFailureKey({ toolName = '', command = '', filePath =
|
|
|
53
57
|
}
|
|
54
58
|
|
|
55
59
|
/**
|
|
56
|
-
* DET-04: Consecutive Tool Failure Breaker (`>= maxConsecutiveFailures` ->
|
|
60
|
+
* DET-04: Consecutive Tool Failure Breaker (`>= maxConsecutiveFailures` -> gate next attempt).
|
|
57
61
|
*/
|
|
58
62
|
export function evaluateDet04ConsecutiveFailures(params = {}) {
|
|
59
63
|
const toolName = String(params.toolName || '');
|
|
@@ -86,15 +90,17 @@ export function evaluateDet04ConsecutiveFailures(params = {}) {
|
|
|
86
90
|
const count = sameTool ? Math.max(0, Number(params.consecutiveFailures || 0)) : 0;
|
|
87
91
|
const threshold = Math.max(1, Number(params.maxConsecutiveFailures ?? params.threshold ?? DEFAULT_MAX_CONSECUTIVE_FAILURES));
|
|
88
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';
|
|
89
95
|
|
|
90
96
|
if (count >= threshold) {
|
|
91
97
|
return {
|
|
92
98
|
detectorId: 'DET-04',
|
|
93
99
|
triggered: true,
|
|
94
|
-
decision: 'deny',
|
|
100
|
+
decision: isStrictAutoMode ? 'deny' : 'ask',
|
|
95
101
|
consecutiveFailures: count,
|
|
96
102
|
lastFailedToolKey: params.lastFailedToolKey || incomingKey || null,
|
|
97
|
-
reason: `[Burnoff DET-04 Consecutive Failure Breaker] ${count} consecutive identical tool failures detected${toolSuffix}.
|
|
103
|
+
reason: `[Burnoff DET-04 Consecutive Failure Breaker] ${count} consecutive identical tool failures detected${toolSuffix}. Confirm retry or re-verify assumptions before continuing.`
|
|
98
104
|
};
|
|
99
105
|
}
|
|
100
106
|
|
|
@@ -110,9 +116,13 @@ export function evaluateDet04ConsecutiveFailures(params = {}) {
|
|
|
110
116
|
|
|
111
117
|
/**
|
|
112
118
|
* Sanitizes a session ID for `burnoff_breaker_state_<sessionId>.json`.
|
|
119
|
+
* Rejects non-string values so objects never stringify into `_object_Object_`.
|
|
113
120
|
*/
|
|
114
121
|
export function sanitizeBreakerSessionId(sessionId = 'default') {
|
|
115
|
-
|
|
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';
|
|
116
126
|
}
|
|
117
127
|
|
|
118
128
|
/**
|
|
@@ -123,11 +133,15 @@ export function getBreakerStateFilePath(sessionId = 'default', options = {}) {
|
|
|
123
133
|
return path.resolve(String(options.breakerStatePath));
|
|
124
134
|
}
|
|
125
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
|
+
}
|
|
126
140
|
if (options?.cwd) {
|
|
127
141
|
return path.join(path.resolve(String(options.cwd)), '.claude', 'cache', `burnoff_breaker_state_${safeSid}.json`);
|
|
128
142
|
}
|
|
129
143
|
if (options?.useRuntimeDir) {
|
|
130
|
-
return path.join(getBurnoffRuntimeDir(options.homeDir ||
|
|
144
|
+
return path.join(getBurnoffRuntimeDir(options.homeDir || null), `burnoff_breaker_state_${safeSid}.json`);
|
|
131
145
|
}
|
|
132
146
|
return path.join(getEffectiveCwd(options), '.claude', 'cache', `burnoff_breaker_state_${safeSid}.json`);
|
|
133
147
|
}
|
|
@@ -295,6 +309,9 @@ export function matchesScopePattern(targetFilePath, scopePattern, cwd = '') {
|
|
|
295
309
|
|
|
296
310
|
export function getScopeLocksPath(options = {}) {
|
|
297
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
|
+
}
|
|
298
315
|
return path.join(getEffectiveCwd(options), '.claude', 'locks', 'active_scopes.json');
|
|
299
316
|
}
|
|
300
317
|
|
|
@@ -385,10 +402,17 @@ export function acquireScopeLock(params = {}, options = {}) {
|
|
|
385
402
|
}
|
|
386
403
|
}
|
|
387
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;
|
|
388
412
|
const nextRecord = {
|
|
389
413
|
ownerId,
|
|
390
|
-
scopes:
|
|
391
|
-
acquiredAt: nowMs,
|
|
414
|
+
scopes: mergedScopes,
|
|
415
|
+
acquiredAt: existingOwner?.acquiredAt || nowMs,
|
|
392
416
|
expiresAt: nowMs + ttlMs
|
|
393
417
|
};
|
|
394
418
|
const nextLocks = [
|
|
@@ -407,18 +431,56 @@ export function acquireScopeLock(params = {}, options = {}) {
|
|
|
407
431
|
);
|
|
408
432
|
return { acquired: true, lock: nextRecord, conflict: null };
|
|
409
433
|
},
|
|
410
|
-
|
|
434
|
+
{
|
|
435
|
+
...options,
|
|
436
|
+
fallbackValue: { ok: false, acquired: false, skippedByLockTimeout: true, conflict: null }
|
|
437
|
+
}
|
|
411
438
|
);
|
|
412
439
|
}
|
|
413
440
|
|
|
414
441
|
export function releaseScopeLock(ownerId, options = {}) {
|
|
415
442
|
const nowMs = options.nowMs ?? Date.now();
|
|
443
|
+
const cwd = getEffectiveCwd(options);
|
|
416
444
|
const filePath = getScopeLocksPath(options);
|
|
445
|
+
const targetOwner = String(ownerId || '').trim();
|
|
446
|
+
const targetScope = options.scope ? normalizeScopePath(options.scope, cwd) : '';
|
|
447
|
+
|
|
417
448
|
return withFileLockSync(
|
|
418
449
|
filePath,
|
|
419
450
|
() => {
|
|
420
451
|
const currentLocks = parseLocksFromRaw(readJsonSafe(filePath, { locks: [] }), nowMs);
|
|
421
|
-
|
|
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
|
+
|
|
422
484
|
atomicWriteJsonSync(
|
|
423
485
|
filePath,
|
|
424
486
|
{
|
|
@@ -431,7 +493,10 @@ export function releaseScopeLock(ownerId, options = {}) {
|
|
|
431
493
|
);
|
|
432
494
|
return { released: true, remainingLocks: nextLocks.length };
|
|
433
495
|
},
|
|
434
|
-
|
|
496
|
+
{
|
|
497
|
+
...options,
|
|
498
|
+
fallbackValue: { ok: false, released: false, skippedByLockTimeout: true, remainingLocks: 0 }
|
|
499
|
+
}
|
|
435
500
|
);
|
|
436
501
|
}
|
|
437
502
|
|
|
@@ -536,11 +601,131 @@ export function evaluateScopeAndQuotaBrake(params = {}, options = {}) {
|
|
|
536
601
|
};
|
|
537
602
|
}
|
|
538
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
|
+
|
|
539
718
|
export default {
|
|
540
719
|
DEFAULT_MAX_CONSECUTIVE_FAILURES,
|
|
541
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,
|
|
542
725
|
computeToolFailureKey,
|
|
543
726
|
evaluateDet04ConsecutiveFailures,
|
|
727
|
+
evaluateDet05SubagentFanout,
|
|
728
|
+
recordSubagentSpawnAtomicSync,
|
|
544
729
|
sanitizeBreakerSessionId,
|
|
545
730
|
getBreakerStateFilePath,
|
|
546
731
|
readBreakerStateSnapshot,
|