@linzumi/cli 1.0.272 → 1.0.274

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 (44) 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 +355 -314
  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 +495 -495
  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/check-package-size-budget.mjs +9 -0
  11. package/scripts/build-auth-parity-oracle.mjs +0 -709
  12. package/scripts/build-canonical-codex-transpiler-oracle.mjs +0 -93
  13. package/scripts/build-config-identity-parity-oracle.mjs +0 -526
  14. package/scripts/build-core-commander-seams-parity-oracle.mjs +0 -799
  15. package/scripts/build-core-daemon-parity-oracle.mjs +0 -573
  16. package/scripts/build-core-dispatch-input-queue-parity-oracle.mjs +0 -225
  17. package/scripts/build-core-fate-ladder-parity-oracle.mjs +0 -350
  18. package/scripts/build-core-generation-overlap-parity-oracle.mjs +0 -292
  19. package/scripts/build-core-integration-parity-oracle.mjs +0 -453
  20. package/scripts/build-core-lifecycle-guards-parity-oracle.mjs +0 -443
  21. package/scripts/build-core-lock-parity-oracle.mjs +0 -462
  22. package/scripts/build-core-reconnect-resume-parity-oracle.mjs +0 -365
  23. package/scripts/build-core-startup-resume-scan-parity-oracle.mjs +0 -296
  24. package/scripts/build-core-supervisor-parity-oracle.mjs +0 -781
  25. package/scripts/build-cross-harness-failover-oracle.mjs +0 -349
  26. package/scripts/build-editor-parity-oracle.mjs +0 -1525
  27. package/scripts/build-forwarding-parity-oracle.mjs +0 -1390
  28. package/scripts/build-harness-claude-parity-oracle.mjs +0 -407
  29. package/scripts/build-harness-codex-parity-oracle.mjs +0 -479
  30. package/scripts/build-mcp-parity-oracle.mjs +0 -412
  31. package/scripts/build-mcp-selector-parity-oracle.mjs +0 -65
  32. package/scripts/build-onboarding-discovery-parity-oracle.mjs +0 -388
  33. package/scripts/build-onboarding-flow-parity-oracle.mjs +0 -562
  34. package/scripts/build-onboarding-gateway-parity-oracle.mjs +0 -313
  35. package/scripts/build-onboarding-support-parity-oracle.mjs +0 -519
  36. package/scripts/build-pipeline-parity-oracle.mjs +0 -614
  37. package/scripts/build-protocol-parity-oracle.mjs +0 -398
  38. package/scripts/build-queue-parity-oracle.mjs +0 -1012
  39. package/scripts/build-session-registry-parity-oracle.mjs +0 -582
  40. package/scripts/build-transport-parity-oracle.mjs +0 -694
  41. package/scripts/build-tui-parity-oracle.mjs +0 -577
  42. package/scripts/build-vm-sandbox-parity-oracle.mjs +0 -1281
  43. package/scripts/build-worker-entry-parity-oracle.mjs +0 -424
  44. package/scripts/build-worker-spawn-parity-oracle.mjs +0 -823
@@ -1,799 +0,0 @@
1
- // Spec: kandan/plans/2026-07-10-compute-nodes-rescript-commander-zero-ts-program.md
2
- // (M3 cluster 10, runner core).
3
- // Relationship: Builds the TS-side PARITY ORACLE for three bounded
4
- // commander-core seams of the ReScript commander port, the sibling of
5
- // build-queue-parity-oracle.mjs (cluster 5) /
6
- // build-transport-parity-oracle.mjs (cluster 4). ONE bundle imports the
7
- // REAL commander-core exports from './src/runner' (the whole module graph
8
- // rides along - large by design, exactly like the transport/config oracles
9
- // that already import runner exports) behind the one-shot batch driver: a
10
- // JSON array of cases on stdin, a JSON array of results on stdout.
11
- //
12
- // The three seams:
13
- // 1. Control-dispatch dedup + commit-then-advance confirmation
14
- // (staleStartInstanceWindowMs / staleStartInstanceAgeMs /
15
- // shouldSkipReplayedStartInstanceForKnownSession /
16
- // shouldSkipReplayedStartTurn / commitAppliedStartTurn /
17
- // dispatchControlConfirmingStartTurn / settleControlDispatch).
18
- // 2. The connection-staleness tracker (constants +
19
- // createConnectionStalenessTracker) driven by scripted clocks and
20
- // scripted escalation callbacks.
21
- // 3. The app-server KILL/RESPAWN ladder (createCodexTurnFailureGuard,
22
- // runnerOwnsRespawnableAppServer, awaitLossReportsThenExit, the
23
- // crash-loop constants/store/classifier, appServerLossCwdDiagnosis).
24
- //
25
- // Determinism: clocks are scripted per case (every seam takes an injected
26
- // now/nowMs), timers are scripted callbacks, scripted promises resolve in
27
- // program order with explicit microtask flushes, and scratch paths are
28
- // normalized through the "$DIR" placeholder in both directions. The
29
- // turn-failure guard's lastActivityAtMs is wall-clock-stamped inside the TS
30
- // original, so both impls report it as a PRESENCE flag only.
31
- //
32
- // SECRETS: the oracle only ever sees the conformance suite's synthetic
33
- // payloads; nothing here logs case contents.
34
- //
35
- // The output is a local test artifact (.differential/ is gitignored, never
36
- // published) and stays unminified for debuggability.
37
- import { copyFile, mkdir } from 'node:fs/promises';
38
- import { dirname, join } from 'node:path';
39
- import { fileURLToPath } from 'node:url';
40
- import { build } from 'esbuild';
41
-
42
- const packageRoot = dirname(dirname(fileURLToPath(import.meta.url)));
43
-
44
- const driverSource = `
45
- import {
46
- mkdtempSync,
47
- readdirSync,
48
- readFileSync,
49
- realpathSync,
50
- statSync,
51
- writeFileSync,
52
- } from 'node:fs';
53
- import { tmpdir } from 'node:os';
54
- import { join, relative } from 'node:path';
55
- import {
56
- appServerCrashLoopExitCode,
57
- appServerCrashLoopExitLimit,
58
- appServerCrashLoopWindowMs,
59
- appServerLossCwdDiagnosis,
60
- awaitLossReportsThenExit,
61
- commitAppliedStartTurn,
62
- connectionStaleForcedReconnectAfterMs,
63
- connectionStaleForcedReconnectRetryMs,
64
- connectionStaleHardResetAfterUninitiatedDispatches,
65
- connectionStaleHardResetFailureLimit,
66
- connectionStaleThresholdMs,
67
- connectionUnrecoverableAfterMs,
68
- createCodexTurnFailureGuard,
69
- createConnectionStalenessTracker,
70
- defaultAppServerExitLoopStatePath,
71
- dispatchControlConfirmingStartTurn,
72
- fileAppServerExitLoopStore,
73
- recordAppServerExitAndClassify,
74
- runnerOwnsRespawnableAppServer,
75
- settleControlDispatch,
76
- shouldSkipReplayedStartInstanceForKnownSession,
77
- shouldSkipReplayedStartTurn,
78
- staleStartInstanceAgeMs,
79
- staleStartInstanceWindowMs,
80
- } from './src/runner';
81
- import {
82
- registerRequiredAdtCandidate, acknowledgeRequiredAdtCandidate,
83
- consumeRequiredAdtAdmission, closeRequiredAdtAdmissionForDisconnect,
84
- reconcileRequiredAdtCandidates, requiredTransportFinalAdmission,
85
- findRequiredAdtCandidate, releaseRequiredAdtCandidate,
86
- recoverRetainedTerminalDebt,
87
- } from './src/channelSession';
88
- import {adoptAdtStreamBinding, installAdtPublicationBinding} from './src/pipeline/contracts';
89
- import {createThreadOutbox} from './src/pipeline/outbox';
90
- import {enqueueTerminalDebtRepair} from './src/pipeline/integration';
91
- import {createHash} from 'node:crypto';
92
-
93
- // --- Placeholder + snapshot plumbing --------------------------------------------
94
-
95
- const dirPlaceholder = '$DIR';
96
-
97
- function scratch() {
98
- // realpath so macOS /var -> /private/var never splits the two impls'
99
- // placeholder substitution.
100
- return realpathSync(mkdtempSync(join(tmpdir(), 'linzumi-core-oracle-')));
101
- }
102
-
103
- function substitute(value, from, to) {
104
- if (typeof value === 'string') {
105
- return value.split(from).join(to);
106
- }
107
- if (Array.isArray(value)) {
108
- return value.map((entry) => substitute(entry, from, to));
109
- }
110
- if (typeof value === 'object' && value !== null) {
111
- return Object.fromEntries(
112
- Object.entries(value).map(([key, entry]) => [
113
- substitute(key, from, to),
114
- substitute(entry, from, to),
115
- ])
116
- );
117
- }
118
- return value;
119
- }
120
-
121
- function snapshotFiles(dir) {
122
- const files = {};
123
- const walk = (current) => {
124
- for (const name of readdirSync(current).sort()) {
125
- const full = join(current, name);
126
- if (statSync(full).isDirectory()) {
127
- walk(full);
128
- } else {
129
- files[relative(dir, full)] = readFileSync(full, 'utf8');
130
- }
131
- }
132
- };
133
- walk(dir);
134
- return files;
135
- }
136
-
137
- function outcome(run) {
138
- try {
139
- const value = run();
140
- return value === undefined ? { defined: false } : { defined: true, value };
141
- } catch (error) {
142
- return {
143
- threw: true,
144
- message: error instanceof Error ? error.message : String(error),
145
- };
146
- }
147
- }
148
-
149
- function collectingLog(events) {
150
- return (event, payload) => {
151
- events.push({ trace: 'log', event, payload });
152
- };
153
- }
154
-
155
- // Deterministic microtask flush: enough passes that a then-chain of any
156
- // scripted depth settles before the trace is read on both impls.
157
- async function flushMicrotasks() {
158
- for (let i = 0; i < 8; i += 1) {
159
- await Promise.resolve();
160
- }
161
- }
162
-
163
- // --- Slice 1: control-dispatch dedup + commit-then-advance -----------------------
164
-
165
- async function handleControlDispatch(testCase) {
166
- switch (testCase.fn) {
167
- case 'constants':
168
- return { staleStartInstanceWindowMs };
169
- case 'staleAge':
170
- return outcome(() =>
171
- staleStartInstanceAgeMs(testCase.control, testCase.nowMs)
172
- );
173
- case 'skipKnownSession': {
174
- const lookups = [];
175
- const known = new Set(testCase.knownThreadIds ?? []);
176
- const result = outcome(() =>
177
- shouldSkipReplayedStartInstanceForKnownSession(
178
- testCase.control,
179
- (threadId) => {
180
- lookups.push(threadId);
181
- return known.has(threadId);
182
- }
183
- )
184
- );
185
- return { result, lookups };
186
- }
187
- case 'skipStartTurn':
188
- return outcome(() =>
189
- shouldSkipReplayedStartTurn(
190
- testCase.applied ?? undefined,
191
- testCase.controlSeq
192
- )
193
- );
194
- case 'commit': {
195
- const calls = [];
196
- const store = {
197
- onAdvance: (key, seq) => calls.push({ call: 'onAdvance', key, seq }),
198
- flush: () => calls.push({ call: 'flush' }),
199
- };
200
- const result = outcome(() =>
201
- commitAppliedStartTurn(store, testCase.watermarkKey, testCase.controlSeq)
202
- );
203
- return { result, calls };
204
- }
205
- case 'dispatchConfirm': {
206
- const trace = [];
207
- const dispatch = () => {
208
- trace.push({ trace: 'dispatch_called' });
209
- return testCase.dispatch.kind === 'resolve'
210
- ? Promise.resolve(testCase.dispatch.value ?? null)
211
- : Promise.reject(
212
- new Error(String(testCase.dispatch.message ?? 'scripted dispatch rejection'))
213
- );
214
- };
215
- const commit =
216
- testCase.hasCommit === true
217
- ? () => trace.push({ trace: 'commit_called' })
218
- : undefined;
219
- try {
220
- const value = await dispatchControlConfirmingStartTurn(dispatch, commit);
221
- trace.push({ trace: 'resolved', value: value ?? null });
222
- } catch (error) {
223
- trace.push({
224
- trace: 'rejected',
225
- message: error instanceof Error ? error.message : String(error),
226
- });
227
- }
228
- return { trace };
229
- }
230
- case 'settle': {
231
- const trace = [];
232
- const log = collectingLog(trace);
233
- const handler = testCase.handler ?? { kind: 'syncUndefined' };
234
- const handle = () => {
235
- trace.push({ trace: 'handle_called' });
236
- switch (handler.kind) {
237
- case 'syncThrow':
238
- throw new Error(String(handler.message ?? 'scripted sync throw'));
239
- case 'syncObject':
240
- return handler.value ?? {};
241
- case 'syncUndefined':
242
- return undefined;
243
- case 'asyncResolve':
244
- return Promise.resolve(handler.value ?? null);
245
- case 'asyncReject':
246
- return Promise.reject(
247
- new Error(String(handler.message ?? 'scripted async rejection'))
248
- );
249
- default:
250
- throw new Error('unknown settle handler kind ' + String(handler.kind));
251
- }
252
- };
253
- const onRejected =
254
- testCase.onRejected === undefined
255
- ? undefined
256
- : (error) => {
257
- trace.push({
258
- trace: 'on_rejected',
259
- message: error instanceof Error ? error.message : String(error),
260
- });
261
- return testCase.onRejected;
262
- };
263
- settleControlDispatch(
264
- testCase.controlType ?? 'scripted_control',
265
- handle,
266
- () => trace.push({ trace: 'ack' }),
267
- log,
268
- onRejected
269
- );
270
- trace.push({ trace: 'settle_returned' });
271
- await flushMicrotasks();
272
- return { trace };
273
- }
274
- default:
275
- return { threw: true, message: 'unknown controlDispatch fn ' + String(testCase.fn) };
276
- }
277
- }
278
-
279
- // --- Slice 2: connection-staleness tracker ----------------------------------------
280
-
281
- function handleStaleness(testCase) {
282
- if (testCase.fn === 'constants') {
283
- return {
284
- connectionStaleThresholdMs,
285
- connectionStaleForcedReconnectAfterMs,
286
- connectionStaleForcedReconnectRetryMs,
287
- connectionStaleHardResetAfterUninitiatedDispatches,
288
- connectionStaleHardResetFailureLimit,
289
- connectionUnrecoverableAfterMs,
290
- };
291
- }
292
- // fn === 'scenario': a scripted clock + scripted escalation callbacks.
293
- const trace = [];
294
- const log = collectingLog(trace);
295
- let nowMs = testCase.startMs ?? 0;
296
- const escalationSpec = testCase.escalation;
297
- const reconnectReturns = [...(escalationSpec?.reconnectReturns ?? [])];
298
- const hardResetReturns = [...(escalationSpec?.hardResetReturns ?? [])];
299
- const escalation =
300
- escalationSpec === undefined
301
- ? undefined
302
- : {
303
- ...(escalationSpec.hasReconnect === true
304
- ? {
305
- onReconnectNeeded: (details) => {
306
- trace.push({ trace: 'reconnect_needed', details });
307
- const scripted = reconnectReturns.shift();
308
- return scripted === null || scripted === undefined
309
- ? undefined
310
- : scripted;
311
- },
312
- }
313
- : {}),
314
- ...(escalationSpec.hasHardReset === true
315
- ? {
316
- onHardResetNeeded: (details) => {
317
- trace.push({ trace: 'hard_reset_needed', details });
318
- const scripted = hardResetReturns.shift();
319
- return scripted === null || scripted === undefined
320
- ? undefined
321
- : scripted;
322
- },
323
- }
324
- : {}),
325
- ...(escalationSpec.forcedReconnectAfterMs === undefined
326
- ? {}
327
- : { forcedReconnectAfterMs: escalationSpec.forcedReconnectAfterMs }),
328
- ...(escalationSpec.forcedReconnectRetryMs === undefined
329
- ? {}
330
- : { forcedReconnectRetryMs: escalationSpec.forcedReconnectRetryMs }),
331
- onUnrecoverable: (details) => {
332
- trace.push({ trace: 'unrecoverable', details });
333
- },
334
- ...(escalationSpec.afterMs === undefined
335
- ? {}
336
- : { afterMs: escalationSpec.afterMs }),
337
- };
338
- const tracker = createConnectionStalenessTracker(
339
- log,
340
- () => nowMs,
341
- testCase.thresholdMs ?? undefined,
342
- escalation
343
- );
344
- for (const step of testCase.steps ?? []) {
345
- switch (step.fn) {
346
- case 'advance':
347
- nowMs += step.byMs;
348
- break;
349
- case 'ack':
350
- tracker.recordServerAck();
351
- break;
352
- case 'check':
353
- tracker.check();
354
- break;
355
- case 'isStale':
356
- trace.push({ trace: 'is_stale', value: tracker.isStale() });
357
- break;
358
- default:
359
- trace.push({ trace: 'unknown_step', fn: String(step.fn) });
360
- }
361
- }
362
- return { trace };
363
- }
364
-
365
- // --- Slice 3: respawn ladder ---------------------------------------------------------
366
-
367
- async function handleRespawn(testCase) {
368
- switch (testCase.fn) {
369
- case 'constants':
370
- return {
371
- appServerCrashLoopWindowMs,
372
- appServerCrashLoopExitLimit,
373
- appServerCrashLoopExitCode,
374
- };
375
- case 'ownsRespawnable':
376
- return outcome(() =>
377
- runnerOwnsRespawnableAppServer({
378
- codexUrl: testCase.codexUrl ?? undefined,
379
- threadProcessRole: testCase.threadProcessRole ?? undefined,
380
- ownsStartedAppServer: testCase.ownsStartedAppServer === true,
381
- })
382
- );
383
- case 'statePath':
384
- return outcome(() =>
385
- defaultAppServerExitLoopStatePath(testCase.runnerId, testCase.env ?? {})
386
- );
387
- case 'cwdDiagnosis': {
388
- const existsMode = testCase.existsMode ?? 'real';
389
- const existsFn =
390
- existsMode === 'real'
391
- ? undefined
392
- : () => {
393
- if (existsMode === 'throw') {
394
- throw new Error('scripted exists probe failure');
395
- }
396
- return existsMode === 'true';
397
- };
398
- return outcome(() =>
399
- existsFn === undefined
400
- ? appServerLossCwdDiagnosis(testCase.cwd)
401
- : appServerLossCwdDiagnosis(testCase.cwd, existsFn)
402
- );
403
- }
404
- case 'exitLoopScenario': {
405
- const dir = scratch();
406
- const path = join(dir, 'exit-loop.json');
407
- if (testCase.initialContents !== undefined) {
408
- writeFileSync(path, testCase.initialContents, 'utf8');
409
- }
410
- const writeErrors = [];
411
- const store = fileAppServerExitLoopStore(path, (message) =>
412
- writeErrors.push(message)
413
- );
414
- const results = (testCase.steps ?? []).map((step) => {
415
- switch (step.fn) {
416
- case 'record':
417
- return outcome(() =>
418
- recordAppServerExitAndClassify(
419
- store,
420
- step.nowMs,
421
- step.windowMs ?? undefined,
422
- step.limit ?? undefined
423
- )
424
- );
425
- case 'load':
426
- return outcome(() => store.load());
427
- case 'save':
428
- return outcome(() => store.save(step.record));
429
- default:
430
- return { threw: true, message: 'unknown exitLoop fn ' + String(step.fn) };
431
- }
432
- });
433
- return substitute(
434
- { results, writeErrors, files: snapshotFiles(dir) },
435
- dir,
436
- dirPlaceholder
437
- );
438
- }
439
- case 'guardScenario': {
440
- const trace = [];
441
- const log = collectingLog(trace);
442
- const sessionSpecs = testCase.sessions ?? [];
443
- const sessions = sessionSpecs.map((spec, index) => ({
444
- handleCodexNotification: (method, params) => {
445
- trace.push({ trace: 'session_dispatch', session: index, method, params });
446
- if (spec.throws === true) {
447
- throw new Error('scripted session dispatch failure ' + String(index));
448
- }
449
- },
450
- }));
451
- const guard = createCodexTurnFailureGuard({
452
- sessions: () => sessions,
453
- log,
454
- ...(testCase.hasOnActiveThreadsFailed === true
455
- ? {
456
- onActiveThreadsFailed: (threadIds) => {
457
- trace.push({ trace: 'active_threads_failed', threadIds: [...threadIds] });
458
- },
459
- }
460
- : {}),
461
- });
462
- for (const step of testCase.steps ?? []) {
463
- switch (step.fn) {
464
- case 'observe':
465
- guard.observeNotification(step.method, step.params ?? {});
466
- break;
467
- case 'fail':
468
- guard.failActiveTurns(String(step.cause ?? 'scripted cause'));
469
- break;
470
- case 'failPerTurn': {
471
- const causes = step.causes ?? {};
472
- guard.failActiveTurns(
473
- (turn) =>
474
- causes[turn.threadId + '|' + turn.turnId] ??
475
- String(step.defaultCause ?? 'scripted default cause')
476
- );
477
- break;
478
- }
479
- case 'count':
480
- trace.push({ trace: 'count', value: guard.activeTurnCount() });
481
- break;
482
- case 'turns':
483
- trace.push({ trace: 'turns', value: guard.activeTurns().map((t) => ({ ...t })) });
484
- break;
485
- case 'lastActivity':
486
- // Wall-clock stamped inside the TS original: presence only.
487
- trace.push({
488
- trace: 'last_activity_defined',
489
- value: guard.lastActivityAtMs() !== undefined,
490
- });
491
- break;
492
- default:
493
- trace.push({ trace: 'unknown_step', fn: String(step.fn) });
494
- }
495
- }
496
- return { trace };
497
- }
498
- case 'awaitLossReports': {
499
- const trace = [];
500
- const pushes = (testCase.pushes ?? []).map((push) => {
501
- if (push.kind === 'resolve') {
502
- return Promise.resolve(undefined);
503
- }
504
- if (push.kind === 'reject') {
505
- const rejected = Promise.reject(
506
- new Error(String(push.message ?? 'scripted push rejection'))
507
- );
508
- // Pre-observed so the scripted rejection can never trip the
509
- // unhandled-rejection handler before allSettled adopts it.
510
- rejected.catch(() => {});
511
- return rejected;
512
- }
513
- // 'never': a push whose ack never comes back.
514
- return new Promise(() => {});
515
- });
516
- await awaitLossReportsThenExit({
517
- pushes,
518
- exit: () => trace.push({ trace: 'exit' }),
519
- safetyCapMs: testCase.safetyCapMs,
520
- setTimeoutFn: (callback, ms) => {
521
- trace.push({ trace: 'cap_scheduled', ms });
522
- if (testCase.capFires === true) {
523
- setImmediate(callback);
524
- }
525
- return undefined;
526
- },
527
- });
528
- trace.push({ trace: 'returned' });
529
- return { trace };
530
- }
531
- default:
532
- return { threw: true, message: 'unknown respawn fn ' + String(testCase.fn) };
533
- }
534
- }
535
-
536
- // --- Dispatch --------------------------------------------------------------------------------
537
-
538
- // Spec: spec/commander-recovery-rules.md rule01 and rule05; retained terminal
539
- // debt is not an unknown provider-start ACK and cannot reset unrelated jobs.
540
- async function terminalDebtJournal(testCase) {
541
- const control = testCase.control;
542
- const logs = [];
543
- const body = 'Synthetic completed answer.';
544
- const outbox = createThreadOutbox({threadKey:'synthetic-terminal-debt', persistDir:scratch(),
545
- push:async()=>{throw new Error('pending repair must not publish or resend provider work');},
546
- builders:{'adt.terminal_attempt':{build:()=>{throw new Error('synthetic retained failure');}}},
547
- retryDelaysMs:[], onPermanentFailure:()=>{}, log:(event,fields)=>logs.push({event,fields}),
548
- });
549
- try {
550
- outbox.enqueue({kind:'adt.terminal_attempt',resolution:'must_ack',data:{seq:44,status:'processed',
551
- turn_id:'synthetic-completed-turn',terminal_frame:{session_id:3600,lease_epoch:2,frame_index:40,
552
- frame_kind:'terminal',assistant_phase:'final_answer',source_stream_key:'synthetic-rejected-key',body}}});
553
- await outbox.flush(1000);
554
- outbox.pause();
555
- await outbox.journalSettled();
556
- const gate = Promise.withResolvers();
557
- const entered = Promise.withResolvers();
558
- let settled = false;
559
- let authority = true;
560
- const barrierOutbox = {...outbox,
561
- journalSettled:async()=>{entered.resolve();await gate.promise;await outbox.journalSettled();settled=true;},
562
- terminalPublicationDebt:()=>!settled || control==='write-failure'
563
- ? {kind:'unavailable',reason:'controlled journal not durable'} : outbox.terminalPublicationDebt(),
564
- };
565
- const repair = enqueueTerminalDebtRepair(barrierOutbox,{threadId:'synthetic-terminal-debt',sourceSeq:44,
566
- sessionId:3600,originalLeaseEpoch:2,authoritativeTerminal:false,authorize:()=>authority,
567
- binding:{session_id:3600,lease_epoch:4,next_frame_index:39,
568
- checkpoint_config:{version:3,thresholds:{max_bytes:512,max_deltas:1,max_interval_ms:2000}},
569
- final_checkpoint:{frame_index:38,source_stream_key:'synthetic-canonical-key',
570
- body_sha256:createHash('sha256').update(body).digest('hex'),byte_len:Buffer.byteLength(body)}}},
571
- (event,fields)=>logs.push({event,fields}));
572
- const first = await Promise.race([entered.promise.then(()=>'waiting'),repair.then(()=>'finished')]);
573
- const before = outbox.pendingTerminalEntries().length;
574
- authority = control !== 'superseded';
575
- gate.resolve();
576
- const result = await repair;
577
- return {first,before,count:outbox.pendingTerminalEntries().length,ready:result.kind==='ready',result,logs};
578
- } finally {await outbox.close(0);}
579
- }
580
-
581
- async function terminalDebtStorm(testCase) {
582
- const ackLease = testCase.control === 'newer-ack-lease' ? 2 : testCase.control === 'future-ack' ? 4 : 1;
583
- const binding = {session_id: 3600, lease_epoch: ackLease, next_frame_index: 39,
584
- checkpoint_config: {version: 3, thresholds: {max_bytes: 1, max_deltas: 1, max_interval_ms: 2000}}};
585
- // Spec: commander-recovery-rules authenticated-terminal-evidence. The
586
- // retained frame and original ACK belong to one attempt across lease churn.
587
- const retainedLease = testCase.control === 'newer-retained-lease' ? 2 : 1;
588
- const body = 'Synthetic completed answer.';
589
- const reconciledBinding = {...binding, lease_epoch: 3, final_checkpoint: {
590
- frame_index: 38, source_stream_key: 'synthetic-canonical-key',
591
- body_sha256: createHash('sha256').update(body).digest('hex'), byte_len: Buffer.byteLength(body),
592
- }};
593
- const adopted = adoptAdtStreamBinding(binding, 44, 0);
594
- if (adopted.kind !== 'accepted') throw new Error('terminal debt fixture binding refused');
595
- const session = adopted.session;
596
- const logs = [];
597
- let resets = 0;
598
- let restarts = 0;
599
- let reconciliations = 0;
600
- let repairs = 0;
601
- const outbox = createThreadOutbox({threadKey:'synthetic-terminal-debt',
602
- persistDir:scratch(),
603
- push:async()=>{throw new Error('failed builder must not publish');},
604
- builders:{'adt.terminal_attempt':{build:()=>{throw new Error('synthetic final rejection');}}},
605
- retryDelaysMs:[], onPermanentFailure:()=>{}, log:(event,fields)=>logs.push({event,fields}),
606
- });
607
- try {
608
- outbox.enqueue({kind:'adt.terminal_attempt',resolution:'must_ack',data:{seq:44,status:'processed',
609
- turn_id:'synthetic-completed-turn',terminal_frame:{session_id:3600,lease_epoch:retainedLease,
610
- frame_index:40,frame_kind:'terminal',assistant_phase:'final_answer',source_stream_key:'synthetic-rejected-key',body}}});
611
- await outbox.flush(1000);
612
- outbox.pause();
613
- // Queue drain completion is distinct from durable journal settlement.
614
- await outbox.journalSettled();
615
- const durableDebt = outbox.terminalPublicationDebt();
616
- if (typeof durableDebt !== 'object' || durableDebt.kind !== 'repair_needed' || durableDebt.count !== 1) {
617
- throw new Error('warm repair fixture must have one durable failed terminal: ' + JSON.stringify(durableDebt));
618
- }
619
- const original = JSON.stringify(outbox.failedTerminalEntries());
620
- const transport = {
621
- push: async (_topic, event) => {
622
- if (event === 'adt_binding_ack') return {status: 'ok', response: {ok: true}};
623
- if (event === 'adt_binding_reconcile') {
624
- reconciliations += 1;
625
- if(testCase.control === 'repair-unavailable' && reconciliations > 1) return {status:'ok',response:{ok:true,adt:{verdict:'still_unavailable'}}};
626
- return {status: 'ok', response: {
627
- ok: true, adt: {verdict: 'already_applied', binding: testCase.control === 'malformed-binding' ? {session_id: 3600} : reconciledBinding},
628
- }};
629
- }
630
- throw new Error('unexpected terminal-debt fixture event: ' + event);
631
- },
632
- hardReset: () => {resets += 1; return true;},
633
- };
634
- const candidate = registerRequiredAdtCandidate({transport,
635
- identity: {thread_id: 'synthetic-terminal-debt', source_seq: 44, session_id: 3600,
636
- lease_epoch: ackLease, checkpoint_config_version: 3},
637
- installFreshBinding: raw => {
638
- const fresh = adoptAdtStreamBinding(raw, 44, 0);
639
- if (fresh.kind !== 'accepted') return false;
640
- if (testCase.localState === 'idle') return false;
641
- return installAdtPublicationBinding(session, fresh.session.binding, true).kind === 'accepted';
642
- },
643
- publicationSession: () => testCase.localState === 'idle' ? undefined : session,
644
- failedTerminalEntries: () => {
645
- const entries = outbox.failedTerminalEntries().map(entry => ({...entry,data:{...entry.data,
646
- ...(testCase.control === 'malformed-repair-presence' ? {terminal_repair:undefined} : {}),
647
- terminal_frame:{...entry.data.terminal_frame,session_id:testCase.control === 'foreign-debt' ? 3601 : 3600,
648
- lease_epoch:testCase.control === 'future-debt' ? 4 : testCase.control === 'fractional-debt' ? 1.5 : retainedLease}}}));
649
- if (testCase.control === 'missing-debt') return [];
650
- if (testCase.control === 'ambiguous-debt') return [...entries, {...entries[0], entrySeq: 62}];
651
- return entries;
652
- },
653
- repairTerminalDebt:async (fresh,authoritativeTerminal,authorize,evidenceEpoch)=>{
654
- if(evidenceEpoch !== retainedLease) throw new Error('repair callback received ACK lease instead of retained evidence');
655
- const result=await enqueueTerminalDebtRepair(outbox,{threadId:'synthetic-terminal-debt',sourceSeq:44,
656
- sessionId:3600,originalLeaseEpoch:evidenceEpoch,binding:fresh,authoritativeTerminal,authorize},()=>{});
657
- if(result.kind!=='ready') throw new Error('actual repair selector refused: '+result.message);
658
- repairs += 1;
659
- },
660
- onUnrecoverable: () => {restarts += 1;},
661
- log: (event,fields) => logs.push({event,fields}),
662
- });
663
- try {
664
- await acknowledgeRequiredAdtCandidate({topic: 'local_runner:fixture', payload: adopted.ackPayload, ticket: candidate});
665
- if (testCase.control !== 'unconsumed-provider' && consumeRequiredAdtAdmission(candidate).kind !== 'admitted') throw new Error('fixture provider was not admitted');
666
- session.emitter.fenced = true;
667
- session.done = true;
668
- for (let reconnect = 0; reconnect < 3; reconnect += 1) {
669
- closeRequiredAdtAdmissionForDisconnect(transport);
670
- await reconcileRequiredAdtCandidates({transport, topic: 'local_runner:fixture'});
671
- }
672
- return {resets, restarts, repairs, originalUnchanged:JSON.stringify(outbox.failedTerminalEntries())===original,
673
- corrections:outbox.pendingTerminalEntries().map(entry=>({originalLease:entry.data.terminal_repair?.original_lease_epoch,
674
- lease:entry.data.terminal_frame?.lease_epoch,body:entry.data.terminal_frame?.body})),
675
- retained: findRequiredAdtCandidate(transport,
676
- identity => identity.thread_id === 'synthetic-terminal-debt' && identity.source_seq === 44) === candidate,
677
- providerEffect: candidate.providerEffect, verdict: candidate.verdict,
678
- nextProviderAdmission: consumeRequiredAdtAdmission(candidate).kind,
679
- admission: requiredTransportFinalAdmission(transport).kind, logs};
680
- } finally {releaseRequiredAdtCandidate(candidate);}
681
- } finally {await outbox.close(0);}
682
- }
683
-
684
- async function handle(testCase) {
685
- switch (testCase.op) {
686
- case 'terminalDebtCold': {
687
- const events = [];
688
- let repairs = 0;
689
- const retainedEpoch = ['ack-before-frame','binding-before-frame'].includes(testCase.control) ? 2 : 1;
690
- const ackEpoch = ['ack-after-frame','binding-before-ack'].includes(testCase.control) ? 2 : 1;
691
- const freshEpoch = testCase.control.startsWith('binding-before-') ? 1 : testCase.control.startsWith('ack-') ? 4 : 2;
692
- const hasAnchor = testCase.control !== 'missing-anchor';
693
- const ackVersion = ['ready','authoritative-terminal','missing-anchor'].includes(testCase.control) ? 7 : 9;
694
- const identity = {thread_id:'synthetic-terminal-debt',source_seq:44,session_id:3600,lease_epoch:retainedEpoch,checkpoint_config_version:7};
695
- const anchor = testCase.control === 'malformed-anchor' ? null : {...identity,
696
- thread_id:testCase.control === 'foreign-anchor' ? 'foreign-thread' : identity.thread_id,
697
- lease_epoch:testCase.control === 'fractional-anchor' ? 1.5 : ackEpoch,checkpoint_config_version:ackVersion};
698
- const binding = {session_id:3600,lease_epoch:freshEpoch,next_frame_index:39,checkpoint_config:{version:8,thresholds:{max_bytes:512,max_deltas:1,max_interval_ms:2000}}};
699
- const transport = {push:async (_topic,event,payload) => {
700
- events.push(event);
701
- if(event === 'terminal_debt_identity') {
702
- if(testCase.control === 'disconnect') closeRequiredAdtAdmissionForDisconnect(transport);
703
- return {status:'ok',response:{ok:true,identity:{...identity,...(hasAnchor ? {ack_identity:anchor} : {}),...(testCase.control === 'foreign' ? {thread_id:'foreign-thread'} : {})}}};
704
- }
705
- if(event === 'adt_binding_reconcile') {
706
- if(payload.checkpoint_config_version !== ackVersion || payload.lease_epoch !== ackEpoch) throw new Error('cold lookup changed durable ACK identity');
707
- return {status:'ok',response:{ok:true,adt:{verdict:testCase.control === 'authoritative-terminal' ? 'authoritative_terminal' : testCase.control === 'missing-anchor' ? 'applied' : 'already_applied',binding}}};
708
- }
709
- throw new Error('cold recovery attempted unexpected event: '+event);
710
- }};
711
- const pipeline = {
712
- failedTerminalEntries:()=>[{entrySeq:61,kind:'adt.terminal_attempt',data:{seq:44,status:'processed',turn_id:'synthetic-completed-turn',terminal_frame:{session_id:3600,lease_epoch:retainedEpoch,frame_index:40,frame_kind:'terminal',assistant_phase:'final_answer',source_stream_key:'wrong-key',body:'Synthetic completed answer.'}}}],
713
- repairTerminalDebt:async request => {
714
- const terminal = testCase.control === 'authoritative-terminal';
715
- if(request.sessionId !== 3600 || request.originalLeaseEpoch !== retainedEpoch || request.sourceSeq !== 44 || request.binding !== (terminal ? null : binding) || request.authoritativeTerminal !== terminal) throw new Error('cold repair identity mismatch');
716
- if(!request.authorize({seq:44})) throw new Error('cold repair unexpectedly unauthorized');
717
- repairs += 1;
718
- return {kind:'ready',id:'fixture',serializedData:'fixture'};
719
- },
720
- };
721
- try {
722
- await recoverRetainedTerminalDebt({transport,topic:'local_runner:fixture',threadId:identity.thread_id,pipeline,log:()=>{}});
723
- return {events,repairs};
724
- } finally {
725
- const candidate = findRequiredAdtCandidate(transport, value => value.thread_id === identity.thread_id);
726
- if(candidate !== undefined) releaseRequiredAdtCandidate(candidate);
727
- }
728
- }
729
- case 'terminalDebtStorm':
730
- return await terminalDebtStorm(testCase);
731
- case 'terminalDebtJournal':
732
- return await terminalDebtJournal(testCase);
733
- case 'controlDispatch':
734
- return await handleControlDispatch(testCase);
735
- case 'staleness':
736
- return handleStaleness(testCase);
737
- case 'respawn':
738
- return await handleRespawn(testCase);
739
- default:
740
- return { threw: true, message: 'unknown op ' + String(testCase.op) };
741
- }
742
- }
743
-
744
- let stdin = '';
745
- process.stdin.setEncoding('utf8');
746
- for await (const chunk of process.stdin) {
747
- stdin += chunk;
748
- }
749
- const cases = JSON.parse(stdin);
750
- const results = [];
751
- for (const testCase of cases) {
752
- results.push(await handle(testCase));
753
- }
754
- // Exit only after stdout is fully flushed: the runner graph can leave
755
- // unref'd handles alive, so the driver exits explicitly - but a bare
756
- // process.exit(0) truncates large result arrays mid-pipe.
757
- process.stdout.write(JSON.stringify(results), () => {
758
- process.exit(0);
759
- });
760
- `;
761
-
762
- await mkdir(join(packageRoot, '.differential'), { recursive: true });
763
-
764
- // runner.ts's graph resolves assets/ relative to the bundle at import time
765
- // (same requirement as build-transport-parity-oracle.mjs).
766
- await mkdir(join(packageRoot, '.differential/assets'), { recursive: true });
767
- await copyFile(
768
- join(packageRoot, 'src/assets/linzumi-logo.svg'),
769
- join(packageRoot, '.differential/assets/linzumi-logo.svg')
770
- );
771
-
772
- await build({
773
- stdin: {
774
- contents: driverSource,
775
- resolveDir: packageRoot,
776
- sourcefile: 'core-commander-seams-parity-driver.ts',
777
- loader: 'ts',
778
- },
779
- bundle: true,
780
- // Spec: plans/2026-09-09-ts-native-account-continuation.md. Match the
781
- // production/auth-oracle ESM bridge for reachable CJS runtime dependencies;
782
- // the distinct banner binding cannot collide with bundled createRequire.
783
- banner: {
784
- js: "import { createRequire as __coreCommanderSeamsOracleCreateRequire } from 'node:module';\nconst require = __coreCommanderSeamsOracleCreateRequire(import.meta.url);",
785
- },
786
- platform: 'node',
787
- target: 'node20',
788
- format: 'esm',
789
- outfile: join(
790
- packageRoot,
791
- '.differential/core-commander-seams-parity-oracle.mjs'
792
- ),
793
- minify: false,
794
- sourcemap: false,
795
- legalComments: 'none',
796
- // runner.ts pulls the wider commander graph; the same runtime externals
797
- // as the differential entry build stay external.
798
- external: ['ws', 'undici', 'blessed', '@anthropic-ai/claude-agent-sdk'],
799
- });