@linzumi/cli 1.0.272 → 1.0.273

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 (43) hide show
  1. package/README.md +1 -1
  2. package/dist/impl-res/cloud-supervisor.mjs +69 -69
  3. package/dist/impl-res/index.js +353 -312
  4. package/dist/impl-res/mcp-server.mjs +34 -34
  5. package/dist/impl-ts/cloud-supervisor.mjs +69 -69
  6. package/dist/impl-ts/index.js +488 -488
  7. package/dist/impl-ts/mcp-server.mjs +1 -1
  8. package/dist/mcp-server.mjs +1 -1
  9. package/package.json +3 -2
  10. package/scripts/build-auth-parity-oracle.mjs +0 -709
  11. package/scripts/build-canonical-codex-transpiler-oracle.mjs +0 -93
  12. package/scripts/build-config-identity-parity-oracle.mjs +0 -526
  13. package/scripts/build-core-commander-seams-parity-oracle.mjs +0 -799
  14. package/scripts/build-core-daemon-parity-oracle.mjs +0 -573
  15. package/scripts/build-core-dispatch-input-queue-parity-oracle.mjs +0 -225
  16. package/scripts/build-core-fate-ladder-parity-oracle.mjs +0 -350
  17. package/scripts/build-core-generation-overlap-parity-oracle.mjs +0 -292
  18. package/scripts/build-core-integration-parity-oracle.mjs +0 -453
  19. package/scripts/build-core-lifecycle-guards-parity-oracle.mjs +0 -443
  20. package/scripts/build-core-lock-parity-oracle.mjs +0 -462
  21. package/scripts/build-core-reconnect-resume-parity-oracle.mjs +0 -365
  22. package/scripts/build-core-startup-resume-scan-parity-oracle.mjs +0 -296
  23. package/scripts/build-core-supervisor-parity-oracle.mjs +0 -781
  24. package/scripts/build-cross-harness-failover-oracle.mjs +0 -349
  25. package/scripts/build-editor-parity-oracle.mjs +0 -1525
  26. package/scripts/build-forwarding-parity-oracle.mjs +0 -1390
  27. package/scripts/build-harness-claude-parity-oracle.mjs +0 -407
  28. package/scripts/build-harness-codex-parity-oracle.mjs +0 -479
  29. package/scripts/build-mcp-parity-oracle.mjs +0 -412
  30. package/scripts/build-mcp-selector-parity-oracle.mjs +0 -65
  31. package/scripts/build-onboarding-discovery-parity-oracle.mjs +0 -388
  32. package/scripts/build-onboarding-flow-parity-oracle.mjs +0 -562
  33. package/scripts/build-onboarding-gateway-parity-oracle.mjs +0 -313
  34. package/scripts/build-onboarding-support-parity-oracle.mjs +0 -519
  35. package/scripts/build-pipeline-parity-oracle.mjs +0 -614
  36. package/scripts/build-protocol-parity-oracle.mjs +0 -398
  37. package/scripts/build-queue-parity-oracle.mjs +0 -1012
  38. package/scripts/build-session-registry-parity-oracle.mjs +0 -582
  39. package/scripts/build-transport-parity-oracle.mjs +0 -694
  40. package/scripts/build-tui-parity-oracle.mjs +0 -577
  41. package/scripts/build-vm-sandbox-parity-oracle.mjs +0 -1281
  42. package/scripts/build-worker-entry-parity-oracle.mjs +0 -424
  43. package/scripts/build-worker-spawn-parity-oracle.mjs +0 -823
@@ -1,781 +0,0 @@
1
- // Spec: kandan/plans/2026-07-10-compute-nodes-rescript-commander-zero-ts-program.md
2
- // (M3 cluster 10, commander-core / supervisor).
3
- // Relationship: Builds the TS-side PARITY ORACLE for the `connect
4
- // --supervise` supervisor port (src/supervisor.ts -> ReScript
5
- // CommanderSupervisor), the sibling of build-pipeline-parity-oracle.mjs
6
- // (cluster 9). The oracle bundles the REAL supervisor module - the flag
7
- // helpers, the code fingerprint, the supervisor lock (real fs on a scratch
8
- // dir, byte-compared records), the console logger + signal disposition, the
9
- // gone-TTY write-guard slice of ttyTeardownGuard.ts, the runSuperviseLoop
10
- // refusal legs, and createSupervisor (THE state machine) driven through
11
- // fully scripted deps: a scripted scheduler/clock (the scriptedTimers
12
- // pattern), a scripted child-process seam (ops declare exits with
13
- // codes/signals and IPC frames; spawns/kills/sends land in the trace), and
14
- // scripted probe/install/fingerprint/reexec seams - behind the one-shot
15
- // stdin/stdout JSON batch driver. Every supervision run returns the FULL
16
- // trace (spawn calls with argv/env deltas, signals sent, timer set/clear,
17
- // log events, store writes) for byte comparison.
18
- //
19
- // Determinism: clocks are injected per case; timers fire in scheduling
20
- // order once the scripted clock passes their due instant, with a full
21
- // microtask settle between fires and between ops (both drivers settle
22
- // identically, so async update-check chains interleave identically); the
23
- // only non-injectable TS timestamp (the lock record's startedAt) is pinned
24
- // with a scoped global-Date override, the cluster 2 oracle's technique.
25
- //
26
- // SECRETS: the oracle only ever sees the conformance suite's synthetic
27
- // argv/env/payloads. The output is a local test artifact (.differential/
28
- // is gitignored, never published) and stays unminified for debuggability.
29
- import { mkdir } from 'node:fs/promises';
30
- import { dirname, join } from 'node:path';
31
- import { fileURLToPath } from 'node:url';
32
- import { build } from 'esbuild';
33
-
34
- const packageRoot = dirname(dirname(fileURLToPath(import.meta.url)));
35
-
36
- const driverSource = `
37
- import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync } from 'node:fs';
38
- import { tmpdir } from 'node:os';
39
- import { dirname, join } from 'node:path';
40
- import {
41
- acquireSupervisorLock,
42
- createSupervisor,
43
- createSupervisorConsoleLogger,
44
- defaultSupervisorReexecStatePath,
45
- defaultSupervisorTiming,
46
- hasSuperviseFlag,
47
- installSupervisorSignalHandlers,
48
- isSupervisedChild,
49
- runSuperviseLoop,
50
- supervisedChildEnvKey,
51
- supervisorCodeFingerprint,
52
- supervisorLockKey,
53
- supervisorLockPath,
54
- withoutSuperviseFlags,
55
- } from './src/supervisor';
56
- import {
57
- defaultGenerationStillbornWindowMs,
58
- generationEpochEnvKey,
59
- generationHandoffPidEnvKey,
60
- generationOverlapFlagEnvKey,
61
- generationTtyOwnerEnvKey,
62
- } from './src/generationOverlap';
63
- import { defaultLinzumiWebSocketUrl } from './src/defaultUrls';
64
- // Spec: plans/2026-09-11-computer-metadata-commander-restart.spec.md.
65
- // Mirror the real supervisor's explicit planned-restart support declaration.
66
- import { supervisorSupportEnvKey } from '../linzumi-cli-rescript/src/core/CommanderRequestedRestart.gen';
67
- import {
68
- goneTtyErrorCode,
69
- goneTtyWriteErrorCode,
70
- guardStreamWriteAgainstGoneTty,
71
- streamGoneTtyWriteCodeForTest,
72
- } from './src/ttyTeardownGuard';
73
-
74
- const RealDate = Date;
75
-
76
- function withPinnedDate(nowMs, fn) {
77
- class PinnedDate extends RealDate {
78
- constructor(...args) {
79
- if (args.length === 0) {
80
- super(nowMs);
81
- } else {
82
- super(...args);
83
- }
84
- }
85
- }
86
- PinnedDate.now = () => nowMs;
87
- globalThis.Date = PinnedDate;
88
- try {
89
- return fn();
90
- } finally {
91
- globalThis.Date = RealDate;
92
- }
93
- }
94
-
95
- const settle = () => new Promise((resolve) => setImmediate(resolve));
96
-
97
- // --- Scripted scheduler (the scriptedTimers pattern; ids in creation order) ---
98
-
99
- function scriptedScheduler(clock, trace) {
100
- let nextId = 1;
101
- const pending = [];
102
- return {
103
- scheduler: {
104
- setTimeout: (callback, ms) => {
105
- const id = nextId;
106
- nextId += 1;
107
- trace.push({ t: 'timer_set', id, delayMs: ms });
108
- pending.push({ id, dueAtMs: clock.nowMs + ms, callback });
109
- return id;
110
- },
111
- clearTimeout: (handle) => {
112
- const index = pending.findIndex((timer) => timer.id === handle);
113
- if (index >= 0) {
114
- trace.push({ t: 'timer_clear', id: pending[index].id });
115
- pending.splice(index, 1);
116
- }
117
- },
118
- },
119
- fireNextDue: () => {
120
- const index = pending.findIndex((timer) => timer.dueAtMs <= clock.nowMs);
121
- if (index < 0) return false;
122
- const timer = pending.splice(index, 1)[0];
123
- trace.push({ t: 'timer_fire', id: timer.id });
124
- timer.callback();
125
- return true;
126
- },
127
- };
128
- }
129
-
130
- // --- The scripted supervision run --------------------------------------------------
131
-
132
- async function runSupervisionCase(caseInput) {
133
- // The TS serial drain reads process.platform at drain time (the win32
134
- // SIGTERM fallback); the ReScript port injects isWin32. Pin the live
135
- // platform for win32 cases so both impls run the same branch.
136
- const platformDescriptor = Object.getOwnPropertyDescriptor(process, 'platform');
137
- if (caseInput.win32 === true) {
138
- Object.defineProperty(process, 'platform', { value: 'win32', configurable: true });
139
- }
140
- try {
141
- return await runSupervisionCaseInner(caseInput);
142
- } finally {
143
- if (caseInput.win32 === true && platformDescriptor !== undefined) {
144
- Object.defineProperty(process, 'platform', platformDescriptor);
145
- }
146
- }
147
- }
148
-
149
- async function runSupervisionCaseInner(caseInput) {
150
- const clock = { nowMs: caseInput.startMs ?? 0 };
151
- const trace = [];
152
- const timers = scriptedScheduler(clock, trace);
153
- const children = [];
154
- const entryBytes = new Map(Object.entries(caseInput.entryBytes ?? {}));
155
- let probeState = { kind: 'none' };
156
- let installState = { kind: 'none' };
157
- let storedAttempt = caseInput.attemptRecord ?? undefined;
158
-
159
- const initialEntryPath = caseInput.initialEntryPath ?? '/stable/v-base/bin/linzumi.js';
160
- const childArgs = caseInput.childArgs ?? ['--workspace', 'ws-parity'];
161
-
162
- const supervisor = createSupervisor({
163
- childArgs,
164
- initialEntryPath,
165
- initialVersion: caseInput.initialVersion ?? '1.0.0',
166
- ownEntryPath:
167
- caseInput.ownEntryPath === null
168
- ? undefined
169
- : (caseInput.ownEntryPath ?? initialEntryPath),
170
- spawnChild: ({
171
- entryPath,
172
- childArgs: spawnArgs,
173
- onExit,
174
- onSpawnError,
175
- generation,
176
- }) => {
177
- const index = children.length;
178
- const pid = 4200 + index;
179
- const record = {
180
- index,
181
- pid,
182
- alive: true,
183
- onExit,
184
- onSpawnError,
185
- generation,
186
- sendOk: true,
187
- };
188
- children.push(record);
189
- trace.push({
190
- t: 'spawn',
191
- index,
192
- pid,
193
- entryPath,
194
- argv: [entryPath, 'connect', ...spawnArgs],
195
- generation:
196
- generation === undefined
197
- ? null
198
- : {
199
- epoch: generation.epoch,
200
- handoffFromPid: generation.handoffFromPid ?? null,
201
- ipc: generation.onMessage !== undefined,
202
- // B7a: the TTY single-owner stamp is part of the pinned
203
- // spawn contract - an incoming overlap child must never be
204
- // spawned as an owner.
205
- ttyOwner: generation.ttyOwner,
206
- },
207
- envDelta:
208
- generation === undefined
209
- ? { [supervisedChildEnvKey]: '1', [supervisorSupportEnvKey]: '1' }
210
- : {
211
- [supervisedChildEnvKey]: '1',
212
- [supervisorSupportEnvKey]: '1',
213
- [generationEpochEnvKey]: String(generation.epoch),
214
- [generationTtyOwnerEnvKey]: generation.ttyOwner ? '1' : '0',
215
- ...(generation.handoffFromPid === undefined
216
- ? {}
217
- : {
218
- [generationHandoffPidEnvKey]: String(generation.handoffFromPid),
219
- }),
220
- },
221
- });
222
- return {
223
- pid,
224
- kill: (signal) => trace.push({ t: 'kill', child: index, signal }),
225
- ...(generation === undefined
226
- ? {}
227
- : {
228
- send: (message) => {
229
- trace.push({ t: 'send', child: index, message, ok: record.sendOk });
230
- return record.sendOk;
231
- },
232
- }),
233
- };
234
- },
235
- probeLatestVersion: async () => {
236
- trace.push({ t: 'probe' });
237
- if (probeState.kind === 'error') throw new Error(probeState.message);
238
- return probeState.kind === 'version' ? probeState.version : undefined;
239
- },
240
- installVersion: async (version) => {
241
- trace.push({ t: 'install', version });
242
- if (installState.kind === 'error') throw new Error(installState.message);
243
- if (installState.kind === 'entry') return { entryPath: installState.entryPath };
244
- throw new Error('no scripted install result');
245
- },
246
- readEntryBytes: (entryPath) => {
247
- trace.push({ t: 'read_bytes', path: entryPath });
248
- return entryBytes.get(entryPath);
249
- },
250
- reexecSelf: ({ entryPath }) => trace.push({ t: 'reexec', entryPath }),
251
- reexecAttemptStore: {
252
- load: () => storedAttempt,
253
- save: (record) => {
254
- trace.push({ t: 'attempt_save', record });
255
- storedAttempt = record;
256
- },
257
- },
258
- log: (event, payload = {}) => trace.push({ t: 'log', event, payload }),
259
- scheduler: timers.scheduler,
260
- now: () => clock.nowMs,
261
- // Spec: plans/2026-08-16-pr-5159-terminal-supervisor-liveness.md.
262
- // The scripted oracle acknowledges manager-visible terminal handoff just
263
- // like the ReScript parity driver; notifier failure is tested separately.
264
- notifyTerminalFailure: () => undefined,
265
- timing: caseInput.timing ?? undefined,
266
- ...(caseInput.overlap === undefined
267
- ? {}
268
- : {
269
- generationOverlap: {
270
- enabled: caseInput.overlap.enabled === true,
271
- stillbornWindowMs: caseInput.overlap.stillbornWindowMs,
272
- },
273
- }),
274
- });
275
-
276
- const aliveChildren = () => children.filter((child) => child.alive);
277
- const exitChild = (record, code, signal) => {
278
- record.alive = false;
279
- trace.push({ t: 'exit', child: record.index, code, signal });
280
- record.onExit({ code, signal });
281
- };
282
- const ipcTo = (record, label, message) => {
283
- if (
284
- record === undefined ||
285
- record.generation === undefined ||
286
- record.generation.onMessage === undefined
287
- ) {
288
- trace.push({ t: 'ipc_no_channel', op: label });
289
- return;
290
- }
291
- trace.push({ t: 'ipc', child: record.index, message });
292
- record.generation.onMessage(message);
293
- };
294
-
295
- for (const op of caseInput.ops ?? []) {
296
- switch (op.op) {
297
- case 'start':
298
- supervisor.start();
299
- break;
300
- case 'advance': {
301
- clock.nowMs += op.byMs;
302
- let fired = timers.fireNextDue();
303
- while (fired) {
304
- await settle();
305
- fired = timers.fireNextDue();
306
- }
307
- break;
308
- }
309
- case 'spawnErrorNewest': {
310
- // Behavioral oracle for
311
- // :machine-liveness/respawn-failures-stay-loud-and-retrying.
312
- const alive = aliveChildren();
313
- const target = alive[alive.length - 1];
314
- if (target === undefined) {
315
- trace.push({ t: 'no_child', op: op.op });
316
- } else {
317
- target.alive = false;
318
- trace.push({
319
- t: 'spawn_error',
320
- child: target.index,
321
- message: op.message,
322
- });
323
- target.onSpawnError(new Error(op.message));
324
- }
325
- break;
326
- }
327
- case 'exitNewest':
328
- case 'exitOldest': {
329
- const alive = aliveChildren();
330
- const target = op.op === 'exitNewest' ? alive[alive.length - 1] : alive[0];
331
- if (target === undefined) {
332
- trace.push({ t: 'no_child', op: op.op });
333
- } else {
334
- exitChild(target, op.code ?? null, op.signal ?? null);
335
- }
336
- break;
337
- }
338
- case 'exitAll': {
339
- for (const record of aliveChildren()) {
340
- exitChild(record, op.code ?? null, op.signal ?? null);
341
- await settle();
342
- }
343
- break;
344
- }
345
- case 'ipcReadyNewest': {
346
- const alive = aliveChildren();
347
- const target = alive[alive.length - 1];
348
- ipcTo(target, op.op, {
349
- type: 'generation_ready',
350
- epoch: target?.generation?.epoch ?? 0,
351
- });
352
- break;
353
- }
354
- case 'ipcPinSnapshotOldest': {
355
- const target = aliveChildren()[0];
356
- ipcTo(target, op.op, {
357
- type: 'generation_pin_snapshot',
358
- epoch: target?.generation?.epoch ?? 0,
359
- threadIds: op.threadIds,
360
- });
361
- break;
362
- }
363
- case 'ipcPinReleasedOldest': {
364
- const target = aliveChildren()[0];
365
- ipcTo(target, op.op, {
366
- type: 'generation_pin_released',
367
- epoch: target?.generation?.epoch ?? 0,
368
- threadId: op.threadId,
369
- });
370
- break;
371
- }
372
- case 'ipcGarbageNewest': {
373
- const alive = aliveChildren();
374
- ipcTo(alive[alive.length - 1], op.op, op.message);
375
- break;
376
- }
377
- case 'setLatest':
378
- probeState =
379
- op.version === null ? { kind: 'none' } : { kind: 'version', version: op.version };
380
- break;
381
- case 'probeError':
382
- probeState = { kind: 'error', message: op.message };
383
- break;
384
- case 'setInstall':
385
- installState = { kind: 'entry', entryPath: op.entryPath };
386
- break;
387
- case 'installError':
388
- installState = { kind: 'error', message: op.message };
389
- break;
390
- case 'setBytes':
391
- if (op.bytes === null) entryBytes.delete(op.path);
392
- else entryBytes.set(op.path, op.bytes);
393
- break;
394
- case 'setSendNewest': {
395
- const alive = aliveChildren();
396
- const target = alive[alive.length - 1];
397
- if (target === undefined) trace.push({ t: 'no_child', op: op.op });
398
- else target.sendOk = op.ok === true;
399
- break;
400
- }
401
- case 'requestStop':
402
- supervisor.requestStop(
403
- op.forwardSignal === undefined ? undefined : { forwardSignal: op.forwardSignal }
404
- );
405
- break;
406
- case 'childActive':
407
- trace.push({ t: 'child_active', value: supervisor.childActive() });
408
- break;
409
- case 'awaitDone': {
410
- const outcome = await Promise.race([
411
- supervisor.done.then(() => 'done'),
412
- new Promise((resolve) => setTimeout(() => resolve('done_timeout'), 5000)),
413
- ]);
414
- trace.push({ t: outcome });
415
- break;
416
- }
417
- default:
418
- trace.push({ t: 'unknown_op', op: op.op });
419
- }
420
- await settle();
421
- }
422
-
423
- return { trace };
424
- }
425
-
426
- // --- Lock acquire runs (real fs on a scratch dir; startedAt pinned) --------------------
427
-
428
- function runAcquireLockCase(caseInput) {
429
- const scratch = mkdtempSync(join(tmpdir(), 'linzumi-core-sup-lock-'));
430
- const lockPath = join(scratch, 'sup.lock');
431
- const trace = [];
432
- const releases = [];
433
- for (const step of caseInput.steps ?? []) {
434
- if (step.action === 'acquire') {
435
- const alivePids = step.alivePids ?? [];
436
- const result = withPinnedDate(caseInput.nowMs ?? 0, () =>
437
- acquireSupervisorLock({
438
- path: lockPath,
439
- workspace: caseInput.workspace ?? 'ws-lock',
440
- linzumiUrl: caseInput.linzumiUrl ?? 'wss://parity.example',
441
- pid: step.pid,
442
- isPidAlive: (candidate) => alivePids.includes(candidate),
443
- })
444
- );
445
- if (result.ok) {
446
- releases.push(result.release);
447
- trace.push({ t: 'acquired' });
448
- } else {
449
- trace.push({ t: 'held', holderPid: result.holderPid ?? null });
450
- }
451
- trace.push({
452
- t: 'lock_bytes',
453
- bytes: existsSync(lockPath) ? readFileSync(lockPath, 'utf8') : null,
454
- });
455
- } else if (step.action === 'releaseLast') {
456
- const release = releases.pop();
457
- if (release !== undefined) release();
458
- trace.push({ t: 'released', fileExists: existsSync(lockPath) });
459
- } else if (step.action === 'seedLock') {
460
- writeFileSync(lockPath, step.content);
461
- trace.push({ t: 'seeded' });
462
- }
463
- }
464
- return { trace };
465
- }
466
-
467
- // --- Console logger / signal handlers / tty guard --------------------------------------
468
-
469
- function runConsoleLoggerCase(caseInput) {
470
- const stderrLines = [];
471
- const audits = [];
472
- let writes = 0;
473
- const logger = createSupervisorConsoleLogger({
474
- writeStderr: (line) => {
475
- writes += 1;
476
- if (
477
- caseInput.stderrFailAfter !== undefined &&
478
- writes > caseInput.stderrFailAfter
479
- ) {
480
- throw new Error('EIO scripted console death');
481
- }
482
- stderrLines.push(line);
483
- },
484
- audit: (event, payload) => {
485
- if (caseInput.auditFails === true) throw new Error('scripted audit failure');
486
- audits.push({ event, payload });
487
- },
488
- now: () => new RealDate(caseInput.nowMs ?? 0),
489
- });
490
- for (const entry of caseInput.events ?? []) {
491
- logger(entry.event, entry.payload);
492
- }
493
- return { stderrLines, audits };
494
- }
495
-
496
- function runSignalHandlersCase(caseInput) {
497
- const trace = [];
498
- const once = new Map();
499
- const on = new Map();
500
- installSupervisorSignalHandlers(
501
- {
502
- requestStop: (options) =>
503
- trace.push({ t: 'request_stop', forwardSignal: options?.forwardSignal ?? null }),
504
- },
505
- (event, payload = {}) => trace.push({ t: 'log', event, payload }),
506
- {
507
- once: (event, listener) => {
508
- const queue = once.get(event) ?? [];
509
- queue.push(listener);
510
- once.set(event, queue);
511
- trace.push({ t: 'registered_once', event });
512
- },
513
- on: (event, listener) => {
514
- const queue = on.get(event) ?? [];
515
- queue.push(listener);
516
- on.set(event, queue);
517
- trace.push({ t: 'registered_on', event });
518
- },
519
- }
520
- );
521
- for (const signal of caseInput.fires ?? []) {
522
- trace.push({ t: 'fire', signal });
523
- const onceQueue = once.get(signal) ?? [];
524
- if (onceQueue.length > 0) {
525
- const listener = onceQueue.shift();
526
- listener();
527
- }
528
- for (const listener of on.get(signal) ?? []) {
529
- listener();
530
- }
531
- }
532
- return { trace };
533
- }
534
-
535
- function errorOfSpec(spec) {
536
- if (spec.kind === 'null') return null;
537
- if (spec.kind === 'string') return spec.value;
538
- if (spec.kind === 'number') return spec.value;
539
- const error = {};
540
- if (spec.code !== undefined) error.code = spec.code;
541
- if (spec.message !== undefined) error.message = spec.message;
542
- return error;
543
- }
544
-
545
- function runTtyClassifyCase(caseInput) {
546
- return (caseInput.errors ?? []).map((spec) => {
547
- const error = errorOfSpec(spec);
548
- return {
549
- gone: goneTtyErrorCode(error) ?? null,
550
- write: goneTtyWriteErrorCode(error) ?? null,
551
- };
552
- });
553
- }
554
-
555
- function runTtyGuardCase(caseInput) {
556
- const trace = [];
557
- const errorListeners = [];
558
- let throwSpec;
559
- const stream = {
560
- isTTY: true,
561
- write: (chunk) => {
562
- if (throwSpec !== undefined) {
563
- const error = new Error(throwSpec.message);
564
- if (throwSpec.code !== undefined) error.code = throwSpec.code;
565
- throwSpec = undefined;
566
- throw error;
567
- }
568
- trace.push({ t: 'underlying_write', chunk });
569
- return true;
570
- },
571
- on: (event, listener) => {
572
- if (event === 'error') errorListeners.push(listener);
573
- trace.push({ t: 'listener_added', event });
574
- },
575
- listenerCount: (event) => (event === 'error' ? errorListeners.length : 0),
576
- };
577
- const sinks = {
578
- audit: (event, fields) => trace.push({ t: 'sink', leg: 'audit', event, fields }),
579
- log: (event, fields) => trace.push({ t: 'sink', leg: 'log', event, fields }),
580
- };
581
- const guard = (label) =>
582
- trace.push({
583
- t: 'guarded',
584
- label,
585
- result: guardStreamWriteAgainstGoneTty(stream, {
586
- context: { surface: 'parity_surface' },
587
- sinks,
588
- onGoneTty: (code) => trace.push({ t: 'gone_tty', label, code }),
589
- rethrow: (error) =>
590
- trace.push({
591
- t: 'rethrown',
592
- message: error instanceof Error ? error.message : String(error),
593
- }),
594
- }),
595
- });
596
- guard('first');
597
- for (const op of caseInput.ops ?? []) {
598
- if (op.op === 'write') {
599
- if (op.throwCode !== undefined || op.throwMessage !== undefined) {
600
- throwSpec = { code: op.throwCode, message: op.throwMessage ?? 'scripted write failure' };
601
- }
602
- let outcome;
603
- let threwMessage = null;
604
- try {
605
- outcome = stream.write(op.data);
606
- } catch (error) {
607
- outcome = null;
608
- threwMessage = error instanceof Error ? error.message : String(error);
609
- }
610
- trace.push({ t: 'write_result', returned: outcome, threw: threwMessage });
611
- } else if (op.op === 'emitError') {
612
- const error = new Error(op.message ?? 'scripted stream error');
613
- if (op.code !== undefined) error.code = op.code;
614
- trace.push({ t: 'emit_error', code: op.code ?? null });
615
- for (const listener of [...errorListeners]) listener(error);
616
- } else if (op.op === 'guardAgain') {
617
- guard(op.label ?? 'again');
618
- }
619
- }
620
- return { trace, goneCode: streamGoneTtyWriteCodeForTest(stream) ?? null };
621
- }
622
-
623
- // --- runSuperviseLoop refusal legs -----------------------------------------------------
624
-
625
- async function runLockRefusalCase(caseInput) {
626
- const scratch = mkdtempSync(join(tmpdir(), 'linzumi-core-sup-home-'));
627
- const workspace = caseInput.workspace ?? '';
628
- const args = workspace === '' ? [] : ['--workspace', workspace];
629
- const lockPath = supervisorLockPath(
630
- { workspace, linzumiUrl: defaultLinzumiWebSocketUrl },
631
- scratch
632
- );
633
- mkdirSync(dirname(lockPath), { recursive: true });
634
- writeFileSync(
635
- lockPath,
636
- JSON.stringify({
637
- pid: 1,
638
- workspace,
639
- linzumiUrl: defaultLinzumiWebSocketUrl,
640
- startedAt: '2026-01-01T00:00:00.000Z',
641
- }) + '\\n'
642
- );
643
- const previousHome = process.env.HOME;
644
- process.env.HOME = scratch;
645
- try {
646
- await runSuperviseLoop(['--supervise', ...args]);
647
- return { message: null };
648
- } catch (error) {
649
- const message = error instanceof Error ? error.message : String(error);
650
- return { message: message.split(scratch).join('$SCRATCH') };
651
- } finally {
652
- process.env.HOME = previousHome;
653
- }
654
- }
655
-
656
- async function runEmptyEntryCase() {
657
- const scratch = mkdtempSync(join(tmpdir(), 'linzumi-core-sup-home-'));
658
- const previousHome = process.env.HOME;
659
- const previousArgv1 = process.argv[1];
660
- process.env.HOME = scratch;
661
- process.argv[1] = '';
662
- try {
663
- await runSuperviseLoop(['--supervise', '--workspace', 'ws-empty']);
664
- return { message: null };
665
- } catch (error) {
666
- const message = error instanceof Error ? error.message : String(error);
667
- return { message: message.split(scratch).join('$SCRATCH') };
668
- } finally {
669
- process.env.HOME = previousHome;
670
- process.argv[1] = previousArgv1;
671
- }
672
- }
673
-
674
- // --- Case dispatch -----------------------------------------------------------------------
675
-
676
- async function runCase(input) {
677
- switch (input.kind) {
678
- case 'constants':
679
- return {
680
- supervisedChildEnvKey,
681
- generationOverlapFlagEnvKey,
682
- generationEpochEnvKey,
683
- generationHandoffPidEnvKey,
684
- generationTtyOwnerEnvKey,
685
- defaultGenerationStillbornWindowMs,
686
- defaultSupervisorTiming,
687
- defaultLinzumiWebSocketUrl,
688
- };
689
- case 'isSupervisedChild':
690
- return isSupervisedChild(input.env);
691
- case 'withoutSuperviseFlags':
692
- return withoutSuperviseFlags(input.args);
693
- case 'hasSuperviseFlag':
694
- return hasSuperviseFlag(input.args);
695
- case 'fingerprint':
696
- return (
697
- supervisorCodeFingerprint(input.entryPath, (path) => {
698
- const bytes = (input.files ?? {})[path];
699
- return bytes === undefined ? undefined : bytes;
700
- }) ?? null
701
- );
702
- case 'lockKey':
703
- return supervisorLockKey({ workspace: input.workspace, linzumiUrl: input.linzumiUrl });
704
- case 'lockPath':
705
- return supervisorLockPath(
706
- { workspace: input.workspace, linzumiUrl: input.linzumiUrl },
707
- input.homeDir
708
- );
709
- case 'reexecStatePath':
710
- return defaultSupervisorReexecStatePath(input.env);
711
- case 'acquireLockRun':
712
- return runAcquireLockCase(input);
713
- case 'consoleLogger':
714
- return runConsoleLoggerCase(input);
715
- case 'signalHandlers':
716
- return runSignalHandlersCase(input);
717
- case 'ttyClassify':
718
- return runTtyClassifyCase(input);
719
- case 'ttyGuardRun':
720
- return runTtyGuardCase(input);
721
- case 'lockRefusalLoop':
722
- return runLockRefusalCase(input);
723
- case 'emptyEntryLoop':
724
- return runEmptyEntryCase();
725
- case 'supervisionRun':
726
- return runSupervisionCase(input);
727
- default:
728
- return { error: 'unknown case kind ' + String(input.kind) };
729
- }
730
- }
731
-
732
- async function runBatch() {
733
- const chunks = [];
734
- for await (const chunk of process.stdin) chunks.push(chunk);
735
- const cases = JSON.parse(Buffer.concat(chunks).toString('utf8'));
736
- const results = [];
737
- for (const testCase of cases) {
738
- results.push(await runCase(testCase));
739
- }
740
- process.stdout.write(JSON.stringify(results), () => {
741
- process.exit(0);
742
- });
743
- }
744
-
745
- runBatch().then(
746
- () => {},
747
- (error) => {
748
- process.stderr.write(String(error && error.stack ? error.stack : error) + '\\n');
749
- process.exit(1);
750
- }
751
- );
752
- `;
753
-
754
- const outDir = join(packageRoot, '.differential');
755
- const outPath = join(outDir, 'core-supervisor-parity-oracle.mjs');
756
-
757
- await mkdir(outDir, { recursive: true });
758
-
759
- await build({
760
- stdin: {
761
- contents: driverSource,
762
- resolveDir: packageRoot,
763
- sourcefile: 'core-supervisor-parity-driver.ts',
764
- loader: 'ts',
765
- },
766
- bundle: true,
767
- platform: 'node',
768
- target: 'node20',
769
- format: 'esm',
770
- outfile: outPath,
771
- minify: false,
772
- sourcemap: false,
773
- legalComments: 'none',
774
- logLevel: 'silent',
775
- // supervisor.ts pulls the wider commander graph (updateNudge,
776
- // workerEntryStability, runnerLogger); the same runtime externals as the
777
- // differential entry build stay external.
778
- external: ['ws', 'undici', 'blessed', '@anthropic-ai/claude-agent-sdk'],
779
- });
780
-
781
- process.stdout.write(outPath + '\n');