-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkernel-bridge.js
More file actions
541 lines (494 loc) · 16.3 KB
/
kernel-bridge.js
File metadata and controls
541 lines (494 loc) · 16.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
/**
* WP-155 — Kernel bridge helper module.
*
* Implements the Phase 6 Wave 0 WP-150 kernel-bridge integration contract as
* the ONLY place in VRE allowed to spawn the sibling kernel's
* `plugin/scripts/core-reader-cli.js`. Produces a typed-duck reader whose
* shape matches what middleware.deriveSignals, orchestrator lanes and the
* `bin/vre` dispatcher already consume.
*
* Spawn ergonomics mirror environment/evals/measure-context-baseline.js
* (stdin-JSON, stdout-JSON, stderr capture, typed error on non-zero exit).
* Timeout + SIGTERM/SIGKILL pattern mirrors
* environment/orchestrator/executors/local-subprocess.js.
*
* @see blueprints/definitive-spec/implementation-plan/phase6-01-wave-0-contracts-and-scope.md WP-150
* @see blueprints/definitive-spec/implementation-plan/phase6-02-wave-1-kernel-bridge-integration.md WP-155
*/
import { spawn } from 'node:child_process';
import { existsSync } from 'node:fs';
import path from 'node:path';
export const DEFAULT_TIMEOUT_MS = 10_000; // WP-150 default
export const SIGKILL_GRACE_MS = 2_000;
export const MAX_STDERR_BYTES = 4 * 1024;
export const KERNEL_PROJECTION_SCHEMA_VERSION = 'wp150.typed-duck.v1';
// Copied from environment/orchestrator/executors/local-subprocess.js:7-20 per
// WP-155 rule (prefer copy to avoid deep refactor scope). If this list ever
// grows in local-subprocess.js, this copy must be updated in tandem.
const DEFAULT_ENV_WHITELIST = Object.freeze([
'PATH',
'HOME',
'USERPROFILE',
'APPDATA',
'LOCALAPPDATA',
'SystemRoot',
'SYSTEMROOT',
'TEMP',
'TMP',
'LANG',
'LC_ALL',
'LC_CTYPE',
]);
export const WP150_TYPED_DUCK_PROJECTION_COUNT = 8;
// The eight projections frozen in WP-150's typed-duck contract.
const PROJECTION_NAMES = Object.freeze([
'listClaimHeads',
'listUnresolvedClaims',
'listCitationChecks',
'getProjectOverview',
'listLiteratureSearches',
'listObserverAlerts',
'listGateChecks',
'getStateSnapshot',
]);
export const KERNEL_PROJECTION_NAMES = PROJECTION_NAMES;
const KERNEL_BRIDGE_META = Symbol('vreKernelBridgeMeta');
export class KernelBridgeError extends Error {
constructor(message, options = {}) {
super(message, options);
this.name = 'KernelBridgeError';
if (options.projection) this.projection = options.projection;
if (options.stderr) this.stderr = options.stderr;
if (typeof options.exitCode === 'number') this.exitCode = options.exitCode;
if (options.sourceMode) this.sourceMode = options.sourceMode;
if (options.degradedReason) this.degradedReason = options.degradedReason;
}
}
export class KernelBridgeUnavailableError extends KernelBridgeError {
constructor(message, options = {}) {
super(message, options);
this.name = 'KernelBridgeUnavailableError';
}
}
export class KernelBridgeContractMismatchError extends KernelBridgeError {
constructor(message, options = {}) {
super(message, options);
this.name = 'KernelBridgeContractMismatchError';
}
}
export class KernelBridgeTimeoutError extends KernelBridgeError {
constructor(message, options = {}) {
super(message, options);
this.name = 'KernelBridgeTimeoutError';
if (options.timeoutPhase) this.timeoutPhase = options.timeoutPhase;
}
}
function sanitizeEnv(passthrough = [], overrideEnv = null) {
const src = overrideEnv ?? process.env;
const allow = new Set([...DEFAULT_ENV_WHITELIST, ...passthrough]);
const env = Object.create(null);
for (const key of allow) {
if (src[key] !== undefined) {
env[key] = src[key];
}
}
return env;
}
function truncateStderr(buffers) {
const joined = Buffer.concat(buffers);
if (joined.length <= MAX_STDERR_BYTES) {
return joined.toString('utf8');
}
return (
joined.slice(0, MAX_STDERR_BYTES).toString('utf8') +
`\n...[truncated ${joined.length - MAX_STDERR_BYTES} bytes]`
);
}
function attachKernelBridgeMeta(value, meta) {
if (value != null && (typeof value === 'object' || typeof value === 'function')) {
Object.defineProperty(value, KERNEL_BRIDGE_META, {
value: Object.freeze({ ...meta }),
enumerable: false,
configurable: false,
});
}
return value;
}
export function getKernelBridgeMeta(value) {
return value?.[KERNEL_BRIDGE_META] ?? {
dbAvailable: true,
sourceMode: 'kernel-backed',
degradedReason: null,
};
}
function normalizeEnvelopeMeta(envelope) {
const dbAvailable = envelope.dbAvailable !== false;
const sourceMode =
typeof envelope.sourceMode === 'string' && envelope.sourceMode.length > 0
? envelope.sourceMode
: (dbAvailable ? 'kernel-backed' : 'degraded');
const degradedReason =
typeof envelope.degradedReason === 'string' && envelope.degradedReason.length > 0
? envelope.degradedReason
: null;
return { dbAvailable, sourceMode, degradedReason };
}
/**
* Spawn the kernel CLI for a single projection call.
*
* @param {object} args
* @param {string} args.cliPath Absolute path to core-reader-cli.js
* @param {string} args.kernelRoot Sibling root used as spawn cwd
* @param {string} args.projection Projection name (also passed as argv[1])
* @param {object} args.stdinPayload JSON payload written to child stdin
* @param {number} args.timeoutMs Per-projection timeout in ms
* @param {string[]} args.envPassthrough Extra env keys to forward
* @param {boolean} [args.allowDegraded=false] Permit ok:true degraded envelopes
* @returns {Promise<object>} The envelope's `data` field on success
*/
function invokeCoreReaderCli({
cliPath,
kernelRoot,
projection,
stdinPayload,
timeoutMs,
envPassthrough,
allowDegraded = false,
}) {
return new Promise((resolve, reject) => {
const env = sanitizeEnv(envPassthrough);
let child;
try {
child = spawn(process.execPath, [cliPath, projection], {
cwd: kernelRoot,
stdio: ['pipe', 'pipe', 'pipe'],
env,
shell: false,
});
} catch (error) {
if (error && error.code === 'ENOENT') {
reject(
new KernelBridgeUnavailableError(
`kernel-bridge: core-reader-cli not spawnable: ${error.message}`,
{ projection, cause: error },
),
);
return;
}
reject(
new KernelBridgeError(
`kernel-bridge: spawn failed: ${error.message}`,
{ projection, cause: error },
),
);
return;
}
const stdoutChunks = [];
const stderrChunks = [];
let timeoutPhase = null;
let timedOut = false;
let killTimer = null;
const clearKillTimer = () => {
if (killTimer) clearTimeout(killTimer);
};
const sigtermTimer = setTimeout(() => {
timedOut = true;
timeoutPhase = 'sigterm';
try {
child.kill('SIGTERM');
} catch {
// ignore — child may already be dead
}
killTimer = setTimeout(() => {
timeoutPhase = 'sigkill';
try {
child.kill('SIGKILL');
} catch {
// ignore
}
}, SIGKILL_GRACE_MS);
}, timeoutMs);
child.on('error', (error) => {
clearTimeout(sigtermTimer);
clearKillTimer();
if (error && error.code === 'ENOENT') {
reject(
new KernelBridgeUnavailableError(
`kernel-bridge: core-reader-cli not found: ${error.message}`,
{ projection, cause: error, stderr: truncateStderr(stderrChunks) },
),
);
return;
}
reject(
new KernelBridgeError(
`kernel-bridge: child error: ${error.message}`,
{ projection, cause: error, stderr: truncateStderr(stderrChunks) },
),
);
});
child.stdout.on('data', (chunk) => stdoutChunks.push(chunk));
child.stderr.on('data', (chunk) => stderrChunks.push(chunk));
child.on('close', (exitCode, signal) => {
clearTimeout(sigtermTimer);
clearKillTimer();
const stderrText = truncateStderr(stderrChunks);
if (timedOut) {
reject(
new KernelBridgeTimeoutError(
`kernel-bridge: projection "${projection}" timed out after ${timeoutMs}ms (${timeoutPhase}).`,
{ projection, stderr: stderrText, timeoutPhase },
),
);
return;
}
if (typeof exitCode === 'number' && exitCode !== 0) {
reject(
new KernelBridgeContractMismatchError(
`kernel-bridge: projection "${projection}" exited with code ${exitCode}.`,
{ projection, stderr: stderrText, exitCode },
),
);
return;
}
if (signal) {
reject(
new KernelBridgeError(
`kernel-bridge: projection "${projection}" terminated by signal ${signal}.`,
{ projection, stderr: stderrText },
),
);
return;
}
const raw = Buffer.concat(stdoutChunks).toString('utf8').trim();
let envelope;
try {
envelope = JSON.parse(raw);
} catch (error) {
reject(
new KernelBridgeContractMismatchError(
`kernel-bridge: projection "${projection}" stdout is not valid JSON: ${error.message}`,
{ projection, stderr: stderrText, cause: error },
),
);
return;
}
if (envelope == null || typeof envelope !== 'object' || Array.isArray(envelope)) {
reject(
new KernelBridgeContractMismatchError(
`kernel-bridge: projection "${projection}" stdout must be a JSON object envelope.`,
{ projection, stderr: stderrText },
),
);
return;
}
if (envelope.ok === false) {
reject(
new KernelBridgeError(
`kernel-bridge: projection "${projection}" reported kernel error: ${envelope.error ?? '<no error message>'}.`,
{
projection,
stderr: stderrText,
cause: new Error(String(envelope.error ?? 'unknown kernel error')),
},
),
);
return;
}
if (envelope.ok !== true) {
reject(
new KernelBridgeContractMismatchError(
`kernel-bridge: projection "${projection}" envelope missing ok:true flag.`,
{ projection, stderr: stderrText },
),
);
return;
}
if (envelope.projection !== projection) {
reject(
new KernelBridgeContractMismatchError(
`kernel-bridge: envelope projection "${envelope.projection}" does not match requested "${projection}".`,
{ projection, stderr: stderrText },
),
);
return;
}
if (typeof envelope.projectPath !== 'string' || envelope.projectPath.length === 0) {
reject(
new KernelBridgeContractMismatchError(
`kernel-bridge: envelope for "${projection}" missing projectPath.`,
{ projection, stderr: stderrText },
),
);
return;
}
if (envelope.data === undefined) {
reject(
new KernelBridgeContractMismatchError(
`kernel-bridge: envelope for "${projection}" missing data field.`,
{ projection, stderr: stderrText },
),
);
return;
}
const meta = normalizeEnvelopeMeta(envelope);
if (!allowDegraded && (meta.sourceMode !== 'kernel-backed' || !meta.dbAvailable)) {
reject(
new KernelBridgeUnavailableError(
`kernel-bridge: projection "${projection}" returned ${meta.sourceMode} kernel data: ${meta.degradedReason ?? 'kernel data unavailable'}.`,
{
projection,
stderr: stderrText,
sourceMode: meta.sourceMode,
degradedReason: meta.degradedReason ?? 'kernel data unavailable',
},
),
);
return;
}
resolve(attachKernelBridgeMeta(envelope.data, meta));
});
try {
child.stdin.end(JSON.stringify(stdinPayload ?? {}) + '\n');
} catch (error) {
clearTimeout(sigtermTimer);
clearKillTimer();
reject(
new KernelBridgeError(
`kernel-bridge: stdin write failed: ${error.message}`,
{ projection, cause: error },
),
);
}
});
}
/**
* Resolve a typed-duck reader that talks to the sibling kernel via
* `plugin/scripts/core-reader-cli.js`.
*
* If `kernelRoot` is absent OR the CLI path does not exist on disk, returns
* the degraded sentinel `{dbAvailable: false, error: <reason>}` matching
* bin/vre:resolveDefaultReader — callers keep their Phase 5.7 fallback.
*
* @param {object} options
* @param {string | null | undefined} options.kernelRoot Sibling root (VRE_KERNEL_PATH)
* @param {number} [options.timeoutMs=10000] Per-projection timeout
* @param {string[]} [options.envPassthrough=[]] Extra env keys to forward
* @param {string} [options.projectPath] Optional default projectPath for calls
* @returns {Promise<object>} reader
*/
export async function resolveKernelReader({
kernelRoot,
timeoutMs = DEFAULT_TIMEOUT_MS,
envPassthrough = [],
projectPath = null,
} = {}) {
if (!kernelRoot || typeof kernelRoot !== 'string') {
return {
dbAvailable: false,
error: 'CLI default: no reader provided',
};
}
const cliPath = path.resolve(kernelRoot, 'plugin', 'scripts', 'core-reader-cli.js');
if (!existsSync(cliPath)) {
return {
dbAvailable: false,
error: `core-reader CLI unavailable at ${cliPath}`,
};
}
const resolvedKernelRoot = path.resolve(kernelRoot);
const defaultProjectPath =
typeof projectPath === 'string' && projectPath.length > 0
? projectPath
: resolvedKernelRoot;
let readerDbAvailable = true;
let readerError = null;
try {
const probe = await invokeCoreReaderCli({
cliPath,
kernelRoot: resolvedKernelRoot,
projection: 'getProjectOverview',
stdinPayload: { projectPath: defaultProjectPath },
timeoutMs,
envPassthrough,
allowDegraded: true,
});
const meta = getKernelBridgeMeta(probe);
readerDbAvailable = meta.dbAvailable && meta.sourceMode === 'kernel-backed';
readerError = readerDbAvailable
? null
: (meta.degradedReason ?? `kernel reader sourceMode=${meta.sourceMode}`);
} catch (error) {
return {
dbAvailable: false,
error: error?.message ?? String(error),
};
}
const callProjection = async (projection, options = {}) => {
const payload = {
projectPath: options.projectPath ?? defaultProjectPath,
...options,
};
const data = await invokeCoreReaderCli({
cliPath,
kernelRoot: resolvedKernelRoot,
projection,
stdinPayload: payload,
timeoutMs,
envPassthrough,
});
const meta = getKernelBridgeMeta(data);
reader.dbAvailable = meta.dbAvailable && meta.sourceMode === 'kernel-backed';
reader.error = reader.dbAvailable
? null
: (meta.degradedReason ?? `kernel reader sourceMode=${meta.sourceMode}`);
return data;
};
const reader = {
dbAvailable: readerDbAvailable,
error: readerError,
close() {
// WP-155 rule: close is a no-op; bridge is stateless, each call re-spawns.
},
};
for (const projection of PROJECTION_NAMES) {
reader[projection] = (options = {}) => callProjection(projection, options);
}
return reader;
}
/**
* Test-only helper exposed so WP-156/WP-157 can exercise trigger projections
* (e.g. __bridge_test_timeout__) without the nine-projection binding loop
* getting in the way. Not part of the WP-150 runtime contract — marked with
* a leading underscore and excluded from the typed-duck reader.
*/
export async function __spawnProjectionForTest({
kernelRoot,
projection,
stdinPayload = { projectPath: path.resolve(kernelRoot ?? '.') },
timeoutMs = DEFAULT_TIMEOUT_MS,
envPassthrough = [],
}) {
if (!kernelRoot) {
throw new KernelBridgeUnavailableError('kernel-bridge(test): kernelRoot required');
}
const cliPath = path.resolve(kernelRoot, 'plugin', 'scripts', 'core-reader-cli.js');
if (!existsSync(cliPath)) {
throw new KernelBridgeUnavailableError(`core-reader CLI unavailable at ${cliPath}`);
}
return invokeCoreReaderCli({
cliPath,
kernelRoot: path.resolve(kernelRoot),
projection,
stdinPayload,
timeoutMs,
envPassthrough,
allowDegraded: false,
});
}
// Exported for tests that need to assert against the contract.
export const __testables = Object.freeze({
PROJECTION_NAMES,
DEFAULT_ENV_WHITELIST,
getKernelBridgeMeta,
});