yakmesh 1.1.0 → 1.3.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.
@@ -0,0 +1,398 @@
1
+ /**
2
+ * YAKMESH™ v1.3.0 Novel Systems Test Suite
3
+ * Tests for: ECHO, PULSE, PHANTOM, BEACON
4
+ */
5
+
6
+ import {
7
+ ECHO_CONFIG,
8
+ EchoProbe,
9
+ EchoResponse,
10
+ VirtualCoordinates,
11
+ LatencyTracker,
12
+ EchoRanging,
13
+ } from './mesh/echo-ranging.js';
14
+
15
+ import {
16
+ PULSE_CONFIG,
17
+ Heartbeat,
18
+ HeartbeatChain,
19
+ MeshHealthMonitor,
20
+ PulseLeaderElection,
21
+ PulseSync,
22
+ } from './mesh/pulse-sync.js';
23
+
24
+ import {
25
+ BEACON_CONFIG,
26
+ BeaconMessage,
27
+ DeliveryReceipt,
28
+ DeduplicationTracker,
29
+ ReceiptCollector,
30
+ PriorityMessageQueue,
31
+ BeaconBroadcast,
32
+ } from './mesh/beacon-broadcast.js';
33
+
34
+ // Test utilities
35
+ let passed = 0;
36
+ let failed = 0;
37
+
38
+ function test(name, fn) {
39
+ try {
40
+ fn();
41
+ console.log('✅ ' + name);
42
+ passed++;
43
+ } catch (err) {
44
+ console.log('❌ ' + name + ': ' + err.message);
45
+ failed++;
46
+ }
47
+ }
48
+
49
+ function assertEqual(actual, expected, msg = '') {
50
+ if (actual !== expected) {
51
+ throw new Error(msg + ' Expected: ' + expected + ', Got: ' + actual);
52
+ }
53
+ }
54
+
55
+ function assertTrue(condition, msg = '') {
56
+ if (!condition) throw new Error(msg || 'Expected true');
57
+ }
58
+
59
+ function assertFalse(condition, msg = '') {
60
+ if (condition) throw new Error(msg || 'Expected false');
61
+ }
62
+
63
+ // ═══════════════════════════════════════════════════════════════════
64
+ console.log('\n╔═══════════════════════════════════════════════════════════╗');
65
+ console.log('║ YAKMESH v1.3.0 NOVEL SYSTEMS TEST SUITE ║');
66
+ console.log('╚═══════════════════════════════════════════════════════════╝\n');
67
+
68
+ // ─────────────────────────────────────────────────────────────────────
69
+ console.log('─── ECHO™ (Encrypted Coordinate Heuristic Oracle) Tests ───\n');
70
+
71
+ test('VirtualCoordinates initializes with random values', () => {
72
+ const vc = new VirtualCoordinates(8);
73
+ assertEqual(vc.dimensions, 8);
74
+ assertEqual(vc.coordinates.length, 8);
75
+ assertTrue(vc.error > 0, 'Should have initial error');
76
+ });
77
+
78
+ test('VirtualCoordinates updates based on RTT measurement', () => {
79
+ const vc = new VirtualCoordinates(4);
80
+ const peerCoords = [10, 20, 30, 40];
81
+ const result = vc.update(peerCoords, 50);
82
+
83
+ assertTrue(result.predictedDistance !== undefined);
84
+ assertTrue(result.measuredRtt === 50);
85
+ assertTrue(result.newCoordinates.length === 4);
86
+ assertEqual(vc.updateCount, 1);
87
+ });
88
+
89
+ test('VirtualCoordinates calculates distance correctly', () => {
90
+ const vc = new VirtualCoordinates(3);
91
+ vc.coordinates = [0, 0, 0];
92
+ const distance = vc.distanceTo([3, 4, 0]);
93
+ assertEqual(distance, 5); // 3-4-5 triangle
94
+ });
95
+
96
+ test('LatencyTracker computes statistics', () => {
97
+ const tracker = new LatencyTracker(5);
98
+ tracker.addSample(100000000n); // 100ms in ns
99
+ tracker.addSample(150000000n);
100
+ tracker.addSample(200000000n);
101
+
102
+ const stats = tracker.getStats();
103
+ assertTrue(stats !== null);
104
+ assertEqual(stats.sampleCount, 3);
105
+ assertTrue(stats.min === 100000000n);
106
+ assertTrue(stats.max === 200000000n);
107
+ });
108
+
109
+ test('EchoRanging creates and handles probes', () => {
110
+ const echo = new EchoRanging({ nodeId: 'node-a' });
111
+ const probe = echo.createProbe('node-b');
112
+
113
+ assertTrue(probe.probeId !== undefined);
114
+ assertEqual(probe.sourceNodeId, 'node-a');
115
+ assertEqual(probe.targetNodeId, 'node-b');
116
+ assertEqual(echo.stats.probesSent, 1);
117
+ });
118
+
119
+ test('EchoRanging handles probe responses', () => {
120
+ const echoA = new EchoRanging({ nodeId: 'node-a' });
121
+ const echoB = new EchoRanging({ nodeId: 'node-b' });
122
+
123
+ // A sends probe to B
124
+ const probe = echoA.createProbe('node-b');
125
+
126
+ // B handles probe and generates response
127
+ const response = echoB.handleProbe(probe, 'node-a');
128
+ assertTrue(response.probeId === probe.probeId);
129
+ assertTrue(response.coordinates !== undefined);
130
+ });
131
+
132
+ test('EchoRanging builds topology from measurements', () => {
133
+ const echo = new EchoRanging({ nodeId: 'center' });
134
+
135
+ // Simulate peer coordinate data
136
+ echo.peerCoordinates.set('peer1', [10, 20, 30, 40, 50, 60, 70, 80]);
137
+ echo.peerCoordinates.set('peer2', [15, 25, 35, 45, 55, 65, 75, 85]);
138
+
139
+ const topology = echo.getTopology();
140
+ assertEqual(topology.self.nodeId, 'center');
141
+ assertEqual(topology.peers.length, 2);
142
+ });
143
+
144
+ test('EchoRanging estimates latency to peer', () => {
145
+ const echo = new EchoRanging({ nodeId: 'node-a' });
146
+ echo.coordinates.coordinates = [0, 0, 0, 0, 0, 0, 0, 0];
147
+ echo.peerCoordinates.set('node-b', [10, 0, 0, 0, 0, 0, 0, 0]);
148
+
149
+ const latency = echo.estimateLatency('node-b');
150
+ assertEqual(latency, 10);
151
+ });
152
+
153
+ // ─────────────────────────────────────────────────────────────────────
154
+ console.log('\n─── PULSE™ (Precision Universal Latency Sync Engine) Tests ───\n');
155
+
156
+ test('Heartbeat creates with valid hash', () => {
157
+ const hb = new Heartbeat({
158
+ nodeId: 'node-a',
159
+ sequence: 0,
160
+ });
161
+
162
+ assertTrue(hb.hash.length === 64);
163
+ assertTrue(hb.verify());
164
+ });
165
+
166
+ test('Heartbeat chaining works correctly', () => {
167
+ const hb1 = new Heartbeat({ nodeId: 'node-a', sequence: 0, timestamp: 1000 });
168
+ const hb2 = new Heartbeat({
169
+ nodeId: 'node-a',
170
+ sequence: 1,
171
+ prevHash: hb1.hash,
172
+ timestamp: 2000,
173
+ });
174
+
175
+ assertTrue(hb2.chainsFrom(hb1));
176
+ });
177
+
178
+ test('Heartbeat rejects tampering', () => {
179
+ const hb = new Heartbeat({
180
+ nodeId: 'node-a',
181
+ sequence: 5,
182
+ });
183
+
184
+ hb.timestamp = Date.now() + 1000; // Tamper
185
+ assertFalse(hb.verify());
186
+ });
187
+
188
+ test('HeartbeatChain tracks node liveness', () => {
189
+ const chain = new HeartbeatChain('node-a');
190
+
191
+ const hb = new Heartbeat({ nodeId: 'node-a', sequence: 0 });
192
+ const result = chain.addHeartbeat(hb);
193
+
194
+ assertTrue(result.success);
195
+ assertEqual(chain.status, 'alive');
196
+ assertEqual(chain.chain.length, 1);
197
+ });
198
+
199
+ test('HeartbeatChain detects missed heartbeats', () => {
200
+ const chain = new HeartbeatChain('node-a');
201
+ const hb = new Heartbeat({ nodeId: 'node-a', sequence: 0 });
202
+ chain.addHeartbeat(hb, Date.now() - 10000); // 10 seconds ago
203
+
204
+ const liveness = chain.checkLiveness();
205
+ assertTrue(liveness.missedBeats >= 5);
206
+ assertEqual(liveness.status, 'dead');
207
+ });
208
+
209
+ test('MeshHealthMonitor tracks multiple nodes', () => {
210
+ const monitor = new MeshHealthMonitor();
211
+
212
+ const hb1 = new Heartbeat({ nodeId: 'node-a', sequence: 0 });
213
+ const hb2 = new Heartbeat({ nodeId: 'node-b', sequence: 0 });
214
+
215
+ monitor.processHeartbeat(hb1);
216
+ monitor.processHeartbeat(hb2);
217
+
218
+ assertEqual(monitor.nodes.size, 2);
219
+ });
220
+
221
+ test('PulseLeaderElection starts election', () => {
222
+ const election = new PulseLeaderElection({ nodeId: 'node-a' });
223
+ const request = election.startElection();
224
+
225
+ assertEqual(request.type, 'VOTE_REQUEST');
226
+ assertEqual(request.term, 1);
227
+ assertEqual(request.candidateId, 'node-a');
228
+ assertEqual(election.state, 'candidate');
229
+ });
230
+
231
+ test('PulseLeaderElection handles vote response', () => {
232
+ const election = new PulseLeaderElection({ nodeId: 'node-a' });
233
+ election.startElection();
234
+
235
+ // Simulate receiving a vote
236
+ const result = election.handleVoteResponse({
237
+ voteGranted: true,
238
+ term: 1,
239
+ voterId: 'node-b'
240
+ }, 2); // 2 total nodes
241
+
242
+ // With 2 votes (self + peer) out of 2 nodes, should be elected
243
+ assertTrue(result.elected);
244
+ assertEqual(election.state, 'leader');
245
+ });
246
+
247
+ test('PulseSync creates and receives heartbeats', () => {
248
+ const syncA = new PulseSync({ nodeId: 'node-a' });
249
+ const syncB = new PulseSync({ nodeId: 'node-b' });
250
+ const hbA = syncA.createHeartbeat({ peerCount: 5 });
251
+ assertTrue(hbA.nodeId === 'node-a');
252
+ assertEqual(syncA.stats.heartbeatsSent, 1);
253
+ const result = syncB.receiveHeartbeat(hbA);
254
+ assertTrue(result.success);
255
+ assertEqual(syncB.stats.heartbeatsReceived, 1);
256
+ });
257
+
258
+ // ─────────────────────────────────────────────────────────────────────
259
+ console.log('\n─── BEACON™ (Broadcast Emergency Alert Channel) Tests ───\n');
260
+
261
+ test('BeaconMessage creates with valid hash', () => {
262
+ const msg = new BeaconMessage({
263
+ originNodeId: 'node-a',
264
+ payload: { alert: 'Test message' },
265
+ });
266
+
267
+ assertTrue(msg.hash.length === 64);
268
+ assertTrue(msg.isValid());
269
+ });
270
+
271
+ test('BeaconMessage forwards with decremented TTL', () => {
272
+ const msg = new BeaconMessage({
273
+ originNodeId: 'node-a',
274
+ payload: { data: 'test' },
275
+ ttl: 5,
276
+ });
277
+
278
+ const forwarded = msg.forward('node-b');
279
+ assertEqual(forwarded.ttl, 4);
280
+ assertTrue(forwarded.hopPath.includes('node-b'));
281
+ });
282
+
283
+ test('BeaconMessage expires correctly', () => {
284
+ const msg = new BeaconMessage({
285
+ originNodeId: 'node-a',
286
+ payload: { data: 'test' },
287
+ expiresAt: Date.now() - 1000, // Already expired
288
+ });
289
+
290
+ assertFalse(msg.isValid());
291
+ });
292
+
293
+ test('DeliveryReceipt creates with valid hash', () => {
294
+ const receipt = new DeliveryReceipt({
295
+ messageId: 'msg-123',
296
+ receiverNodeId: 'node-b',
297
+ });
298
+
299
+ assertTrue(receipt.hash.length === 64);
300
+ });
301
+
302
+ test('DeduplicationTracker detects duplicates', () => {
303
+ const dedup = new DeduplicationTracker();
304
+ const msg = new BeaconMessage({
305
+ originNodeId: 'node-a',
306
+ payload: { test: true },
307
+ });
308
+
309
+ assertTrue(dedup.markSeen(msg)); // First time
310
+ assertTrue(dedup.isDuplicate(msg.id)); // Now it's seen
311
+
312
+ dedup.destroy();
313
+ });
314
+
315
+ test('PriorityMessageQueue respects priority order', () => {
316
+ const queue = new PriorityMessageQueue();
317
+
318
+ const routine = new BeaconMessage({
319
+ originNodeId: 'a',
320
+ payload: 'routine',
321
+ priority: BEACON_CONFIG.priorities.ROUTINE,
322
+ });
323
+
324
+ const critical = new BeaconMessage({
325
+ originNodeId: 'a',
326
+ payload: 'critical',
327
+ priority: BEACON_CONFIG.priorities.CRITICAL,
328
+ });
329
+
330
+ queue.enqueue(routine);
331
+ queue.enqueue(critical);
332
+
333
+ const first = queue.dequeue();
334
+ assertEqual(first.priority, BEACON_CONFIG.priorities.CRITICAL);
335
+ });
336
+
337
+ test('BeaconBroadcast broadcasts messages', () => {
338
+ const beacon = new BeaconBroadcast({ nodeId: 'origin' });
339
+ beacon.addPeer('peer-1');
340
+ beacon.addPeer('peer-2');
341
+
342
+ const result = beacon.broadcast({ alert: 'test' });
343
+
344
+ assertTrue(result.messageId !== undefined);
345
+ assertEqual(result.queuedFor, 2);
346
+ assertEqual(beacon.stats.messagesOriginated, 1);
347
+
348
+ beacon.destroy();
349
+ });
350
+
351
+ test('BeaconBroadcast receives and forwards', () => {
352
+ const beaconA = new BeaconBroadcast({ nodeId: 'node-a' });
353
+ const beaconB = new BeaconBroadcast({ nodeId: 'node-b' });
354
+ beaconB.addPeer('node-c');
355
+
356
+ // A broadcasts
357
+ const msg = new BeaconMessage({
358
+ originNodeId: 'node-a',
359
+ payload: { data: 'hello' },
360
+ });
361
+
362
+ // B receives
363
+ const result = beaconB.receive(msg.serialize());
364
+
365
+ assertTrue(result.accepted);
366
+ assertTrue(result.receipt !== undefined);
367
+ assertEqual(result.forwarded.length, 1); // Forwarded to node-c
368
+
369
+ beaconA.destroy();
370
+ beaconB.destroy();
371
+ });
372
+
373
+ test('BeaconBroadcast sends emergency with max TTL', () => {
374
+ const beacon = new BeaconBroadcast({ nodeId: 'emergency-node' });
375
+ beacon.addPeer('peer-1');
376
+
377
+ let deliveryConfirmed = false;
378
+ const result = beacon.sendEmergency(
379
+ { type: 'EARTHQUAKE', magnitude: 7.2 },
380
+ {
381
+ expectedReceipts: 1,
382
+ onDeliveryConfirm: () => { deliveryConfirmed = true; }
383
+ }
384
+ );
385
+
386
+ assertTrue(result.messageId !== undefined);
387
+
388
+ beacon.destroy();
389
+ });
390
+
391
+ // ═══════════════════════════════════════════════════════════════════
392
+ console.log('\n╔═══════════════════════════════════════════════════════════╗');
393
+ console.log('║ RESULTS: ' + passed + ' passed, ' + failed + ' failed' + ' '.repeat(Math.max(0, 37 - passed.toString().length - failed.toString().length)) + '║');
394
+ console.log('╚═══════════════════════════════════════════════════════════╝\n');
395
+
396
+ if (failed > 0) {
397
+ process.exit(1);
398
+ }