burnoff 1.4.1 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/.github/workflows/burnoff-pr-gate.yml +5 -3
  3. package/.github/workflows/burnoff-startup-lint.yml +2 -2
  4. package/CHANGELOG.md +74 -0
  5. package/README.md +187 -213
  6. package/SECURITY.md +38 -0
  7. package/bin/burnoff.mjs +307 -32
  8. package/commands/burnoff.md +6 -4
  9. package/docs/CLAUDE_CODE_PLUGIN.md +29 -28
  10. package/docs/DESIGN_PARTNER_INTAKE.md +3 -3
  11. package/hooks/hook-io.mjs +216 -11
  12. package/hooks/hooks.json +44 -0
  13. package/hooks/post-tool-use.mjs +3 -1
  14. package/hooks/pre-tool-use.mjs +47 -8
  15. package/hooks/session-lifecycle.mjs +24 -3
  16. package/hooks/user-prompt-submit.mjs +98 -0
  17. package/package.json +6 -4
  18. package/scripts/bench-hooks.mjs +34 -3
  19. package/scripts/bench-savings.mjs +318 -0
  20. package/scripts/burnoff-statusline.mjs +138 -6
  21. package/src/ci/ci-gate.mjs +199 -13
  22. package/src/ci/pr-cost.mjs +417 -45
  23. package/src/ci/pr-summary.mjs +467 -0
  24. package/src/cli/audit.mjs +179 -28
  25. package/src/cli/doctor.mjs +32 -6
  26. package/src/cli/hook-health.mjs +9 -1
  27. package/src/cli/init.mjs +226 -39
  28. package/src/cli/preview.mjs +299 -0
  29. package/src/cli/startup-audit/formatter.mjs +248 -0
  30. package/src/cli/startup-audit/jsonc.mjs +601 -0
  31. package/src/cli/startup-audit/mcp-audit.mjs +735 -0
  32. package/src/cli/startup-audit/rules-hygiene.mjs +645 -0
  33. package/src/cli/startup-audit/telemetry-scan.mjs +975 -0
  34. package/src/cli/startup-audit.mjs +451 -2471
  35. package/src/clients/claude-code.mjs +41 -4
  36. package/src/config/catalog.json +295 -0
  37. package/src/config/effort.mjs +145 -0
  38. package/src/config/harness-quirks.mjs +340 -0
  39. package/src/config/loader.mjs +27 -2
  40. package/src/config/policy.mjs +81 -9
  41. package/src/config/pricing.mjs +247 -19
  42. package/src/config/semver.mjs +25 -0
  43. package/src/config/uncached-attribution.mjs +280 -41
  44. package/src/guards/compaction-baton.mjs +248 -0
  45. package/src/guards/loop-breaker.mjs +328 -47
  46. package/src/guards/model-switch-hook.mjs +126 -0
  47. package/src/guards/phase5-detectors.mjs +275 -21
  48. package/src/guards/post-tool-engine.mjs +333 -11
  49. package/src/guards/pre-tool-engine.mjs +607 -45
  50. package/src/guards/prefix-guard.mjs +609 -0
  51. package/src/guards/prompt-guard.mjs +309 -0
  52. package/src/guards/read-clamp.mjs +192 -8
  53. package/src/guards/session-hook.mjs +149 -7
  54. package/src/guards/shell-guard.mjs +56 -5
  55. package/src/guards/snooze.mjs +169 -5
  56. package/src/ipc/daemon.mjs +76 -0
  57. package/src/ipc/fast-client.mjs +165 -4
  58. package/src/ipc/protocol.mjs +16 -3
  59. package/src/storage/antigravity-parser.mjs +16 -2
  60. package/src/storage/file-lock.mjs +16 -3
  61. package/src/storage/jsonl-parser.mjs +133 -22
  62. package/src/storage/telemetry-metrics.mjs +254 -4
@@ -10,9 +10,14 @@ import { withFileLockSync } from '../storage/file-lock.mjs';
10
10
  import { atomicWriteJsonSync, sleepSync } from '../storage/atomic-io.mjs';
11
11
  import { getBurnoffRuntimeDir, getHomeDir, getWorkspaceStateDir } from '../config/paths.mjs';
12
12
  import { isVerificationShellCommand, normalizeEditThrashPath } from './phase5-detectors.mjs';
13
+ import { isOpenAiModel } from './prefix-guard.mjs';
14
+ import { redactSecretsPure } from './credential-scrubber.mjs';
13
15
 
14
16
  export const DEFAULT_MAX_CONSECUTIVE_FAILURES = 3;
17
+ export const RECENT_COMMANDS_MAX = 8;
18
+ export const RECENT_COMMAND_MAX_CHARS = 140;
15
19
  export const DEFAULT_SCOPE_LOCK_TTL_MS = 15 * 60 * 1000;
20
+ export const DEFAULT_READ_SCOPE_TTL_MS = 120 * 1000;
16
21
  export const SUBAGENT_TOOL_REGEX = /^(?:Task|Agent|invoke_subagent)$/i;
17
22
  export const DEFAULT_SUBAGENT_MAX_BURST_COUNT = 4;
18
23
  export const DEFAULT_SUBAGENT_BURST_WINDOW_SEC = 60;
@@ -163,7 +168,7 @@ export function readBreakerStateSnapshot(sessionId = 'default', options = {}) {
163
168
 
164
169
  export function writeBreakerStateSnapshot(sessionId = 'default', snapshot = {}, options = {}) {
165
170
  const filePath = getBreakerStateFilePath(sessionId, options);
166
- atomicWriteJsonSync(filePath, snapshot, options);
171
+ atomicWriteJsonSync(filePath, snapshot, { skipFsync: true, ...options });
167
172
  return true;
168
173
  }
169
174
 
@@ -182,6 +187,7 @@ export function updateBreakerStateAtomicSync(sessionId = 'default', mutatorFn, o
182
187
  const next = mutatorFn(prior);
183
188
  if (next && typeof next === 'object') {
184
189
  atomicWriteJsonSync(filePath, next, {
190
+ skipFsync: true,
185
191
  ...options,
186
192
  maxRetries: Math.max(10, Number(options?.maxRetries || 10))
187
193
  });
@@ -193,7 +199,19 @@ export function updateBreakerStateAtomicSync(sessionId = 'default', mutatorFn, o
193
199
  }
194
200
 
195
201
  /**
196
- * Atomically records a completed tool outcome (`failed` true/false and optional `git stash` timestamp).
202
+ * Extracts a normalized top module directory (up to 2 relative path segments) for thread-rot tracking.
203
+ */
204
+ export function extractModuleDir(filePath = '', cwd = '') {
205
+ const norm = normalizeScopePath(filePath, cwd);
206
+ if (!norm) return '';
207
+ const parts = norm.split('/').filter(Boolean);
208
+ if (parts.length <= 1) return '.';
209
+ if (parts.length === 2) return parts[0];
210
+ return `${parts[0]}/${parts[1]}`;
211
+ }
212
+
213
+ /**
214
+ * Atomically records a completed tool outcome (`failed` true/false and optional `git stash` / `git commit` timestamp).
197
215
  */
198
216
  export function recordToolOutcomeAtomicSync(
199
217
  sessionId = 'default',
@@ -205,6 +223,11 @@ export function recordToolOutcomeAtomicSync(
205
223
  Boolean(command) &&
206
224
  /\bgit\s+stash\b/i.test(String(command)) &&
207
225
  !/\bgit\s+stash\s+(?:pop|drop|clear|apply|list|show)\b/i.test(String(command));
226
+ const isGitCommit =
227
+ !failed &&
228
+ Boolean(command) &&
229
+ /\bgit\s+commit\b/i.test(String(command)) &&
230
+ !/--dry-run\b/i.test(String(command));
208
231
  const toolKey = computeToolFailureKey({ toolName, command, filePath });
209
232
 
210
233
  return updateBreakerStateAtomicSync(
@@ -214,19 +237,56 @@ export function recordToolOutcomeAtomicSync(
214
237
  const prevFailures = Math.max(0, Number(base.consecutiveFailures || 0));
215
238
  const sameTool = !base.lastFailedToolKey || base.lastFailedToolKey === toolKey;
216
239
  const nextFailures = failed ? (sameTool ? prevFailures + 1 : 1) : 0;
240
+ const prevEditedModules = Array.isArray(base.editedModuleDirs)
241
+ ? base.editedModuleDirs.filter((m) => typeof m === 'string' && m.length > 0)
242
+ : [];
217
243
  const next = {
218
244
  ...base,
219
245
  schemaVersion: '1.0.0',
220
246
  sessionId: String(sessionId || 'default'),
221
247
  consecutiveFailures: nextFailures,
222
248
  lastFailedToolKey: failed ? toolKey : null,
249
+ lastTurnAtMs: nowMs,
223
250
  updatedAt: nowMs
224
251
  };
225
252
  if (isStashPush) {
226
253
  next.lastGitStashAtMs = nowMs;
227
254
  }
255
+ if (isGitCommit) {
256
+ next.lastGitCommitAtMs = nowMs;
257
+ next.preCommitModuleDirs = [...prevEditedModules];
258
+ next.det19WarnedCommitTs = null;
259
+ }
260
+
261
+ // BO-CMP-01: Maintain bounded ring buffer of recent scrubbed shell commands with pass/fail status.
262
+ const prevCommands = Array.isArray(base.recentCommands) ? [...base.recentCommands] : [];
263
+ if (typeof command === 'string' && command.trim().length > 0) {
264
+ const collapsedCmd = String(command).replace(/\s+/g, ' ').trim();
265
+ const scrubbedRaw = redactSecretsPure(collapsedCmd).sanitized;
266
+ const scrubbedCmd =
267
+ scrubbedRaw.length > RECENT_COMMAND_MAX_CHARS
268
+ ? `${scrubbedRaw.slice(0, RECENT_COMMAND_MAX_CHARS - 3)}...`
269
+ : scrubbedRaw;
270
+ if (scrubbedCmd) {
271
+ const nextStatus = failed ? 'failed' : 'passed';
272
+ const lastEntry = prevCommands[prevCommands.length - 1];
273
+ if (!lastEntry || lastEntry.status !== nextStatus || lastEntry.command !== scrubbedCmd) {
274
+ prevCommands.push({
275
+ status: nextStatus,
276
+ command: scrubbedCmd,
277
+ ts: nowMs
278
+ });
279
+ } else {
280
+ prevCommands[prevCommands.length - 1] = {
281
+ ...lastEntry,
282
+ ts: nowMs
283
+ };
284
+ }
285
+ next.recentCommands = prevCommands.slice(-RECENT_COMMANDS_MAX);
286
+ }
287
+ }
228
288
 
229
- // DET-09: Track successful same-file edits and reset on passing verification runs.
289
+ // DET-09 & DET-19: Track successful same-file edits and edited module directories.
230
290
  const prevThrash =
231
291
  base.editThrashHistory && typeof base.editThrashHistory === 'object'
232
292
  ? { ...base.editThrashHistory }
@@ -236,35 +296,43 @@ export function recordToolOutcomeAtomicSync(
236
296
  } else if (
237
297
  !failed &&
238
298
  EDIT_THRASH_TOOL_RE.test(String(toolName || '')) &&
239
- filePath &&
240
- !EXEMPT_MCP_CONFIG_BASENAME_RE.test(path.basename(String(filePath).trim()))
299
+ filePath
241
300
  ) {
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);
301
+ const modDir = extractModuleDir(filePath, options?.cwd || '');
302
+ if (modDir) {
303
+ const updatedModules = prevEditedModules.includes(modDir)
304
+ ? prevEditedModules
305
+ : [...prevEditedModules, modDir].slice(-32);
306
+ next.editedModuleDirs = updatedModules;
307
+ }
308
+ if (!EXEMPT_MCP_CONFIG_BASENAME_RE.test(path.basename(String(filePath).trim()))) {
309
+ const normKey = normalizeEditThrashPath(filePath, options?.cwd || '');
310
+ if (normKey) {
311
+ const cutoff = nowMs - EDIT_THRASH_STORAGE_TTL_MS;
312
+ const prunedHistory = {};
313
+ const keys = Object.keys(prevThrash).slice(-EDIT_THRASH_MAX_FILES);
314
+ for (const k of keys) {
315
+ const list = Array.isArray(prevThrash[k])
316
+ ? prevThrash[k]
317
+ .map((v) => Number(v))
318
+ .filter((v) => Number.isFinite(v) && v >= cutoff && v <= nowMs)
319
+ : [];
320
+ if (list.length > 0) {
321
+ prunedHistory[k] = list.slice(-EDIT_THRASH_MAX_TIMESTAMPS);
322
+ }
255
323
  }
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];
324
+ const currentList = prunedHistory[normKey] ? [...prunedHistory[normKey]] : [];
325
+ currentList.push(nowMs);
326
+ prunedHistory[normKey] = currentList.slice(-EDIT_THRASH_MAX_TIMESTAMPS);
327
+
328
+ const finalKeys = Object.keys(prunedHistory);
329
+ if (finalKeys.length > EDIT_THRASH_MAX_FILES) {
330
+ for (const dropKey of finalKeys.slice(0, finalKeys.length - EDIT_THRASH_MAX_FILES)) {
331
+ if (dropKey !== normKey) delete prunedHistory[dropKey];
332
+ }
265
333
  }
334
+ next.editThrashHistory = prunedHistory;
266
335
  }
267
- next.editThrashHistory = prunedHistory;
268
336
  }
269
337
  }
270
338
  return next;
@@ -408,14 +476,40 @@ function parseLocksFromRaw(raw, nowMs) {
408
476
  return locks;
409
477
  }
410
478
 
479
+ function parseReadScopesFromRaw(raw, nowMs) {
480
+ const out = {};
481
+ const src = raw?.readScopes && typeof raw.readScopes === 'object' ? raw.readScopes : {};
482
+ for (const [rawKey, entries] of Object.entries(src)) {
483
+ const key = String(rawKey || '').trim().toLowerCase();
484
+ if (!key || !Array.isArray(entries)) continue;
485
+ const valid = [];
486
+ const seenOwners = new Set();
487
+ for (const item of entries) {
488
+ if (!item || typeof item !== 'object') continue;
489
+ const ownerId = String(item.ownerId || '').trim();
490
+ if (!ownerId || seenOwners.has(ownerId)) continue;
491
+ const readAt = Number(item.readAt || 0);
492
+ const expiresAt = Number(item.expiresAt || 0);
493
+ if (expiresAt && expiresAt <= nowMs) continue;
494
+ seenOwners.add(ownerId);
495
+ valid.push({ ownerId, readAt, expiresAt });
496
+ }
497
+ if (valid.length > 0) {
498
+ out[key] = valid.slice(-16);
499
+ }
500
+ }
501
+ return out;
502
+ }
503
+
411
504
  export function readActiveScopeLocks(options = {}) {
412
505
  const nowMs = options.nowMs ?? Date.now();
413
506
  const filePath = getScopeLocksPath(options);
414
- const raw = readJsonSafe(filePath, { schemaVersion: '1.0.0', locks: [] });
507
+ const raw = readJsonSafe(filePath, { schemaVersion: '1.0.0', locks: [], readScopes: {} });
415
508
  return {
416
509
  version: 1,
417
510
  schemaVersion: '1.0.0',
418
- locks: parseLocksFromRaw(raw, nowMs)
511
+ locks: parseLocksFromRaw(raw, nowMs),
512
+ readScopes: parseReadScopesFromRaw(raw, nowMs)
419
513
  };
420
514
  }
421
515
 
@@ -432,7 +526,9 @@ export function acquireScopeLock(params = {}, options = {}) {
432
526
  return withFileLockSync(
433
527
  filePath,
434
528
  () => {
435
- const currentLocks = parseLocksFromRaw(readJsonSafe(filePath, { locks: [] }), nowMs);
529
+ const raw = readJsonSafe(filePath, { locks: [], readScopes: {} });
530
+ const currentLocks = parseLocksFromRaw(raw, nowMs);
531
+ const readScopes = parseReadScopesFromRaw(raw, nowMs);
436
532
  for (const existing of currentLocks) {
437
533
  if (existing.ownerId === ownerId) continue;
438
534
  for (const existingScope of existing.scopes) {
@@ -478,9 +574,10 @@ export function acquireScopeLock(params = {}, options = {}) {
478
574
  version: 1,
479
575
  schemaVersion: '1.0.0',
480
576
  updatedAt: nowMs,
481
- locks: nextLocks
577
+ locks: nextLocks,
578
+ ...(Object.keys(readScopes).length > 0 ? { readScopes } : {})
482
579
  },
483
- options
580
+ { skipFsync: true, ...options }
484
581
  );
485
582
  return { acquired: true, lock: nextRecord, conflict: null };
486
583
  },
@@ -501,7 +598,9 @@ export function releaseScopeLock(ownerId, options = {}) {
501
598
  return withFileLockSync(
502
599
  filePath,
503
600
  () => {
504
- const currentLocks = parseLocksFromRaw(readJsonSafe(filePath, { locks: [] }), nowMs);
601
+ const raw = readJsonSafe(filePath, { locks: [], readScopes: {} });
602
+ const currentLocks = parseLocksFromRaw(raw, nowMs);
603
+ const readScopes = parseReadScopesFromRaw(raw, nowMs);
505
604
  let nextLocks;
506
605
  if (targetScope) {
507
606
  nextLocks = [];
@@ -521,7 +620,7 @@ export function releaseScopeLock(ownerId, options = {}) {
521
620
  nextLocks = currentLocks.filter((l) => l.ownerId !== targetOwner);
522
621
  }
523
622
 
524
- if (nextLocks.length === 0) {
623
+ if (nextLocks.length === 0 && Object.keys(readScopes).length === 0) {
525
624
  if (fs.existsSync(filePath)) {
526
625
  try {
527
626
  fs.unlinkSync(filePath);
@@ -540,9 +639,10 @@ export function releaseScopeLock(ownerId, options = {}) {
540
639
  version: 1,
541
640
  schemaVersion: '1.0.0',
542
641
  updatedAt: nowMs,
543
- locks: nextLocks
642
+ locks: nextLocks,
643
+ ...(Object.keys(readScopes).length > 0 ? { readScopes } : {})
544
644
  },
545
- options
645
+ { skipFsync: true, ...options }
546
646
  );
547
647
  return { released: true, remainingLocks: nextLocks.length };
548
648
  },
@@ -643,6 +743,55 @@ export function evaluateScopeAndQuotaBrake(params = {}, options = {}) {
643
743
  }
644
744
  }
645
745
  }
746
+
747
+ if (isRead && params.isSubagent && options.persistReadScope !== false) {
748
+ const readKey = targetFilePath.toLowerCase();
749
+ const readScopeTtlMs = Math.max(1000, Number(params.readScopeTtlMs ?? options.readScopeTtlMs ?? DEFAULT_READ_SCOPE_TTL_MS));
750
+ const filePath = getScopeLocksPath(options);
751
+ const dupRead = withFileLockSync(
752
+ filePath,
753
+ () => {
754
+ const raw = readJsonSafe(filePath, { locks: [], readScopes: {} });
755
+ const locks = parseLocksFromRaw(raw, nowMs);
756
+ const readScopes = parseReadScopesFromRaw(raw, nowMs);
757
+ const existingReaders = Array.isArray(readScopes[readKey]) ? readScopes[readKey] : [];
758
+ const otherReader = existingReaders.find((entry) => entry.ownerId && entry.ownerId !== ownerId);
759
+ const updatedReaders = [
760
+ ...existingReaders.filter((entry) => entry.ownerId !== ownerId),
761
+ { ownerId, readAt: nowMs, expiresAt: nowMs + readScopeTtlMs }
762
+ ].slice(-16);
763
+ readScopes[readKey] = updatedReaders;
764
+ atomicWriteJsonSync(
765
+ filePath,
766
+ {
767
+ version: 1,
768
+ schemaVersion: '1.0.0',
769
+ updatedAt: nowMs,
770
+ locks,
771
+ readScopes
772
+ },
773
+ { skipFsync: true, ...options }
774
+ );
775
+ return otherReader || null;
776
+ },
777
+ { ...options, fallbackValue: null }
778
+ );
779
+ if (dupRead) {
780
+ return {
781
+ detectorId: 'DET-20',
782
+ triggered: true,
783
+ decision: 'allow',
784
+ advisory: true,
785
+ subType: 'DUPLICATE_COLD_READ',
786
+ conflictingOwner: dupRead.ownerId,
787
+ targetFilePath,
788
+ additionalContext:
789
+ `[Burnoff DET-20 Duplicate Subagent Read] "${targetFilePath}" was already read in this wave by worker "${dupRead.ownerId}". ` +
790
+ `Share a compact parent digest/summary instead of repeating cold reads across multiple subagents.`,
791
+ reason: `[Burnoff DET-20 Duplicate Subagent Read] "${targetFilePath}" was already read in this wave by worker "${dupRead.ownerId}".`
792
+ };
793
+ }
794
+ }
646
795
  }
647
796
 
648
797
  return {
@@ -654,9 +803,62 @@ export function evaluateScopeAndQuotaBrake(params = {}, options = {}) {
654
803
  };
655
804
  }
656
805
 
806
+ function hasFrontVolatileEnvelope(rawText = '') {
807
+ const head = String(rawText || '').trim().slice(0, 120);
808
+ if (!head) return false;
809
+ if (/\b20\d{2}-\d{2}-\d{2}[T\s]\d{2}:\d{2}/.test(head)) return true;
810
+ if (/\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/i.test(head)) return true;
811
+ if (/\b1[6-9]\d{8,11}\b/.test(head)) return true;
812
+ if (/(?:^|\s)(?:task|worker|job|run|request)[-_#:= ]+[a-z0-9_-]{2,}/i.test(head)) return true;
813
+ if (/^[\s`"'(]*(?:[\w.-]+\/)+[\w.-]+\.[a-z0-9]{1,8}\b/i.test(head)) return true;
814
+ return false;
815
+ }
816
+
817
+ function longestCommonPrefixLen(a = '', b = '') {
818
+ const len = Math.min(a.length, b.length);
819
+ let i = 0;
820
+ while (i < len && a.charCodeAt(i) === b.charCodeAt(i)) {
821
+ i += 1;
822
+ }
823
+ return i;
824
+ }
825
+
826
+ function hashNormalizedPrompt(str = '') {
827
+ let h1 = 2166136261;
828
+ let h2 = 0x811c9dc5;
829
+ for (let i = 0; i < str.length; i += 1) {
830
+ const code = str.charCodeAt(i);
831
+ h1 ^= code;
832
+ h1 = Math.imul(h1, 16777619);
833
+ h2 ^= (code + i) & 0xffff;
834
+ h2 = Math.imul(h2, 2654435761);
835
+ }
836
+ return `${(h1 >>> 0).toString(16)}-${(h2 >>> 0).toString(16)}`;
837
+ }
838
+
839
+ function extractPromptScopeSignals(promptText = '') {
840
+ const raw = String(promptText || '');
841
+ const normalized = raw.trim().toLowerCase().replace(/\s+/g, ' ');
842
+ // Hash full normalized prompt so sibling subagents sharing a >=120-char static prefix keep distinct tails.
843
+ const promptSig = normalized ? `${normalized.length}:${hashNormalizedPrompt(normalized)}` : '';
844
+ const promptHead = normalized.slice(0, 240);
845
+ const hasFrontVolatile = hasFrontVolatileEnvelope(raw);
846
+ const paths = [];
847
+ const seen = new Set();
848
+ for (const m of raw.matchAll(/(?:^|[\s`"'(])((?:[\w.-]+\/)+[\w.-]+(?:\.[a-z0-9]{1,8})?)/gi)) {
849
+ const p = String(m[1] || '').trim().replace(/\\/g, '/').toLowerCase();
850
+ if (p && !seen.has(p)) {
851
+ seen.add(p);
852
+ paths.push(p);
853
+ if (paths.length >= 16) break;
854
+ }
855
+ }
856
+ return { promptSig, promptHead, hasFrontVolatile, targetPaths: paths };
857
+ }
858
+
657
859
  /**
658
860
  * 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.
861
+ * Flags rapid parallel subagent bursts, duplicate/unscoped swarm waves, divergent sibling prefixes, or oversized child prompts.
660
862
  */
661
863
  export function evaluateDet05SubagentFanout(params = {}) {
662
864
  const toolName = String(params.toolName || '');
@@ -674,7 +876,10 @@ export function evaluateDet05SubagentFanout(params = {}) {
674
876
  }
675
877
 
676
878
  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));
879
+ const baseMaxBurstCount = Math.max(1, Number(params.maxBurstCount ?? DEFAULT_SUBAGENT_MAX_BURST_COUNT));
880
+ const openAiActive = isOpenAiModel(params.model);
881
+ const openaiMaxBurstCount = Math.max(1, Number(params.openaiMaxBurstCount ?? 2));
882
+ const maxBurstCount = openAiActive ? Math.min(baseMaxBurstCount, openaiMaxBurstCount) : baseMaxBurstCount;
678
883
  const burstWindowSec = Math.max(1, Number(params.burstWindowSec ?? DEFAULT_SUBAGENT_BURST_WINDOW_SEC));
679
884
  const maxPromptChars = Math.max(256, Number(params.maxPromptChars ?? DEFAULT_SUBAGENT_MAX_PROMPT_CHARS));
680
885
  const windowStartMs = nowMs - burstWindowSec * 1000;
@@ -683,13 +888,50 @@ export function evaluateDet05SubagentFanout(params = {}) {
683
888
  const pruned = recentRaw
684
889
  .map((ts) => Number(ts))
685
890
  .filter((ts) => Number.isFinite(ts) && ts >= windowStartMs && ts <= nowMs);
686
- const burstCount = pruned.length + 1;
891
+ const recentSpawns = (Array.isArray(params.recentSpawns) ? params.recentSpawns : [])
892
+ .filter((s) => s && Number.isFinite(Number(s.ts)) && Number(s.ts) >= windowStartMs && Number(s.ts) <= nowMs);
893
+
894
+ const burstCount = Math.max(pruned.length, recentSpawns.length) + 1;
687
895
  const promptChars = String(params.promptText || '').length;
896
+ const currentSignals = extractPromptScopeSignals(params.promptText || '');
897
+ const subagentType = String(params.subagentType || params.subagent_type || '').trim().toLowerCase();
898
+
899
+ const matchingPromptCount = currentSignals.promptSig
900
+ ? recentSpawns.filter((s) => s.promptSig === currentSignals.promptSig).length + 1
901
+ : 0;
902
+ const overlappingPath = currentSignals.targetPaths.length > 0 && recentSpawns.some((s) =>
903
+ Array.isArray(s.targetPaths) && s.targetPaths.some((p) => currentSignals.targetPaths.includes(p))
904
+ );
905
+ const redundantScope = matchingPromptCount >= 2 || overlappingPath;
906
+ const unscopedGeneralCount = subagentType === 'general-purpose'
907
+ ? recentSpawns.filter((s) => s.subagentType === 'general-purpose').length + 1
908
+ : 0;
909
+ const unscopedGeneral = unscopedGeneralCount >= maxBurstCount;
910
+
911
+ const prefixCheckEnabled = params.prefixCheckEnabled !== false;
912
+ const minSharedPrefixChars = Math.max(16, Number(params.minSharedPrefixChars ?? 64));
913
+ const siblingSpawns = recentSpawns.filter((s) => String(s.subagentType || '') === subagentType);
914
+ const divergentSiblingPrefix = Boolean(
915
+ prefixCheckEnabled &&
916
+ siblingSpawns.length >= 1 &&
917
+ (currentSignals.hasFrontVolatile ||
918
+ siblingSpawns.some((s) => {
919
+ const sibLen = Number(s.promptLen ?? String(s.promptHead || '').length);
920
+ return (
921
+ s.promptHead &&
922
+ currentSignals.promptHead &&
923
+ sibLen >= 200 &&
924
+ promptChars >= 200 &&
925
+ s.promptSig !== currentSignals.promptSig &&
926
+ longestCommonPrefixLen(currentSignals.promptHead, s.promptHead) < minSharedPrefixChars
927
+ );
928
+ }))
929
+ );
688
930
 
689
931
  const burstExceeded = burstCount > maxBurstCount;
690
932
  const promptExceeded = promptChars > maxPromptChars;
691
933
 
692
- if (!burstExceeded && !promptExceeded) {
934
+ if (!burstExceeded && !promptExceeded && !redundantScope && !unscopedGeneral && !divergentSiblingPrefix) {
693
935
  return {
694
936
  detectorId: 'DET-05',
695
937
  triggered: false,
@@ -707,21 +949,41 @@ export function evaluateDet05SubagentFanout(params = {}) {
707
949
  ? 'BOTH'
708
950
  : burstExceeded
709
951
  ? 'BURST_FANOUT'
710
- : 'OVERSIZED_PROMPT';
952
+ : promptExceeded
953
+ ? 'OVERSIZED_PROMPT'
954
+ : redundantScope
955
+ ? 'REDUNDANT_SWARM_SCOPE'
956
+ : divergentSiblingPrefix
957
+ ? 'DIVERGENT_SIBLING_PREFIX'
958
+ : 'UNSCOPED_GENERAL_SWARM';
711
959
  const action = String(params.action || 'advisory').trim().toLowerCase();
712
960
  const decision = action === 'deny' ? 'deny' : 'allow';
713
961
 
714
962
  const parts = [];
715
963
  if (burstExceeded) {
716
- parts.push(`burst spawn ${burstCount} > ${maxBurstCount} within ${burstWindowSec}s`);
964
+ const providerNote = openAiActive
965
+ ? ` (OpenAI TPM limit counts cached input tokens 100%; tight cap ${maxBurstCount})`
966
+ : '';
967
+ parts.push(`burst spawn ${burstCount} > ${maxBurstCount} within ${burstWindowSec}s${providerNote}`);
717
968
  }
718
969
  if (promptExceeded) {
719
970
  const estTok = Math.ceil(promptChars / 4);
720
971
  parts.push(`child prompt ${promptChars.toLocaleString('en-US')} chars (~${estTok.toLocaleString('en-US')} est. tok) > ${maxPromptChars.toLocaleString('en-US')} chars`);
721
972
  }
973
+ if (redundantScope) {
974
+ parts.push('duplicate or overlapping subagent scope in active burst window');
975
+ }
976
+ if (divergentSiblingPrefix) {
977
+ parts.push('sibling subagent prompts diverge at token index 0 (front-loaded volatile ID/timestamp/path)');
978
+ }
979
+ if (unscopedGeneral) {
980
+ parts.push(`${unscopedGeneralCount} concurrent general-purpose subagents without narrow disjoint file slices`);
981
+ }
982
+ const suffix = divergentSiblingPrefix && !burstExceeded && !promptExceeded && !redundantScope
983
+ ? 'Keep invariant shared instructions/context at token index 0 and append per-worker slice/path/ID at the tail to share KV prefix cache.'
984
+ : 'Assign disjoint file slices, share a compact parent digest, or use a specialized read-only worker instead of overlapping general-purpose spawns.';
722
985
  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.`;
986
+ `[Burnoff DET-05 Subagent Fan-Out Guard] ${parts.join(' and ')} on ${toolName}. ${suffix}`;
725
987
 
726
988
  return {
727
989
  detectorId: 'DET-05',
@@ -736,16 +998,19 @@ export function evaluateDet05SubagentFanout(params = {}) {
736
998
  }
737
999
 
738
1000
  /**
739
- * Atomically records a subagent spawn timestamp within the active burst window.
1001
+ * Atomically records a subagent spawn timestamp and scope metadata within the active burst window.
740
1002
  */
741
1003
  export function recordSubagentSpawnAtomicSync(
742
1004
  sessionId = 'default',
743
- { nowMs = Date.now(), burstWindowSec = DEFAULT_SUBAGENT_BURST_WINDOW_SEC } = {},
1005
+ { nowMs = Date.now(), burstWindowSec = DEFAULT_SUBAGENT_BURST_WINDOW_SEC, promptText = '', subagentType = '' } = {},
744
1006
  options = {}
745
1007
  ) {
746
1008
  const ts = Number.isFinite(Number(nowMs)) ? Number(nowMs) : Date.now();
747
1009
  const winMs = Math.max(1, Number(burstWindowSec || DEFAULT_SUBAGENT_BURST_WINDOW_SEC)) * 1000;
748
1010
  const cutoff = ts - winMs;
1011
+ const signals = extractPromptScopeSignals(promptText);
1012
+ const promptLen = String(promptText || '').length;
1013
+ const normSubagentType = String(subagentType || '').trim().toLowerCase();
749
1014
  return updateBreakerStateAtomicSync(
750
1015
  sessionId,
751
1016
  (prior) => {
@@ -756,11 +1021,25 @@ export function recordSubagentSpawnAtomicSync(
756
1021
  .filter((v) => Number.isFinite(v) && v >= cutoff && v <= ts)
757
1022
  : [];
758
1023
  existing.push(ts);
1024
+ const existingSpawns = Array.isArray(base.recentSpawns)
1025
+ ? base.recentSpawns.filter(
1026
+ (s) => s && Number.isFinite(Number(s.ts)) && Number(s.ts) >= cutoff && Number(s.ts) <= ts
1027
+ )
1028
+ : [];
1029
+ existingSpawns.push({
1030
+ ts,
1031
+ promptSig: signals.promptSig,
1032
+ promptHead: signals.promptHead,
1033
+ promptLen,
1034
+ targetPaths: signals.targetPaths,
1035
+ subagentType: normSubagentType
1036
+ });
759
1037
  return {
760
1038
  ...base,
761
1039
  schemaVersion: '1.0.0',
762
1040
  sessionId: String(sessionId || 'default'),
763
1041
  subagentSpawnTimestampsMs: existing.slice(-32),
1042
+ recentSpawns: existingSpawns.slice(-32),
764
1043
  updatedAt: ts
765
1044
  };
766
1045
  },
@@ -771,11 +1050,13 @@ export function recordSubagentSpawnAtomicSync(
771
1050
  export default {
772
1051
  DEFAULT_MAX_CONSECUTIVE_FAILURES,
773
1052
  DEFAULT_SCOPE_LOCK_TTL_MS,
1053
+ DEFAULT_READ_SCOPE_TTL_MS,
774
1054
  SUBAGENT_TOOL_REGEX,
775
1055
  DEFAULT_SUBAGENT_MAX_BURST_COUNT,
776
1056
  DEFAULT_SUBAGENT_BURST_WINDOW_SEC,
777
1057
  DEFAULT_SUBAGENT_MAX_PROMPT_CHARS,
778
1058
  computeToolFailureKey,
1059
+ extractModuleDir,
779
1060
  evaluateDet04ConsecutiveFailures,
780
1061
  evaluateDet05SubagentFanout,
781
1062
  recordSubagentSpawnAtomicSync,