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
@@ -8,8 +8,13 @@
8
8
  import fs from 'node:fs';
9
9
  import path from 'node:path';
10
10
  import { getHomeDir } from '../config/paths.mjs';
11
+ import { loadBurnoffPolicy } from '../config/policy.mjs';
12
+ import { auditRulesFiles } from '../cli/startup-audit.mjs';
11
13
  import { classifyLedgerBucket, LEDGER_BUCKETS, readLedgerEntries } from '../storage/ledger.mjs';
14
+ import { readBreakerStateSnapshot } from './loop-breaker.mjs';
12
15
  import { getReadSnapFilePath } from './read-clamp.mjs';
16
+ import { writeCompactionBatonAtomicSync, consumeCompactionBatonSync } from './compaction-baton.mjs';
17
+ import { isModelSwitchEvent, runModelSwitchHook } from './model-switch-hook.mjs';
13
18
 
14
19
  function normalizeCwdKey(cwdPath = '') {
15
20
  const raw = String(cwdPath || '').trim();
@@ -165,24 +170,152 @@ export function runSessionLifecycleHook(event = {}, options = {}) {
165
170
  const hookEventName = String(
166
171
  event.hook_event_name || event.hookEventName || options.hookEventName || ''
167
172
  ).trim();
173
+ // Model-switch hooks share this entrypoint but must NOT invalidate read snapshots.
174
+ if (isModelSwitchEvent(event, options)) {
175
+ return runModelSwitchHook(event, options);
176
+ }
168
177
  const source = String(event.source || options.source || '').trim().toLowerCase();
169
178
  const sessionId = String(event.session_id || event.sessionId || options.sessionId || 'default');
170
179
  const cwd = path.resolve(String(event.cwd || options.cwd || process.cwd()));
171
180
 
172
181
  const invalidated = invalidateReadSnapshots(cwd, sessionId, options);
173
- const isCompactEvent = /^PreCompact$/i.test(hookEventName) || source === 'compact';
182
+ const nowMs = Number.isFinite(Number(options.nowMs ?? event.timestamp))
183
+ ? Number(options.nowMs ?? event.timestamp)
184
+ : Date.now();
185
+ const isExplicitSessionStart = /^SessionStart$/i.test(hookEventName);
186
+ const isCompactEvent =
187
+ /^PreCompact$/i.test(hookEventName) ||
188
+ (!isExplicitSessionStart &&
189
+ source === 'compact' &&
190
+ (event.cacheCold !== undefined || event.idle_ms !== undefined || event.idleMs !== undefined));
191
+
192
+ const policy = options.policy || loadBurnoffPolicy(cwd);
174
193
 
175
194
  if (isCompactEvent) {
195
+ let snap = null;
196
+ try {
197
+ snap = readBreakerStateSnapshot(sessionId, { ...options, cwd });
198
+ } catch (err) {
199
+ void err; // ignore: unreadable breaker snapshot falls back cleanly
200
+ }
201
+
202
+ let batonRes = { written: false, path: null };
203
+ if (policy.guards?.compactionBatonEnabled !== false) {
204
+ const explicitFiles = Array.isArray(event.modified_files)
205
+ ? event.modified_files
206
+ : Array.isArray(event.recentEditedFiles)
207
+ ? event.recentEditedFiles
208
+ : [];
209
+ const mergedFiles = [
210
+ ...(Array.isArray(snap?.editedFiles) ? snap.editedFiles : []),
211
+ ...explicitFiles
212
+ ];
213
+ const explicitConstraints = Array.isArray(event.activeConstraints)
214
+ ? event.activeConstraints
215
+ : Array.isArray(event.constraints)
216
+ ? event.constraints
217
+ : [];
218
+ const mergedCommands = [
219
+ ...(Array.isArray(snap?.recentCommands) ? snap.recentCommands : []),
220
+ ...(Array.isArray(event.recentCommands) ? event.recentCommands : [])
221
+ ];
222
+ batonRes = writeCompactionBatonAtomicSync(
223
+ cwd,
224
+ sessionId,
225
+ {
226
+ model: event.model?.id || event.model || snap?.lastModel || '',
227
+ effort: event.effort || snap?.lastEffort || '',
228
+ cacheTtlTier: event.cacheTtlTier || snap?.cacheTtlTier || policy.guards?.cacheTtlTier || '5m',
229
+ promptTokens: event.promptTokens ?? event.context_window?.total_input_tokens ?? snap?.lastPromptTokens ?? 0,
230
+ recentEditedFiles: mergedFiles,
231
+ recentCommands: mergedCommands,
232
+ recentErrorSignature: event.recentErrorSignature || snap?.lastFailedToolKey || '',
233
+ activeConstraints: explicitConstraints,
234
+ nowMs
235
+ },
236
+ {
237
+ ...options,
238
+ cwd,
239
+ nowMs,
240
+ maxBytes: policy.guards?.compactionBatonMaxBytes
241
+ }
242
+ );
243
+ }
244
+
245
+ const ttlTier = String(
246
+ event.cacheTtlTier || snap?.cacheTtlTier || policy.guards?.cacheTtlTier || '5m'
247
+ ).toLowerCase();
248
+ const effectiveTtlMs = ttlTier === '1h' ? 60 * 60 * 1000 : 5 * 60 * 1000;
249
+ const explicitIdleMs = Number(event.idle_ms ?? event.idleMs);
250
+ const elapsedMs = Number.isFinite(explicitIdleMs)
251
+ ? explicitIdleMs
252
+ : snap?.lastTurnAtMs
253
+ ? Math.max(0, nowMs - Number(snap.lastTurnAtMs))
254
+ : null;
255
+ const isCold = event.cacheCold === true || (elapsedMs !== null && elapsedMs > effectiveTtlMs);
256
+ if (!isCold) {
257
+ return {
258
+ exitCode: 0,
259
+ stdout: '',
260
+ stderr: '',
261
+ invalidated,
262
+ batonWritten: Boolean(batonRes?.written),
263
+ batonPath: batonRes?.path || null
264
+ };
265
+ }
266
+ const compactMsg =
267
+ `[Burnoff BO-TTL-02 Cold-Cache PreCompact Advisory] Prompt cache has expired past the ${ttlTier} TTL; ` +
268
+ `compacting now summarizes cold tokens. Consider /handoff + /clear in a fresh session instead.`;
176
269
  return {
177
270
  exitCode: 0,
178
- stdout: '',
271
+ stdout: JSON.stringify({ systemMessage: compactMsg }),
179
272
  stderr: '',
180
- invalidated
273
+ systemMessage: compactMsg,
274
+ invalidated,
275
+ batonWritten: Boolean(batonRes?.written),
276
+ batonPath: batonRes?.path || null
181
277
  };
182
278
  }
183
279
 
184
280
  const receipt = buildLastSessionReceipt(cwd, sessionId, options);
185
- if (!receipt) {
281
+ let rulesNotice = null;
282
+ if (options.auditRules !== false) {
283
+ try {
284
+ const ruleCandidates = [
285
+ path.join(cwd, 'CLAUDE.md'),
286
+ path.join(cwd, '.claude', 'CLAUDE.md'),
287
+ path.join(cwd, 'AGENTS.md'),
288
+ path.join(cwd, '.cursorrules')
289
+ ].filter((p) => fs.existsSync(p));
290
+ if (ruleCandidates.length > 0) {
291
+ const rulesAudit = auditRulesFiles(ruleCandidates);
292
+ if (
293
+ (rulesAudit.status === 'warn' || rulesAudit.status === 'caution') &&
294
+ Array.isArray(rulesAudit.advisories) &&
295
+ rulesAudit.advisories.length > 0
296
+ ) {
297
+ rulesNotice = `Burnoff Startup Notice (BO-CFG-12): ${rulesAudit.advisories.slice(0, 2).join(' | ')}`;
298
+ }
299
+ }
300
+ } catch (auditErr) {
301
+ void auditErr; // ignore: best-effort rules audit on SessionStart
302
+ }
303
+ }
304
+
305
+ let batonContext = null;
306
+ if (policy.guards?.compactionBatonEnabled !== false) {
307
+ const consumed = consumeCompactionBatonSync(cwd, sessionId, { ...options, cwd, nowMs });
308
+ if (consumed?.context) {
309
+ batonContext = consumed.context;
310
+ }
311
+ }
312
+
313
+ const policyWarning =
314
+ policy?.exists && policy?.parseError
315
+ ? `[Burnoff Policy Warning] ${policy.sourcePath ? path.basename(policy.sourcePath) : '.burnoff.yaml'} failed to parse (${policy.parseErrorMessage || 'invalid YAML'}); built-in default policy is in effect.`
316
+ : null;
317
+ const combinedMessage = [policyWarning, receipt, rulesNotice, batonContext].filter(Boolean).join('\n');
318
+ if (!combinedMessage) {
186
319
  return {
187
320
  exitCode: 0,
188
321
  stdout: '',
@@ -191,11 +324,20 @@ export function runSessionLifecycleHook(event = {}, options = {}) {
191
324
  };
192
325
  }
193
326
 
327
+ const stdoutPayload = { systemMessage: combinedMessage };
328
+ if (batonContext) {
329
+ stdoutPayload.hookSpecificOutput = {
330
+ hookEventName: 'SessionStart',
331
+ additionalContext: batonContext
332
+ };
333
+ }
334
+
194
335
  return {
195
336
  exitCode: 0,
196
- stdout: JSON.stringify({ systemMessage: receipt }),
197
- stderr: '',
198
- systemMessage: receipt,
337
+ stdout: JSON.stringify(stdoutPayload),
338
+ stderr: policyWarning ? `${policyWarning}\n` : '',
339
+ systemMessage: combinedMessage,
340
+ ...(batonContext ? { batonContext, hookSpecificOutput: stdoutPayload.hookSpecificOutput } : {}),
199
341
  invalidated
200
342
  };
201
343
  }
@@ -735,6 +735,8 @@ function isExplicitTempTarget(normArg = '') {
735
735
  function isProtectedRecursiveDeleteTarget(rawArg = '') {
736
736
  const norm = String(rawArg || '').trim().replace(/^["']|["']$/g, '').replace(/\\/g, '/');
737
737
  if (!norm || norm.startsWith('-')) return false;
738
+ // Windows CMD single-letter switches (/s /q /f) are flags, not the filesystem root.
739
+ if (/^\/[a-z]$/i.test(norm)) return false;
738
740
  if (isExplicitTempTarget(norm)) return false;
739
741
  if (/^(?:\/+|\/\*|\~|\$HOME|\$\{HOME\}|\$env:USERPROFILE|[A-Za-z]:\/?)$/i.test(norm)) {
740
742
  return true;
@@ -749,10 +751,16 @@ function isProtectedRecursiveDeleteTarget(rawArg = '') {
749
751
  if (bin === 'rm' || bin === 'rm.exe' || bin === 'unlink' || bin === 'unlink.exe') {
750
752
  const rmArgs = rawTokens.slice(idx + 1);
751
753
  const hasRecursive = rmArgs.some(
752
- (a) => a === '--recursive' || (/^-[a-zA-Z]+$/.test(a) && /[rR]/.test(a))
754
+ (a) =>
755
+ a === '--recursive' ||
756
+ /^-r(?:ecurse)?$/i.test(a) ||
757
+ (/^-[a-zA-Z]+$/.test(a) && /[rR]/.test(a))
753
758
  );
754
759
  const hasForce = rmArgs.some(
755
- (a) => a === '--force' || (/^-[a-zA-Z]+$/.test(a) && /f/.test(a))
760
+ (a) =>
761
+ a === '--force' ||
762
+ /^-(?:f(?:orce)?|fo)$/i.test(a) ||
763
+ (/^-[a-zA-Z]+$/.test(a) && /f/.test(a))
756
764
  );
757
765
  const targetsRootOrHome = rmArgs.some((a) => isProtectedRecursiveDeleteTarget(a));
758
766
  if (hasRecursive && hasForce && targetsRootOrHome) {
@@ -781,10 +789,36 @@ function isProtectedRecursiveDeleteTarget(rawArg = '') {
781
789
  continue;
782
790
  }
783
791
 
784
- if (/^(?:remove-item|ri|del|erase|rmdir)$/i.test(bin)) {
792
+ if (
793
+ bin === 'trash' ||
794
+ bin === 'trash.exe' ||
795
+ bin === 'trash-put' ||
796
+ (bin === 'gio' && rawTokens[idx + 1] === 'trash')
797
+ ) {
798
+ const trashArgs = rawTokens.slice(bin === 'gio' ? idx + 2 : idx + 1);
799
+ const targetsProtectedGitOrWorktree = trashArgs.some((arg) => {
800
+ if (!arg || arg.startsWith('-')) return false;
801
+ const unquoted = String(arg).trim().replace(/^['"]|['"]$/g, '');
802
+ return /(?:^|[\\/])\.git(?:[\\/]|$)/i.test(unquoted) ||
803
+ /(?:^|[\\/])\.claude[\\/]worktrees(?:[\\/]|$)/i.test(unquoted);
804
+ });
805
+ if (targetsProtectedGitOrWorktree) {
806
+ return {
807
+ detectorId: 'DET-01',
808
+ triggered: true,
809
+ decision: isStrictAutoMode ? 'deny' : 'ask',
810
+ subType: 'TRASH_PROTECTED_GIT_TARGET',
811
+ reason:
812
+ '[Burnoff DET-01 Worktree Destructive Guard] Moving protected .git or .claude/worktrees path to trash requires confirmation.'
813
+ };
814
+ }
815
+ continue;
816
+ }
817
+
818
+ if (/^(?:remove-item|ri|del|erase|rmdir|rd)(?:\.exe)?$/i.test(bin)) {
785
819
  const psArgs = rawTokens.slice(idx + 1);
786
- const hasRecurse = psArgs.some((a) => /^-r(?:ecurse)?$/i.test(a));
787
- const hasForce = psArgs.some((a) => /^-f(?:orce)?$/i.test(a));
820
+ const hasRecurse = psArgs.some((a) => /^(?:-r(?:ecurse)?|\/s)$/i.test(a));
821
+ const hasForce = psArgs.some((a) => /^(?:-f(?:orce)?|-fo|\/q|\/f)$/i.test(a));
788
822
  const targetsRootOrHome = psArgs.some((a) => isProtectedRecursiveDeleteTarget(a));
789
823
  if (hasRecurse && hasForce && targetsRootOrHome) {
790
824
  return {
@@ -1092,6 +1126,23 @@ function isProtectedRecursiveDeleteTarget(rawArg = '') {
1092
1126
  }
1093
1127
 
1094
1128
  const discardDecision = isStrictAutoMode ? 'deny' : 'ask';
1129
+ if (subcommand === 'worktree' && subArgs[0] === 'remove') {
1130
+ const removeArgs = subArgs.slice(1).filter((a) => a !== '-h' && a !== '--help');
1131
+ const hasForce = removeArgs.some(
1132
+ (a) => a === '--force' || /^-[a-zA-Z]*f[a-zA-Z]*$/.test(a)
1133
+ );
1134
+ if (hasForce) {
1135
+ return {
1136
+ detectorId: 'DET-01',
1137
+ triggered: true,
1138
+ decision: discardDecision,
1139
+ subType: 'GIT_WORKTREE_FORCE_REMOVE',
1140
+ reason:
1141
+ '[Burnoff DET-01 Worktree Destructive Guard] "git worktree remove --force" deletes uncommitted worktree changes (including .claude/worktrees). Commit/stash or remove --force first.'
1142
+ };
1143
+ }
1144
+ }
1145
+
1095
1146
  if (!recentStashActive && !sawGitStashInCommand) {
1096
1147
  if (subcommand === 'checkout') {
1097
1148
  const isBranchCreation = subArgs.some((a) => a === '-b' || a === '-B' || a === '--orphan');
@@ -7,7 +7,7 @@
7
7
  import fs from 'node:fs';
8
8
  import path from 'node:path';
9
9
  import crypto from 'node:crypto';
10
- import { getBurnoffRuntimeDir, getWorkspaceStateDir } from '../config/paths.mjs';
10
+ import { getBurnoffRuntimeDir, getHomeDir, getWorkspaceStateDir } from '../config/paths.mjs';
11
11
  import { atomicWriteJsonSync } from '../storage/atomic-io.mjs';
12
12
  import { withFileLockSync } from '../storage/file-lock.mjs';
13
13
  import { getBreakerStateFilePath, sanitizeBreakerSessionId } from './loop-breaker.mjs';
@@ -20,6 +20,8 @@ export const ALLOWED_SNOOZE_DETECTORS = Object.freeze([
20
20
  'DET-07',
21
21
  'DET-08',
22
22
  'DET-09',
23
+ 'DET-10',
24
+ 'DET-17',
23
25
  '*'
24
26
  ]);
25
27
 
@@ -37,17 +39,56 @@ function readJsonSafe(filePath, fallback = null) {
37
39
  }
38
40
 
39
41
  /**
40
- * Normalizes a detector identifier for ask snooze grants (`DET-01`..`DET-04`, `DET-07`..`DET-09`, or `*`).
41
- * Returns `null` for unsupported or invalid IDs (such as `DET-20` or empty non-default input).
42
+ * Normalizes a detector identifier for ask snooze grants (`DET-01`..`DET-04`, `DET-07`..`DET-10`, `DET-17`, or `*`).
43
+ * Returns `null` for unsupported or invalid IDs (such as `DET-05`, `DET-06`, `DET-20`, or invalid input).
42
44
  */
43
45
  export function normalizeSnoozeDetectorId(raw = '*') {
44
46
  if (raw === undefined || raw === null || raw === '') return '*';
45
47
  const s = String(raw).trim().toUpperCase();
46
48
  if (!s || s === '*' || s === 'ALL') return '*';
47
- if (/^DET-0[1-47-9]$/.test(s)) return s;
49
+ if (/^DET-(?:0[1-47-9]|10|17)$/.test(s)) return s;
48
50
  return null;
49
51
  }
50
52
 
53
+ function jsonFileMentionsBurnoff(filePath, { key = null } = {}) {
54
+ try {
55
+ if (!fs.existsSync(filePath)) return false;
56
+ const parsed = JSON.parse(fs.readFileSync(filePath, 'utf8'));
57
+ if (key) return Boolean(parsed && typeof parsed === 'object' && parsed[key]);
58
+ const text = JSON.stringify(parsed?.hooks || {});
59
+ return text.includes('pre-tool-use.mjs') || text.includes('burnoff-hook-shim.mjs');
60
+ } catch {
61
+ return false; // ignore: unreadable or malformed hook config means that client is not wired
62
+ }
63
+ }
64
+
65
+ /**
66
+ * Resolves which clients an `allow-once` / `snooze` command should write to.
67
+ * Explicit `claude` / `antigravity` / `both` win; `auto` (or omitted) targets every client with
68
+ * Burnoff hooks installed (project or global), falling back to `claude-code`.
69
+ */
70
+ export function resolveSnoozeTargetClients(clientFlag = 'auto', { cwd = process.cwd(), homeDir = null } = {}) {
71
+ const raw = String(clientFlag ?? 'auto').trim().toLowerCase();
72
+ if (raw === 'claude' || raw === 'claude-code') return ['claude-code'];
73
+ if (raw === 'antigravity' || raw === 'ag') return ['antigravity'];
74
+ if (raw === 'both' || raw === 'all') return ['claude-code', 'antigravity'];
75
+
76
+ const baseCwd = path.resolve(String(cwd || process.cwd()));
77
+ const home = homeDir || getHomeDir();
78
+ const claudeActive =
79
+ jsonFileMentionsBurnoff(path.join(baseCwd, '.claude', 'settings.local.json')) ||
80
+ jsonFileMentionsBurnoff(path.join(home, '.claude', 'settings.json'));
81
+ const agActive =
82
+ jsonFileMentionsBurnoff(path.join(baseCwd, '.agents', 'hooks.json'), { key: 'burnoff' }) ||
83
+ jsonFileMentionsBurnoff(path.join(home, '.gemini', 'config', 'hooks.json'), { key: 'burnoff' }) ||
84
+ fs.existsSync(getWorkspaceStateDir(baseCwd, home));
85
+
86
+ const targets = [];
87
+ if (claudeActive) targets.push('claude-code');
88
+ if (agActive) targets.push('antigravity');
89
+ return targets.length > 0 ? targets : ['claude-code'];
90
+ }
91
+
51
92
  /**
52
93
  * Resolves workspace-wide snooze store path `<cacheDir>/burnoff_snoozes.json`.
53
94
  */
@@ -348,6 +389,125 @@ export function consumeMatchingAskSnoozeAtomicSync(
348
389
  return { matched: false };
349
390
  }
350
391
 
392
+ /**
393
+ * Parses a human-readable duration (`15m`, `1h`, `30s`, or bare minutes `15`) into milliseconds.
394
+ * Returns `null` when invalid or non-positive.
395
+ */
396
+ export function parseDurationMs(raw = '15m') {
397
+ if (typeof raw === 'number') {
398
+ return Number.isFinite(raw) && raw > 0 ? Math.round(raw * 60 * 1000) : null;
399
+ }
400
+ const str = String(raw || '').trim().toLowerCase();
401
+ if (!str) return null;
402
+ const m = str.match(/^(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)?$/);
403
+ if (!m) return null;
404
+ const val = Number(m[1]);
405
+ if (!Number.isFinite(val) || val <= 0) return null;
406
+ const unit = m[2] || 'm';
407
+ const mult =
408
+ unit === 'ms'
409
+ ? 1
410
+ : unit === 's'
411
+ ? 1000
412
+ : unit === 'm'
413
+ ? 60_000
414
+ : unit === 'h'
415
+ ? 3_600_000
416
+ : 86_400_000;
417
+ return Math.round(val * mult);
418
+ }
419
+
420
+ /**
421
+ * Sets a timed soft pause on non-Ring-0 `ask` gates, read clamps, and coaches for a workspace.
422
+ * Ring-0 hard blocks (`DET-01`/`DET-02` `deny` / `exitCode: 2`) are NEVER paused.
423
+ */
424
+ export function setWorkspacePauseAtomicSync(
425
+ { durationMs = DEFAULT_SNOOZE_TTL_MS, reason = '', nowMs = Date.now() } = {},
426
+ options = {}
427
+ ) {
428
+ const safeMs = Number.isFinite(Number(durationMs)) && Number(durationMs) > 0
429
+ ? Math.round(Number(durationMs))
430
+ : DEFAULT_SNOOZE_TTL_MS;
431
+ const targetPath = getWorkspaceSnoozeFilePath(options);
432
+ const pauseRecord = {
433
+ createdAtMs: nowMs,
434
+ expiresAtMs: nowMs + safeMs,
435
+ durationMs: safeMs,
436
+ reason: String(reason || '').trim()
437
+ };
438
+
439
+ withFileLockSync(
440
+ targetPath,
441
+ () => {
442
+ const prior = readJsonSafe(targetPath, null);
443
+ const base = prior && typeof prior === 'object' ? { ...prior } : {};
444
+ atomicWriteJsonSync(
445
+ targetPath,
446
+ {
447
+ schemaVersion: '1.0.0',
448
+ ...base,
449
+ softPause: pauseRecord,
450
+ updatedAt: nowMs
451
+ },
452
+ { ...options, maxRetries: Math.max(10, Number(options?.maxRetries || 10)) }
453
+ );
454
+ },
455
+ options
456
+ );
457
+
458
+ return { ok: true, path: targetPath, pause: pauseRecord };
459
+ }
460
+
461
+ /**
462
+ * Returns the active workspace soft-pause status (`{ active: false }` if absent or expired).
463
+ */
464
+ export function getWorkspacePauseStatus({ nowMs = Date.now() } = {}, options = {}) {
465
+ const targetPath = getWorkspaceSnoozeFilePath(options);
466
+ const doc = readJsonSafe(targetPath, null);
467
+ const p = doc?.softPause;
468
+ if (!p || typeof p !== 'object') {
469
+ return { active: false, path: targetPath, expiresAtMs: null, remainingMs: 0 };
470
+ }
471
+ const expiresAtMs = Number(p.expiresAtMs || 0);
472
+ if (!Number.isFinite(expiresAtMs) || expiresAtMs <= nowMs) {
473
+ return { active: false, path: targetPath, expiresAtMs: null, remainingMs: 0 };
474
+ }
475
+ return {
476
+ active: true,
477
+ path: targetPath,
478
+ expiresAtMs,
479
+ remainingMs: expiresAtMs - nowMs,
480
+ reason: p.reason || ''
481
+ };
482
+ }
483
+
484
+ /**
485
+ * Clears any active workspace soft pause immediately.
486
+ */
487
+ export function clearWorkspacePauseAtomicSync(options = {}) {
488
+ const targetPath = getWorkspaceSnoozeFilePath(options);
489
+ if (!fs.existsSync(targetPath)) {
490
+ return { ok: true, cleared: false, path: targetPath };
491
+ }
492
+ let cleared = false;
493
+ withFileLockSync(
494
+ targetPath,
495
+ () => {
496
+ const prior = readJsonSafe(targetPath, null);
497
+ if (!prior || !prior.softPause) return;
498
+ cleared = true;
499
+ const next = { ...prior, updatedAt: Date.now() };
500
+ delete next.softPause;
501
+ atomicWriteJsonSync(targetPath, next, {
502
+ ...options,
503
+ maxRetries: Math.max(10, Number(options?.maxRetries || 10))
504
+ });
505
+ },
506
+ options
507
+ );
508
+ return { ok: true, cleared, path: targetPath };
509
+ }
510
+
351
511
  export default {
352
512
  ALLOWED_SNOOZE_DETECTORS,
353
513
  DEFAULT_ALLOW_ONCE_TTL_MS,
@@ -359,5 +519,9 @@ export default {
359
519
  grantAskSnoozeAtomicSync,
360
520
  listActiveSnoozes,
361
521
  clearAskSnoozesAtomicSync,
362
- consumeMatchingAskSnoozeAtomicSync
522
+ consumeMatchingAskSnoozeAtomicSync,
523
+ parseDurationMs,
524
+ setWorkspacePauseAtomicSync,
525
+ getWorkspacePauseStatus,
526
+ clearWorkspacePauseAtomicSync
363
527
  };
@@ -17,8 +17,21 @@ import {
17
17
  } from './protocol.mjs';
18
18
  import { runPreToolUseHook } from '../guards/pre-tool-engine.mjs';
19
19
  import { runPostToolUseHook } from '../guards/post-tool-engine.mjs';
20
+ import { runUserPromptSubmitHook } from '../guards/prompt-guard.mjs';
20
21
  import { resolveFastDaemonMarkerPath } from './fast-client.mjs';
21
22
 
23
+ const DEFAULT_IDLE_TIMEOUT_MS = 15 * 60 * 1000;
24
+
25
+ function resolveIdleTimeoutMs(options = {}) {
26
+ const raw =
27
+ options.idleTimeoutMs ??
28
+ (process.env.BURNOFF_DAEMON_IDLE_MS !== undefined ? Number(process.env.BURNOFF_DAEMON_IDLE_MS) : undefined);
29
+ if (raw === undefined || raw === null || Number.isNaN(Number(raw))) {
30
+ return DEFAULT_IDLE_TIMEOUT_MS;
31
+ }
32
+ return Math.max(0, Number(raw));
33
+ }
34
+
22
35
  export class BurnoffDaemon {
23
36
  constructor(options = {}) {
24
37
  this.options = options;
@@ -29,11 +42,45 @@ export class BurnoffDaemon {
29
42
  this.activeSockets = new Set();
30
43
  this.sessionQueues = new Map();
31
44
  this.startedAt = null;
45
+ this.lastActivityAt = null;
46
+ this.idleTimeoutMs = resolveIdleTimeoutMs(options);
47
+ this._idleTimer = null;
32
48
  this.requestCount = 0;
33
49
 
34
50
  this._registerDefaultMethods();
35
51
  }
36
52
 
53
+ _armIdleTimer() {
54
+ if (this._idleTimer) {
55
+ clearTimeout(this._idleTimer);
56
+ this._idleTimer = null;
57
+ }
58
+ if (!this.server || !Number.isFinite(this.idleTimeoutMs) || this.idleTimeoutMs <= 0) {
59
+ return;
60
+ }
61
+ const checkDelay = Math.max(50, Math.min(this.idleTimeoutMs, 60_000));
62
+ this._idleTimer = setTimeout(() => {
63
+ this._idleTimer = null;
64
+ if (!this.server) return;
65
+ const idleElapsed = Date.now() - Number(this.lastActivityAt || this.startedAt || Date.now());
66
+ if (idleElapsed >= this.idleTimeoutMs && this.sessionQueues.size === 0) {
67
+ this.close().catch((err) => {
68
+ void err; // ignore: best-effort idle daemon shutdown
69
+ });
70
+ return;
71
+ }
72
+ this._armIdleTimer();
73
+ }, checkDelay);
74
+ if (typeof this._idleTimer.unref === 'function') {
75
+ this._idleTimer.unref();
76
+ }
77
+ }
78
+
79
+ _touchActivity() {
80
+ this.lastActivityAt = Date.now();
81
+ this._armIdleTimer();
82
+ }
83
+
37
84
  /**
38
85
  * Serializes tasks per `sessionId` in FIFO order so concurrent hooks never race on state.
39
86
  */
@@ -61,6 +108,8 @@ export class BurnoffDaemon {
61
108
  pong: true,
62
109
  timestamp: Date.now(),
63
110
  startedAt: this.startedAt,
111
+ lastActivityAt: this.lastActivityAt,
112
+ idleTimeoutMs: this.idleTimeoutMs,
64
113
  requestCount: this.requestCount,
65
114
  platform: process.platform,
66
115
  pid: process.pid,
@@ -112,10 +161,30 @@ export class BurnoffDaemon {
112
161
  });
113
162
  };
114
163
 
164
+ const handleUserPromptSubmit = async (params = {}) => {
165
+ const event = params.event || params.input || params || {};
166
+ const sessionId = String(event.conversationId || event.session_id || event.sessionId || 'default');
167
+ const baseOpts = this.options.cwd && !event.cwd
168
+ ? { persistState: true, cwd: this.options.cwd }
169
+ : { persistState: true };
170
+ const hookOpts = {
171
+ ...baseOpts,
172
+ ...(params.client ? { client: params.client } : {}),
173
+ ...(params.options || {})
174
+ };
175
+
176
+ return this.enqueueSessionTask(sessionId, async () => {
177
+ const res = runUserPromptSubmitHook(event, hookOpts);
178
+ return { fullVerdict: true, ...res };
179
+ });
180
+ };
181
+
115
182
  this.registerMethod('hook.preToolUse', handlePreToolUse);
116
183
  this.registerMethod('hook.postToolUse', handlePostToolUse);
184
+ this.registerMethod('hook.userPromptSubmit', handleUserPromptSubmit);
117
185
  this.registerMethod('hook.claude.preToolUse', handlePreToolUse);
118
186
  this.registerMethod('hook.claude.postToolUse', handlePostToolUse);
187
+ this.registerMethod('hook.claude.userPromptSubmit', handleUserPromptSubmit);
119
188
  }
120
189
 
121
190
  registerMethod(name, handler) {
@@ -200,6 +269,7 @@ export class BurnoffDaemon {
200
269
  }
201
270
 
202
271
  this.requestCount += 1;
272
+ this._touchActivity();
203
273
  try {
204
274
  const result = await handler(msg.params || {}, socket, id);
205
275
  if (!socket.destroyed && id !== null) {
@@ -231,6 +301,8 @@ export class BurnoffDaemon {
231
301
  this.server.once('error', (err) => reject(err));
232
302
  this.server.listen(this.ipcPath, () => {
233
303
  this.startedAt = Date.now();
304
+ this.lastActivityAt = this.startedAt;
305
+ this._armIdleTimer();
234
306
  if (process.platform === 'win32' && !this.options.ipcPath && !process.env.BURNOFF_IPC_PATH) {
235
307
  try {
236
308
  const markerPath = resolveFastDaemonMarkerPath({
@@ -261,6 +333,10 @@ export class BurnoffDaemon {
261
333
  }
262
334
 
263
335
  async close() {
336
+ if (this._idleTimer) {
337
+ clearTimeout(this._idleTimer);
338
+ this._idleTimer = null;
339
+ }
264
340
  for (const socket of this.activeSockets) {
265
341
  try {
266
342
  socket.destroy();