burnoff 1.4.0 → 1.4.1

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.
@@ -0,0 +1,175 @@
1
+ /**
2
+ * @file src/guards/structural-boundaries.mjs
3
+ * Pure structural boundary detector for >=128 KB bounded read clamping (BUG-16).
4
+ * Zero Node built-ins; safe in any ESM runtime.
5
+ */
6
+
7
+ export const UNSTRUCTURED_FALLBACK_LINE_THRESHOLD = 400;
8
+ export const UNSTRUCTURED_SPAN_SIZE = 150;
9
+ export const MIN_STRUCTURAL_BOUNDARIES = 3;
10
+
11
+ const MD_HEADING_RE = /^(#{1,4})\s+(.+?)\s*#*$/;
12
+ const JS_TS_BOUNDARY_RE =
13
+ /^(?:export\s+(?:default\s+)?)?(?:async\s+)?(?:function\*?\s+([A-Za-z_$][\w$]*)|class\s+([A-Za-z_$][\w$]*)|interface\s+([A-Za-z_$][\w$]*)|type\s+([A-Za-z_$][\w$]*)\s*=|(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*(?:async\s*)?(?:\([^)]*\)|[A-Za-z_$][\w$]*)\s*=>)/;
14
+ const PY_BOUNDARY_RE = /^(?:async\s+)?def\s+([A-Za-z_]\w*)|^class\s+([A-Za-z_]\w*)/;
15
+ const GO_BOUNDARY_RE = /^func\s+(?:\([^)]+\)\s*)?([A-Za-z_]\w*)/;
16
+ const RUST_BOUNDARY_RE = /^(?:pub(?:\([^)]+\))?\s+)?(?:async\s+)?(?:fn|struct|enum|trait|impl)\s+([A-Za-z_]\w*)/;
17
+ const JSON_TOP_KEY_RE = /^ {0,2}"([^"\\]{1,120})"\s*:\s*[\[{]/;
18
+ const YAML_TOP_KEY_RE = /^([A-Za-z0-9_.-]{1,120})\s*:(?:\s|$)/;
19
+ const FENCE_RE = /^ {0,3}(`{3,}|~{3,})(.*)$/;
20
+
21
+ /**
22
+ * Matches a structural boundary line (heading, symbol declaration, top-level JSON/YAML key).
23
+ *
24
+ * @param {string} line
25
+ * @param {boolean} [isMarkdownLike=false]
26
+ * @returns {string | null}
27
+ */
28
+ export function matchStructuralBoundary(line, isMarkdownLike = false) {
29
+ const raw = typeof line === 'string' ? line : String(line || '');
30
+ if (!raw || !raw.trim()) return null;
31
+
32
+ if (isMarkdownLike) {
33
+ const md = raw.trimEnd().match(MD_HEADING_RE);
34
+ if (md) return `${md[1]} ${md[2].trim()}`.slice(0, 120);
35
+ }
36
+
37
+ const trimmedRight = raw.trimEnd();
38
+
39
+ if (!/^\s/.test(raw)) {
40
+ const js = trimmedRight.match(JS_TS_BOUNDARY_RE);
41
+ if (js) {
42
+ const name = js[1] || js[2] || js[3] || js[4] || js[5];
43
+ return name ? `sym:${name}` : trimmedRight.slice(0, 80);
44
+ }
45
+ const py = trimmedRight.match(PY_BOUNDARY_RE);
46
+ if (py) {
47
+ const name = py[1] || py[2];
48
+ return name ? `sym:${name}` : trimmedRight.slice(0, 80);
49
+ }
50
+ const go = trimmedRight.match(GO_BOUNDARY_RE);
51
+ if (go) return `func:${go[1]}`;
52
+ const rs = trimmedRight.match(RUST_BOUNDARY_RE);
53
+ if (rs) return `rs:${rs[1]}`;
54
+ }
55
+
56
+ const jsonKey = trimmedRight.match(JSON_TOP_KEY_RE);
57
+ if (jsonKey) {
58
+ return `json:${jsonKey[1]}`;
59
+ }
60
+
61
+ if (!raw.startsWith('#') && !raw.startsWith('-')) {
62
+ const yamlKey = trimmedRight.match(YAML_TOP_KEY_RE);
63
+ if (yamlKey) {
64
+ return `yaml:${yamlKey[1]}`;
65
+ }
66
+ }
67
+
68
+ return null;
69
+ }
70
+
71
+ /**
72
+ * Scans lines for structural boundaries while ignoring lines inside fenced code blocks.
73
+ *
74
+ * @param {string[]} [lines=[]]
75
+ * @param {{ filePath?: string }} [options={}]
76
+ * @returns {{ boundaries: Array<{ lineNum: number, label: string }>, totalLines: number, usedFallback: boolean }}
77
+ */
78
+ export function detectStructuralBoundaries(lines = [], { filePath = '' } = {}) {
79
+ const list = Array.isArray(lines) ? lines : [];
80
+ const isMarkdownLike = /\.(?:md|mdx|markdown)$/i.test(String(filePath || ''));
81
+ const boundaries = [];
82
+
83
+ let activeFenceChar = '';
84
+ let activeFenceLen = 0;
85
+
86
+ for (let i = 0; i < list.length; i += 1) {
87
+ const line = String(list[i] ?? '');
88
+ const fenceMatch = line.match(FENCE_RE);
89
+ if (fenceMatch) {
90
+ const marker = fenceMatch[1];
91
+ const markerChar = marker[0];
92
+ const rest = fenceMatch[2] || '';
93
+ if (!activeFenceChar) {
94
+ activeFenceChar = markerChar;
95
+ activeFenceLen = marker.length;
96
+ continue;
97
+ }
98
+ if (markerChar === activeFenceChar && marker.length >= activeFenceLen && /^\s*$/.test(rest)) {
99
+ activeFenceChar = '';
100
+ activeFenceLen = 0;
101
+ continue;
102
+ }
103
+ }
104
+
105
+ if (activeFenceChar) continue;
106
+
107
+ const label = matchStructuralBoundary(line, isMarkdownLike);
108
+ if (label) {
109
+ boundaries.push({ lineNum: i + 1, label });
110
+ }
111
+ }
112
+
113
+ const totalLines = list.length;
114
+ const usedFallback =
115
+ boundaries.length < MIN_STRUCTURAL_BOUNDARIES && totalLines > UNSTRUCTURED_FALLBACK_LINE_THRESHOLD;
116
+
117
+ return { boundaries, totalLines, usedFallback };
118
+ }
119
+
120
+ /**
121
+ * Selects a clamp end line within `[minLimit, maxLimit]` snapped cleanly before a structural boundary,
122
+ * or falling back to a fixed 150-line span for large unstructured files (>400 lines, <3 boundaries).
123
+ *
124
+ * @param {string[]} [lines=[]]
125
+ * @param {{ filePath?: string, maxLimit?: number, minLimit?: number }} [options={}]
126
+ * @returns {{ endLine: number, snapped: boolean, usedFallback: boolean, boundaryCount: number }}
127
+ */
128
+ export function chooseStructuralClampEndLine(
129
+ lines = [],
130
+ { filePath = '', maxLimit = 250, minLimit = 15 } = {}
131
+ ) {
132
+ const list = Array.isArray(lines) ? lines : [];
133
+ const floorMin = Math.max(1, Number(minLimit) || 15);
134
+ const rawMax = Math.max(1, Math.min(Number(maxLimit) || 250, list.length || Number(maxLimit) || 250));
135
+ const effectiveMax = Math.max(Math.min(floorMin, rawMax), rawMax);
136
+
137
+ const { boundaries, usedFallback } = detectStructuralBoundaries(list, { filePath });
138
+
139
+ if (usedFallback) {
140
+ const endLine = Math.max(Math.min(floorMin, effectiveMax), Math.min(effectiveMax, UNSTRUCTURED_SPAN_SIZE));
141
+ return {
142
+ endLine,
143
+ snapped: true,
144
+ usedFallback: true,
145
+ boundaryCount: boundaries.length
146
+ };
147
+ }
148
+
149
+ if (boundaries.length >= 1) {
150
+ let candidateBoundary = null;
151
+ for (let i = boundaries.length - 1; i >= 0; i -= 1) {
152
+ const b = boundaries[i];
153
+ if (b.lineNum > floorMin && b.lineNum <= effectiveMax + 1) {
154
+ candidateBoundary = b;
155
+ break;
156
+ }
157
+ }
158
+ if (candidateBoundary) {
159
+ const endLine = candidateBoundary.lineNum - 1;
160
+ return {
161
+ endLine,
162
+ snapped: endLine !== effectiveMax,
163
+ usedFallback: false,
164
+ boundaryCount: boundaries.length
165
+ };
166
+ }
167
+ }
168
+
169
+ return {
170
+ endLine: effectiveMax,
171
+ snapped: false,
172
+ usedFallback: false,
173
+ boundaryCount: boundaries.length
174
+ };
175
+ }
@@ -1,255 +1,255 @@
1
- /**
2
- * @file src/ipc/fast-client.mjs
3
- * Minimal zero-heavy-dependency JSON-RPC client for warm Burnoff Daemon IPC checks.
4
- * Imports strictly Node built-ins (`node:fs`, `node:path`, `node:os`, `node:net`, `node:crypto`).
5
- */
6
-
7
- import fs from 'node:fs';
8
- import path from 'node:path';
9
- import os from 'node:os';
10
- import net from 'node:net';
11
- import crypto from 'node:crypto';
12
-
13
- function normalizeHomePath(raw = '') {
14
- return String(raw || '').trim().replace(/\\/g, '/').replace(/\/+$/, '');
15
- }
16
-
17
- /**
18
- * Ensures sandboxed tests overriding `HOME`/`USERPROFILE` never accidentally connect to a live
19
- * host daemon pipe unless `BURNOFF_IPC_PATH` is explicitly set.
20
- */
21
- export function isRealHostHomeEnv(env = process.env) {
22
- if (env && typeof env.BURNOFF_IPC_PATH === 'string' && env.BURNOFF_IPC_PATH.trim()) {
23
- return true;
24
- }
25
- const envHome = normalizeHomePath(env?.USERPROFILE || env?.HOME || '');
26
- if (!envHome) return true;
27
- let realHome = '';
28
- try {
29
- realHome = normalizeHomePath(os.userInfo()?.homedir || '');
30
- } catch (err) {
31
- void err; // ignore: fallback allows connection when userInfo is restricted
32
- return true;
33
- }
34
- if (!realHome) return true;
35
- if (process.platform === 'win32') {
36
- return envHome.toLowerCase() === realHome.toLowerCase();
37
- }
38
- return envHome === realHome;
39
- }
40
-
41
- /**
42
- * Mirrors `resolveIpcPath` from `src/ipc/protocol.mjs` without loading heavyweight modules.
43
- */
44
- export function resolveFastIpcPipePath(options = {}) {
45
- if (options.ipcPath || process.env.BURNOFF_IPC_PATH) {
46
- return String(options.ipcPath || process.env.BURNOFF_IPC_PATH);
47
- }
48
-
49
- const wsTarget = path.resolve(options.cwd || process.cwd());
50
- const wsHash = crypto.createHash('sha1').update(wsTarget.toLowerCase()).digest('hex').slice(0, 10);
51
-
52
- if (process.platform === 'win32') {
53
- let rawUser = process.env.USERNAME || process.env.USER;
54
- if (!rawUser) {
55
- try {
56
- rawUser = typeof os.userInfo === 'function' ? os.userInfo()?.username : null;
57
- } catch (err) {
58
- void err; // ignore: fallback username
59
- rawUser = null;
60
- }
61
- }
62
- const cleanUser = String(rawUser || 'default').replace(/[^a-zA-Z0-9_-]/g, '_');
63
- return `\\\\.\\pipe\\burnoff-${cleanUser}-${wsHash}`;
64
- }
65
-
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');
71
- return path.join(burnoffHome, 'run', `daemon-${wsHash}.sock`);
72
- }
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
-
101
- function sendRawDaemonRpc(method, params = {}, options = {}) {
102
- if (!options.ipcPath && !process.env.BURNOFF_IPC_PATH && !isRealHostHomeEnv()) {
103
- return Promise.resolve(null);
104
- }
105
- const derivedCwd = options.cwd || params?.event?.cwd || params?.input?.cwd || params?.cwd;
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)) {
135
- return Promise.resolve(null);
136
- }
137
-
138
- const connectTimeoutMs = Math.max(1, Number(options.connectTimeoutMs ?? 15));
139
- const requestTimeoutMs = Math.max(20, Number(options.requestTimeoutMs ?? 5000));
140
-
141
- return new Promise((resolve) => {
142
- let settled = false;
143
- let connected = false;
144
- let socket = null;
145
- let connectTimer = null;
146
- let requestTimer = null;
147
- let buffer = '';
148
-
149
- const settle = (val) => {
150
- if (settled) return;
151
- settled = true;
152
- if (connectTimer) {
153
- clearTimeout(connectTimer);
154
- connectTimer = null;
155
- }
156
- if (requestTimer) {
157
- clearTimeout(requestTimer);
158
- requestTimer = null;
159
- }
160
- if (socket) {
161
- try {
162
- socket.removeAllListeners();
163
- socket.destroy();
164
- } catch (cleanupErr) {
165
- void cleanupErr; // ignore: socket cleanup on settle
166
- }
167
- }
168
- resolve(val);
169
- };
170
-
171
- try {
172
- socket = net.connect(pipePath);
173
- } catch (connErr) {
174
- void connErr; // ignore: unavailable daemon socket returns null
175
- settle(null);
176
- return;
177
- }
178
-
179
- connectTimer = setTimeout(() => {
180
- if (!connected) settle(null);
181
- }, connectTimeoutMs);
182
-
183
- requestTimer = setTimeout(() => {
184
- settle(null);
185
- }, requestTimeoutMs);
186
-
187
- socket.once('connect', () => {
188
- connected = true;
189
- if (connectTimer) {
190
- clearTimeout(connectTimer);
191
- connectTimer = null;
192
- }
193
- try {
194
- const frame = JSON.stringify({ jsonrpc: '2.0', id: 1, method: String(method), params }) + '\n';
195
- socket.write(frame);
196
- } catch (writeErr) {
197
- void writeErr; // ignore: broken pipe falls back to cold path
198
- settle(null);
199
- }
200
- });
201
-
202
- socket.on('data', (chunk) => {
203
- buffer += chunk.toString('utf8');
204
- if (buffer.length > 2 * 1024 * 1024) {
205
- settle(null);
206
- return;
207
- }
208
- const nlIdx = buffer.indexOf('\n');
209
- if (nlIdx === -1) return;
210
- const line = buffer.slice(0, nlIdx).trim();
211
- if (!line) {
212
- buffer = buffer.slice(nlIdx + 1);
213
- return;
214
- }
215
- try {
216
- const parsed = JSON.parse(line);
217
- if (parsed && !parsed.error && parsed.result !== undefined) {
218
- settle(parsed.result);
219
- } else {
220
- settle(null);
221
- }
222
- } catch (parseErr) {
223
- void parseErr; // ignore: malformed RPC response falls back to null
224
- settle(null);
225
- }
226
- });
227
-
228
- socket.once('error', () => settle(null));
229
- socket.once('close', () => settle(null));
230
- });
231
- }
232
-
233
- /**
234
- * Sends a JSON-RPC call to the warm daemon (for `daemon.ping`, `daemon.stop`, etc.).
235
- */
236
- export function sendDaemonRpc(method, params = {}, options = {}) {
237
- return sendRawDaemonRpc(method, params, options);
238
- }
239
-
240
- /**
241
- * Attempts a fast hook RPC to the warm Burnoff Daemon pipe.
242
- * Returns `result` strictly when `result?.fullVerdict === true`, otherwise `null`.
243
- */
244
- export async function tryFastDaemonRpc(method, params = {}, options = {}) {
245
- const result = await sendRawDaemonRpc(method, params, options);
246
- return result && result.fullVerdict === true ? result : null;
247
- }
248
-
249
- export default {
250
- isRealHostHomeEnv,
251
- resolveFastIpcPipePath,
252
- resolveFastDaemonMarkerPath,
253
- sendDaemonRpc,
254
- tryFastDaemonRpc
255
- };
1
+ /**
2
+ * @file src/ipc/fast-client.mjs
3
+ * Minimal zero-heavy-dependency JSON-RPC client for warm Burnoff Daemon IPC checks.
4
+ * Imports strictly Node built-ins (`node:fs`, `node:path`, `node:os`, `node:net`, `node:crypto`).
5
+ */
6
+
7
+ import fs from 'node:fs';
8
+ import path from 'node:path';
9
+ import os from 'node:os';
10
+ import net from 'node:net';
11
+ import crypto from 'node:crypto';
12
+
13
+ function normalizeHomePath(raw = '') {
14
+ return String(raw || '').trim().replace(/\\/g, '/').replace(/\/+$/, '');
15
+ }
16
+
17
+ /**
18
+ * Ensures sandboxed tests overriding `HOME`/`USERPROFILE` never accidentally connect to a live
19
+ * host daemon pipe unless `BURNOFF_IPC_PATH` is explicitly set.
20
+ */
21
+ export function isRealHostHomeEnv(env = process.env) {
22
+ if (env && typeof env.BURNOFF_IPC_PATH === 'string' && env.BURNOFF_IPC_PATH.trim()) {
23
+ return true;
24
+ }
25
+ const envHome = normalizeHomePath(env?.USERPROFILE || env?.HOME || '');
26
+ if (!envHome) return true;
27
+ let realHome = '';
28
+ try {
29
+ realHome = normalizeHomePath(os.userInfo()?.homedir || '');
30
+ } catch (err) {
31
+ void err; // ignore: fallback allows connection when userInfo is restricted
32
+ return true;
33
+ }
34
+ if (!realHome) return true;
35
+ if (process.platform === 'win32') {
36
+ return envHome.toLowerCase() === realHome.toLowerCase();
37
+ }
38
+ return envHome === realHome;
39
+ }
40
+
41
+ /**
42
+ * Mirrors `resolveIpcPath` from `src/ipc/protocol.mjs` without loading heavyweight modules.
43
+ */
44
+ export function resolveFastIpcPipePath(options = {}) {
45
+ if (options.ipcPath || process.env.BURNOFF_IPC_PATH) {
46
+ return String(options.ipcPath || process.env.BURNOFF_IPC_PATH);
47
+ }
48
+
49
+ const wsTarget = path.resolve(options.cwd || process.cwd());
50
+ const wsHash = crypto.createHash('sha1').update(wsTarget.toLowerCase()).digest('hex').slice(0, 10);
51
+
52
+ if (process.platform === 'win32') {
53
+ let rawUser = process.env.USERNAME || process.env.USER;
54
+ if (!rawUser) {
55
+ try {
56
+ rawUser = typeof os.userInfo === 'function' ? os.userInfo()?.username : null;
57
+ } catch (err) {
58
+ void err; // ignore: fallback username
59
+ rawUser = null;
60
+ }
61
+ }
62
+ const cleanUser = String(rawUser || 'default').replace(/[^a-zA-Z0-9_-]/g, '_');
63
+ return `\\\\.\\pipe\\burnoff-${cleanUser}-${wsHash}`;
64
+ }
65
+
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');
71
+ return path.join(burnoffHome, 'run', `daemon-${wsHash}.sock`);
72
+ }
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
+
101
+ function sendRawDaemonRpc(method, params = {}, options = {}) {
102
+ if (!options.ipcPath && !options.homeDir && !process.env.BURNOFF_IPC_PATH && !isRealHostHomeEnv()) {
103
+ return Promise.resolve(null);
104
+ }
105
+ const derivedCwd = options.cwd || params?.event?.cwd || params?.input?.cwd || params?.cwd;
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)) {
135
+ return Promise.resolve(null);
136
+ }
137
+
138
+ const connectTimeoutMs = Math.max(1, Number(options.connectTimeoutMs ?? 15));
139
+ const requestTimeoutMs = Math.max(20, Number(options.requestTimeoutMs ?? 5000));
140
+
141
+ return new Promise((resolve) => {
142
+ let settled = false;
143
+ let connected = false;
144
+ let socket = null;
145
+ let connectTimer = null;
146
+ let requestTimer = null;
147
+ let buffer = '';
148
+
149
+ const settle = (val) => {
150
+ if (settled) return;
151
+ settled = true;
152
+ if (connectTimer) {
153
+ clearTimeout(connectTimer);
154
+ connectTimer = null;
155
+ }
156
+ if (requestTimer) {
157
+ clearTimeout(requestTimer);
158
+ requestTimer = null;
159
+ }
160
+ if (socket) {
161
+ try {
162
+ socket.removeAllListeners();
163
+ socket.destroy();
164
+ } catch (cleanupErr) {
165
+ void cleanupErr; // ignore: socket cleanup on settle
166
+ }
167
+ }
168
+ resolve(val);
169
+ };
170
+
171
+ try {
172
+ socket = net.connect(pipePath);
173
+ } catch (connErr) {
174
+ void connErr; // ignore: unavailable daemon socket returns null
175
+ settle(null);
176
+ return;
177
+ }
178
+
179
+ connectTimer = setTimeout(() => {
180
+ if (!connected) settle(null);
181
+ }, connectTimeoutMs);
182
+
183
+ requestTimer = setTimeout(() => {
184
+ settle(null);
185
+ }, requestTimeoutMs);
186
+
187
+ socket.once('connect', () => {
188
+ connected = true;
189
+ if (connectTimer) {
190
+ clearTimeout(connectTimer);
191
+ connectTimer = null;
192
+ }
193
+ try {
194
+ const frame = JSON.stringify({ jsonrpc: '2.0', id: 1, method: String(method), params }) + '\n';
195
+ socket.write(frame);
196
+ } catch (writeErr) {
197
+ void writeErr; // ignore: broken pipe falls back to cold path
198
+ settle(null);
199
+ }
200
+ });
201
+
202
+ socket.on('data', (chunk) => {
203
+ buffer += chunk.toString('utf8');
204
+ if (buffer.length > 2 * 1024 * 1024) {
205
+ settle(null);
206
+ return;
207
+ }
208
+ const nlIdx = buffer.indexOf('\n');
209
+ if (nlIdx === -1) return;
210
+ const line = buffer.slice(0, nlIdx).trim();
211
+ if (!line) {
212
+ buffer = buffer.slice(nlIdx + 1);
213
+ return;
214
+ }
215
+ try {
216
+ const parsed = JSON.parse(line);
217
+ if (parsed && !parsed.error && parsed.result !== undefined) {
218
+ settle(parsed.result);
219
+ } else {
220
+ settle(null);
221
+ }
222
+ } catch (parseErr) {
223
+ void parseErr; // ignore: malformed RPC response falls back to null
224
+ settle(null);
225
+ }
226
+ });
227
+
228
+ socket.once('error', () => settle(null));
229
+ socket.once('close', () => settle(null));
230
+ });
231
+ }
232
+
233
+ /**
234
+ * Sends a JSON-RPC call to the warm daemon (for `daemon.ping`, `daemon.stop`, etc.).
235
+ */
236
+ export function sendDaemonRpc(method, params = {}, options = {}) {
237
+ return sendRawDaemonRpc(method, params, options);
238
+ }
239
+
240
+ /**
241
+ * Attempts a fast hook RPC to the warm Burnoff Daemon pipe.
242
+ * Returns `result` strictly when `result?.fullVerdict === true`, otherwise `null`.
243
+ */
244
+ export async function tryFastDaemonRpc(method, params = {}, options = {}) {
245
+ const result = await sendRawDaemonRpc(method, params, options);
246
+ return result && result.fullVerdict === true ? result : null;
247
+ }
248
+
249
+ export default {
250
+ isRealHostHomeEnv,
251
+ resolveFastIpcPipePath,
252
+ resolveFastDaemonMarkerPath,
253
+ sendDaemonRpc,
254
+ tryFastDaemonRpc
255
+ };