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
@@ -1,22 +1,21 @@
1
1
  # Burnoff Claude Code Plugin & Status Line
2
2
 
3
- Burnoff ships a lightweight Claude Code plugin manifest (`.claude-plugin/plugin.json`), the `/burnoff` slash command (`commands/burnoff.md`), and a zero-dependency status-line snippet (`scripts/burnoff-statusline.mjs`).
3
+ Burnoff ships a lightweight Claude Code plugin manifest (`.claude-plugin/plugin.json`), the `/burnoff` slash command (`commands/burnoff.md`), and a zero-dependency fail-silent status-line renderer (`scripts/burnoff-statusline.mjs`).
4
4
 
5
- ## 1. Install Deterministic Hooks
5
+ ## 1. Install Deterministic Hooks & Status Line
6
6
 
7
7
  Run the CLI installer in your repository (or pass `--global` for user-wide defaults):
8
8
 
9
9
  ```bash
10
- npx -y burnoff@1.4.1 init --client claude
10
+ npx burnoff init --client claude
11
11
  ```
12
12
 
13
- Why hooks are installed via `burnoff init` instead of a static hook file:
13
+ Pass `--no-statusline` if you prefer to keep your terminal footer untouched. When no custom `"statusLine"` already exists in `.claude/settings.local.json` (or `~/.claude/settings.json` for `--global`), `burnoff init` auto-wires `scripts/burnoff-statusline.mjs` alongside `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `SessionStart`, `PreCompact`, `PreModelSwitch`, `PostModelSwitch`, and `UserPromptSubmit`. Existing custom user `statusLine` entries are never overwritten or deleted on `uninstall`.
14
14
 
15
- - `burnoff init` resolves node paths cleanly across Windows, macOS, and Linux and configures `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `SessionStart`, and `PreCompact`.
16
- - Verify installation anytime with:
15
+ Verify installation anytime with:
17
16
 
18
17
  ```bash
19
- npx -y burnoff@1.4.1 doctor
18
+ npx burnoff doctor
20
19
  ```
21
20
 
22
21
  ## 2. Enable `/burnoff` Slash Command
@@ -31,37 +30,39 @@ Or copy `commands/burnoff.md` into your project's `.claude/commands/` folder so
31
30
 
32
31
  - `/burnoff` — run `doctor` + `team-digest --days 7`
33
32
  - `/burnoff startup` — run Turn-0 repo-local linter (`audit --startup --ci`)
33
+ - `/burnoff pause 15m` — soft-pause ask gates & read clamps for 15 minutes (Ring-0 denies stay active)
34
+ - `/burnoff bypass --grant deploy.log` — grant a 1-use `DET-07` override
34
35
  - `/burnoff allow-once DET-03 --scope deploy.yml` — grant a single-use `ask` override
35
36
  - `/burnoff pr-cost` — inspect branch spend attribution
36
37
 
37
- ## 3. Add Status-Line Telemetry Snippet
38
+ ## 3. Status-Line Telemetry Output
38
39
 
39
- Add a `"statusLine"` entry to `.claude/settings.local.json` or `~/.claude/settings.json`:
40
-
41
- ```json
42
- {
43
- "statusLine": {
44
- "type": "command",
45
- "command": "node /abs/path/to/burnoff/scripts/burnoff-statusline.mjs"
46
- }
47
- }
48
- ```
49
-
50
- Example terminal output (`<50 ms`, zero network calls, fail-silent):
40
+ `scripts/burnoff-statusline.mjs` renders in `<50 ms` locally with zero network calls and fail-silent stdin parsing:
51
41
 
52
42
  ```text
53
- burnoff | saved: 14.2k tok ($0.04) | guards: 2 | ctx: 38%
43
+ burnoff | 7d saved: 14.2k tok | guards: 2 | ctx: 38%
54
44
  ```
55
45
 
56
- ## 4. Temporary Overrides for `ask` Prompts
46
+ - Sub-`$0.10` estimated savings suppress the `($0.XX)` badge to reduce noise; once `7d saved >= $0.10`, the formatted USD amount renders automatically: `7d saved: 34.2k tok ($0.14)`.
47
+ - When `burnoff pause <duration>` is active, a live countdown badge renders at the end: `| PAUSED 15m`.
48
+ - Optional live telemetry segments appear automatically when supplied by the host or local breaker snapshot: `ctx:`, `hit:`, `clamp:`, `cliff:`, `sess:`, `ttft:`, `tok/s`, `ttl:`, `mcp: idle`, `tpm:`, `hint: /clear`, and `think:`.
57
49
 
58
- When interactive `ask` gates pause an intentional edit or command (`DET-01`, `DET-02`, `DET-03`, or `DET-04`), grant a scoped single-use or timed snooze from your terminal:
50
+ ## 4. Temporary Overrides, Pause & Bypass
51
+
52
+ Pause non-blocking Friction gates (`ask` prompts and `DET-06` read clamps) across your workspace, grant a scoped bypass, or issue a targeted `DET-*` override:
59
53
 
60
54
  ```bash
61
- npx -y burnoff@1.4.1 allow-once DET-03 --scope deploy.yml
62
- npx -y burnoff@1.4.1 snooze DET-04 --minutes 15
63
- npx -y burnoff@1.4.1 allow-once --list
64
- npx -y burnoff@1.4.1 allow-once --clear
55
+ npx burnoff pause 15m
56
+ npx burnoff pause status
57
+ npx burnoff pause off
58
+
59
+ npx burnoff bypass --grant huge.log
60
+ npx burnoff bypass -- npm test
61
+
62
+ npx burnoff allow-once DET-03 --scope deploy.yml
63
+ npx burnoff snooze DET-04 --minutes 15
64
+ npx burnoff allow-once --list
65
+ npx burnoff allow-once --clear
65
66
  ```
66
67
 
67
- Security invariant: `allow-once` and `snooze` apply **only** to `ask` decisions. Ring-0 `deny` / `exitCode: 2` hard blocks (`git push --force`, `.env`/credential reads, strict-mode blocks) are never bypassed.
68
+ Security invariant: `pause`, `bypass`, `allow-once`, and `snooze` never weaken Ring-0 `deny` / `exitCode: 2` hard blocks (`git push --force`, `--no-verify`, `rm -rf`, `.env`/credential reads, or `strict`-mode blocks).
@@ -30,9 +30,9 @@ Burnoff (`MIT`, zero runtime dependencies, 100% local execution) is onboarding a
30
30
  Run inside a representative repo and paste sanitized summary lines only:
31
31
 
32
32
  ```bash
33
- npx -y burnoff@1.4.1 doctor
34
- npx -y burnoff@1.4.1 audit --startup --ci
35
- npx -y burnoff@1.4.1 team-digest --days 7
33
+ npx -y burnoff@2.1.0 doctor
34
+ npx -y burnoff@2.1.0 audit --startup --ci
35
+ npx -y burnoff@2.1.0 team-digest --days 7
36
36
  ```
37
37
 
38
38
  ### 4. Security & Privacy Requirements
package/hooks/hook-io.mjs CHANGED
@@ -8,6 +8,8 @@ import fs from 'node:fs';
8
8
  import path from 'node:path';
9
9
  import { fileURLToPath } from 'node:url';
10
10
  import { getWorkspaceStateDir } from '../src/config/paths.mjs';
11
+ import { withFileLockSync } from '../src/storage/file-lock.mjs';
12
+ import { atomicWriteJsonSync } from '../src/storage/atomic-io.mjs';
11
13
 
12
14
  const BOUNDED_READ_TOOL_RE = /^(?:Read|read_file|view_file)$/i;
13
15
  const SENSITIVE_SEGMENT_RE =
@@ -16,21 +18,51 @@ const BINARY_OR_MULTIMODAL_EXT_RE =
16
18
  /\.(?:pem|key|pfx|p12|kdbx|keystore|jks|crt|cer|der|ipynb|pdf|png|jpe?g|gif|webp|bmp|ico|mp4|mov|wav|mp3|zip|tar|gz|7z|sqlite3?|db)$/i;
17
19
  const TRAVERSAL_SEGMENT_RE = /(?:^|[\\/])\.\.(?:[\\/]|$)/;
18
20
 
21
+ /**
22
+ * Returns true when `importMetaUrl` is the process entrypoint. When the generated npx hook shim
23
+ * (`burnoff-hook-shim.mjs` / `hook-shim.mjs`) dynamically imports a hook, `argv[1]` is the shim, so the
24
+ * shim publishes the exact hook path via `BURNOFF_SHIM_TARGET`; only that one module matches.
25
+ */
19
26
  export function isCliEntrypoint(importMetaUrl, argv1 = globalThis.process?.argv?.[1]) {
20
- if (!importMetaUrl || !argv1) return false;
27
+ if (!importMetaUrl) return false;
28
+ const targets = [];
29
+ if (argv1) targets.push(String(argv1));
30
+ const shimTarget = globalThis.process?.env?.BURNOFF_SHIM_TARGET;
31
+ if (shimTarget && argv1 === globalThis.process?.argv?.[1]) {
32
+ targets.push(String(shimTarget));
33
+ }
34
+ if (targets.length === 0) return false;
21
35
  try {
22
36
  const modulePath = fileURLToPath(importMetaUrl);
23
- const targetPath = path.resolve(String(argv1));
37
+ let realModule = null;
24
38
  try {
25
- return fs.realpathSync(modulePath) === fs.realpathSync(targetPath);
39
+ realModule = fs.realpathSync(modulePath);
26
40
  } catch {
27
- return path.normalize(modulePath) === path.normalize(targetPath);
41
+ realModule = null; // ignore: unresolvable module path falls back to normalized compare
42
+ }
43
+ for (const rawTarget of targets) {
44
+ const targetPath = path.resolve(rawTarget);
45
+ try {
46
+ if (realModule && realModule === fs.realpathSync(targetPath)) return true;
47
+ } catch {
48
+ if (path.normalize(modulePath) === path.normalize(targetPath)) return true;
49
+ }
28
50
  }
51
+ return false;
29
52
  } catch {
30
53
  return false;
31
54
  }
32
55
  }
33
56
 
57
+ /**
58
+ * Case-folds a POSIX-style path key only on Windows (case-insensitive FS); preserves case elsewhere
59
+ * so `Config.js` and `config.js` never collide on Linux/macOS.
60
+ */
61
+ export function normalizePlatformPathKey(filePath = '') {
62
+ const posix = String(filePath || '').replace(/\\/g, '/');
63
+ return globalThis.process?.platform === 'win32' ? posix.toLowerCase() : posix;
64
+ }
65
+
34
66
  export function readStdinJson(options = {}) {
35
67
  if (globalThis.process?.stdin?.isTTY) return {};
36
68
  let raw = '';
@@ -375,6 +407,25 @@ export function recordHookTrace(eventName, payload = {}, details = {}) {
375
407
  }
376
408
  }
377
409
 
410
+ /** Resolves the inclusive 1-based line range requested by a bounded Read/view_file call. */
411
+ function resolveBoundedReadRange(tIn = {}) {
412
+ const hasSliceOffset =
413
+ tIn.offset !== undefined || tIn.StartLine !== undefined || tIn.start_line !== undefined;
414
+ const hasSliceEnd = tIn.EndLine !== undefined || tIn.end_line !== undefined;
415
+ const hasSliceLimit = tIn.limit !== undefined && tIn.limit !== null;
416
+ const reqStart = Math.max(1, Math.floor(Number(tIn.offset ?? tIn.StartLine ?? tIn.start_line ?? 1)));
417
+ const reqLimit = Number(tIn.limit);
418
+ const reqEnd =
419
+ Number.isFinite(reqLimit) && reqLimit > 0
420
+ ? reqStart + Math.floor(reqLimit) - 1
421
+ : hasSliceEnd
422
+ ? Math.max(reqStart, Math.floor(Number(tIn.EndLine ?? tIn.end_line ?? reqStart)))
423
+ : !hasSliceOffset && !hasSliceLimit
424
+ ? Number.MAX_SAFE_INTEGER
425
+ : reqStart;
426
+ return { reqStart, reqEnd };
427
+ }
428
+
378
429
  /**
379
430
  * Conservative fast-path check for explicitly bounded workspace source file reads.
380
431
  * Returns `false` whenever any active guard, lock, breaker failure state, policy file,
@@ -437,6 +488,14 @@ export function canFastAllowBoundedRead(payload = {}, { cwd = '', homeDir = null
437
488
  }
438
489
  }
439
490
 
491
+ // Missing or non-file targets must be handled by the core engine.
492
+ try {
493
+ const absExisting = path.isAbsolute(rawPath) ? path.resolve(rawPath) : path.resolve(baseCwd, rawPath);
494
+ if (!fs.statSync(absExisting).isFile()) return false;
495
+ } catch {
496
+ return false;
497
+ }
498
+
440
499
  if (
441
500
  fs.existsSync(path.join(baseCwd, '.burnoff.yaml')) ||
442
501
  fs.existsSync(path.join(baseCwd, '.burnoff.yml'))
@@ -470,15 +529,10 @@ export function canFastAllowBoundedRead(payload = {}, { cwd = '', homeDir = null
470
529
  try {
471
530
  const snap = JSON.parse(fs.readFileSync(snapPath, 'utf8'));
472
531
  const absTarget = path.isAbsolute(rawPath) ? path.resolve(rawPath) : path.resolve(baseCwd, rawPath);
473
- const normKey = absTarget.replace(/\\/g, '/').toLowerCase();
532
+ const normKey = normalizePlatformPathKey(absTarget);
474
533
  const entry = snap?.__readIntervals?.[normKey];
475
534
  if (entry && Array.isArray(entry.intervals) && entry.intervals.length > 0) {
476
- const reqStart = Math.max(1, Math.floor(Number(tIn.offset ?? tIn.StartLine ?? tIn.start_line ?? 1)));
477
- const reqLimit = Number(tIn.limit);
478
- const reqEnd =
479
- Number.isFinite(reqLimit) && reqLimit > 0
480
- ? reqStart + Math.floor(reqLimit) - 1
481
- : Math.max(reqStart, Math.floor(Number(tIn.EndLine ?? tIn.end_line ?? reqStart)));
535
+ const { reqStart, reqEnd } = resolveBoundedReadRange(tIn);
482
536
  const hasOverlap = entry.intervals.some(
483
537
  (iv) => Array.isArray(iv) && iv.length >= 2 && reqStart <= iv[1] && reqEnd >= iv[0]
484
538
  );
@@ -494,6 +548,91 @@ export function canFastAllowBoundedRead(payload = {}, { cwd = '', homeDir = null
494
548
  return true;
495
549
  }
496
550
 
551
+ function mergeFastIntervals(intervals = []) {
552
+ const sorted = intervals
553
+ .filter((p) => Array.isArray(p) && Number.isFinite(p[0]) && Number.isFinite(p[1]) && p[1] >= p[0])
554
+ .map((p) => [Math.max(1, Math.floor(p[0])), Math.floor(p[1])])
555
+ .sort((a, b) => (a[0] !== b[0] ? a[0] - b[0] : a[1] - b[1]));
556
+ const merged = [];
557
+ for (const cur of sorted) {
558
+ const last = merged[merged.length - 1];
559
+ if (last && cur[0] <= last[1] + 1) last[1] = Math.max(last[1], cur[1]);
560
+ else merged.push([cur[0], cur[1]]);
561
+ }
562
+ return merged;
563
+ }
564
+
565
+ /**
566
+ * Records a fast-allowed bounded read into `read_snapshots_<sid>.json` (same schema as
567
+ * `read-clamp.mjs#recordReadIntervalEntry`) so repeated reads hit DET-06 overlap dedup and later
568
+ * edits satisfy the DET-07/DET-08 read-before-edit checks. Best-effort: never throws.
569
+ */
570
+ export function recordFastBoundedReadSnapshot(
571
+ payload = {},
572
+ { cwd = '', homeDir = null, client = 'claude-code' } = {}
573
+ ) {
574
+ try {
575
+ const tIn = payload.tool_input || payload.toolInput || payload.args || payload.toolArgs || payload.toolCall?.args || {};
576
+ const rawPath = String(
577
+ tIn.file_path || tIn.Path || tIn.AbsolutePath || tIn.path || tIn.TargetFile || ''
578
+ ).trim();
579
+ if (!rawPath) return false;
580
+ const rawCwd =
581
+ cwd ||
582
+ payload.cwd ||
583
+ (Array.isArray(payload.workspacePaths) && payload.workspacePaths[0]) ||
584
+ payload.workspacePath ||
585
+ process.cwd();
586
+ const baseCwd = path.resolve(String(rawCwd || process.cwd()));
587
+ const absTarget = path.isAbsolute(rawPath) ? path.resolve(rawPath) : path.resolve(baseCwd, rawPath);
588
+ const st = fs.statSync(absTarget);
589
+ if (!st.isFile()) return false;
590
+ const { reqStart, reqEnd } = resolveBoundedReadRange(tIn);
591
+ if (!(reqEnd >= reqStart) || reqEnd === Number.MAX_SAFE_INTEGER) return false;
592
+
593
+ const sessionId = String(payload.session_id || payload.sessionId || payload.conversationId || 'default');
594
+ const safeSid = (sessionId.replace(/[^a-zA-Z0-9._-]/g, '_').slice(0, 80) || 'default').slice(0, 64);
595
+ const snapPath =
596
+ client === 'antigravity'
597
+ ? path.join(getWorkspaceStateDir(baseCwd, homeDir), `read_snapshots_${safeSid}.json`)
598
+ : path.join(baseCwd, '.claude', 'cache', `read_snapshots_${safeSid}.json`);
599
+ const normKey = normalizePlatformPathKey(absTarget);
600
+
601
+ withFileLockSync(snapPath, () => {
602
+ let store = {};
603
+ try {
604
+ const parsed = JSON.parse(fs.readFileSync(snapPath, 'utf8'));
605
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) store = parsed;
606
+ } catch {
607
+ store = {}; // ignore: missing or corrupt snapshot store resets cleanly
608
+ }
609
+ if (!store.__readIntervals || typeof store.__readIntervals !== 'object') store.__readIntervals = {};
610
+ const prev = store.__readIntervals[normKey];
611
+ const sameStat =
612
+ prev && Number(prev.mtimeMs) === Number(st.mtimeMs) && Number(prev.size) === Number(st.size);
613
+ const existing = sameStat && Array.isArray(prev.intervals) ? prev.intervals : [];
614
+ store.__readIntervals[normKey] = {
615
+ mtimeMs: Number(st.mtimeMs),
616
+ size: Number(st.size),
617
+ recordedAt: Date.now(),
618
+ intervals: mergeFastIntervals([...existing, [reqStart, reqEnd]])
619
+ };
620
+ const keys = Object.keys(store.__readIntervals);
621
+ if (keys.length > 200) {
622
+ keys
623
+ .sort((a, b) => Number(store.__readIntervals[a]?.recordedAt || 0) - Number(store.__readIntervals[b]?.recordedAt || 0))
624
+ .slice(0, keys.length - 200)
625
+ .forEach((k) => delete store.__readIntervals[k]);
626
+ }
627
+ fs.mkdirSync(path.dirname(snapPath), { recursive: true });
628
+ atomicWriteJsonSync(snapPath, store, { skipFsync: true });
629
+ });
630
+ return true;
631
+ } catch {
632
+ return false; // ignore: snapshot recording is best-effort and must never block a fast allow
633
+ }
634
+ }
635
+
497
636
  const READ_ONLY_FAST_ALLOW_TOOL_RE = /^(?:Grep|Glob|WebFetch)$/i;
498
637
  const READ_ONLY_TOOL_ALIASES = Object.freeze({
499
638
  grep_search: 'Grep',
@@ -583,6 +722,72 @@ export function tryTier1PreToolFastPath(event = {}, options = {}) {
583
722
  if (hasSensitiveReadOnlyTarget(toolName, toolInput)) {
584
723
  return null;
585
724
  }
725
+
726
+ // Track Grep/Glob discovery calls toward DET-15 exploration budget only when
727
+ // an explicit session ID and cwd are present and persistence is enabled.
728
+ if (/^(?:Grep|Glob)$/i.test(toolName) && options?.persistState !== false) {
729
+ const rawSid = String(event?.session_id || event?.sessionId || event?.conversationId || '').trim();
730
+ const firstWs =
731
+ Array.isArray(event?.workspacePaths) && event.workspacePaths[0]
732
+ ? String(event.workspacePaths[0])
733
+ : '';
734
+ const rawCwd = String(
735
+ event?.cwd || options?.cwd || event?.toolCall?.args?.Cwd || firstWs || ''
736
+ ).trim();
737
+ if (rawSid && rawCwd) {
738
+ const budgetThreshold = Math.max(
739
+ 1,
740
+ Number(options?.explorationBudgetCalls ?? options?.policy?.guards?.explorationBudgetCalls ?? 10)
741
+ );
742
+ const safeSid = rawSid.replace(/[^a-zA-Z0-9._-]/g, '_').slice(0, 80) || 'default';
743
+ const baseCwd = path.resolve(rawCwd);
744
+ const isAgClient = Boolean(
745
+ event?.conversationId ||
746
+ Array.isArray(event?.workspacePaths) ||
747
+ options?.client === 'antigravity' ||
748
+ globalThis.process?.env?.BURNOFF_CLIENT === 'antigravity'
749
+ );
750
+ const breakerPath = options?.breakerStatePath
751
+ ? path.resolve(String(options.breakerStatePath))
752
+ : isAgClient
753
+ ? path.join(
754
+ getWorkspaceStateDir(baseCwd, options?.homeDir),
755
+ `burnoff_breaker_state_${safeSid}.json`
756
+ )
757
+ : path.join(baseCwd, '.claude', 'cache', `burnoff_breaker_state_${safeSid}.json`);
758
+ let fallThroughToEngine = false;
759
+ try {
760
+ // Serialize the read-modify-write so parallel Grep/Glob hooks never lose increments.
761
+ withFileLockSync(breakerPath, () => {
762
+ let cur = {};
763
+ if (fs.existsSync(breakerPath)) {
764
+ const parsed = JSON.parse(fs.readFileSync(breakerPath, 'utf8'));
765
+ if (parsed && typeof parsed === 'object') cur = parsed;
766
+ }
767
+ const prevSince = Math.max(0, Number(cur.discoveryCallsSinceLastMutation || 0));
768
+ if (prevSince + 1 >= budgetThreshold) {
769
+ fallThroughToEngine = true; // DET-15 budget enforcement belongs to the core engine
770
+ return;
771
+ }
772
+ const prevTotal = Math.max(0, Number(cur.discoveryCallsTotal || 0));
773
+ const nextSnap = {
774
+ ...cur,
775
+ schemaVersion: cur.schemaVersion || '1.0.0',
776
+ sessionId: rawSid,
777
+ discoveryCallsTotal: prevTotal + 1,
778
+ discoveryCallsSinceLastMutation: prevSince + 1,
779
+ updatedAt: Date.now()
780
+ };
781
+ fs.mkdirSync(path.dirname(breakerPath), { recursive: true });
782
+ atomicWriteJsonSync(breakerPath, nextSnap, { skipFsync: true });
783
+ });
784
+ } catch {
785
+ // ignore: fast-path discovery counter failure must fail open
786
+ }
787
+ if (fallThroughToEngine) return null;
788
+ }
789
+ }
790
+
586
791
  const tier1Active = Boolean(
587
792
  options?.tier1Active ||
588
793
  event?.tier1Active ||
@@ -0,0 +1,44 @@
1
+ {
2
+ "hooks": {
3
+ "PreToolUse": [
4
+ {
5
+ "matcher": "Bash|PowerShell|Edit|MultiEdit|Write|NotebookEdit|Read|Grep|Glob|Task|Agent|WebFetch|mcp__.*",
6
+ "hooks": [{ "type": "command", "command": "node \"${CLAUDE_PLUGIN_ROOT}/hooks/pre-tool-use.mjs\"", "timeout": 5 }]
7
+ }
8
+ ],
9
+ "PreSkillShellCommand": [
10
+ { "hooks": [{ "type": "command", "command": "node \"${CLAUDE_PLUGIN_ROOT}/hooks/pre-tool-use.mjs\"", "timeout": 5 }] }
11
+ ],
12
+ "PostToolUse": [
13
+ {
14
+ "matcher": "Bash|PowerShell|Edit|MultiEdit|Write|NotebookEdit|Task|Agent|WebFetch|mcp__.*",
15
+ "hooks": [{ "type": "command", "command": "node \"${CLAUDE_PLUGIN_ROOT}/hooks/post-tool-use.mjs\"", "timeout": 5 }]
16
+ }
17
+ ],
18
+ "PostToolUseFailure": [
19
+ {
20
+ "matcher": "Bash|PowerShell|Edit|MultiEdit|Write|NotebookEdit|Task|Agent|WebFetch|mcp__.*",
21
+ "hooks": [{ "type": "command", "command": "node \"${CLAUDE_PLUGIN_ROOT}/hooks/post-tool-use.mjs\"", "timeout": 5 }]
22
+ }
23
+ ],
24
+ "SessionStart": [
25
+ {
26
+ "matcher": "startup|resume|clear|compact",
27
+ "hooks": [{ "type": "command", "command": "node \"${CLAUDE_PLUGIN_ROOT}/hooks/session-lifecycle.mjs\"", "timeout": 5 }]
28
+ }
29
+ ],
30
+ "PreCompact": [
31
+ { "hooks": [{ "type": "command", "command": "node \"${CLAUDE_PLUGIN_ROOT}/hooks/session-lifecycle.mjs\"", "timeout": 5 }] }
32
+ ],
33
+ "PreModelSwitch": [
34
+ { "hooks": [{ "type": "command", "command": "node \"${CLAUDE_PLUGIN_ROOT}/hooks/session-lifecycle.mjs\"", "timeout": 5 }] }
35
+ ],
36
+ "PostModelSwitch": [
37
+ { "hooks": [{ "type": "command", "command": "node \"${CLAUDE_PLUGIN_ROOT}/hooks/session-lifecycle.mjs\"", "timeout": 5 }] }
38
+ ],
39
+ "UserPromptSubmit": [
40
+ { "hooks": [{ "type": "command", "command": "node \"${CLAUDE_PLUGIN_ROOT}/hooks/user-prompt-submit.mjs\"", "timeout": 5 }] }
41
+ ]
42
+ }
43
+ }
44
+
@@ -79,7 +79,7 @@ export async function executePostToolUseCli(cliOptions = {}) {
79
79
  const ipcRes = await tryFastDaemonRpc(
80
80
  'hook.postToolUse',
81
81
  { client, event: payload },
82
- { ipcPath: cliOptions.ipcPath }
82
+ { ipcPath: cliOptions.ipcPath, cwd: canonical.cwd }
83
83
  );
84
84
  if (ipcRes && ipcRes.fullVerdict === true) {
85
85
  emitPostToolResult(ipcRes, payload, traceBase, 'daemon_ipc', ioOverride);
@@ -118,6 +118,8 @@ if (isCliEntrypoint(import.meta.url)) {
118
118
  });
119
119
  }
120
120
 
121
+ export { executePostToolUseCli as main };
122
+
121
123
  export default {
122
124
  runPostToolUseHookAsync,
123
125
  runPostToolUseHook,
@@ -14,17 +14,29 @@ import {
14
14
  exitWithStdoutJson,
15
15
  recordHookTrace,
16
16
  canFastAllowBoundedRead,
17
+ recordFastBoundedReadSnapshot,
17
18
  tryTier1PreToolFastPath
18
19
  } from './hook-io.mjs';
19
- import { tryFastDaemonRpc } from '../src/ipc/fast-client.mjs';
20
+ import { tryFastDaemonRpc, maybeSpawnAutoDaemon } from '../src/ipc/fast-client.mjs';
20
21
  import { getClientAdapter, normalizeHookEvent } from '../src/clients/detect.mjs';
21
22
 
22
23
  let _engineMod = null;
24
+ let _promptMod = null;
23
25
  if (!isCliEntrypoint(import.meta.url)) {
24
26
  _engineMod = await import('../src/guards/pre-tool-engine.mjs');
25
27
  }
26
28
 
29
+ function isUserPromptSubmitEvent(event = {}) {
30
+ return String(event?.hook_event_name || event?.hookEventName || '').trim().toLowerCase() === 'userpromptsubmit';
31
+ }
32
+
27
33
  export async function runPreToolUseHookAsync(event = {}, options = {}) {
34
+ if (isUserPromptSubmitEvent(event)) {
35
+ if (!_promptMod) {
36
+ _promptMod = await import('../src/guards/prompt-guard.mjs');
37
+ }
38
+ return _promptMod.runUserPromptSubmitHook(event, options);
39
+ }
28
40
  const fast = tryTier1PreToolFastPath(event, options);
29
41
  if (fast) return fast;
30
42
  if (!_engineMod) {
@@ -34,6 +46,9 @@ export async function runPreToolUseHookAsync(event = {}, options = {}) {
34
46
  }
35
47
 
36
48
  export function runPreToolUseHook(event = {}, options = {}) {
49
+ if (isUserPromptSubmitEvent(event)) {
50
+ if (_promptMod) return _promptMod.runUserPromptSubmitHook(event, options);
51
+ }
37
52
  const fast = tryTier1PreToolFastPath(event, options);
38
53
  if (fast) return fast;
39
54
  if (!_engineMod) {
@@ -44,19 +59,25 @@ export function runPreToolUseHook(event = {}, options = {}) {
44
59
 
45
60
  function exitOnInternalFault(err, ioOverride = {}, client = 'claude-code') {
46
61
  const msg = err?.message || String(err);
62
+ const strict =
63
+ String(globalThis.process?.env?.BURNOFF_PRETOOL_FAIL_MODE || '').toLowerCase() === 'closed';
47
64
  if (client === 'antigravity') {
48
- const adapter = getClientAdapter(client);
49
- const failRes = adapter.renderFailOpen(msg, 'PreToolUse');
50
65
  const writeStderr =
51
66
  ioOverride.stderrWrite ||
52
67
  ioOverride.writeStderr ||
53
68
  ((s) => globalThis.process?.stderr?.write?.(s));
69
+ if (strict) {
70
+ const reason = `[Burnoff Fail-Closed] Internal pre-tool hook error: ${msg}`;
71
+ writeStderr(`${reason}\n`);
72
+ exitWithStdoutJson({ decision: 'deny', reason }, ioOverride);
73
+ return;
74
+ }
75
+ const adapter = getClientAdapter(client);
76
+ const failRes = adapter.renderFailOpen(msg, 'PreToolUse');
54
77
  writeStderr(failRes.stderr);
55
78
  exitWithStdoutJson(failRes.stdout, ioOverride);
56
79
  return;
57
80
  }
58
- const strict =
59
- String(globalThis.process?.env?.BURNOFF_PRETOOL_FAIL_MODE || '').toLowerCase() === 'closed';
60
81
  if (strict) {
61
82
  exitHardBlockStderr(`[Burnoff Fail-Closed] ${msg}`, 'PreToolUse', ioOverride);
62
83
  return;
@@ -84,6 +105,12 @@ export async function executePreToolUseCli(cliOptions = {}) {
84
105
  let detectedClient = 'claude-code';
85
106
  try {
86
107
  payload = await readPayload(cliOptions.timeoutMs);
108
+ if (isUserPromptSubmitEvent(payload)) {
109
+ const { runUserPromptSubmitHook } = await import('../src/guards/prompt-guard.mjs');
110
+ const promptRes = runUserPromptSubmitHook(payload, { persistState: true, ...(cliOptions.hookOptions || {}) });
111
+ emitPreToolResult(promptRes, payload, { tracePath: cliOptions.tracePath }, 'prompt_delegate', ioOverride);
112
+ return;
113
+ }
87
114
  const { client, adapter, canonical } = normalizeHookEvent(payload, cliOptions.hookOptions);
88
115
  detectedClient = client;
89
116
  const hasCustomOptions = Boolean(cliOptions.runHook || cliOptions.hookOptions);
@@ -106,14 +133,23 @@ export async function executePreToolUseCli(cliOptions = {}) {
106
133
  const ipcRes = await tryFastDaemonRpc(
107
134
  'hook.preToolUse',
108
135
  { client, event: payload },
109
- { ipcPath: cliOptions.ipcPath }
136
+ { ipcPath: cliOptions.ipcPath, cwd: canonical.cwd }
110
137
  );
111
138
  if (ipcRes && ipcRes.fullVerdict === true) {
112
139
  emitPreToolResult(ipcRes, payload, traceBase, 'daemon_ipc', ioOverride);
113
140
  return;
114
141
  }
115
142
 
143
+ if (canonical.cwd) {
144
+ try {
145
+ maybeSpawnAutoDaemon({ cwd: canonical.cwd, ipcPath: cliOptions.ipcPath });
146
+ } catch {
147
+ // ignore: best-effort background daemon warmup on cold miss
148
+ }
149
+ }
150
+
116
151
  if (canFastAllowBoundedRead(payload, { cwd: canonical.cwd })) {
152
+ recordFastBoundedReadSnapshot(payload, { cwd: canonical.cwd, client });
117
153
  const fastRes = client === 'antigravity' ? adapter.renderPre({ exitCode: 0, stdout: '', stderr: '', verdict: { decision: 'allow' } }) : { exitCode: 0, stdout: '', stderr: '' };
118
154
  emitPreToolResult(fastRes, payload, traceBase, 'bounded_read_fast', ioOverride);
119
155
  return;
@@ -124,14 +160,15 @@ export async function executePreToolUseCli(cliOptions = {}) {
124
160
  const res = runCore(payload, { persistState: true, ...(cliOptions.hookOptions || {}) });
125
161
  emitPreToolResult(res, payload, traceBase, 'core', ioOverride);
126
162
  } catch (err) {
127
- const strict =
163
+ // Claude fail-closed exits 2; Antigravity fail-closed emits a JSON deny with exit 0.
164
+ const strictClaude =
128
165
  detectedClient !== 'antigravity' &&
129
166
  String(globalThis.process?.env?.BURNOFF_PRETOOL_FAIL_MODE || '').toLowerCase() === 'closed';
130
167
  recordHookTrace('PreToolUse', payload, {
131
168
  tracePath: cliOptions.tracePath,
132
169
  outcome: 'error',
133
170
  path: 'fault',
134
- exitCode: strict ? 2 : 0,
171
+ exitCode: strictClaude ? 2 : 0,
135
172
  error: err?.message || String(err)
136
173
  });
137
174
  exitOnInternalFault(err, ioOverride, detectedClient);
@@ -144,6 +181,8 @@ if (isCliEntrypoint(import.meta.url)) {
144
181
  });
145
182
  }
146
183
 
184
+ export { executePreToolUseCli as main };
185
+
147
186
  export default {
148
187
  runPreToolUseHookAsync,
149
188
  runPreToolUseHook,
@@ -9,23 +9,42 @@ import {
9
9
  readStdinJsonAsync,
10
10
  exitPassThrough,
11
11
  exitDiagnosticZero,
12
- exitWithStdoutJson
12
+ exitWithStdoutJson,
13
+ exitHardBlockStderr
13
14
  } from './hook-io.mjs';
14
15
  import { runSessionLifecycleHook } from '../src/guards/session-hook.mjs';
16
+ import { maybeSpawnAutoDaemon } from '../src/ipc/fast-client.mjs';
15
17
 
16
18
  export async function executeSessionLifecycleCli(cliOptions = {}) {
17
19
  const readPayload = cliOptions.readPayload || readStdinJsonAsync;
18
20
  const ioOverride = cliOptions.ioOverride || {};
21
+ let eventName = 'SessionStart';
19
22
  try {
20
23
  const payload = await readPayload(cliOptions.timeoutMs);
24
+ eventName = String(payload?.hook_event_name || payload?.hookEventName || 'SessionStart');
25
+ if (eventName.toLowerCase() === 'sessionstart' && !cliOptions.hookOptions) {
26
+ try {
27
+ const ws =
28
+ payload?.cwd ||
29
+ (Array.isArray(payload?.workspacePaths) && payload.workspacePaths[0]) ||
30
+ payload?.workspacePath;
31
+ if (ws) {
32
+ maybeSpawnAutoDaemon({ cwd: ws, ipcPath: cliOptions.ipcPath });
33
+ }
34
+ } catch {
35
+ // ignore: best-effort background daemon warmup
36
+ }
37
+ }
21
38
  const res = runSessionLifecycleHook(payload, cliOptions.hookOptions || {});
22
- if (res.stdout) {
39
+ if (res.exitCode === 2) {
40
+ exitHardBlockStderr(res.stderr, eventName, ioOverride);
41
+ } else if (res.stdout) {
23
42
  exitWithStdoutJson(res.stdout, ioOverride);
24
43
  } else {
25
44
  exitPassThrough(ioOverride.exitFn);
26
45
  }
27
46
  } catch (err) {
28
- exitDiagnosticZero(err?.message || String(err), 'SessionStart', ioOverride);
47
+ exitDiagnosticZero(err?.message || String(err), eventName, ioOverride);
29
48
  }
30
49
  }
31
50
 
@@ -35,6 +54,8 @@ if (isCliEntrypoint(import.meta.url)) {
35
54
  });
36
55
  }
37
56
 
57
+ export { executeSessionLifecycleCli as main };
58
+
38
59
  export default {
39
60
  executeSessionLifecycleCli
40
61
  };