burnoff 1.1.0 → 1.3.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 (45) hide show
  1. package/.claude-plugin/plugin.json +11 -0
  2. package/.github/workflows/burnoff-pr-gate.yml +3 -3
  3. package/.github/workflows/burnoff-startup-lint.yml +37 -0
  4. package/README.md +90 -75
  5. package/bin/burnoff.mjs +185 -24
  6. package/commands/burnoff.md +16 -0
  7. package/docs/CLAUDE_CODE_PLUGIN.md +67 -0
  8. package/docs/DESIGN_PARTNER_INTAKE.md +44 -0
  9. package/hooks/hook-io.mjs +19 -7
  10. package/hooks/post-tool-use.mjs +33 -26
  11. package/hooks/pre-tool-use.mjs +43 -41
  12. package/hooks/session-lifecycle.mjs +40 -0
  13. package/package.json +15 -7
  14. package/scripts/burnoff-statusline.mjs +84 -0
  15. package/src/ci/ci-gate.mjs +22 -0
  16. package/src/ci/pr-cost.mjs +42 -10
  17. package/src/ci/team-digest.mjs +5 -3
  18. package/src/cli/audit.mjs +103 -18
  19. package/src/cli/doctor.mjs +209 -14
  20. package/src/cli/init.mjs +349 -96
  21. package/src/cli/startup-audit.mjs +712 -62
  22. package/src/clients/antigravity.mjs +285 -0
  23. package/src/clients/claude-code.mjs +180 -0
  24. package/src/clients/detect.mjs +64 -0
  25. package/src/config/loader.mjs +11 -4
  26. package/src/config/paths.mjs +62 -2
  27. package/src/config/policy.mjs +34 -5
  28. package/src/config/pricing.mjs +16 -5
  29. package/src/guards/loop-breaker.mjs +198 -13
  30. package/src/guards/post-tool-engine.mjs +289 -29
  31. package/src/guards/pre-tool-engine.mjs +382 -151
  32. package/src/guards/read-clamp.mjs +78 -18
  33. package/src/guards/session-hook.mjs +207 -0
  34. package/src/guards/shell-guard.mjs +583 -73
  35. package/src/guards/snooze.mjs +360 -0
  36. package/src/ipc/daemon.mjs +50 -8
  37. package/src/ipc/fast-client.mjs +62 -5
  38. package/src/ipc/protocol.mjs +1 -1
  39. package/src/storage/antigravity-parser.mjs +258 -0
  40. package/src/storage/file-lock.mjs +13 -4
  41. package/src/storage/fts5-archive.mjs +4 -4
  42. package/src/storage/jsonl-parser.mjs +7 -1
  43. package/src/storage/ledger.mjs +10 -3
  44. package/src/storage/sqlite-client.mjs +4 -2
  45. package/hooks/hooks.json +0 -12
@@ -0,0 +1,360 @@
1
+ /**
2
+ * @file src/guards/snooze.mjs
3
+ * Session- and workspace-scoped `allow-once` / timed snooze grants for interactive `ask` gates.
4
+ * Security invariant: grants NEVER bypass `deny` / `exitCode: 2` Ring-0 hard blocks.
5
+ */
6
+
7
+ import fs from 'node:fs';
8
+ import path from 'node:path';
9
+ import crypto from 'node:crypto';
10
+ import { getBurnoffRuntimeDir, getWorkspaceStateDir } from '../config/paths.mjs';
11
+ import { atomicWriteJsonSync } from '../storage/atomic-io.mjs';
12
+ import { withFileLockSync } from '../storage/file-lock.mjs';
13
+ import { getBreakerStateFilePath, sanitizeBreakerSessionId } from './loop-breaker.mjs';
14
+
15
+ export const ALLOWED_SNOOZE_DETECTORS = Object.freeze([
16
+ 'DET-01',
17
+ 'DET-02',
18
+ 'DET-03',
19
+ 'DET-04',
20
+ '*'
21
+ ]);
22
+
23
+ export const DEFAULT_ALLOW_ONCE_TTL_MS = 30 * 60 * 1000;
24
+ export const DEFAULT_SNOOZE_TTL_MS = 15 * 60 * 1000;
25
+ const MAX_SNOOZES_STORED = 32;
26
+
27
+ function readJsonSafe(filePath, fallback = null) {
28
+ try {
29
+ if (!fs.existsSync(filePath)) return fallback;
30
+ return JSON.parse(fs.readFileSync(filePath, 'utf8'));
31
+ } catch {
32
+ return fallback; // ignore: corrupt or missing snooze file falls back cleanly
33
+ }
34
+ }
35
+
36
+ /**
37
+ * Normalizes a detector identifier for ask snooze grants (`DET-01`..`DET-04` or `*`).
38
+ * Returns `null` for unsupported or invalid IDs (such as `DET-20` or empty non-default input).
39
+ */
40
+ export function normalizeSnoozeDetectorId(raw = '*') {
41
+ if (raw === undefined || raw === null || raw === '') return '*';
42
+ const s = String(raw).trim().toUpperCase();
43
+ if (!s || s === '*' || s === 'ALL') return '*';
44
+ if (/^DET-0[1-4]$/.test(s)) return s;
45
+ return null;
46
+ }
47
+
48
+ /**
49
+ * Resolves workspace-wide snooze store path `<cacheDir>/burnoff_snoozes.json`.
50
+ */
51
+ export function getWorkspaceSnoozeFilePath(options = {}) {
52
+ if (options?.snoozeFilePath) {
53
+ return path.resolve(String(options.snoozeFilePath));
54
+ }
55
+ if (options?.client === 'antigravity') {
56
+ const wsCwd = options?.cwd ? path.resolve(String(options.cwd)) : process.cwd();
57
+ return path.join(getWorkspaceStateDir(wsCwd, options.homeDir), 'burnoff_snoozes.json');
58
+ }
59
+ if (options?.cwd) {
60
+ return path.join(path.resolve(String(options.cwd)), '.claude', 'cache', 'burnoff_snoozes.json');
61
+ }
62
+ if (options?.useRuntimeDir) {
63
+ return path.join(getBurnoffRuntimeDir(options.homeDir || null), 'burnoff_snoozes.json');
64
+ }
65
+ return path.join(process.cwd(), '.claude', 'cache', 'burnoff_snoozes.json');
66
+ }
67
+
68
+ /**
69
+ * Removes expired (`expiresAtMs <= nowMs`) or exhausted (`remaining <= 0`) snooze entries.
70
+ */
71
+ export function pruneExpiredSnoozes(snoozes = [], nowMs = Date.now()) {
72
+ if (!Array.isArray(snoozes)) return [];
73
+ return snoozes.filter((entry) => {
74
+ if (!entry || typeof entry !== 'object') return false;
75
+ const expiresAt = Number(entry.expiresAtMs || 0);
76
+ if (!Number.isFinite(expiresAt) || expiresAt <= nowMs) return false;
77
+ if (entry.remaining !== null && entry.remaining !== undefined) {
78
+ const rem = Number(entry.remaining);
79
+ if (!Number.isFinite(rem) || rem <= 0) return false;
80
+ }
81
+ return true;
82
+ });
83
+ }
84
+
85
+ function normalizeScopeString(val = '') {
86
+ return String(val || '').replace(/\\/g, '/').trim().toLowerCase();
87
+ }
88
+
89
+ /**
90
+ * Returns true if an active snooze entry matches the detector and optional target scope.
91
+ */
92
+ export function matchesSnoozeEntry(entry, { detectorId, target = '', nowMs = Date.now() } = {}) {
93
+ if (!entry || typeof entry !== 'object') return false;
94
+ const det = normalizeSnoozeDetectorId(detectorId);
95
+ if (!det || det === '*') return false;
96
+
97
+ const expiresAt = Number(entry.expiresAtMs || 0);
98
+ if (!Number.isFinite(expiresAt) || expiresAt <= nowMs) return false;
99
+ if (entry.remaining !== null && entry.remaining !== undefined) {
100
+ const rem = Number(entry.remaining);
101
+ if (!Number.isFinite(rem) || rem <= 0) return false;
102
+ }
103
+
104
+ const entryDet = normalizeSnoozeDetectorId(entry.detectorId || '*');
105
+ if (!entryDet || (entryDet !== '*' && entryDet !== det)) return false;
106
+
107
+ const scope = normalizeScopeString(entry.scope || '*');
108
+ if (!scope || scope === '*') return true;
109
+
110
+ const normTarget = normalizeScopeString(target);
111
+ return normTarget.includes(scope);
112
+ }
113
+
114
+ function normalizeGrantInput({
115
+ detectorId = '*',
116
+ scope = '*',
117
+ count = 1,
118
+ ttlMs = DEFAULT_ALLOW_ONCE_TTL_MS,
119
+ reason = '',
120
+ nowMs = Date.now()
121
+ } = {}) {
122
+ const normalizedDet = normalizeSnoozeDetectorId(detectorId);
123
+ if (!normalizedDet) {
124
+ throw new Error(`Unsupported detectorId "${detectorId}". Allowed: ${ALLOWED_SNOOZE_DETECTORS.join(', ')}`);
125
+ }
126
+ const finiteTtl = Number(ttlMs);
127
+ const safeTtlMs = Number.isFinite(finiteTtl) && finiteTtl > 0 ? finiteTtl : DEFAULT_ALLOW_ONCE_TTL_MS;
128
+ const remaining =
129
+ count === null || count === undefined
130
+ ? null
131
+ : Math.max(1, Math.floor(Number(count) || 1));
132
+
133
+ return {
134
+ id: crypto.randomUUID(),
135
+ detectorId: normalizedDet,
136
+ scope: String(scope || '*').trim() || '*',
137
+ remaining,
138
+ reason: String(reason || '').trim(),
139
+ createdAtMs: nowMs,
140
+ expiresAtMs: nowMs + safeTtlMs
141
+ };
142
+ }
143
+
144
+ /**
145
+ * Atomically grants an `allow-once` or timed snooze override.
146
+ * Stores inside `burnoff_breaker_state_<sessionId>.json` when `sessionId` is supplied,
147
+ * otherwise inside workspace-scoped `burnoff_snoozes.json`.
148
+ */
149
+ export function grantAskSnoozeAtomicSync(
150
+ {
151
+ sessionId = null,
152
+ detectorId = '*',
153
+ scope = '*',
154
+ count = 1,
155
+ ttlMs = DEFAULT_ALLOW_ONCE_TTL_MS,
156
+ reason = '',
157
+ nowMs = Date.now()
158
+ } = {},
159
+ options = {}
160
+ ) {
161
+ const grant = normalizeGrantInput({ detectorId, scope, count, ttlMs, reason, nowMs });
162
+ const hasSession = typeof sessionId === 'string' && sessionId.trim().length > 0;
163
+ const targetPath = hasSession
164
+ ? getBreakerStateFilePath(sessionId, options)
165
+ : getWorkspaceSnoozeFilePath(options);
166
+
167
+ withFileLockSync(
168
+ targetPath,
169
+ () => {
170
+ const prior = readJsonSafe(targetPath, null);
171
+ const base = prior && typeof prior === 'object' ? { ...prior } : {};
172
+ const pruned = pruneExpiredSnoozes(base.snoozes || [], nowMs);
173
+ const nextSnoozes = [...pruned, grant].slice(-MAX_SNOOZES_STORED);
174
+ const next = hasSession
175
+ ? {
176
+ schemaVersion: '1.0.0',
177
+ ...base,
178
+ sessionId: sanitizeBreakerSessionId(sessionId),
179
+ snoozes: nextSnoozes,
180
+ updatedAt: nowMs
181
+ }
182
+ : {
183
+ schemaVersion: '1.0.0',
184
+ snoozes: nextSnoozes,
185
+ updatedAt: nowMs
186
+ };
187
+ atomicWriteJsonSync(targetPath, next, {
188
+ ...options,
189
+ maxRetries: Math.max(10, Number(options?.maxRetries || 10))
190
+ });
191
+ },
192
+ options
193
+ );
194
+
195
+ return {
196
+ ok: true,
197
+ target: hasSession ? 'session' : 'workspace',
198
+ path: targetPath,
199
+ grant
200
+ };
201
+ }
202
+
203
+ /**
204
+ * Lists currently active (non-expired, non-exhausted) snoozes for session and/or workspace.
205
+ */
206
+ export function listActiveSnoozes({ sessionId = null, nowMs = Date.now() } = {}, options = {}) {
207
+ const entries = [];
208
+ if (typeof sessionId === 'string' && sessionId.trim().length > 0) {
209
+ const sessPath = getBreakerStateFilePath(sessionId, options);
210
+ const sessDoc = readJsonSafe(sessPath, null);
211
+ for (const entry of pruneExpiredSnoozes(sessDoc?.snoozes || [], nowMs)) {
212
+ entries.push({ ...entry, source: 'session', path: sessPath });
213
+ }
214
+ }
215
+ const wsPath = getWorkspaceSnoozeFilePath(options);
216
+ const wsDoc = readJsonSafe(wsPath, null);
217
+ for (const entry of pruneExpiredSnoozes(wsDoc?.snoozes || [], nowMs)) {
218
+ entries.push({ ...entry, source: 'workspace', path: wsPath });
219
+ }
220
+ return entries;
221
+ }
222
+
223
+ /**
224
+ * Atomically clears snoozes from session and/or workspace stores.
225
+ */
226
+ export function clearAskSnoozesAtomicSync({ sessionId = null, detectorId = null } = {}, options = {}) {
227
+ const filterDet = detectorId ? normalizeSnoozeDetectorId(detectorId) : null;
228
+ if (detectorId && !filterDet) {
229
+ throw new Error(`Unsupported detectorId "${detectorId}". Allowed: ${ALLOWED_SNOOZE_DETECTORS.join(', ')}`);
230
+ }
231
+
232
+ let clearedCount = 0;
233
+ const targets = [getWorkspaceSnoozeFilePath(options)];
234
+ if (typeof sessionId === 'string' && sessionId.trim().length > 0) {
235
+ targets.unshift(getBreakerStateFilePath(sessionId, options));
236
+ }
237
+
238
+ for (const targetPath of targets) {
239
+ if (!fs.existsSync(targetPath)) continue;
240
+ withFileLockSync(
241
+ targetPath,
242
+ () => {
243
+ const prior = readJsonSafe(targetPath, null);
244
+ if (!prior || !Array.isArray(prior.snoozes) || prior.snoozes.length === 0) return;
245
+ const kept =
246
+ !filterDet || filterDet === '*'
247
+ ? []
248
+ : prior.snoozes.filter((e) => normalizeSnoozeDetectorId(e?.detectorId || '*') !== filterDet);
249
+ clearedCount += prior.snoozes.length - kept.length;
250
+ if (kept.length !== prior.snoozes.length) {
251
+ atomicWriteJsonSync(
252
+ targetPath,
253
+ { ...prior, snoozes: kept, updatedAt: Date.now() },
254
+ { ...options, maxRetries: Math.max(10, Number(options?.maxRetries || 10)) }
255
+ );
256
+ }
257
+ },
258
+ options
259
+ );
260
+ }
261
+
262
+ return { ok: true, clearedCount };
263
+ }
264
+
265
+ function tryConsumeFromFileSync(filePath, sourceLabel, { detectorId, target = '', nowMs = Date.now() }, options = {}) {
266
+ if (!filePath || !fs.existsSync(filePath)) return null;
267
+ // Quick lock-free pre-check on parsed JSON so non-snoozed files skip lock overhead cleanly
268
+ const quickSnap = readJsonSafe(filePath, null);
269
+ const quickList = pruneExpiredSnoozes(quickSnap?.snoozes || [], nowMs);
270
+ if (!quickList.some((entry) => matchesSnoozeEntry(entry, { detectorId, target, nowMs }))) {
271
+ return null;
272
+ }
273
+
274
+ let consumed = null;
275
+ withFileLockSync(
276
+ filePath,
277
+ () => {
278
+ const prior = readJsonSafe(filePath, null);
279
+ if (!prior || typeof prior !== 'object') return;
280
+ const active = pruneExpiredSnoozes(prior.snoozes || [], nowMs);
281
+ const idx = active.findIndex((entry) => matchesSnoozeEntry(entry, { detectorId, target, nowMs }));
282
+ if (idx === -1) return;
283
+
284
+ const matchedEntry = { ...active[idx] };
285
+ const nextList = [...active];
286
+ if (matchedEntry.remaining !== null && matchedEntry.remaining !== undefined) {
287
+ const nextRemaining = Number(matchedEntry.remaining) - 1;
288
+ if (nextRemaining <= 0) {
289
+ nextList.splice(idx, 1);
290
+ } else {
291
+ nextList[idx] = { ...matchedEntry, remaining: nextRemaining };
292
+ }
293
+ }
294
+
295
+ atomicWriteJsonSync(
296
+ filePath,
297
+ {
298
+ ...prior,
299
+ snoozes: nextList,
300
+ updatedAt: nowMs
301
+ },
302
+ { ...options, maxRetries: Math.max(10, Number(options?.maxRetries || 10)) }
303
+ );
304
+ consumed = matchedEntry;
305
+ },
306
+ options
307
+ );
308
+
309
+ return consumed ? { matched: true, source: sourceLabel, grant: consumed } : null;
310
+ }
311
+
312
+ /**
313
+ * Checks session breaker state first and workspace snooze store second for an active grant
314
+ * matching an `ask` verdict. Atomically consumes one use when `remaining` is finite.
315
+ */
316
+ export function consumeMatchingAskSnoozeAtomicSync(
317
+ { sessionId = 'default', detectorId, target = '', nowMs = Date.now() } = {},
318
+ options = {}
319
+ ) {
320
+ const det = normalizeSnoozeDetectorId(detectorId);
321
+ if (!det || det === '*') {
322
+ return { matched: false };
323
+ }
324
+
325
+ if (typeof sessionId === 'string' && sessionId.trim().length > 0) {
326
+ const sessPath = getBreakerStateFilePath(sessionId, options);
327
+ const sessMatch = tryConsumeFromFileSync(
328
+ sessPath,
329
+ 'session',
330
+ { detectorId: det, target, nowMs },
331
+ options
332
+ );
333
+ if (sessMatch) return sessMatch;
334
+ }
335
+
336
+ const wsPath = getWorkspaceSnoozeFilePath(options);
337
+ const wsMatch = tryConsumeFromFileSync(
338
+ wsPath,
339
+ 'workspace',
340
+ { detectorId: det, target, nowMs },
341
+ options
342
+ );
343
+ if (wsMatch) return wsMatch;
344
+
345
+ return { matched: false };
346
+ }
347
+
348
+ export default {
349
+ ALLOWED_SNOOZE_DETECTORS,
350
+ DEFAULT_ALLOW_ONCE_TTL_MS,
351
+ DEFAULT_SNOOZE_TTL_MS,
352
+ normalizeSnoozeDetectorId,
353
+ getWorkspaceSnoozeFilePath,
354
+ pruneExpiredSnoozes,
355
+ matchesSnoozeEntry,
356
+ grantAskSnoozeAtomicSync,
357
+ listActiveSnoozes,
358
+ clearAskSnoozesAtomicSync,
359
+ consumeMatchingAskSnoozeAtomicSync
360
+ };
@@ -17,11 +17,13 @@ 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 { resolveFastDaemonMarkerPath } from './fast-client.mjs';
20
21
 
21
22
  export class BurnoffDaemon {
22
23
  constructor(options = {}) {
23
24
  this.options = options;
24
25
  this.ipcPath = resolveIpcPath(options);
26
+ this.markerPath = null;
25
27
  this.server = null;
26
28
  this.methods = new Map();
27
29
  this.activeSockets = new Set();
@@ -74,33 +76,46 @@ export class BurnoffDaemon {
74
76
  return { stopping: true, pid: process.pid };
75
77
  });
76
78
 
77
- this.registerMethod('hook.claude.preToolUse', async (params = {}) => {
79
+ const handlePreToolUse = async (params = {}) => {
78
80
  const event = params.event || params.input || params || {};
79
- const sessionId = String(event.session_id || event.sessionId || 'default');
81
+ const sessionId = String(event.conversationId || event.session_id || event.sessionId || 'default');
80
82
  const baseOpts = this.options.cwd && !event.cwd
81
83
  ? { persistState: true, cwd: this.options.cwd }
82
84
  : { persistState: true };
83
- const hookOpts = { ...baseOpts, ...(params.options || {}) };
85
+ const hookOpts = {
86
+ ...baseOpts,
87
+ ...(params.client ? { client: params.client } : {}),
88
+ ...(params.options || {})
89
+ };
84
90
 
85
91
  return this.enqueueSessionTask(sessionId, async () => {
86
92
  const res = runPreToolUseHook(event, hookOpts);
87
93
  return { fullVerdict: true, ...res };
88
94
  });
89
- });
95
+ };
90
96
 
91
- this.registerMethod('hook.claude.postToolUse', async (params = {}) => {
97
+ const handlePostToolUse = async (params = {}) => {
92
98
  const event = params.event || params.input || params || {};
93
- const sessionId = String(event.session_id || event.sessionId || 'default');
99
+ const sessionId = String(event.conversationId || event.session_id || event.sessionId || 'default');
94
100
  const baseOpts = this.options.cwd && !event.cwd
95
101
  ? { persistState: true, cwd: this.options.cwd }
96
102
  : { persistState: true };
97
- const hookOpts = { ...baseOpts, ...(params.options || {}) };
103
+ const hookOpts = {
104
+ ...baseOpts,
105
+ ...(params.client ? { client: params.client } : {}),
106
+ ...(params.options || {})
107
+ };
98
108
 
99
109
  return this.enqueueSessionTask(sessionId, async () => {
100
110
  const res = runPostToolUseHook(event, hookOpts);
101
111
  return { fullVerdict: true, ...res };
102
112
  });
103
- });
113
+ };
114
+
115
+ this.registerMethod('hook.preToolUse', handlePreToolUse);
116
+ this.registerMethod('hook.postToolUse', handlePostToolUse);
117
+ this.registerMethod('hook.claude.preToolUse', handlePreToolUse);
118
+ this.registerMethod('hook.claude.postToolUse', handlePostToolUse);
104
119
  }
105
120
 
106
121
  registerMethod(name, handler) {
@@ -216,6 +231,23 @@ export class BurnoffDaemon {
216
231
  this.server.once('error', (err) => reject(err));
217
232
  this.server.listen(this.ipcPath, () => {
218
233
  this.startedAt = Date.now();
234
+ if (process.platform === 'win32' && !this.options.ipcPath && !process.env.BURNOFF_IPC_PATH) {
235
+ try {
236
+ const markerPath = resolveFastDaemonMarkerPath({
237
+ cwd: this.options.cwd,
238
+ homeDir: this.options.homeDir
239
+ });
240
+ fs.mkdirSync(path.dirname(markerPath), { recursive: true });
241
+ fs.writeFileSync(
242
+ markerPath,
243
+ JSON.stringify({ pid: process.pid, ipcPath: this.ipcPath, startedAt: this.startedAt }),
244
+ 'utf8'
245
+ );
246
+ this.markerPath = markerPath;
247
+ } catch (err) {
248
+ void err; // ignore: non-fatal Windows daemon marker write
249
+ }
250
+ }
219
251
  if (process.platform !== 'win32') {
220
252
  try {
221
253
  fs.chmodSync(this.ipcPath, 0o600);
@@ -246,6 +278,16 @@ export class BurnoffDaemon {
246
278
  const srv = this.server;
247
279
  this.server = null;
248
280
  srv.close(() => {
281
+ if (this.markerPath) {
282
+ try {
283
+ if (fs.existsSync(this.markerPath)) {
284
+ fs.unlinkSync(this.markerPath);
285
+ }
286
+ } catch (err) {
287
+ void err; // ignore: best-effort Windows daemon marker unlink on shutdown
288
+ }
289
+ this.markerPath = null;
290
+ }
249
291
  if (process.platform !== 'win32') {
250
292
  try {
251
293
  if (fs.existsSync(this.ipcPath)) {
@@ -63,19 +63,75 @@ export function resolveFastIpcPipePath(options = {}) {
63
63
  return `\\\\.\\pipe\\burnoff-${cleanUser}-${wsHash}`;
64
64
  }
65
65
 
66
- const burnoffHome = process.env.BURNOFF_HOME
67
- ? path.resolve(process.env.BURNOFF_HOME)
68
- : path.join(options.homeDir || process.env.HOME || os.homedir() || '/tmp', '.burnoff');
66
+ const burnoffHome = options.homeDir
67
+ ? path.join(path.resolve(options.homeDir), '.burnoff')
68
+ : process.env.BURNOFF_HOME
69
+ ? path.resolve(process.env.BURNOFF_HOME)
70
+ : path.join(process.env.HOME || os.homedir() || '/tmp', '.burnoff');
69
71
  return path.join(burnoffHome, 'run', `daemon-${wsHash}.sock`);
70
72
  }
71
73
 
74
+ function isPidAliveFast(pid) {
75
+ const num = Number(pid);
76
+ if (!Number.isInteger(num) || num <= 0) return false;
77
+ try {
78
+ process.kill(num, 0);
79
+ return true;
80
+ } catch (err) {
81
+ if (err?.code === 'EPERM') return true;
82
+ return false;
83
+ }
84
+ }
85
+
86
+ /**
87
+ * Resolves the workspace-scoped Windows daemon readiness marker (`<BURNOFF_HOME>/run/daemon-<wsHash>.pid`)
88
+ * so cold hook invocations can verify daemon absence synchronously in <1ms without named-pipe connect timeouts.
89
+ */
90
+ export function resolveFastDaemonMarkerPath(options = {}) {
91
+ const wsTarget = path.resolve(options.cwd || process.cwd());
92
+ const wsHash = crypto.createHash('sha1').update(wsTarget.toLowerCase()).digest('hex').slice(0, 10);
93
+ const burnoffHome = options.homeDir
94
+ ? path.join(path.resolve(options.homeDir), '.burnoff')
95
+ : process.env.BURNOFF_HOME
96
+ ? path.resolve(process.env.BURNOFF_HOME)
97
+ : path.join(process.env.USERPROFILE || process.env.HOME || os.homedir() || '/tmp', '.burnoff');
98
+ return path.join(burnoffHome, 'run', `daemon-${wsHash}.pid`);
99
+ }
100
+
72
101
  function sendRawDaemonRpc(method, params = {}, options = {}) {
73
102
  if (!options.ipcPath && !process.env.BURNOFF_IPC_PATH && !isRealHostHomeEnv()) {
74
103
  return Promise.resolve(null);
75
104
  }
76
105
  const derivedCwd = options.cwd || params?.event?.cwd || params?.input?.cwd || params?.cwd;
77
- const pipePath = resolveFastIpcPipePath({ ...options, ...(derivedCwd ? { cwd: derivedCwd } : {}) });
78
- if (!pipePath || (process.platform !== 'win32' && !fs.existsSync(pipePath))) {
106
+ const effectiveOptions = derivedCwd ? { ...options, cwd: derivedCwd } : options;
107
+ const pipePath = resolveFastIpcPipePath(effectiveOptions);
108
+ if (!pipePath) {
109
+ return Promise.resolve(null);
110
+ }
111
+ if (process.platform === 'win32') {
112
+ if (!options.ipcPath && !process.env.BURNOFF_IPC_PATH) {
113
+ const markerPath = resolveFastDaemonMarkerPath(effectiveOptions);
114
+ if (!markerPath || !fs.existsSync(markerPath)) {
115
+ return Promise.resolve(null);
116
+ }
117
+ let alive = false;
118
+ try {
119
+ const parsed = JSON.parse(fs.readFileSync(markerPath, 'utf8'));
120
+ alive = isPidAliveFast(parsed?.pid);
121
+ } catch (err) {
122
+ void err; // ignore: unreadable daemon marker treated as stale
123
+ alive = false;
124
+ }
125
+ if (!alive) {
126
+ try {
127
+ fs.unlinkSync(markerPath);
128
+ } catch (unlinkErr) {
129
+ void unlinkErr; // ignore: best-effort stale daemon marker cleanup
130
+ }
131
+ return Promise.resolve(null);
132
+ }
133
+ }
134
+ } else if (!fs.existsSync(pipePath)) {
79
135
  return Promise.resolve(null);
80
136
  }
81
137
 
@@ -193,6 +249,7 @@ export async function tryFastDaemonRpc(method, params = {}, options = {}) {
193
249
  export default {
194
250
  isRealHostHomeEnv,
195
251
  resolveFastIpcPipePath,
252
+ resolveFastDaemonMarkerPath,
196
253
  sendDaemonRpc,
197
254
  tryFastDaemonRpc
198
255
  };
@@ -53,7 +53,7 @@ export function resolveIpcPath(options = {}) {
53
53
  return `\\\\.\\pipe\\burnoff-${cleanUser}-${wsHash}`;
54
54
  }
55
55
 
56
- const runDir = getBurnoffRunDir(options.homeDir || getHomeDir());
56
+ const runDir = getBurnoffRunDir(options.homeDir || null);
57
57
  return path.join(runDir, `daemon-${wsHash}.sock`);
58
58
  }
59
59