@optimystic/reference-peer 0.27.0 → 0.29.0

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.
package/src/cli.ts CHANGED
@@ -1,909 +1,927 @@
1
- #!/usr/bin/env node
2
- import { Command, InvalidArgumentError } from 'commander';
3
- import { multiaddr } from '@multiformats/multiaddr';
4
- import debug from 'debug';
5
- import { getNetworkManager, createLibp2pNode, MemoryRawStorage, RepoClient, ArachnodeFretAdapter, type IRawStorage } from '@optimystic/db-p2p';
6
- import { FileRawStorage } from '@optimystic/db-p2p-storage-fs';
7
- import { Diary, NetworkTransactor, BTree, type ITransactor, type BlockGets, type GetBlockResults, type ActionBlocks, type BlockActionStatus, type PendRequest, type PendResult, type CommitRequest, type CommitResult } from '@optimystic/db-core';
8
- import * as readline from 'readline';
9
- import * as path from 'path';
10
- import * as fs from 'fs';
11
-
12
- const logDebug = debug('optimystic:ref-peer');
13
-
14
- // Simple local transactor for single-node scenarios
15
- class LocalTransactor implements ITransactor {
16
- constructor(private storageRepo: any) { }
17
-
18
- async get(blockGets: BlockGets): Promise<GetBlockResults> {
19
- return await this.storageRepo.get(blockGets);
20
- }
21
-
22
- async getStatus(_actionRefs: ActionBlocks[]): Promise<BlockActionStatus[]> {
23
- throw new Error("Method not implemented.");
24
- }
25
-
26
- async pend(blockAction: PendRequest): Promise<PendResult> {
27
- return await this.storageRepo.pend(blockAction);
28
- }
29
-
30
- async commit(request: CommitRequest): Promise<CommitResult> {
31
- return await this.storageRepo.commit(request);
32
- }
33
-
34
- async cancel(actionRef: ActionBlocks): Promise<void> {
35
- return await this.storageRepo.cancel(actionRef);
36
- }
37
- }
38
-
39
- interface NetworkSession {
40
- node: any;
41
- transactor: NetworkTransactor | LocalTransactor;
42
- diaries: Map<string, Diary<any>>;
43
- trees: Map<string, BTree<any, any>>;
44
- isConnected: boolean;
45
- isSingleNode: boolean; // Track if we're in single-node mode
46
- }
47
-
48
- class PeerSession {
49
- private session: NetworkSession | null = null;
50
- private rl: readline.Interface | null = null;
51
-
52
- private parseStorageCapacity(options: { storageCapacity?: string }): number | undefined {
53
- if (!options.storageCapacity) return undefined;
54
- const parsed = Number(options.storageCapacity);
55
- if (!Number.isFinite(parsed) || parsed <= 0) {
56
- throw new Error('--storage-capacity must be a positive number of bytes');
57
- }
58
- return parsed;
59
- }
60
-
61
- private parseClusterSize(options: { clusterSize?: string }): number | undefined {
62
- if (options.clusterSize === undefined) return undefined;
63
- const parsed = Number(options.clusterSize);
64
- if (!Number.isInteger(parsed) || parsed <= 0) {
65
- throw new Error('--cluster-size must be a positive integer');
66
- }
67
- return parsed;
68
- }
69
-
70
- private parseAssumedClusterSize(options: { assumedClusterSize?: string }): number | undefined {
71
- if (options.assumedClusterSize === undefined) return undefined;
72
- const parsed = Number(options.assumedClusterSize);
73
- if (!Number.isInteger(parsed) || parsed <= 0) {
74
- throw new Error('--assumed-cluster-size must be a positive integer');
75
- }
76
- return parsed;
77
- }
78
-
79
- private parseSuperMajorityThreshold(options: { superMajorityThreshold?: string }): number | undefined {
80
- if (options.superMajorityThreshold === undefined) return undefined;
81
- const parsed = Number(options.superMajorityThreshold);
82
- if (!Number.isFinite(parsed) || parsed <= 0 || parsed > 1) {
83
- throw new Error('--super-majority-threshold must be a number in (0, 1]');
84
- }
85
- return parsed;
86
- }
87
-
88
- private async waitForFretReady(node: any): Promise<void> {
89
- try {
90
- const fret = (node as any).services?.fret;
91
- if (!fret) {
92
- console.log('⚠️ FRET service not available');
93
- logDebug('FRET service missing on node');
94
- return;
95
- }
96
-
97
- const hadConn = node.getConnections().length > 0;
98
- if (!hadConn) {
99
- console.log('🔗 No connections yet, skipping FRET warm-up');
100
- logDebug('skipping FRET ready check - no connections');
101
- return;
102
- }
103
-
104
- if (typeof fret.ready !== 'function') {
105
- console.log('⚠️ FRET service does not expose ready()');
106
- logDebug('FRET ready() not present, skipping wait');
107
- return;
108
- }
109
- logDebug('waiting for FRET ready');
110
- await fret.ready();
111
- console.log('✅ FRET service ready');
112
-
113
- // Log FRET diagnostics
114
- const knownPeers = typeof fret.listPeers === 'function' ? fret.listPeers() : [];
115
- const netSize = typeof fret.getNetworkSizeEstimate === 'function' ? fret.getNetworkSizeEstimate() : undefined;
116
- logDebug('FRET diagnostics after ready', {
117
- knownPeers: knownPeers.map((p: any) => p.id ?? p.toString()),
118
- knownPeerCount: knownPeers.length,
119
- networkSizeEstimate: netSize
120
- });
121
- console.log(`📊 FRET knows ${knownPeers.length} peer(s)`);
122
- } catch (error) {
123
- console.warn('⚠️ FRET readiness check issue:', error);
124
- logDebug('FRET readiness check issue', error);
125
- }
126
- }
127
-
128
- private async waitForFretConvergence(node: any, minPeers: number, timeoutMs: number): Promise<boolean> {
129
- const fret = (node as any).services?.fret;
130
- if (!fret || typeof fret.listPeers !== 'function') {
131
- logDebug('FRET convergence check skipped - no listPeers method');
132
- return false;
133
- }
134
-
135
- const start = Date.now();
136
- let lastCount = 0;
137
- while (Date.now() - start < timeoutMs) {
138
- const peers = fret.listPeers();
139
- const count = Array.isArray(peers) ? peers.length : 0;
140
- if (count !== lastCount) {
141
- logDebug('FRET convergence progress', { peerCount: count, target: minPeers, peers: peers.map((p: any) => p.id) });
142
- lastCount = count;
143
- }
144
- if (count >= minPeers) {
145
- console.log(`✅ FRET discovered ${count} peer(s)`);
146
- return true;
147
- }
148
- await new Promise(r => setTimeout(r, 200));
149
- }
150
-
151
- const finalPeers = fret.listPeers();
152
- const finalCount = Array.isArray(finalPeers) ? finalPeers.length : 0;
153
- console.log(`✅ FRET discovered ${finalCount} peer(s)`);
154
- logDebug('FRET convergence completed', {
155
- finalPeerCount: finalCount,
156
- targetPeers: minPeers,
157
- elapsed: timeoutMs,
158
- peers: finalPeers.map((p: any) => p.id)
159
- });
160
- // Return true if we have at least some peers, even if not the target
161
- return finalCount > 0;
162
- }
163
-
164
- private logRingInfo(node: any, totalCapacityOverride?: number): void {
165
- const fret = (node as any).services?.fret;
166
- if (!fret) {
167
- logDebug('ring info unavailable (no FRET service)');
168
- return;
169
- }
170
- const adapter = new ArachnodeFretAdapter(fret, node.peerId?.toString());
171
- const myInfo = adapter.getMyArachnodeInfo();
172
- if (myInfo) {
173
- logDebug('local arachnode info', myInfo);
174
- } else {
175
- logDebug('no arachnode info published yet');
176
- }
177
- const rings = adapter.getKnownRings();
178
- const stats = adapter.getRingStats();
179
- logDebug('discovered ring depths', rings);
180
- if (stats.length) {
181
- logDebug('ring statistics', stats);
182
- }
183
- if (totalCapacityOverride) {
184
- logDebug('storage capacity override active', { bytes: totalCapacityOverride });
185
- }
186
- }
187
-
188
- private async ensureDiary(name: string): Promise<Diary<any>> {
189
- const session = this.requireSession();
190
- const existing = session.diaries.get(name);
191
- if (existing) return existing;
192
- // Diary.createOrOpen uses Collection.createOrOpen under the hood, so this will
193
- // attach to an existing diary in the network or create it if missing.
194
- const diary = await Diary.createOrOpen(session.transactor, name);
195
- session.diaries.set(name, diary);
196
- return diary;
197
- }
198
-
199
- async startNetwork(options: {
200
- port?: string;
201
- wsPort?: string;
202
- wsHost?: string;
203
- tcp?: boolean;
204
- bootstrap?: string;
205
- bootstrapFile?: string;
206
- id?: string;
207
- relay?: boolean;
208
- network?: string;
209
- fretProfile?: 'edge' | 'core';
210
- storage?: 'memory' | 'file';
211
- storagePath?: string;
212
- storageCapacity?: string;
213
- clusterSize?: string;
214
- assumedClusterSize?: string;
215
- superMajorityThreshold?: string;
216
- announceFile?: string;
217
- announceAddr?: string[];
218
- appendAnnounceAddr?: string[];
219
- offline?: boolean;
220
- }): Promise<void> {
221
- if (this.session?.isConnected) {
222
- console.log('⚠️ Already connected to network');
223
- return;
224
- }
225
-
226
- console.log('🚀 Starting P2P node...');
227
-
228
- const resolveEffectiveRelay = (): boolean => {
229
- if (options.relay === false) return false;
230
- const wsPortRaw = options.wsPort;
231
- const wsPortConfigured = wsPortRaw !== undefined && wsPortRaw !== '';
232
- const tcpEnabled = options.tcp !== false;
233
- const hasInboundListen = tcpEnabled || wsPortConfigured;
234
- return hasInboundListen;
235
- };
236
- const effectiveRelay = resolveEffectiveRelay();
237
- logDebug('resolved relay default', {
238
- explicit: options.relay,
239
- tcp: options.tcp !== false,
240
- wsPort: options.wsPort,
241
- offline: options.offline,
242
- effectiveRelay
243
- });
244
-
245
- // Validate storage options
246
- if (options.storage === 'file' && !options.storagePath) {
247
- throw new Error('--storage-path is required when using file storage');
248
- }
249
-
250
- // Create storage directory if needed
251
- if (options.storage === 'file' && options.storagePath) {
252
- fs.mkdirSync(options.storagePath, { recursive: true });
253
- }
254
-
255
- // Resolve bootstrap nodes from CLI args and/or file
256
- let bootstrapNodes: string[] = options.bootstrap ? options.bootstrap.split(',') : [];
257
- if (options.bootstrapFile) {
258
- try {
259
- const filePath = path.resolve(options.bootstrapFile);
260
- const stat = fs.statSync(filePath);
261
-
262
- // If it's a directory, wait for mesh-ready.json and use it
263
- if (stat.isDirectory()) {
264
- const readyFile = path.join(filePath, 'mesh-ready.json');
265
-
266
- // Wait for mesh-ready.json (up to 30 seconds)
267
- console.log('⏳ Waiting for mesh to be ready...');
268
- const waitStart = Date.now();
269
- while (!fs.existsSync(readyFile) && Date.now() - waitStart < 30000) {
270
- await new Promise(r => setTimeout(r, 100));
271
- }
272
-
273
- if (fs.existsSync(readyFile)) {
274
- // Use mesh-ready.json which has current node info
275
- const readyContents = fs.readFileSync(readyFile, 'utf-8');
276
- const readyJson = JSON.parse(readyContents) as { ready: boolean; nodes: { peerId: string; multiaddrs: string[] }[] };
277
- logDebug('loading bootstrap from mesh-ready', { nodeCount: readyJson.nodes.length });
278
-
279
- for (const node of readyJson.nodes) {
280
- if (Array.isArray(node.multiaddrs) && node.multiaddrs.length > 0) {
281
- // Prefer localhost for same-machine testing
282
- const localAddr = node.multiaddrs.find(a => a.includes('/ip4/127.0.0.1/'));
283
- bootstrapNodes.push(localAddr ?? node.multiaddrs[0]!);
284
- logDebug('loaded bootstrap from mesh-ready', { peerId: node.peerId, addr: localAddr ?? node.multiaddrs[0] });
285
- }
286
- }
287
- console.log(`📋 Loaded ${bootstrapNodes.length} bootstrap address(es) from mesh-ready.json`);
288
- } else {
289
- console.warn('⚠️ Timeout waiting for mesh-ready.json, falling back to node-*.json files');
290
- // Fallback to old behavior
291
- const files = fs.readdirSync(filePath).filter(f => f.startsWith('node-') && f.endsWith('.json'));
292
- logDebug('loading bootstrap from directory (fallback)', { dir: filePath, files });
293
- for (const file of files) {
294
- const fullPath = path.join(filePath, file);
295
- try {
296
- const contents = fs.readFileSync(fullPath, 'utf-8');
297
- const json = JSON.parse(contents) as { multiaddrs?: string[]; peerId?: string };
298
- if (Array.isArray(json.multiaddrs) && json.multiaddrs.length > 0) {
299
- const localAddr = json.multiaddrs.find(a => a.includes('/ip4/127.0.0.1/'));
300
- bootstrapNodes.push(localAddr ?? json.multiaddrs[0]!);
301
- logDebug('loaded bootstrap from file', { file, peerId: json.peerId, addr: localAddr ?? json.multiaddrs[0] });
302
- }
303
- } catch (err) {
304
- logDebug('failed to read bootstrap file', { file: fullPath, error: (err as Error).message });
305
- }
306
- }
307
- console.log(`📋 Loaded ${bootstrapNodes.length} bootstrap address(es) from ${filePath}`);
308
- }
309
- } else {
310
- // Single file - existing logic
311
- const contents = fs.readFileSync(filePath, 'utf-8');
312
- const json = JSON.parse(contents) as { multiaddrs?: string[] } | { nodes?: { multiaddrs: string[] }[] };
313
- if (Array.isArray((json as any).nodes)) {
314
- for (const n of (json as any).nodes) {
315
- if (Array.isArray(n.multiaddrs)) bootstrapNodes.push(...n.multiaddrs);
316
- }
317
- } else if (Array.isArray((json as any).multiaddrs)) {
318
- bootstrapNodes.push(...(json as any).multiaddrs);
319
- }
320
- }
321
- } catch (err) {
322
- console.error('❌ Failed to read bootstrap file:', (err as Error).message);
323
- }
324
- }
325
-
326
- const storageCapacityBytes = this.parseStorageCapacity(options);
327
- if (storageCapacityBytes) {
328
- const humanReadable = storageCapacityBytes >= 1024 * 1024 * 1024 ? `${(storageCapacityBytes / (1024 * 1024 * 1024)).toFixed(2)} GB` : `${storageCapacityBytes} bytes`;
329
- console.log(`📦 Storage capacity override set to ${humanReadable}`);
330
- logDebug('storage capacity override set', { bytes: storageCapacityBytes, human: humanReadable });
331
- }
332
- const clusterSize = this.parseClusterSize(options);
333
- if (clusterSize !== undefined) {
334
- console.log(`👥 Cluster size override set to ${clusterSize}`);
335
- logDebug('cluster size override set', { clusterSize });
336
- }
337
- const assumedClusterSize = this.parseAssumedClusterSize(options);
338
- if (assumedClusterSize !== undefined) {
339
- console.log(`🛡️ Assumed cluster size set to ${assumedClusterSize.toString()}`);
340
- logDebug('assumed cluster size override set', { assumedClusterSize });
341
- }
342
- const superMajorityThreshold = this.parseSuperMajorityThreshold(options);
343
- if (superMajorityThreshold !== undefined) {
344
- console.log(`🎯 Super-majority threshold set to ${superMajorityThreshold.toString()}`);
345
- logDebug('super-majority threshold override set', { superMajorityThreshold });
346
- }
347
- logDebug('starting libp2p node', {
348
- port: options.port,
349
- bootstrapCount: bootstrapNodes.length,
350
- storage: options.storage,
351
- storagePath: options.storagePath,
352
- storageCapacityBytes,
353
- clusterSize,
354
- assumedClusterSize,
355
- superMajorityThreshold,
356
- mode: options.offline ? 'offline' : 'distributed'
357
- });
358
-
359
- // Create storage provider based on options
360
- const createStorage = (): IRawStorage => {
361
- if (options.storage === 'file') {
362
- return new FileRawStorage(options.storagePath!);
363
- }
364
- return new MemoryRawStorage();
365
- };
366
-
367
- const wsPortNum = options.wsPort !== undefined ? parseInt(options.wsPort, 10) : undefined;
368
- if (wsPortNum !== undefined && (!Number.isFinite(wsPortNum) || wsPortNum < 0)) {
369
- throw new Error('--ws-port must be a non-negative integer');
370
- }
371
- const disableTcp = options.tcp === false;
372
-
373
- console.log(`🔁 Circuit-relay server: ${effectiveRelay ? 'on' : 'off'}`);
374
- if (effectiveRelay) {
375
- console.log('🔁 Circuit-relay limits: disabled (reference-peer trusted)');
376
- }
377
- const node = await createLibp2pNode({
378
- port: parseInt(options.port || '0'),
379
- wsPort: wsPortNum,
380
- wsHost: options.wsHost,
381
- disableTcp,
382
- bootstrapNodes,
383
- id: options.id,
384
- relay: effectiveRelay,
385
- // Reference-peer nodes are trusted local-cluster relays — lift the
386
- // upstream 128 KiB / 2 min per-relayed-connection caps so service↔browser
387
- // circuits survive a full e2e run. See db-p2p NodeOptions.relayServerInit.
388
- relayServerInit: effectiveRelay
389
- ? { reservations: { applyDefaultLimit: false } }
390
- : undefined,
391
- announceAddrs: options.announceAddr,
392
- appendAnnounceAddrs: options.appendAnnounceAddr,
393
- networkName: options.network || 'optimystic',
394
- fretProfile: options.fretProfile,
395
- storage: createStorage,
396
- clusterSize,
397
- clusterPolicy: superMajorityThreshold !== undefined || assumedClusterSize !== undefined
398
- ? { superMajorityThreshold, assumedClusterSize }
399
- : undefined,
400
- arachnode: {
401
- enableRingZulu: true,
402
- storage: storageCapacityBytes ? { totalBytes: storageCapacityBytes } : undefined
403
- }
404
- });
405
-
406
- console.log(`✅ Node started with ID: ${node.peerId.toString()}`);
407
- console.log(`📡 Listening on:`);
408
- const addrs: string[] = [];
409
- node.getMultiaddrs().forEach((ma: any) => {
410
- const s = ma.toString();
411
- addrs.push(s);
412
- console.log(` ${s}`);
413
- });
414
-
415
- // LocalTransactor shares the node's own StorageRepo so offline writes are
416
- // visible to the running node (and to any later distributed reads). These come
417
- // off the node's typed attachment surface (OptimysticNodeAttachments), so no
418
- // presence guard is needed — createLibp2pNode always attaches them.
419
- const storageRepo = node.storageRepo;
420
-
421
- // The node's OWN key network. Do NOT construct a second one: it would resolve a
422
- // different cohort width than this node's consensus path and would not carry the
423
- // network-membership filter, so peers of a DIFFERENT Optimystic network sharing
424
- // these bootstraps would be legal coordinator/cohort candidates.
425
- const keyNetwork = node.keyNetwork;
426
-
427
- // The coordinated repo that includes cluster consensus
428
- const coordinatedRepo = node.coordinatedRepo;
429
-
430
- // Determine operating mode
431
- const isOffline = Boolean(options.offline);
432
- console.log(`🔧 Mode: ${isOffline ? 'Offline (LocalTransactor)' : 'Distributed (NetworkTransactor)'}`);
433
-
434
- // Create appropriate transactor based on mode
435
- let transactor: NetworkTransactor | LocalTransactor;
436
- if (isOffline) {
437
- transactor = new LocalTransactor(storageRepo);
438
- } else {
439
- transactor = new NetworkTransactor({
440
- timeoutMs: 30000,
441
- abortOrCancelTimeoutMs: 10000,
442
- // Per-peer dial cap: an unreachable cluster member fails fast
443
- // (~3s) so the consensus retry loop can re-pick within the 30s
444
- // overall budget instead of one stuck peer monopolizing it.
445
- dialTimeoutMs: 3000,
446
- keyNetwork,
447
- getRepo: (peerId) => {
448
- return peerId.toString() === node.peerId.toString()
449
- ? coordinatedRepo // Use coordinated repo for self to enable cluster consensus
450
- : RepoClient.create(peerId, keyNetwork, `/optimystic/${options.network || 'optimystic'}`);
451
- }
452
- });
453
- }
454
-
455
- this.session = {
456
- node,
457
- transactor,
458
- diaries: new Map(),
459
- trees: new Map(),
460
- isConnected: true,
461
- isSingleNode: isOffline
462
- };
463
-
464
- console.log('✅ Distributed transaction system initialized');
465
- logDebug('session initialized', { peerId: node.peerId.toString(), offline: isOffline, bootstrap: bootstrapNodes });
466
-
467
- // Network manager readiness (service-based)
468
- const nm = getNetworkManager(node);
469
- await nm.ready();
470
- if (bootstrapNodes.length > 0 && (nm as any).awaitHealthy) {
471
- // Require at least 2 connections when multiple bootstrap nodes available
472
- // This ensures better mesh connectivity before operations begin
473
- const minConnections = Math.min(2, bootstrapNodes.length);
474
- const ok = await (nm as any).awaitHealthy(minConnections, 10000);
475
- console.log(`🧭 Network ${ok ? 'healthy' : 'not healthy yet'} (active connections=${ok ? `>=${minConnections}` : '<' + minConnections})`);
476
- logDebug('network manager status', { healthy: ok, status: nm.getStatus?.() });
477
- } else {
478
- console.log('🧭 Network ready');
479
- logDebug('network manager ready', { status: nm.getStatus?.() });
480
- }
481
-
482
- // Wait for FRET to be ready
483
- await this.waitForFretReady(node);
484
- this.logRingInfo(node, storageCapacityBytes);
485
-
486
- // Optionally announce node info to a file for launchers/mesh setups
487
- if (options.announceFile) {
488
- try {
489
- const info = {
490
- peerId: node.peerId.toString(),
491
- multiaddrs: addrs,
492
- port: parseInt(options.port || '0'),
493
- networkName: options.network || 'optimystic',
494
- timestamp: Date.now(),
495
- pid: process.pid
496
- };
497
- fs.mkdirSync(path.dirname(options.announceFile), { recursive: true });
498
- fs.writeFileSync(options.announceFile, JSON.stringify(info, null, 2), 'utf-8');
499
- console.log(`📝 Announced node info to ${options.announceFile}`);
500
- } catch (err) {
501
- console.error('❌ Failed to write announce file:', (err as Error).message);
502
- }
503
- }
504
-
505
- // Wait for network bootstrap if we have bootstrap nodes
506
- if (bootstrapNodes.length > 0) {
507
- console.log('🔄 Bootstrapping to network...');
508
- await new Promise(resolve => setTimeout(resolve, 2000));
509
- console.log('✅ Network bootstrap complete');
510
- this.logRingInfo(node, storageCapacityBytes);
511
-
512
- // Wait for FRET to discover peers (best effort, non-blocking)
513
- // FRET neighbor announcements happen asynchronously and take time to propagate
514
- const minPeers = 1; // At least discover one peer
515
- if (bootstrapNodes.length > 0) {
516
- console.log(`🔍 Waiting for FRET to discover peers...`);
517
- await this.waitForFretConvergence(node, minPeers, 8000);
518
- }
519
- }
520
- }
521
-
522
- async stopNetwork(): Promise<void> {
523
- if (!this.session?.isConnected) {
524
- console.log('⚠️ Not connected to network');
525
- return;
526
- }
527
-
528
- console.log('🛑 Stopping network...');
529
- await this.session.node.stop();
530
- this.session.isConnected = false;
531
- console.log('✅ Network stopped');
532
- }
533
-
534
- private requireSession(): NetworkSession {
535
- if (!this.session?.isConnected) {
536
- throw new Error('Not connected to network. Start network first.');
537
- }
538
- return this.session;
539
- }
540
-
541
- async createDiary(name: string): Promise<void> {
542
- const session = this.requireSession();
543
-
544
- if (session.diaries.has(name)) {
545
- throw new Error(`Diary '${name}' already exists`);
546
- }
547
-
548
- console.log(`📝 Creating diary: ${name}`);
549
- const diary = await Diary.createOrOpen(session.transactor, name);
550
- session.diaries.set(name, diary);
551
- console.log(`✅ Successfully created diary: ${name}`);
552
- }
553
-
554
- async addEntry(diaryName: string, content: string): Promise<void> {
555
- const session = this.requireSession();
556
-
557
- const diary = await this.ensureDiary(diaryName);
558
-
559
- console.log(`📝 Adding entry to diary ${diaryName}: ${content}`);
560
- const entry = {
561
- content,
562
- timestamp: new Date().toISOString(),
563
- author: session.node.peerId.toString()
564
- };
565
-
566
- await diary.append(entry);
567
- console.log(`✅ Successfully added entry to diary: ${diaryName}`);
568
- }
569
-
570
- async listDiaries(): Promise<void> {
571
- // NOTE: lists only diaries touched in this process session, not persisted state.
572
- // No block-storage-level index of collection names exists, so enumerating persisted
573
- // diaries would need a separate registry — a `feat-` ticket if ever required.
574
- const session = this.requireSession();
575
-
576
- if (session.diaries.size === 0) {
577
- console.log('📁 No diaries opened this session');
578
- return;
579
- }
580
-
581
- console.log('📚 Diaries opened this session (not a complete list of persisted diaries):');
582
- for (const [name, _] of session.diaries) {
583
- console.log(` - ${name}`);
584
- }
585
- }
586
-
587
- async readDiary(diaryName: string): Promise<void> {
588
- this.requireSession();
589
-
590
- const diary = await this.ensureDiary(diaryName);
591
-
592
- console.log(`📖 Reading entries from diary: ${diaryName}`);
593
- let entryCount = 0;
594
-
595
- for await (const entry of diary.select()) {
596
- entryCount++;
597
- console.log(`📄 Entry ${entryCount}:`);
598
- console.log(` Content: ${entry.content}`);
599
- console.log(` Timestamp: ${entry.timestamp}`);
600
- if (entry.author) {
601
- console.log(` Author: ${entry.author}`);
602
- }
603
- console.log('');
604
- }
605
-
606
- if (entryCount === 0) {
607
- console.log('📁 No entries found in this diary');
608
- } else {
609
- console.log(`📊 Total entries: ${entryCount}`);
610
- }
611
- }
612
-
613
- async showStatus(): Promise<void> {
614
- if (!this.session?.isConnected) {
615
- console.log('❌ Not connected to network');
616
- return;
617
- }
618
-
619
- const session = this.session;
620
- console.log('🌐 Network Status:');
621
- console.log(` Node ID: ${session.node.peerId.toString()}`);
622
- console.log(` Connected: ${session.isConnected}`);
623
- console.log(` Diaries: ${session.diaries.size}`);
624
- console.log(` Trees: ${session.trees.size}`);
625
-
626
- const multiaddrs = session.node.getMultiaddrs();
627
- console.log(` Addresses (${multiaddrs.length}):`);
628
- multiaddrs.forEach((ma: any) => {
629
- console.log(` ${ma.toString()}`);
630
- });
631
- }
632
-
633
- async startInteractive(): Promise<void> {
634
- this.rl = readline.createInterface({
635
- input: process.stdin,
636
- output: process.stdout,
637
- prompt: 'optimystic> '
638
- });
639
-
640
- console.log('\n🎮 Interactive mode started. Type "help" for commands, "exit" to quit.');
641
- this.rl.prompt();
642
-
643
- this.rl.on('line', async (line) => {
644
- const args = line.trim().split(/\s+/);
645
- const command = args[0];
646
-
647
- try {
648
- switch (command) {
649
- case 'help':
650
- this.showHelp();
651
- break;
652
- case 'status':
653
- await this.showStatus();
654
- break;
655
- case 'create-diary':
656
- if (args.length < 2) {
657
- console.log('Usage: create-diary <name>');
658
- } else {
659
- await this.createDiary(args[1]!);
660
- }
661
- break;
662
- case 'add-entry':
663
- if (args.length < 3) {
664
- console.log('Usage: add-entry <diary-name> <content>');
665
- } else {
666
- const content = args.slice(2).join(' ');
667
- await this.addEntry(args[1]!, content);
668
- }
669
- break;
670
- case 'list-diaries':
671
- await this.listDiaries();
672
- break;
673
- case 'read-diary':
674
- if (args.length < 2) {
675
- console.log('Usage: read-diary <name>');
676
- } else {
677
- await this.readDiary(args[1]!);
678
- }
679
- break;
680
- case 'exit':
681
- case 'quit':
682
- console.log('👋 Goodbye!');
683
- await this.stopNetwork();
684
- process.exit(0);
685
- break;
686
- case '':
687
- // Empty line, just re-prompt
688
- break;
689
- default:
690
- console.log(`Unknown command: ${command}. Type "help" for available commands.`);
691
- break;
692
- }
693
- } catch (error) {
694
- console.error(`❌ Error: ${error instanceof Error ? error.message : error}`);
695
- }
696
-
697
- this.rl?.prompt();
698
- });
699
-
700
- this.rl.on('SIGINT', async () => {
701
- console.log('\n👋 Shutting down...');
702
- await this.stopNetwork();
703
- process.exit(0);
704
- });
705
- }
706
-
707
- private showHelp(): void {
708
- console.log(`
709
- 🎮 Available Commands:
710
- help - Show this help message
711
- status - Show network and session status
712
- create-diary <name> - Create a new diary collection
713
- add-entry <diary> <content> - Add an entry to a diary
714
- list-diaries - List all created diaries
715
- read-diary <name> - Read all entries from a diary
716
- exit/quit - Exit interactive mode
717
- `);
718
- }
719
-
720
- async cleanup(): Promise<void> {
721
- if (this.rl) {
722
- this.rl.close();
723
- }
724
- if (this.session && this.session.isConnected) {
725
- await this.stopNetwork();
726
- }
727
- }
728
- }
729
-
730
- const program = new Command();
731
- const session = new PeerSession();
732
-
733
- // Ensure cleanup on process exit
734
- process.on('SIGINT', async () => {
735
- await session.cleanup();
736
- process.exit(0);
737
- });
738
-
739
- process.on('SIGTERM', async () => {
740
- await session.cleanup();
741
- process.exit(0);
742
- });
743
-
744
- program
745
- .name('optimystic-reference-peer')
746
- .description('Optimystic P2P Database Reference Peer')
747
- .version('0.0.1');
748
-
749
- /**
750
- * Commander reducer for a repeatable multiaddr option: validates on the way in and appends.
751
- *
752
- * Validating here rather than letting libp2p do it matters because libp2p does NOT parse the
753
- * announce set at node construction — it parses lazily inside `getAddresses()`, so a malformed
754
- * value surfaces as a raw `InvalidMultiaddrError` stack trace AFTER "Node started" (port already
755
- * bound), naming neither the flag nor the bad value. A shell that rewrites POSIX-looking arguments
756
- * makes that an easy mistake: MSYS/Git-Bash on Windows turns `/dns4/host/tcp/443/wss` into
757
- * `C:/Program Files/Git/dns4/...` before the CLI ever sees it.
758
- */
759
- const collectMultiaddr = (flag: string) => (val: string, prev: string[]): string[] => {
760
- try {
761
- multiaddr(val);
762
- } catch (err) {
763
- throw new InvalidArgumentError(`${flag} "${val}" is not a valid multiaddr: ${(err as Error).message}`);
764
- }
765
- return prev.concat([val]);
766
- };
767
-
768
- /**
769
- * Apply the network/storage options shared verbatim by the `interactive`,
770
- * `service`, and `run` commands. Extracted so the three stay in lockstep;
771
- * command-specific options (e.g. `run`'s --action/--diary/--content) are layered
772
- * on by each caller after this helper. Flag strings, descriptions, and defaults
773
- * are identical to the previous inline copies, so each command's parsed
774
- * `options` object is unchanged.
775
- */
776
- function withCommonPeerOptions(cmd: Command): Command {
777
- return cmd
778
- .option('-p, --port <number>', 'Port to listen on', '0')
779
- .option('--ws-port <number>', 'WebSocket port to listen on (e.g. 9091); enables /ws listen for browser/RN peers')
780
- .option('--ws-host <ip>', 'Interface to bind the WS listener to', '0.0.0.0')
781
- .option('--no-tcp', 'Disable the default TCP listen (browser-only bootstrap)')
782
- .option('-b, --bootstrap <string>', 'Comma-separated list of bootstrap nodes')
783
- .option('-i, --id <string>', 'Peer ID')
784
- .option('--no-relay', 'Disable circuit-relay-v2 server (default: on for peers with an inbound listen address)')
785
- .option('-n, --network <string>', 'Network name', 'optimystic')
786
- .option('--fret-profile <profile>', "FRET profile: 'edge' or 'core'", 'edge')
787
- .option('-s, --storage <type>', 'Storage type: memory or file', 'memory')
788
- .option('--storage-path <path>', 'Path for file storage')
789
- .option('--storage-capacity <bytes>', 'Override storage capacity in bytes (for ring selection)')
790
- .option('--cluster-size <number>', 'Desired cluster size per key (positive integer)')
791
- .option('--assumed-cluster-size <number>', 'Smallest cohort this deployment can genuinely field. Sets both the membership admission gate\'s fallback floor (used when the node has no confident network-size estimate; defaults to 2 when unset) and the read-repair/reconcile corroboration floor (defaults to --cluster-size when unset). A mesh smaller than --cluster-size needs this to repair damaged blocks')
792
- .option('--super-majority-threshold <number>', 'Super-majority threshold as a fraction in (0, 1] (default 0.75)')
793
- .option('--offline', 'Run as single-node LocalTransactor (no distributed consensus)')
794
- .option('--bootstrap-file <path>', 'Path to JSON containing bootstrap multiaddrs or node list')
795
- .option('--announce-file <path>', 'Write node info (peerId, multiaddrs) to this JSON file for mesh launchers')
796
- .option('--announce-addr <multiaddr>', 'Multiaddr to advertise INSTEAD OF the listen addrs (e.g. behind a TLS proxy: /dns4/host/tcp/443/wss). Repeatable; replaces the advertised set entirely', collectMultiaddr('--announce-addr'), [] as string[])
797
- .option('--append-announce-addr <multiaddr>', 'Multiaddr to advertise IN ADDITION TO the listen addrs. Repeatable; ignored while --announce-addr is set', collectMultiaddr('--append-announce-addr'), [] as string[]);
798
- }
799
-
800
- // Interactive mode - network-first approach
801
- withCommonPeerOptions(
802
- program
803
- .command('interactive')
804
- .description('Start interactive mode (default behavior)')
805
- )
806
- .action(async (options) => {
807
- try {
808
- await session.startNetwork(options);
809
- await session.startInteractive();
810
- } catch (error) {
811
- if (error instanceof Error) {
812
- console.error('❌ Error:', error.message);
813
- if (error.stack) console.error(error.stack);
814
- } else {
815
- console.error('❌ Error:', error);
816
- }
817
- process.exit(1);
818
- }
819
- });
820
-
821
- // Headless service node (no REPL); useful for mesh nodes in launch profiles
822
- withCommonPeerOptions(
823
- program
824
- .command('service')
825
- .description('Start a headless service node (no interactive prompt)')
826
- )
827
- .action(async (options) => {
828
- try {
829
- await session.startNetwork(options);
830
- // Keep process alive
831
- process.stdin.resume();
832
- } catch (error) {
833
- if (error instanceof Error) {
834
- console.error('❌ Error:', error.message);
835
- if (error.stack) console.error(error.stack);
836
- } else {
837
- console.error('❌ Error:', error);
838
- }
839
- process.exit(1);
840
- }
841
- });
842
-
843
- // Single-action mode commands
844
- withCommonPeerOptions(
845
- program
846
- .command('run')
847
- .description('Connect to network, run a single action, optionally stay connected')
848
- )
849
- .option('--stay-connected', 'Stay connected after action completes')
850
- .requiredOption('-a, --action <action>', 'Action to perform: create-diary, add-entry, list-diaries, read-diary')
851
- .option('--diary <name>', 'Diary name (required for diary operations)')
852
- .option('--content <content>', 'Entry content (required for add-entry)')
853
- .action(async (options) => {
854
- try {
855
- await session.startNetwork(options);
856
-
857
- // Perform the requested action
858
- switch (options.action) {
859
- case 'create-diary':
860
- if (!options.diary) {
861
- throw new Error('--diary is required for create-diary action');
862
- }
863
- await session.createDiary(options.diary);
864
- break;
865
- case 'add-entry':
866
- if (!options.diary || !options.content) {
867
- throw new Error('--diary and --content are required for add-entry action');
868
- }
869
- await session.addEntry(options.diary, options.content);
870
- break;
871
- case 'list-diaries':
872
- await session.listDiaries();
873
- break;
874
- case 'read-diary':
875
- if (!options.diary) {
876
- throw new Error('--diary is required for read-diary action');
877
- }
878
- await session.readDiary(options.diary);
879
- break;
880
- default:
881
- throw new Error(`Unknown action: ${options.action}`);
882
- }
883
-
884
- if (options.stayConnected) {
885
- console.log('🔄 Staying connected. Starting interactive mode...');
886
- await session.startInteractive();
887
- } else {
888
- console.log('✅ Action completed. Disconnecting...');
889
- await session.stopNetwork();
890
- }
891
-
892
- } catch (error) {
893
- if (error instanceof Error) {
894
- console.error('❌ Error:', error.message);
895
- if (error.stack) console.error(error.stack);
896
- } else {
897
- console.error('❌ Error:', error);
898
- }
899
- await session.cleanup();
900
- process.exit(1);
901
- }
902
- });
903
-
904
- // Default to interactive mode if no command specified
905
- if (process.argv.length <= 2) {
906
- process.argv.push('interactive');
907
- }
908
-
909
- program.parse();
1
+ #!/usr/bin/env node
2
+ import { Command, InvalidArgumentError } from 'commander';
3
+ import { multiaddr } from '@multiformats/multiaddr';
4
+ import debug from 'debug';
5
+ import { getNetworkManager, createLibp2pNode, MemoryRawStorage, RepoClient, ArachnodeFretAdapter, type IRawStorage } from '@optimystic/db-p2p';
6
+ import { FileRawStorage } from '@optimystic/db-p2p-storage-fs';
7
+ import { Diary, NetworkTransactor, BTree, type ITransactor, type BlockGets, type GetBlockResults, type ActionBlocks, type BlockActionStatus, type PendRequest, type PendResult, type CommitRequest, type CommitResult } from '@optimystic/db-core';
8
+ import * as readline from 'readline';
9
+ import * as path from 'path';
10
+ import * as fs from 'fs';
11
+
12
+ const logDebug = debug('optimystic:ref-peer');
13
+
14
+ // Simple local transactor for single-node scenarios
15
+ class LocalTransactor implements ITransactor {
16
+ constructor(private storageRepo: any) { }
17
+
18
+ async get(blockGets: BlockGets): Promise<GetBlockResults> {
19
+ return await this.storageRepo.get(blockGets);
20
+ }
21
+
22
+ async getStatus(_actionRefs: ActionBlocks[]): Promise<BlockActionStatus[]> {
23
+ throw new Error("Method not implemented.");
24
+ }
25
+
26
+ async pend(blockAction: PendRequest): Promise<PendResult> {
27
+ return await this.storageRepo.pend(blockAction);
28
+ }
29
+
30
+ async commit(request: CommitRequest): Promise<CommitResult> {
31
+ return await this.storageRepo.commit(request);
32
+ }
33
+
34
+ async cancel(actionRef: ActionBlocks): Promise<void> {
35
+ return await this.storageRepo.cancel(actionRef);
36
+ }
37
+ }
38
+
39
+ interface NetworkSession {
40
+ node: any;
41
+ transactor: NetworkTransactor | LocalTransactor;
42
+ diaries: Map<string, Diary<any>>;
43
+ trees: Map<string, BTree<any, any>>;
44
+ isConnected: boolean;
45
+ isSingleNode: boolean; // Track if we're in single-node mode
46
+ }
47
+
48
+ class PeerSession {
49
+ private session: NetworkSession | null = null;
50
+ private rl: readline.Interface | null = null;
51
+
52
+ private parseStorageCapacity(options: { storageCapacity?: string }): number | undefined {
53
+ if (!options.storageCapacity) return undefined;
54
+ const parsed = Number(options.storageCapacity);
55
+ if (!Number.isFinite(parsed) || parsed <= 0) {
56
+ throw new Error('--storage-capacity must be a positive number of bytes');
57
+ }
58
+ return parsed;
59
+ }
60
+
61
+ private parseClusterSize(options: { clusterSize?: string }): number | undefined {
62
+ if (options.clusterSize === undefined) return undefined;
63
+ const parsed = Number(options.clusterSize);
64
+ if (!Number.isInteger(parsed) || parsed <= 0) {
65
+ throw new Error('--cluster-size must be a positive integer');
66
+ }
67
+ return parsed;
68
+ }
69
+
70
+ private parseAssumedClusterSize(options: { assumedClusterSize?: string }): number | undefined {
71
+ if (options.assumedClusterSize === undefined) return undefined;
72
+ const parsed = Number(options.assumedClusterSize);
73
+ if (!Number.isInteger(parsed) || parsed <= 0) {
74
+ throw new Error('--assumed-cluster-size must be a positive integer');
75
+ }
76
+ return parsed;
77
+ }
78
+
79
+ private parseRepairCorroborationClusterSize(options: { repairCorroborationClusterSize?: string }): number | undefined {
80
+ if (options.repairCorroborationClusterSize === undefined) return undefined;
81
+ const parsed = Number(options.repairCorroborationClusterSize);
82
+ if (!Number.isInteger(parsed) || parsed <= 0) {
83
+ throw new Error('--repair-corroboration-cluster-size must be a positive integer');
84
+ }
85
+ return parsed;
86
+ }
87
+
88
+ private parseSuperMajorityThreshold(options: { superMajorityThreshold?: string }): number | undefined {
89
+ if (options.superMajorityThreshold === undefined) return undefined;
90
+ const parsed = Number(options.superMajorityThreshold);
91
+ if (!Number.isFinite(parsed) || parsed <= 0 || parsed > 1) {
92
+ throw new Error('--super-majority-threshold must be a number in (0, 1]');
93
+ }
94
+ return parsed;
95
+ }
96
+
97
+ private async waitForFretReady(node: any): Promise<void> {
98
+ try {
99
+ const fret = (node as any).services?.fret;
100
+ if (!fret) {
101
+ console.log('⚠️ FRET service not available');
102
+ logDebug('FRET service missing on node');
103
+ return;
104
+ }
105
+
106
+ const hadConn = node.getConnections().length > 0;
107
+ if (!hadConn) {
108
+ console.log('🔗 No connections yet, skipping FRET warm-up');
109
+ logDebug('skipping FRET ready check - no connections');
110
+ return;
111
+ }
112
+
113
+ if (typeof fret.ready !== 'function') {
114
+ console.log('⚠️ FRET service does not expose ready()');
115
+ logDebug('FRET ready() not present, skipping wait');
116
+ return;
117
+ }
118
+ logDebug('waiting for FRET ready');
119
+ await fret.ready();
120
+ console.log('✅ FRET service ready');
121
+
122
+ // Log FRET diagnostics
123
+ const knownPeers = typeof fret.listPeers === 'function' ? fret.listPeers() : [];
124
+ const netSize = typeof fret.getNetworkSizeEstimate === 'function' ? fret.getNetworkSizeEstimate() : undefined;
125
+ logDebug('FRET diagnostics after ready', {
126
+ knownPeers: knownPeers.map((p: any) => p.id ?? p.toString()),
127
+ knownPeerCount: knownPeers.length,
128
+ networkSizeEstimate: netSize
129
+ });
130
+ console.log(`📊 FRET knows ${knownPeers.length} peer(s)`);
131
+ } catch (error) {
132
+ console.warn('⚠️ FRET readiness check issue:', error);
133
+ logDebug('FRET readiness check issue', error);
134
+ }
135
+ }
136
+
137
+ private async waitForFretConvergence(node: any, minPeers: number, timeoutMs: number): Promise<boolean> {
138
+ const fret = (node as any).services?.fret;
139
+ if (!fret || typeof fret.listPeers !== 'function') {
140
+ logDebug('FRET convergence check skipped - no listPeers method');
141
+ return false;
142
+ }
143
+
144
+ const start = Date.now();
145
+ let lastCount = 0;
146
+ while (Date.now() - start < timeoutMs) {
147
+ const peers = fret.listPeers();
148
+ const count = Array.isArray(peers) ? peers.length : 0;
149
+ if (count !== lastCount) {
150
+ logDebug('FRET convergence progress', { peerCount: count, target: minPeers, peers: peers.map((p: any) => p.id) });
151
+ lastCount = count;
152
+ }
153
+ if (count >= minPeers) {
154
+ console.log(`✅ FRET discovered ${count} peer(s)`);
155
+ return true;
156
+ }
157
+ await new Promise(r => setTimeout(r, 200));
158
+ }
159
+
160
+ const finalPeers = fret.listPeers();
161
+ const finalCount = Array.isArray(finalPeers) ? finalPeers.length : 0;
162
+ console.log(`✅ FRET discovered ${finalCount} peer(s)`);
163
+ logDebug('FRET convergence completed', {
164
+ finalPeerCount: finalCount,
165
+ targetPeers: minPeers,
166
+ elapsed: timeoutMs,
167
+ peers: finalPeers.map((p: any) => p.id)
168
+ });
169
+ // Return true if we have at least some peers, even if not the target
170
+ return finalCount > 0;
171
+ }
172
+
173
+ private logRingInfo(node: any, totalCapacityOverride?: number): void {
174
+ const fret = (node as any).services?.fret;
175
+ if (!fret) {
176
+ logDebug('ring info unavailable (no FRET service)');
177
+ return;
178
+ }
179
+ const adapter = new ArachnodeFretAdapter(fret, node.peerId?.toString());
180
+ const myInfo = adapter.getMyArachnodeInfo();
181
+ if (myInfo) {
182
+ logDebug('local arachnode info', myInfo);
183
+ } else {
184
+ logDebug('no arachnode info published yet');
185
+ }
186
+ const rings = adapter.getKnownRings();
187
+ const stats = adapter.getRingStats();
188
+ logDebug('discovered ring depths', rings);
189
+ if (stats.length) {
190
+ logDebug('ring statistics', stats);
191
+ }
192
+ if (totalCapacityOverride) {
193
+ logDebug('storage capacity override active', { bytes: totalCapacityOverride });
194
+ }
195
+ }
196
+
197
+ private async ensureDiary(name: string): Promise<Diary<any>> {
198
+ const session = this.requireSession();
199
+ const existing = session.diaries.get(name);
200
+ if (existing) return existing;
201
+ // Diary.createOrOpen uses Collection.createOrOpen under the hood, so this will
202
+ // attach to an existing diary in the network or create it if missing.
203
+ const diary = await Diary.createOrOpen(session.transactor, name);
204
+ session.diaries.set(name, diary);
205
+ return diary;
206
+ }
207
+
208
+ async startNetwork(options: {
209
+ port?: string;
210
+ wsPort?: string;
211
+ wsHost?: string;
212
+ tcp?: boolean;
213
+ bootstrap?: string;
214
+ bootstrapFile?: string;
215
+ id?: string;
216
+ relay?: boolean;
217
+ network?: string;
218
+ fretProfile?: 'edge' | 'core';
219
+ storage?: 'memory' | 'file';
220
+ storagePath?: string;
221
+ storageCapacity?: string;
222
+ clusterSize?: string;
223
+ assumedClusterSize?: string;
224
+ repairCorroborationClusterSize?: string;
225
+ superMajorityThreshold?: string;
226
+ announceFile?: string;
227
+ announceAddr?: string[];
228
+ appendAnnounceAddr?: string[];
229
+ offline?: boolean;
230
+ }): Promise<void> {
231
+ if (this.session?.isConnected) {
232
+ console.log('⚠️ Already connected to network');
233
+ return;
234
+ }
235
+
236
+ console.log('🚀 Starting P2P node...');
237
+
238
+ const resolveEffectiveRelay = (): boolean => {
239
+ if (options.relay === false) return false;
240
+ const wsPortRaw = options.wsPort;
241
+ const wsPortConfigured = wsPortRaw !== undefined && wsPortRaw !== '';
242
+ const tcpEnabled = options.tcp !== false;
243
+ const hasInboundListen = tcpEnabled || wsPortConfigured;
244
+ return hasInboundListen;
245
+ };
246
+ const effectiveRelay = resolveEffectiveRelay();
247
+ logDebug('resolved relay default', {
248
+ explicit: options.relay,
249
+ tcp: options.tcp !== false,
250
+ wsPort: options.wsPort,
251
+ offline: options.offline,
252
+ effectiveRelay
253
+ });
254
+
255
+ // Validate storage options
256
+ if (options.storage === 'file' && !options.storagePath) {
257
+ throw new Error('--storage-path is required when using file storage');
258
+ }
259
+
260
+ // Create storage directory if needed
261
+ if (options.storage === 'file' && options.storagePath) {
262
+ fs.mkdirSync(options.storagePath, { recursive: true });
263
+ }
264
+
265
+ // Resolve bootstrap nodes from CLI args and/or file
266
+ let bootstrapNodes: string[] = options.bootstrap ? options.bootstrap.split(',') : [];
267
+ if (options.bootstrapFile) {
268
+ try {
269
+ const filePath = path.resolve(options.bootstrapFile);
270
+ const stat = fs.statSync(filePath);
271
+
272
+ // If it's a directory, wait for mesh-ready.json and use it
273
+ if (stat.isDirectory()) {
274
+ const readyFile = path.join(filePath, 'mesh-ready.json');
275
+
276
+ // Wait for mesh-ready.json (up to 30 seconds)
277
+ console.log('⏳ Waiting for mesh to be ready...');
278
+ const waitStart = Date.now();
279
+ while (!fs.existsSync(readyFile) && Date.now() - waitStart < 30000) {
280
+ await new Promise(r => setTimeout(r, 100));
281
+ }
282
+
283
+ if (fs.existsSync(readyFile)) {
284
+ // Use mesh-ready.json which has current node info
285
+ const readyContents = fs.readFileSync(readyFile, 'utf-8');
286
+ const readyJson = JSON.parse(readyContents) as { ready: boolean; nodes: { peerId: string; multiaddrs: string[] }[] };
287
+ logDebug('loading bootstrap from mesh-ready', { nodeCount: readyJson.nodes.length });
288
+
289
+ for (const node of readyJson.nodes) {
290
+ if (Array.isArray(node.multiaddrs) && node.multiaddrs.length > 0) {
291
+ // Prefer localhost for same-machine testing
292
+ const localAddr = node.multiaddrs.find(a => a.includes('/ip4/127.0.0.1/'));
293
+ bootstrapNodes.push(localAddr ?? node.multiaddrs[0]!);
294
+ logDebug('loaded bootstrap from mesh-ready', { peerId: node.peerId, addr: localAddr ?? node.multiaddrs[0] });
295
+ }
296
+ }
297
+ console.log(`📋 Loaded ${bootstrapNodes.length} bootstrap address(es) from mesh-ready.json`);
298
+ } else {
299
+ console.warn('⚠️ Timeout waiting for mesh-ready.json, falling back to node-*.json files');
300
+ // Fallback to old behavior
301
+ const files = fs.readdirSync(filePath).filter(f => f.startsWith('node-') && f.endsWith('.json'));
302
+ logDebug('loading bootstrap from directory (fallback)', { dir: filePath, files });
303
+ for (const file of files) {
304
+ const fullPath = path.join(filePath, file);
305
+ try {
306
+ const contents = fs.readFileSync(fullPath, 'utf-8');
307
+ const json = JSON.parse(contents) as { multiaddrs?: string[]; peerId?: string };
308
+ if (Array.isArray(json.multiaddrs) && json.multiaddrs.length > 0) {
309
+ const localAddr = json.multiaddrs.find(a => a.includes('/ip4/127.0.0.1/'));
310
+ bootstrapNodes.push(localAddr ?? json.multiaddrs[0]!);
311
+ logDebug('loaded bootstrap from file', { file, peerId: json.peerId, addr: localAddr ?? json.multiaddrs[0] });
312
+ }
313
+ } catch (err) {
314
+ logDebug('failed to read bootstrap file', { file: fullPath, error: (err as Error).message });
315
+ }
316
+ }
317
+ console.log(`📋 Loaded ${bootstrapNodes.length} bootstrap address(es) from ${filePath}`);
318
+ }
319
+ } else {
320
+ // Single file - existing logic
321
+ const contents = fs.readFileSync(filePath, 'utf-8');
322
+ const json = JSON.parse(contents) as { multiaddrs?: string[] } | { nodes?: { multiaddrs: string[] }[] };
323
+ if (Array.isArray((json as any).nodes)) {
324
+ for (const n of (json as any).nodes) {
325
+ if (Array.isArray(n.multiaddrs)) bootstrapNodes.push(...n.multiaddrs);
326
+ }
327
+ } else if (Array.isArray((json as any).multiaddrs)) {
328
+ bootstrapNodes.push(...(json as any).multiaddrs);
329
+ }
330
+ }
331
+ } catch (err) {
332
+ console.error('❌ Failed to read bootstrap file:', (err as Error).message);
333
+ }
334
+ }
335
+
336
+ const storageCapacityBytes = this.parseStorageCapacity(options);
337
+ if (storageCapacityBytes) {
338
+ const humanReadable = storageCapacityBytes >= 1024 * 1024 * 1024 ? `${(storageCapacityBytes / (1024 * 1024 * 1024)).toFixed(2)} GB` : `${storageCapacityBytes} bytes`;
339
+ console.log(`📦 Storage capacity override set to ${humanReadable}`);
340
+ logDebug('storage capacity override set', { bytes: storageCapacityBytes, human: humanReadable });
341
+ }
342
+ const clusterSize = this.parseClusterSize(options);
343
+ if (clusterSize !== undefined) {
344
+ console.log(`👥 Cluster size override set to ${clusterSize}`);
345
+ logDebug('cluster size override set', { clusterSize });
346
+ }
347
+ const assumedClusterSize = this.parseAssumedClusterSize(options);
348
+ if (assumedClusterSize !== undefined) {
349
+ console.log(`🛡️ Assumed cluster size set to ${assumedClusterSize.toString()}`);
350
+ logDebug('assumed cluster size override set', { assumedClusterSize });
351
+ }
352
+ const repairCorroborationClusterSize = this.parseRepairCorroborationClusterSize(options);
353
+ if (repairCorroborationClusterSize !== undefined) {
354
+ console.log(`\u{1F527} Repair corroboration cluster size set to ${repairCorroborationClusterSize.toString()}`);
355
+ logDebug('repair corroboration cluster size override set', { repairCorroborationClusterSize });
356
+ }
357
+ const superMajorityThreshold = this.parseSuperMajorityThreshold(options);
358
+ if (superMajorityThreshold !== undefined) {
359
+ console.log(`🎯 Super-majority threshold set to ${superMajorityThreshold.toString()}`);
360
+ logDebug('super-majority threshold override set', { superMajorityThreshold });
361
+ }
362
+ logDebug('starting libp2p node', {
363
+ port: options.port,
364
+ bootstrapCount: bootstrapNodes.length,
365
+ storage: options.storage,
366
+ storagePath: options.storagePath,
367
+ storageCapacityBytes,
368
+ clusterSize,
369
+ assumedClusterSize,
370
+ repairCorroborationClusterSize,
371
+ superMajorityThreshold,
372
+ mode: options.offline ? 'offline' : 'distributed'
373
+ });
374
+
375
+ // Create storage provider based on options
376
+ const createStorage = (): IRawStorage => {
377
+ if (options.storage === 'file') {
378
+ return new FileRawStorage(options.storagePath!);
379
+ }
380
+ return new MemoryRawStorage();
381
+ };
382
+
383
+ const wsPortNum = options.wsPort !== undefined ? parseInt(options.wsPort, 10) : undefined;
384
+ if (wsPortNum !== undefined && (!Number.isFinite(wsPortNum) || wsPortNum < 0)) {
385
+ throw new Error('--ws-port must be a non-negative integer');
386
+ }
387
+ const disableTcp = options.tcp === false;
388
+
389
+ console.log(`🔁 Circuit-relay server: ${effectiveRelay ? 'on' : 'off'}`);
390
+ if (effectiveRelay) {
391
+ console.log('🔁 Circuit-relay limits: disabled (reference-peer trusted)');
392
+ }
393
+ const node = await createLibp2pNode({
394
+ port: parseInt(options.port || '0'),
395
+ wsPort: wsPortNum,
396
+ wsHost: options.wsHost,
397
+ disableTcp,
398
+ bootstrapNodes,
399
+ id: options.id,
400
+ relay: effectiveRelay,
401
+ // Reference-peer nodes are trusted local-cluster relays — lift the
402
+ // upstream 128 KiB / 2 min per-relayed-connection caps so service↔browser
403
+ // circuits survive a full e2e run. See db-p2p NodeOptions.relayServerInit.
404
+ relayServerInit: effectiveRelay
405
+ ? { reservations: { applyDefaultLimit: false } }
406
+ : undefined,
407
+ announceAddrs: options.announceAddr,
408
+ appendAnnounceAddrs: options.appendAnnounceAddr,
409
+ networkName: options.network || 'optimystic',
410
+ fretProfile: options.fretProfile,
411
+ storage: createStorage,
412
+ clusterSize,
413
+ clusterPolicy: superMajorityThreshold !== undefined || assumedClusterSize !== undefined
414
+ || repairCorroborationClusterSize !== undefined
415
+ ? { superMajorityThreshold, assumedClusterSize, repairCorroborationClusterSize }
416
+ : undefined,
417
+ arachnode: {
418
+ enableRingZulu: true,
419
+ storage: storageCapacityBytes ? { totalBytes: storageCapacityBytes } : undefined
420
+ }
421
+ });
422
+
423
+ console.log(`✅ Node started with ID: ${node.peerId.toString()}`);
424
+ console.log(`📡 Listening on:`);
425
+ const addrs: string[] = [];
426
+ node.getMultiaddrs().forEach((ma: any) => {
427
+ const s = ma.toString();
428
+ addrs.push(s);
429
+ console.log(` ${s}`);
430
+ });
431
+
432
+ // LocalTransactor shares the node's own StorageRepo so offline writes are
433
+ // visible to the running node (and to any later distributed reads). These come
434
+ // off the node's typed attachment surface (OptimysticNodeAttachments), so no
435
+ // presence guard is needed — createLibp2pNode always attaches them.
436
+ const storageRepo = node.storageRepo;
437
+
438
+ // The node's OWN key network. Do NOT construct a second one: it would resolve a
439
+ // different cohort width than this node's consensus path and would not carry the
440
+ // network-membership filter, so peers of a DIFFERENT Optimystic network sharing
441
+ // these bootstraps would be legal coordinator/cohort candidates.
442
+ const keyNetwork = node.keyNetwork;
443
+
444
+ // The coordinated repo that includes cluster consensus
445
+ const coordinatedRepo = node.coordinatedRepo;
446
+
447
+ // Determine operating mode
448
+ const isOffline = Boolean(options.offline);
449
+ console.log(`🔧 Mode: ${isOffline ? 'Offline (LocalTransactor)' : 'Distributed (NetworkTransactor)'}`);
450
+
451
+ // Create appropriate transactor based on mode
452
+ let transactor: NetworkTransactor | LocalTransactor;
453
+ if (isOffline) {
454
+ transactor = new LocalTransactor(storageRepo);
455
+ } else {
456
+ transactor = new NetworkTransactor({
457
+ timeoutMs: 30000,
458
+ abortOrCancelTimeoutMs: 10000,
459
+ // Per-peer dial cap: an unreachable cluster member fails fast
460
+ // (~3s) so the consensus retry loop can re-pick within the 30s
461
+ // overall budget instead of one stuck peer monopolizing it.
462
+ dialTimeoutMs: 3000,
463
+ keyNetwork,
464
+ getRepo: (peerId) => {
465
+ return peerId.toString() === node.peerId.toString()
466
+ ? coordinatedRepo // Use coordinated repo for self to enable cluster consensus
467
+ : RepoClient.create(peerId, keyNetwork, `/optimystic/${options.network || 'optimystic'}`);
468
+ }
469
+ });
470
+ }
471
+
472
+ this.session = {
473
+ node,
474
+ transactor,
475
+ diaries: new Map(),
476
+ trees: new Map(),
477
+ isConnected: true,
478
+ isSingleNode: isOffline
479
+ };
480
+
481
+ console.log('✅ Distributed transaction system initialized');
482
+ logDebug('session initialized', { peerId: node.peerId.toString(), offline: isOffline, bootstrap: bootstrapNodes });
483
+
484
+ // Network manager readiness (service-based)
485
+ const nm = getNetworkManager(node);
486
+ await nm.ready();
487
+ if (bootstrapNodes.length > 0 && (nm as any).awaitHealthy) {
488
+ // Require at least 2 connections when multiple bootstrap nodes available
489
+ // This ensures better mesh connectivity before operations begin
490
+ const minConnections = Math.min(2, bootstrapNodes.length);
491
+ const ok = await (nm as any).awaitHealthy(minConnections, 10000);
492
+ console.log(`🧭 Network ${ok ? 'healthy' : 'not healthy yet'} (active connections=${ok ? `>=${minConnections}` : '<' + minConnections})`);
493
+ logDebug('network manager status', { healthy: ok, status: nm.getStatus?.() });
494
+ } else {
495
+ console.log('🧭 Network ready');
496
+ logDebug('network manager ready', { status: nm.getStatus?.() });
497
+ }
498
+
499
+ // Wait for FRET to be ready
500
+ await this.waitForFretReady(node);
501
+ this.logRingInfo(node, storageCapacityBytes);
502
+
503
+ // Optionally announce node info to a file for launchers/mesh setups
504
+ if (options.announceFile) {
505
+ try {
506
+ const info = {
507
+ peerId: node.peerId.toString(),
508
+ multiaddrs: addrs,
509
+ port: parseInt(options.port || '0'),
510
+ networkName: options.network || 'optimystic',
511
+ timestamp: Date.now(),
512
+ pid: process.pid
513
+ };
514
+ fs.mkdirSync(path.dirname(options.announceFile), { recursive: true });
515
+ fs.writeFileSync(options.announceFile, JSON.stringify(info, null, 2), 'utf-8');
516
+ console.log(`📝 Announced node info to ${options.announceFile}`);
517
+ } catch (err) {
518
+ console.error('❌ Failed to write announce file:', (err as Error).message);
519
+ }
520
+ }
521
+
522
+ // Wait for network bootstrap if we have bootstrap nodes
523
+ if (bootstrapNodes.length > 0) {
524
+ console.log('🔄 Bootstrapping to network...');
525
+ await new Promise(resolve => setTimeout(resolve, 2000));
526
+ console.log('✅ Network bootstrap complete');
527
+ this.logRingInfo(node, storageCapacityBytes);
528
+
529
+ // Wait for FRET to discover peers (best effort, non-blocking)
530
+ // FRET neighbor announcements happen asynchronously and take time to propagate
531
+ const minPeers = 1; // At least discover one peer
532
+ if (bootstrapNodes.length > 0) {
533
+ console.log(`🔍 Waiting for FRET to discover peers...`);
534
+ await this.waitForFretConvergence(node, minPeers, 8000);
535
+ }
536
+ }
537
+ }
538
+
539
+ async stopNetwork(): Promise<void> {
540
+ if (!this.session?.isConnected) {
541
+ console.log('⚠️ Not connected to network');
542
+ return;
543
+ }
544
+
545
+ console.log('🛑 Stopping network...');
546
+ await this.session.node.stop();
547
+ this.session.isConnected = false;
548
+ console.log('✅ Network stopped');
549
+ }
550
+
551
+ private requireSession(): NetworkSession {
552
+ if (!this.session?.isConnected) {
553
+ throw new Error('Not connected to network. Start network first.');
554
+ }
555
+ return this.session;
556
+ }
557
+
558
+ async createDiary(name: string): Promise<void> {
559
+ const session = this.requireSession();
560
+
561
+ if (session.diaries.has(name)) {
562
+ throw new Error(`Diary '${name}' already exists`);
563
+ }
564
+
565
+ console.log(`📝 Creating diary: ${name}`);
566
+ const diary = await Diary.createOrOpen(session.transactor, name);
567
+ session.diaries.set(name, diary);
568
+ console.log(`✅ Successfully created diary: ${name}`);
569
+ }
570
+
571
+ async addEntry(diaryName: string, content: string): Promise<void> {
572
+ const session = this.requireSession();
573
+
574
+ const diary = await this.ensureDiary(diaryName);
575
+
576
+ console.log(`📝 Adding entry to diary ${diaryName}: ${content}`);
577
+ const entry = {
578
+ content,
579
+ timestamp: new Date().toISOString(),
580
+ author: session.node.peerId.toString()
581
+ };
582
+
583
+ await diary.append(entry);
584
+ console.log(`✅ Successfully added entry to diary: ${diaryName}`);
585
+ }
586
+
587
+ async listDiaries(): Promise<void> {
588
+ // NOTE: lists only diaries touched in this process session, not persisted state.
589
+ // No block-storage-level index of collection names exists, so enumerating persisted
590
+ // diaries would need a separate registry — a `feat-` ticket if ever required.
591
+ const session = this.requireSession();
592
+
593
+ if (session.diaries.size === 0) {
594
+ console.log('📁 No diaries opened this session');
595
+ return;
596
+ }
597
+
598
+ console.log('📚 Diaries opened this session (not a complete list of persisted diaries):');
599
+ for (const [name, _] of session.diaries) {
600
+ console.log(` - ${name}`);
601
+ }
602
+ }
603
+
604
+ async readDiary(diaryName: string): Promise<void> {
605
+ this.requireSession();
606
+
607
+ const diary = await this.ensureDiary(diaryName);
608
+
609
+ console.log(`📖 Reading entries from diary: ${diaryName}`);
610
+ let entryCount = 0;
611
+
612
+ for await (const entry of diary.select()) {
613
+ entryCount++;
614
+ console.log(`📄 Entry ${entryCount}:`);
615
+ console.log(` Content: ${entry.content}`);
616
+ console.log(` Timestamp: ${entry.timestamp}`);
617
+ if (entry.author) {
618
+ console.log(` Author: ${entry.author}`);
619
+ }
620
+ console.log('');
621
+ }
622
+
623
+ if (entryCount === 0) {
624
+ console.log('📁 No entries found in this diary');
625
+ } else {
626
+ console.log(`📊 Total entries: ${entryCount}`);
627
+ }
628
+ }
629
+
630
+ async showStatus(): Promise<void> {
631
+ if (!this.session?.isConnected) {
632
+ console.log('❌ Not connected to network');
633
+ return;
634
+ }
635
+
636
+ const session = this.session;
637
+ console.log('🌐 Network Status:');
638
+ console.log(` Node ID: ${session.node.peerId.toString()}`);
639
+ console.log(` Connected: ${session.isConnected}`);
640
+ console.log(` Diaries: ${session.diaries.size}`);
641
+ console.log(` Trees: ${session.trees.size}`);
642
+
643
+ const multiaddrs = session.node.getMultiaddrs();
644
+ console.log(` Addresses (${multiaddrs.length}):`);
645
+ multiaddrs.forEach((ma: any) => {
646
+ console.log(` ${ma.toString()}`);
647
+ });
648
+ }
649
+
650
+ async startInteractive(): Promise<void> {
651
+ this.rl = readline.createInterface({
652
+ input: process.stdin,
653
+ output: process.stdout,
654
+ prompt: 'optimystic> '
655
+ });
656
+
657
+ console.log('\n🎮 Interactive mode started. Type "help" for commands, "exit" to quit.');
658
+ this.rl.prompt();
659
+
660
+ this.rl.on('line', async (line) => {
661
+ const args = line.trim().split(/\s+/);
662
+ const command = args[0];
663
+
664
+ try {
665
+ switch (command) {
666
+ case 'help':
667
+ this.showHelp();
668
+ break;
669
+ case 'status':
670
+ await this.showStatus();
671
+ break;
672
+ case 'create-diary':
673
+ if (args.length < 2) {
674
+ console.log('Usage: create-diary <name>');
675
+ } else {
676
+ await this.createDiary(args[1]!);
677
+ }
678
+ break;
679
+ case 'add-entry':
680
+ if (args.length < 3) {
681
+ console.log('Usage: add-entry <diary-name> <content>');
682
+ } else {
683
+ const content = args.slice(2).join(' ');
684
+ await this.addEntry(args[1]!, content);
685
+ }
686
+ break;
687
+ case 'list-diaries':
688
+ await this.listDiaries();
689
+ break;
690
+ case 'read-diary':
691
+ if (args.length < 2) {
692
+ console.log('Usage: read-diary <name>');
693
+ } else {
694
+ await this.readDiary(args[1]!);
695
+ }
696
+ break;
697
+ case 'exit':
698
+ case 'quit':
699
+ console.log('👋 Goodbye!');
700
+ await this.stopNetwork();
701
+ process.exit(0);
702
+ break;
703
+ case '':
704
+ // Empty line, just re-prompt
705
+ break;
706
+ default:
707
+ console.log(`Unknown command: ${command}. Type "help" for available commands.`);
708
+ break;
709
+ }
710
+ } catch (error) {
711
+ console.error(`❌ Error: ${error instanceof Error ? error.message : error}`);
712
+ }
713
+
714
+ this.rl?.prompt();
715
+ });
716
+
717
+ this.rl.on('SIGINT', async () => {
718
+ console.log('\n👋 Shutting down...');
719
+ await this.stopNetwork();
720
+ process.exit(0);
721
+ });
722
+ }
723
+
724
+ private showHelp(): void {
725
+ console.log(`
726
+ 🎮 Available Commands:
727
+ help - Show this help message
728
+ status - Show network and session status
729
+ create-diary <name> - Create a new diary collection
730
+ add-entry <diary> <content> - Add an entry to a diary
731
+ list-diaries - List all created diaries
732
+ read-diary <name> - Read all entries from a diary
733
+ exit/quit - Exit interactive mode
734
+ `);
735
+ }
736
+
737
+ async cleanup(): Promise<void> {
738
+ if (this.rl) {
739
+ this.rl.close();
740
+ }
741
+ if (this.session && this.session.isConnected) {
742
+ await this.stopNetwork();
743
+ }
744
+ }
745
+ }
746
+
747
+ const program = new Command();
748
+ const session = new PeerSession();
749
+
750
+ // Ensure cleanup on process exit
751
+ process.on('SIGINT', async () => {
752
+ await session.cleanup();
753
+ process.exit(0);
754
+ });
755
+
756
+ process.on('SIGTERM', async () => {
757
+ await session.cleanup();
758
+ process.exit(0);
759
+ });
760
+
761
+ program
762
+ .name('optimystic-reference-peer')
763
+ .description('Optimystic P2P Database Reference Peer')
764
+ .version('0.0.1');
765
+
766
+ /**
767
+ * Commander reducer for a repeatable multiaddr option: validates on the way in and appends.
768
+ *
769
+ * Validating here rather than letting libp2p do it matters because libp2p does NOT parse the
770
+ * announce set at node construction — it parses lazily inside `getAddresses()`, so a malformed
771
+ * value surfaces as a raw `InvalidMultiaddrError` stack trace AFTER "Node started" (port already
772
+ * bound), naming neither the flag nor the bad value. A shell that rewrites POSIX-looking arguments
773
+ * makes that an easy mistake: MSYS/Git-Bash on Windows turns `/dns4/host/tcp/443/wss` into
774
+ * `C:/Program Files/Git/dns4/...` before the CLI ever sees it.
775
+ */
776
+ const collectMultiaddr = (flag: string) => (val: string, prev: string[]): string[] => {
777
+ try {
778
+ multiaddr(val);
779
+ } catch (err) {
780
+ throw new InvalidArgumentError(`${flag} "${val}" is not a valid multiaddr: ${(err as Error).message}`);
781
+ }
782
+ return prev.concat([val]);
783
+ };
784
+
785
+ /**
786
+ * Apply the network/storage options shared verbatim by the `interactive`,
787
+ * `service`, and `run` commands. Extracted so the three stay in lockstep;
788
+ * command-specific options (e.g. `run`'s --action/--diary/--content) are layered
789
+ * on by each caller after this helper. Flag strings, descriptions, and defaults
790
+ * are identical to the previous inline copies, so each command's parsed
791
+ * `options` object is unchanged.
792
+ */
793
+ function withCommonPeerOptions(cmd: Command): Command {
794
+ return cmd
795
+ .option('-p, --port <number>', 'Port to listen on', '0')
796
+ .option('--ws-port <number>', 'WebSocket port to listen on (e.g. 9091); enables /ws listen for browser/RN peers')
797
+ .option('--ws-host <ip>', 'Interface to bind the WS listener to', '0.0.0.0')
798
+ .option('--no-tcp', 'Disable the default TCP listen (browser-only bootstrap)')
799
+ .option('-b, --bootstrap <string>', 'Comma-separated list of bootstrap nodes')
800
+ .option('-i, --id <string>', 'Peer ID')
801
+ .option('--no-relay', 'Disable circuit-relay-v2 server (default: on for peers with an inbound listen address)')
802
+ .option('-n, --network <string>', 'Network name', 'optimystic')
803
+ .option('--fret-profile <profile>', "FRET profile: 'edge' or 'core'", 'edge')
804
+ .option('-s, --storage <type>', 'Storage type: memory or file', 'memory')
805
+ .option('--storage-path <path>', 'Path for file storage')
806
+ .option('--storage-capacity <bytes>', 'Override storage capacity in bytes (for ring selection)')
807
+ .option('--cluster-size <number>', 'Desired cluster size per key (positive integer)')
808
+ .option('--assumed-cluster-size <number>', 'Smallest cohort this deployment can genuinely field. Sets both the membership admission gate\'s fallback floor (used when the node has no confident network-size estimate; defaults to 2 when unset) and the read-repair/reconcile corroboration floor (unless --repair-corroboration-cluster-size is given; falls back to --cluster-size when neither is set). A mesh smaller than --cluster-size needs this (or --repair-corroboration-cluster-size) to repair damaged blocks')
809
+ .option('--repair-corroboration-cluster-size <number>', 'Cohort size the read-repair/reconcile corroboration floor alone is measured against (positive integer). Unlike --assumed-cluster-size this does NOT raise the membership admission gate\'s low-confidence write floor, so it tightens repair without risking refused writes. Wins over --assumed-cluster-size for the repair floor; defaults to --assumed-cluster-size, then --cluster-size')
810
+ .option('--super-majority-threshold <number>', 'Super-majority threshold as a fraction in (0, 1] (default 0.75)')
811
+ .option('--offline', 'Run as single-node LocalTransactor (no distributed consensus)')
812
+ .option('--bootstrap-file <path>', 'Path to JSON containing bootstrap multiaddrs or node list')
813
+ .option('--announce-file <path>', 'Write node info (peerId, multiaddrs) to this JSON file for mesh launchers')
814
+ .option('--announce-addr <multiaddr>', 'Multiaddr to advertise INSTEAD OF the listen addrs (e.g. behind a TLS proxy: /dns4/host/tcp/443/wss). Repeatable; replaces the advertised set entirely', collectMultiaddr('--announce-addr'), [] as string[])
815
+ .option('--append-announce-addr <multiaddr>', 'Multiaddr to advertise IN ADDITION TO the listen addrs. Repeatable; ignored while --announce-addr is set', collectMultiaddr('--append-announce-addr'), [] as string[]);
816
+ }
817
+
818
+ // Interactive mode - network-first approach
819
+ withCommonPeerOptions(
820
+ program
821
+ .command('interactive')
822
+ .description('Start interactive mode (default behavior)')
823
+ )
824
+ .action(async (options) => {
825
+ try {
826
+ await session.startNetwork(options);
827
+ await session.startInteractive();
828
+ } catch (error) {
829
+ if (error instanceof Error) {
830
+ console.error('❌ Error:', error.message);
831
+ if (error.stack) console.error(error.stack);
832
+ } else {
833
+ console.error('❌ Error:', error);
834
+ }
835
+ process.exit(1);
836
+ }
837
+ });
838
+
839
+ // Headless service node (no REPL); useful for mesh nodes in launch profiles
840
+ withCommonPeerOptions(
841
+ program
842
+ .command('service')
843
+ .description('Start a headless service node (no interactive prompt)')
844
+ )
845
+ .action(async (options) => {
846
+ try {
847
+ await session.startNetwork(options);
848
+ // Keep process alive
849
+ process.stdin.resume();
850
+ } catch (error) {
851
+ if (error instanceof Error) {
852
+ console.error('❌ Error:', error.message);
853
+ if (error.stack) console.error(error.stack);
854
+ } else {
855
+ console.error('❌ Error:', error);
856
+ }
857
+ process.exit(1);
858
+ }
859
+ });
860
+
861
+ // Single-action mode commands
862
+ withCommonPeerOptions(
863
+ program
864
+ .command('run')
865
+ .description('Connect to network, run a single action, optionally stay connected')
866
+ )
867
+ .option('--stay-connected', 'Stay connected after action completes')
868
+ .requiredOption('-a, --action <action>', 'Action to perform: create-diary, add-entry, list-diaries, read-diary')
869
+ .option('--diary <name>', 'Diary name (required for diary operations)')
870
+ .option('--content <content>', 'Entry content (required for add-entry)')
871
+ .action(async (options) => {
872
+ try {
873
+ await session.startNetwork(options);
874
+
875
+ // Perform the requested action
876
+ switch (options.action) {
877
+ case 'create-diary':
878
+ if (!options.diary) {
879
+ throw new Error('--diary is required for create-diary action');
880
+ }
881
+ await session.createDiary(options.diary);
882
+ break;
883
+ case 'add-entry':
884
+ if (!options.diary || !options.content) {
885
+ throw new Error('--diary and --content are required for add-entry action');
886
+ }
887
+ await session.addEntry(options.diary, options.content);
888
+ break;
889
+ case 'list-diaries':
890
+ await session.listDiaries();
891
+ break;
892
+ case 'read-diary':
893
+ if (!options.diary) {
894
+ throw new Error('--diary is required for read-diary action');
895
+ }
896
+ await session.readDiary(options.diary);
897
+ break;
898
+ default:
899
+ throw new Error(`Unknown action: ${options.action}`);
900
+ }
901
+
902
+ if (options.stayConnected) {
903
+ console.log('🔄 Staying connected. Starting interactive mode...');
904
+ await session.startInteractive();
905
+ } else {
906
+ console.log('✅ Action completed. Disconnecting...');
907
+ await session.stopNetwork();
908
+ }
909
+
910
+ } catch (error) {
911
+ if (error instanceof Error) {
912
+ console.error('❌ Error:', error.message);
913
+ if (error.stack) console.error(error.stack);
914
+ } else {
915
+ console.error('❌ Error:', error);
916
+ }
917
+ await session.cleanup();
918
+ process.exit(1);
919
+ }
920
+ });
921
+
922
+ // Default to interactive mode if no command specified
923
+ if (process.argv.length <= 2) {
924
+ process.argv.push('interactive');
925
+ }
926
+
927
+ program.parse();