@johnhenry/browsermesh-sync 0.0.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,1059 @@
1
+ /**
2
+ // STATUS: INTEGRATED — wired into ClawserPod lifecycle, proven via E2E testing
3
+ * clawser-mesh-delta-sync.js -- Delta-Based Synchronization Protocol.
4
+ *
5
+ * Efficient state synchronization using delta (diff) encoding:
6
+ *
7
+ * - DeltaEntry: a single state change with vector clock causality.
8
+ * - DeltaLog: append-only log of delta entries with compaction.
9
+ * - DeltaEncoder: produces compact diffs between states.
10
+ * - DeltaDecoder: applies delta patches to reconstruct state.
11
+ * - SyncSession: manages a sync session between two peers.
12
+ * - SyncCoordinator: orchestrates delta sync across multiple peers.
13
+ *
14
+ * No browser-only imports at module level.
15
+ *
16
+ * Run tests:
17
+ * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-mesh-delta-sync.test.mjs
18
+ */
19
+
20
+ // ---------------------------------------------------------------------------
21
+ // Wire Constants
22
+ // ---------------------------------------------------------------------------
23
+
24
+ /** Wire type for delta sync request (pull). */
25
+ export const DELTA_SYNC_REQUEST = 0xE0;
26
+
27
+ /** Wire type for delta sync response (push deltas). */
28
+ export const DELTA_SYNC_RESPONSE = 0xE1;
29
+
30
+ /** Wire type for delta sync acknowledgment. */
31
+ export const DELTA_SYNC_ACK = 0xE2;
32
+
33
+ /** Wire type for full state snapshot (fallback). */
34
+ export const DELTA_FULL_SNAPSHOT = 0xE3;
35
+
36
+ /** Wire type for branch creation. */
37
+ export const DELTA_BRANCH_CREATE = 0xE4;
38
+
39
+ /** Wire type for branch merge. */
40
+ export const DELTA_BRANCH_MERGE = 0xE5;
41
+
42
+ // ---------------------------------------------------------------------------
43
+ // DeltaEntry
44
+ // ---------------------------------------------------------------------------
45
+
46
+ let _deltaSeq = 0;
47
+
48
+ /**
49
+ * A single state change entry in the delta log.
50
+ */
51
+ export class DeltaEntry {
52
+ /**
53
+ * @param {object} opts
54
+ * @param {string} [opts.id] Unique entry ID
55
+ * @param {string} opts.key State key that changed
56
+ * @param {string} opts.op Operation: 'set', 'delete', 'merge'
57
+ * @param {*} [opts.value] New value (for 'set' and 'merge')
58
+ * @param {string} opts.origin Pod ID that produced this delta
59
+ * @param {number} [opts.seq] Local sequence number
60
+ * @param {number} [opts.timestamp] Unix timestamp (ms)
61
+ * @param {Object} [opts.vectorClock] Causal vector clock snapshot
62
+ */
63
+ constructor({
64
+ id,
65
+ key,
66
+ op,
67
+ value,
68
+ origin,
69
+ seq,
70
+ timestamp,
71
+ vectorClock = {},
72
+ }) {
73
+ if (!key || typeof key !== 'string') {
74
+ throw new Error('key is required and must be a non-empty string');
75
+ }
76
+ if (!op || !['set', 'delete', 'merge'].includes(op)) {
77
+ throw new Error('op must be "set", "delete", or "merge"');
78
+ }
79
+ if (!origin || typeof origin !== 'string') {
80
+ throw new Error('origin is required and must be a non-empty string');
81
+ }
82
+
83
+ this.id = id || `delta_${Date.now()}_${++_deltaSeq}`;
84
+ this.key = key;
85
+ this.op = op;
86
+ this.value = op === 'delete' ? undefined : value;
87
+ this.origin = origin;
88
+ this.seq = seq ?? ++_deltaSeq;
89
+ this.timestamp = timestamp || Date.now();
90
+ this.vectorClock = { ...vectorClock };
91
+ }
92
+
93
+ toJSON() {
94
+ const obj = {
95
+ id: this.id,
96
+ key: this.key,
97
+ op: this.op,
98
+ origin: this.origin,
99
+ seq: this.seq,
100
+ timestamp: this.timestamp,
101
+ vectorClock: { ...this.vectorClock },
102
+ };
103
+ if (this.op !== 'delete') obj.value = this.value;
104
+ return obj;
105
+ }
106
+
107
+ static fromJSON(data) {
108
+ return new DeltaEntry(data);
109
+ }
110
+ }
111
+
112
+ // ---------------------------------------------------------------------------
113
+ // DeltaLog
114
+ // ---------------------------------------------------------------------------
115
+
116
+ /**
117
+ * Append-only log of delta entries with compaction and slicing.
118
+ */
119
+ export class DeltaLog {
120
+ /** @type {DeltaEntry[]} */
121
+ #entries = [];
122
+
123
+ /** @type {number} Max entries before auto-compaction (0 = no auto) */
124
+ #maxSize;
125
+
126
+ /**
127
+ * @param {object} [opts]
128
+ * @param {number} [opts.maxSize=0] Max entries before auto-compaction
129
+ */
130
+ constructor({ maxSize = 0 } = {}) {
131
+ this.#maxSize = maxSize;
132
+ }
133
+
134
+ /** Number of entries. */
135
+ get length() {
136
+ return this.#entries.length;
137
+ }
138
+
139
+ /**
140
+ * Append a delta entry.
141
+ * @param {DeltaEntry} entry
142
+ */
143
+ append(entry) {
144
+ this.#entries.push(entry);
145
+ if (this.#maxSize > 0 && this.#entries.length > this.#maxSize) {
146
+ this.compact();
147
+ }
148
+ }
149
+
150
+ /**
151
+ * Get entries since a given sequence number (exclusive).
152
+ * @param {number} sinceSeq
153
+ * @returns {DeltaEntry[]}
154
+ */
155
+ since(sinceSeq) {
156
+ return this.#entries.filter(e => e.seq > sinceSeq);
157
+ }
158
+
159
+ /**
160
+ * Get entries since a given vector clock.
161
+ * Returns entries not dominated by the provided clock.
162
+ * @param {Object} vclock - { podId: seq }
163
+ * @returns {DeltaEntry[]}
164
+ */
165
+ sinceVectorClock(vclock) {
166
+ return this.#entries.filter(e => {
167
+ const knownSeq = vclock[e.origin] || 0;
168
+ return e.seq > knownSeq;
169
+ });
170
+ }
171
+
172
+ /**
173
+ * Compact the log: for each key, keep only the latest entry.
174
+ * @returns {number} Number of entries removed
175
+ */
176
+ compact() {
177
+ const latest = new Map();
178
+ // Iterate in order; later entries override earlier ones
179
+ for (const entry of this.#entries) {
180
+ latest.set(entry.key, entry);
181
+ }
182
+ const before = this.#entries.length;
183
+ this.#entries = [...latest.values()];
184
+ return before - this.#entries.length;
185
+ }
186
+
187
+ /** Get all entries (copy). */
188
+ toArray() {
189
+ return [...this.#entries];
190
+ }
191
+
192
+ /** Get the latest entry for a specific key. */
193
+ getLatest(key) {
194
+ for (let i = this.#entries.length - 1; i >= 0; i--) {
195
+ if (this.#entries[i].key === key) return this.#entries[i];
196
+ }
197
+ return null;
198
+ }
199
+
200
+ /** Get the maximum sequence number across all entries. */
201
+ getMaxSeq() {
202
+ let max = 0;
203
+ for (const e of this.#entries) {
204
+ if (e.seq > max) max = e.seq;
205
+ }
206
+ return max;
207
+ }
208
+
209
+ /** Build a vector clock from all entries. */
210
+ getVectorClock() {
211
+ const vc = {};
212
+ for (const e of this.#entries) {
213
+ if (!vc[e.origin] || e.seq > vc[e.origin]) {
214
+ vc[e.origin] = e.seq;
215
+ }
216
+ }
217
+ return vc;
218
+ }
219
+
220
+ /** Clear all entries. */
221
+ clear() {
222
+ this.#entries = [];
223
+ }
224
+
225
+ toJSON() {
226
+ return this.#entries.map(e => e.toJSON());
227
+ }
228
+
229
+ static fromJSON(arr) {
230
+ const log = new DeltaLog();
231
+ for (const d of arr) {
232
+ log.append(DeltaEntry.fromJSON(d));
233
+ }
234
+ return log;
235
+ }
236
+ }
237
+
238
+ // ---------------------------------------------------------------------------
239
+ // DeltaEncoder
240
+ // ---------------------------------------------------------------------------
241
+
242
+ /**
243
+ * Produces compact delta diffs between two state snapshots.
244
+ */
245
+ export class DeltaEncoder {
246
+ /**
247
+ * Compute the delta between oldState and newState.
248
+ * @param {Object} oldState - Previous state (key→value map)
249
+ * @param {Object} newState - Current state (key→value map)
250
+ * @param {string} origin - Pod ID producing this delta
251
+ * @returns {DeltaEntry[]} Array of delta entries
252
+ */
253
+ encode(oldState, newState, origin) {
254
+ if (!origin || typeof origin !== 'string') {
255
+ throw new Error('origin is required and must be a non-empty string');
256
+ }
257
+ const entries = [];
258
+ const allKeys = new Set([...Object.keys(oldState), ...Object.keys(newState)]);
259
+
260
+ for (const key of allKeys) {
261
+ const oldVal = oldState[key];
262
+ const newVal = newState[key];
263
+
264
+ if (!(key in newState)) {
265
+ // Key deleted
266
+ entries.push(new DeltaEntry({ key, op: 'delete', origin }));
267
+ } else if (!(key in oldState)) {
268
+ // Key added
269
+ entries.push(new DeltaEntry({ key, op: 'set', value: newVal, origin }));
270
+ } else if (!this._deepEqual(oldVal, newVal)) {
271
+ // Key changed
272
+ if (typeof oldVal === 'object' && typeof newVal === 'object' &&
273
+ oldVal !== null && newVal !== null &&
274
+ !Array.isArray(oldVal) && !Array.isArray(newVal)) {
275
+ // Object merge
276
+ entries.push(new DeltaEntry({ key, op: 'merge', value: newVal, origin }));
277
+ } else {
278
+ entries.push(new DeltaEntry({ key, op: 'set', value: newVal, origin }));
279
+ }
280
+ }
281
+ }
282
+
283
+ return entries;
284
+ }
285
+
286
+ /**
287
+ * Compute the byte size estimate of a set of entries.
288
+ * @param {DeltaEntry[]} entries
289
+ * @returns {number}
290
+ */
291
+ estimateSize(entries) {
292
+ return entries.reduce((sum, e) => sum + JSON.stringify(e.toJSON()).length, 0);
293
+ }
294
+
295
+ /** @private Deep equality check (simple JSON comparison). */
296
+ _deepEqual(a, b) {
297
+ return JSON.stringify(a) === JSON.stringify(b);
298
+ }
299
+ }
300
+
301
+ // ---------------------------------------------------------------------------
302
+ // DeltaDecoder
303
+ // ---------------------------------------------------------------------------
304
+
305
+ /**
306
+ * Applies delta patches to reconstruct/update state.
307
+ */
308
+ export class DeltaDecoder {
309
+ /**
310
+ * Apply a set of delta entries to a state object.
311
+ * @param {Object} state - Mutable state to update
312
+ * @param {DeltaEntry[]} entries - Deltas to apply
313
+ * @returns {Object} Updated state (same reference)
314
+ */
315
+ apply(state, entries) {
316
+ for (const entry of entries) {
317
+ switch (entry.op) {
318
+ case 'set':
319
+ state[entry.key] = entry.value;
320
+ break;
321
+ case 'delete':
322
+ delete state[entry.key];
323
+ break;
324
+ case 'merge':
325
+ if (typeof state[entry.key] === 'object' && state[entry.key] !== null) {
326
+ state[entry.key] = { ...state[entry.key], ...entry.value };
327
+ } else {
328
+ state[entry.key] = entry.value;
329
+ }
330
+ break;
331
+ default:
332
+ throw new Error(`Unknown delta op: ${entry.op}`);
333
+ }
334
+ }
335
+ return state;
336
+ }
337
+
338
+ /**
339
+ * Apply entries in causal order (sort by vector clock).
340
+ * @param {Object} state
341
+ * @param {DeltaEntry[]} entries
342
+ * @returns {Object}
343
+ */
344
+ applyCausal(state, entries) {
345
+ // Sort by timestamp as proxy for causal order
346
+ const sorted = [...entries].sort((a, b) => a.timestamp - b.timestamp || a.seq - b.seq);
347
+ return this.apply(state, sorted);
348
+ }
349
+ }
350
+
351
+ // ---------------------------------------------------------------------------
352
+ // DeltaBranch
353
+ // ---------------------------------------------------------------------------
354
+
355
+ /**
356
+ * A parallel state timeline branched from the main sync state.
357
+ * Each branch captures a snapshot at fork point and maintains its
358
+ * own independent delta log.
359
+ */
360
+ export class DeltaBranch {
361
+ #name
362
+ #snapshot
363
+ #parentBranch
364
+ #log
365
+ #createdAt
366
+
367
+ /**
368
+ * @param {string} name - Branch name
369
+ * @param {Object} snapshotState - State snapshot at fork point
370
+ * @param {string|null} [parentBranch] - Parent branch name (null = main)
371
+ */
372
+ constructor(name, snapshotState, parentBranch = null) {
373
+ if (!name || typeof name !== 'string') {
374
+ throw new Error('Branch name is required and must be a non-empty string')
375
+ }
376
+ this.#name = name
377
+ this.#snapshot = { ...snapshotState }
378
+ this.#parentBranch = parentBranch
379
+ this.#log = new DeltaLog()
380
+ this.#createdAt = Date.now()
381
+ }
382
+
383
+ get name() { return this.#name }
384
+ get parentBranch() { return this.#parentBranch }
385
+ get createdAt() { return this.#createdAt }
386
+ get logSize() { return this.#log.length }
387
+
388
+ /**
389
+ * Apply a set operation on this branch.
390
+ */
391
+ apply(key, value, origin = 'branch') {
392
+ const entry = new DeltaEntry({
393
+ key,
394
+ op: 'set',
395
+ value,
396
+ origin,
397
+ vectorClock: this.#log.getVectorClock(),
398
+ })
399
+ this.#log.append(entry)
400
+ }
401
+
402
+ /**
403
+ * Delete a key on this branch.
404
+ */
405
+ delete(key, origin = 'branch') {
406
+ const entry = new DeltaEntry({
407
+ key,
408
+ op: 'delete',
409
+ origin,
410
+ vectorClock: this.#log.getVectorClock(),
411
+ })
412
+ this.#log.append(entry)
413
+ }
414
+
415
+ /**
416
+ * Get the current state of this branch (snapshot + applied deltas).
417
+ */
418
+ getState() {
419
+ const state = { ...this.#snapshot }
420
+ const decoder = new DeltaDecoder()
421
+ return decoder.apply(state, this.#log.toArray())
422
+ }
423
+
424
+ /**
425
+ * Compute the diff between this branch and another branch (or state).
426
+ * Returns the set of keys that differ.
427
+ */
428
+ diffFrom(otherBranch) {
429
+ const thisState = this.getState()
430
+ const otherState = otherBranch instanceof DeltaBranch
431
+ ? otherBranch.getState()
432
+ : otherBranch // plain state object
433
+
434
+ const allKeys = new Set([...Object.keys(thisState), ...Object.keys(otherState)])
435
+ const changed = []
436
+ for (const key of allKeys) {
437
+ if (JSON.stringify(thisState[key]) !== JSON.stringify(otherState[key])) {
438
+ changed.push({
439
+ key,
440
+ ours: thisState[key],
441
+ theirs: otherState[key],
442
+ })
443
+ }
444
+ }
445
+ return changed
446
+ }
447
+
448
+ /**
449
+ * Get the delta log for this branch.
450
+ */
451
+ getLog() {
452
+ return this.#log
453
+ }
454
+
455
+ toJSON() {
456
+ return {
457
+ name: this.#name,
458
+ snapshot: { ...this.#snapshot },
459
+ parentBranch: this.#parentBranch,
460
+ log: this.#log.toJSON(),
461
+ createdAt: this.#createdAt,
462
+ }
463
+ }
464
+ }
465
+
466
+ // ---------------------------------------------------------------------------
467
+ // SyncSession
468
+ // ---------------------------------------------------------------------------
469
+
470
+ /** @type {readonly string[]} */
471
+ const SYNC_STATES = Object.freeze([
472
+ 'idle',
473
+ 'requesting',
474
+ 'receiving',
475
+ 'applying',
476
+ 'complete',
477
+ 'error',
478
+ ]);
479
+
480
+ /**
481
+ * Manages a sync session between two peers.
482
+ */
483
+ export class SyncSession {
484
+ /** @type {string} */
485
+ #id;
486
+ /** @type {string} */
487
+ #localPodId;
488
+ /** @type {string} */
489
+ #remotePodId;
490
+ /** @type {string} */
491
+ #state = 'idle';
492
+ /** @type {Object} */
493
+ #localClock;
494
+ /** @type {Object} */
495
+ #remoteClock;
496
+ /** @type {DeltaEntry[]} */
497
+ #pendingSend = [];
498
+ /** @type {DeltaEntry[]} */
499
+ #pendingReceive = [];
500
+ /** @type {number} */
501
+ #createdAt;
502
+ /** @type {number} */
503
+ #lastSyncAt = 0;
504
+ /** @type {{ sent: number, received: number, rounds: number }} */
505
+ #stats = { sent: 0, received: 0, rounds: 0 };
506
+ /** @type {Function[]} */
507
+ #stateListeners = [];
508
+
509
+ /**
510
+ * @param {object} opts
511
+ * @param {string} [opts.id]
512
+ * @param {string} opts.localPodId
513
+ * @param {string} opts.remotePodId
514
+ * @param {Object} [opts.localClock] Initial local vector clock
515
+ * @param {Object} [opts.remoteClock] Known remote vector clock
516
+ */
517
+ constructor({ id, localPodId, remotePodId, localClock = {}, remoteClock = {} }) {
518
+ if (!localPodId || typeof localPodId !== 'string') {
519
+ throw new Error('localPodId is required and must be a non-empty string');
520
+ }
521
+ if (!remotePodId || typeof remotePodId !== 'string') {
522
+ throw new Error('remotePodId is required and must be a non-empty string');
523
+ }
524
+
525
+ this.#id = id || `sync_${localPodId}_${remotePodId}_${Date.now()}`;
526
+ this.#localPodId = localPodId;
527
+ this.#remotePodId = remotePodId;
528
+ this.#localClock = { ...localClock };
529
+ this.#remoteClock = { ...remoteClock };
530
+ this.#createdAt = Date.now();
531
+ }
532
+
533
+ get id() { return this.#id; }
534
+ get localPodId() { return this.#localPodId; }
535
+ get remotePodId() { return this.#remotePodId; }
536
+ get state() { return this.#state; }
537
+ get localClock() { return { ...this.#localClock }; }
538
+ get remoteClock() { return { ...this.#remoteClock }; }
539
+ get stats() { return { ...this.#stats }; }
540
+ get lastSyncAt() { return this.#lastSyncAt; }
541
+
542
+ /**
543
+ * Prepare outbound deltas from a delta log.
544
+ * @param {DeltaLog} log
545
+ * @returns {DeltaEntry[]}
546
+ */
547
+ prepareSend(log) {
548
+ this._setState('requesting');
549
+ const deltas = log.sinceVectorClock(this.#remoteClock);
550
+ this.#pendingSend = deltas;
551
+ return deltas;
552
+ }
553
+
554
+ /**
555
+ * Number of entries waiting to be confirmed as sent.
556
+ * @returns {number}
557
+ */
558
+ get pendingSendCount() {
559
+ return this.#pendingSend.length;
560
+ }
561
+
562
+ /**
563
+ * Mark outbound deltas as sent.
564
+ * @param {DeltaEntry[]} sent
565
+ */
566
+ confirmSent(sent) {
567
+ this.#stats.sent += sent.length;
568
+ // Update our knowledge of remote clock
569
+ for (const e of sent) {
570
+ if (!this.#remoteClock[e.origin] || e.seq > this.#remoteClock[e.origin]) {
571
+ this.#remoteClock[e.origin] = e.seq;
572
+ }
573
+ }
574
+ this.#pendingSend = [];
575
+ }
576
+
577
+ /**
578
+ * Receive deltas from the remote peer.
579
+ * @param {DeltaEntry[]} entries
580
+ */
581
+ receiveDeltas(entries) {
582
+ this._setState('receiving');
583
+ this.#pendingReceive = entries;
584
+ this.#stats.received += entries.length;
585
+ }
586
+
587
+ /**
588
+ * Apply received deltas to local state.
589
+ * @param {Object} state - Mutable state
590
+ * @param {DeltaDecoder} decoder
591
+ * @returns {Object} Updated state
592
+ */
593
+ applyReceived(state, decoder) {
594
+ this._setState('applying');
595
+ const result = decoder.applyCausal(state, this.#pendingReceive);
596
+
597
+ // Update local clock
598
+ for (const e of this.#pendingReceive) {
599
+ if (!this.#localClock[e.origin] || e.seq > this.#localClock[e.origin]) {
600
+ this.#localClock[e.origin] = e.seq;
601
+ }
602
+ }
603
+
604
+ this.#pendingReceive = [];
605
+ this.#stats.rounds++;
606
+ this.#lastSyncAt = Date.now();
607
+ this._setState('complete');
608
+ return result;
609
+ }
610
+
611
+ /** Register state change listener. */
612
+ onStateChange(cb) {
613
+ this.#stateListeners.push(cb);
614
+ }
615
+
616
+ /** @private */
617
+ _setState(newState) {
618
+ const old = this.#state;
619
+ this.#state = newState;
620
+ for (const cb of this.#stateListeners) cb(newState, old);
621
+ }
622
+
623
+ toJSON() {
624
+ return {
625
+ id: this.#id,
626
+ localPodId: this.#localPodId,
627
+ remotePodId: this.#remotePodId,
628
+ state: this.#state,
629
+ localClock: { ...this.#localClock },
630
+ remoteClock: { ...this.#remoteClock },
631
+ stats: { ...this.#stats },
632
+ lastSyncAt: this.#lastSyncAt,
633
+ };
634
+ }
635
+ }
636
+
637
+ // ---------------------------------------------------------------------------
638
+ // SyncCoordinator
639
+ // ---------------------------------------------------------------------------
640
+
641
+ /**
642
+ * Orchestrates delta sync across multiple peers.
643
+ */
644
+ export class SyncCoordinator {
645
+ /** @type {string} */
646
+ #localPodId;
647
+
648
+ /** @type {DeltaLog} */
649
+ #log;
650
+
651
+ /** @type {DeltaEncoder} */
652
+ #encoder;
653
+
654
+ /** @type {DeltaDecoder} */
655
+ #decoder;
656
+
657
+ /** @type {Map<string, SyncSession>} remotePodId → session */
658
+ #sessions = new Map();
659
+
660
+ /** @type {Object} Shared state */
661
+ #state;
662
+
663
+ /** @type {Function[]} */
664
+ #syncListeners = [];
665
+
666
+ /** @type {Map<string, DeltaBranch>} branchName → DeltaBranch */
667
+ #branches = new Map();
668
+
669
+ /**
670
+ * @param {object} opts
671
+ * @param {string} opts.localPodId
672
+ * @param {Object} [opts.initialState={}]
673
+ * @param {DeltaLog} [opts.log]
674
+ */
675
+ /** @type {Function|null} (targetId, msg) => void */
676
+ #sendFn;
677
+
678
+ /**
679
+ * @param {object} opts
680
+ * @param {string} opts.localPodId
681
+ * @param {Object} [opts.initialState={}]
682
+ * @param {DeltaLog} [opts.log]
683
+ * @param {Function} [opts.sendFn] Send function: (targetId, msg) => {}
684
+ */
685
+ constructor({ localPodId, initialState = {}, log, sendFn }) {
686
+ if (!localPodId || typeof localPodId !== 'string') {
687
+ throw new Error('localPodId is required and must be a non-empty string');
688
+ }
689
+ this.#localPodId = localPodId;
690
+ this.#state = { ...initialState };
691
+ this.#log = log || new DeltaLog();
692
+ this.#encoder = new DeltaEncoder();
693
+ this.#decoder = new DeltaDecoder();
694
+ this.#sendFn = sendFn || null;
695
+ }
696
+
697
+ get localPodId() { return this.#localPodId; }
698
+ get state() { return { ...this.#state }; }
699
+
700
+ /**
701
+ * Set or replace the send function used for wire protocol messages.
702
+ * Useful when the transport layer is established after construction.
703
+ * @param {Function} fn - (targetId, msg) => void
704
+ */
705
+ setSendFn(fn) {
706
+ this.#sendFn = typeof fn === 'function' ? fn : null;
707
+ }
708
+
709
+ /**
710
+ * Apply a local state change.
711
+ * @param {string} key
712
+ * @param {*} value
713
+ */
714
+ set(key, value) {
715
+ const entry = new DeltaEntry({
716
+ key,
717
+ op: 'set',
718
+ value,
719
+ origin: this.#localPodId,
720
+ vectorClock: this.#log.getVectorClock(),
721
+ });
722
+ this.#log.append(entry);
723
+ this.#state[key] = value;
724
+ }
725
+
726
+ /**
727
+ * Delete a key from local state.
728
+ * @param {string} key
729
+ */
730
+ delete(key) {
731
+ const entry = new DeltaEntry({
732
+ key,
733
+ op: 'delete',
734
+ origin: this.#localPodId,
735
+ vectorClock: this.#log.getVectorClock(),
736
+ });
737
+ this.#log.append(entry);
738
+ delete this.#state[key];
739
+ }
740
+
741
+ /**
742
+ * Get or create a sync session with a remote peer.
743
+ * @param {string} remotePodId
744
+ * @returns {SyncSession}
745
+ */
746
+ getSession(remotePodId) {
747
+ if (!this.#sessions.has(remotePodId)) {
748
+ this.#sessions.set(remotePodId, new SyncSession({
749
+ localPodId: this.#localPodId,
750
+ remotePodId,
751
+ localClock: this.#log.getVectorClock(),
752
+ }));
753
+ }
754
+ return this.#sessions.get(remotePodId);
755
+ }
756
+
757
+ /**
758
+ * Prepare deltas to send to a remote peer.
759
+ * @param {string} remotePodId
760
+ * @returns {DeltaEntry[]}
761
+ */
762
+ prepareSyncTo(remotePodId) {
763
+ const session = this.getSession(remotePodId);
764
+ return session.prepareSend(this.#log);
765
+ }
766
+
767
+ /**
768
+ * Receive and apply deltas from a remote peer.
769
+ * @param {string} remotePodId
770
+ * @param {DeltaEntry[]} entries
771
+ */
772
+ receiveFrom(remotePodId, entries) {
773
+ const session = this.getSession(remotePodId);
774
+ session.receiveDeltas(entries);
775
+ this.#state = session.applyReceived(this.#state, this.#decoder);
776
+
777
+ // Also append to our log for future sync with other peers
778
+ for (const e of entries) {
779
+ this.#log.append(e);
780
+ }
781
+
782
+ for (const cb of this.#syncListeners) cb(remotePodId, entries);
783
+ }
784
+
785
+ /** Remove a sync session. */
786
+ removeSession(remotePodId) {
787
+ this.#sessions.delete(remotePodId);
788
+ }
789
+
790
+ /** List all active sessions. */
791
+ listSessions() {
792
+ return [...this.#sessions.entries()].map(([podId, session]) => ({
793
+ remotePodId: podId,
794
+ state: session.state,
795
+ stats: session.stats,
796
+ lastSyncAt: session.lastSyncAt,
797
+ }));
798
+ }
799
+
800
+ /** Get the delta log. */
801
+ getLog() {
802
+ return this.#log;
803
+ }
804
+
805
+ /** Register sync listener. */
806
+ onSync(cb) {
807
+ this.#syncListeners.push(cb);
808
+ }
809
+
810
+ /**
811
+ * Remove a sync listener.
812
+ * @param {Function} cb
813
+ * @returns {boolean} True if the listener was found and removed
814
+ */
815
+ offSync(cb) {
816
+ const idx = this.#syncListeners.indexOf(cb);
817
+ if (idx !== -1) { this.#syncListeners.splice(idx, 1); return true; }
818
+ return false;
819
+ }
820
+
821
+ /** Get stats. */
822
+ getStats() {
823
+ let totalSent = 0;
824
+ let totalReceived = 0;
825
+ let totalRounds = 0;
826
+ for (const s of this.#sessions.values()) {
827
+ const st = s.stats;
828
+ totalSent += st.sent;
829
+ totalReceived += st.received;
830
+ totalRounds += st.rounds;
831
+ }
832
+ return {
833
+ sessionCount: this.#sessions.size,
834
+ logSize: this.#log.length,
835
+ stateKeys: Object.keys(this.#state).length,
836
+ totalSent,
837
+ totalReceived,
838
+ totalRounds,
839
+ };
840
+ }
841
+
842
+ // -----------------------------------------------------------------------
843
+ // Branch management (CRDT parallel state timelines)
844
+ // -----------------------------------------------------------------------
845
+
846
+ /**
847
+ * Create a new branch with a snapshot of the current state.
848
+ * @param {string} name - Branch name
849
+ * @returns {DeltaBranch}
850
+ */
851
+ createBranch(name) {
852
+ if (this.#branches.has(name)) {
853
+ throw new Error(`Branch "${name}" already exists`);
854
+ }
855
+ const branch = new DeltaBranch(name, this.#state);
856
+ this.#branches.set(name, branch);
857
+ return branch;
858
+ }
859
+
860
+ /**
861
+ * List all branches with metadata.
862
+ * @returns {Array<{ name: string, parentBranch: string|null, logSize: number, createdAt: number }>}
863
+ */
864
+ listBranches() {
865
+ return [...this.#branches.values()].map(b => ({
866
+ name: b.name,
867
+ parentBranch: b.parentBranch,
868
+ logSize: b.logSize,
869
+ createdAt: b.createdAt,
870
+ }));
871
+ }
872
+
873
+ /**
874
+ * Switch to a branch by applying its state as the current state.
875
+ * @param {string} name - Branch name
876
+ * @returns {Object} The new current state
877
+ */
878
+ switchBranch(name) {
879
+ const branch = this.#branches.get(name);
880
+ if (!branch) {
881
+ throw new Error(`Branch "${name}" does not exist`);
882
+ }
883
+ this.#state = branch.getState();
884
+ return { ...this.#state };
885
+ }
886
+
887
+ /**
888
+ * Merge a branch back into the main state.
889
+ * @param {string} name - Branch name
890
+ * @param {'ours'|'theirs'|'fail'} [strategy='ours'] - Conflict resolution strategy
891
+ * @returns {{ merged: number, conflicts: Array<{ key: string, ours: *, theirs: * }> }}
892
+ */
893
+ mergeBranch(name, strategy = 'ours') {
894
+ const branch = this.#branches.get(name);
895
+ if (!branch) {
896
+ throw new Error(`Branch "${name}" does not exist`);
897
+ }
898
+
899
+ const branchState = branch.getState();
900
+ const allKeys = new Set([...Object.keys(this.#state), ...Object.keys(branchState)]);
901
+ const conflicts = [];
902
+ let merged = 0;
903
+
904
+ for (const key of allKeys) {
905
+ const oursVal = this.#state[key];
906
+ const theirsVal = branchState[key];
907
+
908
+ if (JSON.stringify(oursVal) !== JSON.stringify(theirsVal)) {
909
+ conflicts.push({ key, ours: oursVal, theirs: theirsVal });
910
+
911
+ if (strategy === 'theirs') {
912
+ if (theirsVal === undefined) {
913
+ delete this.#state[key];
914
+ } else {
915
+ this.#state[key] = theirsVal;
916
+ }
917
+ merged++;
918
+ } else if (strategy === 'fail') {
919
+ // Collect all conflicts first, then throw
920
+ continue;
921
+ } else {
922
+ // 'ours': keep main state value, count as merged
923
+ merged++;
924
+ }
925
+ }
926
+ }
927
+
928
+ if (strategy === 'fail' && conflicts.length > 0) {
929
+ const keys = conflicts.map(c => c.key).join(', ');
930
+ throw new Error(`Merge conflict on keys: ${keys}`);
931
+ }
932
+
933
+ this.#branches.delete(name);
934
+ return { merged, conflicts };
935
+ }
936
+
937
+ /**
938
+ * Delete a branch.
939
+ * @param {string} name - Branch name
940
+ * @returns {boolean} True if the branch existed and was deleted
941
+ */
942
+ deleteBranch(name) {
943
+ return this.#branches.delete(name);
944
+ }
945
+
946
+ // -----------------------------------------------------------------------
947
+ // Wire protocol
948
+ // -----------------------------------------------------------------------
949
+
950
+ /**
951
+ * Handle an incoming wire message.
952
+ * @param {string} fromId - Sender pod ID
953
+ * @param {object} msg - Message with `type` field
954
+ */
955
+ handleMessage(fromId, msg) {
956
+ switch (msg.type) {
957
+ case DELTA_SYNC_REQUEST: {
958
+ const entries = this.prepareSyncTo(fromId);
959
+ if (this.#sendFn) {
960
+ this.#sendFn(fromId, {
961
+ type: DELTA_SYNC_RESPONSE,
962
+ entries: entries.map(e => e.toJSON()),
963
+ });
964
+ }
965
+ break;
966
+ }
967
+
968
+ case DELTA_SYNC_RESPONSE: {
969
+ const entries = (msg.entries || []).map(e =>
970
+ e instanceof DeltaEntry ? e : DeltaEntry.fromJSON(e)
971
+ );
972
+ this.receiveFrom(fromId, entries);
973
+ if (this.#sendFn) {
974
+ this.#sendFn(fromId, {
975
+ type: DELTA_SYNC_ACK,
976
+ entries: (msg.entries || []),
977
+ });
978
+ }
979
+ break;
980
+ }
981
+
982
+ case DELTA_SYNC_ACK: {
983
+ const session = this.getSession(fromId);
984
+ if (session.pendingSendCount === 0) break; // no pending send to confirm
985
+ const entries = (msg.entries || []).map(e =>
986
+ e instanceof DeltaEntry ? e : DeltaEntry.fromJSON(e)
987
+ );
988
+ session.confirmSent(entries);
989
+ break;
990
+ }
991
+
992
+ case DELTA_FULL_SNAPSHOT: {
993
+ if (msg.state) {
994
+ // Apply as full state replace
995
+ this.#state = { ...msg.state };
996
+ } else if (this.#sendFn) {
997
+ // Send own state snapshot
998
+ this.#sendFn(fromId, {
999
+ type: DELTA_FULL_SNAPSHOT,
1000
+ state: { ...this.#state },
1001
+ });
1002
+ }
1003
+ break;
1004
+ }
1005
+
1006
+ case DELTA_BRANCH_CREATE: {
1007
+ if (msg.name && !this.#branches.has(msg.name)) {
1008
+ this.createBranch(msg.name);
1009
+ }
1010
+ break;
1011
+ }
1012
+
1013
+ case DELTA_BRANCH_MERGE: {
1014
+ if (msg.name && this.#branches.has(msg.name)) {
1015
+ this.mergeBranch(msg.name, msg.strategy || 'ours');
1016
+ }
1017
+ break;
1018
+ }
1019
+
1020
+ default:
1021
+ // Unknown message type — ignore
1022
+ break;
1023
+ }
1024
+ }
1025
+
1026
+ /**
1027
+ * Initiate a sync by sending DELTA_SYNC_REQUEST to a remote peer.
1028
+ * @param {string} remotePodId
1029
+ */
1030
+ requestSync(remotePodId) {
1031
+ if (this.#sendFn) {
1032
+ this.#sendFn(remotePodId, { type: DELTA_SYNC_REQUEST });
1033
+ }
1034
+ }
1035
+
1036
+ /**
1037
+ * Broadcast a full state snapshot to listed peers.
1038
+ * @param {string[]} peerIds
1039
+ */
1040
+ broadcastState(peerIds) {
1041
+ if (!this.#sendFn) return;
1042
+ const snapshot = { ...this.#state };
1043
+ for (const peerId of peerIds) {
1044
+ this.#sendFn(peerId, {
1045
+ type: DELTA_FULL_SNAPSHOT,
1046
+ state: snapshot,
1047
+ });
1048
+ }
1049
+ }
1050
+
1051
+ toJSON() {
1052
+ return {
1053
+ localPodId: this.#localPodId,
1054
+ state: { ...this.#state },
1055
+ log: this.#log.toJSON(),
1056
+ sessions: [...this.#sessions.entries()].map(([k, v]) => ({ remotePodId: k, ...v.toJSON() })),
1057
+ };
1058
+ }
1059
+ }