@linzumi/cli 1.0.95 → 1.0.97

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,520 @@
1
+ // Spec: kandan/plans/2026-07-10-compute-nodes-rescript-commander-zero-ts-program.md
2
+ // (M3 cluster 2, config-identity).
3
+ // Relationship: Builds the TS-side PARITY ORACLE for the config/identity
4
+ // cluster of the ReScript commander port, the sibling of
5
+ // build-protocol-parity-oracle.mjs (cluster 1). The oracle bundles the REAL
6
+ // TS config/identity modules (localConfig.ts, machineFingerprint.ts,
7
+ // machineFingerprintV2.ts, authCache.ts, the cursor-store exports of
8
+ // runner.ts, controlQuarantine.ts's state-file stem, updateNudge.ts's
9
+ // restart-attempt store) behind a one-shot batch driver: a JSON array of
10
+ // cases on stdin, a JSON array of results on stdout. The ReScript package's
11
+ // ConfigIdentityParityConformance drives the SAME inputs through the ported
12
+ // modules in its own scratch directories and asserts
13
+ // accept/reject/normalized-output equivalence AND byte-identical file
14
+ // output - the cross-impl round-trip contract that lets both commanders
15
+ // share ~/.linzumi through M4.
16
+ //
17
+ // Determinism: every source of nondeterminism is pinned per case - id
18
+ // creators are injected constants, timestamps come from a fixed `nowMs`
19
+ // (writeLocalSignupAuth's injectable `now`; a scoped global-Date override
20
+ // for authCache, whose issuedAt is not injectable), and scratch paths are
21
+ // normalized through the "$DIR" placeholder in both directions.
22
+ //
23
+ // SECRETS: the oracle only ever sees the conformance suite's synthetic
24
+ // tokens; nothing here logs case payloads.
25
+ //
26
+ // Like the cluster 1 oracle, the output is a local test artifact
27
+ // (.differential/ is gitignored, never published) and stays unminified for
28
+ // debuggability.
29
+ import { copyFile, 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 {
38
+ mkdtempSync,
39
+ mkdirSync,
40
+ readdirSync,
41
+ readFileSync,
42
+ realpathSync,
43
+ statSync,
44
+ writeFileSync,
45
+ } from 'node:fs';
46
+ import { tmpdir } from 'node:os';
47
+ import { join, relative } from 'node:path';
48
+ import {
49
+ addAllowedCwd,
50
+ addAllowedCwdForLinzumiUrl,
51
+ ensureLocalMachineId,
52
+ ensureLocalMachineIdForLinzumiUrl,
53
+ ensureLocalRunnerId,
54
+ ensureLocalRunnerIdForLinzumiUrl,
55
+ localMachineIdSeedPath,
56
+ localRunnerIdSeedPath,
57
+ readConfiguredAllowedCwdDetails,
58
+ readConfiguredAllowedCwdDetailsForLinzumiUrl,
59
+ readLocalConfig,
60
+ readLocalConfigForLinzumiUrl,
61
+ readLocalSignupAuth,
62
+ removeAllowedCwd,
63
+ removeAllowedCwdForLinzumiUrl,
64
+ replaceAllowedCwdsForLinzumiUrl,
65
+ writeLocalConfig,
66
+ writeLocalSignupAuth,
67
+ writeLocalSignupCompletion,
68
+ } from './src/localConfig';
69
+ import {
70
+ rawStableMachineIdentifier,
71
+ stableMachineFingerprint,
72
+ stableMachineId,
73
+ } from './src/machineFingerprint';
74
+ import {
75
+ machineFingerprintV2HelloFields,
76
+ rawOsUsername,
77
+ stableMachineFingerprintV2,
78
+ } from './src/machineFingerprintV2';
79
+ import {
80
+ readCachedLocalRunnerToken,
81
+ readPersonalAgentDelegationToken,
82
+ writeCachedLocalRunnerToken,
83
+ } from './src/authCache';
84
+ import {
85
+ createControlCursorFileStore,
86
+ createRunnerControlEpochStore,
87
+ } from './src/runner';
88
+ import { runnerStateFileStem } from './src/controlQuarantine';
89
+ import { fileRestartAttemptStore } from './src/updateNudge';
90
+
91
+ // --- Placeholder + snapshot plumbing --------------------------------------------
92
+
93
+ const dirPlaceholder = '$DIR';
94
+
95
+ function scratch() {
96
+ // realpath so macOS /var -> /private/var never splits the two impls'
97
+ // placeholder substitution.
98
+ return realpathSync(mkdtempSync(join(tmpdir(), 'linzumi-config-identity-oracle-')));
99
+ }
100
+
101
+ function substitute(value, from, to) {
102
+ if (typeof value === 'string') {
103
+ return value.split(from).join(to);
104
+ }
105
+ if (Array.isArray(value)) {
106
+ return value.map((entry) => substitute(entry, from, to));
107
+ }
108
+ if (typeof value === 'object' && value !== null) {
109
+ return Object.fromEntries(
110
+ Object.entries(value).map(([key, entry]) => [
111
+ substitute(key, from, to),
112
+ substitute(entry, from, to),
113
+ ])
114
+ );
115
+ }
116
+ return value;
117
+ }
118
+
119
+ function snapshotFiles(dir) {
120
+ const files = {};
121
+ const walk = (current) => {
122
+ for (const name of readdirSync(current).sort()) {
123
+ const full = join(current, name);
124
+ if (statSync(full).isDirectory()) {
125
+ walk(full);
126
+ } else {
127
+ files[relative(dir, full)] = readFileSync(full, 'utf8');
128
+ }
129
+ }
130
+ };
131
+ walk(dir);
132
+ return files;
133
+ }
134
+
135
+ function outcome(run) {
136
+ try {
137
+ const value = run();
138
+ return value === undefined ? { defined: false } : { defined: true, value };
139
+ } catch (error) {
140
+ return {
141
+ threw: true,
142
+ message: error instanceof Error ? error.message : String(error),
143
+ };
144
+ }
145
+ }
146
+
147
+ const RealDate = Date;
148
+
149
+ function withFixedNow(nowMs, run) {
150
+ if (nowMs === undefined) {
151
+ return run();
152
+ }
153
+ class FixedDate extends RealDate {
154
+ constructor(...args) {
155
+ if (args.length === 0) {
156
+ super(nowMs);
157
+ } else {
158
+ super(...args);
159
+ }
160
+ }
161
+ static now() {
162
+ return nowMs;
163
+ }
164
+ }
165
+ globalThis.Date = FixedDate;
166
+ try {
167
+ return run();
168
+ } finally {
169
+ globalThis.Date = RealDate;
170
+ }
171
+ }
172
+
173
+ // --- Config lifecycle ------------------------------------------------------------
174
+
175
+ function runConfigAction(action, dir, configPath) {
176
+ switch (action.fn) {
177
+ case 'mkdir':
178
+ // Setup helper (not a ported function): void the created-path return
179
+ // so both impls report the same undefined outcome.
180
+ return outcome(() => {
181
+ mkdirSync(action.path, { recursive: true });
182
+ });
183
+ case 'writeFile':
184
+ return outcome(() => writeFileSync(action.path, action.contents, 'utf8'));
185
+ case 'ensureLocalMachineId':
186
+ return outcome(() =>
187
+ ensureLocalMachineId(configPath, () => action.machineId)
188
+ );
189
+ case 'ensureLocalMachineIdForLinzumiUrl':
190
+ return outcome(() =>
191
+ ensureLocalMachineIdForLinzumiUrl(
192
+ action.linzumiUrl,
193
+ configPath,
194
+ () => action.machineId
195
+ )
196
+ );
197
+ case 'ensureLocalRunnerId':
198
+ return outcome(() =>
199
+ ensureLocalRunnerId(configPath, () => action.runnerId)
200
+ );
201
+ case 'ensureLocalRunnerIdForLinzumiUrl':
202
+ return outcome(() =>
203
+ ensureLocalRunnerIdForLinzumiUrl(
204
+ action.linzumiUrl,
205
+ configPath,
206
+ () => action.runnerId
207
+ )
208
+ );
209
+ case 'machineIdSeedPath':
210
+ return outcome(() => localMachineIdSeedPath(configPath, action.linzumiUrl));
211
+ case 'runnerIdSeedPath':
212
+ return outcome(() => localRunnerIdSeedPath(configPath, action.linzumiUrl));
213
+ case 'writeLocalConfig':
214
+ return outcome(() => writeLocalConfig(action.config, configPath));
215
+ case 'addAllowedCwd':
216
+ return outcome(() => addAllowedCwd(action.pathValue, configPath));
217
+ case 'addAllowedCwdForLinzumiUrl':
218
+ return outcome(() =>
219
+ addAllowedCwdForLinzumiUrl(action.pathValue, action.linzumiUrl, configPath)
220
+ );
221
+ case 'removeAllowedCwd':
222
+ return outcome(() => removeAllowedCwd(action.pathValue, configPath));
223
+ case 'removeAllowedCwdForLinzumiUrl':
224
+ return outcome(() =>
225
+ removeAllowedCwdForLinzumiUrl(action.pathValue, action.linzumiUrl, configPath)
226
+ );
227
+ case 'replaceAllowedCwdsForLinzumiUrl':
228
+ return outcome(() =>
229
+ replaceAllowedCwdsForLinzumiUrl(action.pathValues, action.linzumiUrl, configPath)
230
+ );
231
+ case 'readLocalConfig':
232
+ return outcome(() => readLocalConfig(configPath));
233
+ case 'readLocalConfigForLinzumiUrl':
234
+ return outcome(() => readLocalConfigForLinzumiUrl(action.linzumiUrl, configPath));
235
+ case 'readConfiguredAllowedCwdDetails':
236
+ return outcome(() => readConfiguredAllowedCwdDetails(configPath));
237
+ case 'readConfiguredAllowedCwdDetailsForLinzumiUrl':
238
+ return outcome(() =>
239
+ readConfiguredAllowedCwdDetailsForLinzumiUrl(action.linzumiUrl, configPath)
240
+ );
241
+ case 'readLocalSignupAuth':
242
+ return outcome(() => readLocalSignupAuth(configPath));
243
+ case 'writeLocalSignupAuth':
244
+ return outcome(() =>
245
+ writeLocalSignupAuth(
246
+ {
247
+ ...action.auth,
248
+ now: action.auth.nowMs === undefined ? undefined : new RealDate(action.auth.nowMs),
249
+ },
250
+ configPath
251
+ )
252
+ );
253
+ case 'writeLocalSignupCompletion':
254
+ return outcome(() =>
255
+ writeLocalSignupCompletion(
256
+ {
257
+ ...action.completion,
258
+ now:
259
+ action.completion.nowMs === undefined
260
+ ? undefined
261
+ : new RealDate(action.completion.nowMs),
262
+ },
263
+ configPath
264
+ )
265
+ );
266
+ default:
267
+ return { threw: true, message: 'unknown config action ' + String(action.fn) };
268
+ }
269
+ }
270
+
271
+ function handleConfigLifecycle(testCase) {
272
+ const dir = scratch();
273
+ const configPath = join(dir, 'config.json');
274
+ const actions = substitute(testCase.actions, dirPlaceholder, dir);
275
+ const results = actions.map((action) => runConfigAction(action, dir, configPath));
276
+ return substitute({ results, files: snapshotFiles(dir) }, dir, dirPlaceholder);
277
+ }
278
+
279
+ // --- Auth lifecycle ----------------------------------------------------------------
280
+
281
+ function runAuthAction(action, authFilePath) {
282
+ switch (action.fn) {
283
+ case 'writeFile':
284
+ return outcome(() => writeFileSync(authFilePath, action.contents, 'utf8'));
285
+ case 'writeCachedLocalRunnerToken':
286
+ return outcome(() =>
287
+ writeCachedLocalRunnerToken({
288
+ kandanUrl: action.kandanUrl,
289
+ accessToken: action.accessToken,
290
+ expiresInSeconds: action.expiresInSeconds,
291
+ authFilePath,
292
+ })
293
+ );
294
+ case 'readCachedLocalRunnerToken':
295
+ return outcome(() => readCachedLocalRunnerToken(action.kandanUrl, authFilePath));
296
+ case 'readPersonalAgentDelegationToken':
297
+ return outcome(() => readPersonalAgentDelegationToken(authFilePath));
298
+ default:
299
+ return { threw: true, message: 'unknown auth action ' + String(action.fn) };
300
+ }
301
+ }
302
+
303
+ function handleAuthLifecycle(testCase) {
304
+ const dir = scratch();
305
+ const authFilePath = join(dir, 'auth.json');
306
+ const actions = substitute(testCase.actions, dirPlaceholder, dir);
307
+ const results = actions.map((action) =>
308
+ withFixedNow(testCase.nowMs, () => runAuthAction(action, authFilePath))
309
+ );
310
+ return substitute({ results, files: snapshotFiles(dir) }, dir, dirPlaceholder);
311
+ }
312
+
313
+ // --- Fingerprint probes ---------------------------------------------------------------
314
+
315
+ function handleFingerprint(testCase) {
316
+ const spec = testCase.probes ?? {};
317
+ const probes = {
318
+ ...(spec.platform === undefined ? {} : { platform: spec.platform }),
319
+ execFile: () => {
320
+ if (spec.execFileOutput === undefined) {
321
+ throw new Error('execFile probe failed');
322
+ }
323
+ return spec.execFileOutput;
324
+ },
325
+ readFile: (path) => {
326
+ const contents = (spec.readFiles ?? {})[path];
327
+ if (contents === undefined) {
328
+ throw new Error('readFile probe failed: ' + path);
329
+ }
330
+ return contents;
331
+ },
332
+ username: () => {
333
+ if (spec.username === undefined) {
334
+ throw new Error('username probe failed');
335
+ }
336
+ return spec.username;
337
+ },
338
+ };
339
+ return {
340
+ raw: outcome(() => rawStableMachineIdentifier(probes)),
341
+ v1: outcome(() => stableMachineFingerprint(probes)),
342
+ machineId: outcome(() => stableMachineId(probes)),
343
+ rawUsername: outcome(() => rawOsUsername(probes)),
344
+ v2: outcome(() => stableMachineFingerprintV2(probes)),
345
+ helloFields: outcome(() =>
346
+ machineFingerprintV2HelloFields(stableMachineFingerprintV2(probes))
347
+ ),
348
+ };
349
+ }
350
+
351
+ // --- Cursor store ------------------------------------------------------------------------
352
+
353
+ function collectingLog(events, dir) {
354
+ return (event, payload) => {
355
+ events.push({ event, payload: substitute(payload, dir, dirPlaceholder) });
356
+ };
357
+ }
358
+
359
+ function runStoreAction(store, action) {
360
+ switch (action.fn) {
361
+ case 'initial':
362
+ return outcome(() => store.initial(action.topic));
363
+ case 'onAdvance':
364
+ return outcome(() => store.onAdvance(action.topic, action.seq));
365
+ case 'reset':
366
+ return outcome(() => store.reset(action.topic, action.seq));
367
+ case 'adoptEpoch':
368
+ return outcome(() => store.adoptEpoch(action.epoch));
369
+ case 'epoch':
370
+ return outcome(() => store.epoch());
371
+ case 'flush':
372
+ return outcome(() => store.flush());
373
+ default:
374
+ return { threw: true, message: 'unknown store action ' + String(action.fn) };
375
+ }
376
+ }
377
+
378
+ function readFileOrNull(path) {
379
+ try {
380
+ return readFileSync(path, 'utf8');
381
+ } catch {
382
+ return null;
383
+ }
384
+ }
385
+
386
+ function handleCursorStore(testCase) {
387
+ const dir = scratch();
388
+ const path = join(dir, 'store.json');
389
+ if (testCase.initialContents !== undefined) {
390
+ writeFileSync(path, testCase.initialContents, 'utf8');
391
+ }
392
+ const events = [];
393
+ const store = createControlCursorFileStore(path, collectingLog(events, dir), {
394
+ ...(testCase.discardSeqsOnFirstEpochAdoption === undefined
395
+ ? {}
396
+ : { discardSeqsOnFirstEpochAdoption: testCase.discardSeqsOnFirstEpochAdoption }),
397
+ ...(testCase.fsyncOnWrite === undefined
398
+ ? {}
399
+ : { fsyncOnWrite: testCase.fsyncOnWrite }),
400
+ });
401
+ const results = (testCase.actions ?? []).map((action) => runStoreAction(store, action));
402
+ store.flush();
403
+ return { results, fileBytes: readFileOrNull(path), events };
404
+ }
405
+
406
+ function handleEpochStore(testCase) {
407
+ const dir = scratch();
408
+ const cursorPath = join(dir, 'cursor.json');
409
+ const startTurnPath = join(dir, 'start-turn.json');
410
+ if (testCase.cursorContents !== undefined) {
411
+ writeFileSync(cursorPath, testCase.cursorContents, 'utf8');
412
+ }
413
+ if (testCase.startTurnContents !== undefined) {
414
+ writeFileSync(startTurnPath, testCase.startTurnContents, 'utf8');
415
+ }
416
+ const events = [];
417
+ const log = collectingLog(events, dir);
418
+ const cursorStore = createControlCursorFileStore(cursorPath, log);
419
+ const startTurnStore = createControlCursorFileStore(startTurnPath, log, {
420
+ discardSeqsOnFirstEpochAdoption: true,
421
+ });
422
+ const epochStore = createRunnerControlEpochStore(cursorStore, startTurnStore, log, {
423
+ runnerId: testCase.runnerId,
424
+ kandanUrl: testCase.kandanUrl,
425
+ });
426
+ const initialEpoch = outcome(() => epochStore.current());
427
+ const adoptResults = (testCase.adopts ?? []).map((adopt) =>
428
+ outcome(() => epochStore.adopt(adopt.topic, adopt.epoch))
429
+ );
430
+ cursorStore.flush();
431
+ startTurnStore.flush();
432
+ return {
433
+ initialEpoch,
434
+ adoptResults,
435
+ cursorBytes: readFileOrNull(cursorPath),
436
+ startTurnBytes: readFileOrNull(startTurnPath),
437
+ events,
438
+ };
439
+ }
440
+
441
+ // --- Restart-attempt store -----------------------------------------------------------------
442
+
443
+ function handleRestartAttemptStore(testCase) {
444
+ const dir = scratch();
445
+ const path = join(dir, 'attempt.json');
446
+ if (testCase.initialContents !== undefined) {
447
+ writeFileSync(path, testCase.initialContents, 'utf8');
448
+ }
449
+ const store = fileRestartAttemptStore(path);
450
+ const loaded = outcome(() => store.load());
451
+ let saved = { defined: false };
452
+ if (testCase.record !== undefined) {
453
+ saved = outcome(() => store.save(testCase.record));
454
+ }
455
+ return { loaded, saved, fileBytes: readFileOrNull(path) };
456
+ }
457
+
458
+ // --- Dispatch --------------------------------------------------------------------------------
459
+
460
+ function handle(testCase) {
461
+ switch (testCase.op) {
462
+ case 'configLifecycle':
463
+ return handleConfigLifecycle(testCase);
464
+ case 'authLifecycle':
465
+ return handleAuthLifecycle(testCase);
466
+ case 'fingerprint':
467
+ return handleFingerprint(testCase);
468
+ case 'cursorStore':
469
+ return handleCursorStore(testCase);
470
+ case 'epochStore':
471
+ return handleEpochStore(testCase);
472
+ case 'stateFileStem':
473
+ return outcome(() => runnerStateFileStem(testCase.runnerId));
474
+ case 'restartAttemptStore':
475
+ return handleRestartAttemptStore(testCase);
476
+ default:
477
+ return { threw: true, message: 'unknown op ' + String(testCase.op) };
478
+ }
479
+ }
480
+
481
+ let stdin = '';
482
+ process.stdin.setEncoding('utf8');
483
+ for await (const chunk of process.stdin) {
484
+ stdin += chunk;
485
+ }
486
+ const cases = JSON.parse(stdin);
487
+ process.stdout.write(JSON.stringify(cases.map(handle)));
488
+ `;
489
+
490
+ await mkdir(join(packageRoot, '.differential'), { recursive: true });
491
+
492
+ // runner.ts's graph resolves assets/ relative to the bundle at import time
493
+ // (same requirement as build-differential-entry.mjs).
494
+ await mkdir(join(packageRoot, '.differential/assets'), { recursive: true });
495
+ await copyFile(
496
+ join(packageRoot, 'src/assets/linzumi-logo.svg'),
497
+ join(packageRoot, '.differential/assets/linzumi-logo.svg')
498
+ );
499
+
500
+ await build({
501
+ stdin: {
502
+ contents: driverSource,
503
+ resolveDir: packageRoot,
504
+ sourcefile: 'config-identity-parity-driver.ts',
505
+ loader: 'ts',
506
+ },
507
+ bundle: true,
508
+ platform: 'node',
509
+ target: 'node20',
510
+ format: 'esm',
511
+ outfile: join(packageRoot, '.differential/config-identity-parity-oracle.mjs'),
512
+ minify: false,
513
+ sourcemap: false,
514
+ legalComments: 'none',
515
+ // runner.ts pulls the wider commander graph; the same runtime externals
516
+ // as the differential entry build stay external (they are installed in
517
+ // this package's node_modules, and the oracle only exercises the
518
+ // config/identity exports).
519
+ external: ['ws', 'undici', 'blessed', '@anthropic-ai/claude-agent-sdk'],
520
+ });