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
@@ -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
 
@@ -0,0 +1,258 @@
1
+ /**
2
+ * @file src/storage/antigravity-parser.mjs
3
+ * Parser and discovery helpers for Google Antigravity `transcript.jsonl` logs.
4
+ * Emits the same `steps[]` contract consumed by `audit.mjs`, `pr-cost.mjs`, and `team-digest.mjs`.
5
+ */
6
+
7
+ import fs from 'node:fs';
8
+ import path from 'node:path';
9
+ import { getHomeDir, resolveAntigravityConfigPaths } from '../config/paths.mjs';
10
+
11
+ function unwrapQuotedArgString(val) {
12
+ if (typeof val !== 'string') return val;
13
+ const trimmed = val.trim();
14
+ if (trimmed.length >= 2 && trimmed.startsWith('"') && trimmed.endsWith('"')) {
15
+ try {
16
+ const unquoted = JSON.parse(trimmed);
17
+ if (typeof unquoted === 'string') return unquoted;
18
+ } catch {
19
+ // ignore: keep original string if not valid JSON-escaped string
20
+ }
21
+ }
22
+ return val;
23
+ }
24
+
25
+ function normalizeToolCallArgs(args) {
26
+ if (!args || typeof args !== 'object' || Array.isArray(args)) return {};
27
+ const out = {};
28
+ for (const [k, v] of Object.entries(args)) {
29
+ out[k] = unwrapQuotedArgString(v);
30
+ }
31
+ return out;
32
+ }
33
+
34
+ function normalizeToolCalls(rawCalls = []) {
35
+ if (!Array.isArray(rawCalls)) return [];
36
+ return rawCalls
37
+ .filter((c) => c && typeof c === 'object')
38
+ .map((c) => ({
39
+ name: String(c.name || ''),
40
+ args: normalizeToolCallArgs(c.args || c.arguments || {})
41
+ }));
42
+ }
43
+
44
+ function extractSessionTitleFromUserInput(rawContent = '') {
45
+ const cleaned = String(rawContent || '')
46
+ .replace(/<\/?USER_REQUEST>/gi, '')
47
+ .replace(/\s+/g, ' ')
48
+ .trim();
49
+ return cleaned.slice(0, 80);
50
+ }
51
+
52
+ /**
53
+ * Returns true if the given JSONL string or parsed lines match Antigravity's transcript schema.
54
+ */
55
+ export function isAntigravityTranscriptContent(jsonlLinesOrContent = '') {
56
+ const lines = Array.isArray(jsonlLinesOrContent)
57
+ ? jsonlLinesOrContent
58
+ : String(jsonlLinesOrContent || '').split(/\r?\n/);
59
+
60
+ for (const raw of lines) {
61
+ if (!raw) continue;
62
+ let obj = raw;
63
+ if (typeof raw === 'string') {
64
+ const trimmed = raw.trim();
65
+ if (!trimmed) continue;
66
+ try {
67
+ obj = JSON.parse(trimmed);
68
+ } catch {
69
+ continue; // ignore: skip malformed line when probing transcript format
70
+ }
71
+ }
72
+ if (!obj || typeof obj !== 'object') continue;
73
+ if (
74
+ typeof obj.step_index === 'number' &&
75
+ (obj.type === 'USER_INPUT' || obj.type === 'PLANNER_RESPONSE' || obj.type === 'GENERIC')
76
+ ) {
77
+ return true;
78
+ }
79
+ if (obj.type === 'PLANNER_RESPONSE' && (obj.input_tokens !== undefined || obj.cache_read_tokens !== undefined)) {
80
+ return true;
81
+ }
82
+ }
83
+ return false;
84
+ }
85
+
86
+ /**
87
+ * Reads the head of a file to determine whether it is an Antigravity `transcript.jsonl`.
88
+ */
89
+ export function isAntigravityTranscriptFile(filePath) {
90
+ if (!filePath || !fs.existsSync(filePath)) return false;
91
+ let fd = null;
92
+ try {
93
+ const stat = fs.statSync(filePath);
94
+ if (!stat.isFile() || stat.size === 0) return false;
95
+ const probeLen = Math.min(stat.size, 8192);
96
+ const buf = Buffer.alloc(probeLen);
97
+ fd = fs.openSync(filePath, 'r');
98
+ const bytesRead = fs.readSync(fd, buf, 0, probeLen, 0);
99
+ return isAntigravityTranscriptContent(buf.subarray(0, bytesRead).toString('utf8'));
100
+ } catch {
101
+ return false; // ignore: unreadable file falls back to false
102
+ } finally {
103
+ if (fd !== null) {
104
+ try { fs.closeSync(fd); } catch { /* ignore: fd close guard */ }
105
+ }
106
+ }
107
+ }
108
+
109
+ /**
110
+ * Parses an Antigravity `transcript.jsonl` string or file path into Burnoff's normalized `steps[]` contract.
111
+ */
112
+ export function parseAntigravityTranscript(filePathOrContent = '', options = {}) {
113
+ let rawContent = '';
114
+ let resolvedPath = null;
115
+ if (
116
+ typeof filePathOrContent === 'string' &&
117
+ !filePathOrContent.includes('\n') &&
118
+ fs.existsSync(filePathOrContent)
119
+ ) {
120
+ resolvedPath = path.resolve(filePathOrContent);
121
+ rawContent = fs.readFileSync(resolvedPath, 'utf8');
122
+ } else {
123
+ rawContent = String(filePathOrContent || '');
124
+ }
125
+
126
+ const lines = rawContent.split(/\r?\n/).filter((l) => l.trim().length > 0);
127
+ const steps = [];
128
+ let sessionTitle = '';
129
+ let lastModel = null;
130
+ const toolsUsedSet = new Set();
131
+
132
+ for (let i = 0; i < lines.length; i += 1) {
133
+ let entry = null;
134
+ try {
135
+ entry = JSON.parse(lines[i]);
136
+ } catch {
137
+ continue; // ignore: skip malformed JSONL line
138
+ }
139
+ if (!entry || typeof entry !== 'object') continue;
140
+
141
+ if (entry.type === 'USER_INPUT' && !sessionTitle && entry.content) {
142
+ sessionTitle = extractSessionTitleFromUserInput(entry.content);
143
+ }
144
+
145
+ if (entry.type !== 'PLANNER_RESPONSE') continue;
146
+
147
+ const freshInputTokens = Math.max(0, Number(entry.input_tokens ?? entry.inputTokens ?? 0));
148
+ const cacheReadTokens = Math.max(0, Number(entry.cache_read_tokens ?? entry.cacheReadTokens ?? 0));
149
+ const outputTokens = Math.max(0, Number(entry.output_tokens ?? entry.outputTokens ?? 0));
150
+ const thinkingTokens = Math.max(0, Number(entry.thinking_tokens ?? entry.thinkingTokens ?? 0));
151
+ const totalPromptTokens = freshInputTokens + cacheReadTokens;
152
+ const model = entry.model ? String(entry.model) : lastModel;
153
+ if (model) lastModel = model;
154
+
155
+ const toolCalls = normalizeToolCalls(entry.tool_calls || entry.toolCalls || []);
156
+ for (const tc of toolCalls) {
157
+ if (tc.name) toolsUsedSet.add(tc.name);
158
+ }
159
+
160
+ steps.push({
161
+ stepIndex: Number.isFinite(Number(entry.step_index)) ? Number(entry.step_index) : steps.length,
162
+ type: 'assistant',
163
+ rawType: entry.type,
164
+ client: 'antigravity',
165
+ entrypoint: 'antigravity',
166
+ createdAt: entry.created_at || entry.createdAt || null,
167
+ model,
168
+ freshInputTokens,
169
+ cacheReadTokens,
170
+ cacheCreationTokens: 0,
171
+ outputTokens,
172
+ thinkingTokens,
173
+ totalPromptTokens,
174
+ tokenUsage: {
175
+ freshInputTokens,
176
+ inputTokens: freshInputTokens,
177
+ cacheReadTokens,
178
+ cacheCreationTokens: 0,
179
+ outputTokens,
180
+ thinkingTokens
181
+ },
182
+ toolCalls
183
+ });
184
+ }
185
+
186
+ return {
187
+ schemaRev: 1,
188
+ client: 'antigravity',
189
+ filePath: resolvedPath,
190
+ sessionId: options.sessionId || (resolvedPath ? path.basename(path.dirname(path.dirname(path.dirname(resolvedPath)))) : 'antigravity-session'),
191
+ sessionTitle,
192
+ entrypoint: 'antigravity',
193
+ toolsUsed: Array.from(toolsUsedSet),
194
+ steps
195
+ };
196
+ }
197
+
198
+ /**
199
+ * Discovers local Google Antigravity `transcript.jsonl` files across CLI, 2.0 App, and IDE brain directories.
200
+ */
201
+ export function discoverAntigravityTranscripts(homeDirOrOptions = getHomeDir(), extraOptions = {}) {
202
+ const opts =
203
+ homeDirOrOptions && typeof homeDirOrOptions === 'object'
204
+ ? homeDirOrOptions
205
+ : { homeDir: homeDirOrOptions, ...extraOptions };
206
+ const homeDir = opts.homeDir || getHomeDir();
207
+ const cwd = opts.cwd || process.cwd();
208
+ const brainDirs = Array.isArray(opts.brainDirs)
209
+ ? opts.brainDirs
210
+ : resolveAntigravityConfigPaths({ homeDir, cwd }).brainDirs;
211
+
212
+ const discovered = [];
213
+ const seenFiles = new Set();
214
+
215
+ for (const brainDir of brainDirs) {
216
+ if (!brainDir || !fs.existsSync(brainDir)) continue;
217
+ let convDirs = [];
218
+ try {
219
+ convDirs = fs.readdirSync(brainDir, { withFileTypes: true }).filter((e) => e.isDirectory());
220
+ } catch {
221
+ continue; // ignore: unreadable brain directory
222
+ }
223
+
224
+ for (const convDir of convDirs) {
225
+ const candidates = [
226
+ path.join(brainDir, convDir.name, '.system_generated', 'logs', 'transcript.jsonl'),
227
+ path.join(brainDir, convDir.name, 'transcript.jsonl')
228
+ ];
229
+ for (const filePath of candidates) {
230
+ if (!fs.existsSync(filePath) || seenFiles.has(filePath)) continue;
231
+ seenFiles.add(filePath);
232
+ try {
233
+ const st = fs.statSync(filePath);
234
+ if (!st.isFile() || st.size === 0) continue;
235
+ discovered.push({
236
+ filePath,
237
+ sessionId: convDir.name,
238
+ projectSlug: 'antigravity',
239
+ client: 'antigravity',
240
+ mtimeMs: st.mtimeMs
241
+ });
242
+ } catch {
243
+ // ignore: unreadable transcript metadata
244
+ }
245
+ }
246
+ }
247
+ }
248
+
249
+ discovered.sort((a, b) => (b.mtimeMs || 0) - (a.mtimeMs || 0));
250
+ return discovered;
251
+ }
252
+
253
+ export default {
254
+ isAntigravityTranscriptContent,
255
+ isAntigravityTranscriptFile,
256
+ parseAntigravityTranscript,
257
+ discoverAntigravityTranscripts
258
+ };
@@ -2,7 +2,7 @@ import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
 
4
4
  const RETRYABLE_RENAME_CODES = new Set(['EPERM', 'EBUSY', 'EACCES']);
5
- const MAX_RENAME_ATTEMPTS = 5;
5
+ const MAX_RENAME_ATTEMPTS = 8;
6
6
 
7
7
  const atomicIoMetrics = {
8
8
  renameRetries: 0,
@@ -85,7 +85,7 @@ export function atomicWriteFileSync(targetPath, content, options = {}) {
85
85
  offset += written;
86
86
  }
87
87
 
88
- if (typeof fsMod.fsyncSync === 'function') {
88
+ if (!opts.skipFsync && typeof fsMod.fsyncSync === 'function') {
89
89
  fsMod.fsyncSync(fd);
90
90
  }
91
91
  fsMod.closeSync(fd);
@@ -18,8 +18,9 @@ export const LOCK_ORDER_DOC = Object.freeze([
18
18
  'ledger_dedupe'
19
19
  ]);
20
20
 
21
- const DEFAULT_MAX_WAIT_MS = 1500;
21
+ const DEFAULT_MAX_WAIT_MS = 2500;
22
22
  const DEFAULT_STALE_MS = 5000;
23
+ const MIN_STALE_MS = 5000;
23
24
 
24
25
  function isPidAlive(pid) {
25
26
  const num = Number(pid);
@@ -37,7 +38,7 @@ function inspectLockFile(lockPath, staleMs, fsMod) {
37
38
  try {
38
39
  const raw = fsMod.readFileSync(lockPath, 'utf8');
39
40
  const parsed = JSON.parse(raw);
40
- const createdAtMs = Number(parsed?.createdAtMs || 0);
41
+ const createdAtMs = Number(parsed?.createdAtMs ?? parsed?.createdAt ?? 0);
41
42
  const pid = Number(parsed?.pid || 0);
42
43
  const ageMs = createdAtMs > 0 ? Date.now() - createdAtMs : Infinity;
43
44
  const staleByAge = ageMs > staleMs;
@@ -90,8 +91,12 @@ export function withFileLockSync(targetPath, fn, options = {}) {
90
91
 
91
92
  const fsMod = options.fsModule || fs;
92
93
  const maxWaitMs = Math.max(50, Number(options.maxWaitMs ?? DEFAULT_MAX_WAIT_MS));
93
- const staleMs = Math.max(250, Number(options.staleMs ?? DEFAULT_STALE_MS));
94
- const onTimeout = options.onTimeout === 'throw' ? 'throw' : 'fail-open';
94
+ const rawStaleMs = Number(options.staleMs ?? options.staleLockAgeMs ?? DEFAULT_STALE_MS);
95
+ const staleMs = Math.max(MIN_STALE_MS, Number.isFinite(rawStaleMs) ? rawStaleMs : DEFAULT_STALE_MS);
96
+ const onTimeout =
97
+ options.onTimeout === 'throw' || options.onTimeout === 'fail-open'
98
+ ? options.onTimeout
99
+ : 'skip';
95
100
 
96
101
  const resolvedTarget = path.resolve(targetPath);
97
102
  const lockPath = `${resolvedTarget}.lock`;
@@ -127,7 +132,8 @@ export function withFileLockSync(targetPath, fn, options = {}) {
127
132
  (err?.code === 'EPERM' || err?.code === 'EBUSY' || err?.code === 'EACCES'));
128
133
  if (!isContentionErr) {
129
134
  if (onTimeout === 'throw') throw err;
130
- return fn();
135
+ if (onTimeout === 'fail-open') return fn();
136
+ return options.fallbackValue !== undefined ? options.fallbackValue : null;
131
137
  }
132
138
 
133
139
  const info = inspectLockFile(lockPath, staleMs, fsMod);
@@ -150,24 +156,54 @@ export function withFileLockSync(targetPath, fn, options = {}) {
150
156
  if (onTimeout === 'throw') {
151
157
  throw new Error(`Timed out waiting for file lock: ${lockPath} (${maxWaitMs}ms)`);
152
158
  }
153
- return fn();
159
+ if (onTimeout === 'fail-open') {
160
+ return fn();
161
+ }
162
+ return options.fallbackValue !== undefined ? options.fallbackValue : null;
154
163
  }
155
164
 
156
165
  try {
157
166
  return fn();
158
167
  } finally {
159
168
  try {
160
- const currentRaw = fsMod.readFileSync(lockPath, 'utf8');
161
- const current = JSON.parse(currentRaw);
169
+ let currentRaw = null;
170
+ for (let rAttempt = 0; rAttempt < 8; rAttempt += 1) {
171
+ try {
172
+ currentRaw = fsMod.readFileSync(lockPath, 'utf8');
173
+ break;
174
+ } catch (readErr) {
175
+ if (
176
+ rAttempt < 7 &&
177
+ (readErr?.code === 'EPERM' || readErr?.code === 'EBUSY' || readErr?.code === 'EACCES')
178
+ ) {
179
+ sleepSync(5);
180
+ continue;
181
+ }
182
+ break;
183
+ }
184
+ }
185
+ const current = currentRaw ? JSON.parse(currentRaw) : null;
162
186
  if (current?.nonce === nonce) {
163
- for (let uAttempt = 0; uAttempt < 4; uAttempt += 1) {
187
+ const relPath = `${lockPath}.rel.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2, 6)}`;
188
+ let released = false;
189
+ for (let rAttempt = 0; rAttempt < 10; rAttempt += 1) {
164
190
  try {
165
- fsMod.unlinkSync(lockPath);
191
+ fsMod.renameSync(lockPath, relPath);
192
+ released = true;
193
+ try {
194
+ fsMod.unlinkSync(relPath);
195
+ } catch {
196
+ // ignore: renamed release tombstone cleanup best-effort
197
+ }
166
198
  break;
167
- } catch (unlinkErr) {
199
+ } catch (relErr) {
200
+ if (relErr?.code === 'ENOENT') {
201
+ released = true;
202
+ break;
203
+ }
168
204
  if (
169
- uAttempt < 3 &&
170
- (unlinkErr?.code === 'EPERM' || unlinkErr?.code === 'EBUSY' || unlinkErr?.code === 'EACCES')
205
+ rAttempt < 9 &&
206
+ (relErr?.code === 'EPERM' || relErr?.code === 'EBUSY' || relErr?.code === 'EACCES')
171
207
  ) {
172
208
  sleepSync(5);
173
209
  continue;
@@ -175,6 +211,23 @@ export function withFileLockSync(targetPath, fn, options = {}) {
175
211
  break;
176
212
  }
177
213
  }
214
+ if (!released) {
215
+ for (let uAttempt = 0; uAttempt < 8; uAttempt += 1) {
216
+ try {
217
+ fsMod.unlinkSync(lockPath);
218
+ break;
219
+ } catch (unlinkErr) {
220
+ if (
221
+ uAttempt < 7 &&
222
+ (unlinkErr?.code === 'EPERM' || unlinkErr?.code === 'EBUSY' || unlinkErr?.code === 'EACCES')
223
+ ) {
224
+ sleepSync(5);
225
+ continue;
226
+ }
227
+ break;
228
+ }
229
+ }
230
+ }
178
231
  }
179
232
  } catch {
180
233
  // ignore: lock already released or vanished