burnoff 1.0.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.
Files changed (41) hide show
  1. package/.github/workflows/burnoff-pr-gate.yml +75 -0
  2. package/README.md +94 -20
  3. package/bin/burnoff.mjs +129 -30
  4. package/hooks/hook-io.mjs +27 -18
  5. package/hooks/post-tool-use.mjs +33 -26
  6. package/hooks/pre-tool-use.mjs +43 -41
  7. package/hooks/session-lifecycle.mjs +40 -0
  8. package/package.json +8 -5
  9. package/src/ci/ci-gate.mjs +84 -9
  10. package/src/ci/pr-cost.mjs +207 -22
  11. package/src/ci/team-digest.mjs +6 -4
  12. package/src/cli/audit.mjs +177 -23
  13. package/src/cli/doctor.mjs +230 -25
  14. package/src/cli/init.mjs +415 -75
  15. package/src/cli/startup-audit.mjs +2824 -0
  16. package/src/clients/antigravity.mjs +285 -0
  17. package/src/clients/claude-code.mjs +180 -0
  18. package/src/clients/detect.mjs +64 -0
  19. package/src/config/catalog.json +188 -45
  20. package/src/config/loader.mjs +96 -13
  21. package/src/config/paths.mjs +92 -2
  22. package/src/config/policy.mjs +103 -17
  23. package/src/config/pricing.mjs +1033 -0
  24. package/src/config/uncached-attribution.mjs +719 -0
  25. package/src/guards/loop-breaker.mjs +267 -24
  26. package/src/guards/post-tool-engine.mjs +316 -35
  27. package/src/guards/pre-tool-engine.mjs +389 -130
  28. package/src/guards/read-clamp.mjs +149 -75
  29. package/src/guards/session-hook.mjs +207 -0
  30. package/src/guards/shell-guard.mjs +610 -74
  31. package/src/ipc/daemon.mjs +50 -8
  32. package/src/ipc/fast-client.mjs +62 -5
  33. package/src/ipc/protocol.mjs +1 -1
  34. package/src/storage/antigravity-parser.mjs +258 -0
  35. package/src/storage/atomic-io.mjs +2 -2
  36. package/src/storage/file-lock.mjs +66 -13
  37. package/src/storage/fts5-archive.mjs +31 -16
  38. package/src/storage/jsonl-parser.mjs +209 -20
  39. package/src/storage/ledger.mjs +15 -10
  40. package/src/storage/sqlite-client.mjs +35 -11
  41. package/hooks/hooks.json +0 -12
@@ -7,42 +7,100 @@
7
7
  import fs from 'node:fs';
8
8
  import path from 'node:path';
9
9
  import { withFileLockSync } from '../storage/file-lock.mjs';
10
- import { atomicWriteJsonSync } from '../storage/atomic-io.mjs';
11
- import { getBurnoffRuntimeDir, getHomeDir } from '../config/paths.mjs';
10
+ import { atomicWriteJsonSync, sleepSync } from '../storage/atomic-io.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;
19
+ const DET04_EXEMPT_READ_TOOLS = /^(?:Read|Grep|Glob)$/i;
15
20
 
16
21
  function readJsonSafe(filePath, fallback = null) {
17
- try {
18
- if (!filePath || !fs.existsSync(filePath)) return fallback;
19
- return JSON.parse(fs.readFileSync(filePath, 'utf8'));
20
- } catch (err) {
21
- void err; // ignore: unreadable or corrupt state JSON falls back safely
22
- return fallback;
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
+ }
23
37
  }
38
+ return fallback;
24
39
  }
25
40
 
26
41
  function getEffectiveCwd(options = {}) {
27
42
  return options?.cwd ? path.resolve(String(options.cwd)) : process.cwd();
28
43
  }
29
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
+
30
59
  /**
31
- * DET-04: Consecutive Tool Failure Breaker (`>= maxConsecutiveFailures` -> block next attempt).
60
+ * DET-04: Consecutive Tool Failure Breaker (`>= maxConsecutiveFailures` -> gate next attempt).
32
61
  */
33
62
  export function evaluateDet04ConsecutiveFailures(params = {}) {
34
- const count = Math.max(0, Number(params.consecutiveFailures || 0));
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;
35
91
  const threshold = Math.max(1, Number(params.maxConsecutiveFailures ?? params.threshold ?? DEFAULT_MAX_CONSECUTIVE_FAILURES));
36
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';
37
95
 
38
96
  if (count >= threshold) {
39
97
  return {
40
98
  detectorId: 'DET-04',
41
99
  triggered: true,
42
- decision: 'deny',
100
+ decision: isStrictAutoMode ? 'deny' : 'ask',
43
101
  consecutiveFailures: count,
44
- lastFailedToolKey: params.lastFailedToolKey || null,
45
- reason: `[Burnoff DET-04 Consecutive Failure Breaker] ${count} consecutive tool failures detected${toolSuffix}. Halting next attempt to prevent retry churn; re-verify assumptions before retrying.`
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.`
46
104
  };
47
105
  }
48
106
 
@@ -58,9 +116,13 @@ export function evaluateDet04ConsecutiveFailures(params = {}) {
58
116
 
59
117
  /**
60
118
  * Sanitizes a session ID for `burnoff_breaker_state_<sessionId>.json`.
119
+ * Rejects non-string values so objects never stringify into `_object_Object_`.
61
120
  */
62
121
  export function sanitizeBreakerSessionId(sessionId = 'default') {
63
- return String(sessionId || 'default').replace(/[^a-zA-Z0-9._-]/g, '_').slice(0, 80) || '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';
64
126
  }
65
127
 
66
128
  /**
@@ -71,11 +133,15 @@ export function getBreakerStateFilePath(sessionId = 'default', options = {}) {
71
133
  return path.resolve(String(options.breakerStatePath));
72
134
  }
73
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
+ }
74
140
  if (options?.cwd) {
75
141
  return path.join(path.resolve(String(options.cwd)), '.claude', 'cache', `burnoff_breaker_state_${safeSid}.json`);
76
142
  }
77
143
  if (options?.useRuntimeDir) {
78
- return path.join(getBurnoffRuntimeDir(options.homeDir || getHomeDir()), `burnoff_breaker_state_${safeSid}.json`);
144
+ return path.join(getBurnoffRuntimeDir(options.homeDir || null), `burnoff_breaker_state_${safeSid}.json`);
79
145
  }
80
146
  return path.join(getEffectiveCwd(options), '.claude', 'cache', `burnoff_breaker_state_${safeSid}.json`);
81
147
  }
@@ -104,7 +170,10 @@ export function updateBreakerStateAtomicSync(sessionId = 'default', mutatorFn, o
104
170
  const prior = readJsonSafe(filePath, null);
105
171
  const next = mutatorFn(prior);
106
172
  if (next && typeof next === 'object') {
107
- atomicWriteJsonSync(filePath, next, options);
173
+ atomicWriteJsonSync(filePath, next, {
174
+ ...options,
175
+ maxRetries: Math.max(10, Number(options?.maxRetries || 10))
176
+ });
108
177
  }
109
178
  return next;
110
179
  },
@@ -117,7 +186,7 @@ export function updateBreakerStateAtomicSync(sessionId = 'default', mutatorFn, o
117
186
  */
118
187
  export function recordToolOutcomeAtomicSync(
119
188
  sessionId = 'default',
120
- { toolName = '', command = '', failed = false, nowMs = Date.now() } = {},
189
+ { toolName = '', command = '', filePath = '', failed = false, nowMs = Date.now() } = {},
121
190
  options = {}
122
191
  ) {
123
192
  const isStashPush =
@@ -125,19 +194,21 @@ export function recordToolOutcomeAtomicSync(
125
194
  Boolean(command) &&
126
195
  /\bgit\s+stash\b/i.test(String(command)) &&
127
196
  !/\bgit\s+stash\s+(?:pop|drop|clear|apply|list|show)\b/i.test(String(command));
197
+ const toolKey = computeToolFailureKey({ toolName, command, filePath });
128
198
 
129
199
  return updateBreakerStateAtomicSync(
130
200
  sessionId,
131
201
  (prior) => {
132
202
  const base = prior && typeof prior === 'object' ? { ...prior } : {};
133
203
  const prevFailures = Math.max(0, Number(base.consecutiveFailures || 0));
134
- const nextFailures = failed ? prevFailures + 1 : 0;
204
+ const sameTool = !base.lastFailedToolKey || base.lastFailedToolKey === toolKey;
205
+ const nextFailures = failed ? (sameTool ? prevFailures + 1 : 1) : 0;
135
206
  const next = {
136
207
  ...base,
137
208
  schemaVersion: '1.0.0',
138
209
  sessionId: String(sessionId || 'default'),
139
210
  consecutiveFailures: nextFailures,
140
- lastFailedToolKey: failed ? (String(toolName || base.lastFailedToolKey || 'unknown')) : null,
211
+ lastFailedToolKey: failed ? toolKey : null,
141
212
  updatedAt: nowMs
142
213
  };
143
214
  if (isStashPush) {
@@ -238,6 +309,9 @@ export function matchesScopePattern(targetFilePath, scopePattern, cwd = '') {
238
309
 
239
310
  export function getScopeLocksPath(options = {}) {
240
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
+ }
241
315
  return path.join(getEffectiveCwd(options), '.claude', 'locks', 'active_scopes.json');
242
316
  }
243
317
 
@@ -328,10 +402,17 @@ export function acquireScopeLock(params = {}, options = {}) {
328
402
  }
329
403
  }
330
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;
331
412
  const nextRecord = {
332
413
  ownerId,
333
- scopes: requestedScopes,
334
- acquiredAt: nowMs,
414
+ scopes: mergedScopes,
415
+ acquiredAt: existingOwner?.acquiredAt || nowMs,
335
416
  expiresAt: nowMs + ttlMs
336
417
  };
337
418
  const nextLocks = [
@@ -350,18 +431,56 @@ export function acquireScopeLock(params = {}, options = {}) {
350
431
  );
351
432
  return { acquired: true, lock: nextRecord, conflict: null };
352
433
  },
353
- options
434
+ {
435
+ ...options,
436
+ fallbackValue: { ok: false, acquired: false, skippedByLockTimeout: true, conflict: null }
437
+ }
354
438
  );
355
439
  }
356
440
 
357
441
  export function releaseScopeLock(ownerId, options = {}) {
358
442
  const nowMs = options.nowMs ?? Date.now();
443
+ const cwd = getEffectiveCwd(options);
359
444
  const filePath = getScopeLocksPath(options);
445
+ const targetOwner = String(ownerId || '').trim();
446
+ const targetScope = options.scope ? normalizeScopePath(options.scope, cwd) : '';
447
+
360
448
  return withFileLockSync(
361
449
  filePath,
362
450
  () => {
363
451
  const currentLocks = parseLocksFromRaw(readJsonSafe(filePath, { locks: [] }), nowMs);
364
- const nextLocks = currentLocks.filter((l) => l.ownerId !== ownerId);
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
+
365
484
  atomicWriteJsonSync(
366
485
  filePath,
367
486
  {
@@ -374,7 +493,10 @@ export function releaseScopeLock(ownerId, options = {}) {
374
493
  );
375
494
  return { released: true, remainingLocks: nextLocks.length };
376
495
  },
377
- options
496
+ {
497
+ ...options,
498
+ fallbackValue: { ok: false, released: false, skippedByLockTimeout: true, remainingLocks: 0 }
499
+ }
378
500
  );
379
501
  }
380
502
 
@@ -479,10 +601,131 @@ export function evaluateScopeAndQuotaBrake(params = {}, options = {}) {
479
601
  };
480
602
  }
481
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
+
482
718
  export default {
483
719
  DEFAULT_MAX_CONSECUTIVE_FAILURES,
484
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,
485
726
  evaluateDet04ConsecutiveFailures,
727
+ evaluateDet05SubagentFanout,
728
+ recordSubagentSpawnAtomicSync,
486
729
  sanitizeBreakerSessionId,
487
730
  getBreakerStateFilePath,
488
731
  readBreakerStateSnapshot,